1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
#![cfg_attr(not(feature = "std"), no_std)]
18
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
19
#![recursion_limit = "256"]
20

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

            
25
use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
26
#[cfg(feature = "std")]
27
use sp_version::NativeVersion;
28

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

            
32
pub mod migrations;
33
pub mod weights;
34

            
35
pub use sp_runtime::{MultiAddress, Perbill, Permill};
36
use {
37
    cumulus_primitives_core::AggregateMessageOrigin,
38
    dp_impl_tanssi_pallets_config::impl_tanssi_pallets_config,
39
    frame_support::{
40
        construct_runtime,
41
        dispatch::DispatchClass,
42
        genesis_builder_helper::{build_state, get_preset},
43
        pallet_prelude::DispatchResult,
44
        parameter_types,
45
        traits::{
46
            tokens::ConversionToAssetBalance, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8,
47
            Contains, InsideBoth, InstanceFilter,
48
        },
49
        weights::{
50
            constants::{
51
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
52
                WEIGHT_REF_TIME_PER_SECOND,
53
            },
54
            ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
55
            WeightToFeeCoefficients, WeightToFeePolynomial,
56
        },
57
    },
58
    frame_system::{
59
        limits::{BlockLength, BlockWeights},
60
        EnsureRoot,
61
    },
62
    nimbus_primitives::{NimbusId, SlotBeacon},
63
    pallet_transaction_payment::FungibleAdapter,
64
    parity_scale_codec::{Decode, Encode},
65
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
66
    scale_info::TypeInfo,
67
    smallvec::smallvec,
68
    sp_api::impl_runtime_apis,
69
    sp_consensus_slots::{Slot, SlotDuration},
70
    sp_core::{MaxEncodedLen, OpaqueMetadata},
71
    sp_runtime::{
72
        create_runtime_str, generic, impl_opaque_keys,
73
        traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
74
        transaction_validity::{TransactionSource, TransactionValidity},
75
        ApplyExtrinsicResult, MultiSignature,
76
    },
77
    sp_std::prelude::*,
78
    sp_version::RuntimeVersion,
79
    staging_xcm::{
80
        IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
81
    },
82
    xcm_fee_payment_runtime_api::Error as XcmPaymentApiError,
83
};
84

            
85
pub mod xcm_config;
86

            
87
// Polkadot imports
88
use polkadot_runtime_common::BlockHashCount;
89

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

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

            
97
/// Balance of an account.
98
pub type Balance = u128;
99

            
100
/// Index of a transaction in the chain.
101
pub type Index = u32;
102

            
103
/// A hash of some data used by the chain.
104
pub type Hash = sp_core::H256;
105

            
106
/// An index to a block.
107
pub type BlockNumber = u32;
108

            
109
/// The address format for describing accounts.
110
pub type Address = MultiAddress<AccountId, ()>;
111

            
112
/// Block header type as expected by this runtime.
113
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
114

            
115
/// Block type as expected by this runtime.
116
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
117

            
118
/// A Block signed with a Justification
119
pub type SignedBlock = generic::SignedBlock<Block>;
120

            
121
/// BlockId type as expected by this runtime.
122
pub type BlockId = generic::BlockId<Block>;
123

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

            
137
/// Unchecked extrinsic type as expected by this runtime.
138
pub type UncheckedExtrinsic =
139
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
140

            
141
/// Extrinsic type that has already been checked.
142
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
143

            
144
/// Executive: handles dispatch to the various modules.
145
pub type Executive = frame_executive::Executive<
146
    Runtime,
147
    Block,
148
    frame_system::ChainContext<Runtime>,
149
    Runtime,
150
    AllPalletsWithSystem,
151
>;
152

            
153
pub mod currency {
154
    use super::Balance;
155

            
156
    pub const MICROUNIT: Balance = 1_000_000;
157
    pub const MILLIUNIT: Balance = 1_000_000_000;
158
    pub const UNIT: Balance = 1_000_000_000_000;
159
    pub const KILOUNIT: Balance = 1_000_000_000_000_000;
160

            
161
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
162

            
163
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
164
        items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
165
    }
