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, 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::{IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm},
85
    xcm_runtime_apis::{
86
        dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects},
87
        fees::Error as XcmPaymentApiError,
88
    },
89
};
90

            
91
pub mod xcm_config;
92

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
147
/// Extrinsic type that has already been checked.
148
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, TxExtension>;
149

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

            
159
pub mod currency {
160
    use super::Balance;
161

            
162
    pub const MICROUNIT: Balance = 1_000_000;
163
    pub const MILLIUNIT: Balance = 1_000_000_000;
164
    pub const UNIT: Balance = 1_000_000_000_000;
165
    pub const KILOUNIT: Balance = 1_000_000_000_000_000;
166

            
167
    pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
168

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

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

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

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

            
220
impl_opaque_keys! {
221
    pub struct SessionKeys { }
222
}
223

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

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

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

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

            
253
pub const SUPPLY_FACTOR: Balance = 100;
254

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

            
260
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
261

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

            
266
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
267
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
268

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

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

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

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

            
292
parameter_types! {
293
    pub const Version: RuntimeVersion = VERSION;
294

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

            
322
// Configure FRAME pallets to include in runtime.
323

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

            
379
parameter_types! {
380
    pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
381
}
382

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

            
402
parameter_types! {
403
    pub const TransactionByteFee: Balance = 1;
404
}
405

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

            
417
parameter_types! {
418
    pub ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
419
    pub ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT / 4;
420
    pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
421
}
422

            
423
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
424
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
425
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
426

            
427
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
428
    Runtime,
429
    BLOCK_PROCESSING_VELOCITY,
430
    UNINCLUDED_SEGMENT_CAPACITY,
431
>;
432

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

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

            
456
parameter_types! {
457
    pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
458
}
459

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

            
467
impl parachain_info::Config for Runtime {}
468

            
469
parameter_types! {
470
    pub const Period: u32 = 6 * HOURS;
471
    pub const Offset: u32 = 0;
472
}
473

            
474
impl pallet_sudo::Config for Runtime {
475
    type RuntimeCall = RuntimeCall;
476
    type RuntimeEvent = RuntimeEvent;
477
    type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
478
}
479

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

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

            
517
impl Default for ProxyType {
518
    fn default() -> Self {
519
        Self::Any
520
    }
521
}
522

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

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

            
554
    fn is_superset(&self, o: &Self) -> bool {
555
        match (self, o) {
556
            (x, y) if x == y => true,
557
            (ProxyType::Any, _) => true,
558
            (_, ProxyType::Any) => false,
559
            _ => false,
560
        }
561
    }
562
}
563

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

            
585
pub struct XcmExecutionManager;
586
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
587
    fn suspend_xcm_execution() -> DispatchResult {
588
        XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
589
    }
590
    fn resume_xcm_execution() -> DispatchResult {
591
        XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
592
    }
593
}
594

            
595
impl pallet_migrations::Config for Runtime {
596
    type RuntimeEvent = RuntimeEvent;
597
    type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
598
    type XcmExecutionManager = XcmExecutionManager;
599
}
600

            
601
parameter_types! {
602
    pub MbmServiceWeight: Weight = Perbill::from_percent(80) * RuntimeBlockWeights::get().max_block;
603
}
604

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

            
620
/// Maintenance mode Call filter
621
pub struct MaintenanceFilter;
622
impl Contains<RuntimeCall> for MaintenanceFilter {
623
    fn contains(c: &RuntimeCall) -> bool {
624
        !matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
625
    }
626
}
627

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

            
640
impl pallet_maintenance_mode::Config for Runtime {
641
    type RuntimeEvent = RuntimeEvent;
642
    type NormalCallFilter = NormalFilter;
643
    type MaintenanceCallFilter = InsideBoth<MaintenanceFilter, NormalFilter>;
644
    type MaintenanceOrigin = EnsureRoot<AccountId>;
645
    type XcmExecutionManager = XcmExecutionManager;
646
}
647

            
648
impl pallet_root_testing::Config for Runtime {
649
    type RuntimeEvent = RuntimeEvent;
650
}
651

            
652
impl pallet_tx_pause::Config for Runtime {
653
    type RuntimeEvent = RuntimeEvent;
654
    type RuntimeCall = RuntimeCall;
655
    type PauseOrigin = EnsureRoot<AccountId>;
656
    type UnpauseOrigin = EnsureRoot<AccountId>;
657
    type WhitelistedCalls = ();
658
    type MaxNameLen = ConstU32<256>;
659
    type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
660
}
661

            
662
impl dp_impl_tanssi_pallets_config::Config for Runtime {
663
    const SLOT_DURATION: u64 = SLOT_DURATION;
664
    type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
665
    type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
666
    type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
667
}
668

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

            
677
impl pallet_multisig::Config for Runtime {
678
    type RuntimeEvent = RuntimeEvent;
679
    type RuntimeCall = RuntimeCall;
680
    type Currency = Balances;
681
    type DepositBase = DepositBase;
682
    type DepositFactor = DepositFactor;
683
    type MaxSignatories = MaxSignatories;
684
    type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
685
}
686

            
687
impl frame_system::offchain::SigningTypes for Runtime {
688
    type Public = <Signature as sp_runtime::traits::Verify>::Signer;
689
    type Signature = Signature;
690
}
691

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

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

            
747
impl<C> frame_system::offchain::CreateTransactionBase<C> for Runtime
748
where
749
    RuntimeCall: From<C>,
