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, 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,
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 #[pallet::whitelist_storage]
995 pub(super) type ExtrinsicCount<T: Config> = StorageValue<_, u32>;
996
997 #[pallet::storage]
999 #[pallet::whitelist_storage]
1000 pub type InherentsApplied<T: Config> = StorageValue<_, bool, ValueQuery>;
1001
1002 #[pallet::storage]
1004 #[pallet::whitelist_storage]
1005 #[pallet::getter(fn block_weight)]
1006 pub type BlockWeight<T: Config> = StorageValue<_, ConsumedWeight, ValueQuery>;
1007
1008 #[pallet::storage]
1010 #[pallet::whitelist_storage]
1011 pub type AllExtrinsicsLen<T: Config> = StorageValue<_, u32>;
1012
1013 #[pallet::storage]
1015 #[pallet::getter(fn block_hash)]
1016 pub type BlockHash<T: Config> =
1017 StorageMap<_, Twox64Concat, BlockNumberFor<T>, T::Hash, ValueQuery>;
1018
1019 #[pallet::storage]
1021 #[pallet::getter(fn extrinsic_data)]
1022 #[pallet::unbounded]
1023 pub(super) type ExtrinsicData<T: Config> =
1024 StorageMap<_, Twox64Concat, u32, Vec<u8>, ValueQuery>;
1025
1026 #[pallet::storage]
1028 #[pallet::whitelist_storage]
1029 #[pallet::getter(fn block_number)]
1030 pub(super) type Number<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;
1031
1032 #[pallet::storage]
1034 #[pallet::getter(fn parent_hash)]
1035 pub(super) type ParentHash<T: Config> = StorageValue<_, T::Hash, ValueQuery>;
1036
1037 #[pallet::storage]
1039 #[pallet::whitelist_storage]
1040 #[pallet::unbounded]
1041 #[pallet::getter(fn digest)]
1042 pub(super) type Digest<T: Config> = StorageValue<_, generic::Digest, ValueQuery>;
1043
1044 #[pallet::storage]
1052 #[pallet::whitelist_storage]
1053 #[pallet::disable_try_decode_storage]
1054 #[pallet::unbounded]
1055 pub(super) type Events<T: Config> =
1056 StorageValue<_, Vec<Box<EventRecord<T::RuntimeEvent, T::Hash>>>, ValueQuery>;
1057
1058 #[pallet::storage]
1060 #[pallet::whitelist_storage]
1061 #[pallet::getter(fn event_count)]
1062 pub(super) type EventCount<T: Config> = StorageValue<_, EventIndex, ValueQuery>;
1063
1064 #[pallet::storage]
1075 #[pallet::unbounded]
1076 #[pallet::getter(fn event_topics)]
1077 pub(super) type EventTopics<T: Config> =
1078 StorageMap<_, Blake2_128Concat, T::Hash, Vec<(BlockNumberFor<T>, EventIndex)>, ValueQuery>;
1079
1080 #[pallet::storage]
1082 #[pallet::unbounded]
1083 pub type LastRuntimeUpgrade<T: Config> = StorageValue<_, LastRuntimeUpgradeInfo>;
1084
1085 #[pallet::storage]
1087 pub(super) type UpgradedToU32RefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1088
1089 #[pallet::storage]
1092 pub(super) type UpgradedToTripleRefCount<T: Config> = StorageValue<_, bool, ValueQuery>;
1093
1094 #[pallet::storage]
1096 #[pallet::whitelist_storage]
1097 pub(super) type ExecutionPhase<T: Config> = StorageValue<_, Phase>;
1098
1099 #[pallet::storage]
1101 #[pallet::getter(fn authorized_upgrade)]
1102 pub(super) type AuthorizedUpgrade<T: Config> =
1103 StorageValue<_, CodeUpgradeAuthorization<T>, OptionQuery>;
1104
1105 #[pallet::storage]
1113 #[pallet::whitelist_storage]
1114 pub type ExtrinsicWeightReclaimed<T: Config> = StorageValue<_, Weight, ValueQuery>;
1115
1116 #[derive(frame_support::DefaultNoBound)]
1117 #[pallet::genesis_config]
1118 pub struct GenesisConfig<T: Config> {
1119 #[serde(skip)]
1120 pub _config: core::marker::PhantomData<T>,
1121 }
1122
1123 #[pallet::genesis_build]
1124 impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
1125 fn build(&self) {
1126 <BlockHash<T>>::insert::<_, T::Hash>(BlockNumberFor::<T>::zero(), hash69());
1127 <ParentHash<T>>::put::<T::Hash>(hash69());
1128 <LastRuntimeUpgrade<T>>::put(LastRuntimeUpgradeInfo::from(T::Version::get()));
1129 <UpgradedToU32RefCount<T>>::put(true);
1130 <UpgradedToTripleRefCount<T>>::put(true);
1131
1132 sp_io::storage::set(well_known_keys::EXTRINSIC_INDEX, &0u32.encode());
1133 }
1134 }
1135
1136 #[pallet::validate_unsigned]
1137 impl<T: Config> sp_runtime::traits::ValidateUnsigned for Pallet<T> {
1138 type Call = Call<T>;
1139 fn validate_unsigned(source: TransactionSource, call: &Self::Call) -> TransactionValidity {
1140 if let Call::apply_authorized_upgrade { ref code } = call {
1141 if let Ok(res) = Self::validate_code_is_authorized(&code[..]) {
1142 if Self::can_set_code(&code, false).is_ok() {
1143 return Ok(ValidTransaction {
1144 priority: u64::max_value(),
1145 requires: Vec::new(),
1146 provides: vec![res.code_hash.encode()],
1147 longevity: TransactionLongevity::max_value(),
1148 propagate: true,
1149 })
1150 }
1151 }
1152 }
1153
1154 #[cfg(feature = "experimental")]
1155 if let Call::do_task { ref task } = call {
1156 if source == TransactionSource::InBlock || source == TransactionSource::Local {
1164 if task.is_valid() {
1165 return Ok(ValidTransaction {
1166 priority: u64::max_value(),
1167 requires: Vec::new(),
1168 provides: vec![T::Hashing::hash_of(&task.encode()).as_ref().to_vec()],
1169 longevity: TransactionLongevity::max_value(),
1170 propagate: false,
1171 })
1172 }
1173 }
1174 }
1175
1176 #[cfg(not(feature = "experimental"))]
1177 let _ = source;
1178
1179 Err(InvalidTransaction::Call.into())
1180 }
1181 }
1182}
1183
1184pub type Key = Vec<u8>;
1185pub type KeyValue = (Vec<u8>, Vec<u8>);
1186
1187#[derive(Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]
1189#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1190pub enum Phase {
1191 ApplyExtrinsic(u32),
1193 Finalization,
1195 Initialization,
1197}
1198
1199impl Default for Phase {
1200 fn default() -> Self {
1201 Self::Initialization
1202 }
1203}
1204
1205#[derive(Encode, Decode, RuntimeDebug, TypeInfo)]
1207#[cfg_attr(feature = "std", derive(Serialize, PartialEq, Eq, Clone))]
1208pub struct EventRecord<E: Parameter + Member, T> {
1209 pub phase: Phase,
1211 pub event: E,
1213 pub topics: Vec<T>,
1215}
1216
1217fn hash69<T: AsMut<[u8]> + Default>() -> T {
1220 let mut h = T::default();
1221 h.as_mut().iter_mut().for_each(|byte| *byte = 69);
1222 h
1223}
1224
1225type EventIndex = u32;
1230
1231pub type RefCount = u32;
1233
1234#[derive(Clone, Eq, PartialEq, Default, RuntimeDebug, Encode, Decode, TypeInfo, MaxEncodedLen)]
1236pub struct AccountInfo<Nonce, AccountData> {
1237 pub nonce: Nonce,
1239 pub consumers: RefCount,
1242 pub providers: RefCount,
1245 pub sufficients: RefCount,
1248 pub data: AccountData,
1251}
1252
1253#[derive(RuntimeDebug, Encode, Decode, TypeInfo)]
1256#[cfg_attr(feature = "std", derive(PartialEq))]
1257pub struct LastRuntimeUpgradeInfo {
1258 pub spec_version: codec::Compact<u32>,
1259 pub spec_name: Cow<'static, str>,
1260}
1261
1262impl LastRuntimeUpgradeInfo {
1263 pub fn was_upgraded(&self, current: &RuntimeVersion) -> bool {
1267 current.spec_version > self.spec_version.0 || current.spec_name != self.spec_name
1268 }
1269}
1270
1271impl From<RuntimeVersion> for LastRuntimeUpgradeInfo {
1272 fn from(version: RuntimeVersion) -> Self {
1273 Self { spec_version: version.spec_version.into(), spec_name: version.spec_name }
1274 }
1275}
1276
1277pub struct EnsureRoot<AccountId>(core::marker::PhantomData<AccountId>);
1279impl<O: OriginTrait, AccountId> EnsureOrigin<O> for EnsureRoot<AccountId> {
1280 type Success = ();
1281 fn try_origin(o: O) -> Result<Self::Success, O> {
1282 match o.as_system_ref() {
1283 Some(RawOrigin::Root) => Ok(()),
1284 _ => Err(o),
1285 }
1286 }
1287
1288 #[cfg(feature = "runtime-benchmarks")]
1289 fn try_successful_origin() -> Result<O, ()> {
1290 Ok(O::root())
1291 }
1292}
1293
1294impl_ensure_origin_with_arg_ignoring_arg! {
1295 impl< { O: .., AccountId: Decode, T } >
1296 EnsureOriginWithArg<O, T> for EnsureRoot<AccountId>
1297 {}
1298}
1299
1300pub struct EnsureRootWithSuccess<AccountId, Success>(
1302 core::marker::PhantomData<(AccountId, Success)>,
1303);
1304impl<O: OriginTrait, AccountId, Success: TypedGet> EnsureOrigin<O>
1305 for EnsureRootWithSuccess<AccountId, Success>
1306{
1307 type Success = Success::Type;
1308 fn try_origin(o: O) -> Result<Self::Success, O> {
1309 match o.as_system_ref() {
1310 Some(RawOrigin::Root) => Ok(Success::get()),
1311 _ => Err(o),
1312 }
1313 }
1314
1315 #[cfg(feature = "runtime-benchmarks")]
1316 fn try_successful_origin() -> Result<O, ()> {
1317 Ok(O::root())
1318 }
1319}
1320
1321impl_ensure_origin_with_arg_ignoring_arg! {
1322 impl< { O: .., AccountId: Decode, Success: TypedGet, T } >
1323 EnsureOriginWithArg<O, T> for EnsureRootWithSuccess<AccountId, Success>
1324 {}
1325}
1326
1327pub struct EnsureWithSuccess<Ensure, AccountId, Success>(
1329 core::marker::PhantomData<(Ensure, AccountId, Success)>,
1330);
1331
1332impl<O: OriginTrait, Ensure: EnsureOrigin<O>, AccountId, Success: TypedGet> EnsureOrigin<O>
1333 for EnsureWithSuccess<Ensure, AccountId, Success>
1334{
1335 type Success = Success::Type;
1336
1337 fn try_origin(o: O) -> Result<Self::Success, O> {
1338 Ensure::try_origin(o).map(|_| Success::get())
1339 }
1340
1341 #[cfg(feature = "runtime-benchmarks")]
1342 fn try_successful_origin() -> Result<O, ()> {
1343 Ensure::try_successful_origin()
1344 }
1345}
1346
1347pub struct EnsureSigned<AccountId>(core::marker::PhantomData<AccountId>);
1349impl<O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone> EnsureOrigin<O>
1350 for EnsureSigned<AccountId>
1351{
1352 type Success = AccountId;
1353 fn try_origin(o: O) -> Result<Self::Success, O> {
1354 match o.as_system_ref() {
1355 Some(RawOrigin::Signed(who)) => Ok(who.clone()),
1356 _ => Err(o),
1357 }
1358 }
1359
1360 #[cfg(feature = "runtime-benchmarks")]
1361 fn try_successful_origin() -> Result<O, ()> {
1362 let zero_account_id =
1363 AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?;
1364 Ok(O::signed(zero_account_id))
1365 }
1366}
1367
1368impl_ensure_origin_with_arg_ignoring_arg! {
1369 impl< { O: OriginTrait<AccountId = AccountId>, AccountId: Decode + Clone, T } >
1370 EnsureOriginWithArg<O, T> for EnsureSigned<AccountId>
1371 {}
1372}
1373
1374pub struct EnsureSignedBy<Who, AccountId>(core::marker::PhantomData<(Who, AccountId)>);
1376impl<
1377 O: OriginTrait<AccountId = AccountId>,
1378 Who: SortedMembers<AccountId>,
1379 AccountId: PartialEq + Clone + Ord + Decode,
1380 > EnsureOrigin<O> for EnsureSignedBy<Who, AccountId>
1381{
1382 type Success = AccountId;
1383 fn try_origin(o: O) -> Result<Self::Success, O> {
1384 match o.as_system_ref() {
1385 Some(RawOrigin::Signed(ref who)) if Who::contains(who) => Ok(who.clone()),
1386 _ => Err(o),
1387 }
1388 }
1389
1390 #[cfg(feature = "runtime-benchmarks")]
1391 fn try_successful_origin() -> Result<O, ()> {
1392 let first_member = match Who::sorted_members().first() {
1393 Some(account) => account.clone(),
1394 None => AccountId::decode(&mut TrailingZeroInput::zeroes()).map_err(|_| ())?,
1395 };
1396 Ok(O::signed(first_member))
1397 }
1398}
1399
1400impl_ensure_origin_with_arg_ignoring_arg! {
1401 impl< { O: OriginTrait<AccountId = AccountId>, Who: SortedMembers<AccountId>, AccountId: PartialEq + Clone + Ord + Decode, T } >
1402 EnsureOriginWithArg<O, T> for EnsureSignedBy<Who, AccountId>
1403 {}
1404}
1405
1406pub struct EnsureNone<AccountId>(core::marker::PhantomData<AccountId>);
1408impl<O: OriginTrait<AccountId = AccountId>, AccountId> EnsureOrigin<O> for EnsureNone<AccountId> {
1409 type Success = ();
1410 fn try_origin(o: O) -> Result<Self::Success, O> {
1411 match o.as_system_ref() {
1412 Some(RawOrigin::None) => Ok(()),
1413 _ => Err(o),
1414 }
1415 }
1416
1417 #[cfg(feature = "runtime-benchmarks")]
1418 fn try_successful_origin() -> Result<O, ()> {
1419 Ok(O::none())
1420 }
1421}
1422
1423impl_ensure_origin_with_arg_ignoring_arg! {
1424 impl< { O: OriginTrait<AccountId = AccountId>, AccountId, T } >
1425 EnsureOriginWithArg<O, T> for EnsureNone<AccountId>
1426 {}
1427}
1428
1429pub struct EnsureNever<Success>(core::marker::PhantomData<Success>);
1431impl<O, Success> EnsureOrigin<O> for EnsureNever<Success> {
1432 type Success = Success;
1433 fn try_origin(o: O) -> Result<Self::Success, O> {
1434 Err(o)
1435 }
1436
1437 #[cfg(feature = "runtime-benchmarks")]
1438 fn try_successful_origin() -> Result<O, ()> {
1439 Err(())
1440 }
1441}
1442
1443impl_ensure_origin_with_arg_ignoring_arg! {
1444 impl< { O, Success, T } >
1445 EnsureOriginWithArg<O, T> for EnsureNever<Success>
1446 {}
1447}
1448
1449#[docify::export]
1450pub fn ensure_signed<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<AccountId, BadOrigin>
1453where
1454 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1455{
1456 match o.into() {
1457 Ok(RawOrigin::Signed(t)) => Ok(t),
1458 _ => Err(BadOrigin),
1459 }
1460}
1461
1462pub fn ensure_signed_or_root<OuterOrigin, AccountId>(
1466 o: OuterOrigin,
1467) -> Result<Option<AccountId>, BadOrigin>
1468where
1469 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1470{
1471 match o.into() {
1472 Ok(RawOrigin::Root) => Ok(None),
1473 Ok(RawOrigin::Signed(t)) => Ok(Some(t)),
1474 _ => Err(BadOrigin),
1475 }
1476}
1477
1478pub fn ensure_root<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1480where
1481 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1482{
1483 match o.into() {
1484 Ok(RawOrigin::Root) => Ok(()),
1485 _ => Err(BadOrigin),
1486 }
1487}
1488
1489pub fn ensure_none<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1491where
1492 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1493{
1494 match o.into() {
1495 Ok(RawOrigin::None) => Ok(()),
1496 _ => Err(BadOrigin),
1497 }
1498}
1499
1500pub fn ensure_authorized<OuterOrigin, AccountId>(o: OuterOrigin) -> Result<(), BadOrigin>
1503where
1504 OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>>,
1505{
1506 match o.into() {
1507 Ok(RawOrigin::Authorized) => Ok(()),
1508 _ => Err(BadOrigin),
1509 }
1510}
1511
1512#[derive(RuntimeDebug)]
1514pub enum RefStatus {
1515 Referenced,
1516 Unreferenced,
1517}
1518
1519#[derive(Eq, PartialEq, RuntimeDebug)]
1521pub enum IncRefStatus {
1522 Created,
1524 Existed,
1526}
1527
1528#[derive(Eq, PartialEq, RuntimeDebug)]
1530pub enum DecRefStatus {
1531 Reaped,
1533 Exists,
1535}
1536
1537pub enum CanSetCodeResult<T: Config> {
1539 Ok,
1541 MultiBlockMigrationsOngoing,
1543 InvalidVersion(Error<T>),
1545}
1546
1547impl<T: Config> CanSetCodeResult<T> {
1548 pub fn into_result(self) -> Result<(), DispatchError> {
1550 match self {
1551 Self::Ok => Ok(()),
1552 Self::MultiBlockMigrationsOngoing =>
1553 Err(Error::<T>::MultiBlockMigrationsOngoing.into()),
1554 Self::InvalidVersion(err) => Err(err.into()),
1555 }
1556 }
1557
1558 pub fn is_ok(&self) -> bool {
1560 matches!(self, Self::Ok)
1561 }
1562}
1563
1564impl<T: Config> Pallet<T> {
1565 #[doc = docify::embed!("src/tests.rs", last_runtime_upgrade_spec_version_usage)]
1579 pub fn last_runtime_upgrade_spec_version() -> u32 {
1580 LastRuntimeUpgrade::<T>::get().map_or(0, |l| l.spec_version.0)
1581 }
1582
1583 pub fn account_exists(who: &T::AccountId) -> bool {
1585 Account::<T>::contains_key(who)
1586 }
1587
1588 pub fn update_code_in_storage(code: &[u8]) {
1594 storage::unhashed::put_raw(well_known_keys::CODE, code);
1595 Self::deposit_log(generic::DigestItem::RuntimeEnvironmentUpdated);
1596 Self::deposit_event(Event::CodeUpdated);
1597 }
1598
1599 pub fn inherents_applied() -> bool {
1601 InherentsApplied::<T>::get()
1602 }
1603
1604 pub fn note_inherents_applied() {
1609 InherentsApplied::<T>::put(true);
1610 }
1611
1612 #[deprecated = "Use `inc_consumers` instead"]
1614 pub fn inc_ref(who: &T::AccountId) {
1615 let _ = Self::inc_consumers(who);
1616 }
1617
1618 #[deprecated = "Use `dec_consumers` instead"]
1621 pub fn dec_ref(who: &T::AccountId) {
1622 let _ = Self::dec_consumers(who);
1623 }
1624
1625 #[deprecated = "Use `consumers` instead"]
1627 pub fn refs(who: &T::AccountId) -> RefCount {
1628 Self::consumers(who)
1629 }
1630
1631 #[deprecated = "Use `!is_provider_required` instead"]
1633 pub fn allow_death(who: &T::AccountId) -> bool {
1634 !Self::is_provider_required(who)
1635 }
1636
1637 pub fn inc_providers(who: &T::AccountId) -> IncRefStatus {
1639 Account::<T>::mutate(who, |a| {
1640 if a.providers == 0 && a.sufficients == 0 {
1641 a.providers = 1;
1643 Self::on_created_account(who.clone(), a);
1644 IncRefStatus::Created
1645 } else {
1646 a.providers = a.providers.saturating_add(1);
1647 IncRefStatus::Existed
1648 }
1649 })
1650 }
1651
1652 pub fn dec_providers(who: &T::AccountId) -> Result<DecRefStatus, DispatchError> {
1656 Account::<T>::try_mutate_exists(who, |maybe_account| {
1657 if let Some(mut account) = maybe_account.take() {
1658 if account.providers == 0 {
1659 log::error!(
1661 target: LOG_TARGET,
1662 "Logic error: Unexpected underflow in reducing provider",
1663 );
1664 account.providers = 1;
1665 }
1666 match (account.providers, account.consumers, account.sufficients) {
1667 (1, 0, 0) => {
1668 Pallet::<T>::on_killed_account(who.clone());
1671 Ok(DecRefStatus::Reaped)
1672 },
1673 (1, c, _) if c > 0 => {
1674 Err(DispatchError::ConsumerRemaining)
1676 },
1677 (x, _, _) => {
1678 account.providers = x - 1;
1681 *maybe_account = Some(account);
1682 Ok(DecRefStatus::Exists)
1683 },
1684 }
1685 } else {
1686 log::error!(
1687 target: LOG_TARGET,
1688 "Logic error: Account already dead when reducing provider",
1689 );
1690 Ok(DecRefStatus::Reaped)
1691 }
1692 })
1693 }
1694
1695 pub fn inc_sufficients(who: &T::AccountId) -> IncRefStatus {
1697 Account::<T>::mutate(who, |a| {
1698 if a.providers + a.sufficients == 0 {
1699 a.sufficients = 1;
1701 Self::on_created_account(who.clone(), a);
1702 IncRefStatus::Created
1703 } else {
1704 a.sufficients = a.sufficients.saturating_add(1);
1705 IncRefStatus::Existed
1706 }
1707 })
1708 }
1709
1710 pub fn dec_sufficients(who: &T::AccountId) -> DecRefStatus {
1714 Account::<T>::mutate_exists(who, |maybe_account| {
1715 if let Some(mut account) = maybe_account.take() {
1716 if account.sufficients == 0 {
1717 log::error!(
1719 target: LOG_TARGET,
1720 "Logic error: Unexpected underflow in reducing sufficients",
1721 );
1722 }
1723 match (account.sufficients, account.providers) {
1724 (0, 0) | (1, 0) => {
1725 Pallet::<T>::on_killed_account(who.clone());
1726 DecRefStatus::Reaped
1727 },
1728 (x, _) => {
1729 account.sufficients = x.saturating_sub(1);
1730 *maybe_account = Some(account);
1731 DecRefStatus::Exists
1732 },
1733 }
1734 } else {
1735 log::error!(
1736 target: LOG_TARGET,
1737 "Logic error: Account already dead when reducing provider",
1738 );
1739 DecRefStatus::Reaped
1740 }
1741 })
1742 }
1743
1744 pub fn providers(who: &T::AccountId) -> RefCount {
1746 Account::<T>::get(who).providers
1747 }
1748
1749 pub fn sufficients(who: &T::AccountId) -> RefCount {
1751 Account::<T>::get(who).sufficients
1752 }
1753
1754 pub fn reference_count(who: &T::AccountId) -> RefCount {
1756 let a = Account::<T>::get(who);
1757 a.providers + a.sufficients
1758 }
1759
1760 pub fn inc_consumers(who: &T::AccountId) -> Result<(), DispatchError> {
1765 Account::<T>::try_mutate(who, |a| {
1766 if a.providers > 0 {
1767 if a.consumers < T::MaxConsumers::max_consumers() {
1768 a.consumers = a.consumers.saturating_add(1);
1769 Ok(())
1770 } else {
1771 Err(DispatchError::TooManyConsumers)
1772 }
1773 } else {
1774 Err(DispatchError::NoProviders)
1775 }
1776 })
1777 }
1778
1779 pub fn inc_consumers_without_limit(who: &T::AccountId) -> Result<(), DispatchError> {
1783 Account::<T>::try_mutate(who, |a| {
1784 if a.providers > 0 {
1785 a.consumers = a.consumers.saturating_add(1);
1786 Ok(())
1787 } else {
1788 Err(DispatchError::NoProviders)
1789 }
1790 })
1791 }
1792
1793 pub fn dec_consumers(who: &T::AccountId) {
1796 Account::<T>::mutate(who, |a| {
1797 if a.consumers > 0 {
1798 a.consumers -= 1;
1799 } else {
1800 log::error!(
1801 target: LOG_TARGET,
1802 "Logic error: Unexpected underflow in reducing consumer",
1803 );
1804 }
1805 })
1806 }
1807
1808 pub fn consumers(who: &T::AccountId) -> RefCount {
1810 Account::<T>::get(who).consumers
1811 }
1812
1813 pub fn is_provider_required(who: &T::AccountId) -> bool {
1815 Account::<T>::get(who).consumers != 0
1816 }
1817
1818 pub fn can_dec_provider(who: &T::AccountId) -> bool {
1820 let a = Account::<T>::get(who);
1821 a.consumers == 0 || a.providers > 1
1822 }
1823
1824 pub fn can_accrue_consumers(who: &T::AccountId, amount: u32) -> bool {
1827 let a = Account::<T>::get(who);
1828 match a.consumers.checked_add(amount) {
1829 Some(c) => a.providers > 0 && c <= T::MaxConsumers::max_consumers(),
1830 None => false,
1831 }
1832 }
1833
1834 pub fn can_inc_consumer(who: &T::AccountId) -> bool {
1837 Self::can_accrue_consumers(who, 1)
1838 }
1839
1840 pub fn deposit_event(event: impl Into<T::RuntimeEvent>) {
1844 Self::deposit_event_indexed(&[], event.into());
1845 }
1846
1847 pub fn deposit_event_indexed(topics: &[T::Hash], event: T::RuntimeEvent) {
1855 let block_number = Self::block_number();
1856
1857 if block_number.is_zero() {
1859 return
1860 }
1861
1862 let phase = ExecutionPhase::<T>::get().unwrap_or_default();
1863 let event = EventRecord { phase, event, topics: topics.to_vec() };
1864
1865 let event_idx = {
1867 let old_event_count = EventCount::<T>::get();
1868 let new_event_count = match old_event_count.checked_add(1) {
1869 None => return,
1872 Some(nc) => nc,
1873 };
1874 EventCount::<T>::put(new_event_count);
1875 old_event_count
1876 };
1877
1878 Events::<T>::append(event);
1879
1880 for topic in topics {
1881 <EventTopics<T>>::append(topic, &(block_number, event_idx));
1882 }
1883 }
1884
1885 pub fn extrinsic_index() -> Option<u32> {
1887 storage::unhashed::get(well_known_keys::EXTRINSIC_INDEX)
1888 }
1889
1890 pub fn extrinsic_count() -> u32 {
1892 ExtrinsicCount::<T>::get().unwrap_or_default()
1893 }
1894
1895 pub fn all_extrinsics_len() -> u32 {
1896 AllExtrinsicsLen::<T>::get().unwrap_or_default()
1897 }
1898
1899 pub fn register_extra_weight_unchecked(weight: Weight, class: DispatchClass) {
1915 BlockWeight::<T>::mutate(|current_weight| {
1916 current_weight.accrue(weight, class);
1917 });
1918 }
1919
1920 pub fn initialize(number: &BlockNumberFor<T>, parent_hash: &T::Hash, digest: &generic::Digest) {
1927 let expected_block_number = Self::block_number() + One::one();
1928 assert_eq!(expected_block_number, *number, "Block number must be strictly increasing.");
1929
1930 ExecutionPhase::<T>::put(Phase::Initialization);
1932 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &0u32);
1933 Self::initialize_intra_block_entropy(parent_hash);
1934 <Number<T>>::put(number);
1935 <Digest<T>>::put(digest);
1936 <ParentHash<T>>::put(parent_hash);
1937 <BlockHash<T>>::insert(*number - One::one(), parent_hash);
1938
1939 BlockWeight::<T>::kill();
1941 }
1942
1943 pub fn initialize_intra_block_entropy(parent_hash: &T::Hash) {
1947 let entropy = (b"frame_system::initialize", parent_hash).using_encoded(blake2_256);
1948 storage::unhashed::put_raw(well_known_keys::INTRABLOCK_ENTROPY, &entropy[..]);
1949 }
1950
1951 pub fn resource_usage_report() {
1955 log::debug!(
1956 target: LOG_TARGET,
1957 "[{:?}] {} extrinsics, length: {} (normal {}%, op: {}%, mandatory {}%) / normal weight:\
1958 {} (ref_time: {}%, proof_size: {}%) op weight {} (ref_time {}%, proof_size {}%) / \
1959 mandatory weight {} (ref_time: {}%, proof_size: {}%)",
1960 Self::block_number(),
1961 Self::extrinsic_count(),
1962 Self::all_extrinsics_len(),
1963 sp_runtime::Percent::from_rational(
1964 Self::all_extrinsics_len(),
1965 *T::BlockLength::get().max.get(DispatchClass::Normal)
1966 ).deconstruct(),
1967 sp_runtime::Percent::from_rational(
1968 Self::all_extrinsics_len(),
1969 *T::BlockLength::get().max.get(DispatchClass::Operational)
1970 ).deconstruct(),
1971 sp_runtime::Percent::from_rational(
1972 Self::all_extrinsics_len(),
1973 *T::BlockLength::get().max.get(DispatchClass::Mandatory)
1974 ).deconstruct(),
1975 Self::block_weight().get(DispatchClass::Normal),
1976 sp_runtime::Percent::from_rational(
1977 Self::block_weight().get(DispatchClass::Normal).ref_time(),
1978 T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).ref_time()
1979 ).deconstruct(),
1980 sp_runtime::Percent::from_rational(
1981 Self::block_weight().get(DispatchClass::Normal).proof_size(),
1982 T::BlockWeights::get().get(DispatchClass::Normal).max_total.unwrap_or(Bounded::max_value()).proof_size()
1983 ).deconstruct(),
1984 Self::block_weight().get(DispatchClass::Operational),
1985 sp_runtime::Percent::from_rational(
1986 Self::block_weight().get(DispatchClass::Operational).ref_time(),
1987 T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).ref_time()
1988 ).deconstruct(),
1989 sp_runtime::Percent::from_rational(
1990 Self::block_weight().get(DispatchClass::Operational).proof_size(),
1991 T::BlockWeights::get().get(DispatchClass::Operational).max_total.unwrap_or(Bounded::max_value()).proof_size()
1992 ).deconstruct(),
1993 Self::block_weight().get(DispatchClass::Mandatory),
1994 sp_runtime::Percent::from_rational(
1995 Self::block_weight().get(DispatchClass::Mandatory).ref_time(),
1996 T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).ref_time()
1997 ).deconstruct(),
1998 sp_runtime::Percent::from_rational(
1999 Self::block_weight().get(DispatchClass::Mandatory).proof_size(),
2000 T::BlockWeights::get().get(DispatchClass::Mandatory).max_total.unwrap_or(Bounded::max_value()).proof_size()
2001 ).deconstruct(),
2002 );
2003 }
2004
2005 pub fn finalize() -> HeaderFor<T> {
2008 Self::resource_usage_report();
2009 ExecutionPhase::<T>::kill();
2010 AllExtrinsicsLen::<T>::kill();
2011 storage::unhashed::kill(well_known_keys::INTRABLOCK_ENTROPY);
2012 InherentsApplied::<T>::kill();
2013
2014 let number = <Number<T>>::get();
2025 let parent_hash = <ParentHash<T>>::get();
2026 let digest = <Digest<T>>::get();
2027
2028 let extrinsics = (0..ExtrinsicCount::<T>::take().unwrap_or_default())
2029 .map(ExtrinsicData::<T>::take)
2030 .collect();
2031 let extrinsics_root_state_version = T::Version::get().extrinsics_root_state_version();
2032 let extrinsics_root =
2033 extrinsics_data_root::<T::Hashing>(extrinsics, extrinsics_root_state_version);
2034
2035 let block_hash_count = T::BlockHashCount::get();
2037 let to_remove = number.saturating_sub(block_hash_count).saturating_sub(One::one());
2038
2039 if !to_remove.is_zero() {
2041 <BlockHash<T>>::remove(to_remove);
2042 }
2043
2044 let version = T::Version::get().state_version();
2045 let storage_root = T::Hash::decode(&mut &sp_io::storage::root(version)[..])
2046 .expect("Node is configured to use the same hash; qed");
2047
2048 HeaderFor::<T>::new(number, extrinsics_root, storage_root, parent_hash, digest)
2049 }
2050
2051 pub fn deposit_log(item: generic::DigestItem) {
2053 <Digest<T>>::append(item);
2054 }
2055
2056 #[cfg(any(feature = "std", test))]
2058 pub fn externalities() -> TestExternalities {
2059 TestExternalities::new(sp_core::storage::Storage {
2060 top: [
2061 (<BlockHash<T>>::hashed_key_for(BlockNumberFor::<T>::zero()), [69u8; 32].encode()),
2062 (<Number<T>>::hashed_key().to_vec(), BlockNumberFor::<T>::one().encode()),
2063 (<ParentHash<T>>::hashed_key().to_vec(), [69u8; 32].encode()),
2064 ]
2065 .into_iter()
2066 .collect(),
2067 children_default: Default::default(),
2068 })
2069 }
2070
2071 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2079 pub fn events() -> Vec<EventRecord<T::RuntimeEvent, T::Hash>> {
2080 Self::read_events_no_consensus().map(|e| *e).collect()
2082 }
2083
2084 pub fn event_no_consensus(index: usize) -> Option<T::RuntimeEvent> {
2089 Self::read_events_no_consensus().nth(index).map(|e| e.event.clone())
2090 }
2091
2092 pub fn read_events_no_consensus(
2097 ) -> impl Iterator<Item = Box<EventRecord<T::RuntimeEvent, T::Hash>>> {
2098 Events::<T>::stream_iter()
2099 }
2100
2101 pub fn read_events_for_pallet<E>() -> Vec<E>
2106 where
2107 T::RuntimeEvent: TryInto<E>,
2108 {
2109 Events::<T>::get()
2110 .into_iter()
2111 .map(|er| er.event)
2112 .filter_map(|e| e.try_into().ok())
2113 .collect::<_>()
2114 }
2115
2116 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2125 pub fn run_to_block_with<AllPalletsWithSystem>(
2126 n: BlockNumberFor<T>,
2127 mut hooks: RunToBlockHooks<T>,
2128 ) where
2129 AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
2130 + frame_support::traits::OnFinalize<BlockNumberFor<T>>,
2131 {
2132 let mut bn = Self::block_number();
2133
2134 while bn < n {
2135 if !bn.is_zero() {
2137 (hooks.before_finalize)(bn);
2138 AllPalletsWithSystem::on_finalize(bn);
2139 (hooks.after_finalize)(bn);
2140 }
2141
2142 bn += One::one();
2143
2144 Self::set_block_number(bn);
2145 (hooks.before_initialize)(bn);
2146 AllPalletsWithSystem::on_initialize(bn);
2147 (hooks.after_initialize)(bn);
2148 }
2149 }
2150
2151 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2153 pub fn run_to_block<AllPalletsWithSystem>(n: BlockNumberFor<T>)
2154 where
2155 AllPalletsWithSystem: frame_support::traits::OnInitialize<BlockNumberFor<T>>
2156 + frame_support::traits::OnFinalize<BlockNumberFor<T>>,
2157 {
2158 Self::run_to_block_with::<AllPalletsWithSystem>(n, Default::default());
2159 }
2160
2161 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2164 pub fn set_block_number(n: BlockNumberFor<T>) {
2165 <Number<T>>::put(n);
2166 }
2167
2168 #[cfg(any(feature = "std", test))]
2170 pub fn set_extrinsic_index(extrinsic_index: u32) {
2171 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &extrinsic_index)
2172 }
2173
2174 #[cfg(any(feature = "std", test))]
2177 pub fn set_parent_hash(n: T::Hash) {
2178 <ParentHash<T>>::put(n);
2179 }
2180
2181 #[cfg(any(feature = "std", test))]
2183 pub fn set_block_consumed_resources(weight: Weight, len: usize) {
2184 BlockWeight::<T>::mutate(|current_weight| {
2185 current_weight.set(weight, DispatchClass::Normal)
2186 });
2187 AllExtrinsicsLen::<T>::put(len as u32);
2188 }
2189
2190 pub fn reset_events() {
2195 <Events<T>>::kill();
2196 EventCount::<T>::kill();
2197 let _ = <EventTopics<T>>::clear(u32::max_value(), None);
2198 }
2199
2200 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2204 #[track_caller]
2205 pub fn assert_has_event(event: T::RuntimeEvent) {
2206 let warn = if Self::block_number().is_zero() {
2207 "WARNING: block number is zero, and events are not registered at block number zero.\n"
2208 } else {
2209 ""
2210 };
2211
2212 let events = Self::events();
2213 assert!(
2214 events.iter().any(|record| record.event == event),
2215 "{warn}expected event {event:?} not found in events {events:?}",
2216 );
2217 }
2218
2219 #[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2223 #[track_caller]
2224 pub fn assert_last_event(event: T::RuntimeEvent) {
2225 let warn = if Self::block_number().is_zero() {
2226 "WARNING: block number is zero, and events are not registered at block number zero.\n"
2227 } else {
2228 ""
2229 };
2230
2231 let last_event = Self::events()
2232 .last()
2233 .expect(&alloc::format!("{warn}events expected"))
2234 .event
2235 .clone();
2236 assert_eq!(
2237 last_event, event,
2238 "{warn}expected event {event:?} is not equal to the last event {last_event:?}",
2239 );
2240 }
2241
2242 pub fn runtime_version() -> RuntimeVersion {
2244 T::Version::get()
2245 }
2246
2247 pub fn account_nonce(who: impl EncodeLike<T::AccountId>) -> T::Nonce {
2249 Account::<T>::get(who).nonce
2250 }
2251
2252 pub fn inc_account_nonce(who: impl EncodeLike<T::AccountId>) {
2254 Account::<T>::mutate(who, |a| a.nonce += T::Nonce::one());
2255 }
2256
2257 pub fn note_extrinsic(encoded_xt: Vec<u8>) {
2262 ExtrinsicData::<T>::insert(Self::extrinsic_index().unwrap_or_default(), encoded_xt);
2263 }
2264
2265 pub fn note_applied_extrinsic(r: &DispatchResultWithPostInfo, info: DispatchInfo) {
2271 let weight = extract_actual_weight(r, &info)
2272 .saturating_add(T::BlockWeights::get().get(info.class).base_extrinsic);
2273 let class = info.class;
2274 let pays_fee = extract_actual_pays_fee(r, &info);
2275 let dispatch_event_info = DispatchEventInfo { weight, class, pays_fee };
2276
2277 Self::deposit_event(match r {
2278 Ok(_) => Event::ExtrinsicSuccess { dispatch_info: dispatch_event_info },
2279 Err(err) => {
2280 log::trace!(
2281 target: LOG_TARGET,
2282 "Extrinsic failed at block({:?}): {:?}",
2283 Self::block_number(),
2284 err,
2285 );
2286 Event::ExtrinsicFailed {
2287 dispatch_error: err.error,
2288 dispatch_info: dispatch_event_info,
2289 }
2290 },
2291 });
2292
2293 log::trace!(
2294 target: LOG_TARGET,
2295 "Used block weight: {:?}",
2296 BlockWeight::<T>::get(),
2297 );
2298
2299 log::trace!(
2300 target: LOG_TARGET,
2301 "Used block length: {:?}",
2302 Pallet::<T>::all_extrinsics_len(),
2303 );
2304
2305 let next_extrinsic_index = Self::extrinsic_index().unwrap_or_default() + 1u32;
2306
2307 storage::unhashed::put(well_known_keys::EXTRINSIC_INDEX, &next_extrinsic_index);
2308 ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(next_extrinsic_index));
2309 ExtrinsicWeightReclaimed::<T>::kill();
2310 }
2311
2312 pub fn note_finished_extrinsics() {
2315 let extrinsic_index: u32 =
2316 storage::unhashed::take(well_known_keys::EXTRINSIC_INDEX).unwrap_or_default();
2317 ExtrinsicCount::<T>::put(extrinsic_index);
2318 ExecutionPhase::<T>::put(Phase::Finalization);
2319 }
2320
2321 pub fn note_finished_initialize() {
2324 ExecutionPhase::<T>::put(Phase::ApplyExtrinsic(0))
2325 }
2326
2327 pub fn on_created_account(who: T::AccountId, _a: &mut AccountInfo<T::Nonce, T::AccountData>) {
2329 T::OnNewAccount::on_new_account(&who);
2330 Self::deposit_event(Event::NewAccount { account: who });
2331 }
2332
2333 fn on_killed_account(who: T::AccountId) {
2335 T::OnKilledAccount::on_killed_account(&who);
2336 Self::deposit_event(Event::KilledAccount { account: who });
2337 }
2338
2339 pub fn can_set_code(code: &[u8], check_version: bool) -> CanSetCodeResult<T> {
2343 if T::MultiBlockMigrator::ongoing() {
2344 return CanSetCodeResult::MultiBlockMigrationsOngoing
2345 }
2346
2347 if check_version {
2348 let current_version = T::Version::get();
2349 let Some(new_version) = sp_io::misc::runtime_version(code)
2350 .and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok())
2351 else {
2352 return CanSetCodeResult::InvalidVersion(Error::<T>::FailedToExtractRuntimeVersion)
2353 };
2354
2355 cfg_if::cfg_if! {
2356 if #[cfg(all(feature = "runtime-benchmarks", not(test)))] {
2357 core::hint::black_box((new_version, current_version));
2359 } else {
2360 if new_version.spec_name != current_version.spec_name {
2361 return CanSetCodeResult::InvalidVersion(Error::<T>::InvalidSpecName)
2362 }
2363
2364 if new_version.spec_version <= current_version.spec_version {
2365 return CanSetCodeResult::InvalidVersion(Error::<T>::SpecVersionNeedsToIncrease)
2366 }
2367 }
2368 }
2369 }
2370
2371 CanSetCodeResult::Ok
2372 }
2373
2374 pub fn do_authorize_upgrade(code_hash: T::Hash, check_version: bool) {
2376 AuthorizedUpgrade::<T>::put(CodeUpgradeAuthorization { code_hash, check_version });
2377 Self::deposit_event(Event::UpgradeAuthorized { code_hash, check_version });
2378 }
2379
2380 fn validate_code_is_authorized(
2384 code: &[u8],
2385 ) -> Result<CodeUpgradeAuthorization<T>, DispatchError> {
2386 let authorization = AuthorizedUpgrade::<T>::get().ok_or(Error::<T>::NothingAuthorized)?;
2387 let actual_hash = T::Hashing::hash(code);
2388 ensure!(actual_hash == authorization.code_hash, Error::<T>::Unauthorized);
2389 Ok(authorization)
2390 }
2391
2392 pub fn reclaim_weight(
2397 info: &DispatchInfoOf<T::RuntimeCall>,
2398 post_info: &PostDispatchInfoOf<T::RuntimeCall>,
2399 ) -> Result<(), TransactionValidityError>
2400 where
2401 T::RuntimeCall: Dispatchable<Info = DispatchInfo, PostInfo = PostDispatchInfo>,
2402 {
2403 let already_reclaimed = crate::ExtrinsicWeightReclaimed::<T>::get();
2404 let unspent = post_info.calc_unspent(info);
2405 let accurate_reclaim = already_reclaimed.max(unspent);
2406 let to_reclaim_more = accurate_reclaim.saturating_sub(already_reclaimed);
2408 if to_reclaim_more != Weight::zero() {
2409 crate::BlockWeight::<T>::mutate(|current_weight| {
2410 current_weight.reduce(to_reclaim_more, info.class);
2411 });
2412 crate::ExtrinsicWeightReclaimed::<T>::put(accurate_reclaim);
2413 }
2414
2415 Ok(())
2416 }
2417
2418 pub fn remaining_block_weight() -> WeightMeter {
2420 let limit = T::BlockWeights::get().max_block;
2421 let consumed = BlockWeight::<T>::get().total();
2422
2423 WeightMeter::with_consumed_and_limit(consumed, limit)
2424 }
2425}
2426
2427pub fn unique(entropy: impl Encode) -> [u8; 32] {
2430 let mut last = [0u8; 32];
2431 sp_io::storage::read(well_known_keys::INTRABLOCK_ENTROPY, &mut last[..], 0);
2432 let next = (b"frame_system::unique", entropy, last).using_encoded(blake2_256);
2433 sp_io::storage::set(well_known_keys::INTRABLOCK_ENTROPY, &next);
2434 next
2435}
2436
2437pub struct Provider<T>(PhantomData<T>);
2439impl<T: Config> HandleLifetime<T::AccountId> for Provider<T> {
2440 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2441 Pallet::<T>::inc_providers(t);
2442 Ok(())
2443 }
2444 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2445 Pallet::<T>::dec_providers(t).map(|_| ())
2446 }
2447}
2448
2449pub struct SelfSufficient<T>(PhantomData<T>);
2451impl<T: Config> HandleLifetime<T::AccountId> for SelfSufficient<T> {
2452 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2453 Pallet::<T>::inc_sufficients(t);
2454 Ok(())
2455 }
2456 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2457 Pallet::<T>::dec_sufficients(t);
2458 Ok(())
2459 }
2460}
2461
2462pub struct Consumer<T>(PhantomData<T>);
2464impl<T: Config> HandleLifetime<T::AccountId> for Consumer<T> {
2465 fn created(t: &T::AccountId) -> Result<(), DispatchError> {
2466 Pallet::<T>::inc_consumers(t)
2467 }
2468 fn killed(t: &T::AccountId) -> Result<(), DispatchError> {
2469 Pallet::<T>::dec_consumers(t);
2470 Ok(())
2471 }
2472}
2473
2474impl<T: Config> BlockNumberProvider for Pallet<T> {
2475 type BlockNumber = BlockNumberFor<T>;
2476
2477 fn current_block_number() -> Self::BlockNumber {
2478 Pallet::<T>::block_number()
2479 }
2480
2481 #[cfg(feature = "runtime-benchmarks")]
2482 fn set_block_number(n: BlockNumberFor<T>) {
2483 Self::set_block_number(n)
2484 }
2485}
2486
2487impl<T: Config> StoredMap<T::AccountId, T::AccountData> for Pallet<T> {
2493 fn get(k: &T::AccountId) -> T::AccountData {
2494 Account::<T>::get(k).data
2495 }
2496
2497 fn try_mutate_exists<R, E: From<DispatchError>>(
2498 k: &T::AccountId,
2499 f: impl FnOnce(&mut Option<T::AccountData>) -> Result<R, E>,
2500 ) -> Result<R, E> {
2501 let account = Account::<T>::get(k);
2502 let is_default = account.data == T::AccountData::default();
2503 let mut some_data = if is_default { None } else { Some(account.data) };
2504 let result = f(&mut some_data)?;
2505 if Self::providers(k) > 0 || Self::sufficients(k) > 0 {
2506 Account::<T>::mutate(k, |a| a.data = some_data.unwrap_or_default());
2507 } else {
2508 Account::<T>::remove(k)
2509 }
2510 Ok(result)
2511 }
2512}
2513
2514pub fn split_inner<T, R, S>(
2516 option: Option<T>,
2517 splitter: impl FnOnce(T) -> (R, S),
2518) -> (Option<R>, Option<S>) {
2519 match option {
2520 Some(inner) => {
2521 let (r, s) = splitter(inner);
2522 (Some(r), Some(s))
2523 },
2524 None => (None, None),
2525 }
2526}
2527
2528pub struct ChainContext<T>(PhantomData<T>);
2529impl<T> Default for ChainContext<T> {
2530 fn default() -> Self {
2531 ChainContext(PhantomData)
2532 }
2533}
2534
2535impl<T: Config> Lookup for ChainContext<T> {
2536 type Source = <T::Lookup as StaticLookup>::Source;
2537 type Target = <T::Lookup as StaticLookup>::Target;
2538
2539 fn lookup(&self, s: Self::Source) -> Result<Self::Target, LookupError> {
2540 <T::Lookup as StaticLookup>::lookup(s)
2541 }
2542}
2543
2544#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2546pub struct RunToBlockHooks<'a, T>
2547where
2548 T: 'a + Config,
2549{
2550 before_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2551 after_initialize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2552 before_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2553 after_finalize: Box<dyn 'a + FnMut(BlockNumberFor<T>)>,
2554}
2555
2556#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2557impl<'a, T> RunToBlockHooks<'a, T>
2558where
2559 T: 'a + Config,
2560{
2561 pub fn before_initialize<F>(mut self, f: F) -> Self
2563 where
2564 F: 'a + FnMut(BlockNumberFor<T>),
2565 {
2566 self.before_initialize = Box::new(f);
2567 self
2568 }
2569 pub fn after_initialize<F>(mut self, f: F) -> Self
2571 where
2572 F: 'a + FnMut(BlockNumberFor<T>),
2573 {
2574 self.after_initialize = Box::new(f);
2575 self
2576 }
2577 pub fn before_finalize<F>(mut self, f: F) -> Self
2579 where
2580 F: 'a + FnMut(BlockNumberFor<T>),
2581 {
2582 self.before_finalize = Box::new(f);
2583 self
2584 }
2585 pub fn after_finalize<F>(mut self, f: F) -> Self
2587 where
2588 F: 'a + FnMut(BlockNumberFor<T>),
2589 {
2590 self.after_finalize = Box::new(f);
2591 self
2592 }
2593}
2594
2595#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
2596impl<'a, T> Default for RunToBlockHooks<'a, T>
2597where
2598 T: Config,
2599{
2600 fn default() -> Self {
2601 Self {
2602 before_initialize: Box::new(|_| {}),
2603 after_initialize: Box::new(|_| {}),
2604 before_finalize: Box::new(|_| {}),
2605 after_finalize: Box::new(|_| {}),
2606 }
2607 }
2608}
2609
2610pub mod pallet_prelude {
2612 pub use crate::{
2613 ensure_authorized, ensure_none, ensure_root, ensure_signed, ensure_signed_or_root,
2614 };
2615
2616 pub type OriginFor<T> = <T as crate::Config>::RuntimeOrigin;
2618
2619 pub type HeaderFor<T> =
2621 <<T as crate::Config>::Block as sp_runtime::traits::HeaderProvider>::HeaderT;
2622
2623 pub type BlockNumberFor<T> = <HeaderFor<T> as sp_runtime::traits::Header>::Number;
2625
2626 pub type ExtrinsicFor<T> =
2628 <<T as crate::Config>::Block as sp_runtime::traits::Block>::Extrinsic;
2629
2630 pub type RuntimeCallFor<T> = <T as crate::Config>::RuntimeCall;
2632
2633 pub type AccountIdFor<T> = <T as crate::Config>::AccountId;
2635}