1use super::*;
19use frame_support::traits::OnRuntimeUpgrade;
20use log;
21
22#[cfg(feature = "try-runtime")]
23use sp_runtime::TryRuntimeError;
24
25pub mod v1 {
26 use frame_support::{pallet_prelude::*, weights::Weight};
27
28 use super::*;
29
30 #[derive(Decode)]
31 pub struct OldCollectionDetails<AccountId, DepositBalance> {
32 pub owner: AccountId,
33 pub owner_deposit: DepositBalance,
34 pub items: u32,
35 pub item_metadatas: u32,
36 pub attributes: u32,
37 }
38
39 impl<AccountId, DepositBalance> OldCollectionDetails<AccountId, DepositBalance> {
40 fn migrate_to_v1(self, item_configs: u32) -> CollectionDetails<AccountId, DepositBalance> {
42 CollectionDetails {
43 owner: self.owner,
44 owner_deposit: self.owner_deposit,
45 items: self.items,
46 item_metadatas: self.item_metadatas,
47 item_configs,
48 attributes: self.attributes,
49 }
50 }
51 }
52
53 pub struct MigrateToV1<T>(core::marker::PhantomData<T>);
55 impl<T: Config> OnRuntimeUpgrade for MigrateToV1<T> {
56 fn on_runtime_upgrade() -> Weight {
57 let in_code_version = Pallet::<T>::in_code_storage_version();
58 let on_chain_version = Pallet::<T>::on_chain_storage_version();
59
60 log::info!(
61 target: LOG_TARGET,
62 "Running migration with in-code storage version {:?} / onchain {:?}",
63 in_code_version,
64 on_chain_version
65 );
66
67 if on_chain_version == 0 && in_code_version == 1 {
68 let mut translated = 0u64;
69 let mut configs_iterated = 0u64;
70 Collection::<T>::translate::<
71 OldCollectionDetails<T::AccountId, DepositBalanceOf<T>>,
72 _,
73 >(|key, old_value| {
74 let item_configs = ItemConfigOf::<T>::iter_prefix(&key).count() as u32;
75 configs_iterated += item_configs as u64;
76 translated.saturating_inc();
77 Some(old_value.migrate_to_v1(item_configs))
78 });
79
80 in_code_version.put::<Pallet<T>>();
81
82 log::info!(
83 target: LOG_TARGET,
84 "Upgraded {} records, storage to version {:?}",
85 translated,
86 in_code_version
87 );
88 T::DbWeight::get().reads_writes(translated + configs_iterated + 1, translated + 1)
89 } else {
90 log::info!(
91 target: LOG_TARGET,
92 "Migration did not execute. This probably should be removed"
93 );
94 T::DbWeight::get().reads(1)
95 }
96 }
97
98 #[cfg(feature = "try-runtime")]
99 fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> {
100 let prev_count = Collection::<T>::iter().count();
101 Ok((prev_count as u32).encode())
102 }
103
104 #[cfg(feature = "try-runtime")]
105 fn post_upgrade(prev_count: Vec<u8>) -> Result<(), TryRuntimeError> {
106 let prev_count: u32 = Decode::decode(&mut prev_count.as_slice()).expect(
107 "the state parameter should be something that was generated by pre_upgrade",
108 );
109 let post_count = Collection::<T>::iter().count() as u32;
110 ensure!(
111 prev_count == post_count,
112 "the records count before and after the migration should be the same"
113 );
114
115 ensure!(Pallet::<T>::on_chain_storage_version() >= 1, "wrong storage version");
116
117 Ok(())
118 }
119 }
120}