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
    cumulus_primitives_core::ParaId,
41
    frame_support::{
42
        migration::{clear_storage_prefix, move_pallet, storage_key_iter},
43
        pallet_prelude::GetStorageVersion,
44
        parameter_types,
45
        traits::{
46
            fungible::MutateHold, OnRuntimeUpgrade, PalletInfoAccess, ReservableCurrency,
47
            StorageVersion,
48
        },
49
        weights::Weight,
50
        Blake2_128Concat, BoundedVec, StoragePrefixedMap,
51
    },
52
    pallet_configuration::{weights::WeightInfo as _, HostConfiguration},
53
    pallet_foreign_asset_creator::{AssetId, AssetIdToForeignAsset, ForeignAssetToAssetId},
54
    pallet_migrations::{GetMigrations, Migration},
55
    pallet_registrar::HoldReason,
56
    sp_core::Get,
57
    sp_runtime::Perbill,
58
    sp_std::{collections::btree_set::BTreeSet, marker::PhantomData, prelude::*},
59
};
60
#[cfg(feature = "try-runtime")]
61
use {frame_support::ensure, parity_scale_codec::DecodeAll};
62

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

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

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

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

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

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

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

            
149
3
        <T as pallet_configuration::Config>::WeightInfo::set_config_with_u32()
150
3
    }
151

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

            
168
        assert!(old_config.is_ok());
169
        assert!(new_config.is_err());
170

            
171
        Ok(vec![])
172
    }
173

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

            
189
        assert!(old_config.is_err());
190
        assert!(new_config.is_ok());
191

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

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

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

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

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

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

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

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

            
255
        Ok(vec![])
256
    }
257

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

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

            
276
        Ok(())
277
    }
278
}
279

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
436
1
        total_weight
437
1
    }
438

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

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

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

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

            
471
        total_weight
472
    }
473

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

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

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

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

            
514
2
        total_weight
515
2
    }
516

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

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

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

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

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

            
553
        Ok(())
554
    }
555
}
556

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

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

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

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

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

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

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

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

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

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

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

            
641
pub struct DataPreserversAssignmentsMigration<T>(pub PhantomData<T>);
642
impl<T> Migration for DataPreserversAssignmentsMigration<T>
643
where
644
    T: pallet_data_preservers::Config + pallet_registrar::Config,
645
    T::AccountId: From<[u8; 32]>,
646
{
647
    fn friendly_name(&self) -> &str {
648
        "TM_DataPreserversAssignmentsMigration"
649
    }
650

            
651
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
652
        use {
653
            frame_support::BoundedBTreeSet,
654
            frame_system::RawOrigin,
655
            pallet_data_preservers::{AssignmentProcessor, ParaIdsFilter, Profile, ProfileMode},
656
        };
657

            
658
2
        let mut total_weight = Weight::default();
659
2

            
660
2
        let (request, _extra, witness) = T::AssignmentProcessor::free_variant_values()
661
2
            .expect("free variant values are necessary to perform migration");
662
2

            
663
2
        let dummy_profile_owner = T::AccountId::from([0u8; 32]);
664
2

            
665
2
        let pallet_prefix: &[u8] = b"DataPreservers";
666
2
        let storage_item_prefix: &[u8] = b"BootNodes";
667
2
        let bootnodes_storage: Vec<_> = storage_key_iter::<
668
2
            ParaId,
669
2
            BoundedVec<BoundedVec<u8, T::MaxNodeUrlLen>, T::MaxAssignmentsPerParaId>,
670
2
            Blake2_128Concat,
671
2
        >(pallet_prefix, storage_item_prefix)
672
2
        .collect();
673
2

            
674
2
        total_weight = total_weight.saturating_add(
675
2
            T::DbWeight::get()
676
2
                .reads(bootnodes_storage.len() as u64)
677
2
                .saturating_add(T::DbWeight::get().writes(bootnodes_storage.len() as u64)),
678
2
        );
679

            
680
6
        for (para_id, bootnodes) in bootnodes_storage {
681
12
            for bootnode_url in bootnodes {
682
8
                let profile = Profile {
683
8
                    url: bootnode_url,
684
8
                    para_ids: ParaIdsFilter::Whitelist({
685
8
                        let mut set = BoundedBTreeSet::new();
686
8
                        set.try_insert(para_id).expect("to be in bound");
687
8
                        set
688
8
                    }),
689
8
                    mode: ProfileMode::Bootnode,
690
8
                    assignment_request: request.clone(),
691
8
                };
692
8

            
693
8
                let profile_id = pallet_data_preservers::NextProfileId::<T>::get();
694

            
695
8
                if let Some(weight) = pallet_data_preservers::Pallet::<T>::force_create_profile(
696
8
                    RawOrigin::Root.into(),
697
8
                    profile,
698
8
                    dummy_profile_owner.clone(),
699
8
                )
700
8
                .expect("to create profile")
701
8
                .actual_weight
702
                {
703
                    total_weight = total_weight.saturating_add(weight);
704
8
                }
705

            
706
8
                if let Some(weight) = pallet_data_preservers::Pallet::<T>::force_start_assignment(
707
8
                    RawOrigin::Root.into(),
708
8
                    profile_id,
709
8
                    para_id,
710
8
                    witness.clone(),
711
8
                )
712
8
                .expect("to start assignment")
713
8
                .actual_weight
714
                {
715
                    total_weight = total_weight.saturating_add(weight);
716
8
                }
717
            }
718
        }
719

            
720
2
        let _ = clear_storage_prefix(pallet_prefix, storage_item_prefix, &[], None, None);
721
2

            
722
2
        total_weight
723
2
    }
