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

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

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

            
34
pub mod migrations;
35
mod precompiles;
36
pub mod weights;
37
pub mod xcm_config;
38

            
39
use {
40
    crate::precompiles::TemplatePrecompiles,
41
    alloc::{vec, vec::Vec},
42
    cumulus_primitives_core::AggregateMessageOrigin,
43
    dp_impl_tanssi_pallets_config::impl_tanssi_pallets_config,
44
    ethereum::AuthorizationList,
45
    fp_account::EthereumSignature,
46
    fp_rpc::TransactionStatus,
47
    frame_support::{
48
        construct_runtime,
49
        dispatch::{DispatchClass, GetDispatchInfo},
50
        dynamic_params::{dynamic_pallet_params, dynamic_params},
51
        genesis_builder_helper::{build_state, get_preset},
52
        pallet_prelude::DispatchResult,
53
        parameter_types,
54
        traits::{
55
            fungible::{Balanced, Credit, Inspect},
56
            tokens::ConversionToAssetBalance,
57
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, FindAuthor, InsideBoth,
58
            InstanceFilter, OnFinalize, OnUnbalanced,
59
        },
60
        weights::{
61
            constants::{
62
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
63
                WEIGHT_REF_TIME_PER_SECOND,
64
            },
65
            ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
66
            WeightToFeeCoefficients, WeightToFeePolynomial,
67
        },
68
    },
69
    frame_system::{
70
        limits::{BlockLength, BlockWeights},
71
        EnsureRoot,
72
    },
73
    nimbus_primitives::{NimbusId, SlotBeacon},
74
    pallet_ethereum::{Call::transact, PostLogContent, Transaction as EthereumTransaction},
75
    pallet_evm::{
76
        Account as EVMAccount, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
77
        EnsureCreateOrigin, FeeCalculator, FrameSystemAccountProvider, GasWeightMapping,
78
        IdentityAddressMapping, OnChargeEVMTransaction as OnChargeEVMTransactionT, Runner,
79
    },
80
    pallet_transaction_payment::FungibleAdapter,
81
    parity_scale_codec::{Decode, DecodeWithMemTracking, Encode},
82
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
83
    scale_info::TypeInfo,
84
    smallvec::smallvec,
85
    sp_api::impl_runtime_apis,
86
    sp_consensus_slots::{Slot, SlotDuration},
87
    sp_core::{Get, MaxEncodedLen, OpaqueMetadata, H160, H256, U256},
88
    sp_runtime::{
89
        generic, impl_opaque_keys,
90
        traits::{
91
            BlakeTwo256, Block as BlockT, DispatchInfoOf, Dispatchable, IdentifyAccount,
92
            IdentityLookup, PostDispatchInfoOf, UniqueSaturatedInto, Verify,
93
        },
94
        transaction_validity::{
95
            InvalidTransaction, TransactionSource, TransactionValidity, TransactionValidityError,
96
        },
97
        ApplyExtrinsicResult, BoundedVec, Cow,
98
    },
99
    sp_version::RuntimeVersion,
100
    xcm::prelude::Location,
101
    xcm::v5::NetworkId,
102
    xcm::Version as XcmVersion,
103
    xcm::{IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm},
104
    xcm_runtime_apis::{
105
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
106
        fees::Error as XcmPaymentApiError,
107
    },
108
};
109
pub use {
110
    sp_consensus_aura::sr25519::AuthorityId as AuraId,
111
    sp_runtime::{MultiAddress, Perbill, Permill},
112
};
113

            
114
// Polkadot imports
115
use polkadot_runtime_common::BlockHashCount;
116

            
117
pub type Precompiles = TemplatePrecompiles<Runtime>;
118

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

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

            
126
/// Balance of an account.
127
pub type Balance = u128;
128

            
129
/// Index of a transaction in the chain.
130
pub type Index = u32;
131

            
132
/// A hash of some data used by the chain.
133
pub type Hash = sp_core::H256;
134

            
135
/// An index to a block.
136
pub type BlockNumber = u32;
137

            
138
/// The address format for describing accounts.
139
pub type Address = AccountId;
140

            
141
/// Block header type as expected by this runtime.
142
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
143

            
144
/// Block type as expected by this runtime.
145
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
146

            
147
/// A Block signed with a Justification
148
pub type SignedBlock = generic::SignedBlock<Block>;
149

            
150
/// BlockId type as expected by this runtime.
151
pub type BlockId = generic::BlockId<Block>;
152

            
153
pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
154
    Runtime,
155
    (
156
        frame_system::CheckNonZeroSender<Runtime>,
157
        frame_system::CheckSpecVersion<Runtime>,
158
        frame_system::CheckTxVersion<Runtime>,
159
        frame_system::CheckGenesis<Runtime>,
160
        frame_system::CheckEra<Runtime>,
161
        frame_system::CheckNonce<Runtime>,
162
        frame_system::CheckWeight<Runtime>,
163
        pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
164
    ),
165
>;
166
/// Unchecked extrinsic type as expected by this runtime.
167
pub type UncheckedExtrinsic =
168
    fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
169
/// Extrinsic type that has already been checked.
170
pub type CheckedExtrinsic =
171
    fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension, H160>;
172
/// The payload being signed in transactions.
173
pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
174

            
175
/// Executive: handles dispatch to the various modules.
176
pub type Executive = frame_executive::Executive<
177
    Runtime,
178
    Block,
179
    frame_system::ChainContext<Runtime>,
180
    Runtime,
181
    AllPalletsWithSystem,
182
>;
183

            
184
pub mod currency {
185
    use super::Balance;
186

            
187
    pub const MICROUNIT: Balance = 1_000_000_000_000;
188
    pub const MILLIUNIT: Balance = 1_000_000_000_000_000;
189
    pub const UNIT: Balance = 1_000_000_000_000_000_000;
190
    pub const KILOUNIT: Balance = 1_000_000_000_000_000_000_000;
191

            
192
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
193

            
194
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
195
        items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
196
    }
