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
extern crate alloc;
22

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

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

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

            
34
pub mod migrations;
35
pub mod weights;
36

            
37
pub use sp_runtime::{traits::ExtrinsicLike, MultiAddress, Perbill, Permill};
38
use {
39
    cumulus_primitives_core::AggregateMessageOrigin,
40
    dp_impl_tanssi_pallets_config::impl_tanssi_pallets_config,
41
    frame_support::{
42
        construct_runtime,
43
        dispatch::DispatchClass,
44
        genesis_builder_helper::{build_state, get_preset},
45
        pallet_prelude::DispatchResult,
46
        parameter_types,
47
        traits::{
48
            tokens::ConversionToAssetBalance, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8,
49
            Contains, InsideBoth, InstanceFilter,
50
        },
51
        weights::{
52
            constants::{
53
                BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
54
                WEIGHT_REF_TIME_PER_SECOND,
55
            },
56
            ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
57
            WeightToFeeCoefficients, WeightToFeePolynomial,
58
        },
59
    },
60
    frame_system::{
61
        limits::{BlockLength, BlockWeights},
62
        EnsureRoot,
63
    },
64
    nimbus_primitives::{NimbusId, SlotBeacon},
65
    pallet_transaction_payment::FungibleAdapter,
66
    parity_scale_codec::{Decode, DecodeWithMemTracking, Encode},
67
    polkadot_runtime_common::SlowAdjustingFeeUpdate,
68
    scale_info::TypeInfo,
69
    serde::{Deserialize, Serialize},
70
    smallvec::smallvec,
71
    sp_api::impl_runtime_apis,
72
    sp_consensus_slots::{Slot, SlotDuration},
73
    sp_core::{MaxEncodedLen, OpaqueMetadata},
74
    sp_runtime::{
75
        generic,
76
        generic::SignedPayload,
77
        impl_opaque_keys,
78
        traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
79
        transaction_validity::{TransactionSource, TransactionValidity},
80
        ApplyExtrinsicResult, Cow, MultiSignature, SaturatedConversion,
81
    },
82
    sp_std::prelude::*,
83
    sp_version::RuntimeVersion,
84
    xcm::Version as XcmVersion,
85
    xcm::{IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm},
86
    xcm_runtime_apis::{
87
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
88
        fees::Error as XcmPaymentApiError,
89
    },
90
};
91

            
92
pub mod xcm_config;
93

            
94
// Polkadot imports
95
use polkadot_runtime_common::BlockHashCount;
96

            
97
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
98
pub type Signature = MultiSignature;
99

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

            
104
/// Balance of an account.
105
pub type Balance = u128;
106

            
107
/// Index of a transaction in the chain.
108
pub type Index = u32;
109

            
110
/// A hash of some data used by the chain.
111
pub type Hash = sp_core::H256;
112

            
113
/// An index to a block.
114
pub type BlockNumber = u32;
115

            
116
/// The address format for describing accounts.
117
pub type Address = MultiAddress<AccountId, ()>;
118

            
119
/// Block header type as expected by this runtime.
120
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
121

            
122
/// Block type as expected by this runtime.
123
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
124

            
125
/// A Block signed with a Justification
126
pub type SignedBlock = generic::SignedBlock<Block>;
127

            
128
/// BlockId type as expected by this runtime.
129
pub type BlockId = generic::BlockId<Block>;
130

            
131
/// The SignedExtension to the basic transaction logic.
132
pub type TxExtension = cumulus_pallet_weight_reclaim::StorageWeightReclaim<
133
    Runtime,
134
    (
135
        frame_system::CheckNonZeroSender<Runtime>,
136
        frame_system::CheckSpecVersion<Runtime>,
137
        frame_system::CheckTxVersion<Runtime>,
138
        frame_system::CheckGenesis<Runtime>,
139
        frame_system::CheckEra<Runtime>,
140
        frame_system::CheckNonce<Runtime>,
141
        frame_system::CheckWeight<Runtime>,
142
        pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
143
    ),
144
>;
145

            
146
/// Unchecked extrinsic type as expected by this runtime.
147
pub type UncheckedExtrinsic =
148
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
149

            
150
/// Extrinsic type that has already been checked.
151
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
152

            
153
/// Executive: handles dispatch to the various modules.
154
pub type Executive = frame_executive::Executive<
155
    Runtime,
156
    Block,
157
    frame_system::ChainContext<Runtime>,
158
    Runtime,
159
    AllPalletsWithSystem,
160
>;
161

            
162
pub mod currency {
163
    use super::Balance;
164

            
165
    pub const MICROUNIT: Balance = 1_000_000;
166
    pub const MILLIUNIT: Balance = 1_000_000_000;
167
    pub const UNIT: Balance = 1_000_000_000_000;
168
    pub const KILOUNIT: Balance = 1_000_000_000_000_000;
169

            
170
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
171

            
172
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
173
        items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
174
    }
