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

            
112
// Polkadot imports
113
use polkadot_runtime_common::BlockHashCount;
114

            
115
pub type Precompiles = TemplatePrecompiles<Runtime>;
116

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

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

            
124
/// Balance of an account.
125
pub type Balance = u128;
126

            
127
/// Index of a transaction in the chain.
128
pub type Index = u32;
129

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

            
133
/// An index to a block.
134
pub type BlockNumber = u32;
135

            
136
/// The address format for describing accounts.
137
pub type Address = AccountId;
138

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

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

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

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

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

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

            
182
pub mod currency {
183
    use super::Balance;
184

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

            
190
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
191

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

            
197
impl fp_self_contained::SelfContainedCall for RuntimeCall {
198
    type SignedInfo = H160;
199

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

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

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

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

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

            
255
#[derive(Clone)]
256
pub struct TransactionConverter;
257

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

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

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

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

            
312
parameter_types! {
313
        /// Network and location for the Ethereum chain. On Starlight, the Ethereum chain bridged
314
        /// to is the Ethereum mainnet, with chain ID 1.
315
        /// <https://chainlist.org/chain/1>
316
        /// <https://ethereum.org/en/developers/docs/apis/json-rpc/#net_version>
317
        pub EthereumNetwork: NetworkId = NetworkId::Ethereum { chain_id: 11155111 };
318

            
319
}
320

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

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

            
340
mod impl_on_charge_evm_transaction;
341

            
342
impl_opaque_keys! {
343
    pub struct SessionKeys { }
344
}
345

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

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

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

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

            
375
pub const EXISTENTIAL_DEPOSIT: Balance = 0;
376

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

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

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

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

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

            
403
parameter_types! {
404
    pub const Version: RuntimeVersion = VERSION;
405

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

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

            
489
parameter_types! {
490
    pub const TransactionByteFee: Balance = 1;
491
}
492

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

            
504
parameter_types! {
505
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
506
}
507

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

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

            
533
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
534
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
535
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
536

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

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

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

            
566
parameter_types! {
567
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
568
}
569

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

            
577
impl parachain_info::Config for Runtime {}
578

            
579
parameter_types! {
580
    pub const Period: u32 = 6 * HOURS;
581
    pub const Offset: u32 = 0;
582
}
583

            
584
impl pallet_sudo::Config for Runtime {
585
    type RuntimeCall = RuntimeCall;
586
    type RuntimeEvent = RuntimeEvent;
587
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
588
}
589

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

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

            
626
impl Default for ProxyType {
627
    fn default() -> Self {
628
        Self::Any
629
    }
630
}
631

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

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

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

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

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

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

            
733
impl cumulus_pallet_weight_reclaim::Config for Runtime {
734
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
735
}
736

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

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

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

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

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

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

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

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

            
818
impl pallet_parameters::Config for Runtime {
819
    type AdminOrigin = EnsureRoot<AccountId>;
820
    type RuntimeEvent = RuntimeEvent;
821
    type RuntimeParameters = RuntimeParameters;
822
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
823
}
824

            
825
#[cfg(feature = "runtime-benchmarks")]
826
impl Default for RuntimeParameters {
827
    fn default() -> Self {
828
        RuntimeParameters::ContractDeployFilter(
829
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
830
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
831
                Some(DeployFilter::All),
832
            ),
833
        )
834
    }
835
}
836

            
837
#[derive(
838
    Clone, PartialEq, Encode, Decode, DecodeWithMemTracking, TypeInfo, Eq, MaxEncodedLen, Debug,
839
)]
840
pub enum DeployFilter {
841
    All,
842
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
843
}
844

            
845
pub struct AddressFilter<Runtime, AddressList>(core::marker::PhantomData<(Runtime, AddressList)>);
846
impl<Runtime, AddressList> EnsureCreateOrigin<Runtime> for AddressFilter<Runtime, AddressList>
847
where
848
    Runtime: pallet_evm::Config,
849
    AddressList: Get<DeployFilter>,