166
}
167

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

            
195
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
196
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
197
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
198
/// to even the core data structures.
199
pub mod opaque {
200
    use {
201
        super::*,
202
        sp_runtime::{generic, traits::BlakeTwo256},
203
    };
204

            
205
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
206
    /// Opaque block header type.
207
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
208
    /// Opaque block type.
209
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
210
    /// Opaque block identifier type.
211
    pub type BlockId = generic::BlockId<Block>;
212
}
213

            
214
impl_opaque_keys! {
215
    pub struct SessionKeys { }
216
}
217

            
218
#[sp_version::runtime_version]
219
pub const VERSION: RuntimeVersion = RuntimeVersion {
220
    spec_name: create_runtime_str!("container-chain-template"),
221
    impl_name: create_runtime_str!("container-chain-template"),
222
    authoring_version: 1,
223
    spec_version: 800,
224
    impl_version: 0,
225
    apis: RUNTIME_API_VERSIONS,
226
    transaction_version: 1,
227
    state_version: 1,
228
};
229

            
230
/// This determines the average expected block time that we are targeting.
231
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
232
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
233
/// up by `pallet_aura` to implement `fn slot_duration()`.
234
///
235
/// Change this to adjust the block time.
236
pub const MILLISECS_PER_BLOCK: u64 = 6000;
237

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

            
242
// Time is measured by number of blocks.
243
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
244
pub const HOURS: BlockNumber = MINUTES * 60;
245
pub const DAYS: BlockNumber = HOURS * 24;
246

            
247
pub const SUPPLY_FACTOR: Balance = 100;
248

            
249
// Unit = the base number of indivisible units for balances
250
pub const UNIT: Balance = 1_000_000_000_000;
251
pub const MILLIUNIT: Balance = 1_000_000_000;
252
pub const MICROUNIT: Balance = 1_000_000;
253

            
254
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
255

            
256
pub const fn deposit(items: u32, bytes: u32) -> Balance {
257
    items as Balance * 100 * MILLIUNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
258
}
259

            
260
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
261
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
262

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

            
267
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
268
/// `Operational` extrinsics.
269
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
270

            
271
/// We allow for 0.5 of a second of compute with a 12 second average block time.
272
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
273
    WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
