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

            
96
pub mod xcm_config;
97

            
98
// Polkadot imports
99
use polkadot_runtime_common::BlockHashCount;
100

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

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

            
108
/// Balance of an account.
109
pub type Balance = u128;
110

            
111
/// Index of a transaction in the chain.
112
pub type Index = u32;
113

            
114
/// A hash of some data used by the chain.
115
pub type Hash = sp_core::H256;
116

            
117
/// An index to a block.
118
pub type BlockNumber = u32;
119

            
120
/// The address format for describing accounts.
121
pub type Address = MultiAddress<AccountId, ()>;
122

            
123
/// Block header type as expected by this runtime.
124
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
125

            
126
/// Block type as expected by this runtime.
127
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
128

            
129
/// A Block signed with a Justification
130
pub type SignedBlock = generic::SignedBlock<Block>;
131

            
132
/// BlockId type as expected by this runtime.
133
pub type BlockId = generic::BlockId<Block>;
134

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

            
150
/// Unchecked extrinsic type as expected by this runtime.
151
pub type UncheckedExtrinsic =
152
    generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, TxExtension>;
153

            
154
/// Extrinsic type that has already been checked.
155
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
156

            
157
/// Executive: handles dispatch to the various modules.
158
pub type Executive = frame_executive::Executive<
159
    Runtime,
160
    Block,
161
    frame_system::ChainContext<Runtime>,
162
    Runtime,
163
    AllPalletsWithSystem,
164
>;
165

            
166
pub mod currency {
167
    use super::Balance;
168

            
169
    pub const MICROUNIT: Balance = 1_000_000;
170
    pub const MILLIUNIT: Balance = 1_000_000_000;
171
    pub const UNIT: Balance = 1_000_000_000_000;
172
    pub const KILOUNIT: Balance = 1_000_000_000_000_000;
173

            
174
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
175

            
176
    pub const fn deposit(items: u32, bytes: u32) -> Balance {
177
        items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
178
    }
179
}
180

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

            
208
parameter_types! {
209
        /// Network and location for the Ethereum chain. On Starlight, the Ethereum chain bridged
210
        /// to is the Ethereum mainnet, with chain ID 1.
211
        /// <https://chainlist.org/chain/1>
212
        /// <https://ethereum.org/en/developers/docs/apis/json-rpc/#net_version>
213
        pub EthereumNetwork: NetworkId = NetworkId::Ethereum { chain_id: 11155111 };
214
}
215

            
216
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
217
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
218
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
219
/// to even the core data structures.
220
pub mod opaque {
221
    use {
222
        super::*,
223
        sp_runtime::{generic, traits::BlakeTwo256},
224
    };
225

            
226
    pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
227
    /// Opaque block header type.
228
    pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
229
    /// Opaque block type.
230
    pub type Block = generic::Block<Header, UncheckedExtrinsic>;
231
    /// Opaque block identifier type.
232
    pub type BlockId = generic::BlockId<Block>;
233
}
234

            
235
impl_opaque_keys! {
236
    pub struct SessionKeys { }
237
}
238

            
239
#[sp_version::runtime_version]
240
pub const VERSION: RuntimeVersion = RuntimeVersion {
241
    spec_name: Cow::Borrowed("container-chain-template"),
242
    impl_name: Cow::Borrowed("container-chain-template"),
243
    authoring_version: 1,
244
    spec_version: 1500,
245
    impl_version: 0,
246
    apis: RUNTIME_API_VERSIONS,
247
    transaction_version: 1,
248
    system_version: 1,
249
};
250

            
251
/// This determines the average expected block time that we are targeting.
252
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
253
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
254
/// up by `pallet_aura` to implement `fn slot_duration()`.
255
///
256
/// Change this to adjust the block time.
257
pub const MILLISECS_PER_BLOCK: u64 = 6000;
258

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

            
263
// Time is measured by number of blocks.
264
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
265
pub const HOURS: BlockNumber = MINUTES * 60;
266
pub const DAYS: BlockNumber = HOURS * 24;
267

            
268
pub const SUPPLY_FACTOR: Balance = 100;
269

            
270
// Unit = the base number of indivisible units for balances
271
pub const UNIT: Balance = 1_000_000_000_000;
272
pub const MILLIUNIT: Balance = 1_000_000_000;
273
pub const MICROUNIT: Balance = 1_000_000;
274

            
275
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
276

            
277
pub const fn deposit(items: u32, bytes: u32) -> Balance {
278
    items as Balance * 100 * MILLIUNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
279
}
280

            
281
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
282
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
283

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

            
288
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
289
/// `Operational` extrinsics.
290
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
291

            
292
/// We allow for 2 seconds of compute with a 6 second average block time
293
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
294
    WEIGHT_REF_TIME_PER_SECOND.saturating_mul(2),
