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

            
110
// Polkadot imports
111
use polkadot_runtime_common::BlockHashCount;
112

            
113
pub type Precompiles = TemplatePrecompiles<Runtime>;
114

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

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

            
122
/// Balance of an account.
123
pub type Balance = u128;
124

            
125
/// Index of a transaction in the chain.
126
pub type Index = u32;
127

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

            
131
/// An index to a block.
132
pub type BlockNumber = u32;
133

            
134
/// The address format for describing accounts.
135
pub type Address = AccountId;
136

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

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

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

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

            
149
/// The `TxExtension` to the basic transaction logic.
150
pub type TxExtension = (
151
    frame_system::CheckNonZeroSender<Runtime>,
152
    frame_system::CheckSpecVersion<Runtime>,
153
    frame_system::CheckTxVersion<Runtime>,
154
    frame_system::CheckGenesis<Runtime>,
155
    frame_system::CheckEra<Runtime>,
156
    frame_system::CheckNonce<Runtime>,
157
    frame_system::CheckWeight<Runtime>,
158
    pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
159
    cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
160
);
161

            
162
/// Unchecked extrinsic type as expected by this runtime.
163
pub type UncheckedExtrinsic =
164
    fp_self_contained::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
165
/// Extrinsic type that has already been checked.
166
pub type CheckedExtrinsic =
167
    fp_self_contained::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension, H160>;
