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
mod precompiles;
34
pub mod weights;
35
pub mod xcm_config;
36

            
37
use {
38
    crate::precompiles::TemplatePrecompiles,
39
    cumulus_primitives_core::AggregateMessageOrigin,
40
    dp_impl_tanssi_pallets_config::impl_tanssi_pallets_config,
41
    fp_account::EthereumSignature,
42
    fp_evm::weight_per_gas,
43
    fp_rpc::TransactionStatus,
44
    frame_support::{
45
        construct_runtime,
46
        dispatch::{DispatchClass, GetDispatchInfo},
47
        dynamic_params::{dynamic_pallet_params, dynamic_params},
48
        genesis_builder_helper::{build_state, get_preset},
49
        pallet_prelude::DispatchResult,
50
        parameter_types,
51
        traits::{
52
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, Currency as CurrencyT,
53
            FindAuthor, Imbalance, InsideBoth, InstanceFilter, OnFinalize, OnUnbalanced,
54
        },
55
        weights::{
56
            constants::{
57
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
58
                WEIGHT_REF_TIME_PER_SECOND,
59
            },
60
            ConstantMultiplier, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients,
61
            WeightToFeePolynomial,
62
        },
63
    },
64
    frame_system::{
65
        limits::{BlockLength, BlockWeights},
66
        EnsureRoot,
67
    },
68
    nimbus_primitives::{NimbusId, SlotBeacon},
69
    pallet_ethereum::{Call::transact, PostLogContent, Transaction as EthereumTransaction},
70
    pallet_evm::{
71
        Account as EVMAccount, EVMCurrencyAdapter, EnsureAddressNever, EnsureAddressRoot,
72
        EnsureCreateOrigin, FeeCalculator, GasWeightMapping, IdentityAddressMapping,
73
        OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
74
    },
75
    pallet_transaction_payment::FungibleAdapter,
76
    parity_scale_codec::{Decode, Encode},
77
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
78
    scale_info::TypeInfo,
79
    smallvec::smallvec,
80
    sp_api::impl_runtime_apis,
81
    sp_consensus_slots::{Slot, SlotDuration},
82
    sp_core::{Get, MaxEncodedLen, OpaqueMetadata, H160, H256, U256},
83
    sp_runtime::{
84
        create_runtime_str, generic, impl_opaque_keys,
85
        traits::{
86
            BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentifyAccount,
87
            IdentityLookup, PostDispatchInfoOf, UniqueSaturatedInto, Verify,
88
        },
89
        transaction_validity::{
90
            InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
91
        },
92
        ApplyExtrinsicResult, BoundedVec,
93
    },
94
    sp_std::prelude::*,
95
    sp_version::RuntimeVersion,
96
};
97
pub use {
98
    sp_consensus_aura::sr25519::AuthorityId as AuraId,
99
    sp_runtime::{MultiAddress, Perbill, Permill},
100
};
101

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

            
105
pub type Precompiles = TemplatePrecompiles<Runtime>;
106

            
107
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
108
pub type Signature = EthereumSignature;
109

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

            
114
/// Balance of an account.
115
pub type Balance = u128;
116

            
117
/// Index of a transaction in the chain.
118
pub type Index = u32;
119

            
120
/// A hash of some data used by the chain.
121
pub type Hash = sp_core::H256;
122

            
123
/// An index to a block.
124
pub type BlockNumber = u32;
125

            
126
/// The address format for describing accounts.
127
pub type Address = AccountId;
128

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

            
132
/// Block type as expected by this runtime.
133
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
134

            
135
/// A Block signed with a Justification
136
pub type SignedBlock = generic::SignedBlock<Block>;
137

            
138
/// BlockId type as expected by this runtime.
139
pub type BlockId = generic::BlockId<Block>;
140

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

            
154
/// Unchecked extrinsic type as expected by this runtime.
155
pub type UncheckedExtrinsic =
156
    fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
157
/// Extrinsic type that has already been checked.
158
pub type CheckedExtrinsic =
159
    fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra, H160>;
160
/// The payload being signed in transactions.
161
pub type SignedPayload = generic::SignedPayload<RuntimeCall, SignedExtra>;
162

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

            
172
pub mod currency {
173
    use super::Balance;
174

            
175
    pub const MICROUNIT: Balance = 1_000_000_000_000;
176
    pub const MILLIUNIT: Balance = 1_000_000_000_000_000;
177
    pub const UNIT: Balance = 1_000_000_000_000_000_000;
178
    pub const KILOUNIT: Balance = 1_000_000_000_000_000_000_000;
179

            
180
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
181

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

            
187
impl fp_self_contained::SelfContainedCall for RuntimeCall {
188
    type SignedInfo = H160;
189

            
190
    fn is_self_contained(&self) -> bool {
191
        match self {
192
            RuntimeCall::Ethereum(call) => call.is_self_contained(),
193
            _ => false,
194
        }
195
    }
196

            
197
    fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
198
        match self {
199
            RuntimeCall::Ethereum(call) => call.check_self_contained(),
200
            _ => None,
201
        }
202
    }
203

            
204
    fn validate_self_contained(
205
        &self,
206
        info: &Self::SignedInfo,
207
        dispatch_info: &DispatchInfoOf<RuntimeCall>,
208
        len: usize,
209
    ) -> Option<TransactionValidity> {
210
        match self {
211
            RuntimeCall::Ethereum(call) => call.validate_self_contained(info, dispatch_info, len),
212
            _ => None,
213
        }
214
    }
215

            
216
    fn pre_dispatch_self_contained(
217
        &self,
218
        info: &Self::SignedInfo,
219
        dispatch_info: &DispatchInfoOf<RuntimeCall>,
220
        len: usize,
221
    ) -> Option<Result<(), TransactionValidityError>> {
222
        match self {
223
            RuntimeCall::Ethereum(call) => {
224
                call.pre_dispatch_self_contained(info, dispatch_info, len)
225
            }
226
            _ => None,
227
        }
228
    }
229

            
230
    fn apply_self_contained(
231
        self,
232
        info: Self::SignedInfo,
233
    ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
234
        match self {
235
            call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
236
                Some(call.dispatch(RuntimeOrigin::from(
237
                    pallet_ethereum::RawOrigin::EthereumTransaction(info),
238
                )))
239
            }
240
            _ => None,
241
        }
242
    }