724

            
725
    #[cfg(feature = "try-runtime")]
726
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
727
        use parity_scale_codec::Encode;
728

            
729
        let pallet_prefix: &[u8] = b"DataPreservers";
730
        let storage_item_prefix: &[u8] = b"BootNodes";
731
        let state: Vec<_> = storage_key_iter::<
732
            ParaId,
733
            BoundedVec<BoundedVec<u8, T::MaxNodeUrlLen>, T::MaxAssignmentsPerParaId>,
734
            Blake2_128Concat,
735
        >(pallet_prefix, storage_item_prefix)
736
        .collect();
737

            
738
        Ok(state.encode())
739
    }
740

            
741
    #[cfg(feature = "try-runtime")]
742
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
743
        use parity_scale_codec::Decode;
744

            
745
        let pallet_prefix: &[u8] = b"DataPreservers";
746
        let storage_item_prefix: &[u8] = b"BootNodes";
747

            
748
        let pre_state: Vec<(ParaId, Vec<Vec<u8>>)> =
749
            Decode::decode(&mut &state[..]).expect("state to be decoded properly");
750

            
751
        for (para_id, bootnodes) in pre_state {
752
            let assignments = pallet_data_preservers::Assignments::<T>::get(para_id);
753
            assert_eq!(assignments.len(), bootnodes.len());
754

            
755
            let profiles: Vec<_> =
756
                pallet_data_preservers::Pallet::<T>::assignments_profiles(para_id).collect();
757

            
758
            for bootnode in bootnodes {
759
                assert_eq!(
760
                    profiles
761
                        .iter()
762
                        .filter(|profile| profile.url == bootnode)
763
                        .count(),
764
                    1
765
                );
766
            }
767
        }
768

            
769
        assert_eq!(
770
            storage_key_iter::<
771
                ParaId,
772
                BoundedVec<BoundedVec<u8, T::MaxNodeUrlLen>, T::MaxAssignmentsPerParaId>,
773
                Blake2_128Concat,
774
            >(pallet_prefix, storage_item_prefix)
775
            .count(),
776
            0
777
        );
778

            
779
        Ok(())
780
    }
781
}
782

            
783
pub struct ForeignAssetCreatorMigration<Runtime>(pub PhantomData<Runtime>);
784

            
785
impl<Runtime> Migration for ForeignAssetCreatorMigration<Runtime>
786
where
787
    Runtime: pallet_foreign_asset_creator::Config,
788
    <Runtime as pallet_foreign_asset_creator::Config>::ForeignAsset:
789
        TryFrom<xcm::v3::MultiLocation>,
