1
// Copyright (C) Moondance Labs Ltd.
2
// This file is part of Tanssi.
3

            
4
// Tanssi is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Tanssi is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
16
// Copyright (C) Moondance Labs Ltd.
17
// This file is part of Tanssi.
18

            
19
// Tanssi is free software: you can redistribute it and/or modify
20
// it under the terms of the GNU General Public License as published by
21
// the Free Software Foundation, either version 3 of the License, or
22
// (at your option) any later version.
23

            
24
// Tanssi is distributed in the hope that it will be useful,
25
// but WITHOUT ANY WARRANTY; without even the implied warranty of
26
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27
// GNU General Public License for more details.
28

            
29
// You should have received a copy of the GNU General Public License
30
// along with Tanssi.  If not, see <http://www.gnu.org/licenses/>
31

            
32
//! # Migrations
33
//!
34
//! This module acts as a registry where each migration is defined. Each migration should implement
35
//! the "Migration" trait declared in the pallet-migrations crate.
36

            
37
extern crate alloc;
38

            
39
use {
40
    alloc::{boxed::Box, collections::btree_set::BTreeSet, vec, vec::Vec},
41
    core::marker::PhantomData,
42
    cumulus_primitives_core::ParaId,
43
    frame_support::{
44
        migration::{clear_storage_prefix, move_pallet, storage_key_iter},
45
        pallet_prelude::GetStorageVersion,
46
        parameter_types,
47
        traits::{
48
            fungible::MutateHold, OnRuntimeUpgrade, PalletInfoAccess, ReservableCurrency,
49
            StorageVersion,
50
        },
51
        weights::Weight,
52
        Blake2_128Concat, StoragePrefixedMap,
53
    },
54
    pallet_configuration::{weights::WeightInfo as _, HostConfiguration},
55
    pallet_foreign_asset_creator::{AssetId, AssetIdToForeignAsset, ForeignAssetToAssetId},
56
    pallet_migrations::{GetMigrations, Migration},
57
    pallet_registrar::HoldReason,
58
    sp_core::Get,
59
    sp_runtime::Perbill,
60
};
61

            
62
#[cfg(feature = "try-runtime")]
63
use {frame_support::ensure, parity_scale_codec::DecodeAll};
64

            
65
#[derive(
66
    Default,
67
    Clone,
68
    parity_scale_codec::Encode,
69
    parity_scale_codec::Decode,
70
    PartialEq,
71
    sp_core::RuntimeDebug,
72
    scale_info::TypeInfo,
73
)]
74
pub struct HostConfigurationV3 {
75
    pub max_collators: u32,
76
    pub min_orchestrator_collators: u32,
77
    pub max_orchestrator_collators: u32,
78
    pub collators_per_container: u32,
79
    pub full_rotation_period: u32,
80
    pub collators_per_parathread: u32,
81
    pub parathreads_per_collator: u32,
82
    pub target_container_chain_fullness: Perbill,
83
    pub max_parachain_cores_percentage: Option<Perbill>,
84
}
85

            
86
pub struct MigrateConfigurationAddFullRotationMode<T>(pub PhantomData<T>);
87
impl<T> Migration for MigrateConfigurationAddFullRotationMode<T>
88
where
89
    T: pallet_configuration::Config,
90
{
91
    fn friendly_name(&self) -> &str {
92
        "TM_MigrateConfigurationAddFullRotationMode"
93
    }
94

            
95
3
    fn migrate(&self, _available_weight: Weight) -> Weight {
96
3
        let default_config = HostConfiguration::default();
97

            
98
        // Modify active config
99
3
        let old_config: HostConfigurationV3 = frame_support::storage::unhashed::get(
100
3
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
101
        )
102
3
        .expect("configuration.activeConfig should have value");
103
3
        let new_config = HostConfiguration {
104
3
            max_collators: old_config.max_collators,
105
3
            min_orchestrator_collators: old_config.min_orchestrator_collators,
106
3
            max_orchestrator_collators: old_config.max_orchestrator_collators,
107
3
            collators_per_container: old_config.collators_per_container,
108
3
            full_rotation_period: old_config.full_rotation_period,
109
3
            collators_per_parathread: old_config.collators_per_parathread,
110
3
            parathreads_per_collator: old_config.parathreads_per_collator,
111
3
            target_container_chain_fullness: old_config.target_container_chain_fullness,
112
3
            max_parachain_cores_percentage: old_config.max_parachain_cores_percentage,
113
3
            full_rotation_mode: default_config.full_rotation_mode.clone(),
114
3
        };
115
3
        frame_support::storage::unhashed::put(
116
3
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
117
3
            &new_config,
118
        );
119

            
120
        // Modify pending configs, if any
121
3
        let old_pending_configs: Vec<(u32, HostConfigurationV3)> =
122
3
            frame_support::storage::unhashed::get(
123
3
                &pallet_configuration::PendingConfigs::<T>::hashed_key(),
124
            )
125
3
            .unwrap_or_default();
126
3
        let mut new_pending_configs: Vec<(u32, HostConfiguration)> = vec![];
127

            
128
9
        for (session_index, old_config) in old_pending_configs {
129
6
            let new_config = HostConfiguration {
130
6
                max_collators: old_config.max_collators,
131
6
                min_orchestrator_collators: old_config.min_orchestrator_collators,
132
6
                max_orchestrator_collators: old_config.max_orchestrator_collators,
133
6
                collators_per_container: old_config.collators_per_container,
134
6
                full_rotation_period: old_config.full_rotation_period,
135
6
                collators_per_parathread: old_config.collators_per_parathread,
136
6
                parathreads_per_collator: old_config.parathreads_per_collator,
137
6
                target_container_chain_fullness: old_config.target_container_chain_fullness,
138
6
                max_parachain_cores_percentage: old_config.max_parachain_cores_percentage,
139
6
                full_rotation_mode: default_config.full_rotation_mode.clone(),
140
6
            };
141
6
            new_pending_configs.push((session_index, new_config));
142
6
        }
143

            
144
3
        if !new_pending_configs.is_empty() {
145
3
            frame_support::storage::unhashed::put(
146
3
                &pallet_configuration::PendingConfigs::<T>::hashed_key(),
147
3
                &new_pending_configs,
148
3
            );
149
3
        }
150

            
151
3
        <T as pallet_configuration::Config>::WeightInfo::set_config_with_u32()
152
3
    }
153

            
154
    /// Run a standard pre-runtime test. This works the same way as in a normal runtime upgrade.
155
    #[cfg(feature = "try-runtime")]
156
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
157
        log::info!(
158
            "hashed key {:?}",
159
            pallet_configuration::ActiveConfig::<T>::hashed_key()
160
        );
161
        let old_config_bytes = frame_support::storage::unhashed::get_raw(
162
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
163
        )
164
        .unwrap();
165
        let old_config: Result<HostConfigurationV3, _> =
166
            DecodeAll::decode_all(&mut old_config_bytes.as_ref());
167
        let new_config: Result<HostConfiguration, _> =
168
            DecodeAll::decode_all(&mut old_config_bytes.as_ref());
169

            
170
        assert!(old_config.is_ok());
171
        assert!(new_config.is_err());
172

            
173
        Ok(vec![])
174
    }
175

            
176
    /// Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
177
    #[cfg(feature = "try-runtime")]
