Skip to content

Commit

Permalink
Merge branch 'feat/rao-2025-01' of github.com:opentensor/subtensor in…
Browse files Browse the repository at this point in the history
…to feat/rao-2025-01
  • Loading branch information
gztensor committed Jan 7, 2025
2 parents d2e2b5c + 125d8a6 commit f9b381c
Show file tree
Hide file tree
Showing 12 changed files with 467 additions and 1,907 deletions.
207 changes: 108 additions & 99 deletions pallets/subtensor/src/coinbase/run_coinbase.rs

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions pallets/subtensor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -744,8 +744,8 @@ pub mod pallet {
/// Eventually, Bittensor should migrate to using Holds afterwhich time we will not require this
/// separate accounting.
#[pallet::storage]
/// --- MAP ( netuid ) --> Global weight
pub type TaoWeight<T> = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultTaoWeight<T>>;
/// --- ITEM --> Global weight
pub type TaoWeight<T> = StorageValue<_, u64, ValueQuery, DefaultTaoWeight<T>>;
#[pallet::storage]
/// --- ITEM ( default_delegate_take )
pub type MaxDelegateTake<T> = StorageValue<_, u16, ValueQuery, DefaultDelegateTake<T>>;
Expand Down Expand Up @@ -895,6 +895,9 @@ pub mod pallet {
#[pallet::storage] // --- DMAP ( netuid ) --> tao_in_emission | Returns the amount of tao emitted into this subent on the last block.
pub type SubnetTaoInEmission<T: Config> =
StorageMap<_, Identity, u16, u64, ValueQuery, DefaultZeroU64<T>>;
#[pallet::storage] // --- DMAP ( netuid ) --> alpha_sell_per_block | Alpha sold per block.
pub type SubnetAlphaEmissionSell<T: Config> =
StorageMap<_, Identity, u16, u64, ValueQuery, DefaultZeroU64<T>>;
#[pallet::storage] // --- DMAP ( netuid ) --> alpha_supply_in_pool | Returns the amount of alpha in the subnet.
pub type SubnetAlphaIn<T: Config> =
StorageMap<_, Identity, u16, u64, ValueQuery, DefaultZeroU64<T>>;
Expand Down
37 changes: 37 additions & 0 deletions pallets/subtensor/src/macros/dispatches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1530,5 +1530,42 @@ mod dispatches {
hotkey,
)
}

/// ---- The implementation for the extrinsic unstake_all: Removes all stake from a hotkey account across all subnets and adds it onto a coldkey.
///
/// # Args:
/// * `origin` - (<T as frame_system::Config>::Origin):
/// - The signature of the caller's coldkey.
///
/// * `hotkey` (T::AccountId):
/// - The associated hotkey account.
///
/// # Event:
/// * StakeRemoved;
/// - On the successfully removing stake from the hotkey account.
///
/// # Raises:
/// * `NotRegistered`:
/// - Thrown if the account we are attempting to unstake from is non existent.
///
/// * `NonAssociatedColdKey`:
/// - Thrown if the coldkey does not own the hotkey we are unstaking from.
///
/// * `NotEnoughStakeToWithdraw`:
/// - Thrown if there is not enough stake on the hotkey to withdraw this amount.
///
/// * `TxRateLimitExceeded`:
/// - Thrown if key has hit transaction rate limit
#[pallet::call_index(84)]
#[pallet::weight((Weight::from_parts(3_000_000, 0).saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))]
pub fn unstake_all_alpha(
origin: OriginFor<T>,
hotkey: T::AccountId,
) -> DispatchResult {
Self::do_unstake_all_alpha(
origin,
hotkey,
)
}
}
}
4 changes: 2 additions & 2 deletions pallets/subtensor/src/migrations/migrate_rao.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ pub fn migrate_rao<T: Config>() -> Weight {
});

