-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathlib.rs
More file actions
1221 lines (1058 loc) · 46.9 KB
/
lib.rs
File metadata and controls
1221 lines (1058 loc) · 46.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) Moondance Labs Ltd.
// This file is part of Tanssi.
// Tanssi is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Tanssi is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Tanssi. If not, see <http://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]
// `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256.
#![recursion_limit = "256"]
// Make the WASM binary available.
#[cfg(feature = "std")]
include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs"));
use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases;
#[cfg(feature = "std")]
use sp_version::NativeVersion;
#[cfg(any(feature = "std", test))]
pub use sp_runtime::BuildStorage;
pub mod migrations;
pub mod weights;
pub use sp_runtime::{MultiAddress, Perbill, Permill};
use {
cumulus_primitives_core::AggregateMessageOrigin,
dp_impl_tanssi_pallets_config::impl_tanssi_pallets_config,
frame_support::{
construct_runtime,
dispatch::DispatchClass,
genesis_builder_helper::{build_state, get_preset},
pallet_prelude::DispatchResult,
parameter_types,
traits::{
tokens::ConversionToAssetBalance, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8,
Contains, InsideBoth, InstanceFilter,
},
weights::{
constants::{
BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight,
WEIGHT_REF_TIME_PER_SECOND,
},
ConstantMultiplier, Weight, WeightToFee as _, WeightToFeeCoefficient,
WeightToFeeCoefficients, WeightToFeePolynomial,
},
},
frame_system::{
limits::{BlockLength, BlockWeights},
EnsureRoot,
},
nimbus_primitives::{NimbusId, SlotBeacon},
pallet_transaction_payment::FungibleAdapter,
parity_scale_codec::{Decode, Encode},
polkadot_runtime_common::SlowAdjustingFeeUpdate,
scale_info::TypeInfo,
smallvec::smallvec,
sp_api::impl_runtime_apis,
sp_consensus_slots::{Slot, SlotDuration},
sp_core::{MaxEncodedLen, OpaqueMetadata},
sp_runtime::{
create_runtime_str, generic, impl_opaque_keys,
traits::{AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, Verify},
transaction_validity::{TransactionSource, TransactionValidity},
ApplyExtrinsicResult, MultiSignature,
},
sp_std::prelude::*,
sp_version::RuntimeVersion,
staging_xcm::{
IntoVersion, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm,
},
xcm_fee_payment_runtime_api::Error as XcmPaymentApiError,
};
pub mod xcm_config;
// Polkadot imports
use polkadot_runtime_common::BlockHashCount;
/// Alias to 512-bit hash when used in the context of a transaction signature on the chain.
pub type Signature = MultiSignature;
/// Some way of identifying an account on the chain. We intentionally make it equivalent
/// to the public key of our transaction signing scheme.
pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;
/// Balance of an account.
pub type Balance = u128;
/// Index of a transaction in the chain.
pub type Index = u32;
/// A hash of some data used by the chain.
pub type Hash = sp_core::H256;
/// An index to a block.
pub type BlockNumber = u32;
/// The address format for describing accounts.
pub type Address = MultiAddress<AccountId, ()>;
/// Block header type as expected by this runtime.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Block type as expected by this runtime.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// A Block signed with a Justification
pub type SignedBlock = generic::SignedBlock<Block>;
/// BlockId type as expected by this runtime.
pub type BlockId = generic::BlockId<Block>;
/// The SignedExtension to the basic transaction logic.
pub type SignedExtra = (
frame_system::CheckNonZeroSender<Runtime>,
frame_system::CheckSpecVersion<Runtime>,
frame_system::CheckTxVersion<Runtime>,
frame_system::CheckGenesis<Runtime>,
frame_system::CheckEra<Runtime>,
frame_system::CheckNonce<Runtime>,
frame_system::CheckWeight<Runtime>,
pallet_transaction_payment::ChargeTransactionPayment<Runtime>,
cumulus_primitives_storage_weight_reclaim::StorageWeightReclaim<Runtime>,
);
/// Unchecked extrinsic type as expected by this runtime.
pub type UncheckedExtrinsic =
generic::UncheckedExtrinsic<Address, RuntimeCall, Signature, SignedExtra>;
/// Extrinsic type that has already been checked.
pub type CheckedExtrinsic = generic::CheckedExtrinsic<AccountId, RuntimeCall, SignedExtra>;
/// Executive: handles dispatch to the various modules.
pub type Executive = frame_executive::Executive<
Runtime,
Block,
frame_system::ChainContext<Runtime>,
Runtime,
AllPalletsWithSystem,
>;
pub mod currency {
use super::Balance;
pub const MICROUNIT: Balance = 1_000_000;
pub const MILLIUNIT: Balance = 1_000_000_000;
pub const UNIT: Balance = 1_000_000_000_000;
pub const KILOUNIT: Balance = 1_000_000_000_000_000;
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT;
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 100 * MILLIUNIT + (bytes as Balance) * STORAGE_BYTE_FEE
}
}
/// Handles converting a weight scalar to a fee value, based on the scale and granularity of the
/// node's balance type.
///
/// This should typically create a mapping between the following ranges:
/// - `[0, MAXIMUM_BLOCK_WEIGHT]`
/// - `[Balance::min, Balance::max]`
///
/// Yet, it can be used for any other sort of change to weight-fee. Some examples being:
/// - Setting it to `0` will essentially disable the weight fee.
/// - Setting it to `1` will cause the literal `#[weight = x]` values to be charged.
pub struct WeightToFee;
impl WeightToFeePolynomial for WeightToFee {
type Balance = Balance;
fn polynomial() -> WeightToFeeCoefficients<Self::Balance> {
// in Rococo, extrinsic base weight (smallest non-zero weight) is mapped to 1 MILLIUNIT:
// in our template, we map to 1/10 of that, or 1/10 MILLIUNIT
let p = MILLIUNIT / 10;
let q = 100 * Balance::from(ExtrinsicBaseWeight::get().ref_time());
smallvec![WeightToFeeCoefficient {
degree: 1,
negative: false,
coeff_frac: Perbill::from_rational(p % q, q),
coeff_integer: p / q,
}]
}
}
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
/// the specifics of the runtime. They can then be made to be agnostic over specific formats
/// of data like extrinsics, allowing for them to continue syncing the network through upgrades
/// to even the core data structures.
pub mod opaque {
use {
super::*,
sp_runtime::{generic, traits::BlakeTwo256},
};
pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic;
/// Opaque block header type.
pub type Header = generic::Header<BlockNumber, BlakeTwo256>;
/// Opaque block type.
pub type Block = generic::Block<Header, UncheckedExtrinsic>;
/// Opaque block identifier type.
pub type BlockId = generic::BlockId<Block>;
}
impl_opaque_keys! {
pub struct SessionKeys { }
}
#[sp_version::runtime_version]
pub const VERSION: RuntimeVersion = RuntimeVersion {
spec_name: create_runtime_str!("container-chain-template"),
impl_name: create_runtime_str!("container-chain-template"),
authoring_version: 1,
spec_version: 800,
impl_version: 0,
apis: RUNTIME_API_VERSIONS,
transaction_version: 1,
state_version: 1,
};
/// This determines the average expected block time that we are targeting.
/// Blocks will be produced at a minimum duration defined by `SLOT_DURATION`.
/// `SLOT_DURATION` is picked up by `pallet_timestamp` which is in turn picked
/// up by `pallet_aura` to implement `fn slot_duration()`.
///
/// Change this to adjust the block time.
pub const MILLISECS_PER_BLOCK: u64 = 6000;
// NOTE: Currently it is not possible to change the slot duration after the chain has started.
// Attempting to do so will brick block production.
pub const SLOT_DURATION: u64 = MILLISECS_PER_BLOCK;
// Time is measured by number of blocks.
pub const MINUTES: BlockNumber = 60_000 / (MILLISECS_PER_BLOCK as BlockNumber);
pub const HOURS: BlockNumber = MINUTES * 60;
pub const DAYS: BlockNumber = HOURS * 24;
pub const SUPPLY_FACTOR: Balance = 100;
// Unit = the base number of indivisible units for balances
pub const UNIT: Balance = 1_000_000_000_000;
pub const MILLIUNIT: Balance = 1_000_000_000;
pub const MICROUNIT: Balance = 1_000_000;
pub const STORAGE_BYTE_FEE: Balance = 100 * MICROUNIT * SUPPLY_FACTOR;
pub const fn deposit(items: u32, bytes: u32) -> Balance {
items as Balance * 100 * MILLIUNIT * SUPPLY_FACTOR + (bytes as Balance) * STORAGE_BYTE_FEE
}
/// The existential deposit. Set to 1/10 of the Connected Relay Chain.
pub const EXISTENTIAL_DEPOSIT: Balance = MILLIUNIT;
/// We assume that ~5% of the block weight is consumed by `on_initialize` handlers. This is
/// used to limit the maximal weight of a single extrinsic.
const AVERAGE_ON_INITIALIZE_RATIO: Perbill = Perbill::from_percent(5);
/// We allow `Normal` extrinsics to fill up the block up to 75%, the rest can be used by
/// `Operational` extrinsics.
const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75);
/// We allow for 0.5 of a second of compute with a 12 second average block time.
const MAXIMUM_BLOCK_WEIGHT: Weight = Weight::from_parts(
WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
cumulus_primitives_core::relay_chain::MAX_POV_SIZE as u64,
);
/// The version information used to identify this runtime when compiled natively.
#[cfg(feature = "std")]
pub fn native_version() -> NativeVersion {
NativeVersion {
runtime_version: VERSION,
can_author_with: Default::default(),
}
}
parameter_types! {
pub const Version: RuntimeVersion = VERSION;
// This part is copied from Substrate's `bin/node/runtime/src/lib.rs`.
// The `RuntimeBlockLength` and `RuntimeBlockWeights` exist here because the
// `DeletionWeightLimit` and `DeletionQueueDepth` depend on those to parameterize
// the lazy contract deletion.
pub RuntimeBlockLength: BlockLength =
BlockLength::max_with_normal_ratio(5 * 1024 * 1024, NORMAL_DISPATCH_RATIO);
pub RuntimeBlockWeights: BlockWeights = BlockWeights::builder()
.base_block(BlockExecutionWeight::get())
.for_class(DispatchClass::all(), |weights| {
weights.base_extrinsic = ExtrinsicBaseWeight::get();
})
.for_class(DispatchClass::Normal, |weights| {
weights.max_total = Some(NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT);
})
.for_class(DispatchClass::Operational, |weights| {
weights.max_total = Some(MAXIMUM_BLOCK_WEIGHT);
// Operational transactions have some extra reserved space, so that they
// are included even if block reached `MAXIMUM_BLOCK_WEIGHT`.
weights.reserved = Some(
MAXIMUM_BLOCK_WEIGHT - NORMAL_DISPATCH_RATIO * MAXIMUM_BLOCK_WEIGHT
);
})
.avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO)
.build_or_panic();
pub const SS58Prefix: u16 = 42;
}
// Configure FRAME pallets to include in runtime.
impl frame_system::Config for Runtime {
/// The identifier used to distinguish between accounts.
type AccountId = AccountId;
/// The aggregated dispatch type that is available for extrinsics.
type RuntimeCall = RuntimeCall;
/// The lookup mechanism to get account ID from whatever is passed in dispatchers.
type Lookup = AccountIdLookup<AccountId, ()>;
/// The index type for storing how many extrinsics an account has signed.
type Nonce = Index;
/// The index type for blocks.
type Block = Block;
/// The type for hashing blocks and tries.
type Hash = Hash;
/// The hashing algorithm used.
type Hashing = BlakeTwo256;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
/// The ubiquitous origin type.
type RuntimeOrigin = RuntimeOrigin;
/// Maximum number of block number to block hash mappings to keep (oldest pruned first).
type BlockHashCount = BlockHashCount;
/// Runtime version.
type Version = Version;
/// Converts a module to an index of this module in the runtime.
type PalletInfo = PalletInfo;
/// The data to be stored in an account.
type AccountData = pallet_balances::AccountData<Balance>;
/// What to do if a new account is created.
type OnNewAccount = ();
/// What to do if an account is fully reaped from the system.
type OnKilledAccount = ();
/// The weight of database operations that the runtime can invoke.
type DbWeight = RocksDbWeight;
/// The basic call filter to use in dispatchable.
type BaseCallFilter = InsideBoth<MaintenanceMode, TxPause>;
/// Weight information for the extrinsics of this pallet.
type SystemWeightInfo = weights::frame_system::SubstrateWeight<Runtime>;
/// Block & extrinsics weights: base values and limits.
type BlockWeights = RuntimeBlockWeights;
/// The maximum length of a block (in bytes).
type BlockLength = RuntimeBlockLength;
/// This is used as an identifier of the chain. 42 is the generic substrate prefix.
type SS58Prefix = SS58Prefix;
/// The action to take on a Runtime Upgrade
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
type RuntimeTask = RuntimeTask;
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
}
parameter_types! {
pub const ExistentialDeposit: Balance = EXISTENTIAL_DEPOSIT;
}
impl pallet_balances::Config for Runtime {
type MaxLocks = ConstU32<50>;
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type MaxReserves = ConstU32<50>;
type ReserveIdentifier = [u8; 8];
type FreezeIdentifier = RuntimeFreezeReason;
type MaxFreezes = ConstU32<0>;
type RuntimeHoldReason = RuntimeHoldReason;
type RuntimeFreezeReason = RuntimeFreezeReason;
type WeightInfo = weights::pallet_balances::SubstrateWeight<Runtime>;
}
parameter_types! {
pub const TransactionByteFee: Balance = 1;
}
impl pallet_transaction_payment::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
// This will burn the fees
type OnChargeTransaction = FungibleAdapter<Balances, ()>;
type OperationalFeeMultiplier = ConstU8<5>;
type WeightToFee = WeightToFee;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const ReservedDmpWeight: Weight = MAXIMUM_BLOCK_WEIGHT.saturating_div(4);
pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
}
pub const RELAY_CHAIN_SLOT_DURATION_MILLIS: u32 = 6000;
pub const UNINCLUDED_SEGMENT_CAPACITY: u32 = 3;
pub const BLOCK_PROCESSING_VELOCITY: u32 = 1;
type ConsensusHook = pallet_async_backing::consensus_hook::FixedVelocityConsensusHook<
Runtime,
BLOCK_PROCESSING_VELOCITY,
UNINCLUDED_SEGMENT_CAPACITY,
>;
impl cumulus_pallet_parachain_system::Config for Runtime {
type WeightInfo = weights::cumulus_pallet_parachain_system::SubstrateWeight<Runtime>;
type RuntimeEvent = RuntimeEvent;
type OnSystemEvent = ();
type OutboundXcmpMessageSource = XcmpQueue;
type SelfParaId = parachain_info::Pallet<Runtime>;
type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
type ReservedDmpWeight = ReservedDmpWeight;
type XcmpMessageHandler = XcmpQueue;
type ReservedXcmpWeight = ReservedXcmpWeight;
type CheckAssociatedRelayNumber = RelayNumberMonotonicallyIncreases;
type ConsensusHook = ConsensusHook;
}
pub struct ParaSlotProvider;
impl sp_core::Get<(Slot, SlotDuration)> for ParaSlotProvider {
fn get() -> (Slot, SlotDuration) {
let slot = u64::from(<Runtime as pallet_author_inherent::Config>::SlotBeacon::slot());
(Slot::from(slot), SlotDuration::from_millis(SLOT_DURATION))
}
}
parameter_types! {
pub const ExpectedBlockTime: u64 = MILLISECS_PER_BLOCK;
}
impl pallet_async_backing::Config for Runtime {
type AllowMultipleBlocksPerSlot = ConstBool<true>;
type GetAndVerifySlot =
pallet_async_backing::ParaSlot<RELAY_CHAIN_SLOT_DURATION_MILLIS, ParaSlotProvider>;
type ExpectedBlockTime = ExpectedBlockTime;
}
impl parachain_info::Config for Runtime {}
parameter_types! {
pub const Period: u32 = 6 * HOURS;
pub const Offset: u32 = 0;
}
impl pallet_sudo::Config for Runtime {
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type WeightInfo = weights::pallet_sudo::SubstrateWeight<Runtime>;
}
impl pallet_utility::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PalletsOrigin = OriginCaller;
type WeightInfo = weights::pallet_utility::SubstrateWeight<Runtime>;
}
/// The type used to represent the kinds of proxying allowed.
#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
#[derive(
Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, Debug, MaxEncodedLen, TypeInfo,
)]
#[allow(clippy::unnecessary_cast)]
pub enum ProxyType {
/// All calls can be proxied. This is the trivial/most permissive filter.
Any = 0,
/// Only extrinsics that do not transfer funds.
NonTransfer = 1,
/// Only extrinsics related to governance (democracy and collectives).
Governance = 2,
/// Allow to veto an announced proxy call.
CancelProxy = 3,
/// Allow extrinsic related to Balances.
Balances = 4,
}
impl Default for ProxyType {
fn default() -> Self {
Self::Any
}
}
impl InstanceFilter<RuntimeCall> for ProxyType {
fn filter(&self, c: &RuntimeCall) -> bool {
// Since proxy filters are respected in all dispatches of the Utility
// pallet, it should never need to be filtered by any proxy.
if let RuntimeCall::Utility(..) = c {
return true;
}
match self {
ProxyType::Any => true,
ProxyType::NonTransfer => {
matches!(
c,
RuntimeCall::System(..)
| RuntimeCall::ParachainSystem(..)
| RuntimeCall::Timestamp(..)
| RuntimeCall::Proxy(..)
)
}
// We don't have governance yet
ProxyType::Governance => false,
ProxyType::CancelProxy => matches!(
c,
RuntimeCall::Proxy(pallet_proxy::Call::reject_announcement { .. })
),
ProxyType::Balances => {
matches!(c, RuntimeCall::Balances(..))
}
}
}
fn is_superset(&self, o: &Self) -> bool {
match (self, o) {
(x, y) if x == y => true,
(ProxyType::Any, _) => true,
(_, ProxyType::Any) => false,
_ => false,
}
}
}
impl pallet_proxy::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type ProxyType = ProxyType;
// One storage item; key size 32, value size 8
type ProxyDepositBase = ConstU128<{ deposit(1, 8) }>;
// Additional storage item size of 33 bytes (32 bytes AccountId + 1 byte sizeof(ProxyType)).
type ProxyDepositFactor = ConstU128<{ deposit(0, 33) }>;
type MaxProxies = ConstU32<32>;
type MaxPending = ConstU32<32>;
type CallHasher = BlakeTwo256;
type AnnouncementDepositBase = ConstU128<{ deposit(1, 8) }>;
// Additional storage item size of 68 bytes:
// - 32 bytes AccountId
// - 32 bytes Hasher (Blake2256)
// - 4 bytes BlockNumber (u32)
type AnnouncementDepositFactor = ConstU128<{ deposit(0, 68) }>;
type WeightInfo = weights::pallet_proxy::SubstrateWeight<Runtime>;
}
pub struct XcmExecutionManager;
impl xcm_primitives::PauseXcmExecution for XcmExecutionManager {
fn suspend_xcm_execution() -> DispatchResult {
XcmpQueue::suspend_xcm_execution(RuntimeOrigin::root())
}
fn resume_xcm_execution() -> DispatchResult {
XcmpQueue::resume_xcm_execution(RuntimeOrigin::root())
}
}
impl pallet_migrations::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type MigrationsList = (migrations::TemplateMigrations<Runtime, XcmpQueue, PolkadotXcm>,);
type XcmExecutionManager = XcmExecutionManager;
}
/// Maintenance mode Call filter
pub struct MaintenanceFilter;
impl Contains<RuntimeCall> for MaintenanceFilter {
fn contains(c: &RuntimeCall) -> bool {
!matches!(c, RuntimeCall::Balances(_) | RuntimeCall::PolkadotXcm(_))
}
}
/// Normal Call Filter
/// We dont allow to create nor mint assets, this for now is disabled
/// We only allow transfers. For now creation of assets will go through
/// asset-manager, while minting/burning only happens through xcm messages
/// This can change in the future
pub struct NormalFilter;
impl Contains<RuntimeCall> for NormalFilter {
fn contains(_c: &RuntimeCall) -> bool {
true
}
}
impl pallet_maintenance_mode::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type NormalCallFilter = NormalFilter;
type MaintenanceCallFilter = MaintenanceFilter;
type MaintenanceOrigin = EnsureRoot<AccountId>;
type XcmExecutionManager = XcmExecutionManager;
}
impl pallet_root_testing::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl pallet_tx_pause::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type PauseOrigin = EnsureRoot<AccountId>;
type UnpauseOrigin = EnsureRoot<AccountId>;
type WhitelistedCalls = ();
type MaxNameLen = ConstU32<256>;
type WeightInfo = weights::pallet_tx_pause::SubstrateWeight<Runtime>;
}
impl dp_impl_tanssi_pallets_config::Config for Runtime {
const SLOT_DURATION: u64 = SLOT_DURATION;
type TimestampWeights = weights::pallet_timestamp::SubstrateWeight<Runtime>;
type AuthorInherentWeights = weights::pallet_author_inherent::SubstrateWeight<Runtime>;
type AuthoritiesNotingWeights = weights::pallet_cc_authorities_noting::SubstrateWeight<Runtime>;
}
parameter_types! {
// One storage item; key size 32; value is size 4+4+16+32. Total = 1 * (32 + 56)
pub const DepositBase: Balance = currency::deposit(1, 88);
// Additional storage item size of 32 bytes.
pub const DepositFactor: Balance = currency::deposit(0, 32);
pub const MaxSignatories: u32 = 100;
}
impl pallet_multisig::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type RuntimeCall = RuntimeCall;
type Currency = Balances;
type DepositBase = DepositBase;
type DepositFactor = DepositFactor;
type MaxSignatories = MaxSignatories;
type WeightInfo = weights::pallet_multisig::SubstrateWeight<Runtime>;
}
impl_tanssi_pallets_config!(Runtime);
// Create the runtime by composing the FRAME pallets that were previously configured.
construct_runtime!(
pub enum Runtime
{
// System support stuff.
System: frame_system = 0,
ParachainSystem: cumulus_pallet_parachain_system = 1,
Timestamp: pallet_timestamp = 2,
ParachainInfo: parachain_info = 3,
Sudo: pallet_sudo = 4,
Utility: pallet_utility = 5,
Proxy: pallet_proxy = 6,
Migrations: pallet_migrations = 7,
MaintenanceMode: pallet_maintenance_mode = 8,
TxPause: pallet_tx_pause = 9,
// Monetary stuff.
Balances: pallet_balances = 10,
TransactionPayment: pallet_transaction_payment = 11,
// Other utilities
Multisig: pallet_multisig = 16,
// ContainerChain Author Verification
AuthoritiesNoting: pallet_cc_authorities_noting = 50,
AuthorInherent: pallet_author_inherent = 51,
// XCM
XcmpQueue: cumulus_pallet_xcmp_queue::{Pallet, Storage, Event<T>} = 70,
CumulusXcm: cumulus_pallet_xcm::{Pallet, Event<T>, Origin} = 71,
DmpQueue: cumulus_pallet_dmp_queue::{Pallet, Call, Storage, Event<T>} = 72,
PolkadotXcm: pallet_xcm::{Pallet, Call, Storage, Event<T>, Origin, Config<T>} = 73,
MessageQueue: pallet_message_queue::{Pallet, Call, Storage, Event<T>} = 74,
ForeignAssets: pallet_assets::<Instance1>::{Pallet, Call, Storage, Event<T>} = 75,
ForeignAssetsCreator: pallet_foreign_asset_creator::{Pallet, Call, Storage, Event<T>} = 76,
AssetRate: pallet_asset_rate::{Pallet, Call, Storage, Event<T>} = 77,
XcmExecutorUtils: pallet_xcm_executor_utils::{Pallet, Call, Storage, Event<T>} = 78,
RootTesting: pallet_root_testing = 100,
AsyncBacking: pallet_async_backing::{Pallet, Storage} = 110,
}
);
#[cfg(feature = "runtime-benchmarks")]
mod benches {
frame_benchmarking::define_benchmarks!(
[frame_system, frame_system_benchmarking::Pallet::<Runtime>]
[cumulus_pallet_parachain_system, ParachainSystem]
[pallet_timestamp, Timestamp]
[pallet_sudo, Sudo]
[pallet_utility, Utility]
[pallet_proxy, Proxy]
[pallet_tx_pause, TxPause]
[pallet_balances, Balances]
[pallet_multisig, Multisig]
[pallet_cc_authorities_noting, AuthoritiesNoting]
[pallet_author_inherent, AuthorInherent]
[cumulus_pallet_xcmp_queue, XcmpQueue]
[cumulus_pallet_dmp_queue, DmpQueue]
[pallet_xcm, PalletXcmExtrinsicsBenchmark::<Runtime>]
[pallet_xcm_benchmarks::generic, pallet_xcm_benchmarks::generic::Pallet::<Runtime>]
[pallet_message_queue, MessageQueue]
[pallet_assets, ForeignAssets]
[pallet_foreign_asset_creator, ForeignAssetsCreator]
[pallet_asset_rate, AssetRate]
[pallet_xcm_executor_utils, XcmExecutorUtils]
);
}
impl_runtime_apis! {
impl sp_api::Core<Block> for Runtime {
fn version() -> RuntimeVersion {
VERSION
}
fn execute_block(block: Block) {
Executive::execute_block(block)
}
fn initialize_block(header: &<Block as BlockT>::Header) -> sp_runtime::ExtrinsicInclusionMode {
Executive::initialize_block(header)
}
}
impl sp_api::Metadata<Block> for Runtime {
fn metadata() -> OpaqueMetadata {
OpaqueMetadata::new(Runtime::metadata().into())
}
fn metadata_at_version(version: u32) -> Option<OpaqueMetadata> {
Runtime::metadata_at_version(version)
}
fn metadata_versions() -> Vec<u32> {
Runtime::metadata_versions()
}
}
impl sp_block_builder::BlockBuilder<Block> for Runtime {
fn apply_extrinsic(extrinsic: <Block as BlockT>::Extrinsic) -> ApplyExtrinsicResult {
Executive::apply_extrinsic(extrinsic)
}
fn finalize_block() -> <Block as BlockT>::Header {
Executive::finalize_block()
}
fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<<Block as BlockT>::Extrinsic> {
data.create_extrinsics()
}
fn check_inherents(
block: Block,
data: sp_inherents::InherentData,
) -> sp_inherents::CheckInherentsResult {
data.check_extrinsics(&block)
}
}
impl sp_transaction_pool::runtime_api::TaggedTransactionQueue<Block> for Runtime {
fn validate_transaction(
source: TransactionSource,
tx: <Block as BlockT>::Extrinsic,
block_hash: <Block as BlockT>::Hash,
) -> TransactionValidity {
Executive::validate_transaction(source, tx, block_hash)
}
}
impl sp_offchain::OffchainWorkerApi<Block> for Runtime {
fn offchain_worker(header: &<Block as BlockT>::Header) {
Executive::offchain_worker(header)
}
}
impl sp_session::SessionKeys<Block> for Runtime {
fn generate_session_keys(seed: Option<Vec<u8>>) -> Vec<u8> {
SessionKeys::generate(seed)
}
fn decode_session_keys(
encoded: Vec<u8>,
) -> Option<Vec<(Vec<u8>, sp_core::crypto::KeyTypeId)>> {
SessionKeys::decode_into_raw_public_keys(&encoded)
}
}
impl frame_system_rpc_runtime_api::AccountNonceApi<Block, AccountId, Index> for Runtime {
fn account_nonce(account: AccountId) -> Index {
System::account_nonce(account)
}
}
impl cumulus_primitives_core::CollectCollationInfo<Block> for Runtime {
fn collect_collation_info(header: &<Block as BlockT>::Header) -> cumulus_primitives_core::CollationInfo {
ParachainSystem::collect_collation_info(header)
}
}
impl async_backing_primitives::UnincludedSegmentApi<Block> for Runtime {
fn can_build_upon(
included_hash: <Block as BlockT>::Hash,
slot: async_backing_primitives::Slot,
) -> bool {
ConsensusHook::can_build_upon(included_hash, slot)
}
}
impl sp_genesis_builder::GenesisBuilder<Block> for Runtime {
fn build_state(config: Vec<u8>) -> sp_genesis_builder::Result {
build_state::<RuntimeGenesisConfig>(config)
}
fn get_preset(id: &Option<sp_genesis_builder::PresetId>) -> Option<Vec<u8>> {
get_preset::<RuntimeGenesisConfig>(id, |_| None)
}
fn preset_names() -> Vec<sp_genesis_builder::PresetId> {
vec![]
}
}
#[cfg(feature = "runtime-benchmarks")]
impl frame_benchmarking::Benchmark<Block> for Runtime {
fn benchmark_metadata(
extra: bool,
) -> (
Vec<frame_benchmarking::BenchmarkList>,
Vec<frame_support::traits::StorageInfo>,
) {
use frame_benchmarking::{Benchmarking, BenchmarkList};
use frame_support::traits::StorageInfoTrait;
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
let mut list = Vec::<BenchmarkList>::new();
list_benchmarks!(list, extra);
let storage_info = AllPalletsWithSystem::storage_info();
(list, storage_info)
}
fn dispatch_benchmark(
config: frame_benchmarking::BenchmarkConfig,
) -> Result<Vec<frame_benchmarking::BenchmarkBatch>, sp_runtime::RuntimeString> {
use frame_benchmarking::{BenchmarkBatch, Benchmarking, BenchmarkError};
use sp_core::storage::TrackedStorageKey;
use staging_xcm::latest::prelude::*;
impl frame_system_benchmarking::Config for Runtime {
fn setup_set_code_requirements(code: &sp_std::vec::Vec<u8>) -> Result<(), BenchmarkError> {
ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32);
Ok(())
}
fn verify_set_code() {
System::assert_last_event(cumulus_pallet_parachain_system::Event::<Runtime>::ValidationFunctionStored.into());
}
}
use crate::xcm_config::SelfReserve;
parameter_types! {
pub ExistentialDepositAsset: Option<Asset> = Some((
SelfReserve::get(),
ExistentialDeposit::get()
).into());
}
impl pallet_xcm_benchmarks::Config for Runtime {
type XcmConfig = xcm_config::XcmConfig;
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
xcm_config::XcmConfig,
ExistentialDepositAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<Location, BenchmarkError> {
Ok(Location::parent())
}
fn worst_case_holding(_depositable_count: u32) -> Assets {
// We only care for native asset until we support others
// TODO: refactor this case once other assets are supported
vec![Asset{
id: AssetId(SelfReserve::get()),
fun: Fungible(u128::MAX),
}].into()
}
}
impl pallet_xcm_benchmarks::generic::Config for Runtime {
type TransactAsset = Balances;
type RuntimeCall = RuntimeCall;
fn worst_case_response() -> (u64, Response) {
(0u64, Response::Version(Default::default()))
}
fn worst_case_asset_exchange() -> Result<(Assets, Assets), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn universal_alias() -> Result<(Location, Junction), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn transact_origin_and_runtime_call() -> Result<(Location, RuntimeCall), BenchmarkError> {
Ok((Location::parent(), frame_system::Call::remark_with_event { remark: vec![] }.into()))
}
fn subscribe_origin() -> Result<Location, BenchmarkError> {
Ok(Location::parent())
}
fn fee_asset() -> Result<Asset, BenchmarkError> {
Ok(Asset {
id: AssetId(SelfReserve::get()),
fun: Fungible(ExistentialDeposit::get()*100),
})
}
fn claimable_asset() -> Result<(Location, Location, Assets), BenchmarkError> {
let origin = Location::parent();
let assets: Assets = (Location::parent(), 1_000u128).into();
let ticket = Location { parents: 0, interior: Here };
Ok((origin, ticket, assets))
}
fn unlockable_asset() -> Result<(Location, Location, Asset), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn export_message_origin_and_destination(
) -> Result<(Location, NetworkId, InteriorLocation), BenchmarkError> {
Err(BenchmarkError::Skip)
}
fn alias_origin() -> Result<(Location, Location), BenchmarkError> {
Err(BenchmarkError::Skip)
}
}
use pallet_xcm::benchmarking::Pallet as PalletXcmExtrinsicsBenchmark;
impl pallet_xcm::benchmarking::Config for Runtime {
type DeliveryHelper = ();
fn get_asset() -> Asset {
Asset {
id: AssetId(SelfReserve::get()),
fun: Fungible(ExistentialDeposit::get()),
}
}
fn reachable_dest() -> Option<Location> {
Some(Parent.into())
}
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
// Relay/native token can be teleported between AH and Relay.
Some((
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT),
id: Parent.into()
},
Parent.into(),
))
}
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
use xcm_config::SelfReserve;
// AH can reserve transfer native token to some random parachain.
let random_para_id = 43211234;
ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(
random_para_id.into()
);
let who = frame_benchmarking::whitelisted_caller();
// Give some multiple of the existential deposit
let balance = EXISTENTIAL_DEPOSIT * 1000;
let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
&who, balance,
);
Some((
Asset {
fun: Fungible(EXISTENTIAL_DEPOSIT*10),
id: SelfReserve::get().into()
},
ParentThen(Parachain(random_para_id).into()).into(),
))
}
fn set_up_complex_asset_transfer(
) -> Option<(Assets, u32, Location, Box<dyn FnOnce()>)> {
use xcm_config::SelfReserve;
// Transfer to Relay some local AH asset (local-reserve-transfer) while paying
// fees using teleported native token.
// (We don't care that Relay doesn't accept incoming unknown AH local asset)
let dest = Parent.into();