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
    serde::{Deserialize, Serialize},
68
    smallvec::smallvec,
69
    sp_api::impl_runtime_apis,
70
    sp_consensus_slots::{Slot, SlotDuration},
71
    sp_core::{MaxEncodedLen, OpaqueMetadata},
72
    sp_runtime::{
73
        create_runtime_str, generic, impl_opaque_keys,
74
        traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
75
        transaction_validity::{TransactionSource, TransactionValidity},
76
        ApplyExtrinsicResult, MultiSignature,
77
    },
78
    sp_std::prelude::*,
79
    sp_version::RuntimeVersion,
80
    staging_xcm::{
81
        IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
82
    },
83
    xcm_runtime_apis::{
84
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
85
        fees::Error as XcmPaymentApiError,
86
    },
87
};
88

            
89
pub mod xcm_config;
90

            
91
// Polkadot imports
92
use polkadot_runtime_common::BlockHashCount;
93

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

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

            
101
/// Balance of an account.
102
pub type Balance = u128;
103

            
104
/// Index of a transaction in the chain.
105
pub type Index = u32;
106

            
107
/// A hash of some data used by the chain.
108
pub type Hash = sp_core::H256;
109

            
110
/// An index to a block.
111
pub type BlockNumber = u32;
112

            
113
/// The address format for describing accounts.
114
pub type Address = MultiAddress<AccountId, ()>;
115

            
116
/// Block header type as expected by this runtime.
117
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
118

            
119
/// Block type as expected by this runtime.
120
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
121

            
122
/// A Block signed with a Justification
123
pub type SignedBlock = generic::SignedBlock<Block>;
124

            
125
/// BlockId type as expected by this runtime.
126
pub type BlockId = generic::BlockId<Block>;
127

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

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

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

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

            
157
pub mod currency {
158
    use super::Balance;
159

            
160
    pub const MICROUNIT: Balance = 1_000_000;
161
    pub const MILLIUNIT: Balance = 1_000_000_000;
162
    pub const UNIT: Balance = 1_000_000_000_000;
163
    pub const KILOUNIT: Balance = 1_000_000_000_000_000;
164

            
165
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
166

            
167
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
168
        items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
169
    }
170
}
171

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

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

            
209
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
210
    /// Opaque block header type.
211
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
212
    /// Opaque block type.
213
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
214
    /// Opaque block identifier type.
215
    pub type BlockId = generic::BlockId<Block>;