790
{
791
    fn friendly_name(&self) -> &str {
792
        "TM_ForeignAssetCreatorMigration"
793
    }
794

            
795
    fn migrate(&self, _available_weight: Weight) -> Weight {
796
        use frame_support::pallet_prelude::*;
797

            
798
        use xcm::v3::MultiLocation as OldLocation;
799

            
800
        let pallet_prefix = AssetIdToForeignAsset::<Runtime>::pallet_prefix();
801
        let asset_id_to_foreign_asset_storage_prefix =
802
            AssetIdToForeignAsset::<Runtime>::storage_prefix();
803
        let foreign_asset_to_asset_id_prefix = ForeignAssetToAssetId::<Runtime>::storage_prefix();
804

            
805
        // Data required to migrate ForeignAsset values
806
        // Read all the data into memory.
807
        let asset_id_to_foreign_asset_data: Vec<_> =
808
            storage_key_iter::<AssetId<Runtime>, OldLocation, Blake2_128Concat>(
809
                pallet_prefix,
810
                asset_id_to_foreign_asset_storage_prefix,
811
            )
812
            .drain()
813
            .collect();
814

            
815
        // Data required to migrate ForeignAsset keys
816
        let foreign_asset_to_asset_id_data: Vec<_> =
817
            storage_key_iter::<OldLocation, AssetId<Runtime>, Blake2_128Concat>(
818
                pallet_prefix,
819
                foreign_asset_to_asset_id_prefix,
820
            )
821
            .drain()
822
            .collect();
823

            
824
        let migrated_count = asset_id_to_foreign_asset_data
825
            .len()
826
            .saturating_add(foreign_asset_to_asset_id_data.len());
827

            
828
        log::info!("Migrating {:?} elements", migrated_count);
829

            
830
        // Write to the new storage with removed and added fields
831
        for (asset_id, old_location) in asset_id_to_foreign_asset_data {
832
            if let Ok(new_location) = Runtime::ForeignAsset::try_from(old_location) {
833
                AssetIdToForeignAsset::<Runtime>::insert(asset_id, new_location);
834
            } else {
835
                log::warn!("Location could not be converted safely to xcmV4")
836
            }
837
        }
838

            
839
        for (old_location, asset_id) in foreign_asset_to_asset_id_data {
840
            if let Ok(new_location) = Runtime::ForeignAsset::try_from(old_location) {
841
                ForeignAssetToAssetId::<Runtime>::insert(new_location, asset_id);
842
            } else {
843
                log::warn!("Location could not be converted safely to xcmV4")
844
            }
845
        }
846

            
847
        // One db read and one db write per element, plus the on-chain storage
848
        Runtime::DbWeight::get().reads_writes(migrated_count as u64, 2 * migrated_count as u64)
849
    }
850

            
851
    #[cfg(feature = "try-runtime")]
852
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
853
        Ok(vec![])
854
    }
855

            
856
    #[cfg(feature = "try-runtime")]
857
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
858
        Ok(())
859
    }
860
}
861

            
862
pub struct ExternalValidatorsInitialMigration<Runtime>(pub PhantomData<Runtime>);
863

            
864
impl<Runtime> Migration for ExternalValidatorsInitialMigration<Runtime>
865
where
866
    Runtime: pallet_external_validators::Config,
867
    Runtime: pallet_session::Config<
868
        ValidatorId = <Runtime as pallet_external_validators::Config>::ValidatorId,
869
    >,
870
{
871
    fn friendly_name(&self) -> &str {
872
        "TM_ExternalValidatorsInitialMigration"
873
    }
874

            
875
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
876
        use frame_support::pallet_prelude::*;
877

            
878
        // Set initial WhitelistedValidators to current validators from pallet session
879
2
        let session_keys = pallet_session::QueuedKeys::<Runtime>::get();
880
2
        let session_validators = BoundedVec::truncate_from(
881
2
            session_keys
882
2
                .into_iter()
883
4
                .map(|(validator, _keys)| validator)
884
2
                .collect(),
885
2
        );
886
2
        pallet_external_validators::WhitelistedValidators::<Runtime>::put(session_validators);
887
2

            
888
2
        // Kill storage of ValidatorManager pallet
889
2
        let pallet_prefix: &[u8] = b"ValidatorManager";
890
2
        let _ = clear_storage_prefix(pallet_prefix, b"", b"", None, None);
891
2

            
892
2
        // One db read and one db write per element, plus the on-chain storage
893
2
        Runtime::DbWeight::get().reads_writes(1, 1)
894
2
    }
