migration.rs 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Clippy linter warning
  2. #![allow(clippy::redundant_closure_call)] // disable it because of the substrate lib design
  3. use crate::VERSION;
  4. use rstd::prelude::*;
  5. // use sr_primitives::{print, traits::Zero};
  6. use srml_support::{debug, decl_event, decl_module, decl_storage};
  7. impl<T: Trait> Module<T> {
  8. /// This method is called from on_initialize() when a runtime upgrade is detected. This
  9. /// happens when the runtime spec version is found to be higher than the stored value.
  10. /// Important to note this method should be carefully maintained, because it runs on every runtime
  11. /// upgrade.
  12. fn runtime_upgraded() {
  13. debug::print!("Running runtime upgraded handler");
  14. // Add initialization of modules introduced in new runtime release. Typically this
  15. // would be any new storage values that need an initial value which would not
  16. // have been initialized with config() or build() chainspec construction mechanism.
  17. // Other tasks like resetting values, migrating values etc.
  18. }
  19. }
  20. pub trait Trait: system::Trait {
  21. type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
  22. }
  23. decl_storage! {
  24. trait Store for Module<T: Trait> as Migration {
  25. /// Records at what runtime spec version the store was initialized. At genesis this will be
  26. /// initialized to Some(VERSION.spec_version). It is an Option because the first time the module
  27. /// was introduced was as a runtime upgrade and type was never changed.
  28. /// When the runtime is upgraded the spec version be updated.
  29. pub SpecVersion get(spec_version) build(|_config: &GenesisConfig| {
  30. VERSION.spec_version
  31. }) : Option<u32>;
  32. }
  33. }
  34. decl_event! {
  35. pub enum Event<T> where <T as system::Trait>::BlockNumber {
  36. Migrated(BlockNumber, u32),
  37. }
  38. }
  39. decl_module! {
  40. pub struct Module<T: Trait> for enum Call where origin: T::Origin {
  41. fn deposit_event() = default;
  42. fn on_initialize(_now: T::BlockNumber) {
  43. if Self::spec_version().map_or(true, |spec_version| VERSION.spec_version > spec_version) {
  44. // Mark store version with current version of the runtime
  45. SpecVersion::put(VERSION.spec_version);
  46. // Run migrations and store initializers
  47. Self::runtime_upgraded();
  48. Self::deposit_event(RawEvent::Migrated(
  49. <system::Module<T>>::block_number(),
  50. VERSION.spec_version,
  51. ));
  52. }
  53. }
  54. }
  55. }