175
}
176

            
177
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
178
/// node's balance type.
179
///
180
/// This should typically create a mapping between the following ranges:
181
///   - `[0, MAXIMUM_BLOCK_WEIGHT]`
182
///   - `[Balance::min, Balance::max]`
183
///
184
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
185
///   - Setting it to `0` will essentially disable the weight fee.
186
///   - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
187
pub struct WeightToFee;
188
impl WeightToFeePolynomial for WeightToFee {
189
    type Balance = Balance;
190
200
    fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
191
200
        // in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
192
200
        // in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
193
200
        let p = MILLIUNIT / 10;
194
200
        let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
195
200
        smallvec![WeightToFeeCoefficient {
196
            degree: 1,
197
            negative: false,
198
            coeff_frac: Perbill::from_rational(p % q, q),
199
            coeff_integer: p / q,
200
        }]
201
200
    }
202
}
203

            
204
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
205
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
206
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
207
/// to even the core data structures.
208
pub mod opaque {
209
    use {
210
        super::*,
211
        sp_runtime::{generic, traits::BlakeTwo256},
212
    };
213

            
214
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
215
    /// Opaque block header type.
216
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
217
    /// Opaque block type.
218
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
219
    /// Opaque block identifier type.
220
    pub type BlockId = generic::BlockId<Block>;
221
}
222

            
223
impl_opaque_keys! {
224
    pub struct SessionKeys { }
225
}
226

            
227
#[sp_version::runtime_version]
228
pub const VERSION: RuntimeVersion = RuntimeVersion {
229
    spec_name: Cow::Borrowed("container-chain-template"),
230
    impl_name: Cow::Borrowed("container-chain-template"),
231
    authoring_version: 1,
232
    spec_version: 1400,
233
    impl_version: 0,
234
    apis: RUNTIME_API_VERSIONS,
235
    transaction_version: 1,
236
    system_version: 1,
237
};
238

            
239
/// This determines the average expected block time that we are targeting.
240
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
241
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
242
/// up by `pallet_aura` to implement `fn slot_duration()`.
243
///
244
/// Change this to adjust the block time.
245
pub const MILLISECS_PER_BLOCK: u64 = 6000;
246

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

            
251
// Time is measured by number of blocks.
252
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
253
pub const HOURS: BlockNumber = MINUTES * 60;
254
pub const DAYS: BlockNumber = HOURS * 24;
255

            
256
pub const SUPPLY_FACTOR: Balance = 100;
257

            
258
// Unit = the base number of indivisible units for balances
259
pub const UNIT: Balance = 1_000_000_000_000;
260
pub const MILLIUNIT: Balance = 1_000_000_000;
261
pub const MICROUNIT: Balance = 1_000_000;
262

            
263
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
264

            
265
pub const fn deposit(items: u32, bytes: u32) -> Balance {
266
    items as Balance * 100 * MILLIUNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
267
}
268

            
269
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
270
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
271

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

            
276
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
277
/// `Operational` extrinsics.
278
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
279

            
280
/// We allow for 2 seconds of compute with a 6 second average block time
281
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
282
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
283
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
284
);
285

            
286
/// The version information used to identify this runtime when compiled natively.
287
#[cfg(feature = "std")]
288
pub fn native_version() -> NativeVersion {
289
    NativeVersion {
290
        runtime_version: VERSION,
291
        can_author_with: Default::default(),
292
    }
293
}
294

            
295
parameter_types! {
296
    pub const Version: RuntimeVersion = VERSION;
297

            
298
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
299
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
300
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
301
    // the lazy contract deletion.
302
    pub RuntimeBlockLength: BlockLength =
303
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
304
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
305
        .base_block(BlockExecutionWeight::get())
306
15237
        .for_class(DispatchClass::all(), |weights| {
307
15237
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
308
15237
        })
309
5079
        .for_class(DispatchClass::Normal, |weights| {
310
5079
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
311
5079
        })
312
5079
        .for_class(DispatchClass::Operational, |weights| {
313
5079
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
314
5079
            // Operational transactions have some extra reserved space, so that they
315
5079
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
316
5079
            weights.reserved = Some(
317
5079
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
318
5079
            );
319
5079
        })
320
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
321
        .build_or_panic();
322
    pub const SS58Prefix: u16 = 42;
323
}
324

            
325
// Configure FRAME pallets to include in runtime.
326

            
327
impl frame_system::Config for Runtime {
328
    /// The identifier used to distinguish between accounts.
329
    type AccountId = AccountId;
330
    /// The aggregated dispatch type that is available for extrinsics.
331
    type RuntimeCall = RuntimeCall;
332
    /// The lookup mechanism to get account ID from whatever is passed in dispatchers.
333
    type Lookup = AccountIdLookup<AccountId, ()>;
334
    /// The index type for storing how many extrinsics an account has signed.
335
    type Nonce = Index;
336
    /// The index type for blocks.
337
    type Block = Block;
338
    /// The type for hashing blocks and tries.
339
    type Hash = Hash;
340
    /// The hashing algorithm used.
341
    type Hashing = BlakeTwo256;
342
    /// The ubiquitous event type.
343
    type RuntimeEvent = RuntimeEvent;
344
    /// The ubiquitous origin type.
345
    type RuntimeOrigin = RuntimeOrigin;
346
    /// Maximum number of block number to block hash mappings to keep (oldest pruned first).
347
    type BlockHashCount = BlockHashCount;
348
    /// Runtime version.
349
    type Version = Version;
350
    /// Converts a module to an index of this module in the runtime.
351
    type PalletInfo = PalletInfo;
352
    /// The data to be stored in an account.
353
    type AccountData = pallet_balances::AccountData<Balance>;
354
    /// What to do if a new account is created.
355
    type OnNewAccount = ();
356
    /// What to do if an account is fully reaped from the system.
357
    type OnKilledAccount = ();
358
    /// The weight of database operations that the runtime can invoke.
359
    type DbWeight = RocksDbWeight;
360
    /// The basic call filter to use in dispatchable.
361
    type BaseCallFilter = InsideBoth<MaintenanceMode, TxPause>;
362
    /// Weight information for the extrinsics of this pallet.
363
    type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
364
    /// Block & extrinsics weights: base values and limits.
365
    type BlockWeights = RuntimeBlockWeights;
366
    /// The maximum length of a block (in bytes).
367
    type BlockLength = RuntimeBlockLength;
368
    /// This is used as an identifier of the chain. 42 is the generic substrate prefix.
369
    type SS58Prefix = SS58Prefix;
370
    /// The action to take on a Runtime Upgrade
371
    type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
372
    type MaxConsumers = frame_support::traits::ConstU32<16>;
373
    type RuntimeTask = RuntimeTask;
374
    type SingleBlockMigrations = ();
375
    type MultiBlockMigrator = MultiBlockMigrations;
376
    type PreInherents = ();
377
    type PostInherents = ();
378
    type PostTransactions = ();
379
    type ExtensionsWeightInfo = weights::frame_system_extensions::SubstrateWeight<Runtime>;
380
}
381

            
382
parameter_types! {
383
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
384
}
385

            
386
impl pallet_balances::Config for Runtime {
387
    type MaxLocks = ConstU32<50>;
388
    /// The type for recording an account's balance.
389
    type Balance = Balance;
390
    /// The ubiquitous event type.
391
    type RuntimeEvent = RuntimeEvent;
392
    type DustRemoval = ();
393
    type ExistentialDeposit = ExistentialDeposit;
394
    type AccountStore = System;
395
    type MaxReserves = ConstU32<50>;
396
    type ReserveIdentifier = [u8; 8];
397
    type FreezeIdentifier = RuntimeFreezeReason;
398
    type MaxFreezes = ConstU32<0>;
399
    type RuntimeHoldReason = RuntimeHoldReason;
400
    type RuntimeFreezeReason = RuntimeFreezeReason;
401
    type DoneSlashHandler = ();
402
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
403
}
404

            
405
parameter_types! {
406
    pub const TransactionByteFee: Balance = 1;
407
}
408

            
409
impl pallet_transaction_payment::Config for Runtime {
410
    type RuntimeEvent = RuntimeEvent;
411
    // This will burn the fees
412
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
413
    type OperationalFeeMultiplier = ConstU8<5>;
414
    type WeightToFee = WeightToFee;
415
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
416
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
417
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
418
}
419

            
420
parameter_types! {
421
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
422
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
423
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
424
}
425

            
426
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
427
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
428
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
429

            
430
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
431
    Runtime,