197
}
198

            
199
impl fp_self_contained::SelfContainedCall for RuntimeCall {
200
    type SignedInfo = H160;
201

            
202
    fn is_self_contained(&self) -> bool {
203
        match self {
204
            RuntimeCall::Ethereum(call) => call.is_self_contained(),
205
            _ => false,
206
        }
207
    }
208

            
209
    fn check_self_contained(&self) -> Option<Result<Self::SignedInfo, TransactionValidityError>> {
210
        match self {
211
            RuntimeCall::Ethereum(call) => call.check_self_contained(),
212
            _ => None,
213
        }
214
    }
215

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

            
228
    fn pre_dispatch_self_contained(
229
        &self,
230
        info: &Self::SignedInfo,
231
        dispatch_info: &DispatchInfoOf<RuntimeCall>,
232
        len: usize,
233
    ) -> Option<Result<(), TransactionValidityError>> {
234
        match self {
235
            RuntimeCall::Ethereum(call) => {
236
                call.pre_dispatch_self_contained(info, dispatch_info, len)
237
            }
238
            _ => None,
239
        }
240
    }
241

            
242
    fn apply_self_contained(
243
        self,
244
        info: Self::SignedInfo,
245
    ) -> Option<sp_runtime::DispatchResultWithInfo<PostDispatchInfoOf<Self>>> {
246
        match self {
247
            call @ RuntimeCall::Ethereum(pallet_ethereum::Call::transact { .. }) => {
248
                Some(call.dispatch(RuntimeOrigin::from(
249
                    pallet_ethereum::RawOrigin::EthereumTransaction(info),
250
                )))
251
            }
252
            _ => None,
253
        }
254
    }
255
}
256

            
257
#[derive(Clone)]
258
pub struct TransactionConverter;
259

            
260
impl fp_rpc::ConvertTransaction<UncheckedExtrinsic> for TransactionConverter {
261
    fn convert_transaction(&self, transaction: pallet_ethereum::Transaction) -> UncheckedExtrinsic {
262
        UncheckedExtrinsic::new_bare(
263
            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
264
        )
265
    }
266
}
267

            
268
impl fp_rpc::ConvertTransaction<opaque::UncheckedExtrinsic> for TransactionConverter {
269
    fn convert_transaction(
270
        &self,
271
        transaction: pallet_ethereum::Transaction,
272
    ) -> opaque::UncheckedExtrinsic {
273
        let extrinsic = UncheckedExtrinsic::new_bare(
274
            pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
275
        );
276
        let encoded = extrinsic.encode();
277
        opaque::UncheckedExtrinsic::decode(&mut &encoded[..])
278
            .expect("Encoded extrinsic is always valid")
279
    }
280
}
281

            
282
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
283
/// node's balance type.
284
///
285
/// This should typically create a mapping between the following ranges:
286
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
287
///   - `[Balance::min, Balance::max]`
288
///
289
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
290
///   - Setting it to `0` will essentially disable the weight fee.
291
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
292
pub struct WeightToFee;
293
impl WeightToFeePolynomial for WeightToFee {
294
    type Balance = Balance;
295
209
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
296
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
297
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
298
        // for benchmarks, we simply put a value to get a coefficeint of 1
299
        #[cfg(not(feature = "runtime-benchmarks"))]
300
209
        let p = currency::MILLIUNIT / 10;
301
        #[cfg(feature = "runtime-benchmarks")]
302
        let p = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
303

            
304
209
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
305
209
        smallvec![WeightToFeeCoefficient {
306
            degree: 1,
307
            negative: false,
308
            coeff_frac: Perbill::from_rational(p % q, q),
309
            coeff_integer: p / q,
310
        }]
311
209
    }
312
}
313

            
314
parameter_types! {
315
        /// Network and location for the Ethereum chain. On Starlight, the Ethereum chain bridged
316
        /// to is the Ethereum mainnet, with chain ID 1.
317
        /// <https://chainlist.org/chain/1>
318
        /// <https://ethereum.org/en/developers/docs/apis/json-rpc/#net_version>
319
        pub EthereumNetwork: NetworkId = NetworkId::Ethereum { chain_id: 11155111 };
320
        pub EthereumLocation: Location = Location::new(2, EthereumNetwork::get());
321
}
322

            
323
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
324
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
325
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
326
/// to even the core data structures.
327
pub mod opaque {
328
    use {
329
        super::*,
330
        sp_runtime::{generic, traits::BlakeTwo256},
331
    };
332

            
333
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
334
    /// Opaque block header type.
335
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
336
    /// Opaque block type.
337
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
338
    /// Opaque block identifier type.
339
    pub type BlockId = generic::BlockId<Block>;
340
}
341

            
342
mod impl_on_charge_evm_transaction;
343

            
344
impl_opaque_keys! {
345
    pub struct SessionKeys { }
346
}
347

            
348
#[sp_version::runtime_version]
349
pub const VERSION: RuntimeVersion = RuntimeVersion {
350
    spec_name: Cow::Borrowed("frontier-template"),
351
    impl_name: Cow::Borrowed("frontier-template"),
352
    authoring_version: 1,
353
    spec_version: 1700,
354
    impl_version: 0,
355
    apis: RUNTIME_API_VERSIONS,
356
    transaction_version: 1,
357
    system_version: 1,
358
};
359

            
360
/// This determines the average expected block time that we are targeting.
361
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
362
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
363
/// up by `pallet_aura` to implement `fn slot_duration()`.
364
///
365
/// Change this to adjust the block time.
366
pub const MILLISECS_PER_BLOCK: u64 = 6000;
367

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

            
372
// Time is measured by number of blocks.
373
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
374
pub const HOURS: BlockNumber = MINUTES * 60;
375
pub const DAYS: BlockNumber = HOURS * 24;
376

            
377
pub const EXISTENTIAL_DEPOSIT: Balance = 0;
378

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

            
383
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
384
/// `Operational` extrinsics.
385
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
386

            
387
/// We allow for 2 seconds of compute with a 6 second average block time
388
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
389
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
390
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
391
);
392

            
393
/// We allow for 2 seconds of compute with a 6 second average block time
394
pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 2000;
395

            
396
/// The version information used to identify this runtime when compiled natively.
397
#[cfg(feature = "std")]
398
pub fn native_version() -> NativeVersion {
399
    NativeVersion {
400
        runtime_version: VERSION,
401
        can_author_with: Default::default(),
402
    }
403
}
404

            
405
parameter_types! {
406
    pub const Version: RuntimeVersion = VERSION;
407

            
408
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
409
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
410
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
411
    // the lazy contract deletion.
412
    pub RuntimeBlockLength: BlockLength =
413
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
414
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
415
        .base_block(BlockExecutionWeight::get())
416
25563
        .for_class(DispatchClass::all(), |weights| {
417
25563
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
418
25563
        })
419
8521
        .for_class(DispatchClass::Normal, |weights| {
420
8521
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
421
8521
        })
422
8521
        .for_class(DispatchClass::Operational, |weights| {
423
8521
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
424
            // Operational transactions have some extra reserved space, so that they
425
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
426
8521
            weights.reserved = Some(
427
8521
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
428
8521
            );
429
8521
        })
430
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
431
        .build_or_panic();
432
    pub const SS58Prefix: u16 = 42;
433
}
434

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

            
491
parameter_types! {
492
    pub const TransactionByteFee: Balance = 1;
493
}
494

            
495
impl pallet_transaction_payment::Config for Runtime {
496
    type RuntimeEvent = RuntimeEvent;
497
    // This will burn the fees
498
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
499
    type OperationalFeeMultiplier = ConstU8<5>;
500
    type WeightToFee = WeightToFee;
501
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
502
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
503
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
504
}
505

            
506
parameter_types! {
507
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
508
}
509

            
510
impl pallet_balances::Config for Runtime {
511
    type MaxLocks = ConstU32<50>;
512
    /// The type for recording an account's balance.
513
    type Balance = Balance;
514
    /// The ubiquitous event type.
515
    type RuntimeEvent = RuntimeEvent;
516
    type DustRemoval = ();
517
    type ExistentialDeposit = ExistentialDeposit;
518
    type AccountStore = System;
519
    type MaxReserves = ConstU32<50>;
520
    type ReserveIdentifier = [u8; 8];
521
    type FreezeIdentifier = RuntimeFreezeReason;
522
    type MaxFreezes = ConstU32<0>;
523
    type RuntimeHoldReason = RuntimeHoldReason;
524
    type RuntimeFreezeReason = RuntimeFreezeReason;
525
    type DoneSlashHandler = ();
526
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
527
}
528

            
529
parameter_types! {
530
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
531
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
532
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
533
}
534

            
535
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
536
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
537
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
538

            
539
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
540
    Runtime,