168
/// The payload being signed in transactions.
169
pub type SignedPayload = generic::SignedPayload<RuntimeCall, TxExtension>;
170

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

            
180
pub mod currency {
181
    use super::Balance;
182

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

            
188
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
189

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

            
195
impl fp_self_contained::SelfContainedCall for RuntimeCall {
196
    type SignedInfo = H160;
197

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

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

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

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

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

            
253
#[derive(Clone)]
254
pub struct TransactionConverter;
255

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

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

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

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

            
310
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
311
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
312
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
313
/// to even the core data structures.
314
pub mod opaque {
315
    use {
316
        super::*,
317
        sp_runtime::{generic, traits::BlakeTwo256},
318
    };
319

            
320
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
321
    /// Opaque block header type.
322
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
323
    /// Opaque block type.
324
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
325
    /// Opaque block identifier type.
326
    pub type BlockId = generic::BlockId<Block>;
327
}
328

            
329
mod impl_on_charge_evm_transaction;
330

            
331
impl_opaque_keys! {
332
    pub struct SessionKeys { }
333
}
334

            
335
#[sp_version::runtime_version]
336
pub const VERSION: RuntimeVersion = RuntimeVersion {
337
    spec_name: Cow::Borrowed("frontier-template"),
338
    impl_name: Cow::Borrowed("frontier-template"),
339
    authoring_version: 1,
340
    spec_version: 1400,
341
    impl_version: 0,
342
    apis: RUNTIME_API_VERSIONS,
343
    transaction_version: 1,
344
    system_version: 1,
345
};
346

            
347
/// This determines the average expected block time that we are targeting.
348
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
349
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
350
/// up by `pallet_aura` to implement `fn slot_duration()`.
351
///
352
/// Change this to adjust the block time.
353
pub const MILLISECS_PER_BLOCK: u64 = 6000;
354

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

            
359
// Time is measured by number of blocks.
360
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
361
pub const HOURS: BlockNumber = MINUTES * 60;
362
pub const DAYS: BlockNumber = HOURS * 24;
363

            
364
pub const EXISTENTIAL_DEPOSIT: Balance = 0;
365

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

            
370
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
371
/// `Operational` extrinsics.
372
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
373

            
374
/// We allow for 2 seconds of compute with a 6 second average block time
375
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
376
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
377
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
378
);
379

            
380
/// We allow for 2 seconds of compute with a 6 second average block time
381
pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 2000;
382

            
383
/// The version information used to identify this runtime when compiled natively.
384
#[cfg(feature = "std")]
385
pub fn native_version() -> NativeVersion {
386
    NativeVersion {
387
        runtime_version: VERSION,
388
        can_author_with: Default::default(),
389
    }
390
}
391

            
392
parameter_types! {
393
    pub const Version: RuntimeVersion = VERSION;
394

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

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

            
478
parameter_types! {
479
    pub const TransactionByteFee: Balance = 1;
480
}
481

            
482
impl pallet_transaction_payment::Config for Runtime {
483
    type RuntimeEvent = RuntimeEvent;
484
    // This will burn the fees
485
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
486
    type OperationalFeeMultiplier = ConstU8<5>;
487
    type WeightToFee = WeightToFee;
488
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
489
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
490
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
491
}
492

            
493
parameter_types! {
494
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
495
}
496

            
497
impl pallet_balances::Config for Runtime {
498
    type MaxLocks = ConstU32<50>;
499
    /// The type for recording an account's balance.
500
    type Balance = Balance;
501
    /// The ubiquitous event type.
502
    type RuntimeEvent = RuntimeEvent;
503
    type DustRemoval = ();
504
    type ExistentialDeposit = ExistentialDeposit;
505
    type AccountStore = System;
506
    type MaxReserves = ConstU32<50>;
507
    type ReserveIdentifier = [u8; 8];
508
    type FreezeIdentifier = RuntimeFreezeReason;
509
    type MaxFreezes = ConstU32<0>;
510
    type RuntimeHoldReason = RuntimeHoldReason;
511
    type RuntimeFreezeReason = RuntimeFreezeReason;
512
    type DoneSlashHandler = ();
513
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
514
}
515

            
516
parameter_types! {
517
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
518
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
519
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
520
}
521

            
522
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
523
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
524
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
525

            
526
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
527
    Runtime,
528
    BLOCK_PROCESSING_VELOCITY,
529
    UNINCLUDED_SEGMENT_CAPACITY,
530
>;
531

            
532
impl cumulus_pallet_parachain_system::Config for Runtime {
533
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
534
    type RuntimeEvent = RuntimeEvent;
535
    type OnSystemEvent = ();
536
    type SelfParaId = parachain_info::Pallet<Runtime>;
537
    type OutboundXcmpMessageSource = XcmpQueue;
538
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
539
    type ReservedDmpWeight = ReservedDmpWeight;
540
    type XcmpMessageHandler = XcmpQueue;
541
    type ReservedXcmpWeight = ReservedXcmpWeight;
542
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
543
    type ConsensusHook = ConsensusHook;
544
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
545
}
546

            
547
pub struct ParaSlotProvider;
548
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
549
726
    fn get() -> (Slot, SlotDuration) {
550
726
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
551
726
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
552
726
    }
553
}
554

            
555
parameter_types! {
556
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
557
}
558

            
559
impl pallet_async_backing::Config for Runtime {
560
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
561
    type GetAndVerifySlot =
562
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
563
    type ExpectedBlockTime = ExpectedBlockTime;
564
}
565

            
566
impl parachain_info::Config for Runtime {}
567

            
568
parameter_types! {
569
    pub const Period: u32 = 6 * HOURS;
570
    pub const Offset: u32 = 0;
571
}
572

            
573
impl pallet_sudo::Config for Runtime {
574
    type RuntimeCall = RuntimeCall;
575
    type RuntimeEvent = RuntimeEvent;
576
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
577
}
578

            
579
impl pallet_utility::Config for Runtime {
580
    type RuntimeEvent = RuntimeEvent;
581
    type RuntimeCall = RuntimeCall;
582
    type PalletsOrigin = OriginCaller;
583
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
584
}
585

            
586
/// The type used to represent the kinds of proxying allowed.
587
#[derive(
588
    Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
589
)]
590
#[allow(clippy::unnecessary_cast)]
591
pub enum ProxyType {
592
    /// All calls can be proxied. This is the trivial/most permissive filter.
593
    Any = 0,
594
    /// Only extrinsics that do not transfer funds.
595
    NonTransfer = 1,
596
    /// Only extrinsics related to governance (democracy and collectives).
597
    Governance = 2,
598
    /// Allow to veto an announced proxy call.
599
    CancelProxy = 3,
600
    /// Allow extrinsic related to Balances.
601
    Balances = 4,
602
}
603

            
604
impl Default for ProxyType {
605
    fn default() -> Self {
606
        Self::Any
607
    }
608
}
609

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

            
638
impl InstanceFilter<RuntimeCall> for ProxyType {
639
    fn filter(&self, c: &RuntimeCall) -> bool {
640
        // Since proxy filters are respected in all dispatches of the Utility
641
        // pallet, it should never need to be filtered by any proxy.
642
        if let RuntimeCall::Utility(..) = c {
643
            return true;
644
        }
645

            
646
        match self {
647
            ProxyType::Any => true,
648
            ProxyType::NonTransfer => {
649
                matches!(
650
                    c,
651
                    RuntimeCall::System(..)
652
                        | RuntimeCall::ParachainSystem(..)
653
                        | RuntimeCall::Timestamp(..)
654
                        | RuntimeCall::Proxy(..)
655
                )
656
            }
657
            // We don't have governance yet
658
            ProxyType::Governance => false,
659
            ProxyType::CancelProxy => matches!(
660
                c,
661
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
662
            ),
663
            ProxyType::Balances => {
664
                matches!(c, RuntimeCall::Balances(..))
665
            }
666
        }
667
    }
668

            
669
    fn is_superset(&self, o: &Self) -> bool {
670
        match (self, o) {
671
            (x, y) if x == y => true,
672
            (ProxyType::Any, _) => true,
673
            (_, ProxyType::Any) => false,
674
            _ => false,
675
        }
676
    }
677
}
678

            
679
impl pallet_proxy::Config for Runtime {
680
    type RuntimeEvent = RuntimeEvent;
681
    type RuntimeCall = RuntimeCall;
682
    type Currency = Balances;
683
    type ProxyType = ProxyType;
684
    // One storage item; key size 32, value size 8
685
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
686
    // Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
687
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
688
    type MaxProxies = ConstU32<32>;
689
    type MaxPending = ConstU32<32>;
690
    type CallHasher = BlakeTwo256;
691
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
692
    // Additional storage item size of 56 bytes:
693
    // - 20 bytes AccountId
694
    // - 32 bytes Hasher (Blake2256)
695
    // - 4 bytes BlockNumber (u32)
696
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
697
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
698
}
699

            
700
pub struct XcmExecutionManager;
701
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
702
    fn suspend_xcm_execution() -> DispatchResult {
703
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
704
    }