216
}
217

            
218
impl_opaque_keys! {
219
    pub struct SessionKeys { }
220
}
221

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

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

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

            
246
// Time is measured by number of blocks.
247
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
248
pub const HOURS: BlockNumber = MINUTES * 60;
249
pub const DAYS: BlockNumber = HOURS * 24;
250

            
251
pub const SUPPLY_FACTOR: Balance = 100;
252

            
253
// Unit = the base number of indivisible units for balances
254
pub const UNIT: Balance = 1_000_000_000_000;
255
pub const MILLIUNIT: Balance = 1_000_000_000;
256
pub const MICROUNIT: Balance = 1_000_000;
257

            
258
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
259

            
260
pub const fn deposit(items: u32, bytes: u32) -> Balance {
261
    items as Balance * 100 * MILLIUNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
262
}
263

            
264
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
265
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
266

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

            
271
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
272
/// `Operational` extrinsics.
273
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
274

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

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

            
290
parameter_types! {
291
    pub const Version: RuntimeVersion = VERSION;
292

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

            
320
// Configure FRAME pallets to include in runtime.
321

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

            
376
parameter_types! {
377
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
378
}
379

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

            
398
parameter_types! {
399
    pub const TransactionByteFee: Balance = 1;
400
}
401

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

            
412
parameter_types! {
413
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
414
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
415
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
416
}
417

            
418
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
419
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
420
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
421

            
422
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
423
    Runtime,
424
    BLOCK_PROCESSING_VELOCITY,
425
    UNINCLUDED_SEGMENT_CAPACITY,
426
>;
427

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

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

            
450
parameter_types! {
451
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
452
}
453

            
454
impl pallet_async_backing::Config for Runtime {
455
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
456
    type GetAndVerifySlot =
457
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
458
    type ExpectedBlockTime = ExpectedBlockTime;
459
}
460

            
461
impl parachain_info::Config for Runtime {}
462

            
463
parameter_types! {
464
    pub const Period: u32 = 6 * HOURS;
465
    pub const Offset: u32 = 0;
466
}
467

            
468
impl pallet_sudo::Config for Runtime {
469
    type RuntimeCall = RuntimeCall;
470
    type RuntimeEvent = RuntimeEvent;
471
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
472
}
473

            
474
impl pallet_utility::Config for Runtime {
475
    type RuntimeEvent = RuntimeEvent;
476
    type RuntimeCall = RuntimeCall;
477
    type PalletsOrigin = OriginCaller;
478
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
479
}
480

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

            
511
impl Default for ProxyType {
512
    fn default() -> Self {
513
        Self::Any
514
    }
515
}
516

            
517
impl InstanceFilter<RuntimeCall> for ProxyType {
518
    fn filter(&self, c: &RuntimeCall) -> bool {
519
        // Since proxy filters are respected in all dispatches of the Utility
520
        // pallet, it should never need to be filtered by any proxy.
521
        if let RuntimeCall::Utility(..) = c {
522
            return true;
523
        }
524

            
525
        match self {
526
            ProxyType::Any => true,
527
            ProxyType::NonTransfer => {
528
                matches!(
529
                    c,
530
                    RuntimeCall::System(..)
531
                        | RuntimeCall::ParachainSystem(..)
532
                        | RuntimeCall::Timestamp(..)
533
                        | RuntimeCall::Proxy(..)
534
                )
535
            }
536
            // We don't have governance yet
537
            ProxyType::Governance => false,
538
            ProxyType::CancelProxy => matches!(
539
                c,
540
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
541
            ),
542
            ProxyType::Balances => {
543
                matches!(c, RuntimeCall::Balances(..))
544
            }
545
        }
546
    }
547

            
548
    fn is_superset(&self, o: &Self) -> bool {
549
        match (self, o) {
550
            (x, y) if x == y => true,
551
            (ProxyType::Any, _) => true,
552
            (_, ProxyType::Any) => false,
553
            _ => false,
554
        }
555
    }
556
}
557

            
558
impl pallet_proxy::Config for Runtime {
559
    type RuntimeEvent = RuntimeEvent;
560
    type RuntimeCall = RuntimeCall;
561
    type Currency = Balances;
562
    type ProxyType = ProxyType;
563
    // One storage item; key size 32, value size 8
564
    type ProxyDepositBase = ConstU128<{ deposit(1, 8) }>;
565
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
566
    type ProxyDepositFactor = ConstU128<{ deposit(0, 33) }>;
567
    type MaxProxies = ConstU32<32>;
568
    type MaxPending = ConstU32<32>;
569
    type CallHasher = BlakeTwo256;
570
    type AnnouncementDepositBase = ConstU128<{ deposit(1, 8) }>;
571
    // Additional storage item size of 68 bytes:
572
    // - 32 bytes AccountId
573
    // - 32 bytes Hasher (Blake2256)
574
    // - 4 bytes BlockNumber (u32)
575
    type AnnouncementDepositFactor = ConstU128<{ deposit(0, 68) }>;
576
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
577
}
578

            
579
pub struct XcmExecutionManager;
580
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
581
    fn suspend_xcm_execution() -> DispatchResult {
582
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
583
    }
584
    fn resume_xcm_execution() -> DispatchResult {
585
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
586
    }
587
}
588

            
589
impl pallet_migrations::Config for Runtime {
590
    type RuntimeEvent = RuntimeEvent;
591
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
592
    type XcmExecutionManager = XcmExecutionManager;
593
}
594

            
595
/// Maintenance mode Call filter
596
pub struct MaintenanceFilter;
597
impl Contains<RuntimeCall> for MaintenanceFilter {
598
    fn contains(c: &RuntimeCall) -> bool {
599
        !matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
600
    }
601
}
602

            
603
/// Normal Call Filter
604
/// We dont allow to create nor mint assets, this for now is disabled
605
/// We only allow transfers. For now creation of assets will go through
606
/// asset-manager, while minting/burning only happens through xcm messages
607
/// This can change in the future
608
pub struct NormalFilter;
609
impl Contains<RuntimeCall> for NormalFilter {
610
    fn contains(_c: &RuntimeCall) -> bool {
611
        true
612
    }
613
}
614

            
615
impl pallet_maintenance_mode::Config for Runtime {
616
    type RuntimeEvent = RuntimeEvent;
617
    type NormalCallFilter = NormalFilter;
618
    type MaintenanceCallFilter = MaintenanceFilter;
619
    type MaintenanceOrigin = EnsureRoot<AccountId>;
620
    type XcmExecutionManager = XcmExecutionManager;
621
}
622

            
623
impl pallet_root_testing::Config for Runtime {
624
    type RuntimeEvent = RuntimeEvent;
625
}
626

            
627
impl pallet_tx_pause::Config for Runtime {
628
    type RuntimeEvent = RuntimeEvent;
629
    type RuntimeCall = RuntimeCall;
630
    type PauseOrigin = EnsureRoot<AccountId>;
631
    type UnpauseOrigin = EnsureRoot<AccountId>;
632
    type WhitelistedCalls = ();
633
    type MaxNameLen = ConstU32<256>;
634
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
635
}
636

            
637
impl dp_impl_tanssi_pallets_config::Config for Runtime {
638
    const SLOT_DURATION: u64 = SLOT_DURATION;
639
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
640
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
641
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
642
}
643

            
644
parameter_types! {
645
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
646
    pub const DepositBase: Balance = currency::deposit(1, 88);
647
    // Additional storage item size of 32 bytes.
648
    pub const DepositFactor: Balance = currency::deposit(0, 32);
649
    pub const MaxSignatories: u32 = 100;
650
}
651

            
652
impl pallet_multisig::Config for Runtime {
653
    type RuntimeEvent = RuntimeEvent;
654
    type RuntimeCall = RuntimeCall;
655
    type Currency = Balances;
656
    type DepositBase = DepositBase;
657
    type DepositFactor = DepositFactor;
658
    type MaxSignatories = MaxSignatories;
659
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
660
}
661

            
662
impl_tanssi_pallets_config!(Runtime);
663

            
664
// Create the runtime by composing the FRAME pallets that were previously configured.
665
25573
construct_runtime!(
666
3716
    pub enum Runtime
667
3716
    {
668
3716
        // System support stuff.
669
3716
        System: frame_system = 0,
670
3716
        ParachainSystem: cumulus_pallet_parachain_system = 1,
671
3716
        Timestamp: pallet_timestamp = 2,
672
3716
        ParachainInfo: parachain_info = 3,
673
3716
        Sudo: pallet_sudo = 4,
674
3716
        Utility: pallet_utility = 5,
675
3716
        Proxy: pallet_proxy = 6,
676
3716
        Migrations: pallet_migrations = 7,
677
3716
        MaintenanceMode: pallet_maintenance_mode = 8,
678
3716
        TxPause: pallet_tx_pause = 9,
679
3716

            
680
3716
        // Monetary stuff.
681
3716
        Balances: pallet_balances = 10,
682
3716
        TransactionPayment: pallet_transaction_payment = 11,
683
3716

            
684
3716
        // Other utilities
685
3716
        Multisig: pallet_multisig = 16,
686
3716

            
687
3716
        // ContainerChain Author Verification
688
3716
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
689
3716
        AuthorInherent: pallet_author_inherent = 51,
690
3716

            
691
3716
        // XCM
692
3716
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
693
3716
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
694
3716
        DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 72,
695
3716
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
696
3716
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
697
3716
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
698
3716
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
699
3716
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
700
3716
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
701
3716

            
702
3716
        RootTesting: pallet_root_testing = 100,
703
3716
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
704
3716

            
705
3716
    }
706
25573
);
707

            
708
#[cfg(feature = "runtime-benchmarks")]
709
mod benches {
710
    frame_benchmarking::define_benchmarks!(
711
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
712
        [cumulus_pallet_parachain_system, ParachainSystem]
713
        [pallet_timestamp, Timestamp]
714
        [pallet_sudo, Sudo]
715
        [pallet_utility, Utility]
716
        [pallet_proxy, Proxy]
717
        [pallet_tx_pause, TxPause]
718
        [pallet_balances, Balances]
719
        [pallet_multisig, Multisig]
720
        [pallet_cc_authorities_noting, AuthoritiesNoting]
721
        [pallet_author_inherent, AuthorInherent]
722
        [cumulus_pallet_xcmp_queue, XcmpQueue]
723
        [cumulus_pallet_dmp_queue, DmpQueue]
724
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
725
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
726
        [pallet_message_queue, MessageQueue]
727
        [pallet_assets, ForeignAssets]
728
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
729
        [pallet_asset_rate, AssetRate]
730
        [pallet_xcm_executor_utils, XcmExecutorUtils]
731
    );
732
}
733

            
734
6582
impl_runtime_apis! {
735
4470
    impl sp_api::Core<Block> for Runtime {
736
4470
        fn version() -> RuntimeVersion {
737
            VERSION
738
        }
739
4470

            
740
4470
        fn execute_block(block: Block) {
741
            Executive::execute_block(block)
742
        }
743
4470

            
744
4470
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
745
            Executive::initialize_block(header)
746
        }
747
4470
    }
