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
            fungible::{Balanced, Credit, Inspect},
52
            tokens::ConversionToAssetBalance,
53
            ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Contains, FindAuthor, InsideBoth,
54
            InstanceFilter, 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, EVMFungibleAdapter, EnsureAddressNever, EnsureAddressRoot,
73
        EnsureCreateOrigin, FeeCalculator, FrameSystemAccountProvider, GasWeightMapping,
74
        IdentityAddressMapping, 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
45
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
292
45
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
293
45
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
294
45
        let p = currency::MILLIUNIT / 10;
295
45
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
296
45
        smallvec![WeightToFeeCoefficient {
297
            degree: 1,
298
            negative: false,
299
            coeff_frac: Perbill::from_rational(p % q, q),
300
            coeff_integer: p / q,
301
        }]
302
45
    }
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: 1200,
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
pub const EXISTENTIAL_DEPOSIT: Balance = 0;
360

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

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

            
369
/// We allow for 2 seconds of compute with a 6 second average block time
370
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
371
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
372
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
373
);
374

            
375
/// We allow for 2 seconds of compute with a 6 second average block time
376
pub const WEIGHT_MILLISECS_PER_BLOCK: u64 = 2000;
377

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

            
387
parameter_types! {
388
    pub const Version: RuntimeVersion = VERSION;
389

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

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

            
472
parameter_types! {
473
    pub const TransactionByteFee: Balance = 1;
474
}
475

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

            
486
parameter_types! {
487
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
488
}
489

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

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

            
514
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
515
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
516
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
517

            
518
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
519
    Runtime,
520
    BLOCK_PROCESSING_VELOCITY,
521
    UNINCLUDED_SEGMENT_CAPACITY,
522
>;
523

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

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

            
546
parameter_types! {
547
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
548
}
549

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

            
557
impl parachain_info::Config for Runtime {}
558

            
559
parameter_types! {
560
    pub const Period: u32 = 6 * HOURS;
561
    pub const Offset: u32 = 0;
562
}
563

            
564
impl pallet_sudo::Config for Runtime {
565
    type RuntimeCall = RuntimeCall;
566
    type RuntimeEvent = RuntimeEvent;
567
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
568
}
569

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

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

            
595
impl Default for ProxyType {
596
    fn default() -> Self {
597
        Self::Any
598
    }
599
}
600

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

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

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

            
660
    fn is_superset(&self, o: &Self) -> bool {
661
        match (self, o) {
662
            (x, y) if x == y => true,
663
            (ProxyType::Any, _) => true,
664
            (_, ProxyType::Any) => false,
665
            _ => false,
666
        }
667
    }
668
}
669

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

            
691
pub struct XcmExecutionManager;
692
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
693
    fn suspend_xcm_execution() -> DispatchResult {
694
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
695
    }
696
    fn resume_xcm_execution() -> DispatchResult {
697
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
698
    }