178
    fn post_upgrade(
179
        &self,
180
        _number_of_invulnerables: Vec<u8>,
181
    ) -> Result<(), sp_runtime::DispatchError> {
182
        let new_config_bytes = frame_support::storage::unhashed::get_raw(
183
            &pallet_configuration::ActiveConfig::<T>::hashed_key(),
184
        )
185
        .unwrap();
186
        let old_config: Result<HostConfigurationV3, _> =
187
            DecodeAll::decode_all(&mut new_config_bytes.as_ref());
188
        let new_config: Result<HostConfiguration, _> =
189
            DecodeAll::decode_all(&mut new_config_bytes.as_ref());
190

            
191
        assert!(old_config.is_err());
192
        assert!(new_config.is_ok());
193

            
194
        let new_config = pallet_configuration::Pallet::<T>::config();
195
        let default_config = HostConfiguration::default();
196
        assert_eq!(
197
            new_config.full_rotation_mode,
198
            default_config.full_rotation_mode
199
        );
200
        Ok(())
201
    }
202
}
203

            
204
pub struct MigrateServicesPaymentAddCollatorAssignmentCredits<T>(pub PhantomData<T>);
205
impl<T> Migration for MigrateServicesPaymentAddCollatorAssignmentCredits<T>
206
where
207
    T: pallet_services_payment::Config + pallet_registrar::Config,
208
{
209
    fn friendly_name(&self) -> &str {
210
        "TM_MigrateServicesPaymentAddCollatorAssignmentCredits"
211
    }
212

            
213
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
214
        // For each parachain in pallet_registrar (active, pending or pending_verification),
215
        // insert `MaxCreditsStored` to pallet_services_payment,
216
        // and mark that parachain as "given_free_credits".
217
2
        let mut para_ids = BTreeSet::new();
218
2
        let active = pallet_registrar::RegisteredParaIds::<T>::get();
219
2
        let pending = pallet_registrar::PendingParaIds::<T>::get();
220

            
221
2
        let paused = pallet_registrar::Paused::<T>::get();
222
2
        para_ids.extend(active);
223
2
        para_ids.extend(pending.into_iter().flat_map(|(_session, active)| active));
224
2
        para_ids.extend(paused);
225

            
226
2
        let reads = 3 + 2 * para_ids.len() as u64;
227
2
        let writes = 2 * para_ids.len() as u64;
228

            
229
6
        for para_id in para_ids {
230
4
            // 2 reads 2 writes
231
4
            pallet_services_payment::Pallet::<T>::set_free_collator_assignment_credits(
232
4
                &para_id,
233
4
                T::FreeCollatorAssignmentCredits::get(),
234
4
            );
235
4
        }
236

            
237
2
        let db_weights = T::DbWeight::get();
238
2
        db_weights.reads_writes(reads, writes)
239
2
    }
240
    /// Run a standard pre-runtime test. This works the same way as in a normal runtime upgrade.
241
    #[cfg(feature = "try-runtime")]
242
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
243
        let mut para_ids = BTreeSet::new();
244
        let active = pallet_registrar::RegisteredParaIds::<T>::get();
245
        let pending = pallet_registrar::PendingParaIds::<T>::get();
246
        let paused = pallet_registrar::Paused::<T>::get();
247
        para_ids.extend(active);
248
        para_ids.extend(pending.into_iter().flat_map(|(_session, active)| active));
249
        para_ids.extend(paused);
250

            
251
        for para_id in para_ids {
252
            assert!(
253
                pallet_services_payment::CollatorAssignmentCredits::<T>::get(para_id).is_none()
254
            );
255
        }
256

            
257
        Ok(vec![])
258
    }
259

            
260
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
261
    #[cfg(feature = "try-runtime")]
262
    fn post_upgrade(&self, _result: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
263
        let mut para_ids = BTreeSet::new();
264
        let active = pallet_registrar::RegisteredParaIds::<T>::get();
265
        let pending = pallet_registrar::PendingParaIds::<T>::get();
266
        let paused = pallet_registrar::Paused::<T>::get();
267
        para_ids.extend(active);
268
        para_ids.extend(pending.into_iter().flat_map(|(_session, active)| active));
269
        para_ids.extend(paused);
270

            
271
        for para_id in para_ids {
272
            assert_eq!(
273
                pallet_services_payment::CollatorAssignmentCredits::<T>::get(para_id),
274
                Some(T::FreeCollatorAssignmentCredits::get())
275
            );
276
        }
277

            
278
        Ok(())
279
    }
280
}
281

            
282
pub struct PolkadotXcmMigrationFixVersion<T, PolkadotXcm>(pub PhantomData<(T, PolkadotXcm)>);
283
impl<T, PolkadotXcm> Migration for PolkadotXcmMigrationFixVersion<T, PolkadotXcm>
284
where
285
    PolkadotXcm: GetStorageVersion + PalletInfoAccess,
286
    T: cumulus_pallet_xcmp_queue::Config,
287
{
288
    fn friendly_name(&self) -> &str {
289
        "MM_PolkadotXcmMigrationFixVersion"
290
    }
291

            
292
    fn migrate(&self, _available_weight: Weight) -> Weight {
293
        if <PolkadotXcm as GetStorageVersion>::on_chain_storage_version() == 0 {
294
            StorageVersion::new(1).put::<PolkadotXcm>();
295
            return T::DbWeight::get().writes(1);
296
        }
297
        Weight::default()
298
    }
299

            
300
    #[cfg(feature = "try-runtime")]
301
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
302
        ensure!(
303
            <PolkadotXcm as GetStorageVersion>::on_chain_storage_version() == 0,
304
            "PolkadotXcm storage version should be 0"
305
        );
306
        Ok(vec![])
307
    }
308

            
309
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
310
    #[cfg(feature = "try-runtime")]
311
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
312
        ensure!(
313
            <PolkadotXcm as GetStorageVersion>::on_chain_storage_version() == 1,
314
            "PolkadotXcm storage version should be 1"
315
        );
316
        Ok(())
317
    }
318
}
319

            
320
pub struct XcmpQueueMigrationFixVersion<T, XcmpQueue>(pub PhantomData<(T, XcmpQueue)>);
321
impl<T, XcmpQueue> Migration for XcmpQueueMigrationFixVersion<T, XcmpQueue>
322
where
323
    XcmpQueue: GetStorageVersion + PalletInfoAccess,
324
    T: cumulus_pallet_xcmp_queue::Config,
325
{
326
    fn friendly_name(&self) -> &str {
327
        "MM_XcmpQueueMigrationFixVersion"
328
    }
329

            
330
    fn migrate(&self, _available_weight: Weight) -> Weight {
331
        if <XcmpQueue as GetStorageVersion>::on_chain_storage_version() == 0 {
332
            StorageVersion::new(2).put::<XcmpQueue>();
333
            return T::DbWeight::get().writes(1);
334
        }
335
        Weight::default()
336
    }
337

            
338
    #[cfg(feature = "try-runtime")]
339
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
340
        ensure!(
341
            <XcmpQueue as GetStorageVersion>::on_chain_storage_version() == 0,
342
            "XcmpQueue storage version should be 0"
343
        );
344
        Ok(vec![])
345
    }
346

            
347
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
348
    #[cfg(feature = "try-runtime")]
349
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
350
        // Greater than because the post_upgrade is run after all the migrations, so
351
        // it can be greater if the following XcmpQueue migrations are applied in the
352
        // same runtime
353
        ensure!(
354
            <XcmpQueue as GetStorageVersion>::on_chain_storage_version() >= 2,
355
            "XcmpQueue storage version should be at least 2"
356
        );
357
        Ok(())
358
    }
