referrerpolicy=no-referrer-when-downgrade

pallet_election_provider_multi_phase/
migrations.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18pub mod v1 {
19	use alloc::collections::btree_map::BTreeMap;
20	use frame_support::{
21		storage::unhashed,
22		traits::{Defensive, GetStorageVersion, OnRuntimeUpgrade},
23		BoundedVec,
24	};
25
26	use crate::*;
27	pub struct MigrateToV1<T>(core::marker::PhantomData<T>);
28	impl<T: Config> OnRuntimeUpgrade for MigrateToV1<T> {
29		fn on_runtime_upgrade() -> Weight {
30			let current = Pallet::<T>::in_code_storage_version();
31			let onchain = Pallet::<T>::on_chain_storage_version();
32
33			log!(
34				info,
35				"Running migration with in-code storage version {:?} / onchain {:?}",
36				current,
37				onchain
38			);
39
40			if current == 1 && onchain == 0 {
41				if SignedSubmissionIndices::<T>::exists() {
42					// This needs to be tested at a both a block height where this value exists, and
43					// when it doesn't.
44					let now = frame_system::Pallet::<T>::block_number();
45					let map = unhashed::get::<BTreeMap<ElectionScore, u32>>(
46						&SignedSubmissionIndices::<T>::hashed_key(),
47					)
48					.defensive_unwrap_or_default();
49					let vector = map
50						.into_iter()
51						.map(|(score, index)| (score, now, index))
52						.collect::<Vec<_>>();
53
54					log!(
55						debug,
56						"{:?} SignedSubmissionIndices read from storage (max: {:?})",
57						vector.len(),
58						T::SignedMaxSubmissions::get()
59					);
60
61					// defensive-only, assuming a constant `SignedMaxSubmissions`.
62					let bounded = BoundedVec::<_, _>::truncate_from(vector);
63					SignedSubmissionIndices::<T>::put(bounded);
64
65					log!(info, "SignedSubmissionIndices existed and got migrated");
66				} else {
67					log!(info, "SignedSubmissionIndices did NOT exist.");
68				}
69
70				current.put::<Pallet<T>>();
71				T::DbWeight::get().reads_writes(2, 1)
72			} else {
73				log!(info, "Migration did not execute. This probably should be removed");
74				T::DbWeight::get().reads(1)
75			}
76		}
77	}
78}