705
    fn resume_xcm_execution() -> DispatchResult {
706
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
707
    }
708
}
709

            
710
impl pallet_migrations::Config for Runtime {
711
    type RuntimeEvent = RuntimeEvent;
712
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
713
    type XcmExecutionManager = XcmExecutionManager;
714
}
715

            
716
parameter_types! {
717
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
718
}
719

            
720
impl pallet_multiblock_migrations::Config for Runtime {
721
    type RuntimeEvent = RuntimeEvent;
722
    #[cfg(not(feature = "runtime-benchmarks"))]
723
    type Migrations = ();
724
    // Benchmarks need mocked migrations to guarantee that they succeed.
725
    #[cfg(feature = "runtime-benchmarks")]
726
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
727
    type CursorMaxLen = ConstU32<65_536>;
728
    type IdentifierMaxLen = ConstU32<256>;
729
    type MigrationStatusHandler = ();
730
    type FailedMigrationHandler = MaintenanceMode;
731
    type MaxServiceWeight = MbmServiceWeight;
732
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
733
}
734

            
735
/// Maintenance mode Call filter
736
pub struct MaintenanceFilter;
737
impl Contains<RuntimeCall> for MaintenanceFilter {
738
    fn contains(c: &RuntimeCall) -> bool {
739
        !matches!(
740
            c,
741
            RuntimeCall::Balances(_)
742
                | RuntimeCall::Ethereum(_)
743
                | RuntimeCall::EVM(_)
744
                | RuntimeCall::PolkadotXcm(_)
745
        )
746
    }
747
}
748

            
749
/// Normal Call Filter
750
/// We dont allow to create nor mint assets, this for now is disabled
751
/// We only allow transfers. For now creation of assets will go through
752
/// asset-manager, while minting/burning only happens through xcm messages
753
/// This can change in the future
754
pub struct NormalFilter;
755
impl Contains<RuntimeCall> for NormalFilter {
756
    fn contains(c: &RuntimeCall) -> bool {
757
        !matches!(
758
            c,
759
            // Filtering the EVM prevents possible re-entrancy from the precompiles which could
760
            // lead to unexpected scenarios.
761
            // See https://github.com/PureStake/sr-moonbeam/issues/30
762
            // Note: It is also assumed that EVM calls are only allowed through `Origin::Root` so
763
            // this can be seen as an additional security
764
            RuntimeCall::EVM(_)
765
        )
766
    }
767
}
768

            
769
impl pallet_maintenance_mode::Config for Runtime {
770
    type RuntimeEvent = RuntimeEvent;
771
    type NormalCallFilter = NormalFilter;
772
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
773
    type MaintenanceOrigin = EnsureRoot<AccountId>;
774
    type XcmExecutionManager = XcmExecutionManager;
775
}
776

            
777
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
778
pub mod dynamic_params {
779
    use super::*;
780

            
781
    #[dynamic_pallet_params]
782
    #[codec(index = 3)]
783
    pub mod contract_deploy_filter {
784
        #[codec(index = 0)]
785
        pub static AllowedAddressesToCreate: DeployFilter = DeployFilter::All;
786
        #[codec(index = 1)]
787
        pub static AllowedAddressesToCreateInner: DeployFilter = DeployFilter::All;
788
    }
789
}
790

            
791
impl pallet_parameters::Config for Runtime {
792
    type AdminOrigin = EnsureRoot<AccountId>;
793
    type RuntimeEvent = RuntimeEvent;
794
    type RuntimeParameters = RuntimeParameters;
795
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
796
}
797

            
798
#[cfg(feature = "runtime-benchmarks")]
799
impl Default for RuntimeParameters {
800
    fn default() -> Self {
801
        RuntimeParameters::ContractDeployFilter(
802
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
803
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
804
                Some(DeployFilter::All),
805
            ),
806
        )
807
    }