850
{
851
    fn check_create_origin(address: &H160) -> Result<(), pallet_evm::Error<Runtime>> {
852
        let deploy_filter: DeployFilter = AddressList::get();
853

            
854
        match deploy_filter {
855
            DeployFilter::All => Ok(()),
856
            DeployFilter::Whitelisted(addresses_vec) => {
857
                if !addresses_vec.contains(address) {
858
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
859
                } else {
860
                    Ok(())
861
                }
862
            }
863
        }
864
    }
865
}
866

            
867
impl pallet_evm_chain_id::Config for Runtime {}
868

            
869
pub struct FindAuthorAdapter;
870
impl FindAuthor<H160> for FindAuthorAdapter {
871
1300
    fn find_author<'a, I>(digests: I) -> Option<H160>
872
1300
    where
873
1300
        I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
874
1300
    {
875
1300
        if let Some(author) = AuthorInherent::find_author(digests) {
876
            return Some(H160::from_slice(&author.encode()[0..20]));
877
1300
        }
878
1300
        None
879
1300
    }
880
}
881

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

            
888
/// Approximate ratio of the amount of Weight per Gas.
889
/// u64 works for approximations because Weight is a very small unit compared to gas.
890
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
891

            
892
parameter_types! {
893
    pub BlockGasLimit: U256
894
        = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
895
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
896
    pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
897
    pub SuicideQuickClearLimit: u32 = 0;
898
    pub GasLimitPovSizeRatio: u32 = 16;
899
    /// Hardcoding the value, since it is computed on block execution. Check calculations in the tests
900
    pub GasLimitStorageGrowthRatio: u64 = 1464;
901
}
902

            
903
impl_on_charge_evm_transaction!();
904
impl pallet_evm::Config for Runtime {
905
    type AccountProvider = FrameSystemAccountProvider<Runtime>;
906
    type FeeCalculator = BaseFee;
907
    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
908
    type WeightPerGas = WeightPerGas;
909
    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
910
    type CallOrigin = EnsureAddressRoot<AccountId>;
911
    type WithdrawOrigin = EnsureAddressNever<AccountId>;
912
    type AddressMapping = IdentityAddressMapping;
913
    type CreateOriginFilter =
914
        AddressFilter<Runtime, dynamic_params::contract_deploy_filter::AllowedAddressesToCreate>;
915
    type CreateInnerOriginFilter = AddressFilter<
916
        Runtime,
917
        dynamic_params::contract_deploy_filter::AllowedAddressesToCreateInner,
918
    >;
919
    type Currency = Balances;
920
    type RuntimeEvent = RuntimeEvent;
921
    type PrecompilesType = TemplatePrecompiles<Self>;
922
    type PrecompilesValue = PrecompilesValue;
923
    type ChainId = EVMChainId;
924
    type BlockGasLimit = BlockGasLimit;
925
    type Runner = pallet_evm::runner::stack::Runner<Self>;
926
    type OnChargeTransaction = OnChargeEVMTransaction<()>;
927
    type OnCreate = ();
928
    type FindAuthor = FindAuthorAdapter;
929
    type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
930
    type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
931
    type Timestamp = Timestamp;
932
    type WeightInfo = ();
933
}
934

            
935
parameter_types! {
936
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
937
}
938

            
939
impl pallet_ethereum::Config for Runtime {
940
    type RuntimeEvent = RuntimeEvent;
941
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
942
    type PostLogContent = PostBlockAndTxnHashes;
943
    type ExtraDataLength = ConstU32<30>;
944
}
945

            
946
parameter_types! {
947
    pub BoundDivision: U256 = U256::from(1024);
948
}
949

            
950
parameter_types! {
951
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
952
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
953
}
954

            
955
pub struct BaseFeeThreshold;
956
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
957
759
    fn lower() -> Permill {
958
759
        Permill::zero()
959
759
    }
960
1518
    fn ideal() -> Permill {
961
1518
        Permill::from_parts(500_000)
962
1518
    }
963
759
    fn upper() -> Permill {
964
759
        Permill::from_parts(1_000_000)
965
759
    }