274
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
275
);
276

            
277
/// The version information used to identify this runtime when compiled natively.
278
#[cfg(feature = "std")]
279
pub fn native_version() -> NativeVersion {
280
    NativeVersion {
281
        runtime_version: VERSION,
282
        can_author_with: Default::default(),
283
    }
284
}
285

            
286
parameter_types! {
287
    pub const Version: RuntimeVersion = VERSION;
288

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

            
316
// Configure FRAME pallets to include in runtime.
317

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

            
372
parameter_types! {
373
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
374
}
375

            
376
impl pallet_balances::Config for Runtime {
377
    type MaxLocks = ConstU32<50>;
378
    /// The type for recording an account's balance.
379
    type Balance = Balance;
380
    /// The ubiquitous event type.
381
    type RuntimeEvent = RuntimeEvent;
382
    type DustRemoval = ();
383
    type ExistentialDeposit = ExistentialDeposit;
384
    type AccountStore = System;
385
    type MaxReserves = ConstU32<50>;
386
    type ReserveIdentifier = [u8; 8];
387
    type FreezeIdentifier = RuntimeFreezeReason;
388
    type MaxFreezes = ConstU32<0>;
389
    type RuntimeHoldReason = RuntimeHoldReason;
390
    type RuntimeFreezeReason = RuntimeFreezeReason;
391
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
392
}
393

            
394
parameter_types! {
395
    pub const TransactionByteFee: Balance = 1;
396
}
397

            
398
impl pallet_transaction_payment::Config for Runtime {
399
    type RuntimeEvent = RuntimeEvent;
400
    // This will burn the fees
401
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
402
    type OperationalFeeMultiplier = ConstU8<5>;
403
    type WeightToFee = WeightToFee;
404
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
405
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
406
}
407

            
408
parameter_types! {
409
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
410
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
411
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
412
}
413

            
414
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
415
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
416
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
417

            
418
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
419
    Runtime,
420
    BLOCK_PROCESSING_VELOCITY,
421
    UNINCLUDED_SEGMENT_CAPACITY,
422
>;
423

            
424
impl cumulus_pallet_parachain_system::Config for Runtime {
425
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
426
    type RuntimeEvent = RuntimeEvent;
427
    type OnSystemEvent = ();
428
    type OutboundXcmpMessageSource = XcmpQueue;
429
    type SelfParaId = parachain_info::Pallet<Runtime>;
430
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
431
    type ReservedDmpWeight = ReservedDmpWeight;
432
    type XcmpMessageHandler = XcmpQueue;
433
    type ReservedXcmpWeight = ReservedXcmpWeight;
434
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
435
    type ConsensusHook = ConsensusHook;
436
}
437

            
438
pub struct ParaSlotProvider;
439
impl sp_core::Get<(Slot, SlotDuration)> for ParaSlotProvider {
440
126
    fn get() -> (Slot, SlotDuration) {
441
126
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
442
126
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
443
126
    }
444
}
445

            
446
parameter_types! {
447
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
448
}
449

            
450
impl pallet_async_backing::Config for Runtime {
451
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
452
    type GetAndVerifySlot =
453
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
454
    type ExpectedBlockTime = ExpectedBlockTime;
455
}
456

            
457
impl parachain_info::Config for Runtime {}
458

            
459
parameter_types! {
460
    pub const Period: u32 = 6 * HOURS;
461
    pub const Offset: u32 = 0;
462
}
463

            
464
impl pallet_sudo::Config for Runtime {
465
    type RuntimeCall = RuntimeCall;
466
    type RuntimeEvent = RuntimeEvent;
467
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
468
}
469

            
470
impl pallet_utility::Config for Runtime {
471
    type RuntimeEvent = RuntimeEvent;
472
    type RuntimeCall = RuntimeCall;
473
    type PalletsOrigin = OriginCaller;
474
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
475
}
476

            
477
/// The type used to represent the kinds of proxying allowed.
478
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
479
#[derive(
480
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
481
)]
482
#[allow(clippy::unnecessary_cast)]
483
pub enum ProxyType {
484
    /// All calls can be proxied. This is the trivial/most permissive filter.
485
    Any = 0,
486
    /// Only extrinsics that do not transfer funds.
487
    NonTransfer = 1,
488
    /// Only extrinsics related to governance (democracy and collectives).
489
    Governance = 2,
490
    /// Allow to veto an announced proxy call.
491
    CancelProxy = 3,
492
    /// Allow extrinsic related to Balances.
493
    Balances = 4,
494
}
495

            
496
impl Default for ProxyType {
497
    fn default() -> Self {
498
        Self::Any
499
    }
500
}
501

            
502
impl InstanceFilter<RuntimeCall> for ProxyType {
503
    fn filter(&self, c: &RuntimeCall) -> bool {
504
        // Since proxy filters are respected in all dispatches of the Utility
505
        // pallet, it should never need to be filtered by any proxy.
506
        if let RuntimeCall::Utility(..) = c {
507
            return true;
508
        }
509

            
510
        match self {
511
            ProxyType::Any => true,
512
            ProxyType::NonTransfer => {
513
                matches!(
514
                    c,
515
                    RuntimeCall::System(..)
516
                        | RuntimeCall::ParachainSystem(..)
517
                        | RuntimeCall::Timestamp(..)
518
                        | RuntimeCall::Proxy(..)
519
                )
520
            }
521
            // We don't have governance yet
522
            ProxyType::Governance => false,
523
            ProxyType::CancelProxy => matches!(
524
                c,
525
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
526
            ),
527
            ProxyType::Balances => {
528
                matches!(c, RuntimeCall::Balances(..))
529
            }
530
        }
531
    }
532

            
533
    fn is_superset(&self, o: &Self) -> bool {
534
        match (self, o) {
535
            (x, y) if x == y => true,
536
            (ProxyType::Any, _) => true,
537
            (_, ProxyType::Any) => false,
538
            _ => false,
539
        }
540
    }
541
}
542

            
543
impl pallet_proxy::Config for Runtime {
544
    type RuntimeEvent = RuntimeEvent;
545
    type RuntimeCall = RuntimeCall;
546
    type Currency = Balances;
547
    type ProxyType = ProxyType;
548
    // One storage item; key size 32, value size 8
549
    type ProxyDepositBase = ConstU128<{ deposit(1, 8) }>;
550
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
551
    type ProxyDepositFactor = ConstU128<{ deposit(0, 33) }>;
552
    type MaxProxies = ConstU32<32>;
553
    type MaxPending = ConstU32<32>;
554
    type CallHasher = BlakeTwo256;
555
    type AnnouncementDepositBase = ConstU128<{ deposit(1, 8) }>;
556
    // Additional storage item size of 68 bytes:
557
    // - 32 bytes AccountId
558
    // - 32 bytes Hasher (Blake2256)
559
    // - 4 bytes BlockNumber (u32)
560
    type AnnouncementDepositFactor = ConstU128<{ deposit(0, 68) }>;
561
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
562
}
563

            
564
pub struct XcmExecutionManager;
565
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
566
    fn suspend_xcm_execution() -> DispatchResult {
567
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
568
    }