359
}
360

            
361
pub struct XcmpQueueMigrationV3<T>(pub PhantomData<T>);
362
impl<T> Migration for XcmpQueueMigrationV3<T>
363
where
364
    T: cumulus_pallet_xcmp_queue::Config,
365
{
366
    fn friendly_name(&self) -> &str {
367
        "MM_XcmpQueueMigrationV3"
368
    }
369

            
370
    fn migrate(&self, _available_weight: Weight) -> Weight {
371
        cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3::<T>::on_runtime_upgrade()
372
    }
373

            
374
    // #[cfg(feature = "try-runtime")]
375
    // let mut pre_upgrade_result: Vec<u8>;
376

            
377
    #[cfg(feature = "try-runtime")]
378
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
379
        cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3::<T>::pre_upgrade()
380
    }
381

            
382
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
383
    #[cfg(feature = "try-runtime")]
384
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
385
        cumulus_pallet_xcmp_queue::migration::v3::MigrationToV3::<T>::post_upgrade(state)
386
    }
387
}
388

            
389
pub struct XcmpQueueMigrationV4<T>(pub PhantomData<T>);
390
impl<T> Migration for XcmpQueueMigrationV4<T>
391
where
392
    T: cumulus_pallet_xcmp_queue::Config,
393
{
394
    fn friendly_name(&self) -> &str {
395
        "MM_XcmpQueueMigrationV4"
396
    }
397

            
398
    fn migrate(&self, _available_weight: Weight) -> Weight {
399
        cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4::<T>::on_runtime_upgrade()
400
    }
401

            
402
    #[cfg(feature = "try-runtime")]
403
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
404
        cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4::<T>::pre_upgrade()
405
    }
406

            
407
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
408
    #[cfg(feature = "try-runtime")]
409
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
410
        cumulus_pallet_xcmp_queue::migration::v4::MigrationToV4::<T>::post_upgrade(state)
411
    }
412
}
413

            
414
pub struct RegistrarPendingVerificationValueToMap<T>(pub PhantomData<T>);
415
impl<T> Migration for RegistrarPendingVerificationValueToMap<T>
416
where
417
    T: pallet_registrar::Config,
418
{
419
    fn friendly_name(&self) -> &str {
420
        "TM_RegistrarPendingVerificationValueToMap"
421
    }
422

            
423
1
    fn migrate(&self, _available_weight: Weight) -> Weight {
424
1
        let para_ids: Vec<ParaId> = frame_support::storage::unhashed::take(
425
1
            &frame_support::storage::storage_prefix(b"Registrar", b"PendingVerification"),
426
        )
427
1
        .unwrap_or_default();
428

            
429
1
        let total_weight = T::DbWeight::get()
430
1
            .reads(1)
431
1
            .saturating_add(T::DbWeight::get().writes(1));
432

            
433
5
        for para_id in para_ids {
434
4
            total_weight.saturating_add(T::DbWeight::get().writes(1));
435
4
            pallet_registrar::PendingVerification::<T>::insert(para_id, ());
436
4
        }
437

            
438
1
        total_weight
439
1
    }
440

            
441
    #[cfg(feature = "try-runtime")]
442
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
443
        Ok(vec![])
444
    }
445

            
446
    // Run a standard post-runtime test. This works the same way as in a normal runtime upgrade.
447
    #[cfg(feature = "try-runtime")]
448
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
449
        Ok(())
450
    }
451
}
452

            
453
pub struct RegistrarParaManagerMigration<T>(pub PhantomData<T>);
454
impl<T> Migration for RegistrarParaManagerMigration<T>
455
where
456
    T: pallet_registrar::Config,
457
{
458
    fn friendly_name(&self) -> &str {
459
        "TM_RegistrarParaManagerMigration"
460
    }
461

            
462
    fn migrate(&self, _available_weight: Weight) -> Weight {
463
        let mut total_weight = Weight::default();
464
        for (para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
465
            pallet_registrar::ParaManager::<T>::insert(para_id, deposit.creator);
466
            total_weight = total_weight.saturating_add(
467
                T::DbWeight::get()
468
                    .reads(1)
469
                    .saturating_add(T::DbWeight::get().writes(1)),
470
            );
471
        }
472

            
473
        total_weight
474
    }
475

            
476
    #[cfg(feature = "try-runtime")]
477
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
478
        Ok(vec![])
479
    }
480

            
481
    #[cfg(feature = "try-runtime")]
482
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
483
        Ok(())
484
    }
485
}
486

            
487
pub struct RegistrarReserveToHoldMigration<T>(pub PhantomData<T>);
488
impl<T> Migration for RegistrarReserveToHoldMigration<T>
489
where
490
    T: pallet_registrar::Config,
491
    T: pallet_balances::Config,
492
    <T as pallet_balances::Config>::RuntimeHoldReason: From<pallet_registrar::HoldReason>,
493
    <T as pallet_balances::Config>::Balance: From<
494
        <<T as pallet_registrar::Config>::Currency as frame_support::traits::fungible::Inspect<
495
            T::AccountId,
496
        >>::Balance,
497
    >,
498
    <T as pallet_balances::Config>::Balance: From<u128>,
499
{
500
    fn friendly_name(&self) -> &str {
501
        "TM_RegistrarReserveToHoldMigration"
502
    }
503

            
504
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
505
2
        let mut total_weight = Weight::default();
506
2
        for (_para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
507
2
            pallet_balances::Pallet::<T>::unreserve(&deposit.creator, deposit.deposit.into());
508
2
            let _ = pallet_balances::Pallet::<T>::hold(
509
2
                &HoldReason::RegistrarDeposit.into(),
510
2
                &deposit.creator,
511
2
                deposit.deposit.into(),
512
2
            );
513
2
            total_weight = total_weight.saturating_add(T::DbWeight::get().reads_writes(2, 2));
514
2
        }
515

            
516
2
        total_weight
517
2
    }
518

            
519
    #[cfg(feature = "try-runtime")]
520
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
521
        use frame_support::traits::fungible::InspectHold;
522

            
523
        for (_para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
524
            ensure!(
525
                pallet_balances::Pallet::<T>::reserved_balance(&deposit.creator)
526
                    >= deposit.deposit.into(),
527
                "Reserved balanced cannot be less than deposit amount"
528
            );
529

            
530
            ensure!(
531
                pallet_balances::Pallet::<T>::balance_on_hold(
532
                    &HoldReason::RegistrarDeposit.into(),
533
                    &deposit.creator
534
                ) == 0u128.into(),
535
                "Balance on hold for RegistrarDeposit should be 0"
536
            );
537
        }
538
        Ok(vec![])
539
    }
540

            
541
    #[cfg(feature = "try-runtime")]
542
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
543
        use frame_support::traits::fungible::InspectHold;
544

            
545
        for (_para_id, deposit) in pallet_registrar::RegistrarDeposit::<T>::iter() {
546
            ensure!(
547
                pallet_balances::Pallet::<T>::balance_on_hold(
548
                    &HoldReason::RegistrarDeposit.into(),
549
                    &deposit.creator
550
                ) >= deposit.deposit.into(),
551
                "Balance on hold for RegistrarDeposit should be deposit"
552
            );
553
        }
554

            
555
        Ok(())
556
    }
557
}
558

            
559
pub struct MigrateSnowbridgeFeePerGasMigrationV0ToV1<T>(PhantomData<T>);
560
impl<T> Migration for MigrateSnowbridgeFeePerGasMigrationV0ToV1<T>
561
where
562
    T: snowbridge_pallet_system::Config,