243
}
244

            
245
#[derive(Clone)]
246
pub struct TransactionConverter;
247

            
248
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
249
    fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
250
        UncheckedExtrinsic::new_unsigned(
251
            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
252
        )
253
    }
254
}
255

            
256
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
257
    fn convert_transaction(
258
        &self,
259
        transaction: pallet_ethereum::Transaction,
260
    ) -> opaque::UncheckedExtrinsic {
261
        let extrinsic = UncheckedExtrinsic::new_unsigned(
262
            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
263
        );
264
        let encoded = extrinsic.encode();
265
        opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
266
            .expect("Encoded extrinsic is always valid")
267
    }
268
}
269

            
270
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
271
/// node's balance type.
272
///
273
/// This should typically create a mapping between the following ranges:
274
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
275
///   - `[Balance::min, Balance::max]`
276
///
277
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
278
///   - Setting it to `0` will essentially disable the weight fee.
279
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
280
pub struct WeightToFee;
281
impl WeightToFeePolynomial for WeightToFee {
282
    type Balance = Balance;
283
30
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
284
30
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
285
30
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
286
30
        let p = currency::MILLIUNIT / 10;
287
30
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
288
30
        smallvec![WeightToFeeCoefficient {
289
            degree: 1,
290
            negative: false,
291
            coeff_frac: Perbill::from_rational(p % q, q),
292
            coeff_integer: p / q,
293
        }]
294
30
    }
295
}
296

            
297
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
298
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
299
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
300
/// to even the core data structures.
301
pub mod opaque {
302
    use {
303
        super::*,
304
        sp_runtime::{generic, traits::BlakeTwo256},
305
    };
306

            
307
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
308
    /// Opaque block header type.
309
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
310
    /// Opaque block type.
311
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
312
    /// Opaque block identifier type.
313
    pub type BlockId = generic::BlockId<Block>;
314
}
315

            
316
mod impl_on_charge_evm_transaction;
317

            
318
impl_opaque_keys! {
319
    pub struct SessionKeys { }
320
}
321

            
322
#[sp_version::runtime_version]
323
pub const VERSION: RuntimeVersion = RuntimeVersion {
324
    spec_name: create_runtime_str!("frontier-template"),
325
    impl_name: create_runtime_str!("frontier-template"),
326
    authoring_version: 1,
327
    spec_version: 800,
328
    impl_version: 0,
329
    apis: RUNTIME_API_VERSIONS,
330
    transaction_version: 1,
331
    state_version: 1,
332
};
333

            
334
/// This determines the average expected block time that we are targeting.
335
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
336
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
337
/// up by `pallet_aura` to implement `fn slot_duration()`.
338
///
339
/// Change this to adjust the block time.
340
pub const MILLISECS_PER_BLOCK: u64 = 6000;
341

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

            
346
// Time is measured by number of blocks.
347
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
348
pub const HOURS: BlockNumber = MINUTES * 60;
349
pub const DAYS: BlockNumber = HOURS * 24;
350

            
351
/// The existential deposit. Set to 0 because this is an ethereum-like chain
352
/// We set this to one for runtime-benchmarks because plenty of the benches we
353
/// incorporate from parity assume ED != 0
354
#[cfg(feature = "runtime-benchmarks")]
355
pub const EXISTENTIAL_DEPOSIT: Balance = 1 * currency::MILLIUNIT;
356
#[cfg(not(feature = "runtime-benchmarks"))]
357
pub const EXISTENTIAL_DEPOSIT: Balance = 0;
358

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

            
363
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
364
/// `Operational` extrinsics.
365
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
366

            
367
/// We allow for 0.5 of a second of compute with a 12 second average block time.
368
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
369
    WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
