use super::*;
use frame_support::{
migrations::VersionedMigration, pallet_prelude::*, traits::UncheckedOnRuntimeUpgrade,
};
#[cfg(feature = "try-runtime")]
use codec::{Decode, Encode};
#[cfg(feature = "try-runtime")]
use sp_runtime::TryRuntimeError;
pub mod versioned {
use super::*;
pub type V0ToV1<T, const KL: u64> = VersionedMigration<
0,
1,
v1::VersionUncheckedMigrateV0ToV1<T, KL>,
crate::pallet::Pallet<T>,
<T as frame_system::Config>::DbWeight,
>;
}
pub mod v1 {
use super::*;
const TARGET: &'static str = "runtime::identity::migration::v1";
mod v0 {
use super::*;
use frame_support::storage_alias;
#[storage_alias]
pub type IdentityOf<T: Config> = StorageMap<
Pallet<T>,
Twox64Concat,
<T as frame_system::Config>::AccountId,
Registration<
BalanceOf<T>,
<T as pallet::Config>::MaxRegistrars,
<T as pallet::Config>::IdentityInformation,
>,
OptionQuery,
>;
}
pub struct VersionUncheckedMigrateV0ToV1<T, const KL: u64>(PhantomData<T>);
impl<T: Config, const KL: u64> UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV0ToV1<T, KL> {
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
let identities = v0::IdentityOf::<T>::iter().count();
log::info!(
target: TARGET,
"pre-upgrade state contains '{}' identities.",
identities
);
ensure!((identities as u64) < KL, "too many identities to migrate");
Ok((identities as u64).encode())
}
fn on_runtime_upgrade() -> Weight {
log::info!(
target: TARGET,
"running storage migration from version 0 to version 1."
);
let mut weight = T::DbWeight::get().reads(1);
let mut translated: u64 = 0;
let mut interrupted = false;
for (account, registration) in v0::IdentityOf::<T>::iter() {
IdentityOf::<T>::insert(account, (registration, None::<Username<T>>));
translated.saturating_inc();
if translated >= KL {
log::warn!(
"Incomplete! Migration limit reached. Only {} identities migrated.",
translated
);
interrupted = true;
break
}
}
if !interrupted {
log::info!("all {} identities migrated", translated);
}
weight.saturating_accrue(T::DbWeight::get().reads_writes(translated, translated));
weight.saturating_accrue(T::DbWeight::get().writes(1));
weight
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(state: Vec<u8>) -> Result<(), TryRuntimeError> {
let identities_to_migrate: u64 = Decode::decode(&mut &state[..])
.expect("failed to decode the state from pre-upgrade.");
let identities = IdentityOf::<T>::iter().count() as u64;
log::info!("post-upgrade expects '{}' identities to have been migrated.", identities);
ensure!(identities_to_migrate == identities, "must migrate all identities.");
log::info!(target: TARGET, "migrated all identities.");
Ok(())
}
}
}