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

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

            
27
use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
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 migrations;
35
pub mod weights;
36

            
37
pub use sp_runtime::{traits::ExtrinsicLike, MultiAddress, Perbill, Permill};
38
use {
39
    alloc::vec,
40
    alloc::vec::Vec,
41
    cumulus_primitives_core::AggregateMessageOrigin,
42
    dp_impl_tanssi_pallets_config::impl_tanssi_pallets_config,
43
    frame_support::{
44
        construct_runtime,
45
        dispatch::DispatchClass,
46
        dynamic_params::{dynamic_pallet_params, dynamic_params},
47
        genesis_builder_helper::{build_state, get_preset},
48
        pallet_prelude::DispatchResult,
49
        parameter_types,
50
        traits::{
51
            tokens::ConversionToAssetBalance, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8,
52
            Contains, InsideBoth, InstanceFilter,
53
        },
54
        weights::{
55
            constants::{
56
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
57
                WEIGHT_REF_TIME_PER_SECOND,
58
            },
59
            ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
60
            WeightToFeeCoefficients, WeightToFeePolynomial,
61
        },
62
    },
63
    frame_system::{
64
        limits::{BlockLength, BlockWeights},
65
        EnsureRoot,
66
    },
67
    nimbus_primitives::{NimbusId, SlotBeacon},
68
    pallet_parameters,
69
    pallet_transaction_payment::FungibleAdapter,
70
    parity_scale_codec::{Decode, DecodeWithMemTracking, Encode},
71
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
72
    scale_info::TypeInfo,
73
    serde::{Deserialize, Serialize},
74
    smallvec::smallvec,
75
    sp_api::impl_runtime_apis,
76
    sp_consensus_slots::{Slot, SlotDuration},
77
    sp_core::{MaxEncodedLen, OpaqueMetadata},
78
    sp_runtime::{
79
        generic,
80
        generic::SignedPayload,
81
        impl_opaque_keys,
82
        traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
83
        transaction_validity::{TransactionSource, TransactionValidity},
84
        ApplyExtrinsicResult, Cow, MultiSignature, SaturatedConversion,
85
    },
86
    sp_version::RuntimeVersion,
87
    xcm::prelude::Location,
88
    xcm::Version as XcmVersion,
89
    xcm::{
90
        v5::NetworkId, IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation,
91
        VersionedXcm,
92
    },
93
    xcm_runtime_apis::{
94
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
95
        fees::Error as XcmPaymentApiError,
96
    },
97
};
98

            
99
pub mod xcm_config;
100

            
101
// Polkadot imports
102
use polkadot_runtime_common::BlockHashCount;
103

            
104
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
105
pub type Signature = MultiSignature;
106

            
107
/// Some way of identifying an account on the chain. We intentionally make it equivalent
108
/// to the public key of our transaction signing scheme.
109
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
110

            
111
/// Balance of an account.
112
pub type Balance = u128;
113

            
114
/// Index of a transaction in the chain.
115
pub type Index = u32;
116

            
117
/// A hash of some data used by the chain.
118
pub type Hash = sp_core::H256;
119

            
120
/// An index to a block.
121
pub type BlockNumber = u32;
122

            
123
/// The address format for describing accounts.
124
pub type Address = MultiAddress<AccountId, ()>;
125

            
126
/// Block header type as expected by this runtime.
127
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
128

            
129
/// Block type as expected by this runtime.
130
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
131

            
132
/// A Block signed with a Justification
133
pub type SignedBlock = generic::SignedBlock<Block>;
134

            
135
/// BlockId type as expected by this runtime.
136
pub type BlockId = generic::BlockId<Block>;
137

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

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

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

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

            
169
pub mod currency {
170
    use super::Balance;
171

            
172
    pub const MICROUNIT: Balance = 1_000_000;
173
    pub const MILLIUNIT: Balance = 1_000_000_000;
174
    pub const UNIT: Balance = 1_000_000_000_000;
175
    pub const KILOUNIT: Balance = 1_000_000_000_000_000;
176

            
177
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
178

            
179
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
180
        items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
181
    }
182
}
183

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

            
211
parameter_types! {
212
        /// Network and location for the Ethereum chain. On Starlight, the Ethereum chain bridged
213
        /// to is the Ethereum mainnet, with chain ID 1.
214
        /// <https://chainlist.org/chain/1>
215
        /// <https://ethereum.org/en/developers/docs/apis/json-rpc/#net_version>
216
        pub EthereumNetwork: NetworkId = NetworkId::Ethereum { chain_id: 11155111 };
217
        pub EthereumLocation: Location = Location::new(2, EthereumNetwork::get());
218
}
219

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

            
230
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
231
    /// Opaque block header type.