370
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
371
);
372

            
373
/// We allow for 500ms of compute with a 12 second average block time.
374
pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 500;
375

            
376
/// The version information used to identify this runtime when compiled natively.
377
#[cfg(feature = "std")]
378
pub fn native_version() -> NativeVersion {
379
    NativeVersion {
380
        runtime_version: VERSION,
381
        can_author_with: Default::default(),
382
    }
383
}
384

            
385
parameter_types! {
386
    pub const Version: RuntimeVersion = VERSION;
387

            
388
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
389
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
390
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
391
    // the lazy contract deletion.
392
    pub RuntimeBlockLength: BlockLength =
393
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
394
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
395
        .base_block(BlockExecutionWeight::get())
396
18
        .for_class(DispatchClass::all(), |weights| {
397
18
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
398
18
        })
399
6
        .for_class(DispatchClass::Normal, |weights| {
400
6
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
401
6
        })
402
6
        .for_class(DispatchClass::Operational, |weights| {
403
6
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
404
6
            // Operational transactions have some extra reserved space, so that they
405
6
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
406
6
            weights.reserved = Some(
407
6
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
408
6
            );
409
6
        })
410
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
411
        .build_or_panic();
412
    pub const SS58Prefix: u16 = 42;
413
}
414

            
415
// Configure FRAME pallets to include in runtime.
416
impl frame_system::Config for Runtime {
417
    /// The identifier used to distinguish between accounts.
418
    type AccountId = AccountId;
419
    /// The aggregated dispatch type that is available for extrinsics.
420
    type RuntimeCall = RuntimeCall;
421
    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
422
    type Lookup = IdentityLookup<AccountId>;
423
    /// The index type for storing how many extrinsics an account has signed.
424
    type Nonce = Index;
425
    /// The index type for blocks.
426
    type Block = Block;
427
    /// The type for hashing blocks and tries.
428
    type Hash = Hash;
429
    /// The hashing algorithm used.
430
    type Hashing = BlakeTwo256;
431
    /// The ubiquitous event type.
432
    type RuntimeEvent = RuntimeEvent;
433
    /// The ubiquitous origin type.
434
    type RuntimeOrigin = RuntimeOrigin;
435
    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
436
    type BlockHashCount = BlockHashCount;
437
    /// Runtime version.
438
    type Version = Version;
439
    /// Converts a module to an index of this module in the runtime.
440
    type PalletInfo = PalletInfo;
441
    /// The data to be stored in an account.
442
    type AccountData = pallet_balances::AccountData<Balance>;
443
    /// What to do if a new account is created.
444
    type OnNewAccount = ();
445
    /// What to do if an account is fully reaped from the system.
446
    type OnKilledAccount = ();
447
    /// The weight of database operations that the runtime can invoke.
448
    type DbWeight = RocksDbWeight;
449
    /// The basic call filter to use in dispatchable.
450
    type BaseCallFilter = InsideBoth<MaintenanceMode, TxPause>;
451
    /// Weight information for the extrinsics of this pallet.
452
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
453
    /// Block & extrinsics weights: base values and limits.
454
    type BlockWeights = RuntimeBlockWeights;
455
    /// The maximum length of a block (in bytes).
456
    type BlockLength = RuntimeBlockLength;
457
    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.
458
    type SS58Prefix = SS58Prefix;
459
    /// The action to take on a Runtime Upgrade
460
    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
461
    type MaxConsumers = frame_support::traits::ConstU32<16>;
462
    type RuntimeTask = RuntimeTask;
463
    type SingleBlockMigrations = ();
464
    type MultiBlockMigrator = ();
465
    type PreInherents = ();
466
    type PostInherents = ();
467
    type PostTransactions = ();
468
}
469

            
470
parameter_types! {
471
    pub const TransactionByteFee: Balance = 1;
472
}
473

            
474
impl pallet_transaction_payment::Config for Runtime {
475
    type RuntimeEvent = RuntimeEvent;
476
    // This will burn the fees
477
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
478
    type OperationalFeeMultiplier = ConstU8<5>;
479
    type WeightToFee = WeightToFee;
480
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
481
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
482
}
483

            
484
parameter_types! {
485
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
486
}
487

            
488
impl pallet_balances::Config for Runtime {
489
    type MaxLocks = ConstU32<50>;
490
    /// The type for recording an account's balance.
491
    type Balance = Balance;
492
    /// The ubiquitous event type.
493
    type RuntimeEvent = RuntimeEvent;
494
    type DustRemoval = ();
495
    type ExistentialDeposit = ExistentialDeposit;
496
    type AccountStore = System;
497
    type MaxReserves = ConstU32<50>;
498
    type ReserveIdentifier = [u8; 8];
499
    type FreezeIdentifier = RuntimeFreezeReason;
500
    type MaxFreezes = ConstU32<0>;
501
    type RuntimeHoldReason = RuntimeHoldReason;
502
    type RuntimeFreezeReason = RuntimeFreezeReason;
503
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
504
}
505

            
506
parameter_types! {
507
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
508
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
509
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
510
}
511

            
512
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
513
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
514
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
515

            
516
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
517
    Runtime,
518
    BLOCK_PROCESSING_VELOCITY,
519
    UNINCLUDED_SEGMENT_CAPACITY,
520
>;
521

            
522
impl cumulus_pallet_parachain_system::Config for Runtime {
523
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
524
    type RuntimeEvent = RuntimeEvent;
525
    type OnSystemEvent = ();
526
    type SelfParaId = parachain_info::Pallet<Runtime>;
527
    type OutboundXcmpMessageSource = XcmpQueue;
528
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
529
    type ReservedDmpWeight = ReservedDmpWeight;
530
    type XcmpMessageHandler = XcmpQueue;
531
    type ReservedXcmpWeight = ReservedXcmpWeight;
532
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
533
    type ConsensusHook = ConsensusHook;
534
}
535

            
536
pub struct ParaSlotProvider;
537
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
538
104
    fn get() -> (Slot, SlotDuration) {
539
104
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
540
104
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
541
104
    }