699
}
700

            
701
impl pallet_migrations::Config for Runtime {
702
    type RuntimeEvent = RuntimeEvent;
703
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
704
    type XcmExecutionManager = XcmExecutionManager;
705
}
706

            
707
parameter_types! {
708
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
709
}
710

            
711
impl pallet_multiblock_migrations::Config for Runtime {
712
    type RuntimeEvent = RuntimeEvent;
713
    #[cfg(not(feature = "runtime-benchmarks"))]
714
    type Migrations = ();
715
    // Benchmarks need mocked migrations to guarantee that they succeed.
716
    #[cfg(feature = "runtime-benchmarks")]
717
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
718
    type CursorMaxLen = ConstU32<65_536>;
719
    type IdentifierMaxLen = ConstU32<256>;
720
    type MigrationStatusHandler = ();
721
    type FailedMigrationHandler = frame_support::migrations::FreezeChainOnFailedMigration;
722
    type MaxServiceWeight = MbmServiceWeight;
723
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
724
}
725

            
726
/// Maintenance mode Call filter
727
pub struct MaintenanceFilter;
728
impl Contains<RuntimeCall> for MaintenanceFilter {
729
    fn contains(c: &RuntimeCall) -> bool {
730
        !matches!(
731
            c,
732
            RuntimeCall::Balances(_)
733
                | RuntimeCall::Ethereum(_)
734
                | RuntimeCall::EVM(_)
735
                | RuntimeCall::PolkadotXcm(_)
736
        )
737
    }
738
}
739

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

            
760
impl pallet_maintenance_mode::Config for Runtime {
761
    type RuntimeEvent = RuntimeEvent;
762
    type NormalCallFilter = NormalFilter;
763
    type MaintenanceCallFilter = MaintenanceFilter;
764
    type MaintenanceOrigin = EnsureRoot<AccountId>;
765
    type XcmExecutionManager = XcmExecutionManager;
766
}
767

            
768
#[dynamic_params(RuntimeParameters, pallet_parameters::Parameters::<Runtime>)]
769
pub mod dynamic_params {
770
    use super::*;
771

            
772
    #[dynamic_pallet_params]
773
    #[codec(index = 3)]
774
    pub mod contract_deploy_filter {
775
        #[codec(index = 0)]
776
        pub static AllowedAddressesToCreate: DeployFilter = DeployFilter::All;
777
        #[codec(index = 1)]
778
        pub static AllowedAddressesToCreateInner: DeployFilter = DeployFilter::All;
779
    }
780
}
781

            
782
impl pallet_parameters::Config for Runtime {
783
    type AdminOrigin = EnsureRoot<AccountId>;
784
    type RuntimeEvent = RuntimeEvent;
785
    type RuntimeParameters = RuntimeParameters;
786
    type WeightInfo = weights::pallet_parameters::SubstrateWeight<Runtime>;
787
}
788

            
789
#[cfg(feature = "runtime-benchmarks")]
790
impl Default for RuntimeParameters {
791
    fn default() -> Self {
792
        RuntimeParameters::ContractDeployFilter(
793
            dynamic_params::contract_deploy_filter::Parameters::AllowedAddressesToCreate(
794
                dynamic_params::contract_deploy_filter::AllowedAddressesToCreate,
795
                Some(DeployFilter::All),
796
            ),
797
        )
798
    }
799
}
800

            
801
#[derive(Clone, PartialEq, Encode, Decode, TypeInfo, Eq, MaxEncodedLen, Debug)]
802
pub enum DeployFilter {
803
    All,
804
    Whitelisted(BoundedVec<H160, ConstU32<100>>),
805
}
806

            
807
pub struct AddressFilter<Runtime, AddressList>(sp_std::marker::PhantomData<(Runtime, AddressList)>);
808
impl<Runtime, AddressList> EnsureCreateOrigin<Runtime> for AddressFilter<Runtime, AddressList>
809
where
810
    Runtime: pallet_evm::Config,
811
    AddressList: Get<DeployFilter>,
812
{
813
    fn check_create_origin(address: &H160) -> Result<(), pallet_evm::Error<Runtime>> {
814
        let deploy_filter: DeployFilter = AddressList::get();
815

            
816
        match deploy_filter {
817
            DeployFilter::All => Ok(()),
818
            DeployFilter::Whitelisted(addresses_vec) => {
819
                if !addresses_vec.contains(address) {
820
                    Err(pallet_evm::Error::<Runtime>::CreateOriginNotAllowed)
821
                } else {
822
                    Ok(())
823
                }
824
            }
825
        }
826
    }
827
}
828

            
829
impl pallet_evm_chain_id::Config for Runtime {}
830

            
831
pub struct FindAuthorAdapter;
832
impl FindAuthor<H160> for FindAuthorAdapter {
833
283
    fn find_author<'a, I>(digests: I) -> Option<H160>
834
283
    where
835
283
        I: 'a + IntoIterator<Item = (sp_runtime::ConsensusEngineId, &'a [u8])>,
836
283
    {
837
283
        if let Some(author) = AuthorInherent::find_author(digests) {
838
            return Some(H160::from_slice(&author.encode()[0..20]));
839
283
        }
840
283
        None
841
283
    }