432
    BLOCK_PROCESSING_VELOCITY,
433
    UNINCLUDED_SEGMENT_CAPACITY,
434
>;
435

            
436
impl cumulus_pallet_parachain_system::Config for Runtime {
437
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
438
    type RuntimeEvent = RuntimeEvent;
439
    type OnSystemEvent = ();
440
    type OutboundXcmpMessageSource = XcmpQueue;
441
    type SelfParaId = parachain_info::Pallet<Runtime>;
442
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
443
    type ReservedDmpWeight = ReservedDmpWeight;
444
    type XcmpMessageHandler = XcmpQueue;
445
    type ReservedXcmpWeight = ReservedXcmpWeight;
446
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
447
    type ConsensusHook = ConsensusHook;
448
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
449
}
450

            
451
pub struct ParaSlotProvider;
452
impl sp_core::Get<(Slot, SlotDuration)> for ParaSlotProvider {
453
616
    fn get() -> (Slot, SlotDuration) {
454
616
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
455
616
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
456
616
    }
457
}
458

            
459
parameter_types! {
460
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
461
}
462

            
463
impl pallet_async_backing::Config for Runtime {
464
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
465
    type GetAndVerifySlot =
466
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
467
    type ExpectedBlockTime = ExpectedBlockTime;
468
}
469

            
470
impl parachain_info::Config for Runtime {}
471

            
472
parameter_types! {
473
    pub const Period: u32 = 6 * HOURS;
474
    pub const Offset: u32 = 0;
475
}
476

            
477
impl pallet_sudo::Config for Runtime {
478
    type RuntimeCall = RuntimeCall;
479
    type RuntimeEvent = RuntimeEvent;
480
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
481
}
482

            
483
impl pallet_utility::Config for Runtime {
484
    type RuntimeEvent = RuntimeEvent;
485
    type RuntimeCall = RuntimeCall;
486
    type PalletsOrigin = OriginCaller;
487
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
488
}
489

            
490
/// The type used to represent the kinds of proxying allowed.
491
#[derive(
492
    Copy,