563
{
564
334
    fn friendly_name(&self) -> &str {
565
334
        "MM_MigrateSnowbridgeFeePerGasMigrationV0ToV1"
566
334
    }
567

            
568
    fn migrate(&self, _available_weight: Weight) -> Weight {
569
        snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1::<T>::on_runtime_upgrade()
570
    }
571

            
572
    #[cfg(feature = "try-runtime")]
573
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
574
        snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1::<T>::pre_upgrade()
575
    }
576

            
577
    #[cfg(feature = "try-runtime")]
578
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
579
        snowbridge_pallet_system::migration::FeePerGasMigrationV0ToV1::<T>::post_upgrade(state)
580
    }
581
}
582

            
583
pub struct MigratePalletSessionV0toV1<T>(PhantomData<T>);
584
impl<T: frame_system::Config + pallet_session::Config> Migration for MigratePalletSessionV0toV1<T>
585
where
586
    pallet_session::migrations::v1::MigrateV0ToV1<
587
        T,
588
        pallet_session::migrations::v1::InitOffenceSeverity<T>,
589
    >: frame_support::traits::OnRuntimeUpgrade,
590
{
591
1216
    fn friendly_name(&self) -> &str {
592
1216
        "MM_MigratePalletSessionV0ToV1"
593
1216
    }
594

            
595
    fn migrate(&self, _available_weight: Weight) -> Weight {
596
        pallet_session::migrations::v1::MigrateV0ToV1::<
597
            T,
598
            pallet_session::migrations::v1::InitOffenceSeverity<T>,
599
        >::on_runtime_upgrade()
600
    }
601

            
602
    #[cfg(feature = "try-runtime")]
603
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
604
        pallet_session::migrations::v1::MigrateV0ToV1::<
605
            T,
606
            pallet_session::migrations::v1::InitOffenceSeverity<T>,
607
        >::pre_upgrade()
608
    }
609

            
610
    #[cfg(feature = "try-runtime")]
611
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
612
        pallet_session::migrations::v1::MigrateV0ToV1::<
613
            T,
614
            pallet_session::migrations::v1::InitOffenceSeverity<T>,
615
        >::post_upgrade(state)
616
    }
617
}
618
pub struct MigrateToLatestXcmVersion<Runtime>(PhantomData<Runtime>);
619
impl<Runtime> Migration for MigrateToLatestXcmVersion<Runtime>
620
where
621
    pallet_xcm::migration::MigrateToLatestXcmVersion<Runtime>:
622
        frame_support::traits::OnRuntimeUpgrade,
623
{
624
    fn friendly_name(&self) -> &str {
625
        "MM_MigrateToLatestXcmVersion5"
626
    }
627

            
628
    fn migrate(&self, _available_weight: Weight) -> Weight {
629
        pallet_xcm::migration::MigrateToLatestXcmVersion::<Runtime>::on_runtime_upgrade()
630
    }
631

            
632
    #[cfg(feature = "try-runtime")]
633
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
634
        pallet_xcm::migration::MigrateToLatestXcmVersion::<Runtime>::pre_upgrade()
635
    }
636

            
637
    #[cfg(feature = "try-runtime")]
638
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
639
        pallet_xcm::migration::MigrateToLatestXcmVersion::<Runtime>::post_upgrade(state)
640
    }
641
}
642

            
643
pub struct ForeignAssetCreatorMigration<Runtime>(pub PhantomData<Runtime>);
644

            
645
impl<Runtime> Migration for ForeignAssetCreatorMigration<Runtime>
646
where
647
    Runtime: pallet_foreign_asset_creator::Config,
648
    <Runtime as pallet_foreign_asset_creator::Config>::ForeignAsset:
649
        TryFrom<xcm::v3::MultiLocation>,
650
{
651
    fn friendly_name(&self) -> &str {
652
        "TM_ForeignAssetCreatorMigration"
653
    }
654

            
655
    fn migrate(&self, _available_weight: Weight) -> Weight {
656
        use frame_support::pallet_prelude::*;
657

            
658
        use xcm::v3::MultiLocation as OldLocation;
659

            
660
        let pallet_prefix = AssetIdToForeignAsset::<Runtime>::pallet_prefix();
661
        let asset_id_to_foreign_asset_storage_prefix =
662
            AssetIdToForeignAsset::<Runtime>::storage_prefix();
663
        let foreign_asset_to_asset_id_prefix = ForeignAssetToAssetId::<Runtime>::storage_prefix();
664

            
665
        // Data required to migrate ForeignAsset values
666
        // Read all the data into memory.
667
        let asset_id_to_foreign_asset_data: Vec<_> =
668
            storage_key_iter::<AssetId<Runtime>, OldLocation, Blake2_128Concat>(
669
                pallet_prefix,
670
                asset_id_to_foreign_asset_storage_prefix,
671
            )
672
            .drain()
673
            .collect();
674

            
675
        // Data required to migrate ForeignAsset keys
676
        let foreign_asset_to_asset_id_data: Vec<_> =
677
            storage_key_iter::<OldLocation, AssetId<Runtime>, Blake2_128Concat>(
678
                pallet_prefix,
679
                foreign_asset_to_asset_id_prefix,
680
            )
681
            .drain()
682
            .collect();
683

            
684
        let migrated_count = asset_id_to_foreign_asset_data
685
            .len()
686
            .saturating_add(foreign_asset_to_asset_id_data.len());
687

            
688
        log::info!("Migrating {:?} elements", migrated_count);
689

            
690
        // Write to the new storage with removed and added fields
691
        for (asset_id, old_location) in asset_id_to_foreign_asset_data {
692
            if let Ok(new_location) = Runtime::ForeignAsset::try_from(old_location) {
693
                AssetIdToForeignAsset::<Runtime>::insert(asset_id, new_location);
694
            } else {
695
                log::warn!("Location could not be converted safely to xcmV4")
696
            }
697
        }
698

            
699
        for (old_location, asset_id) in foreign_asset_to_asset_id_data {
700
            if let Ok(new_location) = Runtime::ForeignAsset::try_from(old_location) {
701
                ForeignAssetToAssetId::<Runtime>::insert(new_location, asset_id);
702
            } else {
703
                log::warn!("Location could not be converted safely to xcmV4")
704
            }
705
        }
706

            
707
        // One db read and one db write per element, plus the on-chain storage
708
        Runtime::DbWeight::get().reads_writes(migrated_count as u64, 2 * migrated_count as u64)
709
    }
710

            
711
    #[cfg(feature = "try-runtime")]
712
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
713
        Ok(vec![])
714
    }
715

            
716
    #[cfg(feature = "try-runtime")]
717
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
718
        Ok(())
719
    }
720
}
721

            
722
pub struct MigrateMMRLeafPallet<T>(pub PhantomData<T>);
723

            
724
impl<T: frame_system::Config> Migration for MigrateMMRLeafPallet<T> {
725
    fn friendly_name(&self) -> &str {
726
        "SM_MigrateMMRLeafPallet"
727
    }
728

            
729
2
    fn migrate(&self, available_weight: Weight) -> Weight {
730
2
        let new_name =
731
2
            <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<
732
2
                pallet_beefy_mmr::Pallet<T>,
733
2
            >()
734
2
            .expect("pallet_beefy_mmr must be part of dancelight before this migration");
735
2
        move_pallet(Self::old_pallet_name().as_bytes(), new_name.as_bytes());
736
2
        available_weight
737
2
    }
738

            
739
    #[cfg(feature = "try-runtime")]
740
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
741
        Ok(vec![])
742
    }
743

            
744
    #[cfg(feature = "try-runtime")]
745
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
746
        Ok(())
747
    }