895

            
896
    #[cfg(feature = "try-runtime")]
897
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
898
        Ok(vec![])
899
    }
900

            
901
    #[cfg(feature = "try-runtime")]
902
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
903
        Ok(())
904
    }
905
}
906

            
907
pub struct MigrateMMRLeafPallet<T>(pub PhantomData<T>);
908

            
909
impl<T: frame_system::Config> Migration for MigrateMMRLeafPallet<T> {
910
    fn friendly_name(&self) -> &str {
911
        "SM_MigrateMMRLeafPallet"
912
    }
913

            
914
2
    fn migrate(&self, available_weight: Weight) -> Weight {
915
2
        let new_name =
916
2
            <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<
917
2
                pallet_beefy_mmr::Pallet<T>,
918
2
            >()
919
2
            .expect("pallet_beefy_mmr must be part of dancelight before this migration");
920
2
        move_pallet(Self::old_pallet_name().as_bytes(), new_name.as_bytes());
921
2
        available_weight
922
2
    }
923

            
924
    #[cfg(feature = "try-runtime")]
925
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
926
        Ok(vec![])
927
    }
928

            
929
    #[cfg(feature = "try-runtime")]
930
    fn post_upgrade(&self, _state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
931
        Ok(())
932
    }
933
}
934

            
935
impl<T> MigrateMMRLeafPallet<T> {
936
4
    pub fn old_pallet_name() -> &'static str {
937
4
        "MMRLeaf"
938
4
    }
939
}
940

            
941
pub struct BondedErasTimestampMigration<Runtime>(pub PhantomData<Runtime>);
942

            
943
impl<Runtime> Migration for BondedErasTimestampMigration<Runtime>
944
where
945
    Runtime: pallet_external_validator_slashes::Config,
946
{
947
    fn friendly_name(&self) -> &str {
948
        "TM_ExternalValidatorSlashesBondedErasTimestampMigration"
949
    }
950

            
951
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
952
        use frame_support::pallet_prelude::*;
953

            
954
2
        let bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
955
2
            frame_support::storage::unhashed::get(
956
2
                &pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key(),
957
2
            )
958
2
            .unwrap_or_default();
959
2
        let new_eras = bonded_eras
960
2
            .iter()
961
6
            .map(|(era, session)| (*era, *session, 0u64))
962
2
            .collect();
963
2
        pallet_external_validator_slashes::BondedEras::<Runtime>::set(new_eras);
964
2

            
965
2
        // One db read and one db write per element, plus the on-chain storage
966
2
        Runtime::DbWeight::get().reads_writes(1, 1)
967
2
    }
968

            
969
    #[cfg(feature = "try-runtime")]
970
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
971
        use frame_support::pallet_prelude::*;
972

            
973
        let previous_bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
974
            frame_support::storage::unhashed::get(
975
                &pallet_external_validator_slashes::BondedEras::<Runtime>::hashed_key(),
976
            )
977
            .unwrap_or_default();
978

            
979
        Ok(previous_bonded_eras.encode())
980
    }
981

            
982
    #[cfg(feature = "try-runtime")]
983
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
984
        use parity_scale_codec::Decode;
985
        let previous_bonded_eras: Vec<(sp_staking::EraIndex, sp_staking::SessionIndex)> =
986
            Decode::decode(&mut &state[..]).expect("state to be decoded properly");
987
        let new_eras = pallet_external_validator_slashes::BondedEras::<Runtime>::get();
988
        for (i, bonded) in new_eras.iter().enumerate() {
989
            assert_eq!(previous_bonded_eras[i].0, bonded.0);
990
            assert_eq!(previous_bonded_eras[i].1, bonded.1);
991
            assert_eq!(bonded.2, 0u64);
992
        }
993
        Ok(())
994
    }
