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, DecodeWithMemTracking, 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::Version as XcmVersion,
100
    xcm::{IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm},
101
    xcm_runtime_apis::{
102
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
103
        fees::Error as XcmPaymentApiError,
104
    },
105
};
106
pub use {
107
    sp_consensus_aura::sr25519::AuthorityId as AuraId,
108
    sp_runtime::{MultiAddress, Perbill, Permill},
109
};
110

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

            
114
pub type Precompiles = TemplatePrecompiles<Runtime>;
115

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
330
mod impl_on_charge_evm_transaction;
331

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

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

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

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

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

            
365
pub const EXISTENTIAL_DEPOSIT: Balance = 0;
366

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
567
impl parachain_info::Config for Runtime {}
568

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

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

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

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

            
616
impl Default for ProxyType {
617
    fn default() -> Self {
618
        Self::Any
619
    }
620
}
621

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

            
650
impl InstanceFilter<RuntimeCall> for ProxyType {
651
    fn filter(&self, c: &RuntimeCall) -> bool {
652
        // Since proxy filters are respected in all dispatches of the Utility
653
        // pallet, it should never need to be filtered by any proxy.
654
        if let RuntimeCall::Utility(..) = c {
655
            return true;
656
        }
657

            
658
        match self {
659
            ProxyType::Any => true,
660
            ProxyType::NonTransfer => {
661
                matches!(
662
                    c,
663
                    RuntimeCall::System(..)
664
                        | RuntimeCall::ParachainSystem(..)
665
                        | RuntimeCall::Timestamp(..)
666
                        | RuntimeCall::Proxy(..)
667
                )
668
            }
669
            // We don't have governance yet
670
            ProxyType::Governance => false,
671
            ProxyType::CancelProxy => matches!(
672
                c,
673
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
674
            ),
675
            ProxyType::Balances => {
676
                matches!(c, RuntimeCall::Balances(..))
677
            }
678
        }
679
    }
680

            
681
    fn is_superset(&self, o: &Self) -> bool {
682
        match (self, o) {
683
            (x, y) if x == y => true,
684
            (ProxyType::Any, _) => true,
685
            (_, ProxyType::Any) => false,
686
            _ => false,
687
        }
688
    }
689
}
690

            
691
impl pallet_proxy::Config for Runtime {
692
    type RuntimeEvent = RuntimeEvent;
693
    type RuntimeCall = RuntimeCall;
694
    type Currency = Balances;
695
    type ProxyType = ProxyType;
696
    // One storage item; key size 32, value size 8
697
    type ProxyDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
698
    // Additional storage item size of 21 bytes (20 bytes AccountId + 1 byte sizeof(ProxyType)).
699
    type ProxyDepositFactor = ConstU128<{ currency::deposit(0, 21) }>;
700
    type MaxProxies = ConstU32<32>;
701
    type MaxPending = ConstU32<32>;
702
    type CallHasher = BlakeTwo256;
703
    type AnnouncementDepositBase = ConstU128<{ currency::deposit(1, 8) }>;
704
    // Additional storage item size of 56 bytes:
705
    // - 20 bytes AccountId
706
    // - 32 bytes Hasher (Blake2256)
707
    // - 4 bytes BlockNumber (u32)
708
    type AnnouncementDepositFactor = ConstU128<{ currency::deposit(0, 56) }>;
709
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
710
    type BlockNumberProvider = System;
711
}
712

            
713
pub struct XcmExecutionManager;
714
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
715
    fn suspend_xcm_execution() -> DispatchResult {
716
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
717
    }
718
    fn resume_xcm_execution() -> DispatchResult {
719
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
720
    }
