Skip to content

Commit 7f5bd9d

Browse files
authored
Merge pull request #1036 from opentensor/chore/cleanup-pallet-subtensor
Remove dead code in pallet-subtensor
2 parents 4914867 + 6bb1afe commit 7f5bd9d

File tree

11 files changed

+85
-155
lines changed

11 files changed

+85
-155
lines changed

pallets/subtensor/src/coinbase/root.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -301,8 +301,9 @@ impl<T: Config> Pallet<T> {
301301

302302
/// Checks if registrations are allowed for a given subnet.
303303
///
304-
/// This function retrieves the subnet hyperparameters for the specified subnet and checks the `registration_allowed` flag.
305-
/// If the subnet doesn't exist or doesn't have hyperparameters defined, it returns `false`.
304+
/// This function retrieves the subnet hyperparameters for the specified subnet and checks the
305+
/// `registration_allowed` flag. If the subnet doesn't exist or doesn't have hyperparameters
306+
/// defined, it returns `false`.
306307
///
307308
/// # Arguments
308309
///

pallets/subtensor/src/coinbase/run_coinbase.rs

+15-13
Original file line numberDiff line numberDiff line change
@@ -20,28 +20,30 @@ pub struct WeightsTlockPayload {
2020
impl<T: Config> Pallet<T> {
2121
/// The `coinbase` function performs a four-part emission distribution process involving
2222
/// subnets, epochs, hotkeys, and nominators.
23+
///
2324
/// It is divided into several steps, each handling a specific part of the distribution:
2425
///
2526
/// Step 1: Compute the block-wise emission for each subnet.
26-
/// This involves calculating how much (TAO) should be emitted into each subnet using the
27-
/// root epoch function.
27+
/// This involves calculating how much (TAO) should be emitted into each subnet using the root
28+
/// epoch function.
2829
///
2930
/// Step 2: Accumulate the subnet block emission.
30-
/// After calculating the block-wise emission, these values are accumulated to keep track
31-
/// of how much each subnet should emit before the next distribution phase. This accumulation
32-
/// is a running total that gets updated each block.
31+
/// After calculating the block-wise emission, these values are accumulated to keep track of how
32+
/// much each subnet should emit before the next distribution phase. This accumulation is a
33+
/// running total that gets updated each block.
3334
///
3435
/// Step 3: Distribute the accumulated emissions through epochs.
35-
/// Subnets periodically distribute their accumulated emissions to hotkeys (active validators/miners)
36-
/// in the network on a `tempo` --- the time between epochs. This step runs Yuma consensus to
37-
/// determine how emissions are split among hotkeys based on their contributions and roles.
38-
/// The accumulation of hotkey emissions is done through the `accumulate_hotkey_emission` function.
39-
/// The function splits the rewards for a hotkey amongst itself and its `parents`. The parents are
40-
/// the hotkeys that are delegating their stake to the hotkey.
36+
/// Subnets periodically distribute their accumulated emissions to hotkeys (active
37+
/// validators/miners) in the network on a `tempo` --- the time between epochs. This step runs
38+
/// Yuma consensus to determine how emissions are split among hotkeys based on their
39+
/// contributions and roles. The accumulation of hotkey emissions is done through the
40+
/// `accumulate_hotkey_emission` function. The function splits the rewards for a hotkey amongst
41+
/// itself and its `parents`. The parents are the hotkeys that are delegating their stake to the
42+
/// hotkey.
4143
///
4244
/// Step 4: Further distribute emissions from hotkeys to nominators.
43-
/// Finally, the emissions received by hotkeys are further distributed to their nominators,
44-
/// who are stakeholders that support the hotkeys.
45+
/// Finally, the emissions received by hotkeys are further distributed to their nominators, who
46+
/// are stakeholders that support the hotkeys.
4547
pub fn run_coinbase() {
4648
// --- 0. Get current block.
4749
let current_block: u64 = Self::get_current_block_as_u64();

pallets/subtensor/src/epoch/run_epoch.rs

-12
Original file line numberDiff line numberDiff line change
@@ -803,18 +803,6 @@ impl<T: Config> Pallet<T> {
803803
I32F32::from_num(Self::get_kappa(netuid)).saturating_div(I32F32::from_num(u16::MAX))
804804
}
805805

806-
pub fn get_normalized_stake(netuid: u16) -> Vec<I32F32> {
807-
let n = Self::get_subnetwork_n(netuid);
808-
let mut stake_64: Vec<I64F64> = (0..n)
809-
.map(|neuron_uid| {
810-
I64F64::from_num(Self::get_stake_for_uid_and_subnetwork(netuid, neuron_uid))
811-
})
812-
.collect();
813-
inplace_normalize_64(&mut stake_64);
814-
let stake: Vec<I32F32> = vec_fixed64_to_fixed32(stake_64);
815-
stake
816-
}
817-
818806
pub fn get_block_at_registration(netuid: u16) -> Vec<u64> {
819807
let n = Self::get_subnetwork_n(netuid);
820808
let block_at_registration: Vec<u64> = (0..n)

pallets/subtensor/src/macros/errors.rs

+22-33
Original file line numberDiff line numberDiff line change
@@ -22,33 +22,42 @@ mod errors {
2222
HotKeyAccountNotExists,
2323
/// The hotkey is not registered in any subnet.
2424
HotKeyNotRegisteredInNetwork,
25-
/// Request to stake, unstake or subscribe is made by a coldkey that is not associated with the hotkey account.
25+
/// Request to stake, unstake or subscribe is made by a coldkey that is not associated with
26+
/// the hotkey account.
2627
NonAssociatedColdKey,
2728
/// The hotkey is not a delegate and the signer is not the owner of the hotkey.
2829
HotKeyNotDelegateAndSignerNotOwnHotKey,
2930
/// Stake amount to withdraw is zero.
3031
StakeToWithdrawIsZero,
31-
/// The caller is requesting removing more stake than there exists in the staking account. See: "[remove_stake()]".
32+
/// The caller is requesting removing more stake than there exists in the staking account.
33+
/// See: "[remove_stake()]".
3234
NotEnoughStakeToWithdraw,
33-
/// The caller is requesting to set weights but the caller has less than minimum stake required to set weights (less than WeightsMinStake).
35+
/// The caller is requesting to set weights but the caller has less than minimum stake
36+
/// required to set weights (less than WeightsMinStake).
3437
NotEnoughStakeToSetWeights,
35-
/// The caller is requesting adding more stake than there exists in the coldkey account. See: "[add_stake()]"
38+
/// The caller is requesting adding more stake than there exists in the coldkey account.
39+
/// See: "[add_stake()]"
3640
NotEnoughBalanceToStake,
37-
/// The caller is trying to add stake, but for some reason the requested amount could not be withdrawn from the coldkey account.
41+
/// The caller is trying to add stake, but for some reason the requested amount could not be
42+
/// withdrawn from the coldkey account.
3843
BalanceWithdrawalError,
39-
/// Unsuccessfully withdraw, balance could be zero (can not make account exist) after withdrawal.
44+
/// Unsuccessfully withdraw, balance could be zero (can not make account exist) after
45+
/// withdrawal.
4046
ZeroBalanceAfterWithdrawn,
4147
/// The caller is attempting to set non-self weights without being a permitted validator.
4248
NeuronNoValidatorPermit,
43-
/// The caller is attempting to set the weight keys and values but these vectors have different size.
49+
/// The caller is attempting to set the weight keys and values but these vectors have
50+
/// different size.
4451
WeightVecNotEqualSize,
4552
/// The caller is attempting to set weights with duplicate UIDs in the weight matrix.
4653
DuplicateUids,
47-
/// The caller is attempting to set weight to at least one UID that does not exist in the metagraph.
54+
/// The caller is attempting to set weight to at least one UID that does not exist in the
55+
/// metagraph.
4856
UidVecContainInvalidOne,
4957
/// The dispatch is attempting to set weights on chain with fewer elements than are allowed.
5058
WeightVecLengthIsLow,
51-
/// Number of registrations in this block exceeds the allowed number (i.e., exceeds the subnet hyperparameter "max_regs_per_block").
59+
/// Number of registrations in this block exceeds the allowed number (i.e., exceeds the
60+
/// subnet hyperparameter "max_regs_per_block").
5261
TooManyRegistrationsThisBlock,
5362
/// The caller is requesting registering a neuron which already exists in the active set.
5463
HotKeyAlreadyRegisteredInSubNet,
@@ -60,7 +69,8 @@ mod errors {
6069
InvalidDifficulty,
6170
/// The supplied PoW hash seal does not match the supplied work.
6271
InvalidSeal,
63-
/// The dispatch is attempting to set weights on chain with weight value exceeding the MaxWeightLimit (max_weight_limit subnet hyperparameter).
72+
/// The dispatch is attempting to set weights on chain with weight value exceeding the
73+
/// MaxWeightLimit (max_weight_limit subnet hyperparameter).
6474
MaxWeightExceeded,
6575
/// The hotkey is attempting to become a delegate when the hotkey is already a delegate.
6676
HotKeyAlreadyDelegate,
@@ -114,7 +124,8 @@ mod errors {
114124
DelegateTakeTooLow,
115125
/// Delegate take is too high.
116126
DelegateTakeTooHigh,
117-
/// No commit found for the provided hotkey+netuid combination when attempting to reveal the weights.
127+
/// No commit found for the provided hotkey+netuid combination when attempting to reveal the
128+
/// weights.
118129
NoWeightsCommitFound,
119130
/// Committed hash does not equal the hashed reveal data.
120131
InvalidRevealCommitHashNotMatch,
@@ -132,28 +143,10 @@ mod errors {
132143
AlphaLowOutOfRange,
133144
/// The coldkey has already been swapped
134145
ColdKeyAlreadyAssociated,
135-
/// The coldkey swap transaction rate limit exceeded
136-
ColdKeySwapTxRateLimitExceeded,
137-
/// The new coldkey is the same as the old coldkey
138-
NewColdKeyIsSameWithOld,
139-
/// The coldkey does not exist
140-
NotExistColdkey,
141146
/// The coldkey balance is not enough to pay for the swap
142147
NotEnoughBalanceToPaySwapColdKey,
143-
/// No balance to transfer
144-
NoBalanceToTransfer,
145-
/// Same coldkey
146-
SameColdkey,
147148
/// The coldkey is in arbitration
148149
ColdkeyIsInArbitration,
149-
/// The new coldkey is already registered for the drain
150-
DuplicateColdkey,
151-
/// Error thrown on a coldkey swap.
152-
ColdkeySwapError,
153-
/// Insufficient Balance to Schedule coldkey swap
154-
InsufficientBalanceToPerformColdkeySwap,
155-
/// The maximum number of coldkey destinations has been reached
156-
MaxColdkeyDestinationsReached,
157150
/// Attempting to set an invalid child for a hotkey on a network.
158151
InvalidChild,
159152
/// Duplicate child when setting children.
@@ -164,16 +157,12 @@ mod errors {
164157
TooManyChildren,
165158
/// Default transaction rate limit exceeded.
166159
TxRateLimitExceeded,
167-
/// Swap coldkey only callable by root.
168-
SwapColdkeyOnlyCallableByRoot,
169160
/// Swap already scheduled.
170161
SwapAlreadyScheduled,
171162
/// failed to swap coldkey
172163
FailedToSchedule,
173164
/// New coldkey is hotkey
174165
NewColdKeyIsHotkey,
175-
/// New coldkey is in arbitration
176-
NewColdkeyIsInArbitration,
177166
/// Childkey take is invalid.
178167
InvalidChildkeyTake,
179168
/// Childkey take rate limit exceeded.

pallets/subtensor/src/rpc_info/delegate_info.rs

-14
Original file line numberDiff line numberDiff line change
@@ -156,20 +156,6 @@ impl<T: Config> Pallet<T> {
156156
total_delegated
157157
}
158158

159-
// Helper function to get total delegated stake for a hotkey
160-
pub fn get_total_hotkey_delegated_stake(hotkey: &T::AccountId) -> u64 {
161-
let mut total_delegated = 0u64;
162-
163-
// Iterate through all delegators for this hotkey
164-
for (delegator, stake) in Stake::<T>::iter_prefix(hotkey) {
165-
if delegator != Self::get_coldkey_for_hotkey(hotkey) {
166-
total_delegated = total_delegated.saturating_add(stake);
167-
}
168-
}
169-
170-
total_delegated
171-
}
172-
173159
// Helper function to get the coldkey associated with a hotkey
174160
pub fn get_coldkey_for_hotkey(hotkey: &T::AccountId) -> T::AccountId {
175161
Owner::<T>::get(hotkey)

pallets/subtensor/src/staking/helpers.rs

+1-8
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use frame_support::{
33
storage::IterableStorageDoubleMap,
44
traits::{
55
tokens::{
6-
fungible::{Balanced as _, Inspect as _, Mutate as _},
6+
fungible::{Balanced as _, Inspect as _},
77
Fortitude, Precision, Preservation,
88
},
99
Imbalance,
@@ -341,13 +341,6 @@ impl<T: Config> Pallet<T> {
341341
let _ = T::Currency::deposit(coldkey, amount, Precision::BestEffort);
342342
}
343343

344-
pub fn set_balance_on_coldkey_account(
345-
coldkey: &T::AccountId,
346-
amount: <<T as Config>::Currency as fungible::Inspect<<T as system::Config>::AccountId>>::Balance,
347-
) {
348-
T::Currency::set_balance(coldkey, amount);
349-
}
350-
351344
pub fn can_remove_balance_from_coldkey_account(
352345
coldkey: &T::AccountId,
353346
amount: <<T as Config>::Currency as fungible::Inspect<<T as system::Config>::AccountId>>::Balance,

pallets/subtensor/src/subnets/serving.rs

-8
Original file line numberDiff line numberDiff line change
@@ -246,14 +246,6 @@ impl<T: Config> Pallet<T> {
246246
rate_limit == 0 || last_serve == 0 || current_block.saturating_sub(last_serve) >= rate_limit
247247
}
248248

249-
pub fn has_axon_info(netuid: u16, hotkey: &T::AccountId) -> bool {
250-
Axons::<T>::contains_key(netuid, hotkey)
251-
}
252-
253-
pub fn has_prometheus_info(netuid: u16, hotkey: &T::AccountId) -> bool {
254-
Prometheus::<T>::contains_key(netuid, hotkey)
255-
}
256-
257249
pub fn get_axon_info(netuid: u16, hotkey: &T::AccountId) -> AxonInfoOf {
258250
if let Some(axons) = Axons::<T>::get(netuid, hotkey) {
259251
axons

pallets/subtensor/src/subnets/uids.rs

-7
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
use super::*;
22
use frame_support::storage::IterableStorageDoubleMap;
3-
use frame_support::storage::IterableStorageMap;
43
use sp_std::vec;
54

65
impl<T: Config> Pallet<T> {
@@ -127,12 +126,6 @@ impl<T: Config> Pallet<T> {
127126
}
128127
}
129128

130-
/// Return the total number of subnetworks available on the chain.
131-
///
132-
pub fn get_number_of_subnets() -> u16 {
133-
<SubnetworkN<T> as IterableStorageMap<u16, u16>>::iter().count() as u16
134-
}
135-
136129
/// Return a list of all networks a hotkey is registered on.
137130
///
138131
pub fn get_registered_networks_for_hotkey(hotkey: &T::AccountId) -> Vec<u16> {

pallets/subtensor/src/tests/epoch.rs

+44-42
Original file line numberDiff line numberDiff line change
@@ -2737,46 +2737,48 @@ fn test_blocks_since_last_step() {
27372737
});
27382738
}
27392739

2740-
// // Map the retention graph for consensus guarantees with an single epoch on a graph with 512 nodes, of which the first 64 are validators, the graph is split into a major and minor set, each setting specific weight on itself and the complement on the other.
2741-
// //
2742-
// // ```import torch
2743-
// // import matplotlib.pyplot as plt
2744-
// // from matplotlib.pyplot import cm
2745-
// // %matplotlib inline
2746-
// //
2747-
// // with open('finney_consensus_0.4.txt') as f: # test output saved to finney_consensus.txt
2748-
// // retention_map = eval(f.read())
2749-
// //
2750-
// // major_ratios = {}
2751-
// // avg_weight_devs = {}
2752-
// // for major_stake, major_weight, minor_weight, avg_weight_dev, major_ratio in retention_map:
2753-
// // major_stake = f'{major_stake:.2f}'
2754-
// // maj, min = int(round(50 * major_weight)), int(round(50 * minor_weight))
2755-
// // avg_weight_devs.setdefault(major_stake, torch.zeros((51, 51)))
2756-
// // avg_weight_devs[major_stake][maj][min] = avg_weight_dev
2757-
// // major_ratios.setdefault(major_stake, torch.zeros((51, 51)))
2758-
// // major_ratios[major_stake][maj][min] = major_ratio
2759-
// //
2760-
// // _x = torch.linspace(0, 1, 51); _y = torch.linspace(0, 1, 51)
2761-
// // x, y = torch.meshgrid(_x, _y, indexing='ij')
2762-
// //
2763-
// // fig = plt.figure(figsize=(6, 6), dpi=70); ax = fig.gca()
2764-
// // ax.set_xticks(torch.arange(0, 1, 0.05)); ax.set_yticks(torch.arange(0, 1., 0.05))
2765-
// // ax.set_xticklabels([f'{_:.2f}'[1:] for _ in torch.arange(0, 1., 0.05)])
2766-
// // plt.grid(); plt.rc('grid', linestyle="dotted", color=[0.85, 0.85, 0.85])
2767-
// //
2768-
// // isolate = ['0.60']; stakes = [0.51, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99]
2769-
// // colors = cm.viridis(torch.linspace(0, 1, len(stakes) + 1))
2770-
// // for i, stake in enumerate(stakes):
2771-
// // contours = plt.contour(x, y, major_ratios[f'{stake:.2f}'], levels=[0., stake], colors=[colors[i + 1]])
2772-
// // if f'{stake:.2f}' in isolate:
2773-
// // contours.collections[1].set_linewidth(3)
2774-
// // plt.clabel(contours, inline=True, fontsize=10)
2775-
// //
2776-
// // plt.title(f'Major emission [$stake_{{maj}}=emission_{{maj}}$ retention lines]')
2777-
// // plt.ylabel('Minor self-weight'); plt.xlabel('Major self-weight'); plt.show()
2778-
// // ```
2779-
// // #[test]
2740+
// Map the retention graph for consensus guarantees with an single epoch on a graph with 512 nodes,
2741+
// of which the first 64 are validators, the graph is split into a major and minor set, each setting
2742+
// specific weight on itself and the complement on the other.
2743+
//
2744+
// ```import torch
2745+
// import matplotlib.pyplot as plt
2746+
// from matplotlib.pyplot import cm
2747+
// %matplotlib inline
2748+
//
2749+
// with open('finney_consensus_0.4.txt') as f: # test output saved to finney_consensus.txt
2750+
// retention_map = eval(f.read())
2751+
//
2752+
// major_ratios = {}
2753+
// avg_weight_devs = {}
2754+
// for major_stake, major_weight, minor_weight, avg_weight_dev, major_ratio in retention_map:
2755+
// major_stake = f'{major_stake:.2f}'
2756+
// maj, min = int(round(50 * major_weight)), int(round(50 * minor_weight))
2757+
// avg_weight_devs.setdefault(major_stake, torch.zeros((51, 51)))
2758+
// avg_weight_devs[major_stake][maj][min] = avg_weight_dev
2759+
// major_ratios.setdefault(major_stake, torch.zeros((51, 51)))
2760+
// major_ratios[major_stake][maj][min] = major_ratio
2761+
//
2762+
// _x = torch.linspace(0, 1, 51); _y = torch.linspace(0, 1, 51)
2763+
// x, y = torch.meshgrid(_x, _y, indexing='ij')
2764+
//
2765+
// fig = plt.figure(figsize=(6, 6), dpi=70); ax = fig.gca()
2766+
// ax.set_xticks(torch.arange(0, 1, 0.05)); ax.set_yticks(torch.arange(0, 1., 0.05))
2767+
// ax.set_xticklabels([f'{_:.2f}'[1:] for _ in torch.arange(0, 1., 0.05)])
2768+
// plt.grid(); plt.rc('grid', linestyle="dotted", color=[0.85, 0.85, 0.85])
2769+
//
2770+
// isolate = ['0.60']; stakes = [0.51, 0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 0.99]
2771+
// colors = cm.viridis(torch.linspace(0, 1, len(stakes) + 1))
2772+
// for i, stake in enumerate(stakes):
2773+
// contours = plt.contour(x, y, major_ratios[f'{stake:.2f}'], levels=[0., stake], colors=[colors[i + 1]])
2774+
// if f'{stake:.2f}' in isolate:
2775+
// contours.collections[1].set_linewidth(3)
2776+
// plt.clabel(contours, inline=True, fontsize=10)
2777+
//
2778+
// plt.title(f'Major emission [$stake_{{maj}}=emission_{{maj}}$ retention lines]')
2779+
// plt.ylabel('Minor self-weight'); plt.xlabel('Major self-weight'); plt.show()
2780+
// ```
2781+
// #[test]
27802782
// fn _map_consensus_guarantees() {
27812783
// let netuid: u16 = 1;
27822784
// let network_n: u16 = 512;
@@ -2811,10 +2813,10 @@ fn test_blocks_since_last_step() {
28112813
// network_n as usize,
28122814
// interleave as usize,
28132815
// );
2814-
2816+
//
28152817
// new_test_ext(1).execute_with(|| {
28162818
// init_run_epochs(netuid, network_n, &validators, &servers, epochs, 1, true, &stake, true, &weights, true, false, 0, true);
2817-
2819+
//
28182820
// let mut major_emission: I64F64 = I64F64::from_num(0);
28192821
// let mut minor_emission: I64F64 = I64F64::from_num(0);
28202822
// for set in vec![major_validators, major_servers] {

pallets/subtensor/src/utils/misc.rs

-3
Original file line numberDiff line numberDiff line change
@@ -424,9 +424,6 @@ impl<T: Config> Pallet<T> {
424424
Self::deposit_event(Event::AdjustmentAlphaSet(netuid, adjustment_alpha));
425425
}
426426

427-
pub fn get_validator_prune_len(netuid: u16) -> u64 {
428-
ValidatorPruneLen::<T>::get(netuid)
429-
}
430427
pub fn set_validator_prune_len(netuid: u16, validator_prune_len: u64) {
431428
ValidatorPruneLen::<T>::insert(netuid, validator_prune_len);
432429
Self::deposit_event(Event::ValidatorPruneLenSet(netuid, validator_prune_len));

0 commit comments

Comments
 (0)