808
}
809

            
810
#[derive(Clone, PartialEq, Encode, Decode, TypeInfo, Eq, MaxEncodedLen, Debug)]
811
pub enum DeployFilter {
812
    All,
813
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
814
}
815

            
816
pub struct AddressFilter<Runtime, AddressList>(sp_std::marker::PhantomData<(Runtime, AddressList)>);
817
impl<Runtime, AddressList> EnsureCreateOrigin<Runtime> for AddressFilter<Runtime, AddressList>
818
where
819
    Runtime: pallet_evm::Config,
820
    AddressList: Get<DeployFilter>,
821
{
822
    fn check_create_origin(address: &H160) -> Result<(), pallet_evm::Error<Runtime>> {
823
        let deploy_filter: DeployFilter = AddressList::get();
824

            
825
        match deploy_filter {
826
            DeployFilter::All => Ok(()),
827
            DeployFilter::Whitelisted(addresses_vec) => {
828
                if !addresses_vec.contains(address) {
829
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
830
                } else {
831
                    Ok(())
832
                }
833
            }
834
        }
835
    }
836
}
837

            
838
impl pallet_evm_chain_id::Config for Runtime {}
839

            
840
pub struct FindAuthorAdapter;
841
impl FindAuthor<H160> for FindAuthorAdapter {
842
1145
    fn find_author<'a, I>(digests: I) -> Option<H160>
843
1145
    where
844
1145
        I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
845
1145
    {
846
1145
        if let Some(author) = AuthorInherent::find_author(digests) {
847
            return Some(H160::from_slice(&author.encode()[0..20]));
848
1145
        }
849
1145
        None
850
1145
    }
851
}
852

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

            
859
/// Approximate ratio of the amount of Weight per Gas.
860
/// u64 works for approximations because Weight is a very small unit compared to gas.
861
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
862

            
863
parameter_types! {
864
    pub BlockGasLimit: U256
865
        = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
866
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
867
    pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
868
    pub SuicideQuickClearLimit: u32 = 0;
869
    pub GasLimitPovSizeRatio: u32 = 16;
870
    /// Hardcoding the value, since it is computed on block execution. Check calculations in the tests
871
    pub GasLimitStorageGrowthRatio: u64 = 1464;
872
}
873

            
874
impl_on_charge_evm_transaction!();
875
impl pallet_evm::Config for Runtime {
876
    type AccountProvider = FrameSystemAccountProvider<Runtime>;
877
    type FeeCalculator = BaseFee;
878
    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
879
    type WeightPerGas = WeightPerGas;
880
    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
881
    type CallOrigin = EnsureAddressRoot<AccountId>;
882
    type WithdrawOrigin = EnsureAddressNever<AccountId>;
883
    type AddressMapping = IdentityAddressMapping;
884
    type CreateOrigin =
885
        AddressFilter<Runtime, dynamic_params::contract_deploy_filter::AllowedAddressesToCreate>;
886
    type CreateInnerOrigin = AddressFilter<
887
        Runtime,
888
        dynamic_params::contract_deploy_filter::AllowedAddressesToCreateInner,
889
    >;
890
    type Currency = Balances;
891
    type RuntimeEvent = RuntimeEvent;
892
    type PrecompilesType = TemplatePrecompiles<Self>;
893
    type PrecompilesValue = PrecompilesValue;
894
    type ChainId = EVMChainId;
895
    type BlockGasLimit = BlockGasLimit;
896
    type Runner = pallet_evm::runner::stack::Runner<Self>;
897
    type OnChargeTransaction = OnChargeEVMTransaction<()>;
898
    type OnCreate = ();
899
    type FindAuthor = FindAuthorAdapter;
900
    type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
901
    type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
902
    type Timestamp = Timestamp;
903
    type WeightInfo = ();
904
}
905

            
906
parameter_types! {
907
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
908
}
909

            
910
impl pallet_ethereum::Config for Runtime {
911
    type RuntimeEvent = RuntimeEvent;
912
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
913
    type PostLogContent = PostBlockAndTxnHashes;
914
    type ExtraDataLength = ConstU32<30>;
915
}
916

            
917
parameter_types! {
918
    pub BoundDivision: U256 = U256::from(1024);
919
}
920

            
921
parameter_types! {
922
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
923
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
924
}
925

            
926
pub struct BaseFeeThreshold;
927
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
928
    fn lower() -> Permill {
929
        Permill::zero()
930
    }
