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

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

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

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

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

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

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

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

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

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

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

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

            
172
        Ok(vec![])
173
    }
174

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

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

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

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

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

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

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

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

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

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

            
256
        Ok(vec![])
257
    }
258

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

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

            
277
        Ok(())
278
    }
279
}
280

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
437
1
        total_weight
438
1
    }
439

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

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

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

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

            
472
        total_weight
473
    }
474

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

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

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

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

            
515
2
        total_weight
516
2
    }
517

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

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

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

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

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

            
554
        Ok(())
555
    }
556
}
557

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
723
2
        total_weight
724
2
    }
725

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

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

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

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

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

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

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

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

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

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

            
780
        Ok(())
781
    }
782
}
783

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
863
pub struct MigrateMMRLeafPallet<T>(pub PhantomData<T>);
864

            
865
impl<T: frame_system::Config> Migration for MigrateMMRLeafPallet<T> {
866
    fn friendly_name(&self) -> &str {
867
        "SM_MigrateMMRLeafPallet"
868
    }
869

            
870
2
    fn migrate(&self, available_weight: Weight) -> Weight {
871
2
        let new_name =
872
2
            <<T as frame_system::Config>::PalletInfo as frame_support::traits::PalletInfo>::name::<
873
2
                pallet_beefy_mmr::Pallet<T>,
874
2
            >()
875
2
            .expect("pallet_beefy_mmr must be part of dancelight before this migration");
876
2
        move_pallet(Self::old_pallet_name().as_bytes(), new_name.as_bytes());
877
2
        available_weight
878
2
    }
879

            
880
    #[cfg(feature = "try-runtime")]
881
    fn pre_upgrade(&self) -> Result<Vec<u8>, sp_runtime::DispatchError> {
882
        Ok(vec![])
883
    }
884

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

            
891
impl<T> MigrateMMRLeafPallet<T> {
892
4
    pub fn old_pallet_name() -> &'static str {
893
4
        "MMRLeaf"
894
4
    }
895
}
896

            
897
pub mod snowbridge_system_migration {
898
    use super::*;
899
    use alloc::vec::Vec;
900
    use frame_support::pallet_prelude::*;
901
    use snowbridge_core::TokenId;
902
    use xcm::{
903
        self,
904
        v5::NetworkId::ByGenesis,
905
        v5::{Junction::GlobalConsensus, ROCOCO_GENESIS_HASH},
906
    };
907

            
908
    pub const DANCELIGHT_GENESIS_HASH: [u8; 32] =
909
        hex_literal::hex!["983a1a72503d6cc3636776747ec627172b51272bf45e50a355348facb67a820a"];
910

            
911
    pub const TANSSI_GENESIS_HASH: [u8; 32] =
912
        hex_literal::hex!["dd6d086f75ec041b66e20c4186d327b23c8af244c534a2418de6574e8c041a60"];
913

            
914
    parameter_types! {
915
        pub DancelightLocation: xcm::v5::Location = xcm::v5::Location::new(
916
            1,
917
            [GlobalConsensus(ByGenesis(DANCELIGHT_GENESIS_HASH))],
918
        );
919
        pub StarlightLocation: xcm::v5::Location = xcm::v5::Location::new(
920
            1,
921
            [GlobalConsensus(ByGenesis(TANSSI_GENESIS_HASH))],
922
        );
923
    }
924

            
925
    // Important: this cannot be called OldNativeToForeignId because that will be a different storage
926
    // item. Polkadot has a bug here.
927
8
    #[frame_support::storage_alias]
928
    pub type NativeToForeignId<T: snowbridge_pallet_system::Config> = StorageMap<
929
        snowbridge_pallet_system::Pallet<T>,
930
        Blake2_128Concat,
931
        xcm::v5::Location,
932
        TokenId,
933
        OptionQuery,
934
    >;
935

            
936
    /// One shot migration to change the genesis hash of NetworkId::ByGenesis()
937
    pub struct MigrationForGenesisHashes<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>(
938
        core::marker::PhantomData<(T, L)>,
939
    );
940
    impl<T: snowbridge_pallet_system::Config, L: Get<xcm::v5::Location>>
941
        frame_support::traits::OnRuntimeUpgrade for MigrationForGenesisHashes<T, L>
942
    {
943
2
        fn on_runtime_upgrade() -> Weight {
944
2
            let mut weight = T::DbWeight::get().reads(1);
945
2
            let mut len_map1 = 0;
946
2
            let mut len_map2 = 0;
947
2

            
948
2
            let translate_genesis_hashes = |pre: xcm::v5::Location| -> Option<xcm::v5::Location> {
949
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
950
2
                len_map1 += 1;
951
2
                let new_location: Option<xcm::v5::Location> = match pre.unpack() {
952
2
                    (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
953
                    _ => None,
954
                };
955
2
                Some(new_location.expect("valid location"))
956
2
            };
957
2
            snowbridge_pallet_system::ForeignToNativeId::<T>::translate_values(
958
2
                translate_genesis_hashes,
959
2
            );
960
2

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

            
963
4
            for old_key in old_keys {
964
2
                if let Some(old_val) = NativeToForeignId::<T>::get(&old_key) {
965
2
                    let new_location: Option<xcm::v5::Location> = match old_key.unpack() {
966
2
                        (1, [GlobalConsensus(ByGenesis(ROCOCO_GENESIS_HASH))]) => Some(L::get()),
967
                        _ => None,
968
                    };
969
2
                    snowbridge_pallet_system::NativeToForeignId::<T>::insert(
970
2
                        new_location.expect("valid location"),
971
2
                        old_val,
972
2
                    );
973
                }
974
2
                NativeToForeignId::<T>::remove(old_key);
975
2
                weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 2));
976
2
                len_map2 += 1;
977
            }
978

            
979
            // Additional sanity check that both mappings have the same number of elements
980
2
            assert_eq!(len_map1, len_map2);
981

            
982
2
            weight
983
2
        }
984
    }
985
}
986

            
987
pub struct MigrateEthSystemGenesisHashes<Runtime, Location>(pub PhantomData<(Runtime, Location)>);
988

            
989
impl<Runtime, Location> Migration for MigrateEthSystemGenesisHashes<Runtime, Location>
990
where
991
    Runtime: snowbridge_pallet_system::Config,
992
    Location: Get<xcm::v5::Location>,
993
{
994
162
    fn friendly_name(&self) -> &str {
995
162
        "TM_MigrateEthSystemGenesisHashes"
996
162
    }
997

            
998
2
    fn migrate(&self, _available_weight: Weight) -> Weight {
999
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
    }
}
#[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()
4
                    .map(|(validator, _keys)| validator)
2
                    .collect(),
2
            );
2
            pallet_external_validators::WhitelistedValidators::<Runtime>::put(session_validators);
2

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

            
2
            // 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
                )
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);
2

            
2
            // 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,
    {
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
        }
    }
}