Skip to content

Commit 6684a27

Browse files
committed
Merge remote-tracking branch 'origin/hotfix/sn-to-emit-to' into devnet
2 parents 8237617 + 3a82a73 commit 6684a27

File tree

14 files changed

+663
-61
lines changed

14 files changed

+663
-61
lines changed

evm-tests/test/neuron.precompile.emission-check.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ describe("Test the Neuron precompile with emission", () => {
6363

6464
let i = 0;
6565
while (i < 10) {
66-
const emission = await api.query.SubtensorModule.PendingEmission.getValue(netuid)
66+
const emission = await api.query.SubtensorModule.ServerEmission.getValue(netuid)
6767

6868
console.log("emission is ", emission);
6969
await new Promise((resolve) => setTimeout(resolve, 2000));

evm-tests/test/staking.precompile.reward.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -74,14 +74,14 @@ describe("Test neuron precompile reward", () => {
7474

7575
let index = 0;
7676
while (index < 60) {
77-
const pending = await api.query.SubtensorModule.PendingEmission.getValue(netuid);
77+
const pending = await api.query.SubtensorModule.ValidatorEmission.getValue(netuid);
7878
if (pending > 0) {
7979
console.log("pending amount is ", pending);
8080
break;
8181
}
8282

8383
await new Promise((resolve) => setTimeout(resolve, 1000));
84-
console.log("wait for the pendingEmission update");
84+
console.log("wait for the ValidatorEmission update");
8585
index += 1;
8686
}
8787

pallets/subtensor/src/coinbase/run_coinbase.rs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,9 +31,12 @@ impl<T: Config> Pallet<T> {
3131
.collect();
3232
log::debug!("All subnet netuids: {subnets:?}");
3333

34+
let subnets_to_emit_to: Vec<NetUid> = Self::get_subnets_to_emit_to(&subnets);
35+
log::debug!("Subnets to emit to: {subnets_to_emit_to:?}");
36+
3437
// 2. Get subnets to emit to and emissions
35-
let subnet_emissions = Self::get_subnet_block_emissions(&subnets, block_emission);
36-
let subnets_to_emit_to: Vec<NetUid> = subnet_emissions.keys().copied().collect();
38+
let subnet_emissions =
39+
Self::get_subnet_block_emissions(&subnets_to_emit_to, block_emission);
3740
let root_sell_flag = Self::get_network_root_sell_flag(&subnets_to_emit_to);
3841

3942
// --- 3. Get subnet terms (tao_in, alpha_in, and alpha_out)

pallets/subtensor/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1433,8 +1433,8 @@ pub mod pallet {
14331433
/// --- MAP ( netuid ) --> pending_server_emission
14341434
pub type PendingServerEmission<T> =
14351435
StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha<T>>;
1436-
#[pallet::storage]
14371436
/// --- MAP ( netuid ) --> pending_validator_emission
1437+
#[pallet::storage]
14381438
pub type PendingValidatorEmission<T> =
14391439
StorageMap<_, Identity, NetUid, AlphaCurrency, ValueQuery, DefaultZeroAlpha<T>>;
14401440
/// --- MAP ( netuid ) --> pending_root_alpha_emission

pallets/subtensor/src/macros/hooks.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -72,9 +72,6 @@ mod hooks {
7272
.saturating_add(migrations::migrate_delete_subnet_21::migrate_delete_subnet_21::<T>())
7373
// Storage version v4 -> v5
7474
.saturating_add(migrations::migrate_delete_subnet_3::migrate_delete_subnet_3::<T>())
75-
// Doesn't check storage version. TODO: Remove after upgrade
76-
// Storage version v5 -> v6
77-
.saturating_add(migrations::migrate_total_issuance::migrate_total_issuance::<T>(false))
7875
// Populate OwnedHotkeys map for coldkey swap. Doesn't update storage vesion.
7976
// Storage version v6 -> v7
8077
.saturating_add(migrations::migrate_populate_owned_hotkeys::migrate_populate_owned::<T>())
@@ -163,7 +160,9 @@ mod hooks {
163160
// Re-init tao flows
164161
.saturating_add(migrations::migrate_init_tao_flow::migrate_init_tao_flow::<T>())
165162
// Migrate pending emissions
166-
.saturating_add(migrations::migrate_pending_emissions::migrate_pending_emissions::<T>());
163+
.saturating_add(migrations::migrate_pending_emissions::migrate_pending_emissions::<T>())
164+
// Reset unactive subnets
165+
.saturating_add(migrations::migrate_reset_unactive_sn::migrate_reset_unactive_sn::<T>());
167166
weight
168167
}
169168

Lines changed: 190 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,190 @@
1+
use super::*;
2+
use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet};
3+
4+
use subtensor_swap_interface::SwapHandler;
5+
6+
pub fn get_unactive_sn_netuids<T: Config>(
7+
pool_initial_alpha: AlphaCurrency,
8+
) -> (Vec<NetUid>, Weight) {
9+
// Loop over all subnets, if the AlphaIssuance is > pool_initial_alpha
10+
// but FirstEmissionBlockNumber is None
11+
// then this subnet should be reset
12+
let mut weight = T::DbWeight::get().reads(1);
13+
let unactive_netuids = Pallet::<T>::get_all_subnet_netuids()
14+
.iter()
15+
.filter(|&netuid| !netuid.is_root())
16+
.filter(|&netuid| {
17+
let alpha_issuance = Pallet::<T>::get_alpha_issuance(*netuid);
18+
let first_emission_block_number = FirstEmissionBlockNumber::<T>::get(*netuid);
19+
alpha_issuance != pool_initial_alpha && first_emission_block_number.is_none()
20+
})
21+
.copied()
22+
.collect::<Vec<_>>();
23+
weight = weight
24+
.saturating_add(T::DbWeight::get().reads(unactive_netuids.len().saturating_mul(3) as u64));
25+
26+
(unactive_netuids, weight)
27+
}
28+
29+
pub fn migrate_reset_unactive_sn<T: Config>() -> Weight {
30+
let migration_name = b"migrate_reset_unactive_sn".to_vec();
31+
let mut weight: Weight = T::DbWeight::get().reads(1);
32+
33+
// Skip if already executed
34+
if HasMigrationRun::<T>::get(&migration_name) {
35+
log::info!(
36+
target: "runtime",
37+
"Migration '{}' already run - skipping.",
38+
String::from_utf8_lossy(&migration_name)
39+
);
40+
return weight;
41+
}
42+
log::info!(
43+
"Running migration '{}'",
44+
String::from_utf8_lossy(&migration_name)
45+
);
46+
47+
// From init_new_network
48+
let pool_initial_tao: TaoCurrency = Pallet::<T>::get_network_min_lock();
49+
let pool_initial_alpha: AlphaCurrency = pool_initial_tao.to_u64().into();
50+
51+
let (unactive_netuids, w) = get_unactive_sn_netuids::<T>(pool_initial_alpha);
52+
weight = weight.saturating_add(w);
53+
54+
// Collect the hotkeys to remove for each subnet
55+
let mut to_remove_alpha_hotkeys: BTreeMap<NetUid, Vec<T::AccountId>> = BTreeMap::new();
56+
let mut to_remove_alpha_coldkeys: BTreeMap<NetUid, Vec<(T::AccountId, T::AccountId)>> =
57+
BTreeMap::new();
58+
let mut all_hotkeys_set = BTreeSet::new();
59+
for (hotkey, netuid_i, _) in TotalHotkeyAlpha::<T>::iter() {
60+
weight = weight.saturating_add(T::DbWeight::get().reads(1));
61+
if unactive_netuids.contains(&netuid_i) {
62+
// Only for unactive subnets
63+
to_remove_alpha_hotkeys
64+
.entry(netuid_i)
65+
.or_insert(Vec::new())
66+
.push(hotkey.clone());
67+
all_hotkeys_set.insert(hotkey);
68+
}
69+
}
70+
71+
// Collect the coldkeys to remove for each subnet
72+
for hotkey in all_hotkeys_set.iter() {
73+
for ((coldkey, netuid_i), _) in Alpha::<T>::iter_prefix((&hotkey,)) {
74+
weight = weight.saturating_add(T::DbWeight::get().reads(1));
75+
if unactive_netuids.contains(&netuid_i) {
76+
// Only for unactive subnets
77+
to_remove_alpha_coldkeys
78+
.entry(netuid_i)
79+
.or_insert(Vec::new())
80+
.push((hotkey.clone(), coldkey));
81+
}
82+
}
83+
}
84+
85+
for netuid in unactive_netuids.iter() {
86+
// Reset the subnet as it shouldn't have any emissions
87+
PendingServerEmission::<T>::remove(*netuid);
88+
PendingValidatorEmission::<T>::remove(*netuid);
89+
PendingRootAlphaDivs::<T>::remove(*netuid);
90+
PendingOwnerCut::<T>::remove(*netuid);
91+
SubnetTaoInEmission::<T>::remove(*netuid);
92+
SubnetAlphaInEmission::<T>::remove(*netuid);
93+
SubnetAlphaOutEmission::<T>::remove(*netuid);
94+
weight = weight.saturating_add(T::DbWeight::get().writes(7));
95+
96+
// Reset v3 pool
97+
let burned_tao = match T::SwapInterface::clear_protocol_liquidity(*netuid) {
98+
Ok((_tao, fee_tao, _alpha, _fee_alpha)) => fee_tao,
99+
Err(e) => {
100+
log::error!("Failed to clear protocol liquidity for netuid {netuid:?}: {e:?}");
101+
TaoCurrency::ZERO
102+
}
103+
};
104+
Pallet::<T>::recycle_tao(burned_tao);
105+
// might be based on ticks but this is a rough estimate
106+
weight = weight.saturating_add(T::DbWeight::get().reads_writes(6, 14));
107+
108+
// Recycle already emitted TAO
109+
// or mint 1 TAO to the pool
110+
let subnet_tao = SubnetTAO::<T>::get(*netuid);
111+
if subnet_tao > pool_initial_tao {
112+
let tao_to_recycle = subnet_tao.saturating_sub(pool_initial_tao);
113+
Pallet::<T>::recycle_tao(tao_to_recycle);
114+
TotalStake::<T>::mutate(|total| {
115+
*total = total.saturating_sub(tao_to_recycle);
116+
});
117+
SubnetTAO::<T>::mutate(*netuid, |amount| {
118+
*amount = amount.saturating_sub(tao_to_recycle);
119+
});
120+
weight = weight.saturating_add(T::DbWeight::get().reads_writes(3, 3));
121+
} else if subnet_tao < pool_initial_tao {
122+
let tao_to_add = pool_initial_tao.saturating_sub(subnet_tao);
123+
TotalStake::<T>::mutate(|total| {
124+
*total = total.saturating_add(tao_to_add);
125+
});
126+
SubnetTAO::<T>::mutate(*netuid, |amount| {
127+
*amount = amount.saturating_add(tao_to_add);
128+
});
129+
TotalIssuance::<T>::mutate(|total| {
130+
*total = total.saturating_add(tao_to_add);
131+
});
132+
weight = weight.saturating_add(T::DbWeight::get().reads_writes(3, 3));
133+
}
134+
135+
// Reset pool alpha
136+
SubnetAlphaIn::<T>::insert(*netuid, pool_initial_alpha);
137+
SubnetAlphaOut::<T>::insert(*netuid, AlphaCurrency::ZERO);
138+
// Reset volume
139+
SubnetVolume::<T>::insert(*netuid, 0u128);
140+
weight = weight.saturating_add(T::DbWeight::get().writes(4));
141+
142+
// Reset Alpha stake entries for this subnet
143+
let to_reset: Vec<T::AccountId> = match to_remove_alpha_hotkeys.get(netuid) {
144+
Some(hotkeys) => hotkeys.clone(),
145+
None => Vec::new(),
146+
};
147+
148+
for hotkey in to_reset {
149+
TotalHotkeyAlpha::<T>::remove(&hotkey, *netuid);
150+
TotalHotkeyShares::<T>::remove(&hotkey, *netuid);
151+
TotalHotkeyAlphaLastEpoch::<T>::remove(&hotkey, *netuid);
152+
weight = weight.saturating_add(T::DbWeight::get().writes(3));
153+
154+
// Reset root claimable and claimed
155+
RootClaimable::<T>::mutate(&hotkey, |claimable| {
156+
claimable.remove(netuid);
157+
});
158+
weight = weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));
159+
let removal_result = RootClaimed::<T>::clear_prefix((*netuid, &hotkey), u32::MAX, None);
160+
weight = weight.saturating_add(
161+
T::DbWeight::get()
162+
.reads_writes(removal_result.loops as u64, removal_result.backend as u64),
163+
);
164+
165+
let to_reset_alpha: Vec<(T::AccountId, T::AccountId)> =
166+
match to_remove_alpha_coldkeys.get(netuid) {
167+
Some(coldkeys) => coldkeys.clone(),
168+
None => Vec::new(),
169+
};
170+
for (hotkey, coldkey) in to_reset_alpha {
171+
Alpha::<T>::remove((hotkey, coldkey, netuid));
172+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
173+
}
174+
}
175+
}
176+
177+
// Run total issuance migration
178+
crate::migrations::migrate_init_total_issuance::migrate_init_total_issuance::<T>();
179+
180+
// Mark Migration as Completed
181+
HasMigrationRun::<T>::insert(&migration_name, true);
182+
weight = weight.saturating_add(T::DbWeight::get().writes(1));
183+
184+
log::info!(
185+
"Migration '{:?}' completed successfully.",
186+
String::from_utf8_lossy(&migration_name)
187+
);
188+
189+
weight
190+
}

pallets/subtensor/src/migrations/migrate_total_issuance.rs

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,6 @@ pub fn migrate_total_issuance<T: Config>(test: bool) -> Weight {
5151
T::DbWeight::get().reads((Owner::<T>::iter().count() as u64).saturating_mul(2)),
5252
);
5353

54-
// Calculate the sum of all locked subnet values
55-
let locked_sum = SubnetLocked::<T>::iter().fold(TaoCurrency::ZERO, |acc, (_, locked)| {
56-
acc.saturating_add(locked)
57-
});
58-
// Add weight for reading all subnet locked entries
59-
weight = weight
60-
.saturating_add(T::DbWeight::get().reads(SubnetLocked::<T>::iter().count() as u64));
61-
6254
// Retrieve the total balance sum
6355
let total_balance = <T as Config>::Currency::total_issuance();
6456
// Add weight for reading total issuance
@@ -69,8 +61,7 @@ pub fn migrate_total_issuance<T: Config>(test: bool) -> Weight {
6961
Ok(total_balance_sum) => {
7062
// Compute the total issuance value
7163
let total_issuance_value = stake_sum
72-
.saturating_add(total_balance_sum.into())
73-
.saturating_add(locked_sum.into());
64+
.saturating_add(total_balance_sum.into());
7465

7566
// Update the total issuance in storage
7667
TotalIssuance::<T>::put(total_issuance_value);

pallets/subtensor/src/migrations/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,7 @@ pub mod migrate_remove_unused_maps_and_values;
4141
pub mod migrate_remove_zero_total_hotkey_alpha;
4242
pub mod migrate_reset_bonds_moving_average;
4343
pub mod migrate_reset_max_burn;
44+
pub mod migrate_reset_unactive_sn;
4445
pub mod migrate_set_first_emission_block_number;
4546
pub mod migrate_set_min_burn;
4647
pub mod migrate_set_min_difficulty;
@@ -55,7 +56,6 @@ pub mod migrate_subnet_symbols;
5556
pub mod migrate_subnet_volume;
5657
pub mod migrate_to_v1_separate_emission;
5758
pub mod migrate_to_v2_fixed_total_stake;
58-
pub mod migrate_total_issuance;
5959
pub mod migrate_transfer_ownership_to_foundation;
6060
pub mod migrate_upgrade_revealed_commitments;
6161

0 commit comments

Comments
 (0)