substrate_test_runtime/
inherent_upgrade_pallet.rs1pub use pallet::*;
25
26#[frame_support::pallet(dev_mode)]
27pub mod pallet {
28 use frame_support::{
29 inherent::{InherentData, InherentIdentifier, ProvideInherent},
30 pallet_prelude::*,
31 };
32 use frame_system::pallet_prelude::*;
33
34 pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"upgrade0";
39
40 #[pallet::pallet]
41 pub struct Pallet<T>(_);
42
43 #[pallet::config]
44 pub trait Config: frame_system::Config {}
45
46 #[pallet::storage]
48 pub type Migrated<T: Config> = StorageValue<_, bool, ValueQuery>;
49
50 #[pallet::hooks]
51 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
52 fn on_runtime_upgrade() -> Weight {
53 Migrated::<T>::put(true);
54 T::DbWeight::get().writes(1)
55 }
56 }
57
58 #[pallet::call]
59 impl<T: Config> Pallet<T> {
60 #[pallet::weight((0, DispatchClass::Mandatory))]
61 pub fn inherent(origin: OriginFor<T>) -> DispatchResult {
62 ensure_none(origin)?;
63 Ok(())
64 }
65 }
66
67 #[pallet::inherent]
68 impl<T: Config> ProvideInherent for Pallet<T> {
69 type Call = Call<T>;
70 type Error = sp_inherents::MakeFatalError<()>;
71 const INHERENT_IDENTIFIER: InherentIdentifier = INHERENT_IDENTIFIER;
72
73 fn create_inherent(data: &InherentData) -> Option<Self::Call> {
74 data.get_data::<bool>(&INHERENT_IDENTIFIER)
75 .ok()
76 .flatten()
77 .map(|_| Call::inherent {})
78 }
79
80 fn check_inherent(_: &Self::Call, data: &InherentData) -> Result<(), Self::Error> {
81 let requires_migration =
82 data.get_data::<bool>(&INHERENT_IDENTIFIER).ok().flatten().unwrap_or(false);
83
84 if requires_migration && !Migrated::<T>::get() {
85 Err(().into())
86 } else {
87 Ok(())
88 }
89 }
90
91 fn is_inherent(call: &Self::Call) -> bool {
92 matches!(call, Call::inherent {})
93 }
94 }
95}