541
    BLOCK_PROCESSING_VELOCITY,
542
    UNINCLUDED_SEGMENT_CAPACITY,
543
>;
544

            
545
impl cumulus_pallet_parachain_system::Config for Runtime {
546
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
547
    type RuntimeEvent = RuntimeEvent;
548
    type OnSystemEvent = ();
549
    type SelfParaId = parachain_info::Pallet<Runtime>;
550
    type OutboundXcmpMessageSource = XcmpQueue;
551
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
552
    type ReservedDmpWeight = ReservedDmpWeight;
553
    type XcmpMessageHandler = XcmpQueue;
554
    type ReservedXcmpWeight = ReservedXcmpWeight;
555
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
556
    type ConsensusHook = ConsensusHook;
557
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
558
    type RelayParentOffset = ConstU32<0>;
559
}
560

            
561
pub struct ParaSlotProvider;
562
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
563
924
    fn get() -> (Slot, SlotDuration) {
564
924
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
565
924
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
566
924
    }
567
}
568

            
569
parameter_types! {
570
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
571
}
572

            
573
impl pallet_async_backing::Config for Runtime {
574
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
575
    type GetAndVerifySlot =
576
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
577
    type ExpectedBlockTime = ExpectedBlockTime;
578
}
579

            
580
impl parachain_info::Config for Runtime {}
581

            
582
parameter_types! {
583
    pub const Period: u32 = 6 * HOURS;
584
    pub const Offset: u32 = 0;
585
}
586

            
587
impl pallet_sudo::Config for Runtime {
588
    type RuntimeCall = RuntimeCall;
589
    type RuntimeEvent = RuntimeEvent;
590
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
591
}
592

            
593
impl pallet_utility::Config for Runtime {
594
    type RuntimeEvent = RuntimeEvent;
595
    type RuntimeCall = RuntimeCall;
596
    type PalletsOrigin = OriginCaller;
597
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
598
}
599

            
600
/// The type used to represent the kinds of proxying allowed.
601
#[derive(
602
    Copy,
603
    Clone,
604
    Eq,
605
    PartialEq,
606
    Ord,
607
    PartialOrd,
608
    Encode,
609
    Decode,
610
    DecodeWithMemTracking,
611
    Debug,
612
    MaxEncodedLen,
613
    TypeInfo,
614
)]
615
#[allow(clippy::unnecessary_cast)]
616
pub enum ProxyType {
617
    /// All calls can be proxied. This is the trivial/most permissive filter.
618
    Any = 0,
619
    /// Only extrinsics that do not transfer funds.
620
    NonTransfer = 1,
621
    /// Only extrinsics related to governance (democracy and collectives).
622
    Governance = 2,
623
    /// Allow to veto an announced proxy call.
624
    CancelProxy = 3,
625
    /// Allow extrinsic related to Balances.
626
    Balances = 4,
627
}
628

            
629
impl Default for ProxyType {
630
    fn default() -> Self {
631
        Self::Any
632
    }
633
}
634

            
635
// Be careful: Each time this filter is modified, the substrate filter must also be modified
636
// consistently.
637
impl pallet_evm_precompile_proxy::EvmProxyCallFilter for ProxyType {
638
    fn is_evm_proxy_call_allowed(
639
        &self,
640
        call: &pallet_evm_precompile_proxy::EvmSubCall,
641
        recipient_has_code: bool,
642
        gas: u64,
643
    ) -> precompile_utils::EvmResult<bool> {
644
        Ok(match self {
645
            ProxyType::Any => true,
646
            ProxyType::NonTransfer => false,
647
            ProxyType::Governance => false,
648
            // The proxy precompile does not contain method cancel_proxy
649
            ProxyType::CancelProxy => false,
650
            ProxyType::Balances => {
651
                // Allow only "simple" accounts as recipient (no code nor precompile).
652
                // Note: Checking the presence of the code is not enough because some precompiles
653
                // have no code.
654
                !recipient_has_code
655
                    && !precompile_utils::precompile_set::is_precompile_or_fail::<Runtime>(
656
                        call.to.0, gas,
657
                    )?
658
            }
659
        })
660
    }
661
}
662

            
663
impl InstanceFilter<RuntimeCall> for ProxyType {
664
    fn filter(&self, c: &RuntimeCall) -> bool {
665
        // Since proxy filters are respected in all dispatches of the Utility
666
        // pallet, it should never need to be filtered by any proxy.
667
        if let RuntimeCall::Utility(..) = c {
668
            return true;
669
        }
670

            
671
        match self {
672
            ProxyType::Any => true,
673
            ProxyType::NonTransfer => {
674
                matches!(
675
                    c,
676
                    RuntimeCall::System(..)
677
                        | RuntimeCall::ParachainSystem(..)
678
                        | RuntimeCall::Timestamp(..)
679
                        | RuntimeCall::Proxy(..)
680
                )
681
            }
682
            // We don't have governance yet
683
            ProxyType::Governance => false,
684
            ProxyType::CancelProxy => matches!(
685
                c,
686
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
687
            ),
688
            ProxyType::Balances => {
689
                matches!(c, RuntimeCall::Balances(..))
690
            }
691
        }
692
    }
693

            
694
    fn is_superset(&self, o: &Self) -> bool {
695
        match (self, o) {
696
            (x, y) if x == y => true,
697
            (ProxyType::Any, _) => true,
698
            (_, ProxyType::Any) => false,
699
            _ => false,
700
        }
701
    }
702
}
703

            
704
impl pallet_proxy::Config for Runtime {
705
    type RuntimeEvent = RuntimeEvent;
706
    type RuntimeCall = RuntimeCall;
707
    type Currency = Balances;
708
    type ProxyType = ProxyType;
709
    // One storage item; key size 32, value size 8
710
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
711
    // Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
712
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
713
    type MaxProxies = ConstU32<32>;
714
    type MaxPending = ConstU32<32>;
715
    type CallHasher = BlakeTwo256;
716
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
717
    // Additional storage item size of 56 bytes:
718
    // - 20 bytes AccountId
719
    // - 32 bytes Hasher (Blake2256)
720
    // - 4 bytes BlockNumber (u32)
721
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
722
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
723
    type BlockNumberProvider = System;
724
}
725

            
726
pub struct XcmExecutionManager;
727
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
728
    fn suspend_xcm_execution() -> DispatchResult {
729
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
730
    }