// Convert subnets and give them lock.
// Set global weight to 18% from the start
TaoWeight::<T>::set(320_413_933_267_719_290);
for netuid in netuids.iter().clone() {
if *netuid == 0 {
// Give root a single RAO in pool to avoid any catestrophic division by zero.
Expand All @@ -74,8 +76,6 @@ pub fn migrate_rao<T: Config>() -> Weight {
SubnetAlphaOut::<T>::insert(netuid, 0); // Set zero subnet alpha out.
SubnetMechanism::<T>::insert(netuid, 1); // Convert to dynamic immediately with initialization.
Tempo::<T>::insert(netuid, DefaultTempo::<T>::get());
// Set global weight to 1.8% from the start
TaoWeight::<T>::insert(netuid, 320_413_933_267_719_290);
// Set the token symbol for this subnet using Self instead of Pallet::<T>
TokenSymbol::<T>::insert(netuid, Pallet::<T>::get_symbol_for_subnet(*netuid));

Expand Down
74 changes: 74 additions & 0 deletions pallets/subtensor/src/staking/remove_stake.rs
Original file line number Diff line number Diff line change
Expand Up @@ -153,4 +153,78 @@ impl<T: Config> Pallet<T> {
// 5. Done and ok.
Ok(())
}


/// ---- The implementation for the extrinsic unstake_all: Removes all stake from a hotkey account across all subnets and adds it onto a coldkey.
///
/// # Args:
/// * 'origin': (<T as frame_system::Config>RuntimeOrigin):
/// - The signature of the caller's coldkey.
///
/// * 'hotkey' (T::AccountId):
/// - The associated hotkey account.
///
/// # Event:
/// * StakeRemoved;
/// - On the successfully removing stake from the hotkey account.
///
/// # Raises:
/// * 'NotRegistered':
/// - Thrown if the account we are attempting to unstake from is non existent.
///
/// * 'NonAssociatedColdKey':
/// - Thrown if the coldkey does not own the hotkey we are unstaking from.
///
/// * 'NotEnoughStakeToWithdraw':
/// - Thrown if there is not enough stake on the hotkey to withdraw this amount.
///
/// * 'TxRateLimitExceeded':
/// - Thrown if key has hit transaction rate limit
///
pub fn do_unstake_all_alpha(
origin: T::RuntimeOrigin,
hotkey: T::AccountId,
) -> dispatch::DispatchResult {

// 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information.
let coldkey = ensure_signed(origin)?;
log::info!(
"do_unstake_all( origin:{:?} hotkey:{:?} )",
coldkey,
hotkey
);

// 2. Ensure that the hotkey account exists this is only possible through registration.
ensure!( Self::hotkey_account_exists(&hotkey), Error::<T>::HotKeyAccountNotExists );

// 3. Get all netuids.
let netuids: Vec<u16> = Self::get_all_subnet_netuids();
log::debug!("All subnet netuids: {:?}", netuids);

// 4. Iterate through all subnets and remove stake.
let mut total_tao_unstaked: u64 = 0;
for netuid in netuids.iter() {
// If not Root network.
if *netuid != Self::get_root_netuid() {
// Ensure that the hotkey has enough stake to withdraw.
let alpha_unstaked = Self::get_stake_for_hotkey_and_coldkey_on_subnet(&hotkey, &coldkey, *netuid);
if alpha_unstaked > 0 {
// Swap the alpha to tao and update counters for this subnet.
let tao_unstaked: u64 = Self::unstake_from_subnet(&hotkey, &coldkey, *netuid, alpha_unstaked);

// Increment total
total_tao_unstaked += tao_unstaked;

// If the stake is below the minimum, we clear the nomination from storage.
Self::clear_small_nomination_if_required(&hotkey, &coldkey, *netuid);
}
}
}

// Stake into root.
Self::stake_into_subnet( &hotkey, &coldkey, Self::get_root_netuid(), total_tao_unstaked );

// 5. Done and ok.
Ok(())
}
}
10 changes: 5 additions & 5 deletions pallets/subtensor/src/staking/stake_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ impl<T: Config> Pallet<T> {
///
/// # Note
/// This function uses saturating division to prevent potential overflow errors.
pub fn get_tao_weight(netuid: u16) -> I96F32 {
pub fn get_tao_weight() -> I96F32 {
// Step 1: Fetch the global weight from storage
let stored_weight = TaoWeight::<T>::get(netuid);
let stored_weight = TaoWeight::<T>::get();

// Step 2: Convert the u64 weight to I96F32
let weight_fixed = I96F32::from_num(stored_weight);
Expand All @@ -84,9 +84,9 @@ impl<T: Config> Pallet<T> {
/// # Note
/// The weight is stored as a raw u64 value. To get the normalized weight between 0 and 1,
/// use the `get_tao_weight()` function.
pub fn set_tao_weight(weight: u64, netuid: u16) {
pub fn set_tao_weight(weight: u64) {
// Update the TaoWeight storage with the new weight value
TaoWeight::<T>::insert(netuid, weight);
TaoWeight::<T>::set(weight);
}

/// Calculates the weighted combination of alpha and global tao for hotkeys on a subnet.
Expand Down Expand Up @@ -115,7 +115,7 @@ impl<T: Config> Pallet<T> {

// Step 5: Combine alpha and root tao stakes.
// Retrieve the global global weight.
let tao_weight: I64F64 = I64F64::from_num(Self::get_tao_weight(netuid));
let tao_weight: I64F64 = I64F64::from_num(Self::get_tao_weight());
// Calculate the weighted average of alpha and global tao stakes for each neuron.
let total_stake: Vec<I64F64> = alpha_stake
.iter()
Expand Down
3 changes: 0 additions & 3 deletions pallets/subtensor/src/subnets/subnet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,9 +337,6 @@ impl<T: Config> Pallet<T> {
BurnRegistrationsThisInterval::<T>::get(netuid),
);
}
if !TaoWeight::<T>::contains_key(netuid) {
TaoWeight::<T>::insert(netuid, DefaultTaoWeight::<T>::get());
}
}
}

Expand Down
Loading

0 comments on commit f9b381c

Please sign in to comment.