750
{
751
    type Extrinsic = UncheckedExtrinsic;
752
    type RuntimeCall = RuntimeCall;
753
}
754

            
755
impl<LocalCall> frame_system::offchain::CreateInherent<LocalCall> for Runtime
756
where
757
    RuntimeCall: From<LocalCall>,
758
{
759
    fn create_inherent(call: RuntimeCall) -> UncheckedExtrinsic {
760
        UncheckedExtrinsic::new_bare(call)
761
    }
762
}
763

            
764
impl pallet_ocw_testing::Config for Runtime {
765
    type RuntimeEvent = RuntimeEvent;
766
    type UnsignedInterval = ConstU32<6>;
767
}
768

            
769
impl_tanssi_pallets_config!(Runtime);
770

            
771
// Create the runtime by composing the FRAME pallets that were previously configured.
772
103513
construct_runtime!(
773
18003
    pub enum Runtime
774
18003
    {
775
18003
        // System support stuff.
776
18003
        System: frame_system = 0,
777
18003
        ParachainSystem: cumulus_pallet_parachain_system = 1,
778
18003
        Timestamp: pallet_timestamp = 2,
779
18003
        ParachainInfo: parachain_info = 3,
780
18003
        Sudo: pallet_sudo = 4,
781
18003
        Utility: pallet_utility = 5,
782
18003
        Proxy: pallet_proxy = 6,
783
18003
        Migrations: pallet_migrations = 7,
784
18003
        MultiBlockMigrations: pallet_multiblock_migrations = 121,
785
18003
        MaintenanceMode: pallet_maintenance_mode = 8,
786
18003
        TxPause: pallet_tx_pause = 9,
787
18003

            
788
18003
        // Monetary stuff.
789
18003
        Balances: pallet_balances = 10,
790
18003
        TransactionPayment: pallet_transaction_payment = 11,
791
18003

            
792
18003
        // Other utilities
793
18003
        Multisig: pallet_multisig = 16,
794
18003

            
795
18003
        // ContainerChain Author Verification
796
18003
        AuthoritiesNoting: pallet_cc_authorities_noting = 50,
797
18003
        AuthorInherent: pallet_author_inherent = 51,
798
18003

            
799
18003
        // XCM
800
18003
        XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
801
18003
        CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
802
18003
        PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
803
18003
        MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
804
18003
        ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
805
18003
        ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
806
18003
        AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
807
18003
        XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
808
18003

            
809
18003
        RootTesting: pallet_root_testing = 100,
810
18003
        AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
811
18003

            
812
18003
        OffchainWorker: pallet_ocw_testing::{Pallet, Call, Storage, Event<T>, ValidateUnsigned} = 120,
813
18003
    }
814
105278
);
815

            
816
#[cfg(feature = "runtime-benchmarks")]
817
mod benches {
818
    frame_benchmarking::define_benchmarks!(
819
        [frame_system, frame_system_benchmarking::Pallet::<Runtime>]
820
        [frame_system_extensions, frame_system_benchmarking::extensions::Pallet::<Runtime>]
821
        [cumulus_pallet_parachain_system, ParachainSystem]
822
        [pallet_timestamp, Timestamp]
823
        [pallet_sudo, Sudo]
824
        [pallet_utility, Utility]
825
        [pallet_proxy, Proxy]
826
        [pallet_tx_pause, TxPause]
827
        [pallet_transaction_payment, TransactionPayment]
828
        [pallet_balances, Balances]
829
        [pallet_multiblock_migrations, MultiBlockMigrations]
830
        [pallet_multisig, Multisig]
831
        [pallet_cc_authorities_noting, AuthoritiesNoting]
832
        [pallet_author_inherent, AuthorInherent]
833
        [cumulus_pallet_xcmp_queue, XcmpQueue]
834
        [pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
835
        [pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
836
        [pallet_message_queue, MessageQueue]
837
        [pallet_assets, ForeignAssets]
838
        [pallet_foreign_asset_creator, ForeignAssetsCreator]
839
        [pallet_asset_rate, AssetRate]
840
        [pallet_xcm_executor_utils, XcmExecutorUtils]
841
    );
842
}
843

            
844
7170
impl_runtime_apis! {
845
5088
    impl sp_api::Core<Block> for Runtime {
846
5088
        fn version() -> RuntimeVersion {
847
5088
            VERSION
848
5088
        }
849
5088

            
850
5088
        fn execute_block(block: Block) {
851
5088
            Executive::execute_block(block)
852
5088
        }
853
5088

            
854
5088
        fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
855
5088
            Executive::initialize_block(header)
856
5088
        }
857
5088
    }
858
5088

            
859
5088
    impl sp_api::Metadata<Block> for Runtime {
860
5088
        fn metadata() -> OpaqueMetadata {
861
5088
            OpaqueMetadata::new(Runtime::metadata().into())
862
5088
        }
863
5088

            
864
5088
        fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
865
5088
            Runtime::metadata_at_version(version)
866
5088
        }
867
5088

            
868
5088
        fn metadata_versions() -> Vec<u32> {
869
5088
            Runtime::metadata_versions()
870
5088
        }
871
5088
    }
872
5088

            
873
5088
    impl sp_block_builder::BlockBuilder<Block> for Runtime {
874
5088
        fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
875
5088
            Executive::apply_extrinsic(extrinsic)
876
5088
        }
877
5088

            
878
5088
        fn finalize_block() -> <Block as BlockT>::Header {
879
5088
            Executive::finalize_block()
880
5088
        }
881
5088

            
882
5088
        fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
883
5088
            data.create_extrinsics()
884
5088
        }
