referrerpolicy=no-referrer-when-downgrade

pallet_example_single_block_migrations/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: MIT-0
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy of
7// this software and associated documentation files (the "Software"), to deal in
8// the Software without restriction, including without limitation the rights to
9// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
10// of the Software, and to permit persons to whom the Software is furnished to do
11// so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in all
14// copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22// SOFTWARE.
23
24//! # Single Block Migration Example Pallet
25//!
26//! An example pallet demonstrating best-practices for writing single-block migrations in the
27//! context of upgrading pallet storage.
28//!
29//! ## Forewarning
30//!
31//! Single block migrations **MUST** execute in a single block, therefore when executed on a
32//! parachain are only appropriate when guaranteed to not exceed block weight limits. If a
33//! parachain submits a block that exceeds the block weight limit it will **brick the chain**!
34//!
35//! If weight is a concern or you are not sure which type of migration to use, you should probably
36//! use a multi-block migration.
37//!
38//! TODO: Link above to multi-block migration example.
39//!
40//! ## Pallet Overview
41//!
42//! This example pallet contains a single storage item [`Value`](pallet::Value), which may be set by
43//! any signed origin by calling the [`set_value`](crate::Call::set_value) extrinsic.
44//!
45//! For the purposes of this exercise, we imagine that in [`StorageVersion`] V0 of this pallet
46//! [`Value`](pallet::Value) is a `u32`, and this what is currently stored on-chain.
47//!
48//! ```ignore
49//! // (Old) Storage Version V0 representation of `Value`
50//! #[pallet::storage]
51//! pub type Value<T: Config> = StorageValue<_, u32>;
52//! ```
53//!
54//! In [`StorageVersion`] V1 of the pallet a new struct [`CurrentAndPreviousValue`] is introduced:
55#![doc = docify::embed!("src/lib.rs", CurrentAndPreviousValue)]
56//! and [`Value`](pallet::Value) is updated to store this new struct instead of a `u32`:
57#![doc = docify::embed!("src/lib.rs", Value)]
58//!
59//! In StorageVersion V1 of the pallet when [`set_value`](crate::Call::set_value) is called, the
60//! new value is stored in the `current` field of [`CurrentAndPreviousValue`], and the previous
61//! value (if it exists) is stored in the `previous` field.
62#![doc = docify::embed!("src/lib.rs", pallet_calls)]
63//!
64//! ## Why a migration is necessary
65//!
66//! Without a migration, there will be a discrepancy between the on-chain storage for [`Value`] (in
67//! V0 it is a `u32`) and the current storage for [`Value`] (in V1 it was changed to a
68//! [`CurrentAndPreviousValue`] struct).
69//!
70//! The on-chain storage for [`Value`] would be a `u32` but the runtime would try to read it as a
71//! [`CurrentAndPreviousValue`]. This would result in unacceptable undefined behavior.
72//!
73//! ## Adding a migration module
74//!
75//! Writing a pallets migrations in a separate module is strongly recommended.
76//!
77//! Here's how the migration module is defined for this pallet:
78//!
79//! ```text
80//! substrate/frame/examples/single-block-migrations/src/
81//! ├── lib.rs       <-- pallet definition
82//! ├── Cargo.toml   <-- pallet manifest
83//! └── migrations/
84//!    ├── mod.rs    <-- migrations module definition
85//!    └── v1.rs     <-- migration logic for the V0 to V1 transition
86//! ```
87//!
88//! This structure allows keeping migration logic separate from the pallet logic and
89//! easily adding new migrations in the future.
90//!
91//! ## Writing the Migration
92//!
93//! All code related to the migration can be found under
94//! [`v1.rs`](migrations::v1).
95//!
96//! See the migration source code for detailed comments.
97//!
98//! Here's a brief overview of modules and types defined in `v1.rs`:
99//!
100//! ### `mod v0`
101//!
102//! Here we define a [`storage_alias`](frame_support::storage_alias) for the old v0 [`Value`]
103//! format.
104//!
105//! This allows reading the old v0 value from storage during the migration.
106//!
107//! ### `InnerMigrateV0ToV1`
108//!
109//! Here we define our raw migration logic,
110//! `InnerMigrateV0ToV1` which implements the [`UncheckedOnRuntimeUpgrade`] trait.
111//!
112//! #### Why [`UncheckedOnRuntimeUpgrade`]?
113//!
114//! Otherwise, we would have two implementations of [`OnRuntimeUpgrade`] which could be confusing,
115//! and may lead to accidentally using the wrong one.
116//!
117//! #### Standalone Struct or Pallet Hook?
118//!
119//! Note that the storage migration logic is attached to a standalone struct implementing
120//! [`UncheckedOnRuntimeUpgrade`], rather than implementing the
121//! [`Hooks::on_runtime_upgrade`](frame_support::traits::Hooks::on_runtime_upgrade) hook directly on
122//! the pallet. The pallet hook is better suited for special types of logic that need to execute on
123//! every runtime upgrade, but not so much for one-off storage migrations.
124//!
125//! ### `MigrateV0ToV1`
126//!
127//! Here, `InnerMigrateV0ToV1` is wrapped in a
128//! [`VersionedMigration`] to define
129//! [`MigrateV0ToV1`](crate::migrations::v1::MigrateV0ToV1), which may be used
130//! in runtimes.
131//!
132//! Using [`VersionedMigration`] ensures that
133//! - The migration only runs once when the on-chain storage version is `0`
134//! - The on-chain storage version is updated to `1` after the migration executes
135//! - Reads and writes from checking and setting the on-chain storage version are accounted for in
136//!   the final [`Weight`](frame_support::weights::Weight)
137//!
138//! ### `mod test`
139//!
140//! Here basic unit tests are defined for the migration.
141//!
142//! When writing migration tests, don't forget to check:
143//! - `on_runtime_upgrade` returns the expected weight
144//! - `post_upgrade` succeeds when given the bytes returned by `pre_upgrade`
145//! - Pallet storage is in the expected state after the migration
146//!
147//! [`VersionedMigration`]: frame_support::migrations::VersionedMigration
148//! [`GetStorageVersion`]: frame_support::traits::GetStorageVersion
149//! [`OnRuntimeUpgrade`]: frame_support::traits::OnRuntimeUpgrade
150//! [`UncheckedOnRuntimeUpgrade`]: frame_support::traits::UncheckedOnRuntimeUpgrade
151//! [`MigrateV0ToV1`]: crate::migrations::v1::MigrateV0ToV1
152
153// We make sure this pallet uses `no_std` for compiling to Wasm.
154#![cfg_attr(not(feature = "std"), no_std)]
155// allow non-camel-case names for storage version V0 value
156#![allow(non_camel_case_types)]
157
158// Re-export pallet items so that they can be accessed from the crate namespace.
159pub use pallet::*;
160
161// Export migrations so they may be used in the runtime.
162pub mod migrations;
163#[doc(hidden)]
164mod mock;
165
166extern crate alloc;
167
168use codec::{Decode, Encode, MaxEncodedLen};
169use frame_support::traits::StorageVersion;
170use sp_runtime::RuntimeDebug;
171
172/// Example struct holding the most recently set [`u32`] and the
173/// second most recently set [`u32`] (if one existed).
174#[docify::export]
175#[derive(
176	Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, scale_info::TypeInfo, MaxEncodedLen,
177)]
178pub struct CurrentAndPreviousValue {
179	/// The most recently set value.
180	pub current: u32,
181	/// The previous value, if one existed.
182	pub previous: Option<u32>,
183}
184
185// Pallet for demonstrating storage migrations.
186#[frame_support::pallet(dev_mode)]
187pub mod pallet {
188	use super::*;
189	use frame_support::pallet_prelude::*;
190	use frame_system::pallet_prelude::*;
191
192	/// Define the current [`StorageVersion`] of the pallet.
193	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
194
195	#[pallet::pallet]
196	#[pallet::storage_version(STORAGE_VERSION)]
197	pub struct Pallet<T>(_);
198
199	#[pallet::config]
200	pub trait Config: frame_system::Config {}
201
202	/// [`StorageVersion`] V1 of [`Value`].
203	///
204	/// Currently used.
205	#[docify::export]
206	#[pallet::storage]
207	pub type Value<T: Config> = StorageValue<_, CurrentAndPreviousValue>;
208
209	#[docify::export(pallet_calls)]
210	#[pallet::call]
211	impl<T: Config> Pallet<T> {
212		pub fn set_value(origin: OriginFor<T>, value: u32) -> DispatchResult {
213			ensure_signed(origin)?;
214
215			let previous = Value::<T>::get().map(|v| v.current);
216			let new_struct = CurrentAndPreviousValue { current: value, previous };
217			<Value<T>>::put(new_struct);
218
219			Ok(())
220		}
221	}
222}