1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
#![cfg_attr(not(feature = "std"), no_std)]
18
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
19
#![recursion_limit = "256"]
20

            
21
// Make the WASM binary available.
22
#[cfg(feature = "std")]
23
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
24

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

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

            
32
pub mod migrations;
33
mod precompiles;
34
pub mod weights;
35
pub mod xcm_config;
36

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

            
107
// Polkadot imports
108
use polkadot_runtime_common::BlockHashCount;
109

            
110
pub type Precompiles = TemplatePrecompiles<Runtime>;
111

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

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

            
119
/// Balance of an account.
120
pub type Balance = u128;
121

            
122
/// Index of a transaction in the chain.
123
pub type Index = u32;
124

            
125
/// A hash of some data used by the chain.
126
pub type Hash = sp_core::H256;
127

            
128
/// An index to a block.
129
pub type BlockNumber = u32;
130

            
131
/// The address format for describing accounts.
132
pub type Address = AccountId;
133

            
134
/// Block header type as expected by this runtime.
135
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
136

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

            
140
/// A Block signed with a Justification
141
pub type SignedBlock = generic::SignedBlock<Block>;
142

            
143
/// BlockId type as expected by this runtime.
144
pub type BlockId = generic::BlockId<Block>;
145

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

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

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

            
177
pub mod currency {
178
    use super::Balance;
179

            
180
    pub const MICROUNIT: Balance = 1_000_000_000_000;
181
    pub const MILLIUNIT: Balance = 1_000_000_000_000_000;
182
    pub const UNIT: Balance = 1_000_000_000_000_000_000;
183
    pub const KILOUNIT: Balance = 1_000_000_000_000_000_000_000;
184

            
185
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
186

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

            
192
impl fp_self_contained::SelfContainedCall for RuntimeCall {
193
    type SignedInfo = H160;
194

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

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

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

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

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

            
250
#[derive(Clone)]
251
pub struct TransactionConverter;
252

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

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

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

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

            
312
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
313
    /// Opaque block header type.
314
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
315
    /// Opaque block type.
316
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
317
    /// Opaque block identifier type.
318
    pub type BlockId = generic::BlockId<Block>;
319
}
320

            
321
mod impl_on_charge_evm_transaction;
322

            
323
impl_opaque_keys! {
324
    pub struct SessionKeys { }
325
}
326

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

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

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

            
351
// Time is measured by number of blocks.
352
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
353
pub const HOURS: BlockNumber = MINUTES * 60;
354
pub const DAYS: BlockNumber = HOURS * 24;
355

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

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

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

            
372
/// We allow for 0.5 of a second of compute with a 12 second average block time.
373
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
374
    WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
375
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
376
);
377

            
378
/// We allow for 500ms of compute with a 12 second average block time.
379
pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 500;
380

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

            
390
parameter_types! {
391
    pub const Version: RuntimeVersion = VERSION;
392

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

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

            
475
parameter_types! {
476
    pub const TransactionByteFee: Balance = 1;
477
}
478

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

            
489
parameter_types! {
490
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
491
}
492

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

            
511
parameter_types! {
512
    pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
513
    pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
514
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
515
}
516

            
517
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
518
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
519
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
520

            
521
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
522
    Runtime,
523
    BLOCK_PROCESSING_VELOCITY,
524
    UNINCLUDED_SEGMENT_CAPACITY,
525
>;
526

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

            
541
pub struct ParaSlotProvider;
542
impl Get<(Slot, SlotDuration)> for ParaSlotProvider {
543
104
    fn get() -> (Slot, SlotDuration) {
544
104
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
545
104
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
546
104
    }
547
}
548

            
549
parameter_types! {
550
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
551
}
552

            
553
impl pallet_async_backing::Config for Runtime {
554
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
555
    type GetAndVerifySlot =
556
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
557
    type ExpectedBlockTime = ExpectedBlockTime;
558
}
559

            
560
impl parachain_info::Config for Runtime {}
561

            
562
parameter_types! {
563
    pub const Period: u32 = 6 * HOURS;
564
    pub const Offset: u32 = 0;
565
}
566

            
567
impl pallet_sudo::Config for Runtime {
568
    type RuntimeCall = RuntimeCall;
569
    type RuntimeEvent = RuntimeEvent;
570
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
571
}
572

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

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

            
599
impl Default for ProxyType {
600
    fn default() -> Self {
601
        Self::Any
602
    }
603
}
604

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

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

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

            
664
    fn is_superset(&self, o: &Self) -> bool {
665
        match (self, o) {
666
            (x, y) if x == y => true,
667
            (ProxyType::Any, _) => true,
668
            (_, ProxyType::Any) => false,
669
            _ => false,
670
        }
671
    }
672
}
673

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

            
695
pub struct XcmExecutionManager;
696
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
697
    fn suspend_xcm_execution() -> DispatchResult {
698
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
699
    }