295
    cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
296
);
297

            
298
/// The version information used to identify this runtime when compiled natively.
299
#[cfg(feature = "std")]
300
pub fn native_version() -> NativeVersion {
301
    NativeVersion {
302
        runtime_version: VERSION,
303
        can_author_with: Default::default(),
304
    }
305
}
306

            
307
parameter_types! {
308
    pub const Version: RuntimeVersion = VERSION;
309

            
310
    // This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
311
    //  The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
312
    // `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
313
    // the lazy contract deletion.
314
    pub RuntimeBlockLength: BlockLength =
315
        BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
316
    pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
317
        .base_block(BlockExecutionWeight::get())
318
15813
        .for_class(DispatchClass::all(), |weights| {
319
15813
            weights.base_extrinsic = ExtrinsicBaseWeight::get();
320
15813
        })
321
5271
        .for_class(DispatchClass::Normal, |weights| {
322
5271
            weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
323
5271
        })
324
5271
        .for_class(DispatchClass::Operational, |weights| {
325
5271
            weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
326
5271
            // Operational transactions have some extra reserved space, so that they
327
5271
            // are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
328
5271
            weights.reserved = Some(
329
5271
                MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
330
5271
            );
331
5271
        })
332
        .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
333
        .build_or_panic();
334
    pub const SS58Prefix: u16 = 42;
335
}
336

            
337
// Configure FRAME pallets to include in runtime.
338

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

            
394
parameter_types! {
395
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
396
}
397

            
398
impl pallet_balances::Config for Runtime {
399
    type MaxLocks = ConstU32<50>;
400
    /// The type for recording an account's balance.
401
    type Balance = Balance;
402
    /// The ubiquitous event type.
403
    type RuntimeEvent = RuntimeEvent;
404
    type DustRemoval = ();
405
    type ExistentialDeposit = ExistentialDeposit;
406
    type AccountStore = System;
407
    type MaxReserves = ConstU32<50>;
408
    type ReserveIdentifier = [u8; 8];
409
    type FreezeIdentifier = RuntimeFreezeReason;
410
    type MaxFreezes = ConstU32<0>;
411
    type RuntimeHoldReason = RuntimeHoldReason;
412
    type RuntimeFreezeReason = RuntimeFreezeReason;
413
    type DoneSlashHandler = ();
414
    type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
415
}
416

            
417
parameter_types! {
418
    pub const TransactionByteFee: Balance = 1;
419
}
420

            
421
impl pallet_transaction_payment::Config for Runtime {
422
    type RuntimeEvent = RuntimeEvent;
423
    // This will burn the fees
424
    type OnChargeTransaction = FungibleAdapter<Balances, ()>;
425
    type OperationalFeeMultiplier = ConstU8<5>;
426
    type WeightToFee = WeightToFee;
427
    type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
428
    type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
429
    type WeightInfo = weights::pallet_transaction_payment::SubstrateWeight<Runtime>;
430
}
431

            
432
parameter_types! {
433
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
434
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
435
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
436
}
437

            
438
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
439
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
440
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
441

            
442
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
443
    Runtime,
444
    BLOCK_PROCESSING_VELOCITY,
445
    UNINCLUDED_SEGMENT_CAPACITY,