721
}
722

            
723
impl cumulus_pallet_weight_reclaim::Config for Runtime {
724
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
725
}
726

            
727
impl pallet_migrations::Config for Runtime {
728
    type RuntimeEvent = RuntimeEvent;
729
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
730
    type XcmExecutionManager = XcmExecutionManager;
731
}
732

            
733
parameter_types! {
734
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
735
}
736

            
737
impl pallet_multiblock_migrations::Config for Runtime {
738
    type RuntimeEvent = RuntimeEvent;
739
    #[cfg(not(feature = "runtime-benchmarks"))]
740
    type Migrations = ();
741
    // Benchmarks need mocked migrations to guarantee that they succeed.
742
    #[cfg(feature = "runtime-benchmarks")]
743
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
744
    type CursorMaxLen = ConstU32<65_536>;
745
    type IdentifierMaxLen = ConstU32<256>;
746
    type MigrationStatusHandler = ();
747
    type FailedMigrationHandler = MaintenanceMode;
748
    type MaxServiceWeight = MbmServiceWeight;
749
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
750
}
751

            
752
/// Maintenance mode Call filter
753
pub struct MaintenanceFilter;
754
impl Contains<RuntimeCall> for MaintenanceFilter {
755
    fn contains(c: &RuntimeCall) -> bool {
756
        !matches!(
757
            c,
758
            RuntimeCall::Balances(_)
759
                | RuntimeCall::Ethereum(_)
760
                | RuntimeCall::EVM(_)
761
                | RuntimeCall::PolkadotXcm(_)
762
        )
763
    }
764
}
765

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

            
786
impl pallet_maintenance_mode::Config for Runtime {
787
    type RuntimeEvent = RuntimeEvent;
788
    type NormalCallFilter = NormalFilter;
789
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
790
    type MaintenanceOrigin = EnsureRoot<AccountId>;
791
    type XcmExecutionManager = XcmExecutionManager;
792
}
793

            
794
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
795
pub mod dynamic_params {
796
    use super::*;
797

            
798
    #[dynamic_pallet_params]
799
    #[codec(index = 3)]
800
    pub mod contract_deploy_filter {
801
        #[codec(index = 0)]
802
        pub static AllowedAddressesToCreate: DeployFilter = DeployFilter::All;
803
        #[codec(index = 1)]
804
        pub static AllowedAddressesToCreateInner: DeployFilter = DeployFilter::All;
805
    }
806
}
807

            
808
impl pallet_parameters::Config for Runtime {
809
    type AdminOrigin = EnsureRoot<AccountId>;
810
    type RuntimeEvent = RuntimeEvent;
811
    type RuntimeParameters = RuntimeParameters;
812
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
813
}
814

            
815
#[cfg(feature = "runtime-benchmarks")]
816
impl Default for RuntimeParameters {
817
    fn default() -> Self {
818
        RuntimeParameters::ContractDeployFilter(
819
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
820
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
821
                Some(DeployFilter::All),
822
            ),
823
        )
824
    }
825
}
826

            
827
#[derive(
828
    Clone, PartialEq, Encode, Decode, DecodeWithMemTracking, TypeInfo, Eq, MaxEncodedLen, Debug,
829
)]
830
pub enum DeployFilter {
831
    All,
832
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
833
}
834

            
835
pub struct AddressFilter<Runtime, AddressList>(sp_std::marker::PhantomData<(Runtime, AddressList)>);
836
impl<Runtime, AddressList> EnsureCreateOrigin<Runtime> for AddressFilter<Runtime, AddressList>
837
where
838
    Runtime: pallet_evm::Config,
839
    AddressList: Get<DeployFilter>,
840
{
841
    fn check_create_origin(address: &H160) -> Result<(), pallet_evm::Error<Runtime>> {
842
        let deploy_filter: DeployFilter = AddressList::get();
843

            
844
        match deploy_filter {
845
            DeployFilter::All => Ok(()),
846
            DeployFilter::Whitelisted(addresses_vec) => {
847
                if !addresses_vec.contains(address) {
848
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
849
                } else {
850
                    Ok(())
851
                }
852
            }
853
        }
854
    }
855
}
856

            
857
impl pallet_evm_chain_id::Config for Runtime {}
858

            
859
pub struct FindAuthorAdapter;
860
impl FindAuthor<H160> for FindAuthorAdapter {
861
1219
    fn find_author<'a, I>(digests: I) -> Option<H160>
862
1219
    where
863
1219
        I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
864
1219
    {
865
1219
        if let Some(author) = AuthorInherent::find_author(digests) {
866
            return Some(H160::from_slice(&author.encode()[0..20]));
867
1219
        }
868
1219
        None
869
1219
    }
870
}
871

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

            
878
/// Approximate ratio of the amount of Weight per Gas.
879
/// u64 works for approximations because Weight is a very small unit compared to gas.
880
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
881

            
882
parameter_types! {
883
    pub BlockGasLimit: U256
884
        = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
885
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
886
    pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
887
    pub SuicideQuickClearLimit: u32 = 0;
888
    pub GasLimitPovSizeRatio: u32 = 16;
889
    /// Hardcoding the value, since it is computed on block execution. Check calculations in the tests
890
    pub GasLimitStorageGrowthRatio: u64 = 1464;
891
}
892

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

            
925
parameter_types! {
926
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
927
}
928

            
929
impl pallet_ethereum::Config for Runtime {
930
    type RuntimeEvent = RuntimeEvent;
931
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
932
    type PostLogContent = PostBlockAndTxnHashes;
933
    type ExtraDataLength = ConstU32<30>;
934
}
935

            
936
parameter_types! {
937
    pub BoundDivision: U256 = U256::from(1024);
938
}
939

            
940
parameter_types! {
941
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
942
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
943
}
944

            
945
pub struct BaseFeeThreshold;
946
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
947
726
    fn lower() -> Permill {
948
726
        Permill::zero()
949
726
    }