232
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
233
    /// Opaque block type.
234
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
235
    /// Opaque block identifier type.
236
    pub type BlockId = generic::BlockId<Block>;
237
}
238

            
239
impl_opaque_keys! {
240
    pub struct SessionKeys { }
241
}
242

            
243
#[sp_version::runtime_version]
244
pub const VERSION: RuntimeVersion = RuntimeVersion {
245
    spec_name: Cow::Borrowed("container-chain-template"),
246
    impl_name: Cow::Borrowed("container-chain-template"),
247
    authoring_version: 1,
248
    spec_version: 1700,
249
    impl_version: 0,
250
    apis: RUNTIME_API_VERSIONS,
251
    transaction_version: 1,
252
    system_version: 1,
253
};
254

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

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

            
267
// Time is measured by number of blocks.
268
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
269
pub const HOURS: BlockNumber = MINUTES * 60;
270
pub const DAYS: BlockNumber = HOURS * 24;
271

            
272
pub const SUPPLY_FACTOR: Balance = 100;
273

            
274
// Unit = the base number of indivisible units for balances
275
pub const UNIT: Balance = 1_000_000_000_000;
276
pub const MILLIUNIT: Balance = 1_000_000_000;
277
pub const MICROUNIT: Balance = 1_000_000;
278

            
279
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
280

            
281
pub const fn deposit(items: u32, bytes: u32) -> Balance {
282
    items as Balance * 100 * MILLIUNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
283
}
284

            
285
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
286
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
287

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

            
292
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
293
/// `Operational` extrinsics.
294
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
295

            
296
/// We allow for 2 seconds of compute with a 6 second average block time
297
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
298
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
299
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
300
);
301

            
302
/// The version information used to identify this runtime when compiled natively.
303
#[cfg(feature = "std")]
304
pub fn native_version() -> NativeVersion {
305
    NativeVersion {
306
        runtime_version: VERSION,
307
        can_author_with: Default::default(),
308
    }
309
}
310

            
311
parameter_types! {
312
    pub const Version: RuntimeVersion = VERSION;
313

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

            
341
// Configure FRAME pallets to include in runtime.
342

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

            
398
parameter_types! {
399
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
400
}
401

            
402
impl pallet_balances::Config for Runtime {
403
    type MaxLocks = ConstU32<50>;
404
    /// The type for recording an account's balance.
405
    type Balance = Balance;
406
    /// The ubiquitous event type.
407
    type RuntimeEvent = RuntimeEvent;
408
    type DustRemoval = ();
409
    type ExistentialDeposit = ExistentialDeposit;
410
    type AccountStore = System;
411
    type MaxReserves = ConstU32<50>;
412
    type ReserveIdentifier = [u8; 8];
413
    type FreezeIdentifier = RuntimeFreezeReason;
414
    type MaxFreezes = ConstU32<0>;
415
    type RuntimeHoldReason = RuntimeHoldReason;
416
    type RuntimeFreezeReason = RuntimeFreezeReason;
417
    type DoneSlashHandler = ();
418
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
419
}
420

            
421
parameter_types! {
422
    pub const TransactionByteFee: Balance = 1;
423
}
424

            
425
impl pallet_transaction_payment::Config for Runtime {
426
    type RuntimeEvent = RuntimeEvent;
427
    // This will burn the fees
428
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
429
    type OperationalFeeMultiplier = ConstU8<5>;
430
    type WeightToFee = WeightToFee;
431
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
432
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
433
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
434
}
435

            
436
/// Dynamic params that can be adjusted at runtime.
437
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
438
pub mod dynamic_params {
439
    use super::*;
440

            
441
    /// The Dancelight genesis hash used as the default relay network identifier.
442
    pub const DANCELIGHT_GENESIS_HASH: [u8; 32] =
443
        hex_literal::hex!["983a1a72503d6cc3636776747ec627172b51272bf45e50a355348facb67a820a"];
444

            
445
    #[dynamic_pallet_params]
446
    #[codec(index = 0)]
447
    pub mod xcm_config {
448
        use super::*;
449

            
450
        /// The relay network identifier for this container chain.
451
        /// Using Dancelight genesis hash as default.
452
        #[codec(index = 0)]
453
        pub static RelayNetwork: xcm::latest::NetworkId =
454
            xcm::latest::NetworkId::ByGenesis(DANCELIGHT_GENESIS_HASH);
455
    }
456
}
457

            
458
#[cfg(feature = "runtime-benchmarks")]
459
impl Default for RuntimeParameters {
460
    fn default() -> Self {
461
        RuntimeParameters::XcmConfig(dynamic_params::xcm_config::Parameters::RelayNetwork(
462
            dynamic_params::xcm_config::RelayNetwork,
463
            Some(xcm::latest::NetworkId::ByGenesis(
464
                dynamic_params::DANCELIGHT_GENESIS_HASH,
465
            )),
466
        ))
467
    }
468
}
469

            
470
impl pallet_parameters::Config for Runtime {
471
    type AdminOrigin = EnsureRoot<AccountId>;
472
    type RuntimeEvent = RuntimeEvent;
473
    type RuntimeParameters = RuntimeParameters;
474
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
475
}
476

            
477
parameter_types! {
478
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
479
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
480
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
481
}
482

            
483
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
484
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
485
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
486

            
487
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
488
    Runtime,
489
    BLOCK_PROCESSING_VELOCITY,
490
    UNINCLUDED_SEGMENT_CAPACITY,
491
>;
492

            
493
impl cumulus_pallet_parachain_system::Config for Runtime {
494
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
495
    type RuntimeEvent = RuntimeEvent;
496
    type OnSystemEvent = ();
497
    type OutboundXcmpMessageSource = XcmpQueue;
498
    type SelfParaId = parachain_info::Pallet<Runtime>;
499
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
500
    type ReservedDmpWeight = ReservedDmpWeight;
501
    type XcmpMessageHandler = XcmpQueue;
502
    type ReservedXcmpWeight = ReservedXcmpWeight;
503
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
504
    type ConsensusHook = ConsensusHook;
505
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
506
    type RelayParentOffset = ConstU32<0>;
507
}
508

            
509
pub struct ParaSlotProvider;
510
impl sp_core::Get<(Slot, SlotDuration)> for ParaSlotProvider {
511
792
    fn get() -> (Slot, SlotDuration) {
512
792
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
513
792
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
514
792
    }
515
}
516

            
517
parameter_types! {
518
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
519
}
520

            
521
impl pallet_async_backing::Config for Runtime {
522
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
523
    type GetAndVerifySlot =
524
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
525
    type ExpectedBlockTime = ExpectedBlockTime;
526
}
527

            
528
impl parachain_info::Config for Runtime {}
529

            
530
parameter_types! {
531
    pub const Period: u32 = 6 * HOURS;
532
    pub const Offset: u32 = 0;
533
}
534

            
535
impl pallet_sudo::Config for Runtime {
536
    type RuntimeCall = RuntimeCall;
537
    type RuntimeEvent = RuntimeEvent;
538
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
539
}
540

            
541
impl pallet_utility::Config for Runtime {
542
    type RuntimeEvent = RuntimeEvent;
543
    type RuntimeCall = RuntimeCall;
544
    type PalletsOrigin = OriginCaller;
545
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
546
}
547

            
548
/// The type used to represent the kinds of proxying allowed.
549
#[derive(
550
    Copy,
551
    Clone,
552
    Eq,
553
    PartialEq,
554
    Ord,
555
    PartialOrd,
556
    Encode,
557
    Decode,
558
    Debug,
559
    MaxEncodedLen,
560
    DecodeWithMemTracking,
561
    TypeInfo,
562
    Serialize,
563
    Deserialize,
564
)]
565
#[allow(clippy::unnecessary_cast)]
566
pub enum ProxyType {
567
    /// All calls can be proxied. This is the trivial/most permissive filter.
568
    Any = 0,
569
    /// Only extrinsics that do not transfer funds.
570
    NonTransfer = 1,
571
    /// Only extrinsics related to governance (democracy and collectives).
572
    Governance = 2,
573
    /// Allow to veto an announced proxy call.
574
    CancelProxy = 3,
575
    /// Allow extrinsic related to Balances.
576
    Balances = 4,
577
}
578

            
579
impl Default for ProxyType {
580
    fn default() -> Self {
581
        Self::Any
582
    }
583
}
584

            
585
impl InstanceFilter<RuntimeCall> for ProxyType {
586
    fn filter(&self, c: &RuntimeCall) -> bool {
587
        // Since proxy filters are respected in all dispatches of the Utility
588
        // pallet, it should never need to be filtered by any proxy.
589
        if let RuntimeCall::Utility(..) = c {
590
            return true;
591
        }
592

            
593
        match self {
594
            ProxyType::Any => true,
595
            ProxyType::NonTransfer => {
596
                matches!(
597
                    c,
598
                    RuntimeCall::System(..)
599
                        | RuntimeCall::ParachainSystem(..)
600
                        | RuntimeCall::Timestamp(..)
601
                        | RuntimeCall::Proxy(..)
602
                )
603
            }
604
            // We don't have governance yet
605
            ProxyType::Governance => false,
606
            ProxyType::CancelProxy => matches!(
607
                c,
608
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
609
            ),
610
            ProxyType::Balances => {
611
                matches!(c, RuntimeCall::Balances(..))
612
            }
613
        }
614
    }
615

            
616
    fn is_superset(&self, o: &Self) -> bool {
617
        match (self, o) {
618
            (x, y) if x == y => true,
619
            (ProxyType::Any, _) => true,
620
            (_, ProxyType::Any) => false,
621
            _ => false,
622
        }
623
    }
624
}
625

            
626
impl pallet_proxy::Config for Runtime {
627
    type RuntimeEvent = RuntimeEvent;
628
    type RuntimeCall = RuntimeCall;
629
    type Currency = Balances;
630
    type ProxyType = ProxyType;
631
    // One storage item; key size 32, value size 8
632
    type ProxyDepositBase = ConstU128<{ deposit(1, 8) }>;
633
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
634
    type ProxyDepositFactor = ConstU128<{ deposit(0, 33) }>;
635
    type MaxProxies = ConstU32<32>;
636
    type MaxPending = ConstU32<32>;
637
    type CallHasher = BlakeTwo256;
638
    type AnnouncementDepositBase = ConstU128<{ deposit(1, 8) }>;
639
    // Additional storage item size of 68 bytes:
640
    // - 32 bytes AccountId
641
    // - 32 bytes Hasher (Blake2256)
642
    // - 4 bytes BlockNumber (u32)
643
    type AnnouncementDepositFactor = ConstU128<{ deposit(0, 68) }>;
644
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
645
    type BlockNumberProvider = System;
646
}
647

            
648
pub struct XcmExecutionManager;
649
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
650
    fn suspend_xcm_execution() -> DispatchResult {
651
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
652
    }
