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

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

            
112
pub type Precompiles = TemplatePrecompiles<Runtime>;
113

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
323
mod impl_on_charge_evm_transaction;
324

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
562
impl parachain_info::Config for Runtime {}
563

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
815
impl pallet_evm_chain_id::Config for Runtime {}
816

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

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

            
836
/// Approximate ratio of the amount of Weight per Gas.
837
/// u64 works for approximations because Weight is a very small unit compared to gas.
838
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
839

            
840
parameter_types! {
841
    pub BlockGasLimit: U256
842
        = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
843
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
844
    pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
845
    pub SuicideQuickClearLimit: u32 = 0;
846
    pub GasLimitPovSizeRatio: u32 = 16;
847
}
848

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

            
880
parameter_types! {
881
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
882
}
883

            
884
impl pallet_ethereum::Config for Runtime {
885
    type RuntimeEvent = RuntimeEvent;
886
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self>;
887
    type PostLogContent = PostBlockAndTxnHashes;
888
    type ExtraDataLength = ConstU32<30>;
889
}
890

            
891
parameter_types! {
892
    pub BoundDivision: U256 = U256::from(1024);
893
}
894

            
895
parameter_types! {
896
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
897
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
898
}
899

            
900
pub struct BaseFeeThreshold;
901
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
902
    fn lower() -> Permill {
903
        Permill::zero()
904
    }
905
    fn ideal() -> Permill {
906
        Permill::from_parts(500_000)
907
    }
908
    fn upper() -> Permill {
909
        Permill::from_parts(1_000_000)
910
    }
911
}
912

            
913
impl pallet_base_fee::Config for Runtime {
914
    type RuntimeEvent = RuntimeEvent;
915
    type Threshold = BaseFeeThreshold;
916
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
917
    type DefaultElasticity = DefaultElasticity;
918
}
919

            
920
impl pallet_root_testing::Config for Runtime {
921
    type RuntimeEvent = RuntimeEvent;
922
}
923

            
924
impl pallet_tx_pause::Config for Runtime {
925
    type RuntimeEvent = RuntimeEvent;
926
    type RuntimeCall = RuntimeCall;
927
    type PauseOrigin = EnsureRoot<AccountId>;
928
    type UnpauseOrigin = EnsureRoot<AccountId>;
929
    type WhitelistedCalls = ();
930
    type MaxNameLen = ConstU32<256>;
931
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
932
}
933

            
934
impl dp_impl_tanssi_pallets_config::Config for Runtime {
935
    const SLOT_DURATION: u64 = SLOT_DURATION;
936
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
937
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
938
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
939
}
940

            
941
parameter_types! {
942
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
943
    pub const DepositBase: Balance = currency::deposit(1, 96);
944
    // Additional storage item size of 20 bytes.
945
    pub const DepositFactor: Balance = currency::deposit(0, 20);
946
    pub const MaxSignatories: u32 = 100;
947
}
948

            
949
impl pallet_multisig::Config for Runtime {
950
    type RuntimeEvent = RuntimeEvent;
951
    type RuntimeCall = RuntimeCall;
952
    type Currency = Balances;
953
    type DepositBase = DepositBase;
954
    type DepositFactor = DepositFactor;
955
    type MaxSignatories = MaxSignatories;
956
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
957
}
958

            
959
impl_tanssi_pallets_config!(Runtime);
960

            
961
// Create the runtime by composing the FRAME pallets that were previously configured.
962
20458
construct_runtime!(
963
1837
    pub enum Runtime
964
1837
    {
965
1837
        // System support stuff.
966
1837
        System: frame_system = 0,
967
1837
        ParachainSystem: cumulus_pallet_parachain_system = 1,
968
1837
        Timestamp: pallet_timestamp = 2,
969
1837
        ParachainInfo: parachain_info = 3,
970
1837
        Sudo: pallet_sudo = 4,
971
1837
        Utility: pallet_utility = 5,
972
1837
        Proxy: pallet_proxy = 6,
973
1837
        Migrations: pallet_migrations = 7,
974
1837
        MaintenanceMode: pallet_maintenance_mode = 8,
975
1837
        TxPause: pallet_tx_pause = 9,
976
1837

            
977
1837
        // Monetary stuff.
978
1837
        Balances: pallet_balances = 10,
979
1837

            
980
1837
        // Other utilities
981
1837
        Multisig: pallet_multisig = 16,
982
1837
        Parameters: pallet_parameters = 17,
983
1837

            
984
1837
        // ContainerChain
985
1837
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
986
1837
        AuthorInherent: pallet_author_inherent = 51,
987
1837

            
988
1837
        // Frontier
989
1837
        Ethereum: pallet_ethereum = 60,
990
1837
        EVM: pallet_evm = 61,
991
1837
        EVMChainId: pallet_evm_chain_id = 62,
992
1837
        BaseFee: pallet_base_fee = 64,
993
1837
        TransactionPayment: pallet_transaction_payment = 66,
994
1837

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
10590
            let dispatch_info = xt.get_dispatch_info();
10590

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
10590
            add_benchmarks!(params, batches);
10590

            
10590
            Ok(batches)
10590
        }
10590
    }
10590

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

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

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

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

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

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

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

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

            
10590
        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;
            // Estimated encoded transaction size must be based on the heaviest transaction
            // type (EIP1559Transaction) to be compatible with all transaction types.
            let mut estimated_transaction_len = data.len() +
                // pallet ethereum index: 1
                // transact call index: 1
                // Transaction enum variant: 1
                // chain_id 8 bytes
                // nonce: 32
                // max_priority_fee_per_gas: 32
                // max_fee_per_gas: 32
                // gas_limit: 32
                // action: 21 (enum varianrt + call address)
                // value: 32
                // access_list: 1 (empty vec size)
                // 65 bytes signature
                258;
            if access_list.is_some() {
                estimated_transaction_len += access_list.encoded_size();
            }
10590
            let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
            let without_base_extrinsic_weight = true;
10590
            let (weight_limit, proof_size_base_cost) =
10590
                match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
                    gas_limit,
                    without_base_extrinsic_weight
                ) {
10590
                    weight_limit if weight_limit.proof_size() > 0 => {
10590
                        (Some(weight_limit), Some(estimated_transaction_len as u64))
10590
                    }
10590
                    _ => (None, None),
10590
                };
10590

            
10590
            <Runtime as pallet_evm::Config>::Runner::call(
                from,
                to,
                data,
                value,
                gas_limit,
                max_fee_per_gas,
                max_priority_fee_per_gas,
                nonce,
                access_list.unwrap_or_default(),
                is_transactional,
                validate,
                weight_limit,
                proof_size_base_cost,
                <Runtime as pallet_evm::Config>::config(),
            ).map_err(|err| err.error.into())
        }
10590

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

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

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

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

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

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

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

            
10590
        fn gas_limit_multiplier_support() {}
10590

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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