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::Version as XcmVersion,
88
    xcm::{
89
        v5::NetworkId, IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation,
90
        VersionedXcm,
91
    },
92
    xcm_runtime_apis::{
93
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
94
        fees::Error as XcmPaymentApiError,
95
    },
96
};
97

            
98
pub mod xcm_config;
99

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
237
impl_opaque_keys! {
238
    pub struct SessionKeys { }
239
}
240

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

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

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

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

            
270
pub const SUPPLY_FACTOR: Balance = 100;
271

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

            
277
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
278

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

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

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

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

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

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

            
309
parameter_types! {
310
    pub const Version: RuntimeVersion = VERSION;
311

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

            
339
// Configure FRAME pallets to include in runtime.
340

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

            
396
parameter_types! {
397
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
398
}
399

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

            
419
parameter_types! {
420
    pub const TransactionByteFee: Balance = 1;
421
}
422

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

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

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

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

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

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

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

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

            
481
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
482
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
483
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
484

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

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

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

            
514
parameter_types! {
515
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
516
}
517

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

            
525
impl parachain_info::Config for Runtime {}
526

            
527
parameter_types! {
528
    pub const Period: u32 = 6 * HOURS;
529
    pub const Offset: u32 = 0;
530
}
531

            
532
impl pallet_sudo::Config for Runtime {
533
    type RuntimeCall = RuntimeCall;
534
    type RuntimeEvent = RuntimeEvent;
535
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
536
}
537

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

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

            
576
impl Default for ProxyType {
577
    fn default() -> Self {
578
        Self::Any
579
    }
580
}
581

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
826
impl pallet_ocw_testing::Config for Runtime {
827
    type RuntimeEvent = RuntimeEvent;
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
21339
construct_runtime!(
839
21339
    pub enum Runtime
840
21339
    {
841
21339
        // System support stuff.
842
21339
        System: frame_system = 0,
843
21339
        ParachainSystem: cumulus_pallet_parachain_system = 1,
844
21339
        Timestamp: pallet_timestamp = 2,
845
21339
        ParachainInfo: parachain_info = 3,
846
21339
        Sudo: pallet_sudo = 4,
847
21339
        Utility: pallet_utility = 5,
848
21339
        Proxy: pallet_proxy = 6,
849
21339
        Migrations: pallet_migrations = 7,
850
21339
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
851
21339
        MaintenanceMode: pallet_maintenance_mode = 8,
852
21339
        TxPause: pallet_tx_pause = 9,
853
21339

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

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

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

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

            
876
21339
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
877
21339

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

            
881
21339
        OffchainWorker: pallet_ocw_testing::{Pallet, Call, Storage, Event<T>, ValidateUnsigned} = 120,
882
21339
    }
883
21339
);
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
5408
impl_runtime_apis! {
915
5408
    impl sp_api::Core<Block> for Runtime {
916
5408
        fn version() -> RuntimeVersion {
917
5408
            VERSION
918
5408
        }
919
5408

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
5408
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
5408
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
5408
        }
5408
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
5408
            vec![]
5408
        }
5408
    }
5408

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

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

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

            
5408
        #[allow(non_local_definitions)]
5408
        fn dispatch_benchmark(
5408
            config: frame_benchmarking::BenchmarkConfig,
5408
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
5408
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
5408
            use sp_core::storage::TrackedStorageKey;
5408
            use xcm::latest::prelude::*;
5408
            use alloc::boxed::Box;
5408

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

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

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

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

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

            
5408
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
5408
                    tanssi_runtime_common::universal_aliases::AliasingBenchmarksHelper::prepare_universal_alias()
5408
                    .ok_or(BenchmarkError::Skip)
5408
                }
5408

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
5408
                    let (asset_id, asset_location) = pallet_foreign_asset_creator::benchmarks::create_default_minted_asset::<Runtime>(
5408
                        initial_asset_amount,
5408
                        who.clone()
5408
                    );
5408

            
5408
                    let transfer_asset: Asset = (asset_location, asset_amount).into();
5408

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

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

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

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

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

            
5408
            add_benchmarks!(params, batches);
5408

            
5408
            Ok(batches)
5408
        }
5408
    }
5408

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

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

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

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

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

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

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

            
5408
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
5408
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
5408
            if !matches!(xcm_version, 3..=5) {
5408
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
5408
            }
5408

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

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

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

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

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

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

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

            
5408
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
5408
        fn convert_location(location: VersionedLocation) -> Result<
5408
            AccountId,
5408
            xcm_runtime_apis::conversions::Error
5408
        > {
5408
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
5408
                AccountId,
5408
                xcm_config::LocationToAccountId,
5408
            >::convert_location(location)
5408
        }
5408
    }
7642
}
#[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>,
}