From 036ad916de2d66ea7b5e800d499ef61001a87d82 Mon Sep 17 00:00:00 2001 From: Liam Date: Thu, 25 Apr 2024 16:07:22 +0400 Subject: [PATCH 01/13] chore: clippy and rustc 1.77.2 chore: large enum chore: update toolchain , fix step --- node/src/benchmarking.rs | 2 +- node/src/cli.rs | 1 + pallets/admin-utils/tests/tests.rs | 6 +-- pallets/collective/src/benchmarking.rs | 2 +- pallets/commitments/src/benchmarking.rs | 9 ++-- pallets/registry/src/benchmarking.rs | 6 +-- pallets/subtensor/src/benchmarks.rs | 24 +++++----- pallets/subtensor/src/lib.rs | 2 +- pallets/subtensor/src/math.rs | 41 ++++------------- pallets/subtensor/src/migration.rs | 4 +- pallets/subtensor/src/root.rs | 17 +++---- pallets/subtensor/src/staking.rs | 6 +-- pallets/subtensor/tests/epoch.rs | 61 +++++++++++++------------ pallets/subtensor/tests/root.rs | 3 +- pallets/subtensor/tests/senate.rs | 3 -- pallets/subtensor/tests/serving.rs | 1 + pallets/subtensor/tests/staking.rs | 14 ++---- rust-toolchain.toml | 15 ++++-- 18 files changed, 96 insertions(+), 121 deletions(-) diff --git a/node/src/benchmarking.rs b/node/src/benchmarking.rs index 7848c2bbe..07c596947 100644 --- a/node/src/benchmarking.rs +++ b/node/src/benchmarking.rs @@ -89,7 +89,7 @@ impl frame_benchmarking_cli::ExtrinsicBuilder for TransferKeepAliveBuilder { acc, BalancesCall::transfer_keep_alive { dest: self.dest.clone().into(), - value: self.value.into(), + value: self.value, } .into(), nonce, diff --git a/node/src/cli.rs b/node/src/cli.rs index d0f848f0e..2c9c4c9fd 100644 --- a/node/src/cli.rs +++ b/node/src/cli.rs @@ -9,6 +9,7 @@ pub struct Cli { pub run: RunCmd, } +#[allow(clippy::large_enum_variant)] #[derive(Debug, clap::Subcommand)] pub enum Subcommand { // Key management cli utilities diff --git a/pallets/admin-utils/tests/tests.rs b/pallets/admin-utils/tests/tests.rs index 7ef34cbef..4d2c44013 100644 --- a/pallets/admin-utils/tests/tests.rs +++ b/pallets/admin-utils/tests/tests.rs @@ -881,13 +881,13 @@ mod sudo_set_nominator_min_required_stake { #[test] fn can_only_be_called_by_admin() { new_test_ext().execute_with(|| { - let to_be_set: u64 = SubtensorModule::get_nominator_min_required_stake() + 5 as u64; + let to_be_set: u64 = SubtensorModule::get_nominator_min_required_stake() + 5_u64; assert_eq!( AdminUtils::sudo_set_nominator_min_required_stake( <::RuntimeOrigin>::signed(U256::from(0)), to_be_set ), - Err(DispatchError::BadOrigin.into()) + Err(DispatchError::BadOrigin) ); }); } @@ -912,7 +912,7 @@ mod sudo_set_nominator_min_required_stake { #[test] fn sets_a_higher_value() { new_test_ext().execute_with(|| { - let to_be_set: u64 = SubtensorModule::get_nominator_min_required_stake() + 5 as u64; + let to_be_set: u64 = SubtensorModule::get_nominator_min_required_stake() + 5_u64; assert_ok!(AdminUtils::sudo_set_nominator_min_required_stake( <::RuntimeOrigin>::root(), to_be_set diff --git a/pallets/collective/src/benchmarking.rs b/pallets/collective/src/benchmarking.rs index ba31ba160..cf44e9948 100644 --- a/pallets/collective/src/benchmarking.rs +++ b/pallets/collective/src/benchmarking.rs @@ -248,7 +248,7 @@ benchmarks_instance_pallet! { verify { // All proposals exist and the last proposal has just been updated. assert_eq!(Collective::::proposals().len(), p as usize); - let voting = Collective::::voting(&last_hash).ok_or("Proposal Missing")?; + let voting = Collective::::voting(last_hash).ok_or("Proposal Missing")?; assert_eq!(voting.ayes.len(), (m - 3) as usize); assert_eq!(voting.nays.len(), 1); } diff --git a/pallets/commitments/src/benchmarking.rs b/pallets/commitments/src/benchmarking.rs index cdf076933..fc40198bc 100644 --- a/pallets/commitments/src/benchmarking.rs +++ b/pallets/commitments/src/benchmarking.rs @@ -4,13 +4,10 @@ use super::*; #[allow(unused)] use crate::Pallet as Commitments; -use frame_benchmarking::v1::account; use frame_benchmarking::v2::*; use frame_system::RawOrigin; -use frame_support::traits::Get; -use sp_runtime::traits::{Bounded, StaticLookup}; -use sp_std::mem::size_of; +use sp_runtime::traits::{Bounded}; fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); @@ -18,8 +15,8 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { // This creates an `IdentityInfo` object with `num_fields` extra fields. // All data is pre-populated with some arbitrary bytes. -fn create_identity_info(num_fields: u32) -> CommitmentInfo { - let data = Data::Raw(vec![0; 32].try_into().unwrap()); +fn create_identity_info(_num_fields: u32) -> CommitmentInfo { + let _data = Data::Raw(vec![0; 32].try_into().unwrap()); CommitmentInfo { fields: Default::default(), diff --git a/pallets/registry/src/benchmarking.rs b/pallets/registry/src/benchmarking.rs index 3cbbdb457..e6ba8c732 100644 --- a/pallets/registry/src/benchmarking.rs +++ b/pallets/registry/src/benchmarking.rs @@ -8,9 +8,7 @@ use frame_benchmarking::v1::account; use frame_benchmarking::v2::*; use frame_system::RawOrigin; -use frame_support::traits::Get; -use sp_runtime::traits::{Bounded, StaticLookup}; -use sp_std::mem::size_of; +use sp_runtime::traits::{Bounded}; fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); @@ -18,7 +16,7 @@ fn assert_last_event(generic_event: ::RuntimeEvent) { // This creates an `IdentityInfo` object with `num_fields` extra fields. // All data is pre-populated with some arbitrary bytes. -fn create_identity_info(num_fields: u32) -> IdentityInfo { +fn create_identity_info(_num_fields: u32) -> IdentityInfo { let data = Data::Raw(vec![0; 32].try_into().unwrap()); IdentityInfo { diff --git a/pallets/subtensor/src/benchmarks.rs b/pallets/subtensor/src/benchmarks.rs index 9c4d5b311..90c3f715a 100644 --- a/pallets/subtensor/src/benchmarks.rs +++ b/pallets/subtensor/src/benchmarks.rs @@ -24,12 +24,12 @@ benchmarks! { let seed : u32 = 1; let block_number: u64 = Subtensor::::get_current_block_as_u64(); - let start_nonce: u64 = (39420842u64 + 100u64*netuid as u64).into(); + let start_nonce: u64 = 39420842u64 + 100u64*netuid as u64; let hotkey: T::AccountId = account("Alice", 0, seed); let (nonce, work): (u64, Vec) = Subtensor::::create_work_for_block_number( netuid, block_number, start_nonce, &hotkey); Subtensor::::init_new_network(netuid, tempo); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true.into()); + Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true); let block_number: u64 = Subtensor::::get_current_block_as_u64(); let coldkey: T::AccountId = account("Test", 0, seed); @@ -46,7 +46,7 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_max_allowed_uids( netuid, 4096 ); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true.into() ); + Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true ); Subtensor::::set_max_registrations_per_block( netuid.try_into().unwrap(), 4096 ); Subtensor::::set_target_registrations_per_interval( netuid.try_into().unwrap(), 4096 ); @@ -55,10 +55,10 @@ benchmarks! { let mut weights: Vec = vec![]; let signer : T::AccountId = account("Alice", 0, seed); - for id in 0..4096 as u16 { + for id in 0..4096_u16 { let hotkey: T::AccountId = account("Alice", 0, seed); let coldkey: T::AccountId = account("Test", 0, seed); - seed = seed +1; + seed += 1; Subtensor::::set_burn(netuid, 1); let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000 ); @@ -67,9 +67,9 @@ benchmarks! { Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())?; let uid = Subtensor::::get_uid_for_net_and_hotkey(netuid, &hotkey.clone()).unwrap(); - Subtensor::::set_validator_permit_for_uid(netuid, uid.clone(), true); - dests.push(id.clone()); - weights.push(id.clone()); + Subtensor::::set_validator_permit_for_uid(netuid, uid, true); + dests.push(id); + weights.push(id); } }: set_weights(RawOrigin::Signed( signer.clone() ), netuid, dests, weights, version_key) @@ -89,7 +89,7 @@ benchmarks! { Subtensor::::set_burn(netuid, 1); Subtensor::::set_max_allowed_uids( netuid, 4096 ); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true.into()); + Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); let coldkey: T::AccountId = account("Test", 0, seed); @@ -113,7 +113,7 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_burn(netuid, 1); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true.into() ); + Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true ); Subtensor::::set_max_allowed_uids( netuid, 4096 ); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); @@ -141,7 +141,7 @@ benchmarks! { Subtensor::::increase_total_stake(1_000_000_000_000); Subtensor::::init_new_network(netuid, tempo); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true.into() ); + Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true ); Subtensor::::set_max_allowed_uids( netuid, 4096 ); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); @@ -270,7 +270,7 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_burn(netuid, 1); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true.into()); + Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true); Subtensor::::set_max_allowed_uids( netuid, 4096 ); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 0b9b7f380..f81efc38a 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -1720,7 +1720,7 @@ pub mod pallet { 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 _stake = Self::get_total_stake_for_hotkey(&hotkey); + let _stake = Self::get_total_stake_for_hotkey(hotkey); 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); diff --git a/pallets/subtensor/src/math.rs b/pallets/subtensor/src/math.rs index c83ba8769..7356c85a9 100644 --- a/pallets/subtensor/src/math.rs +++ b/pallets/subtensor/src/math.rs @@ -74,16 +74,12 @@ pub fn vec_fixed64_to_u64(vec: Vec) -> Vec { #[allow(dead_code)] pub fn vec_u16_proportions_to_fixed(vec: Vec) -> Vec { - vec.into_iter() - .map(u16_proportion_to_fixed) - .collect() + vec.into_iter().map(u16_proportion_to_fixed).collect() } #[allow(dead_code)] pub fn vec_fixed_proportions_to_u16(vec: Vec) -> Vec { - vec.into_iter() - .map(fixed_proportion_to_u16) - .collect() + vec.into_iter().map(fixed_proportion_to_u16).collect() } #[allow(dead_code)] @@ -136,12 +132,8 @@ pub fn check_vec_max_limited(vec: &Vec, max_limit: u16) -> bool { inplace_normalize(&mut vec_fixed); let max_value: Option<&I32F32> = vec_fixed.iter().max(); match max_value { - Some(val) => { - *val <= max_limit_fixed - } - None => { - true - } + Some(val) => *val <= max_limit_fixed, + None => true, } } @@ -1495,7 +1487,7 @@ mod tests { // Reshape vector to sparse matrix with specified number of input rows, cast f32 to I32F32. fn vec_to_sparse_mat_fixed( - vector: &Vec, + vector: &[f32], rows: usize, transpose: bool, ) -> Vec> { @@ -1534,10 +1526,7 @@ mod tests { fn test_math_vec_to_sparse_mat_fixed() { let vector: Vec = vec![0., 1., 2., 0., 10., 100.]; let target: Vec> = vec![ - vec![ - (1_u16, I32F32::from_num(1.)), - (2_u16, I32F32::from_num(2.)), - ], + vec![(1_u16, I32F32::from_num(1.)), (2_u16, I32F32::from_num(2.))], vec![ (1_u16, I32F32::from_num(10.)), (2_u16, I32F32::from_num(100.)), @@ -2668,18 +2657,7 @@ mod tests { let n: usize = 100; for majority in vec_to_fixed(&vec![ - 0., - 0.0000001, - 0.25, - 0.49, - 0.49, - 0.49, - 0.5, - 0.51, - 0.51, - 0.51, - 0.9999999, - 1., + 0., 0.0000001, 0.25, 0.49, 0.49, 0.49, 0.5, 0.51, 0.51, 0.51, 0.9999999, 1., ]) { for allow_equal in [false, true] { let mut stake: Vec = vec![]; @@ -2691,9 +2669,8 @@ mod tests { 1 => stake.push(one), _ => stake.push(zero), } - match rng.gen_range(0..2) { - 1 => last_score += one, - _ => (), + if rng.gen_range(0..2) == 1 { + last_score += one } score.push(last_score); } else { diff --git a/pallets/subtensor/src/migration.rs b/pallets/subtensor/src/migration.rs index 354b199d8..d45a6ebc6 100644 --- a/pallets/subtensor/src/migration.rs +++ b/pallets/subtensor/src/migration.rs @@ -165,8 +165,8 @@ pub fn migrate_create_root_network() -> Weight { // Empty senate members entirely, they will be filled by by registrations // on the subnet. for hotkey_i in T::SenateMembers::members().iter() { - T::TriumvirateInterface::remove_votes(&hotkey_i).defensive_ok(); - T::SenateMembers::remove_member(&hotkey_i).defensive_ok(); + T::TriumvirateInterface::remove_votes(hotkey_i).defensive_ok(); + T::SenateMembers::remove_member(hotkey_i).defensive_ok(); weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2)); } diff --git a/pallets/subtensor/src/root.rs b/pallets/subtensor/src/root.rs index f2db1d979..44ab17659 100644 --- a/pallets/subtensor/src/root.rs +++ b/pallets/subtensor/src/root.rs @@ -137,14 +137,13 @@ impl Pallet { /// pub fn get_block_emission() -> Result { // Convert the total issuance to a fixed-point number for calculation. - Self::get_block_emission_for_issuance( Self::get_total_issuance() ) + Self::get_block_emission_for_issuance(Self::get_total_issuance()) } // Returns the block emission for an issuance value. - pub fn get_block_emission_for_issuance( issuance: u64 ) -> Result { - + pub fn get_block_emission_for_issuance(issuance: u64) -> Result { // Convert issuance to a float for calculations below. - let total_issuance: I96F32 = I96F32::from_num( issuance ); + let total_issuance: I96F32 = I96F32::from_num(issuance); // Check to prevent division by zero when the total supply is reached // and creating an issuance greater than the total supply. if total_issuance >= I96F32::from_num(TotalSupply::::get()) { @@ -376,11 +375,8 @@ impl Pallet { } for trust_score in trust.iter_mut() { - match trust_score.checked_div(total_stake) { - Some(quotient) => { - *trust_score = quotient; - } - None => {} + if let Some(quotient) = trust_score.checked_div(total_stake) { + *trust_score = quotient; } } @@ -690,7 +686,8 @@ impl Pallet { }; // --- 5. Perform the lock operation. - let actual_lock_amount = Self::remove_balance_from_coldkey_account(&coldkey, lock_as_balance.unwrap())?; + let actual_lock_amount = + Self::remove_balance_from_coldkey_account(&coldkey, lock_as_balance.unwrap())?; Self::set_subnet_locked_balance(netuid_to_register, actual_lock_amount); Self::set_network_last_lock(actual_lock_amount); diff --git a/pallets/subtensor/src/staking.rs b/pallets/subtensor/src/staking.rs index 34f1f3c15..41cc8d97a 100644 --- a/pallets/subtensor/src/staking.rs +++ b/pallets/subtensor/src/staking.rs @@ -560,15 +560,15 @@ impl Pallet { stake: u64, ) { // Verify if the account is a nominator account by checking ownership of the hotkey by the coldkey. - if !Self::coldkey_owns_hotkey(&coldkey, &hotkey) { + if !Self::coldkey_owns_hotkey(coldkey, hotkey) { // If the stake is below the minimum required, it's considered a small nomination and needs to be cleared. if stake < Self::get_nominator_min_required_stake() { // Remove the stake from the nominator account. (this is a more forceful unstake operation which ) // Actually deletes the staking account. - Self::empty_stake_on_coldkey_hotkey_account(&coldkey, &hotkey); + Self::empty_stake_on_coldkey_hotkey_account(coldkey, hotkey); // Convert the removed stake back to balance and add it to the coldkey account. let stake_as_balance = Self::u64_to_balance(stake); - Self::add_balance_to_coldkey_account(&coldkey, stake_as_balance.unwrap()); + Self::add_balance_to_coldkey_account(coldkey, stake_as_balance.unwrap()); } } } diff --git a/pallets/subtensor/tests/epoch.rs b/pallets/subtensor/tests/epoch.rs index 3459c952e..415737bdf 100644 --- a/pallets/subtensor/tests/epoch.rs +++ b/pallets/subtensor/tests/epoch.rs @@ -21,13 +21,13 @@ pub fn fixed_proportion_to_u16(x: I32F32) -> u16 { // Normalizes (sum to 1 except 0) the input vector directly in-place. #[allow(dead_code)] -pub fn inplace_normalize(x: &mut Vec) { +pub fn inplace_normalize(x: &mut [I32F32]) { let x_sum: I32F32 = x.iter().sum(); if x_sum == I32F32::from_num(0.0_f32) { return; } - for i in 0..x.len() { - x[i] /= x_sum; + for i in x.iter_mut() { + *i /= x_sum; } } @@ -139,6 +139,7 @@ fn uid_stats(netuid: u16, uid: u16) { ); } +#[allow(clippy::too_many_arguments)] fn init_run_epochs( netuid: u16, n: u16, @@ -147,9 +148,9 @@ fn init_run_epochs( epochs: u16, stake_per_validator: u64, server_self: bool, - input_stake: &Vec, + input_stake: &[u64], use_input_stake: bool, - input_weights: &Vec>, + input_weights: &[Vec<(u16, u16)>], use_input_weights: bool, random_weights: bool, random_seed: u64, @@ -161,16 +162,16 @@ fn init_run_epochs( // === Register uids SubtensorModule::set_max_allowed_uids(netuid, n); for key in 0..n { - let stake: u64; - if use_input_stake { - stake = input_stake[key as usize]; + // let stake: u64; + let stake = if use_input_stake { + input_stake[key as usize] + } else if validators.contains(&key) { + stake_per_validator } else { - stake = if validators.contains(&key) { - stake_per_validator - } else { - 0 - }; // only validators receive stake - } + // only validators receive stake + 0 + }; + // let stake: u64 = 1; // alternative test: all nodes receive stake, should be same outcome, except stake SubtensorModule::add_balance_to_coldkey_account(&(U256::from(key)), stake); SubtensorModule::append_neuron(netuid, &(U256::from(key)), 0); @@ -682,9 +683,9 @@ fn test_512_graph() { epochs, max_stake_per_validator, server_self, - &vec![], + &[], false, - &vec![], + &[], false, false, 0, @@ -743,6 +744,7 @@ fn test_512_graph_random_weights() { ); let server: usize = servers[0] as usize; let validator: usize = validators[0] as usize; + #[allow(clippy::type_complexity)] let (mut rank, mut incentive, mut dividend, mut emission, mut bondv, mut bonds): ( Vec, Vec, @@ -762,9 +764,9 @@ fn test_512_graph_random_weights() { epochs, 1, server_self, - &vec![], + &[], false, - &vec![], + &[], false, true, interleave as u64, @@ -792,9 +794,9 @@ fn test_512_graph_random_weights() { epochs, 1, server_self, - &vec![], + &[], false, - &vec![], + &[], false, true, interleave as u64, @@ -856,9 +858,9 @@ fn test_4096_graph() { epochs, max_stake_per_validator, server_self, - &vec![], + &[], false, - &vec![], + &[], false, false, 0, @@ -923,9 +925,9 @@ fn test_16384_graph_sparse() { epochs, 1, false, - &vec![], + &[], false, - &vec![], + &[], false, false, 0, @@ -1342,12 +1344,13 @@ fn test_active_stake() { 250000000 ); // Note E = 0.5 / (n/2) * 1_000_000_000 = 250_000_000 } - for validator in 0..(n / 2) as usize { - for on_validator in 0..(n / 2) as usize { - assert_eq!(bonds[validator][on_validator], 0); + for bond in bonds.iter().take((n / 2) as usize) { + // for on_validator in 0..(n / 2) as usize { + for i in bond.iter().take((n / 2) as usize) { + assert_eq!(*i, 0); } - for server in ((n / 2) as usize)..n as usize { - assert_eq!(bonds[validator][server], I32F32::from_num(65_535)); // floor(0.5*(2^16-1))/(2^16-1), then max-upscale to 65_535 + for i in bond.iter().take(n as usize).skip((n / 2) as usize) { + assert_eq!(*i, I32F32::from_num(65_535)); // floor(0.5*(2^16-1))/(2^16-1), then max-upscale to 65_535 } } let activity_cutoff: u64 = SubtensorModule::get_activity_cutoff(netuid) as u64; diff --git a/pallets/subtensor/tests/root.rs b/pallets/subtensor/tests/root.rs index bd0db904f..efed94737 100644 --- a/pallets/subtensor/tests/root.rs +++ b/pallets/subtensor/tests/root.rs @@ -784,7 +784,7 @@ fn test_get_emission_across_entire_issuance_range() { let total_supply: u64 = pallet_subtensor::TotalSupply::::get(); let original_emission: u64 = pallet_subtensor::DefaultBlockEmission::::get(); let halving_issuance: u64 = total_supply / 2; - let mut step: usize = original_emission as usize; + let step: usize = original_emission as usize; for issuance in (0..=total_supply).step_by(step) { SubtensorModule::set_total_issuance(issuance); @@ -805,7 +805,6 @@ fn test_get_emission_across_entire_issuance_range() { "Issuance: {}", issuance_f64 ); - step = expected_emission as usize; } }); } diff --git a/pallets/subtensor/tests/senate.rs b/pallets/subtensor/tests/senate.rs index f54aa1a93..a1bdae56d 100644 --- a/pallets/subtensor/tests/senate.rs +++ b/pallets/subtensor/tests/senate.rs @@ -196,7 +196,6 @@ fn test_senate_vote_works() { Box::new(proposal.clone()), proposal_len, TryInto::>::try_into(100u64) - .ok() .expect("convert u64 to block number.") )); @@ -273,7 +272,6 @@ fn test_senate_vote_not_member() { Box::new(proposal.clone()), proposal_len, TryInto::>::try_into(100u64) - .ok() .expect("convert u64 to block number.") )); @@ -434,7 +432,6 @@ fn test_senate_leave_vote_removal() { Box::new(proposal.clone()), proposal_len, TryInto::>::try_into(100u64) - .ok() .expect("convert u64 to block number.") )); diff --git a/pallets/subtensor/tests/serving.rs b/pallets/subtensor/tests/serving.rs index 5a5e1ca08..c637028c3 100644 --- a/pallets/subtensor/tests/serving.rs +++ b/pallets/subtensor/tests/serving.rs @@ -12,6 +12,7 @@ mod test { use std::net::{Ipv4Addr, Ipv6Addr}; // Generates an ipv6 address based on 8 ipv6 words and returns it as u128 + #[allow(clippy::too_many_arguments)] pub fn ipv6(a: u16, b: u16, c: u16, d: u16, e: u16, f: u16, g: u16, h: u16) -> u128 { Ipv6Addr::new(a, b, c, d, e, f, g, h).into() } diff --git a/pallets/subtensor/tests/staking.rs b/pallets/subtensor/tests/staking.rs index b5ba056d1..da157cb5b 100644 --- a/pallets/subtensor/tests/staking.rs +++ b/pallets/subtensor/tests/staking.rs @@ -369,7 +369,6 @@ fn test_add_stake_under_limit() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(561337); let coldkey_account_id = U256::from(61337); - let who: ::AccountId = hotkey_account_id; let netuid: u16 = 1; let start_nonce: u64 = 0; let tempo: u16 = 13; @@ -403,7 +402,6 @@ fn test_add_stake_rate_limit_exceeded() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(561337); let coldkey_account_id = U256::from(61337); - let who: ::AccountId = hotkey_account_id; let netuid: u16 = 1; let start_nonce: u64 = 0; let tempo: u16 = 13; @@ -446,7 +444,6 @@ fn test_remove_stake_under_limit() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(561337); let coldkey_account_id = U256::from(61337); - let who: ::AccountId = hotkey_account_id; let netuid: u16 = 1; let start_nonce: u64 = 0; let tempo: u16 = 13; @@ -482,7 +479,6 @@ fn test_remove_stake_rate_limit_exceeded() { new_test_ext(1).execute_with(|| { let hotkey_account_id = U256::from(561337); let coldkey_account_id = U256::from(61337); - let who: ::AccountId = hotkey_account_id; let netuid: u16 = 1; let start_nonce: u64 = 0; let tempo: u16 = 13; @@ -2549,8 +2545,8 @@ fn test_clear_small_nominations() { let total_cold2_stake_before = TotalColdkeyStake::::get(cold2); let total_hot1_stake_before = TotalHotkeyStake::::get(hot1); let total_hot2_stake_before = TotalHotkeyStake::::get(hot2); - let _ = Stake::::try_get(&hot2, &cold1).unwrap(); // ensure exists before - let _ = Stake::::try_get(&hot1, &cold2).unwrap(); // ensure exists before + let _ = Stake::::try_get(hot2, cold1).unwrap(); // ensure exists before + let _ = Stake::::try_get(hot1, cold2).unwrap(); // ensure exists before let total_stake_before = TotalStake::::get(); SubtensorModule::set_nominator_min_required_stake(10); @@ -2586,8 +2582,8 @@ fn test_clear_small_nominations() { TotalHotkeyStake::::get(hot2), total_hot2_stake_before - 1 ); - Stake::::try_get(&hot2, &cold1).unwrap_err(); - Stake::::try_get(&hot1, &cold2).unwrap_err(); + Stake::::try_get(hot2, cold1).unwrap_err(); + Stake::::try_get(hot1, cold2).unwrap_err(); assert_eq!( TotalColdkeyStake::::get(cold1), total_cold1_stake_before - 1 @@ -2596,7 +2592,7 @@ fn test_clear_small_nominations() { TotalHotkeyStake::::get(hot1), total_hot1_stake_before - 1 ); - Stake::::try_get(&hot2, &cold1).unwrap_err(); + Stake::::try_get(hot2, cold1).unwrap_err(); assert_eq!(TotalStake::::get(), total_stake_before - 2); }); } diff --git a/rust-toolchain.toml b/rust-toolchain.toml index aecd2b0c8..f81199a22 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,14 @@ [toolchain] -channel = "nightly-2024-03-05" -components = [ "rustfmt" ] -targets = [ "wasm32-unknown-unknown" ] +channel = "stable" +components = [ + "cargo", + "clippy", + "rust-analyzer", + "rust-src", + "rust-std", + "rustc", + "rustc-dev", + "rustfmt", +] +targets = ["wasm32-unknown-unknown"] profile = "minimal" From 4c63615e520bfc34605b222750a14d96f3a5537b Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 10:46:38 +0400 Subject: [PATCH 02/13] remove u64_to_balance --- pallets/admin-utils/src/lib.rs | 1 - pallets/admin-utils/tests/mock.rs | 4 -- pallets/commitments/src/lib.rs | 8 ---- pallets/subtensor/src/benchmarks.rs | 52 +++++++++++------------ pallets/subtensor/src/block_step.rs | 6 +-- pallets/subtensor/src/lib.rs | 8 ---- pallets/subtensor/src/registration.rs | 18 ++++---- pallets/subtensor/src/root.rs | 17 +++----- pallets/subtensor/src/staking.rs | 59 ++++++++------------------- runtime/src/lib.rs | 4 -- 10 files changed, 60 insertions(+), 117 deletions(-) diff --git a/pallets/admin-utils/src/lib.rs b/pallets/admin-utils/src/lib.rs index 513304666..ca66bef3b 100644 --- a/pallets/admin-utils/src/lib.rs +++ b/pallets/admin-utils/src/lib.rs @@ -836,7 +836,6 @@ pub trait SubtensorInterface { hotkey: &AccountId, increment: u64, ); - fn u64_to_balance(input: u64) -> Option; fn add_balance_to_coldkey_account(coldkey: &AccountId, amount: Balance); fn get_current_block_as_u64() -> u64; fn get_subnetwork_n(netuid: u16) -> u16; diff --git a/pallets/admin-utils/tests/mock.rs b/pallets/admin-utils/tests/mock.rs index de5efce03..abf663678 100644 --- a/pallets/admin-utils/tests/mock.rs +++ b/pallets/admin-utils/tests/mock.rs @@ -279,10 +279,6 @@ impl pallet_admin_utils::SubtensorInterface f SubtensorModule::increase_stake_on_coldkey_hotkey_account(coldkey, hotkey, increment); } - fn u64_to_balance(input: u64) -> Option { - SubtensorModule::u64_to_balance(input) - } - fn add_balance_to_coldkey_account(coldkey: &AccountId, amount: Balance) { SubtensorModule::add_balance_to_coldkey_account(coldkey, amount); } diff --git a/pallets/commitments/src/lib.rs b/pallets/commitments/src/lib.rs index 372564487..0d126489d 100644 --- a/pallets/commitments/src/lib.rs +++ b/pallets/commitments/src/lib.rs @@ -227,14 +227,6 @@ where // have a higher priority than the set_weights call u64::max_value() } - - pub fn u64_to_balance( - input: u64, - ) -> Option< - <::Currency as Currency<::AccountId>>::Balance, - > { - input.try_into().ok() - } } impl sp_std::fmt::Debug for CommitmentsSignedExtension { diff --git a/pallets/subtensor/src/benchmarks.rs b/pallets/subtensor/src/benchmarks.rs index 90c3f715a..87b86dc23 100644 --- a/pallets/subtensor/src/benchmarks.rs +++ b/pallets/subtensor/src/benchmarks.rs @@ -61,8 +61,8 @@ benchmarks! { seed += 1; Subtensor::::set_burn(netuid, 1); - let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000 ); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 1000000u32.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())?; @@ -95,8 +95,8 @@ benchmarks! { let coldkey: T::AccountId = account("Test", 0, seed); let hotkey: T::AccountId = account("Alice", 0, seed); - let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 1000000000u32.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())); }: become_delegate(RawOrigin::Signed( coldkey.clone() ), hotkey.clone()) @@ -122,8 +122,8 @@ benchmarks! { let hotkey: T::AccountId = account("Alice", 0, seed); let amount: u64 = 1; - let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 1000000000u64.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())); }: add_stake(RawOrigin::Signed( coldkey.clone() ), hotkey, amount) @@ -150,16 +150,16 @@ benchmarks! { let hotkey: T::AccountId = account("Alice", 0, seed); Subtensor::::set_burn(netuid, 1); - let wallet_bal = Subtensor::::u64_to_balance(1000000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), wallet_bal.unwrap()); + let wallet_bal = 1000000u32.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), wallet_bal); assert_ok!(Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())); assert_ok!(Subtensor::::do_become_delegate(RawOrigin::Signed(coldkey.clone()).into(), hotkey.clone(), Subtensor::::get_default_take())); // Stake 10% of our current total staked TAO let u64_staked_amt = 100_000_000_000; - let amount_to_be_staked = Subtensor::::u64_to_balance(u64_staked_amt); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked.unwrap()); + let amount_to_be_staked = u64_staked_amt.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!( Subtensor::::add_stake(RawOrigin::Signed( coldkey.clone() ).into() , hotkey.clone(), u64_staked_amt)); @@ -186,8 +186,8 @@ benchmarks! { assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); Subtensor::::set_burn(netuid, 1); - let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000 ); - Subtensor::::add_balance_to_coldkey_account(&caller.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 1000000u32.into(); + Subtensor::::add_balance_to_coldkey_account(&caller.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(caller_origin.clone(), netuid, caller.clone())); @@ -212,8 +212,8 @@ benchmarks! { assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); Subtensor::::set_burn(netuid, 1); - let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000 ); - Subtensor::::add_balance_to_coldkey_account(&caller.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 1000000u32.into(); + Subtensor::::add_balance_to_coldkey_account(&caller.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(caller_origin.clone(), netuid, caller.clone())); Subtensor::::set_serving_rate_limit(netuid, 0); @@ -239,8 +239,8 @@ benchmarks! { let hotkey: T::AccountId = account("Alice", 0, seed); let coldkey: T::AccountId = account("Test", 0, seed); - let amoun_to_be_staked = Subtensor::::u64_to_balance( balance ); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = balance.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); }: sudo_register(RawOrigin::>::Root, netuid, hotkey, coldkey, stake, balance) */ @@ -255,8 +255,8 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_burn(netuid, 1); - let amoun_to_be_staked = Subtensor::::u64_to_balance( 1000000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 1000000u32.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); }: burned_register(RawOrigin::Signed( coldkey.clone() ), netuid, hotkey) @@ -279,8 +279,8 @@ benchmarks! { let hotkey: T::AccountId = account("Alice", 0, seed); let amount: u64 = 1; - let amoun_to_be_staked = Subtensor::::u64_to_balance( 100_000_000_000_000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 100_000_000_000_000u64.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())); }: root_register(RawOrigin::Signed(coldkey), hotkey) @@ -293,8 +293,8 @@ benchmarks! { Subtensor::::set_network_rate_limit(1); let amount: u64 = 1; - let amoun_to_be_staked = Subtensor::::u64_to_balance(100_000_000_000_000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 100_000_000_000_000u64.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); }: register_network(RawOrigin::Signed(coldkey)) benchmark_dissolve_network { @@ -305,8 +305,8 @@ benchmarks! { Subtensor::::set_network_rate_limit(0); let amount: u64 = 1; - let amoun_to_be_staked = Subtensor::::u64_to_balance(100_000_000_000_000); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amoun_to_be_staked.unwrap()); + let amount_to_be_staked = 100_000_000_000_000u64.into(); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::register_network(RawOrigin::Signed(coldkey.clone()).into())); }: dissolve_network(RawOrigin::Signed(coldkey), 1) @@ -323,7 +323,7 @@ benchmarks! { Subtensor::::set_target_registrations_per_interval(netuid, 256); Subtensor::::set_max_registrations_per_block(netuid, 256); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), Subtensor::::u64_to_balance(10_000_000_000).unwrap()); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 10_000_000_000u64.into()); assert_ok!(Subtensor::::burned_register(RawOrigin::Signed(coldkey.clone()).into(), netuid, old_hotkey.clone())); assert_ok!(Subtensor::::become_delegate(RawOrigin::Signed(coldkey.clone()).into(), old_hotkey.clone())); @@ -332,7 +332,7 @@ benchmarks! { let coldkey: T::AccountId = account("Axon", 0, i); let hotkey: T::AccountId = account("Hotkey", 0, i); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), Subtensor::::u64_to_balance(10_000_000_000).unwrap()); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 10_000_000_000u64.into()); assert_ok!(Subtensor::::burned_register(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey)); assert_ok!(Subtensor::::add_stake(RawOrigin::Signed(coldkey).into(), old_hotkey.clone(), 1_000_000_000)); } diff --git a/pallets/subtensor/src/block_step.rs b/pallets/subtensor/src/block_step.rs index 168c2879e..fda5e944e 100644 --- a/pallets/subtensor/src/block_step.rs +++ b/pallets/subtensor/src/block_step.rs @@ -139,11 +139,11 @@ impl Pallet { Self::add_balance_to_coldkey_account( &Self::get_subnet_owner(netuid), - Self::u64_to_balance(cut.to_num::()).unwrap(), + cut.to_num::().into(), ); // We are creating tokens here from the coinbase. - Self::coinbase( cut.to_num::() ); + Self::coinbase(cut.to_num::()); } // --- 5. Add remaining amount to the network's pending emission. PendingEmission::::mutate(netuid, |queued| *queued += remaining.to_num::()); @@ -346,7 +346,7 @@ impl Pallet { 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: {:?}", + log::debug!("netuid: {:?} last_adjustment_block: {:?} adjustment_interval: {:?} current_block: {:?}", netuid, last_adjustment_block, adjustment_interval, diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 7c001aaeb..5226449c1 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -1812,14 +1812,6 @@ where pub fn check_weights_min_stake(who: &T::AccountId) -> bool { Pallet::::check_weights_min_stake(who) } - - pub fn u64_to_balance( - input: u64, - ) -> Option< - <::Currency as fungible::Inspect<::AccountId>>::Balance, - >{ - input.try_into().ok() - } } impl sp_std::fmt::Debug for SubtensorSignedExtension { diff --git a/pallets/subtensor/src/registration.rs b/pallets/subtensor/src/registration.rs index c26c9a8cb..acf3f89b5 100644 --- a/pallets/subtensor/src/registration.rs +++ b/pallets/subtensor/src/registration.rs @@ -95,14 +95,15 @@ impl Pallet { // --- 7. Ensure the callers coldkey has enough stake to perform the transaction. let current_block_number: u64 = Self::get_current_block_as_u64(); let registration_cost_as_u64 = Self::get_burn_as_u64(netuid); - let registration_cost_as_balance = Self::u64_to_balance(registration_cost_as_u64).unwrap(); + let registration_cost_as_balance = registration_cost_as_u64.into(); ensure!( Self::can_remove_balance_from_coldkey_account(&coldkey, registration_cost_as_balance), Error::::NotEnoughBalanceToStake ); // --- 8. Ensure the remove operation from the coldkey is a success. - let actual_burn_amount = Self::remove_balance_from_coldkey_account(&coldkey, registration_cost_as_balance)?; + let actual_burn_amount = + Self::remove_balance_from_coldkey_account(&coldkey, registration_cost_as_balance)?; // The burn occurs here. Self::burn_tokens(actual_burn_amount); @@ -396,8 +397,8 @@ impl Pallet { let balance_to_add: u64 = 100_000_000_000; Self::coinbase(100_000_000_000); // We are creating tokens here from the coinbase. - let balance_to_be_added_as_balance = Self::u64_to_balance(balance_to_add); - Self::add_balance_to_coldkey_account(&coldkey, balance_to_be_added_as_balance.unwrap()); + let balance_to_be_added_as_balance = balance_to_add.into(); + Self::add_balance_to_coldkey_account(&coldkey, balance_to_be_added_as_balance); // --- 6. Deposit successful event. log::info!( @@ -431,14 +432,14 @@ impl Pallet { if neurons_n == 0 { return 0; // If there are no neurons in this network. } - + let current_block: u64 = Self::get_current_block_as_u64(); let immunity_period: u64 = Self::get_immunity_period(netuid) as u64; for neuron_uid_i in 0..neurons_n { let pruning_score: u16 = Self::get_pruning_score_for_uid(netuid, neuron_uid_i); let block_at_registration: u64 = Self::get_neuron_block_at_registration(netuid, neuron_uid_i); - + if min_score == pruning_score { if current_block - block_at_registration < immunity_period { //neuron is in immunity period @@ -725,12 +726,13 @@ impl Pallet { .saturating_accrue(T::DbWeight::get().reads((TotalNetworks::::get() + 1u16) as u64)); let swap_cost = 1_000_000_000u64; - let swap_cost_as_balance = Self::u64_to_balance(swap_cost).unwrap(); + let swap_cost_as_balance = swap_cost.into(); ensure!( Self::can_remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance), Error::::NotEnoughBalance ); - let actual_burn_amount = Self::remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance)?; + let actual_burn_amount = + Self::remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance)?; Self::burn_tokens(actual_burn_amount); Owner::::remove(old_hotkey); diff --git a/pallets/subtensor/src/root.rs b/pallets/subtensor/src/root.rs index 44ab17659..5fdb1d95d 100644 --- a/pallets/subtensor/src/root.rs +++ b/pallets/subtensor/src/root.rs @@ -646,14 +646,10 @@ impl Pallet { // --- 2. Calculate and lock the required tokens. let lock_amount: u64 = Self::get_network_lock_cost(); - let lock_as_balance = Self::u64_to_balance(lock_amount); + let lock_as_balance = lock_amount.into(); log::debug!("network lock_amount: {:?}", lock_amount,); ensure!( - lock_as_balance.is_some(), - Error::::CouldNotConvertToBalance - ); - ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, lock_as_balance.unwrap()), + Self::can_remove_balance_from_coldkey_account(&coldkey, lock_as_balance), Error::::NotEnoughBalanceToStake ); @@ -687,7 +683,7 @@ impl Pallet { // --- 5. Perform the lock operation. let actual_lock_amount = - Self::remove_balance_from_coldkey_account(&coldkey, lock_as_balance.unwrap())?; + Self::remove_balance_from_coldkey_account(&coldkey, lock_as_balance)?; Self::set_subnet_locked_balance(netuid_to_register, actual_lock_amount); Self::set_network_last_lock(actual_lock_amount); @@ -851,10 +847,7 @@ impl Pallet { let reserved_amount = Self::get_subnet_locked_balance(netuid); // Ensure that we can convert this u64 to a balance. - let reserved_amount_as_bal = Self::u64_to_balance(reserved_amount); - if reserved_amount_as_bal.is_none() { - return; - } + let reserved_amount_as_bal = reserved_amount.into(); // --- 2. Remove network count. SubnetworkN::::remove(netuid); @@ -925,7 +918,7 @@ impl Pallet { BurnRegistrationsThisInterval::::remove(netuid); // --- 12. Add the balance back to the owner. - Self::add_balance_to_coldkey_account(&owner_coldkey, reserved_amount_as_bal.unwrap()); + Self::add_balance_to_coldkey_account(&owner_coldkey, reserved_amount_as_bal); Self::set_subnet_locked_balance(netuid, 0); SubnetOwner::::remove(netuid); } diff --git a/pallets/subtensor/src/staking.rs b/pallets/subtensor/src/staking.rs index 41cc8d97a..a104a7af8 100644 --- a/pallets/subtensor/src/staking.rs +++ b/pallets/subtensor/src/staking.rs @@ -141,16 +141,12 @@ impl Pallet { stake_to_be_added ); - // --- 2. We convert the stake u64 into a balancer. - let stake_as_balance = Self::u64_to_balance(stake_to_be_added); - ensure!( - stake_as_balance.is_some(), - Error::::CouldNotConvertToBalance - ); + // --- 2. We convert the stake u64 into a balance. + let stake_as_balance = stake_to_be_added.into(); // --- 3. Ensure the callers coldkey has enough stake to perform the transaction. ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, stake_as_balance.unwrap()), + Self::can_remove_balance_from_coldkey_account(&coldkey, stake_as_balance), Error::::NotEnoughBalanceToStake ); @@ -190,7 +186,7 @@ impl Pallet { // --- 8. Ensure the remove operation from the coldkey is a success. let actual_amount_to_stake = - Self::remove_balance_from_coldkey_account(&coldkey, stake_as_balance.unwrap())?; + Self::remove_balance_from_coldkey_account(&coldkey, stake_as_balance)?; // --- 9. If we reach here, add the balance to the hotkey. Self::increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, actual_amount_to_stake); @@ -289,11 +285,7 @@ impl Pallet { ); // --- 5. Ensure that we can conver this u64 to a balance. - let stake_to_be_added_as_currency = Self::u64_to_balance(stake_to_be_removed); - ensure!( - stake_to_be_added_as_currency.is_some(), - Error::::CouldNotConvertToBalance - ); + let stake_to_be_added_as_currency = stake_to_be_removed.into(); // --- 6. Ensure we don't exceed stake rate limit let unstakes_this_interval = @@ -321,7 +313,7 @@ impl Pallet { Self::decrease_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_to_be_removed); // --- 9. We add the balancer to the coldkey. If the above fails we will not credit this coldkey. - Self::add_balance_to_coldkey_account(&coldkey, stake_to_be_added_as_currency.unwrap()); + Self::add_balance_to_coldkey_account(&coldkey, stake_to_be_added_as_currency); // Set last block for rate limiting let block: u64 = Self::get_current_block_as_u64(); @@ -567,8 +559,8 @@ impl Pallet { // Actually deletes the staking account. Self::empty_stake_on_coldkey_hotkey_account(coldkey, hotkey); // Convert the removed stake back to balance and add it to the coldkey account. - let stake_as_balance = Self::u64_to_balance(stake); - Self::add_balance_to_coldkey_account(coldkey, stake_as_balance.unwrap()); + let stake_as_balance = stake.into(); + Self::add_balance_to_coldkey_account(coldkey, stake_as_balance); } } } @@ -584,14 +576,6 @@ impl Pallet { } } - pub fn u64_to_balance( - input: u64, - ) -> Option< - <::Currency as fungible::Inspect<::AccountId>>::Balance, - >{ - input.try_into().ok() - } - pub fn add_balance_to_coldkey_account( coldkey: &T::AccountId, amount: <::Currency as fungible::Inspect<::AccountId>>::Balance, @@ -672,25 +656,14 @@ impl Pallet { ) { // Convert to balance and add to the coldkey account. - let stake_i_as_balance = Self::u64_to_balance(stake_i); - if stake_i_as_balance.is_none() { - continue; // Don't unstake if we can't convert to balance. - } else { - // Stake is successfully converted to balance. - - // Remove the stake from the coldkey - hotkey pairing. - Self::decrease_stake_on_coldkey_hotkey_account( - &delegate_coldkey_i, - hotkey, - stake_i, - ); - - // Add the balance to the coldkey account. - Self::add_balance_to_coldkey_account( - &delegate_coldkey_i, - stake_i_as_balance.unwrap(), - ); - } + let stake_i_as_balance = stake_i.into(); + // Stake is successfully converted to balance. + + // Remove the stake from the coldkey - hotkey pairing. + Self::decrease_stake_on_coldkey_hotkey_account(&delegate_coldkey_i, hotkey, stake_i); + + // Add the balance to the coldkey account. + Self::add_balance_to_coldkey_account(&delegate_coldkey_i, stake_i_as_balance); } } } diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index c2ea64da1..ecdcdea17 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -941,10 +941,6 @@ impl SubtensorModule::increase_stake_on_coldkey_hotkey_account(coldkey, hotkey, increment); } - fn u64_to_balance(input: u64) -> Option { - SubtensorModule::u64_to_balance(input) - } - fn add_balance_to_coldkey_account(coldkey: &AccountId, amount: Balance) { SubtensorModule::add_balance_to_coldkey_account(coldkey, amount); } From 20c51d0e604fe095b27e812bb223607094eb0332 Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 11:17:42 +0400 Subject: [PATCH 03/13] fix: more clippy warnings --- Cargo.toml | 3 ++ integration-tests/Cargo.toml | 3 ++ node/Cargo.toml | 3 ++ node/src/chain_spec.rs | 2 + node/src/service.rs | 61 ++++++++++++------------ pallets/admin-utils/Cargo.toml | 3 ++ pallets/collective/Cargo.toml | 3 ++ pallets/commitments/Cargo.toml | 3 ++ pallets/commitments/src/lib.rs | 11 ++--- pallets/registry/Cargo.toml | 3 ++ pallets/registry/src/benchmarking.rs | 5 +- pallets/subtensor/Cargo.toml | 3 ++ pallets/subtensor/rpc/Cargo.toml | 3 ++ pallets/subtensor/runtime-api/Cargo.toml | 5 +- pallets/subtensor/src/lib.rs | 1 + pallets/subtensor/src/migration.rs | 2 +- pallets/subtensor/src/neuron_info.rs | 50 +++++++------------ runtime/Cargo.toml | 3 ++ 18 files changed, 93 insertions(+), 74 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c761877e4..a05b3c9e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,9 @@ members = [ ] resolver = "2" +[workspace.lints.clippy] +type_complexity = "allow" + [profile.release] panic = "unwind" diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index d59aece3b..a83410167 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -7,6 +7,9 @@ edition = "2021" license = "Unlicense" repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [dependencies] ## diff --git a/node/Cargo.toml b/node/Cargo.toml index d02eab74a..5c0a0e489 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -10,6 +10,9 @@ publish = false repository = "https://github.com/opentensor/subtensor" build = "build.rs" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index 69bc8e9c0..c4f703a12 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -492,6 +492,7 @@ fn localnet_genesis( } // Configure initial storage state for FRAME modules. +#[allow(clippy::too_many_arguments)] fn testnet_genesis( wasm_binary: &[u8], initial_authorities: Vec<(AuraId, GrandpaId)>, @@ -551,6 +552,7 @@ fn testnet_genesis( } // Configure initial storage state for FRAME modules. +#[allow(clippy::too_many_arguments)] fn finney_genesis( wasm_binary: &[u8], initial_authorities: Vec<(AuraId, GrandpaId)>, diff --git a/node/src/service.rs b/node/src/service.rs index 8efcc991b..c7eb3d416 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -222,14 +222,14 @@ pub fn new_full(config: Configuration) -> Result { ); } - let finality_proof_provider = sc_consensus_grandpa::FinalityProofProvider::new_for_service( - backend.clone(), - Some(grandpa_link.shared_authority_set().clone()), - ); - let rpc_backend = backend.clone(); - let justification_stream = grandpa_link.justification_stream(); - let shared_authority_set = grandpa_link.shared_authority_set().clone(); - let shared_voter_state = SharedVoterState::empty(); + let finality_proof_provider = sc_consensus_grandpa::FinalityProofProvider::new_for_service( + backend.clone(), + Some(grandpa_link.shared_authority_set().clone()), + ); + let rpc_backend = backend.clone(); + let justification_stream = grandpa_link.justification_stream(); + let shared_authority_set = grandpa_link.shared_authority_set().clone(); + let shared_voter_state = SharedVoterState::empty(); let role = config.role.clone(); let force_authoring = config.force_authoring; @@ -238,28 +238,29 @@ pub fn new_full(config: Configuration) -> Result { let enable_grandpa = !config.disable_grandpa; let prometheus_registry = config.prometheus_registry().cloned(); - let rpc_extensions_builder = { - let client = client.clone(); - let pool = transaction_pool.clone(); - - Box::new(move |deny_unsafe, subscription_executor: sc_rpc::SubscriptionTaskExecutor| { - let deps = - crate::rpc::FullDeps { - client: client.clone(), - pool: pool.clone(), - deny_unsafe, - grandpa: crate::rpc::GrandpaDeps { - shared_voter_state: shared_voter_state.clone(), - shared_authority_set: shared_authority_set.clone(), - justification_stream: justification_stream.clone(), - subscription_executor: subscription_executor.clone(), - finality_provider: finality_proof_provider.clone(), - }, - backend: rpc_backend.clone(), - }; - crate::rpc::create_full(deps).map_err(Into::into) - }) - }; + let rpc_extensions_builder = { + let client = client.clone(); + let pool = transaction_pool.clone(); + + Box::new( + move |deny_unsafe, subscription_executor: sc_rpc::SubscriptionTaskExecutor| { + let deps = crate::rpc::FullDeps { + client: client.clone(), + pool: pool.clone(), + deny_unsafe, + grandpa: crate::rpc::GrandpaDeps { + shared_voter_state: shared_voter_state.clone(), + shared_authority_set: shared_authority_set.clone(), + justification_stream: justification_stream.clone(), + subscription_executor: subscription_executor.clone(), + finality_provider: finality_proof_provider.clone(), + }, + backend: rpc_backend.clone(), + }; + crate::rpc::create_full(deps).map_err(Into::into) + }, + ) + }; let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { network: network.clone(), diff --git a/pallets/admin-utils/Cargo.toml b/pallets/admin-utils/Cargo.toml index d9ff8647a..cecd3cf39 100644 --- a/pallets/admin-utils/Cargo.toml +++ b/pallets/admin-utils/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/collective/Cargo.toml b/pallets/collective/Cargo.toml index 0f7eb33f8..c29f55d09 100644 --- a/pallets/collective/Cargo.toml +++ b/pallets/collective/Cargo.toml @@ -9,6 +9,9 @@ repository = "https://github.com/opentensor/subtensor" description = "Collective system: Members of a set of account IDs can make their collective feelings known through dispatched calls from one of two specialized origins." readme = "README.md" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/commitments/Cargo.toml b/pallets/commitments/Cargo.toml index db6bad359..885ace2f5 100644 --- a/pallets/commitments/Cargo.toml +++ b/pallets/commitments/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/commitments/src/lib.rs b/pallets/commitments/src/lib.rs index 0d126489d..fd9b0bbb3 100644 --- a/pallets/commitments/src/lib.rs +++ b/pallets/commitments/src/lib.rs @@ -258,12 +258,11 @@ where _info: &DispatchInfoOf, _len: usize, ) -> TransactionValidity { - match call.is_sub_type() { - _ => Ok(ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }), - } + call.is_sub_type(); + Ok(ValidTransaction { + priority: Self::get_priority_vanilla(), + ..Default::default() + }) } // NOTE: Add later when we put in a pre and post dispatch step. diff --git a/pallets/registry/Cargo.toml b/pallets/registry/Cargo.toml index 4e0c0bade..40bc5b960 100644 --- a/pallets/registry/Cargo.toml +++ b/pallets/registry/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/registry/src/benchmarking.rs b/pallets/registry/src/benchmarking.rs index e6ba8c732..fe3866dda 100644 --- a/pallets/registry/src/benchmarking.rs +++ b/pallets/registry/src/benchmarking.rs @@ -8,7 +8,7 @@ use frame_benchmarking::v1::account; use frame_benchmarking::v2::*; use frame_system::RawOrigin; -use sp_runtime::traits::{Bounded}; +use sp_runtime::traits::Bounded; fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); @@ -64,7 +64,8 @@ mod benchmarks { RawOrigin::Signed(caller.clone()).into(), vali_account.clone(), Box::new(create_identity_info::(0)), - ); + ) + .unwrap(); #[extrinsic_call] _(RawOrigin::Signed(caller.clone()), vali_account); diff --git a/pallets/subtensor/Cargo.toml b/pallets/subtensor/Cargo.toml index 069f179ac..a66324744 100644 --- a/pallets/subtensor/Cargo.toml +++ b/pallets/subtensor/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/subtensor/rpc/Cargo.toml b/pallets/subtensor/rpc/Cargo.toml index f9a95c851..362e28280 100644 --- a/pallets/subtensor/rpc/Cargo.toml +++ b/pallets/subtensor/rpc/Cargo.toml @@ -8,6 +8,9 @@ description = "A pallet that adds custom RPC calls to subtensor" license = "MIT" publish = false +[lints] +workspace = true + [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive", diff --git a/pallets/subtensor/runtime-api/Cargo.toml b/pallets/subtensor/runtime-api/Cargo.toml index 8193d504b..4648f8e67 100644 --- a/pallets/subtensor/runtime-api/Cargo.toml +++ b/pallets/subtensor/runtime-api/Cargo.toml @@ -8,12 +8,15 @@ description = "A pallet that adds a custom runtime API to Subtensor" license = "MIT" publish = false +[lints] +workspace = true + [dependencies] sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v1.0.0", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v1.0.0" } serde = { version = "1.0.132", features = ["derive"], default-features = false } -# local +# local pallet-subtensor = { version = "4.0.0-dev", path = "../../subtensor", default-features = false } [features] diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 5226449c1..554e2198f 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -1,5 +1,6 @@ #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "512"] +#![allow(clippy::too_many_arguments)] // Edit this file to define custom logic or remove it if it is not needed. // Learn more about FRAME and the core library of Substrate FRAME pallets: // diff --git a/pallets/subtensor/src/migration.rs b/pallets/subtensor/src/migration.rs index d45a6ebc6..700df4723 100644 --- a/pallets/subtensor/src/migration.rs +++ b/pallets/subtensor/src/migration.rs @@ -361,7 +361,7 @@ pub fn migrate_to_v1_separate_emission() -> Weight { for netuid in curr_loaded_emission { // Iterates over the netuids weight.saturating_accrue(T::DbWeight::get().reads(1)); - if let Err(_) = old::LoadedEmission::::try_get(netuid) { + if old::LoadedEmission::::try_get(netuid).is_err() { weight.saturating_accrue(T::DbWeight::get().writes(1)); old::LoadedEmission::::remove(netuid); log::warn!( diff --git a/pallets/subtensor/src/neuron_info.rs b/pallets/subtensor/src/neuron_info.rs index 42e926e80..e3b84ab20 100644 --- a/pallets/subtensor/src/neuron_info.rs +++ b/pallets/subtensor/src/neuron_info.rs @@ -60,14 +60,10 @@ impl Pallet { let mut neurons = Vec::new(); let n = Self::get_subnetwork_n(netuid); for uid in 0..n { - let _neuron = Self::get_neuron_subnet_exists(netuid, uid); - let neuron; - if _neuron.is_none() { - break; // No more neurons - } else { - // No error, hotkey was registered - neuron = _neuron.expect("Neuron should exist"); - } + let neuron = match Self::get_neuron_subnet_exists(netuid, uid) { + Some(n) => n, + None => break, // No more neurons + }; neurons.push(neuron); } @@ -75,14 +71,10 @@ impl Pallet { } fn get_neuron_subnet_exists(netuid: u16, uid: u16) -> Option> { - let _hotkey = Self::get_hotkey_for_net_and_uid(netuid, uid); - let hotkey; - if _hotkey.is_err() { - return None; - } else { - // No error, hotkey was registered - hotkey = _hotkey.expect("Hotkey should exist"); - } + let hotkey = match Self::get_hotkey_for_net_and_uid(netuid, uid) { + Ok(h) => h, + Err(_) => return None, + }; let axon_info = Self::get_axon_info(netuid, &hotkey.clone()); @@ -162,19 +154,14 @@ impl Pallet { return None; } - Self::get_neuron_subnet_exists(netuid, uid) } fn get_neuron_lite_subnet_exists(netuid: u16, uid: u16) -> Option> { - let _hotkey = Self::get_hotkey_for_net_and_uid(netuid, uid); - let hotkey; - if _hotkey.is_err() { - return None; - } else { - // No error, hotkey was registered - hotkey = _hotkey.expect("Hotkey should exist"); - } + let hotkey = match Self::get_hotkey_for_net_and_uid(netuid, uid) { + Ok(h) => h, + Err(_) => return None, + }; let axon_info = Self::get_axon_info(netuid, &hotkey.clone()); @@ -233,14 +220,10 @@ impl Pallet { let mut neurons: Vec> = Vec::new(); let n = Self::get_subnetwork_n(netuid); for uid in 0..n { - let _neuron = Self::get_neuron_lite_subnet_exists(netuid, uid); - let neuron; - if _neuron.is_none() { - break; // No more neurons - } else { - // No error, hotkey was registered - neuron = _neuron.expect("Neuron should exist"); - } + let neuron = match Self::get_neuron_lite_subnet_exists(netuid, uid) { + Some(n) => n, + None => break, // No more neurons + }; neurons.push(neuron); } @@ -252,7 +235,6 @@ impl Pallet { return None; } - Self::get_neuron_lite_subnet_exists(netuid, uid) } } diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index c895bbf7f..5e4fd1900 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor/" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] From 70ba6d90a71c5a310b1397b92927ee817780e6f8 Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 11:17:42 +0400 Subject: [PATCH 04/13] fix: more clippy warnings --- Cargo.toml | 3 ++ integration-tests/Cargo.toml | 3 ++ node/Cargo.toml | 3 ++ node/src/chain_spec.rs | 2 + node/src/service.rs | 61 ++++++++++++------------ pallets/admin-utils/Cargo.toml | 3 ++ pallets/collective/Cargo.toml | 3 ++ pallets/commitments/Cargo.toml | 3 ++ pallets/commitments/src/lib.rs | 11 ++--- pallets/registry/Cargo.toml | 3 ++ pallets/registry/src/benchmarking.rs | 5 +- pallets/subtensor/Cargo.toml | 3 ++ pallets/subtensor/rpc/Cargo.toml | 3 ++ pallets/subtensor/runtime-api/Cargo.toml | 5 +- pallets/subtensor/src/block_step.rs | 2 +- pallets/subtensor/src/lib.rs | 1 + pallets/subtensor/src/math.rs | 6 +-- pallets/subtensor/src/migration.rs | 2 +- pallets/subtensor/src/neuron_info.rs | 50 +++++++------------ pallets/subtensor/src/registration.rs | 16 +++---- pallets/subtensor/src/root.rs | 16 +++---- pallets/subtensor/src/staking.rs | 61 ++++++++++-------------- pallets/subtensor/src/weights.rs | 23 ++++----- pallets/subtensor/tests/epoch.rs | 4 +- runtime/Cargo.toml | 3 ++ 25 files changed, 146 insertions(+), 149 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index c761877e4..a05b3c9e5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -8,6 +8,9 @@ members = [ ] resolver = "2" +[workspace.lints.clippy] +type_complexity = "allow" + [profile.release] panic = "unwind" diff --git a/integration-tests/Cargo.toml b/integration-tests/Cargo.toml index d59aece3b..a83410167 100644 --- a/integration-tests/Cargo.toml +++ b/integration-tests/Cargo.toml @@ -7,6 +7,9 @@ edition = "2021" license = "Unlicense" repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [dependencies] ## diff --git a/node/Cargo.toml b/node/Cargo.toml index d02eab74a..5c0a0e489 100644 --- a/node/Cargo.toml +++ b/node/Cargo.toml @@ -10,6 +10,9 @@ publish = false repository = "https://github.com/opentensor/subtensor" build = "build.rs" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/node/src/chain_spec.rs b/node/src/chain_spec.rs index 69bc8e9c0..c4f703a12 100644 --- a/node/src/chain_spec.rs +++ b/node/src/chain_spec.rs @@ -492,6 +492,7 @@ fn localnet_genesis( } // Configure initial storage state for FRAME modules. +#[allow(clippy::too_many_arguments)] fn testnet_genesis( wasm_binary: &[u8], initial_authorities: Vec<(AuraId, GrandpaId)>, @@ -551,6 +552,7 @@ fn testnet_genesis( } // Configure initial storage state for FRAME modules. +#[allow(clippy::too_many_arguments)] fn finney_genesis( wasm_binary: &[u8], initial_authorities: Vec<(AuraId, GrandpaId)>, diff --git a/node/src/service.rs b/node/src/service.rs index 8efcc991b..c7eb3d416 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -222,14 +222,14 @@ pub fn new_full(config: Configuration) -> Result { ); } - let finality_proof_provider = sc_consensus_grandpa::FinalityProofProvider::new_for_service( - backend.clone(), - Some(grandpa_link.shared_authority_set().clone()), - ); - let rpc_backend = backend.clone(); - let justification_stream = grandpa_link.justification_stream(); - let shared_authority_set = grandpa_link.shared_authority_set().clone(); - let shared_voter_state = SharedVoterState::empty(); + let finality_proof_provider = sc_consensus_grandpa::FinalityProofProvider::new_for_service( + backend.clone(), + Some(grandpa_link.shared_authority_set().clone()), + ); + let rpc_backend = backend.clone(); + let justification_stream = grandpa_link.justification_stream(); + let shared_authority_set = grandpa_link.shared_authority_set().clone(); + let shared_voter_state = SharedVoterState::empty(); let role = config.role.clone(); let force_authoring = config.force_authoring; @@ -238,28 +238,29 @@ pub fn new_full(config: Configuration) -> Result { let enable_grandpa = !config.disable_grandpa; let prometheus_registry = config.prometheus_registry().cloned(); - let rpc_extensions_builder = { - let client = client.clone(); - let pool = transaction_pool.clone(); - - Box::new(move |deny_unsafe, subscription_executor: sc_rpc::SubscriptionTaskExecutor| { - let deps = - crate::rpc::FullDeps { - client: client.clone(), - pool: pool.clone(), - deny_unsafe, - grandpa: crate::rpc::GrandpaDeps { - shared_voter_state: shared_voter_state.clone(), - shared_authority_set: shared_authority_set.clone(), - justification_stream: justification_stream.clone(), - subscription_executor: subscription_executor.clone(), - finality_provider: finality_proof_provider.clone(), - }, - backend: rpc_backend.clone(), - }; - crate::rpc::create_full(deps).map_err(Into::into) - }) - }; + let rpc_extensions_builder = { + let client = client.clone(); + let pool = transaction_pool.clone(); + + Box::new( + move |deny_unsafe, subscription_executor: sc_rpc::SubscriptionTaskExecutor| { + let deps = crate::rpc::FullDeps { + client: client.clone(), + pool: pool.clone(), + deny_unsafe, + grandpa: crate::rpc::GrandpaDeps { + shared_voter_state: shared_voter_state.clone(), + shared_authority_set: shared_authority_set.clone(), + justification_stream: justification_stream.clone(), + subscription_executor: subscription_executor.clone(), + finality_provider: finality_proof_provider.clone(), + }, + backend: rpc_backend.clone(), + }; + crate::rpc::create_full(deps).map_err(Into::into) + }, + ) + }; let _rpc_handlers = sc_service::spawn_tasks(sc_service::SpawnTasksParams { network: network.clone(), diff --git a/pallets/admin-utils/Cargo.toml b/pallets/admin-utils/Cargo.toml index d9ff8647a..cecd3cf39 100644 --- a/pallets/admin-utils/Cargo.toml +++ b/pallets/admin-utils/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/collective/Cargo.toml b/pallets/collective/Cargo.toml index 0f7eb33f8..c29f55d09 100644 --- a/pallets/collective/Cargo.toml +++ b/pallets/collective/Cargo.toml @@ -9,6 +9,9 @@ repository = "https://github.com/opentensor/subtensor" description = "Collective system: Members of a set of account IDs can make their collective feelings known through dispatched calls from one of two specialized origins." readme = "README.md" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/commitments/Cargo.toml b/pallets/commitments/Cargo.toml index db6bad359..885ace2f5 100644 --- a/pallets/commitments/Cargo.toml +++ b/pallets/commitments/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/commitments/src/lib.rs b/pallets/commitments/src/lib.rs index 0d126489d..fd9b0bbb3 100644 --- a/pallets/commitments/src/lib.rs +++ b/pallets/commitments/src/lib.rs @@ -258,12 +258,11 @@ where _info: &DispatchInfoOf, _len: usize, ) -> TransactionValidity { - match call.is_sub_type() { - _ => Ok(ValidTransaction { - priority: Self::get_priority_vanilla(), - ..Default::default() - }), - } + call.is_sub_type(); + Ok(ValidTransaction { + priority: Self::get_priority_vanilla(), + ..Default::default() + }) } // NOTE: Add later when we put in a pre and post dispatch step. diff --git a/pallets/registry/Cargo.toml b/pallets/registry/Cargo.toml index 4e0c0bade..40bc5b960 100644 --- a/pallets/registry/Cargo.toml +++ b/pallets/registry/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/registry/src/benchmarking.rs b/pallets/registry/src/benchmarking.rs index e6ba8c732..fe3866dda 100644 --- a/pallets/registry/src/benchmarking.rs +++ b/pallets/registry/src/benchmarking.rs @@ -8,7 +8,7 @@ use frame_benchmarking::v1::account; use frame_benchmarking::v2::*; use frame_system::RawOrigin; -use sp_runtime::traits::{Bounded}; +use sp_runtime::traits::Bounded; fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); @@ -64,7 +64,8 @@ mod benchmarks { RawOrigin::Signed(caller.clone()).into(), vali_account.clone(), Box::new(create_identity_info::(0)), - ); + ) + .unwrap(); #[extrinsic_call] _(RawOrigin::Signed(caller.clone()), vali_account); diff --git a/pallets/subtensor/Cargo.toml b/pallets/subtensor/Cargo.toml index 069f179ac..a66324744 100644 --- a/pallets/subtensor/Cargo.toml +++ b/pallets/subtensor/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] diff --git a/pallets/subtensor/rpc/Cargo.toml b/pallets/subtensor/rpc/Cargo.toml index f9a95c851..362e28280 100644 --- a/pallets/subtensor/rpc/Cargo.toml +++ b/pallets/subtensor/rpc/Cargo.toml @@ -8,6 +8,9 @@ description = "A pallet that adds custom RPC calls to subtensor" license = "MIT" publish = false +[lints] +workspace = true + [dependencies] codec = { package = "parity-scale-codec", version = "3.0.0", default-features = false, features = [ "derive", diff --git a/pallets/subtensor/runtime-api/Cargo.toml b/pallets/subtensor/runtime-api/Cargo.toml index 8193d504b..4648f8e67 100644 --- a/pallets/subtensor/runtime-api/Cargo.toml +++ b/pallets/subtensor/runtime-api/Cargo.toml @@ -8,12 +8,15 @@ description = "A pallet that adds a custom runtime API to Subtensor" license = "MIT" publish = false +[lints] +workspace = true + [dependencies] sp-api = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v1.0.0", default-features = false } frame-support = { git = "https://github.com/paritytech/substrate", default-features = false, branch = "polkadot-v1.0.0" } serde = { version = "1.0.132", features = ["derive"], default-features = false } -# local +# local pallet-subtensor = { version = "4.0.0-dev", path = "../../subtensor", default-features = false } [features] diff --git a/pallets/subtensor/src/block_step.rs b/pallets/subtensor/src/block_step.rs index fda5e944e..c74611b4f 100644 --- a/pallets/subtensor/src/block_step.rs +++ b/pallets/subtensor/src/block_step.rs @@ -139,7 +139,7 @@ impl Pallet { Self::add_balance_to_coldkey_account( &Self::get_subnet_owner(netuid), - cut.to_num::().into(), + cut.to_num::(), ); // We are creating tokens here from the coinbase. diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index 5226449c1..554e2198f 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -1,5 +1,6 @@ #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "512"] +#![allow(clippy::too_many_arguments)] // Edit this file to define custom logic or remove it if it is not needed. // Learn more about FRAME and the core library of Substrate FRAME pallets: // diff --git a/pallets/subtensor/src/math.rs b/pallets/subtensor/src/math.rs index 7356c85a9..7ecb6ab62 100644 --- a/pallets/subtensor/src/math.rs +++ b/pallets/subtensor/src/math.rs @@ -119,14 +119,14 @@ pub fn vec_max_upscale_to_u16(vec: &Vec) -> Vec { #[allow(dead_code)] // Max-upscale u16 vector and convert to u16 so max_value = u16::MAX. Assumes u16 vector input. -pub fn vec_u16_max_upscale_to_u16(vec: &Vec) -> Vec { +pub fn vec_u16_max_upscale_to_u16(vec: &[u16]) -> Vec { let vec_fixed: Vec = vec.iter().map(|e: &u16| I32F32::from_num(*e)).collect(); vec_max_upscale_to_u16(&vec_fixed) } #[allow(dead_code)] // Checks if u16 vector, when normalized, has a max value not greater than a u16 ratio max_limit. -pub fn check_vec_max_limited(vec: &Vec, max_limit: u16) -> bool { +pub fn check_vec_max_limited(vec: &[u16], max_limit: u16) -> bool { let max_limit_fixed: I32F32 = I32F32::from_num(max_limit) / I32F32::from_num(u16::MAX); let mut vec_fixed: Vec = vec.iter().map(|e: &u16| I32F32::from_num(*e)).collect(); inplace_normalize(&mut vec_fixed); @@ -1131,7 +1131,7 @@ mod tests { } } - fn assert_vec_compare_u16(va: &Vec, vb: &Vec) { + fn assert_vec_compare_u16(va: &[u16], vb: &[u16]) { assert!(va.len() == vb.len()); for i in 0..va.len() { assert_eq!(va[i], vb[i]); diff --git a/pallets/subtensor/src/migration.rs b/pallets/subtensor/src/migration.rs index d45a6ebc6..700df4723 100644 --- a/pallets/subtensor/src/migration.rs +++ b/pallets/subtensor/src/migration.rs @@ -361,7 +361,7 @@ pub fn migrate_to_v1_separate_emission() -> Weight { for netuid in curr_loaded_emission { // Iterates over the netuids weight.saturating_accrue(T::DbWeight::get().reads(1)); - if let Err(_) = old::LoadedEmission::::try_get(netuid) { + if old::LoadedEmission::::try_get(netuid).is_err() { weight.saturating_accrue(T::DbWeight::get().writes(1)); old::LoadedEmission::::remove(netuid); log::warn!( diff --git a/pallets/subtensor/src/neuron_info.rs b/pallets/subtensor/src/neuron_info.rs index 42e926e80..e3b84ab20 100644 --- a/pallets/subtensor/src/neuron_info.rs +++ b/pallets/subtensor/src/neuron_info.rs @@ -60,14 +60,10 @@ impl Pallet { let mut neurons = Vec::new(); let n = Self::get_subnetwork_n(netuid); for uid in 0..n { - let _neuron = Self::get_neuron_subnet_exists(netuid, uid); - let neuron; - if _neuron.is_none() { - break; // No more neurons - } else { - // No error, hotkey was registered - neuron = _neuron.expect("Neuron should exist"); - } + let neuron = match Self::get_neuron_subnet_exists(netuid, uid) { + Some(n) => n, + None => break, // No more neurons + }; neurons.push(neuron); } @@ -75,14 +71,10 @@ impl Pallet { } fn get_neuron_subnet_exists(netuid: u16, uid: u16) -> Option> { - let _hotkey = Self::get_hotkey_for_net_and_uid(netuid, uid); - let hotkey; - if _hotkey.is_err() { - return None; - } else { - // No error, hotkey was registered - hotkey = _hotkey.expect("Hotkey should exist"); - } + let hotkey = match Self::get_hotkey_for_net_and_uid(netuid, uid) { + Ok(h) => h, + Err(_) => return None, + }; let axon_info = Self::get_axon_info(netuid, &hotkey.clone()); @@ -162,19 +154,14 @@ impl Pallet { return None; } - Self::get_neuron_subnet_exists(netuid, uid) } fn get_neuron_lite_subnet_exists(netuid: u16, uid: u16) -> Option> { - let _hotkey = Self::get_hotkey_for_net_and_uid(netuid, uid); - let hotkey; - if _hotkey.is_err() { - return None; - } else { - // No error, hotkey was registered - hotkey = _hotkey.expect("Hotkey should exist"); - } + let hotkey = match Self::get_hotkey_for_net_and_uid(netuid, uid) { + Ok(h) => h, + Err(_) => return None, + }; let axon_info = Self::get_axon_info(netuid, &hotkey.clone()); @@ -233,14 +220,10 @@ impl Pallet { let mut neurons: Vec> = Vec::new(); let n = Self::get_subnetwork_n(netuid); for uid in 0..n { - let _neuron = Self::get_neuron_lite_subnet_exists(netuid, uid); - let neuron; - if _neuron.is_none() { - break; // No more neurons - } else { - // No error, hotkey was registered - neuron = _neuron.expect("Neuron should exist"); - } + let neuron = match Self::get_neuron_lite_subnet_exists(netuid, uid) { + Some(n) => n, + None => break, // No more neurons + }; neurons.push(neuron); } @@ -252,7 +235,6 @@ impl Pallet { return None; } - Self::get_neuron_lite_subnet_exists(netuid, uid) } } diff --git a/pallets/subtensor/src/registration.rs b/pallets/subtensor/src/registration.rs index acf3f89b5..6533a23bc 100644 --- a/pallets/subtensor/src/registration.rs +++ b/pallets/subtensor/src/registration.rs @@ -94,16 +94,15 @@ impl Pallet { // --- 7. Ensure the callers coldkey has enough stake to perform the transaction. let current_block_number: u64 = Self::get_current_block_as_u64(); - let registration_cost_as_u64 = Self::get_burn_as_u64(netuid); - let registration_cost_as_balance = registration_cost_as_u64.into(); + let registration_cost = Self::get_burn_as_u64(netuid); ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, registration_cost_as_balance), + Self::can_remove_balance_from_coldkey_account(&coldkey, registration_cost), Error::::NotEnoughBalanceToStake ); // --- 8. Ensure the remove operation from the coldkey is a success. let actual_burn_amount = - Self::remove_balance_from_coldkey_account(&coldkey, registration_cost_as_balance)?; + Self::remove_balance_from_coldkey_account(&coldkey, registration_cost)?; // The burn occurs here. Self::burn_tokens(actual_burn_amount); @@ -397,8 +396,7 @@ impl Pallet { let balance_to_add: u64 = 100_000_000_000; Self::coinbase(100_000_000_000); // We are creating tokens here from the coinbase. - let balance_to_be_added_as_balance = balance_to_add.into(); - Self::add_balance_to_coldkey_account(&coldkey, balance_to_be_added_as_balance); + Self::add_balance_to_coldkey_account(&coldkey, balance_to_add); // --- 6. Deposit successful event. log::info!( @@ -726,13 +724,11 @@ impl Pallet { .saturating_accrue(T::DbWeight::get().reads((TotalNetworks::::get() + 1u16) as u64)); let swap_cost = 1_000_000_000u64; - let swap_cost_as_balance = swap_cost.into(); ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance), + Self::can_remove_balance_from_coldkey_account(&coldkey, swap_cost), Error::::NotEnoughBalance ); - let actual_burn_amount = - Self::remove_balance_from_coldkey_account(&coldkey, swap_cost_as_balance)?; + let actual_burn_amount = Self::remove_balance_from_coldkey_account(&coldkey, swap_cost)?; Self::burn_tokens(actual_burn_amount); Owner::::remove(old_hotkey); diff --git a/pallets/subtensor/src/root.rs b/pallets/subtensor/src/root.rs index 5fdb1d95d..cf049b74f 100644 --- a/pallets/subtensor/src/root.rs +++ b/pallets/subtensor/src/root.rs @@ -189,7 +189,7 @@ impl Pallet { // # Returns: // * 'bool': 'true' if any of the UIDs are invalid, 'false' otherwise. // - pub fn contains_invalid_root_uids(netuids: &Vec) -> bool { + pub fn contains_invalid_root_uids(netuids: &[u16]) -> bool { for netuid in netuids { if !Self::if_subnet_exist(*netuid) { log::debug!( @@ -205,7 +205,7 @@ impl Pallet { // Sets the emission values for each netuid // // - pub fn set_emission_values(netuids: &Vec, emission: Vec) -> Result<(), &'static str> { + pub fn set_emission_values(netuids: &[u16], emission: Vec) -> Result<(), &'static str> { log::debug!( "set_emission_values: netuids: {:?} emission:{:?}", netuids, @@ -646,10 +646,9 @@ impl Pallet { // --- 2. Calculate and lock the required tokens. let lock_amount: u64 = Self::get_network_lock_cost(); - let lock_as_balance = lock_amount.into(); - log::debug!("network lock_amount: {:?}", lock_amount,); + log::debug!("network lock_amount: {:?}", lock_amount); ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, lock_as_balance), + Self::can_remove_balance_from_coldkey_account(&coldkey, lock_amount), Error::::NotEnoughBalanceToStake ); @@ -683,7 +682,7 @@ impl Pallet { // --- 5. Perform the lock operation. let actual_lock_amount = - Self::remove_balance_from_coldkey_account(&coldkey, lock_as_balance)?; + Self::remove_balance_from_coldkey_account(&coldkey, lock_amount)?; Self::set_subnet_locked_balance(netuid_to_register, actual_lock_amount); Self::set_network_last_lock(actual_lock_amount); @@ -846,9 +845,6 @@ impl Pallet { let owner_coldkey = SubnetOwner::::get(netuid); let reserved_amount = Self::get_subnet_locked_balance(netuid); - // Ensure that we can convert this u64 to a balance. - let reserved_amount_as_bal = reserved_amount.into(); - // --- 2. Remove network count. SubnetworkN::::remove(netuid); @@ -918,7 +914,7 @@ impl Pallet { BurnRegistrationsThisInterval::::remove(netuid); // --- 12. Add the balance back to the owner. - Self::add_balance_to_coldkey_account(&owner_coldkey, reserved_amount_as_bal); + Self::add_balance_to_coldkey_account(&owner_coldkey, reserved_amount); Self::set_subnet_locked_balance(netuid, 0); SubnetOwner::::remove(netuid); } diff --git a/pallets/subtensor/src/staking.rs b/pallets/subtensor/src/staking.rs index a104a7af8..1278e71f9 100644 --- a/pallets/subtensor/src/staking.rs +++ b/pallets/subtensor/src/staking.rs @@ -132,7 +132,7 @@ impl Pallet { hotkey: T::AccountId, stake_to_be_added: u64, ) -> dispatch::DispatchResult { - // --- 1. We check that the transaction is signed by the caller and retrieve the T::AccountId coldkey information. + // We check that the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; log::info!( "do_add_stake( origin:{:?} hotkey:{:?}, stake_to_be_added:{:?} )", @@ -141,28 +141,25 @@ impl Pallet { stake_to_be_added ); - // --- 2. We convert the stake u64 into a balance. - let stake_as_balance = stake_to_be_added.into(); - - // --- 3. Ensure the callers coldkey has enough stake to perform the transaction. + // Ensure the callers coldkey has enough stake to perform the transaction. ensure!( - Self::can_remove_balance_from_coldkey_account(&coldkey, stake_as_balance), + Self::can_remove_balance_from_coldkey_account(&coldkey, stake_to_be_added), Error::::NotEnoughBalanceToStake ); - // --- 4. Ensure that the hotkey account exists this is only possible through registration. + // Ensure that the hotkey account exists this is only possible through registration. ensure!( Self::hotkey_account_exists(&hotkey), Error::::NotRegistered ); - // --- 5. Ensure that the hotkey allows delegation or that the hotkey is owned by the calling coldkey. + // Ensure that the hotkey allows delegation or that the hotkey is owned by the calling coldkey. ensure!( Self::hotkey_is_delegate(&hotkey) || Self::coldkey_owns_hotkey(&coldkey, &hotkey), Error::::NonAssociatedColdKey ); - // --- 6. Ensure we don't exceed stake rate limit + // Ensure we don't exceed stake rate limit let stakes_this_interval = Self::get_stakes_this_interval_for_coldkey_hotkey(&coldkey, &hotkey); ensure!( @@ -170,7 +167,7 @@ impl Pallet { Error::::StakeRateLimitExceeded ); - // --- 7. If this is a nomination stake, check if total stake after adding will be above + // If this is a nomination stake, check if total stake after adding will be above // the minimum required stake. // If coldkey is not owner of the hotkey, it's a nomination stake. @@ -184,18 +181,18 @@ impl Pallet { ); } - // --- 8. Ensure the remove operation from the coldkey is a success. + // Ensure the remove operation from the coldkey is a success. let actual_amount_to_stake = - Self::remove_balance_from_coldkey_account(&coldkey, stake_as_balance)?; + Self::remove_balance_from_coldkey_account(&coldkey, stake_to_be_added)?; - // --- 9. If we reach here, add the balance to the hotkey. + // If we reach here, add the balance to the hotkey. Self::increase_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, actual_amount_to_stake); // Set last block for rate limiting let block: u64 = Self::get_current_block_as_u64(); Self::set_last_tx_block(&coldkey, block); - // --- 10. Emit the staking event. + // Emit the staking event. Self::set_stakes_this_interval_for_coldkey_hotkey( &coldkey, &hotkey, @@ -209,7 +206,7 @@ impl Pallet { ); Self::deposit_event(Event::StakeAdded(hotkey, actual_amount_to_stake)); - // --- 11. Ok and return. + // Ok and return. Ok(()) } @@ -251,7 +248,7 @@ impl Pallet { hotkey: T::AccountId, stake_to_be_removed: u64, ) -> dispatch::DispatchResult { - // --- 1. We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. + // We check the transaction is signed by the caller and retrieve the T::AccountId coldkey information. let coldkey = ensure_signed(origin)?; log::info!( "do_remove_stake( origin:{:?} hotkey:{:?}, stake_to_be_removed:{:?} )", @@ -260,34 +257,31 @@ impl Pallet { stake_to_be_removed ); - // --- 2. Ensure that the hotkey account exists this is only possible through registration. + // Ensure that the hotkey account exists this is only possible through registration. ensure!( Self::hotkey_account_exists(&hotkey), Error::::NotRegistered ); - // --- 3. Ensure that the hotkey allows delegation or that the hotkey is owned by the calling coldkey. + // Ensure that the hotkey allows delegation or that the hotkey is owned by the calling coldkey. ensure!( Self::hotkey_is_delegate(&hotkey) || Self::coldkey_owns_hotkey(&coldkey, &hotkey), Error::::NonAssociatedColdKey ); - // --- Ensure that the stake amount to be removed is above zero. + // Ensure that the stake amount to be removed is above zero. ensure!( stake_to_be_removed > 0, Error::::NotEnoughStaketoWithdraw ); - // --- 4. Ensure that the hotkey has enough stake to withdraw. + // Ensure that the hotkey has enough stake to withdraw. ensure!( Self::has_enough_stake(&coldkey, &hotkey, stake_to_be_removed), Error::::NotEnoughStaketoWithdraw ); - // --- 5. Ensure that we can conver this u64 to a balance. - let stake_to_be_added_as_currency = stake_to_be_removed.into(); - - // --- 6. Ensure we don't exceed stake rate limit + // Ensure we don't exceed stake rate limit let unstakes_this_interval = Self::get_stakes_this_interval_for_coldkey_hotkey(&coldkey, &hotkey); ensure!( @@ -295,7 +289,7 @@ impl Pallet { Error::::UnstakeRateLimitExceeded ); - // --- 7. If this is a nomination stake, check if total stake after removing will be above + // If this is a nomination stake, check if total stake after removing will be above // the minimum required stake. // If coldkey is not owner of the hotkey, it's a nomination stake. @@ -309,17 +303,17 @@ impl Pallet { ); } - // --- 8. We remove the balance from the hotkey. + // We remove the balance from the hotkey. Self::decrease_stake_on_coldkey_hotkey_account(&coldkey, &hotkey, stake_to_be_removed); - // --- 9. We add the balancer to the coldkey. If the above fails we will not credit this coldkey. - Self::add_balance_to_coldkey_account(&coldkey, stake_to_be_added_as_currency); + // We add the balancer to the coldkey. If the above fails we will not credit this coldkey. + Self::add_balance_to_coldkey_account(&coldkey, stake_to_be_removed); // Set last block for rate limiting let block: u64 = Self::get_current_block_as_u64(); Self::set_last_tx_block(&coldkey, block); - // --- 10. Emit the unstaking event. + // Emit the unstaking event. Self::set_stakes_this_interval_for_coldkey_hotkey( &coldkey, &hotkey, @@ -333,7 +327,7 @@ impl Pallet { ); Self::deposit_event(Event::StakeRemoved(hotkey, stake_to_be_removed)); - // --- 11. Done and ok. + // Done and ok. Ok(()) } @@ -559,8 +553,7 @@ impl Pallet { // Actually deletes the staking account. Self::empty_stake_on_coldkey_hotkey_account(coldkey, hotkey); // Convert the removed stake back to balance and add it to the coldkey account. - let stake_as_balance = stake.into(); - Self::add_balance_to_coldkey_account(coldkey, stake_as_balance); + Self::add_balance_to_coldkey_account(coldkey, stake); } } } @@ -655,15 +648,13 @@ impl Pallet { hotkey, ) { - // Convert to balance and add to the coldkey account. - let stake_i_as_balance = stake_i.into(); // Stake is successfully converted to balance. // Remove the stake from the coldkey - hotkey pairing. Self::decrease_stake_on_coldkey_hotkey_account(&delegate_coldkey_i, hotkey, stake_i); // Add the balance to the coldkey account. - Self::add_balance_to_coldkey_account(&delegate_coldkey_i, stake_i_as_balance); + Self::add_balance_to_coldkey_account(&delegate_coldkey_i, stake_i); } } } diff --git a/pallets/subtensor/src/weights.rs b/pallets/subtensor/src/weights.rs index fae38fa2b..6969a3a67 100644 --- a/pallets/subtensor/src/weights.rs +++ b/pallets/subtensor/src/weights.rs @@ -122,7 +122,7 @@ impl Pallet { ); // --- 9. Get the neuron uid of associated hotkey on network netuid. - + let net_neuron_uid = Self::get_uid_for_net_and_hotkey(netuid, &hotkey); ensure!( net_neuron_uid.is_ok(), @@ -230,7 +230,7 @@ impl Pallet { } // Checks for any invalid uids on this network. - pub fn contains_invalid_uids(netuid: u16, uids: &Vec) -> bool { + pub fn contains_invalid_uids(netuid: u16, uids: &[u16]) -> bool { for uid in uids { if !Self::is_uid_exist_on_network(netuid, *uid) { log::debug!( @@ -245,12 +245,12 @@ impl Pallet { } // Returns true if the passed uids have the same length of the passed values. - pub fn uids_match_values(uids: &Vec, values: &Vec) -> bool { + pub fn uids_match_values(uids: &[u16], values: &[u16]) -> bool { uids.len() == values.len() } // Returns true if the items contain duplicates. - pub fn has_duplicate_uids(items: &Vec) -> bool { + pub fn has_duplicate_uids(items: &[u16]) -> bool { let mut parsed: Vec = Vec::new(); for item in items { if parsed.contains(item) { @@ -262,12 +262,7 @@ impl Pallet { } // Returns True if setting self-weight or has validator permit. - pub fn check_validator_permit( - netuid: u16, - uid: u16, - uids: &Vec, - weights: &Vec, - ) -> bool { + pub fn check_validator_permit(netuid: u16, uid: u16, uids: &[u16], weights: &[u16]) -> bool { // Check self weight. Allowed to set single value for self weight. if Self::is_self_weight(uid, uids, weights) { return true; @@ -277,7 +272,7 @@ impl Pallet { } // Returns True if the uids and weights are have a valid length for uid on network. - pub fn check_length(netuid: u16, uid: u16, uids: &Vec, weights: &Vec) -> bool { + pub fn check_length(netuid: u16, uid: u16, uids: &[u16], weights: &[u16]) -> bool { let subnet_n: usize = Self::get_subnetwork_n(netuid) as usize; let min_allowed_length: usize = Self::get_min_allowed_weights(netuid) as usize; let min_allowed: usize = { @@ -314,7 +309,7 @@ impl Pallet { } // Returns False if the weights exceed the max_weight_limit for this network. - pub fn max_weight_limited(netuid: u16, uid: u16, uids: &Vec, weights: &Vec) -> bool { + pub fn max_weight_limited(netuid: u16, uid: u16, uids: &[u16], weights: &[u16]) -> bool { // Allow self weights to exceed max weight limit. if Self::is_self_weight(uid, uids, weights) { return true; @@ -331,7 +326,7 @@ impl Pallet { } // Returns true if the uids and weights correspond to a self weight on the uid. - pub fn is_self_weight(uid: u16, uids: &Vec, weights: &Vec) -> bool { + pub fn is_self_weight(uid: u16, uids: &[u16], weights: &[u16]) -> bool { if weights.len() != 1 { return false; } @@ -342,7 +337,7 @@ impl Pallet { } // Returns False is the number of uids exceeds the allowed number of uids for this network. - pub fn check_len_uids_within_allowed(netuid: u16, uids: &Vec) -> bool { + pub fn check_len_uids_within_allowed(netuid: u16, uids: &[u16]) -> bool { let subnetwork_n: u16 = Self::get_subnetwork_n(netuid); // we should expect at most subnetwork_n uids. uids.len() <= subnetwork_n as usize diff --git a/pallets/subtensor/tests/epoch.rs b/pallets/subtensor/tests/epoch.rs index 415737bdf..9383ea9e6 100644 --- a/pallets/subtensor/tests/epoch.rs +++ b/pallets/subtensor/tests/epoch.rs @@ -143,8 +143,8 @@ fn uid_stats(netuid: u16, uid: u16) { fn init_run_epochs( netuid: u16, n: u16, - validators: &Vec, - servers: &Vec, + validators: &[u16], + servers: &[u16], epochs: u16, stake_per_validator: u64, server_self: bool, diff --git a/runtime/Cargo.toml b/runtime/Cargo.toml index c895bbf7f..5e4fd1900 100644 --- a/runtime/Cargo.toml +++ b/runtime/Cargo.toml @@ -9,6 +9,9 @@ license = "Unlicense" publish = false repository = "https://github.com/opentensor/subtensor/" +[lints] +workspace = true + [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] From 96144e9b8e4d9ee8f65e1140fac61745c486e86b Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 11:51:43 +0400 Subject: [PATCH 05/13] fix: more clippy warnings --- pallets/subtensor/src/math.rs | 96 +++++++++++++-------------- pallets/subtensor/src/registration.rs | 3 + pallets/subtensor/src/staking.rs | 14 +--- pallets/subtensor/tests/weights.rs | 2 +- 4 files changed, 55 insertions(+), 60 deletions(-) diff --git a/pallets/subtensor/src/math.rs b/pallets/subtensor/src/math.rs index 7ecb6ab62..cce3f484d 100644 --- a/pallets/subtensor/src/math.rs +++ b/pallets/subtensor/src/math.rs @@ -84,7 +84,7 @@ pub fn vec_fixed_proportions_to_u16(vec: Vec) -> Vec { #[allow(dead_code)] // Max-upscale vector and convert to u16 so max_value = u16::MAX. Assumes non-negative normalized input. -pub fn vec_max_upscale_to_u16(vec: &Vec) -> Vec { +pub fn vec_max_upscale_to_u16(vec: &[I32F32]) -> Vec { let u16_max: I32F32 = I32F32::from_num(u16::MAX); let threshold: I32F32 = I32F32::from_num(32768); let max_value: Option<&I32F32> = vec.iter().max(); @@ -138,7 +138,7 @@ pub fn check_vec_max_limited(vec: &[u16], max_limit: u16) -> bool { } #[allow(dead_code)] -pub fn sum(x: &Vec) -> I32F32 { +pub fn sum(x: &[I32F32]) -> I32F32 { x.iter().sum() } @@ -166,7 +166,7 @@ where // Return true when vector sum is zero. #[allow(dead_code)] -pub fn is_zero(vector: &Vec) -> bool { +pub fn is_zero(vector: &[I32F32]) -> bool { let vector_sum: I32F32 = sum(vector); vector_sum == I32F32::from_num(0) } @@ -213,7 +213,7 @@ pub fn sigmoid_safe(input: I32F32, rho: I32F32, kappa: I32F32) -> I32F32 { // Returns a bool vector where an item is true if the vector item is in topk values. #[allow(dead_code)] -pub fn is_topk(vector: &Vec, k: usize) -> Vec { +pub fn is_topk(vector: &[I32F32], k: usize) -> Vec { let n: usize = vector.len(); let mut result: Vec = vec![true; n]; if n < k { @@ -229,12 +229,12 @@ pub fn is_topk(vector: &Vec, k: usize) -> Vec { // Returns a normalized (sum to 1 except 0) copy of the input vector. #[allow(dead_code)] -pub fn normalize(x: &Vec) -> Vec { +pub fn normalize(x: &[I32F32]) -> Vec { let x_sum: I32F32 = sum(x); if x_sum != I32F32::from_num(0.0_f32) { return x.iter().map(|xi| xi / x_sum).collect(); } else { - x.clone() + x.to_vec() } } @@ -275,7 +275,7 @@ pub fn inplace_normalize_64(x: &mut Vec) { /// Returns x / y for input vectors x and y, if y == 0 return 0. #[allow(dead_code)] -pub fn vecdiv(x: &Vec, y: &Vec) -> Vec { +pub fn vecdiv(x: &[I32F32], y: &[I32F32]) -> Vec { assert_eq!(x.len(), y.len()); let n = x.len(); let mut result: Vec = vec![I32F32::from_num(0); n]; @@ -314,7 +314,7 @@ pub fn inplace_row_normalize_sparse(sparse_matrix: &mut Vec>) // Sum across each row (dim=0) of a matrix. #[allow(dead_code)] -pub fn row_sum(x: &Vec>) -> Vec { +pub fn row_sum(x: &[Vec]) -> Vec { if x.is_empty() { return vec![]; } @@ -333,7 +333,7 @@ pub fn row_sum(x: &Vec>) -> Vec { // Sum across each row (dim=0) of a sparse matrix. #[allow(dead_code)] -pub fn row_sum_sparse(sparse_matrix: &Vec>) -> Vec { +pub fn row_sum_sparse(sparse_matrix: &[Vec<(u16, I32F32)>]) -> Vec { let rows = sparse_matrix.len(); let mut result: Vec = vec![I32F32::from_num(0); rows]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -346,7 +346,7 @@ pub fn row_sum_sparse(sparse_matrix: &Vec>) -> Vec { // Sum across each column (dim=1) of a matrix. #[allow(dead_code)] -pub fn col_sum(x: &Vec>) -> Vec { +pub fn col_sum(x: &[Vec]) -> Vec { if x.is_empty() { return vec![]; } @@ -366,7 +366,7 @@ pub fn col_sum(x: &Vec>) -> Vec { // Sum across each column (dim=1) of a sparse matrix. #[allow(dead_code)] -pub fn col_sum_sparse(sparse_matrix: &Vec>, columns: u16) -> Vec { +pub fn col_sum_sparse(sparse_matrix: &[Vec<(u16, I32F32)>], columns: u16) -> Vec { let mut result: Vec = vec![I32F32::from_num(0); columns as usize]; for sparse_row in sparse_matrix.iter() { for (j, value) in sparse_row.iter() { @@ -544,7 +544,7 @@ pub fn inplace_mask_diag(matrix: &mut Vec>) { #[allow(dead_code)] pub fn mask_rows_sparse( mask: &Vec, - sparse_matrix: &Vec>, + sparse_matrix: &[Vec<(u16, I32F32)>], ) -> Vec> { let n: usize = sparse_matrix.len(); assert_eq!(n, mask.len()); @@ -559,7 +559,7 @@ pub fn mask_rows_sparse( // Return a new sparse matrix with a masked out diagonal of input sparse matrix. #[allow(dead_code)] -pub fn mask_diag_sparse(sparse_matrix: &Vec>) -> Vec> { +pub fn mask_diag_sparse(sparse_matrix: &[Vec<(u16, I32F32)>]) -> Vec> { let n: usize = sparse_matrix.len(); let mut result: Vec> = vec![vec![]; n]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -575,7 +575,7 @@ pub fn mask_diag_sparse(sparse_matrix: &Vec>) -> Vec>, + sparse_matrix: &[Vec<(u16, I32F32)>], first_vector: &Vec, second_vector: &Vec, mask_fn: &dyn Fn(u64, u64) -> bool, @@ -594,7 +594,7 @@ pub fn vec_mask_sparse_matrix( // Row-wise matrix-vector hadamard product. #[allow(dead_code)] -pub fn row_hadamard(matrix: &Vec>, vector: &Vec) -> Vec> { +pub fn row_hadamard(matrix: &[Vec], vector: &[I32F32]) -> Vec> { if matrix.is_empty() { return vec![vec![]]; } @@ -614,10 +614,10 @@ pub fn row_hadamard(matrix: &Vec>, vector: &Vec) -> Vec>, - vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + vector: &[I32F32], ) -> Vec> { - let mut result: Vec> = sparse_matrix.clone(); + let mut result: Vec> = sparse_matrix.to_vec(); for (i, sparse_row) in result.iter_mut().enumerate() { for (_j, value) in sparse_row.iter_mut() { *value *= vector[i]; @@ -628,7 +628,7 @@ pub fn row_hadamard_sparse( // Row-wise matrix-vector product, column-wise sum: result_j = SUM(i) vector_i * matrix_ij. #[allow(dead_code)] -pub fn matmul(matrix: &Vec>, vector: &Vec) -> Vec { +pub fn matmul(matrix: &[Vec], vector: &[I32F32]) -> Vec { if matrix.is_empty() { return vec![]; } @@ -672,7 +672,7 @@ pub fn matmul_64(matrix: &Vec>, vector: &Vec) -> Vec // Column-wise matrix-vector product, row-wise sum: result_i = SUM(j) vector_j * matrix_ij. #[allow(dead_code)] -pub fn matmul_transpose(matrix: &Vec>, vector: &Vec) -> Vec { +pub fn matmul_transpose(matrix: &[Vec], vector: &[I32F32]) -> Vec { if matrix.is_empty() { return vec![]; } @@ -695,8 +695,8 @@ pub fn matmul_transpose(matrix: &Vec>, vector: &Vec) -> Vec< // Row-wise sparse_matrix-vector product, column-wise sum: result_j = SUM(i) vector_i * matrix_ij. #[allow(dead_code)] pub fn matmul_sparse( - sparse_matrix: &Vec>, - vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + vector: &[I32F32], columns: u16, ) -> Vec { let mut result: Vec = vec![I32F32::from_num(0.0); columns as usize]; @@ -714,8 +714,8 @@ pub fn matmul_sparse( // Column-wise sparse_matrix-vector product, row-wise sum: result_i = SUM(j) vector_j * matrix_ij. #[allow(dead_code)] pub fn matmul_transpose_sparse( - sparse_matrix: &Vec>, - vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + vector: &[I32F32], ) -> Vec { let mut result: Vec = vec![I32F32::from_num(0.0); sparse_matrix.len()]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -731,7 +731,7 @@ pub fn matmul_transpose_sparse( // Set inplace matrix values above column threshold to threshold value. #[allow(dead_code)] -pub fn inplace_col_clip(x: &mut Vec>, col_threshold: &Vec) { +pub fn inplace_col_clip(x: &mut Vec>, col_threshold: &[I32F32]) { for i in 0..x.len() { for j in 0..x[i].len() { if x[i][j] > col_threshold[j] { @@ -744,8 +744,8 @@ pub fn inplace_col_clip(x: &mut Vec>, col_threshold: &Vec) { // Return sparse matrix with values above column threshold set to threshold value. #[allow(dead_code)] pub fn col_clip_sparse( - sparse_matrix: &Vec>, - col_threshold: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + col_threshold: &[I32F32], ) -> Vec> { let mut result: Vec> = vec![vec![]; sparse_matrix.len()]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -765,7 +765,7 @@ pub fn col_clip_sparse( // Set matrix values below threshold to lower, and equal-above to upper. #[allow(dead_code)] pub fn clip( - x: &Vec>, + x: &[Vec], threshold: I32F32, upper: I32F32, lower: I32F32, @@ -803,7 +803,7 @@ pub fn inplace_clip(x: &mut Vec>, threshold: I32F32, upper: I32F32, // Does not add missing elements (0 value assumed) when lower!=0. #[allow(dead_code)] pub fn clip_sparse( - sparse_matrix: &Vec>, + sparse_matrix: &[Vec<(u16, I32F32)>], threshold: I32F32, upper: I32F32, lower: I32F32, @@ -826,10 +826,10 @@ pub fn clip_sparse( // Assumes relatively random score order for efficiency, typically less than O(nlogn) complexity. // // # Args: -// * 'stake': ( &Vec ): +// * 'stake': ( &[I32F32] ): // - stake, assumed to be normalized. // -// * 'score': ( &Vec ): +// * 'score': ( &[I32F32] ): // - score for which median is sought, 0 <= score <= 1 // // * 'partition_idx' ( &Vec ): @@ -850,8 +850,8 @@ pub fn clip_sparse( // #[allow(dead_code)] pub fn weighted_median( - stake: &Vec, - score: &Vec, + stake: &[I32F32], + score: &[I32F32], partition_idx: &Vec, minority: I32F32, partition_lo: I32F32, @@ -910,8 +910,8 @@ pub fn weighted_median( /// Column-wise weighted median, e.g. stake-weighted median scores per server (column) over all validators (rows). #[allow(dead_code)] pub fn weighted_median_col( - stake: &Vec, - score: &Vec>, + stake: &[I32F32], + score: &[Vec], majority: I32F32, ) -> Vec { let rows = stake.len(); @@ -948,8 +948,8 @@ pub fn weighted_median_col( /// Column-wise weighted median, e.g. stake-weighted median scores per server (column) over all validators (rows). #[allow(dead_code)] pub fn weighted_median_col_sparse( - stake: &Vec, - score: &Vec>, + stake: &[I32F32], + score: &[Vec<(u16, I32F32)>], columns: u16, majority: I32F32, ) -> Vec { @@ -987,7 +987,7 @@ pub fn weighted_median_col_sparse( // Element-wise product of two matrices. #[allow(dead_code)] -pub fn hadamard(mat1: &Vec>, mat2: &Vec>) -> Vec> { +pub fn hadamard(mat1: &[Vec], mat2: &[Vec]) -> Vec> { assert!(mat1.len() == mat2.len()); if mat1.is_empty() { return vec![vec![]; 1]; @@ -1008,8 +1008,8 @@ pub fn hadamard(mat1: &Vec>, mat2: &Vec>) -> Vec>, - mat2: &Vec>, + mat1: &[Vec<(u16, I32F32)>], + mat2: &[Vec<(u16, I32F32)>], columns: u16, ) -> Vec> { assert!(mat1.len() == mat2.len()); @@ -1039,7 +1039,7 @@ pub fn hadamard_sparse( // `alpha` is the EMA coefficient, how much to add of the new observation, typically small, // higher alpha discounts older observations faster. #[allow(dead_code)] -pub fn mat_ema(new: &Vec>, old: &Vec>, alpha: I32F32) -> Vec> { +pub fn mat_ema(new: &[Vec], old: &[Vec], alpha: I32F32) -> Vec> { if new.is_empty() { return vec![vec![]; 1]; } @@ -1063,8 +1063,8 @@ pub fn mat_ema(new: &Vec>, old: &Vec>, alpha: I32F32) -> // higher alpha discounts older observations faster. #[allow(dead_code)] pub fn mat_ema_sparse( - new: &Vec>, - old: &Vec>, + new: &[Vec<(u16, I32F32)>], + old: &[Vec<(u16, I32F32)>], alpha: I32F32, ) -> Vec> { assert!(new.len() == old.len()); @@ -1091,7 +1091,7 @@ pub fn mat_ema_sparse( // Return sparse matrix only with elements >= threshold of an input sparse matrix. #[allow(dead_code)] -pub fn sparse_threshold(w: &Vec>, threshold: I32F32) -> Vec> { +pub fn sparse_threshold(w: &[Vec<(u16, I32F32)>], threshold: I32F32) -> Vec> { let mut sparse_threshold_result: Vec> = vec![vec![]; w.len()]; for (uid_i, weights_i) in w.iter().enumerate() { for (uid_j, weight_ij) in weights_i.iter() { @@ -1117,7 +1117,7 @@ mod tests { assert!(I64F64::abs(a - b) <= epsilon, "a({:?}) != b({:?})", a, b); } - fn assert_vec_compare(va: &Vec, vb: &Vec, epsilon: I32F32) { + fn assert_vec_compare(va: &[I32F32], vb: &[I32F32], epsilon: I32F32) { assert!(va.len() == vb.len()); for i in 0..va.len() { assert_float_compare(va[i], vb[i], epsilon); @@ -1138,7 +1138,7 @@ mod tests { } } - fn assert_mat_compare(ma: &Vec>, mb: &Vec>, epsilon: I32F32) { + fn assert_mat_compare(ma: &[Vec], mb: &[Vec], epsilon: I32F32) { assert!(ma.len() == mb.len()); for row in 0..ma.len() { assert!(ma[row].len() == mb[row].len()); @@ -1149,8 +1149,8 @@ mod tests { } fn assert_sparse_mat_compare( - ma: &Vec>, - mb: &Vec>, + ma: &[Vec<(u16, I32F32)>], + mb: &[Vec<(u16, I32F32)>], epsilon: I32F32, ) { assert!(ma.len() == mb.len()); diff --git a/pallets/subtensor/src/registration.rs b/pallets/subtensor/src/registration.rs index 6533a23bc..b75250536 100644 --- a/pallets/subtensor/src/registration.rs +++ b/pallets/subtensor/src/registration.rs @@ -438,6 +438,9 @@ impl Pallet { let block_at_registration: u64 = Self::get_neuron_block_at_registration(netuid, neuron_uid_i); + // Too dangerous to remove this comparison change while enabling clippy. allow it for + // now. + #[allow(clippy::comparison_chain)] if min_score == pruning_score { if current_block - block_at_registration < immunity_period { //neuron is in immunity period diff --git a/pallets/subtensor/src/staking.rs b/pallets/subtensor/src/staking.rs index 1278e71f9..15caa2467 100644 --- a/pallets/subtensor/src/staking.rs +++ b/pallets/subtensor/src/staking.rs @@ -612,11 +612,7 @@ impl Pallet { coldkey: &T::AccountId, amount: <::Currency as fungible::Inspect<::AccountId>>::Balance, ) -> Result { - let amount_u64: u64 = amount - .try_into() - .map_err(|_| Error::::CouldNotConvertToU64)?; - - if amount_u64 == 0 { + if amount == 0 { return Ok(0); } @@ -630,15 +626,11 @@ impl Pallet { .map_err(|_| Error::::BalanceWithdrawalError)? .peek(); - let credit_u64: u64 = credit - .try_into() - .map_err(|_| Error::::CouldNotConvertToU64)?; - - if credit_u64 == 0 { + if credit == 0 { return Err(Error::::BalanceWithdrawalError.into()); } - Ok(credit_u64) + Ok(credit) } pub fn unstake_all_coldkeys_from_hotkey_account(hotkey: &T::AccountId) { diff --git a/pallets/subtensor/tests/weights.rs b/pallets/subtensor/tests/weights.rs index 80bf15e14..c1467abda 100644 --- a/pallets/subtensor/tests/weights.rs +++ b/pallets/subtensor/tests/weights.rs @@ -611,7 +611,7 @@ fn test_set_weights_sum_larger_than_u16_max() { // Get max-upscaled unnormalized weights. let all_weights: Vec> = SubtensorModule::get_weights(netuid); - let weights_set: &Vec = &all_weights[neuron_uid as usize]; + let weights_set: &[I32F32] = &all_weights[neuron_uid as usize]; assert_eq!(weights_set[0], I32F32::from_num(u16::MAX)); assert_eq!(weights_set[1], I32F32::from_num(u16::MAX)); }); From 3aa9975c222a9789b971e13bd68301910cfd7f89 Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 11:51:43 +0400 Subject: [PATCH 06/13] fix: more clippy warnings --- pallets/subtensor/src/block_step.rs | 2 + pallets/subtensor/src/epoch.rs | 9 +- pallets/subtensor/src/math.rs | 169 +++++++++++++++----------- pallets/subtensor/src/registration.rs | 3 + pallets/subtensor/src/staking.rs | 14 +-- pallets/subtensor/tests/weights.rs | 2 +- 6 files changed, 111 insertions(+), 88 deletions(-) diff --git a/pallets/subtensor/src/block_step.rs b/pallets/subtensor/src/block_step.rs index c74611b4f..50c4fc740 100644 --- a/pallets/subtensor/src/block_step.rs +++ b/pallets/subtensor/src/block_step.rs @@ -372,6 +372,7 @@ impl Pallet { // --- 5. Adjust burn + pow // There are six cases to consider. A, B, C, D, E, F if registrations_this_interval > target_registrations_this_interval { + #[allow(clippy::comparison_chain)] 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. @@ -424,6 +425,7 @@ impl Pallet { } } else { // Not enough registrations this interval. + #[allow(clippy::comparison_chain)] if pow_registrations_this_interval > burn_registrations_this_interval { // C. There are not enough registrations this interval and most of them are pow registrations // this triggers a decrease in the burn cost diff --git a/pallets/subtensor/src/epoch.rs b/pallets/subtensor/src/epoch.rs index 4a485bf4b..6be44cf99 100644 --- a/pallets/subtensor/src/epoch.rs +++ b/pallets/subtensor/src/epoch.rs @@ -702,8 +702,8 @@ impl Pallet { pub fn get_normalized_stake(netuid: u16) -> Vec { let n: usize = Self::get_subnetwork_n(netuid) as usize; let mut stake_64: Vec = vec![I64F64::from_num(0.0); n]; - for neuron_uid in 0..n { - stake_64[neuron_uid] = I64F64::from_num(Self::get_stake_for_uid_and_subnetwork( + for (neuron_uid, neuron_stake) in stake_64.iter_mut().enumerate().take(n) { + *neuron_stake = I64F64::from_num(Self::get_stake_for_uid_and_subnetwork( netuid, neuron_uid as u16, )); @@ -716,10 +716,9 @@ impl Pallet { pub fn get_block_at_registration(netuid: u16) -> Vec { let n: usize = Self::get_subnetwork_n(netuid) as usize; let mut block_at_registration: Vec = vec![0; n]; - for neuron_uid in 0..n { + for (neuron_uid, block) in block_at_registration.iter_mut().enumerate().take(n) { if Keys::::contains_key(netuid, neuron_uid as u16) { - block_at_registration[neuron_uid] = - Self::get_neuron_block_at_registration(netuid, neuron_uid as u16); + *block = Self::get_neuron_block_at_registration(netuid, neuron_uid as u16); } } block_at_registration diff --git a/pallets/subtensor/src/math.rs b/pallets/subtensor/src/math.rs index 7ecb6ab62..dbc426b4f 100644 --- a/pallets/subtensor/src/math.rs +++ b/pallets/subtensor/src/math.rs @@ -84,7 +84,7 @@ pub fn vec_fixed_proportions_to_u16(vec: Vec) -> Vec { #[allow(dead_code)] // Max-upscale vector and convert to u16 so max_value = u16::MAX. Assumes non-negative normalized input. -pub fn vec_max_upscale_to_u16(vec: &Vec) -> Vec { +pub fn vec_max_upscale_to_u16(vec: &[I32F32]) -> Vec { let u16_max: I32F32 = I32F32::from_num(u16::MAX); let threshold: I32F32 = I32F32::from_num(32768); let max_value: Option<&I32F32> = vec.iter().max(); @@ -138,7 +138,7 @@ pub fn check_vec_max_limited(vec: &[u16], max_limit: u16) -> bool { } #[allow(dead_code)] -pub fn sum(x: &Vec) -> I32F32 { +pub fn sum(x: &[I32F32]) -> I32F32 { x.iter().sum() } @@ -146,7 +146,7 @@ pub fn sum(x: &Vec) -> I32F32 { // Sums a Vector of type that has CheckedAdd trait. // Returns None if overflow occurs during sum using T::checked_add. // Returns Some(T::default()) if input vector is empty. -pub fn checked_sum(x: &Vec) -> Option +pub fn checked_sum(x: &[T]) -> Option where T: Copy + Default + CheckedAdd, { @@ -166,7 +166,7 @@ where // Return true when vector sum is zero. #[allow(dead_code)] -pub fn is_zero(vector: &Vec) -> bool { +pub fn is_zero(vector: &[I32F32]) -> bool { let vector_sum: I32F32 = sum(vector); vector_sum == I32F32::from_num(0) } @@ -213,7 +213,7 @@ pub fn sigmoid_safe(input: I32F32, rho: I32F32, kappa: I32F32) -> I32F32 { // Returns a bool vector where an item is true if the vector item is in topk values. #[allow(dead_code)] -pub fn is_topk(vector: &Vec, k: usize) -> Vec { +pub fn is_topk(vector: &[I32F32], k: usize) -> Vec { let n: usize = vector.len(); let mut result: Vec = vec![true; n]; if n < k { @@ -229,22 +229,23 @@ pub fn is_topk(vector: &Vec, k: usize) -> Vec { // Returns a normalized (sum to 1 except 0) copy of the input vector. #[allow(dead_code)] -pub fn normalize(x: &Vec) -> Vec { +pub fn normalize(x: &[I32F32]) -> Vec { let x_sum: I32F32 = sum(x); if x_sum != I32F32::from_num(0.0_f32) { return x.iter().map(|xi| xi / x_sum).collect(); } else { - x.clone() + x.to_vec() } } // Normalizes (sum to 1 except 0) the input vector directly in-place. #[allow(dead_code)] -pub fn inplace_normalize(x: &mut Vec) { +pub fn inplace_normalize(x: &mut [I32F32]) { let x_sum: I32F32 = x.iter().sum(); if x_sum == I32F32::from_num(0.0_f32) { return; } + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { x[i] /= x_sum; } @@ -252,10 +253,11 @@ pub fn inplace_normalize(x: &mut Vec) { // Normalizes (sum to 1 except 0) the input vector directly in-place, using the sum arg. #[allow(dead_code)] -pub fn inplace_normalize_using_sum(x: &mut Vec, x_sum: I32F32) { +pub fn inplace_normalize_using_sum(x: &mut [I32F32], x_sum: I32F32) { if x_sum == I32F32::from_num(0.0_f32) { return; } + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { x[i] /= x_sum; } @@ -263,11 +265,12 @@ pub fn inplace_normalize_using_sum(x: &mut Vec, x_sum: I32F32) { // Normalizes (sum to 1 except 0) the I64F64 input vector directly in-place. #[allow(dead_code)] -pub fn inplace_normalize_64(x: &mut Vec) { +pub fn inplace_normalize_64(x: &mut [I64F64]) { let x_sum: I64F64 = x.iter().sum(); if x_sum == I64F64::from_num(0) { return; } + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { x[i] /= x_sum; } @@ -275,7 +278,7 @@ pub fn inplace_normalize_64(x: &mut Vec) { /// Returns x / y for input vectors x and y, if y == 0 return 0. #[allow(dead_code)] -pub fn vecdiv(x: &Vec, y: &Vec) -> Vec { +pub fn vecdiv(x: &[I32F32], y: &[I32F32]) -> Vec { assert_eq!(x.len(), y.len()); let n = x.len(); let mut result: Vec = vec![I32F32::from_num(0); n]; @@ -289,7 +292,8 @@ pub fn vecdiv(x: &Vec, y: &Vec) -> Vec { // Normalizes (sum to 1 except 0) each row (dim=0) of a matrix in-place. #[allow(dead_code)] -pub fn inplace_row_normalize(x: &mut Vec>) { +pub fn inplace_row_normalize(x: &mut [Vec]) { + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { let row_sum: I32F32 = x[i].iter().sum(); if row_sum > I32F32::from_num(0.0_f32) { @@ -301,7 +305,7 @@ pub fn inplace_row_normalize(x: &mut Vec>) { // Normalizes (sum to 1 except 0) each row (dim=0) of a sparse matrix in-place. #[allow(dead_code)] -pub fn inplace_row_normalize_sparse(sparse_matrix: &mut Vec>) { +pub fn inplace_row_normalize_sparse(sparse_matrix: &mut [Vec<(u16, I32F32)>]) { for sparse_row in sparse_matrix.iter_mut() { let row_sum: I32F32 = sparse_row.iter().map(|(_j, value)| *value).sum(); if row_sum > I32F32::from_num(0.0) { @@ -314,7 +318,7 @@ pub fn inplace_row_normalize_sparse(sparse_matrix: &mut Vec>) // Sum across each row (dim=0) of a matrix. #[allow(dead_code)] -pub fn row_sum(x: &Vec>) -> Vec { +pub fn row_sum(x: &[Vec]) -> Vec { if x.is_empty() { return vec![]; } @@ -333,7 +337,7 @@ pub fn row_sum(x: &Vec>) -> Vec { // Sum across each row (dim=0) of a sparse matrix. #[allow(dead_code)] -pub fn row_sum_sparse(sparse_matrix: &Vec>) -> Vec { +pub fn row_sum_sparse(sparse_matrix: &[Vec<(u16, I32F32)>]) -> Vec { let rows = sparse_matrix.len(); let mut result: Vec = vec![I32F32::from_num(0); rows]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -346,7 +350,7 @@ pub fn row_sum_sparse(sparse_matrix: &Vec>) -> Vec { // Sum across each column (dim=1) of a matrix. #[allow(dead_code)] -pub fn col_sum(x: &Vec>) -> Vec { +pub fn col_sum(x: &[Vec]) -> Vec { if x.is_empty() { return vec![]; } @@ -355,8 +359,10 @@ pub fn col_sum(x: &Vec>) -> Vec { } let cols = x[0].len(); let mut result: Vec = vec![I32F32::from_num(0); cols]; + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { assert_eq!(x[i].len(), cols); + #[allow(clippy::needless_range_loop)] for j in 0..cols { result[j] += x[i][j]; } @@ -366,7 +372,7 @@ pub fn col_sum(x: &Vec>) -> Vec { // Sum across each column (dim=1) of a sparse matrix. #[allow(dead_code)] -pub fn col_sum_sparse(sparse_matrix: &Vec>, columns: u16) -> Vec { +pub fn col_sum_sparse(sparse_matrix: &[Vec<(u16, I32F32)>], columns: u16) -> Vec { let mut result: Vec = vec![I32F32::from_num(0); columns as usize]; for sparse_row in sparse_matrix.iter() { for (j, value) in sparse_row.iter() { @@ -378,7 +384,7 @@ pub fn col_sum_sparse(sparse_matrix: &Vec>, columns: u16) -> // Normalizes (sum to 1 except 0) each column (dim=1) of a sparse matrix in-place. #[allow(dead_code)] -pub fn inplace_col_normalize_sparse(sparse_matrix: &mut Vec>, columns: u16) { +pub fn inplace_col_normalize_sparse(sparse_matrix: &mut [Vec<(u16, I32F32)>], columns: u16) { let mut col_sum: Vec = vec![I32F32::from_num(0.0); columns as usize]; // assume square matrix, rows=cols for sparse_row in sparse_matrix.iter() { for (j, value) in sparse_row.iter() { @@ -397,7 +403,7 @@ pub fn inplace_col_normalize_sparse(sparse_matrix: &mut Vec>, // Normalizes (sum to 1 except 0) each column (dim=1) of a matrix in-place. #[allow(dead_code)] -pub fn inplace_col_normalize(x: &mut Vec>) { +pub fn inplace_col_normalize(x: &mut [Vec]) { if x.is_empty() { return; } @@ -406,16 +412,20 @@ pub fn inplace_col_normalize(x: &mut Vec>) { } let cols = x[0].len(); let mut col_sum: Vec = vec![I32F32::from_num(0.0); cols]; + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { assert_eq!(x[i].len(), cols); + #[allow(clippy::needless_range_loop)] for j in 0..cols { col_sum[j] += x[i][j]; } } + #[allow(clippy::needless_range_loop)] for j in 0..cols { if col_sum[j] == I32F32::from_num(0.0_f32) { continue; } + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { x[i][j] /= col_sum[j]; } @@ -424,7 +434,7 @@ pub fn inplace_col_normalize(x: &mut Vec>) { // Max-upscale each column (dim=1) of a sparse matrix in-place. #[allow(dead_code)] -pub fn inplace_col_max_upscale_sparse(sparse_matrix: &mut Vec>, columns: u16) { +pub fn inplace_col_max_upscale_sparse(sparse_matrix: &mut [Vec<(u16, I32F32)>], columns: u16) { let mut col_max: Vec = vec![I32F32::from_num(0.0); columns as usize]; // assume square matrix, rows=cols for sparse_row in sparse_matrix.iter() { for (j, value) in sparse_row.iter() { @@ -445,7 +455,7 @@ pub fn inplace_col_max_upscale_sparse(sparse_matrix: &mut Vec // Max-upscale each column (dim=1) of a matrix in-place. #[allow(dead_code)] -pub fn inplace_col_max_upscale(x: &mut Vec>) { +pub fn inplace_col_max_upscale(x: &mut [Vec]) { if x.is_empty() { return; } @@ -454,6 +464,8 @@ pub fn inplace_col_max_upscale(x: &mut Vec>) { } let cols = x[0].len(); let mut col_max: Vec = vec![I32F32::from_num(0.0); cols]; + + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { assert_eq!(x[i].len(), cols); for j in 0..cols { @@ -462,10 +474,14 @@ pub fn inplace_col_max_upscale(x: &mut Vec>) { } } } + + #[allow(clippy::needless_range_loop)] for j in 0..cols { if col_max[j] == I32F32::from_num(0.0_f32) { continue; } + + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { x[i][j] /= col_max[j]; } @@ -474,7 +490,7 @@ pub fn inplace_col_max_upscale(x: &mut Vec>) { // Apply mask to vector, mask=true will mask out, i.e. set to 0. #[allow(dead_code)] -pub fn inplace_mask_vector(mask: &Vec, vector: &mut Vec) { +pub fn inplace_mask_vector(mask: &[bool], vector: &mut [I32F32]) { if mask.is_empty() { return; } @@ -489,7 +505,7 @@ pub fn inplace_mask_vector(mask: &Vec, vector: &mut Vec) { // Apply mask to matrix, mask=true will mask out, i.e. set to 0. #[allow(dead_code)] -pub fn inplace_mask_matrix(mask: &Vec>, matrix: &mut Vec>) { +pub fn inplace_mask_matrix(mask: &[Vec], matrix: &mut [Vec]) { if mask.is_empty() { return; } @@ -509,7 +525,7 @@ pub fn inplace_mask_matrix(mask: &Vec>, matrix: &mut Vec>) // Apply row mask to matrix, mask=true will mask out, i.e. set to 0. #[allow(dead_code)] -pub fn inplace_mask_rows(mask: &Vec, matrix: &mut Vec>) { +pub fn inplace_mask_rows(mask: &[bool], matrix: &mut [Vec]) { let rows = matrix.len(); if rows == 0 { return; @@ -526,7 +542,7 @@ pub fn inplace_mask_rows(mask: &Vec, matrix: &mut Vec>) { // Mask out the diagonal of the input matrix in-place. #[allow(dead_code)] -pub fn inplace_mask_diag(matrix: &mut Vec>) { +pub fn inplace_mask_diag(matrix: &mut [Vec]) { if matrix.is_empty() { return; } @@ -535,6 +551,7 @@ pub fn inplace_mask_diag(matrix: &mut Vec>) { } assert_eq!(matrix.len(), matrix[0].len()); let zero: I32F32 = I32F32::from_num(0.0); + #[allow(clippy::needless_range_loop)] for i in 0..matrix.len() { matrix[i][i] = zero; } @@ -543,8 +560,8 @@ pub fn inplace_mask_diag(matrix: &mut Vec>) { // Return a new sparse matrix that replaces masked rows with an empty vector placeholder. #[allow(dead_code)] pub fn mask_rows_sparse( - mask: &Vec, - sparse_matrix: &Vec>, + mask: &[bool], + sparse_matrix: &[Vec<(u16, I32F32)>], ) -> Vec> { let n: usize = sparse_matrix.len(); assert_eq!(n, mask.len()); @@ -559,7 +576,7 @@ pub fn mask_rows_sparse( // Return a new sparse matrix with a masked out diagonal of input sparse matrix. #[allow(dead_code)] -pub fn mask_diag_sparse(sparse_matrix: &Vec>) -> Vec> { +pub fn mask_diag_sparse(sparse_matrix: &[Vec<(u16, I32F32)>]) -> Vec> { let n: usize = sparse_matrix.len(); let mut result: Vec> = vec![vec![]; n]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -575,9 +592,9 @@ pub fn mask_diag_sparse(sparse_matrix: &Vec>) -> Vec>, - first_vector: &Vec, - second_vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + first_vector: &[u64], + second_vector: &[u64], mask_fn: &dyn Fn(u64, u64) -> bool, ) -> Vec> { let n: usize = sparse_matrix.len(); @@ -594,7 +611,7 @@ pub fn vec_mask_sparse_matrix( // Row-wise matrix-vector hadamard product. #[allow(dead_code)] -pub fn row_hadamard(matrix: &Vec>, vector: &Vec) -> Vec> { +pub fn row_hadamard(matrix: &[Vec], vector: &[I32F32]) -> Vec> { if matrix.is_empty() { return vec![vec![]]; } @@ -614,10 +631,10 @@ pub fn row_hadamard(matrix: &Vec>, vector: &Vec) -> Vec>, - vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + vector: &[I32F32], ) -> Vec> { - let mut result: Vec> = sparse_matrix.clone(); + let mut result: Vec> = sparse_matrix.to_vec(); for (i, sparse_row) in result.iter_mut().enumerate() { for (_j, value) in sparse_row.iter_mut() { *value *= vector[i]; @@ -628,7 +645,7 @@ pub fn row_hadamard_sparse( // Row-wise matrix-vector product, column-wise sum: result_j = SUM(i) vector_i * matrix_ij. #[allow(dead_code)] -pub fn matmul(matrix: &Vec>, vector: &Vec) -> Vec { +pub fn matmul(matrix: &[Vec], vector: &[I32F32]) -> Vec { if matrix.is_empty() { return vec![]; } @@ -637,7 +654,9 @@ pub fn matmul(matrix: &Vec>, vector: &Vec) -> Vec { } assert!(matrix.len() == vector.len()); let mut result: Vec = vec![I32F32::from_num(0.0); matrix[0].len()]; + #[allow(clippy::needless_range_loop)] for i in 0..matrix.len() { + #[allow(clippy::needless_range_loop)] for j in 0..matrix[i].len() { // Compute ranks: r_j = SUM(i) w_ij * s_i // Compute trust scores: t_j = SUM(i) w_ij * s_i @@ -650,7 +669,7 @@ pub fn matmul(matrix: &Vec>, vector: &Vec) -> Vec { // Row-wise matrix-vector product, column-wise sum: result_j = SUM(i) vector_i * matrix_ij. #[allow(dead_code)] -pub fn matmul_64(matrix: &Vec>, vector: &Vec) -> Vec { +pub fn matmul_64(matrix: &[Vec], vector: &[I64F64]) -> Vec { if matrix.is_empty() { return vec![]; } @@ -659,7 +678,9 @@ pub fn matmul_64(matrix: &Vec>, vector: &Vec) -> Vec } assert!(matrix.len() == vector.len()); let mut result: Vec = vec![I64F64::from_num(0.0); matrix[0].len()]; + #[allow(clippy::needless_range_loop)] for i in 0..matrix.len() { + #[allow(clippy::needless_range_loop)] for j in 0..matrix[i].len() { // Compute ranks: r_j = SUM(i) w_ij * s_i // Compute trust scores: t_j = SUM(i) w_ij * s_i @@ -672,7 +693,7 @@ pub fn matmul_64(matrix: &Vec>, vector: &Vec) -> Vec // Column-wise matrix-vector product, row-wise sum: result_i = SUM(j) vector_j * matrix_ij. #[allow(dead_code)] -pub fn matmul_transpose(matrix: &Vec>, vector: &Vec) -> Vec { +pub fn matmul_transpose(matrix: &[Vec], vector: &[I32F32]) -> Vec { if matrix.is_empty() { return vec![]; } @@ -681,7 +702,9 @@ pub fn matmul_transpose(matrix: &Vec>, vector: &Vec) -> Vec< } assert!(matrix[0].len() == vector.len()); let mut result: Vec = vec![I32F32::from_num(0.0); matrix.len()]; + #[allow(clippy::needless_range_loop)] for i in 0..matrix.len() { + #[allow(clippy::needless_range_loop)] for j in 0..matrix[i].len() { // Compute dividends: d_j = SUM(i) b_ji * inc_i // result_j = SUM(i) vector_i * matrix_ji @@ -695,8 +718,8 @@ pub fn matmul_transpose(matrix: &Vec>, vector: &Vec) -> Vec< // Row-wise sparse_matrix-vector product, column-wise sum: result_j = SUM(i) vector_i * matrix_ij. #[allow(dead_code)] pub fn matmul_sparse( - sparse_matrix: &Vec>, - vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + vector: &[I32F32], columns: u16, ) -> Vec { let mut result: Vec = vec![I32F32::from_num(0.0); columns as usize]; @@ -714,8 +737,8 @@ pub fn matmul_sparse( // Column-wise sparse_matrix-vector product, row-wise sum: result_i = SUM(j) vector_j * matrix_ij. #[allow(dead_code)] pub fn matmul_transpose_sparse( - sparse_matrix: &Vec>, - vector: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + vector: &[I32F32], ) -> Vec { let mut result: Vec = vec![I32F32::from_num(0.0); sparse_matrix.len()]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -731,7 +754,8 @@ pub fn matmul_transpose_sparse( // Set inplace matrix values above column threshold to threshold value. #[allow(dead_code)] -pub fn inplace_col_clip(x: &mut Vec>, col_threshold: &Vec) { +pub fn inplace_col_clip(x: &mut [Vec], col_threshold: &[I32F32]) { + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { for j in 0..x[i].len() { if x[i][j] > col_threshold[j] { @@ -744,8 +768,8 @@ pub fn inplace_col_clip(x: &mut Vec>, col_threshold: &Vec) { // Return sparse matrix with values above column threshold set to threshold value. #[allow(dead_code)] pub fn col_clip_sparse( - sparse_matrix: &Vec>, - col_threshold: &Vec, + sparse_matrix: &[Vec<(u16, I32F32)>], + col_threshold: &[I32F32], ) -> Vec> { let mut result: Vec> = vec![vec![]; sparse_matrix.len()]; for (i, sparse_row) in sparse_matrix.iter().enumerate() { @@ -765,7 +789,7 @@ pub fn col_clip_sparse( // Set matrix values below threshold to lower, and equal-above to upper. #[allow(dead_code)] pub fn clip( - x: &Vec>, + x: &[Vec], threshold: I32F32, upper: I32F32, lower: I32F32, @@ -787,7 +811,8 @@ pub fn clip( // Set inplace matrix values below threshold to lower, and equal-above to upper. #[allow(dead_code)] -pub fn inplace_clip(x: &mut Vec>, threshold: I32F32, upper: I32F32, lower: I32F32) { +pub fn inplace_clip(x: &mut [Vec], threshold: I32F32, upper: I32F32, lower: I32F32) { + #[allow(clippy::needless_range_loop)] for i in 0..x.len() { for j in 0..x[i].len() { if x[i][j] >= threshold { @@ -803,7 +828,7 @@ pub fn inplace_clip(x: &mut Vec>, threshold: I32F32, upper: I32F32, // Does not add missing elements (0 value assumed) when lower!=0. #[allow(dead_code)] pub fn clip_sparse( - sparse_matrix: &Vec>, + sparse_matrix: &[Vec<(u16, I32F32)>], threshold: I32F32, upper: I32F32, lower: I32F32, @@ -826,13 +851,13 @@ pub fn clip_sparse( // Assumes relatively random score order for efficiency, typically less than O(nlogn) complexity. // // # Args: -// * 'stake': ( &Vec ): +// * 'stake': ( &[I32F32] ): // - stake, assumed to be normalized. // -// * 'score': ( &Vec ): +// * 'score': ( &[I32F32] ): // - score for which median is sought, 0 <= score <= 1 // -// * 'partition_idx' ( &Vec ): +// * 'partition_idx' ( &[usize] ): // - indices as input partition // // * 'minority' ( I32F32 ): @@ -850,9 +875,9 @@ pub fn clip_sparse( // #[allow(dead_code)] pub fn weighted_median( - stake: &Vec, - score: &Vec, - partition_idx: &Vec, + stake: &[I32F32], + score: &[I32F32], + partition_idx: &[usize], minority: I32F32, partition_lo: I32F32, partition_hi: I32F32, @@ -910,14 +935,16 @@ pub fn weighted_median( /// Column-wise weighted median, e.g. stake-weighted median scores per server (column) over all validators (rows). #[allow(dead_code)] pub fn weighted_median_col( - stake: &Vec, - score: &Vec>, + stake: &[I32F32], + score: &[Vec], majority: I32F32, ) -> Vec { let rows = stake.len(); let columns = score[0].len(); let zero: I32F32 = I32F32::from_num(0); let mut median: Vec = vec![zero; columns]; + + #[allow(clippy::needless_range_loop)] for c in 0..columns { let mut use_stake: Vec = vec![]; let mut use_score: Vec = vec![]; @@ -935,7 +962,7 @@ pub fn weighted_median_col( median[c] = weighted_median( &use_stake, &use_score, - &(0..use_stake.len()).collect(), + (0..use_stake.len()).collect::>().as_slice(), minority, zero, stake_sum, @@ -948,8 +975,8 @@ pub fn weighted_median_col( /// Column-wise weighted median, e.g. stake-weighted median scores per server (column) over all validators (rows). #[allow(dead_code)] pub fn weighted_median_col_sparse( - stake: &Vec, - score: &Vec>, + stake: &[I32F32], + score: &[Vec<(u16, I32F32)>], columns: u16, majority: I32F32, ) -> Vec { @@ -987,7 +1014,7 @@ pub fn weighted_median_col_sparse( // Element-wise product of two matrices. #[allow(dead_code)] -pub fn hadamard(mat1: &Vec>, mat2: &Vec>) -> Vec> { +pub fn hadamard(mat1: &[Vec], mat2: &[Vec]) -> Vec> { assert!(mat1.len() == mat2.len()); if mat1.is_empty() { return vec![vec![]; 1]; @@ -1008,8 +1035,8 @@ pub fn hadamard(mat1: &Vec>, mat2: &Vec>) -> Vec>, - mat2: &Vec>, + mat1: &[Vec<(u16, I32F32)>], + mat2: &[Vec<(u16, I32F32)>], columns: u16, ) -> Vec> { assert!(mat1.len() == mat2.len()); @@ -1039,7 +1066,7 @@ pub fn hadamard_sparse( // `alpha` is the EMA coefficient, how much to add of the new observation, typically small, // higher alpha discounts older observations faster. #[allow(dead_code)] -pub fn mat_ema(new: &Vec>, old: &Vec>, alpha: I32F32) -> Vec> { +pub fn mat_ema(new: &[Vec], old: &[Vec], alpha: I32F32) -> Vec> { if new.is_empty() { return vec![vec![]; 1]; } @@ -1063,8 +1090,8 @@ pub fn mat_ema(new: &Vec>, old: &Vec>, alpha: I32F32) -> // higher alpha discounts older observations faster. #[allow(dead_code)] pub fn mat_ema_sparse( - new: &Vec>, - old: &Vec>, + new: &[Vec<(u16, I32F32)>], + old: &[Vec<(u16, I32F32)>], alpha: I32F32, ) -> Vec> { assert!(new.len() == old.len()); @@ -1091,7 +1118,7 @@ pub fn mat_ema_sparse( // Return sparse matrix only with elements >= threshold of an input sparse matrix. #[allow(dead_code)] -pub fn sparse_threshold(w: &Vec>, threshold: I32F32) -> Vec> { +pub fn sparse_threshold(w: &[Vec<(u16, I32F32)>], threshold: I32F32) -> Vec> { let mut sparse_threshold_result: Vec> = vec![vec![]; w.len()]; for (uid_i, weights_i) in w.iter().enumerate() { for (uid_j, weight_ij) in weights_i.iter() { @@ -1117,14 +1144,14 @@ mod tests { assert!(I64F64::abs(a - b) <= epsilon, "a({:?}) != b({:?})", a, b); } - fn assert_vec_compare(va: &Vec, vb: &Vec, epsilon: I32F32) { + fn assert_vec_compare(va: &[I32F32], vb: &[I32F32], epsilon: I32F32) { assert!(va.len() == vb.len()); for i in 0..va.len() { assert_float_compare(va[i], vb[i], epsilon); } } - fn assert_vec_compare_64(va: &Vec, vb: &Vec, epsilon: I64F64) { + fn assert_vec_compare_64(va: &[I64F64], vb: &[I64F64], epsilon: I64F64) { assert!(va.len() == vb.len()); for i in 0..va.len() { assert_float_compare_64(va[i], vb[i], epsilon); @@ -1138,7 +1165,7 @@ mod tests { } } - fn assert_mat_compare(ma: &Vec>, mb: &Vec>, epsilon: I32F32) { + fn assert_mat_compare(ma: &[Vec], mb: &[Vec], epsilon: I32F32) { assert!(ma.len() == mb.len()); for row in 0..ma.len() { assert!(ma[row].len() == mb[row].len()); @@ -1149,8 +1176,8 @@ mod tests { } fn assert_sparse_mat_compare( - ma: &Vec>, - mb: &Vec>, + ma: &[Vec<(u16, I32F32)>], + mb: &[Vec<(u16, I32F32)>], epsilon: I32F32, ) { assert!(ma.len() == mb.len()); diff --git a/pallets/subtensor/src/registration.rs b/pallets/subtensor/src/registration.rs index 6533a23bc..b75250536 100644 --- a/pallets/subtensor/src/registration.rs +++ b/pallets/subtensor/src/registration.rs @@ -438,6 +438,9 @@ impl Pallet { let block_at_registration: u64 = Self::get_neuron_block_at_registration(netuid, neuron_uid_i); + // Too dangerous to remove this comparison change while enabling clippy. allow it for + // now. + #[allow(clippy::comparison_chain)] if min_score == pruning_score { if current_block - block_at_registration < immunity_period { //neuron is in immunity period diff --git a/pallets/subtensor/src/staking.rs b/pallets/subtensor/src/staking.rs index 1278e71f9..15caa2467 100644 --- a/pallets/subtensor/src/staking.rs +++ b/pallets/subtensor/src/staking.rs @@ -612,11 +612,7 @@ impl Pallet { coldkey: &T::AccountId, amount: <::Currency as fungible::Inspect<::AccountId>>::Balance, ) -> Result { - let amount_u64: u64 = amount - .try_into() - .map_err(|_| Error::::CouldNotConvertToU64)?; - - if amount_u64 == 0 { + if amount == 0 { return Ok(0); } @@ -630,15 +626,11 @@ impl Pallet { .map_err(|_| Error::::BalanceWithdrawalError)? .peek(); - let credit_u64: u64 = credit - .try_into() - .map_err(|_| Error::::CouldNotConvertToU64)?; - - if credit_u64 == 0 { + if credit == 0 { return Err(Error::::BalanceWithdrawalError.into()); } - Ok(credit_u64) + Ok(credit) } pub fn unstake_all_coldkeys_from_hotkey_account(hotkey: &T::AccountId) { diff --git a/pallets/subtensor/tests/weights.rs b/pallets/subtensor/tests/weights.rs index 80bf15e14..c1467abda 100644 --- a/pallets/subtensor/tests/weights.rs +++ b/pallets/subtensor/tests/weights.rs @@ -611,7 +611,7 @@ fn test_set_weights_sum_larger_than_u16_max() { // Get max-upscaled unnormalized weights. let all_weights: Vec> = SubtensorModule::get_weights(netuid); - let weights_set: &Vec = &all_weights[neuron_uid as usize]; + let weights_set: &[I32F32] = &all_weights[neuron_uid as usize]; assert_eq!(weights_set[0], I32F32::from_num(u16::MAX)); assert_eq!(weights_set[1], I32F32::from_num(u16::MAX)); }); From fffd2ed44284c7a8e4c4e4a4651015e378e61e6a Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 12:11:54 +0400 Subject: [PATCH 07/13] fix: more clippy lints --- pallets/collective/src/tests.rs | 103 +++------ pallets/subtensor/src/benchmarks.rs | 31 ++- pallets/subtensor/src/math.rs | 316 +++++++++++++-------------- pallets/subtensor/tests/epoch.rs | 4 +- pallets/subtensor/tests/migration.rs | 2 +- pallets/subtensor/tests/root.rs | 6 +- 6 files changed, 200 insertions(+), 262 deletions(-) diff --git a/pallets/collective/src/tests.rs b/pallets/collective/src/tests.rs index 032d87c8e..0505d86f0 100644 --- a/pallets/collective/src/tests.rs +++ b/pallets/collective/src/tests.rs @@ -292,9 +292,7 @@ fn close_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); @@ -365,9 +363,7 @@ fn proposal_weight_limit_works_on_approve() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); // With 1's prime vote, this should pass @@ -408,9 +404,7 @@ fn proposal_weight_limit_ignored_on_disapprove() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); // No votes, this proposal wont pass System::set_block_number(4); @@ -442,9 +436,7 @@ fn close_with_prime_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); @@ -504,9 +496,7 @@ fn close_with_voting_prime_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); @@ -570,9 +560,7 @@ fn close_with_no_prime_but_majority_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(CollectiveMajority::vote( RuntimeOrigin::signed(1), @@ -666,9 +654,7 @@ fn removal_of_old_voters_votes_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); @@ -701,9 +687,7 @@ fn removal_of_old_voters_votes_works() { RuntimeOrigin::signed(2), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, false)); @@ -742,9 +726,7 @@ fn removal_of_old_voters_votes_works_with_set_members() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); @@ -782,9 +764,7 @@ fn removal_of_old_voters_votes_works_with_set_members() { RuntimeOrigin::signed(2), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(3), hash, 1, false)); @@ -828,9 +808,7 @@ fn propose_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_eq!(*Collective::proposals(), vec![hash]); assert_eq!(Collective::proposal_of(hash), Some(proposal)); @@ -870,7 +848,6 @@ fn limit_active_proposals() { Box::new(proposal.clone()), proposal_len, TryInto::>::try_into(3u64) - .ok() .expect("convert u64 to block number.") )); } @@ -882,7 +859,6 @@ fn limit_active_proposals() { Box::new(proposal.clone()), proposal_len, TryInto::>::try_into(3u64) - .ok() .expect("convert u64 to block number.") ), Error::::TooManyProposals @@ -903,9 +879,7 @@ fn correct_validate_and_get_proposal() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), length, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); let hash = BlakeTwo256::hash_of(&proposal); @@ -949,7 +923,6 @@ fn motions_ignoring_non_collective_proposals_works() { Box::new(proposal.clone()), proposal_len, TryInto::>::try_into(3u64) - .ok() .expect("convert u64 to block number.") ), Error::::NotMember @@ -967,9 +940,7 @@ fn motions_ignoring_non_collective_votes_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_noop!( Collective::vote(RuntimeOrigin::signed(42), hash, 0, true), @@ -989,9 +960,7 @@ fn motions_ignoring_bad_index_collective_vote_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_noop!( Collective::vote(RuntimeOrigin::signed(2), hash, 1, true), @@ -1011,9 +980,7 @@ fn motions_vote_after_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); // Initially there a no votes when the motion is proposed. assert_eq!( @@ -1100,9 +1067,7 @@ fn motions_all_first_vote_free_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_eq!( Collective::voting(hash), @@ -1176,9 +1141,7 @@ fn motions_reproposing_disapproved_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, false)); @@ -1196,9 +1159,7 @@ fn motions_reproposing_disapproved_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_eq!(*Collective::proposals(), vec![hash]); }); @@ -1220,9 +1181,7 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); @@ -1278,9 +1237,7 @@ fn motions_approval_with_enough_votes_and_lower_voting_threshold_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 1, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 1, true)); @@ -1353,9 +1310,7 @@ fn motions_disapproval_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, false)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, false)); @@ -1414,9 +1369,7 @@ fn motions_approval_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); assert_ok!(Collective::vote(RuntimeOrigin::signed(2), hash, 0, true)); @@ -1479,9 +1432,7 @@ fn motion_with_no_votes_closes_with_disapproval() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); assert_eq!( System::events()[0], @@ -1549,9 +1500,7 @@ fn close_disapprove_does_not_care_about_weight_or_len() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); // First we make the proposal succeed assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); @@ -1595,9 +1544,7 @@ fn disapprove_proposal_works() { RuntimeOrigin::signed(1), Box::new(proposal.clone()), proposal_len, - TryInto::>::try_into(3u64) - .ok() - .expect("convert u64 to block number.") + TryInto::>::try_into(3u64).expect("convert u64 to block number.") )); // Proposal would normally succeed assert_ok!(Collective::vote(RuntimeOrigin::signed(1), hash, 0, true)); diff --git a/pallets/subtensor/src/benchmarks.rs b/pallets/subtensor/src/benchmarks.rs index 87b86dc23..514e98944 100644 --- a/pallets/subtensor/src/benchmarks.rs +++ b/pallets/subtensor/src/benchmarks.rs @@ -29,7 +29,7 @@ benchmarks! { let (nonce, work): (u64, Vec) = Subtensor::::create_work_for_block_number( netuid, block_number, start_nonce, &hotkey); Subtensor::::init_new_network(netuid, tempo); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true); + Subtensor::::set_network_registration_allowed( netuid, true); let block_number: u64 = Subtensor::::get_current_block_as_u64(); let coldkey: T::AccountId = account("Test", 0, seed); @@ -46,9 +46,9 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_max_allowed_uids( netuid, 4096 ); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true ); - Subtensor::::set_max_registrations_per_block( netuid.try_into().unwrap(), 4096 ); - Subtensor::::set_target_registrations_per_interval( netuid.try_into().unwrap(), 4096 ); + Subtensor::::set_network_registration_allowed( netuid, true ); + Subtensor::::set_max_registrations_per_block( netuid, 4096 ); + Subtensor::::set_target_registrations_per_interval( netuid, 4096 ); let mut seed : u32 = 1; let mut dests: Vec = vec![]; @@ -89,7 +89,7 @@ benchmarks! { Subtensor::::set_burn(netuid, 1); Subtensor::::set_max_allowed_uids( netuid, 4096 ); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true); + Subtensor::::set_network_registration_allowed( netuid, true); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); let coldkey: T::AccountId = account("Test", 0, seed); @@ -113,7 +113,7 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_burn(netuid, 1); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true ); + Subtensor::::set_network_registration_allowed( netuid, true ); Subtensor::::set_max_allowed_uids( netuid, 4096 ); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); @@ -122,7 +122,7 @@ benchmarks! { let hotkey: T::AccountId = account("Alice", 0, seed); let amount: u64 = 1; - let amount_to_be_staked = 1000000000u64.into(); + let amount_to_be_staked = 1000000000u64; Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())); @@ -141,7 +141,7 @@ benchmarks! { Subtensor::::increase_total_stake(1_000_000_000_000); Subtensor::::init_new_network(netuid, tempo); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true ); + Subtensor::::set_network_registration_allowed( netuid, true ); Subtensor::::set_max_allowed_uids( netuid, 4096 ); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); @@ -158,8 +158,7 @@ benchmarks! { // Stake 10% of our current total staked TAO let u64_staked_amt = 100_000_000_000; - let amount_to_be_staked = u64_staked_amt.into(); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), u64_staked_amt); assert_ok!( Subtensor::::add_stake(RawOrigin::Signed( coldkey.clone() ).into() , hotkey.clone(), u64_staked_amt)); @@ -270,7 +269,7 @@ benchmarks! { Subtensor::::init_new_network(netuid, tempo); Subtensor::::set_burn(netuid, 1); - Subtensor::::set_network_registration_allowed( netuid.try_into().unwrap(), true); + Subtensor::::set_network_registration_allowed( netuid, true); Subtensor::::set_max_allowed_uids( netuid, 4096 ); assert_eq!(Subtensor::::get_max_allowed_uids(netuid), 4096); @@ -279,7 +278,7 @@ benchmarks! { let hotkey: T::AccountId = account("Alice", 0, seed); let amount: u64 = 1; - let amount_to_be_staked = 100_000_000_000_000u64.into(); + let amount_to_be_staked = 100_000_000_000_000u64; Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::do_burned_registration(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey.clone())); @@ -293,7 +292,7 @@ benchmarks! { Subtensor::::set_network_rate_limit(1); let amount: u64 = 1; - let amount_to_be_staked = 100_000_000_000_000u64.into(); + let amount_to_be_staked = 100_000_000_000_000u64; Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); }: register_network(RawOrigin::Signed(coldkey)) @@ -305,7 +304,7 @@ benchmarks! { Subtensor::::set_network_rate_limit(0); let amount: u64 = 1; - let amount_to_be_staked = 100_000_000_000_000u64.into(); + let amount_to_be_staked = 100_000_000_000_000u64; Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), amount_to_be_staked); assert_ok!(Subtensor::::register_network(RawOrigin::Signed(coldkey.clone()).into())); }: dissolve_network(RawOrigin::Signed(coldkey), 1) @@ -323,7 +322,7 @@ benchmarks! { Subtensor::::set_target_registrations_per_interval(netuid, 256); Subtensor::::set_max_registrations_per_block(netuid, 256); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 10_000_000_000u64.into()); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 10_000_000_000u64); assert_ok!(Subtensor::::burned_register(RawOrigin::Signed(coldkey.clone()).into(), netuid, old_hotkey.clone())); assert_ok!(Subtensor::::become_delegate(RawOrigin::Signed(coldkey.clone()).into(), old_hotkey.clone())); @@ -332,7 +331,7 @@ benchmarks! { let coldkey: T::AccountId = account("Axon", 0, i); let hotkey: T::AccountId = account("Hotkey", 0, i); - Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 10_000_000_000u64.into()); + Subtensor::::add_balance_to_coldkey_account(&coldkey.clone(), 10_000_000_000u64); assert_ok!(Subtensor::::burned_register(RawOrigin::Signed(coldkey.clone()).into(), netuid, hotkey)); assert_ok!(Subtensor::::add_stake(RawOrigin::Signed(coldkey).into(), old_hotkey.clone(), 1_000_000_000)); } diff --git a/pallets/subtensor/src/math.rs b/pallets/subtensor/src/math.rs index dbc426b4f..be6decb25 100644 --- a/pallets/subtensor/src/math.rs +++ b/pallets/subtensor/src/math.rs @@ -1190,43 +1190,41 @@ mod tests { } } - fn vec_to_fixed(vector: &Vec) -> Vec { + fn vec_to_fixed(vector: &[f32]) -> Vec { vector.iter().map(|x| I32F32::from_num(*x)).collect() } #[test] fn test_vec_max_upscale_to_u16() { - let vector: Vec = vec_to_fixed(&vec![]); + let vector: Vec = vec_to_fixed(&[]); let target: Vec = vec![]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0.]); + let vector: Vec = vec_to_fixed(&[0.]); let target: Vec = vec![0]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 0.]); + let vector: Vec = vec_to_fixed(&[0., 0.]); let target: Vec = vec![0, 0]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 1.]); + let vector: Vec = vec_to_fixed(&[0., 1.]); let target: Vec = vec![0, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 0.000000001]); + let vector: Vec = vec_to_fixed(&[0., 0.000000001]); let target: Vec = vec![0, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 0.000016, 1.]); + let vector: Vec = vec_to_fixed(&[0., 0.000016, 1.]); let target: Vec = vec![0, 1, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0.000000001, 0.000000001]); + let vector: Vec = vec_to_fixed(&[0.000000001, 0.000000001]); let target: Vec = vec![65535, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![ - 0.000001, 0.000006, 0.000007, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4, - ]); + let vector: Vec = vec_to_fixed(&[0.000001, 0.000006, 0.000007, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4]); let target: Vec = vec![0, 1, 1, 16, 164, 1638, 16384, 32768, 49151, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); @@ -1250,15 +1248,15 @@ mod tests { let target: Vec = vec![65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 1., 65535.]); + let vector: Vec = vec_to_fixed(&[0., 1., 65535.]); let target: Vec = vec![0, 1, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 0.5, 1., 1.5, 2., 32768.]); + let vector: Vec = vec_to_fixed(&[0., 0.5, 1., 1.5, 2., 32768.]); let target: Vec = vec![0, 1, 2, 3, 4, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 0.5, 1., 1.5, 2., 32768., 32769.]); + let vector: Vec = vec_to_fixed(&[0., 0.5, 1., 1.5, 2., 32768., 32769.]); let target: Vec = vec![0, 1, 2, 3, 4, 65533, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); @@ -1464,7 +1462,7 @@ mod tests { } // Reshape vector to matrix with specified number of rows, cast to I32F32. - fn vec_to_mat_fixed(vector: &Vec, rows: usize, transpose: bool) -> Vec> { + fn vec_to_mat_fixed(vector: &[f32], rows: usize, transpose: bool) -> Vec> { assert!( vector.len() % rows == 0, "Vector of len {:?} cannot reshape to {rows} rows.", @@ -1620,29 +1618,25 @@ mod tests { .iter() .map(|t: &I32F32| sigmoid_safe(*t, I32F32::max_value(), I32F32::max_value())) .collect(); - let target: Vec = vec_to_fixed(&vec![ + let target: Vec = vec_to_fixed(&[0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, - 0.0000000019, - 0.5, - ]); + 0.5]); assert_eq!(&consensus, &target); let consensus: Vec = trust .iter() .map(|t: &I32F32| sigmoid_safe(*t, I32F32::min_value(), I32F32::min_value())) .collect(); - let target: Vec = vec_to_fixed(&vec![ - 0.5, - 0.0000000019, + let target: Vec = vec_to_fixed(&[0.5, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, - ]); + 0.0000000019]); assert_eq!(&consensus, &target); let consensus: Vec = trust .iter() @@ -1660,7 +1654,7 @@ mod tests { let target: Vec = target.iter().map(|c: &f64| I32F32::from_num(*c)).collect(); assert_eq!(&consensus, &target); let trust: Vec = - vec_to_fixed(&vec![0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]); + vec_to_fixed(&[0., 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.]); let consensus: Vec = trust .iter() .map(|t: &I32F32| sigmoid_safe(*t, I32F32::from_num(40), I32F32::from_num(0.5))) @@ -1684,11 +1678,11 @@ mod tests { #[test] fn test_math_is_topk() { - let vector: Vec = vec_to_fixed(&vec![]); + let vector: Vec = vec_to_fixed(&[]); let result = is_topk(&vector, 5); let target: Vec = vec![]; assert_eq!(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]); + let vector: Vec = vec_to_fixed(&[0., 1., 2., 3., 4., 5., 6., 7., 8., 9.]); let result = is_topk(&vector, 0); let target: Vec = vec![ false, false, false, false, false, false, false, false, false, false, @@ -1704,26 +1698,26 @@ mod tests { assert_eq!(&result, &target); let result = is_topk(&vector, 100); assert_eq!(&result, &target); - let vector: Vec = vec_to_fixed(&vec![9., 8., 7., 6., 5., 4., 3., 2., 1., 0.]); + let vector: Vec = vec_to_fixed(&[9., 8., 7., 6., 5., 4., 3., 2., 1., 0.]); let result = is_topk(&vector, 5); let target: Vec = vec![ true, true, true, true, true, false, false, false, false, false, ]; assert_eq!(&result, &target); - let vector: Vec = vec_to_fixed(&vec![9., 0., 8., 1., 7., 2., 6., 3., 5., 4.]); + let vector: Vec = vec_to_fixed(&[9., 0., 8., 1., 7., 2., 6., 3., 5., 4.]); let result = is_topk(&vector, 5); let target: Vec = vec![ true, false, true, false, true, false, true, false, true, false, ]; assert_eq!(&result, &target); let vector: Vec = - vec_to_fixed(&vec![0.9, 0., 0.8, 0.1, 0.7, 0.2, 0.6, 0.3, 0.5, 0.4]); + vec_to_fixed(&[0.9, 0., 0.8, 0.1, 0.7, 0.2, 0.6, 0.3, 0.5, 0.4]); let result = is_topk(&vector, 5); let target: Vec = vec![ true, false, true, false, true, false, true, false, true, false, ]; assert_eq!(&result, &target); - let vector: Vec = vec_to_fixed(&vec![0., 1., 2., 3., 4., 5., 5., 5., 5., 6.]); + let vector: Vec = vec_to_fixed(&[0., 1., 2., 3., 4., 5., 5., 5., 5., 6.]); let result = is_topk(&vector, 5); let target: Vec = vec![ false, false, false, false, false, true, true, true, true, true, @@ -1733,16 +1727,16 @@ mod tests { #[test] fn test_math_sum() { - assert!(sum(&vec![]) == I32F32::from_num(0)); + assert!(sum(&[]) == I32F32::from_num(0)); assert!( - sum(&vec![ + sum(&[ I32F32::from_num(1.0), I32F32::from_num(10.0), I32F32::from_num(30.0) ]) == I32F32::from_num(41) ); assert!( - sum(&vec![ + sum(&[ I32F32::from_num(-1.0), I32F32::from_num(10.0), I32F32::from_num(30.0) @@ -1764,7 +1758,7 @@ mod tests { let y: Vec = normalize(&x); assert_vec_compare( &y, - &vec![ + &[ I32F32::from_num(0.0243902437), I32F32::from_num(0.243902439), I32F32::from_num(0.7317073171), @@ -1780,7 +1774,7 @@ mod tests { let y: Vec = normalize(&x); assert_vec_compare( &y, - &vec![ + &[ I32F32::from_num(-0.0256410255), I32F32::from_num(0.2564102563), I32F32::from_num(0.769230769), @@ -1801,7 +1795,7 @@ mod tests { inplace_normalize(&mut x1); assert_vec_compare( &x1, - &vec![ + &[ I32F32::from_num(0.0243902437), I32F32::from_num(0.243902439), I32F32::from_num(0.7317073171), @@ -1816,7 +1810,7 @@ mod tests { inplace_normalize(&mut x2); assert_vec_compare( &x2, - &vec![ + &[ I32F32::from_num(-0.0256410255), I32F32::from_num(0.2564102563), I32F32::from_num(0.769230769), @@ -1836,7 +1830,7 @@ mod tests { inplace_normalize_64(&mut x1); assert_vec_compare_64( &x1, - &vec![ + &[ I64F64::from_num(0.0243902437), I64F64::from_num(0.243902439), I64F64::from_num(0.7317073171), @@ -1851,7 +1845,7 @@ mod tests { inplace_normalize_64(&mut x2); assert_vec_compare_64( &x2, - &vec![ + &[ I64F64::from_num(-0.0256410255), I64F64::from_num(0.2564102563), I64F64::from_num(0.769230769), @@ -1862,18 +1856,18 @@ mod tests { #[test] fn test_math_vecdiv() { - let x: Vec = vec_to_fixed(&vec![]); - let y: Vec = vec_to_fixed(&vec![]); - let result: Vec = vec_to_fixed(&vec![]); + let x: Vec = vec_to_fixed(&[]); + let y: Vec = vec_to_fixed(&[]); + let result: Vec = vec_to_fixed(&[]); assert_eq!(result, vecdiv(&x, &y)); - let x: Vec = vec_to_fixed(&vec![0., 1., 0., 1.]); - let y: Vec = vec_to_fixed(&vec![0., 1., 1., 0.]); - let result: Vec = vec_to_fixed(&vec![0., 1., 0., 0.]); + let x: Vec = vec_to_fixed(&[0., 1., 0., 1.]); + let y: Vec = vec_to_fixed(&[0., 1., 1., 0.]); + let result: Vec = vec_to_fixed(&[0., 1., 0., 0.]); assert_eq!(result, vecdiv(&x, &y)); - let x: Vec = vec_to_fixed(&vec![1., 1., 10.]); - let y: Vec = vec_to_fixed(&vec![2., 3., 2.]); + let x: Vec = vec_to_fixed(&[1., 1., 10.]); + let y: Vec = vec_to_fixed(&[2., 3., 2.]); let result: Vec = vec![fixed(1.) / fixed(2.), fixed(1.) / fixed(3.), fixed(5.)]; assert_eq!(result, vecdiv(&x, &y)); } @@ -2034,18 +2028,18 @@ mod tests { #[test] fn test_math_inplace_mask_vector() { let mask: Vec = vec![false, false, false]; - let mut vector: Vec = vec_to_fixed(&vec![0., 1., 2.]); - let target: Vec = vec_to_fixed(&vec![0., 1., 2.]); + let mut vector: Vec = vec_to_fixed(&[0., 1., 2.]); + let target: Vec = vec_to_fixed(&[0., 1., 2.]); inplace_mask_vector(&mask, &mut vector); assert_vec_compare(&vector, &target, I32F32::from_num(0)); let mask: Vec = vec![false, true, false]; - let mut vector: Vec = vec_to_fixed(&vec![0., 1., 2.]); - let target: Vec = vec_to_fixed(&vec![0., 0., 2.]); + let mut vector: Vec = vec_to_fixed(&[0., 1., 2.]); + let target: Vec = vec_to_fixed(&[0., 0., 2.]); inplace_mask_vector(&mask, &mut vector); assert_vec_compare(&vector, &target, I32F32::from_num(0)); let mask: Vec = vec![true, true, true]; - let mut vector: Vec = vec_to_fixed(&vec![0., 1., 2.]); - let target: Vec = vec_to_fixed(&vec![0., 0., 0.]); + let mut vector: Vec = vec_to_fixed(&[0., 1., 2.]); + let target: Vec = vec_to_fixed(&[0., 0., 0.]); inplace_mask_vector(&mask, &mut vector); assert_vec_compare(&vector, &target, I32F32::from_num(0)); } @@ -2257,7 +2251,7 @@ mod tests { #[test] fn test_math_row_hadamard() { - let vector: Vec = vec_to_fixed(&vec![1., 2., 3., 4.]); + let vector: Vec = vec_to_fixed(&[1., 2., 3., 4.]); let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_mat_fixed(&matrix, 4, false); let result = row_hadamard(&matrix, &vector); @@ -2268,7 +2262,7 @@ mod tests { #[test] fn test_math_row_hadamard_sparse() { - let vector: Vec = vec_to_fixed(&vec![1., 2., 3., 4.]); + let vector: Vec = vec_to_fixed(&[1., 2., 3., 4.]); let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = row_hadamard_sparse(&matrix, &vector); @@ -2294,7 +2288,7 @@ mod tests { let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_mat_fixed(&matrix, 4, false); let result = row_sum(&matrix); - let target: Vec = vec_to_fixed(&vec![6., 15., 24., 33.]); + let target: Vec = vec_to_fixed(&[6., 15., 24., 33.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } @@ -2303,22 +2297,22 @@ mod tests { let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = row_sum_sparse(&matrix); - let target: Vec = vec_to_fixed(&vec![6., 15., 24., 33.]); + let target: Vec = vec_to_fixed(&[6., 15., 24., 33.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 2., 3., 4., 0., 6., 7., 8., 0., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = row_sum_sparse(&matrix); - let target: Vec = vec_to_fixed(&vec![5., 10., 15., 33.]); + let target: Vec = vec_to_fixed(&[5., 10., 15., 33.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![1., 2., 3., 0., 0., 0., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = row_sum_sparse(&matrix); - let target: Vec = vec_to_fixed(&vec![6., 0., 24., 33.]); + let target: Vec = vec_to_fixed(&[6., 0., 24., 33.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = row_sum_sparse(&matrix); - let target: Vec = vec_to_fixed(&vec![0., 0., 0., 0.]); + let target: Vec = vec_to_fixed(&[0., 0., 0., 0.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } @@ -2327,7 +2321,7 @@ mod tests { let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_mat_fixed(&matrix, 4, false); let result = col_sum(&matrix); - let target: Vec = vec_to_fixed(&vec![22., 26., 30.]); + let target: Vec = vec_to_fixed(&[22., 26., 30.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } @@ -2336,88 +2330,88 @@ mod tests { let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = col_sum_sparse(&matrix, 3); - let target: Vec = vec_to_fixed(&vec![22., 26., 30.]); + let target: Vec = vec_to_fixed(&[22., 26., 30.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 2., 3., 4., 0., 6., 7., 8., 0., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = col_sum_sparse(&matrix, 3); - let target: Vec = vec_to_fixed(&vec![21., 21., 21.]); + let target: Vec = vec_to_fixed(&[21., 21., 21.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![1., 0., 3., 4., 0., 6., 7., 0., 9., 10., 0., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = col_sum_sparse(&matrix, 3); - let target: Vec = vec_to_fixed(&vec![22., 0., 30.]); + let target: Vec = vec_to_fixed(&[22., 0., 30.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = col_sum_sparse(&matrix, 3); - let target: Vec = vec_to_fixed(&vec![0., 0., 0.]); + let target: Vec = vec_to_fixed(&[0., 0., 0.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } #[test] fn test_math_matmul() { - let vector: Vec = vec_to_fixed(&vec![1., 2., 3., 4.]); + let vector: Vec = vec_to_fixed(&[1., 2., 3., 4.]); let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_mat_fixed(&matrix, 4, false); let result = matmul(&matrix, &vector); - let target: Vec = vec_to_fixed(&vec![70., 80., 90.]); + let target: Vec = vec_to_fixed(&[70., 80., 90.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } #[test] fn test_math_matmul_transpose() { - let vector: Vec = vec_to_fixed(&vec![1., 2., 3.]); + let vector: Vec = vec_to_fixed(&[1., 2., 3.]); let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_mat_fixed(&matrix, 4, false); let result = matmul_transpose(&matrix, &vector); - let target: Vec = vec_to_fixed(&vec![14., 32., 50., 68.]); + let target: Vec = vec_to_fixed(&[14., 32., 50., 68.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } #[test] fn test_math_sparse_matmul() { - let vector: Vec = vec_to_fixed(&vec![1., 2., 3., 4.]); + let vector: Vec = vec_to_fixed(&[1., 2., 3., 4.]); let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = matmul_sparse(&matrix, &vector, 3); - let target: Vec = vec_to_fixed(&vec![70., 80., 90.]); + let target: Vec = vec_to_fixed(&[70., 80., 90.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 2., 3., 4., 0., 6., 7., 8., 0., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = matmul_sparse(&matrix, &vector, 3); - let target: Vec = vec_to_fixed(&vec![69., 70., 63.]); + let target: Vec = vec_to_fixed(&[69., 70., 63.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = matmul_sparse(&matrix, &vector, 3); - let target: Vec = vec_to_fixed(&vec![0., 0., 0.]); + let target: Vec = vec_to_fixed(&[0., 0., 0.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } #[test] fn test_math_sparse_matmul_transpose() { - let vector: Vec = vec_to_fixed(&vec![1., 2., 3.]); + let vector: Vec = vec_to_fixed(&[1., 2., 3.]); let matrix: Vec = vec![1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = matmul_transpose_sparse(&matrix, &vector); - let target: Vec = vec_to_fixed(&vec![14., 32., 50., 68.]); + let target: Vec = vec_to_fixed(&[14., 32., 50., 68.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 2., 3., 4., 0., 6., 7., 8., 0., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = matmul_transpose_sparse(&matrix, &vector); - let target: Vec = vec_to_fixed(&vec![13., 22., 23., 68.]); + let target: Vec = vec_to_fixed(&[13., 22., 23., 68.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); let matrix: Vec = vec![0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let result = matmul_transpose_sparse(&matrix, &vector); - let target: Vec = vec_to_fixed(&vec![0., 0., 0., 0.]); + let target: Vec = vec_to_fixed(&[0., 0., 0., 0.]); assert_vec_compare(&result, &target, I32F32::from_num(0)); } #[test] fn test_math_inplace_col_clip() { - let vector: Vec = vec_to_fixed(&vec![0., 5., 12.]); + let vector: Vec = vec_to_fixed(&[0., 5., 12.]); let matrix: Vec = vec![0., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let mut matrix = vec_to_mat_fixed(&matrix, 4, false); let target: Vec = vec![0., 2., 3., 0., 5., 6., 0., 5., 9., 0., 5., 12.]; @@ -2428,7 +2422,7 @@ mod tests { #[test] fn test_math_col_clip_sparse() { - let vector: Vec = vec_to_fixed(&vec![0., 5., 12.]); + let vector: Vec = vec_to_fixed(&[0., 5., 12.]); let matrix: Vec = vec![0., 2., 3., 4., 5., 6., 7., 8., 9., 10., 11., 12.]; let matrix = vec_to_sparse_mat_fixed(&matrix, 4, false); let target: Vec = vec![0., 2., 3., 0., 5., 6., 0., 5., 9., 0., 5., 12.]; @@ -2500,165 +2494,165 @@ mod tests { let zero: I32F32 = fixed(0.); let one: I32F32 = fixed(1.); for _ in 0..100 { - let stake: Vec = vec_to_fixed(&vec![]); - let score: Vec = vec_to_fixed(&vec![]); + let stake: Vec = vec_to_fixed(&[]); + let score: Vec = vec_to_fixed(&[]); let majority: I32F32 = fixed(0.51); assert_eq!( zero, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = normalize(&vec_to_fixed(&vec![0.51])); - let score: Vec = vec_to_fixed(&vec![1.]); + let stake: Vec = normalize(&vec_to_fixed(&[0.51])); + let score: Vec = vec_to_fixed(&[1.]); let majority: I32F32 = fixed(0.51); assert_eq!( one, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.49, 0.51]); - let score: Vec = vec_to_fixed(&vec![0.5, 1.]); + let stake: Vec = vec_to_fixed(&[0.49, 0.51]); + let score: Vec = vec_to_fixed(&[0.5, 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( one, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.51, 0.49]); - let score: Vec = vec_to_fixed(&vec![0.5, 1.]); + let stake: Vec = vec_to_fixed(&[0.51, 0.49]); + let score: Vec = vec_to_fixed(&[0.5, 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( fixed(0.5), weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.49, 0., 0.51]); - let score: Vec = vec_to_fixed(&vec![0.5, 0.7, 1.]); + let stake: Vec = vec_to_fixed(&[0.49, 0., 0.51]); + let score: Vec = vec_to_fixed(&[0.5, 0.7, 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( one, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.49, 0.01, 0.5]); - let score: Vec = vec_to_fixed(&vec![0.5, 0.7, 1.]); + let stake: Vec = vec_to_fixed(&[0.49, 0.01, 0.5]); + let score: Vec = vec_to_fixed(&[0.5, 0.7, 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( fixed(0.7), weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.49, 0.51, 0.0]); - let score: Vec = vec_to_fixed(&vec![0.5, 0.7, 1.]); + let stake: Vec = vec_to_fixed(&[0.49, 0.51, 0.0]); + let score: Vec = vec_to_fixed(&[0.5, 0.7, 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( fixed(0.7), weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.0, 0.49, 0.51]); - let score: Vec = vec_to_fixed(&vec![0.5, 0.7, 1.]); + let stake: Vec = vec_to_fixed(&[0.0, 0.49, 0.51]); + let score: Vec = vec_to_fixed(&[0.5, 0.7, 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( one, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.0, 0.49, 0.0, 0.51]); - let score: Vec = vec_to_fixed(&vec![0.5, 0.5, 1., 1.]); + let stake: Vec = vec_to_fixed(&[0.0, 0.49, 0.0, 0.51]); + let score: Vec = vec_to_fixed(&[0.5, 0.5, 1., 1.]); let majority: I32F32 = fixed(0.51); assert_eq!( one, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.0, 0.49, 0.0, 0.51, 0.0]); - let score: Vec = vec_to_fixed(&vec![0.5, 0.5, 1., 1., 0.5]); + let stake: Vec = vec_to_fixed(&[0.0, 0.49, 0.0, 0.51, 0.0]); + let score: Vec = vec_to_fixed(&[0.5, 0.5, 1., 1., 0.5]); let majority: I32F32 = fixed(0.51); assert_eq!( one, weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() ) ); - let stake: Vec = vec_to_fixed(&vec![0.2, 0.2, 0.2, 0.2, 0.2]); - let score: Vec = vec_to_fixed(&vec![0.8, 0.2, 1., 0.6, 0.4]); + let stake: Vec = vec_to_fixed(&[0.2, 0.2, 0.2, 0.2, 0.2]); + let score: Vec = vec_to_fixed(&[0.8, 0.2, 1., 0.6, 0.4]); let majority: I32F32 = fixed(0.51); assert_eq!( fixed(0.6), weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() @@ -2666,16 +2660,16 @@ mod tests { ); let stake: Vec = - vec_to_fixed(&vec![0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]); + vec_to_fixed(&[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]); let score: Vec = - vec_to_fixed(&vec![0.8, 0.8, 0.2, 0.2, 1.0, 1.0, 0.6, 0.6, 0.4, 0.4]); + vec_to_fixed(&[0.8, 0.8, 0.2, 0.2, 1.0, 1.0, 0.6, 0.6, 0.4, 0.4]); let majority: I32F32 = fixed(0.51); assert_eq!( fixed(0.6), weighted_median( &stake, &score, - &(0..stake.len()).collect(), + (0..stake.len()).collect::>().as_slice(), one - majority, zero, stake.iter().sum() @@ -2683,9 +2677,7 @@ mod tests { ); let n: usize = 100; - for majority in vec_to_fixed(&vec![ - 0., 0.0000001, 0.25, 0.49, 0.49, 0.49, 0.5, 0.51, 0.51, 0.51, 0.9999999, 1., - ]) { + for majority in vec_to_fixed(&[0., 0.0000001, 0.25, 0.49, 0.49, 0.49, 0.5, 0.51, 0.51, 0.51, 0.9999999, 1.]) { for allow_equal in [false, true] { let mut stake: Vec = vec![]; let mut score: Vec = vec![]; @@ -2762,76 +2754,76 @@ mod tests { #[test] fn test_math_weighted_median_col() { - let stake: Vec = vec_to_fixed(&vec![]); + let stake: Vec = vec_to_fixed(&[]); let weights: Vec> = vec![vec![]]; - let median: Vec = vec_to_fixed(&vec![]); + let median: Vec = vec_to_fixed(&[]); assert_eq!(median, weighted_median_col(&stake, &weights, fixed(0.5))); - let stake: Vec = vec_to_fixed(&vec![0., 0.]); + let stake: Vec = vec_to_fixed(&[0., 0.]); let weights: Vec = vec![0., 0., 0., 0.]; let weights: Vec> = vec_to_mat_fixed(&weights, 2, false); - let median: Vec = vec_to_fixed(&vec![0., 0.]); + let median: Vec = vec_to_fixed(&[0., 0.]); assert_eq!(median, weighted_median_col(&stake, &weights, fixed(0.5))); - let stake: Vec = vec_to_fixed(&vec![0., 0.75, 0.25, 0.]); + let stake: Vec = vec_to_fixed(&[0., 0.75, 0.25, 0.]); let weights: Vec = vec![0., 0.1, 0., 0., 0.2, 0.4, 0., 0.3, 0.1, 0., 0.4, 0.5]; let weights: Vec> = vec_to_mat_fixed(&weights, 4, false); - let median: Vec = vec_to_fixed(&vec![0., 0.3, 0.4]); + let median: Vec = vec_to_fixed(&[0., 0.3, 0.4]); assert_eq!(median, weighted_median_col(&stake, &weights, fixed(0.24))); - let median: Vec = vec_to_fixed(&vec![0., 0.2, 0.4]); + let median: Vec = vec_to_fixed(&[0., 0.2, 0.4]); assert_eq!(median, weighted_median_col(&stake, &weights, fixed(0.26))); - let median: Vec = vec_to_fixed(&vec![0., 0.2, 0.1]); + let median: Vec = vec_to_fixed(&[0., 0.2, 0.1]); assert_eq!(median, weighted_median_col(&stake, &weights, fixed(0.76))); - let stake: Vec = vec_to_fixed(&vec![0., 0.3, 0.2, 0.5]); + let stake: Vec = vec_to_fixed(&[0., 0.3, 0.2, 0.5]); let weights: Vec = vec![0., 0.1, 0., 0., 0.2, 0.4, 0., 0.3, 0.1, 0., 0., 0.5]; let weights: Vec> = vec_to_mat_fixed(&weights, 4, false); - let median: Vec = vec_to_fixed(&vec![0., 0., 0.4]); + let median: Vec = vec_to_fixed(&[0., 0., 0.4]); assert_eq!(median, weighted_median_col(&stake, &weights, fixed(0.51))); } #[test] fn test_math_weighted_median_col_sparse() { - let stake: Vec = vec_to_fixed(&vec![]); + let stake: Vec = vec_to_fixed(&[]); let weights: Vec> = vec![vec![]]; - let median: Vec = vec_to_fixed(&vec![]); + let median: Vec = vec_to_fixed(&[]); assert_eq!( median, weighted_median_col_sparse(&stake, &weights, 0, fixed(0.5)) ); - let stake: Vec = vec_to_fixed(&vec![0., 0.]); + let stake: Vec = vec_to_fixed(&[0., 0.]); let weights: Vec = vec![0., 0., 0., 0.]; let weights: Vec> = vec_to_sparse_mat_fixed(&weights, 2, false); - let median: Vec = vec_to_fixed(&vec![0., 0.]); + let median: Vec = vec_to_fixed(&[0., 0.]); assert_eq!( median, weighted_median_col_sparse(&stake, &weights, 2, fixed(0.5)) ); - let stake: Vec = vec_to_fixed(&vec![0., 0.75, 0.25, 0.]); + let stake: Vec = vec_to_fixed(&[0., 0.75, 0.25, 0.]); let weights: Vec = vec![0., 0.1, 0., 0., 0.2, 0.4, 0., 0.3, 0.1, 0., 0.4, 0.5]; let weights: Vec> = vec_to_sparse_mat_fixed(&weights, 4, false); - let median: Vec = vec_to_fixed(&vec![0., 0.3, 0.4]); + let median: Vec = vec_to_fixed(&[0., 0.3, 0.4]); assert_eq!( median, weighted_median_col_sparse(&stake, &weights, 3, fixed(0.24)) ); - let median: Vec = vec_to_fixed(&vec![0., 0.2, 0.4]); + let median: Vec = vec_to_fixed(&[0., 0.2, 0.4]); assert_eq!( median, weighted_median_col_sparse(&stake, &weights, 3, fixed(0.26)) ); - let median: Vec = vec_to_fixed(&vec![0., 0.2, 0.1]); + let median: Vec = vec_to_fixed(&[0., 0.2, 0.1]); assert_eq!( median, weighted_median_col_sparse(&stake, &weights, 3, fixed(0.76)) ); - let stake: Vec = vec_to_fixed(&vec![0., 0.3, 0.2, 0.5]); + let stake: Vec = vec_to_fixed(&[0., 0.3, 0.2, 0.5]); let weights: Vec = vec![0., 0.1, 0., 0., 0.2, 0.4, 0., 0.3, 0.1, 0., 0., 0.5]; let weights: Vec> = vec_to_sparse_mat_fixed(&weights, 4, false); - let median: Vec = vec_to_fixed(&vec![0., 0., 0.4]); + let median: Vec = vec_to_fixed(&[0., 0., 0.4]); assert_eq!( median, weighted_median_col_sparse(&stake, &weights, 3, fixed(0.51)) @@ -2993,8 +2985,8 @@ mod tests { let epsilon: I32F32 = I32F32::from_num(0.0001); let w: Vec> = vec![vec![I32F32::from_num(1.0); 3]; 3]; assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(1.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(1.0); 3]), + &[ I32F32::from_num(3), I32F32::from_num(3), I32F32::from_num(3), @@ -3002,8 +2994,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(2.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(2.0); 3]), + &[ I32F32::from_num(6), I32F32::from_num(6), I32F32::from_num(6), @@ -3011,8 +3003,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(3.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(3.0); 3]), + &[ I32F32::from_num(9), I32F32::from_num(9), I32F32::from_num(9), @@ -3020,8 +3012,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(-1.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(-1.0); 3]), + &[ I32F32::from_num(-3), I32F32::from_num(-3), I32F32::from_num(-3), @@ -3030,8 +3022,8 @@ mod tests { ); let w: Vec> = vec![vec![I32F32::from_num(-1.0); 3]; 3]; assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(1.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(1.0); 3]), + &[ I32F32::from_num(-3), I32F32::from_num(-3), I32F32::from_num(-3), @@ -3039,8 +3031,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(2.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(2.0); 3]), + &[ I32F32::from_num(-6), I32F32::from_num(-6), I32F32::from_num(-6), @@ -3048,8 +3040,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(3.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(3.0); 3]), + &[ I32F32::from_num(-9), I32F32::from_num(-9), I32F32::from_num(-9), @@ -3057,8 +3049,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(-1.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(-1.0); 3]), + &[ I32F32::from_num(3), I32F32::from_num(3), I32F32::from_num(3), @@ -3071,8 +3063,8 @@ mod tests { vec![I32F32::from_num(3.0); 3], ]; assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(0.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(0.0); 3]), + &[ I32F32::from_num(0.0), I32F32::from_num(0.0), I32F32::from_num(0.0), @@ -3080,8 +3072,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(2.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(2.0); 3]), + &[ I32F32::from_num(12), I32F32::from_num(12), I32F32::from_num(12), @@ -3097,8 +3089,8 @@ mod tests { 3 ]; assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(0.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(0.0); 3]), + &[ I32F32::from_num(0.0), I32F32::from_num(0.0), I32F32::from_num(0.0), @@ -3106,8 +3098,8 @@ mod tests { epsilon, ); assert_vec_compare( - &matmul(&w, &vec![I32F32::from_num(2.0); 3]), - &vec![ + &matmul(&w, &[I32F32::from_num(2.0); 3]), + &[ I32F32::from_num(6), I32F32::from_num(12), I32F32::from_num(18), diff --git a/pallets/subtensor/tests/epoch.rs b/pallets/subtensor/tests/epoch.rs index 9383ea9e6..893e01bd8 100644 --- a/pallets/subtensor/tests/epoch.rs +++ b/pallets/subtensor/tests/epoch.rs @@ -217,7 +217,7 @@ fn init_run_epochs( assert_ok!(SubtensorModule::set_weights( RuntimeOrigin::signed(U256::from(*uid as u64)), netuid, - servers.clone(), + servers.to_vec(), weights.clone(), 0 )); @@ -568,7 +568,7 @@ fn test_1_graph() { )); // SubtensorModule::set_weights_for_testing( netuid, i as u16, vec![ ( 0, u16::MAX )]); // doesn't set update status // SubtensorModule::set_bonds_for_testing( netuid, uid, vec![ ( 0, u16::MAX )]); // rather, bonds are calculated in epoch - SubtensorModule::set_emission_values(&vec![netuid], vec![1_000_000_000]).unwrap(); + SubtensorModule::set_emission_values(&[netuid], vec![1_000_000_000]).unwrap(); assert_eq!( SubtensorModule::get_subnet_emission_value(netuid), 1_000_000_000 diff --git a/pallets/subtensor/tests/migration.rs b/pallets/subtensor/tests/migration.rs index 8f31c33a6..2f634d7c0 100644 --- a/pallets/subtensor/tests/migration.rs +++ b/pallets/subtensor/tests/migration.rs @@ -208,7 +208,7 @@ fn test_total_issuance_global() { // Set emission values for the network and verify. let emission: u64 = 1_000_000_000; SubtensorModule::set_tempo(netuid, 1); - SubtensorModule::set_emission_values(&vec![netuid], vec![emission]).unwrap(); // Set the emission value for the network to 1_000_000_000. + SubtensorModule::set_emission_values(&[netuid], vec![emission]).unwrap(); // Set the emission value for the network to 1_000_000_000. assert_eq!(SubtensorModule::get_subnet_emission_value(netuid), emission); // Verify the emission value is set correctly for the network. assert_eq!( SubtensorModule::get_total_issuance(), diff --git a/pallets/subtensor/tests/root.rs b/pallets/subtensor/tests/root.rs index 305866635..d35d570b2 100644 --- a/pallets/subtensor/tests/root.rs +++ b/pallets/subtensor/tests/root.rs @@ -569,17 +569,17 @@ fn test_network_prune_results() { step_block(3); // lowest emission - SubtensorModule::set_emission_values(&vec![1u16, 2u16, 3u16], vec![5u64, 4u64, 4u64]) + SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![5u64, 4u64, 4u64]) .unwrap(); assert_eq!(SubtensorModule::get_subnet_to_prune(), 2u16); // equal emission, creation date - SubtensorModule::set_emission_values(&vec![1u16, 2u16, 3u16], vec![5u64, 5u64, 4u64]) + SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![5u64, 5u64, 4u64]) .unwrap(); assert_eq!(SubtensorModule::get_subnet_to_prune(), 3u16); // equal emission, creation date - SubtensorModule::set_emission_values(&vec![1u16, 2u16, 3u16], vec![4u64, 5u64, 5u64]) + SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![4u64, 5u64, 5u64]) .unwrap(); assert_eq!(SubtensorModule::get_subnet_to_prune(), 1u16); }); From 2489a6f148cf2fc455b19937034a88cb70dfc83e Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 12:21:56 +0400 Subject: [PATCH 08/13] ci: add clippy check --- .github/workflows/check-rust.yml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/workflows/check-rust.yml b/.github/workflows/check-rust.yml index 266ed177a..4c56233f8 100644 --- a/.github/workflows/check-rust.yml +++ b/.github/workflows/check-rust.yml @@ -71,9 +71,9 @@ jobs: - name: cargo fmt run: cargo fmt --check --all - # runs cargo check --workspace - cargo-check: - name: cargo check + # runs cargo clippy --workspace --all-targets --all-features + cargo-clippy: + name: cargo clippy runs-on: SubtensorCI strategy: matrix: @@ -117,8 +117,8 @@ jobs: with: key: ${{ matrix.os }}-${{ env.RUST_BIN_DIR }} - - name: cargo check --workspace - run: cargo check --workspace + - name: cargo clippy --workspace --all-targets --all-features + run: cargo clippy --workspace --all-targets --all-features # runs cargo test --workspace cargo-test: From 115ebe3dda3008db19b0434de293daf8d73bc289 Mon Sep 17 00:00:00 2001 From: orriin <167025436+orriin@users.noreply.github.com> Date: Sun, 28 Apr 2024 12:28:29 +0400 Subject: [PATCH 09/13] Update pallets/subtensor/src/registration.rs --- pallets/subtensor/src/registration.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/pallets/subtensor/src/registration.rs b/pallets/subtensor/src/registration.rs index b75250536..4d43a3683 100644 --- a/pallets/subtensor/src/registration.rs +++ b/pallets/subtensor/src/registration.rs @@ -437,9 +437,6 @@ impl Pallet { let pruning_score: u16 = Self::get_pruning_score_for_uid(netuid, neuron_uid_i); let block_at_registration: u64 = Self::get_neuron_block_at_registration(netuid, neuron_uid_i); - - // Too dangerous to remove this comparison change while enabling clippy. allow it for - // now. #[allow(clippy::comparison_chain)] if min_score == pruning_score { if current_block - block_at_registration < immunity_period { From e8f6f6dfa5c969ac475bc30ce733326b9ff7007b Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 12:32:22 +0400 Subject: [PATCH 10/13] fix: remove redundant comment --- pallets/subtensor/tests/epoch.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/pallets/subtensor/tests/epoch.rs b/pallets/subtensor/tests/epoch.rs index 893e01bd8..0bfd11ba4 100644 --- a/pallets/subtensor/tests/epoch.rs +++ b/pallets/subtensor/tests/epoch.rs @@ -162,7 +162,6 @@ fn init_run_epochs( // === Register uids SubtensorModule::set_max_allowed_uids(netuid, n); for key in 0..n { - // let stake: u64; let stake = if use_input_stake { input_stake[key as usize] } else if validators.contains(&key) { From 93de2c5f76bbbcdc287d5d3263499ff85cd2155a Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 12:35:07 +0400 Subject: [PATCH 11/13] fix: fmt --- pallets/subtensor/tests/root.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/pallets/subtensor/tests/root.rs b/pallets/subtensor/tests/root.rs index d35d570b2..27a652851 100644 --- a/pallets/subtensor/tests/root.rs +++ b/pallets/subtensor/tests/root.rs @@ -569,18 +569,15 @@ fn test_network_prune_results() { step_block(3); // lowest emission - SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![5u64, 4u64, 4u64]) - .unwrap(); + SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![5u64, 4u64, 4u64]).unwrap(); assert_eq!(SubtensorModule::get_subnet_to_prune(), 2u16); // equal emission, creation date - SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![5u64, 5u64, 4u64]) - .unwrap(); + SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![5u64, 5u64, 4u64]).unwrap(); assert_eq!(SubtensorModule::get_subnet_to_prune(), 3u16); // equal emission, creation date - SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![4u64, 5u64, 5u64]) - .unwrap(); + SubtensorModule::set_emission_values(&[1u16, 2u16, 3u16], vec![4u64, 5u64, 5u64]).unwrap(); assert_eq!(SubtensorModule::get_subnet_to_prune(), 1u16); }); } From 904662cff7de1c06172935f0cf0542e9d9b6d889 Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 12:42:33 +0400 Subject: [PATCH 12/13] fix: fmt --- node/src/command.rs | 1 - node/src/rpc.rs | 8 ++++---- pallets/commitments/src/benchmarking.rs | 2 +- pallets/subtensor/src/delegate_info.rs | 8 ++------ pallets/subtensor/src/math.rs | 23 +++++++++++++++-------- pallets/subtensor/src/root.rs | 3 +-- pallets/subtensor/src/stake_info.rs | 4 +--- pallets/subtensor/src/uids.rs | 3 +-- pallets/subtensor/src/utils.rs | 15 ++++++++++++--- 9 files changed, 37 insertions(+), 30 deletions(-) diff --git a/node/src/command.rs b/node/src/command.rs index a3865f7b3..1ce7d4f12 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -17,7 +17,6 @@ use node_subtensor_runtime::Block; use sc_cli::SubstrateCli; use sc_service::PartialComponents; - impl SubstrateCli for Cli { fn impl_name() -> String { "Subtensor Node".into() diff --git a/node/src/rpc.rs b/node/src/rpc.rs index 702357001..511fb74c3 100644 --- a/node/src/rpc.rs +++ b/node/src/rpc.rs @@ -8,12 +8,12 @@ use std::sync::Arc; use jsonrpsee::RpcModule; -use node_subtensor_runtime::{opaque::Block, AccountId, Balance, BlockNumber, Index, Hash}; +use node_subtensor_runtime::{opaque::Block, AccountId, Balance, BlockNumber, Hash, Index}; +use sc_consensus_grandpa::FinalityProofProvider; use sc_transaction_pool_api::TransactionPool; use sp_api::ProvideRuntimeApi; use sp_block_builder::BlockBuilder; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; -use sc_consensus_grandpa::FinalityProofProvider; pub use sc_rpc_api::DenyUnsafe; @@ -64,9 +64,9 @@ where P: TransactionPool + 'static, { use pallet_transaction_payment_rpc::{TransactionPayment, TransactionPaymentApiServer}; + use sc_consensus_grandpa_rpc::{Grandpa, GrandpaApiServer}; use substrate_frame_rpc_system::{System, SystemApiServer}; use subtensor_custom_rpc::{SubtensorCustom, SubtensorCustomApiServer}; - use sc_consensus_grandpa_rpc::{Grandpa, GrandpaApiServer}; let mut module = RpcModule::new(()); let FullDeps { @@ -99,7 +99,7 @@ where justification_stream, finality_provider, ) - .into_rpc(), + .into_rpc(), )?; // Extend this RPC with a custom API by using the following syntax. diff --git a/pallets/commitments/src/benchmarking.rs b/pallets/commitments/src/benchmarking.rs index fc40198bc..27b886e3a 100644 --- a/pallets/commitments/src/benchmarking.rs +++ b/pallets/commitments/src/benchmarking.rs @@ -7,7 +7,7 @@ use crate::Pallet as Commitments; use frame_benchmarking::v2::*; use frame_system::RawOrigin; -use sp_runtime::traits::{Bounded}; +use sp_runtime::traits::Bounded; fn assert_last_event(generic_event: ::RuntimeEvent) { frame_system::Pallet::::assert_last_event(generic_event.into()); diff --git a/pallets/subtensor/src/delegate_info.rs b/pallets/subtensor/src/delegate_info.rs index 03fe2bf34..2d5f38bf3 100644 --- a/pallets/subtensor/src/delegate_info.rs +++ b/pallets/subtensor/src/delegate_info.rs @@ -99,9 +99,7 @@ impl Pallet { pub fn get_delegates() -> Vec> { let mut delegates = Vec::>::new(); - for delegate in - as IterableStorageMap>::iter_keys() - { + for delegate in as IterableStorageMap>::iter_keys() { let delegate_info = Self::get_delegate_by_existing_account(delegate.clone()); delegates.push(delegate_info); } @@ -118,9 +116,7 @@ impl Pallet { T::AccountId::decode(&mut delegatee_account_vec.as_bytes_ref()).unwrap(); let mut delegates: Vec<(DelegateInfo, Compact)> = Vec::new(); - for delegate in - as IterableStorageMap>::iter_keys() - { + for delegate in as IterableStorageMap>::iter_keys() { let staked_to_this_delegatee = Self::get_stake_for_coldkey_and_hotkey(&delegatee.clone(), &delegate.clone()); if staked_to_this_delegatee == 0 { diff --git a/pallets/subtensor/src/math.rs b/pallets/subtensor/src/math.rs index be6decb25..2b69f38cc 100644 --- a/pallets/subtensor/src/math.rs +++ b/pallets/subtensor/src/math.rs @@ -1224,7 +1224,9 @@ mod tests { let target: Vec = vec![65535, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); - let vector: Vec = vec_to_fixed(&[0.000001, 0.000006, 0.000007, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4]); + let vector: Vec = vec_to_fixed(&[ + 0.000001, 0.000006, 0.000007, 0.0001, 0.001, 0.01, 0.1, 0.2, 0.3, 0.4, + ]); let target: Vec = vec![0, 1, 1, 16, 164, 1638, 16384, 32768, 49151, 65535]; let result: Vec = vec_max_upscale_to_u16(&vector); assert_vec_compare_u16(&result, &target); @@ -1618,25 +1620,29 @@ mod tests { .iter() .map(|t: &I32F32| sigmoid_safe(*t, I32F32::max_value(), I32F32::max_value())) .collect(); - let target: Vec = vec_to_fixed(&[0.0000000019, + let target: Vec = vec_to_fixed(&[ 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, - 0.5]); + 0.0000000019, + 0.5, + ]); assert_eq!(&consensus, &target); let consensus: Vec = trust .iter() .map(|t: &I32F32| sigmoid_safe(*t, I32F32::min_value(), I32F32::min_value())) .collect(); - let target: Vec = vec_to_fixed(&[0.5, + let target: Vec = vec_to_fixed(&[ + 0.5, + 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, 0.0000000019, - 0.0000000019]); + ]); assert_eq!(&consensus, &target); let consensus: Vec = trust .iter() @@ -1710,8 +1716,7 @@ mod tests { true, false, true, false, true, false, true, false, true, false, ]; assert_eq!(&result, &target); - let vector: Vec = - vec_to_fixed(&[0.9, 0., 0.8, 0.1, 0.7, 0.2, 0.6, 0.3, 0.5, 0.4]); + let vector: Vec = vec_to_fixed(&[0.9, 0., 0.8, 0.1, 0.7, 0.2, 0.6, 0.3, 0.5, 0.4]); let result = is_topk(&vector, 5); let target: Vec = vec![ true, false, true, false, true, false, true, false, true, false, @@ -2677,7 +2682,9 @@ mod tests { ); let n: usize = 100; - for majority in vec_to_fixed(&[0., 0.0000001, 0.25, 0.49, 0.49, 0.49, 0.5, 0.51, 0.51, 0.51, 0.9999999, 1.]) { + for majority in vec_to_fixed(&[ + 0., 0.0000001, 0.25, 0.49, 0.49, 0.49, 0.5, 0.51, 0.51, 0.51, 0.9999999, 1., + ]) { for allow_equal in [false, true] { let mut stake: Vec = vec![]; let mut score: Vec = vec![]; diff --git a/pallets/subtensor/src/root.rs b/pallets/subtensor/src/root.rs index cf049b74f..b4e9ae8b2 100644 --- a/pallets/subtensor/src/root.rs +++ b/pallets/subtensor/src/root.rs @@ -681,8 +681,7 @@ impl Pallet { }; // --- 5. Perform the lock operation. - let actual_lock_amount = - Self::remove_balance_from_coldkey_account(&coldkey, lock_amount)?; + let actual_lock_amount = Self::remove_balance_from_coldkey_account(&coldkey, lock_amount)?; Self::set_subnet_locked_balance(netuid_to_register, actual_lock_amount); Self::set_network_last_lock(actual_lock_amount); diff --git a/pallets/subtensor/src/stake_info.rs b/pallets/subtensor/src/stake_info.rs index 8e3939766..b6f0fd38e 100644 --- a/pallets/subtensor/src/stake_info.rs +++ b/pallets/subtensor/src/stake_info.rs @@ -56,8 +56,6 @@ impl Pallet { return Vec::new(); // Invalid coldkey } - - Self::_get_stake_info_for_coldkeys(coldkeys) } @@ -71,7 +69,7 @@ impl Pallet { let stake_info = Self::_get_stake_info_for_coldkeys(vec![coldkey]); if stake_info.is_empty() { - Vec::new()// Invalid coldkey + Vec::new() // Invalid coldkey } else { return stake_info.first().unwrap().1.clone(); } diff --git a/pallets/subtensor/src/uids.rs b/pallets/subtensor/src/uids.rs index 822b04540..88c5b0e09 100644 --- a/pallets/subtensor/src/uids.rs +++ b/pallets/subtensor/src/uids.rs @@ -109,8 +109,7 @@ impl Pallet { netuid: u16, hotkey: &T::AccountId, ) -> Result { - Uids::::try_get(netuid, hotkey) - .map_err(|_err| Error::::NotRegistered.into()) + Uids::::try_get(netuid, hotkey).map_err(|_err| Error::::NotRegistered.into()) } // Returns the stake of the uid on network or 0 if it doesnt exist. diff --git a/pallets/subtensor/src/utils.rs b/pallets/subtensor/src/utils.rs index a39589176..91b2d0b26 100644 --- a/pallets/subtensor/src/utils.rs +++ b/pallets/subtensor/src/utils.rs @@ -138,8 +138,17 @@ impl Pallet { pub fn set_target_stakes_per_interval(target_stakes_per_interval: u64) { TargetStakesPerInterval::::set(target_stakes_per_interval) } - pub fn set_stakes_this_interval_for_coldkey_hotkey(coldkey: &T::AccountId, hotkey: &T::AccountId, stakes_this_interval: u64, last_staked_block_number: u64) { - TotalHotkeyColdkeyStakesThisInterval::::insert(coldkey, hotkey, (stakes_this_interval, last_staked_block_number)); + pub fn set_stakes_this_interval_for_coldkey_hotkey( + coldkey: &T::AccountId, + hotkey: &T::AccountId, + stakes_this_interval: u64, + last_staked_block_number: u64, + ) { + TotalHotkeyColdkeyStakesThisInterval::::insert( + coldkey, + hotkey, + (stakes_this_interval, last_staked_block_number), + ); } pub fn set_stake_interval(block: u64) { StakeInterval::::set(block); @@ -300,7 +309,7 @@ impl Pallet { pub fn burn_tokens(amount: u64) { TotalIssuance::::put(TotalIssuance::::get().saturating_sub(amount)); } - pub fn coinbase(amount: u64 ){ + pub fn coinbase(amount: u64) { TotalIssuance::::put(TotalIssuance::::get().saturating_add(amount)); } pub fn get_default_take() -> u16 { From c933675a9edd05d6613873e4061ffe66b3bc7d6b Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 28 Apr 2024 12:51:38 +0400 Subject: [PATCH 13/13] ci: remove redundant job --- .github/workflows/check-rust.yml | 54 -------------------------------- 1 file changed, 54 deletions(-) diff --git a/.github/workflows/check-rust.yml b/.github/workflows/check-rust.yml index 4c56233f8..b1c36057d 100644 --- a/.github/workflows/check-rust.yml +++ b/.github/workflows/check-rust.yml @@ -218,60 +218,6 @@ jobs: - name: cargo test --workspace --features=runtime-benchmarks run: cargo test --workspace --features=runtime-benchmarks - # runs cargo clippy - clippy: - name: cargo clippy - runs-on: SubtensorCI - strategy: - matrix: - rust-branch: - - nightly-2024-03-05 - rust-target: - - x86_64-unknown-linux-gnu - # - x86_64-apple-darwin - os: - - ubuntu-latest - # - macos-latest - include: - - os: ubuntu-latest - # - os: macos-latest - env: - RELEASE_NAME: development - # RUSTFLAGS: -A warnings - RUSTV: ${{ matrix.rust-branch }} - RUST_BACKTRACE: full - RUST_BIN_DIR: target/${{ matrix.rust-target }} - SKIP_WASM_BUILD: 1 - TARGET: ${{ matrix.rust-target }} - steps: - - name: Check-out repository under $GITHUB_WORKSPACE - uses: actions/checkout@v2 - - - name: Install dependencies - run: | - sudo apt-get update && - sudo apt-get install -y clang curl libssl-dev llvm libudev-dev protobuf-compiler - - - name: Install Rust ${{ matrix.rust-branch }} - uses: actions-rs/toolchain@v1.0.6 - with: - toolchain: ${{ matrix.rust-branch }} - components: rustfmt, clippy - profile: minimal - - - name: Utilize Rust shared cached - uses: Swatinem/rust-cache@v2.2.1 - with: - key: ${{ matrix.os }}-${{ env.RUST_BIN_DIR }} - - - name: cargo clippy - run: | - cargo clippy -- -D clippy::panic \ - -D clippy::todo \ - -D clippy::unimplemented - # -D clippy::indexing_slicing \ - # -D clippy::unwrap_used \ - # ensures cargo fix has no trivial changes that can be applied cargo-fix: name: cargo fix