446
>;
447

            
448
impl cumulus_pallet_parachain_system::Config for Runtime {
449
    type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
450
    type RuntimeEvent = RuntimeEvent;
451
    type OnSystemEvent = ();
452
    type OutboundXcmpMessageSource = XcmpQueue;
453
    type SelfParaId = parachain_info::Pallet<Runtime>;
454
    type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
455
    type ReservedDmpWeight = ReservedDmpWeight;
456
    type XcmpMessageHandler = XcmpQueue;
457
    type ReservedXcmpWeight = ReservedXcmpWeight;
458
    type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
459
    type ConsensusHook = ConsensusHook;
460
    type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
461
}
462

            
463
pub struct ParaSlotProvider;
464
impl sp_core::Get<(Slot, SlotDuration)> for ParaSlotProvider {
465
640
    fn get() -> (Slot, SlotDuration) {
466
640
        let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
467
640
        (Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
468
640
    }
469
}
470

            
471
parameter_types! {
472
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
473
}
474

            
475
impl pallet_async_backing::Config for Runtime {
476
    type AllowMultipleBlocksPerSlot = ConstBool<true>;
477
    type GetAndVerifySlot =
478
        pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
479
    type ExpectedBlockTime = ExpectedBlockTime;
480
}
481

            
482
impl parachain_info::Config for Runtime {}
483

            
484
parameter_types! {
485
    pub const Period: u32 = 6 * HOURS;
486
    pub const Offset: u32 = 0;
487
}
488

            
489
impl pallet_sudo::Config for Runtime {
490
    type RuntimeCall = RuntimeCall;
491
    type RuntimeEvent = RuntimeEvent;
492
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
493
}
494

            
495
impl pallet_utility::Config for Runtime {
496
    type RuntimeEvent = RuntimeEvent;
497
    type RuntimeCall = RuntimeCall;
498
    type PalletsOrigin = OriginCaller;
499
    type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
500
}
501

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

            
533
impl Default for ProxyType {
534
    fn default() -> Self {
535
        Self::Any
536
    }
537
}
538

            
539
impl InstanceFilter<RuntimeCall> for ProxyType {
540
    fn filter(&self, c: &RuntimeCall) -> bool {
541
        // Since proxy filters are respected in all dispatches of the Utility
542
        // pallet, it should never need to be filtered by any proxy.
543
        if let RuntimeCall::Utility(..) = c {
544
            return true;
545
        }
546

            
547
        match self {
548
            ProxyType::Any => true,
549
            ProxyType::NonTransfer => {
550
                matches!(
551
                    c,
552
                    RuntimeCall::System(..)
553
                        | RuntimeCall::ParachainSystem(..)
554
                        | RuntimeCall::Timestamp(..)
555
                        | RuntimeCall::Proxy(..)
556
                )
557
            }
558
            // We don't have governance yet
559
            ProxyType::Governance => false,
560
            ProxyType::CancelProxy => matches!(
561
                c,
562
                RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
563
            ),
564
            ProxyType::Balances => {
565
                matches!(c, RuntimeCall::Balances(..))
566
            }
567
        }
568
    }
569

            
570
    fn is_superset(&self, o: &Self) -> bool {
571
        match (self, o) {
572
            (x, y) if x == y => true,
573
            (ProxyType::Any, _) => true,
574
            (_, ProxyType::Any) => false,
575
            _ => false,
576
        }
577
    }
578
}
579

            
580
impl pallet_proxy::Config for Runtime {
581
    type RuntimeEvent = RuntimeEvent;
582
    type RuntimeCall = RuntimeCall;
583
    type Currency = Balances;
584
    type ProxyType = ProxyType;
585
    // One storage item; key size 32, value size 8
586
    type ProxyDepositBase = ConstU128<{ deposit(1, 8) }>;
587
    // Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
588
    type ProxyDepositFactor = ConstU128<{ deposit(0, 33) }>;
589
    type MaxProxies = ConstU32<32>;
590
    type MaxPending = ConstU32<32>;
591
    type CallHasher = BlakeTwo256;
592
    type AnnouncementDepositBase = ConstU128<{ deposit(1, 8) }>;
593
    // Additional storage item size of 68 bytes:
594
    // - 32 bytes AccountId
595
    // - 32 bytes Hasher (Blake2256)
596
    // - 4 bytes BlockNumber (u32)
597
    type AnnouncementDepositFactor = ConstU128<{ deposit(0, 68) }>;
598
    type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
599
    type BlockNumberProvider = System;
600
}
601

            
602
pub struct XcmExecutionManager;
603
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
604
    fn suspend_xcm_execution() -> DispatchResult {
605
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
606
    }
607
    fn resume_xcm_execution() -> DispatchResult {
608
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
609
    }
610
}
611

            
612
impl pallet_migrations::Config for Runtime {
613
    type RuntimeEvent = RuntimeEvent;
614
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
615
    type XcmExecutionManager = XcmExecutionManager;
616
}
617

            
618
parameter_types! {
619
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
620
}
621

            
622
impl pallet_multiblock_migrations::Config for Runtime {
623
    type RuntimeEvent = RuntimeEvent;
624
    #[cfg(not(feature = "runtime-benchmarks"))]
625
    type Migrations = ();
626
    // Benchmarks need mocked migrations to guarantee that they succeed.
627
    #[cfg(feature = "runtime-benchmarks")]
628
    type Migrations = pallet_multiblock_migrations::mock_helpers::MockedMigrations;
629
    type CursorMaxLen = ConstU32<65_536>;
630
    type IdentifierMaxLen = ConstU32<256>;
631
    type MigrationStatusHandler = ();
632
    type FailedMigrationHandler = MaintenanceMode;
633
    type MaxServiceWeight = MbmServiceWeight;
634
    type WeightInfo = weights::pallet_multiblock_migrations::SubstrateWeight<Runtime>;
635
}
636

            
637
/// Maintenance mode Call filter
638
pub struct MaintenanceFilter;
639
impl Contains<RuntimeCall> for MaintenanceFilter {
640
    fn contains(c: &RuntimeCall) -> bool {
641
        !matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
642
    }
643
}
644

            
645
/// Normal Call Filter
646
/// We dont allow to create nor mint assets, this for now is disabled
647
/// We only allow transfers. For now creation of assets will go through
648
/// asset-manager, while minting/burning only happens through xcm messages
649
/// This can change in the future
650
pub struct NormalFilter;
651
impl Contains<RuntimeCall> for NormalFilter {
652
1280
    fn contains(_c: &RuntimeCall) -> bool {
653
1280
        true
654
1280
    }
655
}
656

            
657
impl pallet_maintenance_mode::Config for Runtime {
658
    type RuntimeEvent = RuntimeEvent;
659
    type NormalCallFilter = NormalFilter;
660
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
661
    type MaintenanceOrigin = EnsureRoot<AccountId>;
662
    type XcmExecutionManager = XcmExecutionManager;
663
}
664

            
665
impl pallet_root_testing::Config for Runtime {
666
    type RuntimeEvent = RuntimeEvent;
667
}
668

            
669
impl pallet_tx_pause::Config for Runtime {
670
    type RuntimeEvent = RuntimeEvent;
671
    type RuntimeCall = RuntimeCall;
672
    type PauseOrigin = EnsureRoot<AccountId>;
673
    type UnpauseOrigin = EnsureRoot<AccountId>;
674
    type WhitelistedCalls = ();
675
    type MaxNameLen = ConstU32<256>;
676
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
677
}
678

            
679
impl dp_impl_tanssi_pallets_config::Config for Runtime {
680
    const SLOT_DURATION: u64 = SLOT_DURATION;
681
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
682
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
683
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
684
}
685

            
686
parameter_types! {
687
    // One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
688
    pub const DepositBase: Balance = currency::deposit(1, 88);
689
    // Additional storage item size of 32 bytes.
690
    pub const DepositFactor: Balance = currency::deposit(0, 32);
691
    pub const MaxSignatories: u32 = 100;
692
}
693

            
694
impl pallet_multisig::Config for Runtime {
695
    type RuntimeEvent = RuntimeEvent;
696
    type RuntimeCall = RuntimeCall;
697
    type Currency = Balances;
698
    type DepositBase = DepositBase;
699
    type DepositFactor = DepositFactor;
700
    type MaxSignatories = MaxSignatories;
701
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
702
    type BlockNumberProvider = System;
703
}
704

            
705
impl frame_system::offchain::SigningTypes for Runtime {
706
    type Public = <Signature as sp_runtime::traits::Verify>::Signer;
707
    type Signature = Signature;
708
}
709

            
710
/// Submits a transaction with the node's public and signature type. Adheres to the signed extension
711
/// format of the chain.
712
impl<LocalCall> frame_system::offchain::CreateSignedTransaction<LocalCall> for Runtime
713
where
714
    RuntimeCall: From<LocalCall>,
