Skip to content

Commit

Permalink
refac: remove string utils (#20)
Browse files Browse the repository at this point in the history
Co-authored-by: My Name <[email protected]>
  • Loading branch information
saiintbrisson and foobar123asdf authored Feb 29, 2024
1 parent a65646a commit 17af07a
Show file tree
Hide file tree
Showing 9 changed files with 84 additions and 145 deletions.
10 changes: 5 additions & 5 deletions pallets/subspace/src/benchmarking.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ fn register_helper<T: Config>(
module_key.clone(),
);

let netuid = <Pallet<T>>::get_netuid_for_name(network.clone());
let netuid = <Pallet<T>>::get_netuid_for_name(network.clone()).unwrap_or(u16::MAX);

netuid
}
Expand Down Expand Up @@ -118,7 +118,7 @@ mod benchmarks {
module_key.clone(),
);

let netuid = <Pallet<T>>::get_netuid_for_name(network);
let netuid = <Pallet<T>>::get_netuid_for_name(network).unwrap_or(u16::MAX);

assert!(<Pallet<T>>::is_registered(netuid, &module_key), "Register failed");

Expand Down Expand Up @@ -425,7 +425,7 @@ mod benchmarks {
MIN_STAKE,
);

let netuid = <Pallet<T>>::get_netuid_for_name(network.clone());
let netuid = <Pallet<T>>::get_netuid_for_name(network.clone()).unwrap_or(u16::MAX);

#[extrinsic_call]
add_subnet_update(RawOrigin::Root, netuid, name, 1, 1, 1, 1, 1, 1, 1, 1, 1);
Expand All @@ -448,7 +448,7 @@ mod benchmarks {
MIN_STAKE,
);

let netuid = <Pallet<T>>::get_netuid_for_name(network.clone());
let netuid = <Pallet<T>>::get_netuid_for_name(network.clone()).unwrap_or(u16::MAX);