493
    Clone,
494
    Eq,
495
    PartialEq,
496
    Ord,
497
    PartialOrd,
498
    Encode,
499
    Decode,
500
    Debug,
501
    MaxEncodedLen,
502
    DecodeWithMemTracking,
503
    TypeInfo,
504
    Serialize,
505
    Deserialize,
506
)]
507
#[allow(clippy::unnecessary_cast)]
508
pub enum ProxyType {
509
    /// All calls can be proxied. This is the trivial/most permissive filter.
510
    Any = 0,
511
    /// Only extrinsics that do not transfer funds.
512
    NonTransfer = 1,
513
    /// Only extrinsics related to governance (democracy and collectives).
514
    Governance = 2,
515
    /// Allow to veto an announced proxy call.
516
    CancelProxy = 3,
517
    /// Allow extrinsic related to Balances.
518
    Balances = 4,
519
}
520

            
521
impl Default for ProxyType {
522
    fn default() -> Self {
523
        Self::Any
524
    }
525
}
526

            
527
impl InstanceFilter<RuntimeCall> for ProxyType {
528
    fn filter(&self, c: &RuntimeCall) -> bool {
529
        // Since proxy filters are respected in all dispatches of the Utility
530
        // pallet, it should never need to be filtered by any proxy.
531
        if let RuntimeCall::Utility(..) = c {
532
            return true;
533
        }
534

            
535
        match self {
536
            ProxyType::Any => true,
537
            ProxyType::NonTransfer => {
538
                matches!(
539
                    c,
540
                    RuntimeCall::System(..)
541
                        | RuntimeCall::ParachainSystem(..)
542
                        | RuntimeCall::Timestamp(..)
543
                        | RuntimeCall::Proxy(..)
544
                )
545
            }
546
            // We don't have governance yet
547
            ProxyType::Governance => false,
548
            ProxyType::CancelProxy => matches!(
549
                c,
550
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
551
            ),
552
            ProxyType::Balances => {
553
                matches!(c, RuntimeCall::Balances(..))
554
            }
555
        }
556
    }
557

            
558
    fn is_superset(&self, o: &Self) -> bool {
559
        match (self, o) {
560
            (x, y) if x == y => true,
561
            (ProxyType::Any, _) => true,
562
            (_, ProxyType::Any) => false,
563
            _ => false,
564
        }
565
    }
566
}
567

            
568
impl pallet_proxy::Config for Runtime {
569
    type RuntimeEvent = RuntimeEvent;
570
    type RuntimeCall = RuntimeCall;
571
    type Currency = Balances;
572
    type ProxyType = ProxyType;
573
    // One storage item; key size 32, value size 8
574
    type ProxyDepositBase = ConstU128<{ deposit(1, 8) }>;
575
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
576
    type ProxyDepositFactor = ConstU128<{ deposit(0, 33) }>;
577
    type MaxProxies = ConstU32<32>;
578
    type MaxPending = ConstU32<32>;
579
    type CallHasher = BlakeTwo256;
580
    type AnnouncementDepositBase = ConstU128<{ deposit(1, 8) }>;
581
    // Additional storage item size of 68 bytes:
582
    // - 32 bytes AccountId
583
    // - 32 bytes Hasher (Blake2256)
584
    // - 4 bytes BlockNumber (u32)
585
    type AnnouncementDepositFactor = ConstU128<{ deposit(0, 68) }>;
586
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
587
    type BlockNumberProvider = System;
588
}
589

            
590
pub struct XcmExecutionManager;
591
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
592
    fn suspend_xcm_execution() -> DispatchResult {
593
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
594
    }