885
5088

            
886
5088
        fn check_inherents(
887
5088
            block: Block,
888
5088
            data: sp_inherents::InherentData,
889
5088
        ) -> sp_inherents::CheckInherentsResult {
890
5088
            data.check_extrinsics(&block)
891
5088
        }
892
5088
    }
893
5088

            
894
5088
    impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
895
5088
        fn validate_transaction(
896
5088
            source: TransactionSource,
897
5088
            tx: <Block as BlockT>::Extrinsic,
898
5088
            block_hash: <Block as BlockT>::Hash,
899
5088
        ) -> TransactionValidity {
900
5088
            Executive::validate_transaction(source, tx, block_hash)
901
5088
        }
902
5088
    }
903
5088

            
904
5088
    impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
905
5088
        fn offchain_worker(header: &<Block as BlockT>::Header) {
906
5088
            Executive::offchain_worker(header)
907
5088
        }
908
5088
    }
909
5088

            
910
5088
    impl sp_session::SessionKeys<Block> for Runtime {
911
5088
        fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
912
5088
            SessionKeys::generate(seed)
913
5088
        }
914
5088

            
915
5088
        fn decode_session_keys(
916
5088
            encoded: Vec<u8>,
917
5088
        ) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
918
5088
            SessionKeys::decode_into_raw_public_keys(&encoded)