<Pallet<T>>::add_subnet_update(
RawOrigin::Root.into(),
Expand Down Expand Up @@ -486,7 +486,7 @@ mod benchmarks {
MIN_STAKE,
);

let netuid = <Pallet<T>>::get_netuid_for_name(network.clone());
let netuid = <Pallet<T>>::get_netuid_for_name(network.clone()).unwrap_or(u16::MAX);

<Pallet<T>>::add_subnet_update(
RawOrigin::Root.into(),
Expand Down
7 changes: 4 additions & 3 deletions pallets/subspace/src/global.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::voting::AUTHORITY_MODE;

use super::*;
use crate::utils::is_vec_str;
use frame_support::pallet_prelude::DispatchResult;

use system::ensure_root;
Expand Down Expand Up @@ -135,8 +136,8 @@ impl<T: Config> Pallet<T> {

pub fn do_update_global(origin: T::RuntimeOrigin, params: GlobalParams) -> DispatchResult {
ensure_root(origin)?;
ensure!(is_vec_str(Self::get_vote_mode_global(), "authority"), Error::<T>::InvalidVoteMode);
Self::set_global_params(params.clone());
ensure!(Self::get_vote_mode_global() == AUTHORITY_MODE, Error::<T>::InvalidVoteMode);
Self::set_global_params(params);
Ok(())
}

Expand Down
4 changes: 2 additions & 2 deletions pallets/subspace/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#![allow(deprecated, non_camel_case_types, non_snake_case)]
#![cfg_attr(not(feature = "std"), no_std)]
#![recursion_limit = "512"]

use frame_system::{self as system, ensure_signed};
pub use pallet::*;

Expand Down Expand Up @@ -43,7 +44,6 @@ mod registration;
mod staking;
mod step;
mod subnet;
mod utils;
mod voting;
mod weights;

Expand Down Expand Up @@ -910,7 +910,7 @@ pub mod pallet {
max_weight_age: default_params.max_weight_age,
};

self::Pallet::<T>::add_subnet(params.clone());
self::Pallet::<T>::add_subnet(params);

for (uid_usize, (key, name, address, weights)) in
self.modules[subnet_idx].iter().enumerate()
Expand Down
54 changes: 25 additions & 29 deletions pallets/subspace/src/module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,36 +33,32 @@ impl<T: Config> Pallet<T> {
// --- 1. We check the callers (key) signature.
let key = ensure_signed(origin)?;
let uid: u16 = Self::get_uid_for_key(netuid, &key);
Self::check_module_params(netuid, params.clone())?;
Self::check_module_params(netuid, &params)?;
Self::set_module_params(netuid, uid, params);
// --- 8. Return is successful dispatch.
Ok(())
}

pub fn check_module_params(_netuid: u16, params: ModuleParams<T>) -> DispatchResult {
// if len(name) > 0, then we update the name.
/// Checks whether the module params are valid. Name and address must be non-empty and below the
/// max name length allowed.
pub fn check_module_params(_netuid: u16, params: &ModuleParams<T>) -> DispatchResult {
let max_name_length = MaxNameLength::<T>::get() as usize;

assert!(params.name.len() > 0);
ensure!(
params.name.len() <= MaxNameLength::<T>::get() as usize,
Error::<T>::ModuleNameTooLong
);
ensure!(params.name.len() <= max_name_length, Error::<T>::ModuleNameTooLong);
assert!(params.address.len() > 0);
ensure!(
params.address.len() <= MaxNameLength::<T>::get() as usize,
Error::<T>::ModuleAddressTooLong
);
// delegation fee is a percent
ensure!(params.address.len() <= max_name_length, Error::<T>::ModuleAddressTooLong);

Ok(())
}

pub fn module_params(netuid: u16, uid: u16) -> ModuleParams<T> {
let module_params: ModuleParams<T> = ModuleParams {
ModuleParams {
name: Self::get_module_name(netuid, uid),
address: Self::get_module_address(netuid, uid),
delegation_fee: Self::get_module_delegation_fee(netuid, uid),
controller: Self::get_key_for_uid(netuid, uid),
};
module_params
}
}

pub fn set_module_params(netuid: u16, uid: u16, module_params: ModuleParams<T>) {
Expand Down Expand Up @@ -172,7 +168,7 @@ impl<T: Config> Pallet<T> {
// HANDLE THE DELEGATION FEE
DelegationFee::<T>::insert(
netuid,
replace_key.clone(),
replace_key,
DelegationFee::<T>::get(netuid, uid_key.clone()),
); // Make uid - key association.
DelegationFee::<T>::remove(netuid, uid_key.clone()); // Make uid - key association.
Expand Down Expand Up @@ -241,25 +237,25 @@ impl<T: Config> Pallet<T> {

pub fn get_module_stats(netuid: u16, uid: u16) -> ModuleStats<T> {
let key = Self::get_key_for_uid(netuid, uid);
let emission = Self::get_emission_for_uid(netuid, uid as u16);
let incentive = Self::get_incentive_for_uid(netuid, uid as u16);
let dividends = Self::get_dividends_for_uid(netuid, uid as u16);
let last_update = Self::get_last_update_for_uid(netuid, uid as u16);
let _registration_block = Self::get_registration_block_for_uid(netuid, uid as u16);
let weights = <Weights<T>>::get(netuid, uid)
let emission = Self::get_emission_for_uid(netuid, uid);
let incentive = Self::get_incentive_for_uid(netuid, uid);
let dividends = Self::get_dividends_for_uid(netuid, uid);
let last_update = Self::get_last_update_for_uid(netuid, uid);

let weights: Vec<(u16, u16)> = Weights::<T>::get(netuid, uid)
.iter()
.filter_map(|(i, w)| if *w > 0 { Some(((*i).into(), (*w).into())) } else { None })
.collect::<Vec<(u16, u16)>>();
.collect();
let stake_from: Vec<(T::AccountId, u64)> = StakeFrom::<T>::get(netuid, key);
let registration_block = Self::get_registration_block_for_uid(netuid, uid as u16);
let registration_block = Self::get_registration_block_for_uid(netuid, uid);

ModuleStats {
stake_from,
emission: emission.into(),
incentive: incentive.into(),
dividends: dividends.into(),
last_update: last_update.into(),
registration_block: registration_block.into(),
emission,
incentive,
dividends,
last_update,
registration_block,
weights,
}
}
Expand Down
9 changes: 3 additions & 6 deletions pallets/subspace/src/profit_share.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ impl<T: Config> Pallet<T> {
// make sure the normalized shares add up to the unit
// convert the normalized shares to u16
let mut normalize_shares: Vec<u16> =
normalized_shares_float.iter().map(|x| x.to_num::<u16>()).collect::<Vec<u16>>();
normalized_shares_float.iter().map(|x| x.to_num::<u16>()).collect();

let mut total_normalized_shares: u16 = normalize_shares.iter().sum::<u16>();
let mut total_normalized_shares: u16 = normalize_shares.iter().sum();

// ensure the profit shares add up to the unit
if total_normalized_shares < u16::MAX {
Expand All @@ -53,9 +53,6 @@ impl<T: Config> Pallet<T> {
u16::MAX
);

// check tssat the normalized shares add up to the unit
let _total_normalized_shares: u16 = normalize_shares.iter().sum::<u16>();

// now send the normalized shares to the profit share pallet
let profit_share_tuples: Vec<(T::AccountId, u16)> =
keys.iter().zip(normalize_shares.iter()).map(|(x, y)| (x.clone(), *y)).collect();
Expand All @@ -79,7 +76,7 @@ impl<T: Config> Pallet<T> {
for (share_key, share_ratio) in profit_shares.iter() {
let share_emission_float: I96F32 =
I96F32::from(emission) * (I96F32::from(*share_ratio) / I96F32::from(u16::MAX));
let share_emission: u64 = share_emission_float.to_num::<u64>();
let share_emission: u64 = share_emission_float.to_num();
emission_shares.push((share_key.clone(), share_emission));
}

Expand Down
34 changes: 11 additions & 23 deletions pallets/subspace/src/registration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ use super::*;
use frame_support::pallet_prelude::DispatchResult;
use frame_system::ensure_signed;

use sp_core::H256;

use sp_std::vec::Vec;

// IterableStorageMap
Expand Down Expand Up @@ -38,13 +36,14 @@ impl<T: Config> Pallet<T> {
);

// --- 4. Resolve the network in case it doesn't exist
if !Self::subnet_name_exists(network.clone()) {
// If the subnet doesn't exist, registration will create it.
Self::add_subnet_from_registration(network.clone(), stake_amount, &key)?;
}
let netuid = if let Some(netuid) = Self::get_netuid_for_name(&network) {
netuid
} else {
// Create subnet if it does not exist.
Self::add_subnet_from_registration(network, stake_amount, &key)?
};

// --- 5. Ensure the caller has enough stake to register.
let netuid: u16 = Self::get_netuid_for_name(network.clone());
let min_stake: u64 = MinStake::<T>::get(netuid);
let min_burn: u64 = Self::get_min_burn();

Expand All @@ -66,7 +65,7 @@ impl<T: Config> Pallet<T> {
let uid: u16 = Self::append_module(netuid, &module_key, name.clone(), address.clone());

// --- 9. Add the stake to the module, now that it is registered on the network.
Self::do_add_stake(origin.clone(), netuid, module_key.clone(), stake_amount)?;
Self::do_add_stake(origin, netuid, module_key.clone(), stake_amount)?;

// constant -> min_burn logic
if min_burn > 0 {
Expand Down Expand Up @@ -100,23 +99,16 @@ impl<T: Config> Pallet<T> {
Ok(())
}

/// Whether the netuid has enough stake to cover the minimal stake and min burn
pub fn enough_stake_to_register(
_netuid: u16,
min_stake: u64,
min_burn: u64,
stake_amount: u64,
) -> bool {
// the amount has to cover, the minimal stake as well as burn if it's present
stake_amount >= (min_stake + min_burn)
}

pub fn vec_to_hash(vec_hash: Vec<u8>) -> H256 {
let de_ref_hash = &vec_hash; // b: &Vec<u8>
let de_de_ref_hash: &[u8] = &de_ref_hash; // c: &[u8]
let real_hash: H256 = H256::from_slice(de_de_ref_hash);
real_hash
}

// Determine which peer to prune from the network by finding the element with the lowest pruning
// score out of immunity period. If all modules are in immunity period, return node with lowest
// prunning score. This function will always return an element to prune.
Expand Down Expand Up @@ -165,10 +157,7 @@ impl<T: Config> Pallet<T> {
name: Vec<u8>,
stake: u64,
founder_key: &T::AccountId,
) -> DispatchResult {
// use default parameters
//

) -> Result<u16, sp_runtime::DispatchError> {
let num_subnets: u16 = Self::num_subnets();
let max_subnets: u16 = Self::get_global_max_allowed_subnets();
// if we have not reached the max number of subnets, then we can start a new one
Expand All @@ -187,11 +176,10 @@ impl<T: Config> Pallet<T> {
// if we have reached the max number of subnets, then we can start a new one if the stake is
// greater than the least staked network
let mut params: SubnetParams<T> = Self::default_subnet_params();
params.name = name.clone();
params.name = name;
params.founder = founder_key.clone();
let _netuid = Self::add_subnet(params);

Ok(())
Ok(Self::add_subnet(params))
}

pub fn check_module_limits(netuid: u16) {
Expand Down
Loading

0 comments on commit 17af07a

Please sign in to comment.