748
}
749

            
750
impl<T> MigrateMMRLeafPallet<T> {
751
4
    pub fn old_pallet_name() -> &'static str {
752
4
        "MMRLeaf"
753
4
    }
754
}
755

            
756
pub mod snowbridge_system_migration {
757
    use super::*;
758
    use alloc::vec::Vec;
759
    use frame_support::pallet_prelude::*;
760
    use snowbridge_core::TokenId;
761
    use xcm::{
762
        self,
763
        v5::NetworkId::ByGenesis,
764
        v5::{Junction::GlobalConsensus, ROCOCO_GENESIS_HASH},
765
    };
766

            
767
    pub const DANCELIGHT_GENESIS_HASH: [u8; 32] =
768
        hex_literal::hex!["983a1a72503d6cc3636776747ec627172b51272bf45e50a355348facb67a820a"];
769

            
770
    pub const TANSSI_GENESIS_HASH: [u8; 32] =
771
        hex_literal::hex!["dd6d086f75ec041b66e20c4186d327b23c8af244c534a2418de6574e8c041a60"];
772

            
773
    parameter_types! {
774
        pub DancelightLocation: xcm::v5::Location = xcm::v5::Location::new(
775
            1,
776
            [GlobalConsensus(ByGenesis(DANCELIGHT_GENESIS_HASH))],
777
        );
778
        pub StarlightLocation: xcm::v5::Location = xcm::v5::Location::new(
779
            1,
780
            [GlobalConsensus(ByGenesis(TANSSI_GENESIS_HASH))],
781
        );
782
    }
783

            
784
    // Important: this cannot be called OldNativeToForeignId because that will be a different storage
785
    // item. Polkadot has a bug here.
786
    #[frame_support::storage_alias]
787
    pub type NativeToForeignId<T: snowbridge_pallet_system::Config> = StorageMap<
788
        snowbridge_pallet_system::Pallet<T>,
789
        Blake2_128Concat,
790
        xcm::v5::Location,
791
        TokenId,
792
        OptionQuery,
793
    >;
794

            
795
    /// One shot migration to change the genesis hash of NetworkId::ByGenesis()
796
    pub struct MigrationForGenesisHashes<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>(
797
        core::marker::PhantomData<(T, L)>,
798
    );
799
    impl<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>
800
        frame_support::traits::OnRuntimeUpgrade for MigrationForGenesisHashes<T, L>
801
    {
802
2
        fn on_runtime_upgrade() -> Weight {
803
2
            let mut weight = T::DbWeight::get().reads(1);
804
2
            let mut len_map1 = 0;
805
2
            let mut len_map2 = 0;
806

            
807
2
            let translate_genesis_hashes = |pre: xcm::v5::Location| -> Option<xcm::v5::Location> {
808
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
809
2
                len_map1 += 1;
810
2
                let new_location: Option<xcm::v5::Location> = match pre.unpack() {
811
2
                    (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
812
                    _ => None,
813
                };
814
2
                Some(new_location.expect("valid location"))
815
2
            };
816
2
            snowbridge_pallet_system::ForeignToNativeId::<T>::translate_values(
817
2
                translate_genesis_hashes,
818
            );
819

            
820
2
            let old_keys = NativeToForeignId::<T>::iter_keys().collect::<Vec<_>>();
821

            
822
4
            for old_key in old_keys {
823
2
                if let Some(old_val) = NativeToForeignId::<T>::get(&old_key) {
824
2
                    let new_location: Option<xcm::v5::Location> = match old_key.unpack() {
825
2
                        (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
826
                        _ => None,
827
                    };
828
2
                    snowbridge_pallet_system::NativeToForeignId::<T>::insert(
829
2
                        new_location.expect("valid location"),
830
2
                        old_val,
831
                    );
832
                }
833
2
                NativeToForeignId::<T>::remove(old_key);
834
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
835
2
                len_map2 += 1;
836
            }
837

            
838
            // Additional sanity check that both mappings have the same number of elements
839
2
            assert_eq!(len_map1, len_map2);
840

            
841
2
            weight
842
2
        }
843
    }
844
}
845

            
846
pub struct MigrateEthSystemGenesisHashes<Runtime, Location>(pub PhantomData<(Runtime, Location)>);
847

            
848
impl<Runtime, Location> Migration for MigrateEthSystemGenesisHashes<Runtime, Location>
849
where
850
    Runtime: snowbridge_pallet_system::Config,
851
    Location: Get<xcm::v5::Location>,
852
{
853
334
    fn friendly_name(&self) -> &str {
854
334
        "TM_MigrateEthSystemGenesisHashes"
855
334
    }
856

            
857
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
858
2
        snowbridge_system_migration::MigrationForGenesisHashes::<Runtime, Location>::on_runtime_upgrade()
859
2
    }
860

            
861
    #[cfg(feature = "try-runtime")]
862
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
863
        Ok(vec![])
864
    }
865

            
866
    #[cfg(feature = "try-runtime")]
867
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
868
        Ok(())
869
    }
870
}
871

            
872
pub struct MigrateParaSchedulerToV3<Runtime>(pub PhantomData<Runtime>);
873

            
874
impl<Runtime> Migration for MigrateParaSchedulerToV3<Runtime>
875
where
876
    Runtime: runtime_parachains::scheduler::Config,
877
{
878
    fn friendly_name(&self) -> &str {
879
        "TM_MigrateParaSchedulerToV3"
880
    }
881

            
882
    fn migrate(&self, _available_weight: Weight) -> Weight {
883
        runtime_parachains::scheduler::migration::MigrateV2ToV3::<Runtime>::on_runtime_upgrade()
884
    }
885

            
886
    #[cfg(feature = "try-runtime")]
887
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
888
        Ok(vec![])
889
    }
890

            
891
    #[cfg(feature = "try-runtime")]
892
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
893
        Ok(())
894
    }
895
}
896

            
897
pub struct MigrateParaSharedToV1<Runtime>(pub PhantomData<Runtime>);
898

            
899
impl<Runtime> Migration for MigrateParaSharedToV1<Runtime>
900
where
901
    Runtime: runtime_parachains::shared::Config,
902
{
903
    fn friendly_name(&self) -> &str {
904
        "TM_MigrateParaSharedToV1"
905
    }
906

            
907
    fn migrate(&self, _available_weight: Weight) -> Weight {
908
        runtime_parachains::shared::migration::MigrateToV1::<Runtime>::on_runtime_upgrade()
909
    }
910

            
911
    #[cfg(feature = "try-runtime")]
912
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
913
        Ok(vec![])
914
    }
915

            
916
    #[cfg(feature = "try-runtime")]
917
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
918
        Ok(())
919
    }
920
}
921

            
922
pub struct MigrateStreamPaymentNewConfigFields<Runtime>(pub PhantomData<Runtime>);
923
impl<Runtime> Migration for MigrateStreamPaymentNewConfigFields<Runtime>
924
where
925
    Runtime: pallet_stream_payment::Config,
926
{
927
    fn friendly_name(&self) -> &str {
928
        "TM_MigrateStreamPaymentNewConfigFields"
929
    }
930

            
931
2
    fn migrate(&self, available_weight: Weight) -> Weight {
932
2
        pallet_stream_payment::migrations::migrate_stream_payment_new_config_fields::<Runtime>(
933
2
            available_weight,
934
        )
935
2
    }
936

            
937
    #[cfg(feature = "try-runtime")]
938
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
939
        use pallet_stream_payment::migrations::OldStreamOf;
940
        use parity_scale_codec::Encode;
941

            
942
        let Some(stream_id) = pallet_stream_payment::Streams::<Runtime>::iter_keys().next() else {
943
            return Ok(vec![]);
944
        };
945

            
946
        let old_stream: OldStreamOf<Runtime> = frame_support::storage::unhashed::get(
947
            &pallet_stream_payment::Streams::<Runtime>::hashed_key_for(stream_id),
948
        )
949
        .expect("key was found so entry must exist");
950

            
951
        Ok((stream_id, old_stream).encode())
952
    }
