diff --git a/pallets/subtensor/src/block_step.rs b/pallets/subtensor/src/block_step.rs index 073385fbb..afc30ca92 100644 --- a/pallets/subtensor/src/block_step.rs +++ b/pallets/subtensor/src/block_step.rs @@ -1,75 +1,97 @@ use super::*; -use substrate_fixed::types::I110F18; -use substrate_fixed::types::I64F64; use frame_support::inherent::Vec; -use frame_support::storage::IterableStorageMap; use frame_support::storage::IterableStorageDoubleMap; +use frame_support::storage::IterableStorageMap; +use substrate_fixed::types::I110F18; +use substrate_fixed::types::I64F64; -impl Pallet { - +impl Pallet { pub fn block_step() { let block_number: u64 = Self::get_current_block_as_u64(); - log::debug!("block_step for block: {:?} ", block_number ); + log::debug!("block_step for block: {:?} ", block_number); // --- 1. Adjust difficulties. - Self::adjust_registration_terms_for_networks( ); + Self::adjust_registration_terms_for_networks(); // --- 2. Drains emission tuples ( hotkey, amount ). - Self::drain_emission( block_number ); + Self::drain_emission(block_number); // --- 3. Generates emission tuples from epoch functions. - Self::generate_emission( block_number ); + Self::generate_emission(block_number); } // Helper function which returns the number of blocks remaining before we will run the epoch on this // network. Networks run their epoch when (block_number + netuid + 1 ) % (tempo + 1) = 0 // - pub fn blocks_until_next_epoch( netuid: u16, tempo: u16, block_number: u64 ) -> u64 { - if tempo == 0 { return 1000 } // Special case: tempo = 0, the network never runs. - // tempo | netuid | # first epoch block - // 1 0 0 - // 1 1 1 - // 2 0 1 - // 2 1 0 - // 100 0 99 - // 100 1 98 - return tempo as u64 - ( block_number + netuid as u64 + 1 ) % ( tempo as u64 + 1 ) + pub fn blocks_until_next_epoch(netuid: u16, tempo: u16, block_number: u64) -> u64 { + if tempo == 0 { + return 1000; + } // Special case: tempo = 0, the network never runs. + // tempo | netuid | # first epoch block + // 1 0 0 + // 1 1 1 + // 2 0 1 + // 2 1 0 + // 100 0 99 + // 100 1 98 + return tempo as u64 - (block_number + netuid as u64 + 1) % (tempo as u64 + 1); } - // Helper function returns the number of tuples to drain on a particular step based on // the remaining tuples to sink and the block number // - pub fn tuples_to_drain_this_block( netuid: u16, tempo: u16, block_number: u64, n_remaining: usize ) -> usize { - let blocks_until_epoch: u64 = Self::blocks_until_next_epoch( netuid, tempo, block_number ); - if blocks_until_epoch / 2 == 0 { return n_remaining } // drain all. - if tempo / 2 == 0 { return n_remaining } // drain all - if n_remaining == 0 { return 0 } // nothing to drain at all. - // Else return enough tuples to drain all within half the epoch length. + pub fn tuples_to_drain_this_block( + netuid: u16, + tempo: u16, + block_number: u64, + n_remaining: usize, + ) -> usize { + let blocks_until_epoch: u64 = Self::blocks_until_next_epoch(netuid, tempo, block_number); + if blocks_until_epoch / 2 == 0 { + return n_remaining; + } // drain all. + if tempo / 2 == 0 { + return n_remaining; + } // drain all + if n_remaining == 0 { + return 0; + } // nothing to drain at all. + // Else return enough tuples to drain all within half the epoch length. let to_sink_via_tempo: usize = n_remaining / (tempo as usize / 2); let to_sink_via_blocks_until_epoch: usize = n_remaining / (blocks_until_epoch as usize / 2); if to_sink_via_tempo > to_sink_via_blocks_until_epoch { - return to_sink_via_tempo; + return to_sink_via_tempo; } else { return to_sink_via_blocks_until_epoch; } } - pub fn has_loaded_emission_tuples( netuid: u16 ) -> bool { LoadedEmission::::contains_key( netuid ) } - pub fn get_loaded_emission_tuples( netuid: u16 ) -> Vec<(T::AccountId, u64, u64)> { LoadedEmission::::get( netuid ).unwrap() } + pub fn has_loaded_emission_tuples(netuid: u16) -> bool { + LoadedEmission::::contains_key(netuid) + } + pub fn get_loaded_emission_tuples(netuid: u16) -> Vec<(T::AccountId, u64, u64)> { + LoadedEmission::::get(netuid).unwrap() + } // Reads from the loaded emission storage which contains lists of pending emission tuples ( hotkey, amount ) // and distributes small chunks of them at a time. // - pub fn drain_emission( _: u64 ) { + pub fn drain_emission(_: u64) { // --- 1. We iterate across each network. - for ( netuid, _ ) in as IterableStorageMap>::iter() { - if !Self::has_loaded_emission_tuples( netuid ) { continue } // There are no tuples to emit. - let tuples_to_drain: Vec<(T::AccountId, u64, u64)> = Self::get_loaded_emission_tuples( netuid ); + for (netuid, _) in as IterableStorageMap>::iter() { + if !Self::has_loaded_emission_tuples(netuid) { + continue; + } // There are no tuples to emit. + let tuples_to_drain: Vec<(T::AccountId, u64, u64)> = + Self::get_loaded_emission_tuples(netuid); let mut total_emitted: u64 = 0; - for (hotkey, server_amount, validator_amount) in tuples_to_drain.iter() { - Self::emit_inflation_through_hotkey_account( &hotkey, *server_amount, *validator_amount ); + for (hotkey, server_amount, validator_amount) in tuples_to_drain.iter() { + Self::emit_inflation_through_hotkey_account( + &hotkey, + *server_amount, + *validator_amount, + ); total_emitted += *server_amount + *validator_amount; - } - LoadedEmission::::remove( netuid ); - TotalIssuance::::put( TotalIssuance::::get().saturating_add( total_emitted ) ); + } + LoadedEmission::::remove(netuid); + TotalIssuance::::put(TotalIssuance::::get().saturating_add(total_emitted)); } } @@ -77,125 +99,190 @@ impl Pallet { // If a network has no blocks left until tempo, we run the epoch function and generate // more token emission tuples for later draining onto accounts. // - pub fn generate_emission( block_number: u64 ) { - + pub fn generate_emission(block_number: u64) { // --- 1. Iterate through network ids. - for ( netuid, tempo ) in as IterableStorageMap>::iter() { - + for (netuid, tempo) in as IterableStorageMap>::iter() { // --- 2. Queue the emission due to this network. - let new_queued_emission = EmissionValues::::get( netuid ); - PendingEmission::::mutate( netuid, | queued | *queued += new_queued_emission ); - log::debug!("netuid_i: {:?} queued_emission: +{:?} ", netuid, new_queued_emission ); + let new_queued_emission = EmissionValues::::get(netuid); + PendingEmission::::mutate(netuid, |queued| *queued += new_queued_emission); + log::debug!( + "netuid_i: {:?} queued_emission: +{:?} ", + netuid, + new_queued_emission + ); // --- 3. Check to see if this network has reached tempo. - if Self::blocks_until_next_epoch( netuid, tempo, block_number ) != 0 { + if Self::blocks_until_next_epoch(netuid, tempo, block_number) != 0 { // --- 3.1 No epoch, increase blocks since last step and continue, - Self::set_blocks_since_last_step( netuid, Self::get_blocks_since_last_step( netuid ) + 1 ); + Self::set_blocks_since_last_step( + netuid, + Self::get_blocks_since_last_step(netuid) + 1, + ); continue; } // --- 4 This network is at tempo and we are running its epoch. // First drain the queued emission. - let emission_to_drain:u64 = PendingEmission::::get( netuid ); - PendingEmission::::insert( netuid, 0 ); + let emission_to_drain: u64 = PendingEmission::::get(netuid); + PendingEmission::::insert(netuid, 0); // --- 5. Run the epoch mechanism and return emission tuples for hotkeys in the network. - let emission_tuples_this_block: Vec<(T::AccountId, u64, u64)> = Self::epoch( netuid, emission_to_drain ); - + let emission_tuples_this_block: Vec<(T::AccountId, u64, u64)> = + Self::epoch(netuid, emission_to_drain); + // --- 6. Check that the emission does not exceed the allowed total. - let emission_sum: u128 = emission_tuples_this_block.iter().map( |(_account_id, ve, se)| *ve as u128 + *se as u128 ).sum(); - if emission_sum > emission_to_drain as u128 { continue } // Saftey check. + let emission_sum: u128 = emission_tuples_this_block + .iter() + .map(|(_account_id, ve, se)| *ve as u128 + *se as u128) + .sum(); + if emission_sum > emission_to_drain as u128 { + continue; + } // Saftey check. // --- 7. Sink the emission tuples onto the already loaded. - let mut concat_emission_tuples: Vec<(T::AccountId, u64, u64)> = emission_tuples_this_block.clone(); - if Self::has_loaded_emission_tuples( netuid ) { + let mut concat_emission_tuples: Vec<(T::AccountId, u64, u64)> = + emission_tuples_this_block.clone(); + if Self::has_loaded_emission_tuples(netuid) { // 7.a We already have loaded emission tuples, so we concat the new ones. - let mut current_emission_tuples: Vec<(T::AccountId, u64, u64)> = Self::get_loaded_emission_tuples( netuid ); - concat_emission_tuples.append( &mut current_emission_tuples ); - } - LoadedEmission::::insert( netuid, concat_emission_tuples ); + let mut current_emission_tuples: Vec<(T::AccountId, u64, u64)> = + Self::get_loaded_emission_tuples(netuid); + concat_emission_tuples.append(&mut current_emission_tuples); + } + LoadedEmission::::insert(netuid, concat_emission_tuples); // --- 8 Set counters. - Self::set_blocks_since_last_step( netuid, 0 ); - Self::set_last_mechanism_step_block( netuid, block_number ); + Self::set_blocks_since_last_step(netuid, 0); + Self::set_last_mechanism_step_block(netuid, block_number); } } // Distributes token inflation through the hotkey based on emission. The call ensures that the inflation // is distributed onto the accounts in proportion of the stake delegated minus the take. This function // is called after an epoch to distribute the newly minted stake according to delegation. // - pub fn emit_inflation_through_hotkey_account( hotkey: &T::AccountId, server_emission: u64, validator_emission: u64 ) { - // --- 1. Check if the hotkey is a delegate. If not, we simply pass the stake through to the + pub fn emit_inflation_through_hotkey_account( + hotkey: &T::AccountId, + server_emission: u64, + validator_emission: u64, + ) { + // --- 1. Check if the hotkey is a delegate. If not, we simply pass the stake through to the // coldkey - hotkey account as normal. - if !Self::hotkey_is_delegate( hotkey ) { - Self::increase_stake_on_hotkey_account( &hotkey, server_emission + validator_emission ); - return; + if !Self::hotkey_is_delegate(hotkey) { + Self::increase_stake_on_hotkey_account(&hotkey, server_emission + validator_emission); + return; } // Then this is a delegate, we distribute validator_emission, then server_emission. // --- 2. The hotkey is a delegate. We first distribute a proportion of the validator_emission to the hotkey // directly as a function of its 'take' - let total_hotkey_stake: u64 = Self::get_total_stake_for_hotkey( hotkey ); - let delegate_take: u64 = Self::calculate_delegate_proportional_take( hotkey, validator_emission ); + let total_hotkey_stake: u64 = Self::get_total_stake_for_hotkey(hotkey); + let delegate_take: u64 = + Self::calculate_delegate_proportional_take(hotkey, validator_emission); let validator_emission_minus_take: u64 = validator_emission - delegate_take; let mut remaining_validator_emission: u64 = validator_emission_minus_take; // 3. -- The remaining emission goes to the owners in proportion to the stake delegated. - for ( owning_coldkey_i, stake_i ) in < Stake as IterableStorageDoubleMap>::iter_prefix( hotkey ) { - + for (owning_coldkey_i, stake_i) in + as IterableStorageDoubleMap>::iter_prefix( + hotkey, + ) + { // --- 4. The emission proportion is remaining_emission * ( stake / total_stake ). - let stake_proportion: u64 = Self::calculate_stake_proportional_emission( stake_i, total_hotkey_stake, validator_emission_minus_take ); - Self::increase_stake_on_coldkey_hotkey_account( &owning_coldkey_i, &hotkey, stake_proportion ); - log::debug!("owning_coldkey_i: {:?} hotkey: {:?} emission: +{:?} ", owning_coldkey_i, hotkey, stake_proportion ); + let stake_proportion: u64 = Self::calculate_stake_proportional_emission( + stake_i, + total_hotkey_stake, + validator_emission_minus_take, + ); + Self::increase_stake_on_coldkey_hotkey_account( + &owning_coldkey_i, + &hotkey, + stake_proportion, + ); + log::debug!( + "owning_coldkey_i: {:?} hotkey: {:?} emission: +{:?} ", + owning_coldkey_i, + hotkey, + stake_proportion + ); remaining_validator_emission -= stake_proportion; } - // --- 5. Last increase final account balance of delegate after 4, since 5 will change the stake proportion of + // --- 5. Last increase final account balance of delegate after 4, since 5 will change the stake proportion of // the delegate and effect calculation in 4. - Self::increase_stake_on_hotkey_account( &hotkey, delegate_take + remaining_validator_emission ); - log::debug!("delkey: {:?} delegate_take: +{:?} ", hotkey, delegate_take ); + Self::increase_stake_on_hotkey_account( + &hotkey, + delegate_take + remaining_validator_emission, + ); + log::debug!("delkey: {:?} delegate_take: +{:?} ", hotkey, delegate_take); // Also emit the server_emission to the hotkey // The server emission is distributed in-full to the delegate owner. // We do this after 4. for the same reason as above. - Self::increase_stake_on_hotkey_account( &hotkey, server_emission ); + Self::increase_stake_on_hotkey_account(&hotkey, server_emission); } // Increases the stake on the cold - hot pairing by increment while also incrementing other counters. // This function should be called rather than set_stake under account. - // - pub fn block_step_increase_stake_on_coldkey_hotkey_account( coldkey: &T::AccountId, hotkey: &T::AccountId, increment: u64 ){ - TotalColdkeyStake::::mutate( coldkey, | old | old.saturating_add( increment ) ); - TotalHotkeyStake::::insert( hotkey, TotalHotkeyStake::::get(hotkey).saturating_add( increment ) ); - Stake::::insert( hotkey, coldkey, Stake::::get( hotkey, coldkey).saturating_add( increment ) ); - TotalStake::::put( TotalStake::::get().saturating_add( increment ) ); - TotalIssuance::::put( TotalIssuance::::get().saturating_add( increment ) ); - + // + pub fn block_step_increase_stake_on_coldkey_hotkey_account( + coldkey: &T::AccountId, + hotkey: &T::AccountId, + increment: u64, + ) { + TotalColdkeyStake::::mutate(coldkey, |old| old.saturating_add(increment)); + TotalHotkeyStake::::insert( + hotkey, + TotalHotkeyStake::::get(hotkey).saturating_add(increment), + ); + Stake::::insert( + hotkey, + coldkey, + Stake::::get(hotkey, coldkey).saturating_add(increment), + ); + TotalStake::::put(TotalStake::::get().saturating_add(increment)); + TotalIssuance::::put(TotalIssuance::::get().saturating_add(increment)); } // Decreases the stake on the cold - hot pairing by the decrement while decreasing other counters. // - pub fn block_step_decrease_stake_on_coldkey_hotkey_account( coldkey: &T::AccountId, hotkey: &T::AccountId, decrement: u64 ){ - TotalColdkeyStake::::mutate( coldkey, | old | old.saturating_sub( decrement ) ); - TotalHotkeyStake::::insert( hotkey, TotalHotkeyStake::::get(hotkey).saturating_sub( decrement ) ); - Stake::::insert( hotkey, coldkey, Stake::::get( hotkey, coldkey).saturating_sub( decrement ) ); - TotalStake::::put( TotalStake::::get().saturating_sub( decrement ) ); - TotalIssuance::::put( TotalIssuance::::get().saturating_sub( decrement ) ); + pub fn block_step_decrease_stake_on_coldkey_hotkey_account( + coldkey: &T::AccountId, + hotkey: &T::AccountId, + decrement: u64, + ) { + TotalColdkeyStake::::mutate(coldkey, |old| old.saturating_sub(decrement)); + TotalHotkeyStake::::insert( + hotkey, + TotalHotkeyStake::::get(hotkey).saturating_sub(decrement), + ); + Stake::::insert( + hotkey, + coldkey, + Stake::::get(hotkey, coldkey).saturating_sub(decrement), + ); + TotalStake::::put(TotalStake::::get().saturating_sub(decrement)); + TotalIssuance::::put(TotalIssuance::::get().saturating_sub(decrement)); } // Returns emission awarded to a hotkey as a function of its proportion of the total stake. // - pub fn calculate_stake_proportional_emission( stake: u64, total_stake:u64, emission: u64 ) -> u64 { - if total_stake == 0 { return 0 }; - let stake_proportion: I64F64 = I64F64::from_num( stake ) / I64F64::from_num( total_stake ); - let proportional_emission: I64F64 = I64F64::from_num( emission ) * stake_proportion; + pub fn calculate_stake_proportional_emission( + stake: u64, + total_stake: u64, + emission: u64, + ) -> u64 { + if total_stake == 0 { + return 0; + }; + let stake_proportion: I64F64 = I64F64::from_num(stake) / I64F64::from_num(total_stake); + let proportional_emission: I64F64 = I64F64::from_num(emission) * stake_proportion; return proportional_emission.to_num::(); } // Returns the delegated stake 'take' assigned to this key. (If exists, otherwise 0) // - pub fn calculate_delegate_proportional_take( hotkey: &T::AccountId, emission: u64 ) -> u64 { - if Self::hotkey_is_delegate( hotkey ) { - let take_proportion: I64F64 = I64F64::from_num( Delegates::::get( hotkey ) ) / I64F64::from_num( u16::MAX ); - let take_emission: I64F64 = take_proportion * I64F64::from_num( emission ); + pub fn calculate_delegate_proportional_take(hotkey: &T::AccountId, emission: u64) -> u64 { + if Self::hotkey_is_delegate(hotkey) { + let take_proportion: I64F64 = + I64F64::from_num(Delegates::::get(hotkey)) / I64F64::from_num(u16::MAX); + let take_emission: I64F64 = take_proportion * I64F64::from_num(emission); return take_emission.to_num::(); } else { return 0; @@ -204,15 +291,13 @@ impl Pallet { // Adjusts the network difficulties/burns of every active network. Resetting state parameters. // - pub fn adjust_registration_terms_for_networks( ) { - + pub fn adjust_registration_terms_for_networks() { // --- 1. Iterate through each network. - for ( netuid, _ ) in as IterableStorageMap>::iter(){ - + for (netuid, _) in as IterableStorageMap>::iter() { // --- 2. Pull counters for network difficulty. - let last_adjustment_block: u64 = Self::get_last_adjustment_block( netuid ); - let adjustment_interval: u16 = Self::get_adjustment_interval( netuid ); - let current_block: u64 = Self::get_current_block_as_u64( ); + let last_adjustment_block: u64 = Self::get_last_adjustment_block(netuid); + let adjustment_interval: u16 = Self::get_adjustment_interval(netuid); + let current_block: u64 = Self::get_current_block_as_u64(); log::debug!("netuid: {:?} last_adjustment_block: {:?} adjustment_interval: {:?} current_block: {:?}", netuid, last_adjustment_block, @@ -222,35 +307,70 @@ impl Pallet { // --- 3. Check if we are at the adjustment interval for this network. // If so, we need to adjust the registration difficulty based on target and actual registrations. - if ( current_block - last_adjustment_block ) >= adjustment_interval as u64 { - + if (current_block - last_adjustment_block) >= adjustment_interval as u64 { // --- 4. Get the current counters for this network w.r.t burn and difficulty values. - let current_burn: u64 = Self::get_burn_as_u64( netuid ); - let current_difficulty: u64 = Self::get_difficulty_as_u64( netuid ); - let registrations_this_interval: u16 = Self::get_registrations_this_interval( netuid ); - let pow_registrations_this_interval: u16 = Self::get_pow_registrations_this_interval( netuid ); - let burn_registrations_this_interval: u16 = Self::get_burn_registrations_this_interval( netuid ); - let target_registrations_this_interval: u16 = Self::get_target_registrations_per_interval( netuid ); + let current_burn: u64 = Self::get_burn_as_u64(netuid); + let current_difficulty: u64 = Self::get_difficulty_as_u64(netuid); + let registrations_this_interval: u16 = + Self::get_registrations_this_interval(netuid); + let pow_registrations_this_interval: u16 = + Self::get_pow_registrations_this_interval(netuid); + let burn_registrations_this_interval: u16 = + Self::get_burn_registrations_this_interval(netuid); + let target_registrations_this_interval: u16 = + Self::get_target_registrations_per_interval(netuid); // --- 5. Adjust burn + pow // There are six cases to consider. A, B, C, D, E, F if registrations_this_interval > target_registrations_this_interval { if pow_registrations_this_interval > burn_registrations_this_interval { // A. There are too many registrations this interval and most of them are pow registrations // this triggers an increase in the pow difficulty. - // pow_difficulty ++ - Self::set_difficulty( netuid, Self::adjust_difficulty( netuid, current_difficulty, registrations_this_interval, target_registrations_this_interval ) ); + // pow_difficulty ++ + Self::set_difficulty( + netuid, + Self::adjust_difficulty( + netuid, + current_difficulty, + registrations_this_interval, + target_registrations_this_interval, + ), + ); } else if pow_registrations_this_interval < burn_registrations_this_interval { // B. There are too many registrations this interval and most of them are burn registrations // this triggers an increase in the burn cost. // burn_cost ++ - Self::set_burn( netuid, Self::adjust_burn( netuid, current_burn, registrations_this_interval, target_registrations_this_interval ) ); + Self::set_burn( + netuid, + Self::adjust_burn( + netuid, + current_burn, + registrations_this_interval, + target_registrations_this_interval, + ), + ); } else { // F. There are too many registrations this interval and the pow and burn registrations are equal // this triggers an increase in the burn cost and pow difficulty // burn_cost ++ - Self::set_burn( netuid, Self::adjust_burn( netuid, current_burn, registrations_this_interval, target_registrations_this_interval ) ); + Self::set_burn( + netuid, + Self::adjust_burn( + netuid, + current_burn, + registrations_this_interval, + target_registrations_this_interval, + ), + ); // pow_difficulty ++ - Self::set_difficulty( netuid, Self::adjust_difficulty( netuid, current_difficulty, registrations_this_interval, target_registrations_this_interval ) ); + Self::set_difficulty( + netuid, + Self::adjust_difficulty( + netuid, + current_difficulty, + registrations_this_interval, + target_registrations_this_interval, + ), + ); } } else { // Not enough registrations this interval. @@ -258,48 +378,88 @@ impl Pallet { // C. There are not enough registrations this interval and most of them are pow registrations // this triggers a decrease in the burn cost // burn_cost -- - Self::set_burn( netuid, Self::adjust_burn( netuid, current_burn, registrations_this_interval, target_registrations_this_interval ) ); - } else if pow_registrations_this_interval < burn_registrations_this_interval{ + Self::set_burn( + netuid, + Self::adjust_burn( + netuid, + current_burn, + registrations_this_interval, + target_registrations_this_interval, + ), + ); + } else if pow_registrations_this_interval < burn_registrations_this_interval { // D. There are not enough registrations this interval and most of them are burn registrations // this triggers a decrease in the pow difficulty - // pow_difficulty -- - Self::set_difficulty( netuid, Self::adjust_difficulty( netuid, current_difficulty, registrations_this_interval, target_registrations_this_interval ) ); + // pow_difficulty -- + Self::set_difficulty( + netuid, + Self::adjust_difficulty( + netuid, + current_difficulty, + registrations_this_interval, + target_registrations_this_interval, + ), + ); } else { // E. There are not enough registrations this interval and the pow and burn registrations are equal // this triggers a decrease in the burn cost and pow difficulty // burn_cost -- - Self::set_burn( netuid, Self::adjust_burn( netuid, current_burn, registrations_this_interval, target_registrations_this_interval ) ); - // pow_difficulty -- - Self::set_difficulty( netuid, Self::adjust_difficulty( netuid, current_difficulty, registrations_this_interval, target_registrations_this_interval ) ); + Self::set_burn( + netuid, + Self::adjust_burn( + netuid, + current_burn, + registrations_this_interval, + target_registrations_this_interval, + ), + ); + // pow_difficulty -- + Self::set_difficulty( + netuid, + Self::adjust_difficulty( + netuid, + current_difficulty, + registrations_this_interval, + target_registrations_this_interval, + ), + ); } } // --- 6. Drain all counters for this network for this interval. - Self::set_last_adjustment_block( netuid, current_block ); - Self::set_registrations_this_interval( netuid, 0 ); - Self::set_pow_registrations_this_interval( netuid, 0 ); - Self::set_burn_registrations_this_interval( netuid, 0 ); + Self::set_last_adjustment_block(netuid, current_block); + Self::set_registrations_this_interval(netuid, 0); + Self::set_pow_registrations_this_interval(netuid, 0); + Self::set_burn_registrations_this_interval(netuid, 0); } // --- 7. Drain block registrations for each network. Needed for registration rate limits. - Self::set_registrations_this_block( netuid, 0 ); + Self::set_registrations_this_block(netuid, 0); } } // Performs the difficulty adjustment by multiplying the current difficulty by the ratio ( reg_actual + reg_target / reg_target * reg_target ) // We use I110F18 to avoid any overflows on u64. Also min_difficulty and max_difficulty bound the range. // - pub fn adjust_difficulty( + pub fn adjust_difficulty( netuid: u16, - current_difficulty: u64, - registrations_this_interval: u16, - target_registrations_per_interval: u16 + current_difficulty: u64, + registrations_this_interval: u16, + target_registrations_per_interval: u16, ) -> u64 { - let next_value: I110F18 = I110F18::from_num( current_difficulty ) * I110F18::from_num( registrations_this_interval + target_registrations_per_interval ) / I110F18::from_num( target_registrations_per_interval + target_registrations_per_interval ); - if next_value >= I110F18::from_num( Self::get_max_difficulty( netuid ) ){ - return Self::get_max_difficulty( netuid ); - } else if next_value <= I110F18::from_num( Self::get_min_difficulty( netuid ) ) { - return Self::get_min_difficulty( netuid ); + let updated_difficulty: I110F18 = I110F18::from_num(current_difficulty) + * I110F18::from_num(registrations_this_interval + target_registrations_per_interval) + / I110F18::from_num( + target_registrations_per_interval + target_registrations_per_interval, + ); + let alpha: I110F18 = + I110F18::from_num(Self::get_adjustment_alpha(netuid)) / I110F18::from_num(u64::MAX); + let next_value: I110F18 = alpha * I110F18::from_num(current_difficulty) + + (I110F18::from_num(1.0) - alpha) * updated_difficulty; + if next_value >= I110F18::from_num(Self::get_max_difficulty(netuid)) { + return Self::get_max_difficulty(netuid); + } else if next_value <= I110F18::from_num(Self::get_min_difficulty(netuid)) { + return Self::get_min_difficulty(netuid); } else { return next_value.to_num::(); } @@ -308,20 +468,27 @@ impl Pallet { // Performs the burn adjustment by multiplying the current difficulty by the ratio ( reg_actual + reg_target / reg_target * reg_target ) // We use I110F18 to avoid any overflows on u64. Also min_burn and max_burn bound the range. // - pub fn adjust_burn( + pub fn adjust_burn( netuid: u16, - current_burn: u64, - registrations_this_interval: u16, - target_registrations_per_interval: u16 + current_burn: u64, + registrations_this_interval: u16, + target_registrations_per_interval: u16, ) -> u64 { - let next_value: I110F18 = I110F18::from_num( current_burn ) * I110F18::from_num( registrations_this_interval + target_registrations_per_interval ) / I110F18::from_num( target_registrations_per_interval + target_registrations_per_interval ); - if next_value >= I110F18::from_num( Self::get_max_burn_as_u64( netuid ) ){ - return Self::get_max_burn_as_u64( netuid ); - } else if next_value <= I110F18::from_num( Self::get_min_burn_as_u64( netuid ) ) { - return Self::get_min_burn_as_u64( netuid ); + let updated_burn: I110F18 = I110F18::from_num(current_burn) + * I110F18::from_num(registrations_this_interval + target_registrations_per_interval) + / I110F18::from_num( + target_registrations_per_interval + target_registrations_per_interval, + ); + let alpha: I110F18 = + I110F18::from_num(Self::get_adjustment_alpha(netuid)) / I110F18::from_num(u64::MAX); + let next_value: I110F18 = alpha * I110F18::from_num(current_burn) + + (I110F18::from_num(1.0) - alpha) * updated_burn; + if next_value >= I110F18::from_num(Self::get_max_burn_as_u64(netuid)) { + return Self::get_max_burn_as_u64(netuid); + } else if next_value <= I110F18::from_num(Self::get_min_burn_as_u64(netuid)) { + return Self::get_min_burn_as_u64(netuid); } else { return next_value.to_num::(); } } - } diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 2bcaeb2c3..55d123361 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -5,45 +5,23 @@ // pub use pallet::*; -use frame_system::{ - self as system, - ensure_signed -}; +use frame_system::{self as system, ensure_signed}; use frame_support::{ - dispatch, - dispatch::{ - DispatchInfo, - PostDispatchInfo, - DispatchResult, - DispatchError - }, ensure, - traits::{ - Currency, - ExistenceRequirement, - tokens::{ - WithdrawReasons - }, - IsSubType, - } + dispatch, + dispatch::{DispatchError, DispatchInfo, DispatchResult, PostDispatchInfo}, + ensure, + traits::{tokens::WithdrawReasons, Currency, ExistenceRequirement, IsSubType}, }; -use sp_std::marker::PhantomData; use codec::{Decode, Encode}; +use frame_support::sp_runtime::transaction_validity::ValidTransaction; +use scale_info::TypeInfo; use sp_runtime::{ - traits::{ - Dispatchable, - DispatchInfoOf, - SignedExtension, - PostDispatchInfoOf, - }, - transaction_validity::{ - TransactionValidity, - TransactionValidityError - } + traits::{DispatchInfoOf, Dispatchable, PostDispatchInfoOf, SignedExtension}, + transaction_validity::{TransactionValidity, TransactionValidityError}, }; -use scale_info::TypeInfo; -use frame_support::sp_runtime::transaction_validity::ValidTransaction; +use sp_std::marker::PhantomData; // ============================ // ==== Benchmark Imports ===== @@ -60,12 +38,12 @@ mod epoch; mod math; mod networks; mod registration; +mod senate; mod serving; mod staking; -mod utils; mod uids; +mod utils; mod weights; -mod senate; pub mod delegate_info; pub mod neuron_info; @@ -77,1722 +55,2174 @@ mod migration; #[frame_support::pallet] pub mod pallet { - use frame_support::{ - dispatch::GetDispatchInfo, - pallet_prelude::{*, StorageMap, DispatchResult} - }; - use frame_system::pallet_prelude::*; - use frame_support::traits::{Currency, UnfilteredDispatchable}; - use frame_support::sp_std::vec; - use frame_support::inherent::Vec; - - #[cfg(not(feature = "std"))] - use alloc::boxed::Box; - #[cfg(feature = "std")] - use sp_std::prelude::Box; - - // Tracks version for migrations. Should be monotonic with respect to the - // order of migrations. (i.e. always increasing) - const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); - - #[pallet::pallet] - #[pallet::generate_store(pub(super) trait Store)] - #[pallet::without_storage_info] - #[pallet::storage_version(STORAGE_VERSION)] - pub struct Pallet(_); - - // Configure the pallet by specifying the parameters and types on which it depends. - #[pallet::config] - pub trait Config: frame_system::Config { - // Because this pallet emits events, it depends on the runtime's definition of an event. - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - - /// A sudo-able call. - type SudoRuntimeCall: Parameter - + UnfilteredDispatchable - + GetDispatchInfo; - - /// Origin checking for council majority - type CouncilOrigin: EnsureOrigin; - - // --- Currency type that will be used to place deposits on neurons - type Currency: Currency + Send + Sync; - - type SenateMembers: crate::MemberManagement; - - type TriumvirateInterface: crate::CollectiveInterface; - - // ================================= - // ==== Initial Value Constants ==== - // ================================= - #[pallet::constant] // Initial currency issuance. - type InitialIssuance: Get; - #[pallet::constant] // Initial min allowed weights setting. - type InitialMinAllowedWeights: Get; - #[pallet::constant] // Initial Emission Ratio. - type InitialEmissionValue: Get; - #[pallet::constant] // Initial max weight limit. - type InitialMaxWeightsLimit: Get; - #[pallet::constant] // Tempo for each network. - type InitialTempo: Get; - #[pallet::constant] // Initial Difficulty. - type InitialDifficulty: Get; - #[pallet::constant] // Initial Max Difficulty. - type InitialMaxDifficulty: Get; - #[pallet::constant] // Initial Min Difficulty. - type InitialMinDifficulty: Get; - #[pallet::constant] // Initial RAO Recycled. - type InitialRAORecycledForRegistration: Get; - #[pallet::constant] // Initial Burn. - type InitialBurn: Get; - #[pallet::constant] // Initial Max Burn. - type InitialMaxBurn: Get; - #[pallet::constant] // Initial Min Burn. - type InitialMinBurn: Get; - #[pallet::constant] // Initial adjustment interval. - type InitialAdjustmentInterval: Get; - #[pallet::constant] // Initial bonds moving average. - type InitialBondsMovingAverage: Get; - #[pallet::constant] // Initial target registrations per interval. - type InitialTargetRegistrationsPerInterval: Get; - #[pallet::constant] // Rho constant. - type InitialRho: Get; - #[pallet::constant] // Kappa constant. - type InitialKappa: Get; - #[pallet::constant] // Max UID constant. - type InitialMaxAllowedUids: Get; - #[pallet::constant] // Default batch size. - type InitialValidatorBatchSize: Get; - #[pallet::constant] // Default Sequence length. - type InitialValidatorSequenceLen: Get; - #[pallet::constant] // Default Epoch length. - type InitialValidatorEpochLen: Get; - #[pallet::constant] // Default Reset length. - type InitialValidatorEpochsPerReset: Get; - #[pallet::constant] // Initial validator exclude quantile. - type InitialValidatorExcludeQuantile: Get; - #[pallet::constant] // Initial validator logits divergence penalty/threshold. - type InitialValidatorLogitsDivergence: Get; - #[pallet::constant] // Initial validator context pruning length. - type InitialValidatorPruneLen: Get; - #[pallet::constant] // Initial scaling law power. - type InitialScalingLawPower: Get; - #[pallet::constant] // Initial synergy scaling law power. - type InitialSynergyScalingLawPower: Get; - #[pallet::constant] // Immunity Period Constant. - type InitialImmunityPeriod: Get; - #[pallet::constant] // Activity constant. - type InitialActivityCutoff: Get; - #[pallet::constant] // Initial max registrations per block. - type InitialMaxRegistrationsPerBlock: Get; - #[pallet::constant] // Initial pruning score for each neuron. - type InitialPruningScore: Get; - #[pallet::constant] // Initial maximum allowed validators per network. - type InitialMaxAllowedValidators: Get; - #[pallet::constant] // Initial default delegation take. - type InitialDefaultTake: Get; - #[pallet::constant] // Initial weights version key. - type InitialWeightsVersionKey: Get; - #[pallet::constant] // Initial serving rate limit. - type InitialServingRateLimit: Get; - #[pallet::constant] // Initial transaction rate limit. - type InitialTxRateLimit: Get; - #[pallet::constant] // Initial percentage of total stake required to join senate. - type InitialSenateRequiredStakePercentage: Get; - } - - pub type AccountIdOf = ::AccountId; - - // Senate requirements - #[pallet::type_value] - pub fn DefaultSenateRequiredStakePercentage() -> u64 { T::InitialSenateRequiredStakePercentage::get() } - - #[pallet::storage] // --- ITEM ( tx_rate_limit ) - pub(super) type SenateRequiredStakePercentage = StorageValue<_, u64, ValueQuery, DefaultSenateRequiredStakePercentage>; - - // ============================ - // ==== Staking + Accounts ==== - // ============================ - #[pallet::type_value] - pub fn DefaultDefaultTake() -> u16 { T::InitialDefaultTake::get() } - #[pallet::type_value] - pub fn DefaultAccountTake() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultBlockEmission() -> u64 {1_000_000_000} - #[pallet::type_value] - pub fn DefaultAllowsDelegation() -> bool { false } - #[pallet::type_value] - pub fn DefaultTotalIssuance() -> u64 { T::InitialIssuance::get() } - #[pallet::type_value] - pub fn DefaultAccount() -> T::AccountId { T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap()} - - #[pallet::storage] // --- ITEM ( total_stake ) - pub type TotalStake = StorageValue<_, u64, ValueQuery>; - #[pallet::storage] // --- ITEM ( default_take ) - pub type DefaultTake = StorageValue<_, u16, ValueQuery, DefaultDefaultTake>; - #[pallet::storage] // --- ITEM ( global_block_emission ) - pub type BlockEmission = StorageValue<_, u64, ValueQuery, DefaultBlockEmission>; - #[pallet::storage] // --- ITEM ( total_issuance ) - pub type TotalIssuance = StorageValue<_, u64, ValueQuery, DefaultTotalIssuance>; - #[pallet::storage] // --- MAP ( hot ) --> stake | Returns the total amount of stake under a hotkey. - pub type TotalHotkeyStake = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultAccountTake>; - #[pallet::storage] // --- MAP ( cold ) --> stake | Returns the total amount of stake under a coldkey. - pub type TotalColdkeyStake = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultAccountTake>; - #[pallet::storage] // --- MAP ( hot ) --> cold | Returns the controlling coldkey for a hotkey. - pub type Owner = StorageMap<_, Blake2_128Concat, T::AccountId, T::AccountId, ValueQuery, DefaultAccount>; - #[pallet::storage] // --- MAP ( hot ) --> take | Returns the hotkey delegation take. And signals that this key is open for delegation. - pub type Delegates = StorageMap<_, Blake2_128Concat, T::AccountId, u16, ValueQuery, DefaultDefaultTake>; - #[pallet::storage] // --- DMAP ( hot, cold ) --> stake | Returns the stake under a coldkey prefixed by hotkey. - pub type Stake = StorageDoubleMap<_, Blake2_128Concat, T::AccountId, Identity, T::AccountId, u64, ValueQuery, DefaultAccountTake>; - - // ===================================== - // ==== Difficulty / Registrations ===== - // ===================================== - #[pallet::type_value] - pub fn DefaultLastAdjustmentBlock() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultRegistrationsThisBlock() -> u16 { 0} - #[pallet::type_value] - pub fn DefaultBurn() -> u64 { T::InitialBurn::get() } - #[pallet::type_value] - pub fn DefaultMinBurn() -> u64 { T::InitialMinBurn::get() } - #[pallet::type_value] - pub fn DefaultMaxBurn() -> u64 { T::InitialMaxBurn::get() } - #[pallet::type_value] - pub fn DefaultDifficulty() -> u64 { T::InitialDifficulty::get() } - #[pallet::type_value] - pub fn DefaultMinDifficulty() -> u64 { T::InitialMinDifficulty::get() } - #[pallet::type_value] - pub fn DefaultMaxDifficulty() -> u64 { T::InitialMaxDifficulty::get() } - #[pallet::type_value] - pub fn DefaultMaxRegistrationsPerBlock() -> u16 { T::InitialMaxRegistrationsPerBlock::get() } - #[pallet::type_value] - pub fn DefaultRAORecycledForRegistration() -> u64 { T::InitialRAORecycledForRegistration::get() } - - #[pallet::storage] // ---- StorageItem Global Used Work. - pub type UsedWork = StorageMap<_, Identity, Vec, u64, ValueQuery>; - #[pallet::storage] // --- MAP ( netuid ) --> Burn - pub type Burn = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultBurn >; - #[pallet::storage] // --- MAP ( netuid ) --> Difficulty - pub type Difficulty = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultDifficulty >; - #[pallet::storage] // --- MAP ( netuid ) --> MinBurn - pub type MinBurn = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMinBurn >; - #[pallet::storage] // --- MAP ( netuid ) --> MaxBurn - pub type MaxBurn = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMaxBurn >; - #[pallet::storage] // --- MAP ( netuid ) --> MinDifficulty - pub type MinDifficulty = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMinDifficulty >; - #[pallet::storage] // --- MAP ( netuid ) --> MaxDifficulty - pub type MaxDifficulty = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMaxDifficulty >; - #[pallet::storage] // --- MAP ( netuid ) --> Block at last adjustment. - pub type LastAdjustmentBlock = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultLastAdjustmentBlock >; - #[pallet::storage] // --- MAP ( netuid ) --> Registrations of this Block. - pub type RegistrationsThisBlock = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultRegistrationsThisBlock>; - #[pallet::storage] // --- ITEM( global_max_registrations_per_block ) - pub type MaxRegistrationsPerBlock = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxRegistrationsPerBlock >; - #[pallet::storage] // --- MAP ( netuid, global_RAO_recycled_for_registration ) - pub type RAORecycledForRegistration = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultRAORecycledForRegistration >; - - // ============================== - // ==== Subnetworks Storage ===== - // ============================== - #[pallet::type_value] - pub fn DefaultN() -> u16 { 0 } - #[pallet::type_value] - pub fn DefaultModality() -> u16 { 0 } - #[pallet::type_value] - pub fn DefaultHotkeys() -> Vec { vec![ ] } - #[pallet::type_value] - pub fn DefaultNeworksAdded() -> bool { false } - #[pallet::type_value] - pub fn DefaultIsNetworkMember() -> bool { false } - #[pallet::type_value] - pub fn DefaultRegistrationAllowed() -> bool { false } - - - #[pallet::storage] // --- ITEM( total_number_of_existing_networks ) - pub type TotalNetworks = StorageValue<_, u16, ValueQuery>; - #[pallet::storage] // --- MAP ( netuid ) --> subnetwork_n (Number of UIDs in the network). - pub type SubnetworkN = StorageMap< _, Identity, u16, u16, ValueQuery, DefaultN >; - #[pallet::storage] // --- MAP ( netuid ) --> modality TEXT: 0, IMAGE: 1, TENSOR: 2 - pub type NetworkModality = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultModality> ; - #[pallet::storage] // --- MAP ( netuid ) --> network_is_added - pub type NetworksAdded = StorageMap<_, Identity, u16, bool, ValueQuery, DefaultNeworksAdded>; - #[pallet::storage] // --- DMAP ( netuid, netuid ) -> registration_requirement - pub type NetworkConnect = StorageDoubleMap<_, Identity, u16, Identity, u16, u16, OptionQuery>; - #[pallet::storage] // --- DMAP ( hotkey, netuid ) --> bool - pub type IsNetworkMember = StorageDoubleMap<_, Blake2_128Concat, T::AccountId, Identity, u16, bool, ValueQuery, DefaultIsNetworkMember>; - #[pallet::storage] // --- MAP ( netuid ) --> network_registration_allowed - pub type NetworkRegistrationAllowed = StorageMap<_, Identity, u16, bool, ValueQuery, DefaultRegistrationAllowed>; - - // ============================== - // ==== Subnetwork Features ===== - // ============================== - #[pallet::type_value] - pub fn DefaultEmissionValues() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultPendingEmission() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultBlocksSinceLastStep() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultLastMechansimStepBlock() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultTempo() -> u16 { T::InitialTempo::get() } - - #[pallet::storage] // --- MAP ( netuid ) --> tempo - pub type Tempo = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultTempo >; - #[pallet::storage] // --- MAP ( netuid ) --> emission_values - pub type EmissionValues = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultEmissionValues>; - #[pallet::storage] // --- MAP ( netuid ) --> pending_emission - pub type PendingEmission = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultPendingEmission>; - #[pallet::storage] // --- MAP ( netuid ) --> blocks_since_last_step. - pub type BlocksSinceLastStep = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultBlocksSinceLastStep>; - #[pallet::storage] // --- MAP ( netuid ) --> last_mechanism_step_block - pub type LastMechansimStepBlock = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultLastMechansimStepBlock >; - - // ================================= - // ==== Axon / Promo Endpoints ===== - // ================================= - - // --- Struct for Axon. - pub type AxonInfoOf = AxonInfo; - - #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] + use frame_support::inherent::Vec; + use frame_support::sp_std::vec; + use frame_support::traits::{Currency, UnfilteredDispatchable}; + use frame_support::{ + dispatch::GetDispatchInfo, + pallet_prelude::{DispatchResult, StorageMap, *}, + }; + use frame_system::pallet_prelude::*; + + #[cfg(not(feature = "std"))] + use alloc::boxed::Box; + #[cfg(feature = "std")] + use sp_std::prelude::Box; + + // Tracks version for migrations. Should be monotonic with respect to the + // order of migrations. (i.e. always increasing) + const STORAGE_VERSION: StorageVersion = StorageVersion::new(1); + + #[pallet::pallet] + #[pallet::generate_store(pub(super) trait Store)] + #[pallet::without_storage_info] + #[pallet::storage_version(STORAGE_VERSION)] + pub struct Pallet(_); + + // Configure the pallet by specifying the parameters and types on which it depends. + #[pallet::config] + pub trait Config: frame_system::Config { + // Because this pallet emits events, it depends on the runtime's definition of an event. + type RuntimeEvent: From> + IsType<::RuntimeEvent>; + + /// A sudo-able call. + type SudoRuntimeCall: Parameter + + UnfilteredDispatchable + + GetDispatchInfo; + + /// Origin checking for council majority + type CouncilOrigin: EnsureOrigin; + + // --- Currency type that will be used to place deposits on neurons + type Currency: Currency + Send + Sync; + + type SenateMembers: crate::MemberManagement; + + type TriumvirateInterface: crate::CollectiveInterface; + + // ================================= + // ==== Initial Value Constants ==== + // ================================= + #[pallet::constant] // Initial currency issuance. + type InitialIssuance: Get; + #[pallet::constant] // Initial min allowed weights setting. + type InitialMinAllowedWeights: Get; + #[pallet::constant] // Initial Emission Ratio. + type InitialEmissionValue: Get; + #[pallet::constant] // Initial max weight limit. + type InitialMaxWeightsLimit: Get; + #[pallet::constant] // Tempo for each network. + type InitialTempo: Get; + #[pallet::constant] // Initial Difficulty. + type InitialDifficulty: Get; + #[pallet::constant] // Initial Max Difficulty. + type InitialMaxDifficulty: Get; + #[pallet::constant] // Initial Min Difficulty. + type InitialMinDifficulty: Get; + #[pallet::constant] // Initial RAO Recycled. + type InitialRAORecycledForRegistration: Get; + #[pallet::constant] // Initial Burn. + type InitialBurn: Get; + #[pallet::constant] // Initial Max Burn. + type InitialMaxBurn: Get; + #[pallet::constant] // Initial Min Burn. + type InitialMinBurn: Get; + #[pallet::constant] // Initial adjustment interval. + type InitialAdjustmentInterval: Get; + #[pallet::constant] // Initial bonds moving average. + type InitialBondsMovingAverage: Get; + #[pallet::constant] // Initial target registrations per interval. + type InitialTargetRegistrationsPerInterval: Get; + #[pallet::constant] // Rho constant. + type InitialRho: Get; + #[pallet::constant] // Kappa constant. + type InitialKappa: Get; + #[pallet::constant] // Max UID constant. + type InitialMaxAllowedUids: Get; + #[pallet::constant] // Default batch size. + type InitialValidatorBatchSize: Get; + #[pallet::constant] // Default Sequence length. + type InitialValidatorSequenceLen: Get; + #[pallet::constant] // Default Epoch length. + type InitialValidatorEpochLen: Get; + #[pallet::constant] // Default Reset length. + type InitialValidatorEpochsPerReset: Get; + #[pallet::constant] // Initial validator exclude quantile. + type InitialValidatorExcludeQuantile: Get; + #[pallet::constant] // Initial validator logits divergence penalty/threshold. + type InitialValidatorLogitsDivergence: Get; + #[pallet::constant] // Initial validator context pruning length. + type InitialValidatorPruneLen: Get; + #[pallet::constant] // Initial scaling law power. + type InitialScalingLawPower: Get; + #[pallet::constant] // Initial synergy scaling law power. + type InitialSynergyScalingLawPower: Get; + #[pallet::constant] // Immunity Period Constant. + type InitialImmunityPeriod: Get; + #[pallet::constant] // Activity constant. + type InitialActivityCutoff: Get; + #[pallet::constant] // Initial max registrations per block. + type InitialMaxRegistrationsPerBlock: Get; + #[pallet::constant] // Initial pruning score for each neuron. + type InitialPruningScore: Get; + #[pallet::constant] // Initial maximum allowed validators per network. + type InitialMaxAllowedValidators: Get; + #[pallet::constant] // Initial default delegation take. + type InitialDefaultTake: Get; + #[pallet::constant] // Initial weights version key. + type InitialWeightsVersionKey: Get; + #[pallet::constant] // Initial serving rate limit. + type InitialServingRateLimit: Get; + #[pallet::constant] // Initial transaction rate limit. + type InitialTxRateLimit: Get; + #[pallet::constant] // Initial percentage of total stake required to join senate. + type InitialSenateRequiredStakePercentage: Get; + #[pallet::constant] // Initial adjustment alpha on burn and pow. + type InitialAdjustmentAlpha: Get; + } + + pub type AccountIdOf = ::AccountId; + + // Senate requirements + #[pallet::type_value] + pub fn DefaultSenateRequiredStakePercentage() -> u64 { + T::InitialSenateRequiredStakePercentage::get() + } + + #[pallet::storage] // --- ITEM ( tx_rate_limit ) + pub(super) type SenateRequiredStakePercentage = + StorageValue<_, u64, ValueQuery, DefaultSenateRequiredStakePercentage>; + + // ============================ + // ==== Staking + Accounts ==== + // ============================ + #[pallet::type_value] + pub fn DefaultDefaultTake() -> u16 { + T::InitialDefaultTake::get() + } + #[pallet::type_value] + pub fn DefaultAccountTake() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultBlockEmission() -> u64 { + 1_000_000_000 + } + #[pallet::type_value] + pub fn DefaultAllowsDelegation() -> bool { + false + } + #[pallet::type_value] + pub fn DefaultTotalIssuance() -> u64 { + T::InitialIssuance::get() + } + #[pallet::type_value] + pub fn DefaultAccount() -> T::AccountId { + T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap() + } + + #[pallet::storage] // --- ITEM ( total_stake ) + pub type TotalStake = StorageValue<_, u64, ValueQuery>; + #[pallet::storage] // --- ITEM ( default_take ) + pub type DefaultTake = StorageValue<_, u16, ValueQuery, DefaultDefaultTake>; + #[pallet::storage] // --- ITEM ( global_block_emission ) + pub type BlockEmission = StorageValue<_, u64, ValueQuery, DefaultBlockEmission>; + #[pallet::storage] // --- ITEM ( total_issuance ) + pub type TotalIssuance = StorageValue<_, u64, ValueQuery, DefaultTotalIssuance>; + #[pallet::storage] // --- MAP ( hot ) --> stake | Returns the total amount of stake under a hotkey. + pub type TotalHotkeyStake = + StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultAccountTake>; + #[pallet::storage] // --- MAP ( cold ) --> stake | Returns the total amount of stake under a coldkey. + pub type TotalColdkeyStake = + StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultAccountTake>; + #[pallet::storage] // --- MAP ( hot ) --> cold | Returns the controlling coldkey for a hotkey. + pub type Owner = + StorageMap<_, Blake2_128Concat, T::AccountId, T::AccountId, ValueQuery, DefaultAccount>; + #[pallet::storage] // --- MAP ( hot ) --> take | Returns the hotkey delegation take. And signals that this key is open for delegation. + pub type Delegates = + StorageMap<_, Blake2_128Concat, T::AccountId, u16, ValueQuery, DefaultDefaultTake>; + #[pallet::storage] // --- DMAP ( hot, cold ) --> stake | Returns the stake under a coldkey prefixed by hotkey. + pub type Stake = StorageDoubleMap< + _, + Blake2_128Concat, + T::AccountId, + Identity, + T::AccountId, + u64, + ValueQuery, + DefaultAccountTake, + >; + + // ===================================== + // ==== Difficulty / Registrations ===== + // ===================================== + #[pallet::type_value] + pub fn DefaultLastAdjustmentBlock() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultRegistrationsThisBlock() -> u16 { + 0 + } + #[pallet::type_value] + pub fn DefaultBurn() -> u64 { + T::InitialBurn::get() + } + #[pallet::type_value] + pub fn DefaultMinBurn() -> u64 { + T::InitialMinBurn::get() + } + #[pallet::type_value] + pub fn DefaultMaxBurn() -> u64 { + T::InitialMaxBurn::get() + } + #[pallet::type_value] + pub fn DefaultDifficulty() -> u64 { + T::InitialDifficulty::get() + } + #[pallet::type_value] + pub fn DefaultMinDifficulty() -> u64 { + T::InitialMinDifficulty::get() + } + #[pallet::type_value] + pub fn DefaultMaxDifficulty() -> u64 { + T::InitialMaxDifficulty::get() + } + #[pallet::type_value] + pub fn DefaultMaxRegistrationsPerBlock() -> u16 { + T::InitialMaxRegistrationsPerBlock::get() + } + #[pallet::type_value] + pub fn DefaultRAORecycledForRegistration() -> u64 { + T::InitialRAORecycledForRegistration::get() + } + + #[pallet::storage] // ---- StorageItem Global Used Work. + pub type UsedWork = StorageMap<_, Identity, Vec, u64, ValueQuery>; + #[pallet::storage] // --- MAP ( netuid ) --> Burn + pub type Burn = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultBurn>; + #[pallet::storage] // --- MAP ( netuid ) --> Difficulty + pub type Difficulty = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultDifficulty>; + #[pallet::storage] // --- MAP ( netuid ) --> MinBurn + pub type MinBurn = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMinBurn>; + #[pallet::storage] // --- MAP ( netuid ) --> MaxBurn + pub type MaxBurn = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMaxBurn>; + #[pallet::storage] // --- MAP ( netuid ) --> MinDifficulty + pub type MinDifficulty = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMinDifficulty>; + #[pallet::storage] // --- MAP ( netuid ) --> MaxDifficulty + pub type MaxDifficulty = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultMaxDifficulty>; + #[pallet::storage] // --- MAP ( netuid ) --> Block at last adjustment. + pub type LastAdjustmentBlock = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultLastAdjustmentBlock>; + #[pallet::storage] // --- MAP ( netuid ) --> Registrations of this Block. + pub type RegistrationsThisBlock = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultRegistrationsThisBlock>; + #[pallet::storage] // --- ITEM( global_max_registrations_per_block ) + pub type MaxRegistrationsPerBlock = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxRegistrationsPerBlock>; + #[pallet::storage] // --- MAP ( netuid, global_RAO_recycled_for_registration ) + pub type RAORecycledForRegistration = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultRAORecycledForRegistration>; + + // ============================== + // ==== Subnetworks Storage ===== + // ============================== + #[pallet::type_value] + pub fn DefaultN() -> u16 { + 0 + } + #[pallet::type_value] + pub fn DefaultModality() -> u16 { + 0 + } + #[pallet::type_value] + pub fn DefaultHotkeys() -> Vec { + vec![] + } + #[pallet::type_value] + pub fn DefaultNeworksAdded() -> bool { + false + } + #[pallet::type_value] + pub fn DefaultIsNetworkMember() -> bool { + false + } + #[pallet::type_value] + pub fn DefaultRegistrationAllowed() -> bool { + false + } + + #[pallet::storage] // --- ITEM( total_number_of_existing_networks ) + pub type TotalNetworks = StorageValue<_, u16, ValueQuery>; + #[pallet::storage] // --- MAP ( netuid ) --> subnetwork_n (Number of UIDs in the network). + pub type SubnetworkN = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultN>; + #[pallet::storage] // --- MAP ( netuid ) --> modality TEXT: 0, IMAGE: 1, TENSOR: 2 + pub type NetworkModality = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultModality>; + #[pallet::storage] // --- MAP ( netuid ) --> network_is_added + pub type NetworksAdded = + StorageMap<_, Identity, u16, bool, ValueQuery, DefaultNeworksAdded>; + #[pallet::storage] // --- DMAP ( netuid, netuid ) -> registration_requirement + pub type NetworkConnect = + StorageDoubleMap<_, Identity, u16, Identity, u16, u16, OptionQuery>; + #[pallet::storage] // --- DMAP ( hotkey, netuid ) --> bool + pub type IsNetworkMember = StorageDoubleMap< + _, + Blake2_128Concat, + T::AccountId, + Identity, + u16, + bool, + ValueQuery, + DefaultIsNetworkMember, + >; + #[pallet::storage] // --- MAP ( netuid ) --> network_registration_allowed + pub type NetworkRegistrationAllowed = + StorageMap<_, Identity, u16, bool, ValueQuery, DefaultRegistrationAllowed>; + + // ============================== + // ==== Subnetwork Features ===== + // ============================== + #[pallet::type_value] + pub fn DefaultEmissionValues() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultPendingEmission() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultBlocksSinceLastStep() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultLastMechansimStepBlock() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultTempo() -> u16 { + T::InitialTempo::get() + } + + #[pallet::storage] // --- MAP ( netuid ) --> tempo + pub type Tempo = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultTempo>; + #[pallet::storage] // --- MAP ( netuid ) --> emission_values + pub type EmissionValues = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultEmissionValues>; + #[pallet::storage] // --- MAP ( netuid ) --> pending_emission + pub type PendingEmission = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultPendingEmission>; + #[pallet::storage] // --- MAP ( netuid ) --> blocks_since_last_step. + pub type BlocksSinceLastStep = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultBlocksSinceLastStep>; + #[pallet::storage] // --- MAP ( netuid ) --> last_mechanism_step_block + pub type LastMechansimStepBlock = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultLastMechansimStepBlock>; + + // ================================= + // ==== Axon / Promo Endpoints ===== + // ================================= + + // --- Struct for Axon. + pub type AxonInfoOf = AxonInfo; + + #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] pub struct AxonInfo { - pub block: u64, // --- Axon serving block. - pub version: u32, // --- Axon version - pub ip: u128, // --- Axon u128 encoded ip address of type v6 or v4. - pub port: u16, // --- Axon u16 encoded port. - pub ip_type: u8, // --- Axon ip type, 4 for ipv4 and 6 for ipv6. - pub protocol: u8, // --- Axon protocol. TCP, UDP, other. - pub placeholder1: u8, // --- Axon proto placeholder 1. - pub placeholder2: u8, // --- Axon proto placeholder 1. - } - - // --- Struct for Prometheus. - pub type PrometheusInfoOf = PrometheusInfo; - #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] - pub struct PrometheusInfo { - pub block: u64, // --- Prometheus serving block. + pub block: u64, // --- Axon serving block. + pub version: u32, // --- Axon version + pub ip: u128, // --- Axon u128 encoded ip address of type v6 or v4. + pub port: u16, // --- Axon u16 encoded port. + pub ip_type: u8, // --- Axon ip type, 4 for ipv4 and 6 for ipv6. + pub protocol: u8, // --- Axon protocol. TCP, UDP, other. + pub placeholder1: u8, // --- Axon proto placeholder 1. + pub placeholder2: u8, // --- Axon proto placeholder 1. + } + + // --- Struct for Prometheus. + pub type PrometheusInfoOf = PrometheusInfo; + #[derive(Encode, Decode, Default, TypeInfo, Clone, PartialEq, Eq, Debug)] + pub struct PrometheusInfo { + pub block: u64, // --- Prometheus serving block. pub version: u32, // --- Prometheus version. - pub ip: u128, // --- Prometheus u128 encoded ip address of type v6 or v4. - pub port: u16, // --- Prometheus u16 encoded port. - pub ip_type: u8, // --- Prometheus ip type, 4 for ipv4 and 6 for ipv6. - } - - // Rate limiting - #[pallet::type_value] - pub fn DefaultTxRateLimit() -> u64 { T::InitialTxRateLimit::get() } - #[pallet::type_value] - pub fn DefaultLastTxBlock() -> u64 { 0 } - - #[pallet::storage] // --- ITEM ( tx_rate_limit ) - pub(super) type TxRateLimit = StorageValue<_, u64, ValueQuery, DefaultTxRateLimit>; - #[pallet::storage] // --- MAP ( key ) --> last_block - pub(super) type LastTxBlock = StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; - - - #[pallet::type_value] - pub fn DefaultServingRateLimit() -> u64 { T::InitialServingRateLimit::get() } - - #[pallet::storage] // --- MAP ( netuid ) --> serving_rate_limit - pub type ServingRateLimit = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultServingRateLimit> ; - #[pallet::storage] // --- MAP ( netuid, hotkey ) --> axon_info - pub(super) type Axons = StorageDoubleMap<_, Identity, u16, Blake2_128Concat, T::AccountId, AxonInfoOf, OptionQuery>; - #[pallet::storage] // --- MAP ( netuid, hotkey ) --> prometheus_info - pub(super) type Prometheus = StorageDoubleMap<_, Identity, u16, Blake2_128Concat, T::AccountId, PrometheusInfoOf, OptionQuery>; - - // ======================================= - // ==== Subnetwork Hyperparam storage ==== - // ======================================= - #[pallet::type_value] - pub fn DefaultWeightsSetRateLimit() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultBlockAtRegistration() -> u64 { 0 } - #[pallet::type_value] - pub fn DefaultRho() -> u16 { T::InitialRho::get() } - #[pallet::type_value] - pub fn DefaultKappa() -> u16 { T::InitialKappa::get() } - #[pallet::type_value] - pub fn DefaultMaxAllowedUids() -> u16 { T::InitialMaxAllowedUids::get() } - #[pallet::type_value] - pub fn DefaultImmunityPeriod() -> u16 { T::InitialImmunityPeriod::get() } - #[pallet::type_value] - pub fn DefaultActivityCutoff() -> u16 { T::InitialActivityCutoff::get() } - #[pallet::type_value] - pub fn DefaultMaxWeightsLimit() -> u16 { T::InitialMaxWeightsLimit::get() } - #[pallet::type_value] - pub fn DefaultWeightsVersionKey() -> u64 { T::InitialWeightsVersionKey::get() } - #[pallet::type_value] - pub fn DefaultMinAllowedWeights() -> u16 { T::InitialMinAllowedWeights::get() } - #[pallet::type_value] - pub fn DefaultValidatorEpochLen() -> u16 { T::InitialValidatorEpochLen::get() } - #[pallet::type_value] - pub fn DefaultMaxAllowedValidators() -> u16 { T::InitialMaxAllowedValidators::get() } - #[pallet::type_value] - pub fn DefaultAdjustmentInterval() -> u16 { T::InitialAdjustmentInterval::get() } - #[pallet::type_value] - pub fn DefaultBondsMovingAverage() -> u64 { T::InitialBondsMovingAverage::get() } - #[pallet::type_value] - pub fn DefaultValidatorPruneLen() -> u64 { T::InitialValidatorPruneLen::get() } - #[pallet::type_value] - pub fn DefaultValidatorBatchSize() -> u16 { T::InitialValidatorBatchSize::get() } - #[pallet::type_value] - pub fn DefaultValidatorSequenceLen() -> u16 { T::InitialValidatorSequenceLen::get() } - #[pallet::type_value] - pub fn DefaultValidatorEpochsPerReset() -> u16 { T::InitialValidatorEpochsPerReset::get() } - #[pallet::type_value] - pub fn DefaultValidatorExcludeQuantile() -> u16 { T::InitialValidatorExcludeQuantile::get() } - #[pallet::type_value] - pub fn DefaultValidatorLogitsDivergence() -> u16 { T::InitialValidatorLogitsDivergence::get() } - #[pallet::type_value] - pub fn DefaultScalingLawPower() -> u16 { T::InitialScalingLawPower::get() } - #[pallet::type_value] - pub fn DefaultSynergyScalingLawPower() -> u16 { T::InitialSynergyScalingLawPower::get() } - #[pallet::type_value] - pub fn DefaultTargetRegistrationsPerInterval() -> u16 { T::InitialTargetRegistrationsPerInterval::get() } - - - #[pallet::storage] // --- MAP ( netuid ) --> Rho - pub type Rho = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultRho >; - #[pallet::storage] // --- MAP ( netuid ) --> Kappa - pub type Kappa = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultKappa >; - #[pallet::storage] // --- MAP ( netuid ) --> uid, we use to record uids to prune at next epoch. - pub type NeuronsToPruneAtNextEpoch = StorageMap<_, Identity, u16, u16, ValueQuery>; - #[pallet::storage] // --- MAP ( netuid ) --> registrations_this_interval - pub type RegistrationsThisInterval = StorageMap<_, Identity, u16, u16, ValueQuery>; - #[pallet::storage] // --- MAP ( netuid ) --> pow_registrations_this_interval - pub type POWRegistrationsThisInterval = StorageMap<_, Identity, u16, u16, ValueQuery>; - #[pallet::storage] // --- MAP ( netuid ) --> burn_registrations_this_interval - pub type BurnRegistrationsThisInterval = StorageMap<_, Identity, u16, u16, ValueQuery>; - #[pallet::storage] // --- MAP ( netuid ) --> max_allowed_uids - pub type MaxAllowedUids = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxAllowedUids >; - #[pallet::storage] // --- MAP ( netuid ) --> immunity_period - pub type ImmunityPeriod = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultImmunityPeriod >; - #[pallet::storage] // --- MAP ( netuid ) --> activity_cutoff - pub type ActivityCutoff = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultActivityCutoff >; - #[pallet::storage] // --- MAP ( netuid ) --> max_weight_limit - pub type MaxWeightsLimit = StorageMap< _, Identity, u16, u16, ValueQuery, DefaultMaxWeightsLimit >; - #[pallet::storage] // --- MAP ( netuid ) --> weights_version_key - pub type WeightsVersionKey = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultWeightsVersionKey >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_epoch_len - pub type ValidatorEpochLen = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorEpochLen >; - #[pallet::storage] // --- MAP ( netuid ) --> min_allowed_weights - pub type MinAllowedWeights = StorageMap< _, Identity, u16, u16, ValueQuery, DefaultMinAllowedWeights >; - #[pallet::storage] // --- MAP ( netuid ) --> max_allowed_validators - pub type MaxAllowedValidators = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxAllowedValidators >; - #[pallet::storage] // --- MAP ( netuid ) --> adjustment_interval - pub type AdjustmentInterval = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultAdjustmentInterval >; - #[pallet::storage] // --- MAP ( netuid ) --> bonds_moving_average - pub type BondsMovingAverage = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultBondsMovingAverage >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_batch_size - pub type ValidatorBatchSize = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorBatchSize >; - #[pallet::storage] // --- MAP ( netuid ) --> weights_set_rate_limit - pub type WeightsSetRateLimit = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultWeightsSetRateLimit >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_prune_len - pub type ValidatorPruneLen = StorageMap<_, Identity, u16, u64, ValueQuery, DefaultValidatorPruneLen >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_sequence_length - pub type ValidatorSequenceLength = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorSequenceLen >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_epochs_per_reset - pub type ValidatorEpochsPerReset = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorEpochsPerReset >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_exclude_quantile - pub type ValidatorExcludeQuantile = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorExcludeQuantile >; - #[pallet::storage] // --- MAP ( netuid ) --> validator_logits_divergence - pub type ValidatorLogitsDivergence = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorLogitsDivergence >; - #[pallet::storage] // --- MAP ( netuid ) --> scaling_law_power - pub type ScalingLawPower = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultScalingLawPower >; - #[pallet::storage] // --- MAP ( netuid ) --> synergy_scaling_law_power - pub type SynergyScalingLawPower = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultSynergyScalingLawPower >; - #[pallet::storage] // --- MAP ( netuid ) --> target_registrations_this_interval - pub type TargetRegistrationsPerInterval = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultTargetRegistrationsPerInterval >; - #[pallet::storage] // --- DMAP ( netuid, uid ) --> block_at_registration - pub type BlockAtRegistration = StorageDoubleMap<_, Identity, u16, Identity, u16, u64, ValueQuery, DefaultBlockAtRegistration >; - - // ======================================= - // ==== Subnetwork Consensus Storage ==== - // ======================================= - #[pallet::type_value] - pub fn EmptyU16Vec() -> Vec { vec![] } - #[pallet::type_value] - pub fn EmptyU64Vec() -> Vec { vec![] } - #[pallet::type_value] - pub fn EmptyBoolVec() -> Vec { vec![] } - #[pallet::type_value] - pub fn DefaultBonds() -> Vec<(u16, u16)> { vec![] } - #[pallet::type_value] - pub fn DefaultWeights() -> Vec<(u16, u16)> { vec![] } - #[pallet::type_value] - pub fn DefaultKey() -> T::AccountId { T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap() } - - #[pallet::storage] // --- DMAP ( netuid, hotkey ) --> uid - pub(super) type Uids = StorageDoubleMap<_, Identity, u16, Blake2_128Concat, T::AccountId, u16, OptionQuery>; - #[pallet::storage] // --- DMAP ( netuid, uid ) --> hotkey - pub(super) type Keys = StorageDoubleMap<_, Identity, u16, Identity, u16, T::AccountId, ValueQuery, DefaultKey >; - #[pallet::storage] // --- DMAP ( netuid ) --> (hotkey, se, ve) - pub(super) type LoadedEmission = StorageMap< _, Identity, u16, Vec<(T::AccountId, u64, u64)>, OptionQuery >; - - #[pallet::storage] // --- DMAP ( netuid ) --> active - pub(super) type Active = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyBoolVec >; - #[pallet::storage] // --- DMAP ( netuid ) --> rank - pub(super) type Rank = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> trust - pub(super) type Trust = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> consensus - pub(super) type Consensus = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> incentive - pub(super) type Incentive = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> dividends - pub(super) type Dividends = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> emission - pub(super) type Emission = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU64Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> last_update - pub(super) type LastUpdate = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU64Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> validator_trust - pub(super) type ValidatorTrust = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; - #[pallet::storage] // --- DMAP ( netuid ) --> pruning_scores - pub(super) type PruningScores = StorageMap< _, Identity, u16, Vec, ValueQuery, EmptyU16Vec >; - #[pallet::storage] // --- DMAP ( netuid ) --> validator_permit - pub(super) type ValidatorPermit = StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyBoolVec >; - - #[pallet::storage] // --- DMAP ( netuid, uid ) --> weights - pub(super) type Weights = StorageDoubleMap<_, Identity, u16, Identity, u16, Vec<(u16, u16)>, ValueQuery, DefaultWeights >; - #[pallet::storage] // --- DMAP ( netuid, uid ) --> bonds - pub(super) type Bonds = StorageDoubleMap<_, Identity, u16, Identity, u16, Vec<(u16, u16)>, ValueQuery, DefaultBonds >; - - // Pallets use events to inform users when important changes are made. - // https://docs.substrate.io/main-docs/build/events-errors/ - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - // Event documentation should end with an array that provides descriptive names for event - // parameters. [something, who] - NetworkAdded( u16, u16 ), // --- Event created when a new network is added. - NetworkRemoved( u16 ), // --- Event created when a network is removed. - StakeAdded( T::AccountId, u64 ), // --- Event created when stake has been transfered from the a coldkey account onto the hotkey staking account. - StakeRemoved( T::AccountId, u64 ), // --- Event created when stake has been removed from the hotkey staking account onto the coldkey account. - WeightsSet( u16, u16 ), // ---- Event created when a caller successfully sets their weights on a subnetwork. - NeuronRegistered( u16, u16, T::AccountId ), // --- Event created when a new neuron account has been registered to the chain. - BulkNeuronsRegistered( u16, u16 ), // --- Event created when multiple uids have been concurrently registered. - BulkBalancesSet(u16, u16), // --- FIXME: Not used yet - MaxAllowedUidsSet( u16, u16 ), // --- Event created when max allowed uids has been set for a subnetwork. - MaxWeightLimitSet( u16, u16 ), // --- Event created when the max weight limit has been set for a subnetwork. - DifficultySet( u16, u64 ), // --- Event created when the difficulty has been set for a subnet. - AdjustmentIntervalSet( u16, u16 ), // --- Event created when the adjustment interval is set for a subnet. - RegistrationPerIntervalSet( u16, u16 ), // --- Event created when registeration per interval is set for a subnet. - MaxRegistrationsPerBlockSet( u16, u16), // --- Event created when we set max registrations per block. - ActivityCutoffSet( u16, u16 ), // --- Event created when an activity cutoff is set for a subnet. - RhoSet( u16, u16 ), // --- Event created when Rho value is set. - KappaSet( u16, u16 ), // --- Event created when Kappa is set for a subnet. - MinAllowedWeightSet( u16, u16 ), // --- Event created when minimun allowed weight is set for a subnet. - ValidatorBatchSizeSet( u16, u16 ), // --- Event created when validator batch size is set for a subnet. - ValidatorSequenceLengthSet( u16, u16 ), // --- Event created when validator sequence length is set for a subnet. - ValidatorEpochPerResetSet( u16, u16 ), // --- Event created when validator epoch per reset is set for a subnet. - ValidatorExcludeQuantileSet( u16, u16 ), // --- Event created when the validator exclude quantile has been set for a subnet. - ValidatorEpochLengthSet( u16, u16 ), // --- Event created when the validator epoch length has been set for a subnet. - ValidatorLogitsDivergenceSet( u16, u16 ), // --- Event created when the validator logits divergence value has been set. - ValidatorPruneLenSet( u16, u64 ), // --- Event created when the validator pruning length has been set. - ScalingLawPowerSet( u16, u16 ), // --- Event created when the scaling law power has been set for a subnet. - SynergyScalingLawPowerSet( u16, u16 ), // --- Event created when the synergy scaling law has been set for a subnet. - WeightsSetRateLimitSet( u16, u64 ), // --- Event created when weights set rate limit has been set for a subnet. - ImmunityPeriodSet( u16, u16), // --- Event created when immunity period is set for a subnet. - BondsMovingAverageSet( u16, u64), // --- Event created when bonds moving average is set for a subnet. - MaxAllowedValidatorsSet( u16, u16), // --- Event created when setting the max number of allowed validators on a subnet. - AxonServed( u16, T::AccountId ), // --- Event created when the axon server information is added to the network. - PrometheusServed( u16, T::AccountId ), // --- Event created when the prometheus server information is added to the network. - EmissionValuesSet(), // --- Event created when emission ratios for all networks is set. - NetworkConnectionAdded( u16, u16, u16 ), // --- Event created when a network connection requirement is added. - NetworkConnectionRemoved( u16, u16 ), // --- Event created when a network connection requirement is removed. - DelegateAdded( T::AccountId, T::AccountId, u16 ), // --- Event created to signal that a hotkey has become a delegate. - DefaultTakeSet( u16 ), // --- Event created when the default take is set. - WeightsVersionKeySet( u16, u64 ), // --- Event created when weights version key is set for a network. - MinDifficultySet( u16, u64 ), // --- Event created when setting min difficutly on a network. - MaxDifficultySet( u16, u64 ), // --- Event created when setting max difficutly on a network. - ServingRateLimitSet( u16, u64 ), // --- Event created when setting the prometheus serving rate limit. - BurnSet( u16, u64 ), // --- Event created when setting burn on a network. - MaxBurnSet( u16, u64 ), // --- Event created when setting max burn on a network. - MinBurnSet( u16, u64 ), // --- Event created when setting min burn on a network. - TxRateLimitSet( u64 ), // --- Event created when setting the transaction rate limit. - Sudid ( DispatchResult ), // --- Event created when a sudo call is done. - RegistrationAllowed( u16, bool ), // --- Event created when registration is allowed/disallowed for a subnet. - TempoSet(u16, u16), // --- Event created when setting tempo on a network - RAORecycledForRegistrationSet( u16, u64 ), // Event created when setting the RAO recycled for registration. - SenateRequiredStakePercentSet( u64 ), // Event created when setting the minimum required stake amount for senate registration. - } - - // Errors inform users that something went wrong. - #[pallet::error] - pub enum Error { - InvalidConnectionRequirement, // --- Thrown if we are attempting to create an invalid connection requirement. - NetworkDoesNotExist, // --- Thrown when the network does not exist. - NetworkExist, // --- Thrown when the network already exists. - InvalidModality, // --- Thrown when an invalid modality attempted on serve. - InvalidIpType, // ---- Thrown when the user tries to serve an axon which is not of type 4 (IPv4) or 6 (IPv6). - InvalidIpAddress, // --- Thrown when an invalid IP address is passed to the serve function. - InvalidPort, // --- Thrown when an invalid port is passed to the serve function. - NotRegistered, // ---- Thrown when the caller requests setting or removing data from a neuron which does not exist in the active set. - NonAssociatedColdKey, // ---- Thrown when a stake, unstake or subscribe request is made by a coldkey which is not associated with the hotkey account. - NotEnoughStaketoWithdraw, // ---- Thrown when the caller requests removing more stake than there exists in the staking account. See: fn remove_stake. - NotEnoughBalanceToStake, // ---- Thrown when the caller requests adding more stake than there exists in the cold key account. See: fn add_stake - BalanceWithdrawalError, // ---- Thrown when the caller tries to add stake, but for some reason the requested amount could not be withdrawn from the coldkey account. - NoValidatorPermit, // ---- Thrown when the caller attempts to set non-self weights without being a permitted validator. - WeightVecNotEqualSize, // ---- Thrown when the caller attempts to set the weight keys and values but these vectors have different size. - DuplicateUids, // ---- Thrown when the caller attempts to set weights with duplicate uids in the weight matrix. - InvalidUid, // ---- Thrown when a caller attempts to set weight to at least one uid that does not exist in the metagraph. - NotSettingEnoughWeights, // ---- Thrown when the dispatch attempts to set weights on chain with fewer elements than are allowed. - TooManyRegistrationsThisBlock, // ---- Thrown when registrations this block exceeds allowed number. - AlreadyRegistered, // ---- Thrown when the caller requests registering a neuron which already exists in the active set. - InvalidWorkBlock, // ---- Thrown if the supplied pow hash block is in the future or negative. - InvalidDifficulty, // ---- Thrown if the supplied pow hash block does not meet the network difficulty. - InvalidSeal, // ---- Thrown if the supplied pow hash seal does not match the supplied work. - MaxAllowedUIdsNotAllowed, // --- Thrown if the vaule is invalid for MaxAllowedUids. - CouldNotConvertToBalance, // ---- Thrown when the dispatch attempts to convert between a u64 and T::balance but the call fails. - StakeAlreadyAdded, // --- Thrown when the caller requests adding stake for a hotkey to the total stake which already added. - MaxWeightExceeded, // --- Thrown when the dispatch attempts to set weights on chain with where any normalized weight is more than MaxWeightLimit. - StorageValueOutOfRange, // --- Thrown when the caller attempts to set a storage value outside of its allowed range. - TempoHasNotSet, // --- Thrown when tempo has not set. - InvalidTempo, // --- Thrown when tempo is not valid. - EmissionValuesDoesNotMatchNetworks, // --- Thrown when number or recieved emission rates does not match number of networks. - InvalidEmissionValues, // --- Thrown when emission ratios are not valid (did not sum up to 10^9). - DidNotPassConnectedNetworkRequirement, // --- Thrown when a hotkey attempts to register into a network without passing the registration requirment from another network. - AlreadyDelegate, // --- Thrown if the hotkey attempts to become delegate when they are already. - SettingWeightsTooFast, // --- Thrown if the hotkey attempts to set weights twice within net_tempo/2 blocks. - IncorrectNetworkVersionKey, // --- Thrown when a validator attempts to set weights from a validator with incorrect code base key. - ServingRateLimitExceeded, // --- Thrown when an axon or prometheus serving exceeds the rate limit for a registered neuron. - BalanceSetError, // --- Thrown when an error occurs while setting a balance. - MaxAllowedUidsExceeded, // --- Thrown when number of accounts going to be registered exceeds MaxAllowedUids for the network. - TooManyUids, // ---- Thrown when the caller attempts to set weights with more uids than allowed. - TxRateLimitExceeded, // --- Thrown when a transactor exceeds the rate limit for transactions. - RegistrationDisabled, // --- Thrown when registration is disabled - TooManyRegistrationsThisInterval, // --- Thrown when registration attempt exceeds allowed in interval - BenchmarkingOnly, // --- Thrown when a function is only available for benchmarking - HotkeyOriginMismatch, // --- Thrown when the hotkey passed is not the origin, but it should be - // Senate errors - SenateMember, // --- Thrown when attempting to do something to a senate member that is limited - NotSenateMember, // --- Thrown when a hotkey attempts to do something only senate members can do - AlreadySenateMember, // --- Thrown when a hotkey attempts to join the senate while already being a member - BelowStakeThreshold, // --- Thrown when a hotkey attempts to join the senate without enough stake - NotDelegate, // --- Thrown when a hotkey attempts to join the senate without being a delegate first - IncorrectNetuidsLength, // --- Thrown when an incorrect amount of Netuids are passed as input - } - - // ================== - // ==== Genesis ===== - // ================== - - #[pallet::genesis_config] - #[cfg(feature = "std")] - pub struct GenesisConfig { - pub stakes: Vec<(T::AccountId, Vec<(T::AccountId, (u64, u16))>)>, - pub balances_issuance: u64 - } - - #[cfg(feature = "std")] - impl Default for GenesisConfig { - fn default() -> Self { - Self { - stakes: Default::default(), - balances_issuance: 0 - } - } - } - - #[pallet::genesis_build] - impl GenesisBuild for GenesisConfig { - fn build(&self) { - // Set initial total issuance from balances - TotalIssuance::::put(self.balances_issuance); - - // Subnet config values - let netuid: u16 = 3; - let tempo = 99; - let max_uids = 4096; - - // The functions for initializing new networks/setting defaults cannot be run directly from genesis functions like extrinsics would - // --- Set this network uid to alive. - NetworksAdded::::insert(netuid, true); - - // --- Fill tempo memory item. - Tempo::::insert(netuid, tempo); - - // --- Fill modality item. - // Only modality 0 exists (text) - NetworkModality::::insert(netuid, 0); - - // Make network parameters explicit. - if !Tempo::::contains_key( netuid ) { Tempo::::insert( netuid, Tempo::::get( netuid ));} - if !Kappa::::contains_key( netuid ) { Kappa::::insert( netuid, Kappa::::get( netuid ));} - if !Difficulty::::contains_key( netuid ) { Difficulty::::insert( netuid, Difficulty::::get( netuid ));} - if !MaxAllowedUids::::contains_key( netuid ) { MaxAllowedUids::::insert( netuid, MaxAllowedUids::::get( netuid ));} - if !ImmunityPeriod::::contains_key( netuid ) { ImmunityPeriod::::insert( netuid, ImmunityPeriod::::get( netuid ));} - if !ActivityCutoff::::contains_key( netuid ) { ActivityCutoff::::insert( netuid, ActivityCutoff::::get( netuid ));} - if !EmissionValues::::contains_key( netuid ) { EmissionValues::::insert( netuid, EmissionValues::::get( netuid ));} - if !MaxWeightsLimit::::contains_key( netuid ) { MaxWeightsLimit::::insert( netuid, MaxWeightsLimit::::get( netuid ));} - if !ValidatorEpochLen::::contains_key( netuid ) { ValidatorEpochLen::::insert( netuid, ValidatorEpochLen::::get( netuid ));} - if !MinAllowedWeights::::contains_key( netuid ) { MinAllowedWeights::::insert( netuid, MinAllowedWeights::::get( netuid )); } - if !ValidatorBatchSize::::contains_key( netuid ) { ValidatorBatchSize::::insert( netuid, ValidatorBatchSize::::get( netuid ));} - if !ValidatorEpochsPerReset::::contains_key( netuid ) { ValidatorEpochsPerReset::::insert( netuid, ValidatorEpochsPerReset::::get( netuid ));} - if !ValidatorSequenceLength::::contains_key( netuid ) { ValidatorSequenceLength::::insert( netuid, ValidatorSequenceLength::::get( netuid ));} - if !RegistrationsThisInterval::::contains_key( netuid ) { RegistrationsThisInterval::::insert( netuid, RegistrationsThisInterval::::get( netuid ));} - if !POWRegistrationsThisInterval::::contains_key( netuid ) { POWRegistrationsThisInterval::::insert( netuid, POWRegistrationsThisInterval::::get( netuid ));} - if !BurnRegistrationsThisInterval::::contains_key( netuid ) { BurnRegistrationsThisInterval::::insert( netuid, BurnRegistrationsThisInterval::::get( netuid ));} - - // Set max allowed uids - MaxAllowedUids::::insert(netuid, max_uids); - - let mut next_uid = 0; - - for (coldkey, hotkeys) in self.stakes.iter() { - for (hotkey, stake_uid) in hotkeys.iter() { - let (stake, uid) = stake_uid; - - // Expand Yuma Consensus with new position. - Rank::::mutate(netuid, |v| v.push(0)); - Trust::::mutate(netuid, |v| v.push(0)); - Active::::mutate(netuid, |v| v.push(true)); - Emission::::mutate(netuid, |v| v.push(0)); - Consensus::::mutate(netuid, |v| v.push(0)); - Incentive::::mutate(netuid, |v| v.push(0)); - Dividends::::mutate(netuid, |v| v.push(0)); - LastUpdate::::mutate(netuid, |v| v.push(0)); - PruningScores::::mutate(netuid, |v| v.push(0)); - ValidatorTrust::::mutate(netuid, |v| v.push(0)); - ValidatorPermit::::mutate(netuid, |v| v.push(false)); - - // Insert account information. - Keys::::insert(netuid, uid, hotkey.clone()); // Make hotkey - uid association. - Uids::::insert(netuid, hotkey.clone(), uid); // Make uid - hotkey association. - BlockAtRegistration::::insert(netuid, uid, 0); // Fill block at registration. - IsNetworkMember::::insert(hotkey.clone(), netuid, true); // Fill network is member. - - // Fill stake information. - Owner::::insert(hotkey.clone(), coldkey.clone()); - - TotalHotkeyStake::::insert(hotkey.clone(), stake); - TotalColdkeyStake::::insert(coldkey.clone(), TotalColdkeyStake::::get(coldkey).saturating_add(*stake)); - - // Update total issuance value - TotalIssuance::::put(TotalIssuance::::get().saturating_add(*stake)); - - Stake::::insert(hotkey.clone(), coldkey.clone(), stake); - - next_uid += 1; - } - } - - // Set correct length for Subnet neurons - SubnetworkN::::insert(netuid, next_uid); - - // --- Increase total network count. - TotalNetworks::::mutate(|n| *n += 1); - } - } - - // ================ - // ==== Hooks ===== - // ================ - - #[pallet::hooks] - impl Hooks> for Pallet { - // ---- Called on the initialization of this pallet. (the order of on_finalize calls is determined in the runtime) - // - // # Args: - // * 'n': (T::BlockNumber): - // - The number of the block we are initializing. - fn on_initialize( _block_number: BlockNumberFor ) -> Weight { - Self::block_step(); - - return Weight::from_ref_time(110_634_229_000 as u64) - .saturating_add(T::DbWeight::get().reads(8304 as u64)) - .saturating_add(T::DbWeight::get().writes(110 as u64)); - } - - fn on_runtime_upgrade() -> frame_support::weights::Weight { - // --- Migrate to v2 - use crate::migration; - - migration::migrate_to_v2_separate_emission::() - } - } - - // Dispatchable functions allow users to interact with the pallet and invoke state changes. - // These functions materialize as "extrinsics", which are often compared to transactions. - // Dispatchable functions must be annotated with a weight and must return a DispatchResult. - #[pallet::call] - impl Pallet { - - // --- Sets the caller weights for the incentive mechanism. 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 - // rational values in the range [0,1] which sum to 1 and can be interpreted as - // probabilities. The specific weights determine how inflation propagates outward - // from this peer. - // - // Note: The 16 bit integers weights should represent 1.0 as the max u16. - // However, the function normalizes all integers to u16_max anyway. This means that if the sum of all - // elements is larger or smaller than the amount of elements * u16_max, all elements - // will be corrected for this deviation. - // - // # Args: - // * `origin`: (Origin): - // - The caller, a hotkey who wishes to set their weights. - // - // * `netuid` (u16): - // - The network uid we are setting these weights on. - // - // * `dests` (Vec): - // - The edge endpoint for the weight, i.e. j for w_ij. - // - // * 'weights' (Vec): - // - The u16 integer encoded weights. Interpreted as rational - // values in the range [0,1]. They must sum to in32::MAX. - // - // * 'version_key' ( u64 ): - // - The network version key to check if the validator is up to date. - // - // # Event: - // * WeightsSet; - // - On successfully setting the weights on chain. - // - // # Raises: - // * 'NetworkDoesNotExist': - // - Attempting to set weights on a non-existent network. - // - // * 'NotRegistered': - // - Attempting to set weights from a non registered account. - // - // * 'WeightVecNotEqualSize': - // - Attempting to set weights with uids not of same length. - // - // * 'DuplicateUids': - // - Attempting to set weights with duplicate uids. - // - // * 'TooManyUids': - // - Attempting to set weights above the max allowed uids. - // - // * 'InvalidUid': - // - Attempting to set weights with invalid uids. - // - // * 'NotSettingEnoughWeights': - // - Attempting to set weights with fewer weights than min. - // - // * 'MaxWeightExceeded': - // - Attempting to set weights with max value exceeding limit. - #[pallet::call_index(0)] + pub ip: u128, // --- Prometheus u128 encoded ip address of type v6 or v4. + pub port: u16, // --- Prometheus u16 encoded port. + pub ip_type: u8, // --- Prometheus ip type, 4 for ipv4 and 6 for ipv6. + } + + // Rate limiting + #[pallet::type_value] + pub fn DefaultTxRateLimit() -> u64 { + T::InitialTxRateLimit::get() + } + #[pallet::type_value] + pub fn DefaultLastTxBlock() -> u64 { + 0 + } + + #[pallet::storage] // --- ITEM ( tx_rate_limit ) + pub(super) type TxRateLimit = StorageValue<_, u64, ValueQuery, DefaultTxRateLimit>; + #[pallet::storage] // --- MAP ( key ) --> last_block + pub(super) type LastTxBlock = + StorageMap<_, Identity, T::AccountId, u64, ValueQuery, DefaultLastTxBlock>; + + #[pallet::type_value] + pub fn DefaultServingRateLimit() -> u64 { + T::InitialServingRateLimit::get() + } + + #[pallet::storage] // --- MAP ( netuid ) --> serving_rate_limit + pub type ServingRateLimit = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultServingRateLimit>; + #[pallet::storage] // --- MAP ( netuid, hotkey ) --> axon_info + pub(super) type Axons = + StorageDoubleMap<_, Identity, u16, Blake2_128Concat, T::AccountId, AxonInfoOf, OptionQuery>; + #[pallet::storage] // --- MAP ( netuid, hotkey ) --> prometheus_info + pub(super) type Prometheus = StorageDoubleMap< + _, + Identity, + u16, + Blake2_128Concat, + T::AccountId, + PrometheusInfoOf, + OptionQuery, + >; + + // ======================================= + // ==== Subnetwork Hyperparam storage ==== + // ======================================= + #[pallet::type_value] + pub fn DefaultWeightsSetRateLimit() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultBlockAtRegistration() -> u64 { + 0 + } + #[pallet::type_value] + pub fn DefaultRho() -> u16 { + T::InitialRho::get() + } + #[pallet::type_value] + pub fn DefaultKappa() -> u16 { + T::InitialKappa::get() + } + #[pallet::type_value] + pub fn DefaultMaxAllowedUids() -> u16 { + T::InitialMaxAllowedUids::get() + } + #[pallet::type_value] + pub fn DefaultImmunityPeriod() -> u16 { + T::InitialImmunityPeriod::get() + } + #[pallet::type_value] + pub fn DefaultActivityCutoff() -> u16 { + T::InitialActivityCutoff::get() + } + #[pallet::type_value] + pub fn DefaultMaxWeightsLimit() -> u16 { + T::InitialMaxWeightsLimit::get() + } + #[pallet::type_value] + pub fn DefaultWeightsVersionKey() -> u64 { + T::InitialWeightsVersionKey::get() + } + #[pallet::type_value] + pub fn DefaultMinAllowedWeights() -> u16 { + T::InitialMinAllowedWeights::get() + } + #[pallet::type_value] + pub fn DefaultValidatorEpochLen() -> u16 { + T::InitialValidatorEpochLen::get() + } + #[pallet::type_value] + pub fn DefaultMaxAllowedValidators() -> u16 { + T::InitialMaxAllowedValidators::get() + } + #[pallet::type_value] + pub fn DefaultAdjustmentInterval() -> u16 { + T::InitialAdjustmentInterval::get() + } + #[pallet::type_value] + pub fn DefaultBondsMovingAverage() -> u64 { + T::InitialBondsMovingAverage::get() + } + #[pallet::type_value] + pub fn DefaultValidatorPruneLen() -> u64 { + T::InitialValidatorPruneLen::get() + } + #[pallet::type_value] + pub fn DefaultValidatorBatchSize() -> u16 { + T::InitialValidatorBatchSize::get() + } + #[pallet::type_value] + pub fn DefaultValidatorSequenceLen() -> u16 { + T::InitialValidatorSequenceLen::get() + } + #[pallet::type_value] + pub fn DefaultValidatorEpochsPerReset() -> u16 { + T::InitialValidatorEpochsPerReset::get() + } + #[pallet::type_value] + pub fn DefaultValidatorExcludeQuantile() -> u16 { + T::InitialValidatorExcludeQuantile::get() + } + #[pallet::type_value] + pub fn DefaultValidatorLogitsDivergence() -> u16 { + T::InitialValidatorLogitsDivergence::get() + } + #[pallet::type_value] + pub fn DefaultScalingLawPower() -> u16 { + T::InitialScalingLawPower::get() + } + #[pallet::type_value] + pub fn DefaultSynergyScalingLawPower() -> u16 { + T::InitialSynergyScalingLawPower::get() + } + #[pallet::type_value] + pub fn DefaultTargetRegistrationsPerInterval() -> u16 { + T::InitialTargetRegistrationsPerInterval::get() + } + #[pallet::type_value] + pub fn DefaultAdjustmentAlpha() -> u64 { + T::InitialAdjustmentAlpha::get() + } + + #[pallet::storage] // --- MAP ( netuid ) --> Rho + pub type Rho = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultRho>; + #[pallet::storage] // --- MAP ( netuid ) --> Kappa + pub type Kappa = StorageMap<_, Identity, u16, u16, ValueQuery, DefaultKappa>; + #[pallet::storage] // --- MAP ( netuid ) --> uid, we use to record uids to prune at next epoch. + pub type NeuronsToPruneAtNextEpoch = StorageMap<_, Identity, u16, u16, ValueQuery>; + #[pallet::storage] // --- MAP ( netuid ) --> registrations_this_interval + pub type RegistrationsThisInterval = StorageMap<_, Identity, u16, u16, ValueQuery>; + #[pallet::storage] // --- MAP ( netuid ) --> pow_registrations_this_interval + pub type POWRegistrationsThisInterval = + StorageMap<_, Identity, u16, u16, ValueQuery>; + #[pallet::storage] // --- MAP ( netuid ) --> burn_registrations_this_interval + pub type BurnRegistrationsThisInterval = + StorageMap<_, Identity, u16, u16, ValueQuery>; + #[pallet::storage] // --- MAP ( netuid ) --> max_allowed_uids + pub type MaxAllowedUids = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxAllowedUids>; + #[pallet::storage] // --- MAP ( netuid ) --> immunity_period + pub type ImmunityPeriod = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultImmunityPeriod>; + #[pallet::storage] // --- MAP ( netuid ) --> activity_cutoff + pub type ActivityCutoff = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultActivityCutoff>; + #[pallet::storage] // --- MAP ( netuid ) --> max_weight_limit + pub type MaxWeightsLimit = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxWeightsLimit>; + #[pallet::storage] // --- MAP ( netuid ) --> weights_version_key + pub type WeightsVersionKey = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultWeightsVersionKey>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_epoch_len + pub type ValidatorEpochLen = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorEpochLen>; + #[pallet::storage] // --- MAP ( netuid ) --> min_allowed_weights + pub type MinAllowedWeights = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMinAllowedWeights>; + #[pallet::storage] // --- MAP ( netuid ) --> max_allowed_validators + pub type MaxAllowedValidators = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultMaxAllowedValidators>; + #[pallet::storage] // --- MAP ( netuid ) --> adjustment_interval + pub type AdjustmentInterval = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultAdjustmentInterval>; + #[pallet::storage] // --- MAP ( netuid ) --> bonds_moving_average + pub type BondsMovingAverage = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultBondsMovingAverage>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_batch_size + pub type ValidatorBatchSize = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorBatchSize>; + #[pallet::storage] // --- MAP ( netuid ) --> weights_set_rate_limit + pub type WeightsSetRateLimit = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultWeightsSetRateLimit>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_prune_len + pub type ValidatorPruneLen = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultValidatorPruneLen>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_sequence_length + pub type ValidatorSequenceLength = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorSequenceLen>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_epochs_per_reset + pub type ValidatorEpochsPerReset = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorEpochsPerReset>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_exclude_quantile + pub type ValidatorExcludeQuantile = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorExcludeQuantile>; + #[pallet::storage] // --- MAP ( netuid ) --> validator_logits_divergence + pub type ValidatorLogitsDivergence = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultValidatorLogitsDivergence>; + #[pallet::storage] // --- MAP ( netuid ) --> scaling_law_power + pub type ScalingLawPower = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultScalingLawPower>; + #[pallet::storage] // --- MAP ( netuid ) --> synergy_scaling_law_power + pub type SynergyScalingLawPower = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultSynergyScalingLawPower>; + #[pallet::storage] // --- MAP ( netuid ) --> target_registrations_this_interval + pub type TargetRegistrationsPerInterval = + StorageMap<_, Identity, u16, u16, ValueQuery, DefaultTargetRegistrationsPerInterval>; + #[pallet::storage] // --- DMAP ( netuid, uid ) --> block_at_registration + pub type BlockAtRegistration = StorageDoubleMap< + _, + Identity, + u16, + Identity, + u16, + u64, + ValueQuery, + DefaultBlockAtRegistration, + >; + #[pallet::storage] // --- DMAP ( netuid ) --> adjustment_alpha + pub type AdjustmentAlpha = + StorageMap<_, Identity, u16, u64, ValueQuery, DefaultAdjustmentAlpha>; + + // ======================================= + // ==== Subnetwork Consensus Storage ==== + // ======================================= + #[pallet::type_value] + pub fn EmptyU16Vec() -> Vec { + vec![] + } + #[pallet::type_value] + pub fn EmptyU64Vec() -> Vec { + vec![] + } + #[pallet::type_value] + pub fn EmptyBoolVec() -> Vec { + vec![] + } + #[pallet::type_value] + pub fn DefaultBonds() -> Vec<(u16, u16)> { + vec![] + } + #[pallet::type_value] + pub fn DefaultWeights() -> Vec<(u16, u16)> { + vec![] + } + #[pallet::type_value] + pub fn DefaultKey() -> T::AccountId { + T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap() + } + + #[pallet::storage] // --- DMAP ( netuid, hotkey ) --> uid + pub(super) type Uids = + StorageDoubleMap<_, Identity, u16, Blake2_128Concat, T::AccountId, u16, OptionQuery>; + #[pallet::storage] // --- DMAP ( netuid, uid ) --> hotkey + pub(super) type Keys = + StorageDoubleMap<_, Identity, u16, Identity, u16, T::AccountId, ValueQuery, DefaultKey>; + #[pallet::storage] // --- DMAP ( netuid ) --> (hotkey, se, ve) + pub(super) type LoadedEmission = + StorageMap<_, Identity, u16, Vec<(T::AccountId, u64, u64)>, OptionQuery>; + + #[pallet::storage] // --- DMAP ( netuid ) --> active + pub(super) type Active = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyBoolVec>; + #[pallet::storage] // --- DMAP ( netuid ) --> rank + pub(super) type Rank = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> trust + pub(super) type Trust = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> consensus + pub(super) type Consensus = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> incentive + pub(super) type Incentive = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> dividends + pub(super) type Dividends = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> emission + pub(super) type Emission = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU64Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> last_update + pub(super) type LastUpdate = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU64Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> validator_trust + pub(super) type ValidatorTrust = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> pruning_scores + pub(super) type PruningScores = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyU16Vec>; + #[pallet::storage] // --- DMAP ( netuid ) --> validator_permit + pub(super) type ValidatorPermit = + StorageMap<_, Identity, u16, Vec, ValueQuery, EmptyBoolVec>; + + #[pallet::storage] // --- DMAP ( netuid, uid ) --> weights + pub(super) type Weights = StorageDoubleMap< + _, + Identity, + u16, + Identity, + u16, + Vec<(u16, u16)>, + ValueQuery, + DefaultWeights, + >; + #[pallet::storage] // --- DMAP ( netuid, uid ) --> bonds + pub(super) type Bonds = StorageDoubleMap< + _, + Identity, + u16, + Identity, + u16, + Vec<(u16, u16)>, + ValueQuery, + DefaultBonds, + >; + + // Pallets use events to inform users when important changes are made. + // https://docs.substrate.io/main-docs/build/events-errors/ + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event { + // Event documentation should end with an array that provides descriptive names for event + // parameters. [something, who] + NetworkAdded(u16, u16), // --- Event created when a new network is added. + NetworkRemoved(u16), // --- Event created when a network is removed. + StakeAdded(T::AccountId, u64), // --- Event created when stake has been transfered from the a coldkey account onto the hotkey staking account. + StakeRemoved(T::AccountId, u64), // --- Event created when stake has been removed from the hotkey staking account onto the coldkey account. + WeightsSet(u16, u16), // ---- Event created when a caller successfully sets their weights on a subnetwork. + NeuronRegistered(u16, u16, T::AccountId), // --- Event created when a new neuron account has been registered to the chain. + BulkNeuronsRegistered(u16, u16), // --- Event created when multiple uids have been concurrently registered. + BulkBalancesSet(u16, u16), // --- FIXME: Not used yet + MaxAllowedUidsSet(u16, u16), // --- Event created when max allowed uids has been set for a subnetwork. + MaxWeightLimitSet(u16, u16), // --- Event created when the max weight limit has been set for a subnetwork. + DifficultySet(u16, u64), // --- Event created when the difficulty has been set for a subnet. + AdjustmentIntervalSet(u16, u16), // --- Event created when the adjustment interval is set for a subnet. + RegistrationPerIntervalSet(u16, u16), // --- Event created when registeration per interval is set for a subnet. + MaxRegistrationsPerBlockSet(u16, u16), // --- Event created when we set max registrations per block. + ActivityCutoffSet(u16, u16), // --- Event created when an activity cutoff is set for a subnet. + RhoSet(u16, u16), // --- Event created when Rho value is set. + KappaSet(u16, u16), // --- Event created when Kappa is set for a subnet. + MinAllowedWeightSet(u16, u16), // --- Event created when minimun allowed weight is set for a subnet. + ValidatorBatchSizeSet(u16, u16), // --- Event created when validator batch size is set for a subnet. + ValidatorSequenceLengthSet(u16, u16), // --- Event created when validator sequence length is set for a subnet. + ValidatorEpochPerResetSet(u16, u16), // --- Event created when validator epoch per reset is set for a subnet. + ValidatorExcludeQuantileSet(u16, u16), // --- Event created when the validator exclude quantile has been set for a subnet. + ValidatorEpochLengthSet(u16, u16), // --- Event created when the validator epoch length has been set for a subnet. + ValidatorLogitsDivergenceSet(u16, u16), // --- Event created when the validator logits divergence value has been set. + ValidatorPruneLenSet(u16, u64), // --- Event created when the validator pruning length has been set. + ScalingLawPowerSet(u16, u16), // --- Event created when the scaling law power has been set for a subnet. + SynergyScalingLawPowerSet(u16, u16), // --- Event created when the synergy scaling law has been set for a subnet. + WeightsSetRateLimitSet(u16, u64), // --- Event created when weights set rate limit has been set for a subnet. + ImmunityPeriodSet(u16, u16), // --- Event created when immunity period is set for a subnet. + BondsMovingAverageSet(u16, u64), // --- Event created when bonds moving average is set for a subnet. + MaxAllowedValidatorsSet(u16, u16), // --- Event created when setting the max number of allowed validators on a subnet. + AxonServed(u16, T::AccountId), // --- Event created when the axon server information is added to the network. + PrometheusServed(u16, T::AccountId), // --- Event created when the prometheus server information is added to the network. + EmissionValuesSet(), // --- Event created when emission ratios for all networks is set. + NetworkConnectionAdded(u16, u16, u16), // --- Event created when a network connection requirement is added. + NetworkConnectionRemoved(u16, u16), // --- Event created when a network connection requirement is removed. + DelegateAdded(T::AccountId, T::AccountId, u16), // --- Event created to signal that a hotkey has become a delegate. + DefaultTakeSet(u16), // --- Event created when the default take is set. + WeightsVersionKeySet(u16, u64), // --- Event created when weights version key is set for a network. + MinDifficultySet(u16, u64), // --- Event created when setting min difficutly on a network. + MaxDifficultySet(u16, u64), // --- Event created when setting max difficutly on a network. + ServingRateLimitSet(u16, u64), // --- Event created when setting the prometheus serving rate limit. + BurnSet(u16, u64), // --- Event created when setting burn on a network. + MaxBurnSet(u16, u64), // --- Event created when setting max burn on a network. + MinBurnSet(u16, u64), // --- Event created when setting min burn on a network. + TxRateLimitSet(u64), // --- Event created when setting the transaction rate limit. + Sudid(DispatchResult), // --- Event created when a sudo call is done. + RegistrationAllowed(u16, bool), // --- Event created when registration is allowed/disallowed for a subnet. + TempoSet(u16, u16), // --- Event created when setting tempo on a network + RAORecycledForRegistrationSet(u16, u64), // Event created when setting the RAO recycled for registration. + SenateRequiredStakePercentSet(u64), // Event created when setting the minimum required stake amount for senate registration. + AdjustmentAlphaSet(u16, u64), // Event created when setting the adjustment alpha on a subnet. + } + + // Errors inform users that something went wrong. + #[pallet::error] + pub enum Error { + InvalidConnectionRequirement, // --- Thrown if we are attempting to create an invalid connection requirement. + NetworkDoesNotExist, // --- Thrown when the network does not exist. + NetworkExist, // --- Thrown when the network already exists. + InvalidModality, // --- Thrown when an invalid modality attempted on serve. + InvalidIpType, // ---- Thrown when the user tries to serve an axon which is not of type 4 (IPv4) or 6 (IPv6). + InvalidIpAddress, // --- Thrown when an invalid IP address is passed to the serve function. + InvalidPort, // --- Thrown when an invalid port is passed to the serve function. + NotRegistered, // ---- Thrown when the caller requests setting or removing data from a neuron which does not exist in the active set. + NonAssociatedColdKey, // ---- Thrown when a stake, unstake or subscribe request is made by a coldkey which is not associated with the hotkey account. + NotEnoughStaketoWithdraw, // ---- Thrown when the caller requests removing more stake than there exists in the staking account. See: fn remove_stake. + NotEnoughBalanceToStake, // ---- Thrown when the caller requests adding more stake than there exists in the cold key account. See: fn add_stake + BalanceWithdrawalError, // ---- Thrown when the caller tries to add stake, but for some reason the requested amount could not be withdrawn from the coldkey account. + NoValidatorPermit, // ---- Thrown when the caller attempts to set non-self weights without being a permitted validator. + WeightVecNotEqualSize, // ---- Thrown when the caller attempts to set the weight keys and values but these vectors have different size. + DuplicateUids, // ---- Thrown when the caller attempts to set weights with duplicate uids in the weight matrix. + InvalidUid, // ---- Thrown when a caller attempts to set weight to at least one uid that does not exist in the metagraph. + NotSettingEnoughWeights, // ---- Thrown when the dispatch attempts to set weights on chain with fewer elements than are allowed. + TooManyRegistrationsThisBlock, // ---- Thrown when registrations this block exceeds allowed number. + AlreadyRegistered, // ---- Thrown when the caller requests registering a neuron which already exists in the active set. + InvalidWorkBlock, // ---- Thrown if the supplied pow hash block is in the future or negative. + InvalidDifficulty, // ---- Thrown if the supplied pow hash block does not meet the network difficulty. + InvalidSeal, // ---- Thrown if the supplied pow hash seal does not match the supplied work. + MaxAllowedUIdsNotAllowed, // --- Thrown if the vaule is invalid for MaxAllowedUids. + CouldNotConvertToBalance, // ---- Thrown when the dispatch attempts to convert between a u64 and T::balance but the call fails. + StakeAlreadyAdded, // --- Thrown when the caller requests adding stake for a hotkey to the total stake which already added. + MaxWeightExceeded, // --- Thrown when the dispatch attempts to set weights on chain with where any normalized weight is more than MaxWeightLimit. + StorageValueOutOfRange, // --- Thrown when the caller attempts to set a storage value outside of its allowed range. + TempoHasNotSet, // --- Thrown when tempo has not set. + InvalidTempo, // --- Thrown when tempo is not valid. + EmissionValuesDoesNotMatchNetworks, // --- Thrown when number or recieved emission rates does not match number of networks. + InvalidEmissionValues, // --- Thrown when emission ratios are not valid (did not sum up to 10^9). + DidNotPassConnectedNetworkRequirement, // --- Thrown when a hotkey attempts to register into a network without passing the registration requirment from another network. + AlreadyDelegate, // --- Thrown if the hotkey attempts to become delegate when they are already. + SettingWeightsTooFast, // --- Thrown if the hotkey attempts to set weights twice within net_tempo/2 blocks. + IncorrectNetworkVersionKey, // --- Thrown when a validator attempts to set weights from a validator with incorrect code base key. + ServingRateLimitExceeded, // --- Thrown when an axon or prometheus serving exceeds the rate limit for a registered neuron. + BalanceSetError, // --- Thrown when an error occurs while setting a balance. + MaxAllowedUidsExceeded, // --- Thrown when number of accounts going to be registered exceeds MaxAllowedUids for the network. + TooManyUids, // ---- Thrown when the caller attempts to set weights with more uids than allowed. + TxRateLimitExceeded, // --- Thrown when a transactor exceeds the rate limit for transactions. + RegistrationDisabled, // --- Thrown when registration is disabled + TooManyRegistrationsThisInterval, // --- Thrown when registration attempt exceeds allowed in interval + BenchmarkingOnly, // --- Thrown when a function is only available for benchmarking + HotkeyOriginMismatch, // --- Thrown when the hotkey passed is not the origin, but it should be + // Senate errors + SenateMember, // --- Thrown when attempting to do something to a senate member that is limited + NotSenateMember, // --- Thrown when a hotkey attempts to do something only senate members can do + AlreadySenateMember, // --- Thrown when a hotkey attempts to join the senate while already being a member + BelowStakeThreshold, // --- Thrown when a hotkey attempts to join the senate without enough stake + NotDelegate, // --- Thrown when a hotkey attempts to join the senate without being a delegate first + IncorrectNetuidsLength, // --- Thrown when an incorrect amount of Netuids are passed as input + } + + // ================== + // ==== Genesis ===== + // ================== + + #[pallet::genesis_config] + #[cfg(feature = "std")] + pub struct GenesisConfig { + pub stakes: Vec<(T::AccountId, Vec<(T::AccountId, (u64, u16))>)>, + pub balances_issuance: u64, + } + + #[cfg(feature = "std")] + impl Default for GenesisConfig { + fn default() -> Self { + Self { + stakes: Default::default(), + balances_issuance: 0, + } + } + } + + #[pallet::genesis_build] + impl GenesisBuild for GenesisConfig { + fn build(&self) { + // Set initial total issuance from balances + TotalIssuance::::put(self.balances_issuance); + + // Subnet config values + let netuid: u16 = 3; + let tempo = 99; + let max_uids = 4096; + + // The functions for initializing new networks/setting defaults cannot be run directly from genesis functions like extrinsics would + // --- Set this network uid to alive. + NetworksAdded::::insert(netuid, true); + + // --- Fill tempo memory item. + Tempo::::insert(netuid, tempo); + + // --- Fill modality item. + // Only modality 0 exists (text) + NetworkModality::::insert(netuid, 0); + + // Make network parameters explicit. + if !Tempo::::contains_key(netuid) { + Tempo::::insert(netuid, Tempo::::get(netuid)); + } + if !Kappa::::contains_key(netuid) { + Kappa::::insert(netuid, Kappa::::get(netuid)); + } + if !Difficulty::::contains_key(netuid) { + Difficulty::::insert(netuid, Difficulty::::get(netuid)); + } + if !MaxAllowedUids::::contains_key(netuid) { + MaxAllowedUids::::insert(netuid, MaxAllowedUids::::get(netuid)); + } + if !ImmunityPeriod::::contains_key(netuid) { + ImmunityPeriod::::insert(netuid, ImmunityPeriod::::get(netuid)); + } + if !ActivityCutoff::::contains_key(netuid) { + ActivityCutoff::::insert(netuid, ActivityCutoff::::get(netuid)); + } + if !EmissionValues::::contains_key(netuid) { + EmissionValues::::insert(netuid, EmissionValues::::get(netuid)); + } + if !MaxWeightsLimit::::contains_key(netuid) { + MaxWeightsLimit::::insert(netuid, MaxWeightsLimit::::get(netuid)); + } + if !ValidatorEpochLen::::contains_key(netuid) { + ValidatorEpochLen::::insert(netuid, ValidatorEpochLen::::get(netuid)); + } + if !MinAllowedWeights::::contains_key(netuid) { + MinAllowedWeights::::insert(netuid, MinAllowedWeights::::get(netuid)); + } + if !ValidatorBatchSize::::contains_key(netuid) { + ValidatorBatchSize::::insert(netuid, ValidatorBatchSize::::get(netuid)); + } + if !ValidatorEpochsPerReset::::contains_key(netuid) { + ValidatorEpochsPerReset::::insert( + netuid, + ValidatorEpochsPerReset::::get(netuid), + ); + } + if !ValidatorSequenceLength::::contains_key(netuid) { + ValidatorSequenceLength::::insert( + netuid, + ValidatorSequenceLength::::get(netuid), + ); + } + if !RegistrationsThisInterval::::contains_key(netuid) { + RegistrationsThisInterval::::insert( + netuid, + RegistrationsThisInterval::::get(netuid), + ); + } + if !POWRegistrationsThisInterval::::contains_key(netuid) { + POWRegistrationsThisInterval::::insert( + netuid, + POWRegistrationsThisInterval::::get(netuid), + ); + } + if !BurnRegistrationsThisInterval::::contains_key(netuid) { + BurnRegistrationsThisInterval::::insert( + netuid, + BurnRegistrationsThisInterval::::get(netuid), + ); + } + + // Set max allowed uids + MaxAllowedUids::::insert(netuid, max_uids); + + let mut next_uid = 0; + + for (coldkey, hotkeys) in self.stakes.iter() { + for (hotkey, stake_uid) in hotkeys.iter() { + let (stake, uid) = stake_uid; + + // Expand Yuma Consensus with new position. + Rank::::mutate(netuid, |v| v.push(0)); + Trust::::mutate(netuid, |v| v.push(0)); + Active::::mutate(netuid, |v| v.push(true)); + Emission::::mutate(netuid, |v| v.push(0)); + Consensus::::mutate(netuid, |v| v.push(0)); + Incentive::::mutate(netuid, |v| v.push(0)); + Dividends::::mutate(netuid, |v| v.push(0)); + LastUpdate::::mutate(netuid, |v| v.push(0)); + PruningScores::::mutate(netuid, |v| v.push(0)); + ValidatorTrust::::mutate(netuid, |v| v.push(0)); + ValidatorPermit::::mutate(netuid, |v| v.push(false)); + + // Insert account information. + Keys::::insert(netuid, uid, hotkey.clone()); // Make hotkey - uid association. + Uids::::insert(netuid, hotkey.clone(), uid); // Make uid - hotkey association. + BlockAtRegistration::::insert(netuid, uid, 0); // Fill block at registration. + IsNetworkMember::::insert(hotkey.clone(), netuid, true); // Fill network is member. + + // Fill stake information. + Owner::::insert(hotkey.clone(), coldkey.clone()); + + TotalHotkeyStake::::insert(hotkey.clone(), stake); + TotalColdkeyStake::::insert( + coldkey.clone(), + TotalColdkeyStake::::get(coldkey).saturating_add(*stake), + ); + + // Update total issuance value + TotalIssuance::::put(TotalIssuance::::get().saturating_add(*stake)); + + Stake::::insert(hotkey.clone(), coldkey.clone(), stake); + + next_uid += 1; + } + } + + // Set correct length for Subnet neurons + SubnetworkN::::insert(netuid, next_uid); + + // --- Increase total network count. + TotalNetworks::::mutate(|n| *n += 1); + } + } + + // ================ + // ==== Hooks ===== + // ================ + + #[pallet::hooks] + impl Hooks> for Pallet { + // ---- Called on the initialization of this pallet. (the order of on_finalize calls is determined in the runtime) + // + // # Args: + // * 'n': (T::BlockNumber): + // - The number of the block we are initializing. + fn on_initialize(_block_number: BlockNumberFor) -> Weight { + Self::block_step(); + + return Weight::from_ref_time(110_634_229_000 as u64) + .saturating_add(T::DbWeight::get().reads(8304 as u64)) + .saturating_add(T::DbWeight::get().writes(110 as u64)); + } + + fn on_runtime_upgrade() -> frame_support::weights::Weight { + // --- Migrate to v2 + use crate::migration; + + migration::migrate_to_v2_separate_emission::() + } + } + + // Dispatchable functions allow users to interact with the pallet and invoke state changes. + // These functions materialize as "extrinsics", which are often compared to transactions. + // Dispatchable functions must be annotated with a weight and must return a DispatchResult. + #[pallet::call] + impl Pallet { + // --- Sets the caller weights for the incentive mechanism. 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 + // rational values in the range [0,1] which sum to 1 and can be interpreted as + // probabilities. The specific weights determine how inflation propagates outward + // from this peer. + // + // Note: The 16 bit integers weights should represent 1.0 as the max u16. + // However, the function normalizes all integers to u16_max anyway. This means that if the sum of all + // elements is larger or smaller than the amount of elements * u16_max, all elements + // will be corrected for this deviation. + // + // # Args: + // * `origin`: (Origin): + // - The caller, a hotkey who wishes to set their weights. + // + // * `netuid` (u16): + // - The network uid we are setting these weights on. + // + // * `dests` (Vec): + // - The edge endpoint for the weight, i.e. j for w_ij. + // + // * 'weights' (Vec): + // - The u16 integer encoded weights. Interpreted as rational + // values in the range [0,1]. They must sum to in32::MAX. + // + // * 'version_key' ( u64 ): + // - The network version key to check if the validator is up to date. + // + // # Event: + // * WeightsSet; + // - On successfully setting the weights on chain. + // + // # Raises: + // * 'NetworkDoesNotExist': + // - Attempting to set weights on a non-existent network. + // + // * 'NotRegistered': + // - Attempting to set weights from a non registered account. + // + // * 'WeightVecNotEqualSize': + // - Attempting to set weights with uids not of same length. + // + // * 'DuplicateUids': + // - Attempting to set weights with duplicate uids. + // + // * 'TooManyUids': + // - Attempting to set weights above the max allowed uids. + // + // * 'InvalidUid': + // - Attempting to set weights with invalid uids. + // + // * 'NotSettingEnoughWeights': + // - Attempting to set weights with fewer weights than min. + // + // * 'MaxWeightExceeded': + // - Attempting to set weights with max value exceeding limit. + #[pallet::call_index(0)] #[pallet::weight((Weight::from_ref_time(10_151_000_000) .saturating_add(T::DbWeight::get().reads(4104)) .saturating_add(T::DbWeight::get().writes(2)), DispatchClass::Normal, Pays::No))] - pub fn set_weights( - origin:OriginFor, - netuid: u16, - dests: Vec, - weights: Vec, - version_key: u64 - ) -> DispatchResult { - Self::do_set_weights( origin, netuid, dests, weights, version_key ) - } - - // --- Sets the key as a delegate. - // - // # Args: - // * 'origin': (Origin): - // - The signature of the caller's coldkey. - // - // * 'hotkey' (T::AccountId): - // - The hotkey we are delegating (must be owned by the coldkey.) - // - // * 'take' (u64): - // - The stake proportion that this hotkey takes from delegations. - // - // # Event: - // * DelegateAdded; - // - On successfully setting a hotkey as a delegate. - // - // # Raises: - // * 'NotRegistered': - // - The hotkey we are delegating is not registered on the network. - // - // * 'NonAssociatedColdKey': - // - The hotkey we are delegating is not owned by the calling coldket. - // - // - #[pallet::call_index(1)] - #[pallet::weight((0, DispatchClass::Normal, Pays::No))] - pub fn become_delegate( - origin: OriginFor, - hotkey: T::AccountId - ) -> DispatchResult { - Self::do_become_delegate(origin, hotkey, Self::get_default_take() ) - } - - // --- Adds stake to a hotkey. The call is made from the - // coldkey account linked in the hotkey. - // Only the associated coldkey is allowed to make staking and - // unstaking requests. This protects the neuron against - // attacks on its hotkey running in production code. - // - // # Args: - // * 'origin': (Origin): - // - The signature of the caller's coldkey. - // - // * 'hotkey' (T::AccountId): - // - The associated hotkey account. - // - // * 'amount_staked' (u64): - // - The amount of stake to be added to the hotkey staking account. - // - // # Event: - // * StakeAdded; - // - On the successfully adding stake to a global account. - // - // # Raises: - // * 'CouldNotConvertToBalance': - // - Unable to convert the passed stake value to a balance. - // - // * 'NotEnoughBalanceToStake': - // - Not enough balance on the coldkey to add onto the global account. - // - // * 'NonAssociatedColdKey': - // - The calling coldkey is not associated with this hotkey. - // - // * 'BalanceWithdrawalError': - // - Errors stemming from transaction pallet. - // - // - #[pallet::call_index(2)] - #[pallet::weight((Weight::from_ref_time(65_000_000) + pub fn set_weights( + origin: OriginFor, + netuid: u16, + dests: Vec, + weights: Vec, + version_key: u64, + ) -> DispatchResult { + Self::do_set_weights(origin, netuid, dests, weights, version_key) + } + + // --- Sets the key as a delegate. + // + // # Args: + // * 'origin': (Origin): + // - The signature of the caller's coldkey. + // + // * 'hotkey' (T::AccountId): + // - The hotkey we are delegating (must be owned by the coldkey.) + // + // * 'take' (u64): + // - The stake proportion that this hotkey takes from delegations. + // + // # Event: + // * DelegateAdded; + // - On successfully setting a hotkey as a delegate. + // + // # Raises: + // * 'NotRegistered': + // - The hotkey we are delegating is not registered on the network. + // + // * 'NonAssociatedColdKey': + // - The hotkey we are delegating is not owned by the calling coldket. + // + // + #[pallet::call_index(1)] + #[pallet::weight((0, DispatchClass::Normal, Pays::No))] + pub fn become_delegate(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { + Self::do_become_delegate(origin, hotkey, Self::get_default_take()) + } + + // --- Adds stake to a hotkey. The call is made from the + // coldkey account linked in the hotkey. + // Only the associated coldkey is allowed to make staking and + // unstaking requests. This protects the neuron against + // attacks on its hotkey running in production code. + // + // # Args: + // * 'origin': (Origin): + // - The signature of the caller's coldkey. + // + // * 'hotkey' (T::AccountId): + // - The associated hotkey account. + // + // * 'amount_staked' (u64): + // - The amount of stake to be added to the hotkey staking account. + // + // # Event: + // * StakeAdded; + // - On the successfully adding stake to a global account. + // + // # Raises: + // * 'CouldNotConvertToBalance': + // - Unable to convert the passed stake value to a balance. + // + // * 'NotEnoughBalanceToStake': + // - Not enough balance on the coldkey to add onto the global account. + // + // * 'NonAssociatedColdKey': + // - The calling coldkey is not associated with this hotkey. + // + // * 'BalanceWithdrawalError': + // - Errors stemming from transaction pallet. + // + // + #[pallet::call_index(2)] + #[pallet::weight((Weight::from_ref_time(65_000_000) .saturating_add(T::DbWeight::get().reads(8)) .saturating_add(T::DbWeight::get().writes(6)), DispatchClass::Normal, Pays::No))] - pub fn add_stake( - origin: OriginFor, - hotkey: T::AccountId, - amount_staked: u64 - ) -> DispatchResult { - Self::do_add_stake(origin, hotkey, amount_staked) - } - - // ---- Remove stake from the staking account. The call must be made - // from the coldkey account attached to the neuron metadata. Only this key - // has permission to make staking and unstaking requests. - // - // # Args: - // * 'origin': (Origin): - // - The signature of the caller's coldkey. - // - // * 'hotkey' (T::AccountId): - // - The associated hotkey account. - // - // * 'amount_unstaked' (u64): - // - The amount of stake to be added to the hotkey staking account. - // - // # Event: - // * StakeRemoved; - // - On the successfully removing stake from the hotkey account. - // - // # Raises: - // * 'NotRegistered': - // - Thrown if the account we are attempting to unstake from is non existent. - // - // * 'NonAssociatedColdKey': - // - Thrown if the coldkey does not own the hotkey we are unstaking from. - // - // * 'NotEnoughStaketoWithdraw': - // - Thrown if there is not enough stake on the hotkey to withdwraw this amount. - // - // * 'CouldNotConvertToBalance': - // - Thrown if we could not convert this amount to a balance. - // - // - #[pallet::call_index(3)] - #[pallet::weight((Weight::from_ref_time(63_000_000) + pub fn add_stake( + origin: OriginFor, + hotkey: T::AccountId, + amount_staked: u64, + ) -> DispatchResult { + Self::do_add_stake(origin, hotkey, amount_staked) + } + + // ---- Remove stake from the staking account. The call must be made + // from the coldkey account attached to the neuron metadata. Only this key + // has permission to make staking and unstaking requests. + // + // # Args: + // * 'origin': (Origin): + // - The signature of the caller's coldkey. + // + // * 'hotkey' (T::AccountId): + // - The associated hotkey account. + // + // * 'amount_unstaked' (u64): + // - The amount of stake to be added to the hotkey staking account. + // + // # Event: + // * StakeRemoved; + // - On the successfully removing stake from the hotkey account. + // + // # Raises: + // * 'NotRegistered': + // - Thrown if the account we are attempting to unstake from is non existent. + // + // * 'NonAssociatedColdKey': + // - Thrown if the coldkey does not own the hotkey we are unstaking from. + // + // * 'NotEnoughStaketoWithdraw': + // - Thrown if there is not enough stake on the hotkey to withdwraw this amount. + // + // * 'CouldNotConvertToBalance': + // - Thrown if we could not convert this amount to a balance. + // + // + #[pallet::call_index(3)] + #[pallet::weight((Weight::from_ref_time(63_000_000) .saturating_add(Weight::from_proof_size(43991)) .saturating_add(T::DbWeight::get().reads(14)) .saturating_add(T::DbWeight::get().writes(9)), DispatchClass::Normal, Pays::No))] - pub fn remove_stake( - origin: OriginFor, - hotkey: T::AccountId, - amount_unstaked: u64 - ) -> DispatchResult { - Self::do_remove_stake(origin, hotkey, amount_unstaked) - } - - // ---- Serves or updates axon /promethteus information for the neuron associated with the caller. If the caller is - // already registered the metadata is updated. If the caller is not registered this call throws NotRegistered. - // - // # Args: - // * 'origin': (Origin): - // - The signature of the caller. - // - // * 'netuid' (u16): - // - The u16 network identifier. - // - // * 'version' (u64): - // - The bittensor version identifier. - // - // * 'ip' (u64): - // - The endpoint ip information as a u128 encoded integer. - // - // * 'port' (u16): - // - The endpoint port information as a u16 encoded integer. - // - // * 'ip_type' (u8): - // - The endpoint ip version as a u8, 4 or 6. - // - // * 'protocol' (u8): - // - UDP:1 or TCP:0 - // - // * 'placeholder1' (u8): - // - Placeholder for further extra params. - // - // * 'placeholder2' (u8): - // - Placeholder for further extra params. - // - // # Event: - // * AxonServed; - // - On successfully serving the axon info. - // - // # Raises: - // * 'NetworkDoesNotExist': - // - Attempting to set weights on a non-existent network. - // - // * 'NotRegistered': - // - Attempting to set weights from a non registered account. - // - // * 'InvalidIpType': - // - The ip type is not 4 or 6. - // - // * 'InvalidIpAddress': - // - The numerically encoded ip address does not resolve to a proper ip. - // - // * 'ServingRateLimitExceeded': - // - Attempting to set prometheus information withing the rate limit min. - // - #[pallet::call_index(4)] - #[pallet::weight((Weight::from_ref_time(19_000_000) + pub fn remove_stake( + origin: OriginFor, + hotkey: T::AccountId, + amount_unstaked: u64, + ) -> DispatchResult { + Self::do_remove_stake(origin, hotkey, amount_unstaked) + } + + // ---- Serves or updates axon /promethteus information for the neuron associated with the caller. If the caller is + // already registered the metadata is updated. If the caller is not registered this call throws NotRegistered. + // + // # Args: + // * 'origin': (Origin): + // - The signature of the caller. + // + // * 'netuid' (u16): + // - The u16 network identifier. + // + // * 'version' (u64): + // - The bittensor version identifier. + // + // * 'ip' (u64): + // - The endpoint ip information as a u128 encoded integer. + // + // * 'port' (u16): + // - The endpoint port information as a u16 encoded integer. + // + // * 'ip_type' (u8): + // - The endpoint ip version as a u8, 4 or 6. + // + // * 'protocol' (u8): + // - UDP:1 or TCP:0 + // + // * 'placeholder1' (u8): + // - Placeholder for further extra params. + // + // * 'placeholder2' (u8): + // - Placeholder for further extra params. + // + // # Event: + // * AxonServed; + // - On successfully serving the axon info. + // + // # Raises: + // * 'NetworkDoesNotExist': + // - Attempting to set weights on a non-existent network. + // + // * 'NotRegistered': + // - Attempting to set weights from a non registered account. + // + // * 'InvalidIpType': + // - The ip type is not 4 or 6. + // + // * 'InvalidIpAddress': + // - The numerically encoded ip address does not resolve to a proper ip. + // + // * 'ServingRateLimitExceeded': + // - Attempting to set prometheus information withing the rate limit min. + // + #[pallet::call_index(4)] + #[pallet::weight((Weight::from_ref_time(19_000_000) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::No))] - pub fn serve_axon( - origin:OriginFor, - netuid: u16, - version: u32, - ip: u128, - port: u16, - ip_type: u8, - protocol: u8, - placeholder1: u8, - placeholder2: u8, - ) -> DispatchResult { - Self::do_serve_axon( origin, netuid, version, ip, port, ip_type, protocol, placeholder1, placeholder2 ) - } - - #[pallet::call_index(5)] - #[pallet::weight((Weight::from_ref_time(17_000_000) + pub fn serve_axon( + origin: OriginFor, + netuid: u16, + version: u32, + ip: u128, + port: u16, + ip_type: u8, + protocol: u8, + placeholder1: u8, + placeholder2: u8, + ) -> DispatchResult { + Self::do_serve_axon( + origin, + netuid, + version, + ip, + port, + ip_type, + protocol, + placeholder1, + placeholder2, + ) + } + + #[pallet::call_index(5)] + #[pallet::weight((Weight::from_ref_time(17_000_000) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Normal, Pays::No))] - pub fn serve_prometheus( - origin:OriginFor, - netuid: u16, - version: u32, - ip: u128, - port: u16, - ip_type: u8, - ) -> DispatchResult { - Self::do_serve_prometheus( origin, netuid, version, ip, port, ip_type ) - } - - - // ---- Registers a new neuron to the subnetwork. - // - // # Args: - // * 'origin': (Origin): - // - The signature of the calling hotkey. - // - // * 'netuid' (u16): - // - The u16 network identifier. - // - // * 'block_number' ( u64 ): - // - Block hash used to prove work done. - // - // * 'nonce' ( u64 ): - // - Positive integer nonce used in POW. - // - // * 'work' ( Vec ): - // - Vector encoded bytes representing work done. - // - // * 'hotkey' ( T::AccountId ): - // - Hotkey to be registered to the network. - // - // * 'coldkey' ( T::AccountId ): - // - Associated coldkey account. - // - // # Event: - // * NeuronRegistered; - // - On successfully registereing a uid to a neuron slot on a subnetwork. - // - // # Raises: - // * 'NetworkDoesNotExist': - // - Attempting to registed to a non existent network. - // - // * 'TooManyRegistrationsThisBlock': - // - This registration exceeds the total allowed on this network this block. - // - // * 'AlreadyRegistered': - // - The hotkey is already registered on this network. - // - // * 'InvalidWorkBlock': - // - The work has been performed on a stale, future, or non existent block. - // - // * 'InvalidDifficulty': - // - The work does not match the difficutly. - // - // * 'InvalidSeal': - // - The seal is incorrect. - // - #[pallet::call_index(6)] - #[pallet::weight((Weight::from_ref_time(91_000_000) + pub fn serve_prometheus( + origin: OriginFor, + netuid: u16, + version: u32, + ip: u128, + port: u16, + ip_type: u8, + ) -> DispatchResult { + Self::do_serve_prometheus(origin, netuid, version, ip, port, ip_type) + } + + // ---- Registers a new neuron to the subnetwork. + // + // # Args: + // * 'origin': (Origin): + // - The signature of the calling hotkey. + // + // * 'netuid' (u16): + // - The u16 network identifier. + // + // * 'block_number' ( u64 ): + // - Block hash used to prove work done. + // + // * 'nonce' ( u64 ): + // - Positive integer nonce used in POW. + // + // * 'work' ( Vec ): + // - Vector encoded bytes representing work done. + // + // * 'hotkey' ( T::AccountId ): + // - Hotkey to be registered to the network. + // + // * 'coldkey' ( T::AccountId ): + // - Associated coldkey account. + // + // # Event: + // * NeuronRegistered; + // - On successfully registereing a uid to a neuron slot on a subnetwork. + // + // # Raises: + // * 'NetworkDoesNotExist': + // - Attempting to registed to a non existent network. + // + // * 'TooManyRegistrationsThisBlock': + // - This registration exceeds the total allowed on this network this block. + // + // * 'AlreadyRegistered': + // - The hotkey is already registered on this network. + // + // * 'InvalidWorkBlock': + // - The work has been performed on a stale, future, or non existent block. + // + // * 'InvalidDifficulty': + // - The work does not match the difficutly. + // + // * 'InvalidSeal': + // - The seal is incorrect. + // + #[pallet::call_index(6)] + #[pallet::weight((Weight::from_ref_time(91_000_000) .saturating_add(T::DbWeight::get().reads(27)) .saturating_add(T::DbWeight::get().writes(22)), DispatchClass::Normal, Pays::No))] - pub fn register( - origin:OriginFor, - netuid: u16, - block_number: u64, - nonce: u64, - work: Vec, - hotkey: T::AccountId, - coldkey: T::AccountId, - ) -> DispatchResult { - Self::do_registration(origin, netuid, block_number, nonce, work, hotkey, coldkey) - } - - #[pallet::call_index(7)] - #[pallet::weight((Weight::from_ref_time(89_000_000) + pub fn register( + origin: OriginFor, + netuid: u16, + block_number: u64, + nonce: u64, + work: Vec, + hotkey: T::AccountId, + coldkey: T::AccountId, + ) -> DispatchResult { + Self::do_registration(origin, netuid, block_number, nonce, work, hotkey, coldkey) + } + + #[pallet::call_index(7)] + #[pallet::weight((Weight::from_ref_time(89_000_000) .saturating_add(T::DbWeight::get().reads(27)) .saturating_add(T::DbWeight::get().writes(22)), DispatchClass::Normal, Pays::No))] - pub fn burned_register( - origin:OriginFor, - netuid: u16, - hotkey: T::AccountId, - ) -> DispatchResult { - Self::do_burned_registration(origin, netuid, hotkey) - } - - #[pallet::call_index(8)] - #[pallet::weight((Weight::from_ref_time(81_000_000) + pub fn burned_register( + origin: OriginFor, + netuid: u16, + hotkey: T::AccountId, + ) -> DispatchResult { + Self::do_burned_registration(origin, netuid, hotkey) + } + + #[pallet::call_index(8)] + #[pallet::weight((Weight::from_ref_time(81_000_000) .saturating_add(T::DbWeight::get().reads(21)) .saturating_add(T::DbWeight::get().writes(23)), DispatchClass::Operational, Pays::No))] - pub fn sudo_register( - origin:OriginFor, - netuid: u16, - hotkey: T::AccountId, - coldkey: T::AccountId, - stake: u64, - balance: u64, - ) -> DispatchResult { - Self::do_sudo_registration(origin, netuid, hotkey, coldkey, stake, balance) - } - - // ---- SUDO ONLY FUNCTIONS ------------------------------------------------------------ - - // ---- Sudo add a network to the network set. - // # Args: - // * 'origin': (Origin): - // - Must be sudo. - // - // * 'netuid' (u16): - // - The u16 network identifier. - // - // * 'tempo' ( u16 ): - // - Number of blocks between epoch step. - // - // * 'modality' ( u16 ): - // - Network modality specifier. - // - // # Event: - // * NetworkAdded; - // - On successfully creation of a network. - // - // # Raises: - // * 'NetworkExist': - // - Attempting to register an already existing. - // - // * 'InvalidModality': - // - Attempting to register a network with an invalid modality. - // - // * 'InvalidTempo': - // - Attempting to register a network with an invalid tempo. - // - #[pallet::call_index(9)] - #[pallet::weight((Weight::from_ref_time(50_000_000) + pub fn sudo_register( + origin: OriginFor, + netuid: u16, + hotkey: T::AccountId, + coldkey: T::AccountId, + stake: u64, + balance: u64, + ) -> DispatchResult { + Self::do_sudo_registration(origin, netuid, hotkey, coldkey, stake, balance) + } + + // ---- SUDO ONLY FUNCTIONS ------------------------------------------------------------ + + // ---- Sudo add a network to the network set. + // # Args: + // * 'origin': (Origin): + // - Must be sudo. + // + // * 'netuid' (u16): + // - The u16 network identifier. + // + // * 'tempo' ( u16 ): + // - Number of blocks between epoch step. + // + // * 'modality' ( u16 ): + // - Network modality specifier. + // + // # Event: + // * NetworkAdded; + // - On successfully creation of a network. + // + // # Raises: + // * 'NetworkExist': + // - Attempting to register an already existing. + // + // * 'InvalidModality': + // - Attempting to register a network with an invalid modality. + // + // * 'InvalidTempo': + // - Attempting to register a network with an invalid tempo. + // + #[pallet::call_index(9)] + #[pallet::weight((Weight::from_ref_time(50_000_000) .saturating_add(T::DbWeight::get().reads(17)) .saturating_add(T::DbWeight::get().writes(20)), DispatchClass::Operational, Pays::No))] - pub fn sudo_add_network( - origin: OriginFor, - netuid: u16, - tempo: u16, - modality: u16 - ) -> DispatchResultWithPostInfo { - Self::do_add_network(origin, netuid, tempo, modality) - } - - // ---- Sudo remove a network from the network set. - // # Args: - // * 'origin': (Origin): - // - Must be sudo. - // - // * 'netuid' (u16): - // - The u16 network identifier. - // - // # Event: - // * NetworkRemoved; - // - On the successfull removing of this network. - // - // # Raises: - // * 'NetworkDoesNotExist': - // - Attempting to remove a non existent network. - // - #[pallet::call_index(10)] - #[pallet::weight((Weight::from_ref_time(42_000_000) + pub fn sudo_add_network( + origin: OriginFor, + netuid: u16, + tempo: u16, + modality: u16, + ) -> DispatchResultWithPostInfo { + Self::do_add_network(origin, netuid, tempo, modality) + } + + // ---- Sudo remove a network from the network set. + // # Args: + // * 'origin': (Origin): + // - Must be sudo. + // + // * 'netuid' (u16): + // - The u16 network identifier. + // + // # Event: + // * NetworkRemoved; + // - On the successfull removing of this network. + // + // # Raises: + // * 'NetworkDoesNotExist': + // - Attempting to remove a non existent network. + // + #[pallet::call_index(10)] + #[pallet::weight((Weight::from_ref_time(42_000_000) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(31)), DispatchClass::Operational, Pays::No))] - pub fn sudo_remove_network( - origin: OriginFor, - netuid: u16 - ) -> DispatchResult { - Self::do_remove_network(origin, netuid) - } - - // ---- Sudo set emission values for all networks. - // Args: - // * 'origin': (Origin): - // - The caller, must be sudo. - // - // * `netuids` (Vec): - // - A vector of network uids values. This must include all netuids. - // - // * `emission` (Vec): - // - The emission values associated with passed netuids in order. - // - #[pallet::call_index(11)] - #[pallet::weight((Weight::from_ref_time(28_000_000) + pub fn sudo_remove_network(origin: OriginFor, netuid: u16) -> DispatchResult { + Self::do_remove_network(origin, netuid) + } + + // ---- Sudo set emission values for all networks. + // Args: + // * 'origin': (Origin): + // - The caller, must be sudo. + // + // * `netuids` (Vec): + // - A vector of network uids values. This must include all netuids. + // + // * `emission` (Vec): + // - The emission values associated with passed netuids in order. + // + #[pallet::call_index(11)] + #[pallet::weight((Weight::from_ref_time(28_000_000) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().writes(10)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_emission_values( - origin: OriginFor, - netuids: Vec, - emission: Vec, - ) -> DispatchResult { - Self::do_set_emission_values( - origin, - netuids, - emission - ) - } - - // ---- Sudo add a network connect requirement. - // Args: - // * 'origin': (Origin): - // - The caller, must be sudo. - // - // * `netuid_a` (u16): - // - The network we are adding the requirment to (parent network) - // - // * `netuid_b` (u16): - // - The network we the requirement refers to (child network) - // - // * `requirement` (u16): - // - The topk percentile prunning score requirement (u16:MAX normalized.) - // - #[pallet::call_index(12)] - #[pallet::weight((Weight::from_ref_time(17_000_000) + pub fn sudo_set_emission_values( + origin: OriginFor, + netuids: Vec, + emission: Vec, + ) -> DispatchResult { + Self::do_set_emission_values(origin, netuids, emission) + } + + // ---- Sudo add a network connect requirement. + // Args: + // * 'origin': (Origin): + // - The caller, must be sudo. + // + // * `netuid_a` (u16): + // - The network we are adding the requirment to (parent network) + // + // * `netuid_b` (u16): + // - The network we the requirement refers to (child network) + // + // * `requirement` (u16): + // - The topk percentile prunning score requirement (u16:MAX normalized.) + // + #[pallet::call_index(12)] + #[pallet::weight((Weight::from_ref_time(17_000_000) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_add_network_connection_requirement( origin:OriginFor, netuid_a: u16, netuid_b: u16, requirement: u16 ) -> DispatchResult { - Self::do_sudo_add_network_connection_requirement( origin, netuid_a, netuid_b, requirement ) - } - - // ---- Sudo remove a network connection requirement. - // Args: - // * 'origin': (Origin): - // - The caller, must be sudo. - // - // * `netuid_a` (u16): - // - The network we are removing the requirment from. - // - // * `netuid_b` (u16): - // - The required network connection to remove. - // - #[pallet::call_index(13)] - #[pallet::weight((Weight::from_ref_time(15_000_000) + pub fn sudo_add_network_connection_requirement( + origin: OriginFor, + netuid_a: u16, + netuid_b: u16, + requirement: u16, + ) -> DispatchResult { + Self::do_sudo_add_network_connection_requirement( + origin, + netuid_a, + netuid_b, + requirement, + ) + } + + // ---- Sudo remove a network connection requirement. + // Args: + // * 'origin': (Origin): + // - The caller, must be sudo. + // + // * `netuid_a` (u16): + // - The network we are removing the requirment from. + // + // * `netuid_b` (u16): + // - The required network connection to remove. + // + #[pallet::call_index(13)] + #[pallet::weight((Weight::from_ref_time(15_000_000) .saturating_add(T::DbWeight::get().reads(3)), DispatchClass::Operational, Pays::No))] - pub fn sudo_remove_network_connection_requirement( origin:OriginFor, netuid_a: u16, netuid_b: u16 ) -> DispatchResult { - Self::do_sudo_remove_network_connection_requirement( origin, netuid_a, netuid_b ) - } - - // ================================== - // ==== Parameter Sudo calls ======== - // ================================== - // Each function sets the corresponding hyper paramter on the specified network - // Args: - // * 'origin': (Origin): - // - The caller, must be sudo. - // - // * `netuid` (u16): - // - The network identifier. - // - // * `hyperparameter value` (u16): - // - The value of the hyper parameter. - // - #[pallet::call_index(14)] - #[pallet::weight((Weight::from_ref_time(11_000_000) + pub fn sudo_remove_network_connection_requirement( + origin: OriginFor, + netuid_a: u16, + netuid_b: u16, + ) -> DispatchResult { + Self::do_sudo_remove_network_connection_requirement(origin, netuid_a, netuid_b) + } + + // ================================== + // ==== Parameter Sudo calls ======== + // ================================== + // Each function sets the corresponding hyper paramter on the specified network + // Args: + // * 'origin': (Origin): + // - The caller, must be sudo. + // + // * `netuid` (u16): + // - The network identifier. + // + // * `hyperparameter value` (u16): + // - The value of the hyper parameter. + // + #[pallet::call_index(14)] + #[pallet::weight((Weight::from_ref_time(11_000_000) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_default_take( origin:OriginFor, default_take: u16 ) -> DispatchResult { - Self::do_sudo_set_default_take( origin, default_take ) - } + pub fn sudo_set_default_take(origin: OriginFor, default_take: u16) -> DispatchResult { + Self::do_sudo_set_default_take(origin, default_take) + } - #[pallet::call_index(15)] - #[pallet::weight((Weight::from_ref_time(10_000_000) + #[pallet::call_index(15)] + #[pallet::weight((Weight::from_ref_time(10_000_000) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_serving_rate_limit( origin:OriginFor, netuid: u16, serving_rate_limit: u64 ) -> DispatchResult { - Self::do_sudo_set_serving_rate_limit( origin, netuid, serving_rate_limit ) - } - - // Sudo call for setting tx rate limit - #[pallet::call_index(16)] - #[pallet::weight((0, DispatchClass::Operational, Pays::No))] - pub fn sudo_set_tx_rate_limit( origin:OriginFor, tx_rate_limit: u64 ) -> DispatchResult { - Self::do_sudo_set_tx_rate_limit( origin, tx_rate_limit ) - } - - #[pallet::call_index(17)] - #[pallet::weight((0, DispatchClass::Operational, Pays::No))] - pub fn sudo_set_max_burn( origin:OriginFor, netuid: u16, max_burn: u64 ) -> DispatchResult { - Self::do_sudo_set_max_burn( origin, netuid, max_burn ) - } - - #[pallet::call_index(18)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + pub fn sudo_set_serving_rate_limit( + origin: OriginFor, + netuid: u16, + serving_rate_limit: u64, + ) -> DispatchResult { + Self::do_sudo_set_serving_rate_limit(origin, netuid, serving_rate_limit) + } + + // Sudo call for setting tx rate limit + #[pallet::call_index(16)] + #[pallet::weight((0, DispatchClass::Operational, Pays::No))] + pub fn sudo_set_tx_rate_limit(origin: OriginFor, tx_rate_limit: u64) -> DispatchResult { + Self::do_sudo_set_tx_rate_limit(origin, tx_rate_limit) + } + + #[pallet::call_index(17)] + #[pallet::weight((0, DispatchClass::Operational, Pays::No))] + pub fn sudo_set_max_burn( + origin: OriginFor, + netuid: u16, + max_burn: u64, + ) -> DispatchResult { + Self::do_sudo_set_max_burn(origin, netuid, max_burn) + } + + #[pallet::call_index(18)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_min_burn( origin:OriginFor, netuid: u16, min_burn: u64 ) -> DispatchResult { - Self::do_sudo_set_min_burn( origin, netuid, min_burn ) - } + pub fn sudo_set_min_burn( + origin: OriginFor, + netuid: u16, + min_burn: u64, + ) -> DispatchResult { + Self::do_sudo_set_min_burn(origin, netuid, min_burn) + } - #[pallet::call_index(19)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(19)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_burn( origin:OriginFor, netuid: u16, burn: u64 ) -> DispatchResult { - Self::do_sudo_set_burn( origin, netuid, burn ) - } + pub fn sudo_set_burn(origin: OriginFor, netuid: u16, burn: u64) -> DispatchResult { + Self::do_sudo_set_burn(origin, netuid, burn) + } - #[pallet::call_index(20)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(20)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_max_difficulty( origin:OriginFor, netuid: u16, max_difficulty: u64 ) -> DispatchResult { - Self::do_sudo_set_max_difficulty( origin, netuid, max_difficulty ) - } + pub fn sudo_set_max_difficulty( + origin: OriginFor, + netuid: u16, + max_difficulty: u64, + ) -> DispatchResult { + Self::do_sudo_set_max_difficulty(origin, netuid, max_difficulty) + } - #[pallet::call_index(21)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(21)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_min_difficulty( origin:OriginFor, netuid: u16, min_difficulty: u64 ) -> DispatchResult { - Self::do_sudo_set_min_difficulty( origin, netuid, min_difficulty ) - } + pub fn sudo_set_min_difficulty( + origin: OriginFor, + netuid: u16, + min_difficulty: u64, + ) -> DispatchResult { + Self::do_sudo_set_min_difficulty(origin, netuid, min_difficulty) + } - #[pallet::call_index(22)] - #[pallet::weight((Weight::from_ref_time(15_000_000) + #[pallet::call_index(22)] + #[pallet::weight((Weight::from_ref_time(15_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_weights_set_rate_limit( origin:OriginFor, netuid: u16, weights_set_rate_limit: u64 ) -> DispatchResult { - Self::do_sudo_set_weights_set_rate_limit( origin, netuid, weights_set_rate_limit ) - } + pub fn sudo_set_weights_set_rate_limit( + origin: OriginFor, + netuid: u16, + weights_set_rate_limit: u64, + ) -> DispatchResult { + Self::do_sudo_set_weights_set_rate_limit(origin, netuid, weights_set_rate_limit) + } - #[pallet::call_index(23)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(23)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_weights_version_key( origin:OriginFor, netuid: u16, weights_version_key: u64 ) -> DispatchResult { - Self::do_sudo_set_weights_version_key( origin, netuid, weights_version_key ) - } + pub fn sudo_set_weights_version_key( + origin: OriginFor, + netuid: u16, + weights_version_key: u64, + ) -> DispatchResult { + Self::do_sudo_set_weights_version_key(origin, netuid, weights_version_key) + } - #[pallet::call_index(24)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(24)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_bonds_moving_average( origin:OriginFor, netuid: u16, bonds_moving_average: u64 ) -> DispatchResult { - Self::do_sudo_set_bonds_moving_average( origin, netuid, bonds_moving_average ) - } + pub fn sudo_set_bonds_moving_average( + origin: OriginFor, + netuid: u16, + bonds_moving_average: u64, + ) -> DispatchResult { + Self::do_sudo_set_bonds_moving_average(origin, netuid, bonds_moving_average) + } - #[pallet::call_index(25)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(25)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_max_allowed_validators( origin:OriginFor, netuid: u16, max_allowed_validators: u16 ) -> DispatchResult { - Self::do_sudo_set_max_allowed_validators( origin, netuid, max_allowed_validators ) - } + pub fn sudo_set_max_allowed_validators( + origin: OriginFor, + netuid: u16, + max_allowed_validators: u16, + ) -> DispatchResult { + Self::do_sudo_set_max_allowed_validators(origin, netuid, max_allowed_validators) + } - #[pallet::call_index(26)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(26)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_difficulty( origin:OriginFor, netuid: u16, difficulty: u64 ) -> DispatchResult { - Self::do_sudo_set_difficulty( origin, netuid, difficulty ) - } + pub fn sudo_set_difficulty( + origin: OriginFor, + netuid: u16, + difficulty: u64, + ) -> DispatchResult { + Self::do_sudo_set_difficulty(origin, netuid, difficulty) + } - #[pallet::call_index(27)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(27)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_adjustment_interval( origin:OriginFor, netuid: u16, adjustment_interval: u16 ) -> DispatchResult { - Self::do_sudo_set_adjustment_interval( origin, netuid, adjustment_interval ) - } + pub fn sudo_set_adjustment_interval( + origin: OriginFor, + netuid: u16, + adjustment_interval: u16, + ) -> DispatchResult { + Self::do_sudo_set_adjustment_interval(origin, netuid, adjustment_interval) + } - #[pallet::call_index(28)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(28)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_target_registrations_per_interval( origin:OriginFor, netuid: u16, target_registrations_per_interval: u16 ) -> DispatchResult { - Self::do_sudo_set_target_registrations_per_interval( origin, netuid, target_registrations_per_interval ) - } + pub fn sudo_set_target_registrations_per_interval( + origin: OriginFor, + netuid: u16, + target_registrations_per_interval: u16, + ) -> DispatchResult { + Self::do_sudo_set_target_registrations_per_interval( + origin, + netuid, + target_registrations_per_interval, + ) + } - #[pallet::call_index(29)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(29)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_activity_cutoff( origin:OriginFor, netuid: u16, activity_cutoff: u16 ) -> DispatchResult { - Self::do_sudo_set_activity_cutoff( origin, netuid, activity_cutoff ) - } + pub fn sudo_set_activity_cutoff( + origin: OriginFor, + netuid: u16, + activity_cutoff: u16, + ) -> DispatchResult { + Self::do_sudo_set_activity_cutoff(origin, netuid, activity_cutoff) + } - #[pallet::call_index(30)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(30)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_rho( origin:OriginFor, netuid: u16, rho: u16 ) -> DispatchResult { - Self::do_sudo_set_rho( origin, netuid, rho ) - } + pub fn sudo_set_rho(origin: OriginFor, netuid: u16, rho: u16) -> DispatchResult { + Self::do_sudo_set_rho(origin, netuid, rho) + } - #[pallet::call_index(31)] - #[pallet::weight(( Weight::from_ref_time(14_000_000) + #[pallet::call_index(31)] + #[pallet::weight(( Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_kappa( origin:OriginFor, netuid: u16, kappa: u16 ) -> DispatchResult { - Self::do_sudo_set_kappa( origin, netuid, kappa ) - } + pub fn sudo_set_kappa(origin: OriginFor, netuid: u16, kappa: u16) -> DispatchResult { + Self::do_sudo_set_kappa(origin, netuid, kappa) + } - #[pallet::call_index(32)] - #[pallet::weight((Weight::from_ref_time(18_000_000) + #[pallet::call_index(32)] + #[pallet::weight((Weight::from_ref_time(18_000_000) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_max_allowed_uids( origin:OriginFor, netuid: u16, max_allowed_uids: u16 ) -> DispatchResult { - Self::do_sudo_set_max_allowed_uids(origin, netuid, max_allowed_uids ) - } + pub fn sudo_set_max_allowed_uids( + origin: OriginFor, + netuid: u16, + max_allowed_uids: u16, + ) -> DispatchResult { + Self::do_sudo_set_max_allowed_uids(origin, netuid, max_allowed_uids) + } - #[pallet::call_index(33)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(33)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_min_allowed_weights( origin:OriginFor, netuid: u16, min_allowed_weights: u16 ) -> DispatchResult { - Self::do_sudo_set_min_allowed_weights( origin, netuid, min_allowed_weights ) - } + pub fn sudo_set_min_allowed_weights( + origin: OriginFor, + netuid: u16, + min_allowed_weights: u16, + ) -> DispatchResult { + Self::do_sudo_set_min_allowed_weights(origin, netuid, min_allowed_weights) + } - #[pallet::call_index(34)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(34)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_batch_size( origin:OriginFor, netuid: u16, validator_batch_size: u16 ) -> DispatchResult { - Self::do_sudo_set_validator_batch_size( origin, netuid, validator_batch_size ) - } + pub fn sudo_set_validator_batch_size( + origin: OriginFor, + netuid: u16, + validator_batch_size: u16, + ) -> DispatchResult { + Self::do_sudo_set_validator_batch_size(origin, netuid, validator_batch_size) + } - #[pallet::call_index(35)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(35)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_sequence_length( origin:OriginFor, netuid: u16, validator_sequence_length: u16 ) -> DispatchResult { - Self::do_sudo_set_validator_sequence_length(origin, netuid, validator_sequence_length ) - } + pub fn sudo_set_validator_sequence_length( + origin: OriginFor, + netuid: u16, + validator_sequence_length: u16, + ) -> DispatchResult { + Self::do_sudo_set_validator_sequence_length(origin, netuid, validator_sequence_length) + } - #[pallet::call_index(36)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(36)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_epochs_per_reset( origin:OriginFor, netuid: u16, validator_epochs_per_reset: u16 ) -> DispatchResult { - Self::do_sudo_set_validator_epochs_per_reset( origin, netuid, validator_epochs_per_reset ) - } + pub fn sudo_set_validator_epochs_per_reset( + origin: OriginFor, + netuid: u16, + validator_epochs_per_reset: u16, + ) -> DispatchResult { + Self::do_sudo_set_validator_epochs_per_reset(origin, netuid, validator_epochs_per_reset) + } - #[pallet::call_index(37)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(37)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_exclude_quantile( origin:OriginFor, netuid: u16, validator_exclude_quantile: u16 ) -> DispatchResult { - Self::do_sudo_set_validator_exclude_quantile( origin, netuid, validator_exclude_quantile ) - } + pub fn sudo_set_validator_exclude_quantile( + origin: OriginFor, + netuid: u16, + validator_exclude_quantile: u16, + ) -> DispatchResult { + Self::do_sudo_set_validator_exclude_quantile(origin, netuid, validator_exclude_quantile) + } - #[pallet::call_index(38)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(38)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_prune_len( origin:OriginFor, netuid: u16, validator_prune_len: u64 ) -> DispatchResult { - Self::do_sudo_set_validator_prune_len( origin, netuid, validator_prune_len ) - } + pub fn sudo_set_validator_prune_len( + origin: OriginFor, + netuid: u16, + validator_prune_len: u64, + ) -> DispatchResult { + Self::do_sudo_set_validator_prune_len(origin, netuid, validator_prune_len) + } - #[pallet::call_index(39)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(39)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_logits_divergence( origin:OriginFor, netuid: u16,validator_logits_divergence: u16 ) -> DispatchResult { - Self::do_sudo_set_validator_logits_divergence( origin, netuid, validator_logits_divergence ) - } + pub fn sudo_set_validator_logits_divergence( + origin: OriginFor, + netuid: u16, + validator_logits_divergence: u16, + ) -> DispatchResult { + Self::do_sudo_set_validator_logits_divergence( + origin, + netuid, + validator_logits_divergence, + ) + } - #[pallet::call_index(40)] - #[pallet::weight((Weight::from_ref_time(14_000_000) + #[pallet::call_index(40)] + #[pallet::weight((Weight::from_ref_time(14_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_validator_epoch_len( origin:OriginFor, netuid: u16,validator_epoch_length: u16 ) -> DispatchResult { - Self::do_sudo_set_validator_epoch_length( origin, netuid, validator_epoch_length ) - } + pub fn sudo_set_validator_epoch_len( + origin: OriginFor, + netuid: u16, + validator_epoch_length: u16, + ) -> DispatchResult { + Self::do_sudo_set_validator_epoch_length(origin, netuid, validator_epoch_length) + } - #[pallet::call_index(41)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(41)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_scaling_law_power( origin:OriginFor, netuid: u16, scaling_law_power: u16 ) -> DispatchResult { - Self::do_sudo_set_scaling_law_power( origin, netuid, scaling_law_power ) - } + pub fn sudo_set_scaling_law_power( + origin: OriginFor, + netuid: u16, + scaling_law_power: u16, + ) -> DispatchResult { + Self::do_sudo_set_scaling_law_power(origin, netuid, scaling_law_power) + } - #[pallet::call_index(42)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(42)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_synergy_scaling_law_power( origin:OriginFor, netuid: u16, synergy_scaling_law_power: u16 ) -> DispatchResult { - Self::do_sudo_set_synergy_scaling_law_power( origin, netuid, synergy_scaling_law_power ) - } + pub fn sudo_set_synergy_scaling_law_power( + origin: OriginFor, + netuid: u16, + synergy_scaling_law_power: u16, + ) -> DispatchResult { + Self::do_sudo_set_synergy_scaling_law_power(origin, netuid, synergy_scaling_law_power) + } - #[pallet::call_index(43)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(43)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_immunity_period( origin:OriginFor, netuid: u16, immunity_period: u16 ) -> DispatchResult { - Self::do_sudo_set_immunity_period( origin, netuid, immunity_period ) - } + pub fn sudo_set_immunity_period( + origin: OriginFor, + netuid: u16, + immunity_period: u16, + ) -> DispatchResult { + Self::do_sudo_set_immunity_period(origin, netuid, immunity_period) + } - #[pallet::call_index(44)] - #[pallet::weight((Weight::from_ref_time(13_000_000) + #[pallet::call_index(44)] + #[pallet::weight((Weight::from_ref_time(13_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_max_weight_limit( origin:OriginFor, netuid: u16, max_weight_limit: u16 ) -> DispatchResult { - Self::do_sudo_set_max_weight_limit( origin, netuid, max_weight_limit ) - } + pub fn sudo_set_max_weight_limit( + origin: OriginFor, + netuid: u16, + max_weight_limit: u16, + ) -> DispatchResult { + Self::do_sudo_set_max_weight_limit(origin, netuid, max_weight_limit) + } - #[pallet::call_index(45)] - #[pallet::weight((Weight::from_ref_time(15_000_000) + #[pallet::call_index(45)] + #[pallet::weight((Weight::from_ref_time(15_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_max_registrations_per_block(origin: OriginFor, netuid: u16, max_registrations_per_block: u16 ) -> DispatchResult { - Self::do_sudo_set_max_registrations_per_block(origin, netuid, max_registrations_per_block ) - } - - #[pallet::call_index(46)] - #[pallet::weight((0, DispatchClass::Operational, Pays::No))] - pub fn sudo_set_total_issuance(origin: OriginFor, total_issuance: u64 ) -> DispatchResult { - Self::do_set_total_issuance(origin, total_issuance) - } - - #[pallet::call_index(47)] - #[pallet::weight((Weight::from_ref_time(15_000_000) + pub fn sudo_set_max_registrations_per_block( + origin: OriginFor, + netuid: u16, + max_registrations_per_block: u16, + ) -> DispatchResult { + Self::do_sudo_set_max_registrations_per_block( + origin, + netuid, + max_registrations_per_block, + ) + } + + #[pallet::call_index(46)] + #[pallet::weight((0, DispatchClass::Operational, Pays::No))] + pub fn sudo_set_total_issuance( + origin: OriginFor, + total_issuance: u64, + ) -> DispatchResult { + Self::do_set_total_issuance(origin, total_issuance) + } + + #[pallet::call_index(47)] + #[pallet::weight((Weight::from_ref_time(15_000_000) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_tempo(origin:OriginFor, netuid: u16, tempo: u16) -> DispatchResult { - Self::do_sudo_set_tempo(origin, netuid, tempo) - } - - #[pallet::call_index(48)] - #[pallet::weight((0, DispatchClass::Operational, Pays::No))] - pub fn sudo_set_rao_recycled(origin: OriginFor, netuid: u16, rao_recycled: u64 ) -> DispatchResult { - Self::do_set_rao_recycled(origin, netuid, rao_recycled) - } - - /// Authenticates a council proposal and dispatches a function call with `Root` origin. - /// - /// The dispatch origin for this call must be a council majority. - /// - /// ## Complexity - /// - O(1). - #[pallet::call_index(51)] - #[pallet::weight((Weight::from_ref_time(0), DispatchClass::Operational, Pays::No))] - pub fn sudo( - origin: OriginFor, - call: Box, - ) -> DispatchResultWithPostInfo { - // This is a public call, so we ensure that the origin is a council majority. - T::CouncilOrigin::ensure_origin(origin)?; - - let result = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); - let error = result.map(|_| ()).map_err(|e| e.error); - Self::deposit_event(Event::Sudid(error)); - - return result - } - - /// Authenticates a council proposal and dispatches a function call with `Root` origin. - /// This function does not check the weight of the call, and instead allows the - /// user to specify the weight of the call. - /// - /// The dispatch origin for this call must be a council majority. - /// - /// ## Complexity - /// - O(1). - #[pallet::call_index(52)] - #[pallet::weight((*_weight, call.get_dispatch_info().class, Pays::No))] - pub fn sudo_unchecked_weight( - origin: OriginFor, - call: Box, - _weight: Weight, - ) -> DispatchResultWithPostInfo { - // This is a public call, so we ensure that the origin is a council majority. - T::CouncilOrigin::ensure_origin(origin)?; - - let result = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); - let error = result.map(|_| ()).map_err(|e| e.error); - Self::deposit_event(Event::Sudid(error)); - - return result - } - - #[pallet::call_index(53)] - #[pallet::weight((Weight::from_ref_time(67_000_000) + pub fn sudo_set_tempo(origin: OriginFor, netuid: u16, tempo: u16) -> DispatchResult { + Self::do_sudo_set_tempo(origin, netuid, tempo) + } + + #[pallet::call_index(48)] + #[pallet::weight((0, DispatchClass::Operational, Pays::No))] + pub fn sudo_set_rao_recycled( + origin: OriginFor, + netuid: u16, + rao_recycled: u64, + ) -> DispatchResult { + Self::do_set_rao_recycled(origin, netuid, rao_recycled) + } + + /// Authenticates a council proposal and dispatches a function call with `Root` origin. + /// + /// The dispatch origin for this call must be a council majority. + /// + /// ## Complexity + /// - O(1). + #[pallet::call_index(51)] + #[pallet::weight((Weight::from_ref_time(0), DispatchClass::Operational, Pays::No))] + pub fn sudo( + origin: OriginFor, + call: Box, + ) -> DispatchResultWithPostInfo { + // This is a public call, so we ensure that the origin is a council majority. + T::CouncilOrigin::ensure_origin(origin)?; + + let result = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); + let error = result.map(|_| ()).map_err(|e| e.error); + Self::deposit_event(Event::Sudid(error)); + + return result; + } + + /// Authenticates a council proposal and dispatches a function call with `Root` origin. + /// This function does not check the weight of the call, and instead allows the + /// user to specify the weight of the call. + /// + /// The dispatch origin for this call must be a council majority. + /// + /// ## Complexity + /// - O(1). + #[pallet::call_index(52)] + #[pallet::weight((*_weight, call.get_dispatch_info().class, Pays::No))] + pub fn sudo_unchecked_weight( + origin: OriginFor, + call: Box, + _weight: Weight, + ) -> DispatchResultWithPostInfo { + // This is a public call, so we ensure that the origin is a council majority. + T::CouncilOrigin::ensure_origin(origin)?; + + let result = call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()); + let error = result.map(|_| ()).map_err(|e| e.error); + Self::deposit_event(Event::Sudid(error)); + + return result; + } + + #[pallet::call_index(53)] + #[pallet::weight((Weight::from_ref_time(67_000_000) .saturating_add(Weight::from_proof_size(61173)) .saturating_add(T::DbWeight::get().reads(20)) .saturating_add(T::DbWeight::get().writes(3)), DispatchClass::Normal, Pays::No))] - pub fn join_senate( - origin: OriginFor, - hotkey: T::AccountId - ) -> DispatchResult { - Self::do_join_senate(origin, &hotkey) - } - - #[pallet::call_index(54)] - #[pallet::weight((Weight::from_ref_time(20_000_000) + pub fn join_senate(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { + Self::do_join_senate(origin, &hotkey) + } + + #[pallet::call_index(54)] + #[pallet::weight((Weight::from_ref_time(20_000_000) .saturating_add(Weight::from_proof_size(4748)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(3)), DispatchClass::Normal, Pays::No))] - pub fn leave_senate( - origin: OriginFor, - hotkey: T::AccountId - ) -> DispatchResult { - Self::do_leave_senate(origin, &hotkey) - } - - #[pallet::call_index(55)] - #[pallet::weight((Weight::from_ref_time(0) + pub fn leave_senate(origin: OriginFor, hotkey: T::AccountId) -> DispatchResult { + Self::do_leave_senate(origin, &hotkey) + } + + #[pallet::call_index(55)] + #[pallet::weight((Weight::from_ref_time(0) .saturating_add(Weight::from_proof_size(0)) .saturating_add(T::DbWeight::get().reads(0)) .saturating_add(T::DbWeight::get().writes(0)), DispatchClass::Operational))] - pub fn vote( - origin: OriginFor, - hotkey: T::AccountId, - proposal: T::Hash, - #[pallet::compact] index: u32, - approve: bool, - ) -> DispatchResultWithPostInfo { - Self::do_vote_senate(origin, &hotkey, proposal, index, approve) - } - - // Sudo call for setting registration allowed - #[pallet::call_index(49)] - #[pallet::weight((Weight::from_ref_time(4_000_000) + pub fn vote( + origin: OriginFor, + hotkey: T::AccountId, + proposal: T::Hash, + #[pallet::compact] index: u32, + approve: bool, + ) -> DispatchResultWithPostInfo { + Self::do_vote_senate(origin, &hotkey, proposal, index, approve) + } + + // Sudo call for setting registration allowed + #[pallet::call_index(49)] + #[pallet::weight((Weight::from_ref_time(4_000_000) .saturating_add(Weight::from_proof_size(0)) .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] - pub fn sudo_set_registration_allowed( origin:OriginFor, netuid: u16, registration_allowed: bool ) -> DispatchResult { - Self::do_sudo_set_network_registration_allowed( origin, netuid, registration_allowed ) - } - - #[pallet::call_index(56)] - #[pallet::weight((0, DispatchClass::Operational, Pays::No))] - pub fn sudo_set_senate_required_stake_perc(origin: OriginFor, required_percent: u64 ) -> DispatchResult { - Self::do_set_senate_required_stake_perc(origin, required_percent) - } - - #[pallet::call_index(57)] - #[pallet::weight((0, DispatchClass::Operational, Pays::No))] - pub fn sudo_remove_votes(origin: OriginFor, who: T::AccountId ) -> DispatchResult { - Self::do_remove_votes(origin, &who) - } - } - - // ---- Subtensor helper functions. - impl Pallet { - // --- Returns the transaction priority for setting weights. - pub fn get_priority_set_weights( hotkey: &T::AccountId, netuid: u16 ) -> u64 { - if Uids::::contains_key( netuid, &hotkey ) { - let uid = Self::get_uid_for_net_and_hotkey(netuid, &hotkey.clone()).unwrap(); - let current_block_number: u64 = Self::get_current_block_as_u64(); - let default_priority: u64 = current_block_number - Self::get_last_update_for_uid(netuid, uid as u16); - return default_priority + u32::max_value() as u64; - } - return 0; - } - - // Benchmarking functions. - #[cfg(feature = "runtime-benchmarks")] - pub fn create_network( _: OriginFor, netuid: u16, n: u16, tempo: u16 ) -> DispatchResult { - Self::init_new_network( netuid, tempo, 1 ); - Self::set_max_allowed_uids( netuid, n ); - let mut seed : u32 = 1; - for _ in 0..n { - let block_number: u64 = Self::get_current_block_as_u64(); - let hotkey: T::AccountId = T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap(); - Self::append_neuron( netuid, &hotkey, block_number ); - seed = seed + 1; - } - Ok(()) - } - - #[cfg(feature = "runtime-benchmarks")] - pub fn create_network_with_weights( _: OriginFor, netuid: u16, n: u16, tempo: u16, n_vals: u16, n_weights: u16 ) -> DispatchResult { - Self::init_new_network( netuid, tempo, 1 ); - Self::set_max_allowed_uids( netuid, n ); - Self::set_max_allowed_validators( netuid, n_vals ); - Self::set_min_allowed_weights( netuid, n_weights ); - Self::set_emission_for_network( netuid, 1_000_000_000 ); - let mut seed : u32 = 1; - for _ in 0..n { - let block_number: u64 = Self::get_current_block_as_u64(); - let hotkey: T::AccountId = T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()).unwrap(); - Self::increase_stake_on_coldkey_hotkey_account( &hotkey, &hotkey, 1_000_000_000 ); - Self::append_neuron( netuid, &hotkey, block_number ); - seed = seed + 1; - } - for uid in 0..n { - let uids: Vec = (0..n_weights).collect(); - let values: Vec = vec![1; n_weights as usize]; - let normalized_values = Self::normalize_weights( values ); - let mut zipped_weights: Vec<( u16, u16 )> = vec![]; - for ( uid, val ) in uids.iter().zip(normalized_values.iter()) { zipped_weights.push((*uid, *val)) } - if uid < n_vals { - Weights::::insert( netuid, uid, zipped_weights ); - } else { - break; - } - } - Ok(()) - } - } -} + pub fn sudo_set_registration_allowed( + origin: OriginFor, + netuid: u16, + registration_allowed: bool, + ) -> DispatchResult { + Self::do_sudo_set_network_registration_allowed(origin, netuid, registration_allowed) + } + + #[pallet::call_index(56)] + #[pallet::weight((0, DispatchClass::Operational, Pays::No))] + pub fn sudo_set_senate_required_stake_perc( + origin: OriginFor, + required_percent: u64, + ) -> DispatchResult { + Self::do_set_senate_required_stake_perc(origin, required_percent) + } + + #[pallet::call_index(57)] + #[pallet::weight((0, DispatchClass::Operational, Pays::No))] + pub fn sudo_remove_votes(origin: OriginFor, who: T::AccountId) -> DispatchResult { + Self::do_remove_votes(origin, &who) + } + + #[pallet::call_index(58)] + #[pallet::weight((Weight::from_ref_time(14_000_000) + .saturating_add(T::DbWeight::get().reads(1)) + .saturating_add(T::DbWeight::get().writes(1)), DispatchClass::Operational, Pays::No))] + pub fn sudo_set_adjustment_alpha( + origin: OriginFor, + netuid: u16, + adjustment_alpha: u64, + ) -> DispatchResult { + Self::do_sudo_set_adjustment_alpha(origin, netuid, adjustment_alpha) + } + } + // ---- Subtensor helper functions. + impl Pallet { + // --- Returns the transaction priority for setting weights. + pub fn get_priority_set_weights(hotkey: &T::AccountId, netuid: u16) -> u64 { + if Uids::::contains_key(netuid, &hotkey) { + let uid = Self::get_uid_for_net_and_hotkey(netuid, &hotkey.clone()).unwrap(); + let current_block_number: u64 = Self::get_current_block_as_u64(); + let default_priority: u64 = + current_block_number - Self::get_last_update_for_uid(netuid, uid as u16); + return default_priority + u32::max_value() as u64; + } + return 0; + } + + // Benchmarking functions. + #[cfg(feature = "runtime-benchmarks")] + pub fn create_network(_: OriginFor, netuid: u16, n: u16, tempo: u16) -> DispatchResult { + Self::init_new_network(netuid, tempo, 1); + Self::set_max_allowed_uids(netuid, n); + let mut seed: u32 = 1; + for _ in 0..n { + let block_number: u64 = Self::get_current_block_as_u64(); + let hotkey: T::AccountId = + T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) + .unwrap(); + Self::append_neuron(netuid, &hotkey, block_number); + seed = seed + 1; + } + Ok(()) + } + + #[cfg(feature = "runtime-benchmarks")] + pub fn create_network_with_weights( + _: OriginFor, + netuid: u16, + n: u16, + tempo: u16, + n_vals: u16, + n_weights: u16, + ) -> DispatchResult { + Self::init_new_network(netuid, tempo, 1); + Self::set_max_allowed_uids(netuid, n); + Self::set_max_allowed_validators(netuid, n_vals); + Self::set_min_allowed_weights(netuid, n_weights); + Self::set_emission_for_network(netuid, 1_000_000_000); + let mut seed: u32 = 1; + for _ in 0..n { + let block_number: u64 = Self::get_current_block_as_u64(); + let hotkey: T::AccountId = + T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) + .unwrap(); + Self::increase_stake_on_coldkey_hotkey_account(&hotkey, &hotkey, 1_000_000_000); + Self::append_neuron(netuid, &hotkey, block_number); + seed = seed + 1; + } + for uid in 0..n { + let uids: Vec = (0..n_weights).collect(); + let values: Vec = vec![1; n_weights as usize]; + let normalized_values = Self::normalize_weights(values); + let mut zipped_weights: Vec<(u16, u16)> = vec![]; + for (uid, val) in uids.iter().zip(normalized_values.iter()) { + zipped_weights.push((*uid, *val)) + } + if uid < n_vals { + Weights::::insert(netuid, uid, zipped_weights); + } else { + break; + } + } + Ok(()) + } + } +} /************************************************************ - CallType definition + CallType definition ************************************************************/ #[derive(Debug, PartialEq)] pub enum CallType { SetWeights, AddStake, RemoveStake, - AddDelegate, + AddDelegate, Register, Serve, - Other, + Other, } impl Default for CallType { fn default() -> Self { @@ -1803,97 +2233,94 @@ impl Default for CallType { #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] pub struct SubtensorSignedExtension(pub PhantomData); -impl SubtensorSignedExtension where - T::RuntimeCall: Dispatchable, - ::RuntimeCall: IsSubType>, +impl SubtensorSignedExtension +where + T::RuntimeCall: Dispatchable, + ::RuntimeCall: IsSubType>, { - pub fn new() -> Self { - Self(Default::default()) - } - - pub fn get_priority_vanilla() -> u64 { - // Return high priority so that every extrinsic except set_weights function will - // have a higher priority than the set_weights call - return u64::max_value(); - } + pub fn new() -> Self { + Self(Default::default()) + } - pub fn get_priority_set_weights( who: &T::AccountId, netuid: u16 ) -> u64 { - // Return the non vanilla priority for a set weights call. + pub fn get_priority_vanilla() -> u64 { + // Return high priority so that every extrinsic except set_weights function will + // have a higher priority than the set_weights call + return u64::max_value(); + } - return Pallet::::get_priority_set_weights( who, netuid ); - } + pub fn get_priority_set_weights(who: &T::AccountId, netuid: u16) -> u64 { + // Return the non vanilla priority for a set weights call. - pub fn u64_to_balance( input: u64 ) -> Option<<::Currency as Currency<::AccountId>>::Balance> { input.try_into().ok() } + return Pallet::::get_priority_set_weights(who, netuid); + } + pub fn u64_to_balance( + input: u64, + ) -> Option< + <::Currency as Currency<::AccountId>>::Balance, + > { + input.try_into().ok() + } } -impl sp_std::fmt::Debug for SubtensorSignedExtension { - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { - write!(f, "SubtensorSignedExtension") - } +impl sp_std::fmt::Debug for SubtensorSignedExtension { + fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + write!(f, "SubtensorSignedExtension") + } } impl SignedExtension for SubtensorSignedExtension - where - T::RuntimeCall: Dispatchable, - ::RuntimeCall: IsSubType>, +where + T::RuntimeCall: Dispatchable, + ::RuntimeCall: IsSubType>, { - const IDENTIFIER: &'static str = "SubtensorSignedExtension"; - - type AccountId = T::AccountId; - type Call = T::RuntimeCall; - type AdditionalSigned = (); - type Pre = (CallType, u64, Self::AccountId); - - fn additional_signed( &self ) -> Result { - Ok(()) - } - - - fn validate( - &self, - who: &Self::AccountId, - call: &Self::Call, - _info: &DispatchInfoOf, - _len: usize, - ) -> TransactionValidity { - match call.is_sub_type() { - Some(Call::set_weights{netuid, ..}) => { - let priority: u64 = Self::get_priority_set_weights(who, *netuid); + const IDENTIFIER: &'static str = "SubtensorSignedExtension"; + + type AccountId = T::AccountId; + type Call = T::RuntimeCall; + type AdditionalSigned = (); + type Pre = (CallType, u64, Self::AccountId); + + fn additional_signed(&self) -> Result { + Ok(()) + } + + fn validate( + &self, + who: &Self::AccountId, + call: &Self::Call, + _info: &DispatchInfoOf, + _len: usize, + ) -> TransactionValidity { + match call.is_sub_type() { + Some(Call::set_weights { netuid, .. }) => { + let priority: u64 = Self::get_priority_set_weights(who, *netuid); Ok(ValidTransaction { priority: priority, longevity: 1, ..Default::default() }) } - Some(Call::add_stake{..}) => { - Ok(ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }) - } - Some(Call::remove_stake{..}) => { - Ok(ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }) - } - Some(Call::register{..}) => { - Ok(ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }) - } - _ => { - Ok(ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }) - } - } - } + Some(Call::add_stake { .. }) => Ok(ValidTransaction { + priority: Self::get_priority_vanilla(), + ..Default::default() + }), + Some(Call::remove_stake { .. }) => Ok(ValidTransaction { + priority: Self::get_priority_vanilla(), + ..Default::default() + }), + Some(Call::register { .. }) => Ok(ValidTransaction { + priority: Self::get_priority_vanilla(), + ..Default::default() + }), + _ => Ok(ValidTransaction { + priority: Self::get_priority_vanilla(), + ..Default::default() + }), + } + } - // NOTE: Add later when we put in a pre and post dispatch step. + // NOTE: Add later when we put in a pre and post dispatch step. fn pre_dispatch( self, who: &Self::AccountId, @@ -1901,119 +2328,137 @@ impl SignedExtension for SubtensorSignedExte _info: &DispatchInfoOf, _len: usize, ) -> Result { - match call.is_sub_type() { - Some(Call::add_stake{..}) => { - let transaction_fee = 100000; + Some(Call::add_stake { .. }) => { + let transaction_fee = 100000; Ok((CallType::AddStake, transaction_fee, who.clone())) } - Some(Call::remove_stake{..}) => { - let transaction_fee = 0; + Some(Call::remove_stake { .. }) => { + let transaction_fee = 0; Ok((CallType::RemoveStake, transaction_fee, who.clone())) } - Some(Call::set_weights{..}) => { - let transaction_fee = 0; - Ok((CallType::SetWeights, transaction_fee, who.clone())) + Some(Call::set_weights { .. }) => { + let transaction_fee = 0; + Ok((CallType::SetWeights, transaction_fee, who.clone())) } - Some(Call::register{..}) => { + Some(Call::register { .. }) => { let transaction_fee = 0; Ok((CallType::Register, transaction_fee, who.clone())) } - Some(Call::serve_axon{..}) => { + Some(Call::serve_axon { .. }) => { let transaction_fee = 0; Ok((CallType::Serve, transaction_fee, who.clone())) } _ => { - let transaction_fee = 0; + let transaction_fee = 0; Ok((CallType::Other, transaction_fee, who.clone())) } } } - fn post_dispatch( + fn post_dispatch( maybe_pre: Option, _info: &DispatchInfoOf, _post_info: &PostDispatchInfoOf, _len: usize, _result: &dispatch::DispatchResult, ) -> Result<(), TransactionValidityError> { - - if let Some((call_type, _transaction_fee, _who)) = maybe_pre { - match call_type { - CallType::SetWeights => { - log::debug!("Not Implemented!"); - } - CallType::AddStake => { - log::debug!("Not Implemented! Need to add potential transaction fees here."); - } - CallType::RemoveStake => { - log::debug!("Not Implemented! Need to add potential transaction fees here."); - } - CallType::Register => { - log::debug!("Not Implemented!"); - } - _ => { - log::debug!("Not Implemented!"); - } - } - } - Ok(()) + if let Some((call_type, _transaction_fee, _who)) = maybe_pre { + match call_type { + CallType::SetWeights => { + log::debug!("Not Implemented!"); + } + CallType::AddStake => { + log::debug!("Not Implemented! Need to add potential transaction fees here."); + } + CallType::RemoveStake => { + log::debug!("Not Implemented! Need to add potential transaction fees here."); + } + CallType::Register => { + log::debug!("Not Implemented!"); + } + _ => { + log::debug!("Not Implemented!"); + } + } + } + Ok(()) } - } use frame_support::{inherent::Vec, sp_std::vec}; /// Trait for managing a membership pallet instance in the runtime pub trait MemberManagement { - /// Add member - fn add_member(account: &AccountId) -> DispatchResult; + /// Add member + fn add_member(account: &AccountId) -> DispatchResult; - /// Remove a member - fn remove_member(account: &AccountId) -> DispatchResult; + /// Remove a member + fn remove_member(account: &AccountId) -> DispatchResult; - /// Swap member - fn swap_member(remove: &AccountId, add: &AccountId) -> DispatchResult; + /// Swap member + fn swap_member(remove: &AccountId, add: &AccountId) -> DispatchResult; - /// Get all members - fn members() -> Vec; + /// Get all members + fn members() -> Vec; - /// Check if an account is apart of the set - fn is_member(account: &AccountId) -> bool; + /// Check if an account is apart of the set + fn is_member(account: &AccountId) -> bool; - /// Get our maximum member count - fn max_members() -> u32; + /// Get our maximum member count + fn max_members() -> u32; } impl MemberManagement for () { - /// Add member - fn add_member(_: &T) -> DispatchResult {Ok(())} + /// Add member + fn add_member(_: &T) -> DispatchResult { + Ok(()) + } - // Remove a member - fn remove_member(_: &T) -> DispatchResult {Ok(())} + // Remove a member + fn remove_member(_: &T) -> DispatchResult { + Ok(()) + } - // Swap member - fn swap_member(_: &T, _: &T) -> DispatchResult {Ok(())} + // Swap member + fn swap_member(_: &T, _: &T) -> DispatchResult { + Ok(()) + } - // Get all members - fn members() -> Vec {vec![]} + // Get all members + fn members() -> Vec { + vec![] + } - // Check if an account is apart of the set - fn is_member(_: &T) -> bool {false} + // Check if an account is apart of the set + fn is_member(_: &T) -> bool { + false + } - fn max_members() -> u32 {0} + fn max_members() -> u32 { + 0 + } } /// Trait for interacting with collective pallets pub trait CollectiveInterface { - /// Remove vote - fn remove_votes(hotkey: &AccountId) -> Result; - - fn add_vote(hotkey: &AccountId, proposal: Hash, index: ProposalIndex, approve: bool) -> Result; + /// Remove vote + fn remove_votes(hotkey: &AccountId) -> Result; + + fn add_vote( + hotkey: &AccountId, + proposal: Hash, + index: ProposalIndex, + approve: bool, + ) -> Result; } impl CollectiveInterface for () { - fn remove_votes(_: &T) -> Result {Ok(true)} + fn remove_votes(_: &T) -> Result { + Ok(true) + } - fn add_vote(_: &T, _: H, _: P, _: bool) -> Result {Ok(true)} -} \ No newline at end of file + fn add_vote(_: &T, _: H, _: P, _: bool) -> Result { + Ok(true) + } +} diff --git a/pallets/subtensor/src/utils.rs b/pallets/subtensor/src/utils.rs index 9fa195f7b..db941e7d0 100644 --- a/pallets/subtensor/src/utils.rs +++ b/pallets/subtensor/src/utils.rs @@ -1,542 +1,1209 @@ - use super::*; -use frame_support::{inherent::Vec}; -use sp_core::U256; -use frame_support::pallet_prelude::DispatchResult; use crate::system::ensure_root; +use frame_support::inherent::Vec; +use frame_support::pallet_prelude::DispatchResult; +use sp_core::U256; impl Pallet { - // ======================== - // ==== Global Setters ==== - // ======================== - pub fn set_tempo( netuid: u16, tempo: u16 ) { Tempo::::insert( netuid, tempo ); } - pub fn set_last_adjustment_block( netuid: u16, last_adjustment_block: u64 ) { LastAdjustmentBlock::::insert( netuid, last_adjustment_block ); } - pub fn set_blocks_since_last_step( netuid: u16, blocks_since_last_step: u64 ) { BlocksSinceLastStep::::insert( netuid, blocks_since_last_step ); } - pub fn set_registrations_this_block( netuid: u16, registrations_this_block: u16 ) { RegistrationsThisBlock::::insert(netuid, registrations_this_block); } - pub fn set_last_mechanism_step_block( netuid: u16, last_mechanism_step_block: u64 ) { LastMechansimStepBlock::::insert(netuid, last_mechanism_step_block); } - pub fn set_registrations_this_interval( netuid: u16, registrations_this_interval: u16 ) { RegistrationsThisInterval::::insert(netuid, registrations_this_interval); } - pub fn set_pow_registrations_this_interval( netuid: u16, pow_registrations_this_interval: u16 ) { POWRegistrationsThisInterval::::insert(netuid, pow_registrations_this_interval); } - pub fn set_burn_registrations_this_interval( netuid: u16, burn_registrations_this_interval: u16 ) { BurnRegistrationsThisInterval::::insert(netuid, burn_registrations_this_interval); } + // ==== Global Setters ==== + // ======================== + pub fn set_tempo(netuid: u16, tempo: u16) { + Tempo::::insert(netuid, tempo); + } + pub fn set_last_adjustment_block(netuid: u16, last_adjustment_block: u64) { + LastAdjustmentBlock::::insert(netuid, last_adjustment_block); + } + pub fn set_blocks_since_last_step(netuid: u16, blocks_since_last_step: u64) { + BlocksSinceLastStep::::insert(netuid, blocks_since_last_step); + } + pub fn set_registrations_this_block(netuid: u16, registrations_this_block: u16) { + RegistrationsThisBlock::::insert(netuid, registrations_this_block); + } + pub fn set_last_mechanism_step_block(netuid: u16, last_mechanism_step_block: u64) { + LastMechansimStepBlock::::insert(netuid, last_mechanism_step_block); + } + pub fn set_registrations_this_interval(netuid: u16, registrations_this_interval: u16) { + RegistrationsThisInterval::::insert(netuid, registrations_this_interval); + } + pub fn set_pow_registrations_this_interval(netuid: u16, pow_registrations_this_interval: u16) { + POWRegistrationsThisInterval::::insert(netuid, pow_registrations_this_interval); + } + pub fn set_burn_registrations_this_interval( + netuid: u16, + burn_registrations_this_interval: u16, + ) { + BurnRegistrationsThisInterval::::insert(netuid, burn_registrations_this_interval); + } // ======================== - // ==== Global Getters ==== - // ======================== - pub fn get_total_issuance() -> u64 { TotalIssuance::::get() } - pub fn get_block_emission() -> u64 { BlockEmission::::get() } - pub fn get_current_block_as_u64( ) -> u64 { TryInto::try_into( >::block_number() ).ok().expect("blockchain will not exceed 2^64 blocks; QED.") } + // ==== Global Getters ==== + // ======================== + pub fn get_total_issuance() -> u64 { + TotalIssuance::::get() + } + pub fn get_block_emission() -> u64 { + BlockEmission::::get() + } + pub fn get_current_block_as_u64() -> u64 { + TryInto::try_into(>::block_number()) + .ok() + .expect("blockchain will not exceed 2^64 blocks; QED.") + } // ============================== - // ==== YumaConsensus params ==== - // ============================== - pub fn get_rank( netuid:u16 ) -> Vec { Rank::::get( netuid ) } - pub fn get_trust( netuid:u16 ) -> Vec { Trust::::get( netuid ) } - pub fn get_active( netuid:u16 ) -> Vec { Active::::get( netuid ) } - pub fn get_emission( netuid:u16 ) -> Vec { Emission::::get( netuid ) } - pub fn get_consensus( netuid:u16 ) -> Vec { Consensus::::get( netuid ) } - pub fn get_incentive( netuid:u16 ) -> Vec { Incentive::::get( netuid ) } - pub fn get_dividends( netuid:u16 ) -> Vec { Dividends::::get( netuid ) } - pub fn get_last_update( netuid:u16 ) -> Vec { LastUpdate::::get( netuid ) } - pub fn get_pruning_score( netuid:u16 ) -> Vec { PruningScores::::get( netuid ) } - pub fn get_validator_trust( netuid:u16 ) -> Vec { ValidatorTrust::::get( netuid ) } - pub fn get_validator_permit( netuid:u16 ) -> Vec { ValidatorPermit::::get( netuid ) } + // ==== YumaConsensus params ==== + // ============================== + pub fn get_rank(netuid: u16) -> Vec { + Rank::::get(netuid) + } + pub fn get_trust(netuid: u16) -> Vec { + Trust::::get(netuid) + } + pub fn get_active(netuid: u16) -> Vec { + Active::::get(netuid) + } + pub fn get_emission(netuid: u16) -> Vec { + Emission::::get(netuid) + } + pub fn get_consensus(netuid: u16) -> Vec { + Consensus::::get(netuid) + } + pub fn get_incentive(netuid: u16) -> Vec { + Incentive::::get(netuid) + } + pub fn get_dividends(netuid: u16) -> Vec { + Dividends::::get(netuid) + } + pub fn get_last_update(netuid: u16) -> Vec { + LastUpdate::::get(netuid) + } + pub fn get_pruning_score(netuid: u16) -> Vec { + PruningScores::::get(netuid) + } + pub fn get_validator_trust(netuid: u16) -> Vec { + ValidatorTrust::::get(netuid) + } + pub fn get_validator_permit(netuid: u16) -> Vec { + ValidatorPermit::::get(netuid) + } // ================================== - // ==== YumaConsensus UID params ==== - // ================================== - pub fn set_last_update_for_uid( netuid:u16, uid: u16, last_update: u64 ) { - let mut updated_last_update_vec = Self::get_last_update( netuid ); - if (uid as usize) < updated_last_update_vec.len() { + // ==== YumaConsensus UID params ==== + // ================================== + pub fn set_last_update_for_uid(netuid: u16, uid: u16, last_update: u64) { + let mut updated_last_update_vec = Self::get_last_update(netuid); + if (uid as usize) < updated_last_update_vec.len() { updated_last_update_vec[uid as usize] = last_update; - LastUpdate::::insert( netuid, updated_last_update_vec ); - } + LastUpdate::::insert(netuid, updated_last_update_vec); + } } - pub fn set_active_for_uid( netuid:u16, uid: u16, active: bool ) { - let mut updated_active_vec = Self::get_active( netuid ); - if (uid as usize) < updated_active_vec.len() { + pub fn set_active_for_uid(netuid: u16, uid: u16, active: bool) { + let mut updated_active_vec = Self::get_active(netuid); + if (uid as usize) < updated_active_vec.len() { updated_active_vec[uid as usize] = active; - Active::::insert( netuid, updated_active_vec ); - } + Active::::insert(netuid, updated_active_vec); + } } - pub fn set_pruning_score_for_uid( netuid:u16, uid: u16, pruning_score: u16 ) { + pub fn set_pruning_score_for_uid(netuid: u16, uid: u16, pruning_score: u16) { log::info!("netuid = {:?}", netuid); - log::info!("SubnetworkN::::get( netuid ) = {:?}", SubnetworkN::::get( netuid ) ); - log::info!("uid = {:?}", uid ); - assert!( uid < SubnetworkN::::get( netuid ) ); - PruningScores::::mutate( netuid, |v| v[uid as usize] = pruning_score ); - } - pub fn set_validator_permit_for_uid( netuid:u16, uid: u16, validator_permit: bool ) { - let mut updated_validator_permit = Self::get_validator_permit( netuid ); - if (uid as usize) < updated_validator_permit.len() { + log::info!( + "SubnetworkN::::get( netuid ) = {:?}", + SubnetworkN::::get(netuid) + ); + log::info!("uid = {:?}", uid); + assert!(uid < SubnetworkN::::get(netuid)); + PruningScores::::mutate(netuid, |v| v[uid as usize] = pruning_score); + } + pub fn set_validator_permit_for_uid(netuid: u16, uid: u16, validator_permit: bool) { + let mut updated_validator_permit = Self::get_validator_permit(netuid); + if (uid as usize) < updated_validator_permit.len() { updated_validator_permit[uid as usize] = validator_permit; - ValidatorPermit::::insert( netuid, updated_validator_permit ); - } - } - - pub fn get_rank_for_uid( netuid:u16, uid: u16) -> u16 { let vec = Rank::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_trust_for_uid( netuid:u16, uid: u16) -> u16 { let vec = Trust::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_emission_for_uid( netuid:u16, uid: u16) -> u64 {let vec = Emission::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_active_for_uid( netuid:u16, uid: u16) -> bool { let vec = Active::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return false } } - pub fn get_consensus_for_uid( netuid:u16, uid: u16) -> u16 { let vec = Consensus::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_incentive_for_uid( netuid:u16, uid: u16) -> u16 { let vec = Incentive::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_dividends_for_uid( netuid:u16, uid: u16) -> u16 { let vec = Dividends::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_last_update_for_uid( netuid:u16, uid: u16) -> u64 { let vec = LastUpdate::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_pruning_score_for_uid( netuid:u16, uid: u16) -> u16 { let vec = PruningScores::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return u16::MAX } } - pub fn get_validator_trust_for_uid( netuid:u16, uid: u16) -> u16 { let vec = ValidatorTrust::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return 0 } } - pub fn get_validator_permit_for_uid( netuid:u16, uid: u16) -> bool { let vec = ValidatorPermit::::get( netuid ); if (uid as usize) < vec.len() { return vec[uid as usize] } else{ return false } } + ValidatorPermit::::insert(netuid, updated_validator_permit); + } + } + + pub fn get_rank_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = Rank::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_trust_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = Trust::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_emission_for_uid(netuid: u16, uid: u16) -> u64 { + let vec = Emission::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_active_for_uid(netuid: u16, uid: u16) -> bool { + let vec = Active::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return false; + } + } + pub fn get_consensus_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = Consensus::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_incentive_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = Incentive::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_dividends_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = Dividends::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_last_update_for_uid(netuid: u16, uid: u16) -> u64 { + let vec = LastUpdate::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_pruning_score_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = PruningScores::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return u16::MAX; + } + } + pub fn get_validator_trust_for_uid(netuid: u16, uid: u16) -> u16 { + let vec = ValidatorTrust::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return 0; + } + } + pub fn get_validator_permit_for_uid(netuid: u16, uid: u16) -> bool { + let vec = ValidatorPermit::::get(netuid); + if (uid as usize) < vec.len() { + return vec[uid as usize]; + } else { + return false; + } + } // ============================ - // ==== Subnetwork Getters ==== - // ============================ - pub fn get_tempo( netuid:u16 ) -> u16{ Tempo::::get( netuid ) } - pub fn get_emission_value( netuid: u16 ) -> u64 { EmissionValues::::get( netuid ) } - pub fn get_pending_emission( netuid:u16 ) -> u64{ PendingEmission::::get( netuid ) } - pub fn get_last_adjustment_block( netuid: u16) -> u64 { LastAdjustmentBlock::::get( netuid ) } - pub fn get_blocks_since_last_step(netuid:u16 ) -> u64 { BlocksSinceLastStep::::get( netuid ) } - pub fn get_difficulty( netuid: u16 ) -> U256 { U256::from( Self::get_difficulty_as_u64( netuid ) ) } - pub fn get_registrations_this_block( netuid:u16 ) -> u16 { RegistrationsThisBlock::::get( netuid ) } - pub fn get_last_mechanism_step_block( netuid: u16 ) -> u64 { LastMechansimStepBlock::::get( netuid ) } - pub fn get_registrations_this_interval( netuid: u16 ) -> u16 { RegistrationsThisInterval::::get( netuid ) } - pub fn get_pow_registrations_this_interval( netuid: u16 ) -> u16 { POWRegistrationsThisInterval::::get( netuid ) } - pub fn get_burn_registrations_this_interval( netuid: u16 ) -> u16 { BurnRegistrationsThisInterval::::get( netuid ) } - pub fn get_neuron_block_at_registration( netuid: u16, neuron_uid: u16 ) -> u64 { BlockAtRegistration::::get( netuid, neuron_uid )} + // ==== Subnetwork Getters ==== + // ============================ + pub fn get_tempo(netuid: u16) -> u16 { + Tempo::::get(netuid) + } + pub fn get_emission_value(netuid: u16) -> u64 { + EmissionValues::::get(netuid) + } + pub fn get_pending_emission(netuid: u16) -> u64 { + PendingEmission::::get(netuid) + } + pub fn get_last_adjustment_block(netuid: u16) -> u64 { + LastAdjustmentBlock::::get(netuid) + } + pub fn get_blocks_since_last_step(netuid: u16) -> u64 { + BlocksSinceLastStep::::get(netuid) + } + pub fn get_difficulty(netuid: u16) -> U256 { + U256::from(Self::get_difficulty_as_u64(netuid)) + } + pub fn get_registrations_this_block(netuid: u16) -> u16 { + RegistrationsThisBlock::::get(netuid) + } + pub fn get_last_mechanism_step_block(netuid: u16) -> u64 { + LastMechansimStepBlock::::get(netuid) + } + pub fn get_registrations_this_interval(netuid: u16) -> u16 { + RegistrationsThisInterval::::get(netuid) + } + pub fn get_pow_registrations_this_interval(netuid: u16) -> u16 { + POWRegistrationsThisInterval::::get(netuid) + } + pub fn get_burn_registrations_this_interval(netuid: u16) -> u16 { + BurnRegistrationsThisInterval::::get(netuid) + } + pub fn get_neuron_block_at_registration(netuid: u16, neuron_uid: u16) -> u64 { + BlockAtRegistration::::get(netuid, neuron_uid) + } // ======================== - // ==== Rate Limiting ===== - // ======================== - pub fn set_last_tx_block( key: &T::AccountId, block: u64 ) { LastTxBlock::::insert( key, block ) } - pub fn get_last_tx_block( key: &T::AccountId ) -> u64 { LastTxBlock::::get( key ) } - pub fn exceeds_tx_rate_limit( prev_tx_block: u64, current_block: u64 ) -> bool { + // ==== Rate Limiting ===== + // ======================== + pub fn set_last_tx_block(key: &T::AccountId, block: u64) { + LastTxBlock::::insert(key, block) + } + pub fn get_last_tx_block(key: &T::AccountId) -> u64 { + LastTxBlock::::get(key) + } + pub fn exceeds_tx_rate_limit(prev_tx_block: u64, current_block: u64) -> bool { let rate_limit: u64 = Self::get_tx_rate_limit(); - if rate_limit == 0 || prev_tx_block == 0 { - return false; - } + if rate_limit == 0 || prev_tx_block == 0 { + return false; + } return current_block - prev_tx_block <= rate_limit; } // ======================== - // ==== Sudo calls ======== - // ======================== - pub fn get_default_take() -> u16 { DefaultTake::::get() } - pub fn set_default_take( default_take: u16 ) { DefaultTake::::put( default_take ) } - pub fn do_sudo_set_default_take( origin: T::RuntimeOrigin, default_take: u16 ) -> DispatchResult { - ensure_root( origin )?; - Self::set_default_take( default_take ); + // ==== Sudo calls ======== + // ======================== + pub fn get_default_take() -> u16 { + DefaultTake::::get() + } + pub fn set_default_take(default_take: u16) { + DefaultTake::::put(default_take) + } + pub fn do_sudo_set_default_take(origin: T::RuntimeOrigin, default_take: u16) -> DispatchResult { + ensure_root(origin)?; + Self::set_default_take(default_take); log::info!("DefaultTakeSet( default_take: {:?} ) ", default_take); - Self::deposit_event( Event::DefaultTakeSet( default_take ) ); - Ok(()) - } - - // Configure tx rate limiting - pub fn get_tx_rate_limit() -> u64 { TxRateLimit::::get() } - pub fn set_tx_rate_limit( tx_rate_limit: u64 ) { TxRateLimit::::put( tx_rate_limit ) } - pub fn do_sudo_set_tx_rate_limit( origin: T::RuntimeOrigin, tx_rate_limit: u64 ) -> DispatchResult { - ensure_root( origin )?; - Self::set_tx_rate_limit( tx_rate_limit ); - log::info!("TxRateLimitSet( tx_rate_limit: {:?} ) ", tx_rate_limit ); - Self::deposit_event( Event::TxRateLimitSet( tx_rate_limit ) ); - Ok(()) - } - - pub fn get_serving_rate_limit( netuid: u16 ) -> u64 { ServingRateLimit::::get(netuid) } - pub fn set_serving_rate_limit( netuid: u16, serving_rate_limit: u64 ) { ServingRateLimit::::insert( netuid, serving_rate_limit ) } - pub fn do_sudo_set_serving_rate_limit( origin: T::RuntimeOrigin, netuid: u16, serving_rate_limit: u64 ) -> DispatchResult { - ensure_root( origin )?; - Self::set_serving_rate_limit( netuid, serving_rate_limit ); - log::info!("ServingRateLimitSet( serving_rate_limit: {:?} ) ", serving_rate_limit ); - Self::deposit_event( Event::ServingRateLimitSet( netuid, serving_rate_limit ) ); - Ok(()) - } - - pub fn get_min_difficulty( netuid: u16) -> u64 { MinDifficulty::::get( netuid ) } - pub fn set_min_difficulty( netuid: u16, min_difficulty: u64 ) { MinDifficulty::::insert( netuid, min_difficulty ); } - pub fn do_sudo_set_min_difficulty( origin: T::RuntimeOrigin, netuid: u16, min_difficulty: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_min_difficulty( netuid, min_difficulty ); - log::info!("MinDifficultySet( netuid: {:?} min_difficulty: {:?} ) ", netuid, min_difficulty); - Self::deposit_event( Event::MinDifficultySet( netuid, min_difficulty) ); - Ok(()) - } - - pub fn get_max_difficulty( netuid: u16) -> u64 { MaxDifficulty::::get( netuid ) } - pub fn set_max_difficulty( netuid: u16, max_difficulty: u64 ) { MaxDifficulty::::insert( netuid, max_difficulty ); } - pub fn do_sudo_set_max_difficulty( origin: T::RuntimeOrigin, netuid: u16, max_difficulty: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_max_difficulty( netuid, max_difficulty ); - log::info!("MaxDifficultySet( netuid: {:?} max_difficulty: {:?} ) ", netuid, max_difficulty); - Self::deposit_event( Event::MaxDifficultySet( netuid, max_difficulty) ); - Ok(()) - } - - pub fn get_weights_version_key( netuid: u16) -> u64 { WeightsVersionKey::::get( netuid ) } - pub fn set_weights_version_key( netuid: u16, weights_version_key: u64 ) { WeightsVersionKey::::insert( netuid, weights_version_key ); } - pub fn do_sudo_set_weights_version_key( origin: T::RuntimeOrigin, netuid: u16, weights_version_key: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_weights_version_key( netuid, weights_version_key ); - log::info!("WeightsVersionKeySet( netuid: {:?} weights_version_key: {:?} ) ", netuid, weights_version_key); - Self::deposit_event( Event::WeightsVersionKeySet( netuid, weights_version_key) ); - Ok(()) - } - - pub fn get_weights_set_rate_limit( netuid: u16) -> u64 { WeightsSetRateLimit::::get( netuid ) } - pub fn set_weights_set_rate_limit( netuid: u16, weights_set_rate_limit: u64 ) { WeightsSetRateLimit::::insert( netuid, weights_set_rate_limit ); } - pub fn do_sudo_set_weights_set_rate_limit( origin: T::RuntimeOrigin, netuid: u16, weights_set_rate_limit: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_weights_set_rate_limit( netuid, weights_set_rate_limit ); - log::info!("WeightsSetRateLimitSet( netuid: {:?} weights_set_rate_limit: {:?} ) ", netuid, weights_set_rate_limit); - Self::deposit_event( Event::WeightsSetRateLimitSet( netuid, weights_set_rate_limit) ); - Ok(()) - } - - pub fn get_adjustment_interval( netuid: u16) -> u16 { AdjustmentInterval::::get( netuid ) } - pub fn set_adjustment_interval( netuid: u16, adjustment_interval: u16 ) { AdjustmentInterval::::insert( netuid, adjustment_interval ); } - pub fn do_sudo_set_adjustment_interval( origin: T::RuntimeOrigin, netuid: u16, adjustment_interval: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_adjustment_interval( netuid, adjustment_interval ); - log::info!("AdjustmentIntervalSet( netuid: {:?} adjustment_interval: {:?} ) ", netuid, adjustment_interval); - Self::deposit_event( Event::AdjustmentIntervalSet( netuid, adjustment_interval) ); - Ok(()) - } - - pub fn get_validator_exclude_quantile( netuid: u16 ) -> u16 { ValidatorExcludeQuantile::::get( netuid ) } - pub fn set_validator_exclude_quantile( netuid: u16, validator_exclude_quantile: u16 ) { ValidatorExcludeQuantile::::insert( netuid, validator_exclude_quantile ); } - pub fn do_sudo_set_validator_exclude_quantile( origin:T::RuntimeOrigin, netuid: u16, validator_exclude_quantile: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); - ensure!( validator_exclude_quantile <= u16::MAX, Error::::StorageValueOutOfRange ); // The quantile must be between 0 and u16::MAX => 0% and 100% - Self::set_validator_exclude_quantile( netuid, validator_exclude_quantile ); - log::info!("ValidatorExcludeQuantileSet( netuid: {:?} validator_exclude_quantile: {:?} ) ", netuid, validator_exclude_quantile); - Self::deposit_event( Event::ValidatorExcludeQuantileSet( netuid, validator_exclude_quantile )); - Ok(()) - } - - pub fn get_validator_prune_len( netuid: u16 ) -> u64 { ValidatorPruneLen::::get( netuid ) } - pub fn set_validator_prune_len( netuid: u16, validator_prune_len: u64 ) { ValidatorPruneLen::::insert( netuid, validator_prune_len ); } - pub fn do_sudo_set_validator_prune_len( origin:T::RuntimeOrigin, netuid: u16, validator_prune_len: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); + Self::deposit_event(Event::DefaultTakeSet(default_take)); + Ok(()) + } + + // Configure tx rate limiting + pub fn get_tx_rate_limit() -> u64 { + TxRateLimit::::get() + } + pub fn set_tx_rate_limit(tx_rate_limit: u64) { + TxRateLimit::::put(tx_rate_limit) + } + pub fn do_sudo_set_tx_rate_limit( + origin: T::RuntimeOrigin, + tx_rate_limit: u64, + ) -> DispatchResult { + ensure_root(origin)?; + Self::set_tx_rate_limit(tx_rate_limit); + log::info!("TxRateLimitSet( tx_rate_limit: {:?} ) ", tx_rate_limit); + Self::deposit_event(Event::TxRateLimitSet(tx_rate_limit)); + Ok(()) + } + + pub fn get_serving_rate_limit(netuid: u16) -> u64 { + ServingRateLimit::::get(netuid) + } + pub fn set_serving_rate_limit(netuid: u16, serving_rate_limit: u64) { + ServingRateLimit::::insert(netuid, serving_rate_limit) + } + pub fn do_sudo_set_serving_rate_limit( + origin: T::RuntimeOrigin, + netuid: u16, + serving_rate_limit: u64, + ) -> DispatchResult { + ensure_root(origin)?; + Self::set_serving_rate_limit(netuid, serving_rate_limit); + log::info!( + "ServingRateLimitSet( serving_rate_limit: {:?} ) ", + serving_rate_limit + ); + Self::deposit_event(Event::ServingRateLimitSet(netuid, serving_rate_limit)); + Ok(()) + } + + pub fn get_min_difficulty(netuid: u16) -> u64 { + MinDifficulty::::get(netuid) + } + pub fn set_min_difficulty(netuid: u16, min_difficulty: u64) { + MinDifficulty::::insert(netuid, min_difficulty); + } + pub fn do_sudo_set_min_difficulty( + origin: T::RuntimeOrigin, + netuid: u16, + min_difficulty: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_min_difficulty(netuid, min_difficulty); + log::info!( + "MinDifficultySet( netuid: {:?} min_difficulty: {:?} ) ", + netuid, + min_difficulty + ); + Self::deposit_event(Event::MinDifficultySet(netuid, min_difficulty)); + Ok(()) + } + + pub fn get_max_difficulty(netuid: u16) -> u64 { + MaxDifficulty::::get(netuid) + } + pub fn set_max_difficulty(netuid: u16, max_difficulty: u64) { + MaxDifficulty::::insert(netuid, max_difficulty); + } + pub fn do_sudo_set_max_difficulty( + origin: T::RuntimeOrigin, + netuid: u16, + max_difficulty: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_max_difficulty(netuid, max_difficulty); + log::info!( + "MaxDifficultySet( netuid: {:?} max_difficulty: {:?} ) ", + netuid, + max_difficulty + ); + Self::deposit_event(Event::MaxDifficultySet(netuid, max_difficulty)); + Ok(()) + } + + pub fn get_weights_version_key(netuid: u16) -> u64 { + WeightsVersionKey::::get(netuid) + } + pub fn set_weights_version_key(netuid: u16, weights_version_key: u64) { + WeightsVersionKey::::insert(netuid, weights_version_key); + } + pub fn do_sudo_set_weights_version_key( + origin: T::RuntimeOrigin, + netuid: u16, + weights_version_key: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_weights_version_key(netuid, weights_version_key); + log::info!( + "WeightsVersionKeySet( netuid: {:?} weights_version_key: {:?} ) ", + netuid, + weights_version_key + ); + Self::deposit_event(Event::WeightsVersionKeySet(netuid, weights_version_key)); + Ok(()) + } + + pub fn get_weights_set_rate_limit(netuid: u16) -> u64 { + WeightsSetRateLimit::::get(netuid) + } + pub fn set_weights_set_rate_limit(netuid: u16, weights_set_rate_limit: u64) { + WeightsSetRateLimit::::insert(netuid, weights_set_rate_limit); + } + pub fn do_sudo_set_weights_set_rate_limit( + origin: T::RuntimeOrigin, + netuid: u16, + weights_set_rate_limit: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_weights_set_rate_limit(netuid, weights_set_rate_limit); + log::info!( + "WeightsSetRateLimitSet( netuid: {:?} weights_set_rate_limit: {:?} ) ", + netuid, + weights_set_rate_limit + ); + Self::deposit_event(Event::WeightsSetRateLimitSet( + netuid, + weights_set_rate_limit, + )); + Ok(()) + } + + pub fn get_adjustment_interval(netuid: u16) -> u16 { + AdjustmentInterval::::get(netuid) + } + pub fn set_adjustment_interval(netuid: u16, adjustment_interval: u16) { + AdjustmentInterval::::insert(netuid, adjustment_interval); + } + pub fn do_sudo_set_adjustment_interval( + origin: T::RuntimeOrigin, + netuid: u16, + adjustment_interval: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_adjustment_interval(netuid, adjustment_interval); + log::info!( + "AdjustmentIntervalSet( netuid: {:?} adjustment_interval: {:?} ) ", + netuid, + adjustment_interval + ); + Self::deposit_event(Event::AdjustmentIntervalSet(netuid, adjustment_interval)); + Ok(()) + } + + pub fn get_adjustment_alpha(netuid: u16) -> u64 { + AdjustmentAlpha::::get(netuid) + } + pub fn set_adjustment_alpha(netuid: u16, adjustment_alpha: u64) { + AdjustmentAlpha::::insert(netuid, adjustment_alpha) + } + pub fn do_sudo_set_adjustment_alpha( + origin: T::RuntimeOrigin, + netuid: u16, + adjustment_alpha: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_adjustment_alpha(netuid, adjustment_alpha); + log::info!( + "AdjustmentAlphaSet( adjustment_alpha: {:?} ) ", + adjustment_alpha + ); + Self::deposit_event(Event::AdjustmentAlphaSet(netuid, adjustment_alpha)); + Ok(()) + } + + pub fn get_validator_exclude_quantile(netuid: u16) -> u16 { + ValidatorExcludeQuantile::::get(netuid) + } + pub fn set_validator_exclude_quantile(netuid: u16, validator_exclude_quantile: u16) { + ValidatorExcludeQuantile::::insert(netuid, validator_exclude_quantile); + } + pub fn do_sudo_set_validator_exclude_quantile( + origin: T::RuntimeOrigin, + netuid: u16, + validator_exclude_quantile: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ensure!( + validator_exclude_quantile <= u16::MAX, + Error::::StorageValueOutOfRange + ); // The quantile must be between 0 and u16::MAX => 0% and 100% + Self::set_validator_exclude_quantile(netuid, validator_exclude_quantile); + log::info!( + "ValidatorExcludeQuantileSet( netuid: {:?} validator_exclude_quantile: {:?} ) ", + netuid, + validator_exclude_quantile + ); + Self::deposit_event(Event::ValidatorExcludeQuantileSet( + netuid, + validator_exclude_quantile, + )); + Ok(()) + } + + pub fn get_validator_prune_len(netuid: u16) -> u64 { + ValidatorPruneLen::::get(netuid) + } + pub fn set_validator_prune_len(netuid: u16, validator_prune_len: u64) { + ValidatorPruneLen::::insert(netuid, validator_prune_len); + } + pub fn do_sudo_set_validator_prune_len( + origin: T::RuntimeOrigin, + netuid: u16, + validator_prune_len: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); Self::set_validator_prune_len(netuid, validator_prune_len); - log::info!("ValidatorPruneLenSet( netuid: {:?} validator_prune_len: {:?} ) ", netuid, validator_prune_len); - Self::deposit_event( Event::ValidatorPruneLenSet( netuid, validator_prune_len )); - Ok(()) + log::info!( + "ValidatorPruneLenSet( netuid: {:?} validator_prune_len: {:?} ) ", + netuid, + validator_prune_len + ); + Self::deposit_event(Event::ValidatorPruneLenSet(netuid, validator_prune_len)); + Ok(()) } - pub fn get_validator_logits_divergence( netuid: u16 ) -> u16 { ValidatorLogitsDivergence::::get( netuid ) } - pub fn set_validator_logits_divergence( netuid: u16, validator_logits_divergence: u16 ) { ValidatorLogitsDivergence::::insert( netuid, validator_logits_divergence ); } - pub fn do_sudo_set_validator_logits_divergence( origin:T::RuntimeOrigin, netuid: u16, validator_logits_divergence: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); + pub fn get_validator_logits_divergence(netuid: u16) -> u16 { + ValidatorLogitsDivergence::::get(netuid) + } + pub fn set_validator_logits_divergence(netuid: u16, validator_logits_divergence: u16) { + ValidatorLogitsDivergence::::insert(netuid, validator_logits_divergence); + } + pub fn do_sudo_set_validator_logits_divergence( + origin: T::RuntimeOrigin, + netuid: u16, + validator_logits_divergence: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); Self::set_validator_logits_divergence(netuid, validator_logits_divergence); - log::info!("ValidatorLogitsDivergenceSet( netuid: {:?} validator_logits_divergence: {:?} ) ", netuid, validator_logits_divergence); - Self::deposit_event( Event::ValidatorLogitsDivergenceSet( netuid, validator_logits_divergence )); + log::info!( + "ValidatorLogitsDivergenceSet( netuid: {:?} validator_logits_divergence: {:?} ) ", + netuid, + validator_logits_divergence + ); + Self::deposit_event(Event::ValidatorLogitsDivergenceSet( + netuid, + validator_logits_divergence, + )); Ok(()) } - pub fn get_scaling_law_power( netuid: u16 ) -> u16 { ScalingLawPower::::get( netuid ) } - pub fn set_scaling_law_power( netuid: u16, scaling_law_power: u16 ) { ScalingLawPower::::insert( netuid, scaling_law_power ); } - pub fn do_sudo_set_scaling_law_power( origin:T::RuntimeOrigin, netuid: u16, scaling_law_power: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); - ensure!( scaling_law_power <= 100, Error::::StorageValueOutOfRange ); // The scaling law power must be between 0 and 100 => 0% and 100% - Self::set_scaling_law_power( netuid, scaling_law_power ); - log::info!("ScalingLawPowerSet( netuid: {:?} scaling_law_power: {:?} ) ", netuid, scaling_law_power); - Self::deposit_event( Event::ScalingLawPowerSet( netuid, scaling_law_power )); + pub fn get_scaling_law_power(netuid: u16) -> u16 { + ScalingLawPower::::get(netuid) + } + pub fn set_scaling_law_power(netuid: u16, scaling_law_power: u16) { + ScalingLawPower::::insert(netuid, scaling_law_power); + } + pub fn do_sudo_set_scaling_law_power( + origin: T::RuntimeOrigin, + netuid: u16, + scaling_law_power: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ensure!(scaling_law_power <= 100, Error::::StorageValueOutOfRange); // The scaling law power must be between 0 and 100 => 0% and 100% + Self::set_scaling_law_power(netuid, scaling_law_power); + log::info!( + "ScalingLawPowerSet( netuid: {:?} scaling_law_power: {:?} ) ", + netuid, + scaling_law_power + ); + Self::deposit_event(Event::ScalingLawPowerSet(netuid, scaling_law_power)); Ok(()) } - pub fn get_synergy_scaling_law_power( netuid: u16 ) -> u16 { SynergyScalingLawPower::::get( netuid ) } - pub fn set_synergy_scaling_law_power( netuid: u16, synergy_scaling_law_power: u16 ) { SynergyScalingLawPower::::insert( netuid, synergy_scaling_law_power ); } - pub fn do_sudo_set_synergy_scaling_law_power( origin:T::RuntimeOrigin, netuid: u16, synergy_scaling_law_power: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); - ensure!( synergy_scaling_law_power <= 100, Error::::StorageValueOutOfRange ); // The synergy scaling law power must be between 0 and 100 => 0% and 100% - Self::set_synergy_scaling_law_power( netuid, synergy_scaling_law_power ); - log::info!("SynergyScalingLawPowerSet( netuid: {:?} synergy_scaling_law_power: {:?} ) ", netuid, synergy_scaling_law_power); - Self::deposit_event( Event::SynergyScalingLawPowerSet( netuid, synergy_scaling_law_power )); + pub fn get_synergy_scaling_law_power(netuid: u16) -> u16 { + SynergyScalingLawPower::::get(netuid) + } + pub fn set_synergy_scaling_law_power(netuid: u16, synergy_scaling_law_power: u16) { + SynergyScalingLawPower::::insert(netuid, synergy_scaling_law_power); + } + pub fn do_sudo_set_synergy_scaling_law_power( + origin: T::RuntimeOrigin, + netuid: u16, + synergy_scaling_law_power: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ensure!( + synergy_scaling_law_power <= 100, + Error::::StorageValueOutOfRange + ); // The synergy scaling law power must be between 0 and 100 => 0% and 100% + Self::set_synergy_scaling_law_power(netuid, synergy_scaling_law_power); + log::info!( + "SynergyScalingLawPowerSet( netuid: {:?} synergy_scaling_law_power: {:?} ) ", + netuid, + synergy_scaling_law_power + ); + Self::deposit_event(Event::SynergyScalingLawPowerSet( + netuid, + synergy_scaling_law_power, + )); Ok(()) } - pub fn get_max_weight_limit( netuid: u16) -> u16 { MaxWeightsLimit::::get( netuid ) } - pub fn set_max_weight_limit( netuid: u16, max_weight_limit: u16 ) { MaxWeightsLimit::::insert( netuid, max_weight_limit ); } - pub fn do_sudo_set_max_weight_limit( origin:T::RuntimeOrigin, netuid: u16, max_weight_limit: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); - Self::set_max_weight_limit( netuid, max_weight_limit ); - log::info!("MaxWeightLimitSet( netuid: {:?} max_weight_limit: {:?} ) ", netuid, max_weight_limit); - Self::deposit_event( Event::MaxWeightLimitSet( netuid, max_weight_limit ) ); + pub fn get_max_weight_limit(netuid: u16) -> u16 { + MaxWeightsLimit::::get(netuid) + } + pub fn set_max_weight_limit(netuid: u16, max_weight_limit: u16) { + MaxWeightsLimit::::insert(netuid, max_weight_limit); + } + pub fn do_sudo_set_max_weight_limit( + origin: T::RuntimeOrigin, + netuid: u16, + max_weight_limit: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_max_weight_limit(netuid, max_weight_limit); + log::info!( + "MaxWeightLimitSet( netuid: {:?} max_weight_limit: {:?} ) ", + netuid, + max_weight_limit + ); + Self::deposit_event(Event::MaxWeightLimitSet(netuid, max_weight_limit)); Ok(()) } - pub fn get_immunity_period(netuid: u16 ) -> u16 { ImmunityPeriod::::get( netuid ) } - pub fn set_immunity_period( netuid: u16, immunity_period: u16 ) { ImmunityPeriod::::insert( netuid, immunity_period ); } - pub fn do_sudo_set_immunity_period( origin:T::RuntimeOrigin, netuid: u16, immunity_period: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_immunity_period( netuid, immunity_period ); - log::info!("ImmunityPeriodSet( netuid: {:?} immunity_period: {:?} ) ", netuid, immunity_period); + pub fn get_immunity_period(netuid: u16) -> u16 { + ImmunityPeriod::::get(netuid) + } + pub fn set_immunity_period(netuid: u16, immunity_period: u16) { + ImmunityPeriod::::insert(netuid, immunity_period); + } + pub fn do_sudo_set_immunity_period( + origin: T::RuntimeOrigin, + netuid: u16, + immunity_period: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_immunity_period(netuid, immunity_period); + log::info!( + "ImmunityPeriodSet( netuid: {:?} immunity_period: {:?} ) ", + netuid, + immunity_period + ); Self::deposit_event(Event::ImmunityPeriodSet(netuid, immunity_period)); Ok(()) } - pub fn get_validator_epochs_per_reset( netuid: u16 )-> u16 { ValidatorEpochsPerReset::::get( netuid ) } - pub fn set_validator_epochs_per_reset( netuid: u16, validator_epochs_per_reset: u16 ) { ValidatorEpochsPerReset::::insert( netuid, validator_epochs_per_reset ); } - pub fn do_sudo_set_validator_epochs_per_reset( origin:T::RuntimeOrigin, netuid: u16, validator_epochs_per_reset: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_validator_epochs_per_reset( netuid, validator_epochs_per_reset ); - log::info!("ValidatorEpochPerResetSet( netuid: {:?} validator_epochs_per_reset: {:?} ) ", netuid, validator_epochs_per_reset ); - Self::deposit_event(Event::ValidatorEpochPerResetSet(netuid, validator_epochs_per_reset)); + pub fn get_validator_epochs_per_reset(netuid: u16) -> u16 { + ValidatorEpochsPerReset::::get(netuid) + } + pub fn set_validator_epochs_per_reset(netuid: u16, validator_epochs_per_reset: u16) { + ValidatorEpochsPerReset::::insert(netuid, validator_epochs_per_reset); + } + pub fn do_sudo_set_validator_epochs_per_reset( + origin: T::RuntimeOrigin, + netuid: u16, + validator_epochs_per_reset: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_validator_epochs_per_reset(netuid, validator_epochs_per_reset); + log::info!( + "ValidatorEpochPerResetSet( netuid: {:?} validator_epochs_per_reset: {:?} ) ", + netuid, + validator_epochs_per_reset + ); + Self::deposit_event(Event::ValidatorEpochPerResetSet( + netuid, + validator_epochs_per_reset, + )); Ok(()) } - pub fn get_validator_sequence_length( netuid: u16 )-> u16 {ValidatorSequenceLength::::get( netuid ) } - pub fn set_validator_sequence_length( netuid: u16, validator_sequence_length: u16 ) { ValidatorSequenceLength::::insert( netuid, validator_sequence_length ); } - pub fn do_sudo_set_validator_sequence_length( origin:T::RuntimeOrigin, netuid: u16, validator_sequence_length: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - ValidatorSequenceLength::::insert( netuid, validator_sequence_length ); - log::info!("ValidatorSequenceLengthSet( netuid: {:?} validator_sequence_length: {:?} ) ", netuid, validator_sequence_length ); - Self::deposit_event(Event::ValidatorSequenceLengthSet(netuid, validator_sequence_length)); + pub fn get_validator_sequence_length(netuid: u16) -> u16 { + ValidatorSequenceLength::::get(netuid) + } + pub fn set_validator_sequence_length(netuid: u16, validator_sequence_length: u16) { + ValidatorSequenceLength::::insert(netuid, validator_sequence_length); + } + pub fn do_sudo_set_validator_sequence_length( + origin: T::RuntimeOrigin, + netuid: u16, + validator_sequence_length: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ValidatorSequenceLength::::insert(netuid, validator_sequence_length); + log::info!( + "ValidatorSequenceLengthSet( netuid: {:?} validator_sequence_length: {:?} ) ", + netuid, + validator_sequence_length + ); + Self::deposit_event(Event::ValidatorSequenceLengthSet( + netuid, + validator_sequence_length, + )); Ok(()) } - - pub fn get_validator_epoch_length( netuid: u16 )-> u16 {ValidatorEpochLen::::get( netuid ) } - pub fn set_validator_epoch_length( netuid: u16, validator_epoch_length: u16 ) { ValidatorEpochLen::::insert( netuid, validator_epoch_length ); } - pub fn do_sudo_set_validator_epoch_length( origin:T::RuntimeOrigin, netuid: u16, validator_epoch_length: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - ValidatorEpochLen::::insert( netuid, validator_epoch_length ); - log::info!("ValidatorEpochLengthSet( netuid: {:?} validator_epoch_length: {:?} ) ", netuid, validator_epoch_length ); - Self::deposit_event(Event::ValidatorEpochLengthSet(netuid, validator_epoch_length)); + pub fn get_validator_epoch_length(netuid: u16) -> u16 { + ValidatorEpochLen::::get(netuid) + } + pub fn set_validator_epoch_length(netuid: u16, validator_epoch_length: u16) { + ValidatorEpochLen::::insert(netuid, validator_epoch_length); + } + pub fn do_sudo_set_validator_epoch_length( + origin: T::RuntimeOrigin, + netuid: u16, + validator_epoch_length: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ValidatorEpochLen::::insert(netuid, validator_epoch_length); + log::info!( + "ValidatorEpochLengthSet( netuid: {:?} validator_epoch_length: {:?} ) ", + netuid, + validator_epoch_length + ); + Self::deposit_event(Event::ValidatorEpochLengthSet( + netuid, + validator_epoch_length, + )); Ok(()) } - pub fn get_validator_batch_size( netuid: u16 ) -> u16 { ValidatorBatchSize::::get( netuid ) } - pub fn set_validator_batch_size( netuid: u16, validator_batch_size: u16 ) { ValidatorBatchSize::::insert( netuid, validator_batch_size ); } - pub fn do_sudo_set_validator_batch_size( origin:T::RuntimeOrigin, netuid: u16, validator_batch_size: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_validator_batch_size( netuid, validator_batch_size ); - log::info!("ValidatorBatchSizeSet( netuid: {:?} validator_batch_size: {:?} ) ", netuid, validator_batch_size); + pub fn get_validator_batch_size(netuid: u16) -> u16 { + ValidatorBatchSize::::get(netuid) + } + pub fn set_validator_batch_size(netuid: u16, validator_batch_size: u16) { + ValidatorBatchSize::::insert(netuid, validator_batch_size); + } + pub fn do_sudo_set_validator_batch_size( + origin: T::RuntimeOrigin, + netuid: u16, + validator_batch_size: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_validator_batch_size(netuid, validator_batch_size); + log::info!( + "ValidatorBatchSizeSet( netuid: {:?} validator_batch_size: {:?} ) ", + netuid, + validator_batch_size + ); Self::deposit_event(Event::ValidatorBatchSizeSet(netuid, validator_batch_size)); Ok(()) } - - pub fn get_min_allowed_weights( netuid:u16 ) -> u16 { MinAllowedWeights::::get( netuid ) } - pub fn set_min_allowed_weights( netuid: u16, min_allowed_weights: u16 ) { MinAllowedWeights::::insert( netuid, min_allowed_weights ); } - pub fn do_sudo_set_min_allowed_weights( origin:T::RuntimeOrigin, netuid: u16, min_allowed_weights: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_min_allowed_weights( netuid, min_allowed_weights ); - log::info!("MinAllowedWeightSet( netuid: {:?} min_allowed_weights: {:?} ) ", netuid, min_allowed_weights); - Self::deposit_event( Event::MinAllowedWeightSet( netuid, min_allowed_weights) ); - Ok(()) - } - - pub fn get_max_allowed_uids( netuid: u16 ) -> u16 { MaxAllowedUids::::get( netuid ) } - pub fn set_max_allowed_uids(netuid: u16, max_allowed: u16) { MaxAllowedUids::::insert( netuid, max_allowed ); } - pub fn do_sudo_set_max_allowed_uids( origin:T::RuntimeOrigin, netuid: u16, max_allowed_uids: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!( Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist ); - ensure!( Self::get_subnetwork_n(netuid) < max_allowed_uids, Error::::MaxAllowedUIdsNotAllowed); - Self::set_max_allowed_uids( netuid, max_allowed_uids ); - log::info!("MaxAllowedUidsSet( netuid: {:?} max_allowed_uids: {:?} ) ", netuid, max_allowed_uids); - Self::deposit_event( Event::MaxAllowedUidsSet( netuid, max_allowed_uids) ); - Ok(()) - } - - pub fn get_kappa( netuid: u16 ) -> u16 { Kappa::::get( netuid ) } - pub fn set_kappa( netuid: u16, kappa: u16 ) { Kappa::::insert( netuid, kappa ); } - pub fn do_sudo_set_kappa( origin:T::RuntimeOrigin, netuid: u16, kappa: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_kappa( netuid, kappa ); - log::info!("KappaSet( netuid: {:?} kappa: {:?} ) ", netuid, kappa ); - Self::deposit_event( Event::KappaSet( netuid, kappa) ); - Ok(()) - } - - pub fn get_rho( netuid: u16 ) -> u16 { Rho::::get( netuid ) } - pub fn set_rho( netuid: u16, rho: u16 ) { Rho::::insert( netuid, rho ); } - pub fn do_sudo_set_rho( origin:T::RuntimeOrigin, netuid: u16, rho: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_rho( netuid, rho ); - log::info!("RhoSet( netuid: {:?} rho: {:?} ) ", netuid, rho ); - Self::deposit_event( Event::RhoSet( netuid, rho ) ); - Ok(()) - } - - pub fn get_activity_cutoff( netuid: u16 ) -> u16 { ActivityCutoff::::get( netuid ) } - pub fn set_activity_cutoff( netuid: u16, activity_cutoff: u16 ) { ActivityCutoff::::insert( netuid, activity_cutoff ); } - pub fn do_sudo_set_activity_cutoff( origin:T::RuntimeOrigin, netuid: u16, activity_cutoff: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_activity_cutoff( netuid, activity_cutoff ); - log::info!("ActivityCutoffSet( netuid: {:?} activity_cutoff: {:?} ) ", netuid, activity_cutoff); - Self::deposit_event( Event::ActivityCutoffSet( netuid, activity_cutoff) ); - Ok(()) - } - - // Registration Toggle utils - pub fn get_network_registration_allowed( netuid: u16 ) -> bool { NetworkRegistrationAllowed::::get( netuid ) } - pub fn set_network_registration_allowed( netuid: u16, registration_allowed: bool ) { NetworkRegistrationAllowed::::insert( netuid, registration_allowed ) } - pub fn do_sudo_set_network_registration_allowed( origin: T::RuntimeOrigin, netuid: u16, registration_allowed: bool ) -> DispatchResult { - ensure_root( origin )?; - Self::set_network_registration_allowed( netuid, registration_allowed ); - log::info!("NetworkRegistrationAllowed( registration_allowed: {:?} ) ", registration_allowed ); - Self::deposit_event( Event::RegistrationAllowed( netuid, registration_allowed ) ); - Ok(()) - } - - pub fn get_target_registrations_per_interval( netuid: u16 ) -> u16 { TargetRegistrationsPerInterval::::get( netuid ) } - pub fn set_target_registrations_per_interval( netuid: u16, target_registrations_per_interval: u16 ) { TargetRegistrationsPerInterval::::insert( netuid, target_registrations_per_interval ); } - pub fn do_sudo_set_target_registrations_per_interval( origin:T::RuntimeOrigin, netuid: u16, target_registrations_per_interval: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_target_registrations_per_interval( netuid, target_registrations_per_interval ); - log::info!("RegistrationPerIntervalSet( netuid: {:?} target_registrations_per_interval: {:?} ) ", netuid, target_registrations_per_interval ); - Self::deposit_event( Event::RegistrationPerIntervalSet( netuid, target_registrations_per_interval) ); - Ok(()) - } - - pub fn get_burn_as_u64( netuid: u16 ) -> u64 { Burn::::get( netuid ) } - pub fn set_burn( netuid: u16, burn: u64 ) { Burn::::insert( netuid, burn ); } - pub fn do_sudo_set_burn( origin:T::RuntimeOrigin, netuid: u16, burn: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_burn( netuid, burn ); - log::info!("BurnSet( netuid: {:?} burn: {:?} ) ", netuid, burn ); - Self::deposit_event( Event::BurnSet( netuid, burn ) ); - Ok(()) - } - - pub fn get_min_burn_as_u64( netuid: u16 ) -> u64 { MinBurn::::get( netuid ) } - pub fn set_min_burn( netuid: u16, min_burn: u64 ) { MinBurn::::insert( netuid, min_burn ); } - pub fn do_sudo_set_min_burn( origin:T::RuntimeOrigin, netuid: u16, min_burn: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_min_burn( netuid, min_burn ); - log::info!("MinBurnSet( netuid: {:?} min_burn: {:?} ) ", netuid, min_burn ); - Self::deposit_event( Event::MinBurnSet( netuid, min_burn ) ); - Ok(()) - } - - pub fn get_max_burn_as_u64( netuid: u16 ) -> u64 { MaxBurn::::get( netuid ) } - pub fn set_max_burn( netuid: u16, max_burn: u64 ) { MaxBurn::::insert( netuid, max_burn ); } - pub fn do_sudo_set_max_burn( origin:T::RuntimeOrigin, netuid: u16, max_burn: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_max_burn( netuid, max_burn ); - log::info!("MaxBurnSet( netuid: {:?} max_burn: {:?} ) ", netuid, max_burn ); - Self::deposit_event( Event::MaxBurnSet( netuid, max_burn ) ); - Ok(()) - } - - pub fn get_difficulty_as_u64( netuid: u16 ) -> u64 { Difficulty::::get( netuid ) } - pub fn set_difficulty( netuid: u16, difficulty: u64 ) { Difficulty::::insert( netuid, difficulty ); } - pub fn do_sudo_set_difficulty( origin:T::RuntimeOrigin, netuid: u16, difficulty: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_difficulty( netuid, difficulty ); - log::info!("DifficultySet( netuid: {:?} difficulty: {:?} ) ", netuid, difficulty ); - Self::deposit_event( Event::DifficultySet( netuid, difficulty ) ); - Ok(()) - } - - pub fn get_max_allowed_validators( netuid: u16 ) -> u16 { MaxAllowedValidators::::get( netuid ) } - pub fn set_max_allowed_validators( netuid: u16, max_allowed_validators: u16 ) { MaxAllowedValidators::::insert( netuid, max_allowed_validators ); } - pub fn do_sudo_set_max_allowed_validators( origin:T::RuntimeOrigin, netuid: u16, max_allowed_validators: u16 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_max_allowed_validators( netuid, max_allowed_validators ); - log::info!("MaxAllowedValidatorsSet( netuid: {:?} max_allowed_validators: {:?} ) ", netuid, max_allowed_validators ); - Self::deposit_event( Event::MaxAllowedValidatorsSet( netuid, max_allowed_validators ) ); - Ok(()) - } - - pub fn get_bonds_moving_average( netuid: u16 ) -> u64 { BondsMovingAverage::::get( netuid ) } - pub fn set_bonds_moving_average( netuid: u16, bonds_moving_average: u64 ) { BondsMovingAverage::::insert( netuid, bonds_moving_average ); } - pub fn do_sudo_set_bonds_moving_average( origin:T::RuntimeOrigin, netuid: u16, bonds_moving_average: u64 ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_bonds_moving_average( netuid, bonds_moving_average ); - log::info!("BondsMovingAverageSet( netuid: {:?} bonds_moving_average: {:?} ) ", netuid, bonds_moving_average ); - Self::deposit_event( Event::BondsMovingAverageSet( netuid, bonds_moving_average ) ); - Ok(()) - } - - pub fn get_max_registrations_per_block( netuid: u16 ) -> u16 { MaxRegistrationsPerBlock::::get( netuid ) } - pub fn set_max_registrations_per_block( netuid: u16, max_registrations_per_block: u16 ) { MaxRegistrationsPerBlock::::insert( netuid, max_registrations_per_block ); } - pub fn do_sudo_set_max_registrations_per_block( - origin: T::RuntimeOrigin, - netuid: u16, - max_registrations_per_block: u16 + + pub fn get_min_allowed_weights(netuid: u16) -> u16 { + MinAllowedWeights::::get(netuid) + } + pub fn set_min_allowed_weights(netuid: u16, min_allowed_weights: u16) { + MinAllowedWeights::::insert(netuid, min_allowed_weights); + } + pub fn do_sudo_set_min_allowed_weights( + origin: T::RuntimeOrigin, + netuid: u16, + min_allowed_weights: u16, ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_max_registrations_per_block( netuid, max_registrations_per_block ); - log::info!("MaxRegistrationsPerBlock( netuid: {:?} max_registrations_per_block: {:?} ) ", netuid, max_registrations_per_block ); - Self::deposit_event( Event::MaxRegistrationsPerBlockSet( netuid, max_registrations_per_block) ); + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_min_allowed_weights(netuid, min_allowed_weights); + log::info!( + "MinAllowedWeightSet( netuid: {:?} min_allowed_weights: {:?} ) ", + netuid, + min_allowed_weights + ); + Self::deposit_event(Event::MinAllowedWeightSet(netuid, min_allowed_weights)); Ok(()) } - pub fn do_sudo_set_tempo ( - origin: T::RuntimeOrigin, - netuid: u16, - tempo: u16 + + pub fn get_max_allowed_uids(netuid: u16) -> u16 { + MaxAllowedUids::::get(netuid) + } + pub fn set_max_allowed_uids(netuid: u16, max_allowed: u16) { + MaxAllowedUids::::insert(netuid, max_allowed); + } + pub fn do_sudo_set_max_allowed_uids( + origin: T::RuntimeOrigin, + netuid: u16, + max_allowed_uids: u16, ) -> DispatchResult { - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - ensure!( Self::if_tempo_is_valid( tempo ), Error::::InvalidTempo ); - Self::set_tempo(netuid, tempo); - log::info!("TempoSet( netuid: {:?} tempo: {:?} ) ", netuid, tempo ); - Self::deposit_event( Event::TempoSet(netuid, tempo) ); + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ensure!( + Self::get_subnetwork_n(netuid) < max_allowed_uids, + Error::::MaxAllowedUIdsNotAllowed + ); + Self::set_max_allowed_uids(netuid, max_allowed_uids); + log::info!( + "MaxAllowedUidsSet( netuid: {:?} max_allowed_uids: {:?} ) ", + netuid, + max_allowed_uids + ); + Self::deposit_event(Event::MaxAllowedUidsSet(netuid, max_allowed_uids)); Ok(()) } - pub fn do_set_total_issuance(origin: T::RuntimeOrigin, total_issuance: u64) -> DispatchResult{ - ensure_root( origin )?; - TotalIssuance::::put( total_issuance ); + + pub fn get_kappa(netuid: u16) -> u16 { + Kappa::::get(netuid) + } + pub fn set_kappa(netuid: u16, kappa: u16) { + Kappa::::insert(netuid, kappa); + } + pub fn do_sudo_set_kappa(origin: T::RuntimeOrigin, netuid: u16, kappa: u16) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_kappa(netuid, kappa); + log::info!("KappaSet( netuid: {:?} kappa: {:?} ) ", netuid, kappa); + Self::deposit_event(Event::KappaSet(netuid, kappa)); Ok(()) } - pub fn get_rao_recycled( netuid: u16 ) -> u64 { - RAORecycledForRegistration::::get( netuid ) + pub fn get_rho(netuid: u16) -> u16 { + Rho::::get(netuid) + } + pub fn set_rho(netuid: u16, rho: u16) { + Rho::::insert(netuid, rho); } - pub fn set_rao_recycled( netuid: u16, rao_recycled: u64 ) { - RAORecycledForRegistration::::insert( netuid, rao_recycled ); + pub fn do_sudo_set_rho(origin: T::RuntimeOrigin, netuid: u16, rho: u16) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_rho(netuid, rho); + log::info!("RhoSet( netuid: {:?} rho: {:?} ) ", netuid, rho); + Self::deposit_event(Event::RhoSet(netuid, rho)); + Ok(()) } - pub fn increase_rao_recycled( netuid: u16, inc_rao_recycled: u64 ) { - let curr_rao_recycled = Self::get_rao_recycled( netuid ); - let rao_recycled = curr_rao_recycled.saturating_add( inc_rao_recycled ); - Self::set_rao_recycled( netuid, rao_recycled ); + + pub fn get_activity_cutoff(netuid: u16) -> u16 { + ActivityCutoff::::get(netuid) } - pub fn do_set_rao_recycled(origin: T::RuntimeOrigin, netuid: u16, rao_recycled: u64) -> DispatchResult{ - ensure_root( origin )?; - ensure!(Self::if_subnet_exist(netuid), Error::::NetworkDoesNotExist); - Self::set_rao_recycled( netuid, rao_recycled ); - Self::deposit_event( Event::RAORecycledForRegistrationSet( netuid, rao_recycled ) ); + pub fn set_activity_cutoff(netuid: u16, activity_cutoff: u16) { + ActivityCutoff::::insert(netuid, activity_cutoff); + } + pub fn do_sudo_set_activity_cutoff( + origin: T::RuntimeOrigin, + netuid: u16, + activity_cutoff: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_activity_cutoff(netuid, activity_cutoff); + log::info!( + "ActivityCutoffSet( netuid: {:?} activity_cutoff: {:?} ) ", + netuid, + activity_cutoff + ); + Self::deposit_event(Event::ActivityCutoffSet(netuid, activity_cutoff)); Ok(()) } - pub fn set_senate_required_stake_perc( required_percent: u64 ) { - SenateRequiredStakePercentage::::put( required_percent ); + // Registration Toggle utils + pub fn get_network_registration_allowed(netuid: u16) -> bool { + NetworkRegistrationAllowed::::get(netuid) + } + pub fn set_network_registration_allowed(netuid: u16, registration_allowed: bool) { + NetworkRegistrationAllowed::::insert(netuid, registration_allowed) + } + pub fn do_sudo_set_network_registration_allowed( + origin: T::RuntimeOrigin, + netuid: u16, + registration_allowed: bool, + ) -> DispatchResult { + ensure_root(origin)?; + Self::set_network_registration_allowed(netuid, registration_allowed); + log::info!( + "NetworkRegistrationAllowed( registration_allowed: {:?} ) ", + registration_allowed + ); + Self::deposit_event(Event::RegistrationAllowed(netuid, registration_allowed)); + Ok(()) } - pub fn do_set_senate_required_stake_perc(origin: T::RuntimeOrigin, required_percent: u64) -> DispatchResult { - ensure_root( origin )?; + pub fn get_target_registrations_per_interval(netuid: u16) -> u16 { + TargetRegistrationsPerInterval::::get(netuid) + } + pub fn set_target_registrations_per_interval( + netuid: u16, + target_registrations_per_interval: u16, + ) { + TargetRegistrationsPerInterval::::insert(netuid, target_registrations_per_interval); + } + pub fn do_sudo_set_target_registrations_per_interval( + origin: T::RuntimeOrigin, + netuid: u16, + target_registrations_per_interval: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_target_registrations_per_interval(netuid, target_registrations_per_interval); + log::info!( + "RegistrationPerIntervalSet( netuid: {:?} target_registrations_per_interval: {:?} ) ", + netuid, + target_registrations_per_interval + ); + Self::deposit_event(Event::RegistrationPerIntervalSet( + netuid, + target_registrations_per_interval, + )); + Ok(()) + } - Self::set_senate_required_stake_perc( required_percent ); - Self::deposit_event( Event::SenateRequiredStakePercentSet( required_percent ) ); + pub fn get_burn_as_u64(netuid: u16) -> u64 { + Burn::::get(netuid) + } + pub fn set_burn(netuid: u16, burn: u64) { + Burn::::insert(netuid, burn); + } + pub fn do_sudo_set_burn(origin: T::RuntimeOrigin, netuid: u16, burn: u64) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_burn(netuid, burn); + log::info!("BurnSet( netuid: {:?} burn: {:?} ) ", netuid, burn); + Self::deposit_event(Event::BurnSet(netuid, burn)); + Ok(()) + } + + pub fn get_min_burn_as_u64(netuid: u16) -> u64 { + MinBurn::::get(netuid) + } + pub fn set_min_burn(netuid: u16, min_burn: u64) { + MinBurn::::insert(netuid, min_burn); + } + pub fn do_sudo_set_min_burn( + origin: T::RuntimeOrigin, + netuid: u16, + min_burn: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_min_burn(netuid, min_burn); + log::info!( + "MinBurnSet( netuid: {:?} min_burn: {:?} ) ", + netuid, + min_burn + ); + Self::deposit_event(Event::MinBurnSet(netuid, min_burn)); + Ok(()) + } + + pub fn get_max_burn_as_u64(netuid: u16) -> u64 { + MaxBurn::::get(netuid) + } + pub fn set_max_burn(netuid: u16, max_burn: u64) { + MaxBurn::::insert(netuid, max_burn); + } + pub fn do_sudo_set_max_burn( + origin: T::RuntimeOrigin, + netuid: u16, + max_burn: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_max_burn(netuid, max_burn); + log::info!( + "MaxBurnSet( netuid: {:?} max_burn: {:?} ) ", + netuid, + max_burn + ); + Self::deposit_event(Event::MaxBurnSet(netuid, max_burn)); + Ok(()) + } + + pub fn get_difficulty_as_u64(netuid: u16) -> u64 { + Difficulty::::get(netuid) + } + pub fn set_difficulty(netuid: u16, difficulty: u64) { + Difficulty::::insert(netuid, difficulty); + } + pub fn do_sudo_set_difficulty( + origin: T::RuntimeOrigin, + netuid: u16, + difficulty: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_difficulty(netuid, difficulty); + log::info!( + "DifficultySet( netuid: {:?} difficulty: {:?} ) ", + netuid, + difficulty + ); + Self::deposit_event(Event::DifficultySet(netuid, difficulty)); + Ok(()) + } + + pub fn get_max_allowed_validators(netuid: u16) -> u16 { + MaxAllowedValidators::::get(netuid) + } + pub fn set_max_allowed_validators(netuid: u16, max_allowed_validators: u16) { + MaxAllowedValidators::::insert(netuid, max_allowed_validators); + } + pub fn do_sudo_set_max_allowed_validators( + origin: T::RuntimeOrigin, + netuid: u16, + max_allowed_validators: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_max_allowed_validators(netuid, max_allowed_validators); + log::info!( + "MaxAllowedValidatorsSet( netuid: {:?} max_allowed_validators: {:?} ) ", + netuid, + max_allowed_validators + ); + Self::deposit_event(Event::MaxAllowedValidatorsSet( + netuid, + max_allowed_validators, + )); + Ok(()) + } + + pub fn get_bonds_moving_average(netuid: u16) -> u64 { + BondsMovingAverage::::get(netuid) + } + pub fn set_bonds_moving_average(netuid: u16, bonds_moving_average: u64) { + BondsMovingAverage::::insert(netuid, bonds_moving_average); + } + pub fn do_sudo_set_bonds_moving_average( + origin: T::RuntimeOrigin, + netuid: u16, + bonds_moving_average: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_bonds_moving_average(netuid, bonds_moving_average); + log::info!( + "BondsMovingAverageSet( netuid: {:?} bonds_moving_average: {:?} ) ", + netuid, + bonds_moving_average + ); + Self::deposit_event(Event::BondsMovingAverageSet(netuid, bonds_moving_average)); Ok(()) } -} + pub fn get_max_registrations_per_block(netuid: u16) -> u16 { + MaxRegistrationsPerBlock::::get(netuid) + } + pub fn set_max_registrations_per_block(netuid: u16, max_registrations_per_block: u16) { + MaxRegistrationsPerBlock::::insert(netuid, max_registrations_per_block); + } + pub fn do_sudo_set_max_registrations_per_block( + origin: T::RuntimeOrigin, + netuid: u16, + max_registrations_per_block: u16, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_max_registrations_per_block(netuid, max_registrations_per_block); + log::info!( + "MaxRegistrationsPerBlock( netuid: {:?} max_registrations_per_block: {:?} ) ", + netuid, + max_registrations_per_block + ); + Self::deposit_event(Event::MaxRegistrationsPerBlockSet( + netuid, + max_registrations_per_block, + )); + Ok(()) + } + pub fn do_sudo_set_tempo(origin: T::RuntimeOrigin, netuid: u16, tempo: u16) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + ensure!(Self::if_tempo_is_valid(tempo), Error::::InvalidTempo); + Self::set_tempo(netuid, tempo); + log::info!("TempoSet( netuid: {:?} tempo: {:?} ) ", netuid, tempo); + Self::deposit_event(Event::TempoSet(netuid, tempo)); + Ok(()) + } + pub fn do_set_total_issuance(origin: T::RuntimeOrigin, total_issuance: u64) -> DispatchResult { + ensure_root(origin)?; + TotalIssuance::::put(total_issuance); + Ok(()) + } + + pub fn get_rao_recycled(netuid: u16) -> u64 { + RAORecycledForRegistration::::get(netuid) + } + pub fn set_rao_recycled(netuid: u16, rao_recycled: u64) { + RAORecycledForRegistration::::insert(netuid, rao_recycled); + } + pub fn increase_rao_recycled(netuid: u16, inc_rao_recycled: u64) { + let curr_rao_recycled = Self::get_rao_recycled(netuid); + let rao_recycled = curr_rao_recycled.saturating_add(inc_rao_recycled); + Self::set_rao_recycled(netuid, rao_recycled); + } + pub fn do_set_rao_recycled( + origin: T::RuntimeOrigin, + netuid: u16, + rao_recycled: u64, + ) -> DispatchResult { + ensure_root(origin)?; + ensure!( + Self::if_subnet_exist(netuid), + Error::::NetworkDoesNotExist + ); + Self::set_rao_recycled(netuid, rao_recycled); + Self::deposit_event(Event::RAORecycledForRegistrationSet(netuid, rao_recycled)); + Ok(()) + } + + pub fn set_senate_required_stake_perc(required_percent: u64) { + SenateRequiredStakePercentage::::put(required_percent); + } + pub fn do_set_senate_required_stake_perc( + origin: T::RuntimeOrigin, + required_percent: u64, + ) -> DispatchResult { + ensure_root(origin)?; + Self::set_senate_required_stake_perc(required_percent); + Self::deposit_event(Event::SenateRequiredStakePercentSet(required_percent)); + Ok(()) + } +} diff --git a/pallets/subtensor/tests/block_step.rs b/pallets/subtensor/tests/block_step.rs index 1eca57174..d87cbf286 100644 --- a/pallets/subtensor/tests/block_step.rs +++ b/pallets/subtensor/tests/block_step.rs @@ -6,79 +6,119 @@ use sp_core::U256; #[test] fn test_loaded_emission() { - new_test_ext().execute_with(|| { + new_test_ext().execute_with(|| { let n: u16 = 100; let netuid: u16 = 0; let tempo: u16 = 10; let netuids: Vec = vec![0]; - let emission: Vec = vec![1000000000]; - add_network( netuid, tempo, 0 ); - SubtensorModule::set_max_allowed_uids( netuid, n ); - assert_ok!(SubtensorModule::do_set_emission_values(<::RuntimeOrigin>::root(), netuids, emission)); - for i in 0..n {SubtensorModule::append_neuron( netuid, &U256::from(i), 0 );} - assert!( !SubtensorModule::has_loaded_emission_tuples( netuid ) ); + let emission: Vec = vec![1000000000]; + add_network(netuid, tempo, 0); + SubtensorModule::set_max_allowed_uids(netuid, n); + assert_ok!(SubtensorModule::do_set_emission_values( + <::RuntimeOrigin>::root(), + netuids, + emission + )); + for i in 0..n { + SubtensorModule::append_neuron(netuid, &U256::from(i), 0); + } + assert!(!SubtensorModule::has_loaded_emission_tuples(netuid)); // Try loading at block 0 let block: u64 = 0; - assert_eq!( SubtensorModule::blocks_until_next_epoch( netuid, tempo, block ), 9 ); - SubtensorModule::generate_emission( block ); - assert!( !SubtensorModule::has_loaded_emission_tuples( netuid ) ); + assert_eq!( + SubtensorModule::blocks_until_next_epoch(netuid, tempo, block), + 9 + ); + SubtensorModule::generate_emission(block); + assert!(!SubtensorModule::has_loaded_emission_tuples(netuid)); // Try loading at block = 9; let block: u64 = 9; - assert_eq!( SubtensorModule::blocks_until_next_epoch( netuid, tempo, block ), 0 ); - SubtensorModule::generate_emission( block ); - assert!( SubtensorModule::has_loaded_emission_tuples( netuid ) ); - assert_eq!( SubtensorModule::get_loaded_emission_tuples( netuid ).len(), n as usize ); + assert_eq!( + SubtensorModule::blocks_until_next_epoch(netuid, tempo, block), + 0 + ); + SubtensorModule::generate_emission(block); + assert!(SubtensorModule::has_loaded_emission_tuples(netuid)); + assert_eq!( + SubtensorModule::get_loaded_emission_tuples(netuid).len(), + n as usize + ); // Try draining the emission tuples // None remaining because we are at epoch. let block: u64 = 9; - SubtensorModule::drain_emission( block ); - assert!( !SubtensorModule::has_loaded_emission_tuples( netuid ) ); + SubtensorModule::drain_emission(block); + assert!(!SubtensorModule::has_loaded_emission_tuples(netuid)); // Generate more emission. - SubtensorModule::generate_emission( 9 ); - assert_eq!( SubtensorModule::get_loaded_emission_tuples( netuid ).len(), n as usize ); - + SubtensorModule::generate_emission(9); + assert_eq!( + SubtensorModule::get_loaded_emission_tuples(netuid).len(), + n as usize + ); + for block in 10..20 { let mut n_remaining: usize = 0; let mut n_to_drain: usize = 0; - if SubtensorModule::has_loaded_emission_tuples( netuid ) { - n_remaining = SubtensorModule::get_loaded_emission_tuples( netuid ).len(); - n_to_drain = SubtensorModule::tuples_to_drain_this_block( netuid, tempo, block, SubtensorModule::get_loaded_emission_tuples( netuid ).len() ); + if SubtensorModule::has_loaded_emission_tuples(netuid) { + n_remaining = SubtensorModule::get_loaded_emission_tuples(netuid).len(); + n_to_drain = SubtensorModule::tuples_to_drain_this_block( + netuid, + tempo, + block, + SubtensorModule::get_loaded_emission_tuples(netuid).len(), + ); } - SubtensorModule::drain_emission( block ); // drain it with 9 more blocks to go - if SubtensorModule::has_loaded_emission_tuples( netuid ) { - assert_eq!( SubtensorModule::get_loaded_emission_tuples( netuid ).len(), n_remaining - n_to_drain ); + SubtensorModule::drain_emission(block); // drain it with 9 more blocks to go + if SubtensorModule::has_loaded_emission_tuples(netuid) { + assert_eq!( + SubtensorModule::get_loaded_emission_tuples(netuid).len(), + n_remaining - n_to_drain + ); } - log::info!( "n_to_drain:{:?}", n_to_drain.clone() ); - log::info!( "SubtensorModule::get_loaded_emission_tuples( netuid ).len():{:?}", n_remaining - n_to_drain ); + log::info!("n_to_drain:{:?}", n_to_drain.clone()); + log::info!( + "SubtensorModule::get_loaded_emission_tuples( netuid ).len():{:?}", + n_remaining - n_to_drain + ); } - }) } #[test] -fn test_tuples_to_drain_this_block(){ - new_test_ext().execute_with(|| { +fn test_tuples_to_drain_this_block() { + new_test_ext().execute_with(|| { // pub fn tuples_to_drain_this_block( netuid: u16, tempo: u16, block_number: u64, n_remaining: usize ) -> usize { - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 1, 0, 10 ), 10 ); // drain all epoch block. - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 0, 0, 10 ), 10 ); // drain all no tempo. - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 0, 10 ), 2 ); // drain 10 / ( 10 / 2 ) = 2 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 20, 0, 10 ), 1 ); // drain 10 / ( 20 / 2 ) = 1 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 0, 20 ), 5 ); // drain 20 / ( 9 / 2 ) = 5 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 20, 0, 0 ), 0 ); // nothing to drain. - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 1, 20 ), 5 ); // drain 19 / ( 10 / 2 ) = 4 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 10, 20 ), 4 ); // drain 19 / ( 10 / 2 ) = 4 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 15, 20 ), 10 ); // drain 19 / ( 10 / 2 ) = 4 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 19, 20 ), 20 ); // drain 19 / ( 10 / 2 ) = 4 - assert_eq!( SubtensorModule::tuples_to_drain_this_block( 0, 10, 20, 20 ), 20 ); // drain 19 / ( 10 / 2 ) = 4 + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 1, 0, 10), 10); // drain all epoch block. + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 0, 0, 10), 10); // drain all no tempo. + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 10, 0, 10), 2); // drain 10 / ( 10 / 2 ) = 2 + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 20, 0, 10), 1); // drain 10 / ( 20 / 2 ) = 1 + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 10, 0, 20), 5); // drain 20 / ( 9 / 2 ) = 5 + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 20, 0, 0), 0); // nothing to drain. + assert_eq!(SubtensorModule::tuples_to_drain_this_block(0, 10, 1, 20), 5); // drain 19 / ( 10 / 2 ) = 4 + assert_eq!( + SubtensorModule::tuples_to_drain_this_block(0, 10, 10, 20), + 4 + ); // drain 19 / ( 10 / 2 ) = 4 + assert_eq!( + SubtensorModule::tuples_to_drain_this_block(0, 10, 15, 20), + 10 + ); // drain 19 / ( 10 / 2 ) = 4 + assert_eq!( + SubtensorModule::tuples_to_drain_this_block(0, 10, 19, 20), + 20 + ); // drain 19 / ( 10 / 2 ) = 4 + assert_eq!( + SubtensorModule::tuples_to_drain_this_block(0, 10, 20, 20), + 20 + ); // drain 19 / ( 10 / 2 ) = 4 for i in 0..10 { for j in 0..10 { for k in 0..10 { - for l in 0 .. 10 { - assert!( SubtensorModule::tuples_to_drain_this_block( i, j, k, l ) <= 10 ); + for l in 0..10 { + assert!(SubtensorModule::tuples_to_drain_this_block(i, j, k, l) <= 10); } } } @@ -86,512 +126,672 @@ fn test_tuples_to_drain_this_block(){ }) } - #[test] -fn test_blocks_until_epoch(){ - new_test_ext().execute_with(|| { - +fn test_blocks_until_epoch() { + new_test_ext().execute_with(|| { // Check tempo = 0 block = * netuid = * - assert_eq!( SubtensorModule::blocks_until_next_epoch( 0, 0, 0 ), 1000 ); + assert_eq!(SubtensorModule::blocks_until_next_epoch(0, 0, 0), 1000); // Check tempo = 1 block = * netuid = * - assert_eq!( SubtensorModule::blocks_until_next_epoch( 0, 1, 0 ), 0 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 1, 1, 0 ), 1 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 0, 1, 1 ), 1 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 1, 1, 1 ), 0 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 0, 1, 2 ), 0 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 1, 1, 2 ), 1 ); - for i in 0..100 { + assert_eq!(SubtensorModule::blocks_until_next_epoch(0, 1, 0), 0); + assert_eq!(SubtensorModule::blocks_until_next_epoch(1, 1, 0), 1); + assert_eq!(SubtensorModule::blocks_until_next_epoch(0, 1, 1), 1); + assert_eq!(SubtensorModule::blocks_until_next_epoch(1, 1, 1), 0); + assert_eq!(SubtensorModule::blocks_until_next_epoch(0, 1, 2), 0); + assert_eq!(SubtensorModule::blocks_until_next_epoch(1, 1, 2), 1); + for i in 0..100 { if i % 2 == 0 { - assert_eq!( SubtensorModule::blocks_until_next_epoch( 0, 1, i ), 0 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 1, 1, i ), 1 ); + assert_eq!(SubtensorModule::blocks_until_next_epoch(0, 1, i), 0); + assert_eq!(SubtensorModule::blocks_until_next_epoch(1, 1, i), 1); } else { - assert_eq!( SubtensorModule::blocks_until_next_epoch( 0, 1, i ), 1 ); - assert_eq!( SubtensorModule::blocks_until_next_epoch( 1, 1, i ), 0 ); + assert_eq!(SubtensorModule::blocks_until_next_epoch(0, 1, i), 1); + assert_eq!(SubtensorModule::blocks_until_next_epoch(1, 1, i), 0); } - } + } // Check general case. - for netuid in 0..30 as u16 { + for netuid in 0..30 as u16 { for block in 0..30 as u64 { for tempo in 1..30 as u16 { - assert_eq!( SubtensorModule::blocks_until_next_epoch( netuid, tempo, block ), tempo as u64 - ( block + netuid as u64 + 1 ) % ( tempo as u64 + 1 ) ); + assert_eq!( + SubtensorModule::blocks_until_next_epoch(netuid, tempo, block), + tempo as u64 - (block + netuid as u64 + 1) % (tempo as u64 + 1) + ); } } - } - - + } }); } - /******************************************** - block_step::adjust_registration_terms_for_networks tests + block_step::adjust_registration_terms_for_networks tests *********************************************/ #[test] fn test_burn_adjustment() { - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval = 1; - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. - let hotkey_account_id_1 = U256::from(1); - let coldkey_account_id_1 = U256::from(1); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_1, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_1), netuid, hotkey_account_id_1)); - - // Register key 2. - let hotkey_account_id_2 =U256::from(2); - let coldkey_account_id_2 = U256::from(2); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_2, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_2), netuid, hotkey_account_id_2)); - - // We are over the number of regs allowed this interval. - // Step the block and trigger the adjustment. - step_block( 1 ); - - // Check the adjusted burn. - assert_eq!(SubtensorModule::get_burn_as_u64(netuid), 1500); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval = 1; + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_1, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + hotkey_account_id_1 + )); + + // Register key 2. + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_2, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + hotkey_account_id_2 + )); + + // We are over the number of regs allowed this interval. + // Step the block and trigger the adjustment. + step_block(1); + + // Check the adjusted burn. + assert_eq!(SubtensorModule::get_burn_as_u64(netuid), 1500); + }); +} + +#[test] +fn test_burn_adjustment_with_moving_average() { + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval = 1; + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + // Set alpha here. + add_network(netuid, tempo, 0); + SubtensorModule::set_adjustment_alpha(netuid, u64::MAX / 2); + + // Register key 1. + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_1, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + hotkey_account_id_1 + )); + + // Register key 2. + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_2, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + hotkey_account_id_2 + )); + + // We are over the number of regs allowed this interval. + // Step the block and trigger the adjustment. + step_block(1); + + // Check the adjusted burn. + // 0.5 * 1000 + 0.5 * 1500 = 1250 + assert_eq!(SubtensorModule::get_burn_as_u64(netuid), 1250); + }); } #[test] #[allow(unused_assignments)] fn test_burn_adjustment_case_a() { - // Test case A of the difficulty and burn adjustment algorithm. - // ==================== - // There are too many registrations this interval and most of them are pow registrations + // Test case A of the difficulty and burn adjustment algorithm. + // ==================== + // There are too many registrations this interval and most of them are pow registrations // this triggers an increase in the pow difficulty. - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval = 1; - let start_diff: u64 = 10_000; - let mut curr_block_num = 0; - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. This is a burn registration. - let hotkey_account_id_1 = U256::from(1); - let coldkey_account_id_1 = U256::from(1); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_1, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_1), netuid, hotkey_account_id_1)); - - // Register key 2. This is a POW registration - let hotkey_account_id_2 =U256::from(2); - let coldkey_account_id_2 = U256::from(2); - let (nonce0, work0): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 0, &hotkey_account_id_2); - let result0 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_2), - netuid, - curr_block_num, - nonce0, work0, - hotkey_account_id_2, - coldkey_account_id_2 - ); - assert_ok!(result0); - - // Register key 3. This is a POW registration - let hotkey_account_id_3 =U256::from(3); - let coldkey_account_id_3 = U256::from(3); - let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 11231312312, &hotkey_account_id_3); - let result1 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_3), - netuid, - curr_block_num, - nonce1, work1, - hotkey_account_id_3, - coldkey_account_id_3 - ); - assert_ok!(result1); - - // We are over the number of regs allowed this interval. - // Most of them are POW registrations (2 out of 3) - // Step the block and trigger the adjustment. - step_block( 1 ); - curr_block_num += 1; - - // Check the adjusted POW difficulty has INCREASED. - // and the burn has not changed. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert_eq!(adjusted_burn, burn_cost); - - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert!(adjusted_diff > start_diff); - assert_eq!(adjusted_diff, 20_000); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval = 1; + let start_diff: u64 = 10_000; + let mut curr_block_num = 0; + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. This is a burn registration. + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_1, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + hotkey_account_id_1 + )); + + // Register key 2. This is a POW registration + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + let (nonce0, work0): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 0, + &hotkey_account_id_2, + ); + let result0 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + curr_block_num, + nonce0, + work0, + hotkey_account_id_2, + coldkey_account_id_2, + ); + assert_ok!(result0); + + // Register key 3. This is a POW registration + let hotkey_account_id_3 = U256::from(3); + let coldkey_account_id_3 = U256::from(3); + let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 11231312312, + &hotkey_account_id_3, + ); + let result1 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_3), + netuid, + curr_block_num, + nonce1, + work1, + hotkey_account_id_3, + coldkey_account_id_3, + ); + assert_ok!(result1); + + // We are over the number of regs allowed this interval. + // Most of them are POW registrations (2 out of 3) + // Step the block and trigger the adjustment. + step_block(1); + curr_block_num += 1; + + // Check the adjusted POW difficulty has INCREASED. + // and the burn has not changed. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert_eq!(adjusted_burn, burn_cost); + + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert!(adjusted_diff > start_diff); + assert_eq!(adjusted_diff, 20_000); + }); } #[test] #[allow(unused_assignments)] fn test_burn_adjustment_case_b() { - // Test case B of the difficulty and burn adjustment algorithm. - // ==================== - // There are too many registrations this interval and most of them are burn registrations + // Test case B of the difficulty and burn adjustment algorithm. + // ==================== + // There are too many registrations this interval and most of them are burn registrations // this triggers an increase in the burn cost. - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval = 1; - let start_diff: u64 = 10_000; - let mut curr_block_num = 0; - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. - let hotkey_account_id_1 = U256::from(1); - let coldkey_account_id_1 = U256::from(1); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_1, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_1), netuid, hotkey_account_id_1)); - - // Register key 2. - let hotkey_account_id_2 =U256::from(2); - let coldkey_account_id_2 = U256::from(2); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_2, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_2), netuid, hotkey_account_id_2)); - - // Register key 3. This one is a POW registration - let hotkey_account_id_3 = U256::from(3); - let coldkey_account_id_3 = U256::from(3); - let (nonce, work): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 0, &hotkey_account_id_3); - let result = SubtensorModule::register(<::RuntimeOrigin>::signed(hotkey_account_id_3), netuid, curr_block_num, nonce, work, hotkey_account_id_3, coldkey_account_id_3); - assert_ok!(result); - - // We are over the number of regs allowed this interval. - // Most of them are burn registrations (2 out of 3) - // Step the block and trigger the adjustment. - step_block( 1 ); - curr_block_num += 1; - - // Check the adjusted burn has INCREASED. - // and the difficulty has not changed. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert!(adjusted_burn > burn_cost); - assert_eq!(adjusted_burn, 2_000); - - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert_eq!(adjusted_diff, start_diff); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval = 1; + let start_diff: u64 = 10_000; + let mut curr_block_num = 0; + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_1, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + hotkey_account_id_1 + )); + + // Register key 2. + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_2, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + hotkey_account_id_2 + )); + + // Register key 3. This one is a POW registration + let hotkey_account_id_3 = U256::from(3); + let coldkey_account_id_3 = U256::from(3); + let (nonce, work): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 0, + &hotkey_account_id_3, + ); + let result = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_3), + netuid, + curr_block_num, + nonce, + work, + hotkey_account_id_3, + coldkey_account_id_3, + ); + assert_ok!(result); + + // We are over the number of regs allowed this interval. + // Most of them are burn registrations (2 out of 3) + // Step the block and trigger the adjustment. + step_block(1); + curr_block_num += 1; + + // Check the adjusted burn has INCREASED. + // and the difficulty has not changed. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert!(adjusted_burn > burn_cost); + assert_eq!(adjusted_burn, 2_000); + + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert_eq!(adjusted_diff, start_diff); + }); } #[test] #[allow(unused_assignments)] fn test_burn_adjustment_case_c() { - // Test case C of the difficulty and burn adjustment algorithm. - // ==================== - // There are not enough registrations this interval and most of them are POW registrations + // Test case C of the difficulty and burn adjustment algorithm. + // ==================== + // There are not enough registrations this interval and most of them are POW registrations // this triggers a decrease in the burn cost - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval = 4; // Needs registrations < 4 to trigger - let start_diff: u64 = 10_000; - let mut curr_block_num = 0; - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. This is a BURN registration - let hotkey_account_id_1 = U256::from(1); - let coldkey_account_id_1 = U256::from(1); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_1, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_1), netuid, hotkey_account_id_1)); - - // Register key 2. This is a POW registration - let hotkey_account_id_2 =U256::from(2); - let coldkey_account_id_2 = U256::from(2); - let (nonce0, work0): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 0, &hotkey_account_id_2); - let result0 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_2), - netuid, - curr_block_num, - nonce0, work0, - hotkey_account_id_2, - coldkey_account_id_2 - ); - assert_ok!(result0); - - // Register key 3. This is a POW registration - let hotkey_account_id_3 =U256::from(3); - let coldkey_account_id_3 = U256::from(3); - let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 11231312312, &hotkey_account_id_3); - let result1 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_3), - netuid, - curr_block_num, - nonce1, work1, - hotkey_account_id_3, - coldkey_account_id_3 - ); - assert_ok!(result1); - - // We are UNDER the number of regs allowed this interval. - // Most of them are POW registrations (2 out of 3) - // Step the block and trigger the adjustment. - step_block( 1 ); - curr_block_num += 1; - - // Check the adjusted burn has DECREASED. - // and the difficulty has not changed. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert!(adjusted_burn < burn_cost); - assert_eq!(adjusted_burn, 875); - - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert_eq!(adjusted_diff, start_diff); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval = 4; // Needs registrations < 4 to trigger + let start_diff: u64 = 10_000; + let mut curr_block_num = 0; + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. This is a BURN registration + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_1, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + hotkey_account_id_1 + )); + + // Register key 2. This is a POW registration + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + let (nonce0, work0): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 0, + &hotkey_account_id_2, + ); + let result0 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + curr_block_num, + nonce0, + work0, + hotkey_account_id_2, + coldkey_account_id_2, + ); + assert_ok!(result0); + + // Register key 3. This is a POW registration + let hotkey_account_id_3 = U256::from(3); + let coldkey_account_id_3 = U256::from(3); + let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 11231312312, + &hotkey_account_id_3, + ); + let result1 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_3), + netuid, + curr_block_num, + nonce1, + work1, + hotkey_account_id_3, + coldkey_account_id_3, + ); + assert_ok!(result1); + + // We are UNDER the number of regs allowed this interval. + // Most of them are POW registrations (2 out of 3) + // Step the block and trigger the adjustment. + step_block(1); + curr_block_num += 1; + + // Check the adjusted burn has DECREASED. + // and the difficulty has not changed. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert!(adjusted_burn < burn_cost); + assert_eq!(adjusted_burn, 875); + + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert_eq!(adjusted_diff, start_diff); + }); } #[test] #[allow(unused_assignments)] fn test_burn_adjustment_case_d() { - // Test case D of the difficulty and burn adjustment algorithm. - // ==================== - // There are not enough registrations this interval and most of them are BURN registrations + // Test case D of the difficulty and burn adjustment algorithm. + // ==================== + // There are not enough registrations this interval and most of them are BURN registrations // this triggers a decrease in the POW difficulty - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval = 4; // Needs registrations < 4 to trigger - let start_diff: u64 = 10_000; - let mut curr_block_num = 0; - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. This is a BURN registration - let hotkey_account_id_1 = U256::from(1); - let coldkey_account_id_1 = U256::from(1); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_1, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_1), netuid, hotkey_account_id_1)); - - // Register key 2. This is a BURN registration - let hotkey_account_id_2 = U256::from(2); - let coldkey_account_id_2 = U256::from(2); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_2, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_2), netuid, hotkey_account_id_2)); - - // Register key 3. This is a POW registration - let hotkey_account_id_3 =U256::from(3); - let coldkey_account_id_3 = U256::from(3); - let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 11231312312, &hotkey_account_id_3); - let result1 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_3), - netuid, - curr_block_num, - nonce1, work1, - hotkey_account_id_3, - coldkey_account_id_3 - ); - assert_ok!(result1); - - // We are UNDER the number of regs allowed this interval. - // Most of them are BURN registrations (2 out of 3) - // Step the block and trigger the adjustment. - step_block( 1 ); - curr_block_num += 1; - - // Check the adjusted POW difficulty has DECREASED. - // and the burn has not changed. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert_eq!(adjusted_burn, burn_cost); - - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert!(adjusted_diff < start_diff); - assert_eq!(adjusted_diff, 8750); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval = 4; // Needs registrations < 4 to trigger + let start_diff: u64 = 10_000; + let mut curr_block_num = 0; + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. This is a BURN registration + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_1, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + hotkey_account_id_1 + )); + + // Register key 2. This is a BURN registration + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_2, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + hotkey_account_id_2 + )); + + // Register key 3. This is a POW registration + let hotkey_account_id_3 = U256::from(3); + let coldkey_account_id_3 = U256::from(3); + let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 11231312312, + &hotkey_account_id_3, + ); + let result1 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_3), + netuid, + curr_block_num, + nonce1, + work1, + hotkey_account_id_3, + coldkey_account_id_3, + ); + assert_ok!(result1); + + // We are UNDER the number of regs allowed this interval. + // Most of them are BURN registrations (2 out of 3) + // Step the block and trigger the adjustment. + step_block(1); + curr_block_num += 1; + + // Check the adjusted POW difficulty has DECREASED. + // and the burn has not changed. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert_eq!(adjusted_burn, burn_cost); + + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert!(adjusted_diff < start_diff); + assert_eq!(adjusted_diff, 8750); + }); } #[test] #[allow(unused_assignments)] fn test_burn_adjustment_case_e() { - // Test case E of the difficulty and burn adjustment algorithm. - // ==================== - // There are not enough registrations this interval and nobody registered either POW or BURN + // Test case E of the difficulty and burn adjustment algorithm. + // ==================== + // There are not enough registrations this interval and nobody registered either POW or BURN // this triggers a decrease in the BURN cost and POW difficulty - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval: u16 = 3; - let start_diff: u64 = 10_000; - let mut curr_block_num = 0; - SubtensorModule::set_max_registrations_per_block( netuid, 10 ); - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. This is a POW registration - let hotkey_account_id_1 =U256::from(1); - let coldkey_account_id_1 = U256::from(1); - let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 11231312312, &hotkey_account_id_1); - let result1 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_1), - netuid, - curr_block_num, - nonce1, work1, - hotkey_account_id_1, - coldkey_account_id_1 - ); - assert_ok!(result1); - - // Register key 2. This is a BURN registration - let hotkey_account_id_2 = U256::from(2); - let coldkey_account_id_2 = U256::from(2); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_2, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_2), netuid, hotkey_account_id_2)); - - - step_block( 1 ); - curr_block_num += 1; - - // We are UNDER the number of regs allowed this interval. - // And the number of regs of each type is equal - - // Check the adjusted BURN has DECREASED. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert!(adjusted_burn < burn_cost); - assert_eq!(adjusted_burn, 833); - - // Check the adjusted POW difficulty has DECREASED. - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert!(adjusted_diff < start_diff); - assert_eq!(adjusted_diff, 8_333); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval: u16 = 3; + let start_diff: u64 = 10_000; + let mut curr_block_num = 0; + SubtensorModule::set_max_registrations_per_block(netuid, 10); + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. This is a POW registration + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 11231312312, + &hotkey_account_id_1, + ); + let result1 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + curr_block_num, + nonce1, + work1, + hotkey_account_id_1, + coldkey_account_id_1, + ); + assert_ok!(result1); + + // Register key 2. This is a BURN registration + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_2, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + hotkey_account_id_2 + )); + + step_block(1); + curr_block_num += 1; + + // We are UNDER the number of regs allowed this interval. + // And the number of regs of each type is equal + + // Check the adjusted BURN has DECREASED. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert!(adjusted_burn < burn_cost); + assert_eq!(adjusted_burn, 833); + + // Check the adjusted POW difficulty has DECREASED. + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert!(adjusted_diff < start_diff); + assert_eq!(adjusted_diff, 8_333); + }); } #[test] #[allow(unused_assignments)] fn test_burn_adjustment_case_f() { - // Test case F of the difficulty and burn adjustment algorithm. - // ==================== - // There are too many registrations this interval and the pow and burn registrations are equal + // Test case F of the difficulty and burn adjustment algorithm. + // ==================== + // There are too many registrations this interval and the pow and burn registrations are equal // this triggers an increase in the burn cost and pow difficulty - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval: u16 = 1; - let start_diff: u64 = 10_000; - let mut curr_block_num = 0; - SubtensorModule::set_max_registrations_per_block( netuid, 10 ); - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // Register key 1. This is a POW registration - let hotkey_account_id_1 =U256::from(1); - let coldkey_account_id_1 = U256::from(1); - let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, curr_block_num, 11231312312, &hotkey_account_id_1); - let result1 = SubtensorModule::register( - <::RuntimeOrigin>::signed(hotkey_account_id_1), - netuid, - curr_block_num, - nonce1, work1, - hotkey_account_id_1, - coldkey_account_id_1 - ); - assert_ok!(result1); - - // Register key 2. This is a BURN registration - let hotkey_account_id_2 = U256::from(2); - let coldkey_account_id_2 = U256::from(2); - SubtensorModule::add_balance_to_coldkey_account( &coldkey_account_id_2, 10000 ); - assert_ok!(SubtensorModule::burned_register(<::RuntimeOrigin>::signed(hotkey_account_id_2), netuid, hotkey_account_id_2)); - - step_block( 1 ); - curr_block_num += 1; - // We are OVER the number of regs allowed this interval. - // And the number of regs of each type is equal - - - // Check the adjusted BURN has INCREASED. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert!(adjusted_burn > burn_cost); - assert_eq!(adjusted_burn, 1_500); - - // Check the adjusted POW difficulty has INCREASED. - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert!(adjusted_diff > start_diff); - assert_eq!(adjusted_diff, 15_000); - }); + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval: u16 = 1; + let start_diff: u64 = 10_000; + let mut curr_block_num = 0; + SubtensorModule::set_max_registrations_per_block(netuid, 10); + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // Register key 1. This is a POW registration + let hotkey_account_id_1 = U256::from(1); + let coldkey_account_id_1 = U256::from(1); + let (nonce1, work1): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + curr_block_num, + 11231312312, + &hotkey_account_id_1, + ); + let result1 = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id_1), + netuid, + curr_block_num, + nonce1, + work1, + hotkey_account_id_1, + coldkey_account_id_1, + ); + assert_ok!(result1); + + // Register key 2. This is a BURN registration + let hotkey_account_id_2 = U256::from(2); + let coldkey_account_id_2 = U256::from(2); + SubtensorModule::add_balance_to_coldkey_account(&coldkey_account_id_2, 10000); + assert_ok!(SubtensorModule::burned_register( + <::RuntimeOrigin>::signed(hotkey_account_id_2), + netuid, + hotkey_account_id_2 + )); + + step_block(1); + curr_block_num += 1; + // We are OVER the number of regs allowed this interval. + // And the number of regs of each type is equal + + // Check the adjusted BURN has INCREASED. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert!(adjusted_burn > burn_cost); + assert_eq!(adjusted_burn, 1_500); + + // Check the adjusted POW difficulty has INCREASED. + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert!(adjusted_diff > start_diff); + assert_eq!(adjusted_diff, 15_000); + }); } - #[test] fn test_burn_adjustment_case_e_zero_registrations() { - // Test case E of the difficulty and burn adjustment algorithm. - // ==================== - // There are not enough registrations this interval and nobody registered either POW or BURN + // Test case E of the difficulty and burn adjustment algorithm. + // ==================== + // There are not enough registrations this interval and nobody registered either POW or BURN // this triggers a decrease in the BURN cost and POW difficulty - // BUT there are zero registrations this interval. - new_test_ext().execute_with(|| { - let netuid: u16 = 1; - let tempo: u16 = 13; - let burn_cost:u64 = 1000; - let adjustment_interval = 1; - let target_registrations_per_interval: u16 = 1; - let start_diff: u64 = 10_000; - SubtensorModule::set_max_registrations_per_block( netuid, 10 ); - SubtensorModule::set_burn( netuid, burn_cost); - SubtensorModule::set_difficulty(netuid, start_diff); - SubtensorModule::set_adjustment_interval( netuid, adjustment_interval ); - SubtensorModule::set_target_registrations_per_interval( netuid, target_registrations_per_interval); - add_network(netuid, tempo, 0); - - // No registrations this interval of any kind. - step_block( 1 ); - - // We are UNDER the number of regs allowed this interval. - // And the number of regs of each type is equal - - // Check the adjusted BURN has DECREASED. - let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); - assert!(adjusted_burn < burn_cost); - assert_eq!(adjusted_burn, 500); - - // Check the adjusted POW difficulty has DECREASED. - let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); - assert!(adjusted_diff < start_diff); - assert_eq!(adjusted_diff, 5_000); - }); + // BUT there are zero registrations this interval. + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let tempo: u16 = 13; + let burn_cost: u64 = 1000; + let adjustment_interval = 1; + let target_registrations_per_interval: u16 = 1; + let start_diff: u64 = 10_000; + SubtensorModule::set_max_registrations_per_block(netuid, 10); + SubtensorModule::set_burn(netuid, burn_cost); + SubtensorModule::set_difficulty(netuid, start_diff); + SubtensorModule::set_adjustment_interval(netuid, adjustment_interval); + SubtensorModule::set_target_registrations_per_interval( + netuid, + target_registrations_per_interval, + ); + add_network(netuid, tempo, 0); + + // No registrations this interval of any kind. + step_block(1); + + // We are UNDER the number of regs allowed this interval. + // And the number of regs of each type is equal + + // Check the adjusted BURN has DECREASED. + let adjusted_burn = SubtensorModule::get_burn_as_u64(netuid); + assert!(adjusted_burn < burn_cost); + assert_eq!(adjusted_burn, 500); + + // Check the adjusted POW difficulty has DECREASED. + let adjusted_diff = SubtensorModule::get_difficulty_as_u64(netuid); + assert!(adjusted_diff < start_diff); + assert_eq!(adjusted_diff, 5_000); + }); } - - // add_network( netuid1, tempo1, 0 ); // add_network( netuid2, tempo2, 0 ); @@ -644,10 +844,9 @@ fn test_burn_adjustment_case_e_zero_registrations() { // assert_eq!( SubtensorModule::get_pending_emission( netuid1 ), 1_333_333_332 ); // assert_eq!( SubtensorModule::get_pending_emission( netuid2 ), 1_333_333_336 ); - // #[test] // fn test_nakamoto(){ -// new_test_ext().execute_with(|| { +// new_test_ext().execute_with(|| { // // Create nakamoto. // let n: u16 = 10; @@ -677,4 +876,4 @@ fn test_burn_adjustment_case_e_zero_registrations() { // } // }); -// } \ No newline at end of file +// } diff --git a/pallets/subtensor/tests/mock.rs b/pallets/subtensor/tests/mock.rs index 771ffbc34..5fb5253a8 100644 --- a/pallets/subtensor/tests/mock.rs +++ b/pallets/subtensor/tests/mock.rs @@ -1,13 +1,17 @@ -use frame_support::{assert_ok, parameter_types, traits::{Everything, Hooks}, weights}; -use frame_system::{limits, EnsureNever, EnsureRoot, RawOrigin}; -use frame_support::traits::{StorageMapShim, Hash}; +use frame_support::traits::{Hash, StorageMapShim}; +use frame_support::{ + assert_ok, parameter_types, + traits::{Everything, Hooks}, + weights, +}; use frame_system as system; use frame_system::Config; -use sp_core::{H256, U256, Get}; +use frame_system::{limits, EnsureNever, EnsureRoot, RawOrigin}; +use sp_core::{Get, H256, U256}; use sp_runtime::{ - testing::Header, - traits::{BlakeTwo256, IdentityLookup}, - DispatchResult + testing::Header, + traits::{BlakeTwo256, IdentityLookup}, + DispatchResult, }; use pallet_collective::MemberCount; @@ -17,20 +21,20 @@ type Block = frame_system::mocking::MockBlock; // Configure a mock runtime to test the pallet. frame_support::construct_runtime!( - pub enum Test where - Block = Block, - NodeBlock = Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, - Triumvirate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, - TriumvirateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, - Senate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, - SenateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, - SubtensorModule: pallet_subtensor::{Pallet, Call, Storage, Event}, - Utility: pallet_utility::{Pallet, Call, Storage, Event}, - } + pub enum Test where + Block = Block, + NodeBlock = Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system::{Pallet, Call, Config, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Config, Storage, Event}, + Triumvirate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, + TriumvirateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, + Senate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, + SenateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, + SubtensorModule: pallet_subtensor::{Pallet, Call, Storage, Event}, + Utility: pallet_utility::{Pallet, Call, Storage, Event}, + } ); #[allow(dead_code)] @@ -43,12 +47,12 @@ pub type BalanceCall = pallet_balances::Call; pub type TestRuntimeCall = frame_system::Call; parameter_types! { - pub const BlockHashCount: u64 = 250; - pub const SS58Prefix: u8 = 42; + pub const BlockHashCount: u64 = 250; + pub const SS58Prefix: u8 = 42; } #[allow(dead_code)] -pub type AccountId = U256; +pub type AccountId = U256; // The address format for describing accounts. pub type Address = AccountId; @@ -62,290 +66,301 @@ pub type Balance = u64; pub type BlockNumber = u64; impl pallet_balances::Config for Test { - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = (); - type AccountStore = StorageMapShim< - pallet_balances::Account, - frame_system::Provider, - AccountId, - pallet_balances::AccountData, - >; - type MaxLocks = (); - type WeightInfo = (); - type MaxReserves = (); - type ReserveIdentifier = (); + type Balance = Balance; + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = (); + type AccountStore = StorageMapShim< + pallet_balances::Account, + frame_system::Provider, + AccountId, + pallet_balances::AccountData, + >; + type MaxLocks = (); + type WeightInfo = (); + type MaxReserves = (); + type ReserveIdentifier = (); } impl system::Config for Test { - type BaseCallFilter = Everything; - type BlockWeights = (); - type BlockLength = (); - type DbWeight = (); - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Index = u64; - type BlockNumber = u64; - type Hash = H256; - type Hashing = BlakeTwo256; - type AccountId = U256; - type Lookup = IdentityLookup; - type Header = Header; - type RuntimeEvent = RuntimeEvent; - type BlockHashCount = BlockHashCount; - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = (); - type OnNewAccount = (); - type OnKilledAccount = (); - type SystemWeightInfo = (); - type SS58Prefix = SS58Prefix; - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + type BaseCallFilter = Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type RuntimeCall = RuntimeCall; + type Index = u64; + type BlockNumber = u64; + type Hash = H256; + type Hashing = BlakeTwo256; + type AccountId = U256; + type Lookup = IdentityLookup; + type Header = Header; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = BlockHashCount; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = (); + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = SS58Prefix; + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } parameter_types! { - pub const InitialMinAllowedWeights: u16 = 0; - pub const InitialEmissionValue: u16 = 0; - pub const InitialMaxWeightsLimit: u16 = u16::MAX; - pub BlockWeights: limits::BlockWeights = limits::BlockWeights::simple_max(weights::Weight::from_ref_time(1024)); - pub const ExistentialDeposit: Balance = 1; - pub const TransactionByteFee: Balance = 100; - pub const SDebug:u64 = 1; - pub const InitialRho: u16 = 30; - pub const InitialKappa: u16 = 32_767; - pub const InitialTempo: u16 = 0; - pub const SelfOwnership: u64 = 2; - pub const InitialImmunityPeriod: u16 = 2; - pub const InitialMaxAllowedUids: u16 = 2; - pub const InitialBondsMovingAverage: u64 = 900_000; - pub const InitialStakePruningMin: u16 = 0; - pub const InitialFoundationDistribution: u64 = 0; - pub const InitialDefaultTake: u16 = 11_796; // 18% honest number. - pub const InitialWeightsVersionKey: u16 = 0; - pub const InitialServingRateLimit: u64 = 0; // No limit. - pub const InitialTxRateLimit: u64 = 2; // 2 blocks per stake/unstake/delegate - - pub const InitialBurn: u64 = 0; - pub const InitialMinBurn: u64 = 0; - pub const InitialMaxBurn: u64 = 1_000_000_000; - - pub const InitialValidatorBatchSize: u16 = 10; - pub const InitialValidatorSequenceLen: u16 = 10; - pub const InitialValidatorPruneLen: u64 = 0; - pub const InitialValidatorEpochLen: u16 = 10; - pub const InitialValidatorEpochsPerReset: u16 = 10; - pub const InitialValidatorExcludeQuantile: u16 = 10; - pub const InitialValidatorLogitsDivergence: u16 = 0; - pub const InitialScalingLawPower: u16 = 50; - pub const InitialSynergyScalingLawPower: u16 = 50; - pub const InitialMaxAllowedValidators: u16 = 100; - - pub const InitialIssuance: u64 = 548833985028256; - pub const InitialDifficulty: u64 = 10000; - pub const InitialActivityCutoff: u16 = 5000; - pub const InitialAdjustmentInterval: u16 = 100; - pub const InitialMaxRegistrationsPerBlock: u16 = 3; - pub const InitialTargetRegistrationsPerInterval: u16 = 2; - pub const InitialPruningScore : u16 = u16::MAX; - pub const InitialRegistrationRequirement: u16 = u16::MAX; // Top 100% - pub const InitialMinDifficulty: u64 = 1; - pub const InitialMaxDifficulty: u64 = u64::MAX; - pub const InitialRAORecycledForRegistration: u64 = 0; - - pub const InitialSenateRequiredStakePercentage: u64 = 2; // 2 percent of total stake + pub const InitialMinAllowedWeights: u16 = 0; + pub const InitialEmissionValue: u16 = 0; + pub const InitialMaxWeightsLimit: u16 = u16::MAX; + pub BlockWeights: limits::BlockWeights = limits::BlockWeights::simple_max(weights::Weight::from_ref_time(1024)); + pub const ExistentialDeposit: Balance = 1; + pub const TransactionByteFee: Balance = 100; + pub const SDebug:u64 = 1; + pub const InitialRho: u16 = 30; + pub const InitialKappa: u16 = 32_767; + pub const InitialTempo: u16 = 0; + pub const SelfOwnership: u64 = 2; + pub const InitialImmunityPeriod: u16 = 2; + pub const InitialMaxAllowedUids: u16 = 2; + pub const InitialBondsMovingAverage: u64 = 900_000; + pub const InitialStakePruningMin: u16 = 0; + pub const InitialFoundationDistribution: u64 = 0; + pub const InitialDefaultTake: u16 = 11_796; // 18% honest number. + pub const InitialWeightsVersionKey: u16 = 0; + pub const InitialServingRateLimit: u64 = 0; // No limit. + pub const InitialTxRateLimit: u64 = 2; // 2 blocks per stake/unstake/delegate + + pub const InitialBurn: u64 = 0; + pub const InitialMinBurn: u64 = 0; + pub const InitialMaxBurn: u64 = 1_000_000_000; + + pub const InitialValidatorBatchSize: u16 = 10; + pub const InitialValidatorSequenceLen: u16 = 10; + pub const InitialValidatorPruneLen: u64 = 0; + pub const InitialValidatorEpochLen: u16 = 10; + pub const InitialValidatorEpochsPerReset: u16 = 10; + pub const InitialValidatorExcludeQuantile: u16 = 10; + pub const InitialValidatorLogitsDivergence: u16 = 0; + pub const InitialScalingLawPower: u16 = 50; + pub const InitialSynergyScalingLawPower: u16 = 50; + pub const InitialMaxAllowedValidators: u16 = 100; + + pub const InitialIssuance: u64 = 548833985028256; + pub const InitialDifficulty: u64 = 10000; + pub const InitialActivityCutoff: u16 = 5000; + pub const InitialAdjustmentInterval: u16 = 100; + pub const InitialAdjustmentAlpha: u64 = 0; // no weight to previous value. + pub const InitialMaxRegistrationsPerBlock: u16 = 3; + pub const InitialTargetRegistrationsPerInterval: u16 = 2; + pub const InitialPruningScore : u16 = u16::MAX; + pub const InitialRegistrationRequirement: u16 = u16::MAX; // Top 100% + pub const InitialMinDifficulty: u64 = 1; + pub const InitialMaxDifficulty: u64 = u64::MAX; + pub const InitialRAORecycledForRegistration: u64 = 0; + + pub const InitialSenateRequiredStakePercentage: u64 = 2; // 2 percent of total stake } // Configure collective pallet for council parameter_types! { - pub const CouncilMotionDuration: BlockNumber = 100; - pub const CouncilMaxProposals: u32 = 10; - pub const CouncilMaxMembers: u32 = 3; + pub const CouncilMotionDuration: BlockNumber = 100; + pub const CouncilMaxProposals: u32 = 10; + pub const CouncilMaxMembers: u32 = 3; } // Configure collective pallet for Senate parameter_types! { - pub const SenateMaxMembers: u32 = 10; + pub const SenateMaxMembers: u32 = 10; } use pallet_collective::{CanPropose, CanVote, GetVotingMembers}; pub struct CanProposeToTriumvirate; impl CanPropose for CanProposeToTriumvirate { - fn can_propose(account: &AccountId) -> bool { - Triumvirate::is_member(account) - } + fn can_propose(account: &AccountId) -> bool { + Triumvirate::is_member(account) + } } pub struct CanVoteToTriumvirate; impl CanVote for CanVoteToTriumvirate { - fn can_vote(_: &AccountId) -> bool { - //Senate::is_member(account) - false // Disable voting from pallet_collective::vote - } + fn can_vote(_: &AccountId) -> bool { + //Senate::is_member(account) + false // Disable voting from pallet_collective::vote + } } -use pallet_subtensor::{MemberManagement, CollectiveInterface}; +use pallet_subtensor::{CollectiveInterface, MemberManagement}; pub struct ManageSenateMembers; impl MemberManagement for ManageSenateMembers { - fn add_member(account: &AccountId) -> DispatchResult { - SenateMembers::add_member(RawOrigin::Root.into(), *account) - } + fn add_member(account: &AccountId) -> DispatchResult { + SenateMembers::add_member(RawOrigin::Root.into(), *account) + } - fn remove_member(account: &AccountId) -> DispatchResult { - SenateMembers::remove_member(RawOrigin::Root.into(), *account) - } + fn remove_member(account: &AccountId) -> DispatchResult { + SenateMembers::remove_member(RawOrigin::Root.into(), *account) + } - fn swap_member(remove: &AccountId, add: &AccountId) -> DispatchResult { - SenateMembers::swap_member(RawOrigin::Root.into(), *remove, *add) - } + fn swap_member(remove: &AccountId, add: &AccountId) -> DispatchResult { + SenateMembers::swap_member(RawOrigin::Root.into(), *remove, *add) + } - fn is_member(account: &AccountId) -> bool { - Senate::is_member(account) - } + fn is_member(account: &AccountId) -> bool { + Senate::is_member(account) + } - fn members() -> Vec { - Senate::members() - } + fn members() -> Vec { + Senate::members() + } - fn max_members() -> u32 { - SenateMaxMembers::get() - } + fn max_members() -> u32 { + SenateMaxMembers::get() + } } pub struct GetSenateMemberCount; impl GetVotingMembers for GetSenateMemberCount { - fn get_count() -> MemberCount {Senate::members().len() as u32} + fn get_count() -> MemberCount { + Senate::members().len() as u32 + } } impl Get for GetSenateMemberCount { - fn get() -> MemberCount {SenateMaxMembers::get()} + fn get() -> MemberCount { + SenateMaxMembers::get() + } } pub struct TriumvirateVotes; impl CollectiveInterface for TriumvirateVotes { - fn remove_votes(hotkey: &AccountId) -> Result { - Triumvirate::remove_votes(hotkey) - } + fn remove_votes(hotkey: &AccountId) -> Result { + Triumvirate::remove_votes(hotkey) + } - fn add_vote(hotkey: &AccountId, proposal: Hash, index: u32, approve: bool) -> Result { - Triumvirate::do_vote(hotkey.clone(), proposal, index, approve) - } + fn add_vote( + hotkey: &AccountId, + proposal: Hash, + index: u32, + approve: bool, + ) -> Result { + Triumvirate::do_vote(hotkey.clone(), proposal, index, approve) + } } // We call pallet_collective TriumvirateCollective type TriumvirateCollective = pallet_collective::Instance1; impl pallet_collective::Config for Test { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = GetSenateMemberCount; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureNever; - type CanPropose = CanProposeToTriumvirate; - type CanVote = CanVoteToTriumvirate; - type GetVotingMembers = GetSenateMemberCount; + type RuntimeOrigin = RuntimeOrigin; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = CouncilMaxProposals; + type MaxMembers = GetSenateMemberCount; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = pallet_collective::weights::SubstrateWeight; + type SetMembersOrigin = EnsureNever; + type CanPropose = CanProposeToTriumvirate; + type CanVote = CanVoteToTriumvirate; + type GetVotingMembers = GetSenateMemberCount; } // We call council members Triumvirate type TriumvirateMembership = pallet_membership::Instance1; impl pallet_membership::Config for Test { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRoot; - type RemoveOrigin = EnsureRoot; - type SwapOrigin = EnsureRoot; - type ResetOrigin = EnsureRoot; - type PrimeOrigin = EnsureRoot; - type MembershipInitialized = Triumvirate; - type MembershipChanged = Triumvirate; - type MaxMembers = CouncilMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type AddOrigin = EnsureRoot; + type RemoveOrigin = EnsureRoot; + type SwapOrigin = EnsureRoot; + type ResetOrigin = EnsureRoot; + type PrimeOrigin = EnsureRoot; + type MembershipInitialized = Triumvirate; + type MembershipChanged = Triumvirate; + type MaxMembers = CouncilMaxMembers; + type WeightInfo = pallet_membership::weights::SubstrateWeight; } // This is a dummy collective instance for managing senate members // Probably not the best solution, but fastest implementation type SenateCollective = pallet_collective::Instance2; impl pallet_collective::Config for Test { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = SenateMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureNever; - type CanPropose = (); - type CanVote = (); - type GetVotingMembers = (); + type RuntimeOrigin = RuntimeOrigin; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = CouncilMaxProposals; + type MaxMembers = SenateMaxMembers; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = pallet_collective::weights::SubstrateWeight; + type SetMembersOrigin = EnsureNever; + type CanPropose = (); + type CanVote = (); + type GetVotingMembers = (); } // We call our top K delegates membership Senate type SenateMembership = pallet_membership::Instance2; impl pallet_membership::Config for Test { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRoot; - type RemoveOrigin = EnsureRoot; - type SwapOrigin = EnsureRoot; - type ResetOrigin = EnsureRoot; - type PrimeOrigin = EnsureRoot; - type MembershipInitialized = Senate; - type MembershipChanged = Senate; - type MaxMembers = SenateMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type AddOrigin = EnsureRoot; + type RemoveOrigin = EnsureRoot; + type SwapOrigin = EnsureRoot; + type ResetOrigin = EnsureRoot; + type PrimeOrigin = EnsureRoot; + type MembershipInitialized = Senate; + type MembershipChanged = Senate; + type MaxMembers = SenateMaxMembers; + type WeightInfo = pallet_membership::weights::SubstrateWeight; } impl pallet_subtensor::Config for Test { - type RuntimeEvent = RuntimeEvent; - type Currency = Balances; - type InitialIssuance = InitialIssuance; - type SudoRuntimeCall = TestRuntimeCall; - type CouncilOrigin = frame_system::EnsureSigned; - type SenateMembers = ManageSenateMembers; - type TriumvirateInterface = TriumvirateVotes; - - type InitialMinAllowedWeights = InitialMinAllowedWeights; - type InitialEmissionValue = InitialEmissionValue; - type InitialMaxWeightsLimit = InitialMaxWeightsLimit; - type InitialTempo = InitialTempo; - type InitialDifficulty = InitialDifficulty; - type InitialAdjustmentInterval = InitialAdjustmentInterval; - type InitialTargetRegistrationsPerInterval = InitialTargetRegistrationsPerInterval; - type InitialRho = InitialRho; - type InitialKappa = InitialKappa; - type InitialMaxAllowedUids = InitialMaxAllowedUids; - type InitialValidatorBatchSize = InitialValidatorBatchSize; - type InitialValidatorSequenceLen = InitialValidatorSequenceLen; - type InitialValidatorPruneLen = InitialValidatorPruneLen; - type InitialValidatorEpochLen = InitialValidatorEpochLen; - type InitialValidatorEpochsPerReset = InitialValidatorEpochsPerReset; - type InitialValidatorExcludeQuantile = InitialValidatorExcludeQuantile; - type InitialValidatorLogitsDivergence = InitialValidatorLogitsDivergence; - type InitialScalingLawPower = InitialScalingLawPower; - type InitialSynergyScalingLawPower = InitialSynergyScalingLawPower; - type InitialImmunityPeriod = InitialImmunityPeriod; - type InitialActivityCutoff = InitialActivityCutoff; - type InitialMaxRegistrationsPerBlock = InitialMaxRegistrationsPerBlock; - type InitialPruningScore = InitialPruningScore; - type InitialBondsMovingAverage = InitialBondsMovingAverage; - type InitialMaxAllowedValidators = InitialMaxAllowedValidators; - type InitialDefaultTake = InitialDefaultTake; - type InitialWeightsVersionKey = InitialWeightsVersionKey; - type InitialMaxDifficulty = InitialMaxDifficulty; - type InitialMinDifficulty = InitialMinDifficulty; - type InitialServingRateLimit = InitialServingRateLimit; - type InitialTxRateLimit = InitialTxRateLimit; - type InitialBurn = InitialBurn; - type InitialMaxBurn = InitialMaxBurn; - type InitialMinBurn = InitialMinBurn; - type InitialRAORecycledForRegistration = InitialRAORecycledForRegistration; - type InitialSenateRequiredStakePercentage = InitialSenateRequiredStakePercentage; + type RuntimeEvent = RuntimeEvent; + type Currency = Balances; + type InitialIssuance = InitialIssuance; + type SudoRuntimeCall = TestRuntimeCall; + type CouncilOrigin = frame_system::EnsureSigned; + type SenateMembers = ManageSenateMembers; + type TriumvirateInterface = TriumvirateVotes; + + type InitialMinAllowedWeights = InitialMinAllowedWeights; + type InitialEmissionValue = InitialEmissionValue; + type InitialMaxWeightsLimit = InitialMaxWeightsLimit; + type InitialTempo = InitialTempo; + type InitialDifficulty = InitialDifficulty; + type InitialAdjustmentInterval = InitialAdjustmentInterval; + type InitialAdjustmentAlpha = InitialAdjustmentAlpha; + type InitialTargetRegistrationsPerInterval = InitialTargetRegistrationsPerInterval; + type InitialRho = InitialRho; + type InitialKappa = InitialKappa; + type InitialMaxAllowedUids = InitialMaxAllowedUids; + type InitialValidatorBatchSize = InitialValidatorBatchSize; + type InitialValidatorSequenceLen = InitialValidatorSequenceLen; + type InitialValidatorPruneLen = InitialValidatorPruneLen; + type InitialValidatorEpochLen = InitialValidatorEpochLen; + type InitialValidatorEpochsPerReset = InitialValidatorEpochsPerReset; + type InitialValidatorExcludeQuantile = InitialValidatorExcludeQuantile; + type InitialValidatorLogitsDivergence = InitialValidatorLogitsDivergence; + type InitialScalingLawPower = InitialScalingLawPower; + type InitialSynergyScalingLawPower = InitialSynergyScalingLawPower; + type InitialImmunityPeriod = InitialImmunityPeriod; + type InitialActivityCutoff = InitialActivityCutoff; + type InitialMaxRegistrationsPerBlock = InitialMaxRegistrationsPerBlock; + type InitialPruningScore = InitialPruningScore; + type InitialBondsMovingAverage = InitialBondsMovingAverage; + type InitialMaxAllowedValidators = InitialMaxAllowedValidators; + type InitialDefaultTake = InitialDefaultTake; + type InitialWeightsVersionKey = InitialWeightsVersionKey; + type InitialMaxDifficulty = InitialMaxDifficulty; + type InitialMinDifficulty = InitialMinDifficulty; + type InitialServingRateLimit = InitialServingRateLimit; + type InitialTxRateLimit = InitialTxRateLimit; + type InitialBurn = InitialBurn; + type InitialMaxBurn = InitialMaxBurn; + type InitialMinBurn = InitialMinBurn; + type InitialRAORecycledForRegistration = InitialRAORecycledForRegistration; + type InitialSenateRequiredStakePercentage = InitialSenateRequiredStakePercentage; } impl pallet_utility::Config for Test { - type RuntimeEvent = RuntimeEvent; + type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; type PalletsOrigin = OriginCaller; type WeightInfo = pallet_utility::weights::SubstrateWeight; @@ -359,59 +374,94 @@ impl pallet_utility::Config for Test { // Build genesis storage according to the mock runtime. #[allow(dead_code)] pub fn new_test_ext() -> sp_io::TestExternalities { - sp_tracing::try_init_simple(); - frame_system::GenesisConfig::default().build_storage::().unwrap().into() + sp_tracing::try_init_simple(); + frame_system::GenesisConfig::default() + .build_storage::() + .unwrap() + .into() } #[allow(dead_code)] -pub fn test_ext_with_balances(balances : Vec<(U256, u128)>) -> sp_io::TestExternalities { - sp_tracing::try_init_simple(); - let mut t = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); - - pallet_balances::GenesisConfig:: { balances: balances.iter().map(|(a, b)| (*a, *b as u64)).collect::>() } - .assimilate_storage(&mut t) - .unwrap(); +pub fn test_ext_with_balances(balances: Vec<(U256, u128)>) -> sp_io::TestExternalities { + sp_tracing::try_init_simple(); + let mut t = frame_system::GenesisConfig::default() + .build_storage::() + .unwrap(); + + pallet_balances::GenesisConfig:: { + balances: balances + .iter() + .map(|(a, b)| (*a, *b as u64)) + .collect::>(), + } + .assimilate_storage(&mut t) + .unwrap(); - t.into() + t.into() } #[allow(dead_code)] pub(crate) fn step_block(n: u16) { - for _ in 0..n { - SubtensorModule::on_finalize(System::block_number()); - System::on_finalize(System::block_number()); - System::set_block_number(System::block_number() + 1); - System::on_initialize(System::block_number()); - SubtensorModule::on_initialize(System::block_number()); - } + for _ in 0..n { + SubtensorModule::on_finalize(System::block_number()); + System::on_finalize(System::block_number()); + System::set_block_number(System::block_number() + 1); + System::on_initialize(System::block_number()); + SubtensorModule::on_initialize(System::block_number()); + } } #[allow(dead_code)] pub(crate) fn run_to_block(n: u64) { while System::block_number() < n { - SubtensorModule::on_finalize(System::block_number()); + SubtensorModule::on_finalize(System::block_number()); System::on_finalize(System::block_number()); System::set_block_number(System::block_number() + 1); System::on_initialize(System::block_number()); - SubtensorModule::on_initialize(System::block_number()); + SubtensorModule::on_initialize(System::block_number()); } } #[allow(dead_code)] -pub fn register_ok_neuron( netuid: u16, hotkey_account_id: U256, coldkey_account_id: U256, start_nonce: u64) { - let block_number: u64 = SubtensorModule::get_current_block_as_u64(); - let (nonce, work): (u64, Vec) = SubtensorModule::create_work_for_block_number( netuid, block_number, start_nonce, &hotkey_account_id); - let result = SubtensorModule::register( <::RuntimeOrigin>::signed(hotkey_account_id), netuid, block_number, nonce, work, hotkey_account_id, coldkey_account_id ); - assert_ok!(result); - log::info!("Register ok neuron: netuid: {:?}, coldkey: {:?}, hotkey: {:?}", netuid, hotkey_account_id, coldkey_account_id ); +pub fn register_ok_neuron( + netuid: u16, + hotkey_account_id: U256, + coldkey_account_id: U256, + start_nonce: u64, +) { + let block_number: u64 = SubtensorModule::get_current_block_as_u64(); + let (nonce, work): (u64, Vec) = SubtensorModule::create_work_for_block_number( + netuid, + block_number, + start_nonce, + &hotkey_account_id, + ); + let result = SubtensorModule::register( + <::RuntimeOrigin>::signed(hotkey_account_id), + netuid, + block_number, + nonce, + work, + hotkey_account_id, + coldkey_account_id, + ); + assert_ok!(result); + log::info!( + "Register ok neuron: netuid: {:?}, coldkey: {:?}, hotkey: {:?}", + netuid, + hotkey_account_id, + coldkey_account_id + ); } #[allow(dead_code)] -pub fn add_network(netuid: u16, tempo: u16, modality: u16){ - let result = SubtensorModule::do_add_network(<::RuntimeOrigin>::root(), netuid, tempo, modality); - SubtensorModule::set_network_registration_allowed( netuid, true ); - assert_ok!(result); +pub fn add_network(netuid: u16, tempo: u16, modality: u16) { + let result = SubtensorModule::do_add_network( + <::RuntimeOrigin>::root(), + netuid, + tempo, + modality, + ); + SubtensorModule::set_network_registration_allowed(netuid, true); + assert_ok!(result); } - diff --git a/pallets/subtensor/tests/sudo.rs b/pallets/subtensor/tests/sudo.rs index eaabbffcc..9b1894ecc 100644 --- a/pallets/subtensor/tests/sudo.rs +++ b/pallets/subtensor/tests/sudo.rs @@ -403,6 +403,39 @@ fn test_sudo_set_adjustment_interval() { }); } +#[test] +fn test_sudo_set_adjustment_alpha() { + new_test_ext().execute_with(|| { + let netuid: u16 = 1; + let to_be_set: u64 = 10; + let init_value: u64 = SubtensorModule::get_adjustment_alpha(netuid); + add_network(netuid, 10, 0); + assert_eq!( + SubtensorModule::sudo_set_adjustment_alpha( + <::RuntimeOrigin>::signed(U256::from(0)), + netuid, + to_be_set + ), + Err(DispatchError::BadOrigin.into()) + ); + assert_eq!( + SubtensorModule::sudo_set_adjustment_alpha( + <::RuntimeOrigin>::root(), + netuid + 1, + to_be_set + ), + Err(Error::::NetworkDoesNotExist.into()) + ); + assert_eq!(SubtensorModule::get_adjustment_alpha(netuid), init_value); + assert_ok!(SubtensorModule::sudo_set_adjustment_alpha( + <::RuntimeOrigin>::root(), + netuid, + to_be_set + )); + assert_eq!(SubtensorModule::get_adjustment_alpha(netuid), to_be_set); + }); +} + #[test] fn test_sudo_set_validator_exclude_quantile() { new_test_ext().execute_with(|| { diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 120ae3817..f37c530a2 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -6,26 +6,30 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -use codec::{Encode, Decode}; +use codec::{Decode, Encode}; use pallet_collective::EnsureMember; use pallet_grandpa::{ - fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, + fg_primitives, AuthorityId as GrandpaId, AuthorityList as GrandpaAuthorityList, }; -use frame_support::{pallet_prelude::{Get, TypeInfo, MaxEncodedLen, PhantomData, EnsureOrigin, DispatchResult}, traits::{EitherOfDiverse}, RuntimeDebug}; -use frame_system::{EnsureRoot, Config, EnsureNever, RawOrigin}; +use frame_support::{ + pallet_prelude::{DispatchResult, EnsureOrigin, Get, MaxEncodedLen, PhantomData, TypeInfo}, + traits::EitherOfDiverse, + RuntimeDebug, +}; +use frame_system::{Config, EnsureNever, EnsureRoot, RawOrigin}; use smallvec::smallvec; use sp_api::impl_runtime_apis; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ - create_runtime_str, generic, impl_opaque_keys, - traits::{ - AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify, - }, - transaction_validity::{TransactionSource, TransactionValidity}, - ApplyExtrinsicResult, MultiSignature, + create_runtime_str, generic, impl_opaque_keys, + traits::{ + AccountIdLookup, BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify, + }, + transaction_validity::{TransactionSource, TransactionValidity}, + ApplyExtrinsicResult, MultiSignature, }; use sp_std::prelude::*; @@ -35,17 +39,18 @@ use sp_version::RuntimeVersion; // A few exports that help ease life for downstream crates. pub use frame_support::{ - construct_runtime, parameter_types, - traits::{ - ConstU128, ConstU32, ConstU64, ConstU8, KeyOwnerProofSystem, Randomness, StorageInfo, - }, - weights::{ - constants::{ - BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, - }, - IdentityFee, Weight, WeightToFeeCoefficients, WeightToFeeCoefficient, WeightToFeePolynomial - }, - StorageValue, + construct_runtime, parameter_types, + traits::{ + ConstU128, ConstU32, ConstU64, ConstU8, KeyOwnerProofSystem, Randomness, StorageInfo, + }, + weights::{ + constants::{ + BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight, WEIGHT_REF_TIME_PER_SECOND, + }, + IdentityFee, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, + WeightToFeePolynomial, + }, + StorageValue, }; pub use frame_system::Call as SystemCall; pub use pallet_balances::Call as BalancesCall; @@ -85,42 +90,42 @@ type MemberCount = u32; // of data like extrinsics, allowing for them to continue syncing the network through upgrades // to even the core data structures. pub mod opaque { - use super::*; - - pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; - - // Opaque block header type. - pub type Header = generic::Header; - // Opaque block type. - pub type Block = generic::Block; - // Opaque block identifier type. - pub type BlockId = generic::BlockId; - - impl_opaque_keys! { - pub struct SessionKeys { - pub aura: Aura, - pub grandpa: Grandpa, - } - } + use super::*; + + pub use sp_runtime::OpaqueExtrinsic as UncheckedExtrinsic; + + // Opaque block header type. + pub type Header = generic::Header; + // Opaque block type. + pub type Block = generic::Block; + // Opaque block identifier type. + pub type BlockId = generic::BlockId; + + impl_opaque_keys! { + pub struct SessionKeys { + pub aura: Aura, + pub grandpa: Grandpa, + } + } } // To learn more about runtime versioning, see: // https://docs.substrate.io/main-docs/build/upgrade#runtime-versioning #[sp_version::runtime_version] pub const VERSION: RuntimeVersion = RuntimeVersion { - spec_name: create_runtime_str!("node-subtensor"), - impl_name: create_runtime_str!("node-subtensor"), - authoring_version: 1, - // The version of the runtime specification. A full node will not attempt to use its native - // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, - // `spec_version`, and `authoring_version` are the same between Wasm and native. - // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use - // the compatible custom types. - spec_version: 125, - impl_version: 1, - apis: RUNTIME_API_VERSIONS, - transaction_version: 1, - state_version: 1, + spec_name: create_runtime_str!("node-subtensor"), + impl_name: create_runtime_str!("node-subtensor"), + authoring_version: 1, + // The version of the runtime specification. A full node will not attempt to use its native + // runtime in substitute for the on-chain Wasm runtime unless all of `spec_name`, + // `spec_version`, and `authoring_version` are the same between Wasm and native. + // This value is set to 100 to notify Polkadot-JS App (https://polkadot.js.org/apps) to use + // the compatible custom types. + spec_version: 126, + impl_version: 1, + apis: RUNTIME_API_VERSIONS, + transaction_version: 1, + state_version: 1, }; /// This determines the average expected block time that we are targeting. @@ -143,113 +148,116 @@ pub const DAYS: BlockNumber = HOURS * 24; // The version information used to identify this runtime when compiled natively. #[cfg(feature = "std")] pub fn native_version() -> NativeVersion { - NativeVersion { runtime_version: VERSION, can_author_with: Default::default() } + NativeVersion { + runtime_version: VERSION, + can_author_with: Default::default(), + } } const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); parameter_types! { - pub const BlockHashCount: BlockNumber = 2400; - pub const Version: RuntimeVersion = VERSION; - // We allow for 2 seconds of compute with a 6 second average block time. - pub BlockWeights: frame_system::limits::BlockWeights = - frame_system::limits::BlockWeights::with_sensible_defaults( - Weight::from_parts(4u64 * WEIGHT_REF_TIME_PER_SECOND, u64::MAX), - NORMAL_DISPATCH_RATIO, - ); - pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength - ::max_with_normal_ratio(10 * 1024 * 1024, NORMAL_DISPATCH_RATIO); - pub const SS58Prefix: u8 = 42; + pub const BlockHashCount: BlockNumber = 2400; + pub const Version: RuntimeVersion = VERSION; + // We allow for 2 seconds of compute with a 6 second average block time. + pub BlockWeights: frame_system::limits::BlockWeights = + frame_system::limits::BlockWeights::with_sensible_defaults( + Weight::from_parts(4u64 * WEIGHT_REF_TIME_PER_SECOND, u64::MAX), + NORMAL_DISPATCH_RATIO, + ); + pub BlockLength: frame_system::limits::BlockLength = frame_system::limits::BlockLength + ::max_with_normal_ratio(10 * 1024 * 1024, NORMAL_DISPATCH_RATIO); + pub const SS58Prefix: u8 = 42; } // Configure FRAME pallets to include in runtime. impl frame_system::Config for Runtime { - // The basic call filter to use in dispatchable. - type BaseCallFilter = frame_support::traits::Everything; - // Block & extrinsics weights: base values and limits. - type BlockWeights = BlockWeights; - // The maximum length of a block (in bytes). - type BlockLength = BlockLength; - // The identifier used to distinguish between accounts. - type AccountId = AccountId; - // The aggregated dispatch type that is available for extrinsics. - type RuntimeCall = RuntimeCall; - // The lookup mechanism to get account ID from whatever is passed in dispatchers. - type Lookup = AccountIdLookup; - // The index type for storing how many extrinsics an account has signed. - type Index = Index; - // The index type for blocks. - type BlockNumber = BlockNumber; - // The type for hashing blocks and tries. - type Hash = Hash; - // The hashing algorithm used. - type Hashing = BlakeTwo256; - // The header type. - type Header = generic::Header; - // The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - // The ubiquitous origin type. - type RuntimeOrigin = RuntimeOrigin; - // Maximum number of block number to block hash mappings to keep (oldest pruned first). - type BlockHashCount = BlockHashCount; - // The weight of database operations that the runtime can invoke. - type DbWeight = RocksDbWeight; - // Version of the runtime. - type Version = Version; - // Converts a module to the index of the module in `construct_runtime!`. - // - // This type is being generated by `construct_runtime!`. - type PalletInfo = PalletInfo; - // What to do if a new account is created. - type OnNewAccount = (); - // What to do if an account is fully reaped from the system. - type OnKilledAccount = (); - // The data to be stored in an account. - type AccountData = pallet_balances::AccountData; - // Weight information for the extrinsics of this pallet. - type SystemWeightInfo = (); - // This is used as an identifier of the chain. 42 is the generic substrate prefix. - type SS58Prefix = SS58Prefix; - // The set code logic, just the default since we're not a parachain. - type OnSetCode = (); - type MaxConsumers = frame_support::traits::ConstU32<16>; + // The basic call filter to use in dispatchable. + type BaseCallFilter = frame_support::traits::Everything; + // Block & extrinsics weights: base values and limits. + type BlockWeights = BlockWeights; + // The maximum length of a block (in bytes). + type BlockLength = BlockLength; + // The identifier used to distinguish between accounts. + type AccountId = AccountId; + // The aggregated dispatch type that is available for extrinsics. + type RuntimeCall = RuntimeCall; + // The lookup mechanism to get account ID from whatever is passed in dispatchers. + type Lookup = AccountIdLookup; + // The index type for storing how many extrinsics an account has signed. + type Index = Index; + // The index type for blocks. + type BlockNumber = BlockNumber; + // The type for hashing blocks and tries. + type Hash = Hash; + // The hashing algorithm used. + type Hashing = BlakeTwo256; + // The header type. + type Header = generic::Header; + // The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + // The ubiquitous origin type. + type RuntimeOrigin = RuntimeOrigin; + // Maximum number of block number to block hash mappings to keep (oldest pruned first). + type BlockHashCount = BlockHashCount; + // The weight of database operations that the runtime can invoke. + type DbWeight = RocksDbWeight; + // Version of the runtime. + type Version = Version; + // Converts a module to the index of the module in `construct_runtime!`. + // + // This type is being generated by `construct_runtime!`. + type PalletInfo = PalletInfo; + // What to do if a new account is created. + type OnNewAccount = (); + // What to do if an account is fully reaped from the system. + type OnKilledAccount = (); + // The data to be stored in an account. + type AccountData = pallet_balances::AccountData; + // Weight information for the extrinsics of this pallet. + type SystemWeightInfo = (); + // This is used as an identifier of the chain. 42 is the generic substrate prefix. + type SS58Prefix = SS58Prefix; + // The set code logic, just the default since we're not a parachain. + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; } impl pallet_insecure_randomness_collective_flip::Config for Runtime {} impl pallet_aura::Config for Runtime { - type AuthorityId = AuraId; - type DisabledValidators = (); - type MaxAuthorities = ConstU32<32>; + type AuthorityId = AuraId; + type DisabledValidators = (); + type MaxAuthorities = ConstU32<32>; } impl pallet_grandpa::Config for Runtime { - type RuntimeEvent = RuntimeEvent; + type RuntimeEvent = RuntimeEvent; - type KeyOwnerProofSystem = (); + type KeyOwnerProofSystem = (); - type KeyOwnerProof = - >::Proof; + type KeyOwnerProof = + >::Proof; - type KeyOwnerIdentification = >::IdentificationTuple; + type KeyOwnerIdentification = >::IdentificationTuple; - type HandleEquivocation = (); + type HandleEquivocation = (); - type WeightInfo = (); - type MaxAuthorities = ConstU32<32>; - type MaxSetIdSessionEntries = ConstU64<0>; + type WeightInfo = (); + type MaxAuthorities = ConstU32<32>; + type MaxSetIdSessionEntries = ConstU64<0>; } impl pallet_timestamp::Config for Runtime { - // A timestamp: milliseconds since the unix epoch. - type Moment = u64; - type OnTimestampSet = Aura; - type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; - type WeightInfo = (); + // A timestamp: milliseconds since the unix epoch. + type Moment = u64; + type OnTimestampSet = Aura; + type MinimumPeriod = ConstU64<{ SLOT_DURATION / 2 }>; + type WeightInfo = (); } impl pallet_utility::Config for Runtime { @@ -263,238 +271,248 @@ impl pallet_utility::Config for Runtime { pub const EXISTENTIAL_DEPOSIT: u64 = 500; impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<50>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - // The type for recording an account's balance. - type Balance = Balance; - // The ubiquitous event type. - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64; - type AccountStore = System; - type WeightInfo = pallet_balances::weights::SubstrateWeight; + type MaxLocks = ConstU32<50>; + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + // The type for recording an account's balance. + type Balance = Balance; + // The ubiquitous event type. + type RuntimeEvent = RuntimeEvent; + type DustRemoval = (); + type ExistentialDeposit = ConstU64; + type AccountStore = System; + type WeightInfo = pallet_balances::weights::SubstrateWeight; } pub struct LinearWeightToFee(sp_std::marker::PhantomData); impl WeightToFeePolynomial for LinearWeightToFee where - C: Get, + C: Get, { - type Balance = Balance; - - fn polynomial() -> WeightToFeeCoefficients { - let coefficient = WeightToFeeCoefficient { - coeff_integer: 0, - coeff_frac: Perbill::from_parts(1), - negative: false, - degree: 1, - }; - - smallvec!(coefficient) - } + type Balance = Balance; + + fn polynomial() -> WeightToFeeCoefficients { + let coefficient = WeightToFeeCoefficient { + coeff_integer: 0, + coeff_frac: Perbill::from_parts(1), + negative: false, + degree: 1, + }; + + smallvec!(coefficient) + } } parameter_types! { - // Used with LinearWeightToFee conversion. - pub const FeeWeightRatio: u64 = 1; - pub const TransactionByteFee: u128 = 1; - pub FeeMultiplier: Multiplier = Multiplier::one(); + // Used with LinearWeightToFee conversion. + pub const FeeWeightRatio: u64 = 1; + pub const TransactionByteFee: u128 = 1; + pub FeeMultiplier: Multiplier = Multiplier::one(); } impl pallet_transaction_payment::Config for Runtime { - type RuntimeEvent = RuntimeEvent; + type RuntimeEvent = RuntimeEvent; - type OnChargeTransaction = CurrencyAdapter; - //type TransactionByteFee = TransactionByteFee; + type OnChargeTransaction = CurrencyAdapter; + //type TransactionByteFee = TransactionByteFee; - // Convert dispatch weight to a chargeable fee. - type WeightToFee = LinearWeightToFee; + // Convert dispatch weight to a chargeable fee. + type WeightToFee = LinearWeightToFee; - type FeeMultiplierUpdate = (); + type FeeMultiplierUpdate = (); - type OperationalFeeMultiplier = ConstU8<1>; + type OperationalFeeMultiplier = ConstU8<1>; - type LengthToFee = IdentityFee; - //type FeeMultiplierUpdate = ConstFeeMultiplier; + type LengthToFee = IdentityFee; + //type FeeMultiplierUpdate = ConstFeeMultiplier; } // Configure collective pallet for council parameter_types! { - pub const CouncilMotionDuration: BlockNumber = 6 * DAYS; - pub const CouncilMaxProposals: u32 = 10; - pub const CouncilMaxMembers: u32 = 3; + pub const CouncilMotionDuration: BlockNumber = 6 * DAYS; + pub const CouncilMaxProposals: u32 = 10; + pub const CouncilMaxMembers: u32 = 3; } // Configure collective pallet for Senate parameter_types! { - pub const SenateMaxMembers: u32 = 12; + pub const SenateMaxMembers: u32 = 12; } use pallet_collective::{CanPropose, CanVote, GetVotingMembers}; pub struct CanProposeToTriumvirate; impl CanPropose for CanProposeToTriumvirate { - fn can_propose(account: &AccountId) -> bool { - Triumvirate::is_member(account) - } + fn can_propose(account: &AccountId) -> bool { + Triumvirate::is_member(account) + } } pub struct CanVoteToTriumvirate; impl CanVote for CanVoteToTriumvirate { - fn can_vote(account: &AccountId) -> bool { - //Senate::is_member(account) - false // Disable voting from pallet_collective::vote - } + fn can_vote(account: &AccountId) -> bool { + //Senate::is_member(account) + false // Disable voting from pallet_collective::vote + } } -use pallet_subtensor::{MemberManagement, CollectiveInterface}; +use pallet_subtensor::{CollectiveInterface, MemberManagement}; pub struct ManageSenateMembers; impl MemberManagement for ManageSenateMembers { - fn add_member(account: &AccountId) -> DispatchResult { - let who = Address::Id( account.clone() ); - SenateMembers::add_member(RawOrigin::Root.into(), who) - } - - fn remove_member(account: &AccountId) -> DispatchResult { - let who = Address::Id( account.clone() ); - SenateMembers::remove_member(RawOrigin::Root.into(), who) - } - - fn swap_member(rm: &AccountId, add: &AccountId) -> DispatchResult { - let remove = Address::Id( rm.clone() ); - let add = Address::Id( add.clone() ); - - Triumvirate::remove_votes(rm)?; - SenateMembers::swap_member(RawOrigin::Root.into(), remove, add) - } - - fn is_member(account: &AccountId) -> bool { - Senate::is_member(account) - } - - fn members() -> Vec { - Senate::members() - } - - fn max_members() -> u32 { - SenateMaxMembers::get() - } + fn add_member(account: &AccountId) -> DispatchResult { + let who = Address::Id(account.clone()); + SenateMembers::add_member(RawOrigin::Root.into(), who) + } + + fn remove_member(account: &AccountId) -> DispatchResult { + let who = Address::Id(account.clone()); + SenateMembers::remove_member(RawOrigin::Root.into(), who) + } + + fn swap_member(rm: &AccountId, add: &AccountId) -> DispatchResult { + let remove = Address::Id(rm.clone()); + let add = Address::Id(add.clone()); + + Triumvirate::remove_votes(rm)?; + SenateMembers::swap_member(RawOrigin::Root.into(), remove, add) + } + + fn is_member(account: &AccountId) -> bool { + Senate::is_member(account) + } + + fn members() -> Vec { + Senate::members() + } + + fn max_members() -> u32 { + SenateMaxMembers::get() + } } pub struct GetSenateMemberCount; impl GetVotingMembers for GetSenateMemberCount { - fn get_count() -> MemberCount {Senate::members().len() as u32} + fn get_count() -> MemberCount { + Senate::members().len() as u32 + } } impl Get for GetSenateMemberCount { - fn get() -> MemberCount {SenateMaxMembers::get()} + fn get() -> MemberCount { + SenateMaxMembers::get() + } } pub struct TriumvirateVotes; impl CollectiveInterface for TriumvirateVotes { - fn remove_votes(hotkey: &AccountId) -> Result { - Triumvirate::remove_votes(hotkey) - } - - fn add_vote(hotkey: &AccountId, proposal: Hash, index: u32, approve: bool) -> Result { - Triumvirate::do_vote(hotkey.clone(), proposal, index, approve) - } + fn remove_votes(hotkey: &AccountId) -> Result { + Triumvirate::remove_votes(hotkey) + } + + fn add_vote( + hotkey: &AccountId, + proposal: Hash, + index: u32, + approve: bool, + ) -> Result { + Triumvirate::do_vote(hotkey.clone(), proposal, index, approve) + } } -type EnsureMajoritySenate = pallet_collective::EnsureProportionMoreThan; +type EnsureMajoritySenate = + pallet_collective::EnsureProportionMoreThan; // We call pallet_collective TriumvirateCollective type TriumvirateCollective = pallet_collective::Instance1; impl pallet_collective::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = GetSenateMemberCount; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureNever; - type CanPropose = CanProposeToTriumvirate; - type CanVote = CanVoteToTriumvirate; - type GetVotingMembers = GetSenateMemberCount; + type RuntimeOrigin = RuntimeOrigin; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = CouncilMaxProposals; + type MaxMembers = GetSenateMemberCount; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = pallet_collective::weights::SubstrateWeight; + type SetMembersOrigin = EnsureNever; + type CanPropose = CanProposeToTriumvirate; + type CanVote = CanVoteToTriumvirate; + type GetVotingMembers = GetSenateMemberCount; } // We call council members Triumvirate type TriumvirateMembership = pallet_membership::Instance1; impl pallet_membership::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRoot; - type RemoveOrigin = EnsureRoot; - type SwapOrigin = EnsureRoot; - type ResetOrigin = EnsureRoot; - type PrimeOrigin = EnsureRoot; - type MembershipInitialized = Triumvirate; - type MembershipChanged = Triumvirate; - type MaxMembers = CouncilMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type AddOrigin = EnsureRoot; + type RemoveOrigin = EnsureRoot; + type SwapOrigin = EnsureRoot; + type ResetOrigin = EnsureRoot; + type PrimeOrigin = EnsureRoot; + type MembershipInitialized = Triumvirate; + type MembershipChanged = Triumvirate; + type MaxMembers = CouncilMaxMembers; + type WeightInfo = pallet_membership::weights::SubstrateWeight; } // This is a dummy collective instance for managing senate members // Probably not the best solution, but fastest implementation type SenateCollective = pallet_collective::Instance2; impl pallet_collective::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type Proposal = RuntimeCall; - type RuntimeEvent = RuntimeEvent; - type MotionDuration = CouncilMotionDuration; - type MaxProposals = CouncilMaxProposals; - type MaxMembers = SenateMaxMembers; - type DefaultVote = pallet_collective::PrimeDefaultVote; - type WeightInfo = pallet_collective::weights::SubstrateWeight; - type SetMembersOrigin = EnsureNever; - type CanPropose = (); - type CanVote = (); - type GetVotingMembers = (); + type RuntimeOrigin = RuntimeOrigin; + type Proposal = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type MotionDuration = CouncilMotionDuration; + type MaxProposals = CouncilMaxProposals; + type MaxMembers = SenateMaxMembers; + type DefaultVote = pallet_collective::PrimeDefaultVote; + type WeightInfo = pallet_collective::weights::SubstrateWeight; + type SetMembersOrigin = EnsureNever; + type CanPropose = (); + type CanVote = (); + type GetVotingMembers = (); } // We call our top K delegates membership Senate type SenateMembership = pallet_membership::Instance2; impl pallet_membership::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type AddOrigin = EnsureRoot; - type RemoveOrigin = EnsureRoot; - type SwapOrigin = EnsureRoot; - type ResetOrigin = EnsureRoot; - type PrimeOrigin = EnsureRoot; - type MembershipInitialized = Senate; - type MembershipChanged = Senate; - type MaxMembers = SenateMaxMembers; - type WeightInfo = pallet_membership::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type AddOrigin = EnsureRoot; + type RemoveOrigin = EnsureRoot; + type SwapOrigin = EnsureRoot; + type ResetOrigin = EnsureRoot; + type PrimeOrigin = EnsureRoot; + type MembershipInitialized = Senate; + type MembershipChanged = Senate; + type MaxMembers = SenateMaxMembers; + type WeightInfo = pallet_membership::weights::SubstrateWeight; } impl pallet_sudo::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; } parameter_types! { - // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. - pub const DepositBase: Balance = (1) as Balance * 2_000 * 10_000_000 + (88 as Balance) * 100 * 1_000_000; - // Additional storage item size of 32 bytes. - pub const DepositFactor: Balance = (0) as Balance * 2_000 * 10_000_000 + (32 as Balance) * 100 * 1_000_000; - pub const MaxSignatories: u32 = 100; + // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. + pub const DepositBase: Balance = (1) as Balance * 2_000 * 10_000_000 + (88 as Balance) * 100 * 1_000_000; + // Additional storage item size of 32 bytes. + pub const DepositFactor: Balance = (0) as Balance * 2_000 * 10_000_000 + (32 as Balance) * 100 * 1_000_000; + pub const MaxSignatories: u32 = 100; } impl pallet_multisig::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type RuntimeCall = RuntimeCall; - type Currency = Balances; - type DepositBase = DepositBase; - type DepositFactor = DepositFactor; - type MaxSignatories = MaxSignatories; - type WeightInfo = pallet_multisig::weights::SubstrateWeight; + type RuntimeEvent = RuntimeEvent; + type RuntimeCall = RuntimeCall; + type Currency = Balances; + type DepositBase = DepositBase; + type DepositFactor = DepositFactor; + type MaxSignatories = MaxSignatories; + type WeightInfo = pallet_multisig::weights::SubstrateWeight; } // Configure the pallet subtensor. parameter_types! { - pub const SubtensorInitialRho: u16 = 10; - pub const SubtensorInitialKappa: u16 = 32_767; // 0.5 = 65535/2 + pub const SubtensorInitialRho: u16 = 10; + pub const SubtensorInitialKappa: u16 = 32_767; // 0.5 = 65535/2 pub const SubtensorInitialMaxAllowedUids: u16 = 4096; pub const SubtensorInitialIssuance: u64 = 0; pub const SubtensorInitialMinAllowedWeights: u16 = 1024; @@ -513,6 +531,7 @@ parameter_types! { pub const SubtensorInitialTempo: u16 = 99; pub const SubtensorInitialDifficulty: u64 = 10_000_000; pub const SubtensorInitialAdjustmentInterval: u16 = 100; + pub const SubtensorInitialAdjustmentAlpha: u64 = 0; // no weight to previous value. pub const SubtensorInitialTargetRegistrationsPerInterval: u16 = 2; pub const SubtensorInitialImmunityPeriod: u16 = 4096; pub const SubtensorInitialActivityCutoff: u16 = 5000; @@ -523,86 +542,87 @@ parameter_types! { pub const SubtensorInitialWeightsVersionKey: u64 = 0; pub const SubtensorInitialMinDifficulty: u64 = 10_000_000; pub const SubtensorInitialMaxDifficulty: u64 = u64::MAX / 4; - pub const SubtensorInitialServingRateLimit: u64 = 50; - pub const SubtensorInitialBurn: u64 = 1_000_000_000; // 1 tao - pub const SubtensorInitialMinBurn: u64 = 1_000_000_000; // 1 tao - pub const SubtensorInitialMaxBurn: u64 = 100_000_000_000; // 100 tao - pub const SubtensorInitialTxRateLimit: u64 = 1000; - pub const SubtensorInitialRAORecycledForRegistration: u64 = 0; // 0 rao - pub const SubtensorInitialSenateRequiredStakePercentage: u64 = 1; // 1 percent of total stake + pub const SubtensorInitialServingRateLimit: u64 = 50; + pub const SubtensorInitialBurn: u64 = 1_000_000_000; // 1 tao + pub const SubtensorInitialMinBurn: u64 = 1_000_000_000; // 1 tao + pub const SubtensorInitialMaxBurn: u64 = 100_000_000_000; // 100 tao + pub const SubtensorInitialTxRateLimit: u64 = 1000; + pub const SubtensorInitialRAORecycledForRegistration: u64 = 0; // 0 rao + pub const SubtensorInitialSenateRequiredStakePercentage: u64 = 1; // 1 percent of total stake } impl pallet_subtensor::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SudoRuntimeCall = RuntimeCall; - type Currency = Balances; - type CouncilOrigin = EnsureMajoritySenate; - type SenateMembers = ManageSenateMembers; - type TriumvirateInterface = TriumvirateVotes; - - type InitialRho = SubtensorInitialRho; - type InitialKappa = SubtensorInitialKappa; - type InitialMaxAllowedUids = SubtensorInitialMaxAllowedUids; - type InitialBondsMovingAverage = SubtensorInitialBondsMovingAverage; - type InitialIssuance = SubtensorInitialIssuance; - type InitialMinAllowedWeights = SubtensorInitialMinAllowedWeights; - type InitialEmissionValue = SubtensorInitialEmissionValue; - type InitialMaxWeightsLimit = SubtensorInitialMaxWeightsLimit; - type InitialValidatorBatchSize = SubtensorInitialValidatorBatchSize; - type InitialValidatorSequenceLen = SubtensorInitialValidatorSequenceLen; - type InitialValidatorEpochLen = SubtensorInitialValidatorEpochLen; - type InitialValidatorEpochsPerReset = SubtensorInitialValidatorEpochsPerReset; - type InitialValidatorExcludeQuantile = SubtensorInitialValidatorExcludeQuantile; - type InitialValidatorPruneLen = SubtensorInitialValidatorPruneLen; - type InitialValidatorLogitsDivergence = SubtensorInitialValidatorLogitsDivergence; - type InitialScalingLawPower = SubtensorInitialScalingLawPower; - type InitialSynergyScalingLawPower = SubtensorInitialSynergyScalingLawPower; - type InitialTempo = SubtensorInitialTempo; - type InitialDifficulty = SubtensorInitialDifficulty; - type InitialAdjustmentInterval = SubtensorInitialAdjustmentInterval; - type InitialTargetRegistrationsPerInterval = SubtensorInitialTargetRegistrationsPerInterval; - type InitialImmunityPeriod = SubtensorInitialImmunityPeriod; - type InitialActivityCutoff = SubtensorInitialActivityCutoff; - type InitialMaxRegistrationsPerBlock = SubtensorInitialMaxRegistrationsPerBlock; - type InitialPruningScore = SubtensorInitialPruningScore; - type InitialMaxAllowedValidators = SubtensorInitialMaxAllowedValidators; - type InitialDefaultTake = SubtensorInitialDefaultTake; - type InitialWeightsVersionKey = SubtensorInitialWeightsVersionKey; - type InitialMaxDifficulty = SubtensorInitialMaxDifficulty; - type InitialMinDifficulty = SubtensorInitialMinDifficulty; - type InitialServingRateLimit = SubtensorInitialServingRateLimit; - type InitialBurn = SubtensorInitialBurn; - type InitialMaxBurn = SubtensorInitialMaxBurn; - type InitialMinBurn = SubtensorInitialMinBurn; - type InitialTxRateLimit = SubtensorInitialTxRateLimit; - type InitialRAORecycledForRegistration = SubtensorInitialRAORecycledForRegistration; - type InitialSenateRequiredStakePercentage = SubtensorInitialSenateRequiredStakePercentage; + type RuntimeEvent = RuntimeEvent; + type SudoRuntimeCall = RuntimeCall; + type Currency = Balances; + type CouncilOrigin = EnsureMajoritySenate; + type SenateMembers = ManageSenateMembers; + type TriumvirateInterface = TriumvirateVotes; + + type InitialRho = SubtensorInitialRho; + type InitialKappa = SubtensorInitialKappa; + type InitialMaxAllowedUids = SubtensorInitialMaxAllowedUids; + type InitialBondsMovingAverage = SubtensorInitialBondsMovingAverage; + type InitialIssuance = SubtensorInitialIssuance; + type InitialMinAllowedWeights = SubtensorInitialMinAllowedWeights; + type InitialEmissionValue = SubtensorInitialEmissionValue; + type InitialMaxWeightsLimit = SubtensorInitialMaxWeightsLimit; + type InitialValidatorBatchSize = SubtensorInitialValidatorBatchSize; + type InitialValidatorSequenceLen = SubtensorInitialValidatorSequenceLen; + type InitialValidatorEpochLen = SubtensorInitialValidatorEpochLen; + type InitialValidatorEpochsPerReset = SubtensorInitialValidatorEpochsPerReset; + type InitialValidatorExcludeQuantile = SubtensorInitialValidatorExcludeQuantile; + type InitialValidatorPruneLen = SubtensorInitialValidatorPruneLen; + type InitialValidatorLogitsDivergence = SubtensorInitialValidatorLogitsDivergence; + type InitialScalingLawPower = SubtensorInitialScalingLawPower; + type InitialSynergyScalingLawPower = SubtensorInitialSynergyScalingLawPower; + type InitialTempo = SubtensorInitialTempo; + type InitialDifficulty = SubtensorInitialDifficulty; + type InitialAdjustmentInterval = SubtensorInitialAdjustmentInterval; + type InitialAdjustmentAlpha = SubtensorInitialAdjustmentAlpha; + type InitialTargetRegistrationsPerInterval = SubtensorInitialTargetRegistrationsPerInterval; + type InitialImmunityPeriod = SubtensorInitialImmunityPeriod; + type InitialActivityCutoff = SubtensorInitialActivityCutoff; + type InitialMaxRegistrationsPerBlock = SubtensorInitialMaxRegistrationsPerBlock; + type InitialPruningScore = SubtensorInitialPruningScore; + type InitialMaxAllowedValidators = SubtensorInitialMaxAllowedValidators; + type InitialDefaultTake = SubtensorInitialDefaultTake; + type InitialWeightsVersionKey = SubtensorInitialWeightsVersionKey; + type InitialMaxDifficulty = SubtensorInitialMaxDifficulty; + type InitialMinDifficulty = SubtensorInitialMinDifficulty; + type InitialServingRateLimit = SubtensorInitialServingRateLimit; + type InitialBurn = SubtensorInitialBurn; + type InitialMaxBurn = SubtensorInitialMaxBurn; + type InitialMinBurn = SubtensorInitialMinBurn; + type InitialTxRateLimit = SubtensorInitialTxRateLimit; + type InitialRAORecycledForRegistration = SubtensorInitialRAORecycledForRegistration; + type InitialSenateRequiredStakePercentage = SubtensorInitialSenateRequiredStakePercentage; } // Create the runtime by composing the FRAME pallets that were previously configured. construct_runtime!( - pub struct Runtime - where - Block = Block, - NodeBlock = opaque::Block, - UncheckedExtrinsic = UncheckedExtrinsic, - { - System: frame_system, - RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, - Timestamp: pallet_timestamp, - Aura: pallet_aura, - Grandpa: pallet_grandpa, - Balances: pallet_balances, - TransactionPayment: pallet_transaction_payment, - SubtensorModule: pallet_subtensor, - Triumvirate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, - TriumvirateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, - Senate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, - SenateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, - Utility: pallet_utility, - Sudo: pallet_sudo, - Multisig: pallet_multisig - } + pub struct Runtime + where + Block = Block, + NodeBlock = opaque::Block, + UncheckedExtrinsic = UncheckedExtrinsic, + { + System: frame_system, + RandomnessCollectiveFlip: pallet_insecure_randomness_collective_flip, + Timestamp: pallet_timestamp, + Aura: pallet_aura, + Grandpa: pallet_grandpa, + Balances: pallet_balances, + TransactionPayment: pallet_transaction_payment, + SubtensorModule: pallet_subtensor, + Triumvirate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, + TriumvirateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, + Senate: pallet_collective::::{Pallet, Call, Storage, Origin, Event, Config}, + SenateMembers: pallet_membership::::{Pallet, Call, Storage, Event, Config}, + Utility: pallet_utility, + Sudo: pallet_sudo, + Multisig: pallet_multisig + } ); // The address format for describing accounts. @@ -613,29 +633,29 @@ pub type Header = generic::Header; pub type Block = generic::Block; // The SignedExtension to the basic transaction logic. pub type SignedExtra = ( - frame_system::CheckNonZeroSender, - frame_system::CheckSpecVersion, - frame_system::CheckTxVersion, - frame_system::CheckGenesis, - frame_system::CheckEra, - frame_system::CheckNonce, - frame_system::CheckWeight, - pallet_transaction_payment::ChargeTransactionPayment, - pallet_subtensor::SubtensorSignedExtension + frame_system::CheckNonZeroSender, + frame_system::CheckSpecVersion, + frame_system::CheckTxVersion, + frame_system::CheckGenesis, + frame_system::CheckEra, + frame_system::CheckNonce, + frame_system::CheckWeight, + pallet_transaction_payment::ChargeTransactionPayment, + pallet_subtensor::SubtensorSignedExtension, ); // Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = - generic::UncheckedExtrinsic; + generic::UncheckedExtrinsic; // The payload being signed in transactions. pub type SignedPayload = generic::SignedPayload; // Executive: handles dispatch to the various modules. pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllPalletsWithSystem, + Runtime, + Block, + frame_system::ChainContext, + Runtime, + AllPalletsWithSystem, >; #[cfg(feature = "runtime-benchmarks")] @@ -644,343 +664,343 @@ extern crate frame_benchmarking; #[cfg(feature = "runtime-benchmarks")] mod benches { - define_benchmarks!( - [frame_benchmarking, BaselineBench::] - [frame_system, SystemBench::] - [pallet_balances, Balances] - [pallet_subtensor, SubtensorModule] - [pallet_timestamp, Timestamp] - ); + define_benchmarks!( + [frame_benchmarking, BaselineBench::] + [frame_system, SystemBench::] + [pallet_balances, Balances] + [pallet_subtensor, SubtensorModule] + [pallet_timestamp, Timestamp] + ); } impl_runtime_apis! { - impl sp_api::Core for Runtime { - fn version() -> RuntimeVersion { - VERSION - } - - fn execute_block(block: Block) { - Executive::execute_block(block); - } - - fn initialize_block(header: &::Header) { - Executive::initialize_block(header) - } - } - - impl sp_api::Metadata for Runtime { - fn metadata() -> OpaqueMetadata { - OpaqueMetadata::new(Runtime::metadata().into()) - } - } - - impl sp_block_builder::BlockBuilder for Runtime { - fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { - Executive::apply_extrinsic(extrinsic) - } - - fn finalize_block() -> ::Header { - Executive::finalize_block() - } - - fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { - data.create_extrinsics() - } - - fn check_inherents( - block: Block, - data: sp_inherents::InherentData, - ) -> sp_inherents::CheckInherentsResult { - data.check_extrinsics(&block) - } - } - - impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { - fn validate_transaction( - source: TransactionSource, - tx: ::Extrinsic, - block_hash: ::Hash, - ) -> TransactionValidity { - Executive::validate_transaction(source, tx, block_hash) - } - } - - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(header: &::Header) { - Executive::offchain_worker(header) - } - } - - impl sp_consensus_aura::AuraApi for Runtime { - fn slot_duration() -> sp_consensus_aura::SlotDuration { - sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) - } - - fn authorities() -> Vec { - Aura::authorities().into_inner() - } - } - - impl sp_session::SessionKeys for Runtime { - fn generate_session_keys(seed: Option>) -> Vec { - opaque::SessionKeys::generate(seed) - } - - fn decode_session_keys( - encoded: Vec, - ) -> Option, KeyTypeId)>> { - opaque::SessionKeys::decode_into_raw_public_keys(&encoded) - } - } - - impl fg_primitives::GrandpaApi for Runtime { - fn grandpa_authorities() -> GrandpaAuthorityList { - Grandpa::grandpa_authorities() - } - - fn current_set_id() -> fg_primitives::SetId { - Grandpa::current_set_id() - } - - fn submit_report_equivocation_unsigned_extrinsic( - _equivocation_proof: fg_primitives::EquivocationProof< - ::Hash, - NumberFor, - >, - _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, - ) -> Option<()> { - None - } - - fn generate_key_ownership_proof( - _set_id: fg_primitives::SetId, - _authority_id: GrandpaId, - ) -> Option { - // NOTE: this is the only implementation possible since we've - // defined our key owner proof type as a bottom type (i.e. a type - // with no values). - None - } - } - - impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { - fn account_nonce(account: AccountId) -> Index { - System::account_nonce(account) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { - fn query_info( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { - TransactionPayment::query_info(uxt, len) - } - fn query_fee_details( - uxt: ::Extrinsic, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_fee_details(uxt, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi - for Runtime - { - fn query_call_info( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::RuntimeDispatchInfo { - TransactionPayment::query_call_info(call, len) - } - fn query_call_fee_details( - call: RuntimeCall, - len: u32, - ) -> pallet_transaction_payment::FeeDetails { - TransactionPayment::query_call_fee_details(call, len) - } - fn query_weight_to_fee(weight: Weight) -> Balance { - TransactionPayment::weight_to_fee(weight) - } - fn query_length_to_fee(length: u32) -> Balance { - TransactionPayment::length_to_fee(length) - } - } - - #[cfg(feature = "runtime-benchmarks")] - impl frame_benchmarking::Benchmark for Runtime { - fn benchmark_metadata(extra: bool) -> ( - Vec, - Vec, - ) { - use frame_benchmarking::{baseline, Benchmarking, BenchmarkList}; - use frame_support::traits::StorageInfoTrait; - use frame_system_benchmarking::Pallet as SystemBench; - use baseline::Pallet as BaselineBench; - - let mut list = Vec::::new(); - list_benchmarks!(list, extra); - - let storage_info = AllPalletsWithSystem::storage_info(); - - (list, storage_info) - } - - fn dispatch_benchmark( - config: frame_benchmarking::BenchmarkConfig - ) -> Result, sp_runtime::RuntimeString> { - use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch, TrackedStorageKey}; - - use frame_system_benchmarking::Pallet as SystemBench; - use baseline::Pallet as BaselineBench; - - impl frame_system_benchmarking::Config for Runtime {} - impl baseline::Config for Runtime {} - - use frame_support::traits::WhitelistedStorageKeys; - let whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); - - let mut batches = Vec::::new(); - let params = (&config, &whitelist); - add_benchmarks!(params, batches); - - Ok(batches) - } - } - - #[cfg(feature = "try-runtime")] - impl frame_try_runtime::TryRuntime for Runtime { - fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { - // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to - // have a backtrace here. If any of the pre/post migration checks fail, we shall stop - // right here and right now. - let weight = Executive::try_runtime_upgrade(checks).unwrap(); - (weight, BlockWeights::get().max_block) - } - - fn execute_block( - block: Block, - state_root_check: bool, - signature_check: bool, - select: frame_try_runtime::TryStateSelect - ) -> Weight { - // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to - // have a backtrace here. - Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed") - } - } - - impl subtensor_custom_rpc_runtime_api::DelegateInfoRuntimeApi for Runtime { - fn get_delegates() -> Vec { - let result = SubtensorModule::get_delegates(); - result.encode() - } - - fn get_delegate(delegate_account_vec: Vec) -> Vec { - let _result = SubtensorModule::get_delegate(delegate_account_vec); - if _result.is_some() { - let result = _result.expect("Could not get DelegateInfo"); - result.encode() - } else { - vec![] - } - } - - fn get_delegated(delegatee_account_vec: Vec) -> Vec { - let result = SubtensorModule::get_delegated(delegatee_account_vec); - result.encode() - } - } - - impl subtensor_custom_rpc_runtime_api::NeuronInfoRuntimeApi for Runtime { - fn get_neurons_lite(netuid: u16) -> Vec { - let result = SubtensorModule::get_neurons_lite(netuid); - result.encode() - } - - fn get_neuron_lite(netuid: u16, uid: u16) -> Vec { - let _result = SubtensorModule::get_neuron_lite(netuid, uid); - if _result.is_some() { - let result = _result.expect("Could not get NeuronInfoLite"); - result.encode() - } else { - vec![] - } - } - - fn get_neurons(netuid: u16) -> Vec { - let result = SubtensorModule::get_neurons(netuid); - result.encode() - } - - fn get_neuron(netuid: u16, uid: u16) -> Vec { - let _result = SubtensorModule::get_neuron(netuid, uid); - if _result.is_some() { - let result = _result.expect("Could not get NeuronInfo"); - result.encode() - } else { - vec![] - } - } - } - - impl subtensor_custom_rpc_runtime_api::SubnetInfoRuntimeApi for Runtime { - fn get_subnet_info(netuid: u16) -> Vec { - let _result = SubtensorModule::get_subnet_info(netuid); - if _result.is_some() { - let result = _result.expect("Could not get SubnetInfo"); - result.encode() - } else { - vec![] - } - } - - fn get_subnets_info() -> Vec { - let result = SubtensorModule::get_subnets_info(); - result.encode() - } - } + impl sp_api::Core for Runtime { + fn version() -> RuntimeVersion { + VERSION + } + + fn execute_block(block: Block) { + Executive::execute_block(block); + } + + fn initialize_block(header: &::Header) { + Executive::initialize_block(header) + } + } + + impl sp_api::Metadata for Runtime { + fn metadata() -> OpaqueMetadata { + OpaqueMetadata::new(Runtime::metadata().into()) + } + } + + impl sp_block_builder::BlockBuilder for Runtime { + fn apply_extrinsic(extrinsic: ::Extrinsic) -> ApplyExtrinsicResult { + Executive::apply_extrinsic(extrinsic) + } + + fn finalize_block() -> ::Header { + Executive::finalize_block() + } + + fn inherent_extrinsics(data: sp_inherents::InherentData) -> Vec<::Extrinsic> { + data.create_extrinsics() + } + + fn check_inherents( + block: Block, + data: sp_inherents::InherentData, + ) -> sp_inherents::CheckInherentsResult { + data.check_extrinsics(&block) + } + } + + impl sp_transaction_pool::runtime_api::TaggedTransactionQueue for Runtime { + fn validate_transaction( + source: TransactionSource, + tx: ::Extrinsic, + block_hash: ::Hash, + ) -> TransactionValidity { + Executive::validate_transaction(source, tx, block_hash) + } + } + + impl sp_offchain::OffchainWorkerApi for Runtime { + fn offchain_worker(header: &::Header) { + Executive::offchain_worker(header) + } + } + + impl sp_consensus_aura::AuraApi for Runtime { + fn slot_duration() -> sp_consensus_aura::SlotDuration { + sp_consensus_aura::SlotDuration::from_millis(Aura::slot_duration()) + } + + fn authorities() -> Vec { + Aura::authorities().into_inner() + } + } + + impl sp_session::SessionKeys for Runtime { + fn generate_session_keys(seed: Option>) -> Vec { + opaque::SessionKeys::generate(seed) + } + + fn decode_session_keys( + encoded: Vec, + ) -> Option, KeyTypeId)>> { + opaque::SessionKeys::decode_into_raw_public_keys(&encoded) + } + } + + impl fg_primitives::GrandpaApi for Runtime { + fn grandpa_authorities() -> GrandpaAuthorityList { + Grandpa::grandpa_authorities() + } + + fn current_set_id() -> fg_primitives::SetId { + Grandpa::current_set_id() + } + + fn submit_report_equivocation_unsigned_extrinsic( + _equivocation_proof: fg_primitives::EquivocationProof< + ::Hash, + NumberFor, + >, + _key_owner_proof: fg_primitives::OpaqueKeyOwnershipProof, + ) -> Option<()> { + None + } + + fn generate_key_ownership_proof( + _set_id: fg_primitives::SetId, + _authority_id: GrandpaId, + ) -> Option { + // NOTE: this is the only implementation possible since we've + // defined our key owner proof type as a bottom type (i.e. a type + // with no values). + None + } + } + + impl frame_system_rpc_runtime_api::AccountNonceApi for Runtime { + fn account_nonce(account: AccountId) -> Index { + System::account_nonce(account) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi for Runtime { + fn query_info( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment_rpc_runtime_api::RuntimeDispatchInfo { + TransactionPayment::query_info(uxt, len) + } + fn query_fee_details( + uxt: ::Extrinsic, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_fee_details(uxt, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi + for Runtime + { + fn query_call_info( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::RuntimeDispatchInfo { + TransactionPayment::query_call_info(call, len) + } + fn query_call_fee_details( + call: RuntimeCall, + len: u32, + ) -> pallet_transaction_payment::FeeDetails { + TransactionPayment::query_call_fee_details(call, len) + } + fn query_weight_to_fee(weight: Weight) -> Balance { + TransactionPayment::weight_to_fee(weight) + } + fn query_length_to_fee(length: u32) -> Balance { + TransactionPayment::length_to_fee(length) + } + } + + #[cfg(feature = "runtime-benchmarks")] + impl frame_benchmarking::Benchmark for Runtime { + fn benchmark_metadata(extra: bool) -> ( + Vec, + Vec, + ) { + use frame_benchmarking::{baseline, Benchmarking, BenchmarkList}; + use frame_support::traits::StorageInfoTrait; + use frame_system_benchmarking::Pallet as SystemBench; + use baseline::Pallet as BaselineBench; + + let mut list = Vec::::new(); + list_benchmarks!(list, extra); + + let storage_info = AllPalletsWithSystem::storage_info(); + + (list, storage_info) + } + + fn dispatch_benchmark( + config: frame_benchmarking::BenchmarkConfig + ) -> Result, sp_runtime::RuntimeString> { + use frame_benchmarking::{baseline, Benchmarking, BenchmarkBatch, TrackedStorageKey}; + + use frame_system_benchmarking::Pallet as SystemBench; + use baseline::Pallet as BaselineBench; + + impl frame_system_benchmarking::Config for Runtime {} + impl baseline::Config for Runtime {} + + use frame_support::traits::WhitelistedStorageKeys; + let whitelist: Vec = AllPalletsWithSystem::whitelisted_storage_keys(); + + let mut batches = Vec::::new(); + let params = (&config, &whitelist); + add_benchmarks!(params, batches); + + Ok(batches) + } + } + + #[cfg(feature = "try-runtime")] + impl frame_try_runtime::TryRuntime for Runtime { + fn on_runtime_upgrade(checks: frame_try_runtime::UpgradeCheckSelect) -> (Weight, Weight) { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. If any of the pre/post migration checks fail, we shall stop + // right here and right now. + let weight = Executive::try_runtime_upgrade(checks).unwrap(); + (weight, BlockWeights::get().max_block) + } + + fn execute_block( + block: Block, + state_root_check: bool, + signature_check: bool, + select: frame_try_runtime::TryStateSelect + ) -> Weight { + // NOTE: intentional unwrap: we don't want to propagate the error backwards, and want to + // have a backtrace here. + Executive::try_execute_block(block, state_root_check, signature_check, select).expect("execute-block failed") + } + } + + impl subtensor_custom_rpc_runtime_api::DelegateInfoRuntimeApi for Runtime { + fn get_delegates() -> Vec { + let result = SubtensorModule::get_delegates(); + result.encode() + } + + fn get_delegate(delegate_account_vec: Vec) -> Vec { + let _result = SubtensorModule::get_delegate(delegate_account_vec); + if _result.is_some() { + let result = _result.expect("Could not get DelegateInfo"); + result.encode() + } else { + vec![] + } + } + + fn get_delegated(delegatee_account_vec: Vec) -> Vec { + let result = SubtensorModule::get_delegated(delegatee_account_vec); + result.encode() + } + } + + impl subtensor_custom_rpc_runtime_api::NeuronInfoRuntimeApi for Runtime { + fn get_neurons_lite(netuid: u16) -> Vec { + let result = SubtensorModule::get_neurons_lite(netuid); + result.encode() + } + + fn get_neuron_lite(netuid: u16, uid: u16) -> Vec { + let _result = SubtensorModule::get_neuron_lite(netuid, uid); + if _result.is_some() { + let result = _result.expect("Could not get NeuronInfoLite"); + result.encode() + } else { + vec![] + } + } + + fn get_neurons(netuid: u16) -> Vec { + let result = SubtensorModule::get_neurons(netuid); + result.encode() + } + + fn get_neuron(netuid: u16, uid: u16) -> Vec { + let _result = SubtensorModule::get_neuron(netuid, uid); + if _result.is_some() { + let result = _result.expect("Could not get NeuronInfo"); + result.encode() + } else { + vec![] + } + } + } + + impl subtensor_custom_rpc_runtime_api::SubnetInfoRuntimeApi for Runtime { + fn get_subnet_info(netuid: u16) -> Vec { + let _result = SubtensorModule::get_subnet_info(netuid); + if _result.is_some() { + let result = _result.expect("Could not get SubnetInfo"); + result.encode() + } else { + vec![] + } + } + + fn get_subnets_info() -> Vec { + let result = SubtensorModule::get_subnets_info(); + result.encode() + } + } } #[cfg(test)] mod tests { - use super::*; - use frame_support::traits::WhitelistedStorageKeys; - use sp_core::hexdisplay::HexDisplay; - use std::collections::HashSet; - - #[test] - fn check_whitelist() { - let whitelist: HashSet = AllPalletsWithSystem::whitelisted_storage_keys() - .iter() - .map(|e| HexDisplay::from(&e.key).to_string()) - .collect(); - - // Block Number - assert!( - whitelist.contains("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac") - ); - // Total Issuance - assert!( - whitelist.contains("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80") - ); - // Execution Phase - assert!( - whitelist.contains("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a") - ); - // Event Count - assert!( - whitelist.contains("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850") - ); - // System Events - assert!( - whitelist.contains("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7") - ); - } -} \ No newline at end of file + use super::*; + use frame_support::traits::WhitelistedStorageKeys; + use sp_core::hexdisplay::HexDisplay; + use std::collections::HashSet; + + #[test] + fn check_whitelist() { + let whitelist: HashSet = AllPalletsWithSystem::whitelisted_storage_keys() + .iter() + .map(|e| HexDisplay::from(&e.key).to_string()) + .collect(); + + // Block Number + assert!( + whitelist.contains("26aa394eea5630e07c48ae0c9558cef702a5c1b19ab7a04f536c519aca4983ac") + ); + // Total Issuance + assert!( + whitelist.contains("c2261276cc9d1f8598ea4b6a74b15c2f57c875e4cff74148e4628f264b974c80") + ); + // Execution Phase + assert!( + whitelist.contains("26aa394eea5630e07c48ae0c9558cef7ff553b5a9862a516939d82b3d3d8661a") + ); + // Event Count + assert!( + whitelist.contains("26aa394eea5630e07c48ae0c9558cef70a98fdbe9ce6c55837576c60c7af3850") + ); + // System Events + assert!( + whitelist.contains("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7") + ); + } +}