731
    fn resume_xcm_execution() -> DispatchResult {
732
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
733
    }
734
}
735

            
736
impl cumulus_pallet_weight_reclaim::Config for Runtime {
737
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
738
}
739

            
740
impl pallet_migrations::Config for Runtime {
741
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
742
    type XcmExecutionManager = XcmExecutionManager;
743
}
744

            
745
parameter_types! {
746
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
747
}
748

            
749
impl pallet_multiblock_migrations::Config for Runtime {
750
    type RuntimeEvent = RuntimeEvent;
751
    #[cfg(not(feature = "runtime-benchmarks"))]
752
    type Migrations = ();
753
    // Benchmarks need mocked migrations to guarantee that they succeed.
754
    #[cfg(feature = "runtime-benchmarks")]
755
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
756
    type CursorMaxLen = ConstU32<65_536>;
757
    type IdentifierMaxLen = ConstU32<256>;
758
    type MigrationStatusHandler = ();
759
    type FailedMigrationHandler = MaintenanceMode;
760
    type MaxServiceWeight = MbmServiceWeight;
761
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
762
}
763

            
764
/// Maintenance mode Call filter
765
pub struct MaintenanceFilter;
766
impl Contains<RuntimeCall> for MaintenanceFilter {
767
    fn contains(c: &RuntimeCall) -> bool {
768
        !matches!(
769
            c,
770
            RuntimeCall::Balances(_)
771
                | RuntimeCall::Ethereum(_)
772
                | RuntimeCall::EVM(_)
773
                | RuntimeCall::PolkadotXcm(_)
774
        )
775
    }
776
}
777

            
778
/// Normal Call Filter
779
/// We dont allow to create nor mint assets, this for now is disabled
780
/// We only allow transfers. For now creation of assets will go through
781
/// asset-manager, while minting/burning only happens through xcm messages
782
/// This can change in the future
783
pub struct NormalFilter;
784
impl Contains<RuntimeCall> for NormalFilter {
785
1848
    fn contains(c: &RuntimeCall) -> bool {
786
1848
        !matches!(
787
1848
            c,
788
            // Filtering the EVM prevents possible re-entrancy from the precompiles which could
789
            // lead to unexpected scenarios.
790
            // See https://github.com/PureStake/sr-moonbeam/issues/30
791
            // Note: It is also assumed that EVM calls are only allowed through `Origin::Root` so
792
            // this can be seen as an additional security
793
            RuntimeCall::EVM(_)
794
        )
795
1848
    }
796
}
797

            
798
impl pallet_maintenance_mode::Config for Runtime {
799
    type NormalCallFilter = NormalFilter;
800
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
801
    type MaintenanceOrigin = EnsureRoot<AccountId>;
802
    type XcmExecutionManager = XcmExecutionManager;
803
}
804

            
805
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
806
pub mod dynamic_params {
807
    use super::*;
808

            
809
    #[dynamic_pallet_params]
810
    #[codec(index = 3)]
811
    pub mod contract_deploy_filter {
812
        #[codec(index = 0)]
813
        pub static AllowedAddressesToCreate: DeployFilter = DeployFilter::All;
814
        #[codec(index = 1)]
815
        pub static AllowedAddressesToCreateInner: DeployFilter = DeployFilter::All;
816
    }
817

            
818
    /// The Dancelight genesis hash used as the default relay network identifier.
819
    pub const DANCELIGHT_GENESIS_HASH: [u8; 32] =
820
        hex_literal::hex!["983a1a72503d6cc3636776747ec627172b51272bf45e50a355348facb67a820a"];
821

            
822
    #[dynamic_pallet_params]
823
    #[codec(index = 4)]
824
    pub mod xcm_config {
825
        use super::*;
826

            
827
        /// The relay network identifier for this container chain.
828
        /// Using Dancelight genesis hash as default.
829
        #[codec(index = 0)]
830
        pub static RelayNetwork: xcm::latest::NetworkId =
831
            xcm::latest::NetworkId::ByGenesis(DANCELIGHT_GENESIS_HASH);
832
    }
833
}
834

            
835
impl pallet_parameters::Config for Runtime {
836
    type AdminOrigin = EnsureRoot<AccountId>;
837
    type RuntimeEvent = RuntimeEvent;
838
    type RuntimeParameters = RuntimeParameters;
839
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
840
}
841

            
842
#[cfg(feature = "runtime-benchmarks")]
843
impl Default for RuntimeParameters {
844
    fn default() -> Self {
845
        RuntimeParameters::ContractDeployFilter(
846
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
847
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
848
                Some(DeployFilter::All),
849
            ),
850
        )
851
    }
852
}
853

            
854
#[derive(
855
    Clone, PartialEq, Encode, Decode, DecodeWithMemTracking, TypeInfo, Eq, MaxEncodedLen, Debug,
856
)]
857
pub enum DeployFilter {
858
    All,
859
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
860
}
861

            
862
pub struct AddressFilter<Runtime, AddressList>(core::marker::PhantomData<(Runtime, AddressList)>);
863
impl<Runtime, AddressList> EnsureCreateOrigin<Runtime> for AddressFilter<Runtime, AddressList>
864
where
865
    Runtime: pallet_evm::Config,
866
    AddressList: Get<DeployFilter>,
