-
Notifications
You must be signed in to change notification settings - Fork 699
/
pallet.rs
2444 lines (2201 loc) · 70.9 KB
/
pallet.rs
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
// This file is part of Substrate.
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use frame_support::{
assert_ok, derive_impl,
dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Parameter, Pays},
dispatch_context::with_context,
pallet_prelude::{StorageInfoTrait, ValueQuery},
parameter_types,
storage::{unhashed, unhashed::contains_prefixed_key},
traits::{
ConstU32, GetCallIndex, GetCallName, GetStorageVersion, OnFinalize, OnGenesis,
OnInitialize, OnRuntimeUpgrade, PalletError, PalletInfoAccess, StorageVersion,
UnfilteredDispatchable,
},
weights::{RuntimeDbWeight, Weight},
OrdNoBound, PartialOrdNoBound,
};
use scale_info::{meta_type, TypeInfo};
use sp_io::{
hashing::{blake2_128, twox_128, twox_64},
TestExternalities,
};
use sp_runtime::{
traits::{Dispatchable, Extrinsic as ExtrinsicT, SignaturePayload as SignaturePayloadT},
DispatchError, ModuleError,
};
parameter_types! {
/// Used to control if the storage version should be updated.
storage UpdateStorageVersion: bool = false;
}
/// Latest stable metadata version used for testing.
const LATEST_METADATA_VERSION: u32 = 15;
pub struct SomeType1;
impl From<SomeType1> for u64 {
fn from(_t: SomeType1) -> Self {
0u64
}
}
pub struct SomeType2;
impl From<SomeType2> for u64 {
fn from(_t: SomeType2) -> Self {
100u64
}
}
pub struct SomeType3;
impl From<SomeType3> for u64 {
fn from(_t: SomeType3) -> Self {
0u64
}
}
pub struct SomeType4;
impl From<SomeType4> for u64 {
fn from(_t: SomeType4) -> Self {
0u64
}
}
pub struct SomeType5;
impl From<SomeType5> for u64 {
fn from(_t: SomeType5) -> Self {
0u64
}
}
pub struct SomeType6;
impl From<SomeType6> for u64 {
fn from(_t: SomeType6) -> Self {
0u64
}
}
pub struct SomeType7;
impl From<SomeType7> for u64 {
fn from(_t: SomeType7) -> Self {
0u64
}
}
pub trait SomeAssociation1 {
type _1: Parameter + codec::MaxEncodedLen + TypeInfo;
}
impl SomeAssociation1 for u64 {
type _1 = u64;
}
pub trait SomeAssociation2 {
type _2: Parameter + codec::MaxEncodedLen + TypeInfo;
}
impl SomeAssociation2 for u64 {
type _2 = u64;
}
#[frame_support::pallet]
/// Pallet documentation
// Comments should not be included in the pallet documentation
#[pallet_doc("../../README.md")]
#[doc = include_str!("../../README.md")]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use sp_runtime::DispatchResult;
type BalanceOf<T> = <T as Config>::Balance;
pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(10);
#[pallet::config]
pub trait Config: frame_system::Config
where
<Self as frame_system::Config>::AccountId: From<SomeType1> + SomeAssociation1,
{
/// Some comment
/// Some comment
#[pallet::constant]
type MyGetParam: Get<u32>;
/// Some comment
/// Some comment
#[pallet::constant]
type MyGetParam2: Get<u32>;
#[pallet::constant]
type MyGetParam3: Get<<Self::AccountId as SomeAssociation1>::_1>;
type Balance: Parameter + Default + TypeInfo;
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::extra_constants]
impl<T: Config> Pallet<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1 + From<SomeType2>,
{
/// Some doc
/// Some doc
fn some_extra() -> T::AccountId {
SomeType2.into()
}
/// Some doc
fn some_extra_extra() -> T::AccountId {
SomeType1.into()
}
/// Some doc
#[pallet::constant_name(SomeExtraRename)]
fn some_extra_rename() -> T::AccountId {
SomeType1.into()
}
}
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T>
where
T::AccountId: From<SomeType2> + From<SomeType1> + SomeAssociation1,
{
fn on_initialize(_: BlockNumberFor<T>) -> Weight {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType2); // Test for where clause
Self::deposit_event(Event::Something(10));
Weight::from_parts(10, 0)
}
fn on_finalize(_: BlockNumberFor<T>) {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType2); // Test for where clause
Self::deposit_event(Event::Something(20));
}
fn on_runtime_upgrade() -> Weight {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType2); // Test for where clause
Self::deposit_event(Event::Something(30));
Weight::from_parts(30, 0)
}
fn integrity_test() {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType2); // Test for where clause
}
}
#[pallet::call]
impl<T: Config> Pallet<T>
where
T::AccountId: From<SomeType1> + From<SomeType3> + SomeAssociation1,
{
/// Doc comment put in metadata
#[pallet::call_index(0)]
#[pallet::weight(Weight::from_parts(*foo as u64, 0))]
pub fn foo(
origin: OriginFor<T>,
#[pallet::compact] foo: u32,
_bar: u32,
) -> DispatchResultWithPostInfo {
let _ = foo;
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType3); // Test for where clause
let _ = origin;
Self::deposit_event(Event::Something(3));
Ok(().into())
}
/// Doc comment put in metadata
#[pallet::call_index(1)]
#[pallet::weight({1})]
pub fn foo_storage_layer(
_origin: OriginFor<T>,
#[pallet::compact] foo: u32,
) -> DispatchResultWithPostInfo {
Self::deposit_event(Event::Something(0));
if foo == 0 {
Err(Error::<T>::InsufficientProposersBalance)?;
}
Ok(().into())
}
#[pallet::call_index(4)]
#[pallet::weight({1})]
pub fn foo_index_out_of_order(_origin: OriginFor<T>) -> DispatchResult {
Ok(())
}
// Test for DispatchResult return type
#[pallet::call_index(2)]
#[pallet::weight({1})]
pub fn foo_no_post_info(_origin: OriginFor<T>) -> DispatchResult {
Ok(())
}
#[pallet::call_index(3)]
#[pallet::weight({1})]
pub fn check_for_dispatch_context(_origin: OriginFor<T>) -> DispatchResult {
with_context::<(), _>(|_| ()).ok_or_else(|| DispatchError::Unavailable)
}
#[cfg(feature = "frame-feature-testing")]
#[pallet::call_index(5)]
#[pallet::weight({1})]
pub fn foo_feature_test(_origin: OriginFor<T>) -> DispatchResult {
Ok(())
}
}
#[pallet::error]
#[derive(PartialEq, Eq)]
pub enum Error<T> {
/// doc comment put into metadata
InsufficientProposersBalance,
NonExistentStorageValue,
Code(u8),
#[codec(skip)]
Skipped(u128),
CompactU8(#[codec(compact)] u8),
#[cfg(feature = "frame-feature-testing")]
FeatureTest,
}
#[pallet::event]
#[pallet::generate_deposit(fn deposit_event)]
pub enum Event<T: Config>
where
T::AccountId: SomeAssociation1 + From<SomeType1>,
{
/// doc comment put in metadata
Proposed(<T as frame_system::Config>::AccountId),
/// doc
Spending(BalanceOf<T>),
Something(u32),
SomethingElse(<T::AccountId as SomeAssociation1>::_1),
}
#[pallet::storage]
pub type ValueWhereClause<T: Config>
where
T::AccountId: SomeAssociation2,
= StorageValue<_, <T::AccountId as SomeAssociation2>::_2>;
#[pallet::storage]
pub type Value<T> = StorageValue<Value = u32>;
#[pallet::storage]
#[pallet::storage_prefix = "Value2"]
pub type RenamedValue<T> = StorageValue<Value = u64>;
/// Test some doc
#[pallet::type_value]
pub fn MyDefault<T: Config>() -> u16
where
T::AccountId: From<SomeType7> + From<SomeType1> + SomeAssociation1,
{
let _ = T::AccountId::from(SomeType7); // Test where clause works
4u16
}
#[pallet::storage]
pub type Map<T: Config>
where
T::AccountId: From<SomeType7>,
= StorageMap<_, Blake2_128Concat, u8, u16, ValueQuery, MyDefault<T>>;
#[pallet::storage]
pub type Map2<T> =
StorageMap<Hasher = Twox64Concat, Key = u16, Value = u32, MaxValues = ConstU32<3>>;
#[pallet::storage]
pub type Map3<T> =
StorageMap<_, Blake2_128Concat, u32, u64, ResultQuery<Error<T>::NonExistentStorageValue>>;
#[pallet::storage]
pub type DoubleMap<T> = StorageDoubleMap<_, Blake2_128Concat, u8, Twox64Concat, u16, u32>;
#[pallet::storage]
pub type DoubleMap2<T> = StorageDoubleMap<
Hasher1 = Twox64Concat,
Key1 = u16,
Hasher2 = Blake2_128Concat,
Key2 = u32,
Value = u64,
MaxValues = ConstU32<5>,
>;
#[pallet::storage]
pub type DoubleMap3<T> = StorageDoubleMap<
_,
Blake2_128Concat,
u32,
Twox64Concat,
u64,
u128,
ResultQuery<Error<T>::NonExistentStorageValue>,
>;
#[pallet::storage]
#[pallet::getter(fn nmap)]
pub type NMap<T> = StorageNMap<_, storage::Key<Blake2_128Concat, u8>, u32>;
#[pallet::storage]
#[pallet::getter(fn nmap2)]
pub type NMap2<T> = StorageNMap<
Key = (NMapKey<Twox64Concat, u16>, NMapKey<Blake2_128Concat, u32>),
Value = u64,
MaxValues = ConstU32<11>,
>;
#[pallet::storage]
#[pallet::getter(fn nmap3)]
pub type NMap3<T> = StorageNMap<
_,
(NMapKey<Blake2_128Concat, u8>, NMapKey<Twox64Concat, u16>),
u128,
ResultQuery<Error<T>::NonExistentStorageValue>,
>;
#[pallet::storage]
#[pallet::getter(fn counted_nmap)]
pub type CountedNMap<T> = CountedStorageNMap<_, storage::Key<Blake2_128Concat, u8>, u32>;
#[pallet::storage]
#[pallet::getter(fn counted_nmap2)]
pub type CountedNMap2<T> = CountedStorageNMap<
Key = (NMapKey<Twox64Concat, u16>, NMapKey<Blake2_128Concat, u32>),
Value = u64,
MaxValues = ConstU32<11>,
>;
#[pallet::storage]
#[pallet::getter(fn counted_nmap3)]
pub type CountedNMap3<T> = CountedStorageNMap<
_,
(NMapKey<Blake2_128Concat, u8>, NMapKey<Twox64Concat, u16>),
u128,
ResultQuery<Error<T>::NonExistentStorageValue>,
>;
#[pallet::storage]
#[pallet::getter(fn conditional_value)]
#[cfg(feature = "frame-feature-testing")]
pub type ConditionalValue<T> = StorageValue<_, u32>;
#[cfg(feature = "frame-feature-testing")]
#[pallet::storage]
#[pallet::getter(fn conditional_map)]
pub type ConditionalMap<T> =
StorageMap<_, Twox64Concat, u16, u32, OptionQuery, GetDefault, ConstU32<12>>;
#[cfg(feature = "frame-feature-testing")]
#[pallet::storage]
#[pallet::getter(fn conditional_double_map)]
pub type ConditionalDoubleMap<T> =
StorageDoubleMap<_, Blake2_128Concat, u8, Twox64Concat, u16, u32>;
#[cfg(feature = "frame-feature-testing")]
#[pallet::storage]
#[pallet::getter(fn conditional_nmap)]
pub type ConditionalNMap<T> =
StorageNMap<_, (storage::Key<Blake2_128Concat, u8>, storage::Key<Twox64Concat, u16>), u32>;
#[cfg(feature = "frame-feature-testing")]
#[pallet::storage]
#[pallet::getter(fn conditional_counted_nmap)]
pub type ConditionalCountedNMap<T> = CountedStorageNMap<
_,
(storage::Key<Blake2_128Concat, u8>, storage::Key<Twox64Concat, u16>),
u32,
>;
#[pallet::storage]
#[pallet::storage_prefix = "RenamedCountedMap"]
#[pallet::getter(fn counted_storage_map)]
pub type SomeCountedStorageMap<T> =
CountedStorageMap<Hasher = Twox64Concat, Key = u8, Value = u32>;
#[pallet::storage]
#[pallet::unbounded]
pub type Unbounded<T> = StorageValue<Value = Vec<u8>>;
#[pallet::genesis_config]
#[derive(frame_support::DefaultNoBound)]
pub struct GenesisConfig<T: Config>
where
T::AccountId: From<SomeType1> + SomeAssociation1 + From<SomeType4>,
{
#[serde(skip)]
_config: sp_std::marker::PhantomData<T>,
_myfield: u32,
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1 + From<SomeType4>,
{
fn build(&self) {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType4); // Test for where clause
}
}
#[pallet::origin]
#[derive(
EqNoBound,
RuntimeDebugNoBound,
CloneNoBound,
PartialEqNoBound,
PartialOrdNoBound,
OrdNoBound,
Encode,
Decode,
TypeInfo,
MaxEncodedLen,
)]
pub struct Origin<T>(PhantomData<T>);
#[pallet::validate_unsigned]
impl<T: Config> ValidateUnsigned for Pallet<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1 + From<SomeType5> + From<SomeType3>,
{
type Call = Call<T>;
fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType5); // Test for where clause
if matches!(call, Call::foo_storage_layer { .. }) {
return Ok(ValidTransaction::default())
}
Err(TransactionValidityError::Invalid(InvalidTransaction::Call))
}
}
#[pallet::inherent]
impl<T: Config> ProvideInherent for Pallet<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1 + From<SomeType6> + From<SomeType3>,
{
type Call = Call<T>;
type Error = InherentError;
const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
fn create_inherent(_data: &InherentData) -> Option<Self::Call> {
let _ = T::AccountId::from(SomeType1); // Test for where clause
let _ = T::AccountId::from(SomeType6); // Test for where clause
Some(Call::foo_no_post_info {})
}
fn is_inherent(call: &Self::Call) -> bool {
matches!(call, Call::foo_no_post_info {} | Call::foo { .. })
}
fn check_inherent(call: &Self::Call, _: &InherentData) -> Result<(), Self::Error> {
match call {
Call::foo_no_post_info {} => Ok(()),
Call::foo { foo: 0, bar: 0 } => Err(InherentError::Fatal),
Call::foo { .. } => Ok(()),
_ => unreachable!("other calls are not inherents"),
}
}
fn is_inherent_required(d: &InherentData) -> Result<Option<Self::Error>, Self::Error> {
match d.get_data::<bool>(b"required") {
Ok(Some(true)) => Ok(Some(InherentError::Fatal)),
Ok(Some(false)) | Ok(None) => Ok(None),
Err(_) => unreachable!("should not happen in tests"),
}
}
}
#[pallet::composite_enum]
pub enum HoldReason {
Staking,
}
#[derive(codec::Encode, sp_runtime::RuntimeDebug)]
#[cfg_attr(feature = "std", derive(codec::Decode))]
pub enum InherentError {
Fatal,
}
impl frame_support::inherent::IsFatalError for InherentError {
fn is_fatal_error(&self) -> bool {
matches!(self, InherentError::Fatal)
}
}
pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"testpall";
}
// Test that a pallet with non generic event and generic genesis_config is correctly handled
// and that a pallet with the attribute without_storage_info is correctly handled.
#[frame_support::pallet]
pub mod pallet2 {
use super::{SomeAssociation1, SomeType1, UpdateStorageVersion};
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(2);
#[pallet::config]
pub trait Config: frame_system::Config
where
<Self as frame_system::Config>::AccountId: From<SomeType1> + SomeAssociation1,
{
type RuntimeEvent: From<Event> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
}
#[pallet::pallet]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(_);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1,
{
fn on_initialize(_: BlockNumberFor<T>) -> Weight {
Self::deposit_event(Event::Something(11));
Weight::zero()
}
fn on_finalize(_: BlockNumberFor<T>) {
Self::deposit_event(Event::Something(21));
}
fn on_runtime_upgrade() -> Weight {
Self::deposit_event(Event::Something(31));
if UpdateStorageVersion::get() {
Self::current_storage_version().put::<Self>();
}
Weight::zero()
}
}
#[pallet::call]
impl<T: Config> Pallet<T> where T::AccountId: From<SomeType1> + SomeAssociation1 {}
#[pallet::storage]
pub type SomeValue<T: Config> = StorageValue<_, Vec<u32>>;
#[pallet::storage]
pub type SomeCountedStorageMap<T> =
CountedStorageMap<Hasher = Twox64Concat, Key = u8, Value = u32>;
#[pallet::event]
#[pallet::generate_deposit(fn deposit_event)]
pub enum Event {
/// Something
Something(u32),
}
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config>
where
T::AccountId: From<SomeType1> + SomeAssociation1,
{
phantom: PhantomData<T>,
}
impl<T: Config> Default for GenesisConfig<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1,
{
fn default() -> Self {
GenesisConfig { phantom: Default::default() }
}
}
#[pallet::genesis_build]
impl<T: Config> BuildGenesisConfig for GenesisConfig<T>
where
T::AccountId: From<SomeType1> + SomeAssociation1,
{
fn build(&self) {}
}
#[pallet::composite_enum]
pub enum HoldReason {
Governance,
}
#[pallet::composite_enum]
pub enum SlashReason {
Equivocation,
}
}
/// Test that the supertrait check works when we pass some parameter to the `frame_system::Config`.
#[frame_support::pallet]
pub mod pallet3 {
#[pallet::config]
pub trait Config:
frame_system::Config<RuntimeOrigin = <Self as Config>::RuntimeOrigin>
{
type RuntimeOrigin;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
}
#[frame_support::pallet]
pub mod pallet4 {
#[pallet::config]
pub trait Config: frame_system::Config {}
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::call]
impl<T: Config> Pallet<T> {}
}
/// Test that the supertrait check works when we pass some parameter to the `frame_system::Config`.
#[frame_support::pallet]
pub mod pallet5 {
#[pallet::config]
pub trait Config:
frame_system::Config<RuntimeOrigin = <Self as Config>::RuntimeOrigin>
{
type RuntimeOrigin;
}
#[pallet::pallet]
pub struct Pallet<T>(_);
}
frame_support::parameter_types!(
pub const MyGetParam3: u32 = 12;
);
#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)]
impl frame_system::Config for Runtime {
type BaseCallFilter = frame_support::traits::Everything;
type RuntimeOrigin = RuntimeOrigin;
type Nonce = u64;
type RuntimeCall = RuntimeCall;
type Hash = sp_runtime::testing::H256;
type Hashing = sp_runtime::traits::BlakeTwo256;
type AccountId = u64;
type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
type Block = Block;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = ConstU32<250>;
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = ();
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = ConstU32<16>;
}
impl pallet::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type MyGetParam = ConstU32<10>;
type MyGetParam2 = ConstU32<11>;
type MyGetParam3 = MyGetParam3;
type Balance = u64;
}
impl pallet2::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
}
impl pallet4::Config for Runtime {}
#[cfg(feature = "frame-feature-testing")]
impl pallet3::Config for Runtime {
type RuntimeOrigin = RuntimeOrigin;
}
#[cfg(feature = "frame-feature-testing-2")]
impl pallet5::Config for Runtime {
type RuntimeOrigin = RuntimeOrigin;
}
pub type Header = sp_runtime::generic::Header<u32, sp_runtime::traits::BlakeTwo256>;
pub type Block = sp_runtime::generic::Block<Header, UncheckedExtrinsic>;
pub type UncheckedExtrinsic =
sp_runtime::testing::TestXt<RuntimeCall, frame_system::CheckNonZeroSender<Runtime>>;
frame_support::construct_runtime!(
pub struct Runtime
{
// Exclude part `Storage` in order not to check its metadata in tests.
System: frame_system exclude_parts { Pallet, Storage },
Example: pallet,
Example2: pallet2 exclude_parts { Call },
#[cfg(feature = "frame-feature-testing")]
Example3: pallet3,
Example4: pallet4 use_parts { Call },
#[cfg(feature = "frame-feature-testing-2")]
Example5: pallet5,
}
);
// Test that the part `RuntimeCall` is excluded from Example2 and included in Example4.
fn _ensure_call_is_correctly_excluded_and_included(call: RuntimeCall) {
match call {
RuntimeCall::System(_) | RuntimeCall::Example(_) | RuntimeCall::Example4(_) => (),
}
}
#[test]
fn transactional_works() {
TestExternalities::default().execute_with(|| {
frame_system::Pallet::<Runtime>::set_block_number(1);
pallet::Call::<Runtime>::foo_storage_layer { foo: 0 }
.dispatch_bypass_filter(None.into())
.err()
.unwrap();
assert!(frame_system::Pallet::<Runtime>::events().is_empty());
pallet::Call::<Runtime>::foo_storage_layer { foo: 1 }
.dispatch_bypass_filter(None.into())
.unwrap();
assert_eq!(
frame_system::Pallet::<Runtime>::events()
.iter()
.map(|e| &e.event)
.collect::<Vec<_>>(),
vec![&RuntimeEvent::Example(pallet::Event::Something(0))],
);
})
}
#[test]
fn call_expand() {
let call_foo = pallet::Call::<Runtime>::foo { foo: 3, bar: 0 };
assert_eq!(
call_foo.get_dispatch_info(),
DispatchInfo {
weight: frame_support::weights::Weight::from_parts(3, 0),
class: DispatchClass::Normal,
pays_fee: Pays::Yes
}
);
assert_eq!(call_foo.get_call_name(), "foo");
#[cfg(not(feature = "frame-feature-testing"))]
assert_eq!(
pallet::Call::<Runtime>::get_call_names(),
&[
"foo",
"foo_storage_layer",
"foo_index_out_of_order",
"foo_no_post_info",
"check_for_dispatch_context"
],
);
#[cfg(feature = "frame-feature-testing")]
assert_eq!(
pallet::Call::<Runtime>::get_call_names(),
&[
"foo",
"foo_storage_layer",
"foo_index_out_of_order",
"foo_no_post_info",
"check_for_dispatch_context",
"foo_feature_test"
],
);
assert_eq!(call_foo.get_call_index(), 0u8);
#[cfg(not(feature = "frame-feature-testing"))]
assert_eq!(pallet::Call::<Runtime>::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8]);
#[cfg(feature = "frame-feature-testing")]
assert_eq!(pallet::Call::<Runtime>::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8, 5u8]);
}
#[test]
fn call_expand_index() {
let call_foo = pallet::Call::<Runtime>::foo_index_out_of_order {};
assert_eq!(call_foo.get_call_index(), 4u8);
#[cfg(not(feature = "frame-feature-testing"))]
assert_eq!(pallet::Call::<Runtime>::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8]);
#[cfg(feature = "frame-feature-testing")]
assert_eq!(pallet::Call::<Runtime>::get_call_indices(), &[0u8, 1u8, 4u8, 2u8, 3u8, 5u8]);
}
#[test]
fn error_expand() {
assert_eq!(
format!("{:?}", pallet::Error::<Runtime>::InsufficientProposersBalance),
String::from("InsufficientProposersBalance"),
);
assert_eq!(
<&'static str>::from(pallet::Error::<Runtime>::InsufficientProposersBalance),
"InsufficientProposersBalance",
);
assert_eq!(
DispatchError::from(pallet::Error::<Runtime>::InsufficientProposersBalance),
DispatchError::Module(ModuleError {
index: 1,
error: [0, 0, 0, 0],
message: Some("InsufficientProposersBalance")
}),
);
assert_eq!(<pallet::Error::<Runtime> as PalletError>::MAX_ENCODED_SIZE, 3);
#[cfg(feature = "frame-feature-testing")]
assert_eq!(format!("{:?}", pallet::Error::<Runtime>::FeatureTest), String::from("FeatureTest"),);
}
#[test]
fn instance_expand() {
// Assert same type.
let _: pallet::__InherentHiddenInstance = ();
}
#[test]
fn inherent_expand() {
use frame_support::{inherent::InherentData, traits::EnsureInherentsAreFirst};
use sp_core::Hasher;
use sp_runtime::{
traits::{BlakeTwo256, Block as _, Header},
Digest,
};
let inherents = InherentData::new().create_extrinsics();
let expected = vec![UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo_no_post_info {}),
signature: None,
}];
assert_eq!(expected, inherents);
let block = Block::new(
Header::new(
1,
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
Digest::default(),
),
vec![
UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo_no_post_info {}),
signature: None,
},
UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo { foo: 1, bar: 0 }),
signature: None,
},
],
);
assert!(InherentData::new().check_extrinsics(&block).ok());
let block = Block::new(
Header::new(
1,
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
Digest::default(),
),
vec![
UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo_no_post_info {}),
signature: None,
},
UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo { foo: 0, bar: 0 }),
signature: None,
},
],
);
assert!(InherentData::new().check_extrinsics(&block).fatal_error());
let block = Block::new(
Header::new(
1,
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
Digest::default(),
),
vec![UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo_storage_layer { foo: 0 }),
signature: None,
}],
);
let mut inherent = InherentData::new();
inherent.put_data(*b"required", &true).unwrap();
assert!(inherent.check_extrinsics(&block).fatal_error());
let block = Block::new(
Header::new(
1,
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
Digest::default(),
),
vec![UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo_no_post_info {}),
signature: Some((1, Default::default())),
}],
);
let mut inherent = InherentData::new();
inherent.put_data(*b"required", &true).unwrap();
assert!(inherent.check_extrinsics(&block).fatal_error());
let block = Block::new(
Header::new(
1,
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
BlakeTwo256::hash(b"test"),
Digest::default(),
),
vec![
UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo { foo: 1, bar: 1 }),
signature: None,
},
UncheckedExtrinsic {
call: RuntimeCall::Example(pallet::Call::foo_storage_layer { foo: 0 }),
signature: None,
},
],
);
assert!(Runtime::ensure_inherents_are_first(&block).is_ok());