542
}
543

            
544
parameter_types! {
545
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
546
}
547

            
548
impl pallet_async_backing::Config for Runtime {
549
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
550
    type GetAndVerifySlot =
551
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
552
    type ExpectedBlockTime = ExpectedBlockTime;
553
}
554

            
555
impl parachain_info::Config for Runtime {}
556

            
557
parameter_types! {
558
    pub const Period: u32 = 6 * HOURS;
559
    pub const Offset: u32 = 0;
560
}
561

            
562
impl pallet_sudo::Config for Runtime {
563
    type RuntimeCall = RuntimeCall;
564
    type RuntimeEvent = RuntimeEvent;
565
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
566
}
567

            
568
impl pallet_utility::Config for Runtime {
569
    type RuntimeEvent = RuntimeEvent;
570
    type RuntimeCall = RuntimeCall;
571
    type PalletsOrigin = OriginCaller;
572
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
573
}
574

            
575
/// The type used to represent the kinds of proxying allowed.
576
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
577
#[derive(
578
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
579
)]
580
#[allow(clippy::unnecessary_cast)]
581
pub enum ProxyType {
582
    /// All calls can be proxied. This is the trivial/most permissive filter.
583
    Any = 0,
584
    /// Only extrinsics that do not transfer funds.
585
    NonTransfer = 1,
586
    /// Only extrinsics related to governance (democracy and collectives).
587
    Governance = 2,
588
    /// Allow to veto an announced proxy call.
589
    CancelProxy = 3,
590
    /// Allow extrinsic related to Balances.
591
    Balances = 4,
592
}
593

            
594
impl Default for ProxyType {
595
    fn default() -> Self {
596
        Self::Any
597
    }
598
}
599

            
600
// Be careful: Each time this filter is modified, the substrate filter must also be modified
601
// consistently.
602
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
603
    fn is_evm_proxy_call_allowed(
604
        &self,
605
        call: &pallet_evm_precompile_proxy::EvmSubCall,
606
        recipient_has_code: bool,
607
        gas: u64,
608
    ) -> precompile_utils::EvmResult<bool> {
609
        Ok(match self {
610
            ProxyType::Any => true,
611
            ProxyType::NonTransfer => false,
612
            ProxyType::Governance => false,
613
            // The proxy precompile does not contain method cancel_proxy
614
            ProxyType::CancelProxy => false,
615
            ProxyType::Balances => {
616
                // Allow only "simple" accounts as recipient (no code nor precompile).
617
                // Note: Checking the presence of the code is not enough because some precompiles
618
                // have no code.
619
                !recipient_has_code
620
                    && !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
621
                        call.to.0, gas,
622
                    )?
623
            }
624
        })
625
    }
626
}
627

            
628
impl InstanceFilter<RuntimeCall> for ProxyType {
629
    fn filter(&self, c: &RuntimeCall) -> bool {
630
        // Since proxy filters are respected in all dispatches of the Utility
631
        // pallet, it should never need to be filtered by any proxy.
632
        if let RuntimeCall::Utility(..) = c {
633
            return true;
634
        }
635

            
636
        match self {
637
            ProxyType::Any => true,
638
            ProxyType::NonTransfer => {
639
                matches!(
640
                    c,
641
                    RuntimeCall::System(..)
642
                        | RuntimeCall::ParachainSystem(..)
643
                        | RuntimeCall::Timestamp(..)
644
                        | RuntimeCall::Proxy(..)
645
                )
646
            }
647
            // We don't have governance yet
648
            ProxyType::Governance => false,
649
            ProxyType::CancelProxy => matches!(
650
                c,
651
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
652
            ),
653
            ProxyType::Balances => {
654
                matches!(c, RuntimeCall::Balances(..))
655
            }
656
        }
657
    }
658

            
659
    fn is_superset(&self, o: &Self) -> bool {
660
        match (self, o) {
661
            (x, y) if x == y => true,
662
            (ProxyType::Any, _) => true,
663
            (_, ProxyType::Any) => false,
664
            _ => false,
665
        }
666
    }
667
}
668

            
669
impl pallet_proxy::Config for Runtime {
670
    type RuntimeEvent = RuntimeEvent;
671
    type RuntimeCall = RuntimeCall;
672
    type Currency = Balances;
673
    type ProxyType = ProxyType;
674
    // One storage item; key size 32, value size 8
675
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
676
    // Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
677
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
678
    type MaxProxies = ConstU32<32>;
679
    type MaxPending = ConstU32<32>;
680
    type CallHasher = BlakeTwo256;
681
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
682
    // Additional storage item size of 56 bytes:
683
    // - 20 bytes AccountId
684
    // - 32 bytes Hasher (Blake2256)
685
    // - 4 bytes BlockNumber (u32)
686
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
687
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
688
}
689

            
690
pub struct XcmExecutionManager;
691
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
692
    fn suspend_xcm_execution() -> DispatchResult {
693
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
694
    }
695
    fn resume_xcm_execution() -> DispatchResult {
696
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
697
    }