953

            
954
    #[cfg(feature = "try-runtime")]
955
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
956
        use pallet_stream_payment::{migrations::OldStreamOf, ChangeRequest, Stream, StreamConfig};
957
        use parity_scale_codec::Decode;
958

            
959
        if state.is_empty() {
960
            // there were no streams
961
            return Ok(());
962
        }
963

            
964
        let (stream_id, old_stream) =
965
            <(Runtime::StreamId, OldStreamOf<Runtime>)>::decode(&mut &state[..])
966
                .expect("to decode properly");
967

            
968
        let new_stream = pallet_stream_payment::Streams::<Runtime>::get(stream_id)
969
            .expect("entry should still exist");
970

            
971
        let mut expected = Stream {
972
            source: old_stream.source,
973
            target: old_stream.target,
974
            deposit: old_stream.deposit,
975
            last_time_updated: old_stream.last_time_updated,
976
            request_nonce: old_stream.request_nonce,
977
            pending_request: None, // will be replaced below
978
            opening_deposit: old_stream.opening_deposit,
979
            config: StreamConfig {
980
                time_unit: old_stream.config.time_unit,
981
                asset_id: old_stream.config.asset_id,
982
                rate: old_stream.config.rate,
983
                minimum_request_deadline_delay: 0u32.into(),
984
                soft_minimum_deposit: 0u32.into(),
985
            },
986
        };