715
{
716
    fn create_signed_transaction<
717
        C: frame_system::offchain::AppCrypto<Self::Public, Self::Signature>,
718
    >(
719
        call: RuntimeCall,
720
        public: <Signature as Verify>::Signer,
721
        account: AccountId,
722
        nonce: <Runtime as frame_system::Config>::Nonce,
723
    ) -> Option<UncheckedExtrinsic> {
724
        use sp_runtime::traits::StaticLookup;
725
        // take the biggest period possible.
726
        let period = u64::from(
727
            BlockHashCount::get()
728
                .checked_next_power_of_two()
729
                .map(|c| c / 2)
730
                .unwrap_or(2),
731
        );
732

            
733
        let current_block = System::block_number()
734
            .saturated_into::<u64>()
735
            // The `System::block_number` is initialized with `n+1`,
736
            // so the actual block number is `n`.
737
            .saturating_sub(1);
738
        let tip = 0;
739
        let tx_ext = TxExtension::new((
740
            frame_system::CheckNonZeroSender::<Runtime>::new(),
741
            frame_system::CheckSpecVersion::<Runtime>::new(),
742
            frame_system::CheckTxVersion::<Runtime>::new(),
743
            frame_system::CheckGenesis::<Runtime>::new(),
744
            frame_system::CheckMortality::<Runtime>::from(generic::Era::mortal(
745
                period,
746
                current_block,
747
            )),
748
            frame_system::CheckNonce::<Runtime>::from(nonce),
749
            frame_system::CheckWeight::<Runtime>::new(),
750
            pallet_transaction_payment::ChargeTransactionPayment::<Runtime>::from(tip),
751
            //frame_metadata_hash_extension::CheckMetadataHash::new(true),
752
        ));
753
        let raw_payload = SignedPayload::new(call, tx_ext)
754
            .map_err(|e| {
755
                log::warn!("Unable to create signed payload: {:?}", e);
756
            })
757
            .ok()?;
758
        let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?;
759
        let (call, tx_ext, _) = raw_payload.deconstruct();
760
        let address = <Runtime as frame_system::Config>::Lookup::unlookup(account);
761
        let transaction = UncheckedExtrinsic::new_signed(call, address, signature, tx_ext);
762
        Some(transaction)
763
    }
764
}
765

            
766
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
767
where
768
    RuntimeCall: From<C>,