653
    fn resume_xcm_execution() -> DispatchResult {
654
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
655
    }
656
}
657

            
658
impl pallet_migrations::Config for Runtime {
659
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
660
    type XcmExecutionManager = XcmExecutionManager;
661
}
662

            
663
parameter_types! {
664
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
665
}
666

            
667
impl pallet_multiblock_migrations::Config for Runtime {
668
    type RuntimeEvent = RuntimeEvent;
669
    #[cfg(not(feature = "runtime-benchmarks"))]
670
    type Migrations = ();
671
    // Benchmarks need mocked migrations to guarantee that they succeed.
672
    #[cfg(feature = "runtime-benchmarks")]
673
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
674
    type CursorMaxLen = ConstU32<65_536>;
675
    type IdentifierMaxLen = ConstU32<256>;
676
    type MigrationStatusHandler = ();
677
    type FailedMigrationHandler = MaintenanceMode;
678
    type MaxServiceWeight = MbmServiceWeight;
679
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
680
}
681

            
682
/// Maintenance mode Call filter
683
pub struct MaintenanceFilter;
684
impl Contains<RuntimeCall> for MaintenanceFilter {
685
    fn contains(c: &RuntimeCall) -> bool {
686
        !matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
687
    }
688
}
689

            
690
/// Normal Call Filter
691
/// We dont allow to create nor mint assets, this for now is disabled
692
/// We only allow transfers. For now creation of assets will go through
693
/// asset-manager, while minting/burning only happens through xcm messages
694
/// This can change in the future
695
pub struct NormalFilter;
696
impl Contains<RuntimeCall> for NormalFilter {
697
1584
    fn contains(_c: &RuntimeCall) -> bool {
698
1584
        true
699
1584
    }
700
}
701

            
702
impl pallet_maintenance_mode::Config for Runtime {
703
    type NormalCallFilter = NormalFilter;
704
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
705
    type MaintenanceOrigin = EnsureRoot<AccountId>;
706
    type XcmExecutionManager = XcmExecutionManager;
707
}
708

            
709
impl pallet_root_testing::Config for Runtime {
710
    type RuntimeEvent = RuntimeEvent;
711
}
712

            
713
impl pallet_tx_pause::Config for Runtime {
714
    type RuntimeEvent = RuntimeEvent;
715
    type RuntimeCall = RuntimeCall;
716
    type PauseOrigin = EnsureRoot<AccountId>;
717
    type UnpauseOrigin = EnsureRoot<AccountId>;
718
    type WhitelistedCalls = ();
719
    type MaxNameLen = ConstU32<256>;
720
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
721
}
722

            
723
impl dp_impl_tanssi_pallets_config::Config for Runtime {
724
    const SLOT_DURATION: u64 = SLOT_DURATION;
725
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
726
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
727
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
728
}
729

            
730
parameter_types! {
731
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
732
    pub const DepositBase: Balance = currency::deposit(1, 88);
733
    // Additional storage item size of 32 bytes.
734
    pub const DepositFactor: Balance = currency::deposit(0, 32);
735
    pub const MaxSignatories: u32 = 100;
736
}
737

            
738
impl pallet_multisig::Config for Runtime {
739
    type RuntimeEvent = RuntimeEvent;
740
    type RuntimeCall = RuntimeCall;
741
    type Currency = Balances;
742
    type DepositBase = DepositBase;
743
    type DepositFactor = DepositFactor;
744
    type MaxSignatories = MaxSignatories;
745
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
746
    type BlockNumberProvider = System;
747
}
748

            
749
impl frame_system::offchain::SigningTypes for Runtime {
750
    type Public = <Signature as sp_runtime::traits::Verify>::Signer;
751
    type Signature = Signature;
752
}
753

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

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

            
810
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
811
where
812
    RuntimeCall: From<C>,