698
}
699

            
700
impl pallet_migrations::Config for Runtime {
701
    type RuntimeEvent = RuntimeEvent;
702
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
703
    type XcmExecutionManager = XcmExecutionManager;
704
}
705

            
706
/// Maintenance mode Call filter
707
pub struct MaintenanceFilter;
708
impl Contains<RuntimeCall> for MaintenanceFilter {
709
    fn contains(c: &RuntimeCall) -> bool {
710
        !matches!(
711
            c,
712
            RuntimeCall::Balances(_)
713
                | RuntimeCall::Ethereum(_)
714
                | RuntimeCall::EVM(_)
715
                | RuntimeCall::PolkadotXcm(_)
716
        )
717
    }
718
}
719

            
720
/// Normal Call Filter
721
/// We dont allow to create nor mint assets, this for now is disabled
722
/// We only allow transfers. For now creation of assets will go through
723
/// asset-manager, while minting/burning only happens through xcm messages
724
/// This can change in the future
725
pub struct NormalFilter;
726
impl Contains<RuntimeCall> for NormalFilter {
727
    fn contains(c: &RuntimeCall) -> bool {
728
        !matches!(
729
            c,
730
            // Filtering the EVM prevents possible re-entrancy from the precompiles which could
731
            // lead to unexpected scenarios.
732
            // See https://github.com/PureStake/sr-moonbeam/issues/30
733
            // Note: It is also assumed that EVM calls are only allowed through `Origin::Root` so
734
            // this can be seen as an additional security
735
            RuntimeCall::EVM(_)
736
        )
737
    }
738
}
739

            
740
impl pallet_maintenance_mode::Config for Runtime {
741
    type RuntimeEvent = RuntimeEvent;
742
    type NormalCallFilter = NormalFilter;
743
    type MaintenanceCallFilter = MaintenanceFilter;
744
    type MaintenanceOrigin = EnsureRoot<AccountId>;
745
    type XcmExecutionManager = XcmExecutionManager;
746
}
747

            
748
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
749
pub mod dynamic_params {
750
    use super::*;
751

            
752
    #[dynamic_pallet_params]
753
    #[codec(index = 3)]
754
    pub mod contract_deploy_filter {
755
        #[codec(index = 0)]
756
        pub static AllowedAddressesToCreate: DeployFilter = DeployFilter::All;
757
        #[codec(index = 1)]
758
        pub static AllowedAddressesToCreateInner: DeployFilter = DeployFilter::All;
759
    }
760
}
761

            
762
impl pallet_parameters::Config for Runtime {
763
    type AdminOrigin = EnsureRoot<AccountId>;
764
    type RuntimeEvent = RuntimeEvent;
765
    type RuntimeParameters = RuntimeParameters;
766
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
767
}
768

            
769
#[cfg(feature = "runtime-benchmarks")]
770
impl Default for RuntimeParameters {
771
    fn default() -> Self {
772
        RuntimeParameters::ContractDeployFilter(
773
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
774
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
775
                Some(DeployFilter::All),
776
            ),
777
        )
778
    }
779
}
780

            
781
#[derive(Clone, PartialEq, Encode, Decode, TypeInfo, Eq, MaxEncodedLen, Debug)]
782
pub enum DeployFilter {
783
    All,
784
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
785
}
786

            
787
pub struct AddressFilter<Runtime, AddressList>(sp_std::marker::PhantomData<(Runtime, AddressList)>);
788
impl<Runtime, AddressList> EnsureCreateOrigin<Runtime> for AddressFilter<Runtime, AddressList>
789
where
790
    Runtime: pallet_evm::Config,
791
    AddressList: Get<DeployFilter>,
792
{
793
    fn check_create_origin(address: &H160) -> Result<(), pallet_evm::Error<Runtime>> {
794
        let deploy_filter: DeployFilter = AddressList::get();
795

            
796
        match deploy_filter {
797
            DeployFilter::All => Ok(()),
798
            DeployFilter::Whitelisted(addresses_vec) => {
799
                if !addresses_vec.contains(address) {
800
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
801
                } else {
802
                    Ok(())
803
                }
804
            }
805
        }
806
    }
807
}
808

            
809
// To match ethereum expectations
810
const BLOCK_GAS_LIMIT: u64 = 15_000_000;
811

            
812
impl pallet_evm_chain_id::Config for Runtime {}
813

            
814
pub struct FindAuthorAdapter;
815
impl FindAuthor<H160> for FindAuthorAdapter {
816
153
    fn find_author<'a, I>(digests: I) -> Option<H160>
817
153
    where
818
153
        I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
819
153
    {
820
153
        if let Some(author) = AuthorInherent::find_author(digests) {
821
            return Some(H160::from_slice(&author.encode()[0..20]));
822
153
        }
823
153
        None
824
153
    }
825
}
826

            
827
parameter_types! {
828
    pub BlockGasLimit: U256 = U256::from(BLOCK_GAS_LIMIT);
829
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
830
    pub WeightPerGas: Weight = Weight::from_parts(weight_per_gas(BLOCK_GAS_LIMIT, NORMAL_DISPATCH_RATIO, WEIGHT_MILLISECS_PER_BLOCK), 0);
831
    pub SuicideQuickClearLimit: u32 = 0;
832
}
833

            
834
impl_on_charge_evm_transaction!();
835
impl pallet_evm::Config for Runtime {
836
    type FeeCalculator = BaseFee;
837
    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
838
    type WeightPerGas = WeightPerGas;
839
    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
840
    type CallOrigin = EnsureAddressRoot<AccountId>;
841
    type WithdrawOrigin = EnsureAddressNever<AccountId>;
842
    type AddressMapping = IdentityAddressMapping;
843
    type CreateOrigin =
844
        AddressFilter<Runtime, dynamic_params::contract_deploy_filter::AllowedAddressesToCreate>;
845
    type CreateInnerOrigin = AddressFilter<
846
        Runtime,
847
        dynamic_params::contract_deploy_filter::AllowedAddressesToCreateInner,
848
    >;
849
    type Currency = Balances;
850
    type RuntimeEvent = RuntimeEvent;
851
    type PrecompilesType = TemplatePrecompiles<Self>;
852
    type PrecompilesValue = PrecompilesValue;
853
    type ChainId = EVMChainId;
854
    type BlockGasLimit = BlockGasLimit;
855
    type Runner = pallet_evm::runner::stack::Runner<Self>;
856
    type OnChargeTransaction = OnChargeEVMTransaction<()>;
857
    type OnCreate = ();
858
    type FindAuthor = FindAuthorAdapter;
859
    // TODO: update in the future
860
    type GasLimitPovSizeRatio = ();
861
    type SuicideQuickClearLimit = SuicideQuickClearLimit;
862
    type Timestamp = Timestamp;
863
    type WeightInfo = ();
864
}
865

            
866
parameter_types! {
867
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
868
}
869

            
870
impl pallet_ethereum::Config for Runtime {
871
    type RuntimeEvent = RuntimeEvent;
872
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
873
    type PostLogContent = PostBlockAndTxnHashes;
874
    type ExtraDataLength = ConstU32<30>;
875
}
876

            
877
parameter_types! {
878
    pub BoundDivision: U256 = U256::from(1024);
879
}
880

            
881
parameter_types! {
882
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
883
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
884
}
885

            
886
pub struct BaseFeeThreshold;
887
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
888
    fn lower() -> Permill {
889
        Permill::zero()
890
    }