842
}
843

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

            
850
/// Approximate ratio of the amount of Weight per Gas.
851
/// u64 works for approximations because Weight is a very small unit compared to gas.
852
pub const WEIGHT_PER_GAS: u64 = WEIGHT_REF_TIME_PER_SECOND / GAS_PER_SECOND;
853

            
854
parameter_types! {
855
    pub BlockGasLimit: U256
856
        = U256::from(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT.ref_time() / WEIGHT_PER_GAS);
857
    pub PrecompilesValue: TemplatePrecompiles<Runtime> = TemplatePrecompiles::<_>::new();
858
    pub WeightPerGas: Weight = Weight::from_parts(WEIGHT_PER_GAS, 0);
859
    pub SuicideQuickClearLimit: u32 = 0;
860
    pub GasLimitPovSizeRatio: u32 = 16;
861
}
862

            
863
impl_on_charge_evm_transaction!();
864
impl pallet_evm::Config for Runtime {
865
    type AccountProvider = FrameSystemAccountProvider<Runtime>;
866
    type FeeCalculator = BaseFee;
867
    type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
868
    type WeightPerGas = WeightPerGas;
869
    type BlockHashMapping = pallet_ethereum::EthereumBlockHashMapping<Self>;
870
    type CallOrigin = EnsureAddressRoot<AccountId>;
871
    type WithdrawOrigin = EnsureAddressNever<AccountId>;
872
    type AddressMapping = IdentityAddressMapping;
873
    type CreateOrigin =
874
        AddressFilter<Runtime, dynamic_params::contract_deploy_filter::AllowedAddressesToCreate>;
875
    type CreateInnerOrigin = AddressFilter<
876
        Runtime,
877
        dynamic_params::contract_deploy_filter::AllowedAddressesToCreateInner,
878
    >;
879
    type Currency = Balances;
880
    type RuntimeEvent = RuntimeEvent;
881
    type PrecompilesType = TemplatePrecompiles<Self>;
882
    type PrecompilesValue = PrecompilesValue;
883
    type ChainId = EVMChainId;
884
    type BlockGasLimit = BlockGasLimit;
885
    type Runner = pallet_evm::runner::stack::Runner<Self>;
886
    type OnChargeTransaction = OnChargeEVMTransaction<()>;
887
    type OnCreate = ();
888
    type FindAuthor = FindAuthorAdapter;
889
    type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
890
    type SuicideQuickClearLimit = SuicideQuickClearLimit;
891
    type Timestamp = Timestamp;
892
    type WeightInfo = ();
893
}
894

            
895
parameter_types! {
896
    pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
897
}
898

            
899
impl pallet_ethereum::Config for Runtime {
900
    type RuntimeEvent = RuntimeEvent;
901
    type StateRoot = pallet_ethereum::IntermediateStateRoot<Self::Version>;
902
    type PostLogContent = PostBlockAndTxnHashes;
903
    type ExtraDataLength = ConstU32<30>;
904
}
905

            
906
parameter_types! {
907
    pub BoundDivision: U256 = U256::from(1024);
908
}
909

            
910
parameter_types! {
911
    pub DefaultBaseFeePerGas: U256 = U256::from(2_000_000_000);
912
    pub DefaultElasticity: Permill = Permill::from_parts(125_000);
913
}
914

            
915
pub struct BaseFeeThreshold;
916
impl pallet_base_fee::BaseFeeThreshold for BaseFeeThreshold {
917
    fn lower() -> Permill {
918
        Permill::zero()
919
    }
920
    fn ideal() -> Permill {
921
        Permill::from_parts(500_000)
922
    }
923
    fn upper() -> Permill {
924
        Permill::from_parts(1_000_000)
925
    }
926
}
927

            
928
impl pallet_base_fee::Config for Runtime {
929
    type RuntimeEvent = RuntimeEvent;
930
    type Threshold = BaseFeeThreshold;
931
    type DefaultBaseFeePerGas = DefaultBaseFeePerGas;
932
    type DefaultElasticity = DefaultElasticity;
933
}
934

            
935
impl pallet_root_testing::Config for Runtime {
936
    type RuntimeEvent = RuntimeEvent;
937
}
938

            
939
impl pallet_tx_pause::Config for Runtime {
940
    type RuntimeEvent = RuntimeEvent;
941
    type RuntimeCall = RuntimeCall;
942
    type PauseOrigin = EnsureRoot<AccountId>;
943
    type UnpauseOrigin = EnsureRoot<AccountId>;
944
    type WhitelistedCalls = ();
945
    type MaxNameLen = ConstU32<256>;
946
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
947
}
948

            
949
impl dp_impl_tanssi_pallets_config::Config for Runtime {
950
    const SLOT_DURATION: u64 = SLOT_DURATION;
951
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
952
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
953
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
954
}
955

            
956
parameter_types! {
957
    // One storage item; key size 32 + 20; value is size 4+4+16+20. Total = 1 * (52 + 44)
958
    pub const DepositBase: Balance = currency::deposit(1, 96);
959
    // Additional storage item size of 20 bytes.
960
    pub const DepositFactor: Balance = currency::deposit(0, 20);
961
    pub const MaxSignatories: u32 = 100;
962
}
963

            
964
impl pallet_multisig::Config for Runtime {
965
    type RuntimeEvent = RuntimeEvent;
966
    type RuntimeCall = RuntimeCall;
967
    type Currency = Balances;
968
    type DepositBase = DepositBase;
969
    type DepositFactor = DepositFactor;
970
    type MaxSignatories = MaxSignatories;
971
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
972
}
973

            
974
impl_tanssi_pallets_config!(Runtime);
975

            
976
// Create the runtime by composing the FRAME pallets that were previously configured.
977
29686
construct_runtime!(
978
2907
    pub enum Runtime
979
2907
    {
980
2907
        // System support stuff.
981
2907
        System: frame_system = 0,
982
2907
        ParachainSystem: cumulus_pallet_parachain_system = 1,
983
2907
        Timestamp: pallet_timestamp = 2,
984
2907
        ParachainInfo: parachain_info = 3,
985
2907
        Sudo: pallet_sudo = 4,
986
2907
        Utility: pallet_utility = 5,
987
2907
        Proxy: pallet_proxy = 6,
988
2907
        Migrations: pallet_migrations = 7,
989
2907
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
990
2907
        MaintenanceMode: pallet_maintenance_mode = 8,
991
2907
        TxPause: pallet_tx_pause = 9,
992
2907

            
993
2907
        // Monetary stuff.
994
2907
        Balances: pallet_balances = 10,
995
2907

            
996
2907
        // Other utilities
997
2907
        Multisig: pallet_multisig = 16,
998
2907
        Parameters: pallet_parameters = 17,
999
2907

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

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

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

            
2907
        RootTesting: pallet_root_testing = 100,
2907
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
2907
    }
30179
);
#[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_multiblock_migrations, MultiBlockMigrations]
        [pallet_multisig, Multisig]
        [pallet_parameters, Parameters]
        [pallet_cc_authorities_noting, AuthoritiesNoting]
        [pallet_author_inherent, AuthorInherent]
        [cumulus_pallet_xcmp_queue, XcmpQueue]
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
        [pallet_message_queue, MessageQueue]
        [pallet_assets, ForeignAssets]
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
        [pallet_asset_rate, AssetRate]
        [pallet_xcm_executor_utils, XcmExecutorUtils]
    );
}
17598
impl_runtime_apis! {
10592
    impl sp_api::Core<Block> for Runtime {
10592
        fn version() -> RuntimeVersion {
            VERSION
        }
10592

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

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

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

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

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

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

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

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

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

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

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

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

            
10592
            let dispatch_info = xt.get_dispatch_info();
10592

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
10592
            add_benchmarks!(params, batches);
10592

            
10592
            Ok(batches)
10592
        }
10592
    }
10592

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

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

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

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

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

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

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

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

            
10592
        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();
            }
10592
            let gas_limit = gas_limit.min(u64::MAX.into()).low_u64();
            let without_base_extrinsic_weight = true;
10592
            let (weight_limit, proof_size_base_cost) =
10592
                match <Runtime as pallet_evm::Config>::GasWeightMapping::gas_to_weight(
                    gas_limit,
                    without_base_extrinsic_weight
                ) {
10592
                    weight_limit if weight_limit.proof_size() > 0 => {
10592
                        (Some(weight_limit), Some(estimated_transaction_len as u64))
10592
                    }
10592
                    _ => (None, None),
10592
                };
10592

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

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

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

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

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

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

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

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

            
10592
        fn gas_limit_multiplier_support() {}
10592

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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