813
{
814
    type Extrinsic = UncheckedExtrinsic;
815
    type RuntimeCall = RuntimeCall;
816
}
817

            
818
impl<LocalCall> frame_system::offchain::CreateBare<LocalCall> for Runtime
819
where
820
    RuntimeCall: From<LocalCall>,
821
{
822
    fn create_bare(call: RuntimeCall) -> UncheckedExtrinsic {
823
        UncheckedExtrinsic::new_bare(call)
824
    }
825
}
826

            
827
impl pallet_ocw_testing::Config for Runtime {
828
    type UnsignedInterval = ConstU32<6>;
829
}
830

            
831
impl cumulus_pallet_weight_reclaim::Config for Runtime {
832
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
833
}
834

            
835
impl_tanssi_pallets_config!(Runtime);
836

            
837
// Create the runtime by composing the FRAME pallets that were previously configured.
838
construct_runtime!(
839
    pub enum Runtime
840
    {
841
        // System support stuff.
842
        System: frame_system = 0,
843
        ParachainSystem: cumulus_pallet_parachain_system = 1,
844
        Timestamp: pallet_timestamp = 2,
845
        ParachainInfo: parachain_info = 3,
846
        Sudo: pallet_sudo = 4,
847
        Utility: pallet_utility = 5,
848
        Proxy: pallet_proxy = 6,
849
        Migrations: pallet_migrations = 7,
850
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
851
        MaintenanceMode: pallet_maintenance_mode = 8,
852
        TxPause: pallet_tx_pause = 9,
853

            
854
        // Monetary stuff.
855
        Balances: pallet_balances = 10,
856
        TransactionPayment: pallet_transaction_payment = 11,
857

            
858
        // Other utilities
859
        Multisig: pallet_multisig = 16,
860
        Parameters: pallet_parameters = 17,
861

            
862
        // ContainerChain Author Verification
863
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
864
        AuthorInherent: pallet_author_inherent = 51,
865

            
866
        // XCM
867
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
868
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
869
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
870
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
871
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
872
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
873
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
874
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
875

            
876
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
877

            
878
        RootTesting: pallet_root_testing = 100,
879
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
880

            
881
        OffchainWorker: pallet_ocw_testing::{Pallet, Call, Storage, Event<T>, ValidateUnsigned} = 120,
882
    }
883
);
884

            
885
#[cfg(feature = "runtime-benchmarks")]
886
mod benches {
887
    frame_benchmarking::define_benchmarks!(
888
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
889
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
890
        [cumulus_pallet_parachain_system, ParachainSystem]
891
        [pallet_timestamp, Timestamp]
892
        [pallet_sudo, Sudo]
893
        [pallet_utility, Utility]
894
        [pallet_proxy, Proxy]
895
        [pallet_tx_pause, TxPause]
896
        [pallet_transaction_payment, TransactionPayment]
897
        [pallet_balances, Balances]
898
        [pallet_multiblock_migrations, MultiBlockMigrations]
899
        [pallet_multisig, Multisig]
900
        [pallet_cc_authorities_noting, AuthoritiesNoting]
901
        [pallet_author_inherent, AuthorInherent]
902
        [cumulus_pallet_xcmp_queue, XcmpQueue]
903
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
904
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
905
        [pallet_message_queue, MessageQueue]
906
        [pallet_assets, ForeignAssets]
907
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
908
        [pallet_asset_rate, AssetRate]
909
        [pallet_xcm_executor_utils, XcmExecutorUtils]
910
        [cumulus_pallet_weight_reclaim, WeightReclaim]
911
    );
912
}
913

            
914
impl_runtime_apis! {
915
    impl sp_api::Core<Block> for Runtime {
916
        fn version() -> RuntimeVersion {
917
            VERSION
918
        }
919

            
920
        fn execute_block(block: Block) {
921
            Executive::execute_block(block)
922
        }
923

            
924
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
925
            Executive::initialize_block(header)
926
        }
927
    }
