-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathmigration.rs
More file actions
4424 lines (3883 loc) · 184 KB
/
migration.rs
File metadata and controls
4424 lines (3883 loc) · 184 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(
unused,
clippy::expect_used,
clippy::indexing_slicing,
clippy::panic,
clippy::unwrap_used
)]
use super::mock::*;
use crate::*;
use alloc::collections::BTreeMap;
use approx::{assert_abs_diff_eq, assert_relative_eq};
use codec::{Decode, Encode};
use frame_support::{
StorageHasher, Twox64Concat, assert_ok,
storage::unhashed::{get, get_raw, put, put_raw},
storage_alias,
traits::{StorageInstance, StoredMap},
weights::Weight,
};
use safe_math::SafeDiv;
use crate::migrations::migrate_coldkey_swap_scheduled_to_announcements::deprecated as coldkey_swap_deprecated;
use crate::migrations::migrate_storage;
use frame_support::traits::Bounded;
use frame_system::Config;
use pallet_drand::types::RoundNumber;
use pallet_scheduler::ScheduledOf;
use scale_info::prelude::collections::VecDeque;
use sp_core::{H256, U256, crypto::Ss58Codec};
use sp_io::hashing::twox_128;
use sp_runtime::{
AccountId32,
traits::{Hash, Zero},
};
use sp_std::marker::PhantomData;
use substrate_fixed::types::{I96F32, U64F64};
use substrate_fixed::{traits::ToFixed, types::extra::U2};
use subtensor_runtime_common::{NetUidStorageIndex, TaoBalance};
#[allow(clippy::arithmetic_side_effects)]
fn close(value: u64, target: u64, eps: u64) {
assert!(
(value as i64 - target as i64).abs() < eps as i64,
"Assertion failed: value = {value}, target = {target}, eps = {eps}"
)
}
#[test]
fn test_initialise_ti() {
use frame_support::traits::OnRuntimeUpgrade;
new_test_ext(1).execute_with(|| {
pallet_balances::TotalIssuance::<Test>::put(TaoBalance::from(1000));
crate::SubnetTAO::<Test>::insert(NetUid::from(1), TaoBalance::from(100));
crate::SubnetTAO::<Test>::insert(NetUid::from(2), TaoBalance::from(5));
// Ensure values are NOT initialized prior to running migration
assert!(crate::TotalIssuance::<Test>::get().is_zero());
assert!(crate::TotalStake::<Test>::get().is_zero());
crate::migrations::migrate_init_total_issuance::initialise_total_issuance::Migration::<Test>::on_runtime_upgrade();
// Ensure values were initialized correctly
assert_eq!(crate::TotalStake::<Test>::get(), TaoBalance::from(105));
assert_eq!(
crate::TotalIssuance::<Test>::get(), TaoBalance::from(105 + 1000)
);
});
}
#[test]
fn test_migration_transfer_nets_to_foundation() {
new_test_ext(1).execute_with(|| {
// Create subnet 1
add_network(1.into(), 1, 0);
// Create subnet 11
add_network(11.into(), 1, 0);
log::info!("{:?}", SubtensorModule::get_subnet_owner(1.into()));
//assert_eq!(SubtensorModule::<Test>::get_subnet_owner(1), );
// Run the migration to transfer ownership
let hex =
hex_literal::hex!["feabaafee293d3b76dae304e2f9d885f77d2b17adab9e17e921b321eccd61c77"];
crate::migrations::migrate_transfer_ownership_to_foundation::migrate_transfer_ownership_to_foundation::<Test>(hex);
log::info!("new owner: {:?}", SubtensorModule::get_subnet_owner(1.into()));
})
}
#[test]
fn test_migration_delete_subnet_3() {
new_test_ext(1).execute_with(|| {
// Create subnet 3
add_network(3.into(), 1, 0);
assert!(SubtensorModule::if_subnet_exist(3.into()));
// Run the migration to transfer ownership
crate::migrations::migrate_delete_subnet_3::migrate_delete_subnet_3::<Test>();
assert!(!SubtensorModule::if_subnet_exist(3.into()));
})
}
#[test]
fn test_migration_delete_subnet_21() {
new_test_ext(1).execute_with(|| {
// Create subnet 21
add_network(21.into(), 1, 0);
assert!(SubtensorModule::if_subnet_exist(21.into()));
// Run the migration to transfer ownership
crate::migrations::migrate_delete_subnet_21::migrate_delete_subnet_21::<Test>();
assert!(!SubtensorModule::if_subnet_exist(21.into()));
})
}
#[test]
fn test_migrate_commit_reveal_2() {
new_test_ext(1).execute_with(|| {
// ------------------------------
// Step 1: Simulate Old Storage Entries
// ------------------------------
const MIGRATION_NAME: &str = "migrate_commit_reveal_2_v2";
let pallet_prefix = twox_128("SubtensorModule".as_bytes());
let storage_prefix_interval = twox_128("WeightCommitRevealInterval".as_bytes());
let storage_prefix_commits = twox_128("WeightCommits".as_bytes());
let netuid = NetUid::from(1);
let interval_value: u64 = 50u64;
// Construct the full key for WeightCommitRevealInterval
let mut interval_key = Vec::new();
interval_key.extend_from_slice(&pallet_prefix);
interval_key.extend_from_slice(&storage_prefix_interval);
interval_key.extend_from_slice(&netuid.encode());
put_raw(&interval_key, &interval_value.encode());
let test_account: U256 = U256::from(1);
// Construct the full key for WeightCommits (DoubleMap)
let mut commit_key = Vec::new();
commit_key.extend_from_slice(&pallet_prefix);
commit_key.extend_from_slice(&storage_prefix_commits);
// First key (netuid) hashed with Twox64Concat
let netuid_hashed = Twox64Concat::hash(&netuid.encode());
commit_key.extend_from_slice(&netuid_hashed);
// Second key (account) hashed with Twox64Concat
let account_hashed = Twox64Concat::hash(&test_account.encode());
commit_key.extend_from_slice(&account_hashed);
let commit_value: (H256, u64) = (H256::from_low_u64_be(42), 100);
put_raw(&commit_key, &commit_value.encode());
let stored_interval = get_raw(&interval_key).expect("Expected to get a value");
assert_eq!(
u64::decode(&mut &stored_interval[..]).expect("Failed to decode interval value"),
interval_value
);
let stored_commit = get_raw(&commit_key).expect("Expected to get a value");
assert_eq!(
<(H256, u64)>::decode(&mut &stored_commit[..]).expect("Failed to decode commit value"),
commit_value
);
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet"
);
// ------------------------------
// Step 2: Run the Migration
// ------------------------------
let weight = crate::migrations::migrate_commit_reveal_v2::migrate_commit_reveal_2::<Test>();
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as run"
);
// ------------------------------
// Step 3: Verify Migration Effects
// ------------------------------
let stored_interval_after = get_raw(&interval_key);
assert!(
stored_interval_after.is_none(),
"WeightCommitRevealInterval should be cleared"
);
let stored_commit_after = get_raw(&commit_key);
assert!(
stored_commit_after.is_none(),
"WeightCommits entry should be cleared"
);
assert!(!weight.is_zero(), "Migration weight should be non-zero");
});
}
// Leaving in for reference. Will remove later.
// SKIP_WASM_BUILD=1 RUST_LOG=debug cargo test --package pallet-subtensor --lib -- tests::migration::test_migrate_rao --exact --show-output --nocapture
// #[test]
// fn test_migrate_rao() {
// new_test_ext(1).execute_with(|| {
// // Setup initial state
// let netuid_0: u16 = 0;
// let netuid_1: u16 = 1;
// let netuid_2: u16 = 2;
// let netuid_3: u16 = 3;
// let hotkey1 = U256::from(1);
// let hotkey2 = U256::from(2);
// let coldkey1 = U256::from(3);
// let coldkey2 = U256::from(4);
// let coldkey3 = U256::from(5);
// let stake_amount: u64 = 1_000_000_000;
// let lock_amount: u64 = 500;
// NetworkMinLockCost::<Test>::set(500);
// // Add networks root and alpha
// add_network(netuid_0, 1, 0);
// add_network(netuid_1, 1, 0);
// add_network(netuid_2, 1, 0);
// add_network(netuid_3, 1, 0);
// // Set subnet lock
// SubnetLocked::<Test>::insert(netuid_1, lock_amount);
// // Add some initial stake
// EmissionValues::<Test>::insert(netuid_1, 1_000_000_000);
// EmissionValues::<Test>::insert(netuid_2, 2_000_000_000);
// EmissionValues::<Test>::insert(netuid_3, 3_000_000_000);
// Owner::<Test>::insert(hotkey1, coldkey1);
// Owner::<Test>::insert(hotkey2, coldkey2);
// Stake::<Test>::insert(hotkey1, coldkey1, stake_amount);
// Stake::<Test>::insert(hotkey1, coldkey2, stake_amount);
// Stake::<Test>::insert(hotkey2, coldkey2, stake_amount);
// Stake::<Test>::insert(hotkey2, coldkey3, stake_amount);
// // Verify initial conditions
// assert_eq!(SubnetTAO::<Test>::get(netuid_0), 0);
// assert_eq!(SubnetTAO::<Test>::get(netuid_1), 0);
// assert_eq!(SubnetAlphaOut::<Test>::get(netuid_0), 0);
// assert_eq!(SubnetAlphaOut::<Test>::get(netuid_1), 0);
// assert_eq!(SubnetAlphaIn::<Test>::get(netuid_0), 0);
// assert_eq!(SubnetAlphaIn::<Test>::get(netuid_1), 0);
// assert_eq!(TotalHotkeyShares::<Test>::get(hotkey1, netuid_0), 0);
// assert_eq!(TotalHotkeyShares::<Test>::get(hotkey1, netuid_1), 0);
// assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey1, netuid_0), 0);
// assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey2, netuid_1), 0);
// // Run migration
// crate::migrations::migrate_rao::migrate_rao::<Test>();
// // Verify root subnet (netuid 0) state after migration
// assert_eq!(SubnetTAO::<Test>::get(netuid_0), 4 * stake_amount); // Root has everything
// assert_eq!(SubnetTAO::<Test>::get(netuid_1), 1_000_000_000); // Always 1000000000
// assert_eq!(SubnetAlphaIn::<Test>::get(netuid_0), 1_000_000_000); // Always 1_000_000_000
// assert_eq!(SubnetAlphaIn::<Test>::get(netuid_1), 1_000_000_000); // Always 1_000_000_000
// assert_eq!(SubnetAlphaOut::<Test>::get(netuid_0), 4 * stake_amount); // Root has everything.
// assert_eq!(SubnetAlphaOut::<Test>::get(netuid_1), 0); // No stake outstanding.
// // Assert share information for hotkey1 on netuid_0
// assert_eq!(
// TotalHotkeyShares::<Test>::get(hotkey1, netuid_0),
// 2 * stake_amount
// ); // Shares
// // Assert no shares for hotkey1 on netuid_1
// assert_eq!(TotalHotkeyShares::<Test>::get(hotkey1, netuid_1), 0); // No shares
// // Assert alpha for hotkey1 on netuid_0
// assert_eq!(
// TotalHotkeyAlpha::<Test>::get(hotkey1, netuid_0),
// 2 * stake_amount
// ); // Alpha
// // Assert no alpha for hotkey1 on netuid_1
// assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey1, netuid_1), 0); // No alpha.
// // Assert share information for hotkey2 on netuid_0
// assert_eq!(
// TotalHotkeyShares::<Test>::get(hotkey2, netuid_0),
// 2 * stake_amount
// ); // Shares
// // Assert no shares for hotkey2 on netuid_1
// assert_eq!(TotalHotkeyShares::<Test>::get(hotkey2, netuid_1), 0); // No shares
// // Assert alpha for hotkey2 on netuid_0
// assert_eq!(
// TotalHotkeyAlpha::<Test>::get(hotkey2, netuid_0),
// 2 * stake_amount
// ); // Alpha
// // Assert no alpha for hotkey2 on netuid_1
// assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey2, netuid_1), 0); // No alpha.
// // Assert stake balances for hotkey1 and coldkey1 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey1, &coldkey1, netuid_0
// ),
// stake_amount
// );
// // Assert stake balances for hotkey1 and coldkey2 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey1, &coldkey2, netuid_0
// ),
// stake_amount
// );
// // Assert stake balances for hotkey2 and coldkey2 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey2, &coldkey2, netuid_0
// ),
// stake_amount
// );
// // Assert stake balances for hotkey2 and coldkey3 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey2, &coldkey3, netuid_0
// ),
// stake_amount
// );
// // Assert total stake for hotkey1 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey1, netuid_0),
// 2 * stake_amount
// );
// // Assert total stake for hotkey2 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey2, netuid_0),
// 2 * stake_amount
// );
// // Increase stake for hotkey1 and coldkey1 on netuid_0
// SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey1,
// &coldkey1,
// netuid_0,
// stake_amount,
// );
// // Assert updated stake for hotkey1 and coldkey1 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey1, &coldkey1, netuid_0
// ),
// 2 * stake_amount
// );
// // Assert updated total stake for hotkey1 on netuid_0
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey1, netuid_0),
// 3 * stake_amount
// );
// // Increase stake for hotkey1 and coldkey1 on netuid_1
// SubtensorModule::increase_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey1,
// &coldkey1,
// netuid_1,
// stake_amount,
// );
// // Assert updated stake for hotkey1 and coldkey1 on netuid_1
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_and_coldkey_on_subnet(
// &hotkey1, &coldkey1, netuid_1
// ),
// stake_amount
// );
// // Assert updated total stake for hotkey1 on netuid_1
// assert_eq!(
// SubtensorModule::get_stake_for_hotkey_on_subnet(&hotkey1, netuid_1),
// stake_amount
// );
// // Run the coinbase
// let emission: u64 = 1_000_000_000;
// SubtensorModule::run_coinbase(I96F32::from_num(emission));
// close(
// SubnetTaoInEmission::<Test>::get(netuid_1),
// emission / 6,
// 100,
// );
// close(
// SubnetTaoInEmission::<Test>::get(netuid_2),
// 2 * (emission / 6),
// 100,
// );
// close(
// SubnetTaoInEmission::<Test>::get(netuid_3),
// 3 * (emission / 6),
// 100,
// );
// });
// }
// SKIP_WASM_BUILD=1 RUST_LOG=debug cargo test --package pallet-subtensor --lib -- tests::migration::test_migrate_subnet_volume --exact --show-output
#[test]
fn test_migrate_subnet_volume() {
new_test_ext(1).execute_with(|| {
// Setup initial state
let netuid_1 = NetUid::from(1);
add_network(netuid_1, 1, 0);
// SubnetValue for netuid 1 key
let old_key: [u8; 34] = hex_literal::hex!(
"658faa385070e074c85bf6b568cf05553c3226e141696000b4b239c65bc2b2b40100"
);
// Old value in u64 format
let old_value: u64 = 123_456_789_000_u64;
put::<u64>(&old_key, &old_value); // Store as u64
// Ensure it is stored as `u64`
assert_eq!(get::<u64>(&old_key), Some(old_value));
// Run migration
crate::migrations::migrate_subnet_volume::migrate_subnet_volume::<Test>();
// Verify the value is now stored as `u128`
let new_value: Option<u128> = get(&old_key);
let new_value_as_subnet_volume = SubnetVolume::<Test>::get(netuid_1);
assert_eq!(new_value, Some(old_value as u128));
assert_eq!(new_value_as_subnet_volume, old_value as u128);
// Ensure migration does not break when running twice
let weight_second_run =
crate::migrations::migrate_subnet_volume::migrate_subnet_volume::<Test>();
// Verify the value is still stored as `u128`
let new_value: Option<u128> = get(&old_key);
assert_eq!(new_value, Some(old_value as u128));
});
}
#[test]
fn test_migrate_set_first_emission_block_number() {
new_test_ext(1).execute_with(|| {
let netuids: [NetUid; 3] = [1.into(), 2.into(), 3.into()];
let block_number = 100;
for netuid in netuids.iter() {
add_network(*netuid, 1, 0);
}
run_to_block(block_number);
let weight = crate::migrations::migrate_set_first_emission_block_number::migrate_set_first_emission_block_number::<Test>();
let expected_weight: Weight = <Test as Config>::DbWeight::get().reads(3) + <Test as Config>::DbWeight::get().writes(netuids.len() as u64);
assert_eq!(weight, expected_weight);
assert_eq!(FirstEmissionBlockNumber::<Test>::get(NetUid::ROOT), None);
for netuid in netuids.iter() {
assert_eq!(FirstEmissionBlockNumber::<Test>::get(netuid), Some(block_number));
}
});
}
#[test]
fn test_migrate_set_subtoken_enable() {
new_test_ext(1).execute_with(|| {
let netuids: [NetUid; 3] = [1.into(), 2.into(), 3.into()];
let block_number = 100;
for netuid in netuids.iter() {
add_network(*netuid, 1, 0);
}
let new_netuid = NetUid::from(4);
add_network_without_emission_block(new_netuid, 1, 0);
let weight =
crate::migrations::migrate_set_subtoken_enabled::migrate_set_subtoken_enabled::<Test>();
let expected_weight: Weight = <Test as Config>::DbWeight::get().reads(1)
+ <Test as Config>::DbWeight::get().writes(netuids.len() as u64 + 2);
assert_eq!(weight, expected_weight);
for netuid in netuids.iter() {
assert!(SubtokenEnabled::<Test>::get(netuid));
}
assert!(!SubtokenEnabled::<Test>::get(new_netuid));
});
}
#[test]
fn test_migrate_remove_zero_total_hotkey_alpha() {
new_test_ext(1).execute_with(|| {
const MIGRATION_NAME: &str = "migrate_remove_zero_total_hotkey_alpha";
let netuid = NetUid::from(1u16);
let hotkey_zero = U256::from(100u64);
let hotkey_nonzero = U256::from(101u64);
// Insert one zero-alpha entry and one non-zero entry
TotalHotkeyAlpha::<Test>::insert(hotkey_zero, netuid, AlphaBalance::ZERO);
TotalHotkeyAlpha::<Test>::insert(hotkey_nonzero, netuid, AlphaBalance::from(123));
assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey_zero, netuid), AlphaBalance::ZERO);
assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey_nonzero, netuid), AlphaBalance::from(123));
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet."
);
let weight = crate::migrations::migrate_remove_zero_total_hotkey_alpha::migrate_remove_zero_total_hotkey_alpha::<Test>();
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as run."
);
assert!(
!TotalHotkeyAlpha::<Test>::contains_key(hotkey_zero, netuid),
"Zero-alpha entry should have been removed."
);
assert_eq!(TotalHotkeyAlpha::<Test>::get(hotkey_nonzero, netuid), AlphaBalance::from(123));
assert!(
!weight.is_zero(),
"Migration weight should be non-zero."
);
});
}
#[test]
fn test_migrate_revealed_commitments() {
new_test_ext(1).execute_with(|| {
// --------------------------------
// Step 1: Simulate Old Storage Entries
// --------------------------------
const MIGRATION_NAME: &str = "migrate_revealed_commitments_v2";
// Pallet prefix == twox_128("Commitments")
let pallet_prefix = twox_128("Commitments".as_bytes());
// Storage item prefix == twox_128("RevealedCommitments")
let storage_prefix = twox_128("RevealedCommitments".as_bytes());
// Example keys for the DoubleMap:
// Key1 (netuid) uses Identity (no hash)
// Key2 (account) uses Twox64Concat
let netuid = NetUid::from(123);
let account_id: u64 = 999; // Or however your test `AccountId` is represented
// Construct the full storage key for `RevealedCommitments(netuid, account_id)`
let mut storage_key = Vec::new();
storage_key.extend_from_slice(&pallet_prefix);
storage_key.extend_from_slice(&storage_prefix);
// Identity for netuid => no hashing, just raw encode
storage_key.extend_from_slice(&netuid.encode());
// Twox64Concat for account
let account_hashed = Twox64Concat::hash(&account_id.encode());
storage_key.extend_from_slice(&account_hashed);
// Simulate an old value we might have stored:
// For example, the old type was `RevealedData<Balance, ...>`
// We'll just store a random encoded value for demonstration
let old_value = (vec![1, 2, 3, 4], 42u64);
put_raw(&storage_key, &old_value.encode());
// Confirm the storage value is set
let stored_value = get_raw(&storage_key).expect("Expected to get a value");
let decoded_value = <(Vec<u8>, u64)>::decode(&mut &stored_value[..])
.expect("Failed to decode the old revealed commitments");
assert_eq!(decoded_value, old_value);
// Also confirm that the migration has NOT run yet
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet"
);
// --------------------------------
// Step 2: Run the Migration
// --------------------------------
let weight = crate::migrations::migrate_upgrade_revealed_commitments::migrate_upgrade_revealed_commitments::<Test>();
// Migration should be marked as run
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should now be marked as run"
);
// --------------------------------
// Step 3: Verify Migration Effects
// --------------------------------
// The old key/value should be removed
let stored_value_after = get_raw(&storage_key);
assert!(
stored_value_after.is_none(),
"Old storage entry should be cleared"
);
// Weight returned should be > 0 (some cost was incurred clearing storage)
assert!(!weight.is_zero(), "Migration weight should be non-zero");
});
}
#[test]
fn test_migrate_remove_total_hotkey_coldkey_stakes_this_interval() {
new_test_ext(1).execute_with(|| {
const MIGRATION_NAME: &str = "migrate_remove_total_hotkey_coldkey_stakes_this_interval";
let pallet_name = twox_128(b"SubtensorModule");
let storage_name = twox_128(b"TotalHotkeyColdkeyStakesThisInterval");
let prefix = [pallet_name, storage_name].concat();
// Set up 200 000 entries to be deleted.
for i in 0..200_000{
let hotkey = U256::from(i as u64);
let coldkey = U256::from(i as u64);
let key = [prefix.clone(), hotkey.encode(), coldkey.encode()].concat();
let value = (100 + i, 200 + i);
put_raw(&key, &value.encode());
}
assert!(frame_support::storage::unhashed::contains_prefixed_key(&prefix), "Entries should exist before migration.");
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet."
);
// Run migration
let weight = crate::migrations::migrate_remove_total_hotkey_coldkey_stakes_this_interval::migrate_remove_total_hotkey_coldkey_stakes_this_interval::<Test>();
assert!(!frame_support::storage::unhashed::contains_prefixed_key(&prefix), "All entries should have been removed.");
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as run."
);
assert!(!weight.is_zero(),"Migration weight should be non-zero.");
});
}
fn test_migrate_remove_last_hotkey_coldkey_emission_on_netuid() {
const MIGRATION_NAME: &str = "migrate_remove_last_hotkey_coldkey_emission_on_netuid";
let pallet_name = "SubtensorModule";
let storage_name = "LastHotkeyColdkeyEmissionOnNetuid";
let migration = crate::migrations::migrate_orphaned_storage_items::remove_last_hotkey_coldkey_emission_on_netuid::<Test>;
test_remove_storage_item(
MIGRATION_NAME,
pallet_name,
storage_name,
migration,
200_000,
);
}
#[test]
fn test_migrate_remove_subnet_alpha_emission_sell() {
const MIGRATION_NAME: &str = "migrate_remove_subnet_alpha_emission_sell";
let pallet_name = "SubtensorModule";
let storage_name = "SubnetAlphaEmissionSell";
let migration =
crate::migrations::migrate_orphaned_storage_items::remove_subnet_alpha_emission_sell::<Test>;
test_remove_storage_item(
MIGRATION_NAME,
pallet_name,
storage_name,
migration,
200_000,
);
}
#[test]
fn test_migrate_remove_neurons_to_prune_at_next_epoch() {
const MIGRATION_NAME: &str = "migrate_remove_neurons_to_prune_at_next_epoch";
let pallet_name = "SubtensorModule";
let storage_name = "NeuronsToPruneAtNextEpoch";
let migration =
crate::migrations::migrate_orphaned_storage_items::remove_neurons_to_prune_at_next_epoch::<
Test,
>;
test_remove_storage_item(
MIGRATION_NAME,
pallet_name,
storage_name,
migration,
200_000,
);
}
#[test]
fn test_migrate_remove_total_stake_at_dynamic() {
const MIGRATION_NAME: &str = "migrate_remove_total_stake_at_dynamic";
let pallet_name = "SubtensorModule";
let storage_name = "TotalStakeAtDynamic";
let migration =
crate::migrations::migrate_orphaned_storage_items::remove_total_stake_at_dynamic::<Test>;
test_remove_storage_item(
MIGRATION_NAME,
pallet_name,
storage_name,
migration,
200_000,
);
}
#[test]
fn test_migrate_remove_subnet_name() {
const MIGRATION_NAME: &str = "migrate_remove_subnet_name";
let pallet_name = "SubtensorModule";
let storage_name = "SubnetName";
let migration = crate::migrations::migrate_orphaned_storage_items::remove_subnet_name::<Test>;
test_remove_storage_item(
MIGRATION_NAME,
pallet_name,
storage_name,
migration,
200_000,
);
}
#[test]
fn test_migrate_remove_network_min_allowed_uids() {
const MIGRATION_NAME: &str = "migrate_remove_network_min_allowed_uids";
let pallet_name = "SubtensorModule";
let storage_name = "NetworkMinAllowedUids";
let migration =
crate::migrations::migrate_orphaned_storage_items::remove_network_min_allowed_uids::<Test>;
test_remove_storage_item(MIGRATION_NAME, pallet_name, storage_name, migration, 1);
}
#[test]
fn test_migrate_remove_dynamic_block() {
const MIGRATION_NAME: &str = "migrate_remove_dynamic_block";
let pallet_name = "SubtensorModule";
let storage_name = "DynamicBlock";
let migration = crate::migrations::migrate_orphaned_storage_items::remove_dynamic_block::<Test>;
test_remove_storage_item(MIGRATION_NAME, pallet_name, storage_name, migration, 1);
}
#[allow(clippy::arithmetic_side_effects)]
fn test_remove_storage_item<F: FnOnce() -> Weight>(
migration_name: &'static str,
pallet_name: &'static str,
storage_name: &'static str,
migration: F,
test_entries_number: i32,
) {
new_test_ext(1).execute_with(|| {
let pallet_name = twox_128(pallet_name.as_bytes());
let storage_name = twox_128(storage_name.as_bytes());
let prefix = [pallet_name, storage_name].concat();
// Set up entries to be deleted.
for i in 0..test_entries_number {
let hotkey = U256::from(i as u64);
let coldkey = U256::from(i as u64);
let key = [prefix.clone(), hotkey.encode(), coldkey.encode()].concat();
let value = (100 + i, 200 + i);
put_raw(&key, &value.encode());
}
assert!(
frame_support::storage::unhashed::contains_prefixed_key(&prefix),
"Entries should exist before migration."
);
assert!(
!HasMigrationRun::<Test>::get(migration_name.as_bytes().to_vec()),
"Migration should not have run yet."
);
// Run migration
let weight = migration();
assert!(
!frame_support::storage::unhashed::contains_prefixed_key(&prefix),
"All entries should have been removed."
);
assert!(
HasMigrationRun::<Test>::get(migration_name.as_bytes().to_vec()),
"Migration should be marked as run."
);
assert!(!weight.is_zero(), "Migration weight should be non-zero.");
});
}
#[test]
fn test_migrate_remove_commitments_rate_limit() {
new_test_ext(1).execute_with(|| {
// ------------------------------
// Step 1: Simulate Old Storage Entry
// ------------------------------
const MIGRATION_NAME: &str = "migrate_remove_commitments_rate_limit";
// Build the raw storage key: twox128("Commitments") ++ twox128("RateLimit")
let pallet_prefix = twox_128("Commitments".as_bytes());
let storage_prefix = twox_128("RateLimit".as_bytes());
let mut key = Vec::new();
key.extend_from_slice(&pallet_prefix);
key.extend_from_slice(&storage_prefix);
let original_value: u64 = 123;
put_raw(&key, &original_value.encode());
let stored_before = get_raw(&key).expect("Expected RateLimit to exist");
assert_eq!(
u64::decode(&mut &stored_before[..]).expect("Failed to decode RateLimit"),
original_value
);
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet"
);
// ------------------------------
// Step 2: Run the Migration
// ------------------------------
let weight = crate::migrations::migrate_remove_commitments_rate_limit::
migrate_remove_commitments_rate_limit::<Test>();
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as completed"
);
// ------------------------------
// Step 3: Verify Migration Effects
// ------------------------------
assert!(
get_raw(&key).is_none(),
"RateLimit storage should have been cleared"
);
assert!(!weight.is_zero(), "Migration weight should be non-zero");
});
}
#[test]
fn test_migrate_network_last_registered() {
new_test_ext(1).execute_with(|| {
// ------------------------------
// Step 1: Simulate Old Storage Entry
// ------------------------------
const MIGRATION_NAME: &str = "migrate_network_last_registered";
let pallet_name = "SubtensorModule";
let storage_name = "NetworkLastRegistered";
let pallet_name_hash = twox_128(pallet_name.as_bytes());
let storage_name_hash = twox_128(storage_name.as_bytes());
let prefix = [pallet_name_hash, storage_name_hash].concat();
let mut full_key = prefix.clone();
let original_value: u64 = 123;
put_raw(&full_key, &original_value.encode());
let stored_before = get_raw(&full_key).expect("Expected RateLimit to exist");
assert_eq!(
u64::decode(&mut &stored_before[..]).expect("Failed to decode RateLimit"),
original_value
);
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet"
);
// ------------------------------
// Step 2: Run the Migration
// ------------------------------
let weight = crate::migrations::migrate_rate_limiting_last_blocks::
migrate_obsolete_rate_limiting_last_blocks_storage::<Test>();
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as completed"
);
// ------------------------------
// Step 3: Verify Migration Effects
// ------------------------------
assert_eq!(
SubtensorModule::get_network_last_lock_block(),
original_value
);
assert_eq!(
get_raw(&full_key),
None,
"RateLimit storage should have been cleared"
);
assert!(!weight.is_zero(), "Migration weight should be non-zero");
});
}
#[allow(deprecated)]
#[test]
fn test_migrate_last_block_tx() {
new_test_ext(1).execute_with(|| {
// ------------------------------
// Step 1: Simulate Old Storage Entry
// ------------------------------
const MIGRATION_NAME: &str = "migrate_last_tx_block";
let test_account: U256 = U256::from(1);
let original_value: u64 = 123;
LastTxBlock::<Test>::insert(test_account, original_value);
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet"
);
// ------------------------------
// Step 2: Run the Migration
// ------------------------------
let weight = crate::migrations::migrate_rate_limiting_last_blocks::
migrate_obsolete_rate_limiting_last_blocks_storage::<Test>();
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as completed"
);
// ------------------------------
// Step 3: Verify Migration Effects
// ------------------------------
assert_eq!(
SubtensorModule::get_last_tx_block(&test_account),
original_value
);
assert!(
!LastTxBlock::<Test>::contains_key(test_account),
"RateLimit storage should have been cleared"
);
assert!(!weight.is_zero(), "Migration weight should be non-zero");
});
}
#[allow(deprecated)]
#[test]
fn test_migrate_last_tx_block_childkey_take() {
new_test_ext(1).execute_with(|| {
// ------------------------------
// Step 1: Simulate Old Storage Entry
// ------------------------------
const MIGRATION_NAME: &str = "migrate_last_tx_block_childkey_take";
let test_account: U256 = U256::from(1);
let original_value: u64 = 123;
LastTxBlockChildKeyTake::<Test>::insert(test_account, original_value);
assert!(
!HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should not have run yet"
);
// ------------------------------
// Step 2: Run the Migration
// ------------------------------
let weight = crate::migrations::migrate_rate_limiting_last_blocks::
migrate_obsolete_rate_limiting_last_blocks_storage::<Test>();
assert!(
HasMigrationRun::<Test>::get(MIGRATION_NAME.as_bytes().to_vec()),
"Migration should be marked as completed"
);
// ------------------------------
// Step 3: Verify Migration Effects
// ------------------------------
assert_eq!(
SubtensorModule::get_last_tx_block_childkey_take(&test_account),
original_value
);
assert!(
!LastTxBlockChildKeyTake::<Test>::contains_key(test_account),
"RateLimit storage should have been cleared"
);
assert!(!weight.is_zero(), "Migration weight should be non-zero");
});
}
#[allow(deprecated)]
#[test]
fn test_migrate_last_tx_block_delegate_take() {
new_test_ext(1).execute_with(|| {
// ------------------------------
// Step 1: Simulate Old Storage Entry
// ------------------------------
const MIGRATION_NAME: &str = "migrate_last_tx_block_delegate_take";
let test_account: U256 = U256::from(1);