diff --git a/common/src/lib.rs b/common/src/lib.rs index 26aa6b2f13..6122ef99fa 100644 --- a/common/src/lib.rs +++ b/common/src/lib.rs @@ -224,7 +224,7 @@ pub mod time { pub const DAYS: BlockNumber = HOURS * 24; } -#[freeze_struct("8e576b32bb1bb664")] +#[freeze_struct("7e5202d7f18b39d4")] #[repr(transparent)] #[derive( Deserialize, @@ -244,43 +244,43 @@ pub mod time { RuntimeDebug, )] #[serde(transparent)] -pub struct SubId(u8); +pub struct MechId(u8); -impl SubId { - pub const MAIN: SubId = Self(0); +impl MechId { + pub const MAIN: MechId = Self(0); } -impl From for SubId { +impl From for MechId { fn from(value: u8) -> Self { Self(value) } } -impl From for u16 { - fn from(val: SubId) -> Self { +impl From for u16 { + fn from(val: MechId) -> Self { u16::from(val.0) } } -impl From for u64 { - fn from(val: SubId) -> Self { +impl From for u64 { + fn from(val: MechId) -> Self { u64::from(val.0) } } -impl From for u8 { - fn from(val: SubId) -> Self { +impl From for u8 { + fn from(val: MechId) -> Self { u8::from(val.0) } } -impl Display for SubId { +impl Display for MechId { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { Display::fmt(&self.0, f) } } -impl CompactAs for SubId { +impl CompactAs for MechId { type As = u8; fn encode_as(&self) -> &Self::As { @@ -292,13 +292,13 @@ impl CompactAs for SubId { } } -impl From> for SubId { - fn from(c: Compact) -> Self { +impl From> for MechId { + fn from(c: Compact) -> Self { c.0 } } -impl TypeInfo for SubId { +impl TypeInfo for MechId { type Identity = ::Identity; fn type_info() -> scale_info::Type { ::type_info() diff --git a/pallets/admin-utils/src/lib.rs b/pallets/admin-utils/src/lib.rs index 5569e286b9..e48a9b02b3 100644 --- a/pallets/admin-utils/src/lib.rs +++ b/pallets/admin-utils/src/lib.rs @@ -28,7 +28,7 @@ pub mod pallet { use pallet_subtensor::utils::rate_limiting::{Hyperparameter, TransactionType}; use sp_runtime::BoundedVec; use substrate_fixed::types::I96F32; - use subtensor_runtime_common::{NetUid, SubId, TaoCurrency}; + use subtensor_runtime_common::{MechId, NetUid, TaoCurrency}; /// The main data structure of the module. #[pallet::pallet] @@ -1872,38 +1872,38 @@ pub mod pallet { Ok(()) } - /// Sets the desired number of subsubnets in a subnet + /// Sets the desired number of mechanisms in a subnet #[pallet::call_index(76)] #[pallet::weight(Weight::from_parts(15_000_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] - pub fn sudo_set_subsubnet_count( + pub fn sudo_set_mechanism_count( origin: OriginFor, netuid: NetUid, - subsub_count: SubId, + mechanism_count: MechId, ) -> DispatchResult { let maybe_owner = pallet_subtensor::Pallet::::ensure_sn_owner_or_root_with_limits( origin, netuid, - &[TransactionType::SubsubnetCountUpdate], + &[TransactionType::MechanismCountUpdate], )?; - pallet_subtensor::Pallet::::do_set_subsubnet_count(netuid, subsub_count)?; + pallet_subtensor::Pallet::::do_set_mechanism_count(netuid, mechanism_count)?; pallet_subtensor::Pallet::::record_owner_rl( maybe_owner, netuid, - &[TransactionType::SubsubnetCountUpdate], + &[TransactionType::MechanismCountUpdate], ); Ok(()) } - /// Sets the emission split between subsubnets in a subnet + /// Sets the emission split between mechanisms in a subnet #[pallet::call_index(77)] #[pallet::weight(Weight::from_parts(15_000_000, 0) .saturating_add(::DbWeight::get().reads(1_u64)) .saturating_add(::DbWeight::get().writes(1_u64)))] - pub fn sudo_set_subsubnet_emission_split( + pub fn sudo_set_mechanism_emission_split( origin: OriginFor, netuid: NetUid, maybe_split: Option>, @@ -1911,7 +1911,7 @@ pub mod pallet { let maybe_owner = pallet_subtensor::Pallet::::ensure_sn_owner_or_root_with_limits( origin, netuid, - &[TransactionType::SubsubnetEmission], + &[TransactionType::MechanismEmission], )?; pallet_subtensor::Pallet::::do_set_emission_split(netuid, maybe_split)?; @@ -1919,7 +1919,7 @@ pub mod pallet { pallet_subtensor::Pallet::::record_owner_rl( maybe_owner, netuid, - &[TransactionType::SubsubnetEmission], + &[TransactionType::MechanismEmission], ); Ok(()) } diff --git a/pallets/admin-utils/src/tests/mod.rs b/pallets/admin-utils/src/tests/mod.rs index 3b68db2a91..0e0232859b 100644 --- a/pallets/admin-utils/src/tests/mod.rs +++ b/pallets/admin-utils/src/tests/mod.rs @@ -14,7 +14,7 @@ use pallet_subtensor::{Event, utils::rate_limiting::TransactionType}; use sp_consensus_grandpa::AuthorityId as GrandpaId; use sp_core::{Get, Pair, U256, ed25519}; use substrate_fixed::types::I96F32; -use subtensor_runtime_common::{Currency, NetUid, SubId, TaoCurrency}; +use subtensor_runtime_common::{Currency, MechId, NetUid, TaoCurrency}; use crate::Error; use crate::pallet::PrecompileEnable; @@ -2322,11 +2322,11 @@ fn test_sudo_set_max_burn() { } #[test] -fn test_sudo_set_subsubnet_count() { +fn test_sudo_set_mechanism_count() { new_test_ext().execute_with(|| { let netuid = NetUid::from(1); - let ss_count_ok = SubId::from(8); - let ss_count_bad = SubId::from(9); + let ss_count_ok = MaxMechanismCount::::get(); + let ss_count_bad = MechId::from(u8::from(ss_count_ok) + 1); let sn_owner = U256::from(1324); add_network(netuid, 10); @@ -2334,7 +2334,7 @@ fn test_sudo_set_subsubnet_count() { SubnetOwner::::insert(netuid, sn_owner); assert_eq!( - AdminUtils::sudo_set_subsubnet_count( + AdminUtils::sudo_set_mechanism_count( <::RuntimeOrigin>::signed(U256::from(1)), netuid, ss_count_ok @@ -2342,17 +2342,17 @@ fn test_sudo_set_subsubnet_count() { Err(DispatchError::BadOrigin) ); assert_noop!( - AdminUtils::sudo_set_subsubnet_count(RuntimeOrigin::root(), netuid, ss_count_bad), + AdminUtils::sudo_set_mechanism_count(RuntimeOrigin::root(), netuid, ss_count_bad), pallet_subtensor::Error::::InvalidValue ); - assert_ok!(AdminUtils::sudo_set_subsubnet_count( + assert_ok!(AdminUtils::sudo_set_mechanism_count( <::RuntimeOrigin>::root(), netuid, ss_count_ok )); - assert_ok!(AdminUtils::sudo_set_subsubnet_count( + assert_ok!(AdminUtils::sudo_set_mechanism_count( <::RuntimeOrigin>::signed(sn_owner), netuid, ss_count_ok @@ -2360,28 +2360,28 @@ fn test_sudo_set_subsubnet_count() { }); } -// cargo test --package pallet-admin-utils --lib -- tests::test_sudo_set_subsubnet_count_and_emissions --exact --show-output +// cargo test --package pallet-admin-utils --lib -- tests::test_sudo_set_mechanism_count_and_emissions --exact --show-output #[test] -fn test_sudo_set_subsubnet_count_and_emissions() { +fn test_sudo_set_mechanism_count_and_emissions() { new_test_ext().execute_with(|| { let netuid = NetUid::from(1); - let ss_count_ok = SubId::from(2); + let ss_count_ok = MechId::from(2); let sn_owner = U256::from(1324); add_network(netuid, 10); // Set the Subnet Owner SubnetOwner::::insert(netuid, sn_owner); - assert_ok!(AdminUtils::sudo_set_subsubnet_count( + assert_ok!(AdminUtils::sudo_set_mechanism_count( <::RuntimeOrigin>::signed(sn_owner), netuid, ss_count_ok )); // Cannot set emission split with wrong number of entries - // With two subsubnets the size of the split vector should be 2, not 3 + // With two mechanisms the size of the split vector should be 2, not 3 assert_noop!( - AdminUtils::sudo_set_subsubnet_emission_split( + AdminUtils::sudo_set_mechanism_emission_split( <::RuntimeOrigin>::signed(sn_owner), netuid, Some(vec![0xFFFF / 5 * 2, 0xFFFF / 5 * 2, 0xFFFF / 5]) @@ -2392,7 +2392,7 @@ fn test_sudo_set_subsubnet_count_and_emissions() { // Cannot set emission split with wrong total of entries // Split vector entries should sum up to exactly 0xFFFF assert_noop!( - AdminUtils::sudo_set_subsubnet_emission_split( + AdminUtils::sudo_set_mechanism_emission_split( <::RuntimeOrigin>::signed(sn_owner), netuid, Some(vec![0xFFFF / 5 * 4, 0xFFFF / 5 - 1]) @@ -2401,9 +2401,9 @@ fn test_sudo_set_subsubnet_count_and_emissions() { ); // Can set good split ok - // We also verify here that it can happen in the same block as setting subsubnet counts + // We also verify here that it can happen in the same block as setting mechanism counts // or soon, without rate limiting - assert_ok!(AdminUtils::sudo_set_subsubnet_emission_split( + assert_ok!(AdminUtils::sudo_set_mechanism_emission_split( <::RuntimeOrigin>::signed(sn_owner), netuid, Some(vec![0xFFFF / 5, 0xFFFF / 5 * 4]) @@ -2411,7 +2411,7 @@ fn test_sudo_set_subsubnet_count_and_emissions() { // Cannot set it again due to rate limits assert_noop!( - AdminUtils::sudo_set_subsubnet_emission_split( + AdminUtils::sudo_set_mechanism_emission_split( <::RuntimeOrigin>::signed(sn_owner), netuid, Some(vec![0xFFFF / 5 * 4, 0xFFFF / 5]) @@ -2436,9 +2436,9 @@ fn test_trim_to_max_allowed_uids() { ImmuneOwnerUidsLimit::::insert(netuid, 2); // We set a low value here to make testing easier MinAllowedUids::::set(netuid, 4); - // We define 4 subsubnets - let subsubnet_count = SubId::from(4); - SubsubnetCountCurrent::::insert(netuid, subsubnet_count); + // We define 4 mechanisms + let mechanism_count = MechId::from(4); + MechanismCountCurrent::::insert(netuid, mechanism_count); // Add some neurons let max_n = 16; @@ -2480,9 +2480,9 @@ fn test_trim_to_max_allowed_uids() { ValidatorPermit::::insert(netuid, bool_values.clone()); Active::::insert(netuid, bool_values); - for subid in 0..subsubnet_count.into() { + for mecid in 0..mechanism_count.into() { let netuid_index = - SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(subid)); + SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(mecid)); Incentive::::insert(netuid_index, values.clone()); LastUpdate::::insert(netuid_index, u64_values.clone()); } @@ -2515,9 +2515,9 @@ fn test_trim_to_max_allowed_uids() { } } - for subid in 0..subsubnet_count.into() { + for mecid in 0..mechanism_count.into() { let netuid_index = - SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(subid)); + SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(mecid)); Weights::::insert(netuid_index, uid, weights.clone()); Bonds::::insert(netuid_index, uid, bonds.clone()); } @@ -2563,9 +2563,9 @@ fn test_trim_to_max_allowed_uids() { assert_eq!(ValidatorPermit::::get(netuid), expected_bools); assert_eq!(StakeWeight::::get(netuid), expected_values); - for subid in 0..subsubnet_count.into() { + for mecid in 0..mechanism_count.into() { let netuid_index = - SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(subid)); + SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(mecid)); assert_eq!(Incentive::::get(netuid_index), expected_values); assert_eq!(LastUpdate::::get(netuid_index), expected_u64_values); } @@ -2574,9 +2574,9 @@ fn test_trim_to_max_allowed_uids() { for uid in new_max_n..max_n { assert!(!Keys::::contains_key(netuid, uid)); assert!(!BlockAtRegistration::::contains_key(netuid, uid)); - for subid in 0..subsubnet_count.into() { + for mecid in 0..mechanism_count.into() { let netuid_index = - SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(subid)); + SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(mecid)); assert!(!Weights::::contains_key(netuid_index, uid)); assert!(!Bonds::::contains_key(netuid_index, uid)); } @@ -2610,9 +2610,9 @@ fn test_trim_to_max_allowed_uids() { // Ensure trimmed uids weights and bonds connections have been trimmed correctly for uid in 0..new_max_n { - for subid in 0..subsubnet_count.into() { + for mecid in 0..mechanism_count.into() { let netuid_index = - SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(subid)); + SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(mecid)); assert!( Weights::::get(netuid_index, uid) .iter() @@ -2638,7 +2638,7 @@ fn test_trim_to_max_allowed_uids() { NetUid::from(42), new_max_n ), - pallet_subtensor::Error::::SubNetworkDoesNotExist + pallet_subtensor::Error::::MechanismDoesNotExist ); // New max n less than lower bound diff --git a/pallets/subtensor/rpc/src/lib.rs b/pallets/subtensor/rpc/src/lib.rs index 2a1c13c7a9..2df65242d1 100644 --- a/pallets/subtensor/rpc/src/lib.rs +++ b/pallets/subtensor/rpc/src/lib.rs @@ -9,7 +9,7 @@ use jsonrpsee::{ use sp_blockchain::HeaderBackend; use sp_runtime::{AccountId32, traits::Block as BlockT}; use std::sync::Arc; -use subtensor_runtime_common::{NetUid, SubId, TaoCurrency}; +use subtensor_runtime_common::{MechId, NetUid, TaoCurrency}; use sp_api::ProvideRuntimeApi; @@ -72,13 +72,13 @@ pub trait SubtensorCustomApi { fn get_all_metagraphs(&self, at: Option) -> RpcResult>; #[method(name = "subnetInfo_getMetagraph")] fn get_metagraph(&self, netuid: NetUid, at: Option) -> RpcResult>; - #[method(name = "subnetInfo_getAllSubMetagraphs")] - fn get_all_submetagraphs(&self, at: Option) -> RpcResult>; - #[method(name = "subnetInfo_getSubMetagraph")] - fn get_submetagraph( + #[method(name = "subnetInfo_getAllMechagraphs")] + fn get_all_mechagraphs(&self, at: Option) -> RpcResult>; + #[method(name = "subnetInfo_getMechagraph")] + fn get_mechagraph( &self, netuid: NetUid, - subid: SubId, + mecid: MechId, at: Option, ) -> RpcResult>; #[method(name = "subnetInfo_getSubnetState")] @@ -92,11 +92,11 @@ pub trait SubtensorCustomApi { metagraph_index: Vec, at: Option, ) -> RpcResult>; - #[method(name = "subnetInfo_getSelectiveSubMetagraph")] - fn get_selective_submetagraph( + #[method(name = "subnetInfo_getSelectiveMechagraph")] + fn get_selective_mechagraph( &self, netuid: NetUid, - subid: SubId, + mecid: MechId, metagraph_index: Vec, at: Option, ) -> RpcResult>; @@ -338,11 +338,11 @@ where } } - fn get_all_submetagraphs(&self, at: Option<::Hash>) -> RpcResult> { + fn get_all_mechagraphs(&self, at: Option<::Hash>) -> RpcResult> { let api = self.client.runtime_api(); let at = at.unwrap_or_else(|| self.client.info().best_hash); - match api.get_all_submetagraphs(at) { + match api.get_all_mechagraphs(at) { Ok(result) => Ok(result.encode()), Err(e) => Err(Error::RuntimeError(format!("Unable to get metagraps: {e:?}")).into()), } @@ -381,15 +381,15 @@ where } } - fn get_submetagraph( + fn get_mechagraph( &self, netuid: NetUid, - subid: SubId, + mecid: MechId, at: Option<::Hash>, ) -> RpcResult> { let api = self.client.runtime_api(); let at = at.unwrap_or_else(|| self.client.info().best_hash); - match api.get_submetagraph(at, netuid, subid) { + match api.get_mechagraph(at, netuid, mecid) { Ok(result) => Ok(result.encode()), Err(e) => Err(Error::RuntimeError(format!( "Unable to get dynamic subnets info: {e:?}" @@ -474,17 +474,17 @@ where } } - fn get_selective_submetagraph( + fn get_selective_mechagraph( &self, netuid: NetUid, - subid: SubId, + mecid: MechId, metagraph_index: Vec, at: Option<::Hash>, ) -> RpcResult> { let api = self.client.runtime_api(); let at = at.unwrap_or_else(|| self.client.info().best_hash); - match api.get_selective_submetagraph(at, netuid, subid, metagraph_index) { + match api.get_selective_mechagraph(at, netuid, mecid, metagraph_index) { Ok(result) => Ok(result.encode()), Err(e) => { Err(Error::RuntimeError(format!("Unable to get selective metagraph: {e:?}")).into()) diff --git a/pallets/subtensor/runtime-api/src/lib.rs b/pallets/subtensor/runtime-api/src/lib.rs index 9516b4f8f4..a2df8a3518 100644 --- a/pallets/subtensor/runtime-api/src/lib.rs +++ b/pallets/subtensor/runtime-api/src/lib.rs @@ -12,7 +12,7 @@ use pallet_subtensor::rpc_info::{ subnet_info::{SubnetHyperparams, SubnetHyperparamsV2, SubnetInfo, SubnetInfov2}, }; use sp_runtime::AccountId32; -use subtensor_runtime_common::{AlphaCurrency, NetUid, SubId, TaoCurrency}; +use subtensor_runtime_common::{AlphaCurrency, MechId, NetUid, TaoCurrency}; // Here we declare the runtime API. It is implemented it the `impl` block in // src/neuron_info.rs, src/subnet_info.rs, and src/delegate_info.rs @@ -40,12 +40,12 @@ sp_api::decl_runtime_apis! { fn get_all_dynamic_info() -> Vec>>; fn get_all_metagraphs() -> Vec>>; fn get_metagraph(netuid: NetUid) -> Option>; - fn get_all_submetagraphs() -> Vec>>; - fn get_submetagraph(netuid: NetUid, subid: SubId) -> Option>; + fn get_all_mechagraphs() -> Vec>>; + fn get_mechagraph(netuid: NetUid, mecid: MechId) -> Option>; fn get_dynamic_info(netuid: NetUid) -> Option>; fn get_subnet_state(netuid: NetUid) -> Option>; fn get_selective_metagraph(netuid: NetUid, metagraph_indexes: Vec) -> Option>; - fn get_selective_submetagraph(netuid: NetUid, subid: SubId, metagraph_indexes: Vec) -> Option>; + fn get_selective_mechagraph(netuid: NetUid, subid: MechId, metagraph_indexes: Vec) -> Option>; fn get_subnet_to_prune() -> Option; } diff --git a/pallets/subtensor/src/coinbase/reveal_commits.rs b/pallets/subtensor/src/coinbase/reveal_commits.rs index d0c068303b..889c41d96a 100644 --- a/pallets/subtensor/src/coinbase/reveal_commits.rs +++ b/pallets/subtensor/src/coinbase/reveal_commits.rs @@ -3,7 +3,7 @@ use ark_serialize::CanonicalDeserialize; use codec::Decode; use frame_support::{dispatch, traits::OriginTrait}; use scale_info::prelude::collections::VecDeque; -use subtensor_runtime_common::{NetUid, SubId}; +use subtensor_runtime_common::{MechId, NetUid}; use tle::{ curves::drand::TinyBLS381, stream_ciphers::AESGCMStreamCipherProvider, @@ -44,10 +44,10 @@ impl Pallet { // Weights revealed must have been committed during epoch `cur_epoch - reveal_period`. let reveal_epoch = cur_epoch.saturating_sub(reveal_period); - // All subsubnets share the same epoch, so the reveal_period/reveal_epoch are also the same - // Reveal for all subsubnets - for subid in 0..SubsubnetCountCurrent::::get(netuid).into() { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + // All mechanisms share the same epoch, so the reveal_period/reveal_epoch are also the same + // Reveal for all mechanisms + for mecid in 0..MechanismCountCurrent::::get(netuid).into() { + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid.into()); // Clean expired commits for (epoch, _) in TimelockedWeightCommits::::iter_prefix(netuid_index) { @@ -58,7 +58,7 @@ impl Pallet { // No commits to reveal until at least epoch reveal_period. if cur_epoch < reveal_period { - log::trace!("Failed to reveal commit for subsubnet {netuid_index} Too early"); + log::trace!("Failed to reveal commit for mechanism {netuid_index} Too early"); return Ok(()); } @@ -75,7 +75,7 @@ impl Pallet { None => { // Round number used was not found on the chain. Skip this commit. log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} on block {commit_block} due to missing round number {round_number}; will retry every block in reveal epoch." + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} on block {commit_block} due to missing round number {round_number}; will retry every block in reveal epoch." ); unrevealed.push_back(( who, @@ -92,7 +92,7 @@ impl Pallet { Ok(c) => c, Err(e) => { log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} due to error deserializing the commit: {e:?}" + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} due to error deserializing the commit: {e:?}" ); continue; } @@ -110,7 +110,7 @@ impl Pallet { Ok(s) => s, Err(e) => { log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} due to error deserializing signature from drand pallet: {e:?}" + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} due to error deserializing signature from drand pallet: {e:?}" ); continue; } @@ -122,7 +122,7 @@ impl Pallet { Ok(d) => d, Err(e) => { log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} due to error decrypting the commit: {e:?}" + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} due to error decrypting the commit: {e:?}" ); continue; } @@ -142,7 +142,7 @@ impl Pallet { } Ok(_) => { log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} due to hotkey mismatch in payload" + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} due to hotkey mismatch in payload" ); continue; } @@ -152,7 +152,7 @@ impl Pallet { Ok(legacy) => (legacy.uids, legacy.values, legacy.version_key), Err(_) => { log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} due to error deserializing hotkey: {e:?}" + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} due to error deserializing hotkey: {e:?}" ); continue; } @@ -166,7 +166,7 @@ impl Pallet { Ok(legacy) => (legacy.uids, legacy.values, legacy.version_key), Err(e) => { log::trace!( - "Failed to reveal commit for subsubnet {netuid_index} submitted by {who:?} due to error deserializing both payload formats: {e:?}" + "Failed to reveal commit for mechanism {netuid_index} submitted by {who:?} due to error deserializing both payload formats: {e:?}" ); continue; } @@ -177,16 +177,16 @@ impl Pallet { // ------------------------------------------------------------------ // Apply weights // ------------------------------------------------------------------ - if let Err(e) = Self::do_set_sub_weights( + if let Err(e) = Self::do_set_mechanism_weights( T::RuntimeOrigin::signed(who.clone()), netuid, - SubId::from(subid), + MechId::from(mecid), uids, values, version_key, ) { log::trace!( - "Failed to `do_set_sub_weights` for subsubnet {netuid_index} submitted by {who:?}: {e:?}" + "Failed to `do_set_mechanism_weights` for mechanism {netuid_index} submitted by {who:?}: {e:?}" ); continue; } diff --git a/pallets/subtensor/src/coinbase/root.rs b/pallets/subtensor/src/coinbase/root.rs index e3acbf3432..ac99d03838 100644 --- a/pallets/subtensor/src/coinbase/root.rs +++ b/pallets/subtensor/src/coinbase/root.rs @@ -362,14 +362,14 @@ impl Pallet { /// * 'NetworkRemoved': Emitted when a network is successfully removed. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': If the specified network does not exist. + /// * 'MechanismDoesNotExist': If the specified network does not exist. /// * 'NotSubnetOwner': If the caller does not own the specified subnet. /// pub fn do_dissolve_network(netuid: NetUid) -> dispatch::DispatchResult { // 1. --- The network exists? ensure!( Self::if_subnet_exist(netuid) && netuid != NetUid::ROOT, - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // 2. --- Perform the cleanup before removing the network. @@ -532,9 +532,9 @@ impl Pallet { let _ = AssociatedEvmAddress::::clear_prefix(netuid, u32::MAX, None); // Commit-reveal / weights commits (all per-net prefixes): - let subsubnets: u8 = SubsubnetCountCurrent::::get(netuid).into(); - for subid in 0..subsubnets { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + let mechanisms: u8 = MechanismCountCurrent::::get(netuid).into(); + for subid in 0..mechanisms { + let netuid_index = Self::get_mechanism_storage_index(netuid, subid.into()); LastUpdate::::remove(netuid_index); Incentive::::remove(netuid_index); let _ = WeightCommits::::clear_prefix(netuid_index, u32::MAX, None); @@ -545,8 +545,8 @@ impl Pallet { let _ = Weights::::clear_prefix(netuid_index, u32::MAX, None); } RevealPeriodEpochs::::remove(netuid); - SubsubnetCountCurrent::::remove(netuid); - SubsubnetEmissionSplit::::remove(netuid); + MechanismCountCurrent::::remove(netuid); + MechanismEmissionSplit::::remove(netuid); // Last hotkey swap (DMAP where netuid is FIRST key → easy) let _ = LastHotkeySwapOnNetuid::::clear_prefix(netuid, u32::MAX, None); diff --git a/pallets/subtensor/src/coinbase/run_coinbase.rs b/pallets/subtensor/src/coinbase/run_coinbase.rs index d284f33eda..f1046fb682 100644 --- a/pallets/subtensor/src/coinbase/run_coinbase.rs +++ b/pallets/subtensor/src/coinbase/run_coinbase.rs @@ -648,7 +648,7 @@ impl Pallet { // Run the epoch. let hotkey_emission: Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> = - Self::epoch_with_subsubnets(netuid, pending_alpha.saturating_add(pending_swapped)); + Self::epoch_with_mechanisms(netuid, pending_alpha.saturating_add(pending_swapped)); log::debug!("hotkey_emission: {hotkey_emission:?}"); // Compute the pending validator alpha. diff --git a/pallets/subtensor/src/epoch/run_epoch.rs b/pallets/subtensor/src/epoch/run_epoch.rs index 3dfcf0ac05..7ab4446c3e 100644 --- a/pallets/subtensor/src/epoch/run_epoch.rs +++ b/pallets/subtensor/src/epoch/run_epoch.rs @@ -6,7 +6,7 @@ use safe_math::*; use sp_std::collections::btree_map::IntoIter; use sp_std::vec; use substrate_fixed::types::{I32F32, I64F64, I96F32}; -use subtensor_runtime_common::{AlphaCurrency, NetUid, NetUidStorageIndex, SubId}; +use subtensor_runtime_common::{AlphaCurrency, MechId, NetUid, NetUidStorageIndex}; #[derive(Debug, Default)] pub struct EpochTerms { @@ -65,11 +65,11 @@ impl Pallet { netuid: NetUid, rao_emission: AlphaCurrency, ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { - // Run subsubnet-style epoch - let output = Self::epoch_subsubnet(netuid, SubId::MAIN, rao_emission); + // Run mechanism-style epoch + let output = Self::epoch_mechanism(netuid, MechId::MAIN, rao_emission); // Persist values in legacy format - Self::persist_subsub_epoch_terms(netuid, SubId::MAIN, output.as_map()); + Self::persist_mechanism_epoch_terms(netuid, MechId::MAIN, output.as_map()); Self::persist_netuid_epoch_terms(netuid, output.as_map()); // Remap and return @@ -84,16 +84,16 @@ impl Pallet { netuid: NetUid, rao_emission: AlphaCurrency, ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { - Self::epoch_dense_subsubnet(netuid, SubId::MAIN, rao_emission) + Self::epoch_dense_mechanism(netuid, MechId::MAIN, rao_emission) } /// Persists per-subsubnet epoch output in state - pub fn persist_subsub_epoch_terms( + pub fn persist_mechanism_epoch_terms( netuid: NetUid, - subid: SubId, + mecid: MechId, output: &BTreeMap, ) { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); let mut terms_sorted: sp_std::vec::Vec<&EpochTerms> = output.values().collect(); terms_sorted.sort_unstable_by_key(|t| t.uid); @@ -150,13 +150,13 @@ impl Pallet { /// Calculates reward consensus and returns the emissions for uids/hotkeys in a given `netuid`. /// (Dense version used only for testing purposes.) #[allow(clippy::indexing_slicing)] - pub fn epoch_dense_subsubnet( + pub fn epoch_dense_mechanism( netuid: NetUid, - subid: SubId, + mecid: MechId, rao_emission: AlphaCurrency, ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { // Calculate netuid storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); // Get subnetwork size. let n: u16 = Self::get_subnetwork_n(netuid); @@ -585,13 +585,13 @@ impl Pallet { /// * 'debug' ( bool ): /// - Print debugging outputs. /// - pub fn epoch_subsubnet( + pub fn epoch_mechanism( netuid: NetUid, - subid: SubId, + mecid: MechId, rao_emission: AlphaCurrency, ) -> EpochOutput { // Calculate netuid storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); // Initialize output keys (neuron hotkeys) and UIDs let mut terms_map: BTreeMap = Keys::::iter_prefix(netuid) diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index f4a65de0e1..d2eba9bede 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -87,7 +87,7 @@ pub mod pallet { use substrate_fixed::types::{I96F32, U64F64}; use subtensor_macros::freeze_struct; use subtensor_runtime_common::{ - AlphaCurrency, Currency, NetUid, NetUidStorageIndex, SubId, TaoCurrency, + AlphaCurrency, Currency, MechId, NetUid, NetUidStorageIndex, TaoCurrency, }; #[cfg(not(feature = "std"))] @@ -1852,36 +1852,36 @@ pub mod pallet { pub type NetworkRegistrationStartBlock = StorageValue<_, u64, ValueQuery, DefaultNetworkRegistrationStartBlock>; - /// ====================== - /// ==== Sub-subnets ===== - /// ====================== + /// ============================ + /// ==== Subnet Mechanisms ===== + /// ============================ #[pallet::type_value] /// -- ITEM (Default number of sub-subnets) - pub fn DefaultSubsubnetCount() -> SubId { - SubId::from(1) + pub fn DefaultMechanismCount() -> MechId { + MechId::from(1) } #[pallet::type_value] /// -- ITEM (Maximum number of sub-subnets) - pub fn MaxSubsubnetCount() -> SubId { - SubId::from(8) + pub fn MaxMechanismCount() -> MechId { + MechId::from(2) } #[pallet::type_value] - /// -- ITEM (Rate limit for subsubnet count updates) - pub fn SubsubnetCountSetRateLimit() -> u64 { + /// -- ITEM (Rate limit for mechanism count updates) + pub fn MechanismCountSetRateLimit() -> u64 { prod_or_fast!(7_200, 1) } #[pallet::type_value] - /// -- ITEM (Rate limit for subsubnet emission distribution updates) - pub fn SubsubnetEmissionRateLimit() -> u64 { + /// -- ITEM (Rate limit for mechanism emission distribution updates) + pub fn MechanismEmissionRateLimit() -> u64 { prod_or_fast!(7_200, 1) } #[pallet::storage] - /// --- MAP ( netuid ) --> Current number of sub-subnets - pub type SubsubnetCountCurrent = - StorageMap<_, Twox64Concat, NetUid, SubId, ValueQuery, DefaultSubsubnetCount>; + /// --- MAP ( netuid ) --> Current number of subnet mechanisms + pub type MechanismCountCurrent = + StorageMap<_, Twox64Concat, NetUid, MechId, ValueQuery, DefaultMechanismCount>; #[pallet::storage] - /// --- MAP ( netuid ) --> Normalized vector of emission split proportion between subsubnets - pub type SubsubnetEmissionSplit = + /// --- MAP ( netuid ) --> Normalized vector of emission split proportion between subnet mechanisms + pub type MechanismEmissionSplit = StorageMap<_, Twox64Concat, NetUid, Vec, OptionQuery>; /// ================== diff --git a/pallets/subtensor/src/macros/dispatches.rs b/pallets/subtensor/src/macros/dispatches.rs index e953ac5ae3..d6a199b0f1 100644 --- a/pallets/subtensor/src/macros/dispatches.rs +++ b/pallets/subtensor/src/macros/dispatches.rs @@ -53,7 +53,7 @@ mod dispatches { /// - On successfully setting the weights on chain. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -94,7 +94,7 @@ mod dispatches { } } - /// --- Sets the caller weights for the incentive mechanism for subsubnets. The call + /// --- Sets the caller weights for the incentive mechanism for mechanisms. The call /// can be made from the hotkey account so is potentially insecure, however, the damage /// of changing weights is minimal if caught early. This function includes all the /// checks that the passed weights meet the requirements. Stored as u16s they represent @@ -114,8 +114,8 @@ mod dispatches { /// * `netuid` (u16): /// - The network uid we are setting these weights on. /// - /// * `subid` (`u8`): - /// - The u8 subsubnet identifier. + /// * `mecid` (`u8`): + /// - The u8 mechnism identifier. /// /// * `dests` (Vec): /// - The edge endpoint for the weight, i.e. j for w_ij. @@ -132,7 +132,7 @@ mod dispatches { /// - On successfully setting the weights on chain. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -159,10 +159,10 @@ mod dispatches { #[pallet::weight((Weight::from_parts(15_540_000_000, 0) .saturating_add(T::DbWeight::get().reads(4111)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] - pub fn set_sub_weights( + pub fn set_mechanism_weights( origin: OriginFor, netuid: NetUid, - subid: SubId, + mecid: MechId, dests: Vec, weights: Vec, version_key: u64, @@ -170,7 +170,7 @@ mod dispatches { if Self::get_commit_reveal_weights_enabled(netuid) { Err(Error::::CommitRevealEnabled.into()) } else { - Self::do_set_sub_weights(origin, netuid, subid, dests, weights, version_key) + Self::do_set_mechanism_weights(origin, netuid, mecid, dests, weights, version_key) } } @@ -243,7 +243,7 @@ mod dispatches { Self::do_commit_weights(origin, netuid, commit_hash) } - /// ---- Used to commit a hash of your weight values to later be revealed for subsubnets. + /// ---- Used to commit a hash of your weight values to later be revealed for mechanisms. /// /// # Args: /// * `origin`: (`::RuntimeOrigin`): @@ -252,8 +252,8 @@ mod dispatches { /// * `netuid` (`u16`): /// - The u16 network identifier. /// - /// * `subid` (`u8`): - /// - The u8 subsubnet identifier. + /// * `mecid` (`u8`): + /// - The u8 mechanism identifier. /// /// * `commit_hash` (`H256`): /// - The hash representing the committed weights. @@ -269,13 +269,13 @@ mod dispatches { #[pallet::weight((Weight::from_parts(55_130_000, 0) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] - pub fn commit_sub_weights( + pub fn commit_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit_hash: H256, ) -> DispatchResult { - Self::do_commit_sub_weights(origin, netuid, subid, commit_hash) + Self::do_commit_mechanism_weights(origin, netuid, mecid, commit_hash) } /// --- Allows a hotkey to commit weight hashes for multiple netuids as a batch. @@ -364,7 +364,7 @@ mod dispatches { Self::do_reveal_weights(origin, netuid, uids, values, salt, version_key) } - /// ---- Used to reveal the weights for a previously committed hash for subsubnets. + /// ---- Used to reveal the weights for a previously committed hash for mechanisms. /// /// # Args: /// * `origin`: (`::RuntimeOrigin`): @@ -373,8 +373,8 @@ mod dispatches { /// * `netuid` (`u16`): /// - The u16 network identifier. /// - /// * `subid` (`u8`): - /// - The u8 subsubnet identifier. + /// * `mecid` (`u8`): + /// - The u8 mechanism identifier. /// /// * `uids` (`Vec`): /// - The uids for the weights being revealed. @@ -408,16 +408,24 @@ mod dispatches { #[pallet::weight((Weight::from_parts(122_000_000, 0) .saturating_add(T::DbWeight::get().reads(16)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] - pub fn reveal_sub_weights( + pub fn reveal_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, uids: Vec, values: Vec, salt: Vec, version_key: u64, ) -> DispatchResult { - Self::do_reveal_sub_weights(origin, netuid, subid, uids, values, salt, version_key) + Self::do_reveal_mechanism_weights( + origin, + netuid, + mecid, + uids, + values, + salt, + version_key, + ) } /// ---- Used to commit encrypted commit-reveal v3 weight values to later be revealed. @@ -462,7 +470,7 @@ mod dispatches { Self::do_commit_timelocked_weights(origin, netuid, commit, reveal_round, 4) } - /// ---- Used to commit encrypted commit-reveal v3 weight values to later be revealed for subsubnets. + /// ---- Used to commit encrypted commit-reveal v3 weight values to later be revealed for mechanisms. /// /// # Args: /// * `origin`: (`::RuntimeOrigin`): @@ -471,8 +479,8 @@ mod dispatches { /// * `netuid` (`u16`): /// - The u16 network identifier. /// - /// * `subid` (`u8`): - /// - The u8 subsubnet identifier. + /// * `mecid` (`u8`): + /// - The u8 mechanism identifier. /// /// * `commit` (`Vec`): /// - The encrypted compressed commit. @@ -498,14 +506,21 @@ mod dispatches { #[pallet::weight((Weight::from_parts(77_750_000, 0) .saturating_add(T::DbWeight::get().reads(7_u64)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] - pub fn commit_crv3_sub_weights( + pub fn commit_crv3_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit: BoundedVec>, reveal_round: u64, ) -> DispatchResult { - Self::do_commit_timelocked_sub_weights(origin, netuid, subid, commit, reveal_round, 4) + Self::do_commit_timelocked_mechanism_weights( + origin, + netuid, + mecid, + commit, + reveal_round, + 4, + ) } /// ---- The implementation for batch revealing committed weights. @@ -782,7 +797,7 @@ mod dispatches { /// - On successfully serving the axon info. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -866,7 +881,7 @@ mod dispatches { /// - On successfully serving the axon info. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -975,7 +990,7 @@ mod dispatches { /// - On successfully registering a uid to a neuron slot on a subnetwork. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to register to a non existent network. /// /// * 'TooManyRegistrationsThisBlock': @@ -1300,7 +1315,7 @@ mod dispatches { #[pallet::call_index(59)] #[pallet::weight((Weight::from_parts(235_400_000, 0) .saturating_add(T::DbWeight::get().reads(37_u64)) - .saturating_add(T::DbWeight::get().writes(60_u64)), DispatchClass::Normal, Pays::No))] + .saturating_add(T::DbWeight::get().writes(51_u64)), DispatchClass::Normal, Pays::Yes))] pub fn register_network(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { Self::do_register_network(origin, &hotkey, 1, None) } @@ -1366,7 +1381,7 @@ mod dispatches { /// - On successfully registering a child to a hotkey. /// /// # Errors: - /// * `SubNetworkDoesNotExist`: + /// * `MechanismDoesNotExist`: /// - Attempting to register to a non-existent network. /// * `RegistrationNotPermittedOnRootSubnet`: /// - Attempting to register a child on the root network. @@ -1586,8 +1601,8 @@ mod dispatches { /// User register a new subnetwork #[pallet::call_index(79)] #[pallet::weight((Weight::from_parts(234_200_000, 0) - .saturating_add(T::DbWeight::get().reads(36_u64)) - .saturating_add(T::DbWeight::get().writes(59_u64)), DispatchClass::Normal, Pays::No))] + .saturating_add(T::DbWeight::get().reads(36_u64)) + .saturating_add(T::DbWeight::get().writes(50_u64)), DispatchClass::Normal, Pays::Yes))] pub fn register_network_with_identity( origin: OriginFor, hotkey: T::AccountId, @@ -2295,7 +2310,7 @@ mod dispatches { } /// ---- Used to commit timelock encrypted commit-reveal weight values to later be revealed for - /// a subsubnet. + /// a mechanism. /// /// # Args: /// * `origin`: (`::RuntimeOrigin`): @@ -2304,8 +2319,8 @@ mod dispatches { /// * `netuid` (`u16`): /// - The u16 network identifier. /// - /// * `subid` (`u8`): - /// - The u8 subsubnet identifier. + /// * `mecid` (`u8`): + /// - The u8 mechanism identifier. /// /// * `commit` (`Vec`): /// - The encrypted compressed commit. @@ -2326,33 +2341,22 @@ mod dispatches { #[pallet::weight((Weight::from_parts(84_020_000, 0) .saturating_add(T::DbWeight::get().reads(9_u64)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] - pub fn commit_timelocked_sub_weights( + pub fn commit_timelocked_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit: BoundedVec>, reveal_round: u64, commit_reveal_version: u16, ) -> DispatchResult { - Self::do_commit_timelocked_sub_weights( + Self::do_commit_timelocked_mechanism_weights( origin, netuid, - subid, + mecid, commit, reveal_round, commit_reveal_version, ) } - - /// Remove a user's subnetwork - /// The caller must be root - #[pallet::call_index(120)] - #[pallet::weight((Weight::from_parts(119_000_000, 0) - .saturating_add(T::DbWeight::get().reads(6)) - .saturating_add(T::DbWeight::get().writes(31)), DispatchClass::Operational, Pays::No))] - pub fn root_dissolve_network(origin: OriginFor, netuid: NetUid) -> DispatchResult { - ensure_root(origin)?; - Self::do_dissolve_network(netuid) - } } } diff --git a/pallets/subtensor/src/macros/errors.rs b/pallets/subtensor/src/macros/errors.rs index 8ae3566819..e962b661ca 100644 --- a/pallets/subtensor/src/macros/errors.rs +++ b/pallets/subtensor/src/macros/errors.rs @@ -7,8 +7,6 @@ mod errors { #[derive(PartialEq)] #[pallet::error] pub enum Error { - /// The subnet does not exist. - SubNetworkDoesNotExist, /// The root network does not exist. RootNetworkDoesNotExist, /// The user is trying to serve an axon which is not of type 4 (IPv4) or 6 (IPv6). @@ -168,7 +166,7 @@ mod errors { TxChildkeyTakeRateLimitExceeded, /// Invalid identity. InvalidIdentity, - /// Trying to register a subnet into a mechanism that does not exist. + /// Subnet mechanism does not exist. MechanismDoesNotExist, /// Trying to unstake your lock amount. CannotUnstakeLock, diff --git a/pallets/subtensor/src/rpc_info/metagraph.rs b/pallets/subtensor/src/rpc_info/metagraph.rs index 2d3ef32509..d0d7b1b94e 100644 --- a/pallets/subtensor/src/rpc_info/metagraph.rs +++ b/pallets/subtensor/src/rpc_info/metagraph.rs @@ -8,7 +8,7 @@ use pallet_commitments::GetCommitments; use substrate_fixed::types::I64F64; use substrate_fixed::types::I96F32; use subtensor_macros::freeze_struct; -use subtensor_runtime_common::{AlphaCurrency, NetUid, NetUidStorageIndex, SubId, TaoCurrency}; +use subtensor_runtime_common::{AlphaCurrency, MechId, NetUid, NetUidStorageIndex, TaoCurrency}; #[freeze_struct("6fc49d5a7dc0e339")] #[derive(Decode, Encode, PartialEq, Eq, Clone, Debug, TypeInfo)] @@ -805,17 +805,17 @@ impl Pallet { metagraphs } - pub fn get_submetagraph(netuid: NetUid, subid: SubId) -> Option> { - if Self::ensure_subsubnet_exists(netuid, subid).is_err() { + pub fn get_mechagraph(netuid: NetUid, mecid: MechId) -> Option> { + if Self::ensure_mechanism_exists(netuid, mecid).is_err() { return None; } // Get netuid metagraph let maybe_meta = Self::get_metagraph(netuid); if let Some(mut meta) = maybe_meta { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); - // Update with subsubnet information + // Update with mechanism information meta.netuid = NetUid::from(u16::from(netuid_index)).into(); meta.last_update = LastUpdate::::get(netuid_index) .into_iter() @@ -832,13 +832,13 @@ impl Pallet { } } - pub fn get_all_submetagraphs() -> Vec>> { + pub fn get_all_mechagraphs() -> Vec>> { let netuids = Self::get_all_subnet_netuids(); let mut metagraphs = Vec::>>::new(); for netuid in netuids.clone().iter() { - let subsub_count = u8::from(SubsubnetCountCurrent::::get(netuid)); - for subid in 0..subsub_count { - metagraphs.push(Self::get_submetagraph(*netuid, SubId::from(subid))); + let mechanism_count = u8::from(MechanismCountCurrent::::get(netuid)); + for mecid in 0..mechanism_count { + metagraphs.push(Self::get_mechagraph(*netuid, MechId::from(mecid))); } } metagraphs @@ -860,9 +860,9 @@ impl Pallet { } } - pub fn get_selective_submetagraph( + pub fn get_selective_mechagraph( netuid: NetUid, - subid: SubId, + mecid: MechId, metagraph_indexes: Vec, ) -> Option> { if !Self::if_subnet_exist(netuid) { @@ -870,7 +870,7 @@ impl Pallet { } else { let mut result = SelectiveMetagraph::default(); for index in metagraph_indexes.iter() { - let value = Self::get_single_selective_submetagraph(netuid, subid, *index); + let value = Self::get_single_selective_mechagraph(netuid, mecid, *index); result.merge_value(&value, *index as usize); } Some(result) @@ -1441,14 +1441,14 @@ impl Pallet { } } - fn get_single_selective_submetagraph( + fn get_single_selective_mechagraph( netuid: NetUid, - subid: SubId, + mecid: MechId, metagraph_index: u16, ) -> SelectiveMetagraph { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); - // Default to netuid, replace as needed for subid + // Default to netuid, replace as needed for mecid match SelectiveMetagraphIndex::from_index(metagraph_index as usize) { Some(SelectiveMetagraphIndex::Incentives) => SelectiveMetagraph { netuid: netuid.into(), diff --git a/pallets/subtensor/src/staking/recycle_alpha.rs b/pallets/subtensor/src/staking/recycle_alpha.rs index 4c1bbd0b9f..f803838743 100644 --- a/pallets/subtensor/src/staking/recycle_alpha.rs +++ b/pallets/subtensor/src/staking/recycle_alpha.rs @@ -25,7 +25,7 @@ impl Pallet { ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); ensure!( @@ -93,7 +93,7 @@ impl Pallet { ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); ensure!( diff --git a/pallets/subtensor/src/staking/remove_stake.rs b/pallets/subtensor/src/staking/remove_stake.rs index 8a691a9866..bb136c1196 100644 --- a/pallets/subtensor/src/staking/remove_stake.rs +++ b/pallets/subtensor/src/staking/remove_stake.rs @@ -445,7 +445,7 @@ impl Pallet { // 1) Ensure the subnet exists. ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // 2) Owner / lock cost. diff --git a/pallets/subtensor/src/staking/set_children.rs b/pallets/subtensor/src/staking/set_children.rs index c6c37f7e96..b4629ec54d 100644 --- a/pallets/subtensor/src/staking/set_children.rs +++ b/pallets/subtensor/src/staking/set_children.rs @@ -23,7 +23,7 @@ impl Pallet { /// - If all checks pass and setting the childkeys is scheduled. /// /// # Errors: - /// * `SubNetworkDoesNotExist`: + /// * `MechanismDoesNotExist`: /// - Attempting to register to a non-existent network. /// * `RegistrationNotPermittedOnRootSubnet`: /// - Attempting to register a child on the root network. @@ -64,7 +64,7 @@ impl Pallet { // Check that the network we are trying to create the child on exists. ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // Check that the coldkey owns the hotkey. @@ -148,7 +148,7 @@ impl Pallet { /// - On successfully registering children to a hotkey. /// /// # Errors: - /// * `SubNetworkDoesNotExist`: + /// * `MechanismDoesNotExist`: /// - Attempting to register to a non-existent network. /// * `RegistrationNotPermittedOnRootSubnet`: /// - Attempting to register a child on the root network. diff --git a/pallets/subtensor/src/subnets/subsubnet.rs b/pallets/subtensor/src/subnets/mechanism.rs similarity index 79% rename from pallets/subtensor/src/subnets/subsubnet.rs rename to pallets/subtensor/src/subnets/mechanism.rs index 337bf809fd..f8fa76ad51 100644 --- a/pallets/subtensor/src/subnets/subsubnet.rs +++ b/pallets/subtensor/src/subnets/mechanism.rs @@ -6,7 +6,7 @@ use crate::epoch::run_epoch::EpochTerms; use alloc::collections::BTreeMap; use safe_math::*; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{AlphaCurrency, NetUid, NetUidStorageIndex, SubId}; +use subtensor_runtime_common::{AlphaCurrency, MechId, NetUid, NetUidStorageIndex}; pub type LeaseId = u32; @@ -27,12 +27,12 @@ pub type BalanceOf = /// pub const GLOBAL_MAX_SUBNET_COUNT: u16 = 4096; -// Theoretical maximum number of subsubnets per subnet -// GLOBAL_MAX_SUBNET_COUNT * MAX_SUBSUBNET_COUNT_PER_SUBNET should be 0x10000 -pub const MAX_SUBSUBNET_COUNT_PER_SUBNET: u8 = 16; +// Theoretical maximum number of mechanisms per subnet +// GLOBAL_MAX_SUBNET_COUNT * MAX_MECHANISM_COUNT_PER_SUBNET should be 0x10000 +pub const MAX_MECHANISM_COUNT_PER_SUBNET: u8 = 16; impl Pallet { - pub fn get_subsubnet_storage_index(netuid: NetUid, sub_id: SubId) -> NetUidStorageIndex { + pub fn get_mechanism_storage_index(netuid: NetUid, sub_id: MechId) -> NetUidStorageIndex { u16::from(sub_id) .saturating_mul(GLOBAL_MAX_SUBNET_COUNT) .saturating_add(u16::from(netuid)) @@ -41,7 +41,7 @@ impl Pallet { pub fn get_netuid_and_subid( netuid_index: NetUidStorageIndex, - ) -> Result<(NetUid, SubId), Error> { + ) -> Result<(NetUid, MechId), Error> { let maybe_netuid = u16::from(netuid_index).checked_rem(GLOBAL_MAX_SUBNET_COUNT); if let Some(netuid_u16) = maybe_netuid { let netuid = NetUid::from(netuid_u16); @@ -49,68 +49,68 @@ impl Pallet { // Make sure the base subnet exists ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // Extract sub_id let sub_id_u8 = u8::try_from(u16::from(netuid_index).safe_div(GLOBAL_MAX_SUBNET_COUNT)) - .map_err(|_| Error::::SubNetworkDoesNotExist)?; - let sub_id = SubId::from(sub_id_u8); + .map_err(|_| Error::::MechanismDoesNotExist)?; + let sub_id = MechId::from(sub_id_u8); - if SubsubnetCountCurrent::::get(netuid) > sub_id { + if MechanismCountCurrent::::get(netuid) > sub_id { Ok((netuid, sub_id)) } else { - Err(Error::::SubNetworkDoesNotExist.into()) + Err(Error::::MechanismDoesNotExist.into()) } } else { - Err(Error::::SubNetworkDoesNotExist.into()) + Err(Error::::MechanismDoesNotExist.into()) } } - pub fn get_current_subsubnet_count(netuid: NetUid) -> SubId { - SubsubnetCountCurrent::::get(netuid) + pub fn get_current_mechanism_count(netuid: NetUid) -> MechId { + MechanismCountCurrent::::get(netuid) } - pub fn ensure_subsubnet_exists(netuid: NetUid, sub_id: SubId) -> DispatchResult { + pub fn ensure_mechanism_exists(netuid: NetUid, sub_id: MechId) -> DispatchResult { // Make sure the base subnet exists ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); - // Make sure the subsub limit is not exceeded + // Make sure the mechanism limit is not exceeded ensure!( - SubsubnetCountCurrent::::get(netuid) > sub_id, - Error::::SubNetworkDoesNotExist + MechanismCountCurrent::::get(netuid) > sub_id, + Error::::MechanismDoesNotExist ); Ok(()) } /// Set the desired valus of sub-subnet count for a subnet identified /// by netuid - pub fn do_set_subsubnet_count(netuid: NetUid, subsubnet_count: SubId) -> DispatchResult { + pub fn do_set_mechanism_count(netuid: NetUid, mechanism_count: MechId) -> DispatchResult { // Make sure the subnet exists ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // Count cannot be zero - ensure!(subsubnet_count > 0.into(), Error::::InvalidValue); + ensure!(mechanism_count > 0.into(), Error::::InvalidValue); // Make sure we are not exceeding the max sub-subnet count ensure!( - subsubnet_count <= MaxSubsubnetCount::::get(), + mechanism_count <= MaxMechanismCount::::get(), Error::::InvalidValue ); // Make sure we are not allowing numbers that will break the math ensure!( - subsubnet_count <= SubId::from(MAX_SUBSUBNET_COUNT_PER_SUBNET), + mechanism_count <= MechId::from(MAX_MECHANISM_COUNT_PER_SUBNET), Error::::InvalidValue ); - Self::update_subsubnet_counts_if_needed(netuid, subsubnet_count); + Self::update_mechanism_counts_if_needed(netuid, mechanism_count); Ok(()) } @@ -118,14 +118,14 @@ impl Pallet { /// Update current count for a subnet identified by netuid /// - Cleans up all sub-subnet maps if count is reduced /// - pub fn update_subsubnet_counts_if_needed(netuid: NetUid, new_count: SubId) { - let old_count = u8::from(SubsubnetCountCurrent::::get(netuid)); + pub fn update_mechanism_counts_if_needed(netuid: NetUid, new_count: MechId) { + let old_count = u8::from(MechanismCountCurrent::::get(netuid)); let new_count_u8 = u8::from(new_count); if old_count != new_count_u8 { if old_count > new_count_u8 { - for subid in new_count_u8..old_count { + for mecid in new_count_u8..old_count { let netuid_index = - Self::get_subsubnet_storage_index(netuid, SubId::from(subid)); + Self::get_mechanism_storage_index(netuid, MechId::from(mecid)); // Cleanup Weights let _ = Weights::::clear_prefix(netuid_index, u32::MAX, None); @@ -148,10 +148,10 @@ impl Pallet { } } - SubsubnetCountCurrent::::insert(netuid, SubId::from(new_count)); + MechanismCountCurrent::::insert(netuid, MechId::from(new_count)); // Reset split back to even - SubsubnetEmissionSplit::::remove(netuid); + MechanismEmissionSplit::::remove(netuid); } } @@ -159,14 +159,14 @@ impl Pallet { // Make sure the subnet exists ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); if let Some(split) = maybe_split { // Check the length ensure!(!split.is_empty(), Error::::InvalidValue); ensure!( - split.len() <= u8::from(SubsubnetCountCurrent::::get(netuid)) as usize, + split.len() <= u8::from(MechanismCountCurrent::::get(netuid)) as usize, Error::::InvalidValue ); @@ -174,20 +174,20 @@ impl Pallet { let total: u64 = split.iter().map(|s| *s as u64).sum(); ensure!(total == u16::MAX as u64, Error::::InvalidValue); - SubsubnetEmissionSplit::::insert(netuid, split); + MechanismEmissionSplit::::insert(netuid, split); } else { - SubsubnetEmissionSplit::::remove(netuid); + MechanismEmissionSplit::::remove(netuid); } Ok(()) } /// Split alpha emission in sub-subnet proportions - /// stored in SubsubnetEmissionSplit + /// stored in MechanismEmissionSplit /// pub fn split_emissions(netuid: NetUid, alpha: AlphaCurrency) -> Vec { - let subsubnet_count = u64::from(SubsubnetCountCurrent::::get(netuid)); - let maybe_split = SubsubnetEmissionSplit::::get(netuid); + let mechanism_count = u64::from(MechanismCountCurrent::::get(netuid)); + let maybe_split = MechanismEmissionSplit::::get(netuid); // Unset split means even distribution let mut result: Vec = if let Some(split) = maybe_split { @@ -202,16 +202,16 @@ impl Pallet { }) .collect() } else { - let per_subsubnet = u64::from(alpha).safe_div(subsubnet_count); - vec![AlphaCurrency::from(per_subsubnet); subsubnet_count as usize] + let per_mechanism = u64::from(alpha).safe_div(mechanism_count); + vec![AlphaCurrency::from(per_mechanism); mechanism_count as usize] }; - // Trim / extend and pad with zeroes if result is shorter than subsubnet_count - if result.len() != subsubnet_count as usize { - result.resize(subsubnet_count as usize, 0u64.into()); // pad with AlphaCurrency::from(0) + // Trim / extend and pad with zeroes if result is shorter than mechanism_count + if result.len() != mechanism_count as usize { + result.resize(mechanism_count as usize, 0u64.into()); // pad with AlphaCurrency::from(0) } - // If there's any rounding error or lost due to truncation emission, credit it to subsubnet 0 + // If there's any rounding error or lost due to truncation emission, credit it to mechanism 0 let rounding_err = u64::from(alpha).saturating_sub(result.iter().map(|s| u64::from(*s)).sum()); if let Some(cell) = result.first_mut() { @@ -242,7 +242,7 @@ impl Pallet { /// Runs the epoch function for each sub-subnet and consolidates hotkey_emission /// into a single vector. /// - pub fn epoch_with_subsubnets( + pub fn epoch_with_mechanisms( netuid: NetUid, rao_emission: AlphaCurrency, ) -> Vec<(T::AccountId, AlphaCurrency, AlphaCurrency)> { @@ -250,18 +250,18 @@ impl Pallet { Self::split_emissions(netuid, rao_emission) .into_iter() .enumerate() - // Run epoch function for each subsubnet to distribute its portion of emissions + // Run epoch function for each mechanism to distribute its portion of emissions .flat_map(|(sub_id_usize, sub_emission)| { let sub_id_u8: u8 = sub_id_usize.try_into().unwrap_or_default(); - let sub_id = SubId::from(sub_id_u8); + let sub_id = MechId::from(sub_id_u8); - // Run epoch function on the subsubnet emission - let epoch_output = Self::epoch_subsubnet(netuid, sub_id, sub_emission); - Self::persist_subsub_epoch_terms(netuid, sub_id, epoch_output.as_map()); + // Run epoch function on the mechanism emission + let epoch_output = Self::epoch_mechanism(netuid, sub_id, sub_emission); + Self::persist_mechanism_epoch_terms(netuid, sub_id, epoch_output.as_map()); - // Calculate subsubnet weight from the split emission (not the other way because preserving + // Calculate mechanism weight from the split emission (not the other way because preserving // emission accuracy is the priority) - // For zero emission the first subsubnet gets full weight + // For zero emission the first mechanism gets full weight let sub_weight = U64F64::saturating_from_num(sub_emission).safe_div_or( U64F64::saturating_from_num(rao_emission), U64F64::saturating_from_num(if sub_id_u8 == 0 { 1 } else { 0 }), @@ -277,7 +277,7 @@ impl Pallet { .fold(BTreeMap::new(), |mut acc, (hotkey, (terms, sub_weight))| { acc.entry(hotkey) .and_modify(|acc_terms| { - // Server and validator emission come from subsubnet emission and need to be added up + // Server and validator emission come from mechanism emission and need to be added up acc_terms.validator_emission = acc_terms .validator_emission .saturating_add(terms.validator_emission); diff --git a/pallets/subtensor/src/subnets/mod.rs b/pallets/subtensor/src/subnets/mod.rs index a3705af084..e93628eef4 100644 --- a/pallets/subtensor/src/subnets/mod.rs +++ b/pallets/subtensor/src/subnets/mod.rs @@ -1,9 +1,9 @@ use super::*; pub mod leasing; +pub mod mechanism; pub mod registration; pub mod serving; pub mod subnet; -pub mod subsubnet; pub mod symbols; pub mod uids; pub mod weights; diff --git a/pallets/subtensor/src/subnets/registration.rs b/pallets/subtensor/src/subnets/registration.rs index a620755f2e..90ba2ea1aa 100644 --- a/pallets/subtensor/src/subnets/registration.rs +++ b/pallets/subtensor/src/subnets/registration.rs @@ -55,7 +55,7 @@ impl Pallet { /// - On successfully registereing a uid to a neuron slot on a subnetwork. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to registed to a non existent network. /// /// * 'TooManyRegistrationsThisBlock': @@ -80,7 +80,7 @@ impl Pallet { ); ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // --- 3. Ensure the passed network allows registrations. @@ -193,7 +193,7 @@ impl Pallet { /// - On successfully registereing a uid to a neuron slot on a subnetwork. /// /// # Raises: - /// *'SubNetworkDoesNotExist': + /// *'MechanismDoesNotExist': /// - Attempting to registed to a non existent network. /// /// *'TooManyRegistrationsThisBlock': @@ -238,7 +238,7 @@ impl Pallet { ); ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // --- 3. Ensure the passed network allows registrations. diff --git a/pallets/subtensor/src/subnets/serving.rs b/pallets/subtensor/src/subnets/serving.rs index ae1c97cc7c..cdaf39e51b 100644 --- a/pallets/subtensor/src/subnets/serving.rs +++ b/pallets/subtensor/src/subnets/serving.rs @@ -40,7 +40,7 @@ impl Pallet { /// - On successfully serving the axon info. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -144,7 +144,7 @@ impl Pallet { /// - On successfully serving the axon info. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': diff --git a/pallets/subtensor/src/subnets/subnet.rs b/pallets/subtensor/src/subnets/subnet.rs index bbb9ff9b11..c6a9fd8840 100644 --- a/pallets/subtensor/src/subnets/subnet.rs +++ b/pallets/subtensor/src/subnets/subnet.rs @@ -343,7 +343,7 @@ impl Pallet { /// /// # Raises /// - /// * `Error::::SubNetworkDoesNotExist`: If the subnet does not exist. + /// * `Error::::MechanismDoesNotExist`: If the subnet does not exist. /// * `DispatchError::BadOrigin`: If the caller is not the subnet owner. /// * `Error::::FirstEmissionBlockNumberAlreadySet`: If the last emission block number has already been set. /// @@ -353,7 +353,7 @@ impl Pallet { pub fn do_start_call(origin: T::RuntimeOrigin, netuid: NetUid) -> DispatchResult { ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); Self::ensure_subnet_owner(origin, netuid)?; ensure!( diff --git a/pallets/subtensor/src/subnets/uids.rs b/pallets/subtensor/src/subnets/uids.rs index e01f17cad6..cf639f9fbf 100644 --- a/pallets/subtensor/src/subnets/uids.rs +++ b/pallets/subtensor/src/subnets/uids.rs @@ -25,8 +25,8 @@ impl Pallet { Emission::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0.into())); Trust::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0)); Consensus::::mutate(netuid, |v| Self::set_element_at(v, neuron_index, 0)); - for subid in 0..SubsubnetCountCurrent::::get(netuid).into() { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + for mecid in 0..MechanismCountCurrent::::get(netuid).into() { + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid.into()); Incentive::::mutate(netuid_index, |v| Self::set_element_at(v, neuron_index, 0)); Bonds::::remove(netuid_index, neuron_uid); // Remove bonds for Validator. @@ -114,8 +114,8 @@ impl Pallet { Active::::mutate(netuid, |v| v.push(true)); Emission::::mutate(netuid, |v| v.push(0.into())); Consensus::::mutate(netuid, |v| v.push(0)); - for subid in 0..SubsubnetCountCurrent::::get(netuid).into() { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + for mecid in 0..MechanismCountCurrent::::get(netuid).into() { + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid.into()); Incentive::::mutate(netuid_index, |v| v.push(0)); LastUpdate::::mutate(netuid_index, |v| v.push(block_number)); } @@ -135,7 +135,7 @@ impl Pallet { // Reasonable limits ensure!( Self::if_subnet_exist(netuid), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); ensure!( max_n >= MinAllowedUids::::get(netuid), @@ -178,7 +178,7 @@ impl Pallet { let mut removed_uids = BTreeSet::new(); let mut uids_left_to_process = current_n; - let subsubnets_count = SubsubnetCountCurrent::::get(netuid).into(); + let mechanisms_count = MechanismCountCurrent::::get(netuid).into(); // Iterate from the end (lowest emitters) to the beginning for i in (0..current_n).rev() { @@ -212,8 +212,8 @@ impl Pallet { #[allow(unknown_lints)] Keys::::remove(netuid, neuron_uid); BlockAtRegistration::::remove(netuid, neuron_uid); - for subid in 0..subsubnets_count { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + for mecid in 0..mechanisms_count { + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid.into()); Weights::::remove(netuid_index, neuron_uid); Bonds::::remove(netuid_index, neuron_uid); } @@ -282,9 +282,9 @@ impl Pallet { ValidatorPermit::::insert(netuid, trimmed_vpermit); StakeWeight::::insert(netuid, trimmed_stake_weight); - // Update incentives/lastupdates for subsubnets - for subid in 0..subsubnets_count { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + // Update incentives/lastupdates for mechanisms + for mecid in 0..mechanisms_count { + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid.into()); let incentive = Incentive::::get(netuid_index); let lastupdate = LastUpdate::::get(netuid_index); let mut trimmed_incentive = Vec::with_capacity(trimmed_uids.len()); @@ -320,8 +320,8 @@ impl Pallet { Keys::::swap(netuid, old_neuron_uid, netuid, new_neuron_uid); BlockAtRegistration::::swap(netuid, old_neuron_uid, netuid, new_neuron_uid); - for subid in 0..subsubnets_count { - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid.into()); + for mecid in 0..mechanisms_count { + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid.into()); // Swap to new position and remap all target uids Weights::::swap(netuid_index, old_neuron_uid, netuid_index, new_neuron_uid); diff --git a/pallets/subtensor/src/subnets/weights.rs b/pallets/subtensor/src/subnets/weights.rs index b751630d85..61b64df137 100644 --- a/pallets/subtensor/src/subnets/weights.rs +++ b/pallets/subtensor/src/subnets/weights.rs @@ -10,7 +10,7 @@ use sp_runtime::{ traits::{BlakeTwo256, Hash}, }; use sp_std::{collections::vec_deque::VecDeque, vec}; -use subtensor_runtime_common::{NetUid, NetUidStorageIndex, SubId}; +use subtensor_runtime_common::{MechId, NetUid, NetUidStorageIndex}; impl Pallet { /// ---- The implementation for committing weight hashes. @@ -46,29 +46,29 @@ impl Pallet { netuid: NetUid, commit_hash: H256, ) -> DispatchResult { - Self::internal_commit_weights(origin, netuid, SubId::MAIN, commit_hash) + Self::internal_commit_weights(origin, netuid, MechId::MAIN, commit_hash) } - pub fn do_commit_sub_weights( + pub fn do_commit_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit_hash: H256, ) -> DispatchResult { - Self::internal_commit_weights(origin, netuid, subid, commit_hash) + Self::internal_commit_weights(origin, netuid, mecid, commit_hash) } fn internal_commit_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit_hash: H256, ) -> DispatchResult { - // Ensure netuid and subid exist - Self::ensure_subsubnet_exists(netuid, subid)?; + // Ensure netuid and mecid exist + Self::ensure_mechanism_exists(netuid, mecid)?; // Calculate subnet storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); // 1. Verify the caller's signature (hotkey). let who = ensure_signed(origin)?; @@ -267,17 +267,17 @@ impl Pallet { Self::internal_commit_timelocked_weights( origin, netuid, - SubId::MAIN, + MechId::MAIN, commit, reveal_round, commit_reveal_version, ) } - pub fn do_commit_timelocked_sub_weights( + pub fn do_commit_timelocked_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit: BoundedVec>, reveal_round: u64, commit_reveal_version: u16, @@ -285,7 +285,7 @@ impl Pallet { Self::internal_commit_timelocked_weights( origin, netuid, - subid, + mecid, commit, reveal_round, commit_reveal_version, @@ -295,16 +295,16 @@ impl Pallet { pub fn internal_commit_timelocked_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, commit: BoundedVec>, reveal_round: u64, commit_reveal_version: u16, ) -> DispatchResult { - // Ensure netuid and subid exist - Self::ensure_subsubnet_exists(netuid, subid)?; + // Ensure netuid and mecid exist + Self::ensure_mechanism_exists(netuid, mecid)?; // Calculate netuid storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); // 1. Verify the caller's signature (hotkey). let who = ensure_signed(origin)?; @@ -425,32 +425,40 @@ impl Pallet { salt: Vec, version_key: u64, ) -> DispatchResult { - Self::internal_reveal_weights(origin, netuid, SubId::MAIN, uids, values, salt, version_key) + Self::internal_reveal_weights( + origin, + netuid, + MechId::MAIN, + uids, + values, + salt, + version_key, + ) } - pub fn do_reveal_sub_weights( + pub fn do_reveal_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, uids: Vec, values: Vec, salt: Vec, version_key: u64, ) -> DispatchResult { - Self::internal_reveal_weights(origin, netuid, subid, uids, values, salt, version_key) + Self::internal_reveal_weights(origin, netuid, mecid, uids, values, salt, version_key) } fn internal_reveal_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, uids: Vec, values: Vec, salt: Vec, version_key: u64, ) -> DispatchResult { // Calculate netuid storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); // --- 1. Check the caller's signature (hotkey). let who = ensure_signed(origin.clone())?; @@ -525,10 +533,10 @@ impl Pallet { } // --- 12. Proceed to set the revealed weights. - Self::do_set_sub_weights( + Self::do_set_mechanism_weights( origin, netuid, - subid, + mecid, uids.clone(), values.clone(), version_key, @@ -603,7 +611,7 @@ impl Pallet { version_keys: Vec, ) -> DispatchResult { // Calculate netuid storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, SubId::MAIN); + let netuid_index = Self::get_mechanism_storage_index(netuid, MechId::MAIN); // --- 1. Check that the input lists are of the same length. let num_reveals = uids_list.len(); @@ -740,13 +748,13 @@ impl Pallet { fn internal_set_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, uids: Vec, values: Vec, version_key: u64, ) -> dispatch::DispatchResult { // Calculate subnet storage index - let netuid_index = Self::get_subsubnet_storage_index(netuid, subid); + let netuid_index = Self::get_mechanism_storage_index(netuid, mecid); // --- 1. Check the caller's signature. This is the hotkey of a registered account. let hotkey = ensure_signed(origin)?; @@ -764,7 +772,7 @@ impl Pallet { ); // --- 3. Check to see if this is a valid network and sub-subnet. - Self::ensure_subsubnet_exists(netuid, subid)?; + Self::ensure_mechanism_exists(netuid, mecid)?; // --- 4. Check to see if the number of uids is within the max allowed uids for this network. ensure!( @@ -875,7 +883,7 @@ impl Pallet { /// - On successfully setting the weights on chain. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -915,7 +923,7 @@ impl Pallet { values: Vec, version_key: u64, ) -> dispatch::DispatchResult { - Self::internal_set_weights(origin, netuid, SubId::MAIN, uids, values, version_key) + Self::internal_set_weights(origin, netuid, MechId::MAIN, uids, values, version_key) } /// ---- The implementation for the extrinsic set_weights. @@ -927,7 +935,7 @@ impl Pallet { /// * 'netuid' (u16): /// - The u16 network identifier. /// - /// * 'subid' (u8): + /// * 'mecid' (u8): /// - The u8 identifier of sub-subnet. /// /// * 'uids' ( Vec ): @@ -944,7 +952,7 @@ impl Pallet { /// - On successfully setting the weights on chain. /// /// # Raises: - /// * 'SubNetworkDoesNotExist': + /// * 'MechanismDoesNotExist': /// - Attempting to set weights on a non-existent network. /// /// * 'NotRegistered': @@ -977,15 +985,15 @@ impl Pallet { /// * 'MaxWeightExceeded': /// - Attempting to set weights with max value exceeding limit. /// - pub fn do_set_sub_weights( + pub fn do_set_mechanism_weights( origin: T::RuntimeOrigin, netuid: NetUid, - subid: SubId, + mecid: MechId, uids: Vec, values: Vec, version_key: u64, ) -> dispatch::DispatchResult { - Self::internal_set_weights(origin, netuid, subid, uids, values, version_key) + Self::internal_set_weights(origin, netuid, mecid, uids, values, version_key) } /// ---- The implementation for the extrinsic batch_set_weights. @@ -1113,7 +1121,7 @@ impl Pallet { } } - // --- 3. Non registered peers cant pass. Neither can non-existing subid + // --- 3. Non registered peers cant pass. Neither can non-existing mecid false } diff --git a/pallets/subtensor/src/swap/swap_hotkey.rs b/pallets/subtensor/src/swap/swap_hotkey.rs index 19737f765c..4509c57864 100644 --- a/pallets/subtensor/src/swap/swap_hotkey.rs +++ b/pallets/subtensor/src/swap/swap_hotkey.rs @@ -2,7 +2,7 @@ use super::*; use frame_support::weights::Weight; use sp_core::Get; use substrate_fixed::types::U64F64; -use subtensor_runtime_common::{Currency, NetUid, SubId}; +use subtensor_runtime_common::{Currency, MechId, NetUid}; impl Pallet { /// Swaps the hotkey of a coldkey account. @@ -411,8 +411,8 @@ impl Pallet { // 3.5 Swap WeightCommits // WeightCommits( hotkey ) --> Vec -- the weight commits for the hotkey. if is_network_member { - for subid in 0..SubsubnetCountCurrent::::get(netuid).into() { - let netuid_index = Self::get_subsubnet_storage_index(netuid, SubId::from(subid)); + for mecid in 0..MechanismCountCurrent::::get(netuid).into() { + let netuid_index = Self::get_mechanism_storage_index(netuid, MechId::from(mecid)); if let Ok(old_weight_commits) = WeightCommits::::try_get(netuid_index, old_hotkey) { diff --git a/pallets/subtensor/src/tests/children.rs b/pallets/subtensor/src/tests/children.rs index 67dfe47fbe..cf11cf6190 100644 --- a/pallets/subtensor/src/tests/children.rs +++ b/pallets/subtensor/src/tests/children.rs @@ -62,7 +62,7 @@ fn test_do_set_child_singular_network_does_not_exist() { netuid, vec![(proportion, child)] ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } @@ -328,7 +328,7 @@ fn test_add_singular_child() { netuid, vec![(u64::MAX, child)] ), - Err(Error::::SubNetworkDoesNotExist.into()) + Err(Error::::MechanismDoesNotExist.into()) ); add_network(netuid, 1, 0); step_rate_limit(&TransactionType::SetChildren, netuid); @@ -472,7 +472,7 @@ fn test_do_set_empty_children_network_does_not_exist() { netuid, vec![] ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } @@ -601,7 +601,7 @@ fn test_do_schedule_children_multiple_network_does_not_exist() { netuid, vec![(proportion, child1)] ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } @@ -1200,7 +1200,7 @@ fn test_do_revoke_children_multiple_network_does_not_exist() { netuid, vec![(u64::MAX / 2, child1), (u64::MAX / 2, child2)] ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } diff --git a/pallets/subtensor/src/tests/subsubnet.rs b/pallets/subtensor/src/tests/mechanism.rs similarity index 79% rename from pallets/subtensor/src/tests/subsubnet.rs rename to pallets/subtensor/src/tests/mechanism.rs index 8b128a7241..8e5b1563d8 100644 --- a/pallets/subtensor/src/tests/subsubnet.rs +++ b/pallets/subtensor/src/tests/mechanism.rs @@ -5,39 +5,39 @@ )] // Run all tests -// SKIP_WASM_BUILD=1 RUST_LOG=debug cargo test --package pallet-subtensor --lib -- tests::subsubnet --show-output +// SKIP_WASM_BUILD=1 RUST_LOG=debug cargo test --package pallet-subtensor --lib -- tests::mechanism --show-output // Test plan: -// - [x] Netuid index math (with SubsubnetCountCurrent limiting) +// - [x] Netuid index math (with MechanismCountCurrent limiting) // - [x] Sub-subnet validity tests // - [x] do_set_desired tests // - [x] Emissions are split proportionally // - [x] Sum of split emissions is equal to rao_emission passed to epoch -// - [x] Only subnet owner or root can set desired subsubnet count (pallet admin test) -// - [x] Weights can be set by subsubnet -// - [x] Weights can be commited/revealed by subsubnet -// - [x] Weights can be commited/revealed in crv3 by subsubnet -// - [x] Prevent weight setting/commitment/revealing above subsubnet_limit_in_force -// - [x] Prevent weight commitment/revealing above subsubnet_limit_in_force -// - [x] Prevent weight commitment/revealing in crv3 above subsubnet_limit_in_force -// - [x] When a miner is deregistered, their weights are cleaned across all subsubnets -// - [x] Weight setting rate limiting is enforced by subsubnet -// - [x] Bonds are applied per subsubnet -// - [x] Incentives are per subsubnet -// - [x] Per-subsubnet incentives are distributed proportionally to miner weights -// - [x] Subsubnet limit can be set up to 8 (with admin pallet) -// - [x] When reduction of subsubnet limit occurs, Weights, Incentive, LastUpdate, Bonds, and WeightCommits are cleared -// - [x] Epoch terms of subnet are weighted sum (or logical OR) of all subsubnet epoch terms +// - [x] Only subnet owner or root can set desired mechanism count (pallet admin test) +// - [x] Weights can be set by mechanism +// - [x] Weights can be commited/revealed by mechanism +// - [x] Weights can be commited/revealed in crv3 by mechanism +// - [x] Prevent weight setting/commitment/revealing above mechanism_limit_in_force +// - [x] Prevent weight commitment/revealing above mechanism_limit_in_force +// - [x] Prevent weight commitment/revealing in crv3 above mechanism_limit_in_force +// - [x] When a miner is deregistered, their weights are cleaned across all mechanisms +// - [x] Weight setting rate limiting is enforced by mechanism +// - [x] Bonds are applied per mechanism +// - [x] Incentives are per mechanism +// - [x] Per-mechanism incentives are distributed proportionally to miner weights +// - [x] Mechanism limit can be set up to 8 (with admin pallet) +// - [x] When reduction of mechanism limit occurs, Weights, Incentive, LastUpdate, Bonds, and WeightCommits are cleared +// - [x] Epoch terms of subnet are weighted sum (or logical OR) of all mechanism epoch terms // - [x] Subnet epoch terms persist in state -// - [x] Subsubnet epoch terms persist in state -// - [x] "Yuma Emergency Mode" (consensus sum is 0 for a subsubnet), emission distributed by stake -// - [x] Miner with no weights on any subsubnet receives no reward -// - [x] SubsubnetEmissionSplit is reset on subsubnet count increase -// - [x] SubsubnetEmissionSplit is reset on subsubnet count decrease +// - [x] Mechanism epoch terms persist in state +// - [x] "Yuma Emergency Mode" (consensus sum is 0 for a mechanism), emission distributed by stake +// - [x] Miner with no weights on any mechanism receives no reward +// - [x] MechanismEmissionSplit is reset on mechanism count increase +// - [x] MechanismEmissionSplit is reset on mechanism count decrease use super::mock::*; use crate::coinbase::reveal_commits::WeightsTlockPayload; -use crate::subnets::subsubnet::{GLOBAL_MAX_SUBNET_COUNT, MAX_SUBSUBNET_COUNT_PER_SUBNET}; +use crate::subnets::mechanism::{GLOBAL_MAX_SUBNET_COUNT, MAX_MECHANISM_COUNT_PER_SUBNET}; use crate::*; use alloc::collections::BTreeMap; use approx::assert_abs_diff_eq; @@ -52,7 +52,7 @@ use sp_core::{H256, U256}; use sp_runtime::traits::{BlakeTwo256, Hash}; use sp_std::collections::vec_deque::VecDeque; use substrate_fixed::types::{I32F32, U64F64}; -use subtensor_runtime_common::{NetUid, NetUidStorageIndex, SubId}; +use subtensor_runtime_common::{MechId, NetUid, NetUidStorageIndex}; use tle::{ curves::drand::TinyBLS381, ibe::fullident::Identity, stream_ciphers::AESGCMStreamCipherProvider, tlock::tle, @@ -75,9 +75,9 @@ fn test_index_from_netuid_and_subnet() { ] .iter() .for_each(|(netuid, sub_id)| { - let idx = SubtensorModule::get_subsubnet_storage_index( + let idx = SubtensorModule::get_mechanism_storage_index( NetUid::from(*netuid), - SubId::from(*sub_id), + MechId::from(*sub_id), ); let expected = *sub_id as u64 * GLOBAL_MAX_SUBNET_COUNT as u64 + *netuid as u64; assert_eq!(idx, NetUidStorageIndex::from(expected as u16)); @@ -109,16 +109,16 @@ fn test_netuid_and_subnet_from_index() { // Allow subnet ID NetworksAdded::::insert(NetUid::from(expected_netuid), true); - SubsubnetCountCurrent::::insert( + MechanismCountCurrent::::insert( NetUid::from(expected_netuid), - SubId::from(expected_subid + 1), + MechId::from(expected_subid + 1), ); - let (netuid, subid) = + let (netuid, mecid) = SubtensorModule::get_netuid_and_subid(NetUidStorageIndex::from(*netuid_index)) .unwrap(); assert_eq!(netuid, NetUid::from(expected_netuid)); - assert_eq!(subid, SubId::from(expected_subid)); + assert_eq!(mecid, MechId::from(expected_subid)); }); }); } @@ -126,98 +126,101 @@ fn test_netuid_and_subnet_from_index() { #[test] fn test_netuid_index_math_constants() { assert_eq!( - GLOBAL_MAX_SUBNET_COUNT as u64 * MAX_SUBSUBNET_COUNT_PER_SUBNET as u64, + GLOBAL_MAX_SUBNET_COUNT as u64 * MAX_MECHANISM_COUNT_PER_SUBNET as u64, 0x10000 ); } #[test] -fn ensure_subsubnet_exists_ok() { +fn ensure_mechanism_exists_ok() { new_test_ext(1).execute_with(|| { let netuid: NetUid = 3u16.into(); - let sub_id = SubId::from(1u8); + let sub_id = MechId::from(1u8); // ensure base subnet exists NetworksAdded::::insert(NetUid::from(netuid), true); // Allow at least 2 sub-subnets (so sub_id = 1 is valid) - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); - assert_ok!(SubtensorModule::ensure_subsubnet_exists(netuid, sub_id)); + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); + assert_ok!(SubtensorModule::ensure_mechanism_exists(netuid, sub_id)); }); } #[test] -fn ensure_subsubnet_fails_when_base_subnet_missing() { +fn ensure_mechanism_fails_when_base_subnet_missing() { new_test_ext(1).execute_with(|| { let netuid: NetUid = 7u16.into(); - let sub_id = SubId::from(0u8); + let sub_id = MechId::from(0u8); // Intentionally DO NOT create the base subnet assert_noop!( - SubtensorModule::ensure_subsubnet_exists(netuid, sub_id), - Error::::SubNetworkDoesNotExist + SubtensorModule::ensure_mechanism_exists(netuid, sub_id), + Error::::MechanismDoesNotExist ); }); } #[test] -fn ensure_subsubnet_fails_when_subid_out_of_range() { +fn ensure_mechanism_fails_when_subid_out_of_range() { new_test_ext(1).execute_with(|| { let netuid: NetUid = 9u16.into(); NetworksAdded::::insert(NetUid::from(netuid), true); // Current allowed sub-subnet count is 2 => valid sub_ids: {0, 1} - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); // sub_id == 2 is out of range (must be < 2) - let sub_id_eq = SubId::from(2u8); + let sub_id_eq = MechId::from(2u8); assert_noop!( - SubtensorModule::ensure_subsubnet_exists(netuid, sub_id_eq), - Error::::SubNetworkDoesNotExist + SubtensorModule::ensure_mechanism_exists(netuid, sub_id_eq), + Error::::MechanismDoesNotExist ); // sub_id > 2 is also out of range - let sub_id_gt = SubId::from(3u8); + let sub_id_gt = MechId::from(3u8); assert_noop!( - SubtensorModule::ensure_subsubnet_exists(netuid, sub_id_gt), - Error::::SubNetworkDoesNotExist + SubtensorModule::ensure_mechanism_exists(netuid, sub_id_gt), + Error::::MechanismDoesNotExist ); }); } #[test] -fn do_set_subsubnet_count_ok_minimal() { +fn do_set_mechanism_count_ok_minimal() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(3u16); NetworksAdded::::insert(NetUid::from(3u16), true); // base subnet exists - assert_ok!(SubtensorModule::do_set_subsubnet_count( + assert_ok!(SubtensorModule::do_set_mechanism_count( netuid, - SubId::from(1u8) + MechId::from(1u8) )); - assert_eq!(SubsubnetCountCurrent::::get(netuid), SubId::from(1u8)); + assert_eq!( + MechanismCountCurrent::::get(netuid), + MechId::from(1u8) + ); }); } #[test] -fn do_set_subsubnet_count_ok_at_effective_cap() { +fn do_set_mechanism_count_ok_at_effective_cap() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(4u16); NetworksAdded::::insert(NetUid::from(4u16), true); // base subnet exists // Effective bound is min(runtime cap, compile-time cap) - let runtime_cap = MaxSubsubnetCount::::get(); // e.g., SubId::from(8) - let compile_cap = SubId::from(MAX_SUBSUBNET_COUNT_PER_SUBNET); + let runtime_cap = MaxMechanismCount::::get(); // e.g., MechId::from(8) + let compile_cap = MechId::from(MAX_MECHANISM_COUNT_PER_SUBNET); let bound = if runtime_cap <= compile_cap { runtime_cap } else { compile_cap }; - assert_ok!(SubtensorModule::do_set_subsubnet_count(netuid, bound)); - assert_eq!(SubsubnetCountCurrent::::get(netuid), bound); + assert_ok!(SubtensorModule::do_set_mechanism_count(netuid, bound)); + assert_eq!(MechanismCountCurrent::::get(netuid), bound); }); } @@ -228,8 +231,8 @@ fn do_set_fails_when_base_subnet_missing() { // No NetworksAdded insert => base subnet absent assert_noop!( - SubtensorModule::do_set_subsubnet_count(netuid, SubId::from(1u8)), - Error::::SubNetworkDoesNotExist + SubtensorModule::do_set_mechanism_count(netuid, MechId::from(1u8)), + Error::::MechanismDoesNotExist ); }); } @@ -241,7 +244,7 @@ fn do_set_fails_for_zero() { NetworksAdded::::insert(NetUid::from(9u16), true); // base subnet exists assert_noop!( - SubtensorModule::do_set_subsubnet_count(netuid, SubId::from(0u8)), + SubtensorModule::do_set_mechanism_count(netuid, MechId::from(0u8)), Error::::InvalidValue ); }); @@ -255,7 +258,7 @@ fn do_set_fails_when_over_runtime_cap() { // Runtime cap is 8 (per function), so 9 must fail assert_noop!( - SubtensorModule::do_set_subsubnet_count(netuid, SubId::from(9u8)), + SubtensorModule::do_set_mechanism_count(netuid, MechId::from(9u8)), Error::::InvalidValue ); }); @@ -267,16 +270,16 @@ fn do_set_fails_when_over_compile_time_cap() { let netuid = NetUid::from(12u16); NetworksAdded::::insert(NetUid::from(12u16), true); // base subnet exists - let too_big = SubId::from(MAX_SUBSUBNET_COUNT_PER_SUBNET + 1); + let too_big = MechId::from(MAX_MECHANISM_COUNT_PER_SUBNET + 1); assert_noop!( - SubtensorModule::do_set_subsubnet_count(netuid, too_big), + SubtensorModule::do_set_mechanism_count(netuid, too_big), Error::::InvalidValue ); }); } #[test] -fn update_subsubnet_counts_decreases_and_cleans() { +fn update_mechanism_counts_decreases_and_cleans() { new_test_ext(1).execute_with(|| { let hotkey = U256::from(1); @@ -285,16 +288,16 @@ fn update_subsubnet_counts_decreases_and_cleans() { NetworksAdded::::insert(NetUid::from(42u16), true); // Choose counts so result is deterministic. - let old = SubId::from(3); - let desired = SubId::from(2u8); - SubsubnetCountCurrent::::insert(netuid, old); + let old = MechId::from(3); + let desired = MechId::from(2u8); + MechanismCountCurrent::::insert(netuid, old); // Set non-default subnet emission split - SubsubnetEmissionSplit::::insert(netuid, vec![123u16, 234u16, 345u16]); + MechanismEmissionSplit::::insert(netuid, vec![123u16, 234u16, 345u16]); - // Seed data at a kept subid (1) and a removed subid (2) - let idx_keep = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1u8)); - let idx_rm3 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(2u8)); + // Seed data at a kept mecid (1) and a removed mecid (2) + let idx_keep = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1u8)); + let idx_rm3 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(2u8)); Weights::::insert(idx_keep, 0u16, vec![(1u16, 1u16)]); Incentive::::insert(idx_keep, vec![1u16]); @@ -327,10 +330,10 @@ fn update_subsubnet_counts_decreases_and_cleans() { ); // Act - SubtensorModule::update_subsubnet_counts_if_needed(netuid, desired); + SubtensorModule::update_mechanism_counts_if_needed(netuid, desired); // New count is as desired - assert_eq!(SubsubnetCountCurrent::::get(netuid), desired); + assert_eq!(MechanismCountCurrent::::get(netuid), desired); // Kept prefix intact assert_eq!(Incentive::::get(idx_keep), vec![1u16]); @@ -342,7 +345,7 @@ fn update_subsubnet_counts_decreases_and_cleans() { idx_keep, 1u64 )); - // Removed prefix (subid 3) cleared + // Removed prefix (mecid 3) cleared assert!(Weights::::iter_prefix(idx_rm3).next().is_none()); assert_eq!(Incentive::::get(idx_rm3), Vec::::new()); assert!(!LastUpdate::::contains_key(idx_rm3)); @@ -352,34 +355,34 @@ fn update_subsubnet_counts_decreases_and_cleans() { idx_rm3, 1u64 )); - // SubsubnetEmissionSplit is reset - assert!(SubsubnetEmissionSplit::::get(netuid).is_none()); + // MechanismEmissionSplit is reset + assert!(MechanismEmissionSplit::::get(netuid).is_none()); }); } #[test] -fn update_subsubnet_counts_increases() { +fn update_mechanism_counts_increases() { new_test_ext(1).execute_with(|| { // Base subnet exists let netuid = NetUid::from(42u16); NetworksAdded::::insert(NetUid::from(42u16), true); // Choose counts - let old = SubId::from(1u8); - let desired = SubId::from(2u8); - SubsubnetCountCurrent::::insert(netuid, old); + let old = MechId::from(1u8); + let desired = MechId::from(2u8); + MechanismCountCurrent::::insert(netuid, old); // Set non-default subnet emission split - SubsubnetEmissionSplit::::insert(netuid, vec![123u16, 234u16, 345u16]); + MechanismEmissionSplit::::insert(netuid, vec![123u16, 234u16, 345u16]); // Act - SubtensorModule::update_subsubnet_counts_if_needed(netuid, desired); + SubtensorModule::update_mechanism_counts_if_needed(netuid, desired); // New count is as desired - assert_eq!(SubsubnetCountCurrent::::get(netuid), desired); + assert_eq!(MechanismCountCurrent::::get(netuid), desired); - // SubsubnetEmissionSplit is reset - assert!(SubsubnetEmissionSplit::::get(netuid).is_none()); + // MechanismEmissionSplit is reset + assert!(MechanismEmissionSplit::::get(netuid).is_none()); }); } @@ -387,7 +390,7 @@ fn update_subsubnet_counts_increases() { fn split_emissions_even_division() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(5u16); - SubsubnetCountCurrent::::insert(netuid, SubId::from(5u8)); // 5 sub-subnets + MechanismCountCurrent::::insert(netuid, MechId::from(5u8)); // 5 sub-subnets let out = SubtensorModule::split_emissions(netuid, AlphaCurrency::from(25u64)); assert_eq!(out, vec![AlphaCurrency::from(5u64); 5]); }); @@ -397,7 +400,7 @@ fn split_emissions_even_division() { fn split_emissions_rounding_to_first() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(6u16); - SubsubnetCountCurrent::::insert(netuid, SubId::from(4u8)); // 4 sub-subnets + MechanismCountCurrent::::insert(netuid, MechId::from(4u8)); // 4 sub-subnets let out = SubtensorModule::split_emissions(netuid, AlphaCurrency::from(10u64)); // 10 / 4 = 2, rem=2 assert_eq!( out, @@ -415,8 +418,8 @@ fn split_emissions_rounding_to_first() { fn split_emissions_fibbonacci() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(5u16); - SubsubnetCountCurrent::::insert(netuid, SubId::from(5u8)); // 5 sub-subnets - SubsubnetEmissionSplit::::insert(netuid, vec![3450, 6899, 10348, 17247, 27594]); + MechanismCountCurrent::::insert(netuid, MechId::from(5u8)); // 5 sub-subnets + MechanismEmissionSplit::::insert(netuid, vec![3450, 6899, 10348, 17247, 27594]); let out = SubtensorModule::split_emissions(netuid, AlphaCurrency::from(19u64)); assert_eq!( out, @@ -431,16 +434,16 @@ fn split_emissions_fibbonacci() { }); } -/// Seeds a 2-neuron and 2-subsubnet subnet so `epoch_subsubnet` produces non-zero +/// Seeds a 2-neuron and 2-mechanism subnet so `epoch_mechanism` produces non-zero /// incentives & dividends. /// Returns the sub-subnet storage index. pub fn mock_epoch_state(netuid: NetUid, ck0: U256, hk0: U256, ck1: U256, hk1: U256) { - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); // Base subnet exists; 2 neurons. NetworksAdded::::insert(NetUid::from(u16::from(netuid)), true); - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); SubnetworkN::::insert(netuid, 2); // Register two neurons (UID 0,1) → keys drive `get_subnetwork_n`. @@ -474,7 +477,7 @@ pub fn mock_epoch_state(netuid: NetUid, ck0: U256, hk0: U256, ck1: U256, hk1: U2 StakeThreshold::::put(0u64); ValidatorPermit::::insert(netuid, vec![true, true]); - // Simple weights, setting for each other on both subsubnets + // Simple weights, setting for each other on both mechanisms Weights::::insert(idx0, 0, vec![(0u16, 0xFFFF), (1u16, 0xFFFF)]); Weights::::insert(idx0, 1, vec![(0u16, 0xFFFF), (1u16, 0xFFFF)]); Weights::::insert(idx1, 0, vec![(0u16, 0xFFFF), (1u16, 0xFFFF)]); @@ -486,8 +489,8 @@ pub fn mock_epoch_state(netuid: NetUid, ck0: U256, hk0: U256, ck1: U256, hk1: U2 } pub fn mock_3_neurons(netuid: NetUid, hk: U256) { - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); SubnetworkN::::insert(netuid, 3); Keys::::insert(netuid, 2u16, hk); @@ -497,11 +500,11 @@ pub fn mock_3_neurons(netuid: NetUid, hk: U256) { } #[test] -fn epoch_with_subsubnets_produces_per_subsubnet_incentive() { +fn epoch_with_mechanisms_produces_per_mechanism_incentive() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1u16); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); let ck0 = U256::from(1); let hk0 = U256::from(2); let ck1 = U256::from(3); @@ -509,7 +512,7 @@ fn epoch_with_subsubnets_produces_per_subsubnet_incentive() { let emission = AlphaCurrency::from(1_000_000_000); mock_epoch_state(netuid, ck0, hk0, ck1, hk1); - SubtensorModule::epoch_with_subsubnets(netuid, emission); + SubtensorModule::epoch_with_mechanisms(netuid, emission); let actual_incentive_sub0 = Incentive::::get(idx0); let actual_incentive_sub1 = Incentive::::get(idx1); @@ -522,11 +525,11 @@ fn epoch_with_subsubnets_produces_per_subsubnet_incentive() { } #[test] -fn epoch_with_subsubnets_updates_bonds() { +fn epoch_with_mechanisms_updates_bonds() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1u16); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); let ck0 = U256::from(1); let hk0 = U256::from(2); let ck1 = U256::from(3); @@ -535,33 +538,33 @@ fn epoch_with_subsubnets_updates_bonds() { mock_epoch_state(netuid, ck0, hk0, ck1, hk1); - // Cause bonds to be asymmetric on diff subsubnets + // Cause bonds to be asymmetric on diff mechanisms Weights::::insert(idx1, 0, vec![(0u16, 0xFFFF), (1u16, 0)]); Weights::::insert(idx1, 1, vec![(0u16, 0xFFFF), (1u16, 0xFFFF)]); - SubtensorModule::epoch_with_subsubnets(netuid, emission); + SubtensorModule::epoch_with_mechanisms(netuid, emission); let bonds_uid0_sub0 = Bonds::::get(idx0, 0); let bonds_uid1_sub0 = Bonds::::get(idx0, 1); let bonds_uid0_sub1 = Bonds::::get(idx1, 0); let bonds_uid1_sub1 = Bonds::::get(idx1, 1); - // Subsubnet 0: UID0 fully bonds to UID1, UID1 fully bonds to UID0 + // Mechanism 0: UID0 fully bonds to UID1, UID1 fully bonds to UID0 assert_eq!(bonds_uid0_sub0, vec![(1, 65535)]); assert_eq!(bonds_uid1_sub0, vec![(0, 65535)]); - // Subsubnet 1: UID0 no bond to UID1, UID1 fully bonds to UID0 + // Mechanism 1: UID0 no bond to UID1, UID1 fully bonds to UID0 assert_eq!(bonds_uid0_sub1, vec![]); assert_eq!(bonds_uid1_sub1, vec![(0, 65535)]); }); } #[test] -fn epoch_with_subsubnets_incentives_proportional_to_weights() { +fn epoch_with_mechanisms_incentives_proportional_to_weights() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1u16); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); let ck0 = U256::from(1); let hk0 = U256::from(2); let ck1 = U256::from(3); @@ -575,11 +578,11 @@ fn epoch_with_subsubnets_incentives_proportional_to_weights() { // Need 3 neurons for this: One validator that will be setting weights to 2 miners ValidatorPermit::::insert(netuid, vec![true, false, false]); - // Set greater weight to uid1 on sub-subnet 0 and to uid2 on subsubnet 1 + // Set greater weight to uid1 on sub-subnet 0 and to uid2 on mechanism 1 Weights::::insert(idx0, 0, vec![(1u16, 0xFFFF / 5 * 4), (2u16, 0xFFFF / 5)]); Weights::::insert(idx1, 0, vec![(1u16, 0xFFFF / 5), (2u16, 0xFFFF / 5 * 4)]); - SubtensorModule::epoch_with_subsubnets(netuid, emission); + SubtensorModule::epoch_with_mechanisms(netuid, emission); let actual_incentive_sub0 = Incentive::::get(idx0); let actual_incentive_sub1 = Incentive::::get(idx1); @@ -610,11 +613,11 @@ fn epoch_with_subsubnets_incentives_proportional_to_weights() { } #[test] -fn epoch_with_subsubnets_persists_and_aggregates_all_terms() { +fn epoch_with_mechanisms_persists_and_aggregates_all_terms() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1u16); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); // Three neurons: validator (uid=0) + two miners (uid=1,2) let ck0 = U256::from(1); @@ -632,10 +635,10 @@ fn epoch_with_subsubnets_persists_and_aggregates_all_terms() { let uid2 = 2_usize; // Two sub-subnets with non-equal split (~25% / 75%) - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); let split0 = u16::MAX / 4; let split1 = u16::MAX - split0; - SubsubnetEmissionSplit::::insert(netuid, vec![split0, split1]); + MechanismEmissionSplit::::insert(netuid, vec![split0, split1]); // One validator; skew weights differently per sub-subnet ValidatorPermit::::insert(netuid, vec![true, false, false]); @@ -649,20 +652,22 @@ fn epoch_with_subsubnets_persists_and_aggregates_all_terms() { Weights::::insert(idx1, 0, vec![(1u16, 0xFFFF / 5), (2u16, 0xFFFF / 5 * 4)]); // Per-sub emissions (and weights used for aggregation) - let subsubnet_emissions = SubtensorModule::split_emissions(netuid, emission); - let w0 = U64F64::from_num(u64::from(subsubnet_emissions[0])) + let mechanism_emissions = SubtensorModule::split_emissions(netuid, emission); + let w0 = U64F64::from_num(u64::from(mechanism_emissions[0])) / U64F64::from_num(u64::from(emission)); - let w1 = U64F64::from_num(u64::from(subsubnet_emissions[1])) + let w1 = U64F64::from_num(u64::from(mechanism_emissions[1])) / U64F64::from_num(u64::from(emission)); assert_abs_diff_eq!(w0.to_num::(), 0.25, epsilon = 0.0001); assert_abs_diff_eq!(w1.to_num::(), 0.75, epsilon = 0.0001); - // Get per-subsubnet epoch outputs to build expectations - let out0 = SubtensorModule::epoch_subsubnet(netuid, SubId::from(0), subsubnet_emissions[0]); - let out1 = SubtensorModule::epoch_subsubnet(netuid, SubId::from(1), subsubnet_emissions[1]); + // Get per-mechanism epoch outputs to build expectations + let out0 = + SubtensorModule::epoch_mechanism(netuid, MechId::from(0), mechanism_emissions[0]); + let out1 = + SubtensorModule::epoch_mechanism(netuid, MechId::from(1), mechanism_emissions[1]); // Now run the real aggregated path (also persists terms) - let agg = SubtensorModule::epoch_with_subsubnets(netuid, emission); + let agg = SubtensorModule::epoch_with_mechanisms(netuid, emission); // hotkey -> (server_emission_u64, validator_emission_u64) let agg_map: BTreeMap = agg @@ -674,7 +679,7 @@ fn epoch_with_subsubnets_persists_and_aggregates_all_terms() { let terms0 = |hk: &U256| out0.0.get(hk).unwrap(); let terms1 = |hk: &U256| out1.0.get(hk).unwrap(); - // Returned aggregated emissions match plain sums of subsubnet emissions + // Returned aggregated emissions match plain sums of mechanism emissions for hk in [&hk1, &hk2] { let (got_se, got_ve) = agg_map.get(hk).cloned().expect("present"); let t0 = terms0(hk); @@ -689,7 +694,7 @@ fn epoch_with_subsubnets_persists_and_aggregates_all_terms() { assert_abs_diff_eq!(u64::from(got_ve), exp_ve, epsilon = 1); } - // Persisted per-subsubnet Incentive vectors match per-sub terms + // Persisted per-mechanism Incentive vectors match per-sub terms let inc0 = Incentive::::get(idx0); let inc1 = Incentive::::get(idx1); let exp_inc0 = { @@ -794,11 +799,11 @@ fn epoch_with_subsubnets_persists_and_aggregates_all_terms() { } #[test] -fn epoch_with_subsubnets_no_weight_no_incentive() { +fn epoch_with_mechanisms_no_weight_no_incentive() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1u16); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(1)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(1)); let ck0 = U256::from(1); let hk0 = U256::from(2); let ck1 = U256::from(3); @@ -816,7 +821,7 @@ fn epoch_with_subsubnets_no_weight_no_incentive() { Weights::::insert(idx0, 0, vec![(1u16, 1), (2u16, 0)]); Weights::::insert(idx1, 0, vec![(1u16, 1), (2u16, 0)]); - SubtensorModule::epoch_with_subsubnets(netuid, emission); + SubtensorModule::epoch_with_mechanisms(netuid, emission); let actual_incentive_sub0 = Incentive::::get(idx0); let actual_incentive_sub1 = Incentive::::get(idx1); @@ -838,7 +843,7 @@ fn neuron_dereg_cleans_weights_across_subids() { let netuid = NetUid::from(77u16); let neuron_uid: u16 = 1; // we'll deregister UID=1 // two sub-subnets - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); // Setup initial map values Emission::::insert( @@ -853,9 +858,9 @@ fn neuron_dereg_cleans_weights_across_subids() { Consensus::::insert(netuid, vec![21u16, 88u16, 44u16]); Dividends::::insert(netuid, vec![7u16, 77u16, 17u16]); - // Clearing per-subid maps + // Clearing per-mecid maps for sub in [0u8, 1u8] { - let idx = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(sub)); + let idx = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(sub)); // Incentive vector: position 1 should become 0 Incentive::::insert(idx, vec![10u16, 20u16, 30u16]); @@ -887,9 +892,9 @@ fn neuron_dereg_cleans_weights_across_subids() { let d = Dividends::::get(netuid); assert_eq!(d, vec![7, 0, 17]); - // Per-subid cleanup + // Per-mecid cleanup for sub in [0u8, 1u8] { - let idx = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(sub)); + let idx = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(sub)); // Incentive element at index 1 set to 0 let inc = Incentive::::get(idx); @@ -911,7 +916,7 @@ fn neuron_dereg_cleans_weights_across_subids() { fn clear_neuron_handles_absent_rows_gracefully() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(55u16); - SubsubnetCountCurrent::::insert(netuid, SubId::from(1u8)); // single sub-subnet + MechanismCountCurrent::::insert(netuid, MechId::from(1u8)); // single sub-subnet // Minimal vectors with non-zero at index 0 (we will clear UID=0) Emission::::insert(netuid, vec![AlphaCurrency::from(5u64)]); @@ -935,7 +940,7 @@ fn clear_neuron_handles_absent_rows_gracefully() { } #[test] -fn test_set_sub_weights_happy_path_sets_row_under_subid() { +fn test_set_mechanism_weights_happy_path_sets_row_under_subid() { new_test_ext(0).execute_with(|| { let netuid = NetUid::from(1); let tempo: u16 = 13; @@ -967,36 +972,36 @@ fn test_set_sub_weights_happy_path_sets_row_under_subid() { 1.into(), ); - // Have at least two sub-subnets; write under subid = 1 - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); - let subid = SubId::from(1u8); + // Have at least two sub-subnets; write under mecid = 1 + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); + let mecid = MechId::from(1u8); // Call extrinsic let dests = vec![uid2, uid3]; let weights = vec![88u16, 0xFFFF]; - assert_ok!(SubtensorModule::set_sub_weights( + assert_ok!(SubtensorModule::set_mechanism_weights( RawOrigin::Signed(hk1).into(), netuid, - subid, + mecid, dests.clone(), weights.clone(), 0, // version_key )); - // Verify row exists under the chosen subid and not under a different subid - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, subid); + // Verify row exists under the chosen mecid and not under a different mecid + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, mecid); assert_eq!( Weights::::get(idx1, uid1), vec![(uid2, 88u16), (uid3, 0xFFFF)] ); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0u8)); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0u8)); assert!(Weights::::get(idx0, uid1).is_empty()); }); } #[test] -fn test_set_sub_weights_above_subsubnet_count_fails() { +fn test_set_mechanism_weights_above_mechanism_count_fails() { new_test_ext(0).execute_with(|| { let netuid = NetUid::from(1); let tempo: u16 = 13; @@ -1024,15 +1029,15 @@ fn test_set_sub_weights_above_subsubnet_count_fails() { 1.into(), ); - // Have exactly two sub-subnets; write under subid = 1 - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); - let subid_above = SubId::from(2u8); + // Have exactly two sub-subnets; write under mecid = 1 + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); + let subid_above = MechId::from(2u8); // Call extrinsic let dests = vec![uid2]; let weights = vec![88u16]; assert_noop!( - SubtensorModule::set_sub_weights( + SubtensorModule::set_mechanism_weights( RawOrigin::Signed(hk1).into(), netuid, subid_above, @@ -1040,13 +1045,13 @@ fn test_set_sub_weights_above_subsubnet_count_fails() { weights.clone(), 0, // version_key ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } #[test] -fn test_commit_reveal_sub_weights_ok() { +fn test_commit_reveal_mechanism_weights_ok() { new_test_ext(1).execute_with(|| { System::set_block_number(0); @@ -1082,13 +1087,13 @@ fn test_commit_reveal_sub_weights_ok() { 1.into(), ); - // Ensure sub-subnet exists; write under subid = 1 - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); - let subid = SubId::from(1u8); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, SubId::from(0u8)); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, subid); + // Ensure sub-subnet exists; write under mecid = 1 + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); + let mecid = MechId::from(1u8); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, MechId::from(0u8)); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, mecid); - // Prepare payload and commit hash (include subid!) + // Prepare payload and commit hash (include mecid!) let dests = vec![uid2, uid3]; let weights = vec![88u16, 0xFFFFu16]; let salt: Vec = vec![1, 2, 3, 4, 5, 6, 7, 8]; @@ -1103,38 +1108,38 @@ fn test_commit_reveal_sub_weights_ok() { )); // Commit in epoch 0 - assert_ok!(SubtensorModule::commit_sub_weights( + assert_ok!(SubtensorModule::commit_mechanism_weights( RuntimeOrigin::signed(hk1), netuid, - subid, + mecid, commit_hash )); // Advance one epoch, then reveal step_epochs(1, netuid); - assert_ok!(SubtensorModule::reveal_sub_weights( + assert_ok!(SubtensorModule::reveal_mechanism_weights( RuntimeOrigin::signed(hk1), netuid, - subid, + mecid, dests.clone(), weights.clone(), salt, version_key )); - // Verify weights stored under the chosen subid (normalized keeps max=0xFFFF here) + // Verify weights stored under the chosen mecid (normalized keeps max=0xFFFF here) assert_eq!( Weights::::get(idx1, uid1), vec![(uid2, 88u16), (uid3, 0xFFFFu16)] ); - // And not under a different subid + // And not under a different mecid assert!(Weights::::get(idx0, uid1).is_empty()); }); } #[test] -fn test_commit_reveal_above_subsubnet_count_fails() { +fn test_commit_reveal_above_mechanism_count_fails() { new_test_ext(1).execute_with(|| { System::set_block_number(0); @@ -1166,10 +1171,10 @@ fn test_commit_reveal_above_subsubnet_count_fails() { 1.into(), ); - // Ensure there are two subsubnets: 0 and 1 - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); - let subid_above = SubId::from(2u8); // non-existing sub-subnet - let idx2 = SubtensorModule::get_subsubnet_storage_index(netuid, subid_above); + // Ensure there are two mechanisms: 0 and 1 + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); + let subid_above = MechId::from(2u8); // non-existing sub-subnet + let idx2 = SubtensorModule::get_mechanism_storage_index(netuid, subid_above); // Prepare payload and commit hash let dests = vec![uid2]; @@ -1187,19 +1192,19 @@ fn test_commit_reveal_above_subsubnet_count_fails() { // Commit in epoch 0 assert_noop!( - SubtensorModule::commit_sub_weights( + SubtensorModule::commit_mechanism_weights( RuntimeOrigin::signed(hk1), netuid, subid_above, commit_hash ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // Advance one epoch, then attempt to reveal step_epochs(1, netuid); assert_noop!( - SubtensorModule::reveal_sub_weights( + SubtensorModule::reveal_mechanism_weights( RuntimeOrigin::signed(hk1), netuid, subid_above, @@ -1223,14 +1228,14 @@ fn test_reveal_crv3_commits_sub_success() { System::set_block_number(0); let netuid = NetUid::from(1); - let subid = SubId::from(1u8); // write under sub-subnet #1 + let mecid = MechId::from(1u8); // write under sub-subnet #1 let hotkey1: AccountId = U256::from(1); let hotkey2: AccountId = U256::from(2); let reveal_round: u64 = 1000; add_network(netuid, 5, 0); - // ensure we actually have subid=1 available - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); + // ensure we actually have mecid=1 available + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); // Register neurons and set up configs register_ok_neuron(netuid, hotkey1, U256::from(3), 100_000); @@ -1252,7 +1257,7 @@ fn test_reveal_crv3_commits_sub_success() { let version_key = SubtensorModule::get_weights_version_key(netuid); - // Payload (same as legacy; subid is provided to the extrinsic) + // Payload (same as legacy; mecid is provided to the extrinsic) let payload = WeightsTlockPayload { hotkey: hotkey1.encode(), values: vec![10, 20], @@ -1279,10 +1284,10 @@ fn test_reveal_crv3_commits_sub_success() { ct.serialize_compressed(&mut commit_bytes).expect("serialize"); // Commit (sub variant) - assert_ok!(SubtensorModule::commit_timelocked_sub_weights( + assert_ok!(SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey1), netuid, - subid, + mecid, commit_bytes.clone().try_into().expect("bounded"), reveal_round, SubtensorModule::get_commit_reveal_weights_version() @@ -1302,11 +1307,11 @@ fn test_reveal_crv3_commits_sub_success() { // Run epochs so the commit is processed step_epochs(3, netuid); - // Verify weights applied under the selected subid index - let idx = SubtensorModule::get_subsubnet_storage_index(netuid, subid); + // Verify weights applied under the selected mecid index + let idx = SubtensorModule::get_mechanism_storage_index(netuid, mecid); let weights_sparse = SubtensorModule::get_weights_sparse(idx); let row = weights_sparse.get(uid1 as usize).cloned().unwrap_or_default(); - assert!(!row.is_empty(), "expected weights set for validator uid1 under subid"); + assert!(!row.is_empty(), "expected weights set for validator uid1 under mecid"); // Compare rounded normalized weights to expected proportions (like legacy test) let expected: Vec<(u16, I32F32)> = payload.uids.iter().zip(payload.values.iter()).map(|(&u,&v)|(u, I32F32::from_num(v))).collect(); @@ -1324,19 +1329,19 @@ fn test_reveal_crv3_commits_sub_success() { } #[test] -fn test_crv3_above_subsubnet_count_fails() { +fn test_crv3_above_mechanism_count_fails() { new_test_ext(100).execute_with(|| { System::set_block_number(0); let netuid = NetUid::from(1); - let subid_above = SubId::from(2u8); // non-existing sub-subnet + let subid_above = MechId::from(2u8); // non-existing sub-subnet let hotkey1: AccountId = U256::from(1); let hotkey2: AccountId = U256::from(2); let reveal_round: u64 = 1000; add_network(netuid, 5, 0); - // ensure we actually have subid=1 available - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); + // ensure we actually have mecid=1 available + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); // Register neurons and set up configs register_ok_neuron(netuid, hotkey1, U256::from(3), 100_000); @@ -1355,7 +1360,7 @@ fn test_crv3_above_subsubnet_count_fails() { let version_key = SubtensorModule::get_weights_version_key(netuid); - // Payload (same as legacy; subid is provided to the extrinsic) + // Payload (same as legacy; mecid is provided to the extrinsic) let payload = WeightsTlockPayload { hotkey: hotkey1.encode(), values: vec![10, 20], @@ -1383,7 +1388,7 @@ fn test_crv3_above_subsubnet_count_fails() { // Commit (sub variant) assert_noop!( - SubtensorModule::commit_timelocked_sub_weights( + SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey1), netuid, subid_above, @@ -1391,30 +1396,30 @@ fn test_crv3_above_subsubnet_count_fails() { reveal_round, SubtensorModule::get_commit_reveal_weights_version() ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } #[test] -fn test_do_commit_crv3_sub_weights_committing_too_fast() { +fn test_do_commit_crv3_mechanism_weights_committing_too_fast() { new_test_ext(1).execute_with(|| { let netuid = NetUid::from(1); - let subid = SubId::from(1u8); + let mecid = MechId::from(1u8); let hotkey: AccountId = U256::from(1); let commit_data_1: Vec = vec![1, 2, 3]; let commit_data_2: Vec = vec![4, 5, 6]; let reveal_round: u64 = 1000; add_network(netuid, 5, 0); - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); // allow subids {0,1} + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); // allow subids {0,1} register_ok_neuron(netuid, hotkey, U256::from(2), 100_000); SubtensorModule::set_weights_set_rate_limit(netuid, 5); SubtensorModule::set_commit_reveal_weights_enabled(netuid, true); let uid = SubtensorModule::get_uid_for_net_and_hotkey(netuid, &hotkey).expect("uid"); - let idx1 = SubtensorModule::get_subsubnet_storage_index(netuid, subid); + let idx1 = SubtensorModule::get_mechanism_storage_index(netuid, mecid); SubtensorModule::set_last_update_for_uid(idx1, uid, 0); // make validator with stake @@ -1428,22 +1433,22 @@ fn test_do_commit_crv3_sub_weights_committing_too_fast() { 1.into(), ); - // first commit OK on subid=1 - assert_ok!(SubtensorModule::commit_timelocked_sub_weights( + // first commit OK on mecid=1 + assert_ok!(SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey), netuid, - subid, + mecid, commit_data_1.clone().try_into().expect("bounded"), reveal_round, SubtensorModule::get_commit_reveal_weights_version() )); - // immediate second commit on SAME subid blocked + // immediate second commit on SAME mecid blocked assert_noop!( - SubtensorModule::commit_timelocked_sub_weights( + SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey), netuid, - subid, + mecid, commit_data_2.clone().try_into().expect("bounded"), reveal_round, SubtensorModule::get_commit_reveal_weights_version() @@ -1451,11 +1456,11 @@ fn test_do_commit_crv3_sub_weights_committing_too_fast() { Error::::CommittingWeightsTooFast ); - // BUT committing too soon on a DIFFERENT subid is allowed - let other_subid = SubId::from(0u8); - let idx0 = SubtensorModule::get_subsubnet_storage_index(netuid, other_subid); + // BUT committing too soon on a DIFFERENT mecid is allowed + let other_subid = MechId::from(0u8); + let idx0 = SubtensorModule::get_mechanism_storage_index(netuid, other_subid); SubtensorModule::set_last_update_for_uid(idx0, uid, 0); // baseline like above - assert_ok!(SubtensorModule::commit_timelocked_sub_weights( + assert_ok!(SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey), netuid, other_subid, @@ -1464,13 +1469,13 @@ fn test_do_commit_crv3_sub_weights_committing_too_fast() { SubtensorModule::get_commit_reveal_weights_version() )); - // still too fast on original subid after 2 blocks + // still too fast on original mecid after 2 blocks step_block(2); assert_noop!( - SubtensorModule::commit_timelocked_sub_weights( + SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey), netuid, - subid, + mecid, commit_data_2.clone().try_into().expect("bounded"), reveal_round, SubtensorModule::get_commit_reveal_weights_version() @@ -1478,12 +1483,12 @@ fn test_do_commit_crv3_sub_weights_committing_too_fast() { Error::::CommittingWeightsTooFast ); - // after enough blocks, OK again on original subid + // after enough blocks, OK again on original mecid step_block(3); - assert_ok!(SubtensorModule::commit_timelocked_sub_weights( + assert_ok!(SubtensorModule::commit_timelocked_mechanism_weights( RuntimeOrigin::signed(hotkey), netuid, - subid, + mecid, commit_data_2.try_into().expect("bounded"), reveal_round, SubtensorModule::get_commit_reveal_weights_version() @@ -1492,15 +1497,15 @@ fn test_do_commit_crv3_sub_weights_committing_too_fast() { } #[test] -fn epoch_subsubnet_emergency_mode_distributes_by_stake() { +fn epoch_mechanism_emergency_mode_distributes_by_stake() { new_test_ext(1).execute_with(|| { // setup a single sub-subnet where consensus sum becomes 0 let netuid = NetUid::from(1u16); - let subid = SubId::from(1u8); - let idx = SubtensorModule::get_subsubnet_storage_index(netuid, subid); + let mecid = MechId::from(1u8); + let idx = SubtensorModule::get_mechanism_storage_index(netuid, mecid); let tempo: u16 = 5; add_network(netuid, tempo, 0); - SubsubnetCountCurrent::::insert(netuid, SubId::from(2u8)); // allow subids {0,1} + MechanismCountCurrent::::insert(netuid, MechId::from(2u8)); // allow subids {0,1} SubtensorModule::set_max_registrations_per_block(netuid, 4); SubtensorModule::set_target_registrations_per_interval(netuid, 4); @@ -1556,7 +1561,7 @@ fn epoch_subsubnet_emergency_mode_distributes_by_stake() { let emission = AlphaCurrency::from(1_000_000u64); // --- act: run epoch on this sub-subnet only --- - let out = SubtensorModule::epoch_subsubnet(netuid, subid, emission); + let out = SubtensorModule::epoch_mechanism(netuid, mecid, emission); // collect validator emissions per hotkey let t0 = out.0.get(&hk0).unwrap(); diff --git a/pallets/subtensor/src/tests/mod.rs b/pallets/subtensor/src/tests/mod.rs index 205b4977cd..b9f4ff5366 100644 --- a/pallets/subtensor/src/tests/mod.rs +++ b/pallets/subtensor/src/tests/mod.rs @@ -10,6 +10,7 @@ mod epoch; mod evm; mod leasing; mod math; +mod mechanism; mod migration; mod mock; mod move_stake; @@ -22,7 +23,6 @@ mod serving; mod staking; mod staking2; mod subnet; -mod subsubnet; mod swap_coldkey; mod swap_hotkey; mod swap_hotkey_with_subnet; diff --git a/pallets/subtensor/src/tests/networks.rs b/pallets/subtensor/src/tests/networks.rs index 732f93d13d..779879a129 100644 --- a/pallets/subtensor/src/tests/networks.rs +++ b/pallets/subtensor/src/tests/networks.rs @@ -270,7 +270,7 @@ fn dissolve_nonexistent_subnet_fails() { new_test_ext(0).execute_with(|| { assert_err!( SubtensorModule::do_dissolve_network(9_999.into()), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } diff --git a/pallets/subtensor/src/tests/recycle_alpha.rs b/pallets/subtensor/src/tests/recycle_alpha.rs index e61a7aee26..d230af6f30 100644 --- a/pallets/subtensor/src/tests/recycle_alpha.rs +++ b/pallets/subtensor/src/tests/recycle_alpha.rs @@ -430,7 +430,7 @@ fn test_recycle_errors() { 100_000.into(), 99.into() // non-existent subnet ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); assert_noop!( @@ -502,7 +502,7 @@ fn test_burn_errors() { 100_000.into(), 99.into() // non-existent subnet ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); assert_noop!( diff --git a/pallets/subtensor/src/tests/subnet.rs b/pallets/subtensor/src/tests/subnet.rs index ba5640af3d..a1331a1707 100644 --- a/pallets/subtensor/src/tests/subnet.rs +++ b/pallets/subtensor/src/tests/subnet.rs @@ -52,7 +52,7 @@ fn test_do_start_call_fail_with_not_existed_subnet() { <::RuntimeOrigin>::signed(coldkey_account_id), netuid ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } diff --git a/pallets/subtensor/src/utils/rate_limiting.rs b/pallets/subtensor/src/utils/rate_limiting.rs index 190634212a..1125c9c17f 100644 --- a/pallets/subtensor/src/utils/rate_limiting.rs +++ b/pallets/subtensor/src/utils/rate_limiting.rs @@ -13,8 +13,8 @@ pub enum TransactionType { SetWeightsVersionKey, SetSNOwnerHotkey, OwnerHyperparamUpdate(Hyperparameter), - SubsubnetCountUpdate, - SubsubnetEmission, + MechanismCountUpdate, + MechanismEmission, MaxUidsTrimming, } @@ -25,8 +25,8 @@ impl TransactionType { Self::SetChildren => 150, // 30 minutes Self::SetChildkeyTake => TxChildkeyTakeRateLimit::::get(), Self::RegisterNetwork => NetworkRateLimit::::get(), - Self::SubsubnetCountUpdate => SubsubnetCountSetRateLimit::::get(), - Self::SubsubnetEmission => SubsubnetEmissionRateLimit::::get(), + Self::MechanismCountUpdate => MechanismCountSetRateLimit::::get(), + Self::MechanismEmission => MechanismEmissionRateLimit::::get(), Self::MaxUidsTrimming => MaxUidsTrimmingRateLimit::::get(), Self::Unknown => 0, // Default to no limit for unknown types (no limit) _ => 0, @@ -138,8 +138,8 @@ impl From for u16 { TransactionType::SetWeightsVersionKey => 4, TransactionType::SetSNOwnerHotkey => 5, TransactionType::OwnerHyperparamUpdate(_) => 6, - TransactionType::SubsubnetCountUpdate => 7, - TransactionType::SubsubnetEmission => 8, + TransactionType::MechanismCountUpdate => 7, + TransactionType::MechanismEmission => 8, TransactionType::MaxUidsTrimming => 9, } } @@ -155,8 +155,8 @@ impl From for TransactionType { 4 => TransactionType::SetWeightsVersionKey, 5 => TransactionType::SetSNOwnerHotkey, 6 => TransactionType::OwnerHyperparamUpdate(Hyperparameter::Unknown), - 7 => TransactionType::SubsubnetCountUpdate, - 8 => TransactionType::SubsubnetEmission, + 7 => TransactionType::MechanismCountUpdate, + 8 => TransactionType::MechanismEmission, 9 => TransactionType::MaxUidsTrimming, _ => TransactionType::Unknown, } diff --git a/pallets/swap/src/pallet/mod.rs b/pallets/swap/src/pallet/mod.rs index 442c4852aa..554c7aeead 100644 --- a/pallets/swap/src/pallet/mod.rs +++ b/pallets/swap/src/pallet/mod.rs @@ -265,7 +265,7 @@ mod pallet { ReservesTooLow, /// The subnet does not exist. - SubNetworkDoesNotExist, + MechanismDoesNotExist, /// User liquidity operations are disabled for this subnet UserLiquidityDisabled, @@ -294,7 +294,7 @@ mod pallet { // Ensure that the subnet exists. ensure!( T::SubnetInfo::exists(netuid.into()), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); ensure!(rate <= T::MaxFeeRate::get(), Error::::FeeRateTooHigh); @@ -331,7 +331,7 @@ mod pallet { ensure!( T::SubnetInfo::exists(netuid.into()), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); EnabledUserLiquidity::::insert(netuid, enable); @@ -366,7 +366,7 @@ mod pallet { // Ensure that the subnet exists. ensure!( T::SubnetInfo::exists(netuid.into()), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); ensure!( @@ -434,7 +434,7 @@ mod pallet { // Ensure that the subnet exists. ensure!( T::SubnetInfo::exists(netuid.into()), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); // Remove liquidity @@ -494,7 +494,7 @@ mod pallet { // Ensure that the subnet exists. ensure!( T::SubnetInfo::exists(netuid.into()), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); ensure!( diff --git a/pallets/swap/src/pallet/tests.rs b/pallets/swap/src/pallet/tests.rs index 153e13a822..dc7f08baa8 100644 --- a/pallets/swap/src/pallet/tests.rs +++ b/pallets/swap/src/pallet/tests.rs @@ -141,7 +141,7 @@ mod dispatchables { NON_EXISTENT_NETUID.into(), true ), - Error::::SubNetworkDoesNotExist + Error::::MechanismDoesNotExist ); }); } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index ecadb7c289..b6857cf7ae 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1066,10 +1066,10 @@ pub struct ResetBondsOnCommit; impl OnMetadataCommitment for ResetBondsOnCommit { #[cfg(not(feature = "runtime-benchmarks"))] fn on_metadata_commitment(netuid: NetUid, address: &AccountId) { - // Reset bonds for each subsubnet of this subnet - let subsub_count = SubtensorModule::get_current_subsubnet_count(netuid); - for subid in 0..u8::from(subsub_count) { - let netuid_index = SubtensorModule::get_subsubnet_storage_index(netuid, subid.into()); + // Reset bonds for each mechanism of this subnet + let mechanism_count = SubtensorModule::get_current_mechanism_count(netuid); + for mecid in 0..u8::from(mechanism_count) { + let netuid_index = SubtensorModule::get_mechanism_storage_index(netuid, mecid.into()); let _ = SubtensorModule::do_reset_bonds(netuid_index, address); } } @@ -2344,8 +2344,8 @@ impl_runtime_apis! { SubtensorModule::get_metagraph(netuid) } - fn get_submetagraph(netuid: NetUid, subid: SubId) -> Option> { - SubtensorModule::get_submetagraph(netuid, subid) + fn get_mechagraph(netuid: NetUid, mecid: MechId) -> Option> { + SubtensorModule::get_mechagraph(netuid, mecid) } fn get_subnet_state(netuid: NetUid) -> Option> { @@ -2356,8 +2356,8 @@ impl_runtime_apis! { SubtensorModule::get_all_metagraphs() } - fn get_all_submetagraphs() -> Vec>> { - SubtensorModule::get_all_submetagraphs() + fn get_all_mechagraphs() -> Vec>> { + SubtensorModule::get_all_mechagraphs() } fn get_all_dynamic_info() -> Vec>> { @@ -2371,8 +2371,8 @@ impl_runtime_apis! { pallet_subtensor::Pallet::::get_network_to_prune() } - fn get_selective_submetagraph(netuid: NetUid, subid: SubId, metagraph_indexes: Vec) -> Option> { - SubtensorModule::get_selective_submetagraph(netuid, subid, metagraph_indexes) + fn get_selective_mechagraph(netuid: NetUid, mecid: MechId, metagraph_indexes: Vec) -> Option> { + SubtensorModule::get_selective_mechagraph(netuid, mecid, metagraph_indexes) } }