928

            
929
    impl sp_api::Metadata<Block> for Runtime {
930
        fn metadata() -> OpaqueMetadata {
931
            OpaqueMetadata::new(Runtime::metadata().into())
932
        }
933

            
934
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
935
            Runtime::metadata_at_version(version)
936
        }
937

            
938
        fn metadata_versions() -> Vec<u32> {
939
            Runtime::metadata_versions()
940
        }
941
    }
942

            
943
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
944
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
945
            Executive::apply_extrinsic(extrinsic)
946
        }
947

            
948
        fn finalize_block() -> <Block as BlockT>::Header {
949
            Executive::finalize_block()
950
        }
951

            
952
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
953
            data.create_extrinsics()
954
        }
955

            
956
        fn check_inherents(
957
            block: Block,
958
            data: sp_inherents::InherentData,
959
        ) -> sp_inherents::CheckInherentsResult {
960
            data.check_extrinsics(&block)
961
        }
962
    }
963

            
964
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
965
        fn validate_transaction(
966
            source: TransactionSource,
967
            tx: <Block as BlockT>::Extrinsic,
968
            block_hash: <Block as BlockT>::Hash,
969
        ) -> TransactionValidity {
970
            Executive::validate_transaction(source, tx, block_hash)
971
        }
972
    }