748
4470

            
749
4470
    impl sp_api::Metadata<Block> for Runtime {
750
4470
        fn metadata() -> OpaqueMetadata {
751
            OpaqueMetadata::new(Runtime::metadata().into())
752
        }
753
4470

            
754
4470
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
755
            Runtime::metadata_at_version(version)
756
        }
757
4470

            
758
4470
        fn metadata_versions() -> Vec<u32> {
759
            Runtime::metadata_versions()
760
        }
761
4470
    }
762
4470

            
763
4470
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
764
4470
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
765
            Executive::apply_extrinsic(extrinsic)
766
        }
767
4470

            
768
4470
        fn finalize_block() -> <Block as BlockT>::Header {
769
            Executive::finalize_block()
770
        }
771
4470

            
772
4470
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
773
            data.create_extrinsics()
774
        }
775
4470

            
776
4470
        fn check_inherents(
777
            block: Block,
778
            data: sp_inherents::InherentData,
779
        ) -> sp_inherents::CheckInherentsResult {
780
            data.check_extrinsics(&block)
781
        }
782
4470
    }
783
4470

            
784
4470
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
785
4470
        fn validate_transaction(
786
            source: TransactionSource,
787
            tx: <Block as BlockT>::Extrinsic,
788
            block_hash: <Block as BlockT>::Hash,
789
        ) -> TransactionValidity {
790
            Executive::validate_transaction(source, tx, block_hash)
791
        }
