1#![cfg_attr(not(feature = "std"), no_std)]
99
100extern crate alloc;
101
102use alloc::{borrow::Cow, boxed::Box, vec, vec::Vec};
103use core::{fmt::Debug, marker::PhantomData};
104use pallet_prelude::{BlockNumberFor, HeaderFor};
105#[cfg(feature = "std")]
106use serde::Serialize;
107use sp_io::hashing::blake2_256;
108#[cfg(feature = "runtime-benchmarks")]
109use sp_runtime::traits::TrailingZeroInput;
110use sp_runtime::{
111 generic,
112 traits::{
113 self, AsTransactionAuthorizedOrigin, AtLeast32Bit, BadOrigin, BlockNumberProvider, Bounded,
114 CheckEqual, Dispatchable, Hash, Header, Lookup, LookupError, MaybeDisplay,
115 MaybeSerializeDeserialize, Member, One, Saturating, SimpleBitOps, StaticLookup, Zero,
116 },
117 transaction_validity::{
118 InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity,
119 ValidTransaction,
120 },
121 DispatchError,
122};
123use sp_version::RuntimeVersion;
124
125use codec::{Decode, DecodeWithMemTracking, Encode, EncodeLike, FullCodec, MaxEncodedLen};
126#[cfg(feature = "std")]
127use frame_support::traits::BuildGenesisConfig;
128use frame_support::{
129 dispatch::{
130 extract_actual_pays_fee, extract_actual_weight, DispatchClass, DispatchInfo,
131 DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, PerDispatchClass,
132 PostDispatchInfo,
133 },
134 ensure, impl_ensure_origin_with_arg_ignoring_arg,
135 migrations::MultiStepMigrator,
136 pallet_prelude::Pays,
137 storage::{self, StorageStreamIter},
138 traits::{
139 ConstU32, Contains, EnsureOrigin, EnsureOriginWithArg, Get, HandleLifetime,
140 OnKilledAccount, OnNewAccount, OnRuntimeUpgrade, OriginTrait, PalletInfo, SortedMembers,
141 StoredMap, TypedGet,
142 },
143 Parameter,
144};
145use scale_info::TypeInfo;
146use sp_core::storage::well_known_keys;
147use sp_runtime::{
148 traits::{DispatchInfoOf, PostDispatchInfoOf},
149 transaction_validity::TransactionValidityError,
150};
151use sp_weights::{RuntimeDbWeight, Weight, WeightMeter};
152
153#[cfg(any(feature = "std", test))]
154use sp_io::TestExternalities;
155
156pub mod limits;
157#[cfg(test)]
158pub(crate) mod mock;
159
160pub mod offchain;
161
162mod extensions;
163#[cfg(feature = "std")]
164pub mod mocking;
165#[cfg(test)]
166mod tests;
167pub mod weights;
168
169pub mod migrations;
170
171pub use extensions::{
172 authorize_call::AuthorizeCall,
173 check_genesis::CheckGenesis,
174 check_mortality::CheckMortality,
175 check_non_zero_sender::CheckNonZeroSender,
176 check_nonce::{CheckNonce, ValidNonceInfo},
177 check_spec_version::CheckSpecVersion,
178 check_tx_version::CheckTxVersion,
179 check_weight::CheckWeight,
180 weight_reclaim::WeightReclaim,
181 weights::SubstrateWeight as SubstrateExtensionsWeight,
182 WeightInfo as ExtensionsWeightInfo,
183};
184pub use extensions::check_mortality::CheckMortality as CheckEra;
186pub use frame_support::dispatch::RawOrigin;
187use frame_support::traits::{Authorize, PostInherents, PostTransactions, PreInherents};
188use sp_core::storage::StateVersion;
189pub use weights::WeightInfo;
190
191const LOG_TARGET: &str = "runtime::system";
192
193pub fn extrinsics_root<H: Hash, E: codec::Encode>(
198 extrinsics: &[E],
199 state_version: StateVersion,
200) -> H::Output {
201 extrinsics_data_root::<H>(extrinsics.iter().map(codec::Encode::encode).collect(), state_version)
202}
203
204pub fn extrinsics_data_root<H: Hash>(xts: Vec<Vec<u8>>, state_version: StateVersion) -> H::Output {
209 H::ordered_trie_root(xts, state_version)
210}
211
212pub type ConsumedWeight = PerDispatchClass<Weight>;
214
215pub use pallet::*;
216
217pub trait SetCode<T: Config> {
219 fn set_code(code: Vec<u8>) -> DispatchResult;
221}
222
223impl<T: Config> SetCode<T> for () {
224 fn set_code(code: Vec<u8>) -> DispatchResult {
225 <Pallet<T>>::update_code_in_storage(&code);
226 Ok(())
227 }
228}
229
230pub trait ConsumerLimits {
232 fn max_consumers() -> RefCount;
234 fn max_overflow() -> RefCount;
240}
241
242impl<const Z: u32> ConsumerLimits for ConstU32<Z> {
243 fn max_consumers() -> RefCount {
244 Z
245 }
246 fn max_overflow() -> RefCount {
247 Z
248 }
249}
250
251impl<MaxNormal: Get<u32>, MaxOverflow: Get<u32>> ConsumerLimits for (MaxNormal, MaxOverflow) {
252 fn max_consumers() -> RefCount {
253 MaxNormal::get()
254 }
255 fn max_overflow() -> RefCount {
256 MaxOverflow::get()
257 }
258}
259
260#[derive(Decode, Encode, Default, PartialEq, Eq, MaxEncodedLen, TypeInfo)]
263#[scale_info(skip_type_params(T))]
264pub struct CodeUpgradeAuthorization<T>
265where
266 T: Config,
267{
268 code_hash: T::Hash,
270 check_version: bool,
272}
273
274#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
275impl<T> CodeUpgradeAuthorization<T>
276where
277 T: Config,
278{
279 pub fn code_hash(&self) -> &T::Hash {
280 &self.code_hash
281 }
282}
283
284#[derive(
288 Clone, Copy, Eq, PartialEq, Default, Debug, Encode, Decode, DecodeWithMemTracking, TypeInfo,
289)]
290pub struct DispatchEventInfo {
291 pub weight: Weight,
293 pub class: DispatchClass,
295 pub pays_fee: Pays,
297}
298
299#[frame_support::pallet]
300pub mod pallet {
301 use crate::{self as frame_system, pallet_prelude::*, *};
302 use codec::HasCompact;
303 use frame_support::pallet_prelude::*;
304
305 pub mod config_preludes {
307 use super::{inject_runtime_type, DefaultConfig};
308 use frame_support::{derive_impl, traits::Get};
309
310 pub struct TestBlockHashCount<C: Get<u32>>(core::marker::PhantomData<C>);
316 impl<I: From<u32>, C: Get<u32>> Get<I> for TestBlockHashCount<C> {
317 fn get() -> I {
318 C::get().into()
319 }
320 }
321
322 pub struct TestDefaultConfig;
329
330 #[frame_support::register_default_impl(TestDefaultConfig)]
331 impl DefaultConfig for TestDefaultConfig {
332 type Nonce = u32;
333 type Hash = sp_core::hash::H256;
334 type Hashing = sp_runtime::traits::BlakeTwo256;
335 type AccountId = u64;
336 type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
337 type MaxConsumers = frame_support::traits::ConstU32<16>;
338 type AccountData = ();
339 type OnNewAccount = ();
340 type OnKilledAccount = ();
341 type SystemWeightInfo = ();
342 type ExtensionsWeightInfo = ();
343 type SS58Prefix = ();
344 type Version = ();
345 type BlockWeights = ();
346 type BlockLength = ();
347 type DbWeight = ();
348 #[inject_runtime_type]
349 type RuntimeEvent = ();
350 #[inject_runtime_type]
351 type RuntimeOrigin = ();
352 #[inject_runtime_type]
353 type RuntimeCall = ();
354 #[inject_runtime_type]
355 type PalletInfo = ();
356 #[inject_runtime_type]
357 type RuntimeTask = ();
358 type BaseCallFilter = frame_support::traits::Everything;
359 type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<10>>;
360 type OnSetCode = ();
361 type SingleBlockMigrations = ();
362 type MultiBlockMigrator = ();
363 type PreInherents = ();
364 type PostInherents = ();
365 type PostTransactions = ();
366 }
367
368 pub struct SolochainDefaultConfig;
382
383 #[frame_support::register_default_impl(SolochainDefaultConfig)]
384 impl DefaultConfig for SolochainDefaultConfig {
385 type Nonce = u32;
387
388 type Hash = sp_core::hash::H256;
390
391 type Hashing = sp_runtime::traits::BlakeTwo256;
393
394 type AccountId = sp_runtime::AccountId32;
396
397 type Lookup = sp_runtime::traits::AccountIdLookup<Self::AccountId, ()>;
399
400 type MaxConsumers = frame_support::traits::ConstU32<128>;
402
403 type AccountData = ();
405
406 type OnNewAccount = ();
408
409 type OnKilledAccount = ();
411
412 type SystemWeightInfo = ();
414
415 type ExtensionsWeightInfo = ();
417
418 type SS58Prefix = ();
420
421 type Version = ();
423
424 type BlockWeights = ();
426
427 type BlockLength = ();
429
430 type DbWeight = ();
432
433 #[inject_runtime_type]
435 type RuntimeEvent = ();
436
437 #[inject_runtime_type]
439 type RuntimeOrigin = ();
440
441 #[inject_runtime_type]
444 type RuntimeCall = ();
445
446 #[inject_runtime_type]
448 type RuntimeTask = ();
449
450 #[inject_runtime_type]
452 type PalletInfo = ();
453
454 type BaseCallFilter = frame_support::traits::Everything;
456
457 type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<256>>;
460
461 type OnSetCode = ();
463 type SingleBlockMigrations = ();
464 type MultiBlockMigrator = ();
465 type PreInherents = ();
466 type PostInherents = ();
467 type PostTransactions = ();
468 }
469
470 pub struct RelayChainDefaultConfig;
472
473 #[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
475 #[frame_support::register_default_impl(RelayChainDefaultConfig)]
476 impl DefaultConfig for RelayChainDefaultConfig {}
477
478 pub struct ParaChainDefaultConfig;
480
481 #[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
483 #[frame_support::register_default_impl(ParaChainDefaultConfig)]
484 impl DefaultConfig for ParaChainDefaultConfig {}
485 }
486
487 #[pallet::config(with_default, frame_system_config)]
489 #[pallet::disable_frame_system_supertrait_check]
490 pub trait Config: 'static + Eq + Clone {
491 #[pallet::no_default_bounds]
493 type RuntimeEvent: Parameter
494 + Member
495 + From<Event<Self>>
496 + Debug
497 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
498
499 #[pallet::no_default_bounds]
510 type BaseCallFilter: Contains<Self::RuntimeCall>;
511
512 #[pallet::constant]
514 type BlockWeights: Get<limits::BlockWeights>;
515
516 #[pallet::constant]
518 type BlockLength: Get<limits::BlockLength>;
519
520 #[pallet::no_default_bounds]
522 type RuntimeOrigin: Into<Result<RawOrigin<Self::AccountId>, Self::RuntimeOrigin>>
523 + From<RawOrigin<Self::AccountId>>
524 + Clone
525 + OriginTrait<Call = Self::RuntimeCall, AccountId = Self::AccountId>
526 + AsTransactionAuthorizedOrigin;
527
528 #[docify::export(system_runtime_call)]
529 #[pallet::no_default_bounds]
531 type RuntimeCall: Parameter
532 + Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
533 + Debug
534 + GetDispatchInfo
535 + From<Call<Self>>
536 + Authorize;
537
538 #[pallet::no_default_bounds]
540 type RuntimeTask: Task;
541
542 type Nonce: Parameter
544 + HasCompact<Type: DecodeWithMemTracking>
545 + Member
546 + MaybeSerializeDeserialize
547 + Debug
548 + Default
549 + MaybeDisplay
550 + AtLeast32Bit
551 + Copy
552 + MaxEncodedLen;
553
554 type Hash: Parameter
556 + Member
557 + MaybeSerializeDeserialize
558 + Debug
559 + MaybeDisplay
560 + SimpleBitOps
561 + Ord
562 + Default
563 + Copy
564 + CheckEqual
565 + core::hash::Hash
566 + AsRef<[u8]>
567 + AsMut<[u8]>
568 + MaxEncodedLen;
569
570 type Hashing: Hash<Output = Self::Hash> + TypeInfo;
572
573 type AccountId: Parameter
575 + Member
576 + MaybeSerializeDeserialize
577 + Debug
578 + MaybeDisplay
579 + Ord
580 + MaxEncodedLen;
581
582 type Lookup: StaticLookup<Target = Self::AccountId>;
589
590 #[pallet::no_default]
593 type Block: Parameter + Member + traits::Block<Hash = Self::Hash>;
594
595 #[pallet::constant]
597 #[pallet::no_default_bounds]
598 type BlockHashCount: Get<BlockNumberFor<Self>>;
599
600 #[pallet::constant]
602 type DbWeight: Get<RuntimeDbWeight>;
603
604 #[pallet::constant]
606 type Version: Get<RuntimeVersion>;
607
608 #[pallet::no_default_bounds]
615 type PalletInfo: PalletInfo;
616
617 type AccountData: Member + FullCodec + Clone + Default + TypeInfo + MaxEncodedLen;
620
621 type OnNewAccount: OnNewAccount<Self::AccountId>;
623
624 type OnKilledAccount: OnKilledAccount<Self::AccountId>;
628
629 type SystemWeightInfo: WeightInfo;
631
632 type ExtensionsWeightInfo: extensions::WeightInfo;
634
635 #[pallet::constant]
641 type SS58Prefix: Get<u16>;
642
643 #[pallet::no_default_bounds]
651 type OnSetCode: SetCode<Self>;
652
653 type MaxConsumers: ConsumerLimits;
655
656 type SingleBlockMigrations: OnRuntimeUpgrade;
663
664 type MultiBlockMigrator: MultiStepMigrator;
669
670 type PreInherents: PreInherents;
674
675 type PostInherents: PostInherents;
679
680 type PostTransactions: PostTransactions;
684 }
685
686 #[pallet::pallet]
687 pub struct Pallet<T>(_);
688
689 #[pallet::hooks]
690 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
691 #[cfg(feature = "std")]
692 fn integrity_test() {
693 T::BlockWeights::get().validate().expect("The weights are invalid.");
694 }
695 }
696
697 #[pallet::call(weight = <T as Config>::SystemWeightInfo)]
698 impl<T: Config> Pallet<T> {
699 #[pallet::call_index(0)]
703 #[pallet::weight(T::SystemWeightInfo::remark(remark.len() as u32))]
704 pub fn remark(_origin: OriginFor<T>, remark: Vec<u8>) -> DispatchResultWithPostInfo {
705 let _ = remark; Ok(().into())
707 }
708
709 #[pallet::call_index(1)]
711 #[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))]
712 pub fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo {
713 ensure_root(origin)?;
714 storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
715 Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
716 Ok(().into())
717 }
718
719 #[pallet::call_index(2)]
721 #[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
722 pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo {
723 ensure_root(origin)?;
724 Self::can_set_code(&code, true).into_result()?;
725 T::OnSetCode::set_code(code)?;
726 Ok(Some(T::BlockWeights::get().max_block).into())
728 }
729
730 #[pallet::call_index(3)]
735 #[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
736 pub fn set_code_without_checks(
737 origin: OriginFor<T>,
738 code: Vec<u8>,
739 ) -> DispatchResultWithPostInfo {
740 ensure_root(origin)?;
741 Self::can_set_code(&code, false).into_result()?;
742 T::OnSetCode::set_code(code)?;
743 Ok(Some(T::BlockWeights::get().max_block).into())
744 }
745
746 #[pallet::call_index(4)]
748 #[pallet::weight((
749 T::SystemWeightInfo::set_storage(items.len() as u32),
750 DispatchClass::Operational,
751 ))]
752 pub fn set_storage(
753 origin: OriginFor<T>,
754 items: Vec<KeyValue>,
755 ) -> DispatchResultWithPostInfo {
756 ensure_root(origin)?;
757 for i in &items {
758 storage::unhashed::put_raw(&i.0, &i.1);
759 }
760 Ok(().into())
761 }
762
763 #[pallet::call_index(5)]
765 #[pallet::weight((
766 T::SystemWeightInfo::kill_storage(keys.len() as u32),
767 DispatchClass::Operational,
768 ))]
769 pub fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo {
770 ensure_root(origin)?;
771 for key in &keys {
772 storage::unhashed::kill(key);
773 }
774 Ok(().into())
775 }
776
777 #[pallet::call_index(6)]
782 #[pallet::weight((
783 T::SystemWeightInfo::kill_prefix(subkeys.saturating_add(1)),
784 DispatchClass::Operational,
785 ))]
786 pub fn kill_prefix(
787 origin: OriginFor<T>,
788 prefix: Key,
789 subkeys: u32,
790 ) -> DispatchResultWithPostInfo {
791 ensure_root(origin)?;
792 let _ = storage::unhashed::clear_prefix(&prefix, Some(subkeys), None);
793 Ok(().into())
794 }
795
796 #[pallet::call_index(7)]
798 #[pallet::weight(T::SystemWeightInfo::remark_with_event(remark.len() as u32))]
799 pub fn remark_with_event(
800 origin: OriginFor<T>,
801 remark: Vec<u8>,
802 ) -> DispatchResultWithPostInfo {
803 let who = ensure_signed(origin)?;
804 let hash = T::Hashing::hash(&remark[..]);
805 Self::deposit_event(Event::Remarked { sender: who, hash });
806 Ok(().into())
807 }
808
809 #[cfg(feature = "experimental")]
810 #[pallet::call_index(8)]
811 #[pallet::weight(task.weight())]
812 pub fn do_task(_origin: OriginFor<T>, task: T::RuntimeTask) -> DispatchResultWithPostInfo {
813 if !task.is_valid() {
814 return Err(Error::<T>::InvalidTask.into())
815 }
816
817 Self::deposit_event(Event::TaskStarted { task: task.clone() });
818 if let Err(err) = task.run() {
819 Self::deposit_event(Event::TaskFailed { task, err });
820 return Err(Error::<T>::FailedTask.into())
821 }
822
823 Self::deposit_event(Event::TaskCompleted { task });
825
826 Ok(().into())
828 }
829
830 #[pallet::call_index(9)]
835 #[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
836 pub fn authorize_upgrade(origin: OriginFor<T>, code_hash: T::Hash) -> DispatchResult {
837 ensure_root(origin)?;
838 Self::do_authorize_upgrade(code_hash, true);
839 Ok(())
840 }
841
842 #[pallet::call_index(10)]
851 #[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
852 pub fn authorize_upgrade_without_checks(
853 origin: OriginFor<T>,
854 code_hash: T::Hash,
855 ) -> DispatchResult {
856 ensure_root(origin)?;
857 Self::do_authorize_upgrade(code_hash, false);
858 Ok(())
859 }
860
861 #[pallet::call_index(11)]
871 #[pallet::weight((T::SystemWeightInfo::apply_authorized_upgrade(), DispatchClass::Operational))]
872 pub fn apply_authorized_upgrade(
873 _: OriginFor<T>,
874 code: Vec<u8>,
875 ) -> DispatchResultWithPostInfo {
876 let res = Self::validate_code_is_authorized(&code)?;
877 AuthorizedUpgrade::<T>::kill();
878
879 match Self::can_set_code(&code, res.check_version) {
880 CanSetCodeResult::Ok => {},
881 CanSetCodeResult::MultiBlockMigrationsOngoing =>
882 return Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
883 CanSetCodeResult::InvalidVersion(error) => {
884 Self::deposit_event(Event::RejectedInvalidAuthorizedUpgrade {
886 code_hash: res.code_hash,
887 error: error.into(),
888 });
889
890 return Ok(Pays::No.into())
892 },
893 };
894 T::OnSetCode::set_code(code)?;
895
896 Ok(PostDispatchInfo {
897 actual_weight: Some(T::BlockWeights::get().max_block),
899 pays_fee: Pays::No,
901 })
902 }
903 }
904
905 #[pallet::event]
907 pub enum Event<T: Config> {
908 ExtrinsicSuccess { dispatch_info: DispatchEventInfo },
910 ExtrinsicFailed { dispatch_error: DispatchError, dispatch_info: DispatchEventInfo },
912 CodeUpdated,
914 NewAccount { account: T::AccountId },
916 KilledAccount { account: T::AccountId },
918 Remarked { sender: T::AccountId, hash: T::Hash },
920 #[cfg(feature = "experimental")]
921 TaskStarted { task: T::RuntimeTask },
923 #[cfg(feature = "experimental")]
924 TaskCompleted { task: T::RuntimeTask },
926 #[cfg(feature = "experimental")]
927 TaskFailed { task: T::RuntimeTask, err: DispatchError },
929 UpgradeAuthorized { code_hash: T::Hash, check_version: bool },
931 RejectedInvalidAuthorizedUpgrade { code_hash: T::Hash, error: DispatchError },
933 }
934
935 #[pallet::error]
937 pub enum Error<T> {
938 InvalidSpecName,
941 SpecVersionNeedsToIncrease,
944 FailedToExtractRuntimeVersion,
948 NonDefaultComposite,
950 NonZeroRefCount,
952 CallFiltered,
954 MultiBlockMigrationsOngoing,
956 #[cfg(feature = "experimental")]
957 InvalidTask,
959 #[cfg(feature = "experimental")]
960 FailedTask,
962 NothingAuthorized,
964 Unauthorized,
966 }
967
968 #[pallet::origin]
970 pub type Origin<T> = RawOrigin<<T as Config>::AccountId>;
971
972 #[pallet::storage]
974 #[pallet::getter(fn account)]
975 pub type Account<T: Config> = StorageMap<
976 _,
977 Blake2_128Concat,
978 T::AccountId,
979 AccountInfo<T::Nonce, T::AccountData>,
980 ValueQuery,
981 >;
982
983 #[pallet::storage]
985 #[pallet::whitelist_storage]
986 pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
987
988 #[pallet::storage]
990 #[pallet::whitelist_storage]
991 pub type InherentsApplied<T: Config> = StorageValue<_, bool, ValueQuery>;
992
993 #[pallet::storage]
995 #[pallet::whitelist_storage]
996 #[pallet::getter(fn block_weight)]
997 pub type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
998
999 #[pallet::storage]
1001 #[pallet::whitelist_storage]
1002 pub type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
1003
1004 #[pallet::storage]
1006 #[pallet::getter(fn block_hash)]
1007 pub type BlockHash<T: Config> =
1008 StorageMap<_, Twox64Concat, BlockNumberFor<T>, T::Hash, ValueQuery>;
1009
1010 #[pallet::storage]
1012 #[pallet::getter(fn extrinsic_data)]
1013 #[pallet::unbounded]
1014 pub(super) type ExtrinsicData<T: Config> =
1015 StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
1016
1017 #[pallet::storage]
1019 #[pallet::whitelist_storage]
1020 #[pallet::getter(fn block_number)]
1021 pub(super) type Number<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
1022
1023 #[pallet::storage]
1025 #[pallet::getter(fn parent_hash)]
1026 pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
1027
1028 #[pallet::storage]
1030 #[pallet::whitelist_storage]
1031 #[pallet::unbounded]
1032 #[pallet::getter(fn digest)]
1033 pub(super) type Digest<T: Config> = StorageValue<_, generic::Digest, ValueQuery>;
1034
1035 #[pallet::storage]
1043 #[pallet::whitelist_storage]
1044 #[pallet::disable_try_decode_storage]
1045 #[pallet::unbounded]
1046 pub(super) type Events<T: Config> =
1047 StorageValue<_, Vec<Box<EventRecord<T::RuntimeEvent, T::Hash>>>, ValueQuery>;
1048
1049 #[pallet::storage]
1051 #[pallet::whitelist_storage]
1052 #[pallet::getter(fn event_count)]
1053 pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
1054
1055 #[pallet::storage]
1066 #[pallet::unbounded]
1067 #[pallet::getter(fn event_topics)]
1068 pub(super) type EventTopics<T: Config> =
1069 StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor<T>, EventIndex)>, ValueQuery>;
1070
1071 #[pallet::storage]
1073 #[pallet::unbounded]
1074 pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
1075
1076 #[pallet::storage]
1078 pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1079
1080 #[pallet::storage]
1083 pub(super) type UpgradedToTripleRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1084
1085 #[pallet::storage]
1087 #[pallet::whitelist_storage]
1088 pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
1089
1090 #[pallet::storage]
1092 #[pallet::getter(fn authorized_upgrade)]
1093 pub(super) type AuthorizedUpgrade<T: Config> =
1094 StorageValue<_, CodeUpgradeAuthorization<T>, OptionQuery>;
1095
1096 #[pallet::storage]
1104 #[pallet::whitelist_storage]
1105 pub type ExtrinsicWeightReclaimed<T: Config> = StorageValue<_, Weight, ValueQuery>;
1106
1107 #[derive(frame_support::DefaultNoBound)]
1108 #[pallet::genesis_config]
1109 pub struct GenesisConfig<T: Config> {
1110 #[serde(skip)]
1111 pub _config: core::marker::PhantomData<T>,
1112 }
1113
1114 #[pallet::genesis_build]
1115 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
1116 fn build(&self) {
1117 <BlockHash<T>>::insert::<_, T::Hash>(BlockNumberFor::<T>::zero(), hash69());
1118 <ParentHash<T>>::put::<T::Hash>(hash69());
1119 <LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
1120 <UpgradedToU32RefCount<T>>::put(true);
1121 <UpgradedToTripleRefCount<T>>::put(true);
1122
1123 sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
1124 }
1125 }
1126
1127 #[pallet::validate_unsigned]
1128 impl<T: Config> sp_runtime::traits::ValidateUnsigned for Pallet<T> {
1129 type Call = Call<T>;
1130 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
1131 if let Call::apply_authorized_upgrade { ref code } = call {
1132 if let Ok(res) = Self::validate_code_is_authorized(&code[..]) {
1133 if Self::can_set_code(&code, false).is_ok() {
1134 return Ok(ValidTransaction {
1135 priority: u64::max_value(),
1136 requires: Vec::new(),
1137 provides: vec![res.code_hash.encode()],
1138 longevity: TransactionLongevity::max_value(),
1139 propagate: true,
1140 })
1141 }
1142 }
1143 }
1144
1145 #[cfg(feature = "experimental")]
1146 if let Call::do_task { ref task } = call {
1147 if source == TransactionSource::InBlock || source == TransactionSource::Local {
1155 if task.is_valid() {
1156 return Ok(ValidTransaction {
1157 priority: u64::max_value(),
1158 requires: Vec::new(),
1159 provides: vec![T::Hashing::hash_of(&task.encode()).as_ref().to_vec()],
1160 longevity: TransactionLongevity::max_value(),
1161 propagate: false,
1162 })
1163 }
1164 }
1165 }
1166
1167 #[cfg(not(feature = "experimental"))]
1168 let _ = source;
1169
1170 Err(InvalidTransaction::Call.into())
1171 }
1172 }
1173}
1174
1175pub type Key = Vec<u8>;
1176pub type KeyValue = (Vec<u8>, Vec<u8>);
1177
1178#[derive(Encode, Decode, Debug, TypeInfo, MaxEncodedLen)]
1180#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1181pub enum Phase {
1182 ApplyExtrinsic(u32),
1184 Finalization,
1186 Initialization,
1188}
1189
1190impl Default for Phase {
1191 fn default() -> Self {
1192 Self::Initialization
1193 }
1194}
1195
1196#[derive(Encode, Decode, Debug, TypeInfo)]
1198#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1199pub struct EventRecord<E: Parameter + Member, T> {
1200 pub phase: Phase,
1202 pub event: E,
1204 pub topics: Vec<T>,
1206}
1207
1208fn hash69<T: AsMut<[u8]> + Default>() -> T {
1211 let mut h = T::default();
1212 h.as_mut().iter_mut().for_each(|byte| *byte = 69);
1213 h
1214}
1215
1216type EventIndex = u32;
1221
1222pub type RefCount = u32;
1224
1225#[derive(Clone, Eq, PartialEq, Default, Debug, Encode, Decode, TypeInfo, MaxEncodedLen)]
1227pub struct AccountInfo<Nonce, AccountData> {
1228 pub nonce: Nonce,
1230 pub consumers: RefCount,
1233 pub providers: RefCount,
1236 pub sufficients: RefCount,
1239 pub data: AccountData,
1242}
1243
1244#[derive(Debug, Encode, Decode, TypeInfo)]
1247#[cfg_attr(feature = "std", derive(PartialEq))]
1248pub struct LastRuntimeUpgradeInfo {
1249 pub spec_version: codec::Compact<u32>,
1250 pub spec_name: Cow<'static, str>,
1251}
1252
1253impl LastRuntimeUpgradeInfo {
1254 pub fn was_upgraded(&self, current: &RuntimeVersion) -> bool {
1258 current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
1259 }
1260}
1261
1262impl From<RuntimeVersion> for LastRuntimeUpgradeInfo {
1263 fn from(version: RuntimeVersion) -> Self {
1264 Self { spec_version: version.spec_version.into(), spec_name: version.spec_name }
1265 }
1266}
1267
1268pub struct EnsureRoot<AccountId>(core::marker::PhantomData<AccountId>);
1270impl<O: OriginTrait, AccountId> EnsureOrigin<O> for EnsureRoot<AccountId> {
1271 type Success = ();
1272 fn try_origin(o: O) -> Result<Self::Success, O> {
1273 match o.as_system_ref() {
1274 Some(RawOrigin::Root) => Ok(()),
1275 _ => Err(o),
1276 }
1277 }
1278
1279 #[cfg(feature = "runtime-benchmarks")]
1280 fn try_successful_origin() -> Result<O, ()> {
1281 Ok(O::root())
1282 }
1283}
1284
1285impl_ensure_origin_with_arg_ignoring_arg! {
1286 impl< { O: .., AccountId: Decode, T } >
1287 EnsureOriginWithArg<O, T> for EnsureRoot<AccountId>
1288 {}
1289}
1290
1291pub struct EnsureRootWithSuccess<AccountId, Success>(
1293 core::marker::PhantomData<(AccountId, Success)>,
1294);
1295impl<O: OriginTrait, AccountId, Success: TypedGet> EnsureOrigin<O>
1296 for EnsureRootWithSuccess<AccountId, Success>
1297{
1298 type Success = Success::Type;
1299 fn try_origin(o: O) -> Result<Self::Success, O> {
1300 match o.as_system_ref() {
1301 Some(RawOrigin::Root) => Ok(Success::get()),
1302 _ => Err(o),
1303 }
1304 }
1305
1306 #[cfg(feature = "runtime-benchmarks")]
1307 fn try_successful_origin() -> Result<O, ()> {
1308 Ok(O::root())
1309 }
1310}
1311
1312impl_ensure_origin_with_arg_ignoring_arg! {
1313 impl< { O: .., AccountId: Decode, Success: TypedGet, T } >
1314 EnsureOriginWithArg<O, T> for EnsureRootWithSuccess<AccountId, Success>
1315 {}
1316}
1317
1318pub struct EnsureWithSuccess<Ensure, AccountId, Success>(
1320 core::marker::PhantomData<(Ensure, AccountId, Success)>,
1321);
1322
1323impl<O: OriginTrait, Ensure: EnsureOrigin<O>, AccountId, Success: TypedGet> EnsureOrigin<O>
1324 for EnsureWithSuccess<Ensure, AccountId, Success>
1325{
1326 type Success = Success::Type;
1327
1328 fn try_origin(o: O) -> Result<Self::Success, O> {
1329 Ensure::try_origin(o).map(|_| Success::get())
1330 }
1331
1332 #[cfg(feature = "runtime-benchmarks")]
1333 fn try_successful_origin() -> Result<O, ()> {
1334 Ensure::try_successful_origin()
1335 }
1336}
1337
1338pub struct EnsureSigned<AccountId>(core::marker::PhantomData<AccountId>);
1340impl<O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone> EnsureOrigin<O>
1341 for EnsureSigned<AccountId>
1342{
1343 type Success = AccountId;
1344 fn try_origin(o: O) -> Result<Self::Success, O> {
1345 match o.as_system_ref() {
1346 Some(RawOrigin::Signed(who)) => Ok(who.clone()),
1347 _ => Err(o),
1348 }
1349 }
1350
1351 #[cfg(feature = "runtime-benchmarks")]
1352 fn try_successful_origin() -> Result<O, ()> {
1353 let zero_account_id =
1354 AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?;
1355 Ok(O::signed(zero_account_id))
1356 }
1357}
1358
1359impl_ensure_origin_with_arg_ignoring_arg! {
1360 impl< { O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone, T } >
1361 EnsureOriginWithArg<O, T> for EnsureSigned<AccountId>
1362 {}
1363}
1364
1365pub struct EnsureSignedBy<Who, AccountId>(core::marker::PhantomData<(Who, AccountId)>);
1367impl<
1368 O: OriginTrait<AccountId = AccountId>,
1369 Who: SortedMembers<AccountId>,
1370 AccountId: PartialEq + Clone + Ord + Decode,
1371 > EnsureOrigin<O> for EnsureSignedBy<Who, AccountId>
1372{
1373 type Success = AccountId;
1374 fn try_origin(o: O) -> Result<Self::Success, O> {
1375 match o.as_system_ref() {
1376 Some(RawOrigin::Signed(ref who)) if Who::contains(who) => Ok(who.clone()),
1377 _ => Err(o),
1378 }
1379 }
1380
1381 #[cfg(feature = "runtime-benchmarks")]
1382 fn try_successful_origin() -> Result<O, ()> {
1383 let first_member = match Who::sorted_members().first() {
1384 Some(account) => account.clone(),
1385 None => AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?,
1386 };
1387 Ok(O::signed(first_member))
1388 }
1389}
1390
1391impl_ensure_origin_with_arg_ignoring_arg! {
1392 impl< { O: OriginTrait<AccountId = AccountId>, Who: SortedMembers<AccountId>, AccountId: PartialEq + Clone + Ord + Decode, T } >
1393 EnsureOriginWithArg<O, T> for EnsureSignedBy<Who, AccountId>
1394 {}
1395}
1396
1397pub struct EnsureNone<AccountId>(core::marker::PhantomData<AccountId>);
1399impl<O: OriginTrait<AccountId = AccountId>, AccountId> EnsureOrigin<O> for EnsureNone<AccountId> {
1400 type Success = ();
1401 fn try_origin(o: O) -> Result<Self::Success, O> {
1402 match o.as_system_ref() {
1403 Some(RawOrigin::None) => Ok(()),
1404 _ => Err(o),
1405 }
1406 }
1407
1408 #[cfg(feature = "runtime-benchmarks")]
1409 fn try_successful_origin() -> Result<O, ()> {
1410 Ok(O::none())
1411 }
1412}
1413
1414impl_ensure_origin_with_arg_ignoring_arg! {
1415 impl< { O: OriginTrait<AccountId = AccountId>, AccountId, T } >
1416 EnsureOriginWithArg<O, T> for EnsureNone<AccountId>
1417 {}
1418}
1419
1420pub struct EnsureNever<Success>(core::marker::PhantomData<Success>);
1422impl<O, Success> EnsureOrigin<O> for EnsureNever<Success> {
1423 type Success = Success;
1424 fn try_origin(o: O) -> Result<Self::Success, O> {
1425 Err(o)
1426 }
1427
1428 #[cfg(feature = "runtime-benchmarks")]
1429 fn try_successful_origin() -> Result<O, ()> {
1430 Err(())
1431 }
1432}
1433
1434impl_ensure_origin_with_arg_ignoring_arg! {
1435 impl< { O, Success, T } >
1436 EnsureOriginWithArg<O, T> for EnsureNever<Success>
1437 {}
1438}
1439
1440#[docify::export]
1441pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
1444where
1445 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1446{
1447 match o.into() {
1448 Ok(RawOrigin::Signed(t)) => Ok(t),
1449 _ => Err(BadOrigin),
1450 }
1451}
1452
1453pub fn ensure_signed_or_root<OuterOrigin, AccountId>(
1457 o: OuterOrigin,
1458) -> Result<Option<AccountId>, BadOrigin>
1459where
1460 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1461{
1462 match o.into() {
1463 Ok(RawOrigin::Root) => Ok(None),
1464 Ok(RawOrigin::Signed(t)) => Ok(Some(t)),
1465 _ => Err(BadOrigin),
1466 }
1467}
1468
1469pub fn ensure_root<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1471where
1472 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1473{
1474 match o.into() {
1475 Ok(RawOrigin::Root) => Ok(()),
1476 _ => Err(BadOrigin),
1477 }
1478}
1479
1480pub fn ensure_none<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1482where
1483 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1484{
1485 match o.into() {
1486 Ok(RawOrigin::None) => Ok(()),
1487 _ => Err(BadOrigin),
1488 }
1489}
1490
1491pub fn ensure_authorized<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1494where
1495 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1496{
1497 match o.into() {
1498 Ok(RawOrigin::Authorized) => Ok(()),
1499 _ => Err(BadOrigin),
1500 }
1501}
1502
1503#[derive(Debug)]
1505pub enum RefStatus {
1506 Referenced,
1507 Unreferenced,
1508}
1509
1510#[derive(Eq, PartialEq, Debug)]
1512pub enum IncRefStatus {
1513 Created,
1515 Existed,
1517}
1518
1519#[derive(Eq, PartialEq, Debug)]
1521pub enum DecRefStatus {
1522 Reaped,
1524 Exists,
1526}
1527
1528pub enum CanSetCodeResult<T: Config> {
1530 Ok,
1532 MultiBlockMigrationsOngoing,
1534 InvalidVersion(Error<T>),
1536}
1537
1538impl<T: Config> CanSetCodeResult<T> {
1539 pub fn into_result(self) -> Result<(), DispatchError> {
1541 match self {
1542 Self::Ok => Ok(()),
1543 Self::MultiBlockMigrationsOngoing =>
1544 Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
1545 Self::InvalidVersion(err) => Err(err.into()),
1546 }
1547 }
1548
1549 pub fn is_ok(&self) -> bool {
1551 matches!(self, Self::Ok)
1552 }
1553}
1554
1555impl<T: Config> Pallet<T> {
1556 #[doc = docify::embed!("src/tests.rs", last_runtime_upgrade_spec_version_usage)]
1570 pub fn last_runtime_upgrade_spec_version() -> u32 {
1571 LastRuntimeUpgrade::<T>::get().map_or(0, |l| l.spec_version.0)
1572 }
1573
1574 pub fn account_exists(who: &T::AccountId) -> bool {
1576 Account::<T>::contains_key(who)
1577 }
1578
1579 pub fn update_code_in_storage(code: &[u8]) {
1585 storage::unhashed::put_raw(well_known_keys::CODE, code);
1586 Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
1587 Self::deposit_event(Event::CodeUpdated);
1588 }
1589
1590 pub fn inherents_applied() -> bool {
1592 InherentsApplied::<T>::get()
1593 }
1594
1595 pub fn note_inherents_applied() {
1600 InherentsApplied::<T>::put(true);
1601 }
1602
1603 #[deprecated = "Use `inc_consumers` instead"]
1605 pub fn inc_ref(who: &T::AccountId) {
1606 let _ = Self::inc_consumers(who);
1607 }
1608
1609 #[deprecated = "Use `dec_consumers` instead"]
1612 pub fn dec_ref(who: &T::AccountId) {
1613 let _ = Self::dec_consumers(who);
1614 }
1615
1616 #[deprecated = "Use `consumers` instead"]
1618 pub fn refs(who: &T::AccountId) -> RefCount {
1619 Self::consumers(who)
1620 }
1621
1622 #[deprecated = "Use `!is_provider_required` instead"]
1624 pub fn allow_death(who: &T::AccountId) -> bool {
1625 !Self::is_provider_required(who)
1626 }
1627
1628 pub fn inc_providers(who: &T::AccountId) -> IncRefStatus {
1630 Account::<T>::mutate(who, |a| {
1631 if a.providers == 0 && a.sufficients == 0 {
1632 a.providers = 1;
1634 Self::on_created_account(who.clone(), a);
1635 IncRefStatus::Created
1636 } else {
1637 a.providers = a.providers.saturating_add(1);
1638 IncRefStatus::Existed
1639 }
1640 })
1641 }
1642
1643 pub fn dec_providers(who: &T::AccountId) -> Result<DecRefStatus, DispatchError> {
1647 Account::<T>::try_mutate_exists(who, |maybe_account| {
1648 if let Some(mut account) = maybe_account.take() {
1649 if account.providers == 0 {
1650 log::error!(
1652 target: LOG_TARGET,
1653 "Logic error: Unexpected underflow in reducing provider",
1654 );
1655 account.providers = 1;
1656 }
1657 match (account.providers, account.consumers, account.sufficients) {
1658 (1, 0, 0) => {
1659 Pallet::<T>::on_killed_account(who.clone());
1662 Ok(DecRefStatus::Reaped)
1663 },
1664 (1, c, _) if c > 0 => {
1665 Err(DispatchError::ConsumerRemaining)
1667 },
1668 (x, _, _) => {
1669 account.providers = x - 1;
1672 *maybe_account = Some(account);
1673 Ok(DecRefStatus::Exists)
1674 },
1675 }
1676 } else {
1677 log::error!(
1678 target: LOG_TARGET,
1679 "Logic error: Account already dead when reducing provider",
1680 );
1681 Ok(DecRefStatus::Reaped)
1682 }
1683 })
1684 }
1685
1686 pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus {
1688 Account::<T>::mutate(who, |a| {
1689 if a.providers + a.sufficients == 0 {
1690 a.sufficients = 1;
1692 Self::on_created_account(who.clone(), a);
1693 IncRefStatus::Created
1694 } else {
1695 a.sufficients = a.sufficients.saturating_add(1);
1696 IncRefStatus::Existed
1697 }
1698 })
1699 }
1700
1701 pub fn dec_sufficients(who: &T::AccountId) -> DecRefStatus {
1705 Account::<T>::mutate_exists(who, |maybe_account| {
1706 if let Some(mut account) = maybe_account.take() {
1707 if account.sufficients == 0 {
1708 log::error!(
1710 target: LOG_TARGET,
1711 "Logic error: Unexpected underflow in reducing sufficients",
1712 );
1713 }
1714 match (account.sufficients, account.providers) {
1715 (0, 0) | (1, 0) => {
1716 Pallet::<T>::on_killed_account(who.clone());
1717 DecRefStatus::Reaped
1718 },
1719 (x, _) => {
1720 account.sufficients = x.saturating_sub(1);
1721 *maybe_account = Some(account);
1722 DecRefStatus::Exists
1723 },
1724 }
1725 } else {
1726 log::error!(
1727 target: LOG_TARGET,
1728 "Logic error: Account already dead when reducing provider",
1729 );
1730 DecRefStatus::Reaped
1731 }
1732 })
1733 }
1734
1735 pub fn providers(who: &T::AccountId) -> RefCount {
1737 Account::<T>::get(who).providers
1738 }
1739
1740 pub fn sufficients(who: &T::AccountId) -> RefCount {
1742 Account::<T>::get(who).sufficients
1743 }
1744
1745 pub fn reference_count(who: &T::AccountId) -> RefCount {
1747 let a = Account::<T>::get(who);
1748 a.providers + a.sufficients
1749 }
1750
1751 pub fn inc_consumers(who: &T::AccountId) -> Result<(), DispatchError> {
1756 Account::<T>::try_mutate(who, |a| {
1757 if a.providers > 0 {
1758 if a.consumers < T::MaxConsumers::max_consumers() {
1759 a.consumers = a.consumers.saturating_add(1);
1760 Ok(())
1761 } else {
1762 Err(DispatchError::TooManyConsumers)
1763 }
1764 } else {
1765 Err(DispatchError::NoProviders)
1766 }
1767 })
1768 }
1769
1770 pub fn inc_consumers_without_limit(who: &T::AccountId) -> Result<(), DispatchError> {
1774 Account::<T>::try_mutate(who, |a| {
1775 if a.providers > 0 {
1776 a.consumers = a.consumers.saturating_add(1);
1777 Ok(())
1778 } else {
1779 Err(DispatchError::NoProviders)
1780 }
1781 })
1782 }
1783
1784 pub fn dec_consumers(who: &T::AccountId) {
1787 Account::<T>::mutate(who, |a| {
1788 if a.consumers > 0 {
1789 a.consumers -= 1;
1790 } else {
1791 log::error!(
1792 target: LOG_TARGET,
1793 "Logic error: Unexpected underflow in reducing consumer",
1794 );
1795 }
1796 })
1797 }
1798
1799 pub fn consumers(who: &T::AccountId) -> RefCount {
1801 Account::<T>::get(who).consumers
1802 }
1803
1804 pub fn is_provider_required(who: &T::AccountId) -> bool {
1806 Account::<T>::get(who).consumers != 0
1807 }
1808
1809 pub fn can_dec_provider(who: &T::AccountId) -> bool {
1811 let a = Account::<T>::get(who);
1812 a.consumers == 0 || a.providers > 1
1813 }
1814
1815 pub fn can_accrue_consumers(who: &T::AccountId, amount: u32) -> bool {
1818 let a = Account::<T>::get(who);
1819 match a.consumers.checked_add(amount) {
1820 Some(c) => a.providers > 0 && c <= T::MaxConsumers::max_consumers(),
1821 None => false,
1822 }
1823 }
1824
1825 pub fn can_inc_consumer(who: &T::AccountId) -> bool {
1828 Self::can_accrue_consumers(who, 1)
1829 }
1830
1831 pub fn deposit_event(event: impl Into<T::RuntimeEvent>) {
1835 Self::deposit_event_indexed(&[], event.into());
1836 }
1837
1838 pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
1846 let block_number = Self::block_number();
1847
1848 if block_number.is_zero() {
1850 return
1851 }
1852
1853 let phase = ExecutionPhase::<T>::get().unwrap_or_default();
1854 let event = EventRecord { phase, event, topics: topics.to_vec() };
1855
1856 let event_idx = {
1858 let old_event_count = EventCount::<T>::get();
1859 let new_event_count = match old_event_count.checked_add(1) {
1860 None => return,
1863 Some(nc) => nc,
1864 };
1865 EventCount::<T>::put(new_event_count);
1866 old_event_count
1867 };
1868
1869 Events::<T>::append(event);
1870
1871 for topic in topics {
1872 <EventTopics<T>>::append(topic, &(block_number, event_idx));
1873 }
1874 }
1875
1876 pub fn extrinsic_index() -> Option<u32> {
1878 storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
1879 }
1880
1881 pub fn extrinsic_count() -> u32 {
1883 ExtrinsicCount::<T>::get().unwrap_or_default()
1884 }
1885
1886 pub fn all_extrinsics_len() -> u32 {
1887 AllExtrinsicsLen::<T>::get().unwrap_or_default()
1888 }
1889
1890 pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) {
1906 BlockWeight::<T>::mutate(|current_weight| {
1907 current_weight.accrue(weight, class);
1908 });
1909 }
1910
1911 pub fn initialize(number: &BlockNumberFor<T>, parent_hash: &T::Hash, digest: &generic::Digest) {
1918 let expected_block_number = Self::block_number() + One::one();
1919 assert_eq!(expected_block_number, *number, "Block number must be strictly increasing.");
1920
1921 ExecutionPhase::<T>::put(Phase::Initialization);
1923 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
1924 Self::initialize_intra_block_entropy(parent_hash);
1925 <Number<T>>::put(number);
1926 <Digest<T>>::put(digest);
1927 <ParentHash<T>>::put(parent_hash);
1928 <BlockHash<T>>::insert(*number - One::one(), parent_hash);
1929
1930 BlockWeight::<T>::kill();
1932 }
1933
1934 pub fn initialize_intra_block_entropy(parent_hash: &T::Hash) {
1938 let entropy = (b"frame_system::initialize", parent_hash).using_encoded(blake2_256);
1939 storage::unhashed::put_raw(well_known_keys::INTRABLOCK_ENTROPY, &entropy[..]);
1940 }
1941
1942 pub fn resource_usage_report() {
1946 log::debug!(
1947 target: LOG_TARGET,
1948 "[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\
1949 {} (ref_time: {}%, proof_size: {}%) op weight {} (ref_time {}%, proof_size {}%) / \
1950 mandatory weight {} (ref_time: {}%, proof_size: {}%)",
1951 Self::block_number(),
1952 Self::extrinsic_count(),
1953 Self::all_extrinsics_len(),
1954 sp_runtime::Percent::from_rational(
1955 Self::all_extrinsics_len(),
1956 *T::BlockLength::get().max.get(DispatchClass::Normal)
1957 ).deconstruct(),
1958 sp_runtime::Percent::from_rational(
1959 Self::all_extrinsics_len(),
1960 *T::BlockLength::get().max.get(DispatchClass::Operational)
1961 ).deconstruct(),
1962 sp_runtime::Percent::from_rational(
1963 Self::all_extrinsics_len(),
1964 *T::BlockLength::get().max.get(DispatchClass::Mandatory)
1965 ).deconstruct(),
1966 Self::block_weight().get(DispatchClass::Normal),
1967 sp_runtime::Percent::from_rational(
1968 Self::block_weight().get(DispatchClass::Normal).ref_time(),
1969 T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).ref_time()
1970 ).deconstruct(),
1971 sp_runtime::Percent::from_rational(
1972 Self::block_weight().get(DispatchClass::Normal).proof_size(),
1973 T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).proof_size()
1974 ).deconstruct(),
1975 Self::block_weight().get(DispatchClass::Operational),
1976 sp_runtime::Percent::from_rational(
1977 Self::block_weight().get(DispatchClass::Operational).ref_time(),
1978 T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).ref_time()
1979 ).deconstruct(),
1980 sp_runtime::Percent::from_rational(
1981 Self::block_weight().get(DispatchClass::Operational).proof_size(),
1982 T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).proof_size()
1983 ).deconstruct(),
1984 Self::block_weight().get(DispatchClass::Mandatory),
1985 sp_runtime::Percent::from_rational(
1986 Self::block_weight().get(DispatchClass::Mandatory).ref_time(),
1987 T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).ref_time()
1988 ).deconstruct(),
1989 sp_runtime::Percent::from_rational(
1990 Self::block_weight().get(DispatchClass::Mandatory).proof_size(),
1991 T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).proof_size()
1992 ).deconstruct(),
1993 );
1994 }
1995
1996 pub fn finalize() -> HeaderFor<T> {
1999 Self::resource_usage_report();
2000 ExecutionPhase::<T>::kill();
2001 AllExtrinsicsLen::<T>::kill();
2002 storage::unhashed::kill(well_known_keys::INTRABLOCK_ENTROPY);
2003 InherentsApplied::<T>::kill();
2004
2005 let number = <Number<T>>::get();
2016 let parent_hash = <ParentHash<T>>::get();
2017 let digest = <Digest<T>>::get();
2018
2019 let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
2020 .map(ExtrinsicData::<T>::take)
2021 .collect();
2022 let extrinsics_root_state_version = T::Version::get().extrinsics_root_state_version();
2023 let extrinsics_root =
2024 extrinsics_data_root::<T::Hashing>(extrinsics, extrinsics_root_state_version);
2025
2026 let block_hash_count = T::BlockHashCount::get();
2028 let to_remove = number.saturating_sub(block_hash_count).saturating_sub(One::one());
2029
2030 if !to_remove.is_zero() {
2032 <BlockHash<T>>::remove(to_remove);
2033 }
2034
2035 let version = T::Version::get().state_version();
2036 let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..])
2037 .expect("Node is configured to use the same hash; qed");
2038
2039 HeaderFor::<T>::new(number, extrinsics_root, storage_root, parent_hash, digest)
2040 }
2041
2042 pub fn deposit_log(item: generic::DigestItem) {
2044 <Digest<T>>::append(item);
2045 }
2046
2047 #[cfg(any(feature = "std", test))]
2049 pub fn externalities() -> TestExternalities {
2050 TestExternalities::new(sp_core::storage::Storage {
2051 top: [
2052 (<BlockHash<T>>::hashed_key_for(BlockNumberFor::<T>::zero()), [69u8; 32].encode()),
2053 (<Number<T>>::hashed_key().to_vec(), BlockNumberFor::<T>::one().encode()),
2054 (<ParentHash<T>>::hashed_key().to_vec(), [69u8; 32].encode()),
2055 ]
2056 .into_iter()
2057 .collect(),
2058 children_default: Default::default(),
2059 })
2060 }
2061
2062 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2070 pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
2071 Self::read_events_no_consensus().map(|e| *e).collect()
2073 }
2074
2075 pub fn event_no_consensus(index: usize) -> Option<T::RuntimeEvent> {
2080 Self::read_events_no_consensus().nth(index).map(|e| e.event.clone())
2081 }
2082
2083 pub fn read_events_no_consensus(
2088 ) -> impl Iterator<Item = Box<EventRecord<T::RuntimeEvent, T::Hash>>> {
2089 Events::<T>::stream_iter()
2090 }
2091
2092 pub fn read_events_for_pallet<E>() -> Vec<E>
2097 where
2098 T::RuntimeEvent: TryInto<E>,
2099 {
2100 Events::<T>::get()
2101 .into_iter()
2102 .map(|er| er.event)
2103 .filter_map(|e| e.try_into().ok())
2104 .collect::<_>()
2105 }
2106
2107 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2116 pub fn run_to_block_with<AllPalletsWithSystem>(
2117 n: BlockNumberFor<T>,
2118 mut hooks: RunToBlockHooks<T>,
2119 ) where
2120 AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
2121 + frame_support::traits::OnFinalize<BlockNumberFor<T>>,
2122 {
2123 let mut bn = Self::block_number();
2124
2125 while bn < n {
2126 if !bn.is_zero() {
2128 (hooks.before_finalize)(bn);
2129 AllPalletsWithSystem::on_finalize(bn);
2130 (hooks.after_finalize)(bn);
2131 }
2132
2133 bn += One::one();
2134
2135 Self::set_block_number(bn);
2136 (hooks.before_initialize)(bn);
2137 AllPalletsWithSystem::on_initialize(bn);
2138 (hooks.after_initialize)(bn);
2139 }
2140 }
2141
2142 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2144 pub fn run_to_block<AllPalletsWithSystem>(n: BlockNumberFor<T>)
2145 where
2146 AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
2147 + frame_support::traits::OnFinalize<BlockNumberFor<T>>,
2148 {
2149 Self::run_to_block_with::<AllPalletsWithSystem>(n, Default::default());
2150 }
2151
2152 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2155 pub fn set_block_number(n: BlockNumberFor<T>) {
2156 <Number<T>>::put(n);
2157 }
2158
2159 #[cfg(any(feature = "std", test))]
2161 pub fn set_extrinsic_index(extrinsic_index: u32) {
2162 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
2163 }
2164
2165 #[cfg(any(feature = "std", test))]
2168 pub fn set_parent_hash(n: T::Hash) {
2169 <ParentHash<T>>::put(n);
2170 }
2171
2172 #[cfg(any(feature = "std", test))]
2174 pub fn set_block_consumed_resources(weight: Weight, len: usize) {
2175 BlockWeight::<T>::mutate(|current_weight| {
2176 current_weight.set(weight, DispatchClass::Normal)
2177 });
2178 AllExtrinsicsLen::<T>::put(len as u32);
2179 }
2180
2181 pub fn reset_events() {
2186 <Events<T>>::kill();
2187 EventCount::<T>::kill();
2188 let _ = <EventTopics<T>>::clear(u32::max_value(), None);
2189 }
2190
2191 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2195 #[track_caller]
2196 pub fn assert_has_event(event: T::RuntimeEvent) {
2197 let warn = if Self::block_number().is_zero() {
2198 "WARNING: block number is zero, and events are not registered at block number zero.\n"
2199 } else {
2200 ""
2201 };
2202
2203 let events = Self::events();
2204 assert!(
2205 events.iter().any(|record| record.event == event),
2206 "{warn}expected event {event:?} not found in events {events:?}",
2207 );
2208 }
2209
2210 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2214 #[track_caller]
2215 pub fn assert_last_event(event: T::RuntimeEvent) {
2216 let warn = if Self::block_number().is_zero() {
2217 "WARNING: block number is zero, and events are not registered at block number zero.\n"
2218 } else {
2219 ""
2220 };
2221
2222 let last_event = Self::events()
2223 .last()
2224 .expect(&alloc::format!("{warn}events expected"))
2225 .event
2226 .clone();
2227 assert_eq!(
2228 last_event, event,
2229 "{warn}expected event {event:?} is not equal to the last event {last_event:?}",
2230 );
2231 }
2232
2233 pub fn runtime_version() -> RuntimeVersion {
2235 T::Version::get()
2236 }
2237
2238 pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Nonce {
2240 Account::<T>::get(who).nonce
2241 }
2242
2243 pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
2245 Account::<T>::mutate(who, |a| a.nonce += T::Nonce::one());
2246 }
2247
2248 pub fn note_extrinsic(encoded_xt: Vec<u8>) {
2253 ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
2254 }
2255
2256 pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, info: DispatchInfo) {
2262 let weight = extract_actual_weight(r, &info)
2263 .saturating_add(T::BlockWeights::get().get(info.class).base_extrinsic);
2264 let class = info.class;
2265 let pays_fee = extract_actual_pays_fee(r, &info);
2266 let dispatch_event_info = DispatchEventInfo { weight, class, pays_fee };
2267
2268 Self::deposit_event(match r {
2269 Ok(_) => Event::ExtrinsicSuccess { dispatch_info: dispatch_event_info },
2270 Err(err) => {
2271 log::trace!(
2272 target: LOG_TARGET,
2273 "Extrinsic failed at block({:?}): {:?}",
2274 Self::block_number(),
2275 err,
2276 );
2277 Event::ExtrinsicFailed {
2278 dispatch_error: err.error,
2279 dispatch_info: dispatch_event_info,
2280 }
2281 },
2282 });
2283
2284 log::trace!(
2285 target: LOG_TARGET,
2286 "Used block weight: {:?}",
2287 BlockWeight::<T>::get(),
2288 );
2289
2290 log::trace!(
2291 target: LOG_TARGET,
2292 "Used block length: {:?}",
2293 Pallet::<T>::all_extrinsics_len(),
2294 );
2295
2296 let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
2297
2298 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
2299 ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index));
2300 ExtrinsicWeightReclaimed::<T>::kill();
2301 }
2302
2303 pub fn note_finished_extrinsics() {
2306 let extrinsic_index: u32 =
2307 storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
2308 ExtrinsicCount::<T>::put(extrinsic_index);
2309 ExecutionPhase::<T>::put(Phase::Finalization);
2310 }
2311
2312 pub fn note_finished_initialize() {
2315 ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0))
2316 }
2317
2318 pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Nonce, T::AccountData>) {
2320 T::OnNewAccount::on_new_account(&who);
2321 Self::deposit_event(Event::NewAccount { account: who });
2322 }
2323
2324 fn on_killed_account(who: T::AccountId) {
2326 T::OnKilledAccount::on_killed_account(&who);
2327 Self::deposit_event(Event::KilledAccount { account: who });
2328 }
2329
2330 pub fn can_set_code(code: &[u8], check_version: bool) -> CanSetCodeResult<T> {
2334 if T::MultiBlockMigrator::ongoing() {
2335 return CanSetCodeResult::MultiBlockMigrationsOngoing
2336 }
2337
2338 if check_version {
2339 let current_version = T::Version::get();
2340 let Some(new_version) = sp_io::misc::runtime_version(code)
2341 .and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
2342 else {
2343 return CanSetCodeResult::InvalidVersion(Error::<T>::FailedToExtractRuntimeVersion)
2344 };
2345
2346 cfg_if::cfg_if! {
2347 if #[cfg(all(feature = "runtime-benchmarks", not(test)))] {
2348 core::hint::black_box((new_version, current_version));
2350 } else {
2351 if new_version.spec_name != current_version.spec_name {
2352 return CanSetCodeResult::InvalidVersion(Error::<T>::InvalidSpecName)
2353 }
2354
2355 if new_version.spec_version <= current_version.spec_version {
2356 return CanSetCodeResult::InvalidVersion(Error::<T>::SpecVersionNeedsToIncrease)
2357 }
2358 }
2359 }
2360 }
2361
2362 CanSetCodeResult::Ok
2363 }
2364
2365 pub fn do_authorize_upgrade(code_hash: T::Hash, check_version: bool) {
2367 AuthorizedUpgrade::<T>::put(CodeUpgradeAuthorization { code_hash, check_version });
2368 Self::deposit_event(Event::UpgradeAuthorized { code_hash, check_version });
2369 }
2370
2371 fn validate_code_is_authorized(
2375 code: &[u8],
2376 ) -> Result<CodeUpgradeAuthorization<T>, DispatchError> {
2377 let authorization = AuthorizedUpgrade::<T>::get().ok_or(Error::<T>::NothingAuthorized)?;
2378 let actual_hash = T::Hashing::hash(code);
2379 ensure!(actual_hash == authorization.code_hash, Error::<T>::Unauthorized);
2380 Ok(authorization)
2381 }
2382
2383 pub fn reclaim_weight(
2388 info: &DispatchInfoOf<T::RuntimeCall>,
2389 post_info: &PostDispatchInfoOf<T::RuntimeCall>,
2390 ) -> Result<(), TransactionValidityError>
2391 where
2392 T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
2393 {
2394 let already_reclaimed = crate::ExtrinsicWeightReclaimed::<T>::get();
2395 let unspent = post_info.calc_unspent(info);
2396 let accurate_reclaim = already_reclaimed.max(unspent);
2397 let to_reclaim_more = accurate_reclaim.saturating_sub(already_reclaimed);
2399 if to_reclaim_more != Weight::zero() {
2400 crate::BlockWeight::<T>::mutate(|current_weight| {
2401 current_weight.reduce(to_reclaim_more, info.class);
2402 });
2403 crate::ExtrinsicWeightReclaimed::<T>::put(accurate_reclaim);
2404 }
2405
2406 Ok(())
2407 }
2408
2409 pub fn remaining_block_weight() -> WeightMeter {
2411 let limit = T::BlockWeights::get().max_block;
2412 let consumed = BlockWeight::<T>::get().total();
2413
2414 WeightMeter::with_consumed_and_limit(consumed, limit)
2415 }
2416}
2417
2418pub fn unique(entropy: impl Encode) -> [u8; 32] {
2421 let mut last = [0u8; 32];
2422 sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
2423 let next = (b"frame_system::unique", entropy, last).using_encoded(blake2_256);
2424 sp_io::storage::set(well_known_keys::INTRABLOCK_ENTROPY, &next);
2425 next
2426}
2427
2428pub struct Provider<T>(PhantomData<T>);
2430impl<T: Config> HandleLifetime<T::AccountId> for Provider<T> {
2431 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2432 Pallet::<T>::inc_providers(t);
2433 Ok(())
2434 }
2435 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2436 Pallet::<T>::dec_providers(t).map(|_| ())
2437 }
2438}
2439
2440pub struct SelfSufficient<T>(PhantomData<T>);
2442impl<T: Config> HandleLifetime<T::AccountId> for SelfSufficient<T> {
2443 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2444 Pallet::<T>::inc_sufficients(t);
2445 Ok(())
2446 }
2447 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2448 Pallet::<T>::dec_sufficients(t);
2449 Ok(())
2450 }
2451}
2452
2453pub struct Consumer<T>(PhantomData<T>);
2455impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> {
2456 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2457 Pallet::<T>::inc_consumers(t)
2458 }
2459 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2460 Pallet::<T>::dec_consumers(t);
2461 Ok(())
2462 }
2463}
2464
2465impl<T: Config> BlockNumberProvider for Pallet<T> {
2466 type BlockNumber = BlockNumberFor<T>;
2467
2468 fn current_block_number() -> Self::BlockNumber {
2469 Pallet::<T>::block_number()
2470 }
2471
2472 #[cfg(feature = "runtime-benchmarks")]
2473 fn set_block_number(n: BlockNumberFor<T>) {
2474 Self::set_block_number(n)
2475 }
2476}
2477
2478impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> {
2484 fn get(k: &T::AccountId) -> T::AccountData {
2485 Account::<T>::get(k).data
2486 }
2487
2488 fn try_mutate_exists<R, E: From<DispatchError>>(
2489 k: &T::AccountId,
2490 f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
2491 ) -> Result<R, E> {
2492 let account = Account::<T>::get(k);
2493 let is_default = account.data == T::AccountData::default();
2494 let mut some_data = if is_default { None } else { Some(account.data) };
2495 let result = f(&mut some_data)?;
2496 if Self::providers(k) > 0 || Self::sufficients(k) > 0 {
2497 Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
2498 } else {
2499 Account::<T>::remove(k)
2500 }
2501 Ok(result)
2502 }
2503}
2504
2505pub fn split_inner<T, R, S>(
2507 option: Option<T>,
2508 splitter: impl FnOnce(T) -> (R, S),
2509) -> (Option<R>, Option<S>) {
2510 match option {
2511 Some(inner) => {
2512 let (r, s) = splitter(inner);
2513 (Some(r), Some(s))
2514 },
2515 None => (None, None),
2516 }
2517}
2518
2519pub struct ChainContext<T>(PhantomData<T>);
2520impl<T> Default for ChainContext<T> {
2521 fn default() -> Self {
2522 ChainContext(PhantomData)
2523 }
2524}
2525
2526impl<T: Config> Lookup for ChainContext<T> {
2527 type Source = <T::Lookup as StaticLookup>::Source;
2528 type Target = <T::Lookup as StaticLookup>::Target;
2529
2530 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
2531 <T::Lookup as StaticLookup>::lookup(s)
2532 }
2533}
2534
2535#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2537pub struct RunToBlockHooks<'a, T>
2538where
2539 T: 'a + Config,
2540{
2541 before_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2542 after_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2543 before_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2544 after_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2545}
2546
2547#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2548impl<'a, T> RunToBlockHooks<'a, T>
2549where
2550 T: 'a + Config,
2551{
2552 pub fn before_initialize<F>(mut self, f: F) -> Self
2554 where
2555 F: 'a + FnMut(BlockNumberFor<T>),
2556 {
2557 self.before_initialize = Box::new(f);
2558 self
2559 }
2560 pub fn after_initialize<F>(mut self, f: F) -> Self
2562 where
2563 F: 'a + FnMut(BlockNumberFor<T>),
2564 {
2565 self.after_initialize = Box::new(f);
2566 self
2567 }
2568 pub fn before_finalize<F>(mut self, f: F) -> Self
2570 where
2571 F: 'a + FnMut(BlockNumberFor<T>),
2572 {
2573 self.before_finalize = Box::new(f);
2574 self
2575 }
2576 pub fn after_finalize<F>(mut self, f: F) -> Self
2578 where
2579 F: 'a + FnMut(BlockNumberFor<T>),
2580 {
2581 self.after_finalize = Box::new(f);
2582 self
2583 }
2584}
2585
2586#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2587impl<'a, T> Default for RunToBlockHooks<'a, T>
2588where
2589 T: Config,
2590{
2591 fn default() -> Self {
2592 Self {
2593 before_initialize: Box::new(|_| {}),
2594 after_initialize: Box::new(|_| {}),
2595 before_finalize: Box::new(|_| {}),
2596 after_finalize: Box::new(|_| {}),
2597 }
2598 }
2599}
2600
2601pub mod pallet_prelude {
2603 pub use crate::{
2604 ensure_authorized, ensure_none, ensure_root, ensure_signed, ensure_signed_or_root,
2605 };
2606
2607 pub type OriginFor<T> = <T as crate::Config>::RuntimeOrigin;
2609
2610 pub type HeaderFor<T> =
2612 <<T as crate::Config>::Block as sp_runtime::traits::HeaderProvider>::HeaderT;
2613
2614 pub type BlockNumberFor<T> = <HeaderFor<T> as sp_runtime::traits::Header>::Number;
2616
2617 pub type ExtrinsicFor<T> =
2619 <<T as crate::Config>::Block as sp_runtime::traits::Block>::Extrinsic;
2620
2621 pub type RuntimeCallFor<T> = <T as crate::Config>::RuntimeCall;
2623
2624 pub type AccountIdFor<T> = <T as crate::Config>::AccountId;
2626}