973

            
974
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
975
        fn offchain_worker(header: &<Block as BlockT>::Header) {
976
            Executive::offchain_worker(header)
977
        }
978
    }
979

            
980
    impl sp_session::SessionKeys<Block> for Runtime {
981
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
982
            SessionKeys::generate(seed)
983
        }
984

            
985
        fn decode_session_keys(
986
            encoded: Vec<u8>,
987
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
988
            SessionKeys::decode_into_raw_public_keys(&encoded)
989
        }
990
    }
991

            
992
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
993
        fn account_nonce(account: AccountId) -> Index {
994
            System::account_nonce(account)
995
        }
996
    }
997

            
998
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
999
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
            ParachainSystem::collect_collation_info(header)
        }
    }
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
        fn can_build_upon(
            included_hash: <Block as BlockT>::Hash,
            slot: async_backing_primitives::Slot,
        ) -> bool {
            ConsensusHook::can_build_upon(included_hash, slot)
        }
    }
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
            build_state::<RuntimeGenesisConfig>(config)
        }
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
        }
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec![]
        }
    }
    #[cfg(feature = "runtime-benchmarks")]
    impl frame_benchmarking::Benchmark<Block> for Runtime {
        fn benchmark_metadata(
            extra: bool,
        ) -> (
            Vec<frame_benchmarking::BenchmarkList>,
            Vec<frame_support::traits::StorageInfo>,
        ) {
            use frame_benchmarking::{BenchmarkList};
            use frame_support::traits::StorageInfoTrait;
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            let mut list = Vec::<BenchmarkList>::new();
            list_benchmarks!(list, extra);
            let storage_info = AllPalletsWithSystem::storage_info();
            (list, storage_info)
        }
        #[allow(non_local_definitions)]
        fn dispatch_benchmark(
            config: frame_benchmarking::BenchmarkConfig,
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
            use sp_core::storage::TrackedStorageKey;
            use xcm::latest::prelude::*;
            use alloc::boxed::Box;
            impl frame_system_benchmarking::Config for Runtime {
                fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
                    Ok(())
                }
                fn verify_set_code() {
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
                }
            }
            use crate::xcm_config::SelfReserve;
            parameter_types! {
                pub ExistentialDepositAsset: Option<Asset> = Some((
                    SelfReserve::get(),
                    ExistentialDeposit::get()
                ).into());
            }
            impl pallet_xcm_benchmarks::Config for Runtime {
                type XcmConfig = xcm_config::XcmConfig;
                type AccountIdConverter = xcm_config::LocationToAccountId;
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
                xcm_config::XcmConfig,
                ExistentialDepositAsset,
                xcm_config::PriceForParentDelivery,
                >;
                fn valid_destination() -> Result<Location, BenchmarkError> {
                    Ok(Location::parent())
                }
                fn worst_case_holding(_depositable_count: u32) -> Assets {
                    // We only care for native asset until we support others
                    // TODO: refactor this case once other assets are supported
                    vec![Asset{
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(u128::MAX),
                    }].into()
                }
            }
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
                type TransactAsset = Balances;
                type RuntimeCall = RuntimeCall;
                fn worst_case_response() -> (u64, Response) {
                    (0u64, Response::Version(Default::default()))
                }
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
                    tanssi_runtime_common::universal_aliases::AliasingBenchmarksHelper::prepare_universal_alias()
                    .ok_or(BenchmarkError::Skip)
                }
                fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
                    Ok((Location::parent(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
                }
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
                    Ok(Location::parent())
                }
                fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
                    Ok((Asset {
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(ExistentialDeposit::get()*100),
                    }, WeightLimit::Unlimited))
                }
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
                    let origin = Location::parent();
                    let assets: Assets = (Location::parent(), 1_000u128).into();
                    let ticket = Location { parents: 0, interior: Here };
                    Ok((origin, ticket, assets))
                }
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn export_message_origin_and_destination(
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
            }
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            impl pallet_xcm::benchmarking::Config for Runtime {
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
                xcm_config::XcmConfig,
                ExistentialDepositAsset,
                xcm_config::PriceForParentDelivery,
                >;
                fn get_asset() -> Asset {
                    Asset {
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(ExistentialDeposit::get()),
                    }
                }
                fn reachable_dest() -> Option<Location> {
                    Some(Parent.into())
                }
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
                    // Relay/native token can be teleported between AH and Relay.
                    Some((
                        Asset {
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
                            id: Parent.into()
                        },
                        Parent.into(),
                    ))
                }
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
                    use xcm_config::SelfReserve;
                    // AH can reserve transfer native token to some random parachain.
                    let random_para_id = 43211234;
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
                        random_para_id.into()
                    );
                    let who = frame_benchmarking::whitelisted_caller();
                    // Give some multiple of the existential deposit
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
                        &who, balance,
                    );
                    Some((
                        Asset {
                            fun: Fungible(EXISTENTIAL_DEPOSIT*10),
                            id: SelfReserve::get().into()
                        },
                        ParentThen(Parachain(random_para_id).into()).into(),
                    ))
                }
                fn set_up_complex_asset_transfer(
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
                    use xcm_config::SelfReserve;
                    // Transfer to Relay some local AH asset (local-reserve-transfer) while paying
                    // fees using teleported native token.
                    // (We don't care that Relay doesn't accept incoming unknown AH local asset)
                    let dest = Parent.into();
                    let fee_amount = EXISTENTIAL_DEPOSIT;
                    let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
                    let who = frame_benchmarking::whitelisted_caller();
                    // Give some multiple of the existential deposit
                    let balance = fee_amount + EXISTENTIAL_DEPOSIT * 1000;
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
                        &who, balance,
                    );
                    // verify initial balance
                    assert_eq!(Balances::free_balance(&who), balance);
                    // set up local asset
                    let asset_amount = 10u128;
                    let initial_asset_amount = asset_amount * 10;
                    let (asset_id, asset_location) = pallet_foreign_asset_creator::benchmarks::create_minted_asset::<Runtime>(
                        initial_asset_amount,
                        who.clone(),
                        None,
                    );
                    let transfer_asset: Asset = (asset_location, asset_amount).into();
                    let assets: Assets = vec![fee_asset.clone(), transfer_asset].into();
                    let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
                    // verify transferred successfully
                    let verify = Box::new(move || {
                        // verify native balance after transfer, decreased by transferred fee amount
                        // (plus transport fees)
                        assert!(Balances::free_balance(&who) <= balance - fee_amount);
                        // verify asset balance decreased by exactly transferred amount
                        assert_eq!(
                            ForeignAssets::balance(asset_id, &who),
                            initial_asset_amount - asset_amount,
                        );
                    });
                    Some((assets, fee_index, dest, verify))
                }
            }
            let whitelist: Vec<TrackedStorageKey> = vec![
                // Block Number
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
                    .to_vec()
                    .into(),
                // Total Issuance
                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
                    .to_vec()
                    .into(),
                // Execution Phase
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
                    .to_vec()
                    .into(),
                // Event Count
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
                    .to_vec()
                    .into(),
                // System Events
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
                    .to_vec()
                    .into(),
                // The transactional storage limit.
                hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a")
                    .to_vec()
                    .into(),
                // ParachainInfo ParachainId
                hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb2782604a74d81251e398fd8a0a4d55023bb3f")
                    .to_vec()
                    .into(),
            ];
            let mut batches = Vec::<BenchmarkBatch>::new();
            let params = (&config, &whitelist);
            add_benchmarks!(params, batches);
            Ok(batches)
        }
    }
    #[cfg(feature = "try-runtime")]
    impl frame_try_runtime::TryRuntime<Block> for Runtime {
        fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
            let weight = Executive::try_runtime_upgrade(checks).unwrap();
            (weight, RuntimeBlockWeights::get().max_block)
        }
        fn execute_block(
            block: Block,
            state_root_check: bool,
            signature_check: bool,
            select: frame_try_runtime::TryStateSelect,
        ) -> Weight {
            // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
            // have a backtrace here.
            Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
        }
    }
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
    for Runtime {
        fn query_info(
            uxt: <Block as BlockT>::Extrinsic,
            len: u32,
        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_info(uxt, len)
        }
        fn query_fee_details(
            uxt: <Block as BlockT>::Extrinsic,
            len: u32,
        ) -> pallet_transaction_payment::FeeDetails<Balance> {
            TransactionPayment::query_fee_details(uxt, len)
        }
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
    }
    impl dp_slot_duration_runtime_api::TanssiSlotDurationApi<Block> for Runtime {
        fn slot_duration() -> u64 {
            SLOT_DURATION
        }
    }
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
            if !matches!(xcm_version, 3..=5) {
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
            }
            Ok([VersionedAssetId::V5(xcm_config::SelfReserve::get().into())]
                .into_iter()
                .chain(
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
                            VersionedAssetId::V5(location.into())
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
                            None
                        })
                    })
                )
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
                }).ok())
                .collect())
        }
        fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
            let local_asset = VersionedAssetId::V5(xcm_config::SelfReserve::get().into());
            let asset = asset
                .into_version(5)
                .map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
            if asset == local_asset {
                Ok(WeightToFee::weight_to_fee(&weight))
            } else {
                let native_fee = WeightToFee::weight_to_fee(&weight);
                let asset_v5: xcm::latest::AssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
                let location: xcm::latest::Location = asset_v5.0;
                let asset_id = pallet_foreign_asset_creator::ForeignAssetToAssetId::<Runtime>::get(location).ok_or(XcmPaymentApiError::AssetNotFound)?;
                let asset_rate = AssetRate::to_asset_balance(native_fee, asset_id);
                match asset_rate {
                    Ok(x) => Ok(x),
                    Err(pallet_asset_rate::Error::UnknownAssetKind) => Err(XcmPaymentApiError::AssetNotFound),
                    // Error when converting native balance to asset balance, probably overflow
                    Err(_e) => Err(XcmPaymentApiError::WeightNotComputable),
                }
            }
        }
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
            PolkadotXcm::query_xcm_weight(message)
        }
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
    }
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
        fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
        }
        fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
        }
    }
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
        fn convert_location(location: VersionedLocation) -> Result<
            AccountId,
            xcm_runtime_apis::conversions::Error
        > {
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
                AccountId,
                xcm_config::LocationToAccountId,
            >::convert_location(location)
        }
    }
13536
}
#[allow(dead_code)]
struct CheckInherents;
#[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,
                core::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>,
}