769
{
770
    type Extrinsic = UncheckedExtrinsic;
771
    type RuntimeCall = RuntimeCall;
772
}
773

            
774
impl<LocalCall> frame_system::offchain::CreateInherent<LocalCall> for Runtime
775
where
776
    RuntimeCall: From<LocalCall>,
777
{
778
    fn create_inherent(call: RuntimeCall) -> UncheckedExtrinsic {
779
        UncheckedExtrinsic::new_bare(call)
780
    }
781
}
782

            
783
impl pallet_ocw_testing::Config for Runtime {
784
    type RuntimeEvent = RuntimeEvent;
785
    type UnsignedInterval = ConstU32<6>;
786
}
787

            
788
impl cumulus_pallet_weight_reclaim::Config for Runtime {
789
    type WeightInfo = weights::cumulus_pallet_weight_reclaim::SubstrateWeight<Runtime>;
790
}
791

            
792
impl_tanssi_pallets_config!(Runtime);
793

            
794
// Create the runtime by composing the FRAME pallets that were previously configured.
795
21339
construct_runtime!(
796
21339
    pub enum Runtime
797
21339
    {
798
21339
        // System support stuff.
799
21339
        System: frame_system = 0,
800
21339
        ParachainSystem: cumulus_pallet_parachain_system = 1,
801
21339
        Timestamp: pallet_timestamp = 2,
802
21339
        ParachainInfo: parachain_info = 3,
803
21339
        Sudo: pallet_sudo = 4,
804
21339
        Utility: pallet_utility = 5,
805
21339
        Proxy: pallet_proxy = 6,
806
21339
        Migrations: pallet_migrations = 7,
807
21339
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
808
21339
        MaintenanceMode: pallet_maintenance_mode = 8,
809
21339
        TxPause: pallet_tx_pause = 9,
810
21339

            
811
21339
        // Monetary stuff.
812
21339
        Balances: pallet_balances = 10,
813
21339
        TransactionPayment: pallet_transaction_payment = 11,
814
21339

            
815
21339
        // Other utilities
816
21339
        Multisig: pallet_multisig = 16,
817
21339

            
818
21339
        // ContainerChain Author Verification
819
21339
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
820
21339
        AuthorInherent: pallet_author_inherent = 51,
821
21339

            
822
21339
        // XCM
823
21339
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
824
21339
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
825
21339
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
826
21339
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
827
21339
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
828
21339
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
829
21339
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
830
21339
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
831
21339

            
832
21339
        WeightReclaim: cumulus_pallet_weight_reclaim = 80,
833
21339

            
834
21339
        RootTesting: pallet_root_testing = 100,
835
21339
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
836
21339

            
837
21339
        OffchainWorker: pallet_ocw_testing::{Pallet, Call, Storage, Event<T>, ValidateUnsigned} = 120,
838
21339
    }
839
21339
);
840

            
841
#[cfg(feature = "runtime-benchmarks")]
842
mod benches {
843
    frame_benchmarking::define_benchmarks!(
844
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
845
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
846
        [cumulus_pallet_parachain_system, ParachainSystem]
847
        [pallet_timestamp, Timestamp]
848
        [pallet_sudo, Sudo]
849
        [pallet_utility, Utility]
850
        [pallet_proxy, Proxy]
851
        [pallet_tx_pause, TxPause]
852
        [pallet_transaction_payment, TransactionPayment]
853
        [pallet_balances, Balances]
854
        [pallet_multiblock_migrations, MultiBlockMigrations]
855
        [pallet_multisig, Multisig]
856
        [pallet_cc_authorities_noting, AuthoritiesNoting]
857
        [pallet_author_inherent, AuthorInherent]
858
        [cumulus_pallet_xcmp_queue, XcmpQueue]
859
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
860
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
861
        [pallet_message_queue, MessageQueue]
862
        [pallet_assets, ForeignAssets]
863
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
864
        [pallet_asset_rate, AssetRate]
865
        [pallet_xcm_executor_utils, XcmExecutorUtils]
866
        [cumulus_pallet_weight_reclaim, WeightReclaim]
867
    );
868
}
869

            
870
5274
impl_runtime_apis! {
871
5274
    impl sp_api::Core<Block> for Runtime {
872
5274
        fn version() -> RuntimeVersion {
873
5274
            VERSION
874
5274
        }
875
5274

            
876
5274
        fn execute_block(block: Block) {
877
5274
            Executive::execute_block(block)
878
5274
        }
879
5274

            
880
5274
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
881
5274
            Executive::initialize_block(header)
882
5274
        }
883
5274
    }