792
4470
    }
793
4470

            
794
4470
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
795
4470
        fn offchain_worker(header: &<Block as BlockT>::Header) {
796
            Executive::offchain_worker(header)
797
        }
798
4470
    }
799
4470

            
800
4470
    impl sp_session::SessionKeys<Block> for Runtime {
801
4470
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
802
            SessionKeys::generate(seed)
803
        }
804
4470

            
805
4470
        fn decode_session_keys(
806
            encoded: Vec<u8>,
807
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
808
            SessionKeys::decode_into_raw_public_keys(&encoded)
809
        }
810
4470
    }
811
4470

            
812
4470
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
813
4470
        fn account_nonce(account: AccountId) -> Index {
814
            System::account_nonce(account)
815
        }
816
4470
    }
817
4470

            
818
4470
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
819
4470
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
820
            ParachainSystem::collect_collation_info(header)
821
        }
822
4470
    }
823
4470

            
824
4470
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
825
4470
        fn can_build_upon(
826
            included_hash: <Block as BlockT>::Hash,
827
            slot: async_backing_primitives::Slot,
828
        ) -> bool {
829
            ConsensusHook::can_build_upon(included_hash, slot)
830
        }
831
4470
    }
832
4470

            
833
4470
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
834
4470
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
835
            build_state::<RuntimeGenesisConfig>(config)
836
        }
837
4470

            
838
4470
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
839
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
840
        }
841
4470
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
842
            vec![]
843
        }
844
4470
    }
845
4470

            
846
4470
    #[cfg(feature = "runtime-benchmarks")]
