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_runtime_apis::{
101
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
102
        fees::Error as XcmPaymentApiError,
103
    },
104
};
105
pub use {
106
    sp_consensus_aura::sr25519::AuthorityId as AuraId,
107
    sp_runtime::{MultiAddress, Perbill, Permill},
108
};
109

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

            
113
pub type Precompiles = TemplatePrecompiles<Runtime>;
114

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
324
mod impl_on_charge_evm_transaction;
325

            
326
impl_opaque_keys! {
327
    pub struct SessionKeys { }
328
}
329

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

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

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

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

            
359
/// The existential deposit. Set to 0 because this is an ethereum-like chain
360
/// We set this to one for runtime-benchmarks because plenty of the benches we
361
/// incorporate from parity assume ED != 0
362
#[cfg(feature = "runtime-benchmarks")]
363
pub const EXISTENTIAL_DEPOSIT: Balance = 1 * currency::MILLIUNIT;
364
#[cfg(not(feature = "runtime-benchmarks"))]
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 0.5 of a second of compute with a 12 second average block time.
376
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
377
    WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
378
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
379
);
380

            
381
/// We allow for 500ms of compute with a 12 second average block time.
382
pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 500;
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
18
        .for_class(DispatchClass::all(), |weights| {
405
18
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
406
18
        })
407
6
        .for_class(DispatchClass::Normal, |weights| {
408
6
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
409
6
        })
410
6
        .for_class(DispatchClass::Operational, |weights| {
411
6
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
412
6
            // Operational transactions have some extra reserved space, so that they
413
6
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
414
6
            weights.reserved = Some(
415
6
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
416
6
            );
417
6
        })
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 = ();
473
    type PreInherents = ();
474
    type PostInherents = ();
475
    type PostTransactions = ();
476
}
477

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

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

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

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

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

            
520
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
521
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
522
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
523

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

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

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

            
552
parameter_types! {
553
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
554
}
555

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

            
563
impl parachain_info::Config for Runtime {}
564

            
565
parameter_types! {
566
    pub const Period: u32 = 6 * HOURS;
567
    pub const Offset: u32 = 0;
568
}
569

            
570
impl pallet_sudo::Config for Runtime {
571
    type RuntimeCall = RuntimeCall;
572
    type RuntimeEvent = RuntimeEvent;
573
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
574
}
575

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
816
// To match ethereum expectations
817
const BLOCK_GAS_LIMIT: u64 = 15_000_000;
818

            
819
impl pallet_evm_chain_id::Config for Runtime {}
820

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

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

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

            
873
parameter_types! {
874
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
875
}
876

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

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

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

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

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

            
913
impl pallet_root_testing::Config for Runtime {
914
    type RuntimeEvent = RuntimeEvent;
915
}
916

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

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

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

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

            
952
impl_tanssi_pallets_config!(Runtime);
953

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

            
970
2148
        // Monetary stuff.
971
2148
        Balances: pallet_balances = 10,
972
2148

            
973
2148
        // Other utilities
974
2148
        Multisig: pallet_multisig = 16,
975
2148
        Parameters: pallet_parameters = 17,
976
2148

            
977
2148
        // ContainerChain
978
2148
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
979
2148
        AuthorInherent: pallet_author_inherent = 51,
980
2148

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
9058
            let dispatch_info = xt.get_dispatch_info();
9058

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
9058
            add_benchmarks!(params, batches);
9058

            
9058
            Ok(batches)
9058
        }
9058
    }
9058

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

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

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

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

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

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

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

            
9058
        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[..]))
        }
9058

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

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

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

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

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

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

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

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

            
9058
        fn gas_limit_multiplier_support() {}
9058

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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