867
{
868
    fn check_create_origin(address: &H160) -> Result<(), pallet_evm::Error<Runtime>> {
869
        let deploy_filter: DeployFilter = AddressList::get();
870

            
871
        match deploy_filter {
872
            DeployFilter::All => Ok(()),
873
            DeployFilter::Whitelisted(addresses_vec) => {
874
                if !addresses_vec.contains(address) {
875
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
876
                } else {
877
                    Ok(())
878
                }
879
            }
880
        }
881
    }
882
}
883

            
884
impl pallet_evm_chain_id::Config for Runtime {}
885

            
886
pub struct FindAuthorAdapter;
887
impl FindAuthor<H160> for FindAuthorAdapter {
888
1467
    fn find_author<'a, I>(digests: I) -> Option<H160>
889
1467
    where
890
1467
        I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
891
    {
892
1467
        if let Some(author) = AuthorInherent::find_author(digests) {
893
            return Some(H160::from_slice(&author.encode()[0..20]));
894
1467
        }
895
1467
        None
896
1467
    }
897
}
898

            
899
/// Current approximation of the gas/s consumption considering
900
/// EVM execution over compiled WASM (on 4.4Ghz CPU).
901
/// Given the 1000ms Weight, from which 75% only are used for transactions,
902
/// the total EVM execution gas limit is: GAS_PER_SECOND * 1 * 0.75 ~= 30_000_000.
903
pub const GAS_PER_SECOND: u64 = 40_000_000;
904

            
905
/// Approximate ratio of the amount of Weight per Gas.
906
/// u64 works for approximations because Weight is a very small unit compared to gas.
907
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
908

            
909
parameter_types! {
910
    pub BlockGasLimit: U256
911
        = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
912
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
913
    pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
914
    pub SuicideQuickClearLimit: u32 = 0;
915
    pub GasLimitPovSizeRatio: u32 = 16;
916
    /// Hardcoding the value, since it is computed on block execution. Check calculations in the tests
917
    pub GasLimitStorageGrowthRatio: u64 = 1464;
918
}
919

            
920
impl_on_charge_evm_transaction!();
921
impl pallet_evm::Config for Runtime {
922
    type AccountProvider = FrameSystemAccountProvider<Runtime>;
923
    type FeeCalculator = BaseFee;
924
    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
925
    type WeightPerGas = WeightPerGas;
926
    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
927
    type CallOrigin = EnsureAddressRoot<AccountId>;
928
    type WithdrawOrigin = EnsureAddressNever<AccountId>;
929
    type AddressMapping = IdentityAddressMapping;
930
    type CreateOriginFilter =
931
        AddressFilter<Runtime, dynamic_params::contract_deploy_filter::AllowedAddressesToCreate>;
932
    type CreateInnerOriginFilter = AddressFilter<
933
        Runtime,
934
        dynamic_params::contract_deploy_filter::AllowedAddressesToCreateInner,
935
    >;
936
    type Currency = Balances;
937
    type PrecompilesType = TemplatePrecompiles<Self>;
938
    type PrecompilesValue = PrecompilesValue;
939
    type ChainId = EVMChainId;
940
    type BlockGasLimit = BlockGasLimit;
941
    type Runner = pallet_evm::runner::stack::Runner<Self>;
942
    type OnChargeTransaction = OnChargeEVMTransaction<()>;
943
    type OnCreate = ();
944
    type FindAuthor = FindAuthorAdapter;
945
    type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
946
    type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
947
    type Timestamp = Timestamp;
948
    type WeightInfo = ();
949
}
950

            
951
parameter_types! {
952
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
953
}
954

            
955
impl pallet_ethereum::Config for Runtime {
956
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
957
    type PostLogContent = PostBlockAndTxnHashes;
958
    type ExtraDataLength = ConstU32<30>;
959
}
960

            
961
parameter_types! {
962
    pub BoundDivision: U256 = U256::from(1024);
963
}
964

            
965
parameter_types! {
966
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
967
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
968
}
969

            
970
pub struct BaseFeeThreshold;
971
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
972
924
    fn lower() -> Permill {
973
924
        Permill::zero()
974
924
    }
975
1848
    fn ideal() -> Permill {
976
1848
        Permill::from_parts(500_000)
977
1848
    }
978
924
    fn upper() -> Permill {
979
924
        Permill::from_parts(1_000_000)
980
924
    }