966
}
967

            
968
impl pallet_base_fee::Config for Runtime {
969
    type RuntimeEvent = RuntimeEvent;
970
    type Threshold = BaseFeeThreshold;
971
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
972
    type DefaultElasticity = DefaultElasticity;
973
}
974

            
975
impl pallet_root_testing::Config for Runtime {
976
    type RuntimeEvent = RuntimeEvent;
977
}
978

            
979
impl pallet_tx_pause::Config for Runtime {
980
    type RuntimeEvent = RuntimeEvent;
981
    type RuntimeCall = RuntimeCall;
982
    type PauseOrigin = EnsureRoot<AccountId>;
983
    type UnpauseOrigin = EnsureRoot<AccountId>;
984
    type WhitelistedCalls = ();
985
    type MaxNameLen = ConstU32<256>;
986
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
987
}
988

            
989
impl dp_impl_tanssi_pallets_config::Config for Runtime {
990
    const SLOT_DURATION: u64 = SLOT_DURATION;
991
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
992
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
993
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
994
}
995

            
996
parameter_types! {
997
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
998
    pub const DepositBase: Balance = currency::deposit(1, 96);
999
    // 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.
17504
construct_runtime!(
17504
    pub enum Runtime
17504
    {
17504
        // System support stuff.
17504
        System: frame_system = 0,
17504
        ParachainSystem: cumulus_pallet_parachain_system = 1,
17504
        Timestamp: pallet_timestamp = 2,
17504
        ParachainInfo: parachain_info = 3,
17504
        Sudo: pallet_sudo = 4,
17504
        Utility: pallet_utility = 5,
17504
        Proxy: pallet_proxy = 6,
17504
        Migrations: pallet_migrations = 7,
17504
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
17504
        MaintenanceMode: pallet_maintenance_mode = 8,
17504
        TxPause: pallet_tx_pause = 9,
17504

            
17504
        // Monetary stuff.
17504
        Balances: pallet_balances = 10,
17504

            
17504
        // Other utilities
17504
        Multisig: pallet_multisig = 16,
17504
        Parameters: pallet_parameters = 17,
17504

            
17504
        // ContainerChain
17504
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
17504
        AuthorInherent: pallet_author_inherent = 51,
17504

            
17504
        // Frontier
17504
        Ethereum: pallet_ethereum = 60,
17504
        EVM: pallet_evm = 61,
17504
        EVMChainId: pallet_evm_chain_id = 62,
17504
        BaseFee: pallet_base_fee = 64,
17504
        TransactionPayment: pallet_transaction_payment = 66,
17504

            
17504
        // XCM
17504
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
17504
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
17504
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
17504
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
17504
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
17504
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
17504
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
17504
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
17504

            
17504
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
17504

            
17504
        RootTesting: pallet_root_testing = 100,
17504
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
17504
    }
17504
);
#[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]
    );
}
24824
impl_runtime_apis! {
24824
    impl sp_api::Core<Block> for Runtime {
24824
        fn version() -> RuntimeVersion {
            VERSION
        }
24824

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

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

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

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

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

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

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

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

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

            
24824
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
24824
        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) {
24824
                return InvalidTransaction::Call.into();
24824
            }
24824

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

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

            
24824
            let dispatch_info = xt.get_dispatch_info();
24824

            
24824
            // If this is a pallet ethereum transaction, then its priority is already set
24824
            // according to effective priority fee from pallet ethereum. If it is any other kind of
24824
            // transaction, we modify its priority. The goal is to arrive at a similar metric used
24824
            // by pallet ethereum, which means we derive a fee-per-gas from the txn's tip and
24824
            // weight.
24824
            Ok(match &xt.0.function {
24824
                RuntimeCall::Ethereum(transact { .. }) => intermediate_valid,
24824
                _ if dispatch_info.class != DispatchClass::Normal => intermediate_valid,
24824
                _ => {
24824
                    let tip = match xt.0.preamble.to_signed() {
24824
                        None => 0,
24824
                        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()
24824
                        }
24824
                    };
24824

            
24824
                    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
24824
                }
24824
            })
24824
        }
24824
    }
24824

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
24824
                fn fee_asset() -> Result<Asset, BenchmarkError> {
24824
                    Ok(Asset {
24824
                        id: AssetId(SelfReserve::get()),
24824
                        fun: Fungible(crate::currency::MICROUNIT*100),
24824
                    })
24824
                }
24824

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

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

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

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

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

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

            
24824
                fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
24824
                    let teleportable = crate::currency::MICROUNIT;
24824
                    // Relay/native token can be teleported between AH and Relay.
24824
                    Some((
24824
                        Asset {
24824
                            fun: Fungible(teleportable),
24824
                            id: Parent.into()
24824
                        },
24824
                        Parent.into(),
24824
                    ))
24824
                }
24824

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

            
24824
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
24824
                        random_para_id.into()
24824
                    );
24824
                    let who = frame_benchmarking::whitelisted_caller();
24824

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

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

            
24824
                    let fee_amount = crate::currency::MICROUNIT;
24824
                    let fee_asset: Asset = (SelfReserve::get(), fee_amount).into();
24824

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

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

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

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

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

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

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

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

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

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

            
24824
            add_benchmarks!(params, batches);
24824

            
24824
            Ok(batches)
24824
        }
24824
    }
24824

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

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

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

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

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

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

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

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

            
24824
        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> {
24824
            let config = if estimate {
24824
                let mut config = <Runtime as pallet_evm::Config>::config().clone();
                config.estimate = true;
                Some(config)
24824
            } else {
24824
                None
24824
            };
24824
            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(),
                            );
            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(),
                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())
        }
24824

            
24824
        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> {
24824
            let config = if estimate {
24824
                let mut config = <Runtime as pallet_evm::Config>::config().clone();
                config.estimate = true;
                Some(config)
24824
            } else {
24824
                None
24824
            };
24824
            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(),
            );
            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(),
                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())
        }
24824

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

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

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

            
24824
        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()
            )
        }
24824

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

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

            
24824
        fn gas_limit_multiplier_support() {}
24824

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

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

            
24824
        fn initialize_pending_block(header: &<Block as BlockT>::Header) {
            Executive::initialize_block(header);
        }
24824
    }
24824

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

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

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

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

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

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

            
24824
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
24824
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
24824
            if !matches!(xcm_version, 3..=5) {
24824
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
24824
            }
            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);
24824
                            None
                        })
                    })
                )
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
24824
                }).ok())
                .collect())
24824
        }
24824

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

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

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

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

            
24824
    impl xcm_runtime_apis::dry_run::DryRunApi<Block, RuntimeCall, RuntimeEvent, OriginCaller> for Runtime {
24824
        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)
        }
24824

            
24824
        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)
        }
24824
    }
24824

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