891
    fn ideal() -> Permill {
892
        Permill::from_parts(500_000)
893
    }
894
    fn upper() -> Permill {
895
        Permill::from_parts(1_000_000)
896
    }
897
}
898

            
899
impl pallet_base_fee::Config for Runtime {
900
    type RuntimeEvent = RuntimeEvent;
901
    type Threshold = BaseFeeThreshold;
902
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
903
    type DefaultElasticity = DefaultElasticity;
904
}
905

            
906
impl pallet_root_testing::Config for Runtime {
907
    type RuntimeEvent = RuntimeEvent;
908
}
909

            
910
impl pallet_tx_pause::Config for Runtime {
911
    type RuntimeEvent = RuntimeEvent;
912
    type RuntimeCall = RuntimeCall;
913
    type PauseOrigin = EnsureRoot<AccountId>;
914
    type UnpauseOrigin = EnsureRoot<AccountId>;
915
    type WhitelistedCalls = ();
916
    type MaxNameLen = ConstU32<256>;
917
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
918
}
919

            
920
impl dp_impl_tanssi_pallets_config::Config for Runtime {
921
    const SLOT_DURATION: u64 = SLOT_DURATION;
922
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
923
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
924
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
925
}
926

            
927
parameter_types! {
928
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
929
    pub const DepositBase: Balance = currency::deposit(1, 96);
930
    // Additional storage item size of 20 bytes.
931
    pub const DepositFactor: Balance = currency::deposit(0, 20);
932
    pub const MaxSignatories: u32 = 100;
933
}
934

            
935
impl pallet_multisig::Config for Runtime {
936
    type RuntimeEvent = RuntimeEvent;
937
    type RuntimeCall = RuntimeCall;
938
    type Currency = Balances;
939
    type DepositBase = DepositBase;
940
    type DepositFactor = DepositFactor;
941
    type MaxSignatories = MaxSignatories;
942
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
943
}
944

            
945
impl_tanssi_pallets_config!(Runtime);
946

            
947
// Create the runtime by composing the FRAME pallets that were previously configured.
948
18127
construct_runtime!(
949
1908
    pub enum Runtime
950
1908
    {
951
1908
        // System support stuff.
952
1908
        System: frame_system = 0,
953
1908
        ParachainSystem: cumulus_pallet_parachain_system = 1,
954
1908
        Timestamp: pallet_timestamp = 2,
955
1908
        ParachainInfo: parachain_info = 3,
956
1908
        Sudo: pallet_sudo = 4,
957
1908
        Utility: pallet_utility = 5,
958
1908
        Proxy: pallet_proxy = 6,
959
1908
        Migrations: pallet_migrations = 7,
960
1908
        MaintenanceMode: pallet_maintenance_mode = 8,
961
1908
        TxPause: pallet_tx_pause = 9,
962
1908

            
963
1908
        // Monetary stuff.
964
1908
        Balances: pallet_balances = 10,
965
1908

            
966
1908
        // Other utilities
967
1908
        Multisig: pallet_multisig = 16,
968
1908
        Parameters: pallet_parameters = 17,
969
1908

            
970
1908
        // ContainerChain
971
1908
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
972
1908
        AuthorInherent: pallet_author_inherent = 51,
973
1908

            
974
1908
        // Frontier
975
1908
        Ethereum: pallet_ethereum = 60,
976
1908
        EVM: pallet_evm = 61,
977
1908
        EVMChainId: pallet_evm_chain_id = 62,
978
1908
        BaseFee: pallet_base_fee = 64,
979
1908
        TransactionPayment: pallet_transaction_payment = 66,
980
1908

            
981
1908
        // XCM
982
1908
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
983
1908
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
984
1908
        DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 72,
985
1908
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
986
1908
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
987
1908
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
988
1908
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
989
1908
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
990
1908
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
991
1908

            
992
1908
        RootTesting: pallet_root_testing = 100,
993
1908
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
994
1908
    }
995
18127
);
996

            
997
#[cfg(feature = "runtime-benchmarks")]
998
mod benches {
999
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_multisig, Multisig]
        [pallet_parameters, Parameters]
        [pallet_cc_authorities_noting, AuthoritiesNoting]
        [pallet_author_inherent, AuthorInherent]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        [cumulus_pallet_dmp_queue, DmpQueue]
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
        [pallet_message_queue, MessageQueue]
        [pallet_assets, ForeignAssets]
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
        [pallet_asset_rate, AssetRate]
        [pallet_xcm_executor_utils, XcmExecutorUtils]
    );
}
16564
impl_runtime_apis! {
9032
    impl sp_api::Core<Block> for Runtime {
9032
        fn version() -> RuntimeVersion {
            VERSION
        }
9032

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

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

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

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

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

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

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

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

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

            
9032
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
9032
        fn validate_transaction(
            source: TransactionSource,
            xt: <Block as BlockT>::Extrinsic,
            block_hash: <Block as BlockT>::Hash,
        ) -> TransactionValidity {
            // Filtered calls should not enter the tx pool as they'll fail if inserted.
            // If this call is not allowed, we return early.
            if !<Runtime as frame_system::Config>::BaseCallFilter::contains(&xt.0.function) {
9032
                return InvalidTransaction::Call.into();
9032
            }
9032

            
9032
            // This runtime uses Substrate's pallet transaction payment. This
9032
            // makes the chain feel like a standard Substrate chain when submitting
9032
            // frame transactions and using Substrate ecosystem tools. It has the downside that
9032
            // transaction are not prioritized by gas_price. The following code reprioritizes
9032
            // transactions to overcome this.
9032
            //
9032
            // A more elegant, ethereum-first solution is
9032
            // a pallet that replaces pallet transaction payment, and allows users
9032
            // to directly specify a gas price rather than computing an effective one.
9032
            // #HopefullySomeday
9032

            
9032
            // First we pass the transactions to the standard FRAME executive. This calculates all the
9032
            // necessary tags, longevity and other properties that we will leave unchanged.
9032
            // This also assigns some priority that we don't care about and will overwrite next.
9032
            let mut intermediate_valid = Executive::validate_transaction(source, xt.clone(), block_hash)?;
9032

            
9032
            let dispatch_info = xt.get_dispatch_info();
9032

            
9032
            // If this is a pallet ethereum transaction, then its priority is already set
9032
            // according to effective priority fee from pallet ethereum. If it is any other kind of
9032
            // transaction, we modify its priority. The goal is to arrive at a similar metric used
9032
            // by pallet ethereum, which means we derive a fee-per-gas from the txn's tip and
9032
            // weight.
9032
            Ok(match &xt.0.function {
9032
                RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
9032
                _ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
9032
                _ => {
9032
                    let tip = match xt.0.signature {
9032
                        None => 0,
9032
                        Some((_, _, ref signed_extra)) => {
                            // Yuck, this depends on the index of charge transaction in Signed Extra
                            let charge_transaction = &signed_extra.7;
                            charge_transaction.tip()
9032
                        }
9032
                    };
9032

            
9032
                    let effective_gas =
                        <Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
                            dispatch_info.weight
                        );
9032
                    let tip_per_gas = if effective_gas > 0 {
9032
                        tip.saturating_div(u128::from(effective_gas))
9032
                    } else {
9032
                        0
9032
                    };
9032

            
9032
                    // Overwrite the original prioritization with this ethereum one
9032
                    intermediate_valid.priority = tip_per_gas as u64;
                    intermediate_valid
9032
                }
9032
            })
9032
        }
9032
    }
