frame-system: Add last_runtime_upgrade_spec_version (#2351)

Adds a function for querying the last runtime upgrade spec version. This
can be useful for when writing runtime level migrations to ensure that
they are not executed multiple times. An example would be a session key
migration.

---------

Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Oliver Tale-Yazdi <oliver.tale-yazdi@parity.io>
This commit is contained in:
Bastian Köcher
2023-11-15 23:54:08 +01:00
committed by GitHub
parent f4bb17cc86
commit ea4085ab74
5 changed files with 71 additions and 27 deletions
+19
View File
@@ -1094,6 +1094,25 @@ pub enum DecRefStatus {
}
impl<T: Config> Pallet<T> {
/// Returns the `spec_version` of the last runtime upgrade.
///
/// This function is useful for writing guarded runtime migrations in the runtime. A runtime
/// migration can use the `spec_version` to ensure that it isn't applied twice. This works
/// similar as the storage version for pallets.
///
/// This functions returns the `spec_version` of the last runtime upgrade while executing the
/// runtime migrations
/// [`on_runtime_upgrade`](frame_support::traits::OnRuntimeUpgrade::on_runtime_upgrade)
/// function. After all migrations are executed, this will return the `spec_version` of the
/// current runtime until there is another runtime upgrade.
///
/// Example:
#[doc = docify::embed!("src/tests.rs", last_runtime_upgrade_spec_version_usage)]
pub fn last_runtime_upgrade_spec_version() -> u32 {
LastRuntimeUpgrade::<T>::get().map_or(0, |l| l.spec_version.0)
}
/// Returns true if the given account exists.
pub fn account_exists(who: &T::AccountId) -> bool {
Account::<T>::contains_key(who)
}
+24 -1
View File
@@ -19,7 +19,7 @@ use crate::*;
use frame_support::{
assert_noop, assert_ok,
dispatch::{Pays, PostDispatchInfo, WithPostDispatchInfo},
traits::WhitelistedStorageKeys,
traits::{OnRuntimeUpgrade, WhitelistedStorageKeys},
};
use std::collections::BTreeSet;
@@ -773,3 +773,26 @@ pub fn from_actual_ref_time(ref_time: Option<u64>) -> PostDispatchInfo {
pub fn from_post_weight_info(ref_time: Option<u64>, pays_fee: Pays) -> PostDispatchInfo {
PostDispatchInfo { actual_weight: ref_time.map(|t| Weight::from_all(t)), pays_fee }
}
#[docify::export]
#[test]
fn last_runtime_upgrade_spec_version_usage() {
struct Migration;
impl OnRuntimeUpgrade for Migration {
fn on_runtime_upgrade() -> Weight {
// Ensure to compare the spec version against some static version to prevent applying
// the same migration multiple times.
//
// `1337` here is the spec version of the runtime running on chain. If there is maybe
// a runtime upgrade in the pipeline of being applied, you should use the spec version
// of this upgrade.
if System::last_runtime_upgrade_spec_version() > 1337 {
return Weight::zero();
}
// Do the migration.
Weight::zero()
}
}
}