884
5274

            
885
5274
    impl sp_api::Metadata<Block> for Runtime {
886
5274
        fn metadata() -> OpaqueMetadata {
887
5274
            OpaqueMetadata::new(Runtime::metadata().into())
888
5274
        }
889
5274

            
890
5274
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
891
5274
            Runtime::metadata_at_version(version)
892
5274
        }
893
5274

            
894
5274
        fn metadata_versions() -> Vec<u32> {
895
5274
            Runtime::metadata_versions()
896
5274
        }
897
5274
    }
898
5274

            
899
5274
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
900
5274
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
901
5274
            Executive::apply_extrinsic(extrinsic)
902
5274
        }
903
5274

            
904
5274
        fn finalize_block() -> <Block as BlockT>::Header {
905
5274
            Executive::finalize_block()
906
5274
        }
907
5274

            
908
5274
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
909
5274
            data.create_extrinsics()
910
5274
        }
911
5274

            
912
5274
        fn check_inherents(
913
5274
            block: Block,
914
5274
            data: sp_inherents::InherentData,
915
5274
        ) -> sp_inherents::CheckInherentsResult {
916
5274
            data.check_extrinsics(&block)
917
5274
        }
918
5274
    }
919
5274

            
920
5274
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
921
5274
        fn validate_transaction(
922
5274
            source: TransactionSource,
923
5274
            tx: <Block as BlockT>::Extrinsic,
924
5274
            block_hash: <Block as BlockT>::Hash,
925
5274
        ) -> TransactionValidity {
926
5274
            Executive::validate_transaction(source, tx, block_hash)
927
5274
        }
