pallet_sidechain/migrations/
v1.rs

1//! Storage migration of `pallet-sidechain` from storage version 0 to 1, removing dependence on slots
2//!
3//! This version change obsoletes the [SlotsPerEpoch] storage which is now deprecated
4//! and will be removed in the future, and introduces a new storage [EpochDurationMillis]
5//! to replace it.
6
7/// Storage migration for chains using the slot-based legacy version of the pallet.
8///
9/// This migration sets the value in [EpochDurationMillis] based on the contents
10/// of [SlotsPerEpoch] and slot duration.
11pub type LegacyToV1Migration<T, const SLOT_DURATION_MILLIS: u64> =
12	frame_support::migrations::VersionedMigration<
13		0, // The migration will only execute when the on-chain storage version is 0
14		1, // The on-chain storage version will be set to 1 after the migration is complete
15		_impl::InnerMigrateV0ToV1<T, SLOT_DURATION_MILLIS>,
16		crate::pallet::Pallet<T>,
17		<T as frame_system::Config>::DbWeight,
18	>;
19
20/// Private module to void leaking
21#[allow(deprecated)]
22mod _impl {
23	#[cfg(feature = "try-runtime")]
24	extern crate alloc;
25
26	use frame_support::traits::Get;
27	use frame_support::traits::UncheckedOnRuntimeUpgrade;
28	use sidechain_domain::ScEpochDuration;
29
30	/// Helper type used internally by [LegacyToV1Migration]
31	pub struct InnerMigrateV0ToV1<T: crate::Config, const SLOT_DURATION_MILLIS: u64>(
32		core::marker::PhantomData<T>,
33	);
34
35	impl<T: crate::pallet::Config, const SLOT_DURATION_MILLIS: u64> UncheckedOnRuntimeUpgrade
36		for InnerMigrateV0ToV1<T, SLOT_DURATION_MILLIS>
37	{
38		fn on_runtime_upgrade() -> sp_runtime::Weight {
39			let slots_per_epoch = crate::SlotsPerEpoch::<T>::get();
40			let epoch_duration_millis =
41				ScEpochDuration::from_millis(slots_per_epoch as u64 * SLOT_DURATION_MILLIS);
42			crate::EpochDurationMillis::<T>::put(epoch_duration_millis);
43
44			log::info!(
45				"⬆️ Migrated pallet-sidechain to version 1, with epoch duration of {epoch_duration_millis:?} ms = {slots_per_epoch} slots × {SLOT_DURATION_MILLIS} ms"
46			);
47
48			T::DbWeight::get().reads_writes(1, 1)
49		}
50
51		#[cfg(feature = "try-runtime")]
52		fn pre_upgrade() -> Result<alloc::vec::Vec<u8>, sp_runtime::TryRuntimeError> {
53			let slots_per_epoch = crate::SlotsPerEpoch::<T>::get();
54
55			Ok(slots_per_epoch.to_be_bytes().to_vec())
56		}
57
58		#[cfg(feature = "try-runtime")]
59		fn post_upgrade(state: alloc::vec::Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
60			let slots_per_epoch = u32::from_be_bytes(state.try_into().unwrap());
61
62			let epoch_duration_millis = crate::EpochDurationMillis::<T>::get();
63
64			frame_support::ensure!(
65				slots_per_epoch as u64 * SLOT_DURATION_MILLIS == epoch_duration_millis.millis(),
66				sp_runtime::TryRuntimeError::Corruption
67			);
68
69			Ok(())
70		}
71	}
72}