919
5088
        }
920
5088
    }
921
5088

            
922
5088
    impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
923
5088
        fn account_nonce(account: AccountId) -> Index {
924
5088
            System::account_nonce(account)
925
5088
        }
926
5088
    }
927
5088

            
928
5088
    impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
929
5088
        fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
930
5088
            ParachainSystem::collect_collation_info(header)
931
5088
        }
932
5088
    }
933
5088

            
934
5088
    impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
935
5088
        fn can_build_upon(
936
5088
            included_hash: <Block as BlockT>::Hash,
937
5088
            slot: async_backing_primitives::Slot,
938
5088
        ) -> bool {
939
5088
            ConsensusHook::can_build_upon(included_hash, slot)
940
5088
        }
941
5088
    }
942
5088

            
943
5088
    impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
944
5088
        fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
945
5088
            build_state::<RuntimeGenesisConfig>(config)
946
5088
        }
947
5088

            
948
5088
        fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
949
5088
            get_preset::<RuntimeGenesisConfig>(id, |_| None)
950
5088
        }
951
5088
        fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
952
5088
            vec![]
953
5088
        }
954
5088
    }
955
5088

            
956
5088
    #[cfg(feature = "runtime-benchmarks")]
957
5088
    impl frame_benchmarking::Benchmark<Block> for Runtime {
958
5088
        fn benchmark_metadata(
959
5088
            extra: bool,
960
5088
        ) -> (
961
5088
            Vec<frame_benchmarking::BenchmarkList>,
962
5088
            Vec<frame_support::traits::StorageInfo>,
963
5088
        ) {
964
5088
            use frame_benchmarking::{Benchmarking, BenchmarkList};
965
5088
            use frame_support::traits::StorageInfoTrait;
966
5088
            use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
967
5088

            
968
5088
            let mut list = Vec::<BenchmarkList>::new();
969
5088
            list_benchmarks!(list, extra);
970
5088

            
971
5088
            let storage_info = AllPalletsWithSystem::storage_info();
972
5088
            (list, storage_info)
973
5088
        }
974
5088

            
975
5088
        fn dispatch_benchmark(
976
5088
            config: frame_benchmarking::BenchmarkConfig,
977
5088
        ) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, alloc::string::String> {
978
5088
            use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
979
5088
            use sp_core::storage::TrackedStorageKey;
980
5088
            use xcm::latest::prelude::*;
981
5088
            impl frame_system_benchmarking::Config for Runtime {
982
5088
                fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
983
5088
                    ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
984
5088
                    Ok(())
985
5088
                }
986
5088

            
987
5088
                fn verify_set_code() {
988
5088
                    System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
989
5088
                }
990
5088
            }
991
5088
            use crate::xcm_config::SelfReserve;
992
5088
            parameter_types! {
993
5088
                pub ExistentialDepositAsset: Option<Asset> = Some((
994
5088
                    SelfReserve::get(),
995
5088
                    ExistentialDeposit::get()
996
5088
                ).into());
997
5088
            }
998
5088

            
999
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<CallDryRunEffects<RuntimeEvent>, XcmDryRunApiError> {
5088
            PolkadotXcm::dry_run_call::<Runtime, xcm_config::XcmRouter, OriginCaller, RuntimeCall>(origin, call)
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>,
}