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, RuntimeDebug,
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};
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,
289 Copy,
290 Eq,
291 PartialEq,
292 Default,
293 RuntimeDebug,
294 Encode,
295 Decode,
296 DecodeWithMemTracking,
297 TypeInfo,
298)]
299pub struct DispatchEventInfo {
300 pub weight: Weight,
302 pub class: DispatchClass,
304 pub pays_fee: Pays,
306}
307
308#[frame_support::pallet]
309pub mod pallet {
310 use crate::{self as frame_system, pallet_prelude::*, *};
311 use codec::HasCompact;
312 use frame_support::pallet_prelude::*;
313
314 pub mod config_preludes {
316 use super::{inject_runtime_type, DefaultConfig};
317 use frame_support::{derive_impl, traits::Get};
318
319 pub struct TestBlockHashCount<C: Get<u32>>(core::marker::PhantomData<C>);
325 impl<I: From<u32>, C: Get<u32>> Get<I> for TestBlockHashCount<C> {
326 fn get() -> I {
327 C::get().into()
328 }
329 }
330
331 pub struct TestDefaultConfig;
338
339 #[frame_support::register_default_impl(TestDefaultConfig)]
340 impl DefaultConfig for TestDefaultConfig {
341 type Nonce = u32;
342 type Hash = sp_core::hash::H256;
343 type Hashing = sp_runtime::traits::BlakeTwo256;
344 type AccountId = u64;
345 type Lookup = sp_runtime::traits::IdentityLookup<Self::AccountId>;
346 type MaxConsumers = frame_support::traits::ConstU32<16>;
347 type AccountData = ();
348 type OnNewAccount = ();
349 type OnKilledAccount = ();
350 type SystemWeightInfo = ();
351 type ExtensionsWeightInfo = ();
352 type SS58Prefix = ();
353 type Version = ();
354 type BlockWeights = ();
355 type BlockLength = ();
356 type DbWeight = ();
357 #[inject_runtime_type]
358 type RuntimeEvent = ();
359 #[inject_runtime_type]
360 type RuntimeOrigin = ();
361 #[inject_runtime_type]
362 type RuntimeCall = ();
363 #[inject_runtime_type]
364 type PalletInfo = ();
365 #[inject_runtime_type]
366 type RuntimeTask = ();
367 type BaseCallFilter = frame_support::traits::Everything;
368 type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<10>>;
369 type OnSetCode = ();
370 type SingleBlockMigrations = ();
371 type MultiBlockMigrator = ();
372 type PreInherents = ();
373 type PostInherents = ();
374 type PostTransactions = ();
375 }
376
377 pub struct SolochainDefaultConfig;
391
392 #[frame_support::register_default_impl(SolochainDefaultConfig)]
393 impl DefaultConfig for SolochainDefaultConfig {
394 type Nonce = u32;
396
397 type Hash = sp_core::hash::H256;
399
400 type Hashing = sp_runtime::traits::BlakeTwo256;
402
403 type AccountId = sp_runtime::AccountId32;
405
406 type Lookup = sp_runtime::traits::AccountIdLookup<Self::AccountId, ()>;
408
409 type MaxConsumers = frame_support::traits::ConstU32<128>;
411
412 type AccountData = ();
414
415 type OnNewAccount = ();
417
418 type OnKilledAccount = ();
420
421 type SystemWeightInfo = ();
423
424 type ExtensionsWeightInfo = ();
426
427 type SS58Prefix = ();
429
430 type Version = ();
432
433 type BlockWeights = ();
435
436 type BlockLength = ();
438
439 type DbWeight = ();
441
442 #[inject_runtime_type]
444 type RuntimeEvent = ();
445
446 #[inject_runtime_type]
448 type RuntimeOrigin = ();
449
450 #[inject_runtime_type]
453 type RuntimeCall = ();
454
455 #[inject_runtime_type]
457 type RuntimeTask = ();
458
459 #[inject_runtime_type]
461 type PalletInfo = ();
462
463 type BaseCallFilter = frame_support::traits::Everything;
465
466 type BlockHashCount = TestBlockHashCount<frame_support::traits::ConstU32<256>>;
469
470 type OnSetCode = ();
472 type SingleBlockMigrations = ();
473 type MultiBlockMigrator = ();
474 type PreInherents = ();
475 type PostInherents = ();
476 type PostTransactions = ();
477 }
478
479 pub struct RelayChainDefaultConfig;
481
482 #[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
484 #[frame_support::register_default_impl(RelayChainDefaultConfig)]
485 impl DefaultConfig for RelayChainDefaultConfig {}
486
487 pub struct ParaChainDefaultConfig;
489
490 #[derive_impl(SolochainDefaultConfig as DefaultConfig, no_aggregated_types)]
492 #[frame_support::register_default_impl(ParaChainDefaultConfig)]
493 impl DefaultConfig for ParaChainDefaultConfig {}
494 }
495
496 #[pallet::config(with_default, frame_system_config)]
498 #[pallet::disable_frame_system_supertrait_check]
499 pub trait Config: 'static + Eq + Clone {
500 #[pallet::no_default_bounds]
502 type RuntimeEvent: Parameter
503 + Member
504 + From<Event<Self>>
505 + Debug
506 + IsType<<Self as frame_system::Config>::RuntimeEvent>;
507
508 #[pallet::no_default_bounds]
519 type BaseCallFilter: Contains<Self::RuntimeCall>;
520
521 #[pallet::constant]
523 type BlockWeights: Get<limits::BlockWeights>;
524
525 #[pallet::constant]
527 type BlockLength: Get<limits::BlockLength>;
528
529 #[pallet::no_default_bounds]
531 type RuntimeOrigin: Into<Result<RawOrigin<Self::AccountId>, Self::RuntimeOrigin>>
532 + From<RawOrigin<Self::AccountId>>
533 + Clone
534 + OriginTrait<Call = Self::RuntimeCall, AccountId = Self::AccountId>
535 + AsTransactionAuthorizedOrigin;
536
537 #[docify::export(system_runtime_call)]
538 #[pallet::no_default_bounds]
540 type RuntimeCall: Parameter
541 + Dispatchable<RuntimeOrigin = Self::RuntimeOrigin>
542 + Debug
543 + GetDispatchInfo
544 + From<Call<Self>>
545 + Authorize;
546
547 #[pallet::no_default_bounds]
549 type RuntimeTask: Task;
550
551 type Nonce: Parameter
553 + HasCompact<Type: DecodeWithMemTracking>
554 + Member
555 + MaybeSerializeDeserialize
556 + Debug
557 + Default
558 + MaybeDisplay
559 + AtLeast32Bit
560 + Copy
561 + MaxEncodedLen;
562
563 type Hash: Parameter
565 + Member
566 + MaybeSerializeDeserialize
567 + Debug
568 + MaybeDisplay
569 + SimpleBitOps
570 + Ord
571 + Default
572 + Copy
573 + CheckEqual
574 + core::hash::Hash
575 + AsRef<[u8]>
576 + AsMut<[u8]>
577 + MaxEncodedLen;
578
579 type Hashing: Hash<Output = Self::Hash> + TypeInfo;
581
582 type AccountId: Parameter
584 + Member
585 + MaybeSerializeDeserialize
586 + Debug
587 + MaybeDisplay
588 + Ord
589 + MaxEncodedLen;
590
591 type Lookup: StaticLookup<Target = Self::AccountId>;
598
599 #[pallet::no_default]
602 type Block: Parameter + Member + traits::Block<Hash = Self::Hash>;
603
604 #[pallet::constant]
606 #[pallet::no_default_bounds]
607 type BlockHashCount: Get<BlockNumberFor<Self>>;
608
609 #[pallet::constant]
611 type DbWeight: Get<RuntimeDbWeight>;
612
613 #[pallet::constant]
615 type Version: Get<RuntimeVersion>;
616
617 #[pallet::no_default_bounds]
624 type PalletInfo: PalletInfo;
625
626 type AccountData: Member + FullCodec + Clone + Default + TypeInfo + MaxEncodedLen;
629
630 type OnNewAccount: OnNewAccount<Self::AccountId>;
632
633 type OnKilledAccount: OnKilledAccount<Self::AccountId>;
637
638 type SystemWeightInfo: WeightInfo;
640
641 type ExtensionsWeightInfo: extensions::WeightInfo;
643
644 #[pallet::constant]
650 type SS58Prefix: Get<u16>;
651
652 #[pallet::no_default_bounds]
660 type OnSetCode: SetCode<Self>;
661
662 type MaxConsumers: ConsumerLimits;
664
665 type SingleBlockMigrations: OnRuntimeUpgrade;
672
673 type MultiBlockMigrator: MultiStepMigrator;
678
679 type PreInherents: PreInherents;
683
684 type PostInherents: PostInherents;
688
689 type PostTransactions: PostTransactions;
693 }
694
695 #[pallet::pallet]
696 pub struct Pallet<T>(_);
697
698 #[pallet::hooks]
699 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
700 #[cfg(feature = "std")]
701 fn integrity_test() {
702 T::BlockWeights::get().validate().expect("The weights are invalid.");
703 }
704 }
705
706 #[pallet::call(weight = <T as Config>::SystemWeightInfo)]
707 impl<T: Config> Pallet<T> {
708 #[pallet::call_index(0)]
712 #[pallet::weight(T::SystemWeightInfo::remark(remark.len() as u32))]
713 pub fn remark(_origin: OriginFor<T>, remark: Vec<u8>) -> DispatchResultWithPostInfo {
714 let _ = remark; Ok(().into())
716 }
717
718 #[pallet::call_index(1)]
720 #[pallet::weight((T::SystemWeightInfo::set_heap_pages(), DispatchClass::Operational))]
721 pub fn set_heap_pages(origin: OriginFor<T>, pages: u64) -> DispatchResultWithPostInfo {
722 ensure_root(origin)?;
723 storage::unhashed::put_raw(well_known_keys::HEAP_PAGES, &pages.encode());
724 Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
725 Ok(().into())
726 }
727
728 #[pallet::call_index(2)]
730 #[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
731 pub fn set_code(origin: OriginFor<T>, code: Vec<u8>) -> DispatchResultWithPostInfo {
732 ensure_root(origin)?;
733 Self::can_set_code(&code, true).into_result()?;
734 T::OnSetCode::set_code(code)?;
735 Ok(Some(T::BlockWeights::get().max_block).into())
737 }
738
739 #[pallet::call_index(3)]
744 #[pallet::weight((T::SystemWeightInfo::set_code(), DispatchClass::Operational))]
745 pub fn set_code_without_checks(
746 origin: OriginFor<T>,
747 code: Vec<u8>,
748 ) -> DispatchResultWithPostInfo {
749 ensure_root(origin)?;
750 Self::can_set_code(&code, false).into_result()?;
751 T::OnSetCode::set_code(code)?;
752 Ok(Some(T::BlockWeights::get().max_block).into())
753 }
754
755 #[pallet::call_index(4)]
757 #[pallet::weight((
758 T::SystemWeightInfo::set_storage(items.len() as u32),
759 DispatchClass::Operational,
760 ))]
761 pub fn set_storage(
762 origin: OriginFor<T>,
763 items: Vec<KeyValue>,
764 ) -> DispatchResultWithPostInfo {
765 ensure_root(origin)?;
766 for i in &items {
767 storage::unhashed::put_raw(&i.0, &i.1);
768 }
769 Ok(().into())
770 }
771
772 #[pallet::call_index(5)]
774 #[pallet::weight((
775 T::SystemWeightInfo::kill_storage(keys.len() as u32),
776 DispatchClass::Operational,
777 ))]
778 pub fn kill_storage(origin: OriginFor<T>, keys: Vec<Key>) -> DispatchResultWithPostInfo {
779 ensure_root(origin)?;
780 for key in &keys {
781 storage::unhashed::kill(key);
782 }
783 Ok(().into())
784 }
785
786 #[pallet::call_index(6)]
791 #[pallet::weight((
792 T::SystemWeightInfo::kill_prefix(subkeys.saturating_add(1)),
793 DispatchClass::Operational,
794 ))]
795 pub fn kill_prefix(
796 origin: OriginFor<T>,
797 prefix: Key,
798 subkeys: u32,
799 ) -> DispatchResultWithPostInfo {
800 ensure_root(origin)?;
801 let _ = storage::unhashed::clear_prefix(&prefix, Some(subkeys), None);
802 Ok(().into())
803 }
804
805 #[pallet::call_index(7)]
807 #[pallet::weight(T::SystemWeightInfo::remark_with_event(remark.len() as u32))]
808 pub fn remark_with_event(
809 origin: OriginFor<T>,
810 remark: Vec<u8>,
811 ) -> DispatchResultWithPostInfo {
812 let who = ensure_signed(origin)?;
813 let hash = T::Hashing::hash(&remark[..]);
814 Self::deposit_event(Event::Remarked { sender: who, hash });
815 Ok(().into())
816 }
817
818 #[cfg(feature = "experimental")]
819 #[pallet::call_index(8)]
820 #[pallet::weight(task.weight())]
821 pub fn do_task(_origin: OriginFor<T>, task: T::RuntimeTask) -> DispatchResultWithPostInfo {
822 if !task.is_valid() {
823 return Err(Error::<T>::InvalidTask.into())
824 }
825
826 Self::deposit_event(Event::TaskStarted { task: task.clone() });
827 if let Err(err) = task.run() {
828 Self::deposit_event(Event::TaskFailed { task, err });
829 return Err(Error::<T>::FailedTask.into())
830 }
831
832 Self::deposit_event(Event::TaskCompleted { task });
834
835 Ok(().into())
837 }
838
839 #[pallet::call_index(9)]
844 #[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
845 pub fn authorize_upgrade(origin: OriginFor<T>, code_hash: T::Hash) -> DispatchResult {
846 ensure_root(origin)?;
847 Self::do_authorize_upgrade(code_hash, true);
848 Ok(())
849 }
850
851 #[pallet::call_index(10)]
860 #[pallet::weight((T::SystemWeightInfo::authorize_upgrade(), DispatchClass::Operational))]
861 pub fn authorize_upgrade_without_checks(
862 origin: OriginFor<T>,
863 code_hash: T::Hash,
864 ) -> DispatchResult {
865 ensure_root(origin)?;
866 Self::do_authorize_upgrade(code_hash, false);
867 Ok(())
868 }
869
870 #[pallet::call_index(11)]
880 #[pallet::weight((T::SystemWeightInfo::apply_authorized_upgrade(), DispatchClass::Operational))]
881 pub fn apply_authorized_upgrade(
882 _: OriginFor<T>,
883 code: Vec<u8>,
884 ) -> DispatchResultWithPostInfo {
885 let res = Self::validate_code_is_authorized(&code)?;
886 AuthorizedUpgrade::<T>::kill();
887
888 match Self::can_set_code(&code, res.check_version) {
889 CanSetCodeResult::Ok => {},
890 CanSetCodeResult::MultiBlockMigrationsOngoing =>
891 return Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
892 CanSetCodeResult::InvalidVersion(error) => {
893 Self::deposit_event(Event::RejectedInvalidAuthorizedUpgrade {
895 code_hash: res.code_hash,
896 error: error.into(),
897 });
898
899 return Ok(Pays::No.into())
901 },
902 };
903 T::OnSetCode::set_code(code)?;
904
905 Ok(PostDispatchInfo {
906 actual_weight: Some(T::BlockWeights::get().max_block),
908 pays_fee: Pays::No,
910 })
911 }
912 }
913
914 #[pallet::event]
916 pub enum Event<T: Config> {
917 ExtrinsicSuccess { dispatch_info: DispatchEventInfo },
919 ExtrinsicFailed { dispatch_error: DispatchError, dispatch_info: DispatchEventInfo },
921 CodeUpdated,
923 NewAccount { account: T::AccountId },
925 KilledAccount { account: T::AccountId },
927 Remarked { sender: T::AccountId, hash: T::Hash },
929 #[cfg(feature = "experimental")]
930 TaskStarted { task: T::RuntimeTask },
932 #[cfg(feature = "experimental")]
933 TaskCompleted { task: T::RuntimeTask },
935 #[cfg(feature = "experimental")]
936 TaskFailed { task: T::RuntimeTask, err: DispatchError },
938 UpgradeAuthorized { code_hash: T::Hash, check_version: bool },
940 RejectedInvalidAuthorizedUpgrade { code_hash: T::Hash, error: DispatchError },
942 }
943
944 #[pallet::error]
946 pub enum Error<T> {
947 InvalidSpecName,
950 SpecVersionNeedsToIncrease,
953 FailedToExtractRuntimeVersion,
957 NonDefaultComposite,
959 NonZeroRefCount,
961 CallFiltered,
963 MultiBlockMigrationsOngoing,
965 #[cfg(feature = "experimental")]
966 InvalidTask,
968 #[cfg(feature = "experimental")]
969 FailedTask,
971 NothingAuthorized,
973 Unauthorized,
975 }
976
977 #[pallet::origin]
979 pub type Origin<T> = RawOrigin<<T as Config>::AccountId>;
980
981 #[pallet::storage]
983 #[pallet::getter(fn account)]
984 pub type Account<T: Config> = StorageMap<
985 _,
986 Blake2_128Concat,
987 T::AccountId,
988 AccountInfo<T::Nonce, T::AccountData>,
989 ValueQuery,
990 >;
991
992 #[pallet::storage]
994 pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
995
996 #[pallet::storage]
998 pub type InherentsApplied<T: Config> = StorageValue<_, bool, ValueQuery>;
999
1000 #[pallet::storage]
1002 #[pallet::whitelist_storage]
1003 #[pallet::getter(fn block_weight)]
1004 pub type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
1005
1006 #[pallet::storage]
1008 #[pallet::whitelist_storage]
1009 pub type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
1010
1011 #[pallet::storage]
1013 #[pallet::getter(fn block_hash)]
1014 pub type BlockHash<T: Config> =
1015 StorageMap<_, Twox64Concat, BlockNumberFor<T>, T::Hash, ValueQuery>;
1016
1017 #[pallet::storage]
1019 #[pallet::getter(fn extrinsic_data)]
1020 #[pallet::unbounded]
1021 pub(super) type ExtrinsicData<T: Config> =
1022 StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
1023
1024 #[pallet::storage]
1026 #[pallet::whitelist_storage]
1027 #[pallet::getter(fn block_number)]
1028 pub(super) type Number<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
1029
1030 #[pallet::storage]
1032 #[pallet::getter(fn parent_hash)]
1033 pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
1034
1035 #[pallet::storage]
1037 #[pallet::whitelist_storage]
1038 #[pallet::unbounded]
1039 #[pallet::getter(fn digest)]
1040 pub(super) type Digest<T: Config> = StorageValue<_, generic::Digest, ValueQuery>;
1041
1042 #[pallet::storage]
1050 #[pallet::whitelist_storage]
1051 #[pallet::disable_try_decode_storage]
1052 #[pallet::unbounded]
1053 pub(super) type Events<T: Config> =
1054 StorageValue<_, Vec<Box<EventRecord<T::RuntimeEvent, T::Hash>>>, ValueQuery>;
1055
1056 #[pallet::storage]
1058 #[pallet::whitelist_storage]
1059 #[pallet::getter(fn event_count)]
1060 pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
1061
1062 #[pallet::storage]
1073 #[pallet::unbounded]
1074 #[pallet::getter(fn event_topics)]
1075 pub(super) type EventTopics<T: Config> =
1076 StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor<T>, EventIndex)>, ValueQuery>;
1077
1078 #[pallet::storage]
1080 #[pallet::unbounded]
1081 pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
1082
1083 #[pallet::storage]
1085 pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1086
1087 #[pallet::storage]
1090 pub(super) type UpgradedToTripleRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1091
1092 #[pallet::storage]
1094 #[pallet::whitelist_storage]
1095 pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
1096
1097 #[pallet::storage]
1099 #[pallet::getter(fn authorized_upgrade)]
1100 pub(super) type AuthorizedUpgrade<T: Config> =
1101 StorageValue<_, CodeUpgradeAuthorization<T>, OptionQuery>;
1102
1103 #[pallet::storage]
1111 #[pallet::whitelist_storage]
1112 pub type ExtrinsicWeightReclaimed<T: Config> = StorageValue<_, Weight, ValueQuery>;
1113
1114 #[derive(frame_support::DefaultNoBound)]
1115 #[pallet::genesis_config]
1116 pub struct GenesisConfig<T: Config> {
1117 #[serde(skip)]
1118 pub _config: core::marker::PhantomData<T>,
1119 }
1120
1121 #[pallet::genesis_build]
1122 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
1123 fn build(&self) {
1124 <BlockHash<T>>::insert::<_, T::Hash>(BlockNumberFor::<T>::zero(), hash69());
1125 <ParentHash<T>>::put::<T::Hash>(hash69());
1126 <LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
1127 <UpgradedToU32RefCount<T>>::put(true);
1128 <UpgradedToTripleRefCount<T>>::put(true);
1129
1130 sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
1131 }
1132 }
1133
1134 #[pallet::validate_unsigned]
1135 impl<T: Config> sp_runtime::traits::ValidateUnsigned for Pallet<T> {
1136 type Call = Call<T>;
1137 fn validate_unsigned(_source: TransactionSource, call: &Self::Call) -> TransactionValidity {
1138 if let Call::apply_authorized_upgrade { ref code } = call {
1139 if let Ok(res) = Self::validate_code_is_authorized(&code[..]) {
1140 if Self::can_set_code(&code, false).is_ok() {
1141 return Ok(ValidTransaction {
1142 priority: u64::max_value(),
1143 requires: Vec::new(),
1144 provides: vec![res.code_hash.encode()],
1145 longevity: TransactionLongevity::max_value(),
1146 propagate: true,
1147 })
1148 }
1149 }
1150 }
1151
1152 #[cfg(feature = "experimental")]
1153 if let Call::do_task { ref task } = call {
1154 if task.is_valid() {
1155 return Ok(ValidTransaction {
1156 priority: u64::max_value(),
1157 requires: Vec::new(),
1158 provides: vec![T::Hashing::hash_of(&task.encode()).as_ref().to_vec()],
1159 longevity: TransactionLongevity::max_value(),
1160 propagate: true,
1161 })
1162 }
1163 }
1164
1165 Err(InvalidTransaction::Call.into())
1166 }
1167 }
1168}
1169
1170pub type Key = Vec<u8>;
1171pub type KeyValue = (Vec<u8>, Vec<u8>);
1172
1173#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
1175#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1176pub enum Phase {
1177 ApplyExtrinsic(u32),
1179 Finalization,
1181 Initialization,
1183}
1184
1185impl Default for Phase {
1186 fn default() -> Self {
1187 Self::Initialization
1188 }
1189}
1190
1191#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
1193#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1194pub struct EventRecord<E: Parameter + Member, T> {
1195 pub phase: Phase,
1197 pub event: E,
1199 pub topics: Vec<T>,
1201}
1202
1203fn hash69<T: AsMut<[u8]> + Default>() -> T {
1206 let mut h = T::default();
1207 h.as_mut().iter_mut().for_each(|byte| *byte = 69);
1208 h
1209}
1210
1211type EventIndex = u32;
1216
1217pub type RefCount = u32;
1219
1220#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
1222pub struct AccountInfo<Nonce, AccountData> {
1223 pub nonce: Nonce,
1225 pub consumers: RefCount,
1228 pub providers: RefCount,
1231 pub sufficients: RefCount,
1234 pub data: AccountData,
1237}
1238
1239#[derive(RuntimeDebug, Encode, Decode, TypeInfo)]
1242#[cfg_attr(feature = "std", derive(PartialEq))]
1243pub struct LastRuntimeUpgradeInfo {
1244 pub spec_version: codec::Compact<u32>,
1245 pub spec_name: Cow<'static, str>,
1246}
1247
1248impl LastRuntimeUpgradeInfo {
1249 pub fn was_upgraded(&self, current: &RuntimeVersion) -> bool {
1253 current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
1254 }
1255}
1256
1257impl From<RuntimeVersion> for LastRuntimeUpgradeInfo {
1258 fn from(version: RuntimeVersion) -> Self {
1259 Self { spec_version: version.spec_version.into(), spec_name: version.spec_name }
1260 }
1261}
1262
1263pub struct EnsureRoot<AccountId>(core::marker::PhantomData<AccountId>);
1265impl<O: OriginTrait, AccountId> EnsureOrigin<O> for EnsureRoot<AccountId> {
1266 type Success = ();
1267 fn try_origin(o: O) -> Result<Self::Success, O> {
1268 match o.as_system_ref() {
1269 Some(RawOrigin::Root) => Ok(()),
1270 _ => Err(o),
1271 }
1272 }
1273
1274 #[cfg(feature = "runtime-benchmarks")]
1275 fn try_successful_origin() -> Result<O, ()> {
1276 Ok(O::root())
1277 }
1278}
1279
1280impl_ensure_origin_with_arg_ignoring_arg! {
1281 impl< { O: .., AccountId: Decode, T } >
1282 EnsureOriginWithArg<O, T> for EnsureRoot<AccountId>
1283 {}
1284}
1285
1286pub struct EnsureRootWithSuccess<AccountId, Success>(
1288 core::marker::PhantomData<(AccountId, Success)>,
1289);
1290impl<O: OriginTrait, AccountId, Success: TypedGet> EnsureOrigin<O>
1291 for EnsureRootWithSuccess<AccountId, Success>
1292{
1293 type Success = Success::Type;
1294 fn try_origin(o: O) -> Result<Self::Success, O> {
1295 match o.as_system_ref() {
1296 Some(RawOrigin::Root) => Ok(Success::get()),
1297 _ => Err(o),
1298 }
1299 }
1300
1301 #[cfg(feature = "runtime-benchmarks")]
1302 fn try_successful_origin() -> Result<O, ()> {
1303 Ok(O::root())
1304 }
1305}
1306
1307impl_ensure_origin_with_arg_ignoring_arg! {
1308 impl< { O: .., AccountId: Decode, Success: TypedGet, T } >
1309 EnsureOriginWithArg<O, T> for EnsureRootWithSuccess<AccountId, Success>
1310 {}
1311}
1312
1313pub struct EnsureWithSuccess<Ensure, AccountId, Success>(
1315 core::marker::PhantomData<(Ensure, AccountId, Success)>,
1316);
1317
1318impl<O: OriginTrait, Ensure: EnsureOrigin<O>, AccountId, Success: TypedGet> EnsureOrigin<O>
1319 for EnsureWithSuccess<Ensure, AccountId, Success>
1320{
1321 type Success = Success::Type;
1322
1323 fn try_origin(o: O) -> Result<Self::Success, O> {
1324 Ensure::try_origin(o).map(|_| Success::get())
1325 }
1326
1327 #[cfg(feature = "runtime-benchmarks")]
1328 fn try_successful_origin() -> Result<O, ()> {
1329 Ensure::try_successful_origin()
1330 }
1331}
1332
1333pub struct EnsureSigned<AccountId>(core::marker::PhantomData<AccountId>);
1335impl<O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone> EnsureOrigin<O>
1336 for EnsureSigned<AccountId>
1337{
1338 type Success = AccountId;
1339 fn try_origin(o: O) -> Result<Self::Success, O> {
1340 match o.as_system_ref() {
1341 Some(RawOrigin::Signed(who)) => Ok(who.clone()),
1342 _ => Err(o),
1343 }
1344 }
1345
1346 #[cfg(feature = "runtime-benchmarks")]
1347 fn try_successful_origin() -> Result<O, ()> {
1348 let zero_account_id =
1349 AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?;
1350 Ok(O::signed(zero_account_id))
1351 }
1352}
1353
1354impl_ensure_origin_with_arg_ignoring_arg! {
1355 impl< { O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone, T } >
1356 EnsureOriginWithArg<O, T> for EnsureSigned<AccountId>
1357 {}
1358}
1359
1360pub struct EnsureSignedBy<Who, AccountId>(core::marker::PhantomData<(Who, AccountId)>);
1362impl<
1363 O: OriginTrait<AccountId = AccountId>,
1364 Who: SortedMembers<AccountId>,
1365 AccountId: PartialEq + Clone + Ord + Decode,
1366 > EnsureOrigin<O> for EnsureSignedBy<Who, AccountId>
1367{
1368 type Success = AccountId;
1369 fn try_origin(o: O) -> Result<Self::Success, O> {
1370 match o.as_system_ref() {
1371 Some(RawOrigin::Signed(ref who)) if Who::contains(who) => Ok(who.clone()),
1372 _ => Err(o),
1373 }
1374 }
1375
1376 #[cfg(feature = "runtime-benchmarks")]
1377 fn try_successful_origin() -> Result<O, ()> {
1378 let first_member = match Who::sorted_members().first() {
1379 Some(account) => account.clone(),
1380 None => AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?,
1381 };
1382 Ok(O::signed(first_member))
1383 }
1384}
1385
1386impl_ensure_origin_with_arg_ignoring_arg! {
1387 impl< { O: OriginTrait<AccountId = AccountId>, Who: SortedMembers<AccountId>, AccountId: PartialEq + Clone + Ord + Decode, T } >
1388 EnsureOriginWithArg<O, T> for EnsureSignedBy<Who, AccountId>
1389 {}
1390}
1391
1392pub struct EnsureNone<AccountId>(core::marker::PhantomData<AccountId>);
1394impl<O: OriginTrait<AccountId = AccountId>, AccountId> EnsureOrigin<O> for EnsureNone<AccountId> {
1395 type Success = ();
1396 fn try_origin(o: O) -> Result<Self::Success, O> {
1397 match o.as_system_ref() {
1398 Some(RawOrigin::None) => Ok(()),
1399 _ => Err(o),
1400 }
1401 }
1402
1403 #[cfg(feature = "runtime-benchmarks")]
1404 fn try_successful_origin() -> Result<O, ()> {
1405 Ok(O::none())
1406 }
1407}
1408
1409impl_ensure_origin_with_arg_ignoring_arg! {
1410 impl< { O: OriginTrait<AccountId = AccountId>, AccountId, T } >
1411 EnsureOriginWithArg<O, T> for EnsureNone<AccountId>
1412 {}
1413}
1414
1415pub struct EnsureNever<Success>(core::marker::PhantomData<Success>);
1417impl<O, Success> EnsureOrigin<O> for EnsureNever<Success> {
1418 type Success = Success;
1419 fn try_origin(o: O) -> Result<Self::Success, O> {
1420 Err(o)
1421 }
1422
1423 #[cfg(feature = "runtime-benchmarks")]
1424 fn try_successful_origin() -> Result<O, ()> {
1425 Err(())
1426 }
1427}
1428
1429impl_ensure_origin_with_arg_ignoring_arg! {
1430 impl< { O, Success, T } >
1431 EnsureOriginWithArg<O, T> for EnsureNever<Success>
1432 {}
1433}
1434
1435#[docify::export]
1436pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
1439where
1440 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1441{
1442 match o.into() {
1443 Ok(RawOrigin::Signed(t)) => Ok(t),
1444 _ => Err(BadOrigin),
1445 }
1446}
1447
1448pub fn ensure_signed_or_root<OuterOrigin, AccountId>(
1452 o: OuterOrigin,
1453) -> Result<Option<AccountId>, BadOrigin>
1454where
1455 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1456{
1457 match o.into() {
1458 Ok(RawOrigin::Root) => Ok(None),
1459 Ok(RawOrigin::Signed(t)) => Ok(Some(t)),
1460 _ => Err(BadOrigin),
1461 }
1462}
1463
1464pub fn ensure_root<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1466where
1467 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1468{
1469 match o.into() {
1470 Ok(RawOrigin::Root) => Ok(()),
1471 _ => Err(BadOrigin),
1472 }
1473}
1474
1475pub fn ensure_none<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1477where
1478 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1479{
1480 match o.into() {
1481 Ok(RawOrigin::None) => Ok(()),
1482 _ => Err(BadOrigin),
1483 }
1484}
1485
1486pub fn ensure_authorized<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1489where
1490 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1491{
1492 match o.into() {
1493 Ok(RawOrigin::Authorized) => Ok(()),
1494 _ => Err(BadOrigin),
1495 }
1496}
1497
1498#[derive(RuntimeDebug)]
1500pub enum RefStatus {
1501 Referenced,
1502 Unreferenced,
1503}
1504
1505#[derive(Eq, PartialEq, RuntimeDebug)]
1507pub enum IncRefStatus {
1508 Created,
1510 Existed,
1512}
1513
1514#[derive(Eq, PartialEq, RuntimeDebug)]
1516pub enum DecRefStatus {
1517 Reaped,
1519 Exists,
1521}
1522
1523pub enum CanSetCodeResult<T: Config> {
1525 Ok,
1527 MultiBlockMigrationsOngoing,
1529 InvalidVersion(Error<T>),
1531}
1532
1533impl<T: Config> CanSetCodeResult<T> {
1534 pub fn into_result(self) -> Result<(), DispatchError> {
1536 match self {
1537 Self::Ok => Ok(()),
1538 Self::MultiBlockMigrationsOngoing =>
1539 Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
1540 Self::InvalidVersion(err) => Err(err.into()),
1541 }
1542 }
1543
1544 pub fn is_ok(&self) -> bool {
1546 matches!(self, Self::Ok)
1547 }
1548}
1549
1550impl<T: Config> Pallet<T> {
1551 #[doc = docify::embed!("src/tests.rs", last_runtime_upgrade_spec_version_usage)]
1565 pub fn last_runtime_upgrade_spec_version() -> u32 {
1566 LastRuntimeUpgrade::<T>::get().map_or(0, |l| l.spec_version.0)
1567 }
1568
1569 pub fn account_exists(who: &T::AccountId) -> bool {
1571 Account::<T>::contains_key(who)
1572 }
1573
1574 pub fn update_code_in_storage(code: &[u8]) {
1580 storage::unhashed::put_raw(well_known_keys::CODE, code);
1581 Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
1582 Self::deposit_event(Event::CodeUpdated);
1583 }
1584
1585 pub fn inherents_applied() -> bool {
1587 InherentsApplied::<T>::get()
1588 }
1589
1590 pub fn note_inherents_applied() {
1595 InherentsApplied::<T>::put(true);
1596 }
1597
1598 #[deprecated = "Use `inc_consumers` instead"]
1600 pub fn inc_ref(who: &T::AccountId) {
1601 let _ = Self::inc_consumers(who);
1602 }
1603
1604 #[deprecated = "Use `dec_consumers` instead"]
1607 pub fn dec_ref(who: &T::AccountId) {
1608 let _ = Self::dec_consumers(who);
1609 }
1610
1611 #[deprecated = "Use `consumers` instead"]
1613 pub fn refs(who: &T::AccountId) -> RefCount {
1614 Self::consumers(who)
1615 }
1616
1617 #[deprecated = "Use `!is_provider_required` instead"]
1619 pub fn allow_death(who: &T::AccountId) -> bool {
1620 !Self::is_provider_required(who)
1621 }
1622
1623 pub fn inc_providers(who: &T::AccountId) -> IncRefStatus {
1625 Account::<T>::mutate(who, |a| {
1626 if a.providers == 0 && a.sufficients == 0 {
1627 a.providers = 1;
1629 Self::on_created_account(who.clone(), a);
1630 IncRefStatus::Created
1631 } else {
1632 a.providers = a.providers.saturating_add(1);
1633 IncRefStatus::Existed
1634 }
1635 })
1636 }
1637
1638 pub fn dec_providers(who: &T::AccountId) -> Result<DecRefStatus, DispatchError> {
1642 Account::<T>::try_mutate_exists(who, |maybe_account| {
1643 if let Some(mut account) = maybe_account.take() {
1644 if account.providers == 0 {
1645 log::error!(
1647 target: LOG_TARGET,
1648 "Logic error: Unexpected underflow in reducing provider",
1649 );
1650 account.providers = 1;
1651 }
1652 match (account.providers, account.consumers, account.sufficients) {
1653 (1, 0, 0) => {
1654 Pallet::<T>::on_killed_account(who.clone());
1657 Ok(DecRefStatus::Reaped)
1658 },
1659 (1, c, _) if c > 0 => {
1660 Err(DispatchError::ConsumerRemaining)
1662 },
1663 (x, _, _) => {
1664 account.providers = x - 1;
1667 *maybe_account = Some(account);
1668 Ok(DecRefStatus::Exists)
1669 },
1670 }
1671 } else {
1672 log::error!(
1673 target: LOG_TARGET,
1674 "Logic error: Account already dead when reducing provider",
1675 );
1676 Ok(DecRefStatus::Reaped)
1677 }
1678 })
1679 }
1680
1681 pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus {
1683 Account::<T>::mutate(who, |a| {
1684 if a.providers + a.sufficients == 0 {
1685 a.sufficients = 1;
1687 Self::on_created_account(who.clone(), a);
1688 IncRefStatus::Created
1689 } else {
1690 a.sufficients = a.sufficients.saturating_add(1);
1691 IncRefStatus::Existed
1692 }
1693 })
1694 }
1695
1696 pub fn dec_sufficients(who: &T::AccountId) -> DecRefStatus {
1700 Account::<T>::mutate_exists(who, |maybe_account| {
1701 if let Some(mut account) = maybe_account.take() {
1702 if account.sufficients == 0 {
1703 log::error!(
1705 target: LOG_TARGET,
1706 "Logic error: Unexpected underflow in reducing sufficients",
1707 );
1708 }
1709 match (account.sufficients, account.providers) {
1710 (0, 0) | (1, 0) => {
1711 Pallet::<T>::on_killed_account(who.clone());
1712 DecRefStatus::Reaped
1713 },
1714 (x, _) => {
1715 account.sufficients = x.saturating_sub(1);
1716 *maybe_account = Some(account);
1717 DecRefStatus::Exists
1718 },
1719 }
1720 } else {
1721 log::error!(
1722 target: LOG_TARGET,
1723 "Logic error: Account already dead when reducing provider",
1724 );
1725 DecRefStatus::Reaped
1726 }
1727 })
1728 }
1729
1730 pub fn providers(who: &T::AccountId) -> RefCount {
1732 Account::<T>::get(who).providers
1733 }
1734
1735 pub fn sufficients(who: &T::AccountId) -> RefCount {
1737 Account::<T>::get(who).sufficients
1738 }
1739
1740 pub fn reference_count(who: &T::AccountId) -> RefCount {
1742 let a = Account::<T>::get(who);
1743 a.providers + a.sufficients
1744 }
1745
1746 pub fn inc_consumers(who: &T::AccountId) -> Result<(), DispatchError> {
1751 Account::<T>::try_mutate(who, |a| {
1752 if a.providers > 0 {
1753 if a.consumers < T::MaxConsumers::max_consumers() {
1754 a.consumers = a.consumers.saturating_add(1);
1755 Ok(())
1756 } else {
1757 Err(DispatchError::TooManyConsumers)
1758 }
1759 } else {
1760 Err(DispatchError::NoProviders)
1761 }
1762 })
1763 }
1764
1765 pub fn inc_consumers_without_limit(who: &T::AccountId) -> Result<(), DispatchError> {
1769 Account::<T>::try_mutate(who, |a| {
1770 if a.providers > 0 {
1771 a.consumers = a.consumers.saturating_add(1);
1772 Ok(())
1773 } else {
1774 Err(DispatchError::NoProviders)
1775 }
1776 })
1777 }
1778
1779 pub fn dec_consumers(who: &T::AccountId) {
1782 Account::<T>::mutate(who, |a| {
1783 if a.consumers > 0 {
1784 a.consumers -= 1;
1785 } else {
1786 log::error!(
1787 target: LOG_TARGET,
1788 "Logic error: Unexpected underflow in reducing consumer",
1789 );
1790 }
1791 })
1792 }
1793
1794 pub fn consumers(who: &T::AccountId) -> RefCount {
1796 Account::<T>::get(who).consumers
1797 }
1798
1799 pub fn is_provider_required(who: &T::AccountId) -> bool {
1801 Account::<T>::get(who).consumers != 0
1802 }
1803
1804 pub fn can_dec_provider(who: &T::AccountId) -> bool {
1806 let a = Account::<T>::get(who);
1807 a.consumers == 0 || a.providers > 1
1808 }
1809
1810 pub fn can_accrue_consumers(who: &T::AccountId, amount: u32) -> bool {
1813 let a = Account::<T>::get(who);
1814 match a.consumers.checked_add(amount) {
1815 Some(c) => a.providers > 0 && c <= T::MaxConsumers::max_consumers(),
1816 None => false,
1817 }
1818 }
1819
1820 pub fn can_inc_consumer(who: &T::AccountId) -> bool {
1823 Self::can_accrue_consumers(who, 1)
1824 }
1825
1826 pub fn deposit_event(event: impl Into<T::RuntimeEvent>) {
1830 Self::deposit_event_indexed(&[], event.into());
1831 }
1832
1833 pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
1841 let block_number = Self::block_number();
1842
1843 if block_number.is_zero() {
1845 return
1846 }
1847
1848 let phase = ExecutionPhase::<T>::get().unwrap_or_default();
1849 let event = EventRecord { phase, event, topics: topics.to_vec() };
1850
1851 let event_idx = {
1853 let old_event_count = EventCount::<T>::get();
1854 let new_event_count = match old_event_count.checked_add(1) {
1855 None => return,
1858 Some(nc) => nc,
1859 };
1860 EventCount::<T>::put(new_event_count);
1861 old_event_count
1862 };
1863
1864 Events::<T>::append(event);
1865
1866 for topic in topics {
1867 <EventTopics<T>>::append(topic, &(block_number, event_idx));
1868 }
1869 }
1870
1871 pub fn extrinsic_index() -> Option<u32> {
1873 storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
1874 }
1875
1876 pub fn extrinsic_count() -> u32 {
1878 ExtrinsicCount::<T>::get().unwrap_or_default()
1879 }
1880
1881 pub fn all_extrinsics_len() -> u32 {
1882 AllExtrinsicsLen::<T>::get().unwrap_or_default()
1883 }
1884
1885 pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) {
1901 BlockWeight::<T>::mutate(|current_weight| {
1902 current_weight.accrue(weight, class);
1903 });
1904 }
1905
1906 pub fn initialize(number: &BlockNumberFor<T>, parent_hash: &T::Hash, digest: &generic::Digest) {
1913 let expected_block_number = Self::block_number() + One::one();
1914 assert_eq!(expected_block_number, *number, "Block number must be strictly increasing.");
1915
1916 ExecutionPhase::<T>::put(Phase::Initialization);
1918 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
1919 Self::initialize_intra_block_entropy(parent_hash);
1920 <Number<T>>::put(number);
1921 <Digest<T>>::put(digest);
1922 <ParentHash<T>>::put(parent_hash);
1923 <BlockHash<T>>::insert(*number - One::one(), parent_hash);
1924 <InherentsApplied<T>>::kill();
1925
1926 BlockWeight::<T>::kill();
1928 }
1929
1930 pub fn initialize_intra_block_entropy(parent_hash: &T::Hash) {
1934 let entropy = (b"frame_system::initialize", parent_hash).using_encoded(blake2_256);
1935 storage::unhashed::put_raw(well_known_keys::INTRABLOCK_ENTROPY, &entropy[..]);
1936 }
1937
1938 pub fn resource_usage_report() {
1942 log::debug!(
1943 target: LOG_TARGET,
1944 "[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\
1945 {} (ref_time: {}%, proof_size: {}%) op weight {} (ref_time {}%, proof_size {}%) / \
1946 mandatory weight {} (ref_time: {}%, proof_size: {}%)",
1947 Self::block_number(),
1948 Self::extrinsic_count(),
1949 Self::all_extrinsics_len(),
1950 sp_runtime::Percent::from_rational(
1951 Self::all_extrinsics_len(),
1952 *T::BlockLength::get().max.get(DispatchClass::Normal)
1953 ).deconstruct(),
1954 sp_runtime::Percent::from_rational(
1955 Self::all_extrinsics_len(),
1956 *T::BlockLength::get().max.get(DispatchClass::Operational)
1957 ).deconstruct(),
1958 sp_runtime::Percent::from_rational(
1959 Self::all_extrinsics_len(),
1960 *T::BlockLength::get().max.get(DispatchClass::Mandatory)
1961 ).deconstruct(),
1962 Self::block_weight().get(DispatchClass::Normal),
1963 sp_runtime::Percent::from_rational(
1964 Self::block_weight().get(DispatchClass::Normal).ref_time(),
1965 T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).ref_time()
1966 ).deconstruct(),
1967 sp_runtime::Percent::from_rational(
1968 Self::block_weight().get(DispatchClass::Normal).proof_size(),
1969 T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).proof_size()
1970 ).deconstruct(),
1971 Self::block_weight().get(DispatchClass::Operational),
1972 sp_runtime::Percent::from_rational(
1973 Self::block_weight().get(DispatchClass::Operational).ref_time(),
1974 T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).ref_time()
1975 ).deconstruct(),
1976 sp_runtime::Percent::from_rational(
1977 Self::block_weight().get(DispatchClass::Operational).proof_size(),
1978 T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).proof_size()
1979 ).deconstruct(),
1980 Self::block_weight().get(DispatchClass::Mandatory),
1981 sp_runtime::Percent::from_rational(
1982 Self::block_weight().get(DispatchClass::Mandatory).ref_time(),
1983 T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).ref_time()
1984 ).deconstruct(),
1985 sp_runtime::Percent::from_rational(
1986 Self::block_weight().get(DispatchClass::Mandatory).proof_size(),
1987 T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).proof_size()
1988 ).deconstruct(),
1989 );
1990 }
1991
1992 pub fn finalize() -> HeaderFor<T> {
1995 Self::resource_usage_report();
1996 ExecutionPhase::<T>::kill();
1997 AllExtrinsicsLen::<T>::kill();
1998 storage::unhashed::kill(well_known_keys::INTRABLOCK_ENTROPY);
1999 InherentsApplied::<T>::kill();
2000
2001 let number = <Number<T>>::get();
2012 let parent_hash = <ParentHash<T>>::get();
2013 let digest = <Digest<T>>::get();
2014
2015 let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
2016 .map(ExtrinsicData::<T>::take)
2017 .collect();
2018 let extrinsics_root_state_version = T::Version::get().extrinsics_root_state_version();
2019 let extrinsics_root =
2020 extrinsics_data_root::<T::Hashing>(extrinsics, extrinsics_root_state_version);
2021
2022 let block_hash_count = T::BlockHashCount::get();
2024 let to_remove = number.saturating_sub(block_hash_count).saturating_sub(One::one());
2025
2026 if !to_remove.is_zero() {
2028 <BlockHash<T>>::remove(to_remove);
2029 }
2030
2031 let version = T::Version::get().state_version();
2032 let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..])
2033 .expect("Node is configured to use the same hash; qed");
2034
2035 HeaderFor::<T>::new(number, extrinsics_root, storage_root, parent_hash, digest)
2036 }
2037
2038 pub fn deposit_log(item: generic::DigestItem) {
2040 <Digest<T>>::append(item);
2041 }
2042
2043 #[cfg(any(feature = "std", test))]
2045 pub fn externalities() -> TestExternalities {
2046 TestExternalities::new(sp_core::storage::Storage {
2047 top: [
2048 (<BlockHash<T>>::hashed_key_for(BlockNumberFor::<T>::zero()), [69u8; 32].encode()),
2049 (<Number<T>>::hashed_key().to_vec(), BlockNumberFor::<T>::one().encode()),
2050 (<ParentHash<T>>::hashed_key().to_vec(), [69u8; 32].encode()),
2051 ]
2052 .into_iter()
2053 .collect(),
2054 children_default: Default::default(),
2055 })
2056 }
2057
2058 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2066 pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
2067 Self::read_events_no_consensus().map(|e| *e).collect()
2069 }
2070
2071 pub fn event_no_consensus(index: usize) -> Option<T::RuntimeEvent> {
2076 Self::read_events_no_consensus().nth(index).map(|e| e.event.clone())
2077 }
2078
2079 pub fn read_events_no_consensus(
2084 ) -> impl Iterator<Item = Box<EventRecord<T::RuntimeEvent, T::Hash>>> {
2085 Events::<T>::stream_iter()
2086 }
2087
2088 pub fn read_events_for_pallet<E>() -> Vec<E>
2093 where
2094 T::RuntimeEvent: TryInto<E>,
2095 {
2096 Events::<T>::get()
2097 .into_iter()
2098 .map(|er| er.event)
2099 .filter_map(|e| e.try_into().ok())
2100 .collect::<_>()
2101 }
2102
2103 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2112 pub fn run_to_block_with<AllPalletsWithSystem>(
2113 n: BlockNumberFor<T>,
2114 mut hooks: RunToBlockHooks<T>,
2115 ) where
2116 AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
2117 + frame_support::traits::OnFinalize<BlockNumberFor<T>>,
2118 {
2119 let mut bn = Self::block_number();
2120
2121 while bn < n {
2122 if !bn.is_zero() {
2124 (hooks.before_finalize)(bn);
2125 AllPalletsWithSystem::on_finalize(bn);
2126 (hooks.after_finalize)(bn);
2127 }
2128
2129 bn += One::one();
2130
2131 Self::set_block_number(bn);
2132 (hooks.before_initialize)(bn);
2133 AllPalletsWithSystem::on_initialize(bn);
2134 (hooks.after_initialize)(bn);
2135 }
2136 }
2137
2138 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2140 pub fn run_to_block<AllPalletsWithSystem>(n: BlockNumberFor<T>)
2141 where
2142 AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
2143 + frame_support::traits::OnFinalize<BlockNumberFor<T>>,
2144 {
2145 Self::run_to_block_with::<AllPalletsWithSystem>(n, Default::default());
2146 }
2147
2148 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2151 pub fn set_block_number(n: BlockNumberFor<T>) {
2152 <Number<T>>::put(n);
2153 }
2154
2155 #[cfg(any(feature = "std", test))]
2157 pub fn set_extrinsic_index(extrinsic_index: u32) {
2158 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
2159 }
2160
2161 #[cfg(any(feature = "std", test))]
2164 pub fn set_parent_hash(n: T::Hash) {
2165 <ParentHash<T>>::put(n);
2166 }
2167
2168 #[cfg(any(feature = "std", test))]
2170 pub fn set_block_consumed_resources(weight: Weight, len: usize) {
2171 BlockWeight::<T>::mutate(|current_weight| {
2172 current_weight.set(weight, DispatchClass::Normal)
2173 });
2174 AllExtrinsicsLen::<T>::put(len as u32);
2175 }
2176
2177 pub fn reset_events() {
2182 <Events<T>>::kill();
2183 EventCount::<T>::kill();
2184 let _ = <EventTopics<T>>::clear(u32::max_value(), None);
2185 }
2186
2187 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2191 #[track_caller]
2192 pub fn assert_has_event(event: T::RuntimeEvent) {
2193 let warn = if Self::block_number().is_zero() {
2194 "WARNING: block number is zero, and events are not registered at block number zero.\n"
2195 } else {
2196 ""
2197 };
2198
2199 let events = Self::events();
2200 assert!(
2201 events.iter().any(|record| record.event == event),
2202 "{warn}expected event {event:?} not found in events {events:?}",
2203 );
2204 }
2205
2206 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2210 #[track_caller]
2211 pub fn assert_last_event(event: T::RuntimeEvent) {
2212 let warn = if Self::block_number().is_zero() {
2213 "WARNING: block number is zero, and events are not registered at block number zero.\n"
2214 } else {
2215 ""
2216 };
2217
2218 let last_event = Self::events()
2219 .last()
2220 .expect(&alloc::format!("{warn}events expected"))
2221 .event
2222 .clone();
2223 assert_eq!(
2224 last_event, event,
2225 "{warn}expected event {event:?} is not equal to the last event {last_event:?}",
2226 );
2227 }
2228
2229 pub fn runtime_version() -> RuntimeVersion {
2231 T::Version::get()
2232 }
2233
2234 pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Nonce {
2236 Account::<T>::get(who).nonce
2237 }
2238
2239 pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
2241 Account::<T>::mutate(who, |a| a.nonce += T::Nonce::one());
2242 }
2243
2244 pub fn note_extrinsic(encoded_xt: Vec<u8>) {
2249 ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
2250 }
2251
2252 pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, info: DispatchInfo) {
2258 let weight = extract_actual_weight(r, &info)
2259 .saturating_add(T::BlockWeights::get().get(info.class).base_extrinsic);
2260 let class = info.class;
2261 let pays_fee = extract_actual_pays_fee(r, &info);
2262 let dispatch_event_info = DispatchEventInfo { weight, class, pays_fee };
2263
2264 Self::deposit_event(match r {
2265 Ok(_) => Event::ExtrinsicSuccess { dispatch_info: dispatch_event_info },
2266 Err(err) => {
2267 log::trace!(
2268 target: LOG_TARGET,
2269 "Extrinsic failed at block({:?}): {:?}",
2270 Self::block_number(),
2271 err,
2272 );
2273 Event::ExtrinsicFailed {
2274 dispatch_error: err.error,
2275 dispatch_info: dispatch_event_info,
2276 }
2277 },
2278 });
2279
2280 log::trace!(
2281 target: LOG_TARGET,
2282 "Used block weight: {:?}",
2283 BlockWeight::<T>::get(),
2284 );
2285
2286 log::trace!(
2287 target: LOG_TARGET,
2288 "Used block length: {:?}",
2289 Pallet::<T>::all_extrinsics_len(),
2290 );
2291
2292 let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
2293
2294 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
2295 ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index));
2296 ExtrinsicWeightReclaimed::<T>::kill();
2297 }
2298
2299 pub fn note_finished_extrinsics() {
2302 let extrinsic_index: u32 =
2303 storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
2304 ExtrinsicCount::<T>::put(extrinsic_index);
2305 ExecutionPhase::<T>::put(Phase::Finalization);
2306 }
2307
2308 pub fn note_finished_initialize() {
2311 ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0))
2312 }
2313
2314 pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Nonce, T::AccountData>) {
2316 T::OnNewAccount::on_new_account(&who);
2317 Self::deposit_event(Event::NewAccount { account: who });
2318 }
2319
2320 fn on_killed_account(who: T::AccountId) {
2322 T::OnKilledAccount::on_killed_account(&who);
2323 Self::deposit_event(Event::KilledAccount { account: who });
2324 }
2325
2326 pub fn can_set_code(code: &[u8], check_version: bool) -> CanSetCodeResult<T> {
2330 if T::MultiBlockMigrator::ongoing() {
2331 return CanSetCodeResult::MultiBlockMigrationsOngoing
2332 }
2333
2334 if check_version {
2335 let current_version = T::Version::get();
2336 let Some(new_version) = sp_io::misc::runtime_version(code)
2337 .and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
2338 else {
2339 return CanSetCodeResult::InvalidVersion(Error::<T>::FailedToExtractRuntimeVersion)
2340 };
2341
2342 cfg_if::cfg_if! {
2343 if #[cfg(all(feature = "runtime-benchmarks", not(test)))] {
2344 core::hint::black_box((new_version, current_version));
2346 } else {
2347 if new_version.spec_name != current_version.spec_name {
2348 return CanSetCodeResult::InvalidVersion( Error::<T>::InvalidSpecName)
2349 }
2350
2351 if new_version.spec_version <= current_version.spec_version {
2352 return CanSetCodeResult::InvalidVersion(Error::<T>::SpecVersionNeedsToIncrease)
2353 }
2354 }
2355 }
2356 }
2357
2358 CanSetCodeResult::Ok
2359 }
2360
2361 pub fn do_authorize_upgrade(code_hash: T::Hash, check_version: bool) {
2363 AuthorizedUpgrade::<T>::put(CodeUpgradeAuthorization { code_hash, check_version });
2364 Self::deposit_event(Event::UpgradeAuthorized { code_hash, check_version });
2365 }
2366
2367 fn validate_code_is_authorized(
2371 code: &[u8],
2372 ) -> Result<CodeUpgradeAuthorization<T>, DispatchError> {
2373 let authorization = AuthorizedUpgrade::<T>::get().ok_or(Error::<T>::NothingAuthorized)?;
2374 let actual_hash = T::Hashing::hash(code);
2375 ensure!(actual_hash == authorization.code_hash, Error::<T>::Unauthorized);
2376 Ok(authorization)
2377 }
2378
2379 pub fn reclaim_weight(
2384 info: &DispatchInfoOf<T::RuntimeCall>,
2385 post_info: &PostDispatchInfoOf<T::RuntimeCall>,
2386 ) -> Result<(), TransactionValidityError>
2387 where
2388 T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
2389 {
2390 let already_reclaimed = crate::ExtrinsicWeightReclaimed::<T>::get();
2391 let unspent = post_info.calc_unspent(info);
2392 let accurate_reclaim = already_reclaimed.max(unspent);
2393 let to_reclaim_more = accurate_reclaim.saturating_sub(already_reclaimed);
2395 if to_reclaim_more != Weight::zero() {
2396 crate::BlockWeight::<T>::mutate(|current_weight| {
2397 current_weight.reduce(to_reclaim_more, info.class);
2398 });
2399 crate::ExtrinsicWeightReclaimed::<T>::put(accurate_reclaim);
2400 }
2401
2402 Ok(())
2403 }
2404}
2405
2406pub fn unique(entropy: impl Encode) -> [u8; 32] {
2409 let mut last = [0u8; 32];
2410 sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
2411 let next = (b"frame_system::unique", entropy, last).using_encoded(blake2_256);
2412 sp_io::storage::set(well_known_keys::INTRABLOCK_ENTROPY, &next);
2413 next
2414}
2415
2416pub struct Provider<T>(PhantomData<T>);
2418impl<T: Config> HandleLifetime<T::AccountId> for Provider<T> {
2419 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2420 Pallet::<T>::inc_providers(t);
2421 Ok(())
2422 }
2423 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2424 Pallet::<T>::dec_providers(t).map(|_| ())
2425 }
2426}
2427
2428pub struct SelfSufficient<T>(PhantomData<T>);
2430impl<T: Config> HandleLifetime<T::AccountId> for SelfSufficient<T> {
2431 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2432 Pallet::<T>::inc_sufficients(t);
2433 Ok(())
2434 }
2435 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2436 Pallet::<T>::dec_sufficients(t);
2437 Ok(())
2438 }
2439}
2440
2441pub struct Consumer<T>(PhantomData<T>);
2443impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> {
2444 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2445 Pallet::<T>::inc_consumers(t)
2446 }
2447 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2448 Pallet::<T>::dec_consumers(t);
2449 Ok(())
2450 }
2451}
2452
2453impl<T: Config> BlockNumberProvider for Pallet<T> {
2454 type BlockNumber = BlockNumberFor<T>;
2455
2456 fn current_block_number() -> Self::BlockNumber {
2457 Pallet::<T>::block_number()
2458 }
2459
2460 #[cfg(feature = "runtime-benchmarks")]
2461 fn set_block_number(n: BlockNumberFor<T>) {
2462 Self::set_block_number(n)
2463 }
2464}
2465
2466impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> {
2472 fn get(k: &T::AccountId) -> T::AccountData {
2473 Account::<T>::get(k).data
2474 }
2475
2476 fn try_mutate_exists<R, E: From<DispatchError>>(
2477 k: &T::AccountId,
2478 f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
2479 ) -> Result<R, E> {
2480 let account = Account::<T>::get(k);
2481 let is_default = account.data == T::AccountData::default();
2482 let mut some_data = if is_default { None } else { Some(account.data) };
2483 let result = f(&mut some_data)?;
2484 if Self::providers(k) > 0 || Self::sufficients(k) > 0 {
2485 Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
2486 } else {
2487 Account::<T>::remove(k)
2488 }
2489 Ok(result)
2490 }
2491}
2492
2493pub fn split_inner<T, R, S>(
2495 option: Option<T>,
2496 splitter: impl FnOnce(T) -> (R, S),
2497) -> (Option<R>, Option<S>) {
2498 match option {
2499 Some(inner) => {
2500 let (r, s) = splitter(inner);
2501 (Some(r), Some(s))
2502 },
2503 None => (None, None),
2504 }
2505}
2506
2507pub struct ChainContext<T>(PhantomData<T>);
2508impl<T> Default for ChainContext<T> {
2509 fn default() -> Self {
2510 ChainContext(PhantomData)
2511 }
2512}
2513
2514impl<T: Config> Lookup for ChainContext<T> {
2515 type Source = <T::Lookup as StaticLookup>::Source;
2516 type Target = <T::Lookup as StaticLookup>::Target;
2517
2518 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
2519 <T::Lookup as StaticLookup>::lookup(s)
2520 }
2521}
2522
2523#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2525pub struct RunToBlockHooks<'a, T>
2526where
2527 T: 'a + Config,
2528{
2529 before_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2530 after_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2531 before_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2532 after_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2533}
2534
2535#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2536impl<'a, T> RunToBlockHooks<'a, T>
2537where
2538 T: 'a + Config,
2539{
2540 pub fn before_initialize<F>(mut self, f: F) -> Self
2542 where
2543 F: 'a + FnMut(BlockNumberFor<T>),
2544 {
2545 self.before_initialize = Box::new(f);
2546 self
2547 }
2548 pub fn after_initialize<F>(mut self, f: F) -> Self
2550 where
2551 F: 'a + FnMut(BlockNumberFor<T>),
2552 {
2553 self.after_initialize = Box::new(f);
2554 self
2555 }
2556 pub fn before_finalize<F>(mut self, f: F) -> Self
2558 where
2559 F: 'a + FnMut(BlockNumberFor<T>),
2560 {
2561 self.before_finalize = Box::new(f);
2562 self
2563 }
2564 pub fn after_finalize<F>(mut self, f: F) -> Self
2566 where
2567 F: 'a + FnMut(BlockNumberFor<T>),
2568 {
2569 self.after_finalize = Box::new(f);
2570 self
2571 }
2572}
2573
2574#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2575impl<'a, T> Default for RunToBlockHooks<'a, T>
2576where
2577 T: Config,
2578{
2579 fn default() -> Self {
2580 Self {
2581 before_initialize: Box::new(|_| {}),
2582 after_initialize: Box::new(|_| {}),
2583 before_finalize: Box::new(|_| {}),
2584 after_finalize: Box::new(|_| {}),
2585 }
2586 }
2587}
2588
2589pub mod pallet_prelude {
2591 pub use crate::{
2592 ensure_authorized, ensure_none, ensure_root, ensure_signed, ensure_signed_or_root,
2593 };
2594
2595 pub type OriginFor<T> = <T as crate::Config>::RuntimeOrigin;
2597
2598 pub type HeaderFor<T> =
2600 <<T as crate::Config>::Block as sp_runtime::traits::HeaderProvider>::HeaderT;
2601
2602 pub type BlockNumberFor<T> = <HeaderFor<T> as sp_runtime::traits::Header>::Number;
2604
2605 pub type ExtrinsicFor<T> =
2607 <<T as crate::Config>::Block as sp_runtime::traits::Block>::Extrinsic;
2608
2609 pub type RuntimeCallFor<T> = <T as crate::Config>::RuntimeCall;
2611
2612 pub type AccountIdFor<T> = <T as crate::Config>::AccountId;
2614}