diff --git a/Cargo.toml b/Cargo.toml index 1d1a144bd9..4eb8a2f9b9 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -40,6 +40,7 @@ edition = "2024" [workspace.lints.clippy] arithmetic-side-effects = "deny" +expect-used = "deny" indexing-slicing = "deny" manual_inspect = "allow" result_large_err = "allow" diff --git a/node/src/benchmarking.rs b/node/src/benchmarking.rs index ad2abfc935..4acece56f4 100644 --- a/node/src/benchmarking.rs +++ b/node/src/benchmarking.rs @@ -105,6 +105,7 @@ impl frame_benchmarking_cli::ExtrinsicBuilder for TransferKeepAliveBuilder { // Create a transaction using the given `call`. // // Note: Should only be used for benchmarking. +#[allow(clippy::expect_used)] pub fn create_benchmark_extrinsic( client: &FullClient, sender: sp_core::sr25519::Pair, diff --git a/node/src/chain_spec/mod.rs b/node/src/chain_spec/mod.rs index 733f416e69..90a1493aa4 100644 --- a/node/src/chain_spec/mod.rs +++ b/node/src/chain_spec/mod.rs @@ -1,5 +1,5 @@ // Allowed since it's actually better to panic during chain setup when there is an error -#![allow(clippy::unwrap_used)] +#![allow(clippy::expect_used, clippy::unwrap_used)] pub mod devnet; pub mod finney; diff --git a/node/src/command.rs b/node/src/command.rs index 31e31a1196..67cb200e43 100644 --- a/node/src/command.rs +++ b/node/src/command.rs @@ -245,6 +245,7 @@ pub fn run() -> sc_cli::Result<()> { } } +#[allow(clippy::expect_used)] fn start_babe_service(arg_matches: &ArgMatches) -> Result<(), sc_cli::Error> { let cli = Cli::from_arg_matches(arg_matches).expect("Bad arg_matches"); let runner = cli.create_runner(&cli.run)?; @@ -281,6 +282,7 @@ fn start_babe_service(arg_matches: &ArgMatches) -> Result<(), sc_cli::Error> { } } +#[allow(clippy::expect_used)] fn start_aura_service(arg_matches: &ArgMatches) -> Result<(), sc_cli::Error> { let cli = Cli::from_arg_matches(arg_matches).expect("Bad arg_matches"); let runner = cli.create_runner(&cli.run)?; @@ -313,6 +315,7 @@ fn start_aura_service(arg_matches: &ArgMatches) -> Result<(), sc_cli::Error> { } } +#[allow(clippy::expect_used)] fn customise_config(arg_matches: &ArgMatches, config: Configuration) -> Configuration { let cli = Cli::from_arg_matches(arg_matches).expect("Bad arg_matches"); diff --git a/node/src/consensus/babe_consensus.rs b/node/src/consensus/babe_consensus.rs index 8a848ff408..8c9a974d20 100644 --- a/node/src/consensus/babe_consensus.rs +++ b/node/src/consensus/babe_consensus.rs @@ -44,6 +44,7 @@ impl ConsensusMechanism for BabeConsensus { sp_timestamp::InherentDataProvider, ); + #[allow(clippy::expect_used)] fn start_authoring( self, task_manager: &mut TaskManager, diff --git a/node/src/consensus/hybrid_import_queue.rs b/node/src/consensus/hybrid_import_queue.rs index 5d2a1e9162..30d8ff4065 100644 --- a/node/src/consensus/hybrid_import_queue.rs +++ b/node/src/consensus/hybrid_import_queue.rs @@ -77,6 +77,7 @@ impl HybridBlockImport { FrontierBlockImport::new(grandpa_block_import.clone(), client.clone()), ); + #[allow(clippy::expect_used)] let (babe_import, babe_link) = sc_consensus_babe::block_import( babe_config, grandpa_block_import.clone(), diff --git a/node/src/service.rs b/node/src/service.rs index 8670c277a2..2ef1904f08 100644 --- a/node/src/service.rs +++ b/node/src/service.rs @@ -60,6 +60,7 @@ pub type BIQ<'a> = Box< + 'a, >; +#[allow(clippy::expect_used)] pub fn new_partial( config: &Configuration, eth_config: &EthConfiguration, @@ -250,6 +251,7 @@ pub fn build_manual_seal_import_queue( } /// Builds a new service for a full client. +#[allow(clippy::expect_used)] pub async fn new_full( mut config: Configuration, eth_config: EthConfiguration, diff --git a/pallets/admin-utils/src/lib.rs b/pallets/admin-utils/src/lib.rs index a18150ec86..66e7eab318 100644 --- a/pallets/admin-utils/src/lib.rs +++ b/pallets/admin-utils/src/lib.rs @@ -18,6 +18,7 @@ mod tests; #[deny(missing_docs)] #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; use frame_support::pallet_prelude::*; @@ -162,6 +163,8 @@ pub mod pallet { /// Dispatchable functions allows users to interact with the pallet and invoke state changes. #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// The extrinsic sets the new authorities for Aura consensus. /// It is only callable by the root account. /// The extrinsic will call the Aura pallet to change the authorities. diff --git a/pallets/collective/src/benchmarking.rs b/pallets/collective/src/benchmarking.rs index dcca9dd3b0..ec5c736614 100644 --- a/pallets/collective/src/benchmarking.rs +++ b/pallets/collective/src/benchmarking.rs @@ -16,7 +16,11 @@ // limitations under the License. //! Staking pallet benchmarking. -#![allow(clippy::arithmetic_side_effects, clippy::indexing_slicing)] +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::indexing_slicing +)] use super::*; use crate::Pallet as Collective; diff --git a/pallets/collective/src/lib.rs b/pallets/collective/src/lib.rs index e964a28539..8a9fc09fb5 100644 --- a/pallets/collective/src/lib.rs +++ b/pallets/collective/src/lib.rs @@ -179,6 +179,7 @@ pub struct Votes { #[deny(missing_docs)] #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; use frame_system::pallet_prelude::*; @@ -397,6 +398,8 @@ pub mod pallet { // Note that councillor operations are assigned to the operational class. #[pallet::call] impl, I: 'static> Pallet { + #![deny(clippy::expect_used)] + /// Set the collective's membership. /// /// - `new_members`: The new member list. Be nice to the chain and provide it sorted. @@ -1128,6 +1131,7 @@ impl< } #[cfg(feature = "runtime-benchmarks")] + #[allow(clippy::expect_used)] fn try_successful_origin() -> Result { let zero_account_id = AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) diff --git a/pallets/collective/src/tests.rs b/pallets/collective/src/tests.rs index d447384746..5c39c3d2f4 100644 --- a/pallets/collective/src/tests.rs +++ b/pallets/collective/src/tests.rs @@ -15,7 +15,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -#![allow(non_camel_case_types, clippy::indexing_slicing, clippy::unwrap_used)] +#![allow( + non_camel_case_types, + clippy::expect_used, + clippy::indexing_slicing, + clippy::unwrap_used +)] use super::{Event as CollectiveEvent, *}; use crate as pallet_collective; diff --git a/pallets/commitments/src/benchmarking.rs b/pallets/commitments/src/benchmarking.rs index d09083f749..d385c6f57f 100644 --- a/pallets/commitments/src/benchmarking.rs +++ b/pallets/commitments/src/benchmarking.rs @@ -1,6 +1,6 @@ //! Benchmarking setup #![cfg(feature = "runtime-benchmarks")] -#![allow(clippy::arithmetic_side_effects)] +#![allow(clippy::arithmetic_side_effects, clippy::expect_used)] use super::*; #[allow(unused)] diff --git a/pallets/commitments/src/lib.rs b/pallets/commitments/src/lib.rs index f61ecf22a6..a627220f76 100644 --- a/pallets/commitments/src/lib.rs +++ b/pallets/commitments/src/lib.rs @@ -37,6 +37,7 @@ type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; #[deny(missing_docs)] #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; use frame_support::{pallet_prelude::*, traits::ReservableCurrency}; @@ -204,6 +205,8 @@ pub mod pallet { #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// Set the commitment for a given netuid #[pallet::call_index(0)] #[pallet::weight(( diff --git a/pallets/commitments/src/mock.rs b/pallets/commitments/src/mock.rs index 9b6f6b034a..24e259b23c 100644 --- a/pallets/commitments/src/mock.rs +++ b/pallets/commitments/src/mock.rs @@ -1,3 +1,4 @@ +#![allow(clippy::expect_used)] use crate as pallet_commitments; use frame_support::{ derive_impl, diff --git a/pallets/commitments/src/tests.rs b/pallets/commitments/src/tests.rs index 5f19070ea2..9270a84bb7 100644 --- a/pallets/commitments/src/tests.rs +++ b/pallets/commitments/src/tests.rs @@ -1,3 +1,5 @@ +#![allow(clippy::expect_used, clippy::indexing_slicing)] + use codec::Encode; use sp_std::prelude::*; use subtensor_runtime_common::NetUid; @@ -19,7 +21,6 @@ use frame_support::{ }; use frame_system::{Pallet as System, RawOrigin}; -#[allow(clippy::indexing_slicing)] #[test] fn manual_data_type_info() { let mut registry = scale_info::Registry::new(); diff --git a/pallets/commitments/src/types.rs b/pallets/commitments/src/types.rs index 0467fee8f3..cdca47922b 100644 --- a/pallets/commitments/src/types.rs +++ b/pallets/commitments/src/types.rs @@ -100,7 +100,7 @@ impl Decode for Data { n @ 1..=129 => { let mut r: BoundedVec<_, _> = vec![0u8; (n as usize).saturating_sub(1)] .try_into() - .expect("bound checked in match arm condition; qed"); + .map_err(|_| codec::Error::from("bound checked in match arm condition; qed"))?; input.read(&mut r[..])?; Data::Raw(r) } diff --git a/pallets/crowdloan/src/lib.rs b/pallets/crowdloan/src/lib.rs index aa3d4950bc..52ea3bd166 100644 --- a/pallets/crowdloan/src/lib.rs +++ b/pallets/crowdloan/src/lib.rs @@ -88,6 +88,7 @@ pub type CrowdloanInfoOf = CrowdloanInfo< >; #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; @@ -285,6 +286,8 @@ pub mod pallet { #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// Create a crowdloan that will raise funds up to a maximum cap and if successful, /// will transfer funds to the target address if provided and dispatch the call /// (using creator origin). diff --git a/pallets/crowdloan/src/mock.rs b/pallets/crowdloan/src/mock.rs index d96069c05e..fa2f5533d2 100644 --- a/pallets/crowdloan/src/mock.rs +++ b/pallets/crowdloan/src/mock.rs @@ -1,5 +1,9 @@ #![cfg(test)] -#![allow(clippy::arithmetic_side_effects, clippy::unwrap_used)] +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::unwrap_used +)] use frame_support::{ PalletId, derive_impl, parameter_types, traits::{OnFinalize, OnInitialize, fungible, fungible::*, tokens::Preservation}, diff --git a/pallets/proxy/src/benchmarking.rs b/pallets/proxy/src/benchmarking.rs index 8b1f5ababf..9a759e1846 100644 --- a/pallets/proxy/src/benchmarking.rs +++ b/pallets/proxy/src/benchmarking.rs @@ -18,7 +18,7 @@ // Benchmarks for Proxy Pallet #![cfg(feature = "runtime-benchmarks")] -#![allow(clippy::arithmetic_side_effects)] +#![allow(clippy::arithmetic_side_effects, clippy::unwrap_used)] use super::*; use crate::Pallet as Proxy; @@ -321,7 +321,8 @@ mod benchmarks { 0, ); - let pure_account = Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None); + let pure_account = + Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None).unwrap(); assert_last_event::( Event::PureCreated { pure: pure_account, @@ -348,7 +349,8 @@ mod benchmarks { )?; let height = T::BlockNumberProvider::current_block_number(); let ext_index = frame_system::Pallet::::extrinsic_index().unwrap_or(0); - let pure_account = Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None); + let pure_account = + Pallet::::pure_account(&caller, &T::ProxyType::default(), 0, None).unwrap(); add_proxies::(p, Some(pure_account.clone()))?; ensure!( diff --git a/pallets/proxy/src/lib.rs b/pallets/proxy/src/lib.rs index 9fbb481591..93ac568668 100644 --- a/pallets/proxy/src/lib.rs +++ b/pallets/proxy/src/lib.rs @@ -113,6 +113,7 @@ pub enum DepositKind { } #[frame::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; @@ -215,6 +216,8 @@ pub mod pallet { #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// Dispatch the given `call` from an account that the sender is authorised for through /// `add_proxy`. /// @@ -333,7 +336,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; - let pure = Self::pure_account(&who, &proxy_type, index, None); + let pure = Self::pure_account(&who, &proxy_type, index, None)?; ensure!(!Proxies::::contains_key(&pure), Error::::Duplicate); let proxy_def = ProxyDefinition { @@ -389,7 +392,7 @@ pub mod pallet { let spawner = T::Lookup::lookup(spawner)?; let when = (height, ext_index); - let proxy = Self::pure_account(&spawner, &proxy_type, index, Some(when)); + let proxy = Self::pure_account(&spawner, &proxy_type, index, Some(when))?; ensure!(proxy == who, Error::::NoPermission); let (_, deposit) = Proxies::::take(&who); @@ -445,24 +448,24 @@ pub mod pallet { pending .try_push(announcement) .map_err(|_| Error::::TooMany)?; - Self::rejig_deposit( + let new_deposit = Self::rejig_deposit( &who, *deposit, T::AnnouncementDepositBase::get(), T::AnnouncementDepositFactor::get(), pending.len(), - ) - .map(|d| { - d.expect("Just pushed; pending.len() > 0; rejig_deposit returns Some; qed") - }) - .map(|d| *deposit = d) + )? + .ok_or(Error::::AnnouncementDepositInvariantViolated)?; + + *deposit = new_deposit; + Ok::<(), DispatchError>(()) })?; + Self::deposit_event(Event::Announced { real, proxy: who, call_hash, }); - Ok(()) } @@ -743,6 +746,10 @@ pub mod pallet { Unannounced, /// Cannot add self as proxy. NoSelfProxy, + /// Invariant violated: deposit recomputation returned None after updating announcements. + AnnouncementDepositInvariantViolated, + /// Failed to derive a valid account id from the provided entropy. + InvalidDerivedAccountId, } /// The set of account proxies. Maps the account which has delegated to the accounts @@ -829,7 +836,7 @@ impl Pallet { proxy_type: &T::ProxyType, index: u16, maybe_when: Option<(BlockNumberFor, u32)>, - ) -> T::AccountId { + ) -> Result { let (height, ext_index) = maybe_when.unwrap_or_else(|| { ( T::BlockNumberProvider::current_block_number(), @@ -845,8 +852,9 @@ impl Pallet { index, ) .using_encoded(blake2_256); - Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) - .expect("infinite length input; no invalid inputs for type; qed") + + T::AccountId::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .map_err(|_| Error::::InvalidDerivedAccountId.into()) } /// Register a proxy account for the delegator that is able to make calls on its behalf. diff --git a/pallets/proxy/src/tests.rs b/pallets/proxy/src/tests.rs index e7e729318c..ea64aef030 100644 --- a/pallets/proxy/src/tests.rs +++ b/pallets/proxy/src/tests.rs @@ -494,7 +494,7 @@ fn filtering_works() { .into(), ); - let derivative_id = Utility::derivative_account_id(1, 0); + let derivative_id = Utility::derivative_account_id(1, 0).unwrap(); Balances::make_free_balance_be(&derivative_id, 1000); let inner = Box::new(call_transfer(6, 1)); @@ -876,7 +876,7 @@ fn pure_works() { 0, 0 )); - let anon = Proxy::pure_account(&1, &ProxyType::Any, 0, None); + let anon = Proxy::pure_account(&1, &ProxyType::Any, 0, None).unwrap(); System::assert_last_event( ProxyEvent::PureCreated { pure: anon, @@ -900,7 +900,7 @@ fn pure_works() { 0, 1 )); - let anon2 = Proxy::pure_account(&2, &ProxyType::Any, 0, None); + let anon2 = Proxy::pure_account(&2, &ProxyType::Any, 0, None).unwrap(); assert_ok!(Proxy::create_pure( RuntimeOrigin::signed(2), ProxyType::Any, diff --git a/pallets/registry/src/benchmarking.rs b/pallets/registry/src/benchmarking.rs index f75ff1726e..7a008a4e40 100644 --- a/pallets/registry/src/benchmarking.rs +++ b/pallets/registry/src/benchmarking.rs @@ -1,6 +1,10 @@ //! Benchmarking setup #![cfg(feature = "runtime-benchmarks")] -#![allow(clippy::arithmetic_side_effects, clippy::unwrap_used)] +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::unwrap_used +)] use super::*; #[allow(unused)] diff --git a/pallets/registry/src/lib.rs b/pallets/registry/src/lib.rs index 87f164c3e1..9d52e691ef 100644 --- a/pallets/registry/src/lib.rs +++ b/pallets/registry/src/lib.rs @@ -22,6 +22,7 @@ type BalanceOf = <::Currency as fungible::Inspect<::AccountId>>::Balance; #[deny(missing_docs)] #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; use frame_support::{pallet_prelude::*, traits::tokens::fungible}; @@ -107,6 +108,8 @@ pub mod pallet { #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// Register an identity for an account. This will overwrite any existing identity. #[pallet::call_index(0)] #[pallet::weight(( diff --git a/pallets/registry/src/types.rs b/pallets/registry/src/types.rs index eb19e145d6..0e5cbe3332 100644 --- a/pallets/registry/src/types.rs +++ b/pallets/registry/src/types.rs @@ -71,7 +71,7 @@ impl Decode for Data { n @ 1..=65 => { let mut r: BoundedVec<_, _> = vec![0u8; (n as usize).saturating_sub(1)] .try_into() - .expect("bound checked in match arm condition; qed"); + .map_err(|_| codec::Error::from("bounded vec length exceeds limit"))?; input.read(&mut r[..])?; Data::Raw(r) } diff --git a/pallets/subtensor/src/epoch/run_epoch.rs b/pallets/subtensor/src/epoch/run_epoch.rs index 8c6a77c98b..04e1db9413 100644 --- a/pallets/subtensor/src/epoch/run_epoch.rs +++ b/pallets/subtensor/src/epoch/run_epoch.rs @@ -1169,12 +1169,17 @@ impl Pallet { Bonds::::iter_prefix(netuid_index).filter(|(uid_i, _)| *uid_i < n as u16) { for (uid_j, bonds_ij) in bonds_vec { - bonds - .get_mut(uid_i as usize) - .expect("uid_i is filtered to be less than n; qed") - .push((uid_j, u16_to_fixed(bonds_ij))); + if let Some(row) = bonds.get_mut(uid_i as usize) { + row.push((uid_j, u16_to_fixed(bonds_ij))); + } else { + // If the index is unexpectedly out of bounds, skip and log math error + log::error!( + "math error: bonds row index out of bounds (uid_i={uid_i}, n={n}, netuid_index={netuid_index})", + ); + } } } + bonds } @@ -1187,14 +1192,22 @@ impl Pallet { Bonds::::iter_prefix(netuid_index).filter(|(uid_i, _)| *uid_i < n as u16) { for (uid_j, bonds_ij) in bonds_vec.into_iter().filter(|(uid_j, _)| *uid_j < n as u16) { - *bonds - .get_mut(uid_i as usize) - .expect("uid_i has been filtered to be less than n; qed") - .get_mut(uid_j as usize) - .expect("uid_j has been filtered to be less than n; qed") = - u16_to_fixed(bonds_ij); + if let Some(row) = bonds.get_mut(uid_i as usize) { + if let Some(cell) = row.get_mut(uid_j as usize) { + *cell = u16_to_fixed(bonds_ij); + } else { + log::error!( + "math error: uid_j index out of bounds (uid_i={uid_i}, uid_j={uid_j}, n={n}, netuid_index={netuid_index})" + ); + } + } else { + log::error!( + "math error: uid_i row index out of bounds (uid_i={uid_i}, n={n}, netuid_index={netuid_index})" + ); + } } } + bonds } diff --git a/pallets/subtensor/src/lib.rs b/pallets/subtensor/src/lib.rs index ae463d1ed4..c52c589ad6 100644 --- a/pallets/subtensor/src/lib.rs +++ b/pallets/subtensor/src/lib.rs @@ -63,6 +63,7 @@ pub const MAX_CRV3_COMMIT_SIZE_BYTES: u32 = 5000; #[import_section(hooks::hooks)] #[import_section(config::config)] #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use crate::RateLimitKey; use crate::migrations; @@ -415,6 +416,7 @@ pub mod pallet { #[pallet::type_value] /// Default account, derived from zero trailing bytes. pub fn DefaultAccount() -> T::AccountId { + #[allow(clippy::expect_used)] T::AccountId::decode(&mut TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed") } @@ -588,6 +590,7 @@ pub mod pallet { #[pallet::type_value] /// Default value for subnet owner. pub fn DefaultSubnetOwner() -> T::AccountId { + #[allow(clippy::expect_used)] T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed") } @@ -749,6 +752,7 @@ pub mod pallet { #[pallet::type_value] /// Default value for key with type T::AccountId derived from trailing zeroes. pub fn DefaultKey() -> T::AccountId { + #[allow(clippy::expect_used)] T::AccountId::decode(&mut sp_runtime::traits::TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed") } @@ -873,6 +877,7 @@ pub mod pallet { #[pallet::type_value] /// Default value for coldkey swap scheduled pub fn DefaultColdkeySwapScheduled() -> (BlockNumberFor, T::AccountId) { + #[allow(clippy::expect_used)] let default_account = T::AccountId::decode(&mut TrailingZeroInput::zeroes()) .expect("trailing zeroes always produce a valid account ID; qed"); (BlockNumberFor::::from(0_u32), default_account) @@ -2145,6 +2150,7 @@ impl CollectiveInterface for () { pub struct TaoCurrencyReserve(PhantomData); impl CurrencyReserve for TaoCurrencyReserve { + #![deny(clippy::expect_used)] fn reserve(netuid: NetUid) -> TaoCurrency { SubnetTAO::::get(netuid).saturating_add(SubnetTaoProvided::::get(netuid)) } @@ -2162,6 +2168,7 @@ impl CurrencyReserve for TaoCurrencyReserve { pub struct AlphaCurrencyReserve(PhantomData); impl CurrencyReserve for AlphaCurrencyReserve { + #![deny(clippy::expect_used)] fn reserve(netuid: NetUid) -> AlphaCurrency { SubnetAlphaIn::::get(netuid).saturating_add(SubnetAlphaInProvided::::get(netuid)) } @@ -2183,6 +2190,7 @@ pub type GetTaoForAlpha = impl> subtensor_runtime_common::SubnetInfo for Pallet { + #![deny(clippy::expect_used)] fn exists(netuid: NetUid) -> bool { Self::if_subnet_exist(netuid) } @@ -2215,6 +2223,7 @@ impl> impl> subtensor_runtime_common::BalanceOps for Pallet { + #![deny(clippy::expect_used)] fn tao_balance(account_id: &T::AccountId) -> TaoCurrency { pallet_balances::Pallet::::free_balance(account_id).into() } diff --git a/pallets/subtensor/src/macros/dispatches.rs b/pallets/subtensor/src/macros/dispatches.rs index 839cbfeac7..78874b9f43 100644 --- a/pallets/subtensor/src/macros/dispatches.rs +++ b/pallets/subtensor/src/macros/dispatches.rs @@ -18,6 +18,8 @@ mod dispatches { /// Dispatchable functions must be annotated with a weight and must return a DispatchResult. #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// --- Sets the caller weights for the incentive mechanism. The call can be /// made from the hotkey account so is potentially insecure, however, the damage /// of changing weights is minimal if caught early. This function includes all the diff --git a/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs b/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs index cf9b1fdf07..11711a9184 100644 --- a/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs +++ b/pallets/subtensor/src/migrations/migrate_transfer_ownership_to_foundation.rs @@ -5,7 +5,7 @@ use frame_support::{ traits::{GetStorageVersion, StorageVersion}, weights::Weight, }; -use log::info; +use log::{error, info}; use sp_core::Get; use sp_std::vec::Vec; use subtensor_runtime_common::NetUid; @@ -41,7 +41,7 @@ pub mod deprecated_loaded_emission_format { pub fn migrate_transfer_ownership_to_foundation(coldkey: [u8; 32]) -> Weight { let new_storage_version = 3; - // Initialize weight counter + // Start with one read (on-chain storage version). let mut weight = T::DbWeight::get().reads(1); // Get current on-chain storage version @@ -54,10 +54,14 @@ pub fn migrate_transfer_ownership_to_foundation(coldkey: [u8; 32]) -> "Migrating subnet 1 and 11 to foundation control. Current version: {onchain_version:?}" ); - // Decode the foundation's coldkey into an AccountId - // TODO: Consider error handling for decoding failure - let coldkey_account: T::AccountId = T::AccountId::decode(&mut &coldkey[..]) - .expect("coldkey should be a valid 32-byte array"); + // Decode the foundation's coldkey into an AccountId — if it fails, log and abort migration. + let Ok(coldkey_account) = T::AccountId::decode(&mut &coldkey[..]) else { + error!( + target: LOG_TARGET, + "migration error: failed to decode foundation coldkey from 32 bytes" + ); + return weight; + }; info!(target: LOG_TARGET, "Foundation coldkey: {coldkey_account:?}"); // Get the current block number diff --git a/pallets/subtensor/src/subnets/leasing.rs b/pallets/subtensor/src/subnets/leasing.rs index a33c32e4ef..cf263a1335 100644 --- a/pallets/subtensor/src/subnets/leasing.rs +++ b/pallets/subtensor/src/subnets/leasing.rs @@ -87,8 +87,8 @@ impl Pallet { // Initialize the lease id, coldkey and hotkey and keep track of them let lease_id = Self::get_next_lease_id()?; - let lease_coldkey = Self::lease_coldkey(lease_id); - let lease_hotkey = Self::lease_hotkey(lease_id); + let lease_coldkey = Self::lease_coldkey(lease_id)?; + let lease_hotkey = Self::lease_hotkey(lease_id)?; frame_system::Pallet::::inc_providers(&lease_coldkey); frame_system::Pallet::::inc_providers(&lease_hotkey); @@ -341,16 +341,16 @@ impl Pallet { AccumulatedLeaseDividends::::insert(lease_id, AlphaCurrency::ZERO); } - fn lease_coldkey(lease_id: LeaseId) -> T::AccountId { + fn lease_coldkey(lease_id: LeaseId) -> Result { let entropy = ("leasing/coldkey", lease_id).using_encoded(blake2_256); - Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) - .expect("infinite length input; no invalid inputs for type; qed") + T::AccountId::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .map_err(|_| Error::::InvalidValue.into()) } - fn lease_hotkey(lease_id: LeaseId) -> T::AccountId { + fn lease_hotkey(lease_id: LeaseId) -> Result { let entropy = ("leasing/hotkey", lease_id).using_encoded(blake2_256); - Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) - .expect("infinite length input; no invalid inputs for type; qed") + T::AccountId::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .map_err(|_| Error::::InvalidValue.into()) } fn get_next_lease_id() -> Result> { diff --git a/pallets/subtensor/src/tests/consensus.rs b/pallets/subtensor/src/tests/consensus.rs index 7eb65c3fc0..454f41e2cf 100644 --- a/pallets/subtensor/src/tests/consensus.rs +++ b/pallets/subtensor/src/tests/consensus.rs @@ -1,5 +1,6 @@ #![allow( clippy::arithmetic_side_effects, + clippy::expect_used, clippy::indexing_slicing, clippy::unwrap_used )] diff --git a/pallets/subtensor/src/tests/delegate_info.rs b/pallets/subtensor/src/tests/delegate_info.rs index c7aabb899e..0553a88fe5 100644 --- a/pallets/subtensor/src/tests/delegate_info.rs +++ b/pallets/subtensor/src/tests/delegate_info.rs @@ -1,3 +1,4 @@ +#![allow(clippy::expect_used)] use super::mock::*; use codec::Compact; diff --git a/pallets/subtensor/src/tests/ensure.rs b/pallets/subtensor/src/tests/ensure.rs index 298339defa..a59bfd7484 100644 --- a/pallets/subtensor/src/tests/ensure.rs +++ b/pallets/subtensor/src/tests/ensure.rs @@ -1,3 +1,4 @@ +#![allow(clippy::expect_used)] use frame_support::{assert_noop, assert_ok}; use frame_system::Config; use sp_core::U256; diff --git a/pallets/subtensor/src/tests/epoch.rs b/pallets/subtensor/src/tests/epoch.rs index 4d8108ac29..a6e37fd15a 100644 --- a/pallets/subtensor/src/tests/epoch.rs +++ b/pallets/subtensor/src/tests/epoch.rs @@ -1,5 +1,6 @@ #![allow( clippy::arithmetic_side_effects, + clippy::expect_used, clippy::indexing_slicing, clippy::unwrap_used )] diff --git a/pallets/subtensor/src/tests/evm.rs b/pallets/subtensor/src/tests/evm.rs index 0e10262497..6d668d738d 100644 --- a/pallets/subtensor/src/tests/evm.rs +++ b/pallets/subtensor/src/tests/evm.rs @@ -1,5 +1,6 @@ #![allow( clippy::arithmetic_side_effects, + clippy::expect_used, clippy::unwrap_used, clippy::indexing_slicing )] diff --git a/pallets/subtensor/src/tests/mechanism.rs b/pallets/subtensor/src/tests/mechanism.rs index 8e5b1563d8..e5c46e8722 100644 --- a/pallets/subtensor/src/tests/mechanism.rs +++ b/pallets/subtensor/src/tests/mechanism.rs @@ -1,5 +1,6 @@ #![allow( clippy::arithmetic_side_effects, + clippy::expect_used, clippy::indexing_slicing, clippy::unwrap_used )] diff --git a/pallets/subtensor/src/tests/migration.rs b/pallets/subtensor/src/tests/migration.rs index 2d5ada4099..ede32aa06c 100644 --- a/pallets/subtensor/src/tests/migration.rs +++ b/pallets/subtensor/src/tests/migration.rs @@ -1,4 +1,10 @@ -#![allow(unused, clippy::indexing_slicing, clippy::panic, clippy::unwrap_used)] +#![allow( + unused, + clippy::expect_used, + clippy::indexing_slicing, + clippy::panic, + clippy::unwrap_used +)] use super::mock::*; use crate::*; diff --git a/pallets/subtensor/src/tests/mock.rs b/pallets/subtensor/src/tests/mock.rs index 7c731b604c..c5a58511ac 100644 --- a/pallets/subtensor/src/tests/mock.rs +++ b/pallets/subtensor/src/tests/mock.rs @@ -1,4 +1,8 @@ -#![allow(clippy::arithmetic_side_effects, clippy::unwrap_used)] +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::unwrap_used +)] use core::num::NonZeroU64; diff --git a/pallets/subtensor/src/tests/networks.rs b/pallets/subtensor/src/tests/networks.rs index 94069c633d..57875699b0 100644 --- a/pallets/subtensor/src/tests/networks.rs +++ b/pallets/subtensor/src/tests/networks.rs @@ -1,3 +1,5 @@ +#![allow(clippy::expect_used)] + use super::mock::*; use crate::migrations::migrate_network_immunity_period; use crate::*; diff --git a/pallets/subtensor/src/tests/serving.rs b/pallets/subtensor/src/tests/serving.rs index b4173a8ebb..d8a9b866d9 100644 --- a/pallets/subtensor/src/tests/serving.rs +++ b/pallets/subtensor/src/tests/serving.rs @@ -1,4 +1,4 @@ -#![allow(clippy::unwrap_used)] +#![allow(clippy::expect_used, clippy::unwrap_used)] use super::mock::*; use crate::Error; diff --git a/pallets/subtensor/src/tests/swap_coldkey.rs b/pallets/subtensor/src/tests/swap_coldkey.rs index b85d87c66b..4c683671ae 100644 --- a/pallets/subtensor/src/tests/swap_coldkey.rs +++ b/pallets/subtensor/src/tests/swap_coldkey.rs @@ -1,4 +1,10 @@ -#![allow(unused, clippy::indexing_slicing, clippy::panic, clippy::unwrap_used)] +#![allow( + unused, + clippy::expect_used, + clippy::indexing_slicing, + clippy::panic, + clippy::unwrap_used +)] use approx::assert_abs_diff_eq; use codec::Encode; diff --git a/pallets/subtensor/src/tests/uids.rs b/pallets/subtensor/src/tests/uids.rs index 4317337ffd..8fee5f7507 100644 --- a/pallets/subtensor/src/tests/uids.rs +++ b/pallets/subtensor/src/tests/uids.rs @@ -1,4 +1,4 @@ -#![allow(clippy::unwrap_used)] +#![allow(clippy::expect_used, clippy::unwrap_used)] use super::mock::*; use crate::*; diff --git a/pallets/subtensor/src/tests/weights.rs b/pallets/subtensor/src/tests/weights.rs index db7a8ee8d4..d703cb0840 100644 --- a/pallets/subtensor/src/tests/weights.rs +++ b/pallets/subtensor/src/tests/weights.rs @@ -1,4 +1,4 @@ -#![allow(clippy::indexing_slicing, clippy::unwrap_used)] +#![allow(clippy::expect_used, clippy::indexing_slicing, clippy::unwrap_used)] use ark_serialize::CanonicalDeserialize; use ark_serialize::CanonicalSerialize; diff --git a/pallets/subtensor/src/utils/try_state.rs b/pallets/subtensor/src/utils/try_state.rs index 4ade47eeef..ad5a8e9dc8 100644 --- a/pallets/subtensor/src/utils/try_state.rs +++ b/pallets/subtensor/src/utils/try_state.rs @@ -5,6 +5,7 @@ use super::*; impl Pallet { /// Checks [`TotalIssuance`] equals the sum of currency issuance, total stake, and total subnet /// locked. + #[allow(clippy::expect_used)] pub(crate) fn check_total_issuance() -> Result<(), sp_runtime::TryRuntimeError> { // Get the total currency issuance let currency_issuance = ::Currency::total_issuance(); diff --git a/pallets/swap/src/pallet/mod.rs b/pallets/swap/src/pallet/mod.rs index c8df6f262d..fc1894da7d 100644 --- a/pallets/swap/src/pallet/mod.rs +++ b/pallets/swap/src/pallet/mod.rs @@ -23,6 +23,7 @@ mod tests; #[allow(clippy::module_inception)] #[frame_support::pallet] +#[allow(clippy::expect_used)] mod pallet { use super::*; use frame_system::{ensure_root, ensure_signed}; @@ -280,6 +281,8 @@ mod pallet { #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// Set the fee rate for swaps on a specific subnet (normalized value). /// For example, 0.3% is approximately 196. /// diff --git a/pallets/swap/src/pallet/tests.rs b/pallets/swap/src/pallet/tests.rs index 88172c66ac..f793f8d332 100644 --- a/pallets/swap/src/pallet/tests.rs +++ b/pallets/swap/src/pallet/tests.rs @@ -1,6 +1,9 @@ -#![allow(clippy::unwrap_used)] -#![allow(clippy::indexing_slicing)] -#![allow(clippy::arithmetic_side_effects)] +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::indexing_slicing, + clippy::unwrap_used +)] use approx::assert_abs_diff_eq; use frame_support::{assert_err, assert_noop, assert_ok}; diff --git a/pallets/utility/src/lib.rs b/pallets/utility/src/lib.rs index cac7b0a1b1..b4dd0ca507 100644 --- a/pallets/utility/src/lib.rs +++ b/pallets/utility/src/lib.rs @@ -69,7 +69,10 @@ use frame_support::{ }; use sp_core::TypeId; use sp_io::hashing::blake2_256; -use sp_runtime::traits::{BadOrigin, Dispatchable, TrailingZeroInput}; +use sp_runtime::{ + DispatchError, + traits::{BadOrigin, Dispatchable, TrailingZeroInput}, +}; pub use weights::WeightInfo; use subtensor_macros::freeze_struct; @@ -77,6 +80,7 @@ use subtensor_macros::freeze_struct; pub use pallet::*; #[frame_support::pallet] +#[allow(clippy::expect_used)] pub mod pallet { use super::*; use frame_support::{dispatch::DispatchClass, pallet_prelude::*}; @@ -167,10 +171,14 @@ pub mod pallet { pub enum Error { /// Too many calls batched. TooManyCalls, + /// Bad input data for derived account ID + InvalidDerivedAccount, } #[pallet::call] impl Pallet { + #![deny(clippy::expect_used)] + /// Send a batch of dispatch calls. /// /// May be called from any origin except `None`. @@ -271,7 +279,7 @@ pub mod pallet { ) -> DispatchResultWithPostInfo { let mut origin = origin; let who = ensure_signed(origin.clone())?; - let pseudonym = Self::derivative_account_id(who, index); + let pseudonym = Self::derivative_account_id(who, index)?; origin.set_caller_from(frame_system::RawOrigin::Signed(pseudonym)); let info = call.get_dispatch_info(); let result = call.dispatch(origin); @@ -638,9 +646,12 @@ impl TypeId for IndexedUtilityPalletId { impl Pallet { /// Derive a derivative account ID from the owner account and the sub-account index. - pub fn derivative_account_id(who: T::AccountId, index: u16) -> T::AccountId { + pub fn derivative_account_id( + who: T::AccountId, + index: u16, + ) -> Result { let entropy = (b"modlpy/utilisuba", who, index).using_encoded(blake2_256); - Decode::decode(&mut TrailingZeroInput::new(entropy.as_ref())) - .expect("infinite length input; no invalid inputs for type; qed") + T::AccountId::decode(&mut TrailingZeroInput::new(entropy.as_ref())) + .map_err(|_| Error::::InvalidDerivedAccount.into()) } } diff --git a/pallets/utility/src/tests.rs b/pallets/utility/src/tests.rs index 09bb7192bc..8a3b198c4b 100644 --- a/pallets/utility/src/tests.rs +++ b/pallets/utility/src/tests.rs @@ -18,7 +18,11 @@ // Tests for Utility Pallet #![cfg(test)] -#![allow(clippy::arithmetic_side_effects, clippy::unwrap_used)] +#![allow( + clippy::arithmetic_side_effects, + clippy::expect_used, + clippy::unwrap_used +)] use super::*; @@ -302,7 +306,7 @@ fn utility_events() -> Vec { #[test] fn as_derivative_works() { new_test_ext().execute_with(|| { - let sub_1_0 = Utility::derivative_account_id(1, 0); + let sub_1_0 = Utility::derivative_account_id(1, 0).unwrap(); assert_ok!(Balances::transfer_allow_death( RuntimeOrigin::signed(1), sub_1_0, diff --git a/runtime/src/lib.rs b/runtime/src/lib.rs index 293de80de8..645d20523e 100644 --- a/runtime/src/lib.rs +++ b/runtime/src/lib.rs @@ -1297,8 +1297,7 @@ parameter_types! { pub const SwapMaxFeeRate: u16 = 10000; // 15.26% pub const SwapMaxPositions: u32 = 100; pub const SwapMinimumLiquidity: u64 = 1_000; - pub const SwapMinimumReserve: NonZeroU64 = NonZeroU64::new(1_000_000) - .expect("1_000_000 fits NonZeroU64"); + pub const SwapMinimumReserve: NonZeroU64 = unsafe { NonZeroU64::new_unchecked(1_000_000) }; } impl pallet_subtensor_swap::Config for Runtime { @@ -1526,6 +1525,7 @@ impl Default for TransactionConverter { } } +#[allow(clippy::expect_used)] impl fp_rpc::ConvertTransaction<::Extrinsic> for TransactionConverter { fn convert_transaction( &self, @@ -2293,6 +2293,7 @@ impl_runtime_apis! { (weight, BlockWeights::get().max_block) } + #[allow(clippy::expect_used)] fn execute_block( block: Block, state_root_check: bool, diff --git a/support/linting/src/forbid_as_primitive.rs b/support/linting/src/forbid_as_primitive.rs index 228b978ef2..5e01d0741c 100644 --- a/support/linting/src/forbid_as_primitive.rs +++ b/support/linting/src/forbid_as_primitive.rs @@ -49,6 +49,7 @@ mod tests { fn lint(input: proc_macro2::TokenStream) -> Result { let mut visitor = AsPrimitiveVisitor::default(); + #[allow(clippy::expect_used)] let expr: ExprMethodCall = syn::parse2(input).expect("should be a valid method call"); visitor.visit_expr_method_call(&expr); if !visitor.errors.is_empty() { diff --git a/support/linting/src/forbid_keys_remove.rs b/support/linting/src/forbid_keys_remove.rs index 204020fa22..163eeb703a 100644 --- a/support/linting/src/forbid_keys_remove.rs +++ b/support/linting/src/forbid_keys_remove.rs @@ -57,6 +57,7 @@ fn is_keys_remove_call(func: &Expr, args: &Punctuated) -> bool { #[cfg(test)] mod tests { + #![allow(clippy::expect_used)] use super::*; use quote::quote; diff --git a/support/linting/src/forbid_saturating_math.rs b/support/linting/src/forbid_saturating_math.rs index 9ad5385b36..02f99c0bcd 100644 --- a/support/linting/src/forbid_saturating_math.rs +++ b/support/linting/src/forbid_saturating_math.rs @@ -56,6 +56,7 @@ fn is_saturating_math_call(func: &Expr) -> bool { #[cfg(test)] mod tests { + #![allow(clippy::expect_used)] use super::*; use quote::quote; diff --git a/support/linting/src/require_freeze_struct.rs b/support/linting/src/require_freeze_struct.rs index a1d86109e4..b697c5b824 100644 --- a/support/linting/src/require_freeze_struct.rs +++ b/support/linting/src/require_freeze_struct.rs @@ -68,6 +68,7 @@ fn is_derive_encode_or_decode(attr: &Attribute) -> bool { #[cfg(test)] mod tests { + #![allow(clippy::expect_used)] use super::*; fn lint_struct(input: &str) -> Result {