569
    fn resume_xcm_execution() -> DispatchResult {
570
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
571
    }
572
}
573

            
574
impl pallet_migrations::Config for Runtime {
575
    type RuntimeEvent = RuntimeEvent;
576
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
577
    type XcmExecutionManager = XcmExecutionManager;
578
}
579

            
580
/// Maintenance mode Call filter
581
pub struct MaintenanceFilter;
582
impl Contains<RuntimeCall> for MaintenanceFilter {
583
    fn contains(c: &RuntimeCall) -> bool {
584
        !matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
585
    }
586
}
587

            
588
/// Normal Call Filter
589
/// We dont allow to create nor mint assets, this for now is disabled
590
/// We only allow transfers. For now creation of assets will go through
591
/// asset-manager, while minting/burning only happens through xcm messages
592
/// This can change in the future
593
pub struct NormalFilter;
594
impl Contains<RuntimeCall> for NormalFilter {
595
    fn contains(_c: &RuntimeCall) -> bool {
596
        true
597
    }
598
}
599

            
600
impl pallet_maintenance_mode::Config for Runtime {
601
    type RuntimeEvent = RuntimeEvent;
602
    type NormalCallFilter = NormalFilter;
603
    type MaintenanceCallFilter = MaintenanceFilter;
604
    type MaintenanceOrigin = EnsureRoot<AccountId>;
605
    type XcmExecutionManager = XcmExecutionManager;
606
}
607

            
608
impl pallet_root_testing::Config for Runtime {
609
    type RuntimeEvent = RuntimeEvent;
610
}
611

            
612
impl pallet_tx_pause::Config for Runtime {
613
    type RuntimeEvent = RuntimeEvent;
614
    type RuntimeCall = RuntimeCall;
615
    type PauseOrigin = EnsureRoot<AccountId>;
616
    type UnpauseOrigin = EnsureRoot<AccountId>;
617
    type WhitelistedCalls = ();
618
    type MaxNameLen = ConstU32<256>;
619
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
620
}
621

            
622
impl dp_impl_tanssi_pallets_config::Config for Runtime {
623
    const SLOT_DURATION: u64 = SLOT_DURATION;
624
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
625
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
626
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
627
}
628

            
629
parameter_types! {
630
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
631
    pub const DepositBase: Balance = currency::deposit(1, 88);
632
    // Additional storage item size of 32 bytes.
633
    pub const DepositFactor: Balance = currency::deposit(0, 32);
634
    pub const MaxSignatories: u32 = 100;
635
}
636

            
637
impl pallet_multisig::Config for Runtime {
638
    type RuntimeEvent = RuntimeEvent;
639
    type RuntimeCall = RuntimeCall;
640
    type Currency = Balances;
641
    type DepositBase = DepositBase;
642
    type DepositFactor = DepositFactor;
643
    type MaxSignatories = MaxSignatories;
644
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
645
}
646

            
647
impl_tanssi_pallets_config!(Runtime);
648

            
649
// Create the runtime by composing the FRAME pallets that were previously configured.
650
25573
construct_runtime!(
651
3716
    pub enum Runtime
652
3716
    {
653
3716
        // System support stuff.
654
3716
        System: frame_system = 0,
655
3716
        ParachainSystem: cumulus_pallet_parachain_system = 1,
656
3716
        Timestamp: pallet_timestamp = 2,
657
3716
        ParachainInfo: parachain_info = 3,
658
3716
        Sudo: pallet_sudo = 4,
659
3716
        Utility: pallet_utility = 5,
660
3716
        Proxy: pallet_proxy = 6,
661
3716
        Migrations: pallet_migrations = 7,
662
3716
        MaintenanceMode: pallet_maintenance_mode = 8,
663
3716
        TxPause: pallet_tx_pause = 9,
664
3716

            
665
3716
        // Monetary stuff.
666
3716
        Balances: pallet_balances = 10,
667
3716
        TransactionPayment: pallet_transaction_payment = 11,
668
3716

            
669
3716
        // Other utilities
670
3716
        Multisig: pallet_multisig = 16,
671
3716

            
672
3716
        // ContainerChain Author Verification
673
3716
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
674
3716
        AuthorInherent: pallet_author_inherent = 51,
675
3716

            
676
3716
        // XCM
677
3716
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
678
3716
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
679
3716
        DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 72,
680
3716
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
681
3716
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
682
3716
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
683
3716
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
684
3716
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
685
3716
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
686
3716

            
687
3716
        RootTesting: pallet_root_testing = 100,
688
3716
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
689
3716

            
690
3716
    }
691
25573
);
692

            
693
#[cfg(feature = "runtime-benchmarks")]
694
mod benches {
695
    frame_benchmarking::define_benchmarks!(
696
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
697
        [cumulus_pallet_parachain_system, ParachainSystem]
698
        [pallet_timestamp, Timestamp]
699
        [pallet_sudo, Sudo]
700
        [pallet_utility, Utility]
701
        [pallet_proxy, Proxy]
702
        [pallet_tx_pause, TxPause]
703
        [pallet_balances, Balances]
704
        [pallet_multisig, Multisig]
705
        [pallet_cc_authorities_noting, AuthoritiesNoting]
706
        [pallet_author_inherent, AuthorInherent]
707
        [cumulus_pallet_xcmp_queue, XcmpQueue]
708
        [cumulus_pallet_dmp_queue, DmpQueue]
709
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
710
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
711
        [pallet_message_queue, MessageQueue]
712
        [pallet_assets, ForeignAssets]
713
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
714
        [pallet_asset_rate, AssetRate]
715
        [pallet_xcm_executor_utils, XcmExecutorUtils]
716
    );
717
}
718

            
719
6568
impl_runtime_apis! {
720
4470
    impl sp_api::Core<Block> for Runtime {
721
4470
        fn version() -> RuntimeVersion {
722
            VERSION
723
        }
724
4470

            
725
4470
        fn execute_block(block: Block) {
726
            Executive::execute_block(block)
727
        }
728
4470

            
729
4470
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
730
            Executive::initialize_block(header)
731
        }
732
4470
    }