595
    fn resume_xcm_execution() -> DispatchResult {
596
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
597
    }
598
}
599

            
600
impl pallet_migrations::Config for Runtime {
601
    type RuntimeEvent = RuntimeEvent;
602
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
603
    type XcmExecutionManager = XcmExecutionManager;
604
}
605

            
606
parameter_types! {
607
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
608
}
609

            
610
impl pallet_multiblock_migrations::Config for Runtime {
611
    type RuntimeEvent = RuntimeEvent;
612
    #[cfg(not(feature = "runtime-benchmarks"))]
613
    type Migrations = ();
614
    // Benchmarks need mocked migrations to guarantee that they succeed.
615
    #[cfg(feature = "runtime-benchmarks")]
616
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
617
    type CursorMaxLen = ConstU32<65_536>;
618
    type IdentifierMaxLen = ConstU32<256>;
619
    type MigrationStatusHandler = ();
620
    type FailedMigrationHandler = MaintenanceMode;
621
    type MaxServiceWeight = MbmServiceWeight;
622
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
623
}
624

            
625
/// Maintenance mode Call filter
626
pub struct MaintenanceFilter;
627
impl Contains<RuntimeCall> for MaintenanceFilter {
628
    fn contains(c: &RuntimeCall) -> bool {
629
        !matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
630
    }
631
}
632

            
633
/// Normal Call Filter
634
/// We dont allow to create nor mint assets, this for now is disabled
635
/// We only allow transfers. For now creation of assets will go through
636
/// asset-manager, while minting/burning only happens through xcm messages
637
/// This can change in the future
638
pub struct NormalFilter;
639
impl Contains<RuntimeCall> for NormalFilter {
640
1232
    fn contains(_c: &RuntimeCall) -> bool {
641
1232
        true
642
1232
    }
643
}
644

            
645
impl pallet_maintenance_mode::Config for Runtime {
646
    type RuntimeEvent = RuntimeEvent;
647
    type NormalCallFilter = NormalFilter;
648
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
649
    type MaintenanceOrigin = EnsureRoot<AccountId>;
650
    type XcmExecutionManager = XcmExecutionManager;
651
}
652

            
653
impl pallet_root_testing::Config for Runtime {
654
    type RuntimeEvent = RuntimeEvent;
655
}
656

            
657
impl pallet_tx_pause::Config for Runtime {
658
    type RuntimeEvent = RuntimeEvent;
659
    type RuntimeCall = RuntimeCall;
660
    type PauseOrigin = EnsureRoot<AccountId>;
661
    type UnpauseOrigin = EnsureRoot<AccountId>;
662
    type WhitelistedCalls = ();
663
    type MaxNameLen = ConstU32<256>;
664
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
665
}
666

            
667
impl dp_impl_tanssi_pallets_config::Config for Runtime {
668
    const SLOT_DURATION: u64 = SLOT_DURATION;
669
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
670
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
671
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
672
}
673

            
674
parameter_types! {
675
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
676
    pub const DepositBase: Balance = currency::deposit(1, 88);
677
    // Additional storage item size of 32 bytes.
678
    pub const DepositFactor: Balance = currency::deposit(0, 32);
679
    pub const MaxSignatories: u32 = 100;
680
}
681

            
682
impl pallet_multisig::Config for Runtime {
683
    type RuntimeEvent = RuntimeEvent;
684
    type RuntimeCall = RuntimeCall;
685
    type Currency = Balances;
686
    type DepositBase = DepositBase;
687
    type DepositFactor = DepositFactor;
688
    type MaxSignatories = MaxSignatories;
689
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
690
    type BlockNumberProvider = System;
691
}
692

            
693
impl frame_system::offchain::SigningTypes for Runtime {
694
    type Public = <Signature as sp_runtime::traits::Verify>::Signer;
695
    type Signature = Signature;
696
}
697

            
698
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
699
/// format of the chain.
700
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
701
where
702
    RuntimeCall: From<LocalCall>,