9032

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

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

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

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

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

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

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

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

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

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

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

            
9032
        fn dispatch_benchmark(
9032
            config: frame_benchmarking::BenchmarkConfig,
9032
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
9032
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
9032
            use sp_core::storage::TrackedStorageKey;
9032
            use staging_xcm::latest::prelude::*;
9032
            impl frame_system_benchmarking::Config for Runtime {
9032
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
9032
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
9032
                    Ok(())
9032
                }
9032

            
9032
                fn verify_set_code() {
9032
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
9032
                }
9032
            }
9032
            use xcm_config::SelfReserve;
9032

            
9032
            parameter_types! {
9032
                pub ExistentialDepositAsset: Option<Asset> = Some((
9032
                    SelfReserve::get(),
9032
                    ExistentialDeposit::get()
9032
                ).into());
9032
            }
9032

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
9032
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
9032
                    use xcm_config::SelfReserve;
9032
                    // AH can reserve transfer native token to some random parachain.
9032
                    let random_para_id = 43211234;
9032

            
9032
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
9032
                        random_para_id.into()
9032
                    );
9032
                    let who = frame_benchmarking::whitelisted_caller();
9032
                    // Give some multiple of the existential deposit
9032
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
9032
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
9032
                        &who, balance,
9032
                    );
9032
                    Some((
9032
                        Asset {
9032
                            fun: Fungible(balance),
9032
                            id: SelfReserve::get().into()
9032
                        },
9032
                        ParentThen(Parachain(random_para_id).into()).into(),
9032
                    ))
9032
                }
9032

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

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

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

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

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

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

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

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

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

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

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

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

            
9032
            add_benchmarks!(params, batches);
9032

            
9032
            Ok(batches)
9032
        }
9032
    }
9032

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

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

            
9032
    impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