733
4470

            
734
4470
    impl sp_api::Metadata<Block> for Runtime {
735
4470
        fn metadata() -> OpaqueMetadata {
736
            OpaqueMetadata::new(Runtime::metadata().into())
737
        }
738
4470

            
739
4470
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
740
            Runtime::metadata_at_version(version)
741
        }
742
4470

            
743
4470
        fn metadata_versions() -> Vec<u32> {
744
            Runtime::metadata_versions()
745
        }
746
4470
    }
747
4470

            
748
4470
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
749
4470
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
750
            Executive::apply_extrinsic(extrinsic)
751
        }
752
4470

            
753
4470
        fn finalize_block() -> <Block as BlockT>::Header {
754
            Executive::finalize_block()
755
        }
756
4470

            
757
4470
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
758
            data.create_extrinsics()
759
        }
760
4470

            
761
4470
        fn check_inherents(
762
            block: Block,
763
            data: sp_inherents::InherentData,
764
        ) -> sp_inherents::CheckInherentsResult {
765
            data.check_extrinsics(&block)
766
        }
767
4470
    }
768
4470

            
769
4470
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
770
4470
        fn validate_transaction(
771
            source: TransactionSource,
772
            tx: <Block as BlockT>::Extrinsic,
773
            block_hash: <Block as BlockT>::Hash,
774
        ) -> TransactionValidity {
775
            Executive::validate_transaction(source, tx, block_hash)
776
        }
777
4470
    }