700
    fn resume_xcm_execution() -> DispatchResult {
701
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
702
    }
703
}
704

            
705
impl pallet_migrations::Config for Runtime {
706
    type RuntimeEvent = RuntimeEvent;
707
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
708
    type XcmExecutionManager = XcmExecutionManager;
709
}
710

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

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

            
745
impl pallet_maintenance_mode::Config for Runtime {
746
    type RuntimeEvent = RuntimeEvent;
747
    type NormalCallFilter = NormalFilter;
748
    type MaintenanceCallFilter = MaintenanceFilter;
749
    type MaintenanceOrigin = EnsureRoot<AccountId>;
750
    type XcmExecutionManager = XcmExecutionManager;
751
}
752

            
753
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
754
pub mod dynamic_params {
755
    use super::*;
756

            
757
    #[dynamic_pallet_params]
758
    #[codec(index = 3)]
759
    pub mod contract_deploy_filter {
760
        #[codec(index = 0)]
761
        pub static AllowedAddressesToCreate: DeployFilter = DeployFilter::All;
762
        #[codec(index = 1)]
763
        pub static AllowedAddressesToCreateInner: DeployFilter = DeployFilter::All;
764
    }
765
}
766

            
767
impl pallet_parameters::Config for Runtime {
768
    type AdminOrigin = EnsureRoot<AccountId>;
769
    type RuntimeEvent = RuntimeEvent;
770
    type RuntimeParameters = RuntimeParameters;
771
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
772
}
773

            
774
#[cfg(feature = "runtime-benchmarks")]
775
impl Default for RuntimeParameters {
776
    fn default() -> Self {
777
        RuntimeParameters::ContractDeployFilter(
778
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
779
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
780
                Some(DeployFilter::All),
781
            ),
782
        )
783
    }
784
}
785

            
786
#[derive(Clone, PartialEq, Encode, Decode, TypeInfo, Eq, MaxEncodedLen, Debug)]
787
pub enum DeployFilter {
788
    All,
789
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
790
}
791

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

            
801
        match deploy_filter {
802
            DeployFilter::All => Ok(()),
803
            DeployFilter::Whitelisted(addresses_vec) => {
804
                if !addresses_vec.contains(address) {
805
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
806
                } else {
807
                    Ok(())
808
                }
809
            }
810
        }
811
    }
812
}
813

            
814
// To match ethereum expectations
815
const BLOCK_GAS_LIMIT: u64 = 15_000_000;
816

            
817
impl pallet_evm_chain_id::Config for Runtime {}
818

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

            
832
parameter_types! {
833
    pub BlockGasLimit: U256 = U256::from(BLOCK_GAS_LIMIT);
834
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
835
    pub WeightPerGas: Weight = Weight::from_parts(weight_per_gas(BLOCK_GAS_LIMIT, NORMAL_DISPATCH_RATIO, WEIGHT_MILLISECS_PER_BLOCK), 0);
836
    pub SuicideQuickClearLimit: u32 = 0;
837
}
838

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

            
871
parameter_types! {
872
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
873
}
874

            
875
impl pallet_ethereum::Config for Runtime {
876
    type RuntimeEvent = RuntimeEvent;
877
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
878
    type PostLogContent = PostBlockAndTxnHashes;
879
    type ExtraDataLength = ConstU32<30>;
880
}
881

            
882
parameter_types! {
883
    pub BoundDivision: U256 = U256::from(1024);
884
}
885

            
886
parameter_types! {
887
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
888
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
889
}
890

            
891
pub struct BaseFeeThreshold;
892
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
893
    fn lower() -> Permill {
894
        Permill::zero()
895
    }