703
{
704
    fn create_signed_transaction<
705
        C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>,
706
    >(
707
        call: RuntimeCall,
708
        public: <Signature as Verify>::Signer,
709
        account: AccountId,
710
        nonce: <Runtime as frame_system::Config>::Nonce,
711
    ) -> Option<UncheckedExtrinsic> {
712
        use sp_runtime::traits::StaticLookup;
713
        // take the biggest period possible.
714
        let period = BlockHashCount::get()
715
            .checked_next_power_of_two()
716
            .map(|c| c / 2)
717
            .unwrap_or(2) as u64;
718

            
719
        let current_block = System::block_number()
720
            .saturated_into::<u64>()
721
            // The `System::block_number` is initialized with `n+1`,
722
            // so the actual block number is `n`.
723
            .saturating_sub(1);
724
        let tip = 0;
725
        let tx_ext = TxExtension::new((
726
            frame_system::CheckNonZeroSender::<Runtime>::new(),
727
            frame_system::CheckSpecVersion::<Runtime>::new(),
728
            frame_system::CheckTxVersion::<Runtime>::new(),
729
            frame_system::CheckGenesis::<Runtime>::new(),
730
            frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
731
                period,
732
                current_block,
733
            )),
734
            frame_system::CheckNonce::<Runtime>::from(nonce),
735
            frame_system::CheckWeight::<Runtime>::new(),
736
            pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
737
            //frame_metadata_hash_extension::CheckMetadataHash::new(true),
738
        ));
739
        let raw_payload = SignedPayload::new(call, tx_ext)
740
            .map_err(|e| {
741
                log::warn!("Unable to create signed payload: {:?}", e);
742
            })
743
            .ok()?;
744
        let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
745
        let (call, tx_ext, _) = raw_payload.deconstruct();
746
        let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
747
        let transaction = UncheckedExtrinsic::new_signed(call, address, signature, tx_ext);
748
        Some(transaction)
749
    }
750
}
751

            
752
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
753
where
754
    RuntimeCall: From<C>,
755
{
756
    type Extrinsic = UncheckedExtrinsic;
757
    type RuntimeCall = RuntimeCall;
758
}
759

            
760
impl<LocalCall> frame_system::offchain::CreateInherent<LocalCall> for Runtime
761
where
762
    RuntimeCall: From<LocalCall>,
763
{
764
    fn create_inherent(call: RuntimeCall) -> UncheckedExtrinsic {
765
        UncheckedExtrinsic::new_bare(call)
766
    }
767
}
768

            
769
impl pallet_ocw_testing::Config for Runtime {
770
    type RuntimeEvent = RuntimeEvent;
771
    type UnsignedInterval = ConstU32<6>;
772
}
773

            
774
impl cumulus_pallet_weight_reclaim::Config for Runtime {
775
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
776
}
777

            
778
impl_tanssi_pallets_config!(Runtime);
779

            
780
// Create the runtime by composing the FRAME pallets that were previously configured.
781
20499
construct_runtime!(
782
20499
    pub enum Runtime
783
20499
    {
784
20499
        // System support stuff.
785
20499
        System: frame_system = 0,
786
20499
        ParachainSystem: cumulus_pallet_parachain_system = 1,
787
20499
        Timestamp: pallet_timestamp = 2,
788
20499
        ParachainInfo: parachain_info = 3,
789
20499
        Sudo: pallet_sudo = 4,
790
20499
        Utility: pallet_utility = 5,
791
20499
        Proxy: pallet_proxy = 6,
792
20499
        Migrations: pallet_migrations = 7,
793
20499
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
794
20499
        MaintenanceMode: pallet_maintenance_mode = 8,
795
20499
        TxPause: pallet_tx_pause = 9,
796
20499

            
797
20499
        // Monetary stuff.
798
20499
        Balances: pallet_balances = 10,
799
20499
        TransactionPayment: pallet_transaction_payment = 11,
800
20499

            
801
20499
        // Other utilities
802
20499
        Multisig: pallet_multisig = 16,
803
20499

            
804
20499
        // ContainerChain Author Verification
805
20499
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
806
20499
        AuthorInherent: pallet_author_inherent = 51,
807
20499

            
808
20499
        // XCM
809
20499
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
810
20499
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
811
20499
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
812
20499
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
813
20499
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
814
20499
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
815
20499
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
816
20499
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
817
20499

            
818
20499
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
819
20499

            
820
20499
        RootTesting: pallet_root_testing = 100,
821
20499
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
822
20499

            
823
20499
        OffchainWorker: pallet_ocw_testing::{Pallet, Call, Storage, Event<T>, ValidateUnsigned} = 120,
824
20499
    }
825
20499
);
826

            
827
#[cfg(feature = "runtime-benchmarks")]
828
mod benches {
829
    frame_benchmarking::define_benchmarks!(
830
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
831
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
832
        [cumulus_pallet_parachain_system, ParachainSystem]
833
        [pallet_timestamp, Timestamp]
834
        [pallet_sudo, Sudo]
835
        [pallet_utility, Utility]
836
        [pallet_proxy, Proxy]
837
        [pallet_tx_pause, TxPause]
838
        [pallet_transaction_payment, TransactionPayment]
839
        [pallet_balances, Balances]
840
        [pallet_multiblock_migrations, MultiBlockMigrations]
841
        [pallet_multisig, Multisig]
842
        [pallet_cc_authorities_noting, AuthoritiesNoting]
843
        [pallet_author_inherent, AuthorInherent]
844
        [cumulus_pallet_xcmp_queue, XcmpQueue]
845
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
846
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
847
        [pallet_message_queue, MessageQueue]
848
        [pallet_assets, ForeignAssets]
849
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
850
        [pallet_asset_rate, AssetRate]
851
        [pallet_xcm_executor_utils, XcmExecutorUtils]
852
        [cumulus_pallet_weight_reclaim, WeightReclaim]
853
    );
854
}
855

            
856
5088
impl_runtime_apis! {
857
5088
    impl sp_api::Core<Block> for Runtime {
858
5088
        fn version() -> RuntimeVersion {
859
5088
            VERSION
860
5088
        }
861
5088

            
862
5088
        fn execute_block(block: Block) {
863
5088
            Executive::execute_block(block)
864
5088
        }
865
5088

            
866
5088
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
867
5088
            Executive::initialize_block(header)
868
5088
        }
869
5088
    }