995
}
996

            
997
pub mod snowbridge_system_migration {
998
    use super::*;
999
    use alloc::vec::Vec;
    use frame_support::pallet_prelude::*;
    use snowbridge_core::TokenId;
    use xcm::{
        self,
        v5::NetworkId::ByGenesis,
        v5::{Junction::GlobalConsensus, ROCOCO_GENESIS_HASH},
    };
    pub const DANCELIGHT_GENESIS_HASH: [u8; 32] =
        hex_literal::hex!["983a1a72503d6cc3636776747ec627172b51272bf45e50a355348facb67a820a"];
    pub const TANSSI_GENESIS_HASH: [u8; 32] =
        hex_literal::hex!["dd6d086f75ec041b66e20c4186d327b23c8af244c534a2418de6574e8c041a60"];
    parameter_types! {
        pub DancelightLocation: xcm::v5::Location = xcm::v5::Location::new(
            1,
            [GlobalConsensus(ByGenesis(DANCELIGHT_GENESIS_HASH))],
        );
        pub StarlightLocation: xcm::v5::Location = xcm::v5::Location::new(
            1,
            [GlobalConsensus(ByGenesis(TANSSI_GENESIS_HASH))],
        );
    }
    // Important: this cannot be called OldNativeToForeignId because that will be a different storage
    // item. Polkadot has a bug here.
8
    #[frame_support::storage_alias]
    pub type NativeToForeignId<T: snowbridge_pallet_system::Config> = StorageMap<
        snowbridge_pallet_system::Pallet<T>,
        Blake2_128Concat,
        xcm::v5::Location,
        TokenId,
        OptionQuery,
    >;
    /// One shot migration to change the genesis hash of NetworkId::ByGenesis()
    pub struct MigrationForGenesisHashes<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>(
        core::marker::PhantomData<(T, L)>,
    );
    impl<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>
        frame_support::traits::OnRuntimeUpgrade for MigrationForGenesisHashes<T, L>
    {
2
        fn on_runtime_upgrade() -> Weight {
2
            let mut weight = T::DbWeight::get().reads(1);
2
            let mut len_map1 = 0;
2
            let mut len_map2 = 0;
2

            
2
            let translate_genesis_hashes = |pre: xcm::v5::Location| -> Option<xcm::v5::Location> {
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
2
                len_map1 += 1;
2
                let new_location: Option<xcm::v5::Location> = match pre.unpack() {
2
                    (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
                    _ => None,
                };
2
                Some(new_location.expect("valid location"))
2
            };
2
            snowbridge_pallet_system::ForeignToNativeId::<T>::translate_values(
2
                translate_genesis_hashes,
2
            );
2

            
2
            let old_keys = NativeToForeignId::<T>::iter_keys().collect::<Vec<_>>();
4
            for old_key in old_keys {
2
                if let Some(old_val) = NativeToForeignId::<T>::get(&old_key) {
2
                    let new_location: Option<xcm::v5::Location> = match old_key.unpack() {
2
                        (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
                        _ => None,
                    };
2
                    snowbridge_pallet_system::NativeToForeignId::<T>::insert(
2
                        &new_location.expect("valid location"),
2
                        old_val,
2
                    );
                }
2
                NativeToForeignId::<T>::remove(old_key);
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
2
                len_map2 += 1;
            }
            // Additional sanity check that both mappings have the same number of elements
2
            assert_eq!(len_map1, len_map2);
2
            weight
2
        }
    }
}
pub struct MigrateEthSystemGenesisHashes<Runtime, Location>(pub PhantomData<(Runtime, Location)>);
impl<Runtime, Location> Migration for MigrateEthSystemGenesisHashes<Runtime, Location>
where
    Runtime: snowbridge_pallet_system::Config,
    Location: Get<xcm::v5::Location>,
{
162
    fn friendly_name(&self) -> &str {
162
        "TM_MigrateEthSystemGenesisHashes"
162
    }
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
2
        snowbridge_system_migration::MigrationForGenesisHashes::<Runtime, Location>::on_runtime_upgrade()
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 MigrateParaSchedulerToV3<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for MigrateParaSchedulerToV3<Runtime>
where
    Runtime: runtime_parachains::scheduler::Config,
{
    fn friendly_name(&self) -> &str {
        "TM_MigrateParaSchedulerToV3"
    }
    fn migrate(&self, _available_weight: Weight) -> Weight {
        runtime_parachains::scheduler::migration::MigrateV2ToV3::<Runtime>::on_runtime_upgrade()
    }
    #[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 MigrateParaSharedToV1<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for MigrateParaSharedToV1<Runtime>
where
    Runtime: runtime_parachains::shared::Config,
{
    fn friendly_name(&self) -> &str {
        "TM_MigrateParaSharedToV1"
    }
    fn migrate(&self, _available_weight: Weight) -> Weight {
        runtime_parachains::shared::migration::MigrateToV1::<Runtime>::on_runtime_upgrade()
    }
    #[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 MigrateStreamPaymentNewConfigFields<Runtime>(pub PhantomData<Runtime>);
impl<Runtime> Migration for MigrateStreamPaymentNewConfigFields<Runtime>
where
    Runtime: pallet_stream_payment::Config,
{
    fn friendly_name(&self) -> &str {
        "TM_MigrateStreamPaymentNewConfigFields"
    }
2
    fn migrate(&self, available_weight: Weight) -> Weight {
2
        pallet_stream_payment::migrations::migrate_stream_payment_new_config_fields::<Runtime>(
2
            available_weight,
2
        )
2
    }
    #[cfg(feature = "try-runtime")]
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
        use pallet_stream_payment::migrations::OldStreamOf;
        use parity_scale_codec::Encode;
        let Some(stream_id) = pallet_stream_payment::Streams::<Runtime>::iter_keys().next() else {
            return Ok(vec![]);
        };
        let old_stream: OldStreamOf<Runtime> = frame_support::storage::unhashed::get(
            &pallet_stream_payment::Streams::<Runtime>::hashed_key_for(stream_id),
        )
        .expect("key was found so entry must exist");
        Ok((stream_id, old_stream).encode())
    }
    #[cfg(feature = "try-runtime")]
    fn post_upgrade(&self, state: Vec<u8>) -> Result<(), sp_runtime::DispatchError> {
        use pallet_stream_payment::{migrations::OldStreamOf, ChangeRequest, Stream, StreamConfig};
        use parity_scale_codec::Decode;
        if state.is_empty() {
            // there were no streams
            return Ok(());
        }
        let (stream_id, old_stream) =
            <(Runtime::StreamId, OldStreamOf<Runtime>)>::decode(&mut &state[..])
                .expect("to decode properly");
        let new_stream = pallet_stream_payment::Streams::<Runtime>::get(stream_id)
            .expect("entry should still exist");
        let mut expected = Stream {
            source: old_stream.source,
            target: old_stream.target,
            deposit: old_stream.deposit,
            last_time_updated: old_stream.last_time_updated,
            request_nonce: old_stream.request_nonce,
            pending_request: None, // will be replaced below
            opening_deposit: old_stream.opening_deposit,
            config: StreamConfig {
                time_unit: old_stream.config.time_unit,
                asset_id: old_stream.config.asset_id,
                rate: old_stream.config.rate,
                minimum_request_deadline_delay: 0u32.into(),
                soft_minimum_deposit: 0u32.into(),
            },
        };
        if let Some(pending_request) = old_stream.pending_request {
            expected.pending_request = Some(ChangeRequest {
                requester: pending_request.requester,
                kind: pending_request.kind,
                deposit_change: pending_request.deposit_change,
                new_config: StreamConfig {
                    time_unit: pending_request.new_config.time_unit,
                    asset_id: pending_request.new_config.asset_id,
                    rate: pending_request.new_config.rate,
                    minimum_request_deadline_delay: 0u32.into(),
                    soft_minimum_deposit: 0u32.into(),
                },
            });
        }
        assert_eq!(
            new_stream, expected,
            "Migrated stream don't match expected value"
        );
        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>> {
1
        //let migrate_services_payment =
1
        //    MigrateServicesPaymentAddCredits::<Runtime>(Default::default());
1
        //let migrate_boot_nodes = MigrateBootNodes::<Runtime>(Default::default());
1
        //let migrate_config_parathread_params =
1
        //    MigrateConfigurationParathreads::<Runtime>(Default::default());
1

            
1
        //let migrate_add_collator_assignment_credits =
1
        //    MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
1
        //let migrate_registrar_pending_verification =
1
        //    RegistrarPendingVerificationValueToMap::<Runtime>(Default::default());
1
        //let migrate_registrar_manager =
1
        //    RegistrarParaManagerMigration::<Runtime>(Default::default());
1
        //let migrate_data_preservers_assignments =
1
        //    DataPreserversAssignmentsMigration::<Runtime>(Default::default());
1
        //let migrate_registrar_reserves = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
1
        //let migrate_config_max_parachain_percentage = MigrateConfigurationAddParachainPercentage::<Runtime>(Default::default());
1
        //let migrate_config_full_rotation_mode = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
1
        //let migrate_stream_payment_new_config_items = MigrateStreamPaymentNewConfigFields::<Runtime>(Default::default());
1
        let migrate_pallet_session_v0_to_v1 = MigratePalletSessionV0toV1::<Runtime>(Default::default());
1

            
1
        vec![
1
            // Applied in runtime 400
1
            //Box::new(migrate_services_payment),
1
            // Applied in runtime 400
1
            //Box::new(migrate_boot_nodes),
1
            // Applied in runtime 400
1
            //Box::new(migrate_config_parathread_params),
1
            // Applied in runtime 500
1
            //Box::new(migrate_add_collator_assignment_credits),
1
            // Applied in runtime 700
1
            //Box::new(migrate_registrar_pending_verification),
1
            // Applied in runtime 700
1
            //Box::new(migrate_registrar_manager),
1
            // Applied in runtime 700
1
            //Box::new(migrate_data_preservers_assignments),
1
            // Applied in runtime 800
1
            //Box::new(migrate_registrar_reserves),
1
            // Applied in runtime 900
1
            //Box::new(migrate_config_max_parachain_percentage),
1
            // Applied in runtime 1100
1
            //Box::new(migrate_config_full_rotation_mode),
1
            // Applied in runtime 1200
1
            //Box::new(migrate_stream_payment_new_config_items),
1
            Box::new(migrate_pallet_session_v0_to_v1),
1
        ]
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 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>,
{
623
    fn get_migrations() -> Vec<Box<dyn Migration>> {
623
        // let migrate_invulnerables = MigrateInvulnerables::<Runtime>(Default::default());
623
        // let migrate_holds = MigrateHoldReason::<Runtime>(Default::default());
623
        // let migrate_config = MigrateConfigurationFullRotationPeriod::<Runtime>(Default::default());
623
        // let migrate_xcm = PolkadotXcmMigration::<Runtime>(Default::default());
623
        // let migrate_xcmp_queue = XcmpQueueMigration::<Runtime>(Default::default());
623
        // let migrate_services_payment =
623
        //     MigrateServicesPaymentAddCredits::<Runtime>(Default::default());
623
        // let migrate_boot_nodes = MigrateBootNodes::<Runtime>(Default::default());
623
        // let migrate_hold_reason_runtime_enum =
623
        //     MigrateHoldReasonRuntimeEnum::<Runtime>(Default::default());
623

            
623
        //let migrate_config_parathread_params =
623
        //    MigrateConfigurationParathreads::<Runtime>(Default::default());
623
        //let migrate_add_collator_assignment_credits =
623
        //    MigrateServicesPaymentAddCollatorAssignmentCredits::<Runtime>(Default::default());
623
        //let migrate_xcmp_queue_v4 = XcmpQueueMigrationV4::<Runtime>(Default::default());
623
        //let migrate_registrar_pending_verification =
623
        //    RegistrarPendingVerificationValueToMap::<Runtime>(Default::default());
623
        //let migrate_registrar_manager =
623
        //    RegistrarParaManagerMigration::<Runtime>(Default::default());
623
        //let migrate_data_preservers_assignments =
623
        //    DataPreserversAssignmentsMigration::<Runtime>(Default::default());
623

            
623
        //let migrate_pallet_xcm_v4 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
623
        //let foreign_asset_creator_migration =
623
        //    ForeignAssetCreatorMigration::<Runtime>(Default::default());
623
        //let migrate_registrar_reserves = RegistrarReserveToHoldMigration::<Runtime>(Default::default());
623
        //let migrate_config_full_rotation_mode = MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());
623
        //let migrate_stream_payment_new_config_items = MigrateStreamPaymentNewConfigFields::<Runtime>(Default::default());
623
        //let migrate_pallet_xcm_v5 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
623
        let migrate_pallet_session_v0_to_v1 = MigratePalletSessionV0toV1::<Runtime>(Default::default());
623

            
623
        vec![
623
            // Applied in runtime 200
623
            //Box::new(migrate_invulnerables),
623
            // Applied in runtime 200
623
            //Box::new(migrate_holds),
623
            // Applied in runtime 300
623
            //Box::new(migrate_config),
623
            // Applied in runtime 300
623
            //Box::new(migrate_xcm),
623
            // Applied in runtime 300
623
            //Box::new(migrate_xcmp_queue),
623
            // Applied in runtime 400
623
            //Box::new(migrate_services_payment),
623
            // Applied in runtime 400
623
            //Box::new(migrate_hold_reason_runtime_enum),
623
            // Applied in runtime 400
623
            //Box::new(migrate_boot_nodes),
623
            // Applied in runtime 500
623
            //Box::new(migrate_config_parathread_params),
623
            // Applied in runtime 500
623
            //Box::new(migrate_add_collator_assignment_credits),
623
            // Applied in runtime 500
623
            //Box::new(migrate_xcmp_queue_v4),
623
            // Applied in runtime 700
623
            //Box::new(migrate_registrar_pending_verification),
623
            // Applied in runtime 700
623
            //Box::new(migrate_registrar_manager),
623
            // Applied in runtime 700
623
            //Box::new(migrate_pallet_xcm_v4),
623
            // Applied in runtime 700
623
            //Box::new(foreign_asset_creator_migration),
623
            // Applied in runtime 700
623
            //Box::new(migrate_data_preservers_assignments),
623
            // Applied in runtime 800
623
            //Box::new(migrate_registrar_reserves),
623
            // Applied in runtime 900
623
            //Box::new(migrate_config_max_parachain_percentage),
623
            // Applied in runtime 1100
623
            //Box::new(migrate_config_full_rotation_mode),
623
            // Applied in runtime 1200
623
            //Box::new(migrate_stream_payment_new_config_items),
623
            // Applied in runtime 1200
623
            //Box::new(migrate_pallet_xcm_v5),
623
            Box::new(migrate_pallet_session_v0_to_v1),
623
        ]
623
    }
}
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,
{
81
    fn get_migrations() -> Vec<Box<dyn Migration>> {
81
        /*let migrate_config_full_rotation_mode =
81
        MigrateConfigurationAddFullRotationMode::<Runtime>(Default::default());*/
81
        /*let external_validator_slashes_bonded_eras_timestamp =
81
        BondedErasTimestampMigration::<Runtime>(Default::default());*/
81
        /*let snowbridge_ethereum_system_xcm_v5 =
81
        SnowbridgeEthereumSystemXcmV5::<Runtime>(Default::default());*/
81
        //let migrate_pallet_xcm_v5 = MigrateToLatestXcmVersion::<Runtime>(Default::default());
81
        //let para_shared_v1_migration = MigrateParaSharedToV1::<Runtime>(Default::default());
81
        //let para_scheduler_v3_migration = MigrateParaSchedulerToV3::<Runtime>(Default::default());
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::DancelightLocation,
81
        >(Default::default());
81

            
81
        vec![
81
            // Applied in runtime 1000
81
            //Box::new(migrate_mmr_leaf_pallet),
81
            // Applied in runtime 900
81
            //Box::new(migrate_external_validators),
81
            // Applied in runtime 1100
81
            //Box::new(migrate_config_full_rotation_mode),
81
            // Applied in runtime  1100
81
            //Box::new(external_validator_slashes_bonded_eras_timestamp),
81
            // Applied in runtime 1200
81
            //Box::new(snowbridge_ethereum_system_xcm_v5),
81
            // Applied in runtime 1200
81
            //Box::new(migrate_pallet_xcm_v5),
81
            // Apllied in runtime 1200
81
            // Box::new(para_shared_v1_migration),
81
            // Applied in runtime 1200
81
            //Box::new(para_scheduler_v3_migration),
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
        ]
81
    }
}
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,
{
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
        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
        ]
81
    }
}