896
    fn ideal() -> Permill {
897
        Permill::from_parts(500_000)
898
    }
899
    fn upper() -> Permill {
900
        Permill::from_parts(1_000_000)
901
    }
902
}
903

            
904
impl pallet_base_fee::Config for Runtime {
905
    type RuntimeEvent = RuntimeEvent;
906
    type Threshold = BaseFeeThreshold;
907
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
908
    type DefaultElasticity = DefaultElasticity;
909
}
910

            
911
impl pallet_root_testing::Config for Runtime {
912
    type RuntimeEvent = RuntimeEvent;
913
}
914

            
915
impl pallet_tx_pause::Config for Runtime {
916
    type RuntimeEvent = RuntimeEvent;
917
    type RuntimeCall = RuntimeCall;
918
    type PauseOrigin = EnsureRoot<AccountId>;
919
    type UnpauseOrigin = EnsureRoot<AccountId>;
920
    type WhitelistedCalls = ();
921
    type MaxNameLen = ConstU32<256>;
922
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
923
}
924

            
925
impl dp_impl_tanssi_pallets_config::Config for Runtime {
926
    const SLOT_DURATION: u64 = SLOT_DURATION;
927
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
928
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
929
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
930
}
931

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

            
940
impl pallet_multisig::Config for Runtime {
941
    type RuntimeEvent = RuntimeEvent;
942
    type RuntimeCall = RuntimeCall;
943
    type Currency = Balances;
944
    type DepositBase = DepositBase;
945
    type DepositFactor = DepositFactor;
946
    type MaxSignatories = MaxSignatories;
947
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
948
}
949

            
950
impl_tanssi_pallets_config!(Runtime);
951

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

            
968
1908
        // Monetary stuff.
969
1908
        Balances: pallet_balances = 10,
970
1908

            
971
1908
        // Other utilities
972
1908
        Multisig: pallet_multisig = 16,
973
1908
        Parameters: pallet_parameters = 17,
974
1908

            
975
1908
        // ContainerChain
976
1908
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
977
1908
        AuthorInherent: pallet_author_inherent = 51,
978
1908

            
979
1908
        // Frontier
980
1908
        Ethereum: pallet_ethereum = 60,
981
1908
        EVM: pallet_evm = 61,
982
1908
        EVMChainId: pallet_evm_chain_id = 62,
983
1908
        BaseFee: pallet_base_fee = 64,
984
1908
        TransactionPayment: pallet_transaction_payment = 66,
985
1908

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
9054
            let dispatch_info = xt.get_dispatch_info();
9054

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
9054
            add_benchmarks!(params, batches);
9054

            
9054
            Ok(batches)
9054
        }
9054
    }
9054

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
9054
        fn gas_limit_multiplier_support() {}
9054

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

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

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

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

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

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

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

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

            
9054
    impl xcm_fee_payment_runtime_api::XcmPaymentApi<Block> for Runtime {
9054
        fn query_acceptable_payment_assets(xcm_version: staging_xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
9054
            if !matches!(xcm_version, 3 | 4) {
9054
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
9054
            }
            Ok([VersionedAssetId::V4(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::V4(location.into())
                        }).or_else(|| {
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
9054
                            None
                        })
                    })
                )
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
9054
                }).ok())
                .collect())
9054
        }
9054

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

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

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

            
9054
        fn query_delivery_fees(destination: VersionedLocation, message: VersionedXcm<()>) -> Result<VersionedAssets, XcmPaymentApiError> {
            PolkadotXcm::query_delivery_fees(destination, message)
        }
9054
    }
16610
}
#[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>,
}