870
5088

            
871
5088
    impl sp_api::Metadata<Block> for Runtime {
872
5088
        fn metadata() -> OpaqueMetadata {
873
5088
            OpaqueMetadata::new(Runtime::metadata().into())
874
5088
        }
875
5088

            
876
5088
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
877
5088
            Runtime::metadata_at_version(version)
878
5088
        }
879
5088

            
880
5088
        fn metadata_versions() -> Vec<u32> {
881
5088
            Runtime::metadata_versions()
882
5088
        }
883
5088
    }
884
5088

            
885
5088
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
886
5088
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
887
5088
            Executive::apply_extrinsic(extrinsic)
888
5088
        }
889
5088

            
890
5088
        fn finalize_block() -> <Block as BlockT>::Header {
891
5088
            Executive::finalize_block()
892
5088
        }
893
5088

            
894
5088
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
895
5088
            data.create_extrinsics()
896
5088
        }
897
5088

            
898
5088
        fn check_inherents(
899
5088
            block: Block,
900
5088
            data: sp_inherents::InherentData,
901
5088
        ) -> sp_inherents::CheckInherentsResult {
902
5088
            data.check_extrinsics(&block)
903
5088
        }
904
5088
    }
905
5088

            
906
5088
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
907
5088
        fn validate_transaction(
908
5088
            source: TransactionSource,
909
5088
            tx: <Block as BlockT>::Extrinsic,
910
5088
            block_hash: <Block as BlockT>::Hash,
911
5088
        ) -> TransactionValidity {
912
5088
            Executive::validate_transaction(source, tx, block_hash)
913
5088
        }
914
5088
    }
915
5088

            
916
5088
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
917
5088
        fn offchain_worker(header: &<Block as BlockT>::Header) {
918
5088
            Executive::offchain_worker(header)
919
5088
        }
920
5088
    }
921
5088

            
922
5088
    impl sp_session::SessionKeys<Block> for Runtime {
923
5088
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
924
5088
            SessionKeys::generate(seed)
925
5088
        }
926
5088

            
927
5088
        fn decode_session_keys(
928
5088
            encoded: Vec<u8>,
929
5088
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
930
5088
            SessionKeys::decode_into_raw_public_keys(&encoded)
931
5088
        }
932
5088
    }
933
5088

            
934
5088
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
935
5088
        fn account_nonce(account: AccountId) -> Index {
936
5088
            System::account_nonce(account)
937
5088
        }
938
5088
    }
939
5088

            
940
5088
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
941
5088
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
942
5088
            ParachainSystem::collect_collation_info(header)
943
5088
        }
944
5088
    }
945
5088

            
946
5088
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
947
5088
        fn can_build_upon(
948
5088
            included_hash: <Block as BlockT>::Hash,
949
5088
            slot: async_backing_primitives::Slot,
950
5088
        ) -> bool {
951
5088
            ConsensusHook::can_build_upon(included_hash, slot)
952
5088
        }
953
5088
    }
954
5088

            
955
5088
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
956
5088
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
957
5088
            build_state::<RuntimeGenesisConfig>(config)
958
5088
        }
959
5088

            
960
5088
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
961
5088
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
962
5088
        }
963
5088
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
964
5088
            vec![]
965
5088
        }
966
5088
    }
967
5088

            
968
5088
    #[cfg(feature = "runtime-benchmarks")]