9032
        fn chain_id() -> u64 {
            <Runtime as pallet_evm::Config>::ChainId::get()
        }
9032

            
9032
        fn account_basic(address: H160) -> EVMAccount {
            let (account, _) = pallet_evm::Pallet::<Runtime>::account_basic(&address);
            account
        }
9032

            
9032
        fn gas_price() -> U256 {
            let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
            gas_price
        }
9032

            
9032
        fn account_code_at(address: H160) -> Vec<u8> {
            pallet_evm::AccountCodes::<Runtime>::get(address)
        }
9032

            
9032
        fn author() -> H160 {
            <pallet_evm::Pallet<Runtime>>::find_author()
        }
9032

            
9032
        fn storage_at(address: H160, index: U256) -> H256 {
            let mut tmp = [0u8; 32];
            index.to_big_endian(&mut tmp);
            pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
        }
9032

            
9032
        fn call(
            from: H160,
            to: H160,
            data: Vec<u8>,
            value: U256,
            gas_limit: U256,
            max_fee_per_gas: Option<U256>,
            max_priority_fee_per_gas: Option<U256>,
            nonce: Option<U256>,
            _estimate: bool,
            access_list: Option<Vec<(H160, Vec<H256>)>>,
        ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
            let is_transactional = false;
            let validate = true;
            <Runtime as pallet_evm::Config>::Runner::call(
                from,
                to,
                data,
                value,
                gas_limit.min(u64::MAX.into()).low_u64(),
                max_fee_per_gas,
                max_priority_fee_per_gas,
                nonce,
                access_list.unwrap_or_default(),
                is_transactional,
                validate,
                None,
                None,
                <Runtime as pallet_evm::Config>::config(),
            ).map_err(|err| err.error.into())
        }
9032

            
9032
        fn create(
            from: H160,
            data: Vec<u8>,
            value: U256,
            gas_limit: U256,
            max_fee_per_gas: Option<U256>,
            max_priority_fee_per_gas: Option<U256>,
            nonce: Option<U256>,
            _estimate: bool,
            access_list: Option<Vec<(H160, Vec<H256>)>>,
        ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
            let is_transactional = false;
            let validate = true;
            <Runtime as pallet_evm::Config>::Runner::create(
                from,
                data,
                value,
                gas_limit.min(u64::MAX.into()).low_u64(),
                max_fee_per_gas,
                max_priority_fee_per_gas,
                nonce,
                access_list.unwrap_or_default(),
                is_transactional,
                validate,
                None,
                None,
                <Runtime as pallet_evm::Config>::config(),
            ).map_err(|err| err.error.into())
        }
9032

            
9032
        fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
            pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
        }
9032

            
9032
        fn current_block() -> Option<pallet_ethereum::Block> {
            pallet_ethereum::CurrentBlock::<Runtime>::get()
        }
9032

            
9032
        fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
            pallet_ethereum::CurrentReceipts::<Runtime>::get()
        }
9032

            
9032
        fn current_all() -> (
            Option<pallet_ethereum::Block>,
            Option<Vec<pallet_ethereum::Receipt>>,
            Option<Vec<TransactionStatus>>,
        ) {
            (
                pallet_ethereum::CurrentBlock::<Runtime>::get(),
                pallet_ethereum::CurrentReceipts::<Runtime>::get(),
                pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
            )
        }
9032

            
9032
        fn extrinsic_filter(
            xts: Vec<<Block as BlockT>::Extrinsic>,
        ) -> Vec<EthereumTransaction> {
            xts.into_iter().filter_map(|xt| match xt.0.function {
9032
                RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
9032
                _ => None
9032
            }).collect::<Vec<EthereumTransaction>>()
        }
9032

            
9032
        fn elasticity() -> Option<Permill> {
            Some(pallet_base_fee::Elasticity::<Runtime>::get())
        }
9032

            
9032
        fn gas_limit_multiplier_support() {}
9032

            
9032
        fn pending_block(xts: Vec<<Block as BlockT>::Extrinsic>) -> (Option<pallet_ethereum::Block>, Option<sp_std::prelude::Vec<TransactionStatus>>) {
9032
            for ext in xts.into_iter() {
                let _ = Executive::apply_extrinsic(ext);
            }
9032

            
9032
            Ethereum::on_finalize(System::block_number() + 1);
            (
                pallet_ethereum::CurrentBlock::<Runtime>::get(),
                pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
            )
         }
9032
    }
9032

            
9032
    impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
9032
        fn convert_transaction(
            transaction: pallet_ethereum::Transaction
        ) -> <Block as BlockT>::Extrinsic {
            UncheckedExtrinsic::new_unsigned(
                pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
            )
        }
9032
    }
9032

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

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

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

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

            
9032
    impl dp_slot_duration_runtime_api::TanssiSlotDurationApi<Block> for Runtime {
9032
        fn slot_duration() -> u64 {
            SLOT_DURATION
        }
9032
    }
16564
}
#[allow(dead_code)]
struct CheckInherents;
// TODO: this should be removed but currently if we remove it the relay does not check anything
// related to other inherents that are not parachain-system
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
    fn check_inherents(
        block: &Block,
        relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
    ) -> sp_inherents::CheckInherentsResult {
        let relay_chain_slot = relay_state_proof
            .read_slot()
            .expect("Could not read the relay chain slot from the proof");
        let inherent_data =
            cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
                relay_chain_slot,
                sp_std::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}