931
    fn ideal() -> Permill {
932
        Permill::from_parts(500_000)
933
    }
934
    fn upper() -> Permill {
935
        Permill::from_parts(1_000_000)
936
    }
937
}
938

            
939
impl pallet_base_fee::Config for Runtime {
940
    type RuntimeEvent = RuntimeEvent;
941
    type Threshold = BaseFeeThreshold;
942
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
943
    type DefaultElasticity = DefaultElasticity;
944
}
945

            
946
impl pallet_root_testing::Config for Runtime {
947
    type RuntimeEvent = RuntimeEvent;
948
}
949

            
950
impl pallet_tx_pause::Config for Runtime {
951
    type RuntimeEvent = RuntimeEvent;
952
    type RuntimeCall = RuntimeCall;
953
    type PauseOrigin = EnsureRoot<AccountId>;
954
    type UnpauseOrigin = EnsureRoot<AccountId>;
955
    type WhitelistedCalls = ();
956
    type MaxNameLen = ConstU32<256>;
957
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
958
}
959

            
960
impl dp_impl_tanssi_pallets_config::Config for Runtime {
961
    const SLOT_DURATION: u64 = SLOT_DURATION;
962
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
963
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
964
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
965
}
966

            
967
parameter_types! {
968
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
969
    pub const DepositBase: Balance = currency::deposit(1, 96);
970
    // Additional storage item size of 20 bytes.
971
    pub const DepositFactor: Balance = currency::deposit(0, 20);
972
    pub const MaxSignatories: u32 = 100;
973
}
974

            
975
impl pallet_multisig::Config for Runtime {
976
    type RuntimeEvent = RuntimeEvent;
977
    type RuntimeCall = RuntimeCall;
978
    type Currency = Balances;
979
    type DepositBase = DepositBase;
980
    type DepositFactor = DepositFactor;
981
    type MaxSignatories = MaxSignatories;
982
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
983
}
984

            
985
impl_tanssi_pallets_config!(Runtime);
986

            
987
// Create the runtime by composing the FRAME pallets that were previously configured.
988
93014
construct_runtime!(
989
11542
    pub enum Runtime
990
11542
    {
991
11542
        // System support stuff.
992
11542
        System: frame_system = 0,
993
11542
        ParachainSystem: cumulus_pallet_parachain_system = 1,
994
11542
        Timestamp: pallet_timestamp = 2,
995
11542
        ParachainInfo: parachain_info = 3,
996
11542
        Sudo: pallet_sudo = 4,
997
11542
        Utility: pallet_utility = 5,
998
11542
        Proxy: pallet_proxy = 6,
999
11542
        Migrations: pallet_migrations = 7,
11542
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
11542
        MaintenanceMode: pallet_maintenance_mode = 8,
11542
        TxPause: pallet_tx_pause = 9,
11542

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
24630
            let dispatch_info = xt.get_dispatch_info();
24630

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

            
24630
                    // TODO: call_weight or call_weight+extension_weight
24630
                    // In stable2412, polkadot has added extension weight, which is an extra weight
24630
                    // for some transaction validations such as nonce, age, signature, etc.
24630
                    // Currently we ignore that in the frontier template
24630
                    let effective_gas =
                        <Runtime as pallet_evm::Config>::GasWeightMapping::weight_to_gas(
                            dispatch_info.call_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
24630
                }
24630
            })
24630
        }
24630
    }
24630

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
24630
            add_benchmarks!(params, batches);
24630

            
24630
            Ok(batches)
24630
        }
24630
    }