987

            
988
        if let Some(pending_request) = old_stream.pending_request {
989
            expected.pending_request = Some(ChangeRequest {
990
                requester: pending_request.requester,
991
                kind: pending_request.kind,
992
                deposit_change: pending_request.deposit_change,
993
                new_config: StreamConfig {
994
                    time_unit: pending_request.new_config.time_unit,
995
                    asset_id: pending_request.new_config.asset_id,
996
                    rate: pending_request.new_config.rate,
997
                    minimum_request_deadline_delay: 0u32.into(),
998
                    soft_minimum_deposit: 0u32.into(),
999
                },
            });
        }
        assert_eq!(
            new_stream, expected,
            "Migrated stream don't match expected value"
        );
        Ok(())
    }
}
pub struct OfflineMarkingStorageMigration<Runtime>(PhantomData<Runtime>);
impl<Runtime> Migration for OfflineMarkingStorageMigration<Runtime>
where
    Runtime: pallet_inactivity_tracking::Config,
{
1215
    fn friendly_name(&self) -> &str {
1215
        "TM_OfflineMarkingStorageMigration"
1215
    }
    fn migrate(&self, available_weight: Weight) -> Weight {
        pallet_inactivity_tracking::migrations::migrate_offline_collators_storage::<Runtime>(
            available_weight,
        )
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        use parity_scale_codec::Encode;
        let Some(collator_id) =
            pallet_inactivity_tracking::OfflineCollators::<Runtime>::iter_keys().next()
        else {
            return Ok(vec![]);
        };
        let old_collator_offline_status: bool =
            frame_support::storage::unhashed::get(&pallet_inactivity_tracking::OfflineCollators::<
                Runtime,
            >::hashed_key_for(
                collator_id.clone()
            ))
            .expect("key was found so entry must exist");
        Ok((collator_id, old_collator_offline_status).encode())
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        use parity_scale_codec::Decode;
        if state.is_empty() {
            // There were no offline collators
            return Ok(());
        }
        let (collator_id, old_collator_offline_status) =
            <(Runtime::AccountId, bool)>::decode(&mut &state[..]).expect("to decode properly");
        if old_collator_offline_status {
            let new_collator_offline_status =
                pallet_inactivity_tracking::OfflineCollators::<Runtime>::get(collator_id.clone())
                    .expect("entry should still exist");
            let expected_collator_offline_status =
                pallet_inactivity_tracking::OfflineStatus::Disabled;
            assert_eq!(
                new_collator_offline_status, expected_collator_offline_status,
                "Migrated collator offline status don't match expected value"
            );
        }
        Ok(())
    }
}
pub struct DataPreserversProfileContentMigration<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for DataPreserversProfileContentMigration<Runtime>
where
    Runtime: pallet_data_preservers::Config,
{
1216
    fn friendly_name(&self) -> &str {
1216
        "TM_DataPreserversProfileContentMigration"
1216
    }
1
    fn migrate(&self, available_weight: Weight) -> Weight {
1
        pallet_data_preservers::migrations::migrate_profiles_content::<Runtime>(available_weight)
1
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        Ok(vec![])
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        Ok(())
    }
}
pub struct FlashboxMigrations<Runtime>(PhantomData<Runtime>);
impl<Runtime> GetMigrations for FlashboxMigrations<Runtime>
where
    Runtime: pallet_balances::Config,
    Runtime: pallet_configuration::Config,
    Runtime: pallet_registrar::Config,
    Runtime: pallet_session::Config,
    Runtime: pallet_services_payment::Config,
    Runtime: pallet_data_preservers::Config,
    Runtime: pallet_stream_payment::Config,
    Runtime::AccountId: From<[u8; 32]>,
    <Runtime as pallet_balances::Config>::RuntimeHoldReason: From<pallet_registrar::HoldReason>,
    <Runtime as pallet_balances::Config>::Balance: From<<<Runtime as pallet_registrar::Config>::Currency as frame_support::traits::fungible::Inspect<Runtime::AccountId>>::Balance>,
    <Runtime as pallet_balances::Config>::Balance: From<u128>,
{
1
    fn get_migrations() -> Vec<Box<dyn Migration>> {
        //let migrate_services_payment =
        //    MigrateServicesPaymentAddCredits::<Runtime>(Default::default());
        //let migrate_boot_nodes = MigrateBootNodes::<Runtime>(Default::default());
        //let migrate_config_parathread_params =
        //    MigrateConfigurationParathreads::<Runtime>(Default::default());
        //let migrate_add_collator_assignment_credits =
        //    MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
        //let migrate_registrar_pending_verification =
        //    RegistrarPendingVerificationValueToMap::<Runtime>(Default::default());
        //let migrate_registrar_manager =
        //    RegistrarParaManagerMigration::<Runtime>(Default::default());
        //let migrate_data_preservers_assignments =
        //    DataPreserversAssignmentsMigration::<Runtime>(Default::default());
        //let migrate_registrar_reserves = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
        //let migrate_config_max_parachain_percentage = MigrateConfigurationAddParachainPercentage::<Runtime>(Default::default());
        //let migrate_config_full_rotation_mode = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
        //let migrate_stream_payment_new_config_items = MigrateStreamPaymentNewConfigFields::<Runtime>(Default::default());
1
        let migrate_pallet_session_v0_to_v1 = MigratePalletSessionV0toV1::<Runtime>(Default::default());
1
        let migrate_data_preservers_profiles = DataPreserversProfileContentMigration::<Runtime>(Default::default());
1
        vec![
            // Applied in runtime 400
            //Box::new(migrate_services_payment),
            // Applied in runtime 400
            //Box::new(migrate_boot_nodes),
            // Applied in runtime 400
            //Box::new(migrate_config_parathread_params),
            // Applied in runtime 500
            //Box::new(migrate_add_collator_assignment_credits),
            // Applied in runtime 700
            //Box::new(migrate_registrar_pending_verification),
            // Applied in runtime 700
            //Box::new(migrate_registrar_manager),
            // Applied in runtime 700
            //Box::new(migrate_data_preservers_assignments),
            // Applied in runtime 800
            //Box::new(migrate_registrar_reserves),
            // Applied in runtime 900
            //Box::new(migrate_config_max_parachain_percentage),
            // Applied in runtime 1100
            //Box::new(migrate_config_full_rotation_mode),
            // Applied in runtime 1200
            //Box::new(migrate_stream_payment_new_config_items),
1
            Box::new(migrate_pallet_session_v0_to_v1),
1
            Box::new(migrate_data_preservers_profiles),
        ]
1
    }
}
pub struct DanceboxMigrations<Runtime>(PhantomData<Runtime>);
impl<Runtime> GetMigrations for DanceboxMigrations<Runtime>
where
    Runtime: pallet_pooled_staking::Config,
    Runtime: pallet_session::Config,
    Runtime: pallet_registrar::Config,
    Runtime: pallet_balances::Config,
    Runtime: pallet_configuration::Config,
    Runtime: pallet_services_payment::Config,
    Runtime: cumulus_pallet_xcmp_queue::Config,
    Runtime: pallet_data_preservers::Config,
    Runtime: pallet_xcm::Config,
    Runtime: pallet_stream_payment::Config,
    Runtime: pallet_inactivity_tracking::Config,
    <Runtime as pallet_balances::Config>::RuntimeHoldReason:
        From<pallet_pooled_staking::HoldReason>,
    Runtime: pallet_foreign_asset_creator::Config,
    <Runtime as pallet_balances::Config>::RuntimeHoldReason:
        From<pallet_registrar::HoldReason>,
    Runtime::AccountId: From<[u8; 32]>,
    <Runtime as pallet_balances::Config>::Balance: From<<<Runtime as pallet_registrar::Config>::Currency as frame_support::traits::fungible::Inspect<Runtime::AccountId>>::Balance>,
    <Runtime as pallet_balances::Config>::Balance: From<u128>,
{
881
    fn get_migrations() -> Vec<Box<dyn Migration>> {
        // let migrate_invulnerables = MigrateInvulnerables::<Runtime>(Default::default());
        // let migrate_holds = MigrateHoldReason::<Runtime>(Default::default());
        // let migrate_config = MigrateConfigurationFullRotationPeriod::<Runtime>(Default::default());
        // let migrate_xcm = PolkadotXcmMigration::<Runtime>(Default::default());
        // let migrate_xcmp_queue = XcmpQueueMigration::<Runtime>(Default::default());
        // let migrate_services_payment =
        //     MigrateServicesPaymentAddCredits::<Runtime>(Default::default());
        // let migrate_boot_nodes = MigrateBootNodes::<Runtime>(Default::default());
        // let migrate_hold_reason_runtime_enum =
        //     MigrateHoldReasonRuntimeEnum::<Runtime>(Default::default());
        //let migrate_config_parathread_params =
        //    MigrateConfigurationParathreads::<Runtime>(Default::default());
        //let migrate_add_collator_assignment_credits =
        //    MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
        //let migrate_xcmp_queue_v4 = XcmpQueueMigrationV4::<Runtime>(Default::default());
        //let migrate_registrar_pending_verification =
        //    RegistrarPendingVerificationValueToMap::<Runtime>(Default::default());
        //let migrate_registrar_manager =
        //    RegistrarParaManagerMigration::<Runtime>(Default::default());
        //let migrate_data_preservers_assignments =
        //    DataPreserversAssignmentsMigration::<Runtime>(Default::default());
        //let migrate_pallet_xcm_v4 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
        //let foreign_asset_creator_migration =
        //    ForeignAssetCreatorMigration::<Runtime>(Default::default());
        //let migrate_registrar_reserves = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
        //let migrate_config_full_rotation_mode = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
        //let migrate_stream_payment_new_config_items = MigrateStreamPaymentNewConfigFields::<Runtime>(Default::default());
        //let migrate_pallet_xcm_v5 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
881
        let migrate_pallet_session_v0_to_v1 = MigratePalletSessionV0toV1::<Runtime>(Default::default());
881
        let migrate_offline_marking_storage =
881
            OfflineMarkingStorageMigration::<Runtime>(Default::default());
881
            let migrate_data_preservers_profiles = DataPreserversProfileContentMigration::<Runtime>(Default::default());
881
        vec![
            // Applied in runtime 200
            //Box::new(migrate_invulnerables),
            // Applied in runtime 200
            //Box::new(migrate_holds),
            // Applied in runtime 300
            //Box::new(migrate_config),
            // Applied in runtime 300
            //Box::new(migrate_xcm),
            // Applied in runtime 300
            //Box::new(migrate_xcmp_queue),
            // Applied in runtime 400
            //Box::new(migrate_services_payment),
            // Applied in runtime 400
            //Box::new(migrate_hold_reason_runtime_enum),
            // Applied in runtime 400
            //Box::new(migrate_boot_nodes),
            // Applied in runtime 500
            //Box::new(migrate_config_parathread_params),
            // Applied in runtime 500
            //Box::new(migrate_add_collator_assignment_credits),
            // Applied in runtime 500
            //Box::new(migrate_xcmp_queue_v4),
            // Applied in runtime 700
            //Box::new(migrate_registrar_pending_verification),
            // Applied in runtime 700
            //Box::new(migrate_registrar_manager),
            // Applied in runtime 700
            //Box::new(migrate_pallet_xcm_v4),
            // Applied in runtime 700
            //Box::new(foreign_asset_creator_migration),
            // Applied in runtime 700
            //Box::new(migrate_data_preservers_assignments),
            // Applied in runtime 800
            //Box::new(migrate_registrar_reserves),
            // Applied in runtime 900
            //Box::new(migrate_config_max_parachain_percentage),
            // Applied in runtime 1100
            //Box::new(migrate_config_full_rotation_mode),
            // Applied in runtime 1200
            //Box::new(migrate_stream_payment_new_config_items),
            // Applied in runtime 1200
            //Box::new(migrate_pallet_xcm_v5),
881
            Box::new(migrate_pallet_session_v0_to_v1),
881
            Box::new(migrate_offline_marking_storage),
881
            Box::new(migrate_data_preservers_profiles),
        ]
881
    }
}
#[cfg(feature = "relay")]
pub use relay::*;
#[cfg(feature = "relay")]
mod relay {
    use super::*;
    pub struct ExternalValidatorsInitialMigration<Runtime>(pub PhantomData<Runtime>);
    impl<Runtime> Migration for ExternalValidatorsInitialMigration<Runtime>
    where
        Runtime: pallet_external_validators::Config,
        Runtime: pallet_session::Config<
            ValidatorId = <Runtime as pallet_external_validators::Config>::ValidatorId,
        >,
    {
        fn friendly_name(&self) -> &str {
            "TM_ExternalValidatorsInitialMigration"
        }
2
        fn migrate(&self, _available_weight: Weight) -> Weight {
            use frame_support::pallet_prelude::*;
            // Set initial WhitelistedValidators to current validators from pallet session
2
            let session_keys = pallet_session::QueuedKeys::<Runtime>::get();
2
            let session_validators = BoundedVec::truncate_from(
2
                session_keys
2
                    .into_iter()
2
                    .map(|(validator, _keys)| validator)
2
                    .collect(),
            );
2
            pallet_external_validators::WhitelistedValidators::<Runtime>::put(session_validators);
            // Kill storage of ValidatorManager pallet
2
            let pallet_prefix: &[u8] = b"ValidatorManager";
2
            let _ = clear_storage_prefix(pallet_prefix, b"", b"", None, None);
            // One db read and one db write per element, plus the on-chain storage
2
            Runtime::DbWeight::get().reads_writes(1, 1)
2
        }
        #[cfg(feature = "try-runtime")]
        fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
            Ok(vec![])
        }
        #[cfg(feature = "try-runtime")]
        fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
            Ok(())
        }
    }
    pub struct BondedErasTimestampMigration<Runtime>(pub PhantomData<Runtime>);
    impl<Runtime> Migration for BondedErasTimestampMigration<Runtime>
    where
        Runtime: pallet_external_validator_slashes::Config,
    {
        fn friendly_name(&self) -> &str {
            "TM_ExternalValidatorSlashesBondedErasTimestampMigration"
        }
2
        fn migrate(&self, _available_weight: Weight) -> Weight {
            use frame_support::pallet_prelude::*;
2
            let bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
2
                frame_support::storage::unhashed::get(
2
                    &pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key(),
                )
2
                .unwrap_or_default();
2
            let new_eras = bonded_eras
2
                .iter()
6
                .map(|(era, session)| (*era, *session, 0u64))
2
                .collect();
2
            pallet_external_validator_slashes::BondedEras::<Runtime>::set(new_eras);
            // One db read and one db write per element, plus the on-chain storage
2
            Runtime::DbWeight::get().reads_writes(1, 1)
2
        }
        #[cfg(feature = "try-runtime")]
        fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
            use frame_support::pallet_prelude::*;
            let previous_bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
                frame_support::storage::unhashed::get(
                    &pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key(),
                )
                .unwrap_or_default();
            Ok(previous_bonded_eras.encode())
        }
        #[cfg(feature = "try-runtime")]
        fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
            use parity_scale_codec::Decode;
            let previous_bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
                Decode::decode(&mut &state[..]).expect("state to be decoded properly");
            let new_eras = pallet_external_validator_slashes::BondedEras::<Runtime>::get();
            for (i, bonded) in new_eras.iter().enumerate() {
                assert_eq!(previous_bonded_eras[i].0, bonded.0);
                assert_eq!(previous_bonded_eras[i].1, bonded.1);
                assert_eq!(bonded.2, 0u64);
            }
            Ok(())
        }
    }
    pub struct DancelightMigrations<Runtime>(PhantomData<Runtime>);
    impl<Runtime> GetMigrations for DancelightMigrations<Runtime>
    where
        Runtime: frame_system::Config,
        Runtime: pallet_external_validators::Config,
        Runtime: pallet_configuration::Config,
        Runtime: pallet_session::Config<
            ValidatorId = <Runtime as pallet_external_validators::Config>::ValidatorId,
        >,
        Runtime: pallet_external_validator_slashes::Config,
        Runtime: snowbridge_pallet_system::Config,
        Runtime: runtime_parachains::scheduler::Config,
        Runtime: runtime_parachains::shared::Config,
        Runtime: pallet_xcm::Config,
        Runtime: pallet_inactivity_tracking::Config,
        Runtime: pallet_data_preservers::Config,
    {
253
        fn get_migrations() -> Vec<Box<dyn Migration>> {
            /*let migrate_config_full_rotation_mode =
            MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());*/
            /*let external_validator_slashes_bonded_eras_timestamp =
            BondedErasTimestampMigration::<Runtime>(Default::default());*/
            /*let snowbridge_ethereum_system_xcm_v5 =
            SnowbridgeEthereumSystemXcmV5::<Runtime>(Default::default());*/
            //let migrate_pallet_xcm_v5 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
            //let para_shared_v1_migration = MigrateParaSharedToV1::<Runtime>(Default::default());
            //let para_scheduler_v3_migration = MigrateParaSchedulerToV3::<Runtime>(Default::default());
253
            let migrate_pallet_session_v0_to_v1 =
253
                MigratePalletSessionV0toV1::<Runtime>(Default::default());
253
            let migrate_snowbridge_fee_per_gas_migration_v0_to_v1 =
253
                MigrateSnowbridgeFeePerGasMigrationV0ToV1::<Runtime>(Default::default());
253
            let eth_system_genesis_hashes = MigrateEthSystemGenesisHashes::<
253
                Runtime,
253
                snowbridge_system_migration::DancelightLocation,
253
            >(Default::default());
253
            let migrate_offline_marking_storage =
253
                OfflineMarkingStorageMigration::<Runtime>(Default::default());
253
            let migrate_data_preservers_profiles =
253
                DataPreserversProfileContentMigration::<Runtime>(Default::default());
253
            vec![
                // Applied in runtime 1000
                //Box::new(migrate_mmr_leaf_pallet),
                // Applied in runtime 900
                //Box::new(migrate_external_validators),
                // Applied in runtime 1100
                //Box::new(migrate_config_full_rotation_mode),
                // Applied in runtime  1100
                //Box::new(external_validator_slashes_bonded_eras_timestamp),
                // Applied in runtime 1200
                //Box::new(snowbridge_ethereum_system_xcm_v5),
                // Applied in runtime 1200
                //Box::new(migrate_pallet_xcm_v5),
                // Apllied in runtime 1200
                // Box::new(para_shared_v1_migration),
                // Applied in runtime 1200
                //Box::new(para_scheduler_v3_migration),
253
                Box::new(migrate_pallet_session_v0_to_v1),
253
                Box::new(migrate_snowbridge_fee_per_gas_migration_v0_to_v1),
253
                Box::new(eth_system_genesis_hashes),
253
                Box::new(migrate_offline_marking_storage),
253
                Box::new(migrate_data_preservers_profiles),
            ]
253
        }
    }
    pub struct StarlightMigrations<Runtime>(PhantomData<Runtime>);
    impl<Runtime> GetMigrations for StarlightMigrations<Runtime>
    where
        Runtime: frame_system::Config,
        Runtime: pallet_session::Config,
        Runtime: snowbridge_pallet_system::Config,
        Runtime: pallet_inactivity_tracking::Config,
        Runtime: pallet_data_preservers::Config,
    {
81
        fn get_migrations() -> Vec<Box<dyn Migration>> {
81
            let migrate_pallet_session_v0_to_v1 =
81
                MigratePalletSessionV0toV1::<Runtime>(Default::default());
81
            let migrate_snowbridge_fee_per_gas_migration_v0_to_v1 =
81
                MigrateSnowbridgeFeePerGasMigrationV0ToV1::<Runtime>(Default::default());
81
            let eth_system_genesis_hashes = MigrateEthSystemGenesisHashes::<
81
                Runtime,
81
                snowbridge_system_migration::StarlightLocation,
81
            >(Default::default());
81
            let migrate_offline_marking_storage =
81
                OfflineMarkingStorageMigration::<Runtime>(Default::default());
81
            let migrate_data_preservers_profiles =
81
                DataPreserversProfileContentMigration::<Runtime>(Default::default());
81
            vec![
81
                Box::new(migrate_pallet_session_v0_to_v1),
81
                Box::new(migrate_snowbridge_fee_per_gas_migration_v0_to_v1),
81
                Box::new(eth_system_genesis_hashes),
81
                Box::new(migrate_offline_marking_storage),
81
                Box::new(migrate_data_preservers_profiles),
            ]
81
        }
    }
}