778
4470

            
779
4470
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
780
4470
        fn offchain_worker(header: &<Block as BlockT>::Header) {
781
            Executive::offchain_worker(header)
782
        }
783
4470
    }
784
4470

            
785
4470
    impl sp_session::SessionKeys<Block> for Runtime {
786
4470
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
787
            SessionKeys::generate(seed)
788
        }
789
4470

            
790
4470
        fn decode_session_keys(
791
            encoded: Vec<u8>,
792
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
793
            SessionKeys::decode_into_raw_public_keys(&encoded)
794
        }
795
4470
    }
796
4470

            
797
4470
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
798
4470
        fn account_nonce(account: AccountId) -> Index {
799
            System::account_nonce(account)
800
        }
801
4470
    }
802
4470

            
803
4470
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
804
4470
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
805
            ParachainSystem::collect_collation_info(header)
806
        }
807
4470
    }
808
4470

            
809
4470
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
810
4470
        fn can_build_upon(
811
            included_hash: <Block as BlockT>::Hash,
812
            slot: async_backing_primitives::Slot,
813
        ) -> bool {
814
            ConsensusHook::can_build_upon(included_hash, slot)
815
        }
816
4470
    }
817
4470

            
818
4470
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
819
4470
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
820
            build_state::<RuntimeGenesisConfig>(config)
821
        }
822
4470

            
823
4470
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
824
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
825
        }
826
4470
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
827
            vec![]
828
        }
829
4470
    }
830
4470

            
831
4470
    #[cfg(feature = "runtime-benchmarks")]
832
4470
    impl frame_benchmarking::Benchmark<Block> for Runtime {
833
4470
        fn benchmark_metadata(
834
4470
            extra: bool,
835
4470
        ) -> (
836
4470
            Vec<frame_benchmarking::BenchmarkList>,
837
4470
            Vec<frame_support::traits::StorageInfo>,
838
4470
        ) {
839
4470
            use frame_benchmarking::{Benchmarking, BenchmarkList};
840
4470
            use frame_support::traits::StorageInfoTrait;
841
4470
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
842
4470

            
843
4470
            let mut list = Vec::<BenchmarkList>::new();
844
4470
            list_benchmarks!(list, extra);
845
4470

            
846
4470
            let storage_info = AllPalletsWithSystem::storage_info();
847
4470
            (list, storage_info)
848
4470
        }
849
4470

            
850
4470
        fn dispatch_benchmark(
851
4470
            config: frame_benchmarking::BenchmarkConfig,
852
4470
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
853
4470
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
854
4470
            use sp_core::storage::TrackedStorageKey;
855
4470
            use staging_xcm::latest::prelude::*;
856
4470
            impl frame_system_benchmarking::Config for Runtime {
857
4470
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
858
4470
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
859
4470
                    Ok(())
860
4470
                }
861
4470

            
862
4470
                fn verify_set_code() {
863
4470
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
864
4470
                }
865
4470
            }
866
4470
            use crate::xcm_config::SelfReserve;
867
4470
            parameter_types! {
868
4470
                pub ExistentialDepositAsset: Option<Asset> = Some((
869
4470
                    SelfReserve::get(),
870
4470
                    ExistentialDeposit::get()
871
4470
                ).into());
872
4470
            }
873
4470

            
874
4470
            impl pallet_xcm_benchmarks::Config for Runtime {
875
4470
                type XcmConfig = xcm_config::XcmConfig;
876
4470
                type AccountIdConverter = xcm_config::LocationToAccountId;
877
4470
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
878
4470
                xcm_config::XcmConfig,
879
4470
                ExistentialDepositAsset,
880
4470
                xcm_config::PriceForParentDelivery,
881
4470
                >;
882
4470
                fn valid_destination() -> Result<Location, BenchmarkError> {
883
4470
                    Ok(Location::parent())
884
4470
                }
885
4470
                fn worst_case_holding(_depositable_count: u32) -> Assets {
886
4470
                    // We only care for native asset until we support others
887
4470
                    // TODO: refactor this case once other assets are supported
888
4470
                    vec![Asset{
889
4470
                        id: AssetId(SelfReserve::get()),
890
4470
                        fun: Fungible(u128::MAX),
891
4470
                    }].into()
892
4470
                }
893
4470
            }
894
4470

            
895
4470
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
896
4470
                type TransactAsset = Balances;
897
4470
                type RuntimeCall = RuntimeCall;
898
4470

            
899
4470
                fn worst_case_response() -> (u64, Response) {
900
4470
                    (0u64, Response::Version(Default::default()))
901
4470
                }
902
4470

            
903
4470
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
904
4470
                    Err(BenchmarkError::Skip)
905
4470
                }