24630

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

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

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

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

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

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

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

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

            
24630
        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> {
24630
            let config = if estimate {
24630
                let mut config = <Runtime as pallet_evm::Config>::config().clone();
                config.estimate = true;
                Some(config)
24630
            } else {
24630
                None
24630
            };
24630
            let is_transactional = false;
            let validate = true;
            // Estimated encoded transaction size must be based on the heaviest transaction
            // type (EIP1559Transaction) to be compatible with all transaction types.
            // TODO: remove, since we will get rid of base_cost
            let mut estimated_transaction_len = data.len() +
                // pallet ethereum index: 1
                // transact call index: 1
                // Transaction enum variant: 1
                // chain_id 8 bytes
                // nonce: 32
                // max_priority_fee_per_gas: 32
                // max_fee_per_gas: 32
                // gas_limit: 32
                // action: 21 (enum varianrt + call address)
                // value: 32
                // access_list: 1 (empty vec size)
                // 65 bytes signature
                258;
24630

            
24630
            if let Some(ref list) = access_list {
                estimated_transaction_len += list.encoded_size();
            }
24630

            
24630
            let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
            let without_base_extrinsic_weight = true;
24630

            
24630
            let (weight_limit, proof_size_base_cost) = match
24630
                <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
                    gas_limit,
                    without_base_extrinsic_weight
                ) {
24630
                    weight_limit if weight_limit.proof_size() > 0 => {
24630
                        (Some(weight_limit), Some(estimated_transaction_len as u64))
24630
                    }
24630
                    _ => (None, None),
24630
                };
24630

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

            
24630
        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> {
24630
            let config = if estimate {
24630
                let mut config = <Runtime as pallet_evm::Config>::config().clone();
                config.estimate = true;
                Some(config)
24630
            } else {
24630
                None
24630
            };
24630
            let is_transactional = false;
            let validate = true;
            let mut estimated_transaction_len = data.len() +
                        // from: 20
                        // value: 32
                        // gas_limit: 32
                        // nonce: 32
                        // 1 byte transaction action variant
                        // chain id 8 bytes
                        // 65 bytes signature
                        190;
            if max_fee_per_gas.is_some() {
                estimated_transaction_len += 32;
            }
24630
            if max_priority_fee_per_gas.is_some() {
                estimated_transaction_len += 32;
            }
24630
            if let Some(ref list) = access_list {
                estimated_transaction_len += list.encoded_size();
            }
24630

            
24630
            let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
            let without_base_extrinsic_weight = true;
24630

            
24630
            let (weight_limit, proof_size_base_cost) = match
24630
                <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
                    gas_limit,
                    without_base_extrinsic_weight
                ) {
24630
                    weight_limit if weight_limit.proof_size() > 0 => {
24630
                        (Some(weight_limit), Some(estimated_transaction_len as u64))
24630
                    }
24630
                    _ => (None, None),
24630
                };
24630

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

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

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

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

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

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

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

            
24630
        fn gas_limit_multiplier_support() {}
24630

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
24630
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
24630
        fn convert_location(location: VersionedLocation) -> Result<
            AccountId,
            xcm_runtime_apis::conversions::Error
        > {
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
                AccountId,
                xcm_config::LocationToAccountId,
            >::convert_location(location)
        }
24630
    }
41472
}
#[allow(dead_code)]
struct CheckInherents;
// TODO: this should be removed but currently if we remove it the relay does not check anything
// related to other inherents that are not parachain-system
#[allow(deprecated)]
impl cumulus_pallet_parachain_system::CheckInherents<Block> for CheckInherents {
    fn check_inherents(
        block: &Block,
        relay_state_proof: &cumulus_pallet_parachain_system::RelayChainStateProof,
    ) -> sp_inherents::CheckInherentsResult {
        let relay_chain_slot = relay_state_proof
            .read_slot()
            .expect("Could not read the relay chain slot from the proof");
        let inherent_data =
            cumulus_primitives_timestamp::InherentDataProvider::from_relay_chain_slot_and_duration(
                relay_chain_slot,
                sp_std::time::Duration::from_secs(6),
            )
            .create_inherent_data()
            .expect("Could not create the timestamp inherent data");
        inherent_data.check_extrinsics(block)
    }
}
cumulus_pallet_parachain_system::register_validate_block! {
    Runtime = Runtime,
    CheckInherents = CheckInherents,
    BlockExecutor = pallet_author_inherent::BlockExecutor::<Runtime, Executive>,
}
#[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
    }
}