969
5088
    impl frame_benchmarking::Benchmark<Block> for Runtime {
970
5088
        fn benchmark_metadata(
971
5088
            extra: bool,
972
5088
        ) -> (
973
5088
            Vec<frame_benchmarking::BenchmarkList>,
974
5088
            Vec<frame_support::traits::StorageInfo>,
975
5088
        ) {
976
5088
            use frame_benchmarking::{BenchmarkList};
977
5088
            use frame_support::traits::StorageInfoTrait;
978
5088
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
979
5088

            
980
5088
            let mut list = Vec::<BenchmarkList>::new();
981
5088
            list_benchmarks!(list, extra);
982
5088

            
983
5088
            let storage_info = AllPalletsWithSystem::storage_info();
984
5088
            (list, storage_info)
985
5088
        }
986
5088

            
987
5088
        #[allow(non_local_definitions)]
988
5088
        fn dispatch_benchmark(
989
5088
            config: frame_benchmarking::BenchmarkConfig,
990
5088
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
991
5088
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
992
5088
            use sp_core::storage::TrackedStorageKey;
993
5088
            use xcm::latest::prelude::*;
994
5088
            impl frame_system_benchmarking::Config for Runtime {
995
5088
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
996
5088
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
997
5088
                    Ok(())
998
5088
                }
999
5088

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
5088
                fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
5088
                    use xcm_config::SelfReserve;
5088
                    // AH can reserve transfer native token to some random parachain.
5088
                    let random_para_id = 43211234;
5088
                    ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
5088
                        random_para_id.into()
5088
                    );
5088
                    let who = frame_benchmarking::whitelisted_caller();
5088
                    // Give some multiple of the existential deposit
5088
                    let balance = EXISTENTIAL_DEPOSIT * 1000;
5088
                    let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
5088
                        &who, balance,
5088
                    );
5088
                    Some((
5088
                        Asset {
5088
                            fun: Fungible(EXISTENTIAL_DEPOSIT*10),
5088
                            id: SelfReserve::get().into()
5088
                        },
5088
                        ParentThen(Parachain(random_para_id).into()).into(),
5088
                    ))
5088
                }
5088

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

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

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

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

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

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

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

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

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

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

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

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

            
5088
            add_benchmarks!(params, batches);
5088

            
5088
            Ok(batches)
5088
        }
5088
    }
5088

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

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

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

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

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

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

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

            
5088
    impl xcm_runtime_apis::fees::XcmPaymentApi<Block> for Runtime {
5088
        fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result<Vec<VersionedAssetId>, XcmPaymentApiError> {
5088
            if !matches!(xcm_version, 3..=5) {
5088
                return Err(XcmPaymentApiError::UnhandledXcmVersion);
5088
            }
5088

            
5088
            Ok([VersionedAssetId::V5(xcm_config::SelfReserve::get().into())]
5088
                .into_iter()
5088
                .chain(
5088
                    pallet_asset_rate::ConversionRateToNative::<Runtime>::iter_keys().filter_map(|asset_id_u16| {
5088
                        pallet_foreign_asset_creator::AssetIdToForeignAsset::<Runtime>::get(asset_id_u16).map(|location| {
5088
                            VersionedAssetId::V5(location.into())
5088
                        }).or_else(|| {
5088
                            log::warn!("Asset `{}` is present in pallet_asset_rate but not in pallet_foreign_asset_creator", asset_id_u16);
5088
                            None
5088
                        })
5088
                    })
5088
                )
5088
                .filter_map(|asset| asset.into_version(xcm_version).map_err(|e| {
5088
                    log::warn!("Failed to convert asset to version {}: {:?}", xcm_version, e);
5088
                }).ok())
5088
                .collect())
5088
        }
5088

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

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

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

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

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

            
5088
        fn dry_run_xcm(origin_location: VersionedLocation, xcm: VersionedXcm<RuntimeCall>) -> Result<XcmDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
5088
            PolkadotXcm::dry_run_xcm::<Runtime, xcm_config::XcmRouter, RuntimeCall, xcm_config::XcmConfig>(origin_location, xcm)
5088
        }
5088
    }
5088

            
5088
    impl xcm_runtime_apis::conversions::LocationToAccountApi<Block, AccountId> for Runtime {
5088
        fn convert_location(location: VersionedLocation) -> Result<
5088
            AccountId,
5088
            xcm_runtime_apis::conversions::Error
5088
        > {
5088
            xcm_runtime_apis::conversions::LocationToAccountHelper::<
5088
                AccountId,
5088
                xcm_config::LocationToAccountId,
5088
            >::convert_location(location)
5088
        }
5088
    }
7170
}
#[allow(dead_code)]
struct CheckInherents;
#[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>,
}