981
}
982

            
983
impl pallet_base_fee::Config for Runtime {
984
    type Threshold = BaseFeeThreshold;
985
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
986
    type DefaultElasticity = DefaultElasticity;
987
}
988

            
989
impl pallet_root_testing::Config for Runtime {
990
    type RuntimeEvent = RuntimeEvent;
991
}
992

            
993
impl pallet_tx_pause::Config for Runtime {
994
    type RuntimeEvent = RuntimeEvent;
995
    type RuntimeCall = RuntimeCall;
996
    type PauseOrigin = EnsureRoot<AccountId>;
997
    type UnpauseOrigin = EnsureRoot<AccountId>;
998
    type WhitelistedCalls = ();
999
    type MaxNameLen = ConstU32<256>;
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
}
impl dp_impl_tanssi_pallets_config::Config for Runtime {
    const SLOT_DURATION: u64 = SLOT_DURATION;
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
}
parameter_types! {
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
    pub const DepositBase: Balance = currency::deposit(1, 96);
    // Additional storage item size of 20 bytes.
    pub const DepositFactor: Balance = currency::deposit(0, 20);
    pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
    type RuntimeEvent = RuntimeEvent;
    type RuntimeCall = RuntimeCall;
    type Currency = Balances;
    type DepositBase = DepositBase;
    type DepositFactor = DepositFactor;
    type MaxSignatories = MaxSignatories;
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
    type BlockNumberProvider = System;
}
impl_tanssi_pallets_config!(Runtime);
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
    pub enum Runtime
    {
        // System support stuff.
        System: frame_system = 0,
        ParachainSystem: cumulus_pallet_parachain_system = 1,
        Timestamp: pallet_timestamp = 2,
        ParachainInfo: parachain_info = 3,
        Sudo: pallet_sudo = 4,
        Utility: pallet_utility = 5,
        Proxy: pallet_proxy = 6,
        Migrations: pallet_migrations = 7,
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
        MaintenanceMode: pallet_maintenance_mode = 8,
        TxPause: pallet_tx_pause = 9,
        // Monetary stuff.
        Balances: pallet_balances = 10,
        // Other utilities
        Multisig: pallet_multisig = 16,
        Parameters: pallet_parameters = 17,
        // ContainerChain
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
        AuthorInherent: pallet_author_inherent = 51,
        // Frontier
        Ethereum: pallet_ethereum = 60,
        EVM: pallet_evm = 61,
        EVMChainId: pallet_evm_chain_id = 62,
        BaseFee: pallet_base_fee = 64,
        TransactionPayment: pallet_transaction_payment = 66,
        // XCM
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
        RootTesting: pallet_root_testing = 100,
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
    }
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
    frame_benchmarking::define_benchmarks!(
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
        [cumulus_pallet_parachain_system, ParachainSystem]
        [pallet_timestamp, Timestamp]
        [pallet_sudo, Sudo]
        [pallet_utility, Utility]
        [pallet_proxy, Proxy]
        [pallet_transaction_payment, TransactionPayment]
        [pallet_tx_pause, TxPause]
        [pallet_balances, Balances]
        [pallet_multiblock_migrations, MultiBlockMigrations]
        [pallet_multisig, Multisig]
        [pallet_parameters, Parameters]
        [pallet_cc_authorities_noting, AuthoritiesNoting]
        [pallet_author_inherent, AuthorInherent]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        [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]
        [cumulus_pallet_weight_reclaim, WeightReclaim]
        [pallet_evm_precompile_sha3fips, EVMPrecompileSha3FIPSBench::<Runtime>]
    );
}
impl_runtime_apis! {
    impl sp_api::Core<Block> for Runtime {
        fn version() -> RuntimeVersion {
            VERSION
        }
        fn execute_block(block: Block) {
            Executive::execute_block(block)
        }
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
            Executive::initialize_block(header)
        }
    }
    impl sp_api::Metadata<Block> for Runtime {
        fn metadata() -> OpaqueMetadata {
            OpaqueMetadata::new(Runtime::metadata().into())
        }
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
            Runtime::metadata_at_version(version)
        }
        fn metadata_versions() -> Vec<u32> {
            Runtime::metadata_versions()
        }
    }
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
            Executive::apply_extrinsic(extrinsic)
        }
        fn finalize_block() -> <Block as BlockT>::Header {
            Executive::finalize_block()
        }
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
            data.create_extrinsics()
        }
        fn check_inherents(
            block: Block,
            data: sp_inherents::InherentData,
        ) -> sp_inherents::CheckInherentsResult {
            data.check_extrinsics(&block)
        }
    }
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
        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) {
                return InvalidTransaction::Call.into();
            }
            // This runtime uses Substrate's pallet transaction payment. This
            // makes the chain feel like a standard Substrate chain when submitting
            // frame transactions and using Substrate ecosystem tools. It has the downside that
            // transaction are not prioritized by gas_price. The following code reprioritizes
            // transactions to overcome this.
            //
            // A more elegant, ethereum-first solution is
            // a pallet that replaces pallet transaction payment, and allows users
            // to directly specify a gas price rather than computing an effective one.
            // #HopefullySomeday
            // First we pass the transactions to the standard FRAME executive. This calculates all the
            // necessary tags, longevity and other properties that we will leave unchanged.
            // This also assigns some priority that we don't care about and will overwrite next.
            let mut intermediate_valid = Executive::validate_transaction(source, xt.clone(), block_hash)?;
            let dispatch_info = xt.get_dispatch_info();
            // If this is a pallet ethereum transaction, then its priority is already set
            // according to effective priority fee from pallet ethereum. If it is any other kind of
            // transaction, we modify its priority. The goal is to arrive at a similar metric used
            // by pallet ethereum, which means we derive a fee-per-gas from the txn's tip and
            // weight.
            Ok(match &xt.0.function {
                RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
                _ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
                _ => {
                    let tip = match xt.0.preamble.to_signed() {
                        None => 0,
                        Some((_, _, ref signed_extra)) => {
                            // Yuck, this depends on the index of charge transaction in Signed Extra
                            let charge_transaction = &signed_extra.0.7;
                            charge_transaction.tip()
                        }
                    };
                    let effective_gas =
                        <Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
                            dispatch_info.total_weight()
                        );
                    let tip_per_gas = tip.checked_div(u128::from(effective_gas)).unwrap_or(0);
                    // Overwrite the original prioritization with this ethereum one
                    intermediate_valid.priority = tip_per_gas as u64;
                    intermediate_valid
                }
            })
        }
    }
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
        fn offchain_worker(header: &<Block as BlockT>::Header) {
            Executive::offchain_worker(header)
        }
    }
    impl sp_session::SessionKeys<Block> for Runtime {
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
            SessionKeys::generate(seed)
        }
        fn decode_session_keys(
            encoded: Vec<u8>,
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
            SessionKeys::decode_into_raw_public_keys(&encoded)
        }
    }
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
        fn account_nonce(account: AccountId) -> Index {
            System::account_nonce(account)
        }
    }
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
            ParachainSystem::collect_collation_info(header)
        }
    }
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
        fn can_build_upon(
            included_hash: <Block as BlockT>::Hash,
            slot: async_backing_primitives::Slot,
        ) -> bool {
            ConsensusHook::can_build_upon(included_hash, slot)
        }
    }
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
            build_state::<RuntimeGenesisConfig>(config)
        }
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
        }
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
            vec![]
        }
    }
    #[cfg(feature = "runtime-benchmarks")]
    impl frame_benchmarking::Benchmark<Block> for Runtime {
        fn benchmark_metadata(
            extra: bool,
        ) -> (
            Vec<frame_benchmarking::BenchmarkList>,
            Vec<frame_support::traits::StorageInfo>,
        ) {
            use frame_benchmarking::{BenchmarkList};
            use frame_support::traits::StorageInfoTrait;
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            use pallet_evm_precompile_sha3fips_benchmarking::Pallet as EVMPrecompileSha3FIPSBench;
            let mut list = Vec::<BenchmarkList>::new();
            list_benchmarks!(list, extra);
            let storage_info = AllPalletsWithSystem::storage_info();
            (list, storage_info)
        }
        #[allow(non_local_definitions)]
        fn dispatch_benchmark(
            config: frame_benchmarking::BenchmarkConfig,
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
            use sp_core::storage::TrackedStorageKey;
            use xcm::latest::prelude::*;
            use alloc::boxed::Box;
            use pallet_evm_precompile_sha3fips_benchmarking::Pallet as EVMPrecompileSha3FIPSBench;
            impl pallet_evm_precompile_sha3fips_benchmarking::Config for Runtime {}
            impl frame_system_benchmarking::Config for Runtime {
                fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
                    Ok(())
                }
                fn verify_set_code() {
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
                }
            }
            use xcm_config::SelfReserve;
            parameter_types! {
                pub ExistentialDepositAsset: Option<Asset> = Some((
                    SelfReserve::get(),
                    ExistentialDeposit::get()
                ).into());
            }
            impl pallet_xcm_benchmarks::Config for Runtime {
                type XcmConfig = xcm_config::XcmConfig;
                type AccountIdConverter = xcm_config::LocationToAccountId;
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
                    xcm_config::XcmConfig,
                    ExistentialDepositAsset,
                    xcm_config::PriceForParentDelivery,
                >;
                fn valid_destination() -> Result<Location, BenchmarkError> {
                    Ok(Location::parent())
                }
                fn worst_case_holding(_depositable_count: u32) -> Assets {
                    // We only care for native asset until we support others
                    // TODO: refactor this case once other assets are supported
                    vec![Asset{
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(u128::MAX),
                    }].into()
                }
            }
            impl pallet_xcm_benchmarks::generic::Config for Runtime {
                type TransactAsset = Balances;
                type RuntimeCall = RuntimeCall;
                fn worst_case_response() -> (u64, Response) {
                    (0u64, Response::Version(Default::default()))
                }
                fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
                    tanssi_runtime_common::universal_aliases::AliasingBenchmarksHelper::prepare_universal_alias()
                    .ok_or(BenchmarkError::Skip)
                }
                fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
                    Ok((Location::parent(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
                }
                fn subscribe_origin() -> Result<Location, BenchmarkError> {
                    Ok(Location::parent())
                }
                fn worst_case_for_trader() -> Result<(Asset, WeightLimit), BenchmarkError> {
                    Ok((Asset {
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(crate::currency::MICROUNIT*100),
                    }, WeightLimit::Unlimited))
                }
                fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
                    let origin = Location::parent();
                    let assets: Assets = (Location::parent(), 1_000u128).into();
                    let ticket = Location { parents: 0, interior: Here };
                    Ok((origin, ticket, assets))
                }
                fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn export_message_origin_and_destination(
                ) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
                fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
                    Err(BenchmarkError::Skip)
                }
            }
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
            impl pallet_xcm::benchmarking::Config for Runtime {
                type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
                    xcm_config::XcmConfig,
                    ExistentialDepositAsset,
                    xcm_config::PriceForParentDelivery,
                >;
                fn get_asset() -> Asset {
                    Asset {
                        id: AssetId(SelfReserve::get()),
                        fun: Fungible(crate::currency::MICROUNIT),
                    }
                }
                fn reachable_dest() -> Option<Location> {
                    Some(Parent.into())
                }
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
                    let teleportable = crate::currency::MICROUNIT;
                    // Relay/native token can be teleported between AH and Relay.
                    Some((
                        Asset {
                            fun: Fungible(teleportable),
                            id: Parent.into()
                        },
                        Parent.into(),
                    ))
                }
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
                    use xcm_config::SelfReserve;
                    // AH can reserve transfer native token to some random parachain.
                    let random_para_id = 43211234;
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
                        random_para_id.into()
                    );
                    let who = frame_benchmarking::whitelisted_caller();
                    // Give some multiple of the existential deposit
                    let balance = crate::currency::MICROUNIT* 1000;
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
                        &who, balance,
                    );
                    Some((
                        Asset {
                            fun: Fungible(balance),
                            id: SelfReserve::get().into()
                        },
                        ParentThen(Parachain(random_para_id).into()).into(),
                    ))
                }
                fn set_up_complex_asset_transfer(
                ) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
                    use xcm_config::SelfReserve;
                    // Transfer to Relay some local AH asset (local-reserve-transfer) while paying
                    // fees using teleported native token.
                    // (We don't care that Relay doesn't accept incoming unknown AH local asset)
                    let dest = Parent.into();
                    let fee_amount = crate::currency::MICROUNIT;
                    let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
                    let who = frame_benchmarking::whitelisted_caller();
                    // Give some multiple of the existential deposit
                    let balance = fee_amount + crate::currency::MICROUNIT * 1000;
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
                        &who, balance,
                    );
                    // verify initial balance
                    assert_eq!(Balances::free_balance(who), balance);
                    // set up local asset
                    let asset_amount = 10u128;
                    let initial_asset_amount = asset_amount * 10;
                    let (asset_id, asset_location) = pallet_foreign_asset_creator::benchmarks::create_minted_asset::<Runtime>(
                        initial_asset_amount,
                        who,
                        None,
                    );
                    let transfer_asset: Asset = (asset_location, asset_amount).into();
                    let assets: Assets = vec![fee_asset.clone(), transfer_asset].into();
                    let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 };
                    // verify transferred successfully
                    let verify = Box::new(move || {
                        // verify native balance after transfer, decreased by transferred fee amount
                        // (plus transport fees)
                        assert!(Balances::free_balance(who) <= balance - fee_amount);
                        // verify asset balance decreased by exactly transferred amount
                        assert_eq!(
                            ForeignAssets::balance(asset_id, who),
                            initial_asset_amount - asset_amount,
                        );
                    });
                    Some((assets, fee_index, dest, verify))
                }
            }
            let whitelist: Vec<TrackedStorageKey> = vec![
                // Block Number
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac")
                    .to_vec()
                    .into(),
                // Total Issuance
                hex_literal::hex!("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80")
                    .to_vec()
                    .into(),
                // Execution Phase
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a")
                    .to_vec()
                    .into(),
                // Event Count
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850")
                    .to_vec()
                    .into(),
                // System Events
                hex_literal::hex!("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7")
                    .to_vec()
                    .into(),
                // The transactional storage limit.
                hex_literal::hex!("3a7472616e73616374696f6e5f6c6576656c3a")
                    .to_vec()
                    .into(),
                // ParachainInfo ParachainId
                hex_literal::hex!(  "0d715f2646c8f85767b5d2764bb2782604a74d81251e398fd8a0a4d55023bb3f")
                    .to_vec()
                    .into(),
            ];
            let mut batches = Vec::<BenchmarkBatch>::new();
            let params = (&config, &whitelist);
            add_benchmarks!(params, batches);
            Ok(batches)
        }
    }
    #[cfg(feature = "try-runtime")]
    impl frame_try_runtime::TryRuntime<Block> for Runtime {
        fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) {
            let weight = Executive::try_runtime_upgrade(checks).unwrap();
            (weight, RuntimeBlockWeights::get().max_block)
        }
        fn execute_block(
            block: Block,
            state_root_check: bool,
            signature_check: bool,
            select: frame_try_runtime::TryStateSelect,
        ) -> Weight {
            // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to
            // have a backtrace here.
            Executive::try_execute_block(block, state_root_check, signature_check, select).unwrap()
        }
    }
    impl fp_rpc::EthereumRuntimeRPCApi<Block> for Runtime {
        fn chain_id() -> u64 {
            <Runtime as pallet_evm::Config>::ChainId::get()
        }
        fn account_basic(address: H160) -> EVMAccount {
            let (account, _) = pallet_evm::Pallet::<Runtime>::account_basic(&address);
            account
        }
        fn gas_price() -> U256 {
            let (gas_price, _) = <Runtime as pallet_evm::Config>::FeeCalculator::min_gas_price();
            gas_price
        }
        fn account_code_at(address: H160) -> Vec<u8> {
            pallet_evm::AccountCodes::<Runtime>::get(address)
        }
        fn author() -> H160 {
            <pallet_evm::Pallet<Runtime>>::find_author()
        }
        fn storage_at(address: H160, index: U256) -> H256 {
            let tmp = index.to_big_endian();
            pallet_evm::AccountStorages::<Runtime>::get(address, H256::from_slice(&tmp[..]))
        }
        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>)>>,
            authorization_list: Option<AuthorizationList>,
        ) -> Result<pallet_evm::CallInfo, sp_runtime::DispatchError> {
            let config = if estimate {
                let mut config = <Runtime as pallet_evm::Config>::config().clone();
                config.estimate = true;
                Some(config)
            } else {
                None
            };
            let is_transactional = false;
            let validate = true;
            let transaction_data = pallet_ethereum::TransactionData::new(
                pallet_ethereum::TransactionAction::Call(to),
                data.clone(),
                nonce.unwrap_or_default(),
                gas_limit,
                None,
                max_fee_per_gas.or(Some(U256::default())),
                max_priority_fee_per_gas.or(Some(U256::default())),
                value,
                Some(<Runtime as pallet_evm::Config>::ChainId::get()),
                access_list.clone().unwrap_or_default(),
                authorization_list.clone().unwrap_or_default(),
            );
            let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
            let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
            <Runtime as pallet_evm::Config>::Runner::call(
                from,
                to,
                data,
                value,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                nonce,
                access_list.unwrap_or_default(),
                authorization_list.unwrap_or_default(),
                is_transactional,
                validate,
                weight_limit,
                proof_size_base_cost,
                config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
            ).map_err(|err| err.error.into())
        }
        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>)>>,
            authorization_list: Option<AuthorizationList>,
        ) -> Result<pallet_evm::CreateInfo, sp_runtime::DispatchError> {
            let config = if estimate {
                let mut config = <Runtime as pallet_evm::Config>::config().clone();
                config.estimate = true;
                Some(config)
            } else {
                None
            };
            let is_transactional = false;
            let validate = true;
            let transaction_data = pallet_ethereum::TransactionData::new(
                pallet_ethereum::TransactionAction::Create,
                data.clone(),
                nonce.unwrap_or_default(),
                gas_limit,
                None,
                max_fee_per_gas.or(Some(U256::default())),
                max_priority_fee_per_gas.or(Some(U256::default())),
                value,
                Some(<Runtime as pallet_evm::Config>::ChainId::get()),
                access_list.clone().unwrap_or_default(),
                authorization_list.clone().unwrap_or_default(),
            );
            let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
            let (weight_limit, proof_size_base_cost) = pallet_ethereum::Pallet::<Runtime>::transaction_weight(&transaction_data);
            <Runtime as pallet_evm::Config>::Runner::create(
                from,
                data,
                value,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                nonce,
                access_list.unwrap_or_default(),
                authorization_list.unwrap_or_default(),
                is_transactional,
                validate,
                weight_limit,
                proof_size_base_cost,
                config.as_ref().unwrap_or(<Runtime as pallet_evm::Config>::config()),
            ).map_err(|err| err.error.into())
        }
        fn current_transaction_statuses() -> Option<Vec<TransactionStatus>> {
            pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
        }
        fn current_block() -> Option<pallet_ethereum::Block> {
            pallet_ethereum::CurrentBlock::<Runtime>::get()
        }
        fn current_receipts() -> Option<Vec<pallet_ethereum::Receipt>> {
            pallet_ethereum::CurrentReceipts::<Runtime>::get()
        }
        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()
            )
        }
        fn extrinsic_filter(
            xts: Vec<<Block as BlockT>::Extrinsic>,
        ) -> Vec<EthereumTransaction> {
            xts.into_iter().filter_map(|xt| match xt.0.function {
                RuntimeCall::Ethereum(transact { transaction }) => Some(transaction),
                _ => None
            }).collect::<Vec<EthereumTransaction>>()
        }
        fn elasticity() -> Option<Permill> {
            Some(pallet_base_fee::Elasticity::<Runtime>::get())
        }
        fn gas_limit_multiplier_support() {}
        fn pending_block(xts: Vec<<Block as BlockT>::Extrinsic>) -> (Option<pallet_ethereum::Block>, Option<alloc::vec::Vec<TransactionStatus>>) {
            for ext in xts.into_iter() {
                let _ = Executive::apply_extrinsic(ext);
            }
            Ethereum::on_finalize(System::block_number() + 1);
            (
                pallet_ethereum::CurrentBlock::<Runtime>::get(),
                pallet_ethereum::CurrentTransactionStatuses::<Runtime>::get()
            )
        }
        fn initialize_pending_block(header: &<Block as BlockT>::Header) {
            Executive::initialize_block(header);
        }
    }
    impl fp_rpc::ConvertTransactionRuntimeApi<Block> for Runtime {
        fn convert_transaction(
            transaction: pallet_ethereum::Transaction
        ) -> <Block as BlockT>::Extrinsic {
            UncheckedExtrinsic::new_bare(
                pallet_ethereum::Call::<Runtime>::transact { transaction }.into(),
            )
        }
    }
    impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<Block, Balance>
    for Runtime {
        fn query_info(
            uxt: <Block as BlockT>::Extrinsic,
            len: u32,
        ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo<Balance> {
            TransactionPayment::query_info(uxt, len)
        }
        fn query_fee_details(
            uxt: <Block as BlockT>::Extrinsic,
            len: u32,
        ) -> pallet_transaction_payment::FeeDetails<Balance> {
            TransactionPayment::query_fee_details(uxt, len)
        }
        fn query_weight_to_fee(weight: Weight) -> Balance {
            TransactionPayment::weight_to_fee(weight)
        }
        fn query_length_to_fee(length: u32) -> Balance {
            TransactionPayment::length_to_fee(length)
        }
    }
    impl dp_slot_duration_runtime_api::TanssiSlotDurationApi<Block> for Runtime {
        fn slot_duration() -> u64 {
            SLOT_DURATION
        }
    }
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
            if !matches!(xcm_version, 3..=5) {
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
            }
            Ok([VersionedAssetId::V5(xcm_config::SelfReserve::get().into())]
                .into_iter()
                .chain(
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
                            VersionedAssetId::V5(location.into())
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
                            None
                        })
                    })
                )
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
                }).ok())
                .collect())
        }
        fn query_weight_to_asset_fee(weight: Weight, asset: VersionedAssetId) -> Result<u128, XcmPaymentApiError> {
            let local_asset = VersionedAssetId::V5(xcm_config::SelfReserve::get().into());
            let asset = asset
                .into_version(5)
                .map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
            if asset == local_asset {
                Ok(WeightToFee::weight_to_fee(&weight))
            } else {
                let native_fee = WeightToFee::weight_to_fee(&weight);
                let asset_v5: xcm::latest::AssetId = asset.try_into().map_err(|_| XcmPaymentApiError::VersionedConversionFailed)?;
                let location: xcm::latest::Location = asset_v5.0;
                let asset_id = pallet_foreign_asset_creator::ForeignAssetToAssetId::<Runtime>::get(location).ok_or(XcmPaymentApiError::AssetNotFound)?;
                let asset_rate = AssetRate::to_asset_balance(native_fee, asset_id);
                match asset_rate {
                    Ok(x) => Ok(x),
                    Err(pallet_asset_rate::Error::UnknownAssetKind) => Err(XcmPaymentApiError::AssetNotFound),
                    // Error when converting native balance to asset balance, probably overflow
                    Err(_e) => Err(XcmPaymentApiError::WeightNotComputable),
                }
            }
        }
        fn query_xcm_weight(message: VersionedXcm<()>) -> Result<Weight, XcmPaymentApiError> {
            PolkadotXcm::query_xcm_weight(message)
        }
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
    }
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
        fn dry_run_call(origin: OriginCaller, call: RuntimeCall, result_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
        }
        fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
        }
    }
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
        fn convert_location(location: VersionedLocation) -> Result<
            AccountId,
            xcm_runtime_apis::conversions::Error
        > {
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
                AccountId,
                xcm_config::LocationToAccountId,
            >::convert_location(location)
        }
    }
66178
}
#[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,
                core::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}
#[cfg(test)]
mod tests {
    use super::*;
    /// Block storage limit in bytes. Set to 40 KB.
    const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
    #[test]
1
    fn check_ratio_constant() {
1
        assert_eq!(
1
            BlockGasLimit::get().min(u64::MAX.into()).low_u64() / BLOCK_STORAGE_LIMIT,
1
            GasLimitStorageGrowthRatio::get()
        );
1
    }
}