906
4470

            
907
4470
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
908
4470
                    Err(BenchmarkError::Skip)
909
4470
                }
910
4470

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

            
915
4470
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
916
4470
                    Ok(Location::parent())
917
4470
                }
918
4470

            
919
4470
                fn fee_asset() -> Result<Asset, BenchmarkError> {
920
4470
                    Ok(Asset {
921
4470
                        id: AssetId(SelfReserve::get()),
922
4470
                        fun: Fungible(ExistentialDeposit::get()*100),
923
4470
                    })
924
4470
                }
925
4470

            
926
4470
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
927
4470
                    let origin = Location::parent();
928
4470
                    let assets: Assets = (Location::parent(), 1_000u128).into();
929
4470
                    let ticket = Location { parents: 0, interior: Here };
930
4470
                    Ok((origin, ticket, assets))
931
4470
                }
932
4470

            
933
4470
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
934
4470
                    Err(BenchmarkError::Skip)
935
4470
                }
936
4470

            
937
4470
                fn export_message_origin_and_destination(
938
4470
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
939
4470
                    Err(BenchmarkError::Skip)
940
4470
                }
941
4470

            
942
4470
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
943
4470
                    Err(BenchmarkError::Skip)
944
4470
                }
945
4470
            }
946
4470

            
947
4470
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
948
4470
            impl pallet_xcm::benchmarking::Config for Runtime {
949
4470
                type DeliveryHelper = ();
950
4470
                fn get_asset() -> Asset {
951
4470
                    Asset {
952
4470
                        id: AssetId(SelfReserve::get()),
953
4470
                        fun: Fungible(ExistentialDeposit::get()),
954
4470
                    }
955
4470
                }
956
4470

            
957
4470
                fn reachable_dest() -> Option<Location> {
958
4470
                    Some(Parent.into())
959
4470
                }
960
4470

            
961
4470
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
962
4470
                    // Relay/native token can be teleported between AH and Relay.
963
4470
                    Some((
964
4470
                        Asset {
965
4470
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
966
4470
                            id: Parent.into()
967
4470
                        },
968
4470
                        Parent.into(),
969
4470
                    ))
970
4470
                }
971
4470

            
972
4470
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
973
4470
                    use xcm_config::SelfReserve;
974
4470
                    // AH can reserve transfer native token to some random parachain.
975
4470
                    let random_para_id = 43211234;
976
4470
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
977
4470
                        random_para_id.into()
978
4470
                    );
979
4470
                    let who = frame_benchmarking::whitelisted_caller();
980
4470
                    // Give some multiple of the existential deposit
981
4470
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
982
4470
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
983
4470
                        &who, balance,
984
4470
                    );
985
4470
                    Some((
986
4470
                        Asset {
987
4470
                            fun: Fungible(EXISTENTIAL_DEPOSIT*10),
988
4470
                            id: SelfReserve::get().into()
989
4470
                        },
990
4470
                        ParentThen(Parachain(random_para_id).into()).into(),
991
4470
                    ))
992
4470
                }
993
4470

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

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

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

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

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

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

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

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

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

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

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

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

            
4470
            add_benchmarks!(params, batches);
4470

            
4470
            Ok(batches)
4470
        }
4470
    }
4470

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

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

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

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

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

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

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

            
4470
    impl xcm_fee_payment_runtime_api::XcmPaymentApi<Block> for Runtime {
4470
        fn query_acceptable_payment_assets(xcm_version: staging_xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
4470
            if !matches!(xcm_version, 3 | 4) {
4470
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
4470
            }
            Ok([VersionedAssetId::V4(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::V4(location.into())
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
4470
                            None
                        })
                    })
                )
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
4470
                }).ok())
                .collect())
4470
        }
4470

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

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

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

            
4470
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
4470
    }
6568
}
#[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,
                sp_std::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}