847
4470
    impl frame_benchmarking::Benchmark<Block> for Runtime {
848
4470
        fn benchmark_metadata(
849
4470
            extra: bool,
850
4470
        ) -> (
851
4470
            Vec<frame_benchmarking::BenchmarkList>,
852
4470
            Vec<frame_support::traits::StorageInfo>,
853
4470
        ) {
854
4470
            use frame_benchmarking::{Benchmarking, BenchmarkList};
855
4470
            use frame_support::traits::StorageInfoTrait;
856
4470
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
857
4470

            
858
4470
            let mut list = Vec::<BenchmarkList>::new();
859
4470
            list_benchmarks!(list, extra);
860
4470

            
861
4470
            let storage_info = AllPalletsWithSystem::storage_info();
862
4470
            (list, storage_info)
863
4470
        }
864
4470

            
865
4470
        fn dispatch_benchmark(
866
4470
            config: frame_benchmarking::BenchmarkConfig,
867
4470
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
868
4470
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
869
4470
            use sp_core::storage::TrackedStorageKey;
870
4470
            use staging_xcm::latest::prelude::*;
871
4470
            impl frame_system_benchmarking::Config for Runtime {
872
4470
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
873
4470
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
874
4470
                    Ok(())
875
4470
                }
876
4470

            
877
4470
                fn verify_set_code() {
878
4470
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
879
4470
                }
880
4470
            }
881
4470
            use crate::xcm_config::SelfReserve;
882
4470
            parameter_types! {
883
4470
                pub ExistentialDepositAsset: Option<Asset> = Some((
884
4470
                    SelfReserve::get(),
885
4470
                    ExistentialDeposit::get()
886
4470
                ).into());
887
4470
            }
888
4470

            
889
4470
            impl pallet_xcm_benchmarks::Config for Runtime {
890
4470
                type XcmConfig = xcm_config::XcmConfig;
891
4470
                type AccountIdConverter = xcm_config::LocationToAccountId;
892
4470
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
893
4470
                xcm_config::XcmConfig,
894
4470
                ExistentialDepositAsset,
895
4470
                xcm_config::PriceForParentDelivery,
896
4470
                >;
897
4470
                fn valid_destination() -> Result<Location, BenchmarkError> {
898
4470
                    Ok(Location::parent())
899
4470
                }
900
4470
                fn worst_case_holding(_depositable_count: u32) -> Assets {
901
4470
                    // We only care for native asset until we support others
902
4470
                    // TODO: refactor this case once other assets are supported
903
4470
                    vec![Asset{
904
4470
                        id: AssetId(SelfReserve::get()),
905
4470
                        fun: Fungible(u128::MAX),
906
4470
                    }].into()
907
4470
                }
908
4470
            }
909
4470

            
910
4470
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
911
4470
                type TransactAsset = Balances;
912
4470
                type RuntimeCall = RuntimeCall;
913
4470

            
914
4470
                fn worst_case_response() -> (u64, Response) {
915
4470
                    (0u64, Response::Version(Default::default()))
916
4470
                }
917
4470

            
918
4470
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
919
4470
                    Err(BenchmarkError::Skip)
920
4470
                }
921
4470

            
922
4470
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
923
4470
                    Err(BenchmarkError::Skip)
924
4470
                }
925
4470

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

            
930
4470
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
931
4470
                    Ok(Location::parent())
932
4470
                }
933
4470

            
934
4470
                fn fee_asset() -> Result<Asset, BenchmarkError> {
935
4470
                    Ok(Asset {
936
4470
                        id: AssetId(SelfReserve::get()),
937
4470
                        fun: Fungible(ExistentialDeposit::get()*100),
938
4470
                    })
939
4470
                }
940
4470

            
941
4470
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
942
4470
                    let origin = Location::parent();
943
4470
                    let assets: Assets = (Location::parent(), 1_000u128).into();
944
4470
                    let ticket = Location { parents: 0, interior: Here };
945
4470
                    Ok((origin, ticket, assets))
946
4470
                }
947
4470

            
948
4470
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
949
4470
                    Err(BenchmarkError::Skip)
950
4470
                }
951
4470

            
952
4470
                fn export_message_origin_and_destination(
953
4470
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
954
4470
                    Err(BenchmarkError::Skip)
955
4470
                }
956
4470

            
957
4470
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
958
4470
                    Err(BenchmarkError::Skip)
959
4470
                }
960
4470
            }
961
4470

            
962
4470
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
963
4470
            impl pallet_xcm::benchmarking::Config for Runtime {
964
4470
                type DeliveryHelper = ();
965
4470
                fn get_asset() -> Asset {
966
4470
                    Asset {
967
4470
                        id: AssetId(SelfReserve::get()),
968
4470
                        fun: Fungible(ExistentialDeposit::get()),
969
4470
                    }
970
4470
                }
971
4470

            
972
4470
                fn reachable_dest() -> Option<Location> {
973
4470
                    Some(Parent.into())
974
4470
                }
975
4470

            
976
4470
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
977
4470
                    // Relay/native token can be teleported between AH and Relay.
978
4470
                    Some((
979
4470
                        Asset {
980
4470
                            fun: Fungible(EXISTENTIAL_DEPOSIT),
981
4470
                            id: Parent.into()
982
4470
                        },
983
4470
                        Parent.into(),
984
4470
                    ))
985
4470
                }
986
4470

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

            
4470
                fn set_up_complex_asset_transfer(
4470
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
4470
                    use xcm_config::SelfReserve;
4470
                    // Transfer to Relay some local AH asset (local-reserve-transfer) while paying
4470
                    // fees using teleported native token.
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_runtime_apis::fees::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
    }
4470

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

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

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