928
5274
    }
929
5274

            
930
5274
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
931
5274
        fn offchain_worker(header: &<Block as BlockT>::Header) {
932
5274
            Executive::offchain_worker(header)
933
5274
        }
934
5274
    }
935
5274

            
936
5274
    impl sp_session::SessionKeys<Block> for Runtime {
937
5274
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
938
5274
            SessionKeys::generate(seed)
939
5274
        }
940
5274

            
941
5274
        fn decode_session_keys(
942
5274
            encoded: Vec<u8>,
943
5274
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
944
5274
            SessionKeys::decode_into_raw_public_keys(&encoded)
945
5274
        }
946
5274
    }
947
5274

            
948
5274
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
949
5274
        fn account_nonce(account: AccountId) -> Index {
950
5274
            System::account_nonce(account)
951
5274
        }
952
5274
    }
953
5274

            
954
5274
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
955
5274
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
956
5274
            ParachainSystem::collect_collation_info(header)
957
5274
        }
958
5274
    }
959
5274

            
960
5274
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
961
5274
        fn can_build_upon(
962
5274
            included_hash: <Block as BlockT>::Hash,
963
5274
            slot: async_backing_primitives::Slot,
964
5274
        ) -> bool {
965
5274
            ConsensusHook::can_build_upon(included_hash, slot)
966
5274
        }
967
5274
    }
968
5274

            
969
5274
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
970
5274
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
971
5274
            build_state::<RuntimeGenesisConfig>(config)
972
5274
        }
973
5274

            
974
5274
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
975
5274
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
976
5274
        }
977
5274
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
978
5274
            vec![]
979
5274
        }
980
5274
    }
981
5274

            
982
5274
    #[cfg(feature = "runtime-benchmarks")]
983
5274
    impl frame_benchmarking::Benchmark<Block> for Runtime {
984
5274
        fn benchmark_metadata(
985
5274
            extra: bool,
986
5274
        ) -> (
987
5274
            Vec<frame_benchmarking::BenchmarkList>,
988
5274
            Vec<frame_support::traits::StorageInfo>,
989
5274
        ) {
990
5274
            use frame_benchmarking::{BenchmarkList};
991
5274
            use frame_support::traits::StorageInfoTrait;
992
5274
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
993
5274

            
994
5274
            let mut list = Vec::<BenchmarkList>::new();
995
5274
            list_benchmarks!(list, extra);
996
5274

            
997
5274
            let storage_info = AllPalletsWithSystem::storage_info();
998
5274
            (list, storage_info)
999
5274
        }
5274

            
5274
        #[allow(non_local_definitions)]
5274
        fn dispatch_benchmark(
5274
            config: frame_benchmarking::BenchmarkConfig,
5274
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
5274
            use frame_benchmarking::{BenchmarkBatch, BenchmarkError};
5274
            use sp_core::storage::TrackedStorageKey;
5274
            use xcm::latest::prelude::*;
5274
            use alloc::boxed::Box;
5274

            
5274
            impl frame_system_benchmarking::Config for Runtime {
5274
                fn setup_set_code_requirements(code: &alloc::vec::Vec<u8>) -> Result<(), BenchmarkError> {
5274
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
5274
                    Ok(())
5274
                }
5274

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

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

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

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

            
5274
                fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
5274
                    tanssi_runtime_common::universal_aliases::AliasingBenchmarksHelper::prepare_universal_alias()
5274
                    .ok_or(BenchmarkError::Skip)
5274
                }
5274

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
5274
            add_benchmarks!(params, batches);
5274

            
5274
            Ok(batches)
5274
        }
5274
    }
5274

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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