950
1452
    fn ideal() -> Permill {
951
1452
        Permill::from_parts(500_000)
952
1452
    }
953
726
    fn upper() -> Permill {
954
726
        Permill::from_parts(1_000_000)
955
726
    }
956
}
957

            
958
impl pallet_base_fee::Config for Runtime {
959
    type RuntimeEvent = RuntimeEvent;
960
    type Threshold = BaseFeeThreshold;
961
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
962
    type DefaultElasticity = DefaultElasticity;
963
}
964

            
965
impl pallet_root_testing::Config for Runtime {
966
    type RuntimeEvent = RuntimeEvent;
967
}
968

            
969
impl pallet_tx_pause::Config for Runtime {
970
    type RuntimeEvent = RuntimeEvent;
971
    type RuntimeCall = RuntimeCall;
972
    type PauseOrigin = EnsureRoot<AccountId>;
973
    type UnpauseOrigin = EnsureRoot<AccountId>;
974
    type WhitelistedCalls = ();
975
    type MaxNameLen = ConstU32<256>;
976
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
977
}
978

            
979
impl dp_impl_tanssi_pallets_config::Config for Runtime {
980
    const SLOT_DURATION: u64 = SLOT_DURATION;
981
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
982
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
983
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
984
}
985

            
986
parameter_types! {
987
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
988
    pub const DepositBase: Balance = currency::deposit(1, 96);
989
    // Additional storage item size of 20 bytes.
990
    pub const DepositFactor: Balance = currency::deposit(0, 20);
991
    pub const MaxSignatories: u32 = 100;
992
}
993

            
994
impl pallet_multisig::Config for Runtime {
995
    type RuntimeEvent = RuntimeEvent;
996
    type RuntimeCall = RuntimeCall;
997
    type Currency = Balances;
998
    type DepositBase = DepositBase;
999
    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.
16701
construct_runtime!(
16701
    pub enum Runtime
16701
    {
16701
        // System support stuff.
16701
        System: frame_system = 0,
16701
        ParachainSystem: cumulus_pallet_parachain_system = 1,
16701
        Timestamp: pallet_timestamp = 2,
16701
        ParachainInfo: parachain_info = 3,
16701
        Sudo: pallet_sudo = 4,
16701
        Utility: pallet_utility = 5,
16701
        Proxy: pallet_proxy = 6,
16701
        Migrations: pallet_migrations = 7,
16701
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
16701
        MaintenanceMode: pallet_maintenance_mode = 8,
16701
        TxPause: pallet_tx_pause = 9,
16701

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

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

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

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

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

            
16701
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
16701

            
16701
        RootTesting: pallet_root_testing = 100,
16701
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
16701
    }
16701
);
#[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]
    );
}
24630
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.0.7;
                            charge_transaction.tip()
24630
                        }
24630
                    };
24630

            
24630
                    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
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::{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
        #[allow(non_local_definitions)]
24630
        fn dispatch_benchmark(
24630
            config: frame_benchmarking::BenchmarkConfig,
24630
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
24630
            use frame_benchmarking::{BenchmarkBatch, 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;
            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())
        }
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 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())
        }
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_xcms_version: XcmVersion) -> Result<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call, result_xcms_version)
        }
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
    }
39874
}
#[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
    }
}