diff --git a/substrate/bin/node-template/node/src/rpc.rs b/substrate/bin/node-template/node/src/rpc.rs index d23b23178e..7f3701b5ab 100644 --- a/substrate/bin/node-template/node/src/rpc.rs +++ b/substrate/bin/node-template/node/src/rpc.rs @@ -43,7 +43,7 @@ where io.extend_with(SystemApi::to_delegate(FullSystem::new(client.clone(), pool, deny_unsafe))); - io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client.clone()))); + io.extend_with(TransactionPaymentApi::to_delegate(TransactionPayment::new(client))); // Extend this RPC with a custom API by using the following syntax. // `YourRpcStruct` should have a reference to a client, which is needed diff --git a/substrate/bin/node-template/node/src/service.rs b/substrate/bin/node-template/node/src/service.rs index e2a8cb4ed8..5f46a16a96 100644 --- a/substrate/bin/node-template/node/src/service.rs +++ b/substrate/bin/node-template/node/src/service.rs @@ -82,7 +82,7 @@ pub fn new_partial( let (client, backend, keystore_container, task_manager) = sc_service::new_full_parts::( - &config, + config, telemetry.as_ref().map(|(_, telemetry)| telemetry.handle()), executor, )?; @@ -263,7 +263,7 @@ pub fn new_full(mut config: Configuration) -> Result let aura = sc_consensus_aura::start_aura::( StartAuraParams { slot_duration, - client: client.clone(), + client, select_chain, block_import, proposer_factory, diff --git a/substrate/bin/node-template/pallets/template/src/lib.rs b/substrate/bin/node-template/pallets/template/src/lib.rs index f5ce8c5a0f..067c7ce257 100644 --- a/substrate/bin/node-template/pallets/template/src/lib.rs +++ b/substrate/bin/node-template/pallets/template/src/lib.rs @@ -88,7 +88,7 @@ pub mod pallet { // Read a value from storage. match >::get() { // Return an error if the value has not been set. - None => Err(Error::::NoneValue)?, + None => return Err(Error::::NoneValue.into()), Some(old) => { // Increment the value read from storage; will error in the event of overflow. let new = old.checked_add(1).ok_or(Error::::StorageOverflow)?; diff --git a/substrate/bin/node-template/runtime/src/lib.rs b/substrate/bin/node-template/runtime/src/lib.rs index a7a162bf74..0145cacef8 100644 --- a/substrate/bin/node-template/runtime/src/lib.rs +++ b/substrate/bin/node-template/runtime/src/lib.rs @@ -478,7 +478,7 @@ impl_runtime_apis! { let storage_info = AllPalletsWithSystem::storage_info(); - return (list, storage_info) + (list, storage_info) } fn dispatch_benchmark( diff --git a/substrate/bin/node/bench/src/core.rs b/substrate/bin/node/bench/src/core.rs index b6ad3ecd80..3b3060a888 100644 --- a/substrate/bin/node/bench/src/core.rs +++ b/substrate/bin/node/bench/src/core.rs @@ -132,7 +132,7 @@ pub fn run_benchmark(benchmark: Box, mode: Mode) -> Be durations.push(duration.as_nanos()); } - durations.sort(); + durations.sort_unstable(); let raw_average = (durations.iter().sum::() / (durations.len() as u128)) as u64; let average = (durations.iter().skip(10).take(30).sum::() / 30) as u64; diff --git a/substrate/bin/node/bench/src/main.rs b/substrate/bin/node/bench/src/main.rs index 0e50447d46..d97c7af265 100644 --- a/substrate/bin/node/bench/src/main.rs +++ b/substrate/bin/node/bench/src/main.rs @@ -85,7 +85,7 @@ fn main() { let mut import_benchmarks = Vec::new(); - for profile in [Profile::Wasm, Profile::Native].iter() { + for profile in [Profile::Wasm, Profile::Native] { for size in [ SizeType::Empty, SizeType::Small, @@ -93,25 +93,14 @@ fn main() { SizeType::Large, SizeType::Full, SizeType::Custom(opt.transactions.unwrap_or(0)), - ] - .iter() - { + ] { for block_type in [ BlockType::RandomTransfersKeepAlive, BlockType::RandomTransfersReaping, BlockType::Noop, - ] - .iter() - { - for database_type in - [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb].iter() - { - import_benchmarks.push(( - profile, - size.clone(), - block_type.clone(), - database_type, - )); + ] { + for database_type in [BenchDataBaseType::RocksDb, BenchDataBaseType::ParityDb] { + import_benchmarks.push((profile, size, block_type, database_type)); } } } @@ -120,11 +109,11 @@ fn main() { let benchmarks = matrix!( (profile, size, block_type, database_type) in import_benchmarks.into_iter() => ImportBenchmarkDescription { - profile: *profile, + profile, key_types: KeyTypes::Sr25519, - size: size, - block_type: block_type, - database_type: *database_type, + size, + block_type, + database_type, }, (size, db_type) in [ diff --git a/substrate/bin/node/bench/src/state_sizes.rs b/substrate/bin/node/bench/src/state_sizes.rs index f97645423e..5387850666 100644 --- a/substrate/bin/node/bench/src/state_sizes.rs +++ b/substrate/bin/node/bench/src/state_sizes.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . /// Kusama value size distribution -pub const KUSAMA_STATE_DISTRIBUTION: &'static [(u32, u32)] = &[ +pub const KUSAMA_STATE_DISTRIBUTION: &[(u32, u32)] = &[ (32, 35), (33, 20035), (34, 5369), diff --git a/substrate/bin/node/bench/src/trie.rs b/substrate/bin/node/bench/src/trie.rs index 1b4534cbd0..0539c9ce11 100644 --- a/substrate/bin/node/bench/src/trie.rs +++ b/substrate/bin/node/bench/src/trie.rs @@ -282,7 +282,7 @@ impl core::Benchmark for TrieWriteBenchmark { let mut db = self.database.clone(); let kvdb = db.open(self.database_type); - let mut new_root = self.root.clone(); + let mut new_root = self.root; let mut overlay = HashMap::new(); let mut trie = SimpleTrie { db: kvdb.clone(), overlay: &mut overlay }; diff --git a/substrate/bin/node/cli/src/service.rs b/substrate/bin/node/cli/src/service.rs index 2742e7b113..01c7eb9abe 100644 --- a/substrate/bin/node/cli/src/service.rs +++ b/substrate/bin/node/cli/src/service.rs @@ -113,10 +113,10 @@ pub fn create_extrinsic( let signature = raw_payload.using_encoded(|e| sender.sign(e)); node_runtime::UncheckedExtrinsic::new_signed( - function.clone(), + function, sp_runtime::AccountId32::from(sender.public()).into(), - node_runtime::Signature::Sr25519(signature.clone()), - extra.clone(), + node_runtime::Signature::Sr25519(signature), + extra, ) } diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 18ce64c29f..8c999bb76f 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -631,7 +631,7 @@ impl Get> for OffchainRandomBalancing { use sp_runtime::traits::TrailingZeroInput; let iters = match MINER_MAX_ITERATIONS { 0 => 0, - max @ _ => { + max => { let seed = sp_io::offchain::random_seed(); let random = ::decode(&mut TrailingZeroInput::new(&seed)) .expect("input is padded with zeroes; qed") % @@ -1148,7 +1148,7 @@ where let signature = raw_payload.using_encoded(|payload| C::sign(payload, public))?; let address = Indices::unlookup(account); let (call, extra, _) = raw_payload.deconstruct(); - Some((call, (address, signature.into(), extra))) + Some((call, (address, signature, extra))) } } @@ -1911,7 +1911,7 @@ impl_runtime_apis! { let storage_info = AllPalletsWithSystem::storage_info(); - return (list, storage_info) + (list, storage_info) } fn dispatch_benchmark( diff --git a/substrate/bin/node/testing/src/bench.rs b/substrate/bin/node/testing/src/bench.rs index 8227582d88..7e13c0a0ac 100644 --- a/substrate/bin/node/testing/src/bench.rs +++ b/substrate/bin/node/testing/src/bench.rs @@ -280,8 +280,7 @@ impl<'a> BlockContentIterator<'a> { let genesis_hash = client .block_hash(Zero::zero()) .expect("Database error?") - .expect("Genesis block always exists; qed") - .into(); + .expect("Genesis block always exists; qed"); BlockContentIterator { iteration: 0, content, keyring, runtime_version, genesis_hash } } @@ -569,15 +568,13 @@ impl BenchKeyring { genesis_hash, ); let key = self.accounts.get(&signed).expect("Account id not found in keyring"); - let signature = payload - .using_encoded(|b| { - if b.len() > 256 { - key.sign(&sp_io::hashing::blake2_256(b)) - } else { - key.sign(b) - } - }) - .into(); + let signature = payload.using_encoded(|b| { + if b.len() > 256 { + key.sign(&sp_io::hashing::blake2_256(b)) + } else { + key.sign(b) + } + }); UncheckedExtrinsic { signature: Some((sp_runtime::MultiAddress::Id(signed), signature, extra)), function: payload.0, diff --git a/substrate/bin/utils/chain-spec-builder/src/main.rs b/substrate/bin/utils/chain-spec-builder/src/main.rs index 3e8b1f4ea7..e972e130fc 100644 --- a/substrate/bin/utils/chain-spec-builder/src/main.rs +++ b/substrate/bin/utils/chain-spec-builder/src/main.rs @@ -163,7 +163,7 @@ fn generate_chain_spec( } fn generate_authority_keys_and_store(seeds: &[String], keystore_path: &Path) -> Result<(), String> { - for (n, seed) in seeds.into_iter().enumerate() { + for (n, seed) in seeds.iter().enumerate() { let keystore: SyncCryptoStorePtr = Arc::new( LocalKeystore::open(keystore_path.join(format!("auth-{}", n)), None) .map_err(|err| err.to_string())?, diff --git a/substrate/client/allocator/src/freeing_bump.rs b/substrate/client/allocator/src/freeing_bump.rs index 7eeda45370..f14c31c79c 100644 --- a/substrate/client/allocator/src/freeing_bump.rs +++ b/substrate/client/allocator/src/freeing_bump.rs @@ -90,7 +90,7 @@ fn error(msg: &'static str) -> Error { Error::Other(msg) } -const LOG_TARGET: &'static str = "wasm-heap"; +const LOG_TARGET: &str = "wasm-heap"; // The minimum possible allocation size is chosen to be 8 bytes because in that case we would have // easier time to provide the guaranteed alignment of 8. diff --git a/substrate/client/api/src/backend.rs b/substrate/client/api/src/backend.rs index e96616d541..394fcd420f 100644 --- a/substrate/client/api/src/backend.rs +++ b/substrate/client/api/src/backend.rs @@ -499,7 +499,7 @@ pub trait Backend: AuxStore + Send + Sync { /// Returns true if state for given block is available. fn have_state_at(&self, hash: &Block::Hash, _number: NumberFor) -> bool { - self.state_at(BlockId::Hash(hash.clone())).is_ok() + self.state_at(BlockId::Hash(*hash)).is_ok() } /// Returns state backend with post-state of given block. diff --git a/substrate/client/api/src/execution_extensions.rs b/substrate/client/api/src/execution_extensions.rs index 92efafe91a..574687312c 100644 --- a/substrate/client/api/src/execution_extensions.rs +++ b/substrate/client/api/src/execution_extensions.rs @@ -151,7 +151,7 @@ impl ExecutionExtensions { where T: OffchainSubmitTransaction + 'static, { - *self.transaction_pool.write() = Some(Arc::downgrade(&pool) as _); + *self.transaction_pool.write() = Some(Arc::downgrade(pool) as _); } /// Based on the execution context and capabilities it produces diff --git a/substrate/client/api/src/in_mem.rs b/substrate/client/api/src/in_mem.rs index 51370f47e7..8b8473287a 100644 --- a/substrate/client/api/src/in_mem.rs +++ b/substrate/client/api/src/in_mem.rs @@ -166,23 +166,19 @@ impl Blockchain { body: Option::Extrinsic>>, new_state: NewBlockState, ) -> sp_blockchain::Result<()> { - let number = header.number().clone(); + let number = *header.number(); if new_state.is_best() { self.apply_head(&header)?; } { let mut storage = self.storage.write(); - storage - .leaves - .import(hash.clone(), number.clone(), header.parent_hash().clone()); - storage - .blocks - .insert(hash.clone(), StoredBlock::new(header, body, justifications)); + storage.leaves.import(hash, number, header.parent_hash().clone()); + storage.blocks.insert(hash, StoredBlock::new(header, body, justifications)); if let NewBlockState::Final = new_state { storage.finalized_hash = hash; - storage.finalized_number = number.clone(); + storage.finalized_number = number; } if number == Zero::zero() { @@ -266,9 +262,9 @@ impl Blockchain { } } - storage.best_hash = hash.clone(); - storage.best_number = number.clone(); - storage.hashes.insert(number.clone(), hash.clone()); + storage.best_hash = hash; + storage.best_number = *number; + storage.hashes.insert(*number, hash); Ok(()) } @@ -362,7 +358,7 @@ impl HeaderBackend for Blockchain { finalized_hash: storage.finalized_hash, finalized_number: storage.finalized_number, finalized_state: if storage.finalized_hash != Default::default() { - Some((storage.finalized_hash.clone(), storage.finalized_number)) + Some((storage.finalized_hash, storage.finalized_number)) } else { None }, @@ -428,16 +424,12 @@ impl blockchain::Backend for Blockchain { fn justifications(&self, id: BlockId) -> sp_blockchain::Result> { Ok(self.id(id).and_then(|hash| { - self.storage - .read() - .blocks - .get(&hash) - .and_then(|b| b.justifications().map(|x| x.clone())) + self.storage.read().blocks.get(&hash).and_then(|b| b.justifications().cloned()) })) } fn last_finalized(&self) -> sp_blockchain::Result { - Ok(self.storage.read().finalized_hash.clone()) + Ok(self.storage.read().finalized_hash) } fn leaves(&self) -> sp_blockchain::Result> { @@ -810,15 +802,15 @@ impl backend::LocalBackend for Backend where Block: /// Check that genesis storage is valid. pub fn check_genesis_storage(storage: &Storage) -> sp_blockchain::Result<()> { if storage.top.iter().any(|(k, _)| well_known_keys::is_child_storage_key(k)) { - return Err(sp_blockchain::Error::InvalidState.into()) + return Err(sp_blockchain::Error::InvalidState) } if storage .children_default .keys() - .any(|child_key| !well_known_keys::is_child_storage_key(&child_key)) + .any(|child_key| !well_known_keys::is_child_storage_key(child_key)) { - return Err(sp_blockchain::Error::InvalidState.into()) + return Err(sp_blockchain::Error::InvalidState) } Ok(()) diff --git a/substrate/client/api/src/lib.rs b/substrate/client/api/src/lib.rs index aab2fabd5e..3d21f12f69 100644 --- a/substrate/client/api/src/lib.rs +++ b/substrate/client/api/src/lib.rs @@ -57,10 +57,10 @@ pub mod utils { /// represent the current block `hash` and its `parent hash`, if given the /// function that's returned will assume that `hash` isn't part of the local DB /// yet, and all searches in the DB will instead reference the parent. - pub fn is_descendent_of<'a, Block: BlockT, T>( - client: &'a T, + pub fn is_descendent_of( + client: &T, current: Option<(Block::Hash, Block::Hash)>, - ) -> impl Fn(&Block::Hash, &Block::Hash) -> Result + 'a + ) -> impl Fn(&Block::Hash, &Block::Hash) -> Result + '_ where T: HeaderBackend + HeaderMetadata, { diff --git a/substrate/client/api/src/notifications.rs b/substrate/client/api/src/notifications.rs index 36798abc5b..9fcc381f96 100644 --- a/substrate/client/api/src/notifications.rs +++ b/substrate/client/api/src/notifications.rs @@ -71,10 +71,9 @@ type ChildKeys = Option>>>; impl StorageChangeSet { /// Convert the change set into iterator over storage items. - pub fn iter<'a>( - &'a self, - ) -> impl Iterator, &'a StorageKey, Option<&'a StorageData>)> + 'a - { + pub fn iter( + &self, + ) -> impl Iterator, &StorageKey, Option<&StorageData>)> + '_ { let top = self .changes .iter() diff --git a/substrate/client/api/src/notifications/registry.rs b/substrate/client/api/src/notifications/registry.rs index b34d5a6b67..882d6ed40b 100644 --- a/substrate/client/api/src/notifications/registry.rs +++ b/substrate/client/api/src/notifications/registry.rs @@ -134,7 +134,7 @@ impl<'a> Subscribe> for Registry { }); if let Some(m) = self.metrics.as_ref() { - m.with_label_values(&[&"added"]).inc(); + m.with_label_values(&["added"]).inc(); } if self @@ -195,7 +195,7 @@ impl Registry { let k = StorageKey(k); let listeners = self.listeners.get(&k); - if let Some(ref listeners) = listeners { + if let Some(listeners) = listeners { subscribers.extend(listeners.iter()); } @@ -211,7 +211,7 @@ impl Registry { let k = StorageKey(k); let listeners = cl.get(&k); - if let Some(ref listeners) = listeners { + if let Some(listeners) = listeners { subscribers.extend(listeners.iter()); } @@ -268,22 +268,22 @@ impl Registry { ); if let Some(child_filters) = &sink.child_keys { for (c_key, filters) in child_filters { - if let Some((listeners, wildcards)) = self.child_listeners.get_mut(&c_key) { + if let Some((listeners, wildcards)) = self.child_listeners.get_mut(c_key) { Self::remove_subscriber_from( subscriber, - &filters, + filters, &mut *listeners, &mut *wildcards, ); if listeners.is_empty() && wildcards.is_empty() { - self.child_listeners.remove(&c_key); + self.child_listeners.remove(c_key); } } } } if let Some(m) = self.metrics.as_ref() { - m.with_label_values(&[&"removed"]).inc(); + m.with_label_values(&["removed"]).inc(); } Some((sink.keys.clone(), sink.child_keys.clone())) diff --git a/substrate/client/authority-discovery/src/worker.rs b/substrate/client/authority-discovery/src/worker.rs index 0912359501..87cc72ba7a 100644 --- a/substrate/client/authority-discovery/src/worker.rs +++ b/substrate/client/authority-discovery/src/worker.rs @@ -64,7 +64,7 @@ mod schema { #[cfg(test)] pub mod tests; -const LOG_TARGET: &'static str = "sub-authority-discovery"; +const LOG_TARGET: &str = "sub-authority-discovery"; /// Maximum number of addresses cached per authority. Additional addresses are discarded. const MAX_ADDRESSES_PER_AUTHORITY: usize = 10; @@ -510,7 +510,7 @@ where // Ignore [`Multiaddr`]s without [`PeerId`] or with own addresses. let addresses: Vec = addresses .into_iter() - .filter(|a| get_peer_id(&a).filter(|p| *p != local_peer_id).is_some()) + .filter(|a| get_peer_id(a).filter(|p| *p != local_peer_id).is_some()) .collect(); let remote_peer_id = single(addresses.iter().map(get_peer_id)) @@ -525,7 +525,7 @@ where if let Some(peer_signature) = peer_signature { let public_key = sc_network::PublicKey::from_protobuf_encoding(&peer_signature.public_key) - .map_err(|e| Error::ParsingLibp2pIdentity(e))?; + .map_err(Error::ParsingLibp2pIdentity)?; let signature = sc_network::Signature { public_key, bytes: peer_signature.signature }; diff --git a/substrate/client/authority-discovery/src/worker/addr_cache.rs b/substrate/client/authority-discovery/src/worker/addr_cache.rs index 3cac5a6bf0..f768b9c4e6 100644 --- a/substrate/client/authority-discovery/src/worker/addr_cache.rs +++ b/substrate/client/authority-discovery/src/worker/addr_cache.rs @@ -165,10 +165,7 @@ fn peer_id_from_multiaddr(addr: &Multiaddr) -> Option { } fn addresses_to_peer_ids(addresses: &HashSet) -> HashSet { - addresses - .iter() - .filter_map(|a| peer_id_from_multiaddr(a)) - .collect::>() + addresses.iter().filter_map(peer_id_from_multiaddr).collect::>() } #[cfg(test)] diff --git a/substrate/client/basic-authorship/src/basic_authorship.rs b/substrate/client/basic-authorship/src/basic_authorship.rs index 23725e5138..5a020ee810 100644 --- a/substrate/client/basic-authorship/src/basic_authorship.rs +++ b/substrate/client/basic-authorship/src/basic_authorship.rs @@ -371,7 +371,7 @@ where error!( "❌️ Mandatory inherent extrinsic returned error. Block cannot be produced." ); - Err(ApplyExtrinsicFailed(Validity(e)))? + return Err(ApplyExtrinsicFailed(Validity(e))) }, Err(e) => { warn!("❗️ Inherent extrinsic returned unexpected error: {}. Dropping.", e); diff --git a/substrate/client/beefy/rpc/src/lib.rs b/substrate/client/beefy/rpc/src/lib.rs index 4c1bc03e22..e49af3352a 100644 --- a/substrate/client/beefy/rpc/src/lib.rs +++ b/substrate/client/beefy/rpc/src/lib.rs @@ -192,7 +192,7 @@ where .read() .as_ref() .cloned() - .ok_or(Error::EndpointNotReady.into()); + .ok_or_else(|| Error::EndpointNotReady.into()); let future = async move { result }.boxed(); future.map_err(jsonrpc_core::Error::from).boxed() } diff --git a/substrate/client/beefy/src/lib.rs b/substrate/client/beefy/src/lib.rs index 5d8aa5c866..c025ec5686 100644 --- a/substrate/client/beefy/src/lib.rs +++ b/substrate/client/beefy/src/lib.rs @@ -51,9 +51,9 @@ pub use beefy_protocol_name::standard_name as protocol_standard_name; pub(crate) mod beefy_protocol_name { use sc_chain_spec::ChainSpec; - const NAME: &'static str = "/beefy/1"; + const NAME: &str = "/beefy/1"; /// Old names for the notifications protocol, used for backward compatibility. - pub(crate) const LEGACY_NAMES: [&'static str; 1] = ["/paritytech/beefy/1"]; + pub(crate) const LEGACY_NAMES: [&str; 1] = ["/paritytech/beefy/1"]; /// Name of the notifications protocol used by BEEFY. /// diff --git a/substrate/client/block-builder/src/lib.rs b/substrate/client/block-builder/src/lib.rs index 3f9fecbccb..803e9c1e8b 100644 --- a/substrate/client/block-builder/src/lib.rs +++ b/substrate/client/block-builder/src/lib.rs @@ -264,7 +264,7 @@ where let storage_changes = self .api .into_storage_changes(&state, parent_hash) - .map_err(|e| sp_blockchain::Error::StorageChanges(e))?; + .map_err(sp_blockchain::Error::StorageChanges)?; Ok(BuiltBlock { block: ::new(header, self.extrinsics), diff --git a/substrate/client/cli/src/commands/generate.rs b/substrate/client/cli/src/commands/generate.rs index 9c1e5b6895..5b1b708f86 100644 --- a/substrate/client/cli/src/commands/generate.rs +++ b/substrate/client/cli/src/commands/generate.rs @@ -61,16 +61,11 @@ impl GenerateCmd { }; let mnemonic = Mnemonic::new(words, Language::English); let password = self.keystore_params.read_password()?; - let output = self.output_scheme.output_type.clone(); + let output = self.output_scheme.output_type; with_crypto_scheme!( self.crypto_scheme.scheme, - print_from_uri( - mnemonic.phrase(), - password, - self.network_scheme.network.clone(), - output, - ) + print_from_uri(mnemonic.phrase(), password, self.network_scheme.network, output) ); Ok(()) } diff --git a/substrate/client/cli/src/commands/inspect_key.rs b/substrate/client/cli/src/commands/inspect_key.rs index 61fa8d2157..14bb059503 100644 --- a/substrate/client/cli/src/commands/inspect_key.rs +++ b/substrate/client/cli/src/commands/inspect_key.rs @@ -87,15 +87,15 @@ impl InspectKeyCmd { self.crypto_scheme.scheme, print_from_public( &uri, - self.network_scheme.network.clone(), - self.output_scheme.output_type.clone(), + self.network_scheme.network, + self.output_scheme.output_type, ) )?; } else { if let Some(ref expect_public) = self.expect_public { with_crypto_scheme!( self.crypto_scheme.scheme, - expect_public_from_phrase(&&expect_public, &uri, password.as_ref(),) + expect_public_from_phrase(expect_public, &uri, password.as_ref()) )?; } @@ -104,8 +104,8 @@ impl InspectKeyCmd { print_from_uri( &uri, password, - self.network_scheme.network.clone(), - self.output_scheme.output_type.clone(), + self.network_scheme.network, + self.output_scheme.output_type, ) ); } diff --git a/substrate/client/cli/src/commands/purge_chain_cmd.rs b/substrate/client/cli/src/commands/purge_chain_cmd.rs index 7dd7c1f5a5..b89487a18f 100644 --- a/substrate/client/cli/src/commands/purge_chain_cmd.rs +++ b/substrate/client/cli/src/commands/purge_chain_cmd.rs @@ -60,7 +60,7 @@ impl PurgeChainCmd { io::stdin().read_line(&mut input)?; let input = input.trim(); - match input.chars().nth(0) { + match input.chars().next() { Some('y') | Some('Y') => {}, _ => { println!("Aborted"); diff --git a/substrate/client/cli/src/commands/utils.rs b/substrate/client/cli/src/commands/utils.rs index fa776c25a2..32556f0ea7 100644 --- a/substrate/client/cli/src/commands/utils.rs +++ b/substrate/client/cli/src/commands/utils.rs @@ -74,7 +74,7 @@ pub fn print_from_uri( { let password = password.as_ref().map(|s| s.expose_secret().as_str()); let network_id = String::from(unwrap_or_default_ss58_version(network_override)); - if let Ok((pair, seed)) = Pair::from_phrase(uri, password.clone()) { + if let Ok((pair, seed)) = Pair::from_phrase(uri, password) { let public_key = pair.public(); let network_override = unwrap_or_default_ss58_version(network_override); @@ -113,7 +113,7 @@ pub fn print_from_uri( ); }, } - } else if let Ok((pair, seed)) = Pair::from_string_with_seed(uri, password.clone()) { + } else if let Ok((pair, seed)) = Pair::from_string_with_seed(uri, password) { let public_key = pair.public(); let network_override = unwrap_or_default_ss58_version(network_override); diff --git a/substrate/client/cli/src/commands/vanity.rs b/substrate/client/cli/src/commands/vanity.rs index 834b220df6..6a1bf77f6c 100644 --- a/substrate/client/cli/src/commands/vanity.rs +++ b/substrate/client/cli/src/commands/vanity.rs @@ -64,8 +64,8 @@ impl VanityCmd { print_from_uri( &formated_seed, None, - self.network_scheme.network.clone(), - self.output_scheme.output_type.clone(), + self.network_scheme.network, + self.output_scheme.output_type, ), ); Ok(()) @@ -98,7 +98,7 @@ where let p = Pair::from_seed(&seed); let ss58 = p.public().into_account().to_ss58check_with_version(network_override); - let score = calculate_score(&desired, &ss58); + let score = calculate_score(desired, &ss58); if score > best || desired.len() < 2 { best = score; if best >= top { @@ -117,20 +117,20 @@ where fn good_waypoint(done: u64) -> u64 { match done { 0..=1_000_000 => 100_000, - 0..=10_000_000 => 1_000_000, - 0..=100_000_000 => 10_000_000, - _ => 100_000_000, + 1_000_001..=10_000_000 => 1_000_000, + 10_000_001..=100_000_000 => 10_000_000, + 100_000_001.. => 100_000_000, } } fn next_seed(seed: &mut [u8]) { - for i in 0..seed.len() { - match seed[i] { + for s in seed { + match s { 255 => { - seed[i] = 0; + *s = 0; }, _ => { - seed[i] += 1; + *s += 1; break }, } diff --git a/substrate/client/cli/src/config.rs b/substrate/client/cli/src/config.rs index d0f10dc9f6..5c44a05ab6 100644 --- a/substrate/client/cli/src/config.rs +++ b/substrate/client/cli/src/config.rs @@ -40,7 +40,7 @@ use std::{net::SocketAddr, path::PathBuf}; pub(crate) const NODE_NAME_MAX_LENGTH: usize = 64; /// Default sub directory to store network config. -pub(crate) const DEFAULT_NETWORK_CONFIG_PATH: &'static str = "network"; +pub(crate) const DEFAULT_NETWORK_CONFIG_PATH: &str = "network"; /// The recommended open file descriptor limit to be configured for the process. const RECOMMENDED_OPEN_FILE_DESCRIPTOR_LIMIT: u64 = 10_000; @@ -629,7 +629,7 @@ pub trait CliConfiguration: Sized { } // Call hook for custom profiling setup. - logger_hook(&mut logger, &config); + logger_hook(&mut logger, config); logger.init()?; diff --git a/substrate/client/cli/src/lib.rs b/substrate/client/cli/src/lib.rs index 244f6e167f..e01befbef4 100644 --- a/substrate/client/cli/src/lib.rs +++ b/substrate/client/cli/src/lib.rs @@ -122,7 +122,7 @@ pub trait SubstrateCli: Sized { let app = ::command(); let mut full_version = Self::impl_version(); - full_version.push_str("\n"); + full_version.push('\n'); let name = Self::executable_name(); let author = Self::author(); @@ -164,7 +164,7 @@ pub trait SubstrateCli: Sized { let app = ::command(); let mut full_version = Self::impl_version(); - full_version.push_str("\n"); + full_version.push('\n'); let name = Self::executable_name(); let author = Self::author(); diff --git a/substrate/client/cli/src/params/keystore_params.rs b/substrate/client/cli/src/params/keystore_params.rs index 72b09134f5..46403f95fb 100644 --- a/substrate/client/cli/src/params/keystore_params.rs +++ b/substrate/client/cli/src/params/keystore_params.rs @@ -26,7 +26,7 @@ use std::{ }; /// default sub directory for the key store -const DEFAULT_KEYSTORE_CONFIG_PATH: &'static str = "keystore"; +const DEFAULT_KEYSTORE_CONFIG_PATH: &str = "keystore"; /// Parameters of the keystore #[derive(Debug, Clone, Args)] diff --git a/substrate/client/cli/src/params/node_key_params.rs b/substrate/client/cli/src/params/node_key_params.rs index 699d0c4ece..d51b6143ed 100644 --- a/substrate/client/cli/src/params/node_key_params.rs +++ b/substrate/client/cli/src/params/node_key_params.rs @@ -112,7 +112,7 @@ fn invalid_node_key(e: impl std::fmt::Display) -> error::Error { /// Parse a Ed25519 secret key from a hex string into a `sc_network::Secret`. fn parse_ed25519_secret(hex: &str) -> error::Result { - H256::from_str(&hex).map_err(invalid_node_key).and_then(|bytes| { + H256::from_str(hex).map_err(invalid_node_key).and_then(|bytes| { ed25519::SecretKey::from_bytes(bytes) .map(sc_network::config::Secret::Input) .map_err(invalid_node_key) diff --git a/substrate/client/cli/src/params/shared_params.rs b/substrate/client/cli/src/params/shared_params.rs index 01df2cf9ab..67b18aa8b0 100644 --- a/substrate/client/cli/src/params/shared_params.rs +++ b/substrate/client/cli/src/params/shared_params.rs @@ -126,7 +126,7 @@ impl SharedParams { /// Receiver to process tracing messages. pub fn tracing_receiver(&self) -> sc_service::TracingReceiver { - self.tracing_receiver.clone().into() + self.tracing_receiver.into() } /// Comma separated list of targets for tracing. diff --git a/substrate/client/consensus/aura/src/import_queue.rs b/substrate/client/consensus/aura/src/import_queue.rs index 56eb45c621..3055400673 100644 --- a/substrate/client/consensus/aura/src/import_queue.rs +++ b/substrate/client/consensus/aura/src/import_queue.rs @@ -68,7 +68,7 @@ where C: sc_client_api::backend::AuxStore, P::Public: Encode + Decode + PartialEq + Clone, { - let seal = header.digest_mut().pop().ok_or_else(|| Error::HeaderUnsealed(hash))?; + let seal = header.digest_mut().pop().ok_or(Error::HeaderUnsealed(hash))?; let sig = seal.as_aura_seal().ok_or_else(|| aura_err(Error::HeaderBadSeal(hash)))?; @@ -81,7 +81,7 @@ where // check the signature is valid under the expected authority and // chain state. let expected_author = - slot_author::

(slot, &authorities).ok_or_else(|| Error::SlotAuthorNotFound)?; + slot_author::

(slot, authorities).ok_or(Error::SlotAuthorNotFound)?; let pre_hash = header.hash(); @@ -360,7 +360,7 @@ pub struct ImportQueueParams<'a, Block, I, C, S, CAW, CIDP> { } /// Start an import queue for the Aura consensus algorithm. -pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>( +pub fn import_queue( ImportQueueParams { block_import, justification_import, @@ -371,7 +371,7 @@ pub fn import_queue<'a, P, Block, I, C, S, CAW, CIDP>( can_author_with, check_for_equivocation, telemetry, - }: ImportQueueParams<'a, Block, I, C, S, CAW, CIDP>, + }: ImportQueueParams, ) -> Result, sp_consensus::Error> where Block: BlockT, diff --git a/substrate/client/consensus/aura/src/lib.rs b/substrate/client/consensus/aura/src/lib.rs index d803aa4ae9..ac3b89f2ff 100644 --- a/substrate/client/consensus/aura/src/lib.rs +++ b/substrate/client/consensus/aura/src/lib.rs @@ -186,7 +186,7 @@ where Error: std::error::Error + Send + From + 'static, { let worker = build_aura_worker::(BuildAuraWorkerParams { - client: client.clone(), + client, block_import, proposer_factory, keystore, @@ -459,7 +459,7 @@ where fn proposer(&mut self, block: &B::Header) -> Self::CreateProposer { self.env .init(block) - .map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e)).into()) + .map_err(|e| sp_consensus::Error::ClientImport(format!("{:?}", e))) .boxed() } @@ -534,7 +534,7 @@ pub fn find_pre_digest(header: &B::Header) -> Resul for log in header.digest().logs() { trace!(target: "aura", "Checking log {:?}", log); match (CompatibleDigestItem::::as_aura_pre_digest(log), pre_digest.is_some()) { - (Some(_), true) => Err(aura_err(Error::MultipleHeaders))?, + (Some(_), true) => return Err(aura_err(Error::MultipleHeaders)), (None, _) => trace!(target: "aura", "Ignoring digest not meant for us"), (s, false) => pre_digest = s, } @@ -553,7 +553,7 @@ where .runtime_api() .authorities(at) .ok() - .ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet.into()) + .ok_or(sp_consensus::Error::InvalidAuthoritiesSet) } #[cfg(test)] diff --git a/substrate/client/consensus/babe/rpc/src/lib.rs b/substrate/client/consensus/babe/rpc/src/lib.rs index 1fbe23e54f..2d0c81afc7 100644 --- a/substrate/client/consensus/babe/rpc/src/lib.rs +++ b/substrate/client/consensus/babe/rpc/src/lib.rs @@ -142,7 +142,7 @@ where claims.entry(key).or_default().secondary.push(slot); }, PreDigest::SecondaryVRF { .. } => { - claims.entry(key).or_default().secondary_vrf.push(slot.into()); + claims.entry(key).or_default().secondary_vrf.push(slot); }, }; } @@ -205,7 +205,7 @@ where .epoch_data_for_child_of( descendent_query(&**client), &parent.hash(), - parent.number().clone(), + *parent.number(), slot.into(), |slot| Epoch::genesis(babe_config.genesis_config(), slot), ) diff --git a/substrate/client/consensus/babe/src/authorship.rs b/substrate/client/consensus/babe/src/authorship.rs index 1f74afb0e7..7a9b09495c 100644 --- a/substrate/client/consensus/babe/src/authorship.rs +++ b/substrate/client/consensus/babe/src/authorship.rs @@ -202,15 +202,15 @@ pub fn claim_slot_using_keys( keystore: &SyncCryptoStorePtr, keys: &[(AuthorityId, usize)], ) -> Option<(PreDigest, AuthorityId)> { - claim_primary_slot(slot, epoch, epoch.config.c, keystore, &keys).or_else(|| { + claim_primary_slot(slot, epoch, epoch.config.c, keystore, keys).or_else(|| { if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() || epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() { claim_secondary_slot( slot, - &epoch, + epoch, keys, - &keystore, + keystore, epoch.config.allowed_slots.is_secondary_vrf_slots_allowed(), ) } else { diff --git a/substrate/client/consensus/babe/src/lib.rs b/substrate/client/consensus/babe/src/lib.rs index be5c2809bd..490fdfb174 100644 --- a/substrate/client/consensus/babe/src/lib.rs +++ b/substrate/client/consensus/babe/src/lib.rs @@ -528,7 +528,7 @@ where let (worker_tx, worker_rx) = channel(HANDLE_BUFFER_SIZE); let answer_requests = - answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes.clone()); + answer_requests(worker_rx, babe_link.config, client, babe_link.epoch_changes); let inner = future::select(Box::pin(slot_worker), Box::pin(answer_requests)); Ok(BabeWorker { @@ -638,13 +638,13 @@ async fn answer_requests( slot_number, ) .map_err(|e| Error::::ForkTree(Box::new(e)))? - .ok_or_else(|| Error::::FetchEpoch(parent_hash))?; + .ok_or(Error::::FetchEpoch(parent_hash))?; let viable_epoch = epoch_changes .viable_epoch(&epoch_descriptor, |slot| { Epoch::genesis(&config.genesis_config, slot) }) - .ok_or_else(|| Error::::FetchEpoch(parent_hash))?; + .ok_or(Error::::FetchEpoch(parent_hash))?; Ok(sp_consensus_babe::Epoch { epoch_index: viable_epoch.as_ref().epoch_index, @@ -788,7 +788,7 @@ where .epoch_descriptor_for_child_of( descendent_query(&*self.client), &parent.hash(), - parent.number().clone(), + *parent.number(), slot, ) .map_err(|e| ConsensusError::ChainLookup(e.to_string()))? @@ -798,7 +798,7 @@ where fn authorities_len(&self, epoch_descriptor: &Self::EpochData) -> Option { self.epoch_changes .shared_data() - .viable_epoch(&epoch_descriptor, |slot| { + .viable_epoch(epoch_descriptor, |slot| { Epoch::genesis(&self.config.genesis_config, slot) }) .map(|epoch| epoch.as_ref().authorities.len()) @@ -815,7 +815,7 @@ where slot, self.epoch_changes .shared_data() - .viable_epoch(&epoch_descriptor, |slot| { + .viable_epoch(epoch_descriptor, |slot| { Epoch::genesis(&self.config.genesis_config, slot) })? .as_ref(), @@ -886,7 +886,7 @@ where .clone() .try_into() .map_err(|_| sp_consensus::Error::InvalidSignature(signature, public))?; - let digest_item = ::babe_seal(signature.into()); + let digest_item = ::babe_seal(signature); let mut import_block = BlockImportParams::new(BlockOrigin::Own, header); import_block.post_digests.push(digest_item); @@ -1245,12 +1245,12 @@ where pre_digest.slot(), ) .map_err(|e| Error::::ForkTree(Box::new(e)))? - .ok_or_else(|| Error::::FetchEpoch(parent_hash))?; + .ok_or(Error::::FetchEpoch(parent_hash))?; let viable_epoch = epoch_changes .viable_epoch(&epoch_descriptor, |slot| { Epoch::genesis(&self.config.genesis_config, slot) }) - .ok_or_else(|| Error::::FetchEpoch(parent_hash))?; + .ok_or(Error::::FetchEpoch(parent_hash))?; // We add one to the current slot to allow for some small drift. // FIXME #1019 in the future, alter this queue to allow deferring of headers diff --git a/substrate/client/consensus/babe/src/verification.rs b/substrate/client/consensus/babe/src/verification.rs index 41d1e1bfa5..53ec3002e6 100644 --- a/substrate/client/consensus/babe/src/verification.rs +++ b/substrate/client/consensus/babe/src/verification.rs @@ -99,7 +99,7 @@ pub(super) fn check_header( primary.slot, ); - check_primary_header::(pre_hash, primary, sig, &epoch, epoch.config.c)?; + check_primary_header::(pre_hash, primary, sig, epoch, epoch.config.c)?; }, PreDigest::SecondaryPlain(secondary) if epoch.config.allowed_slots.is_secondary_plain_slots_allowed() => @@ -110,7 +110,7 @@ pub(super) fn check_header( secondary.slot, ); - check_secondary_plain_header::(pre_hash, secondary, sig, &epoch)?; + check_secondary_plain_header::(pre_hash, secondary, sig, epoch)?; }, PreDigest::SecondaryVRF(secondary) if epoch.config.allowed_slots.is_secondary_vrf_slots_allowed() => @@ -121,7 +121,7 @@ pub(super) fn check_header( secondary.slot, ); - check_secondary_vrf_header::(pre_hash, secondary, sig, &epoch)?; + check_secondary_vrf_header::(pre_hash, secondary, sig, epoch)?; }, _ => return Err(babe_err(Error::SecondarySlotAssignmentsDisabled)), } @@ -153,7 +153,7 @@ fn check_primary_header( ) -> Result<(), Error> { let author = &epoch.authorities[pre_digest.authority_index as usize].0; - if AuthorityPair::verify(&signature, pre_hash, &author) { + if AuthorityPair::verify(&signature, pre_hash, author) { let (inout, _) = { let transcript = make_transcript(&epoch.randomness, pre_digest.slot, epoch.epoch_index); @@ -191,7 +191,7 @@ fn check_secondary_plain_header( // chain state. let expected_author = secondary_slot_author(pre_digest.slot, &epoch.authorities, epoch.randomness) - .ok_or_else(|| Error::NoSecondaryAuthorExpected)?; + .ok_or(Error::NoSecondaryAuthorExpected)?; let author = &epoch.authorities[pre_digest.authority_index as usize].0; @@ -217,7 +217,7 @@ fn check_secondary_vrf_header( // chain state. let expected_author = secondary_slot_author(pre_digest.slot, &epoch.authorities, epoch.randomness) - .ok_or_else(|| Error::NoSecondaryAuthorExpected)?; + .ok_or(Error::NoSecondaryAuthorExpected)?; let author = &epoch.authorities[pre_digest.authority_index as usize].0; diff --git a/substrate/client/consensus/common/src/block_import.rs b/substrate/client/consensus/common/src/block_import.rs index 24fec9b974..f81c8eb7e8 100644 --- a/substrate/client/consensus/common/src/block_import.rs +++ b/substrate/client/consensus/common/src/block_import.rs @@ -62,8 +62,7 @@ impl ImportResult { /// `clear_justification_requests`, `needs_justification`, /// `bad_justification` set to false. pub fn imported(is_new_best: bool) -> ImportResult { - let mut aux = ImportedAux::default(); - aux.is_new_best = is_new_best; + let aux = ImportedAux { is_new_best, ..Default::default() }; ImportResult::Imported(aux) } diff --git a/substrate/client/consensus/common/src/import_queue.rs b/substrate/client/consensus/common/src/import_queue.rs index 8b560d0447..a7b456191b 100644 --- a/substrate/client/consensus/common/src/import_queue.rs +++ b/substrate/client/consensus/common/src/import_queue.rs @@ -232,17 +232,17 @@ pub(crate) async fn import_single_block_metered< trace!(target: "sync", "Header {} has {:?} logs", block.hash, header.digest().logs().len()); - let number = header.number().clone(); + let number = *header.number(); let hash = block.hash; - let parent_hash = header.parent_hash().clone(); + let parent_hash = *header.parent_hash(); let import_handler = |import| match import { Ok(ImportResult::AlreadyInChain) => { trace!(target: "sync", "Block already in chain {}: {:?}", number, hash); - Ok(BlockImportStatus::ImportedKnown(number, peer.clone())) + Ok(BlockImportStatus::ImportedKnown(number, peer)) }, Ok(ImportResult::Imported(aux)) => - Ok(BlockImportStatus::ImportedUnknown(number, aux, peer.clone())), + Ok(BlockImportStatus::ImportedUnknown(number, aux, peer)), Ok(ImportResult::MissingState) => { debug!(target: "sync", "Parent state is missing for {}: {:?}, parent: {:?}", number, hash, parent_hash); @@ -255,7 +255,7 @@ pub(crate) async fn import_single_block_metered< }, Ok(ImportResult::KnownBad) => { debug!(target: "sync", "Peer gave us a bad block {}: {:?}", number, hash); - Err(BlockImportError::BadBlock(peer.clone())) + Err(BlockImportError::BadBlock(peer)) }, Err(e) => { debug!(target: "sync", "Error importing block {}: {:?}: {}", number, hash, e); @@ -306,7 +306,7 @@ pub(crate) async fn import_single_block_metered< if let Some(metrics) = metrics.as_ref() { metrics.report_verification(false, started.elapsed()); } - BlockImportError::VerificationFailed(peer.clone(), msg) + BlockImportError::VerificationFailed(peer, msg) })?; if let Some(metrics) = metrics.as_ref() { diff --git a/substrate/client/consensus/common/src/import_queue/basic_queue.rs b/substrate/client/consensus/common/src/import_queue/basic_queue.rs index 5134dc041c..9fe2931420 100644 --- a/substrate/client/consensus/common/src/import_queue/basic_queue.rs +++ b/substrate/client/consensus/common/src/import_queue/basic_queue.rs @@ -374,7 +374,7 @@ async fn import_many_blocks, Transaction: Send + 'stat }, }; - let block_number = block.header.as_ref().map(|h| h.number().clone()); + let block_number = block.header.as_ref().map(|h| *h.number()); let block_hash = block.hash; let import_result = if has_error { Err(BlockImportError::Cancelled) @@ -382,7 +382,7 @@ async fn import_many_blocks, Transaction: Send + 'stat // The actual import. import_single_block_metered( import_handle, - blocks_origin.clone(), + blocks_origin, block, verifier, metrics.clone(), diff --git a/substrate/client/consensus/common/src/import_queue/buffered_link.rs b/substrate/client/consensus/common/src/import_queue/buffered_link.rs index 8fb5689075..d3d91f5bd3 100644 --- a/substrate/client/consensus/common/src/import_queue/buffered_link.rs +++ b/substrate/client/consensus/common/src/import_queue/buffered_link.rs @@ -105,14 +105,14 @@ impl Link for BufferedLinkSender { number: NumberFor, success: bool, ) { - let msg = BlockImportWorkerMsg::JustificationImported(who, hash.clone(), number, success); + let msg = BlockImportWorkerMsg::JustificationImported(who, *hash, number, success); let _ = self.tx.unbounded_send(msg); } fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { let _ = self .tx - .unbounded_send(BlockImportWorkerMsg::RequestJustification(hash.clone(), number)); + .unbounded_send(BlockImportWorkerMsg::RequestJustification(*hash, number)); } } diff --git a/substrate/client/consensus/common/src/longest_chain.rs b/substrate/client/consensus/common/src/longest_chain.rs index b38183b8ac..941cd4b944 100644 --- a/substrate/client/consensus/common/src/longest_chain.rs +++ b/substrate/client/consensus/common/src/longest_chain.rs @@ -79,12 +79,12 @@ where Block: BlockT, { async fn leaves(&self) -> Result::Hash>, ConsensusError> { - LongestChain::leaves(self).map_err(|e| ConsensusError::ChainLookup(e.to_string()).into()) + LongestChain::leaves(self).map_err(|e| ConsensusError::ChainLookup(e.to_string())) } async fn best_chain(&self) -> Result<::Header, ConsensusError> { - LongestChain::best_block_header(&self) - .map_err(|e| ConsensusError::ChainLookup(e.to_string()).into()) + LongestChain::best_block_header(self) + .map_err(|e| ConsensusError::ChainLookup(e.to_string())) } async fn finality_target( @@ -97,6 +97,6 @@ where .blockchain() .best_containing(target_hash, maybe_max_number, import_lock) .map(|maybe_hash| maybe_hash.unwrap_or(target_hash)) - .map_err(|e| ConsensusError::ChainLookup(e.to_string()).into()) + .map_err(|e| ConsensusError::ChainLookup(e.to_string())) } } diff --git a/substrate/client/consensus/epochs/src/lib.rs b/substrate/client/consensus/epochs/src/lib.rs index 90081bf9af..3a943e4851 100644 --- a/substrate/client/consensus/epochs/src/lib.rs +++ b/substrate/client/consensus/epochs/src/lib.rs @@ -566,7 +566,7 @@ where ViableEpochDescriptor::UnimportedGenesis(slot) => Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))), ViableEpochDescriptor::Signaled(identifier, _) => - self.epoch(&identifier).map(ViableEpoch::Signaled), + self.epoch(identifier).map(ViableEpoch::Signaled), } } @@ -599,7 +599,7 @@ where ViableEpochDescriptor::UnimportedGenesis(slot) => Some(ViableEpoch::UnimportedGenesis(make_genesis(*slot))), ViableEpochDescriptor::Signaled(identifier, _) => - self.epoch_mut(&identifier).map(ViableEpoch::Signaled), + self.epoch_mut(identifier).map(ViableEpoch::Signaled), } } @@ -618,7 +618,7 @@ where { match descriptor { ViableEpochDescriptor::UnimportedGenesis(slot) => Some(make_genesis(*slot)), - ViableEpochDescriptor::Signaled(identifier, _) => self.epoch(&identifier).cloned(), + ViableEpochDescriptor::Signaled(identifier, _) => self.epoch(identifier).cloned(), } } @@ -750,7 +750,7 @@ where if let Some(gap) = &mut self.gap { if let PersistedEpoch::Regular(e) = epoch { - epoch = match gap.import(slot, hash.clone(), number.clone(), e) { + epoch = match gap.import(slot, hash, number, e) { Ok(()) => return Ok(()), Err(e) => PersistedEpoch::Regular(e), } diff --git a/substrate/client/consensus/manual-seal/src/consensus/babe.rs b/substrate/client/consensus/manual-seal/src/consensus/babe.rs index 53cc58df30..3e7770cd98 100644 --- a/substrate/client/consensus/manual-seal/src/consensus/babe.rs +++ b/substrate/client/consensus/manual-seal/src/consensus/babe.rs @@ -114,7 +114,7 @@ where .epoch_descriptor_for_child_of( descendent_query(&*self.client), &parent.hash(), - parent.number().clone(), + *parent.number(), pre_digest.slot(), ) .map_err(|e| format!("failed to fetch epoch_descriptor: {}", e))? @@ -162,11 +162,11 @@ where .epoch_descriptor_for_child_of( descendent_query(&*self.client), &parent.hash(), - parent.number().clone(), + *parent.number(), slot, ) .map_err(|e| Error::StringError(format!("failed to fetch epoch_descriptor: {}", e)))? - .ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?; + .ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?; let epoch = epoch_changes .viable_epoch(&epoch_descriptor, |slot| { @@ -216,19 +216,19 @@ where .epoch_descriptor_for_child_of( descendent_query(&*self.client), &parent.hash(), - parent.number().clone(), + *parent.number(), slot, ) .map_err(|e| { Error::StringError(format!("failed to fetch epoch_descriptor: {}", e)) })? - .ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?; + .ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?; match epoch_descriptor { ViableEpochDescriptor::Signaled(identifier, _epoch_header) => { let epoch_mut = epoch_changes .epoch_mut(&identifier) - .ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?; + .ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?; // mutate the current epoch epoch_mut.authorities = self.authorities.clone(); @@ -236,7 +236,7 @@ where let next_epoch = ConsensusLog::NextEpochData(NextEpochDescriptor { authorities: self.authorities.clone(), // copy the old randomness - randomness: epoch_mut.randomness.clone(), + randomness: epoch_mut.randomness, }); vec![ @@ -268,11 +268,11 @@ where .epoch_descriptor_for_child_of( descendent_query(&*self.client), &parent.hash(), - parent.number().clone(), + *parent.number(), slot, ) .map_err(|e| Error::StringError(format!("failed to fetch epoch_descriptor: {}", e)))? - .ok_or_else(|| sp_consensus::Error::InvalidAuthoritiesSet)?; + .ok_or(sp_consensus::Error::InvalidAuthoritiesSet)?; // drop the lock drop(epoch_changes); // a quick check to see if we're in the authorities diff --git a/substrate/client/consensus/pow/src/lib.rs b/substrate/client/consensus/pow/src/lib.rs index 8885099ceb..6f9ee6f864 100644 --- a/substrate/client/consensus/pow/src/lib.rs +++ b/substrate/client/consensus/pow/src/lib.rs @@ -234,7 +234,7 @@ impl Clone select_chain: self.select_chain.clone(), client: self.client.clone(), create_inherent_data_providers: self.create_inherent_data_providers.clone(), - check_inherents_after: self.check_inherents_after.clone(), + check_inherents_after: self.check_inherents_after, can_author_with: self.can_author_with.clone(), } } @@ -652,21 +652,19 @@ where }, }; - let proposal = match proposer - .propose(inherent_data, inherent_digest, build_time.clone(), None) - .await - { - Ok(x) => x, - Err(err) => { - warn!( - target: "pow", - "Unable to propose new block for authoring. \ - Creating proposal failed: {}", - err, - ); - continue - }, - }; + let proposal = + match proposer.propose(inherent_data, inherent_digest, build_time, None).await { + Ok(x) => x, + Err(err) => { + warn!( + target: "pow", + "Unable to propose new block for authoring. \ + Creating proposal failed: {}", + err, + ); + continue + }, + }; let build = MiningBuild:: { metadata: MiningMetadata { @@ -710,8 +708,8 @@ fn fetch_seal(digest: Option<&DigestItem>, hash: B::Hash) -> Result::WrongEngine(*id).into()) + Err(Error::::WrongEngine(*id)) }, - _ => return Err(Error::::HeaderUnsealed(hash).into()), + _ => Err(Error::::HeaderUnsealed(hash)), } } diff --git a/substrate/client/consensus/pow/src/worker.rs b/substrate/client/consensus/pow/src/worker.rs index 42f82fb43e..750e78cd9a 100644 --- a/substrate/client/consensus/pow/src/worker.rs +++ b/substrate/client/consensus/pow/src/worker.rs @@ -295,7 +295,7 @@ impl Stream for UntilImportedOrTimeout { } } - let timeout = self.timeout.clone(); + let timeout = self.timeout; let inner_delay = self.inner_delay.get_or_insert_with(|| Delay::new(timeout)); match Future::poll(Pin::new(inner_delay), cx) { diff --git a/substrate/client/consensus/slots/src/aux_schema.rs b/substrate/client/consensus/slots/src/aux_schema.rs index 275b12ff48..eeaec68d36 100644 --- a/substrate/client/consensus/slots/src/aux_schema.rs +++ b/substrate/client/consensus/slots/src/aux_schema.rs @@ -63,7 +63,7 @@ where P: Clone + Encode + Decode + PartialEq, { // We don't check equivocations for old headers out of our capacity. - if slot_now.saturating_sub(*slot) > Slot::from(MAX_SLOT_CAPACITY) { + if slot_now.saturating_sub(*slot) > MAX_SLOT_CAPACITY { return Ok(None) } diff --git a/substrate/client/consensus/slots/src/lib.rs b/substrate/client/consensus/slots/src/lib.rs index a97469fbcc..a6fbc4bebc 100644 --- a/substrate/client/consensus/slots/src/lib.rs +++ b/substrate/client/consensus/slots/src/lib.rs @@ -606,7 +606,7 @@ pub fn proposing_remaining_duration( // if we defined a maximum portion of the slot for proposal then we must make sure the // lenience doesn't go over it let lenient_proposing_duration = - if let Some(ref max_block_proposal_slot_portion) = max_block_proposal_slot_portion { + if let Some(max_block_proposal_slot_portion) = max_block_proposal_slot_portion { std::cmp::min( lenient_proposing_duration, slot_info.duration.mul_f32(max_block_proposal_slot_portion.get()), diff --git a/substrate/client/db/src/bench.rs b/substrate/client/db/src/bench.rs index fe31d31dfe..8bc4a0f489 100644 --- a/substrate/client/db/src/bench.rs +++ b/substrate/client/db/src/bench.rs @@ -57,14 +57,14 @@ impl sp_state_machine::Storage> for StorageDb Result, String> { let prefixed_key = prefixed_key::>(key, prefix); if let Some(recorder) = &self.proof_recorder { - if let Some(v) = recorder.get(&key) { - return Ok(v.clone()) + if let Some(v) = recorder.get(key) { + return Ok(v) } let backend_value = self .db .get(0, &prefixed_key) .map_err(|e| format!("Database backend error: {:?}", e))?; - recorder.record(key.clone(), backend_value.clone()); + recorder.record(*key, backend_value.clone()); Ok(backend_value) } else { self.db @@ -114,7 +114,7 @@ impl BenchmarkingState { let mut state = BenchmarkingState { state: RefCell::new(None), db: Cell::new(None), - root: Cell::new(root.clone()), + root: Cell::new(root), genesis: Default::default(), genesis_root: Default::default(), record: Default::default(), @@ -123,7 +123,7 @@ impl BenchmarkingState { child_key_tracker: Default::default(), whitelist: Default::default(), proof_recorder: record_proof.then(Default::default), - proof_recorder_root: Cell::new(root.clone()), + proof_recorder_root: Cell::new(root), enable_tracking, }; @@ -143,7 +143,7 @@ impl BenchmarkingState { state_version, ); state.genesis = transaction.clone().drain(); - state.genesis_root = root.clone(); + state.genesis_root = root; state.commit(root, transaction, Vec::new(), Vec::new())?; state.record.take(); Ok(state) @@ -201,9 +201,7 @@ impl BenchmarkingState { let mut main_key_tracker = self.main_key_tracker.borrow_mut(); let key_tracker = if let Some(childtrie) = childtrie { - child_key_tracker - .entry(childtrie.to_vec()) - .or_insert_with(|| LinkedHashMap::new()) + child_key_tracker.entry(childtrie.to_vec()).or_insert_with(LinkedHashMap::new) } else { &mut main_key_tracker }; @@ -244,9 +242,7 @@ impl BenchmarkingState { let mut main_key_tracker = self.main_key_tracker.borrow_mut(); let key_tracker = if let Some(childtrie) = childtrie { - child_key_tracker - .entry(childtrie.to_vec()) - .or_insert_with(|| LinkedHashMap::new()) + child_key_tracker.entry(childtrie.to_vec()).or_insert_with(LinkedHashMap::new) } else { &mut main_key_tracker }; @@ -517,7 +513,7 @@ impl StateBackend> for BenchmarkingState { self.db.set(Some(db)); } - self.root.set(self.genesis_root.clone()); + self.root.set(self.genesis_root); self.reopen()?; self.wipe_tracker(); Ok(()) @@ -612,18 +608,17 @@ impl StateBackend> for BenchmarkingState { if proof_recorder_root == Default::default() || proof_size == 1 { // empty trie proof_size + } else if let Some(size) = proof.encoded_compact_size::>(proof_recorder_root) + { + size as u32 } else { - if let Some(size) = proof.encoded_compact_size::>(proof_recorder_root) { - size as u32 - } else { - panic!( - "proof rec root {:?}, root {:?}, genesis {:?}, rec_len {:?}", - self.proof_recorder_root.get(), - self.root.get(), - self.genesis_root, - proof_size, - ); - } + panic!( + "proof rec root {:?}, root {:?}, genesis {:?}, rec_len {:?}", + self.proof_recorder_root.get(), + self.root.get(), + self.genesis_root, + proof_size, + ); } }) } diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index 7350588973..72422eb82d 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -352,8 +352,8 @@ impl DatabaseSource { // // IIUC this is needed for polkadot to create its own dbs, so until it can use parity db // I would think rocksdb, but later parity-db. - DatabaseSource::Auto { paritydb_path, .. } => Some(&paritydb_path), - DatabaseSource::RocksDb { path, .. } | DatabaseSource::ParityDb { path } => Some(&path), + DatabaseSource::Auto { paritydb_path, .. } => Some(paritydb_path), + DatabaseSource::RocksDb { path, .. } | DatabaseSource::ParityDb { path } => Some(path), DatabaseSource::Custom(..) => None, } } @@ -478,7 +478,7 @@ impl BlockchainDb { if is_finalized { if with_state { - meta.finalized_state = Some((hash.clone(), number)); + meta.finalized_state = Some((hash, number)); } meta.finalized_number = number; meta.finalized_hash = hash; @@ -501,7 +501,7 @@ impl sc_client_api::blockchain::HeaderBackend for Blockcha } let header = utils::read_header(&*self.db, columns::KEY_LOOKUP, columns::HEADER, id)?; - cache_header(&mut cache, h.clone(), header.clone()); + cache_header(&mut cache, *h, header.clone()); Ok(header) }, BlockId::Number(_) => @@ -517,7 +517,7 @@ impl sc_client_api::blockchain::HeaderBackend for Blockcha genesis_hash: meta.genesis_hash, finalized_hash: meta.finalized_hash, finalized_number: meta.finalized_number, - finalized_state: meta.finalized_state.clone(), + finalized_state: meta.finalized_state, number_leaves: self.leaves.read().count(), block_gap: meta.block_gap, } @@ -540,10 +540,7 @@ impl sc_client_api::blockchain::HeaderBackend for Blockcha fn hash(&self, number: NumberFor) -> ClientResult> { self.header(BlockId::Number(number)) - .and_then(|maybe_header| match maybe_header { - Some(header) => Ok(Some(header.hash().clone())), - None => Ok(None), - }) + .map(|maybe_header| maybe_header.map(|header| header.hash())) } } @@ -621,7 +618,7 @@ impl sc_client_api::blockchain::Backend for BlockchainDb ClientResult { - Ok(self.meta.read().finalized_hash.clone()) + Ok(self.meta.read().finalized_hash) } fn leaves(&self) -> ClientResult> { @@ -765,8 +762,8 @@ impl BlockImportOperation { storage: Storage, state_version: StateVersion, ) -> ClientResult { - if storage.top.keys().any(|k| well_known_keys::is_child_storage_key(&k)) { - return Err(sp_blockchain::Error::InvalidState.into()) + if storage.top.keys().any(|k| well_known_keys::is_child_storage_key(k)) { + return Err(sp_blockchain::Error::InvalidState) } let child_delta = storage.children_default.iter().map(|(_storage_key, child_content)| { @@ -1063,7 +1060,7 @@ impl Backend { ) -> ClientResult { let is_archive_pruning = config.state_pruning.is_archive(); let blockchain = BlockchainDb::new(db.clone())?; - let map_e = |e: sc_state_db::Error| sp_blockchain::Error::from_state_db(e); + let map_e = sp_blockchain::Error::from_state_db; let state_db: StateDb<_, _> = StateDb::new( config.state_pruning.clone(), !db.supports_ref_counting(), @@ -1087,7 +1084,7 @@ impl Backend { is_archive: is_archive_pruning, io_stats: FrozenForDuration::new(std::time::Duration::from_secs(1)), state_usage: Arc::new(StateUsageStats::new()), - keep_blocks: config.keep_blocks.clone(), + keep_blocks: config.keep_blocks, genesis_state: RwLock::new(None), }; @@ -1135,7 +1132,7 @@ impl Backend { (meta.best_number - best_number).saturated_into::() > self.canonicalization_delay { - return Err(sp_blockchain::Error::SetHeadTooOld.into()) + return Err(sp_blockchain::Error::SetHeadTooOld) } let parent_exists = @@ -1154,16 +1151,16 @@ impl Backend { (&r.number, &r.hash) ); - return Err(::sp_blockchain::Error::NotInFinalizedChain.into()) + return Err(::sp_blockchain::Error::NotInFinalizedChain) } - retracted.push(r.hash.clone()); + retracted.push(r.hash); utils::remove_number_to_key_mapping(transaction, columns::KEY_LOOKUP, r.number)?; } // canonicalize: set the number lookup to map to this block's hash. for e in tree_route.enacted() { - enacted.push(e.hash.clone()); + enacted.push(e.hash); utils::insert_number_to_key_mapping( transaction, columns::KEY_LOOKUP, @@ -1199,8 +1196,7 @@ impl Backend { "Last finalized {:?} not parent of {:?}", last_finalized, header.hash() - )) - .into()) + ))) } Ok(()) } @@ -1217,7 +1213,7 @@ impl Backend { // TODO: ensure best chain contains this block. let number = *header.number(); self.ensure_sequential_finalization(header, last_finalized)?; - let with_state = sc_client_api::Backend::have_state_at(self, &hash, number); + let with_state = sc_client_api::Backend::have_state_at(self, hash, number); self.note_finalized(transaction, header, *hash, finalization_displaced, with_state)?; @@ -1264,9 +1260,10 @@ impl Backend { } trace!(target: "db", "Canonicalize block #{} ({:?})", new_canonical, hash); - let commit = self.storage.state_db.canonicalize_block(&hash).map_err( - |e: sc_state_db::Error| sp_blockchain::Error::from_state_db(e), - )?; + let commit = + self.storage.state_db.canonicalize_block(&hash).map_err( + sp_blockchain::Error::from_state_db::>, + )?; apply_state_commit(transaction, commit); } Ok(()) @@ -1282,7 +1279,7 @@ impl Backend { let mut meta_updates = Vec::with_capacity(operation.finalized_blocks.len()); let (best_num, mut last_finalized_hash, mut last_finalized_num, mut block_gap) = { let meta = self.blockchain.meta.read(); - (meta.best_number, meta.finalized_hash, meta.finalized_number, meta.block_gap.clone()) + (meta.best_number, meta.finalized_hash, meta.finalized_number, meta.block_gap) }; for (block, justification) in operation.finalized_blocks { @@ -1297,14 +1294,14 @@ impl Backend { &mut finalization_displaced_leaves, )?); last_finalized_hash = block_hash; - last_finalized_num = block_header.number().clone(); + last_finalized_num = *block_header.number(); } let imported = if let Some(pending_block) = operation.pending_block { let hash = pending_block.header.hash(); let parent_hash = *pending_block.header.parent_hash(); - let number = pending_block.header.number().clone(); + let number = *pending_block.header.number(); let existing_header = number <= best_num && self.blockchain.header(BlockId::hash(hash))?.is_some(); @@ -1352,7 +1349,7 @@ impl Backend { // memory to bootstrap consensus. It is queried for an initial list of // authorities, etc. *self.genesis_state.write() = Some(Arc::new(DbGenesisStorage::new( - pending_block.header.state_root().clone(), + *pending_block.header.state_root(), operation.db_updates.clone(), ))); } @@ -1411,7 +1408,7 @@ impl Backend { let commit = self .storage .state_db - .insert_block(&hash, number_u64, &pending_block.header.parent_hash(), changeset) + .insert_block(&hash, number_u64, pending_block.header.parent_hash(), changeset) .map_err(|e: sc_state_db::Error| { sp_blockchain::Error::from_state_db(e) })?; @@ -1419,7 +1416,7 @@ impl Backend { if number <= last_finalized_num { // Canonicalize in the db when re-importing existing blocks with state. let commit = self.storage.state_db.canonicalize_block(&hash).map_err( - |e: sc_state_db::Error| sp_blockchain::Error::from_state_db(e), + sp_blockchain::Error::from_state_db::>, )?; apply_state_commit(&mut transaction, commit); meta_updates.push(MetaUpdate { @@ -1549,11 +1546,8 @@ impl Backend { let number = header.number(); let hash = header.hash(); - let (enacted, retracted) = self.set_head_with_transaction( - &mut transaction, - hash.clone(), - (number.clone(), hash.clone()), - )?; + let (enacted, retracted) = + self.set_head_with_transaction(&mut transaction, hash, (*number, hash))?; meta_updates.push(MetaUpdate { hash, number: *number, @@ -1616,9 +1610,9 @@ impl Backend { displaced: &mut Option>>, with_state: bool, ) -> ClientResult<()> { - let f_num = f_header.number().clone(); + let f_num = *f_header.number(); - let lookup_key = utils::number_and_hash_to_lookup_key(f_num, f_hash.clone())?; + let lookup_key = utils::number_and_hash_to_lookup_key(f_num, f_hash)?; if with_state { transaction.set_from_vec(columns::META, meta_keys::FINALIZED_STATE, lookup_key.clone()); } @@ -1631,9 +1625,10 @@ impl Backend { .map(|c| f_num.saturated_into::() > c) .unwrap_or(true) { - let commit = self.storage.state_db.canonicalize_block(&f_hash).map_err( - |e: sc_state_db::Error| sp_blockchain::Error::from_state_db(e), - )?; + let commit = + self.storage.state_db.canonicalize_block(&f_hash).map_err( + sp_blockchain::Error::from_state_db::>, + )?; apply_state_commit(transaction, commit); } @@ -1664,18 +1659,18 @@ impl Backend { // Also discard all blocks from displaced branches for h in displaced.leaves() { let mut number = finalized; - let mut hash = h.clone(); + let mut hash = *h; // Follow displaced chains back until we reach a finalized block. // Since leaves are discarded due to finality, they can't have parents // that are canonical, but not yet finalized. So we stop deleting as soon as // we reach canonical chain. - while self.blockchain.hash(number)? != Some(hash.clone()) { - let id = BlockId::::hash(hash.clone()); + while self.blockchain.hash(number)? != Some(hash) { + let id = BlockId::::hash(hash); match self.blockchain.header(id)? { Some(header) => { self.prune_block(transaction, id)?; number = header.number().saturating_sub(One::one()); - hash = header.parent_hash().clone(); + hash = *header.parent_hash(); }, None => break, } @@ -1780,7 +1775,7 @@ fn apply_index_ops( // Bump ref counter let extrinsic = extrinsic.encode(); transaction.reference(columns::TRANSACTION, DbHash::from_slice(hash.as_ref())); - DbExtrinsic::Indexed { hash: hash.clone(), header: extrinsic } + DbExtrinsic::Indexed { hash: *hash, header: extrinsic } } else { match index_map.get(&(index as u32)) { Some((hash, size)) => { @@ -2063,8 +2058,7 @@ impl sc_client_api::backend::Backend for Backend { let update_finalized = best_number < finalized; - let key = - utils::number_and_hash_to_lookup_key(best_number.clone(), &best_hash)?; + let key = utils::number_and_hash_to_lookup_key(best_number, &best_hash)?; if update_finalized { transaction.set_from_vec( columns::META, @@ -2143,8 +2137,8 @@ impl sc_client_api::backend::Backend for Backend { return Err(sp_blockchain::Error::Backend(format!("Can't remove best block {:?}", hash))) } - let hdr = self.blockchain.header_metadata(hash.clone())?; - if !self.have_state_at(&hash, hdr.number) { + let hdr = self.blockchain.header_metadata(*hash)?; + if !self.have_state_at(hash, hdr.number) { return Err(sp_blockchain::Error::UnknownBlock(format!( "State already discarded for {:?}", hash @@ -2164,7 +2158,7 @@ impl sc_client_api::backend::Backend for Backend { apply_state_commit(&mut transaction, commit); } transaction.remove(columns::KEY_LOOKUP, hash.as_ref()); - leaves.revert(hash.clone(), hdr.number); + leaves.revert(*hash, hdr.number); leaves.prepare_transaction(&mut transaction, columns::META, meta_keys::LEAF_PREFIX); self.storage.db.commit(transaction)?; self.blockchain().remove_header_metadata(*hash); @@ -2185,8 +2179,7 @@ impl sc_client_api::backend::Backend for Backend { }; if is_genesis { if let Some(genesis_state) = &*self.genesis_state.read() { - let root = genesis_state.root.clone(); - let db_state = DbState::::new(genesis_state.clone(), root); + let db_state = DbState::::new(genesis_state.clone(), genesis_state.root); let state = RefTrackingState::new(db_state, self.storage.clone(), None); let caching_state = CachingState::new(state, self.shared_cache.clone(), None); let mut state = SyncingCachingState::new( @@ -2218,8 +2211,7 @@ impl sc_client_api::backend::Backend for Backend { if let Ok(()) = self.storage.state_db.pin(&hash) { let root = hdr.state_root; let db_state = DbState::::new(self.storage.clone(), root); - let state = - RefTrackingState::new(db_state, self.storage.clone(), Some(hash.clone())); + let state = RefTrackingState::new(db_state, self.storage.clone(), Some(hash)); let caching_state = CachingState::new(state, self.shared_cache.clone(), Some(hash)); Ok(SyncingCachingState::new( @@ -2241,7 +2233,7 @@ impl sc_client_api::backend::Backend for Backend { fn have_state_at(&self, hash: &Block::Hash, number: NumberFor) -> bool { if self.is_archive { - match self.blockchain.header_metadata(hash.clone()) { + match self.blockchain.header_metadata(*hash) { Ok(header) => sp_state_machine::Storage::get( self.storage.as_ref(), &header.state_root, diff --git a/substrate/client/db/src/offchain.rs b/substrate/client/db/src/offchain.rs index 4f0a77ce57..030a410981 100644 --- a/substrate/client/db/src/offchain.rs +++ b/substrate/client/db/src/offchain.rs @@ -104,7 +104,7 @@ impl sp_core::offchain::OffchainStorage for LocalStorage { { drop(key_lock); let key_lock = locks.get_mut(&key); - if let Some(_) = key_lock.and_then(Arc::get_mut) { + if key_lock.and_then(Arc::get_mut).is_some() { locks.remove(&key); } } @@ -114,7 +114,7 @@ impl sp_core::offchain::OffchainStorage for LocalStorage { /// Concatenate the prefix and key to create an offchain key in the db. pub(crate) fn concatenate_prefix_and_key(prefix: &[u8], key: &[u8]) -> Vec { - prefix.iter().chain(key.into_iter()).cloned().collect() + prefix.iter().chain(key.iter()).cloned().collect() } #[cfg(test)] diff --git a/substrate/client/db/src/storage_cache.rs b/substrate/client/db/src/storage_cache.rs index 5047087376..9dada92b06 100644 --- a/substrate/client/db/src/storage_cache.rs +++ b/substrate/client/db/src/storage_cache.rs @@ -360,9 +360,9 @@ impl CacheChanges { // Same block comitted twice with different state changes. // Treat it as reenacted/retracted. if is_best { - enacted.push(commit_hash.clone()); + enacted.push(*commit_hash); } else { - retracted.to_mut().push(commit_hash.clone()); + retracted.to_mut().push(*commit_hash); } } } @@ -371,7 +371,7 @@ impl CacheChanges { // Propagate cache only if committing on top of the latest canonical state // blocks are ordered by number and only one block with a given number is marked as // canonical (contributed to canonical state cache) - if let Some(_) = self.parent_hash { + if self.parent_hash.is_some() { let mut local_cache = self.local_cache.write(); if is_best { trace!( @@ -423,9 +423,9 @@ impl CacheChanges { storage: modifications, child_storage: child_modifications, number: *number, - hash: hash.clone(), + hash: *hash, is_canon: is_best, - parent: parent.clone(), + parent: *parent, }; let insert_at = cache .modifications @@ -564,7 +564,7 @@ impl>, B: BlockT> StateBackend> for Cachin let cache = self.cache.shared_cache.upgradable_read(); if Self::is_allowed(Some(key), None, &self.cache.parent_hash, &cache.modifications) { let mut cache = RwLockUpgradableReadGuard::upgrade(cache); - if let Some(entry) = cache.lru_hashes.get(key).map(|a| a.0.clone()) { + if let Some(entry) = cache.lru_hashes.get(key).map(|a| a.0) { trace!("Found hash in shared cache: {:?}", HexDisplay::from(&key)); return Ok(entry) } @@ -934,7 +934,7 @@ impl Drop for SyncingCachingState { let _lock = self.lock.read(); self.state_usage.merge_sm(caching_state.usage.take()); - if let Some(hash) = caching_state.cache.parent_hash.clone() { + if let Some(hash) = caching_state.cache.parent_hash { let is_best = self.meta.read().best_hash == hash; caching_state.cache.sync_cache(&[], &[], vec![], vec![], None, None, is_best); } diff --git a/substrate/client/db/src/upgrade.rs b/substrate/client/db/src/upgrade.rs index ec91a753ed..cd18554fb0 100644 --- a/substrate/client/db/src/upgrade.rs +++ b/substrate/client/db/src/upgrade.rs @@ -30,7 +30,7 @@ use kvdb_rocksdb::{Database, DatabaseConfig}; use sp_runtime::traits::Block as BlockT; /// Version file name. -const VERSION_FILE_NAME: &'static str = "db_version"; +const VERSION_FILE_NAME: &str = "db_version"; /// Current db version. const CURRENT_VERSION: u32 = 4; diff --git a/substrate/client/db/src/utils.rs b/substrate/client/db/src/utils.rs index 1798838ecc..d3cb9a994f 100644 --- a/substrate/client/db/src/utils.rs +++ b/substrate/client/db/src/utils.rs @@ -201,16 +201,16 @@ fn open_database_at( db_type: DatabaseType, ) -> sp_blockchain::Result>> { let db: Arc> = match &source { - DatabaseSource::ParityDb { path } => open_parity_db::(&path, db_type, true)?, + DatabaseSource::ParityDb { path } => open_parity_db::(path, db_type, true)?, DatabaseSource::RocksDb { path, cache_size } => - open_kvdb_rocksdb::(&path, db_type, true, *cache_size)?, + open_kvdb_rocksdb::(path, db_type, true, *cache_size)?, DatabaseSource::Custom(db) => db.clone(), DatabaseSource::Auto { paritydb_path, rocksdb_path, cache_size } => { // check if rocksdb exists first, if not, open paritydb - match open_kvdb_rocksdb::(&rocksdb_path, db_type, false, *cache_size) { + match open_kvdb_rocksdb::(rocksdb_path, db_type, false, *cache_size) { Ok(db) => db, Err(OpenDbError::NotEnabled(_)) | Err(OpenDbError::DoesNotExist) => - open_parity_db::(&paritydb_path, db_type, true)?, + open_parity_db::(paritydb_path, db_type, true)?, Err(_) => return Err(backend_err("cannot open rocksdb. corrupted database")), } }, @@ -234,7 +234,7 @@ type OpenDbResult = Result>, OpenDbError>; impl fmt::Display for OpenDbError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - OpenDbError::Internal(e) => write!(f, "{}", e.to_string()), + OpenDbError::Internal(e) => write!(f, "{}", e), OpenDbError::DoesNotExist => write!(f, "Database does not exist at given location"), OpenDbError::NotEnabled(feat) => { write!(f, "`{}` feature not enabled, database can not be opened", feat) @@ -300,7 +300,7 @@ fn open_kvdb_rocksdb( cache_size: usize, ) -> OpenDbResult { // first upgrade database to required version - match crate::upgrade::upgrade_db::(&path, db_type) { + match crate::upgrade::upgrade_db::(path, db_type) { // in case of missing version file, assume that database simply does not exist at given // location Ok(_) | Err(crate::upgrade::UpgradeError::MissingDatabaseVersionFile) => (), @@ -363,8 +363,7 @@ pub fn check_database_type( return Err(sp_blockchain::Error::Backend(format!( "Unexpected database type. Expected: {}", db_type.as_str() - )) - .into()) + ))) }, None => { let mut transaction = Transaction::new(); @@ -425,9 +424,9 @@ pub fn read_db( where Block: BlockT, { - block_id_to_lookup_key(db, col_index, id).and_then(|key| match key { - Some(key) => Ok(db.get(col, key.as_ref())), - None => Ok(None), + block_id_to_lookup_key(db, col_index, id).map(|key| match key { + Some(key) => db.get(col, key.as_ref()), + None => None, }) } @@ -442,9 +441,10 @@ pub fn remove_from_db( where Block: BlockT, { - block_id_to_lookup_key(db, col_index, id).and_then(|key| match key { - Some(key) => Ok(transaction.remove(col, key.as_ref())), - None => Ok(()), + block_id_to_lookup_key(db, col_index, id).map(|key| { + if let Some(key) = key { + transaction.remove(col, key.as_ref()); + } }) } @@ -458,7 +458,7 @@ pub fn read_header( match read_db(db, col_index, col, id)? { Some(header) => match Block::Header::decode(&mut &header[..]) { Ok(header) => Ok(Some(header)), - Err(_) => return Err(sp_blockchain::Error::Backend("Error decoding header".into())), + Err(_) => Err(sp_blockchain::Error::Backend("Error decoding header".into())), }, None => Ok(None), } diff --git a/substrate/client/executor/common/src/runtime_blob/data_segments_snapshot.rs b/substrate/client/executor/common/src/runtime_blob/data_segments_snapshot.rs index b44370e681..e65fc32f63 100644 --- a/substrate/client/executor/common/src/runtime_blob/data_segments_snapshot.rs +++ b/substrate/client/executor/common/src/runtime_blob/data_segments_snapshot.rs @@ -39,7 +39,7 @@ impl DataSegmentsSnapshot { .map(|mut segment| { // Just replace contents of the segment since the segments will be discarded later // anyway. - let contents = mem::replace(segment.value_mut(), vec![]); + let contents = mem::take(segment.value_mut()); let init_expr = match segment.offset() { Some(offset) => offset.code(), diff --git a/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs b/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs index 649ff51f28..08df4b32d5 100644 --- a/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs +++ b/substrate/client/executor/common/src/runtime_blob/runtime_blob.rs @@ -187,9 +187,7 @@ impl RuntimeBlob { } /// Returns an iterator of all globals which were exported by [`expose_mutable_globals`]. - pub(super) fn exported_internal_global_names<'module>( - &'module self, - ) -> impl Iterator { + pub(super) fn exported_internal_global_names(&self) -> impl Iterator { let exports = self.raw_module.export_section().map(|es| es.entries()).unwrap_or(&[]); exports.iter().filter_map(|export| match export.internal() { Internal::Global(_) if export.field().starts_with("exported_internal_global") => diff --git a/substrate/client/executor/common/src/sandbox.rs b/substrate/client/executor/common/src/sandbox.rs index fe14c0865c..1e925bd5a7 100644 --- a/substrate/client/executor/common/src/sandbox.rs +++ b/substrate/client/executor/common/src/sandbox.rs @@ -264,8 +264,8 @@ fn decode_environment_definition( let memory_ref = memories .get(memory_idx as usize) .cloned() - .ok_or_else(|| InstantiationError::EnvironmentDefinitionCorrupted)? - .ok_or_else(|| InstantiationError::EnvironmentDefinitionCorrupted)?; + .ok_or(InstantiationError::EnvironmentDefinitionCorrupted)? + .ok_or(InstantiationError::EnvironmentDefinitionCorrupted)?; memories_map.insert((module, field), memory_ref); }, } @@ -458,7 +458,7 @@ impl Store

{ }; let mem_idx = memories.len(); - memories.push(Some(memory.clone())); + memories.push(Some(memory)); Ok(mem_idx as u32) } @@ -472,7 +472,7 @@ impl Store
{ pub fn instance(&self, instance_idx: u32) -> Result> { self.instances .get(instance_idx as usize) - .ok_or_else(|| "Trying to access a non-existent instance")? + .ok_or("Trying to access a non-existent instance")? .as_ref() .map(|v| v.0.clone()) .ok_or_else(|| "Trying to access a torndown instance".into()) @@ -488,7 +488,7 @@ impl Store
{ self.instances .get(instance_idx as usize) .as_ref() - .ok_or_else(|| "Trying to access a non-existent instance")? + .ok_or("Trying to access a non-existent instance")? .as_ref() .map(|v| v.1.clone()) .ok_or_else(|| "Trying to access a torndown instance".into()) @@ -504,7 +504,7 @@ impl Store
{ self.memories .get(memory_idx as usize) .cloned() - .ok_or_else(|| "Trying to access a non-existent sandboxed memory")? + .ok_or("Trying to access a non-existent sandboxed memory")? .ok_or_else(|| "Trying to access a torndown sandboxed memory".into()) } @@ -564,7 +564,7 @@ impl Store
{ #[cfg(feature = "wasmer-sandbox")] BackendContext::Wasmer(ref context) => - wasmer_instantiate(&context, wasm, guest_env, state, sandbox_context)?, + wasmer_instantiate(context, wasm, guest_env, state, sandbox_context)?, }; Ok(UnregisteredInstance { sandbox_instance }) diff --git a/substrate/client/executor/common/src/sandbox/wasmer_backend.rs b/substrate/client/executor/common/src/sandbox/wasmer_backend.rs index ab585c7d15..29926141ed 100644 --- a/substrate/client/executor/common/src/sandbox/wasmer_backend.rs +++ b/substrate/client/executor/common/src/sandbox/wasmer_backend.rs @@ -113,7 +113,7 @@ pub fn instantiate( type Exports = HashMap; let mut exports_map = Exports::new(); - for import in module.imports().into_iter() { + for import in module.imports() { match import.ty() { // Nothing to do here wasmer::ExternType::Global(_) | wasmer::ExternType::Table(_) => (), @@ -121,7 +121,7 @@ pub fn instantiate( wasmer::ExternType::Memory(_) => { let exports = exports_map .entry(import.module().to_string()) - .or_insert(wasmer::Exports::new()); + .or_insert_with(wasmer::Exports::new); let memory = guest_env .imports @@ -173,7 +173,7 @@ pub fn instantiate( let exports = exports_map .entry(import.module().to_string()) - .or_insert(wasmer::Exports::new()); + .or_insert_with(wasmer::Exports::new); exports.insert(import.name(), wasmer::Extern::Function(function)); }, diff --git a/substrate/client/executor/common/src/sandbox/wasmi_backend.rs b/substrate/client/executor/common/src/sandbox/wasmi_backend.rs index 9c7c154b5b..03fa5dc06d 100644 --- a/substrate/client/executor/common/src/sandbox/wasmi_backend.rs +++ b/substrate/client/executor/common/src/sandbox/wasmi_backend.rs @@ -78,7 +78,7 @@ impl ImportResolver for Imports { // Here we use inner memory reference only to resolve the imports // without accessing the memory contents. All subsequent memory accesses // should happen through the wrapper, that enforces the memory access protocol. - let mem = wrapper.0.clone(); + let mem = wrapper.0; Ok(mem) } @@ -247,7 +247,7 @@ impl<'a> wasmi::Externals for GuestExternals<'a> { serialized_result_val_ptr, "Can't deallocate memory for dispatch thunk's result", ) - .and_then(|_| serialized_result_val) + .and(serialized_result_val) .and_then(|serialized_result_val| { let result_val = std::result::Result::::decode(&mut serialized_result_val.as_slice()) .map_err(|_| trap("Decoding Result failed!"))?; diff --git a/substrate/client/executor/src/native_executor.rs b/substrate/client/executor/src/native_executor.rs index 669780f2a4..ea060a89c1 100644 --- a/substrate/client/executor/src/native_executor.rs +++ b/substrate/client/executor/src/native_executor.rs @@ -253,7 +253,7 @@ where wasm_code: &[u8], ext: &mut dyn Externalities, ) -> std::result::Result, String> { - let runtime_blob = RuntimeBlob::uncompress_if_needed(&wasm_code) + let runtime_blob = RuntimeBlob::uncompress_if_needed(wasm_code) .map_err(|e| format!("Failed to create runtime blob: {:?}", e))?; if let Some(version) = crate::wasm_runtime::read_embedded_version(&runtime_blob) @@ -493,8 +493,7 @@ impl RuntimeSpawn for RuntimeInstanceSpawn { fn join(&self, handle: u64) -> Vec { let receiver = self.tasks.lock().remove(&handle).expect("No task for the handle"); - let output = receiver.recv().expect("Spawned task panicked for the handle"); - output + receiver.recv().expect("Spawned task panicked for the handle") } } diff --git a/substrate/client/executor/src/wasm_runtime.rs b/substrate/client/executor/src/wasm_runtime.rs index 952130e980..9c07dd7abf 100644 --- a/substrate/client/executor/src/wasm_runtime.rs +++ b/substrate/client/executor/src/wasm_runtime.rs @@ -368,7 +368,7 @@ pub fn read_embedded_version(blob: &RuntimeBlob) -> Result sandbox::SandboxContext for SandboxContext<'a> { match result { Ok(Some(RuntimeValue::I64(val))) => Ok(val), - Ok(_) => return Err("Supervisor function returned unexpected result!".into()), + Ok(_) => Err("Supervisor function returned unexpected result!".into()), Err(err) => Err(Error::Sandbox(err.to_string())), } } @@ -161,7 +161,7 @@ impl Sandbox for FunctionExecutor { Ok(buffer) => buffer, }; - if let Err(_) = self.memory.set(buf_ptr.into(), &buffer) { + if self.memory.set(buf_ptr.into(), &buffer).is_err() { return Ok(sandbox_env::ERR_OUT_OF_BOUNDS) } @@ -185,7 +185,7 @@ impl Sandbox for FunctionExecutor { Ok(buffer) => buffer, }; - if let Err(_) = sandboxed_memory.write_from(Pointer::new(offset as u32), &buffer) { + if sandboxed_memory.write_from(Pointer::new(offset as u32), &buffer).is_err() { return Ok(sandbox_env::ERR_OUT_OF_BOUNDS) } @@ -241,9 +241,9 @@ impl Sandbox for FunctionExecutor { Ok(None) => Ok(sandbox_env::ERR_OK), Ok(Some(val)) => { // Serialize return value and write it back into the memory. - sp_wasm_interface::ReturnValue::Value(val.into()).using_encoded(|val| { + sp_wasm_interface::ReturnValue::Value(val).using_encoded(|val| { if val.len() > return_val_len as usize { - Err("Return value buffer is too small")?; + return Err("Return value buffer is too small".into()) } self.write_memory(return_val, val).map_err(|_| "Return value buffer is OOB")?; Ok(sandbox_env::ERR_OK) @@ -272,11 +272,11 @@ impl Sandbox for FunctionExecutor { let table = self .table .as_ref() - .ok_or_else(|| "Runtime doesn't have a table; sandbox is unavailable")?; + .ok_or("Runtime doesn't have a table; sandbox is unavailable")?; table .get(dispatch_thunk_id) .map_err(|_| "dispatch_thunk_idx is out of the table bounds")? - .ok_or_else(|| "dispatch_thunk_idx points on an empty table entry")? + .ok_or("dispatch_thunk_idx points on an empty table entry")? }; let guest_env = @@ -458,9 +458,9 @@ impl wasmi::Externals for FunctionExecutor { fn get_mem_instance(module: &ModuleRef) -> Result { Ok(module .export_by_name("memory") - .ok_or_else(|| Error::InvalidMemoryReference)? + .ok_or(Error::InvalidMemoryReference)? .as_memory() - .ok_or_else(|| Error::InvalidMemoryReference)? + .ok_or(Error::InvalidMemoryReference)? .clone()) } @@ -469,9 +469,9 @@ fn get_mem_instance(module: &ModuleRef) -> Result { fn get_heap_base(module: &ModuleRef) -> Result { let heap_base_val = module .export_by_name("__heap_base") - .ok_or_else(|| Error::HeapBaseNotFoundOrInvalid)? + .ok_or(Error::HeapBaseNotFoundOrInvalid)? .as_global() - .ok_or_else(|| Error::HeapBaseNotFoundOrInvalid)? + .ok_or(Error::HeapBaseNotFoundOrInvalid)? .get(); match heap_base_val { @@ -564,7 +564,7 @@ fn call_in_wasm_module( match result { Ok(Some(I64(r))) => { let (ptr, length) = unpack_ptr_and_len(r as u64); - memory.get(ptr.into(), length as usize).map_err(|_| Error::Runtime) + memory.get(ptr, length as usize).map_err(|_| Error::Runtime) }, Err(e) => { trace!( @@ -572,7 +572,7 @@ fn call_in_wasm_module( "Failed to execute code with {} pages", memory.current_size().0, ); - Err(e.into()) + Err(e) }, _ => Err(Error::InvalidReturn), } diff --git a/substrate/client/executor/wasmtime/src/host.rs b/substrate/client/executor/wasmtime/src/host.rs index 376eba8682..0cb64820fa 100644 --- a/substrate/client/executor/wasmtime/src/host.rs +++ b/substrate/client/executor/wasmtime/src/host.rs @@ -243,7 +243,7 @@ impl<'a> Sandbox for HostContext<'a> { // Serialize return value and write it back into the memory. sp_wasm_interface::ReturnValue::Value(val.into()).using_encoded(|val| { if val.len() > return_val_len as usize { - Err("Return value buffer is too small")?; + return Err("Return value buffer is too small".into()) } ::write_memory(self, return_val, val) .map_err(|_| "can't write return value")?; @@ -273,19 +273,18 @@ impl<'a> Sandbox for HostContext<'a> { .caller .data() .table() - .ok_or_else(|| "Runtime doesn't have a table; sandbox is unavailable")?; + .ok_or("Runtime doesn't have a table; sandbox is unavailable")?; let table_item = table.get(&mut self.caller, dispatch_thunk_id); table_item - .ok_or_else(|| "dispatch_thunk_id is out of bounds")? + .ok_or("dispatch_thunk_id is out of bounds")? .funcref() - .ok_or_else(|| "dispatch_thunk_idx should be a funcref")? - .ok_or_else(|| "dispatch_thunk_idx should point to actual func")? + .ok_or("dispatch_thunk_idx should be a funcref")? + .ok_or("dispatch_thunk_idx should point to actual func")? .clone() }; - let guest_env = match sandbox::GuestEnvironment::decode(&self.sandbox_store(), raw_env_def) - { + let guest_env = match sandbox::GuestEnvironment::decode(self.sandbox_store(), raw_env_def) { Ok(guest_env) => guest_env, Err(_) => return Ok(sandbox_env::ERR_MODULE as u32), }; @@ -304,7 +303,7 @@ impl<'a> Sandbox for HostContext<'a> { wasm, guest_env, state, - &mut SandboxContext { host_context: self, dispatch_thunk: dispatch_thunk.clone() }, + &mut SandboxContext { host_context: self, dispatch_thunk }, ) })); @@ -316,7 +315,7 @@ impl<'a> Sandbox for HostContext<'a> { }; let instance_idx_or_err_code = match result { - Ok(instance) => instance.register(&mut self.sandbox_store_mut(), dispatch_thunk), + Ok(instance) => instance.register(self.sandbox_store_mut(), dispatch_thunk), Err(sandbox::InstantiationError::StartTrapped) => sandbox_env::ERR_EXECUTION, Err(_) => sandbox_env::ERR_MODULE, }; @@ -366,7 +365,7 @@ impl<'a, 'b> sandbox::SandboxContext for SandboxContext<'a, 'b> { if let Some(ret_val) = ret_vals[0].i64() { Ok(ret_val) } else { - return Err("Supervisor function returned unexpected result!".into()) + Err("Supervisor function returned unexpected result!".into()) }, Err(err) => Err(err.to_string().into()), } diff --git a/substrate/client/finality-grandpa/rpc/src/report.rs b/substrate/client/finality-grandpa/rpc/src/report.rs index 24d0b5ab0d..8c04ca28ef 100644 --- a/substrate/client/finality-grandpa/rpc/src/report.rs +++ b/substrate/client/finality-grandpa/rpc/src/report.rs @@ -88,10 +88,10 @@ impl RoundState { voters: &HashSet, ) -> Result { let prevotes = &round_state.prevote_ids; - let missing_prevotes = voters.difference(&prevotes).cloned().collect(); + let missing_prevotes = voters.difference(prevotes).cloned().collect(); let precommits = &round_state.precommit_ids; - let missing_precommits = voters.difference(&precommits).cloned().collect(); + let missing_precommits = voters.difference(precommits).cloned().collect(); Ok(Self { round: round.try_into()?, diff --git a/substrate/client/finality-grandpa/src/authorities.rs b/substrate/client/finality-grandpa/src/authorities.rs index 668fe5f269..c2d4437198 100644 --- a/substrate/client/finality-grandpa/src/authorities.rs +++ b/substrate/client/finality-grandpa/src/authorities.rs @@ -557,8 +557,7 @@ where fork_tree::FinalizationResult::Changed(change) => { status.changed = true; - let pending_forced_changes = - std::mem::replace(&mut self.pending_forced_changes, Vec::new()); + let pending_forced_changes = std::mem::take(&mut self.pending_forced_changes); // we will keep all forced changes for any later blocks and that are a // descendent of the finalized block (i.e. they are part of this branch). diff --git a/substrate/client/finality-grandpa/src/aux_schema.rs b/substrate/client/finality-grandpa/src/aux_schema.rs index 0ac9ba9e64..25ed4a3f49 100644 --- a/substrate/client/finality-grandpa/src/aux_schema.rs +++ b/substrate/client/finality-grandpa/src/aux_schema.rs @@ -430,7 +430,7 @@ where // reset. let set_state = VoterSetState::::live( new_set.set_id, - &set, + set, (new_set.canon_hash, new_set.canon_number), ); let encoded = set_state.encode(); diff --git a/substrate/client/finality-grandpa/src/communication/gossip.rs b/substrate/client/finality-grandpa/src/communication/gossip.rs index c39e2e82a6..250e640cbf 100644 --- a/substrate/client/finality-grandpa/src/communication/gossip.rs +++ b/substrate/client/finality-grandpa/src/communication/gossip.rs @@ -504,13 +504,13 @@ impl Peers { fn new_peer(&mut self, who: PeerId, role: ObservedRole) { match role { ObservedRole::Authority if self.first_stage_peers.len() < LUCKY_PEERS => { - self.first_stage_peers.insert(who.clone()); + self.first_stage_peers.insert(who); }, ObservedRole::Authority if self.second_stage_peers.len() < LUCKY_PEERS => { - self.second_stage_peers.insert(who.clone()); + self.second_stage_peers.insert(who); }, ObservedRole::Light if self.lucky_light_peers.len() < LUCKY_PEERS => { - self.lucky_light_peers.insert(who.clone()); + self.lucky_light_peers.insert(who); }, _ => {}, } @@ -590,11 +590,8 @@ impl Peers { // - third set: LUCKY_PEERS random light client peers let shuffled_peers = { - let mut peers = self - .inner - .iter() - .map(|(peer_id, info)| (*peer_id, info.clone())) - .collect::>(); + let mut peers = + self.inner.iter().map(|(peer_id, info)| (*peer_id, info)).collect::>(); peers.shuffle(&mut rand::thread_rng()); peers @@ -1103,7 +1100,7 @@ impl Inner { // won't be able to reply since they don't follow the full GRANDPA // protocol and therefore might not have the vote data available. if let (Some(peer), Some(local_view)) = (self.peers.peer(who), &self.local_view) { - if self.catch_up_config.request_allowed(&peer) && + if self.catch_up_config.request_allowed(peer) && peer.view.set_id == local_view.set_id && peer.view.round.0.saturating_sub(CATCH_UP_THRESHOLD) > local_view.round.0 { @@ -1195,7 +1192,7 @@ impl Inner { return (false, None) } else { // report peer for timeout - Some((peer.clone(), cost::CATCH_UP_REQUEST_TIMEOUT)) + Some((*peer, cost::CATCH_UP_REQUEST_TIMEOUT)) } }, PendingCatchUp::Processing { instant, .. } => { @@ -1209,7 +1206,7 @@ impl Inner { }; self.pending_catch_up = PendingCatchUp::Requesting { - who: who.clone(), + who: *who, request: catch_up_request.clone(), instant: Instant::now(), }; @@ -1488,7 +1485,7 @@ impl sc_network_gossip::Validator for GossipValidator sc_network_gossip::Validator for GossipValidator { - self.report(who.clone(), cb); + self.report(*who, cb); context.broadcast_message(topic, data.to_vec(), false); sc_network_gossip::ValidationResult::ProcessAndKeep(topic) }, Action::ProcessAndDiscard(topic, cb) => { - self.report(who.clone(), cb); + self.report(*who, cb); sc_network_gossip::ValidationResult::ProcessAndDiscard(topic) }, Action::Discard(cb) => { - self.report(who.clone(), cb); + self.report(*who, cb); sc_network_gossip::ValidationResult::Discard }, } @@ -1572,7 +1569,7 @@ impl sc_network_gossip::Validator for GossipValidator return false, Some(x) => x, }; @@ -1583,11 +1580,9 @@ impl sc_network_gossip::Validator for GossipValidator( let mut total_weight = 0; for id in votes { - if let Some(weight) = voters.get(&id).map(|info| info.weight()) { + if let Some(weight) = voters.get(id).map(|info| info.weight()) { total_weight += weight.get(); if total_weight > full_threshold { return Err(cost::MALFORMED_CATCH_UP) diff --git a/substrate/client/finality-grandpa/src/environment.rs b/substrate/client/finality-grandpa/src/environment.rs index 6ffcdc719a..63c8697053 100644 --- a/substrate/client/finality-grandpa/src/environment.rs +++ b/substrate/client/finality-grandpa/src/environment.rs @@ -451,7 +451,7 @@ impl, SC, VR> Environment) -> Result>, Error>, { self.voter_set_state.with(|voter_set_state| { - if let Some(set_state) = f(&voter_set_state)? { + if let Some(set_state) = f(voter_set_state)? { *voter_set_state = set_state; if let Some(metrics) = self.metrics.as_ref() { @@ -987,11 +987,9 @@ where let mut current_rounds = current_rounds.clone(); current_rounds.remove(&round); - // NOTE: this condition should always hold as GRANDPA rounds are always + // NOTE: this entry should always exist as GRANDPA rounds are always // started in increasing order, still it's better to play it safe. - if !current_rounds.contains_key(&(round + 1)) { - current_rounds.insert(round + 1, HasVoted::No); - } + current_rounds.entry(round + 1).or_insert(HasVoted::No); let set_state = VoterSetState::::Live { completed_rounds, current_rounds }; @@ -1046,7 +1044,7 @@ where .votes .extend(historical_votes.seen().iter().skip(n_existing_votes).cloned()); already_completed.state = state; - crate::aux_schema::write_concluded_round(&*self.client, &already_completed)?; + crate::aux_schema::write_concluded_round(&*self.client, already_completed)?; } let set_state = VoterSetState::::Live { diff --git a/substrate/client/finality-grandpa/src/import.rs b/substrate/client/finality-grandpa/src/import.rs index ae5839d0c2..eefb3d3f0a 100644 --- a/substrate/client/finality-grandpa/src/import.rs +++ b/substrate/client/finality-grandpa/src/import.rs @@ -439,8 +439,7 @@ where // This code may be removed once warp sync to an old runtime is no longer needed. for prefix in ["GrandpaFinality", "Grandpa"] { let k = [twox_128(prefix.as_bytes()), twox_128(b"CurrentSetId")].concat(); - if let Ok(Some(id)) = - self.inner.storage(&id, &sc_client_api::StorageKey(k.to_vec())) + if let Ok(Some(id)) = self.inner.storage(id, &sc_client_api::StorageKey(k.to_vec())) { if let Ok(id) = SetId::decode(&mut id.0.as_ref()) { return Ok(id) @@ -451,7 +450,7 @@ where } else { self.inner .runtime_api() - .current_set_id(&id) + .current_set_id(id) .map_err(|e| ConsensusError::ClientImport(e.to_string())) } } @@ -732,7 +731,7 @@ impl GrandpaBlockImport Result, GrandpaError> { - environment::ancestry(&self.client, base, block) + environment::ancestry(self.client, base, block) } } @@ -193,13 +193,13 @@ where ); let observer_work = ObserverWork::new( - client.clone(), + client, network, persistent_data, config.keystore, voter_commands_rx, Some(justification_sender), - telemetry.clone(), + telemetry, ); let observer_work = observer_work.map_ok(|_| ()).map_err(|e| { diff --git a/substrate/client/finality-grandpa/src/voting_rule.rs b/substrate/client/finality-grandpa/src/voting_rule.rs index 749c504a05..209b0f1b33 100644 --- a/substrate/client/finality-grandpa/src/voting_rule.rs +++ b/substrate/client/finality-grandpa/src/voting_rule.rs @@ -125,7 +125,7 @@ where let current_target = current_target.clone(); // find the block at the given target height - Box::pin(std::future::ready(find_target(&*backend, target_number.clone(), ¤t_target))) + Box::pin(std::future::ready(find_target(&*backend, target_number, ¤t_target))) } } diff --git a/substrate/client/finality-grandpa/src/warp_proof.rs b/substrate/client/finality-grandpa/src/warp_proof.rs index bdb8e36373..90f6828a11 100644 --- a/substrate/client/finality-grandpa/src/warp_proof.rs +++ b/substrate/client/finality-grandpa/src/warp_proof.rs @@ -205,7 +205,7 @@ impl WarpSyncProof { let hash = proof.header.hash(); let number = *proof.header.number(); - if let Some((set_id, list)) = hard_forks.get(&(hash.clone(), number)) { + if let Some((set_id, list)) = hard_forks.get(&(hash, number)) { current_set_id = *set_id; current_authorities = list.clone(); } else { diff --git a/substrate/client/informant/src/lib.rs b/substrate/client/informant/src/lib.rs index 88a500a3a9..5dca77f1a7 100644 --- a/substrate/client/informant/src/lib.rs +++ b/substrate/client/informant/src/lib.rs @@ -116,7 +116,7 @@ where if let Some((ref last_num, ref last_hash)) = last_best { if n.header.parent_hash() != last_hash && n.is_new_best { let maybe_ancestor = - sp_blockchain::lowest_common_ancestor(&*client, last_hash.clone(), n.hash); + sp_blockchain::lowest_common_ancestor(&*client, *last_hash, n.hash); match maybe_ancestor { Ok(ref ancestor) if ancestor.hash != *last_hash => info!( @@ -135,13 +135,13 @@ where } if n.is_new_best { - last_best = Some((n.header.number().clone(), n.hash.clone())); + last_best = Some((*n.header.number(), n.hash)); } // If we already printed a message for a given block recently, // we should not print it again. if !last_blocks.contains(&n.hash) { - last_blocks.push_back(n.hash.clone()); + last_blocks.push_back(n.hash); if last_blocks.len() > max_blocks_to_track { last_blocks.pop_front(); diff --git a/substrate/client/keystore/src/local.rs b/substrate/client/keystore/src/local.rs index 9f6f18d0c2..19be6715ff 100644 --- a/substrate/client/keystore/src/local.rs +++ b/substrate/client/keystore/src/local.rs @@ -198,7 +198,7 @@ impl SyncCryptoStore for LocalKeystore { .0 .read() .key_pair_by_type::(&pub_key, id) - .map_err(|e| TraitError::from(e))?; + .map_err(TraitError::from)?; key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose() }, sr25519::CRYPTO_ID => { @@ -209,7 +209,7 @@ impl SyncCryptoStore for LocalKeystore { .0 .read() .key_pair_by_type::(&pub_key, id) - .map_err(|e| TraitError::from(e))?; + .map_err(TraitError::from)?; key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose() }, ecdsa::CRYPTO_ID => { @@ -220,7 +220,7 @@ impl SyncCryptoStore for LocalKeystore { .0 .read() .key_pair_by_type::(&pub_key, id) - .map_err(|e| TraitError::from(e))?; + .map_err(TraitError::from)?; key_pair.map(|k| k.sign(msg).encode()).map(Ok).transpose() }, _ => Err(TraitError::KeyNotSupported(id)), @@ -320,7 +320,7 @@ impl SyncCryptoStore for LocalKeystore { fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { public_keys .iter() - .all(|(p, t)| self.0.read().key_phrase_by_type(&p, *t).ok().flatten().is_some()) + .all(|(p, t)| self.0.read().key_phrase_by_type(p, *t).ok().flatten().is_some()) } fn sr25519_vrf_sign( @@ -536,7 +536,7 @@ impl KeystoreInner { if let Some(name) = path.file_name().and_then(|n| n.to_str()) { match hex::decode(name) { Ok(ref hex) if hex.len() > 4 => { - if &hex[0..4] != &id.0 { + if hex[0..4] != id.0 { continue } let public = hex[4..].to_vec(); diff --git a/substrate/client/network-gossip/src/state_machine.rs b/substrate/client/network-gossip/src/state_machine.rs index 4f06819df6..8a016cbaab 100644 --- a/substrate/client/network-gossip/src/state_machine.rs +++ b/substrate/client/network-gossip/src/state_machine.rs @@ -88,8 +88,7 @@ impl<'g, 'p, B: BlockT> ValidatorContext for NetworkContext<'g, 'p, B> { /// Send addressed message to a peer. fn send_message(&mut self, who: &PeerId, message: Vec) { - self.network - .write_notification(who.clone(), self.gossip.protocol.clone(), message); + self.network.write_notification(*who, self.gossip.protocol.clone(), message); } /// Send all messages with given topic to a peer. @@ -116,13 +115,13 @@ where for (message_hash, topic, message) in messages.clone() { let intent = match intent { MessageIntent::Broadcast { .. } => - if peer.known_messages.contains(&message_hash) { + if peer.known_messages.contains(message_hash) { continue } else { MessageIntent::Broadcast }, MessageIntent::PeriodicRebroadcast => { - if peer.known_messages.contains(&message_hash) { + if peer.known_messages.contains(message_hash) { MessageIntent::PeriodicRebroadcast } else { // peer doesn't know message, so the logic should treat it as an @@ -133,11 +132,11 @@ where other => other, }; - if !message_allowed(id, intent, &topic, &message) { + if !message_allowed(id, intent, topic, message) { continue } - peer.known_messages.insert(message_hash.clone()); + peer.known_messages.insert(*message_hash); tracing::trace!( target: "gossip", @@ -146,7 +145,7 @@ where ?message, "Propagating message", ); - network.write_notification(id.clone(), protocol.clone(), message.clone()); + network.write_notification(*id, protocol.clone(), message.clone()); } } } @@ -198,8 +197,7 @@ impl ConsensusGossip { ?role, "Registering peer", ); - self.peers - .insert(who.clone(), PeerConsensus { known_messages: Default::default() }); + self.peers.insert(who, PeerConsensus { known_messages: Default::default() }); let validator = self.validator.clone(); let mut context = NetworkContext { gossip: self, network }; @@ -213,7 +211,7 @@ impl ConsensusGossip { message: Vec, sender: Option, ) { - if self.known_messages.put(message_hash.clone(), ()).is_none() { + if self.known_messages.put(message_hash, ()).is_none() { self.messages.push(MessageEntry { message_hash, topic, message, sender }); if let Some(ref metrics) = self.metrics { @@ -319,10 +317,7 @@ impl ConsensusGossip { self.messages .iter() .filter(move |e| e.topic == topic) - .map(|entry| TopicNotification { - message: entry.message.clone(), - sender: entry.sender.clone(), - }) + .map(|entry| TopicNotification { message: entry.message.clone(), sender: entry.sender }) } /// Register incoming messages and return the ones that are new and valid (according to a gossip @@ -355,7 +350,7 @@ impl ConsensusGossip { protocol = %self.protocol, "Ignored already known message", ); - network.report_peer(who.clone(), rep::DUPLICATE_GOSSIP); + network.report_peer(who, rep::DUPLICATE_GOSSIP); continue } @@ -393,15 +388,13 @@ impl ConsensusGossip { }, }; - network.report_peer(who.clone(), rep::GOSSIP_SUCCESS); + network.report_peer(who, rep::GOSSIP_SUCCESS); peer.known_messages.insert(message_hash); - to_forward.push(( - topic, - TopicNotification { message: message.clone(), sender: Some(who.clone()) }, - )); + to_forward + .push((topic, TopicNotification { message: message.clone(), sender: Some(who) })); if keep { - self.register_message_hashed(message_hash, topic, message, Some(who.clone())); + self.register_message_hashed(message_hash, topic, message, Some(who)); } } @@ -431,7 +424,7 @@ impl ConsensusGossip { continue } - peer.known_messages.insert(entry.message_hash.clone()); + peer.known_messages.insert(entry.message_hash); tracing::trace!( target: "gossip", @@ -440,11 +433,7 @@ impl ConsensusGossip { ?entry.message, "Sending topic message", ); - network.write_notification( - who.clone(), - self.protocol.clone(), - entry.message.clone(), - ); + network.write_notification(*who, self.protocol.clone(), entry.message.clone()); } } } @@ -489,7 +478,7 @@ impl ConsensusGossip { ); peer.known_messages.insert(message_hash); - network.write_notification(who.clone(), self.protocol.clone(), message); + network.write_notification(*who, self.protocol.clone(), message); } } diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index 5ff3ba1ad4..b0bf3d6a1c 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -434,7 +434,6 @@ where "Trying to send warp sync request when no protocol is configured {:?}", request, ); - return }, }, CustomMessageOutcome::NotificationStreamOpened { @@ -449,7 +448,7 @@ where protocol, negotiated_fallback, role: reported_roles_to_observed_role(roles), - notifications_sink: notifications_sink.clone(), + notifications_sink, }); }, CustomMessageOutcome::NotificationStreamReplaced { diff --git a/substrate/client/network/src/bitswap.rs b/substrate/client/network/src/bitswap.rs index c46990997c..d5039faaca 100644 --- a/substrate/client/network/src/bitswap.rs +++ b/substrate/client/network/src/bitswap.rs @@ -65,7 +65,7 @@ const MAX_RESPONSE_QUEUE: usize = 20; // Max number of blocks per wantlist const MAX_WANTED_BLOCKS: usize = 16; -const PROTOCOL_NAME: &'static [u8] = b"/ipfs/bitswap/1.2.0"; +const PROTOCOL_NAME: &[u8] = b"/ipfs/bitswap/1.2.0"; type FutureResult = Pin> + Send>>; @@ -167,10 +167,10 @@ impl Prefix { let version = varint_encode::u64(self.version.into(), &mut buf); res.extend_from_slice(version); let mut buf = varint_encode::u64_buffer(); - let codec = varint_encode::u64(self.codec.into(), &mut buf); + let codec = varint_encode::u64(self.codec, &mut buf); res.extend_from_slice(codec); let mut buf = varint_encode::u64_buffer(); - let mh_type = varint_encode::u64(self.mh_type.into(), &mut buf); + let mh_type = varint_encode::u64(self.mh_type, &mut buf); res.extend_from_slice(mh_type); let mut buf = varint_encode::u64_buffer(); let mh_len = varint_encode::u64(self.mh_len as u64, &mut buf); diff --git a/substrate/client/network/src/block_request_handler.rs b/substrate/client/network/src/block_request_handler.rs index 2e238c0163..7458f421af 100644 --- a/substrate/client/network/src/block_request_handler.rs +++ b/substrate/client/network/src/block_request_handler.rs @@ -197,7 +197,7 @@ where peer: *peer, max_blocks, direction, - from: from_block_id.clone(), + from: from_block_id, attributes, support_multiple_justifications, }; diff --git a/substrate/client/network/src/discovery.rs b/substrate/client/network/src/discovery.rs index a916ffda07..ae65d4f23c 100644 --- a/substrate/client/network/src/discovery.rs +++ b/substrate/client/network/src/discovery.rs @@ -287,7 +287,7 @@ impl DiscoveryBehaviour { for b in k.kbuckets() { for e in b.iter() { if !peers.contains(e.node.key.preimage()) { - peers.insert(e.node.key.preimage().clone()); + peers.insert(*e.node.key.preimage()); } } } @@ -307,7 +307,7 @@ impl DiscoveryBehaviour { k.add_address(&peer_id, addr.clone()); } - self.pending_events.push_back(DiscoveryOut::Discovered(peer_id.clone())); + self.pending_events.push_back(DiscoveryOut::Discovered(peer_id)); addrs_list.push(addr); } } @@ -718,7 +718,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { // Poll the stream that fires when we need to start a random Kademlia query. if let Some(next_kad_random_query) = self.next_kad_random_query.as_mut() { - while let Poll::Ready(_) = next_kad_random_query.poll_unpin(cx) { + while next_kad_random_query.poll_unpin(cx).is_ready() { let actually_started = if self.num_connections < self.discovery_only_if_under_num { let random_peer_id = PeerId::random(); debug!( @@ -815,7 +815,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { DiscoveryOut::ValueFound( results, - stats.duration().unwrap_or_else(Default::default), + stats.duration().unwrap_or_default(), ) }, Err(e @ libp2p::kad::GetRecordError::NotFound { .. }) => { @@ -826,7 +826,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { ); DiscoveryOut::ValueNotFound( e.into_key(), - stats.duration().unwrap_or_else(Default::default), + stats.duration().unwrap_or_default(), ) }, Err(e) => { @@ -837,7 +837,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { ); DiscoveryOut::ValueNotFound( e.into_key(), - stats.duration().unwrap_or_else(Default::default), + stats.duration().unwrap_or_default(), ) }, }; @@ -851,7 +851,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { let ev = match res { Ok(ok) => DiscoveryOut::ValuePut( ok.key, - stats.duration().unwrap_or_else(Default::default), + stats.duration().unwrap_or_default(), ), Err(e) => { debug!( @@ -861,7 +861,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { ); DiscoveryOut::ValuePutFailed( e.into_key(), - stats.duration().unwrap_or_else(Default::default), + stats.duration().unwrap_or_default(), ) }, }; diff --git a/substrate/client/network/src/light_client_requests.rs b/substrate/client/network/src/light_client_requests.rs index c77416003f..d36158b2a3 100644 --- a/substrate/client/network/src/light_client_requests.rs +++ b/substrate/client/network/src/light_client_requests.rs @@ -27,11 +27,7 @@ use std::time::Duration; /// Generate the light client protocol name from chain specific protocol identifier. fn generate_protocol_name(protocol_id: &ProtocolId) -> String { - let mut s = String::new(); - s.push_str("/"); - s.push_str(protocol_id.as_ref()); - s.push_str("/light/2"); - s + format!("/{}/light/2", protocol_id.as_ref()) } /// Generates a [`ProtocolConfig`] for the light client request protocol, refusing incoming diff --git a/substrate/client/network/src/protocol.rs b/substrate/client/network/src/protocol.rs index 9999d278a2..7214e60172 100644 --- a/substrate/client/network/src/protocol.rs +++ b/substrate/client/network/src/protocol.rs @@ -391,13 +391,8 @@ where sc_peerset::Peerset::from_config(sc_peerset::PeersetConfig { sets }) }; - let block_announces_protocol: Cow<'static, str> = Cow::from({ - let mut proto = String::new(); - proto.push_str("/"); - proto.push_str(protocol_id.as_ref()); - proto.push_str("/block-announces/1"); - proto - }); + let block_announces_protocol: Cow<'static, str> = + format!("/{}/block-announces/1", protocol_id.as_ref()).into(); let behaviour = { let best_number = info.best_number; @@ -952,7 +947,7 @@ where }, }; - peer.known_blocks.insert(hash.clone()); + peer.known_blocks.insert(hash); let is_best = match announce.state.unwrap_or(message::BlockState::Best) { message::BlockState::Best => true, @@ -1062,7 +1057,7 @@ where /// Uses `protocol` to queue a new justification request and tries to dispatch all pending /// requests. pub fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { - self.sync.request_justification(&hash, number) + self.sync.request_justification(hash, number) } /// Clear all pending justification requests. @@ -1479,7 +1474,7 @@ where }, }; - finished_block_requests.push((id.clone(), req, protobuf_response)); + finished_block_requests.push((*id, req, protobuf_response)); }, PeerRequest::State => { let protobuf_response = @@ -1576,7 +1571,7 @@ where } for (id, request) in self.sync.block_requests() { - let event = prepare_block_request(&mut self.peers, id.clone(), request); + let event = prepare_block_request(&mut self.peers, *id, request); self.pending_messages.push_back(event); } if let Some((id, request)) = self.sync.state_request() { @@ -1727,9 +1722,9 @@ where } }, NotificationsOut::CustomProtocolReplaced { peer_id, notifications_sink, set_id } => - if set_id == HARDCODED_PEERSETS_SYNC { - CustomMessageOutcome::None - } else if self.bad_handshake_substreams.contains(&(peer_id, set_id)) { + if set_id == HARDCODED_PEERSETS_SYNC || + self.bad_handshake_substreams.contains(&(peer_id, set_id)) + { CustomMessageOutcome::None } else { CustomMessageOutcome::NotificationStreamReplaced { diff --git a/substrate/client/network/src/protocol/message.rs b/substrate/client/network/src/protocol/message.rs index 3fb57b1c82..f173fff850 100644 --- a/substrate/client/network/src/protocol/message.rs +++ b/substrate/client/network/src/protocol/message.rs @@ -154,7 +154,7 @@ impl generic::BlockAnnounce { AnnouncementSummary { block_hash: self.header.hash(), number: *self.header.number(), - parent_hash: self.header.parent_hash().clone(), + parent_hash: *self.header.parent_hash(), state: self.state, } } diff --git a/substrate/client/network/src/protocol/notifications/behaviour.rs b/substrate/client/network/src/protocol/notifications/behaviour.rs index 61f7db78c9..1f872ec857 100644 --- a/substrate/client/network/src/protocol/notifications/behaviour.rs +++ b/substrate/client/network/src/protocol/notifications/behaviour.rs @@ -402,7 +402,7 @@ impl Notifications { } /// Returns the list of all the peers we have an open channel to. - pub fn open_peers<'a>(&'a self) -> impl Iterator + 'a { + pub fn open_peers(&self) -> impl Iterator { self.peers.iter().filter(|(_, state)| state.is_open()).map(|((id, _), _)| id) } @@ -551,10 +551,7 @@ impl Notifications { } /// Returns the list of reserved peers. - pub fn reserved_peers<'a>( - &'a self, - set_id: sc_peerset::SetId, - ) -> impl Iterator + 'a { + pub fn reserved_peers(&self, set_id: sc_peerset::SetId) -> impl Iterator { self.peerset.reserved_peers(set_id) } @@ -621,7 +618,7 @@ impl Notifications { ); trace!(target: "sub-libp2p", "Libp2p <= Dial {}", entry.key().0); self.events.push_back(NetworkBehaviourAction::Dial { - opts: entry.key().0.clone().into(), + opts: entry.key().0.into(), handler, }); entry.insert(PeerState::Requested); @@ -634,7 +631,7 @@ impl Notifications { match mem::replace(occ_entry.get_mut(), PeerState::Poisoned) { // Backoff (not expired) => PendingRequest PeerState::Backoff { ref timer, ref timer_deadline } if *timer_deadline > now => { - let peer_id = occ_entry.key().0.clone(); + let peer_id = occ_entry.key().0; trace!( target: "sub-libp2p", "PSM => Connect({}, {:?}): Will start to connect at until {:?}", @@ -656,7 +653,7 @@ impl Notifications { ); trace!(target: "sub-libp2p", "Libp2p <= Dial {:?}", occ_entry.key()); self.events.push_back(NetworkBehaviourAction::Dial { - opts: occ_entry.key().0.clone().into(), + opts: occ_entry.key().0.into(), handler, }); *occ_entry.into_mut() = PeerState::Requested; @@ -666,7 +663,7 @@ impl Notifications { PeerState::Disabled { connections, backoff_until: Some(ref backoff) } if *backoff > now => { - let peer_id = occ_entry.key().0.clone(); + let peer_id = occ_entry.key().0; trace!( target: "sub-libp2p", "PSM => Connect({}, {:?}): But peer is backed-off until {:?}", @@ -781,7 +778,7 @@ impl Notifications { trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Open({:?})", occ_entry.key(), *connec_id, set_id); self.events.push_back(NetworkBehaviourAction::NotifyHandler { - peer_id: occ_entry.key().0.clone(), + peer_id: occ_entry.key().0, handler: NotifyHandler::One(*connec_id), event: NotifsHandlerIn::Open { protocol_index: set_id.into() }, }); @@ -861,10 +858,8 @@ impl Notifications { if connections.iter().any(|(_, s)| matches!(s, ConnectionState::Open(_))) { trace!(target: "sub-libp2p", "External API <= Closed({}, {:?})", entry.key().0, set_id); - let event = NotificationsOut::CustomProtocolClosed { - peer_id: entry.key().0.clone(), - set_id, - }; + let event = + NotificationsOut::CustomProtocolClosed { peer_id: entry.key().0, set_id }; self.events.push_back(NetworkBehaviourAction::GenerateEvent(event)); } @@ -874,7 +869,7 @@ impl Notifications { trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})", entry.key(), *connec_id, set_id); self.events.push_back(NetworkBehaviourAction::NotifyHandler { - peer_id: entry.key().0.clone(), + peer_id: entry.key().0, handler: NotifyHandler::One(*connec_id), event: NotifsHandlerIn::Close { protocol_index: set_id.into() }, }); @@ -887,7 +882,7 @@ impl Notifications { trace!(target: "sub-libp2p", "Handler({:?}, {:?}) <= Close({:?})", entry.key(), *connec_id, set_id); self.events.push_back(NetworkBehaviourAction::NotifyHandler { - peer_id: entry.key().0.clone(), + peer_id: entry.key().0, handler: NotifyHandler::One(*connec_id), event: NotifsHandlerIn::Close { protocol_index: set_id.into() }, }); @@ -1406,7 +1401,7 @@ impl NetworkBehaviour for Notifications { trace!(target: "sub-libp2p", "Libp2p => Dial failure for {:?}", peer_id); for set_id in (0..self.notif_protocols.len()).map(sc_peerset::SetId::from) { - if let Entry::Occupied(mut entry) = self.peers.entry((peer_id.clone(), set_id)) { + if let Entry::Occupied(mut entry) = self.peers.entry((peer_id, set_id)) { match mem::replace(entry.get_mut(), PeerState::Poisoned) { // The peer is not in our list. st @ PeerState::Backoff { .. } => { @@ -1646,7 +1641,6 @@ impl NetworkBehaviour for Notifications { "OpenDesiredByRemote: Unexpected state in the custom protos handler: {:?}", state); debug_assert!(false); - return }, }; }, @@ -1742,13 +1736,11 @@ impl NetworkBehaviour for Notifications { state @ PeerState::Disabled { .. } | state @ PeerState::DisabledPendingEnable { .. } => { *entry.into_mut() = state; - return }, state => { error!(target: "sub-libp2p", "Unexpected state in the custom protos handler: {:?}", state); - return }, } }, @@ -1853,7 +1845,6 @@ impl NetworkBehaviour for Notifications { "OpenResultOk: Unexpected state in the custom protos handler: {:?}", state); debug_assert!(false); - return }, } }, @@ -2052,9 +2043,7 @@ impl NetworkBehaviour for Notifications { event: NotifsHandlerIn::Open { protocol_index: set_id.into() }, }); *connec_state = ConnectionState::Opening; - *peer_state = PeerState::Enabled { - connections: mem::replace(connections, Default::default()), - }; + *peer_state = PeerState::Enabled { connections: mem::take(connections) }; } else { *timer_deadline = Instant::now() + Duration::from_secs(5); let delay = futures_timer::Delay::new(Duration::from_secs(5)); diff --git a/substrate/client/network/src/protocol/notifications/handler.rs b/substrate/client/network/src/protocol/notifications/handler.rs index 510f72d4b0..c1602319d0 100644 --- a/substrate/client/network/src/protocol/notifications/handler.rs +++ b/substrate/client/network/src/protocol/notifications/handler.rs @@ -400,7 +400,7 @@ impl NotificationsSink { /// error to send a notification using an unknown protocol. /// /// This method will be removed in a future version. - pub fn send_sync_notification<'a>(&'a self, message: impl Into>) { + pub fn send_sync_notification(&self, message: impl Into>) { let mut lock = self.inner.sync_channel.lock(); if let Some(tx) = lock.as_mut() { @@ -425,7 +425,7 @@ impl NotificationsSink { /// /// The protocol name is expected to be checked ahead of calling this method. It is a logic /// error to send a notification using an unknown protocol. - pub async fn reserve_notification<'a>(&'a self) -> Result, ()> { + pub async fn reserve_notification(&self) -> Result, ()> { let mut lock = self.inner.async_channel.lock().await; let poll_ready = future::poll_fn(|cx| lock.poll_ready(cx)).await; diff --git a/substrate/client/network/src/protocol/sync.rs b/substrate/client/network/src/protocol/sync.rs index 7e6a2a3c78..fb89e12a44 100644 --- a/substrate/client/network/src/protocol/sync.rs +++ b/substrate/client/network/src/protocol/sync.rs @@ -672,7 +672,7 @@ where self.best_queued_number ); self.peers.insert( - who.clone(), + who, PeerSync { peer_id: who, common_number: self.best_queued_number, @@ -796,7 +796,7 @@ where .iter() // Only request blocks from peers who are ahead or on a par. .filter(|(_, peer)| peer.best_number >= number) - .map(|(id, _)| id.clone()) + .map(|(id, _)| *id) .collect(); debug!( @@ -809,7 +809,7 @@ where debug!(target: "sync", "Explicit sync request for block {:?} with {:?}", hash, peers); } - if self.is_known(&hash) { + if self.is_known(hash) { debug!(target: "sync", "Refusing to sync known hash {:?}", hash); return } @@ -843,7 +843,7 @@ where let peers = &mut self.peers; let mut matcher = self.extra_justifications.matcher(); std::iter::from_fn(move || { - if let Some((peer, request)) = matcher.next(&peers) { + if let Some((peer, request)) = matcher.next(peers) { peers .get_mut(&peer) .expect( @@ -1087,7 +1087,7 @@ where if let Some(start_block) = validate_blocks::(&blocks, who, Some(request))? { - self.blocks.insert(start_block, blocks, who.clone()); + self.blocks.insert(start_block, blocks, *who); } self.drain_blocks() }, @@ -1098,7 +1098,7 @@ where if let Some(start_block) = validate_blocks::(&blocks, who, Some(request))? { - gap_sync.blocks.insert(start_block, blocks, who.clone()); + gap_sync.blocks.insert(start_block, blocks, *who); } gap = true; let blocks: Vec<_> = gap_sync @@ -1106,11 +1106,12 @@ where .drain(gap_sync.best_queued_number + One::one()) .into_iter() .map(|block_data| { - let justifications = block_data.block.justifications.or( - legacy_justification_mapping( - block_data.block.justification, - ), - ); + let justifications = + block_data.block.justifications.or_else(|| { + legacy_justification_mapping( + block_data.block.justification, + ) + }); IncomingBlock { hash: block_data.block.hash, header: block_data.block.header, @@ -1129,7 +1130,7 @@ where blocks } else { debug!(target: "sync", "Unexpected gap block response from {}", who); - return Err(BadPeer(who.clone(), rep::NO_BLOCK)) + return Err(BadPeer(*who, rep::NO_BLOCK)) } }, PeerSyncState::DownloadingStale(_) => { @@ -1144,7 +1145,7 @@ where .map(|b| { let justifications = b .justifications - .or(legacy_justification_mapping(b.justification)); + .or_else(|| legacy_justification_mapping(b.justification)); IncomingBlock { hash: b.hash, header: b.header, @@ -1261,8 +1262,9 @@ where blocks .into_iter() .map(|b| { - let justifications = - b.justifications.or(legacy_justification_mapping(b.justification)); + let justifications = b + .justifications + .or_else(|| legacy_justification_mapping(b.justification)); IncomingBlock { hash: b.hash, header: b.header, @@ -1294,7 +1296,7 @@ where who: &PeerId, response: StateResponse, ) -> Result, BadPeer> { - if let Some(peer) = self.peers.get_mut(&who) { + if let Some(peer) = self.peers.get_mut(who) { if let PeerSyncState::DownloadingState = peer.state { peer.state = PeerSyncState::Available; self.allowed_requests.set_all(); @@ -1357,7 +1359,7 @@ where who: &PeerId, response: warp::EncodedProof, ) -> Result<(), BadPeer> { - if let Some(peer) = self.peers.get_mut(&who) { + if let Some(peer) = self.peers.get_mut(who) { if let PeerSyncState::DownloadingWarpProof = peer.state { peer.state = PeerSyncState::Available; self.allowed_requests.set_all(); @@ -1458,7 +1460,9 @@ where return Err(BadPeer(who, rep::BAD_JUSTIFICATION)) } - block.justifications.or(legacy_justification_mapping(block.justification)) + block + .justifications + .or_else(|| legacy_justification_mapping(block.justification)) } else { // we might have asked the peer for a justification on a block that we assumed it // had but didn't (regardless of whether it had a justification for it or not). @@ -1488,19 +1492,19 @@ where /// queue, with or without errors. /// /// `peer_info` is passed in case of a restart. - pub fn on_blocks_processed<'a>( - &'a mut self, + pub fn on_blocks_processed( + &mut self, imported: usize, count: usize, results: Vec<(Result>, BlockImportError>, B::Hash)>, - ) -> impl Iterator), BadPeer>> + 'a { + ) -> impl Iterator), BadPeer>> { trace!(target: "sync", "Imported {} of {}", imported, count); let mut output = Vec::new(); let mut has_error = false; for (_, hash) in &results { - self.queue_blocks.remove(&hash); + self.queue_blocks.remove(hash); } for (result, hash) in results { if has_error { @@ -1659,7 +1663,7 @@ where heads.sort(); let median = heads[heads.len() / 2]; if number + STATE_SYNC_FINALITY_THRESHOLD.saturated_into() >= median { - if let Ok(Some(header)) = self.client.header(BlockId::hash(hash.clone())) { + if let Ok(Some(header)) = self.client.header(BlockId::hash(*hash)) { log::debug!( target: "sync", "Starting state sync for #{} ({})", @@ -1688,7 +1692,7 @@ where /// Updates our internal state for best queued block and then goes /// through all peers to update our view of their state as well. fn on_block_queued(&mut self, hash: &B::Hash, number: NumberFor) { - if self.fork_targets.remove(&hash).is_some() { + if self.fork_targets.remove(hash).is_some() { trace!(target: "sync", "Completed fork sync {:?}", hash); } if let Some(gap_sync) = &mut self.gap_sync { @@ -1741,7 +1745,7 @@ where return HasSlotForBlockAnnounceValidation::TotalMaximumSlotsReached } - match self.block_announce_validation_per_peer_stats.entry(peer.clone()) { + match self.block_announce_validation_per_peer_stats.entry(*peer) { Entry::Vacant(entry) => { entry.insert(1); HasSlotForBlockAnnounceValidation::Yes @@ -1830,8 +1834,7 @@ where // Let external validator check the block announcement. let assoc_data = announce.data.as_ref().map_or(&[][..], |v| v.as_slice()); - let future = self.block_announce_validator.validate(&header, assoc_data); - let hash = hash.clone(); + let future = self.block_announce_validator.validate(header, assoc_data); self.block_announce_validation.push( async move { @@ -1900,7 +1903,7 @@ where PreValidateBlockAnnounce::Skip => return, }; - match self.block_announce_validation_per_peer_stats.entry(peer.clone()) { + match self.block_announce_validation_per_peer_stats.entry(*peer) { Entry::Vacant(_) => { error!( target: "sync", @@ -1994,7 +1997,7 @@ where if known || self.is_already_downloading(&hash) { trace!(target: "sync", "Known block announce from {}: {}", who, hash); if let Some(target) = self.fork_targets.get_mut(&hash) { - target.peers.insert(who.clone()); + target.peers.insert(who); } return PollBlockAnnounceValidation::Nothing { is_best, who, announce } } @@ -2070,9 +2073,7 @@ where /// Restart the sync process. This will reset all pending block requests and return an iterator /// of new block requests to make to peers. Peers that were downloading finality data (i.e. /// their state was `DownloadingJustification`) are unaffected and will stay in the same state. - fn restart<'a>( - &'a mut self, - ) -> impl Iterator), BadPeer>> + 'a { + fn restart(&mut self) -> impl Iterator), BadPeer>> + '_ { self.blocks.clear(); if let Err(e) = self.reset_sync_start_point() { warn!(target: "sync", "💔 Unable to restart sync: {}", e); @@ -2084,18 +2085,15 @@ where old_peers.into_iter().filter_map(move |(id, mut p)| { // peers that were downloading justifications // should be kept in that state. - match p.state { - PeerSyncState::DownloadingJustification(_) => { - // We make sure our commmon number is at least something we have. - p.common_number = self.best_queued_number; - self.peers.insert(id, p); - return None - }, - _ => {}, + if let PeerSyncState::DownloadingJustification(_) = p.state { + // We make sure our commmon number is at least something we have. + p.common_number = self.best_queued_number; + self.peers.insert(id, p); + return None } // handle peers that were in other states. - match self.new_peer(id.clone(), p.best_hash, p.best_number) { + match self.new_peer(id, p.best_hash, p.best_number) { Ok(None) => None, Ok(Some(x)) => Some(Ok((id, x))), Err(e) => Some(Err(e)), @@ -2124,23 +2122,24 @@ where self.import_existing = false; self.best_queued_hash = info.best_hash; self.best_queued_number = info.best_number; - if self.mode == SyncMode::Full { - if self.client.block_status(&BlockId::hash(info.best_hash))? != + + if self.mode == SyncMode::Full && + self.client.block_status(&BlockId::hash(info.best_hash))? != BlockStatus::InChainWithState - { - self.import_existing = true; - // Latest state is missing, start with the last finalized state or genesis instead. - if let Some((hash, number)) = info.finalized_state { - debug!(target: "sync", "Starting from finalized state #{}", number); - self.best_queued_hash = hash; - self.best_queued_number = number; - } else { - debug!(target: "sync", "Restarting from genesis"); - self.best_queued_hash = Default::default(); - self.best_queued_number = Zero::zero(); - } + { + self.import_existing = true; + // Latest state is missing, start with the last finalized state or genesis instead. + if let Some((hash, number)) = info.finalized_state { + debug!(target: "sync", "Starting from finalized state #{}", number); + self.best_queued_hash = hash; + self.best_queued_number = number; + } else { + debug!(target: "sync", "Restarting from genesis"); + self.best_queued_hash = Default::default(); + self.best_queued_number = Zero::zero(); } } + if let Some((start, end)) = info.block_gap { debug!(target: "sync", "Starting gap sync #{} - #{}", start, end); self.gap_sync = Some(GapSync { @@ -2192,7 +2191,7 @@ where let justifications = block_data .block .justifications - .or(legacy_justification_mapping(block_data.block.justification)); + .or_else(|| legacy_justification_mapping(block_data.block.justification)); IncomingBlock { hash: block_data.block.hash, header: block_data.block.header, @@ -2349,7 +2348,7 @@ fn peer_block_request( let request = message::generic::BlockRequest { id: 0, - fields: attrs.clone(), + fields: attrs, from, to: None, direction: message::Direction::Descending, @@ -2369,7 +2368,7 @@ fn peer_gap_block_request( common_number: NumberFor, ) -> Option<(Range>, BlockRequest)> { let range = blocks.needed_blocks( - id.clone(), + *id, MAX_BLOCKS_TO_REQUEST, std::cmp::min(peer.best_number, target), common_number, @@ -2383,7 +2382,7 @@ fn peer_gap_block_request( let request = message::generic::BlockRequest { id: 0, - fields: attrs.clone(), + fields: attrs, from, to: None, direction: message::Direction::Descending, @@ -2430,11 +2429,11 @@ fn fork_sync_request( }; trace!(target: "sync", "Downloading requested fork {:?} from {}, {} blocks", hash, id, count); return Some(( - hash.clone(), + *hash, message::generic::BlockRequest { id: 0, - fields: attributes.clone(), - from: message::FromBlock::Hash(hash.clone()), + fields: attributes, + from: message::FromBlock::Hash(*hash), to: None, direction: message::Direction::Descending, max: Some(count), diff --git a/substrate/client/network/src/protocol/sync/extra_requests.rs b/substrate/client/network/src/protocol/sync/extra_requests.rs index d0bfebab66..43122631d3 100644 --- a/substrate/client/network/src/protocol/sync/extra_requests.rs +++ b/substrate/client/network/src/protocol/sync/extra_requests.rs @@ -327,7 +327,7 @@ impl<'a, B: BlockT> Matcher<'a, B> { { continue } - self.extras.active_requests.insert(peer.clone(), request); + self.extras.active_requests.insert(*peer, request); trace!(target: "sync", "Sending {} request to {:?} for {:?}", diff --git a/substrate/client/network/src/protocol/sync/state.rs b/substrate/client/network/src/protocol/sync/state.rs index 4eddc4c608..6208b2bcdd 100644 --- a/substrate/client/network/src/protocol/sync/state.rs +++ b/substrate/client/network/src/protocol/sync/state.rs @@ -71,7 +71,7 @@ where Self { client, target_block: target.hash(), - target_root: target.state_root().clone(), + target_root: *target.state_root(), target_header: target, last_key: SmallVec::default(), state: HashMap::default(), @@ -149,18 +149,16 @@ where if entry.0.len() > 0 && entry.1.len() > 1 { // Already imported child_trie with same root. // Warning this will not work with parallel download. - } else { - if entry.0.is_empty() { - for (key, _value) in key_values.iter() { - self.imported_bytes += key.len() as u64; - } + } else if entry.0.is_empty() { + for (key, _value) in key_values.iter() { + self.imported_bytes += key.len() as u64; + } - entry.0 = key_values; - } else { - for (key, value) in key_values { - self.imported_bytes += key.len() as u64; - entry.0.push((key, value)) - } + entry.0 = key_values; + } else { + for (key, value) in key_values { + self.imported_bytes += key.len() as u64; + entry.0.push((key, value)) } } } @@ -172,7 +170,7 @@ where // the parent cursor stays valid. // Empty parent trie content only happens when all the response content // is part of a single child trie. - if self.last_key.len() == 2 && response.entries[0].entries.len() == 0 { + if self.last_key.len() == 2 && response.entries[0].entries.is_empty() { // Do not remove the parent trie position. self.last_key.pop(); } else { @@ -220,7 +218,7 @@ where self.target_block, self.target_header.clone(), ImportedState { - block: self.target_block.clone(), + block: self.target_block, state: std::mem::take(&mut self.state).into(), }, ) diff --git a/substrate/client/network/src/protocol/sync/warp.rs b/substrate/client/network/src/protocol/sync/warp.rs index fa2c23a0b3..6845d6d1dc 100644 --- a/substrate/client/network/src/protocol/sync/warp.rs +++ b/substrate/client/network/src/protocol/sync/warp.rs @@ -94,7 +94,7 @@ where match &mut self.phase { Phase::WarpProof { .. } => { log::debug!(target: "sync", "Unexpected state response"); - return ImportResult::BadResponse + ImportResult::BadResponse }, Phase::State(sync) => sync.import(response), } @@ -111,13 +111,13 @@ where match self.warp_sync_provider.verify(&response, *set_id, authorities.clone()) { Err(e) => { log::debug!(target: "sync", "Bad warp proof response: {}", e); - return WarpProofImportResult::BadResponse + WarpProofImportResult::BadResponse }, Ok(VerificationResult::Partial(new_set_id, new_authorities, new_last_hash)) => { log::debug!(target: "sync", "Verified partial proof, set_id={:?}", new_set_id); *set_id = new_set_id; *authorities = new_authorities; - *last_hash = new_last_hash.clone(); + *last_hash = new_last_hash; self.total_proof_bytes += response.0.len() as u64; WarpProofImportResult::Success }, diff --git a/substrate/client/network/src/request_responses.rs b/substrate/client/network/src/request_responses.rs index 87d070bc46..04d6ccb543 100644 --- a/substrate/client/network/src/request_responses.rs +++ b/substrate/client/network/src/request_responses.rs @@ -355,25 +355,21 @@ impl RequestResponsesBehaviour { (Instant::now(), pending_response), ); debug_assert!(prev_req_id.is_none(), "Expect request id to be unique."); - } else { - if pending_response.send(Err(RequestFailure::NotConnected)).is_err() { - log::debug!( - target: "sub-libp2p", - "Not connected to peer {:?}. At the same time local \ - node is no longer interested in the result.", - target, - ); - }; - } - } else { - if pending_response.send(Err(RequestFailure::UnknownProtocol)).is_err() { + } else if pending_response.send(Err(RequestFailure::NotConnected)).is_err() { log::debug!( target: "sub-libp2p", - "Unknown protocol {:?}. At the same time local \ + "Not connected to peer {:?}. At the same time local \ node is no longer interested in the result.", - protocol_name, + target, ); - }; + } + } else if pending_response.send(Err(RequestFailure::UnknownProtocol)).is_err() { + log::debug!( + target: "sub-libp2p", + "Unknown protocol {:?}. At the same time local \ + node is no longer interested in the result.", + protocol_name, + ); } } @@ -599,7 +595,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour { // will be reported by the corresponding `RequestResponse` through // an `InboundFailure::Omission` event. let _ = resp_builder.try_send(IncomingRequest { - peer: peer.clone(), + peer, payload: request, pending_response: tx, }); @@ -648,7 +644,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour { if let Ok(payload) = result { if let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name) { - if let Err(_) = protocol.send_response(inner_channel, Ok(payload)) { + if protocol.send_response(inner_channel, Ok(payload)).is_err() { // Note: Failure is handled further below when receiving // `InboundFailure` event from `RequestResponse` behaviour. log::debug!( @@ -658,11 +654,9 @@ impl NetworkBehaviour for RequestResponsesBehaviour { Dropping response", request_id, protocol_name, ); - } else { - if let Some(sent_feedback) = sent_feedback { - self.send_feedback - .insert((protocol_name, request_id).into(), sent_feedback); - } + } else if let Some(sent_feedback) = sent_feedback { + self.send_feedback + .insert((protocol_name, request_id).into(), sent_feedback); } } } @@ -718,13 +712,10 @@ impl NetworkBehaviour for RequestResponsesBehaviour { message: RequestResponseMessage::Request { request_id, request, channel, .. }, } => { - self.pending_responses_arrival_time.insert( - (protocol.clone(), request_id.clone()).into(), - Instant::now(), - ); + self.pending_responses_arrival_time + .insert((protocol.clone(), request_id).into(), Instant::now()); - let get_peer_reputation = - self.peerset.clone().peer_reputation(peer.clone()); + let get_peer_reputation = self.peerset.clone().peer_reputation(peer); let get_peer_reputation = Box::pin(get_peer_reputation); // Save the Future-like state with params to poll `get_peer_reputation` diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 6ffc0ec49b..91517e1491 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -195,7 +195,7 @@ where // Private and public keys configuration. let local_identity = params.network_config.node_key.clone().into_keypair()?; let local_public = local_identity.public(); - let local_peer_id = local_public.clone().to_peer_id(); + let local_peer_id = local_public.to_peer_id(); info!( target: "sub-libp2p", "🏷 Local node identity is: {}", @@ -248,7 +248,7 @@ where Err(Error::DuplicateBootnode { address: addr.clone(), first_id: *peer_id, - second_id: other.0.clone(), + second_id: other.0, }) } else { Ok(()) @@ -644,7 +644,7 @@ where .collect() }; - let peer_id = Swarm::>::local_peer_id(&swarm).to_base58(); + let peer_id = Swarm::>::local_peer_id(swarm).to_base58(); let listened_addresses = swarm.listeners().cloned().collect(); let external_addresses = swarm.external_addresses().map(|r| &r.addr).cloned().collect(); @@ -664,7 +664,7 @@ where .behaviour_mut() .user_protocol_mut() .peers_info() - .map(|(id, info)| (id.clone(), info.clone())) + .map(|(id, info)| (*id, info.clone())) .collect() } @@ -753,7 +753,7 @@ impl NetworkService { // `peers_notifications_sinks` mutex as soon as possible. let sink = { let peers_notifications_sinks = self.peers_notifications_sinks.lock(); - if let Some(sink) = peers_notifications_sinks.get(&(target.clone(), protocol.clone())) { + if let Some(sink) = peers_notifications_sinks.get(&(target, protocol.clone())) { sink.clone() } else { // Notification silently discarded, as documented. @@ -1093,7 +1093,7 @@ impl NetworkService { let _ = self .to_worker - .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr)); + .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr)); let _ = self.to_worker.unbounded_send(ServiceToWorkerMsg::AddReserved(peer_id)); Ok(()) } @@ -1173,7 +1173,7 @@ impl NetworkService { if !addr.is_empty() { let _ = self .to_worker - .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr)); + .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr)); } let _ = self .to_worker @@ -1227,7 +1227,7 @@ impl NetworkService { if !addr.is_empty() { let _ = self .to_worker - .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id.clone(), addr)); + .unbounded_send(ServiceToWorkerMsg::AddKnownAddress(peer_id, addr)); } let _ = self .to_worker @@ -1351,9 +1351,7 @@ pub struct NotificationSender { impl NotificationSender { /// Returns a future that resolves when the `NotificationSender` is ready to send a /// notification. - pub async fn ready<'a>( - &'a self, - ) -> Result, NotificationSenderError> { + pub async fn ready(&self) -> Result, NotificationSenderError> { Ok(NotificationSenderReady { ready: match self.sink.reserve_notification().await { Ok(r) => r, @@ -1771,7 +1769,7 @@ where if let Some(metrics) = this.metrics.as_ref() { metrics .kademlia_random_queries_total - .with_label_values(&[&protocol.as_ref()]) + .with_label_values(&[protocol.as_ref()]) .inc(); }, Poll::Ready(SwarmEvent::Behaviour(BehaviourOut::NotificationStreamOpened { @@ -1790,7 +1788,7 @@ where { let mut peers_notifications_sinks = this.peers_notifications_sinks.lock(); let _previous_value = peers_notifications_sinks - .insert((remote.clone(), protocol.clone()), notifications_sink); + .insert((remote, protocol.clone()), notifications_sink); debug_assert!(_previous_value.is_none()); } this.event_streams.send(Event::NotificationStreamOpened { @@ -1848,13 +1846,12 @@ where .inc(); } this.event_streams.send(Event::NotificationStreamClosed { - remote: remote.clone(), + remote, protocol: protocol.clone(), }); { let mut peers_notifications_sinks = this.peers_notifications_sinks.lock(); - let _previous_value = - peers_notifications_sinks.remove(&(remote.clone(), protocol)); + let _previous_value = peers_notifications_sinks.remove(&(remote, protocol)); debug_assert!(_previous_value.is_some()); } }, @@ -2117,10 +2114,7 @@ where for (lower_ilog2_bucket_bound, num_entries) in buckets { metrics .kbuckets_num_nodes - .with_label_values(&[ - &proto.as_ref(), - &lower_ilog2_bucket_bound.to_string(), - ]) + .with_label_values(&[proto.as_ref(), &lower_ilog2_bucket_bound.to_string()]) .set(num_entries as u64); } } @@ -2128,7 +2122,7 @@ where { metrics .kademlia_records_count - .with_label_values(&[&proto.as_ref()]) + .with_label_values(&[proto.as_ref()]) .set(num_entries as u64); } for (proto, num_entries) in @@ -2136,7 +2130,7 @@ where { metrics .kademlia_records_sizes_total - .with_label_values(&[&proto.as_ref()]) + .with_label_values(&[proto.as_ref()]) .set(num_entries as u64); } metrics @@ -2211,12 +2205,10 @@ where number: NumberFor, success: bool, ) { - self.protocol.behaviour_mut().user_protocol_mut().justification_import_result( - who, - hash.clone(), - number, - success, - ); + self.protocol + .behaviour_mut() + .user_protocol_mut() + .justification_import_result(who, *hash, number, success); } fn request_justification(&mut self, hash: &B::Hash, number: NumberFor) { self.protocol diff --git a/substrate/client/network/src/service/metrics.rs b/substrate/client/network/src/service/metrics.rs index ad30b1b093..4b63df00b8 100644 --- a/substrate/client/network/src/service/metrics.rs +++ b/substrate/client/network/src/service/metrics.rs @@ -280,8 +280,8 @@ impl MetricSource for BandwidthCounters { type N = u64; fn collect(&self, mut set: impl FnMut(&[&str], Self::N)) { - set(&[&"in"], self.0.total_inbound()); - set(&[&"out"], self.0.total_outbound()); + set(&["in"], self.0.total_inbound()); + set(&["out"], self.0.total_outbound()); } } diff --git a/substrate/client/network/src/service/out_events.rs b/substrate/client/network/src/service/out_events.rs index 3bff5a16fd..c95b46af4c 100644 --- a/substrate/client/network/src/service/out_events.rs +++ b/substrate/client/network/src/service/out_events.rs @@ -197,9 +197,9 @@ fn format_label(prefix: &str, protocol: &str, callback: impl FnOnce(&str)) { label_buffer.clear(); label_buffer.reserve(prefix.len() + protocol.len() + 2); label_buffer.push_str(prefix); - label_buffer.push_str("\""); + label_buffer.push('"'); label_buffer.push_str(protocol); - label_buffer.push_str("\""); + label_buffer.push('"'); callback(&label_buffer); }); } @@ -249,14 +249,14 @@ impl Metrics { .inc_by(num); }, Event::NotificationStreamOpened { protocol, .. } => { - format_label("notif-open-", &protocol, |protocol_label| { + format_label("notif-open-", protocol, |protocol_label| { self.events_total .with_label_values(&[protocol_label, "sent", name]) .inc_by(num); }); }, Event::NotificationStreamClosed { protocol, .. } => { - format_label("notif-closed-", &protocol, |protocol_label| { + format_label("notif-closed-", protocol, |protocol_label| { self.events_total .with_label_values(&[protocol_label, "sent", name]) .inc_by(num); @@ -264,7 +264,7 @@ impl Metrics { }, Event::NotificationsReceived { messages, .. } => for (protocol, message) in messages { - format_label("notif-", &protocol, |protocol_label| { + format_label("notif-", protocol, |protocol_label| { self.events_total .with_label_values(&[protocol_label, "sent", name]) .inc_by(num); @@ -290,24 +290,24 @@ impl Metrics { .inc(); }, Event::NotificationStreamOpened { protocol, .. } => { - format_label("notif-open-", &protocol, |protocol_label| { + format_label("notif-open-", protocol, |protocol_label| { self.events_total.with_label_values(&[protocol_label, "received", name]).inc(); }); }, Event::NotificationStreamClosed { protocol, .. } => { - format_label("notif-closed-", &protocol, |protocol_label| { + format_label("notif-closed-", protocol, |protocol_label| { self.events_total.with_label_values(&[protocol_label, "received", name]).inc(); }); }, Event::NotificationsReceived { messages, .. } => for (protocol, message) in messages { - format_label("notif-", &protocol, |protocol_label| { + format_label("notif-", protocol, |protocol_label| { self.events_total .with_label_values(&[protocol_label, "received", name]) .inc(); }); self.notifications_sizes - .with_label_values(&[&protocol, "received", name]) + .with_label_values(&[protocol, "received", name]) .inc_by(u64::try_from(message.len()).unwrap_or(u64::MAX)); }, } diff --git a/substrate/client/network/src/state_request_handler.rs b/substrate/client/network/src/state_request_handler.rs index 3e208e22e3..7ac1a17e8e 100644 --- a/substrate/client/network/src/state_request_handler.rs +++ b/substrate/client/network/src/state_request_handler.rs @@ -63,11 +63,7 @@ pub fn generate_protocol_config(protocol_id: &ProtocolId) -> ProtocolConfig { /// Generate the state protocol name from chain specific protocol identifier. fn generate_protocol_name(protocol_id: &ProtocolId) -> String { - let mut s = String::new(); - s.push_str("/"); - s.push_str(protocol_id.as_ref()); - s.push_str("/state/2"); - s + format!("/{}/state/2", protocol_id.as_ref()) } /// The key of [`BlockRequestHandler::seen_requests`]. @@ -152,8 +148,7 @@ where let request = StateRequest::decode(&payload[..])?; let block: B::Hash = Decode::decode(&mut request.block.as_ref())?; - let key = - SeenRequestsKey { peer: *peer, block: block.clone(), start: request.start.clone() }; + let key = SeenRequestsKey { peer: *peer, block, start: request.start.clone() }; let mut reputation_changes = Vec::new(); diff --git a/substrate/client/network/src/transactions.rs b/substrate/client/network/src/transactions.rs index c09c6b88da..64e208d718 100644 --- a/substrate/client/network/src/transactions.rs +++ b/substrate/client/network/src/transactions.rs @@ -133,15 +133,7 @@ pub struct TransactionsHandlerPrototype { impl TransactionsHandlerPrototype { /// Create a new instance. pub fn new(protocol_id: ProtocolId) -> Self { - Self { - protocol_name: Cow::from({ - let mut proto = String::new(); - proto.push_str("/"); - proto.push_str(protocol_id.as_ref()); - proto.push_str("/transactions/1"); - proto - }), - } + Self { protocol_name: format!("/{}/transactions/1", protocol_id.as_ref()).into() } } /// Returns the configuration of the set to put in the network configuration. diff --git a/substrate/client/network/src/transport.rs b/substrate/client/network/src/transport.rs index 9a8e080234..64b199e9d7 100644 --- a/substrate/client/network/src/transport.rs +++ b/substrate/client/network/src/transport.rs @@ -82,11 +82,11 @@ pub fn build_transport( rare panic here is basically zero"); // Legacy noise configurations for backward compatibility. - let mut noise_legacy = noise::LegacyConfig::default(); - noise_legacy.recv_legacy_handshake = true; + let noise_legacy = + noise::LegacyConfig { recv_legacy_handshake: true, ..Default::default() }; let mut xx_config = noise::NoiseConfig::xx(noise_keypair); - xx_config.set_legacy_config(noise_legacy.clone()); + xx_config.set_legacy_config(noise_legacy); xx_config.into_authenticated() }; diff --git a/substrate/client/network/src/warp_request_handler.rs b/substrate/client/network/src/warp_request_handler.rs index 4c839825ff..d5bee5833a 100644 --- a/substrate/client/network/src/warp_request_handler.rs +++ b/substrate/client/network/src/warp_request_handler.rs @@ -82,11 +82,7 @@ pub fn generate_request_response_config(protocol_id: ProtocolId) -> RequestRespo /// Generate the grandpa warp sync protocol name from chain specific protocol identifier. fn generate_protocol_name(protocol_id: ProtocolId) -> String { - let mut s = String::new(); - s.push_str("/"); - s.push_str(protocol_id.as_ref()); - s.push_str("/sync/warp"); - s + format!("/{}/sync/warp", protocol_id.as_ref()) } /// Handler for incoming grandpa warp sync requests from a remote peer. diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index 1760c08759..20f1a30148 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -236,7 +236,7 @@ where { /// Get this peer ID. pub fn id(&self) -> PeerId { - self.network.service().local_peer_id().clone() + *self.network.service().local_peer_id() } /// Returns true if we're major syncing. @@ -387,7 +387,7 @@ where if inform_sync_about_new_best_block { self.network.new_best_block_imported( at, - full_client.header(&BlockId::Hash(at)).ok().flatten().unwrap().number().clone(), + *full_client.header(&BlockId::Hash(at)).ok().flatten().unwrap().number(), ); } at @@ -458,7 +458,7 @@ where nonce, }; builder.push(transfer.into_signed_tx()).unwrap(); - nonce = nonce + 1; + nonce += 1; builder.build().unwrap().block }, headers_only, @@ -494,7 +494,7 @@ where /// Get a reference to the network service. pub fn network_service(&self) -> &Arc::Hash>> { - &self.network.service() + self.network.service() } /// Get a reference to the network worker. @@ -801,7 +801,7 @@ where let addrs = connect_to .iter() .map(|v| { - let peer_id = self.peer(*v).network_service().local_peer_id().clone(); + let peer_id = *self.peer(*v).network_service().local_peer_id(); let multiaddr = self.peer(*v).listen_addr.clone(); MultiaddrWithPeerId { peer_id, multiaddr } }) @@ -868,10 +868,8 @@ where self.mut_peers(move |peers| { for peer in peers.iter_mut() { - peer.network.add_known_address( - network.service().local_peer_id().clone(), - listen_addr.clone(), - ); + peer.network + .add_known_address(*network.service().local_peer_id(), listen_addr.clone()); } let imported_blocks_stream = Box::pin(client.import_notification_stream().fuse()); @@ -986,7 +984,7 @@ where /// Polls the testnet. Processes all the pending actions. fn poll(&mut self, cx: &mut FutureContext) { self.mut_peers(|peers| { - for (i, peer) in peers.into_iter().enumerate() { + for (i, peer) in peers.iter_mut().enumerate() { trace!(target: "sync", "-- Polling {}: {}", i, peer.id()); if let Poll::Ready(()) = peer.network.poll_unpin(cx) { panic!("NetworkWorker has terminated unexpectedly.") @@ -1076,7 +1074,7 @@ impl JustificationImport for ForceFinalized { ) -> Result<(), Self::Error> { self.0 .finalize_block(BlockId::Hash(hash), Some(justification), true) - .map_err(|_| ConsensusError::InvalidJustification.into()) + .map_err(|_| ConsensusError::InvalidJustification) } } diff --git a/substrate/client/offchain/src/api/http.rs b/substrate/client/offchain/src/api/http.rs index 012de78c5f..f4fa7e0800 100644 --- a/substrate/client/offchain/src/api/http.rs +++ b/substrate/client/offchain/src/api/http.rs @@ -199,7 +199,7 @@ impl HttpApi { ) -> Result<(), HttpError> { // Extract the request from the list. // Don't forget to add it back if necessary when returning. - let mut request = self.requests.remove(&request_id).ok_or_else(|| HttpError::Invalid)?; + let mut request = self.requests.remove(&request_id).ok_or(HttpError::Invalid)?; let mut deadline = timestamp::deadline_to_future(deadline); // Closure that writes data to a sender, taking the deadline into account. Can return `Ok` diff --git a/substrate/client/peerset/src/lib.rs b/substrate/client/peerset/src/lib.rs index 859319fab1..ec09835c48 100644 --- a/substrate/client/peerset/src/lib.rs +++ b/substrate/client/peerset/src/lib.rs @@ -619,11 +619,9 @@ impl Peerset { self.update_time(); - if self.reserved_nodes[set_id.0].1 { - if !self.reserved_nodes[set_id.0].0.contains(&peer_id) { - self.message_queue.push_back(Message::Reject(index)); - return - } + if self.reserved_nodes[set_id.0].1 && !self.reserved_nodes[set_id.0].0.contains(&peer_id) { + self.message_queue.push_back(Message::Reject(index)); + return } let not_connected = match self.data.peer(set_id.0, &peer_id) { @@ -730,8 +728,7 @@ impl Stream for Peerset { return Poll::Ready(Some(message)) } - if let Poll::Ready(_) = Future::poll(Pin::new(&mut self.next_periodic_alloc_slots), cx) - { + if Future::poll(Pin::new(&mut self.next_periodic_alloc_slots), cx).is_ready() { self.next_periodic_alloc_slots = Delay::new(Duration::new(1, 0)); for set_index in 0..self.data.num_sets() { @@ -798,7 +795,7 @@ mod tests { fn next_message(mut peerset: Peerset) -> Result<(Message, Peerset), ()> { let next = futures::executor::block_on_stream(&mut peerset).next(); - let message = next.ok_or_else(|| ())?; + let message = next.ok_or(())?; Ok((message, peerset)) } diff --git a/substrate/client/peerset/src/peersstate.rs b/substrate/client/peerset/src/peersstate.rs index ca22cac324..c9af5b8e2c 100644 --- a/substrate/client/peerset/src/peersstate.rs +++ b/substrate/client/peerset/src/peersstate.rs @@ -169,9 +169,7 @@ impl PeersState { /// Returns an object that grants access to the reputation value of a peer. pub fn peer_reputation(&mut self, peer_id: PeerId) -> Reputation { - if !self.nodes.contains_key(&peer_id) { - self.nodes.insert(peer_id, Node::new(self.sets.len())); - } + self.nodes.entry(peer_id).or_insert_with(|| Node::new(self.sets.len())); let entry = match self.nodes.entry(peer_id) { Entry::Vacant(_) => unreachable!("guaranteed to be inserted above; qed"), @@ -652,7 +650,7 @@ mod tests { let id1 = PeerId::random(); let id2 = PeerId::random(); - peers_state.add_no_slot_node(0, id1.clone()); + peers_state.add_no_slot_node(0, id1); if let Peer::Unknown(p) = peers_state.peer(0, &id1) { assert!(p.discover().try_accept_incoming().is_ok()); } else { @@ -705,43 +703,28 @@ mod tests { assert!(peers_state.highest_not_connected_peer(0).is_none()); peers_state.peer(0, &id1).into_unknown().unwrap().discover().set_reputation(50); peers_state.peer(0, &id2).into_unknown().unwrap().discover().set_reputation(25); - assert_eq!( - peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), - Some(id1.clone()) - ); + assert_eq!(peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), Some(id1)); peers_state.peer(0, &id2).into_not_connected().unwrap().set_reputation(75); - assert_eq!( - peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), - Some(id2.clone()) - ); + assert_eq!(peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), Some(id2)); peers_state .peer(0, &id2) .into_not_connected() .unwrap() .try_accept_incoming() .unwrap(); - assert_eq!( - peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), - Some(id1.clone()) - ); + assert_eq!(peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), Some(id1)); peers_state.peer(0, &id1).into_not_connected().unwrap().set_reputation(100); peers_state.peer(0, &id2).into_connected().unwrap().disconnect(); - assert_eq!( - peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), - Some(id1.clone()) - ); + assert_eq!(peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), Some(id1)); peers_state.peer(0, &id1).into_not_connected().unwrap().set_reputation(-100); - assert_eq!( - peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), - Some(id2.clone()) - ); + assert_eq!(peers_state.highest_not_connected_peer(0).map(|p| p.into_peer_id()), Some(id2)); } #[test] fn disconnect_no_slot_doesnt_panic() { let mut peers_state = PeersState::new(iter::once(SetConfig { in_peers: 1, out_peers: 1 })); let id = PeerId::random(); - peers_state.add_no_slot_node(0, id.clone()); + peers_state.add_no_slot_node(0, id); let peer = peers_state .peer(0, &id) .into_unknown() diff --git a/substrate/client/peerset/tests/fuzz.rs b/substrate/client/peerset/tests/fuzz.rs index af4838d724..48c5cb341c 100644 --- a/substrate/client/peerset/tests/fuzz.rs +++ b/substrate/client/peerset/tests/fuzz.rs @@ -52,7 +52,7 @@ fn test_once() { bootnodes: (0..Uniform::new_inclusive(0, 4).sample(&mut rng)) .map(|_| { let id = PeerId::random(); - known_nodes.insert(id.clone()); + known_nodes.insert(id); id }) .collect(), @@ -60,8 +60,8 @@ fn test_once() { (0..Uniform::new_inclusive(0, 2).sample(&mut rng)) .map(|_| { let id = PeerId::random(); - known_nodes.insert(id.clone()); - reserved_nodes.insert(id.clone()); + known_nodes.insert(id); + reserved_nodes.insert(id); id }) .collect() @@ -114,7 +114,7 @@ fn test_once() { // If we generate 1, discover a new node. 1 => { let new_id = PeerId::random(); - known_nodes.insert(new_id.clone()); + known_nodes.insert(new_id); peerset.add_to_peers_set(SetId::from(0), new_id); }, @@ -122,7 +122,7 @@ fn test_once() { 2 => if let Some(id) = known_nodes.iter().choose(&mut rng) { let val = Uniform::new_inclusive(i32::MIN, i32::MAX).sample(&mut rng); - peerset_handle.report_peer(id.clone(), ReputationChange::new(val, "")); + peerset_handle.report_peer(*id, ReputationChange::new(val, "")); }, // If we generate 3, disconnect from a random node. @@ -142,8 +142,8 @@ fn test_once() { }) .choose(&mut rng) { - peerset.incoming(SetId::from(0), id.clone(), next_incoming_id.clone()); - incoming_nodes.insert(next_incoming_id.clone(), id.clone()); + peerset.incoming(SetId::from(0), *id, next_incoming_id); + incoming_nodes.insert(next_incoming_id, *id); next_incoming_id.0 += 1; } }, @@ -157,8 +157,8 @@ fn test_once() { if let Some(id) = known_nodes.iter().filter(|n| !reserved_nodes.contains(*n)).choose(&mut rng) { - peerset_handle.add_reserved_peer(SetId::from(0), id.clone()); - reserved_nodes.insert(id.clone()); + peerset_handle.add_reserved_peer(SetId::from(0), *id); + reserved_nodes.insert(*id); } }, 8 => diff --git a/substrate/client/rpc-api/src/author/error.rs b/substrate/client/rpc-api/src/author/error.rs index fe12bd581f..1f8c65c471 100644 --- a/substrate/client/rpc-api/src/author/error.rs +++ b/substrate/client/rpc-api/src/author/error.rs @@ -89,12 +89,12 @@ impl From for rpc::Error { match e { Error::BadFormat(e) => rpc::Error { code: rpc::ErrorCode::ServerError(BAD_FORMAT), - message: format!("Extrinsic has invalid format: {}", e).into(), + message: format!("Extrinsic has invalid format: {}", e), data: None, }, Error::Verification(e) => rpc::Error { code: rpc::ErrorCode::ServerError(VERIFICATION_ERROR), - message: format!("Verification Error: {}", e).into(), + message: format!("Verification Error: {}", e), data: Some(e.to_string().into()), }, Error::Pool(PoolError::InvalidTransaction(InvalidTransaction::Custom(e))) => rpc::Error { diff --git a/substrate/client/rpc-servers/src/middleware.rs b/substrate/client/rpc-servers/src/middleware.rs index 4adc878660..d4ac787ce9 100644 --- a/substrate/client/rpc-servers/src/middleware.rs +++ b/substrate/client/rpc-servers/src/middleware.rs @@ -237,8 +237,5 @@ fn call_name<'a>(call: &'a jsonrpc_core::Call, known_methods: &HashSet) } fn is_success(output: &Option) -> bool { - match output { - Some(jsonrpc_core::Output::Success(..)) => true, - _ => false, - } + matches!(output, Some(jsonrpc_core::Output::Success(..))) } diff --git a/substrate/client/rpc/src/author/mod.rs b/substrate/client/rpc/src/author/mod.rs index 5064e61342..2821eea2cc 100644 --- a/substrate/client/rpc/src/author/mod.rs +++ b/substrate/client/rpc/src/author/mod.rs @@ -119,7 +119,7 @@ where .runtime_api() .decode_session_keys(&generic::BlockId::Hash(best_block_hash), session_keys.to_vec()) .map_err(|e| Error::Client(Box::new(e)))? - .ok_or_else(|| Error::InvalidSessionKeys)?; + .ok_or(Error::InvalidSessionKeys)?; Ok(SyncCryptoStore::has_keys(&*self.keystore, &keys)) } @@ -143,7 +143,7 @@ where .map_err(|e| { e.into_pool_error() .map(Into::into) - .unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into()) + .unwrap_or_else(|e| error::Error::Verification(Box::new(e))) }) .boxed() } @@ -201,7 +201,7 @@ where .map_err(|e| { e.into_pool_error() .map(error::Error::from) - .unwrap_or_else(|e| error::Error::Verification(Box::new(e)).into()) + .unwrap_or_else(|e| error::Error::Verification(Box::new(e))) }); let subscriptions = self.subscriptions.clone(); diff --git a/substrate/client/rpc/src/chain/mod.rs b/substrate/client/rpc/src/chain/mod.rs index c20e5a188a..64231dd78c 100644 --- a/substrate/client/rpc/src/chain/mod.rs +++ b/substrate/client/rpc/src/chain/mod.rs @@ -60,7 +60,7 @@ where /// Tries to unwrap passed block hash, or uses best block hash otherwise. fn unwrap_or_best(&self, hash: Option) -> Block::Hash { - match hash.into() { + match hash { None => self.client().info().best_hash, Some(hash) => hash, } @@ -311,7 +311,7 @@ fn subscribe_headers( // send further subscriptions let stream = stream() .inspect_err(|e| warn!("Block notification stream error: {:?}", e)) - .map(|res| Ok(res)); + .map(Ok); stream::iter(vec![Ok(header)]) .chain(stream) diff --git a/substrate/client/rpc/src/state/state_full.rs b/substrate/client/rpc/src/state/state_full.rs index 1a35760bd6..38f9b078d8 100644 --- a/substrate/client/rpc/src/state/state_full.rs +++ b/substrate/client/rpc/src/state/state_full.rs @@ -151,10 +151,8 @@ where changes: &mut Vec>, ) -> Result<()> { for block_hash in &range.hashes { - let block_hash = block_hash.clone(); - let mut block_changes = - StorageChangeSet { block: block_hash.clone(), changes: Vec::new() }; - let id = BlockId::hash(block_hash); + let mut block_changes = StorageChangeSet { block: *block_hash, changes: Vec::new() }; + let id = BlockId::hash(*block_hash); for key in keys { let (has_changed, data) = { let curr_data = self.client.storage(&id, key).map_err(client_err)?; diff --git a/substrate/client/service/src/builder.rs b/substrate/client/service/src/builder.rs index 882d7666db..35ea67d8fb 100644 --- a/substrate/client/service/src/builder.rs +++ b/substrate/client/service/src/builder.rs @@ -263,7 +263,7 @@ where state_cache_child_ratio: config.state_cache_child_ratio.map(|v| (v, 100)), state_pruning: config.state_pruning.clone(), source: config.database.clone(), - keep_blocks: config.keep_blocks.clone(), + keep_blocks: config.keep_blocks, }; let backend = new_db_backend(db_config)?; @@ -421,10 +421,10 @@ where Some("offchain-worker"), sc_offchain::notification_future( config.role.is_authority(), - client.clone(), + client, offchain, Clone::clone(&spawn_handle), - network.clone(), + network, ), ); } @@ -517,7 +517,7 @@ where let metrics_service = if let Some(PrometheusConfig { port, registry }) = config.prometheus_config.clone() { // Set static metrics. - let metrics = MetricsService::with_prometheus(telemetry.clone(), ®istry, &config)?; + let metrics = MetricsService::with_prometheus(telemetry, ®istry, &config)?; spawn_handle.spawn( "prometheus-endpoint", None, @@ -526,7 +526,7 @@ where metrics } else { - MetricsService::new(telemetry.clone()) + MetricsService::new(telemetry) }; // Periodically updated metrics and telemetry updates. @@ -572,7 +572,7 @@ where None, sc_informant::build( client.clone(), - network.clone(), + network, transaction_pool.clone(), config.informant_output_format, ), diff --git a/substrate/client/service/src/client/block_rules.rs b/substrate/client/service/src/client/block_rules.rs index 519d5a13f5..2ed27b8fe1 100644 --- a/substrate/client/service/src/client/block_rules.rs +++ b/substrate/client/service/src/client/block_rules.rs @@ -47,8 +47,8 @@ impl BlockRules { /// New block rules with provided black and white lists. pub fn new(fork_blocks: ForkBlocks, bad_blocks: BadBlocks) -> Self { Self { - bad: bad_blocks.unwrap_or_else(|| HashSet::new()), - forks: fork_blocks.unwrap_or_else(|| vec![]).into_iter().collect(), + bad: bad_blocks.unwrap_or_default(), + forks: fork_blocks.unwrap_or_default().into_iter().collect(), } } @@ -61,7 +61,7 @@ impl BlockRules { pub fn lookup(&self, number: NumberFor, hash: &B::Hash) -> LookupResult { if let Some(hash_for_height) = self.forks.get(&number) { if hash_for_height != hash { - return LookupResult::Expected(hash_for_height.clone()) + return LookupResult::Expected(*hash_for_height) } } diff --git a/substrate/client/service/src/client/call_executor.rs b/substrate/client/service/src/client/call_executor.rs index 0f13b08d0c..1e8114df13 100644 --- a/substrate/client/service/src/client/call_executor.rs +++ b/substrate/client/service/src/client/call_executor.rs @@ -283,7 +283,7 @@ where state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; self.executor .runtime_version(&mut ext, &runtime_code) - .map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string()).into()) + .map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string())) } fn prove_execution( @@ -305,7 +305,7 @@ where let runtime_code = self.check_override(runtime_code, at)?; sp_state_machine::prove_execution_on_trie_backend( - &trie_backend, + trie_backend, &mut Default::default(), &self.executor, self.spawn_handle.clone(), diff --git a/substrate/client/service/src/client/client.rs b/substrate/client/service/src/client/client.rs index dfa392bc96..48e4d0141c 100644 --- a/substrate/client/service/src/client/client.rs +++ b/substrate/client/service/src/client/client.rs @@ -367,7 +367,7 @@ where let mut op = backend.begin_operation()?; let state_root = op.set_genesis_state(genesis_storage, !config.no_genesis, genesis_state_version)?; - let genesis_block = genesis::construct_genesis_block::(state_root.into()); + let genesis_block = genesis::construct_genesis_block::(state_root); info!( "🔨 Initializing Genesis block/state (state: {}, header-hash: {})", genesis_block.header().state_root(), @@ -551,7 +551,7 @@ where >::Api: CoreApi + ApiExt, { - let parent_hash = import_headers.post().parent_hash().clone(); + let parent_hash = *import_headers.post().parent_hash(); let status = self.backend.blockchain().status(BlockId::Hash(hash))?; let parent_exists = self.backend.blockchain().status(BlockId::Hash(parent_hash))? == blockchain::BlockStatus::InChain; @@ -609,7 +609,7 @@ where sc_consensus::StorageChanges::Import(changes) => { let mut storage = sp_storage::Storage::default(); for state in changes.state.0.into_iter() { - if state.parent_storage_keys.len() == 0 && state.state_root.len() == 0 { + if state.parent_storage_keys.is_empty() && state.state_root.is_empty() { for (key, value) in state.key_values.into_iter() { storage.top.insert(key, value); } @@ -617,7 +617,7 @@ where for parent_storage in state.parent_storage_keys { let storage_key = PrefixedStorageKey::new_ref(&parent_storage); let storage_key = - match ChildType::from_prefixed_key(&storage_key) { + match ChildType::from_prefixed_key(storage_key) { Some((ChildType::ParentKeyId, storage_key)) => storage_key, None => @@ -1033,7 +1033,7 @@ where return Ok(BlockStatus::Queued) } } - let hash_and_number = match id.clone() { + let hash_and_number = match *id { BlockId::Hash(hash) => self.backend.blockchain().number(hash)?.map(|n| (hash, n)), BlockId::Number(n) => self.backend.blockchain().hash(n)?.map(|hash| (hash, n)), }; @@ -1212,8 +1212,8 @@ where } let state = self.state_at(id)?; let child_info = |storage_key: &Vec| -> sp_blockchain::Result { - let storage_key = PrefixedStorageKey::new_ref(&storage_key); - match ChildType::from_prefixed_key(&storage_key) { + let storage_key = PrefixedStorageKey::new_ref(storage_key); + match ChildType::from_prefixed_key(storage_key) { Some((ChildType::ParentKeyId, storage_key)) => Ok(ChildInfo::new_default(storage_key)), None => Err(Error::Backend("Invalid child storage key.".to_string())), @@ -1222,7 +1222,7 @@ where let mut current_child = if start_key.len() == 2 { let start_key = start_key.get(0).expect("checked len"); if let Some(child_root) = state - .storage(&start_key) + .storage(start_key) .map_err(|e| sp_blockchain::Error::from_state(Box::new(e)))? { Some((child_info(start_key)?, child_root)) @@ -1232,7 +1232,7 @@ where } else { None }; - let mut current_key = start_key.last().map(Clone::clone).unwrap_or(Vec::new()); + let mut current_key = start_key.last().map(Clone::clone).unwrap_or_default(); let mut total_size = 0; let mut result = vec![( KeyValueStorageLevel { @@ -1276,14 +1276,13 @@ where total_size += size; if current_child.is_none() && - sp_core::storage::well_known_keys::is_child_storage_key(next_key.as_slice()) + sp_core::storage::well_known_keys::is_child_storage_key(next_key.as_slice()) && + !child_roots.contains(value.as_slice()) { - if !child_roots.contains(value.as_slice()) { - child_roots.insert(value.clone()); - switch_child_key = Some((next_key.clone(), value.clone())); - entries.push((next_key.clone(), value)); - break - } + child_roots.insert(value.clone()); + switch_child_key = Some((next_key.clone(), value.clone())); + entries.push((next_key.clone(), value)); + break } entries.push((next_key.clone(), value)); current_key = next_key; @@ -1647,7 +1646,7 @@ where { type Api = >::RuntimeApi; - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api> { + fn runtime_api(&self) -> ApiRef { RA::construct_runtime_api(self) } } @@ -1661,12 +1660,11 @@ where type StateBackend = B::State; fn call_api_at< - 'a, R: Encode + Decode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, >( &self, - params: CallApiAtParams<'a, Block, NC, B::State>, + params: CallApiAtParams, ) -> Result, sp_api::ApiError> { let at = params.at; @@ -1742,7 +1740,7 @@ where }) .map_err(|e| { warn!("Block import error: {}", e); - ConsensusError::ClientImport(e.to_string()).into() + ConsensusError::ClientImport(e.to_string()) }) } diff --git a/substrate/client/service/src/client/wasm_override.rs b/substrate/client/service/src/client/wasm_override.rs index fa35be9fca..5fc748f3e8 100644 --- a/substrate/client/service/src/client/wasm_override.rs +++ b/substrate/client/service/src/client/wasm_override.rs @@ -87,7 +87,7 @@ fn make_hash(val: &K) -> Vec { } impl FetchRuntimeCode for WasmBlob { - fn fetch_runtime_code<'a>(&'a self) -> Option> { + fn fetch_runtime_code(&self) -> Option> { Some(self.code.as_slice().into()) } } @@ -186,34 +186,30 @@ impl WasmOverride { for entry in fs::read_dir(dir).map_err(handle_err)? { let entry = entry.map_err(handle_err)?; let path = entry.path(); - match path.extension().and_then(|e| e.to_str()) { - Some("wasm") => { - let code = fs::read(&path).map_err(handle_err)?; - let code_hash = make_hash(&code); - let version = Self::runtime_version(executor, &code, &code_hash, Some(128))?; + if let Some("wasm") = path.extension().and_then(|e| e.to_str()) { + let code = fs::read(&path).map_err(handle_err)?; + let code_hash = make_hash(&code); + let version = Self::runtime_version(executor, &code, &code_hash, Some(128))?; + tracing::info!( + target: "wasm_overrides", + version = %version, + file = %path.display(), + "Found wasm override.", + ); + let wasm = + WasmBlob::new(code, code_hash, path.clone(), version.spec_name.to_string()); + + if let Some(other) = overrides.insert(version.spec_version, wasm) { tracing::info!( target: "wasm_overrides", - version = %version, - file = %path.display(), - "Found wasm override.", + first = %other.path.display(), + second = %path.display(), + %version, + "Found duplicate spec version for runtime.", ); - - let wasm = - WasmBlob::new(code, code_hash, path.clone(), version.spec_name.to_string()); - - if let Some(other) = overrides.insert(version.spec_version, wasm) { - tracing::info!( - target: "wasm_overrides", - first = %other.path.display(), - second = %path.display(), - %version, - "Found duplicate spec version for runtime.", - ); - duplicates.push(path.display().to_string()); - } - }, - _ => (), + duplicates.push(path.display().to_string()); + } } } diff --git a/substrate/client/service/src/client/wasm_substitutes.rs b/substrate/client/service/src/client/wasm_substitutes.rs index 3690672512..f826fa3613 100644 --- a/substrate/client/service/src/client/wasm_substitutes.rs +++ b/substrate/client/service/src/client/wasm_substitutes.rs @@ -56,7 +56,7 @@ impl WasmSubstitute { /// Returns `true` when the substitute matches for the given `block_id`. fn matches(&self, block_id: &BlockId, backend: &impl backend::Backend) -> bool { let requested_block_number = - backend.blockchain().block_number_from_id(&block_id).ok().flatten(); + backend.blockchain().block_number_from_id(block_id).ok().flatten(); Some(self.block_number) <= requested_block_number } @@ -70,7 +70,7 @@ fn make_hash(val: &K) -> Vec { } impl FetchRuntimeCode for WasmSubstitute { - fn fetch_runtime_code<'a>(&'a self) -> Option> { + fn fetch_runtime_code(&self) -> Option> { Some(self.code.as_slice().into()) } } diff --git a/substrate/client/service/src/lib.rs b/substrate/client/service/src/lib.rs index a48e6168c5..0d2461376d 100644 --- a/substrate/client/service/src/lib.rs +++ b/substrate/client/service/src/lib.rs @@ -180,7 +180,7 @@ async fn build_network_future< if notification.is_new_best { network.service().new_best_block_imported( notification.hash, - notification.header.number().clone(), + *notification.header.number(), ); } } @@ -204,7 +204,7 @@ async fn build_network_future< let _ = sender.send(network.local_peer_id().to_base58()); }, sc_rpc::system::Request::LocalListenAddresses(sender) => { - let peer_id = network.local_peer_id().clone().into(); + let peer_id = (*network.local_peer_id()).into(); let p2p_proto_suffix = sc_network::multiaddr::Protocol::P2p(peer_id); let addresses = network.listen_addresses() .map(|addr| addr.clone().with(p2p_proto_suffix.clone()).to_string()) @@ -222,7 +222,7 @@ async fn build_network_future< ).collect()); } sc_rpc::system::Request::NetworkState(sender) => { - if let Some(network_state) = serde_json::to_value(&network.network_state()).ok() { + if let Ok(network_state) = serde_json::to_value(&network.network_state()) { let _ = sender.send(network_state); } } @@ -265,7 +265,7 @@ async fn build_network_future< use sc_rpc::system::SyncState; let _ = sender.send(SyncState { - starting_block: starting_block, + starting_block, current_block: client.info().best_number, highest_block: network.best_seen_block(), }); @@ -385,7 +385,7 @@ fn start_rpc_servers< address, config.rpc_cors.as_ref(), gen_handler( - deny_unsafe(&address, &config.rpc_methods), + deny_unsafe(address, &config.rpc_methods), sc_rpc_server::RpcMiddleware::new( rpc_metrics.clone(), rpc_method_names.clone(), @@ -404,7 +404,7 @@ fn start_rpc_servers< config.rpc_ws_max_connections, config.rpc_cors.as_ref(), gen_handler( - deny_unsafe(&address, &config.rpc_methods), + deny_unsafe(address, &config.rpc_methods), sc_rpc_server::RpcMiddleware::new( rpc_metrics.clone(), rpc_method_names.clone(), diff --git a/substrate/client/service/src/metrics.rs b/substrate/client/service/src/metrics.rs index 9fbf2c3ea3..555023f894 100644 --- a/substrate/client/service/src/metrics.rs +++ b/substrate/client/service/src/metrics.rs @@ -61,13 +61,13 @@ impl PrometheusMetrics { .const_label("name", name) .const_label("version", version), )?, - ®istry, + registry, )? .set(1); register( Gauge::::new("substrate_node_roles", "The roles the node is running as")?, - ®istry, + registry, )? .set(roles); diff --git a/substrate/client/service/src/task_manager/mod.rs b/substrate/client/service/src/task_manager/mod.rs index 2f9cd257c3..49189dc21c 100644 --- a/substrate/client/service/src/task_manager/mod.rs +++ b/substrate/client/service/src/task_manager/mod.rs @@ -38,12 +38,12 @@ mod prometheus_future; mod tests; /// Default task group name. -pub const DEFAULT_GROUP_NAME: &'static str = "default"; +pub const DEFAULT_GROUP_NAME: &str = "default"; /// The name of a group a task belongs to. /// /// This name is passed belong-side the task name to the prometheus metrics and can be used -/// to group tasks. +/// to group tasks. pub enum GroupName { /// Sets the group name to `default`. Default, diff --git a/substrate/client/service/test/src/lib.rs b/substrate/client/service/test/src/lib.rs index c492ed30f7..ef04e16a65 100644 --- a/substrate/client/service/test/src/lib.rs +++ b/substrate/client/service/test/src/lib.rs @@ -308,15 +308,15 @@ where handle.clone(), Some(key), self.base_port, - &temp, + temp, ); - let addr = node_config.network.listen_addresses.iter().next().unwrap().clone(); + let addr = node_config.network.listen_addresses.first().unwrap().clone(); let (service, user_data) = authority(node_config).expect("Error creating test node service"); handle.spawn(service.clone().map_err(|_| ())); - let addr = addr - .with(multiaddr::Protocol::P2p(service.network().local_peer_id().clone().into())); + let addr = + addr.with(multiaddr::Protocol::P2p((*service.network().local_peer_id()).into())); self.authority_nodes.push((self.nodes, service, user_data, addr)); self.nodes += 1; } @@ -329,14 +329,14 @@ where handle.clone(), None, self.base_port, - &temp, + temp, ); - let addr = node_config.network.listen_addresses.iter().next().unwrap().clone(); + let addr = node_config.network.listen_addresses.first().unwrap().clone(); let (service, user_data) = full(node_config).expect("Error creating test node service"); handle.spawn(service.clone().map_err(|_| ())); - let addr = addr - .with(multiaddr::Protocol::P2p(service.network().local_peer_id().clone().into())); + let addr = + addr.with(multiaddr::Protocol::P2p((*service.network().local_peer_id()).into())); self.full_nodes.push((self.nodes, service, user_data, addr)); self.nodes += 1; } @@ -461,7 +461,7 @@ pub fn sync( info!("Generating #{}", i + 1); } - make_block_and_import(&first_service, first_user_data); + make_block_and_import(first_service, first_user_data); } let info = network.full_nodes[0].1.client().info(); network.full_nodes[0] diff --git a/substrate/client/state-db/src/lib.rs b/substrate/client/state-db/src/lib.rs index 74f218e88f..8fe2cdc9d9 100644 --- a/substrate/client/state-db/src/lib.rs +++ b/substrate/client/state-db/src/lib.rs @@ -268,7 +268,7 @@ impl StateDbSync Ok(()), @@ -314,7 +314,7 @@ impl StateDbSync if self.mode == PruningMode::ArchiveCanonical { commit.data.deleted.clear(); @@ -322,14 +322,14 @@ impl StateDbSync return Err(e), }; if let Some(ref mut pruning) = self.pruning { - pruning.note_canonical(&hash, &mut commit); + pruning.note_canonical(hash, &mut commit); } self.prune(&mut commit); Ok(commit) } fn best_canonical(&self) -> Option { - return self.non_canonical.last_canonicalized_block_number() + self.non_canonical.last_canonicalized_block_number() } fn is_pruned(&self, hash: &BlockHash, number: u64) -> bool { @@ -438,7 +438,7 @@ impl StateDbSync(values: &mut HashMap, inserted fn discard_descendants( levels: &mut (&mut [OverlayLevel], &mut [OverlayLevel]), - mut values: &mut HashMap, + values: &mut HashMap, parents: &mut HashMap, pinned: &HashMap, pinned_insertions: &mut HashMap, u32)>, @@ -135,12 +135,10 @@ fn discard_descendants( ) -> u32 { let (first, mut remainder) = if let Some((first, rest)) = levels.0.split_first_mut() { (Some(first), (rest, &mut *levels.1)) + } else if let Some((first, rest)) = levels.1.split_first_mut() { + (Some(first), (&mut *levels.0, rest)) } else { - if let Some((first, rest)) = levels.1.split_first_mut() { - (Some(first), (&mut *levels.0, rest)) - } else { - (None, (&mut *levels.0, &mut *levels.1)) - } + (None, (&mut *levels.0, &mut *levels.1)) }; let mut pinned_children = 0; if let Some(level) = first { @@ -169,7 +167,7 @@ fn discard_descendants( } else { // discard immediately. parents.remove(&overlay.hash); - discard_values(&mut values, overlay.inserted); + discard_values(values, overlay.inserted); } } } @@ -180,7 +178,7 @@ impl NonCanonicalOverlay { /// Creates a new instance. Does not expect any metadata to be present in the DB. pub fn new(db: &D) -> Result, Error> { let last_canonicalized = - db.get_meta(&to_meta_key(LAST_CANONICAL, &())).map_err(|e| Error::Db(e))?; + db.get_meta(&to_meta_key(LAST_CANONICAL, &())).map_err(Error::Db)?; let last_canonicalized = last_canonicalized .map(|buffer| <(BlockHash, u64)>::decode(&mut buffer.as_slice())) .transpose()?; @@ -196,7 +194,7 @@ impl NonCanonicalOverlay { let mut level = OverlayLevel::new(); for index in 0..MAX_BLOCKS_PER_LEVEL { let journal_key = to_journal_key(block, index); - if let Some(record) = db.get_meta(&journal_key).map_err(|e| Error::Db(e))? { + if let Some(record) = db.get_meta(&journal_key).map_err(Error::Db)? { let record: JournalRecord = Decode::decode(&mut record.as_slice())?; let inserted = record.inserted.iter().map(|(k, _)| k.clone()).collect(); @@ -280,7 +278,7 @@ impl NonCanonicalOverlay { { return Err(Error::InvalidParent) } - } else if !self.parents.contains_key(&parent_hash) { + } else if !self.parents.contains_key(parent_hash) { return Err(Error::InvalidParent) } } @@ -391,12 +389,12 @@ impl NonCanonicalOverlay { let level = self .levels .get(self.pending_canonicalizations.len()) - .ok_or_else(|| Error::InvalidBlock)?; + .ok_or(Error::InvalidBlock)?; let index = level .blocks .iter() .position(|overlay| overlay.hash == *hash) - .ok_or_else(|| Error::InvalidBlock)?; + .ok_or(Error::InvalidBlock)?; let mut discarded_journals = Vec::new(); let mut discarded_blocks = Vec::new(); @@ -493,10 +491,7 @@ impl NonCanonicalOverlay { Key: std::borrow::Borrow, Q: std::hash::Hash + Eq, { - if let Some((_, value)) = self.values.get(&key) { - return Some(value.clone()) - } - None + self.values.get(key).map(|v| v.1.clone()) } /// Check if the block is in the canonicalization queue. diff --git a/substrate/client/state-db/src/pruning.rs b/substrate/client/state-db/src/pruning.rs index 2631405cdf..0fdcb8e822 100644 --- a/substrate/client/state-db/src/pruning.rs +++ b/substrate/client/state-db/src/pruning.rs @@ -76,7 +76,7 @@ impl RefWindow { db: &D, count_insertions: bool, ) -> Result, Error> { - let last_pruned = db.get_meta(&to_meta_key(LAST_PRUNED, &())).map_err(|e| Error::Db(e))?; + let last_pruned = db.get_meta(&to_meta_key(LAST_PRUNED, &())).map_err(Error::Db)?; let pending_number: u64 = match last_pruned { Some(buffer) => u64::decode(&mut buffer.as_slice())? + 1, None => 0, @@ -94,7 +94,7 @@ impl RefWindow { trace!(target: "state-db", "Reading pruning journal. Pending #{}", pending_number); loop { let journal_key = to_journal_key(block); - match db.get_meta(&journal_key).map_err(|e| Error::Db(e))? { + match db.get_meta(&journal_key).map_err(Error::Db)? { Some(record) => { let record: JournalRecord = Decode::decode(&mut record.as_slice())?; @@ -208,7 +208,7 @@ impl RefWindow { trace!(target: "state-db", "Applying pruning {:?} ({} deleted)", pruned.hash, pruned.deleted.len()); if self.count_insertions { for k in pruned.deleted.iter() { - self.death_index.remove(&k); + self.death_index.remove(k); } } self.pending_number += 1; diff --git a/substrate/client/sync-state-rpc/src/lib.rs b/substrate/client/sync-state-rpc/src/lib.rs index 6fc0d17800..d7696c662e 100644 --- a/substrate/client/sync-state-rpc/src/lib.rs +++ b/substrate/client/sync-state-rpc/src/lib.rs @@ -166,7 +166,7 @@ where let finalized_block_weight = sc_consensus_babe::aux_schema::load_block_weight(&*self.client, finalized_hash)? - .ok_or_else(|| Error::LoadingBlockWeightFailed(finalized_hash))?; + .ok_or(Error::LoadingBlockWeightFailed(finalized_hash))?; Ok(LightSyncState { finalized_block_header: finalized_header, diff --git a/substrate/client/telemetry/src/lib.rs b/substrate/client/telemetry/src/lib.rs index d570701a3d..fc40f999a6 100644 --- a/substrate/client/telemetry/src/lib.rs +++ b/substrate/client/telemetry/src/lib.rs @@ -246,7 +246,7 @@ impl TelemetryWorker { "Initializing telemetry for: {:?}", addr, ); - node_map.entry(id.clone()).or_default().push((verbosity, addr.clone())); + node_map.entry(id).or_default().push((verbosity, addr.clone())); let node = node_pool.entry(addr.clone()).or_insert_with(|| { Node::new(transport.clone(), addr.clone(), Vec::new(), Vec::new()) @@ -288,7 +288,7 @@ impl TelemetryWorker { ) { let (id, verbosity, payload) = input.expect("the stream is never closed; qed"); - let ts = chrono::Local::now().to_rfc3339().to_string(); + let ts = chrono::Local::now().to_rfc3339(); let mut message = serde_json::Map::new(); message.insert("id".into(), id.into()); message.insert("ts".into(), ts.into()); @@ -318,7 +318,7 @@ impl TelemetryWorker { continue } - if let Some(node) = node_pool.get_mut(&addr) { + if let Some(node) = node_pool.get_mut(addr) { let _ = node.send(message.clone()).await; } else { log::debug!( @@ -386,7 +386,7 @@ impl Telemetry { /// The `connection_message` argument is a JSON object that is sent every time the connection /// (re-)establishes. pub fn start_telemetry(&mut self, connection_message: ConnectionMessage) -> Result<()> { - let endpoints = self.endpoints.take().ok_or_else(|| Error::TelemetryAlreadyInitialized)?; + let endpoints = self.endpoints.take().ok_or(Error::TelemetryAlreadyInitialized)?; self.register_sender .unbounded_send(Register::Telemetry { id: self.id, endpoints, connection_message }) diff --git a/substrate/client/telemetry/src/node.rs b/substrate/client/telemetry/src/node.rs index f3d746abb2..aa0f5a3843 100644 --- a/substrate/client/telemetry/src/node.rs +++ b/substrate/client/telemetry/src/node.rs @@ -239,7 +239,7 @@ where }, }, NodeSocket::WaitingReconnect(mut s) => { - if let Poll::Ready(_) = Future::poll(Pin::new(&mut s), cx) { + if Future::poll(Pin::new(&mut s), cx).is_ready() { socket = NodeSocket::ReconnectNow; } else { break NodeSocket::WaitingReconnect(s) diff --git a/substrate/client/tracing/src/block/mod.rs b/substrate/client/tracing/src/block/mod.rs index 259827e4b4..6de3a0220e 100644 --- a/substrate/client/tracing/src/block/mod.rs +++ b/substrate/client/tracing/src/block/mod.rs @@ -108,7 +108,7 @@ impl BlockSubscriber { impl Subscriber for BlockSubscriber { fn enabled(&self, metadata: &tracing::Metadata<'_>) -> bool { - if !metadata.is_span() && !metadata.fields().field(REQUIRED_EVENT_FIELD).is_some() { + if !metadata.is_span() && metadata.fields().field(REQUIRED_EVENT_FIELD).is_none() { return false } for (target, level) in &self.targets { @@ -221,12 +221,12 @@ where let mut header = self .client .header(id) - .map_err(|e| Error::InvalidBlockId(e))? + .map_err(Error::InvalidBlockId)? .ok_or_else(|| Error::MissingBlockComponent("Header not found".to_string()))?; let extrinsics = self .client .block_body(&id) - .map_err(|e| Error::InvalidBlockId(e))? + .map_err(Error::InvalidBlockId)? .ok_or_else(|| Error::MissingBlockComponent("Extrinsics not found".to_string()))?; tracing::debug!(target: "state_tracing", "Found {} extrinsics", extrinsics.len()); let parent_hash = *header.parent_hash(); @@ -252,16 +252,18 @@ where let _enter = span.enter(); self.client.runtime_api().execute_block(&parent_id, block) }) { - return Err(Error::Dispatch( - format!("Failed to collect traces and execute block: {}", e).to_string(), - )) + return Err(Error::Dispatch(format!( + "Failed to collect traces and execute block: {}", + e + ))) } } - let block_subscriber = - dispatch.downcast_ref::().ok_or(Error::Dispatch( + let block_subscriber = dispatch.downcast_ref::().ok_or_else(|| { + Error::Dispatch( "Cannot downcast Dispatch to BlockSubscriber after tracing block".to_string(), - ))?; + ) + })?; let spans: Vec<_> = block_subscriber .spans .lock() diff --git a/substrate/client/tracing/src/lib.rs b/substrate/client/tracing/src/lib.rs index ff3723e0d1..1ae695a725 100644 --- a/substrate/client/tracing/src/lib.rs +++ b/substrate/client/tracing/src/lib.rs @@ -166,8 +166,7 @@ impl Visit for Values { } fn record_debug(&mut self, field: &Field, value: &dyn std::fmt::Debug) { - self.string_values - .insert(field.name().to_string(), format!("{:?}", value).to_owned()); + self.string_values.insert(field.name().to_string(), format!("{:?}", value)); } } @@ -239,7 +238,7 @@ impl ProfilingLayer { /// or without: "pallet" in which case the level defaults to `trace`. /// wasm_tracing indicates whether to enable wasm traces pub fn new_with_handler(trace_handler: Box, targets: &str) -> Self { - let targets: Vec<_> = targets.split(',').map(|s| parse_target(s)).collect(); + let targets: Vec<_> = targets.split(',').map(parse_target).collect(); Self { targets, trace_handlers: vec![trace_handler] } } diff --git a/substrate/client/tracing/src/logging/directives.rs b/substrate/client/tracing/src/logging/directives.rs index fe7d6a780d..b5fb373674 100644 --- a/substrate/client/tracing/src/logging/directives.rs +++ b/substrate/client/tracing/src/logging/directives.rs @@ -84,7 +84,7 @@ pub fn reload_filter() -> Result<(), String> { log::debug!(target: "tracing", "Reloading log filter with: {}", env_filter); FILTER_RELOAD_HANDLE .get() - .ok_or("No reload handle present".to_string())? + .ok_or("No reload handle present")? .reload(env_filter) .map_err(|e| format!("{}", e)) } diff --git a/substrate/client/tracing/src/logging/mod.rs b/substrate/client/tracing/src/logging/mod.rs index f5cdda4d35..33c83dd871 100644 --- a/substrate/client/tracing/src/logging/mod.rs +++ b/substrate/client/tracing/src/logging/mod.rs @@ -110,7 +110,7 @@ where // Accept all valid directives and print invalid ones fn parse_user_directives(mut env_filter: EnvFilter, dirs: &str) -> Result { for dir in dirs.split(',') { - env_filter = env_filter.add_directive(parse_default_directive(&dir)?); + env_filter = env_filter.add_directive(parse_default_directive(dir)?); } Ok(env_filter) } @@ -299,32 +299,30 @@ impl LoggerBuilder { Ok(()) } + } else if self.log_reloading { + let subscriber = prepare_subscriber( + &self.directives, + None, + self.force_colors, + self.detailed_output, + |builder| enable_log_reloading!(builder), + )?; + + tracing::subscriber::set_global_default(subscriber)?; + + Ok(()) } else { - if self.log_reloading { - let subscriber = prepare_subscriber( - &self.directives, - None, - self.force_colors, - self.detailed_output, - |builder| enable_log_reloading!(builder), - )?; + let subscriber = prepare_subscriber( + &self.directives, + None, + self.force_colors, + self.detailed_output, + |builder| builder, + )?; - tracing::subscriber::set_global_default(subscriber)?; + tracing::subscriber::set_global_default(subscriber)?; - Ok(()) - } else { - let subscriber = prepare_subscriber( - &self.directives, - None, - self.force_colors, - self.detailed_output, - |builder| builder, - )?; - - tracing::subscriber::set_global_default(subscriber)?; - - Ok(()) - } + Ok(()) } } } diff --git a/substrate/client/transaction-pool/api/src/lib.rs b/substrate/client/transaction-pool/api/src/lib.rs index d7b3ddc996..448578b327 100644 --- a/substrate/client/transaction-pool/api/src/lib.rs +++ b/substrate/client/transaction-pool/api/src/lib.rs @@ -350,7 +350,7 @@ impl OffchainSubmitTransaction for TP extrinsic ); - let result = self.submit_local(&at, extrinsic); + let result = self.submit_local(at, extrinsic); result.map(|_| ()).map_err(|e| { log::warn!( diff --git a/substrate/client/transaction-pool/src/api.rs b/substrate/client/transaction-pool/src/api.rs index 12909f313d..4710c96b00 100644 --- a/substrate/client/transaction-pool/src/api.rs +++ b/substrate/client/transaction-pool/src/api.rs @@ -123,7 +123,7 @@ where type BodyFuture = Ready::Extrinsic>>>>; fn block_body(&self, id: &BlockId) -> Self::BodyFuture { - ready(self.client.block_body(&id).map_err(|e| error::Error::from(e))) + ready(self.client.block_body(id).map_err(error::Error::from)) } fn validate_transaction( @@ -134,7 +134,7 @@ where ) -> Self::ValidationFuture { let (tx, rx) = oneshot::channel(); let client = self.client.clone(); - let at = at.clone(); + let at = *at; let validation_pool = self.validation_pool.clone(); let metrics = self.metrics.clone(); @@ -212,7 +212,7 @@ where let runtime_api = client.runtime_api(); let api_version = sp_tracing::within_span! { sp_tracing::Level::TRACE, "check_version"; runtime_api - .api_version::>(&at) + .api_version::>(at) .map_err(|e| Error::RuntimeApi(e.to_string()))? .ok_or_else(|| Error::RuntimeApi( format!("Could not find `TaggedTransactionQueue` api for block `{:?}`.", at) @@ -229,7 +229,7 @@ where sp_tracing::Level::TRACE, "runtime::validate_transaction"; { if api_version >= 3 { - runtime_api.validate_transaction(&at, source, uxt, block_hash) + runtime_api.validate_transaction(at, source, uxt, block_hash) .map_err(|e| Error::RuntimeApi(e.to_string())) } else { let block_number = client.to_number(at) @@ -249,11 +249,11 @@ where if api_version == 2 { #[allow(deprecated)] // old validate_transaction - runtime_api.validate_transaction_before_version_3(&at, source, uxt) + runtime_api.validate_transaction_before_version_3(at, source, uxt) .map_err(|e| Error::RuntimeApi(e.to_string())) } else { #[allow(deprecated)] // old validate_transaction - runtime_api.validate_transaction_before_version_2(&at, uxt) + runtime_api.validate_transaction_before_version_2(at, uxt) .map_err(|e| Error::RuntimeApi(e.to_string())) } } diff --git a/substrate/client/transaction-pool/src/graph/pool.rs b/substrate/client/transaction-pool/src/graph/pool.rs index 39be43f82c..618ba8ccf2 100644 --- a/substrate/client/transaction-pool/src/graph/pool.rs +++ b/substrate/client/transaction-pool/src/graph/pool.rs @@ -335,7 +335,7 @@ impl Pool { // And finally - submit reverified transactions back to the pool self.validated_pool.resubmit_pruned( - &at, + at, known_imported_hashes, pruned_hashes, reverified_transactions.into_iter().map(|(_, xt)| xt).collect(), diff --git a/substrate/client/transaction-pool/src/graph/ready.rs b/substrate/client/transaction-pool/src/graph/ready.rs index ebaa73f149..220e69b13e 100644 --- a/substrate/client/transaction-pool/src/graph/ready.rs +++ b/substrate/client/transaction-pool/src/graph/ready.rs @@ -300,7 +300,7 @@ impl ReadyTransactions { for tag in &tx.transaction.transaction.requires { if let Some(hash) = self.provided_tags.get(tag) { if let Some(tx) = ready.get_mut(hash) { - remove_item(&mut tx.unlocks, &hash); + remove_item(&mut tx.unlocks, hash); } } } @@ -351,7 +351,7 @@ impl ReadyTransactions { let mut ready = self.ready.write(); let mut find_previous = |tag| -> Option> { let prev_hash = self.provided_tags.get(tag)?; - let tx2 = ready.get_mut(&prev_hash)?; + let tx2 = ready.get_mut(prev_hash)?; remove_item(&mut tx2.unlocks, hash); // We eagerly prune previous transactions as well. // But it might not always be good. @@ -551,7 +551,7 @@ impl Iterator for BestIterator { continue } - let ready = match self.all.get(&hash).cloned() { + let ready = match self.all.get(hash).cloned() { Some(ready) => ready, // The transaction is not in all, maybe it was removed in the meantime? None => continue, diff --git a/substrate/client/transaction-pool/src/graph/validated_pool.rs b/substrate/client/transaction-pool/src/graph/validated_pool.rs index 4ddaf8de5c..084b04842e 100644 --- a/substrate/client/transaction-pool/src/graph/validated_pool.rs +++ b/substrate/client/transaction-pool/src/graph/validated_pool.rs @@ -442,7 +442,7 @@ impl ValidatedPool { pub fn extrinsics_tags(&self, hashes: &[ExtrinsicHash]) -> Vec>> { self.pool .read() - .by_hashes(&hashes) + .by_hashes(hashes) .into_iter() .map(|existing_in_pool| { existing_in_pool.map(|transaction| transaction.provides.to_vec()) @@ -546,7 +546,7 @@ impl ValidatedPool { let now = Instant::now(); let to_remove = { self.ready() - .filter(|tx| self.rotator.ban_if_stale(&now, block_number, &tx)) + .filter(|tx| self.rotator.ban_if_stale(&now, block_number, tx)) .map(|tx| tx.hash) .collect::>() }; @@ -554,7 +554,7 @@ impl ValidatedPool { let p = self.pool.read(); let mut hashes = Vec::new(); for tx in p.futures() { - if self.rotator.ban_if_stale(&now, block_number, &tx) { + if self.rotator.ban_if_stale(&now, block_number, tx) { hashes.push(tx.hash); } } @@ -630,11 +630,7 @@ impl ValidatedPool { /// Returns a Vec of hashes and extrinsics in the future pool. pub fn futures(&self) -> Vec<(ExtrinsicHash, ExtrinsicFor)> { - self.pool - .read() - .futures() - .map(|tx| (tx.hash.clone(), tx.data.clone())) - .collect() + self.pool.read().futures().map(|tx| (tx.hash, tx.data.clone())).collect() } /// Returns pool status. @@ -663,9 +659,9 @@ where match *imported { base::Imported::Ready { ref promoted, ref failed, ref removed, ref hash } => { listener.ready(hash, None); - failed.into_iter().for_each(|f| listener.invalid(f)); - removed.into_iter().for_each(|r| listener.dropped(&r.hash, Some(hash))); - promoted.into_iter().for_each(|p| listener.ready(p, None)); + failed.iter().for_each(|f| listener.invalid(f)); + removed.iter().for_each(|r| listener.dropped(&r.hash, Some(hash))); + promoted.iter().for_each(|p| listener.ready(p, None)); }, base::Imported::Future { ref hash } => listener.future(hash), } diff --git a/substrate/client/transaction-pool/src/lib.rs b/substrate/client/transaction-pool/src/lib.rs index 9fd2ef1dee..eb36d46538 100644 --- a/substrate/client/transaction-pool/src/lib.rs +++ b/substrate/client/transaction-pool/src/lib.rs @@ -430,7 +430,7 @@ where let validated = ValidatedTransaction::valid_at( block_number.saturated_into::(), - hash.clone(), + hash, TransactionSource::Local, xt, bytes, @@ -538,7 +538,7 @@ async fn prune_known_txs_for_block>(); + let hashes = extrinsics.iter().map(|tx| pool.hash_of(tx)).collect::>(); log::trace!(target: "txpool", "Pruning transactions: {:?}", hashes); @@ -609,11 +609,11 @@ where if let Some(ref tree_route) = tree_route { for retracted in tree_route.retracted() { // notify txs awaiting finality that it has been retracted - pool.validated_pool().on_block_retracted(retracted.hash.clone()); + pool.validated_pool().on_block_retracted(retracted.hash); } future::join_all(tree_route.enacted().iter().map(|h| { - prune_known_txs_for_block(BlockId::Hash(h.hash.clone()), &*api, &*pool) + prune_known_txs_for_block(BlockId::Hash(h.hash), &*api, &*pool) })) .await .into_iter() @@ -622,7 +622,7 @@ where }) } - pruned_log.extend(prune_known_txs_for_block(id.clone(), &*api, &*pool).await); + pruned_log.extend(prune_known_txs_for_block(id, &*api, &*pool).await); metrics.report(|metrics| { metrics.block_transactions_pruned.inc_by(pruned_log.len() as u64) @@ -632,7 +632,7 @@ where let mut resubmit_transactions = Vec::new(); for retracted in tree_route.retracted() { - let hash = retracted.hash.clone(); + let hash = retracted.hash; let block_transactions = api .block_body(&BlockId::hash(hash)) @@ -649,7 +649,7 @@ where resubmit_transactions.extend(block_transactions.into_iter().filter( |tx| { - let tx_hash = pool.hash_of(&tx); + let tx_hash = pool.hash_of(tx); let contains = pruned_log.contains(&tx_hash); // need to count all transactions, not just filtered, here @@ -699,8 +699,7 @@ where }); if next_action.revalidate { - let hashes = - pool.validated_pool().ready().map(|tx| tx.hash.clone()).collect(); + let hashes = pool.validated_pool().ready().map(|tx| tx.hash).collect(); revalidation_queue.revalidate_later(block_number, hashes).await; revalidation_strategy.lock().clear(); diff --git a/substrate/client/transaction-pool/src/revalidation.rs b/substrate/client/transaction-pool/src/revalidation.rs index e3641008a7..b4b4299240 100644 --- a/substrate/client/transaction-pool/src/revalidation.rs +++ b/substrate/client/transaction-pool/src/revalidation.rs @@ -92,7 +92,7 @@ async fn batch_revalidate( }, Ok(Ok(validity)) => { revalidated.insert( - ext_hash.clone(), + ext_hash, ValidatedTransaction::valid_at( at.saturated_into::(), ext_hash, @@ -194,14 +194,14 @@ impl RevalidationWorker { self.block_ordered .entry(block_number) .and_modify(|value| { - value.insert(ext_hash.clone()); + value.insert(ext_hash); }) .or_insert_with(|| { let mut bt = HashSet::new(); - bt.insert(ext_hash.clone()); + bt.insert(ext_hash); bt }); - self.members.insert(ext_hash.clone(), block_number); + self.members.insert(ext_hash, block_number); } } diff --git a/substrate/client/utils/src/pubsub.rs b/substrate/client/utils/src/pubsub.rs index c8e51e3494..ba6e9ddc6c 100644 --- a/substrate/client/utils/src/pubsub.rs +++ b/substrate/client/utils/src/pubsub.rs @@ -195,8 +195,8 @@ impl Hub { let mut shared_borrowed = shared_locked.borrow_mut(); let (registry, sinks) = shared_borrowed.get_mut(); - let dispatch_result = registry.dispatch(trigger, |subs_id, item| { - if let Some(tx) = sinks.get_mut(&subs_id) { + registry.dispatch(trigger, |subs_id, item| { + if let Some(tx) = sinks.get_mut(subs_id) { if let Err(send_err) = tx.unbounded_send(item) { log::warn!("Sink with SubsID = {} failed to perform unbounded_send: {} ({} as Dispatch<{}, Item = {}>::dispatch(...))", subs_id, send_err, std::any::type_name::(), std::any::type_name::(), @@ -211,9 +211,7 @@ impl Hub { std::any::type_name::(), ); } - }); - - dispatch_result + }) } } diff --git a/substrate/frame/assets/src/benchmarking.rs b/substrate/frame/assets/src/benchmarking.rs index 33de190a8e..ca88899edf 100644 --- a/substrate/frame/assets/src/benchmarking.rs +++ b/substrate/frame/assets/src/benchmarking.rs @@ -281,7 +281,7 @@ benchmarks_instance_pallet! { let target0 = T::Lookup::unlookup(account("target", 0, SEED)); let target1 = T::Lookup::unlookup(account("target", 1, SEED)); let target2 = T::Lookup::unlookup(account("target", 2, SEED)); - }: _(SystemOrigin::Signed(caller), Default::default(), target0.clone(), target1.clone(), target2.clone()) + }: _(SystemOrigin::Signed(caller), Default::default(), target0, target1, target2) verify { assert_last_event::(Event::TeamChanged { asset_id: Default::default(), @@ -346,7 +346,7 @@ benchmarks_instance_pallet! { let (caller, _) = create_default_asset::(true); T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); let dummy = vec![0u8; T::StringLimit::get() as usize]; - let origin = SystemOrigin::Signed(caller.clone()).into(); + let origin = SystemOrigin::Signed(caller).into(); Assets::::set_metadata(origin, Default::default(), dummy.clone(), dummy, 12)?; let origin = T::ForceOrigin::successful_origin(); @@ -365,7 +365,7 @@ benchmarks_instance_pallet! { owner: caller_lookup.clone(), issuer: caller_lookup.clone(), admin: caller_lookup.clone(), - freezer: caller_lookup.clone(), + freezer: caller_lookup, min_balance: 100u32.into(), is_sufficient: true, is_frozen: false, @@ -398,7 +398,7 @@ benchmarks_instance_pallet! { let delegate_lookup = T::Lookup::unlookup(delegate.clone()); let amount = 100u32.into(); let origin = SystemOrigin::Signed(owner.clone()).into(); - Assets::::approve_transfer(origin, id, delegate_lookup.clone(), amount)?; + Assets::::approve_transfer(origin, id, delegate_lookup, amount)?; let dest: T::AccountId = account("dest", 0, SEED); let dest_lookup = T::Lookup::unlookup(dest.clone()); diff --git a/substrate/frame/assets/src/functions.rs b/substrate/frame/assets/src/functions.rs index a6abfd9e04..0f8e7096e8 100644 --- a/substrate/frame/assets/src/functions.rs +++ b/substrate/frame/assets/src/functions.rs @@ -204,7 +204,7 @@ impl, I: 'static> Pallet { who: &T::AccountId, keep_alive: bool, ) -> Result { - let details = Asset::::get(id).ok_or_else(|| Error::::Unknown)?; + let details = Asset::::get(id).ok_or(Error::::Unknown)?; ensure!(!details.is_frozen, Error::::Frozen); let account = Account::::get(id, who).ok_or(Error::::NoAccount)?; @@ -258,7 +258,7 @@ impl, I: 'static> Pallet { Ok(dust) => actual.saturating_add(dust), //< guaranteed by reducible_balance Err(e) => { debug_assert!(false, "passed from reducible_balance; qed"); - return Err(e.into()) + return Err(e) }, }; @@ -291,7 +291,7 @@ impl, I: 'static> Pallet { (true, Some(dust)) => (amount, Some(dust)), _ => (debit, None), }; - Self::can_increase(id, &dest, credit, false).into_result()?; + Self::can_increase(id, dest, credit, false).into_result()?; Ok((credit, maybe_burn)) } @@ -352,7 +352,7 @@ impl, I: 'static> Pallet { ) -> DispatchResult { Self::increase_balance(id, beneficiary, amount, |details| -> DispatchResult { if let Some(check_issuer) = maybe_check_issuer { - ensure!(&check_issuer == &details.issuer, Error::::NoPermission); + ensure!(check_issuer == details.issuer, Error::::NoPermission); } debug_assert!( T::Balance::max_value() - details.supply >= amount, @@ -433,7 +433,7 @@ impl, I: 'static> Pallet { let actual = Self::decrease_balance(id, target, amount, f, |actual, details| { // Check admin rights. if let Some(check_admin) = maybe_check_admin { - ensure!(&check_admin == &details.admin, Error::::NoPermission); + ensure!(check_admin == details.admin, Error::::NoPermission); } debug_assert!(details.supply >= actual, "checked in prep; qed"); @@ -471,7 +471,7 @@ impl, I: 'static> Pallet { let mut target_died: Option = None; Asset::::try_mutate(id, |maybe_details| -> DispatchResult { - let mut details = maybe_details.as_mut().ok_or(Error::::Unknown)?; + let details = maybe_details.as_mut().ok_or(Error::::Unknown)?; check(actual, details)?; @@ -483,8 +483,7 @@ impl, I: 'static> Pallet { account.balance = account.balance.saturating_sub(actual); if account.balance < details.min_balance { debug_assert!(account.balance.is_zero(), "checked in prep; qed"); - target_died = - Some(Self::dead_account(target, &mut details, &account.reason, false)); + target_died = Some(Self::dead_account(target, details, &account.reason, false)); if let Some(Remove) = target_died { return Ok(()) } @@ -543,8 +542,8 @@ impl, I: 'static> Pallet { } // Figure out the debit and credit, together with side-effects. - let debit = Self::prep_debit(id, &source, amount, f.into())?; - let (credit, maybe_burn) = Self::prep_credit(id, &dest, amount, debit, f.burn_dust)?; + let debit = Self::prep_debit(id, source, amount, f.into())?; + let (credit, maybe_burn) = Self::prep_credit(id, dest, amount, debit, f.burn_dust)?; let mut source_account = Account::::get(id, &source).ok_or(Error::::NoAccount)?; @@ -555,7 +554,7 @@ impl, I: 'static> Pallet { // Check admin rights. if let Some(need_admin) = maybe_need_admin { - ensure!(&need_admin == &details.admin, Error::::NoPermission); + ensure!(need_admin == details.admin, Error::::NoPermission); } // Skip if source == dest @@ -590,7 +589,7 @@ impl, I: 'static> Pallet { *maybe_account = Some(AssetAccountOf:: { balance: credit, is_frozen: false, - reason: Self::new_account(&dest, details, None)?, + reason: Self::new_account(dest, details, None)?, extra: T::Extra::default(), }); }, @@ -602,7 +601,7 @@ impl, I: 'static> Pallet { if source_account.balance < details.min_balance { debug_assert!(source_account.balance.is_zero(), "checked in prep; qed"); source_died = - Some(Self::dead_account(&source, details, &source_account.reason, false)); + Some(Self::dead_account(source, details, &source_account.reason, false)); if let Some(Remove) = source_died { Account::::remove(id, &source); return Ok(()) @@ -746,7 +745,7 @@ impl, I: 'static> Pallet { }; let deposit_required = T::ApprovalDeposit::get(); if approved.deposit < deposit_required { - T::Currency::reserve(&owner, deposit_required - approved.deposit)?; + T::Currency::reserve(owner, deposit_required - approved.deposit)?; approved.deposit = deposit_required; } approved.amount = approved.amount.saturating_add(amount); @@ -789,10 +788,10 @@ impl, I: 'static> Pallet { approved.amount.checked_sub(&amount).ok_or(Error::::Unapproved)?; let f = TransferFlags { keep_alive: false, best_effort: false, burn_dust: false }; - owner_died = Self::transfer_and_die(id, &owner, &destination, amount, None, f)?.1; + owner_died = Self::transfer_and_die(id, owner, destination, amount, None, f)?.1; if remaining.is_zero() { - T::Currency::unreserve(&owner, approved.deposit); + T::Currency::unreserve(owner, approved.deposit); Asset::::mutate(id, |maybe_details| { if let Some(details) = maybe_details { details.approvals.saturating_dec(); diff --git a/substrate/frame/assets/src/impl_stored_map.rs b/substrate/frame/assets/src/impl_stored_map.rs index dfdcff37d1..a4669c776e 100644 --- a/substrate/frame/assets/src/impl_stored_map.rs +++ b/substrate/frame/assets/src/impl_stored_map.rs @@ -42,7 +42,7 @@ impl, I: 'static> StoredMap<(T::AssetId, T::AccountId), T::Extra> f if let Some(ref mut account) = maybe_account { account.extra = extra; } else { - Err(DispatchError::NoProviders)?; + return Err(DispatchError::NoProviders.into()) } } else { // They want to delete it. Let this pass if the item never existed anyway. diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index 9b0f23a0a1..eb412de58f 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -788,7 +788,7 @@ pub mod pallet { let origin = ensure_signed(origin)?; let d = Asset::::get(id).ok_or(Error::::Unknown)?; - ensure!(&origin == &d.freezer, Error::::NoPermission); + ensure!(origin == d.freezer, Error::::NoPermission); let who = T::Lookup::lookup(who)?; Account::::try_mutate(id, &who, |maybe_account| -> DispatchResult { @@ -819,7 +819,7 @@ pub mod pallet { let origin = ensure_signed(origin)?; let details = Asset::::get(id).ok_or(Error::::Unknown)?; - ensure!(&origin == &details.admin, Error::::NoPermission); + ensure!(origin == details.admin, Error::::NoPermission); let who = T::Lookup::lookup(who)?; Account::::try_mutate(id, &who, |maybe_account| -> DispatchResult { @@ -849,7 +849,7 @@ pub mod pallet { Asset::::try_mutate(id, |maybe_details| { let d = maybe_details.as_mut().ok_or(Error::::Unknown)?; - ensure!(&origin == &d.freezer, Error::::NoPermission); + ensure!(origin == d.freezer, Error::::NoPermission); d.is_frozen = true; @@ -876,7 +876,7 @@ pub mod pallet { Asset::::try_mutate(id, |maybe_details| { let d = maybe_details.as_mut().ok_or(Error::::Unknown)?; - ensure!(&origin == &d.admin, Error::::NoPermission); + ensure!(origin == d.admin, Error::::NoPermission); d.is_frozen = false; @@ -906,7 +906,7 @@ pub mod pallet { Asset::::try_mutate(id, |maybe_details| { let details = maybe_details.as_mut().ok_or(Error::::Unknown)?; - ensure!(&origin == &details.owner, Error::::NoPermission); + ensure!(origin == details.owner, Error::::NoPermission); if details.owner == owner { return Ok(()) } @@ -951,7 +951,7 @@ pub mod pallet { Asset::::try_mutate(id, |maybe_details| { let details = maybe_details.as_mut().ok_or(Error::::Unknown)?; - ensure!(&origin == &details.owner, Error::::NoPermission); + ensure!(origin == details.owner, Error::::NoPermission); details.issuer = issuer.clone(); details.admin = admin.clone(); @@ -1009,7 +1009,7 @@ pub mod pallet { let origin = ensure_signed(origin)?; let d = Asset::::get(id).ok_or(Error::::Unknown)?; - ensure!(&origin == &d.owner, Error::::NoPermission); + ensure!(origin == d.owner, Error::::NoPermission); Metadata::::try_mutate_exists(id, |metadata| { let deposit = metadata.take().ok_or(Error::::Unknown)?.deposit; @@ -1241,7 +1241,7 @@ pub mod pallet { .map(|_| ()) .or_else(|origin| -> DispatchResult { let origin = ensure_signed(origin)?; - ensure!(&origin == &d.admin, Error::::NoPermission); + ensure!(origin == d.admin, Error::::NoPermission); Ok(()) })?; diff --git a/substrate/frame/assets/src/types.rs b/substrate/frame/assets/src/types.rs index 56034e5908..2e8a1f911f 100644 --- a/substrate/frame/assets/src/types.rs +++ b/substrate/frame/assets/src/types.rs @@ -104,9 +104,9 @@ impl ExistenceReason { if let ExistenceReason::DepositHeld(deposit) = sp_std::mem::replace(self, ExistenceReason::DepositRefunded) { - return Some(deposit) + Some(deposit) } else { - return None + None } } } diff --git a/substrate/frame/atomic-swap/src/lib.rs b/substrate/frame/atomic-swap/src/lib.rs index 40429c226e..b999aefaaa 100644 --- a/substrate/frame/atomic-swap/src/lib.rs +++ b/substrate/frame/atomic-swap/src/lib.rs @@ -138,7 +138,7 @@ where C: ReservableCurrency, { fn reserve(&self, source: &AccountId) -> DispatchResult { - C::reserve(&source, self.value) + C::reserve(source, self.value) } fn claim(&self, source: &AccountId, target: &AccountId) -> bool { @@ -267,7 +267,7 @@ pub mod pallet { action, end_block: frame_system::Pallet::::block_number() + duration, }; - PendingSwaps::::insert(target.clone(), hashed_proof.clone(), swap.clone()); + PendingSwaps::::insert(target.clone(), hashed_proof, swap.clone()); Self::deposit_event(Event::NewSwap { account: target, proof: hashed_proof, swap }); @@ -303,7 +303,7 @@ pub mod pallet { let succeeded = swap.action.claim(&swap.source, &target); - PendingSwaps::::remove(target.clone(), hashed_proof.clone()); + PendingSwaps::::remove(target.clone(), hashed_proof); Self::deposit_event(Event::SwapClaimed { account: target, diff --git a/substrate/frame/aura/src/lib.rs b/substrate/frame/aura/src/lib.rs index 0f47477001..222360dc3a 100644 --- a/substrate/frame/aura/src/lib.rs +++ b/substrate/frame/aura/src/lib.rs @@ -261,7 +261,7 @@ impl> FindAuthor let i = Inner::find_author(digests)?; let validators = >::authorities(); - validators.get(i as usize).map(|k| k.clone()) + validators.get(i as usize).cloned() } } diff --git a/substrate/frame/authorship/src/lib.rs b/substrate/frame/authorship/src/lib.rs index 6b72d6ac5d..561db20849 100644 --- a/substrate/frame/authorship/src/lib.rs +++ b/substrate/frame/authorship/src/lib.rs @@ -106,7 +106,7 @@ where let number = header.number(); if let Some(ref author) = author { - if !acc.insert((number.clone(), author.clone())) { + if !acc.insert((*number, author.clone())) { return Err("more than one uncle per number per author included") } } @@ -225,7 +225,7 @@ pub mod pallet { ensure!(new_uncles.len() <= MAX_UNCLES, Error::::TooManyUncles); if >::get() { - Err(Error::::UnclesAlreadySet)? + return Err(Error::::UnclesAlreadySet.into()) } >::put(true); @@ -334,7 +334,7 @@ impl Pallet { let hash = uncle.hash(); if let Some(author) = maybe_author.clone() { - T::EventHandler::note_uncle(author, now - uncle.number().clone()); + T::EventHandler::note_uncle(author, now - *uncle.number()); } uncles.push(UncleEntryItem::Uncle(hash, maybe_author)); } @@ -368,7 +368,7 @@ impl Pallet { } { - let parent_number = uncle.number().clone() - One::one(); + let parent_number = *uncle.number() - One::one(); let parent_hash = >::block_hash(&parent_number); if &parent_hash != uncle.parent_hash() { return Err(Error::::InvalidUncleParent.into()) @@ -387,7 +387,7 @@ impl Pallet { } // check uncle validity. - T::FilterUncle::filter_uncle(&uncle, accumulator).map_err(|e| Into::into(e)) + T::FilterUncle::filter_uncle(uncle, accumulator).map_err(Into::into) } fn prune_old_uncles(minimum_height: T::BlockNumber) { diff --git a/substrate/frame/babe/src/lib.rs b/substrate/frame/babe/src/lib.rs index 87ae762707..2709316d87 100644 --- a/substrate/frame/babe/src/lib.rs +++ b/substrate/frame/babe/src/lib.rs @@ -438,7 +438,7 @@ impl FindAuthor for Pallet { } } - return None + None } } @@ -641,7 +641,7 @@ impl Pallet { let segment_idx = segment_idx + 1; let bounded_randomness = BoundedVec::<_, ConstU32>::try_from(vec![ - randomness.clone(), + *randomness, ]) .expect("UNDER_CONSTRUCTION_SEGMENT_LENGTH >= 1"); UnderConstruction::::insert(&segment_idx, bounded_randomness); @@ -726,7 +726,7 @@ impl Pallet { vrf_output.0.attach_input_hash(&pubkey, transcript).ok() }) - .map(|inout| inout.make_bytes(&sp_consensus_babe::BABE_VRF_INOUT_CONTEXT)) + .map(|inout| inout.make_bytes(sp_consensus_babe::BABE_VRF_INOUT_CONTEXT)) }) }); diff --git a/substrate/frame/bags-list/fuzzer/src/main.rs b/substrate/frame/bags-list/fuzzer/src/main.rs index 6f538eb28e..387c266d32 100644 --- a/substrate/frame/bags-list/fuzzer/src/main.rs +++ b/substrate/frame/bags-list/fuzzer/src/main.rs @@ -62,7 +62,7 @@ fn main() { match action { Action::Insert => { - if BagsList::on_insert(id.clone(), vote_weight).is_err() { + if BagsList::on_insert(id, vote_weight).is_err() { // this was a duplicate id, which is ok. We can just update it. BagsList::on_update(&id, vote_weight); } diff --git a/substrate/frame/bags-list/remote-tests/src/lib.rs b/substrate/frame/bags-list/remote-tests/src/lib.rs index caf7a2a547..458064cf79 100644 --- a/substrate/frame/bags-list/remote-tests/src/lib.rs +++ b/substrate/frame/bags-list/remote-tests/src/lib.rs @@ -21,7 +21,7 @@ use frame_election_provider_support::ScoreProvider; use sp_std::prelude::*; /// A common log target to use. -pub const LOG_TARGET: &'static str = "runtime::bags-list::remote-tests"; +pub const LOG_TARGET: &str = "runtime::bags-list::remote-tests"; pub mod migration; pub mod sanity_check; diff --git a/substrate/frame/bags-list/src/benchmarks.rs b/substrate/frame/bags-list/src/benchmarks.rs index 1a901c4d9d..dba0c9ee1e 100644 --- a/substrate/frame/bags-list/src/benchmarks.rs +++ b/substrate/frame/bags-list/src/benchmarks.rs @@ -133,7 +133,7 @@ frame_benchmarking::benchmarks! { List::::get_bags(), vec![ (origin_bag_thresh, vec![origin_head.clone()]), - (dest_bag_thresh, vec![dest_head.clone(), origin_tail.clone()]) + (dest_bag_thresh, vec![dest_head.clone(), origin_tail]) ] ); } diff --git a/substrate/frame/bags-list/src/lib.rs b/substrate/frame/bags-list/src/lib.rs index 94553433e2..53ccd5e4c1 100644 --- a/substrate/frame/bags-list/src/lib.rs +++ b/substrate/frame/bags-list/src/lib.rs @@ -74,7 +74,7 @@ pub use list::{notional_bag_for, Bag, List, ListError, Node}; pub use pallet::*; pub use weights::WeightInfo; -pub(crate) const LOG_TARGET: &'static str = "runtime::bags_list"; +pub(crate) const LOG_TARGET: &str = "runtime::bags_list"; // syntactic sugar for logging. #[macro_export] @@ -254,7 +254,7 @@ impl, I: 'static> Pallet { pub fn do_rebag(account: &T::AccountId, new_weight: T::Score) -> Option<(T::Score, T::Score)> { // if no voter at that node, don't do anything. // the caller just wasted the fee to call this. - let maybe_movement = list::Node::::get(&account) + let maybe_movement = list::Node::::get(account) .and_then(|node| List::update_position_for(node, new_weight)); if let Some((from, to)) = maybe_movement { Self::deposit_event(Event::::Rebagged { who: account.clone(), from, to }); diff --git a/substrate/frame/bags-list/src/list/mod.rs b/substrate/frame/bags-list/src/list/mod.rs index db8c06a38d..4de7056925 100644 --- a/substrate/frame/bags-list/src/list/mod.rs +++ b/substrate/frame/bags-list/src/list/mod.rs @@ -59,7 +59,7 @@ mod tests; pub fn notional_bag_for, I: 'static>(score: T::Score) -> T::Score { let thresholds = T::BagThresholds::get(); let idx = thresholds.partition_point(|&threshold| score > threshold); - thresholds.get(idx).copied().unwrap_or(T::Score::max_value()) + thresholds.get(idx).copied().unwrap_or_else(T::Score::max_value) } /// The **ONLY** entry point of this module. All operations to the bags-list should happen through @@ -163,7 +163,7 @@ impl, I: 'static> List { let affected_bag = { // this recreates `notional_bag_for` logic, but with the old thresholds. let idx = old_thresholds.partition_point(|&threshold| inserted_bag > threshold); - old_thresholds.get(idx).copied().unwrap_or(T::Score::max_value()) + old_thresholds.get(idx).copied().unwrap_or_else(T::Score::max_value) }; if !affected_old_bags.insert(affected_bag) { // If the previous threshold list was [10, 20], and we insert [3, 5], then there's @@ -420,24 +420,24 @@ impl, I: 'static> List { use crate::pallet; use frame_support::ensure; - let lighter_node = Node::::get(&lighter_id).ok_or(pallet::Error::IdNotFound)?; - let heavier_node = Node::::get(&heavier_id).ok_or(pallet::Error::IdNotFound)?; + let lighter_node = Node::::get(lighter_id).ok_or(pallet::Error::IdNotFound)?; + let heavier_node = Node::::get(heavier_id).ok_or(pallet::Error::IdNotFound)?; ensure!(lighter_node.bag_upper == heavier_node.bag_upper, pallet::Error::NotInSameBag); // this is the most expensive check, so we do it last. ensure!( - T::ScoreProvider::score(&heavier_id) > T::ScoreProvider::score(&lighter_id), + T::ScoreProvider::score(heavier_id) > T::ScoreProvider::score(lighter_id), pallet::Error::NotHeavier ); // remove the heavier node from this list. Note that this removes the node from storage and // decrements the node counter. - Self::remove(&heavier_id); + Self::remove(heavier_id); // re-fetch `lighter_node` from storage since it may have been updated when `heavier_node` // was removed. - let lighter_node = Node::::get(&lighter_id).ok_or_else(|| { + let lighter_node = Node::::get(lighter_id).ok_or_else(|| { debug_assert!(false, "id that should exist cannot be found"); crate::log!(warn, "id that should exist cannot be found"); pallet::Error::IdNotFound @@ -527,7 +527,7 @@ impl, I: 'static> List { thresholds.into_iter().filter_map(|t| Bag::::get(t)) }; - let _ = active_bags.clone().map(|b| b.sanity_check()).collect::>()?; + let _ = active_bags.clone().try_for_each(|b| b.sanity_check())?; let nodes_in_bags_count = active_bags.clone().fold(0u32, |acc, cur| acc + cur.iter().count() as u32); @@ -708,7 +708,7 @@ impl, I: 'static> Bag { // the first insertion into the bag. In this case, both head and tail should point to the // same node. if self.head.is_none() { - self.head = Some(id.clone()); + self.head = Some(id); debug_assert!(self.iter().count() == 1); } } diff --git a/substrate/frame/bags-list/src/mock.rs b/substrate/frame/bags-list/src/mock.rs index fce1431054..961bf2b835 100644 --- a/substrate/frame/bags-list/src/mock.rs +++ b/substrate/frame/bags-list/src/mock.rs @@ -42,7 +42,7 @@ impl frame_election_provider_support::ScoreProvider for StakingMock { #[cfg(any(feature = "runtime-benchmarks", test))] fn set_score_of(id: &AccountId, weight: Self::Score) { - NEXT_VOTE_WEIGHT_MAP.with(|m| m.borrow_mut().insert(id.clone(), weight)); + NEXT_VOTE_WEIGHT_MAP.with(|m| m.borrow_mut().insert(*id, weight)); } } diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index 5ba6c4dfa1..7060486f85 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -775,7 +775,7 @@ impl, I: 'static> Pallet { /// Get both the free and reserved balances of an account. fn account(who: &T::AccountId) -> AccountData { - T::AccountStore::get(&who) + T::AccountStore::get(who) } /// Handles any steps needed after mutating an account. @@ -988,17 +988,15 @@ impl, I: 'static> Pallet { } } else { Locks::::insert(who, bounded_locks); - if !existed { - if system::Pallet::::inc_consumers_without_limit(who).is_err() { - // No providers for the locks. This is impossible under normal circumstances - // since the funds that are under the lock will themselves be stored in the - // account and therefore will need a reference. - log::warn!( - target: "runtime::balances", - "Warning: Attempt to introduce lock consumer reference, yet no providers. \ - This is unexpected but should be safe." - ); - } + if !existed && system::Pallet::::inc_consumers_without_limit(who).is_err() { + // No providers for the locks. This is impossible under normal circumstances + // since the funds that are under the lock will themselves be stored in the + // account and therefore will need a reference. + log::warn!( + target: "runtime::balances", + "Warning: Attempt to introduce lock consumer reference, yet no providers. \ + This is unexpected but should be safe." + ); } } } @@ -1107,7 +1105,7 @@ impl, I: 'static> fungible::Mutate for Pallet { return Ok(()) } Self::try_mutate_account(who, |account, _is_new| -> DispatchResult { - Self::deposit_consequence(who, amount, &account, true).into_result()?; + Self::deposit_consequence(who, amount, account, true).into_result()?; account.free += amount; Ok(()) })?; @@ -1126,7 +1124,7 @@ impl, I: 'static> fungible::Mutate for Pallet { let actual = Self::try_mutate_account( who, |account, _is_new| -> Result { - let extra = Self::withdraw_consequence(who, amount, &account).into_result()?; + let extra = Self::withdraw_consequence(who, amount, account).into_result()?; let actual = amount + extra; account.free -= actual; Ok(actual) @@ -1214,7 +1212,7 @@ impl, I: 'static> fungible::MutateHold for Pallet::InsufficientBalance); // ^^^ Guaranteed to be <= amount and <= a.reserved a.free = new_free; - a.reserved = a.reserved.saturating_sub(actual.clone()); + a.reserved = a.reserved.saturating_sub(actual); Ok(actual) }) } @@ -1318,7 +1316,7 @@ mod imbalances { } } fn peek(&self) -> T::Balance { - self.0.clone() + self.0 } } @@ -1377,7 +1375,7 @@ mod imbalances { } } fn peek(&self) -> T::Balance { - self.0.clone() + self.0 } } @@ -1560,7 +1558,7 @@ where if value.is_zero() { return (NegativeImbalance::zero(), Zero::zero()) } - if Self::total_balance(&who).is_zero() { + if Self::total_balance(who).is_zero() { return (NegativeImbalance::zero(), value) } @@ -1656,7 +1654,7 @@ where return Self::PositiveImbalance::zero() } - let r = Self::try_mutate_account( + Self::try_mutate_account( who, |account, is_new| -> Result { let ed = T::ExistentialDeposit::get(); @@ -1673,9 +1671,7 @@ where Ok(PositiveImbalance::new(value)) }, ) - .unwrap_or_else(|_| Self::PositiveImbalance::zero()); - - r + .unwrap_or_else(|_| Self::PositiveImbalance::zero()) } /// Withdraw some free balance from an account, respecting existence requirements. @@ -1785,7 +1781,7 @@ where account.free.checked_sub(&value).ok_or(Error::::InsufficientBalance)?; account.reserved = account.reserved.checked_add(&value).ok_or(ArithmeticError::Overflow)?; - Self::ensure_can_withdraw(&who, value.clone(), WithdrawReasons::RESERVE, account.free) + Self::ensure_can_withdraw(&who, value, WithdrawReasons::RESERVE, account.free) })?; Self::deposit_event(Event::Reserved { who: who.clone(), amount: value }); @@ -1799,7 +1795,7 @@ where if value.is_zero() { return Zero::zero() } - if Self::total_balance(&who).is_zero() { + if Self::total_balance(who).is_zero() { return value } @@ -1820,7 +1816,7 @@ where }, }; - Self::deposit_event(Event::Unreserved { who: who.clone(), amount: actual.clone() }); + Self::deposit_event(Event::Unreserved { who: who.clone(), amount: actual }); value - actual } @@ -1835,7 +1831,7 @@ where if value.is_zero() { return (NegativeImbalance::zero(), Zero::zero()) } - if Self::total_balance(&who).is_zero() { + if Self::total_balance(who).is_zero() { return (NegativeImbalance::zero(), value) } @@ -1925,7 +1921,7 @@ where }, Err(index) => { reserves - .try_insert(index, ReserveData { id: id.clone(), amount: value }) + .try_insert(index, ReserveData { id: *id, amount: value }) .map_err(|_| Error::::TooManyReserves)?; }, }; @@ -2086,7 +2082,7 @@ where reserves .try_insert( index, - ReserveData { id: id.clone(), amount: actual }, + ReserveData { id: *id, amount: actual }, ) .map_err(|_| Error::::TooManyReserves)?; diff --git a/substrate/frame/benchmarking/src/analysis.rs b/substrate/frame/benchmarking/src/analysis.rs index 52baec80e6..c19af78123 100644 --- a/substrate/frame/benchmarking/src/analysis.rs +++ b/substrate/frame/benchmarking/src/analysis.rs @@ -91,7 +91,7 @@ impl Analysis { }) .collect(); - values.sort(); + values.sort_unstable(); let mid = values.len() / 2; Some(Self { @@ -216,7 +216,7 @@ impl Analysis { } for (_, rs) in results.iter_mut() { - rs.sort(); + rs.sort_unstable(); let ql = rs.len() / 4; *rs = rs[ql..rs.len() - ql].to_vec(); } @@ -255,7 +255,7 @@ impl Analysis { .iter() .map(|(p, vs)| { // Avoid divide by zero - if vs.len() == 0 { + if vs.is_empty() { return (p.clone(), 0, 0) } let total = vs.iter().fold(0u128, |acc, v| acc + *v); diff --git a/substrate/frame/bounties/src/benchmarking.rs b/substrate/frame/bounties/src/benchmarking.rs index 04adacf6e4..912e461501 100644 --- a/substrate/frame/bounties/src/benchmarking.rs +++ b/substrate/frame/bounties/src/benchmarking.rs @@ -99,7 +99,7 @@ benchmarks! { propose_curator { setup_pot_account::(); let (caller, curator, fee, value, reason) = setup_bounty::(0, T::MaximumReasonLength::get()); - let curator_lookup = T::Lookup::unlookup(curator.clone()); + let curator_lookup = T::Lookup::unlookup(curator); Bounties::::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?; let bounty_id = BountyCount::::get() - 1; Bounties::::approve_bounty(RawOrigin::Root.into(), bounty_id)?; diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index 886c758bbe..dfeef36a1f 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -474,7 +474,7 @@ pub mod pallet { // Else this is the curator, willingly giving up their role. // Give back their deposit. let err_amount = - T::Currency::unreserve(&curator, bounty.curator_deposit); + T::Currency::unreserve(curator, bounty.curator_deposit); debug_assert!(err_amount.is_zero()); bounty.curator_deposit = Zero::zero(); // Continue to change bounty status below... @@ -706,7 +706,7 @@ pub mod pallet { BountyStatus::Active { curator, .. } => { // Cancelled by council, refund deposit of the working curator. let err_amount = - T::Currency::unreserve(&curator, bounty.curator_deposit); + T::Currency::unreserve(curator, bounty.curator_deposit); debug_assert!(err_amount.is_zero()); // Then execute removal of the bounty below. }, diff --git a/substrate/frame/child-bounties/src/benchmarking.rs b/substrate/frame/child-bounties/src/benchmarking.rs index d9edf14bbc..dcb54361fa 100644 --- a/substrate/frame/child-bounties/src/benchmarking.rs +++ b/substrate/frame/child-bounties/src/benchmarking.rs @@ -110,7 +110,7 @@ fn activate_bounty( Bounties::::propose_curator( RawOrigin::Root.into(), child_bounty_setup.bounty_id, - curator_lookup.clone(), + curator_lookup, child_bounty_setup.fee, )?; Bounties::::accept_curator( @@ -141,7 +141,7 @@ fn activate_child_bounty( RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_id, - child_curator_lookup.clone(), + child_curator_lookup, bounty_setup.child_bounty_fee, )?; @@ -211,7 +211,7 @@ benchmarks! { RawOrigin::Signed(bounty_setup.curator.clone()).into(), bounty_setup.bounty_id, bounty_setup.child_bounty_id, - child_curator_lookup.clone(), + child_curator_lookup, bounty_setup.child_bounty_fee, )?; }: _(RawOrigin::Signed(bounty_setup.child_curator), bounty_setup.bounty_id, @@ -246,7 +246,7 @@ benchmarks! { setup_pot_account::(); let bounty_setup = activate_child_bounty::(0, T::MaximumReasonLength::get())?; let beneficiary_account: T::AccountId = account("beneficiary", 0, SEED); - let beneficiary = T::Lookup::unlookup(beneficiary_account.clone()); + let beneficiary = T::Lookup::unlookup(beneficiary_account); ChildBounties::::award_child_bounty( RawOrigin::Signed(bounty_setup.child_curator.clone()).into(), diff --git a/substrate/frame/child-bounties/src/lib.rs b/substrate/frame/child-bounties/src/lib.rs index 0bbd451244..a8496d4e7a 100644 --- a/substrate/frame/child-bounties/src/lib.rs +++ b/substrate/frame/child-bounties/src/lib.rs @@ -512,7 +512,7 @@ pub mod pallet { Some(sender) if sender == *curator => { // This is the child-bounty curator, willingly giving up their // role. Give back their deposit. - T::Currency::unreserve(&curator, child_bounty.curator_deposit); + T::Currency::unreserve(curator, child_bounty.curator_deposit); // Reset curator deposit. child_bounty.curator_deposit = Zero::zero(); // Continue to change bounty status below. @@ -673,13 +673,13 @@ pub mod pallet { // Unreserve the curator deposit. Should not fail // because the deposit is always reserved when curator is // assigned. - let _ = T::Currency::unreserve(&curator, child_bounty.curator_deposit); + let _ = T::Currency::unreserve(curator, child_bounty.curator_deposit); // Make payout to child-bounty curator. // Should not fail because curator fee is always less than bounty value. let fee_transfer_result = T::Currency::transfer( &child_bounty_account, - &curator, + curator, curator_fee, AllowDeath, ); diff --git a/substrate/frame/collective/src/benchmarking.rs b/substrate/frame/collective/src/benchmarking.rs index d5d0fc5f26..076afcd203 100644 --- a/substrate/frame/collective/src/benchmarking.rs +++ b/substrate/frame/collective/src/benchmarking.rs @@ -250,7 +250,7 @@ benchmarks_instance_pallet! { let approve = true; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; @@ -259,7 +259,7 @@ benchmarks_instance_pallet! { let approve = true; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; @@ -272,7 +272,7 @@ benchmarks_instance_pallet! { // Whitelist voter account from further DB operations. let voter_key = frame_system::Account::::hashed_key_for(&voter); frame_benchmarking::benchmarking::add_to_whitelist(voter_key.into()); - }: _(SystemOrigin::Signed(voter), last_hash.clone(), index, approve) + }: _(SystemOrigin::Signed(voter), last_hash, index, approve) verify { // All proposals exist and the last proposal has just been updated. assert_eq!(Collective::::proposals().len(), p as usize); @@ -327,7 +327,7 @@ benchmarks_instance_pallet! { let approve = true; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; @@ -336,7 +336,7 @@ benchmarks_instance_pallet! { let approve = true; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; @@ -347,7 +347,7 @@ benchmarks_instance_pallet! { let approve = false; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; @@ -355,7 +355,7 @@ benchmarks_instance_pallet! { // Whitelist voter account from further DB operations. let voter_key = frame_system::Account::::hashed_key_for(&voter); frame_benchmarking::benchmarking::add_to_whitelist(voter_key.into()); - }: close(SystemOrigin::Signed(voter), last_hash.clone(), index, Weight::max_value(), bytes_in_storage) + }: close(SystemOrigin::Signed(voter), last_hash, index, Weight::max_value(), bytes_in_storage) verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); @@ -400,7 +400,7 @@ benchmarks_instance_pallet! { // Caller switches vote to nay on their own proposal, allowing them to be the deciding approval vote Collective::::vote( SystemOrigin::Signed(caller.clone()).into(), - last_hash.clone(), + last_hash, p - 1, false, )?; @@ -411,7 +411,7 @@ benchmarks_instance_pallet! { let approve = false; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, p - 1, approve, )?; @@ -420,7 +420,7 @@ benchmarks_instance_pallet! { // Member zero is the first aye Collective::::vote( SystemOrigin::Signed(members[0].clone()).into(), - last_hash.clone(), + last_hash, p - 1, true, )?; @@ -432,11 +432,11 @@ benchmarks_instance_pallet! { let approve = true; Collective::::vote( SystemOrigin::Signed(caller.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; - }: close(SystemOrigin::Signed(caller), last_hash.clone(), index, Weight::max_value(), bytes_in_storage) + }: close(SystemOrigin::Signed(caller), last_hash, index, Weight::max_value(), bytes_in_storage) verify { // The last proposal is removed. assert_eq!(Collective::::proposals().len(), (p - 1) as usize); @@ -493,7 +493,7 @@ benchmarks_instance_pallet! { let approve = true; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, index, approve, )?; @@ -502,7 +502,7 @@ benchmarks_instance_pallet! { // caller is prime, prime votes nay Collective::::vote( SystemOrigin::Signed(caller.clone()).into(), - last_hash.clone(), + last_hash, index, false, )?; @@ -560,7 +560,7 @@ benchmarks_instance_pallet! { // The prime member votes aye, so abstentions default to aye. Collective::::vote( SystemOrigin::Signed(caller.clone()).into(), - last_hash.clone(), + last_hash, p - 1, true // Vote aye. )?; @@ -572,7 +572,7 @@ benchmarks_instance_pallet! { let approve = false; Collective::::vote( SystemOrigin::Signed(voter.clone()).into(), - last_hash.clone(), + last_hash, p - 1, approve )?; diff --git a/substrate/frame/contracts/src/benchmarking/code.rs b/substrate/frame/contracts/src/benchmarking/code.rs index 2544fd6b7f..5f9b43d3e3 100644 --- a/substrate/frame/contracts/src/benchmarking/code.rs +++ b/substrate/frame/contracts/src/benchmarking/code.rs @@ -277,15 +277,14 @@ where } module }; - let limits = module + let limits = *module .import_section() .unwrap() .entries() .iter() .find_map(|e| if let External::Memory(mem) = e.external() { Some(mem) } else { None }) .unwrap() - .limits() - .clone(); + .limits(); let code = module.to_bytes().unwrap(); let hash = T::Hashing::hash(&code); let memory = @@ -512,16 +511,10 @@ pub mod body { DynInstr::RandomI32(low, high) => { vec![Instruction::I32Const(rng.gen_range(*low..*high))] }, - DynInstr::RandomI32Repeated(num) => (&mut rng) - .sample_iter(Standard) - .take(*num) - .map(|val| Instruction::I32Const(val)) - .collect(), - DynInstr::RandomI64Repeated(num) => (&mut rng) - .sample_iter(Standard) - .take(*num) - .map(|val| Instruction::I64Const(val)) - .collect(), + DynInstr::RandomI32Repeated(num) => + (&mut rng).sample_iter(Standard).take(*num).map(Instruction::I32Const).collect(), + DynInstr::RandomI64Repeated(num) => + (&mut rng).sample_iter(Standard).take(*num).map(Instruction::I64Const).collect(), DynInstr::RandomGetLocal(low, high) => { vec![Instruction::GetLocal(rng.gen_range(*low..*high))] }, diff --git a/substrate/frame/contracts/src/benchmarking/mod.rs b/substrate/frame/contracts/src/benchmarking/mod.rs index e67436fbc9..84f4cb6083 100644 --- a/substrate/frame/contracts/src/benchmarking/mod.rs +++ b/substrate/frame/contracts/src/benchmarking/mod.rs @@ -138,7 +138,7 @@ where Storage::::write(&info.trie_id, &item.0, Some(item.1.clone()), None, false) .map_err(|_| "Failed to write storage to restoration dest")?; } - >::insert(&self.account_id, info.clone()); + >::insert(&self.account_id, info); Ok(()) } @@ -253,7 +253,7 @@ benchmarks! { )?; let value = T::Currency::minimum_balance(); let origin = RawOrigin::Signed(instance.caller.clone()); - let callee = instance.addr.clone(); + let callee = instance.addr; }: call(origin, callee, value, Weight::MAX, None, vec![]) // This constructs a contract that is maximal expensive to instrument. @@ -1067,7 +1067,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1164,7 +1164,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1216,7 +1216,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1263,7 +1263,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1308,7 +1308,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1360,7 +1360,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1412,7 +1412,7 @@ benchmarks! { ) .map_err(|_| "Failed to write to storage during setup.")?; } - >::insert(&instance.account_id, info.clone()); + >::insert(&instance.account_id, info); let origin = RawOrigin::Signed(instance.caller.clone()); }: call(origin, instance.addr, 0u32.into(), Weight::MAX, None, vec![]) @@ -1577,7 +1577,7 @@ benchmarks! { }); let instance = Contract::::new(code, vec![])?; let callee = instance.addr.clone(); - let origin = RawOrigin::Signed(instance.caller.clone()); + let origin = RawOrigin::Signed(instance.caller); }: call(origin, callee, 0u32.into(), Weight::MAX, None, vec![]) seal_call_per_transfer_clone_kb { @@ -1739,7 +1739,7 @@ benchmarks! { .collect::>(); for addr in &addresses { - if let Some(_) = ContractInfoOf::::get(&addr) { + if ContractInfoOf::::get(&addr).is_some() { return Err("Expected that contract does not exist at this point.".into()); } } @@ -1747,7 +1747,7 @@ benchmarks! { verify { for addr in &addresses { ContractInfoOf::::get(&addr) - .ok_or_else(|| "Contract should have been instantiated")?; + .ok_or("Contract should have been instantiated")?; } } @@ -1755,7 +1755,7 @@ benchmarks! { let t in 0 .. 1; let s in 0 .. (code::max_pages::() - 1) * 64; let callee_code = WasmModule::::dummy(); - let hash = callee_code.hash.clone(); + let hash = callee_code.hash; let hash_bytes = callee_code.hash.encode(); let hash_len = hash_bytes.len(); Contracts::::store_code_raw(callee_code.code, whitelisted_caller())?; diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 54a5223b53..e3ff478879 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -610,7 +610,7 @@ where debug_message: Option<&'a mut Vec>, ) -> Result<(Self, E), ExecError> { let (first_frame, executable, nonce) = - Self::new_frame(args, value, gas_meter, storage_meter, 0, &schedule)?; + Self::new_frame(args, value, gas_meter, storage_meter, 0, schedule)?; let stack = Self { origin, schedule, @@ -660,13 +660,10 @@ where }, FrameArgs::Instantiate { sender, nonce, executable, salt } => { let account_id = - >::contract_address(&sender, executable.code_hash(), &salt); + >::contract_address(&sender, executable.code_hash(), salt); let trie_id = Storage::::generate_trie_id(&account_id, nonce); - let contract = Storage::::new_contract( - &account_id, - trie_id, - executable.code_hash().clone(), - )?; + let contract = + Storage::::new_contract(&account_id, trie_id, *executable.code_hash())?; ( account_id, contract, @@ -742,7 +739,7 @@ where top_frame.nested_storage.charge_instantiate( &self.origin, &top_frame.account_id, - &mut top_frame.contract_info.get(&top_frame.account_id), + top_frame.contract_info.get(&top_frame.account_id), )?; } @@ -1020,11 +1017,11 @@ where code_hash: CodeHash, input_data: Vec, ) -> Result { - let executable = E::from_storage(code_hash, &self.schedule, self.gas_meter())?; + let executable = E::from_storage(code_hash, self.schedule, self.gas_meter())?; let top_frame = self.top_frame_mut(); let contract_info = top_frame.contract_info().clone(); let account_id = top_frame.account_id.clone(); - let value = top_frame.value_transferred.clone(); + let value = top_frame.value_transferred; let executable = self.push_frame( FrameArgs::Call { dest: account_id, @@ -1045,7 +1042,7 @@ where input_data: Vec, salt: &[u8], ) -> Result<(AccountIdOf, ExecReturnValue), ExecError> { - let executable = E::from_storage(code_hash, &self.schedule, self.gas_meter())?; + let executable = E::from_storage(code_hash, self.schedule, self.gas_meter())?; let nonce = self.next_nonce(); let executable = self.push_frame( FrameArgs::Instantiate { @@ -1118,7 +1115,7 @@ where fn caller(&self) -> &T::AccountId { if let Some(caller) = &self.top_frame().delegate_caller { - &caller + caller } else { self.frames().nth(1).map(|f| &f.account_id).unwrap_or(&self.origin) } @@ -1180,7 +1177,7 @@ where } fn schedule(&self) -> &Schedule { - &self.schedule + self.schedule } fn gas_meter(&mut self) -> &mut GasMeter { @@ -1205,7 +1202,7 @@ where } fn ecdsa_recover(&self, signature: &[u8; 65], message_hash: &[u8; 32]) -> Result<[u8; 33], ()> { - secp256k1_ecdsa_recover_compressed(&signature, &message_hash).map_err(|_| ()) + secp256k1_ecdsa_recover_compressed(signature, message_hash).map_err(|_| ()) } fn ecdsa_to_eth_address(&self, pk: &[u8; 33]) -> Result<[u8; 20], ()> { @@ -1220,8 +1217,8 @@ where fn set_code_hash(&mut self, hash: CodeHash) -> Result<(), DispatchError> { E::add_user(hash)?; let top_frame = self.top_frame_mut(); - let prev_hash = top_frame.contract_info().code_hash.clone(); - E::remove_user(prev_hash.clone()); + let prev_hash = top_frame.contract_info().code_hash; + E::remove_user(prev_hash); top_frame.contract_info().code_hash = hash; Contracts::::deposit_event(Event::ContractCodeUpdated { contract: top_frame.account_id.clone(), diff --git a/substrate/frame/contracts/src/gas.rs b/substrate/frame/contracts/src/gas.rs index cdf0c1407c..41df125da0 100644 --- a/substrate/frame/contracts/src/gas.rs +++ b/substrate/frame/contracts/src/gas.rs @@ -114,7 +114,7 @@ where if self.gas_left < amount { Err(>::OutOfGas.into()) } else { - self.gas_left = self.gas_left - amount; + self.gas_left -= amount; Ok(GasMeter::new(amount)) } } diff --git a/substrate/frame/contracts/src/schedule.rs b/substrate/frame/contracts/src/schedule.rs index bbbeb72f2c..9e9f213fab 100644 --- a/substrate/frame/contracts/src/schedule.rs +++ b/substrate/frame/contracts/src/schedule.rs @@ -670,7 +670,7 @@ struct ScheduleRules<'a, T: Config> { impl Schedule { pub(crate) fn rules(&self, module: &elements::Module) -> impl gas_metering::Rules + '_ { ScheduleRules { - schedule: &self, + schedule: self, params: module .type_section() .iter() diff --git a/substrate/frame/contracts/src/storage.rs b/substrate/frame/contracts/src/storage.rs index 17022e9427..2bdacc15cb 100644 --- a/substrate/frame/contracts/src/storage.rs +++ b/substrate/frame/contracts/src/storage.rs @@ -154,10 +154,10 @@ where let hashed_key = blake2_256(key); let child_trie_info = &child_trie_info(trie_id); let (old_len, old_value) = if take { - let val = child::get_raw(&child_trie_info, &hashed_key); + let val = child::get_raw(child_trie_info, &hashed_key); (val.as_ref().map(|v| v.len() as u32), val) } else { - (child::len(&child_trie_info, &hashed_key), None) + (child::len(child_trie_info, &hashed_key), None) }; if let Some(storage_meter) = storage_meter { @@ -183,8 +183,8 @@ where } match &new_value { - Some(new_value) => child::put_raw(&child_trie_info, &hashed_key, new_value), - None => child::kill(&child_trie_info, &hashed_key), + Some(new_value) => child::put_raw(child_trie_info, &hashed_key, new_value), + None => child::kill(child_trie_info, &hashed_key), } Ok(match (old_len, old_value) { diff --git a/substrate/frame/contracts/src/storage/meter.rs b/substrate/frame/contracts/src/storage/meter.rs index 28dc3356f7..af51a5edc9 100644 --- a/substrate/frame/contracts/src/storage/meter.rs +++ b/substrate/frame/contracts/src/storage/meter.rs @@ -230,7 +230,7 @@ where self.total_deposit = self.total_deposit.saturating_add(&absorbed.total_deposit); if !absorbed.own_deposit.is_zero() { - E::charge(origin, &contract, &absorbed.own_deposit, absorbed.terminated); + E::charge(origin, contract, &absorbed.own_deposit, absorbed.terminated); } } @@ -255,7 +255,7 @@ where limit: Option>, min_leftover: BalanceOf, ) -> Result { - let limit = E::check_limit(&origin, limit, min_leftover)?; + let limit = E::check_limit(origin, limit, min_leftover)?; Ok(Self { limit, ..Default::default() }) } diff --git a/substrate/frame/contracts/src/wasm/code_cache.rs b/substrate/frame/contracts/src/wasm/code_cache.rs index ee5cdd5307..ca91fa3131 100644 --- a/substrate/frame/contracts/src/wasm/code_cache.rs +++ b/substrate/frame/contracts/src/wasm/code_cache.rs @@ -165,8 +165,7 @@ where { let charged = gas_meter.charge(CodeToken::Load(schedule.limits.code_len))?; - let mut prefab_module = - >::get(code_hash).ok_or_else(|| Error::::CodeNotFound)?; + let mut prefab_module = >::get(code_hash).ok_or(Error::::CodeNotFound)?; gas_meter.adjust_gas(charged, CodeToken::Load(prefab_module.code.len() as u32)); prefab_module.code_hash = code_hash; @@ -189,7 +188,7 @@ pub fn reinstrument( schedule: &Schedule, ) -> Result { let original_code = - >::get(&prefab_module.code_hash).ok_or_else(|| Error::::CodeNotFound)?; + >::get(&prefab_module.code_hash).ok_or(Error::::CodeNotFound)?; let original_code_len = original_code.len(); prefab_module.code = prepare::reinstrument_contract::(original_code, schedule)?; prefab_module.instruction_weights_version = schedule.instruction_weights.version; diff --git a/substrate/frame/contracts/src/wasm/prepare.rs b/substrate/frame/contracts/src/wasm/prepare.rs index 4571d752a8..6e9babe126 100644 --- a/substrate/frame/contracts/src/wasm/prepare.rs +++ b/substrate/frame/contracts/src/wasm/prepare.rs @@ -225,10 +225,7 @@ impl<'a, T: Config> ContractModule<'a, T> { .map(|is| is.entries()) .unwrap_or(&[]) .iter() - .filter(|entry| match *entry.external() { - External::Function(_) => true, - _ => false, - }) + .filter(|entry| matches!(*entry.external(), External::Function(_))) .count(); for export in export_entries { @@ -259,11 +256,10 @@ impl<'a, T: Config> ContractModule<'a, T> { // We still support () -> (i32) for backwards compatibility. let func_ty_idx = func_entries .get(fn_idx as usize) - .ok_or_else(|| "export refers to non-existent function")? + .ok_or("export refers to non-existent function")? .type_ref(); - let Type::Function(ref func_ty) = types - .get(func_ty_idx as usize) - .ok_or_else(|| "function has a non-existent type")?; + let Type::Function(ref func_ty) = + types.get(func_ty_idx as usize).ok_or("function has a non-existent type")?; if !(func_ty.params().is_empty() && (func_ty.results().is_empty() || func_ty.results() == [ValueType::I32])) { @@ -300,11 +296,11 @@ impl<'a, T: Config> ContractModule<'a, T> { let mut imported_mem_type = None; for import in import_entries { - let type_idx = match import.external() { - &External::Table(_) => return Err("Cannot import tables"), - &External::Global(_) => return Err("Cannot import globals"), - &External::Function(ref type_idx) => type_idx, - &External::Memory(ref memory_type) => { + let type_idx = match *import.external() { + External::Table(_) => return Err("Cannot import tables"), + External::Global(_) => return Err("Cannot import globals"), + External::Function(ref type_idx) => type_idx, + External::Memory(ref memory_type) => { if import.module() != IMPORT_MODULE_MEMORY { return Err("Invalid module for imported memory") } @@ -321,7 +317,7 @@ impl<'a, T: Config> ContractModule<'a, T> { let Type::Function(ref func_ty) = types .get(*type_idx as usize) - .ok_or_else(|| "validation: import entry points to a non-existent type")?; + .ok_or("validation: import entry points to a non-existent type")?; if !T::ChainExtension::enabled() && import.field().as_bytes() == b"seal_call_chain_extension" @@ -352,17 +348,15 @@ fn get_memory_limits( let limits = memory_type.limits(); match (limits.initial(), limits.maximum()) { (initial, Some(maximum)) if initial > maximum => - return Err( - "Requested initial number of pages should not exceed the requested maximum", - ), + Err("Requested initial number of pages should not exceed the requested maximum"), (_, Some(maximum)) if maximum > schedule.limits.memory_pages => - return Err("Maximum number of pages should not exceed the configured maximum."), + Err("Maximum number of pages should not exceed the configured maximum."), (initial, Some(maximum)) => Ok((initial, maximum)), (_, None) => { // Maximum number of pages should be always declared. // This isn't a hard requirement and can be treated as a maximum set // to configured maximum. - return Err("Maximum number of pages should be always declared.") + Err("Maximum number of pages should be always declared.") }, } } else { @@ -377,7 +371,7 @@ fn check_and_instrument( schedule: &Schedule, ) -> Result<(Vec, (u32, u32)), &'static str> { let result = (|| { - let contract_module = ContractModule::new(&original_code, schedule)?; + let contract_module = ContractModule::new(original_code, schedule)?; contract_module.scan_exports()?; contract_module.ensure_no_internal_memory()?; contract_module.ensure_table_size_limit(schedule.limits.table_size)?; diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 876bd8848b..7719d512b8 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -460,13 +460,13 @@ where return match trap_reason { // The trap was the result of the execution `return` host function. TrapReason::Return(ReturnData { flags, data }) => { - let flags = ReturnFlags::from_bits(flags) - .ok_or_else(|| Error::::InvalidCallFlags)?; + let flags = + ReturnFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?; Ok(ExecReturnValue { flags, data: Bytes(data) }) }, TrapReason::Termination => Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Bytes(Vec::new()) }), - TrapReason::SupervisorError(error) => Err(error)?, + TrapReason::SupervisorError(error) => return Err(error.into()), } } @@ -480,10 +480,10 @@ where // // Because panics are really undesirable in the runtime code, we treat this as // a trap for now. Eventually, we might want to revisit this. - Err(sp_sandbox::Error::Module) => Err("validation error")?, + Err(sp_sandbox::Error::Module) => return Err("validation error".into()), // Any other kind of a trap should result in a failure. Err(sp_sandbox::Error::Execution) | Err(sp_sandbox::Error::OutOfBounds) => - Err(Error::::ContractTrapped)?, + return Err(Error::::ContractTrapped.into()), } } @@ -620,7 +620,7 @@ where let len: u32 = self.read_sandbox_memory_as(out_len_ptr)?; if len < buf_len { - Err(Error::::OutputBufferTooSmall)? + return Err(Error::::OutputBufferTooSmall.into()) } if let Some(costs) = create_token(buf_len) { @@ -717,7 +717,7 @@ where let charged = self .charge_gas(RuntimeCosts::SetStorage { new_bytes: value_len, old_bytes: max_size })?; if value_len > max_size { - Err(Error::::ValueTooLarge)?; + return Err(Error::::ValueTooLarge.into()) } let mut key: StorageKey = [0; 32]; self.read_sandbox_memory_into_buf(key_ptr, &mut key)?; @@ -750,11 +750,11 @@ where ) -> Result { self.charge_gas(call_type.cost())?; let input_data = if flags.contains(CallFlags::CLONE_INPUT) { - let input = self.input_data.as_ref().ok_or_else(|| Error::::InputForwarded)?; + let input = self.input_data.as_ref().ok_or(Error::::InputForwarded)?; charge_gas!(self, RuntimeCosts::CallInputCloned(input.len() as u32))?; input.clone() } else if flags.contains(CallFlags::FORWARD_INPUT) { - self.input_data.take().ok_or_else(|| Error::::InputForwarded)? + self.input_data.take().ok_or(Error::::InputForwarded)? } else { self.charge_gas(RuntimeCosts::CopyFromContract(input_data_len))?; self.read_sandbox_memory(input_data_ptr, input_data_len)? @@ -1108,7 +1108,7 @@ define_env!(Env, , output_len_ptr: u32 ) -> ReturnCode => { ctx.call( - CallFlags::from_bits(flags).ok_or_else(|| Error::::InvalidCallFlags)?, + CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, CallType::Call{callee_ptr, value_ptr, gas}, input_data_ptr, input_data_len, @@ -1151,7 +1151,7 @@ define_env!(Env, , output_len_ptr: u32 ) -> ReturnCode => { ctx.call( - CallFlags::from_bits(flags).ok_or_else(|| Error::::InvalidCallFlags)?, + CallFlags::from_bits(flags).ok_or(Error::::InvalidCallFlags)?, CallType::DelegateCall{code_hash_ptr}, input_data_ptr, input_data_len, @@ -1486,7 +1486,7 @@ define_env!(Env, , ctx.charge_gas(RuntimeCosts::GasLeft)?; let gas_left = &ctx.ext.gas_meter().gas_left().encode(); Ok(ctx.write_sandbox_output( - out_ptr, out_len_ptr, &gas_left, false, already_charged, + out_ptr, out_len_ptr, gas_left, false, already_charged, )?) }, @@ -1535,7 +1535,7 @@ define_env!(Env, , [seal0] seal_random(ctx, subject_ptr: u32, subject_len: u32, out_ptr: u32, out_len_ptr: u32) => { ctx.charge_gas(RuntimeCosts::Random)?; if subject_len > ctx.ext.schedule().limits.subject_len { - Err(Error::::RandomSubjectTooLong)?; + return Err(Error::::RandomSubjectTooLong.into()); } let subject_buf = ctx.read_sandbox_memory(subject_ptr, subject_len)?; Ok(ctx.write_sandbox_output( @@ -1567,7 +1567,7 @@ define_env!(Env, , [seal1] seal_random(ctx, subject_ptr: u32, subject_len: u32, out_ptr: u32, out_len_ptr: u32) => { ctx.charge_gas(RuntimeCosts::Random)?; if subject_len > ctx.ext.schedule().limits.subject_len { - Err(Error::::RandomSubjectTooLong)?; + return Err(Error::::RandomSubjectTooLong.into()); } let subject_buf = ctx.read_sandbox_memory(subject_ptr, subject_len)?; Ok(ctx.write_sandbox_output( @@ -1685,13 +1685,13 @@ define_env!(Env, , let num_topic = topics_len .checked_div(sp_std::mem::size_of::>() as u32) - .ok_or_else(|| "Zero sized topics are not allowed")?; + .ok_or("Zero sized topics are not allowed")?; ctx.charge_gas(RuntimeCosts::DepositEvent { num_topic, len: data_len, })?; if data_len > ctx.ext.max_value_size() { - Err(Error::::ValueTooLarge)?; + return Err(Error::::ValueTooLarge.into()); } let mut topics: Vec::::T>> = match topics_len { @@ -1701,14 +1701,14 @@ define_env!(Env, , // If there are more than `event_topics`, then trap. if topics.len() > ctx.ext.schedule().limits.event_topics as usize { - Err(Error::::TooManyTopics)?; + return Err(Error::::TooManyTopics.into()); } // Check for duplicate topics. If there are any, then trap. // Complexity O(n * log(n)) and no additional allocations. // This also sorts the topics. if has_duplicates(&mut topics) { - Err(Error::::DuplicateTopics)?; + return Err(Error::::DuplicateTopics.into()); } let event_data = ctx.read_sandbox_memory(data_ptr, data_len)?; @@ -1888,7 +1888,7 @@ define_env!(Env, , ) -> u32 => { use crate::chain_extension::{ChainExtension, Environment, RetVal}; if !::ChainExtension::enabled() { - Err(Error::::NoChainExtension)?; + return Err(Error::::NoChainExtension.into()); } let env = Environment::new(ctx, input_ptr, input_len, output_ptr, output_len_ptr); match ::ChainExtension::call(func_id, env)? { diff --git a/substrate/frame/conviction-voting/src/benchmarking.rs b/substrate/frame/conviction-voting/src/benchmarking.rs index 2beee4f3b4..53ac7a0730 100644 --- a/substrate/frame/conviction-voting/src/benchmarking.rs +++ b/substrate/frame/conviction-voting/src/benchmarking.rs @@ -44,7 +44,7 @@ fn fill_voting() -> (ClassOf, BTreeMap, Vec> } } } - let c = r.iter().max_by_key(|(_, ref v)| v.len()).unwrap().0.clone(); + let c = r.iter().max_by_key(|(_, v)| v.len()).unwrap().0.clone(); (c, r) } @@ -73,7 +73,7 @@ benchmarks! { let r = polls.len() - 1; // We need to create existing votes for i in polls.iter().skip(1) { - ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, account_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, account_vote)?; } let votes = match VotingFor::::get(&caller, &class) { Voting::Casting(Casting { votes, .. }) => votes, @@ -100,7 +100,7 @@ benchmarks! { let r = polls.len(); // We need to create existing votes for i in polls.iter() { - ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote)?; } let votes = match VotingFor::::get(&caller, &class) { Voting::Casting(Casting { votes, .. }) => votes, @@ -128,7 +128,7 @@ benchmarks! { let r = polls.len(); // We need to create existing votes for i in polls.iter() { - ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, old_account_vote)?; } let votes = match VotingFor::::get(&caller, &class) { Voting::Casting(Casting { votes, .. }) => votes, @@ -156,7 +156,7 @@ benchmarks! { let r = polls.len(); // We need to create existing votes for i in polls.iter() { - ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, old_account_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, old_account_vote)?; } let votes = match VotingFor::::get(&caller, &class) { Voting::Casting(Casting { votes, .. }) => votes, @@ -189,14 +189,14 @@ benchmarks! { // We need to create existing delegations for i in polls.iter().take(r as usize) { - ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote)?; } assert_matches!( VotingFor::::get(&voter, &class), Voting::Casting(Casting { votes, .. }) if votes.len() == r as usize ); - }: _(RawOrigin::Signed(caller.clone()), class.clone(), voter.clone(), Conviction::Locked1x, delegated_balance) + }: _(RawOrigin::Signed(caller.clone()), class.clone(), voter, Conviction::Locked1x, delegated_balance) verify { assert_matches!(VotingFor::::get(&caller, &class), Voting::Delegating(_)); } @@ -224,7 +224,7 @@ benchmarks! { // We need to create delegations for i in polls.iter().take(r as usize) { - ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(voter.clone()).into(), *i, delegate_vote)?; } assert_matches!( VotingFor::::get(&voter, &class), @@ -248,7 +248,7 @@ benchmarks! { for (class, polls) in all_polls.iter() { assert!(polls.len() > 0); for i in polls.iter() { - ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, normal_account_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), *i, normal_account_vote)?; } } @@ -257,7 +257,7 @@ benchmarks! { // Vote big on the class with the most ongoing votes of them to bump the lock and make it // hard to recompute when removed. - ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), polls[0], big_account_vote.clone())?; + ConvictionVoting::::vote(RawOrigin::Signed(caller.clone()).into(), polls[0], big_account_vote)?; let now_usable = >::reducible_balance(&caller, false); assert_eq!(orig_usable - now_usable, 100u32.into()); diff --git a/substrate/frame/conviction-voting/src/lib.rs b/substrate/frame/conviction-voting/src/lib.rs index af91e99fb3..58ac76dac3 100644 --- a/substrate/frame/conviction-voting/src/lib.rs +++ b/substrate/frame/conviction-voting/src/lib.rs @@ -553,7 +553,8 @@ impl, I: 'static> Pallet { }), ); match old { - Voting::Delegating(Delegating { .. }) => Err(Error::::AlreadyDelegating)?, + Voting::Delegating(Delegating { .. }) => + return Err(Error::::AlreadyDelegating.into()), Voting::Casting(Casting { votes, delegations, prior }) => { // here we just ensure that we're currently idling with no votes recorded. ensure!(votes.is_empty(), Error::::AlreadyVoting); diff --git a/substrate/frame/democracy/src/benchmarking.rs b/substrate/frame/democracy/src/benchmarking.rs index bce830b385..c51fde8a3d 100644 --- a/substrate/frame/democracy/src/benchmarking.rs +++ b/substrate/frame/democracy/src/benchmarking.rs @@ -52,7 +52,7 @@ fn add_proposal(n: u32) -> Result { let value = T::MinimumDeposit::get(); let proposal_hash: T::Hash = T::Hashing::hash_of(&n); - Democracy::::propose(RawOrigin::Signed(other).into(), proposal_hash, value.into())?; + Democracy::::propose(RawOrigin::Signed(other).into(), proposal_hash, value)?; Ok(proposal_hash) } @@ -98,7 +98,7 @@ benchmarks! { let proposal_hash: T::Hash = T::Hashing::hash_of(&0); let value = T::MinimumDeposit::get(); whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), proposal_hash, value.into()) + }: _(RawOrigin::Signed(caller), proposal_hash, value) verify { assert_eq!(Democracy::::public_props().len(), p as usize, "Proposals not created."); } @@ -133,7 +133,7 @@ benchmarks! { // We need to create existing direct votes for i in 0 .. r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?; } let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, @@ -161,7 +161,7 @@ benchmarks! { // We need to create existing direct votes for i in 0 ..=r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?; } let votes = match VotingOf::::get(&caller) { Voting::Direct { votes, .. } => votes, @@ -217,7 +217,7 @@ benchmarks! { // Place our proposal in the external queue, too. let hash = T::Hashing::hash_of(&0); assert_ok!( - Democracy::::external_propose(T::ExternalOrigin::successful_origin(), hash.clone()) + Democracy::::external_propose(T::ExternalOrigin::successful_origin(), hash) ); let origin = T::BlacklistOrigin::successful_origin(); // Add a referendum of our proposal. @@ -275,13 +275,13 @@ benchmarks! { fast_track { let origin_propose = T::ExternalDefaultOrigin::successful_origin(); let proposal_hash: T::Hash = T::Hashing::hash_of(&0); - Democracy::::external_propose_default(origin_propose, proposal_hash.clone())?; + Democracy::::external_propose_default(origin_propose, proposal_hash)?; // NOTE: Instant origin may invoke a little bit more logic, but may not always succeed. let origin_fast_track = T::FastTrackOrigin::successful_origin(); let voting_period = T::FastTrackVotingPeriod::get(); let delay = 0u32; - }: _(origin_fast_track, proposal_hash, voting_period.into(), delay.into()) + }: _(origin_fast_track, proposal_hash, voting_period, delay.into()) verify { assert_eq!(Democracy::::referendum_count(), 1, "referendum not created") } @@ -293,7 +293,7 @@ benchmarks! { let proposal_hash: T::Hash = T::Hashing::hash_of(&v); let origin_propose = T::ExternalDefaultOrigin::successful_origin(); - Democracy::::external_propose_default(origin_propose, proposal_hash.clone())?; + Democracy::::external_propose_default(origin_propose, proposal_hash)?; let mut vetoers: Vec = Vec::new(); for i in 0 .. v { @@ -499,7 +499,7 @@ benchmarks! { // We need to create existing direct votes for the `new_delegate` for i in 0..r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(new_delegate.clone()).into(), ref_idx, account_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(new_delegate.clone()).into(), ref_idx, account_vote)?; } let votes = match VotingOf::::get(&new_delegate) { Voting::Direct { votes, .. } => votes, @@ -550,7 +550,7 @@ benchmarks! { Democracy::::vote( RawOrigin::Signed(the_delegate.clone()).into(), ref_idx, - account_vote.clone() + account_vote )?; } let votes = match VotingOf::::get(&the_delegate) { @@ -619,17 +619,17 @@ benchmarks! { let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); let submitter = funded_account::("submitter", b); - Democracy::::note_preimage(RawOrigin::Signed(submitter.clone()).into(), encoded_proposal.clone())?; + Democracy::::note_preimage(RawOrigin::Signed(submitter).into(), encoded_proposal.clone())?; // We need to set this otherwise we get `Early` error. let block_number = T::VotingPeriod::get() + T::EnactmentPeriod::get() + T::BlockNumber::one(); - System::::set_block_number(block_number.into()); + System::::set_block_number(block_number); assert!(Preimages::::contains_key(proposal_hash)); let caller = funded_account::("caller", 0); whitelist_account!(caller); - }: _(RawOrigin::Signed(caller), proposal_hash.clone(), u32::MAX) + }: _(RawOrigin::Signed(caller), proposal_hash, u32::MAX) verify { let proposal_hash = T::Hashing::hash(&encoded_proposal[..]); assert!(!Preimages::::contains_key(proposal_hash)); @@ -646,7 +646,7 @@ benchmarks! { // Vote and immediately unvote for i in 0 .. r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote)?; Democracy::::remove_vote(RawOrigin::Signed(locker.clone()).into(), ref_idx)?; } @@ -669,7 +669,7 @@ benchmarks! { let small_vote = account_vote::(base_balance); for i in 0 .. r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(locker.clone()).into(), ref_idx, small_vote)?; } // Create a big vote so lock increases @@ -711,7 +711,7 @@ benchmarks! { for i in 0 .. r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?; } let votes = match VotingOf::::get(&caller) { @@ -740,7 +740,7 @@ benchmarks! { for i in 0 .. r { let ref_idx = add_referendum::(i)?; - Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote.clone())?; + Democracy::::vote(RawOrigin::Signed(caller.clone()).into(), ref_idx, account_vote)?; } let votes = match VotingOf::::get(&caller) { diff --git a/substrate/frame/democracy/src/lib.rs b/substrate/frame/democracy/src/lib.rs index 8588f1876d..91362a0a3e 100644 --- a/substrate/frame/democracy/src/lib.rs +++ b/substrate/frame/democracy/src/lib.rs @@ -670,8 +670,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; - let seconds = - Self::len_of_deposit_of(proposal).ok_or_else(|| Error::::ProposalMissing)?; + let seconds = Self::len_of_deposit_of(proposal).ok_or(Error::::ProposalMissing)?; ensure!(seconds <= seconds_upper_bound, Error::::WrongUpperBound); let mut deposit = Self::deposit_of(proposal).ok_or(Error::::ProposalMissing)?; T::Currency::reserve(&who, deposit.1)?; @@ -820,12 +819,10 @@ pub mod pallet { // - `InstantAllowed` is `true` and `origin` is `InstantOrigin`. let maybe_ensure_instant = if voting_period < T::FastTrackVotingPeriod::get() { Some(origin) + } else if let Err(origin) = T::FastTrackOrigin::try_origin(origin) { + Some(origin) } else { - if let Err(origin) = T::FastTrackOrigin::try_origin(origin) { - Some(origin) - } else { - None - } + None }; if let Some(ensure_instant) = maybe_ensure_instant { T::InstantOrigin::ensure_origin(ensure_instant)?; @@ -867,7 +864,7 @@ pub mod pallet { if let Some((e_proposal_hash, _)) = >::get() { ensure!(proposal_hash == e_proposal_hash, Error::::ProposalMissing); } else { - Err(Error::::NoProposal)?; + return Err(Error::::NoProposal.into()) } let mut existing_vetoers = @@ -966,7 +963,7 @@ pub mod pallet { /// voted on. Weight is charged as if maximum votes. // NOTE: weight must cover an incorrect voting of origin with max votes, this is ensure // because a valid delegation cover decoding a direct voting with max votes. - #[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get().into()))] + #[pallet::weight(T::WeightInfo::undelegate(T::MaxVotes::get()))] pub fn undelegate(origin: OriginFor) -> DispatchResultWithPostInfo { let who = ensure_signed(origin)?; let votes = Self::try_undelegate(who)?; @@ -1634,7 +1631,7 @@ impl Pallet { ); Ok(()) } else { - Err(Error::::NoneWaiting)? + return Err(Error::::NoneWaiting.into()) } } @@ -1667,7 +1664,7 @@ impl Pallet { } Ok(()) } else { - Err(Error::::NoneWaiting)? + return Err(Error::::NoneWaiting.into()) } } @@ -1822,8 +1819,7 @@ impl Pallet { // To decode the enum variant we only need the first byte. let mut buf = [0u8; 1]; let key = >::hashed_key_for(proposal_hash); - let bytes = - sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::::NotImminent)?; + let bytes = sp_io::storage::read(&key, &mut buf, 0).ok_or(Error::::NotImminent)?; // The value may be smaller that 1 byte. let mut input = &buf[0..buf.len().min(bytes as usize)]; @@ -1851,8 +1847,7 @@ impl Pallet { // * at most 5 bytes to decode a `Compact` let mut buf = [0u8; 6]; let key = >::hashed_key_for(proposal_hash); - let bytes = - sp_io::storage::read(&key, &mut buf, 0).ok_or_else(|| Error::::PreimageMissing)?; + let bytes = sp_io::storage::read(&key, &mut buf, 0).ok_or(Error::::PreimageMissing)?; // The value may be smaller that 6 bytes. let mut input = &buf[0..buf.len().min(bytes as usize)]; @@ -1931,7 +1926,7 @@ impl Pallet { fn decode_compact_u32_at(key: &[u8]) -> Option { // `Compact` takes at most 5 bytes. let mut buf = [0u8; 5]; - let bytes = sp_io::storage::read(&key, &mut buf, 0)?; + let bytes = sp_io::storage::read(key, &mut buf, 0)?; // The value may be smaller than 5 bytes. let mut input = &buf[0..buf.len().min(bytes as usize)]; match codec::Compact::::decode(&mut input) { diff --git a/substrate/frame/election-provider-multi-phase/src/benchmarking.rs b/substrate/frame/election-provider-multi-phase/src/benchmarking.rs index 6dfb2ac794..a1c6437541 100644 --- a/substrate/frame/election-provider-multi-phase/src/benchmarking.rs +++ b/substrate/frame/election-provider-multi-phase/src/benchmarking.rs @@ -491,7 +491,7 @@ frame_benchmarking::benchmarks! { // sort assignments by decreasing voter stake assignments.sort_by_key(|crate::unsigned::Assignment:: { who, .. }| { - let stake = cache.get(&who).map(|idx| { + let stake = cache.get(who).map(|idx| { let (_, stake, _) = voters[*idx]; stake }).unwrap_or_default(); diff --git a/substrate/frame/election-provider-multi-phase/src/lib.rs b/substrate/frame/election-provider-multi-phase/src/lib.rs index a9e341bad6..4aea5b9da4 100644 --- a/substrate/frame/election-provider-multi-phase/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/src/lib.rs @@ -264,7 +264,7 @@ mod mock; #[macro_use] pub mod helpers; -const LOG_TARGET: &'static str = "runtime::election-provider"; +const LOG_TARGET: &str = "runtime::election-provider"; pub mod signed; pub mod unsigned; @@ -1446,7 +1446,7 @@ impl Pallet { ensure!(winners.len() as u32 == desired_targets, FeasibilityError::WrongWinnerCount); // Ensure that the solution's score can pass absolute min-score. - let submitted_score = raw_solution.score.clone(); + let submitted_score = raw_solution.score; ensure!( Self::minimum_untrusted_score().map_or(true, |min_score| { submitted_score.strict_threshold_better(min_score, Perbill::zero()) @@ -1471,29 +1471,26 @@ impl Pallet { .map_err::(Into::into)?; // Ensure that assignments is correct. - let _ = assignments - .iter() - .map(|ref assignment| { - // Check that assignment.who is actually a voter (defensive-only). - // NOTE: while using the index map from `voter_index` is better than a blind linear - // search, this *still* has room for optimization. Note that we had the index when - // we did `solution -> assignment` and we lost it. Ideal is to keep the index - // around. + let _ = assignments.iter().try_for_each(|assignment| { + // Check that assignment.who is actually a voter (defensive-only). + // NOTE: while using the index map from `voter_index` is better than a blind linear + // search, this *still* has room for optimization. Note that we had the index when + // we did `solution -> assignment` and we lost it. Ideal is to keep the index + // around. - // Defensive-only: must exist in the snapshot. - let snapshot_index = - voter_index(&assignment.who).ok_or(FeasibilityError::InvalidVoter)?; - // Defensive-only: index comes from the snapshot, must exist. - let (_voter, _stake, targets) = - snapshot_voters.get(snapshot_index).ok_or(FeasibilityError::InvalidVoter)?; + // Defensive-only: must exist in the snapshot. + let snapshot_index = + voter_index(&assignment.who).ok_or(FeasibilityError::InvalidVoter)?; + // Defensive-only: index comes from the snapshot, must exist. + let (_voter, _stake, targets) = + snapshot_voters.get(snapshot_index).ok_or(FeasibilityError::InvalidVoter)?; - // Check that all of the targets are valid based on the snapshot. - if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) { - return Err(FeasibilityError::InvalidVote) - } - Ok(()) - }) - .collect::>()?; + // Check that all of the targets are valid based on the snapshot. + if assignment.distribution.iter().any(|(d, _)| !targets.contains(d)) { + return Err(FeasibilityError::InvalidVote) + } + Ok(()) + })?; // ----- Start building support. First, we need one more closure. let stake_of = helpers::stake_of_fn::(&snapshot_voters, &cache); diff --git a/substrate/frame/election-provider-multi-phase/src/unsigned.rs b/substrate/frame/election-provider-multi-phase/src/unsigned.rs index d184c3acfe..126dcb1041 100644 --- a/substrate/frame/election-provider-multi-phase/src/unsigned.rs +++ b/substrate/frame/election-provider-multi-phase/src/unsigned.rs @@ -99,7 +99,7 @@ impl From for MinerError { /// Save a given call into OCW storage. fn save_solution(call: &Call) -> Result<(), MinerError> { log!(debug, "saving a call to the offchain storage."); - let storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL); + let storage = StorageValueRef::persistent(OFFCHAIN_CACHED_CALL); match storage.mutate::<_, (), _>(|_| Ok(call.clone())) { Ok(_) => Ok(()), Err(MutateStorageError::ConcurrentModification(_)) => @@ -116,7 +116,7 @@ fn save_solution(call: &Call) -> Result<(), MinerError> { /// Get a saved solution from OCW storage if it exists. fn restore_solution() -> Result, MinerError> { - StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL) + StorageValueRef::persistent(OFFCHAIN_CACHED_CALL) .get() .ok() .flatten() @@ -126,7 +126,7 @@ fn restore_solution() -> Result, MinerError> { /// Clear a saved solution from OCW storage. pub(super) fn kill_ocw_solution() { log!(debug, "clearing offchain call cache storage."); - let mut storage = StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL); + let mut storage = StorageValueRef::persistent(OFFCHAIN_CACHED_CALL); storage.clear(); } @@ -135,14 +135,14 @@ pub(super) fn kill_ocw_solution() { /// After calling this, the next offchain worker is guaranteed to work, with respect to the /// frequency repeat. fn clear_offchain_repeat_frequency() { - let mut last_block = StorageValueRef::persistent(&OFFCHAIN_LAST_BLOCK); + let mut last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK); last_block.clear(); } /// `true` when OCW storage contains a solution #[cfg(test)] fn ocw_solution_exists() -> bool { - matches!(StorageValueRef::persistent(&OFFCHAIN_CACHED_CALL).get::>(), Ok(Some(_))) + matches!(StorageValueRef::persistent(OFFCHAIN_CACHED_CALL).get::>(), Ok(Some(_))) } impl Pallet { @@ -206,9 +206,8 @@ impl Pallet { // get the solution, with a load of checks to ensure if submitted, IT IS ABSOLUTELY VALID. let (raw_solution, witness) = Self::mine_and_check()?; - let score = raw_solution.score.clone(); - let call: Call = - Call::submit_unsigned { raw_solution: Box::new(raw_solution), witness }.into(); + let score = raw_solution.score; + let call: Call = Call::submit_unsigned { raw_solution: Box::new(raw_solution), witness }; log!( debug, @@ -532,7 +531,7 @@ impl Pallet { // we found the right value - early exit the function. Ok(next) => return next, } - step = step / 2; + step /= 2; current_weight = weight_with(voters); } @@ -566,7 +565,7 @@ impl Pallet { /// is returned, `now` is written in storage and will be used in further calls as the baseline. pub fn ensure_offchain_repeat_frequency(now: T::BlockNumber) -> Result<(), MinerError> { let threshold = T::OffchainRepeat::get(); - let last_block = StorageValueRef::persistent(&OFFCHAIN_LAST_BLOCK); + let last_block = StorageValueRef::persistent(OFFCHAIN_LAST_BLOCK); let mutate_stat = last_block.mutate::<_, &'static str, _>( |maybe_head: Result, _>| { diff --git a/substrate/frame/election-provider-support/solution-type/src/lib.rs b/substrate/frame/election-provider-support/solution-type/src/lib.rs index 7c5cb960d2..0a5c11e76d 100644 --- a/substrate/frame/election-provider-support/solution-type/src/lib.rs +++ b/substrate/frame/election-provider-support/solution-type/src/lib.rs @@ -153,7 +153,7 @@ fn check_attributes(input: ParseStream) -> syn::Result { if attrs.len() > 1 { let extra_attr = attrs.pop().expect("attributes vec with len > 1 can be popped"); return Err(syn::Error::new_spanned( - extra_attr.clone(), + extra_attr, "compact solution can accept only #[compact]", )) } @@ -164,7 +164,7 @@ fn check_attributes(input: ParseStream) -> syn::Result { if attr.path.is_ident("compact") { Ok(true) } else { - Err(syn::Error::new_spanned(attr.clone(), "compact solution can accept only #[compact]")) + Err(syn::Error::new_spanned(attr, "compact solution can accept only #[compact]")) } } diff --git a/substrate/frame/election-provider-support/solution-type/src/single_page.rs b/substrate/frame/election-provider-support/solution-type/src/single_page.rs index a20f054298..a7ccf5085d 100644 --- a/substrate/frame/election-provider-support/solution-type/src/single_page.rs +++ b/substrate/frame/election-provider-support/solution-type/src/single_page.rs @@ -33,7 +33,7 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result { } = def; if count <= 2 { - Err(syn_err("cannot build solution struct with capacity less than 3."))? + return Err(syn_err("cannot build solution struct with capacity less than 3.")) } let single = { diff --git a/substrate/frame/election-provider-support/src/lib.rs b/substrate/frame/election-provider-support/src/lib.rs index 37ea2fcc59..69bd3025fa 100644 --- a/substrate/frame/election-provider-support/src/lib.rs +++ b/substrate/frame/election-provider-support/src/lib.rs @@ -244,7 +244,7 @@ impl IndexAssignment>>() .or_invalid_index()?, }) diff --git a/substrate/frame/elections-phragmen/src/benchmarking.rs b/substrate/frame/elections-phragmen/src/benchmarking.rs index 05e9df60c7..493f209242 100644 --- a/substrate/frame/elections-phragmen/src/benchmarking.rs +++ b/substrate/frame/elections-phragmen/src/benchmarking.rs @@ -93,8 +93,7 @@ fn submit_candidates_with_self_vote( let stake = default_stake::(c); let _ = candidates .iter() - .map(|c| submit_voter::(c.clone(), vec![c.clone()], stake).map(|_| ())) - .collect::>()?; + .try_for_each(|c| submit_voter::(c.clone(), vec![c.clone()], stake).map(|_| ()))?; Ok(candidates) } diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index a59da9c20f..270d3853e2 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -503,7 +503,7 @@ pub mod pallet { let had_replacement = Self::remove_and_replace_member(&who, true)?; debug_assert_eq!(has_replacement, had_replacement); - Self::deposit_event(Event::MemberKicked { member: who.clone() }); + Self::deposit_event(Event::MemberKicked { member: who }); if !had_replacement { Self::do_phragmen(); @@ -782,7 +782,7 @@ impl Pallet { })?; let remaining_member_ids_sorted = - Self::members().into_iter().map(|x| x.who.clone()).collect::>(); + Self::members().into_iter().map(|x| x.who).collect::>(); let outgoing = &[who.clone()]; let maybe_current_prime = T::ChangeMembers::get_prime(); let return_value = match maybe_replacement { @@ -861,7 +861,7 @@ impl Pallet { /// Reads Members, RunnersUp, Candidates and Voting(who) from database. fn is_defunct_voter(votes: &[T::AccountId]) -> bool { votes.iter().all(|v| { - !Self::is_member(v) && !Self::is_runner_up(v) && !Self::is_candidate(v).is_ok() + !Self::is_member(v) && !Self::is_runner_up(v) && Self::is_candidate(v).is_err() }) } @@ -923,148 +923,156 @@ impl Pallet { let weight_candidates = candidates_and_deposit.len() as u32; let weight_voters = voters_and_votes.len() as u32; let weight_edges = num_edges; - let _ = sp_npos_elections::seq_phragmen( - num_to_elect, - candidate_ids, - voters_and_votes.clone(), - None, - ) - .map(|ElectionResult:: { winners, assignments: _ }| { - // this is already sorted by id. - let old_members_ids_sorted = - >::take().into_iter().map(|m| m.who).collect::>(); - // this one needs a sort by id. - let mut old_runners_up_ids_sorted = - >::take().into_iter().map(|r| r.who).collect::>(); - old_runners_up_ids_sorted.sort(); + let _ = + sp_npos_elections::seq_phragmen(num_to_elect, candidate_ids, voters_and_votes, None) + .map(|ElectionResult:: { winners, assignments: _ }| { + // this is already sorted by id. + let old_members_ids_sorted = >::take() + .into_iter() + .map(|m| m.who) + .collect::>(); + // this one needs a sort by id. + let mut old_runners_up_ids_sorted = >::take() + .into_iter() + .map(|r| r.who) + .collect::>(); + old_runners_up_ids_sorted.sort(); - // filter out those who end up with no backing stake. - let mut new_set_with_stake = winners - .into_iter() - .filter_map(|(m, b)| if b.is_zero() { None } else { Some((m, to_balance(b))) }) - .collect::)>>(); + // filter out those who end up with no backing stake. + let mut new_set_with_stake = winners + .into_iter() + .filter_map( + |(m, b)| if b.is_zero() { None } else { Some((m, to_balance(b))) }, + ) + .collect::)>>(); - // OPTIMIZATION NOTE: we could bail out here if `new_set.len() == 0`. There isn't - // much left to do. Yet, re-arranging the code would require duplicating the - // slashing of exposed candidates, cleaning any previous members, and so on. For - // now, in favor of readability and veracity, we keep it simple. + // OPTIMIZATION NOTE: we could bail out here if `new_set.len() == 0`. There + // isn't much left to do. Yet, re-arranging the code would require duplicating + // the slashing of exposed candidates, cleaning any previous members, and so on. + // For now, in favor of readability and veracity, we keep it simple. - // split new set into winners and runners up. - let split_point = desired_seats.min(new_set_with_stake.len()); - let mut new_members_sorted_by_id = - new_set_with_stake.drain(..split_point).collect::>(); - new_members_sorted_by_id.sort_by(|i, j| i.0.cmp(&j.0)); + // split new set into winners and runners up. + let split_point = desired_seats.min(new_set_with_stake.len()); + let mut new_members_sorted_by_id = + new_set_with_stake.drain(..split_point).collect::>(); + new_members_sorted_by_id.sort_by(|i, j| i.0.cmp(&j.0)); - // all the rest will be runners-up - new_set_with_stake.reverse(); - let new_runners_up_sorted_by_rank = new_set_with_stake; - let mut new_runners_up_ids_sorted = - new_runners_up_sorted_by_rank.iter().map(|(r, _)| r.clone()).collect::>(); - new_runners_up_ids_sorted.sort(); + // all the rest will be runners-up + new_set_with_stake.reverse(); + let new_runners_up_sorted_by_rank = new_set_with_stake; + let mut new_runners_up_ids_sorted = new_runners_up_sorted_by_rank + .iter() + .map(|(r, _)| r.clone()) + .collect::>(); + new_runners_up_ids_sorted.sort(); - // Now we select a prime member using a [Borda - // count](https://en.wikipedia.org/wiki/Borda_count). We weigh everyone's vote for - // that new member by a multiplier based on the order of the votes. i.e. the first - // person a voter votes for gets a 16x multiplier, the next person gets a 15x - // multiplier, an so on... (assuming `MAXIMUM_VOTE` = 16) - let mut prime_votes = new_members_sorted_by_id - .iter() - .map(|c| (&c.0, BalanceOf::::zero())) - .collect::>(); - for (_, stake, votes) in voters_and_stakes.into_iter() { - for (vote_multiplier, who) in votes - .iter() - .enumerate() - .map(|(vote_position, who)| ((MAXIMUM_VOTE - vote_position) as u32, who)) - { - if let Ok(i) = prime_votes.binary_search_by_key(&who, |k| k.0) { - prime_votes[i].1 = prime_votes[i] - .1 - .saturating_add(stake.saturating_mul(vote_multiplier.into())); + // Now we select a prime member using a [Borda + // count](https://en.wikipedia.org/wiki/Borda_count). We weigh everyone's vote for + // that new member by a multiplier based on the order of the votes. i.e. the + // first person a voter votes for gets a 16x multiplier, the next person gets a + // 15x multiplier, an so on... (assuming `MAXIMUM_VOTE` = 16) + let mut prime_votes = new_members_sorted_by_id + .iter() + .map(|c| (&c.0, BalanceOf::::zero())) + .collect::>(); + for (_, stake, votes) in voters_and_stakes.into_iter() { + for (vote_multiplier, who) in + votes.iter().enumerate().map(|(vote_position, who)| { + ((MAXIMUM_VOTE - vote_position) as u32, who) + }) { + if let Ok(i) = prime_votes.binary_search_by_key(&who, |k| k.0) { + prime_votes[i].1 = prime_votes[i] + .1 + .saturating_add(stake.saturating_mul(vote_multiplier.into())); + } + } } - } - } - // We then select the new member with the highest weighted stake. In the case of a tie, - // the last person in the list with the tied score is selected. This is the person with - // the "highest" account id based on the sort above. - let prime = prime_votes.into_iter().max_by_key(|x| x.1).map(|x| x.0.clone()); + // We then select the new member with the highest weighted stake. In the case of + // a tie, the last person in the list with the tied score is selected. This is + // the person with the "highest" account id based on the sort above. + let prime = prime_votes.into_iter().max_by_key(|x| x.1).map(|x| x.0.clone()); - // new_members_sorted_by_id is sorted by account id. - let new_members_ids_sorted = new_members_sorted_by_id - .iter() - .map(|(m, _)| m.clone()) - .collect::>(); + // new_members_sorted_by_id is sorted by account id. + let new_members_ids_sorted = new_members_sorted_by_id + .iter() + .map(|(m, _)| m.clone()) + .collect::>(); - // report member changes. We compute diff because we need the outgoing list. - let (incoming, outgoing) = T::ChangeMembers::compute_members_diff_sorted( - &new_members_ids_sorted, - &old_members_ids_sorted, - ); - T::ChangeMembers::change_members_sorted(&incoming, &outgoing, &new_members_ids_sorted); - T::ChangeMembers::set_prime(prime); + // report member changes. We compute diff because we need the outgoing list. + let (incoming, outgoing) = T::ChangeMembers::compute_members_diff_sorted( + &new_members_ids_sorted, + &old_members_ids_sorted, + ); + T::ChangeMembers::change_members_sorted( + &incoming, + &outgoing, + &new_members_ids_sorted, + ); + T::ChangeMembers::set_prime(prime); - // All candidates/members/runners-up who are no longer retaining a position as a - // seat holder will lose their bond. - candidates_and_deposit.iter().for_each(|(c, d)| { - if new_members_ids_sorted.binary_search(c).is_err() && - new_runners_up_ids_sorted.binary_search(c).is_err() - { - let (imbalance, _) = T::Currency::slash_reserved(c, *d); - T::LoserCandidate::on_unbalanced(imbalance); - Self::deposit_event(Event::CandidateSlashed { - candidate: c.clone(), - amount: *d, + // All candidates/members/runners-up who are no longer retaining a position as a + // seat holder will lose their bond. + candidates_and_deposit.iter().for_each(|(c, d)| { + if new_members_ids_sorted.binary_search(c).is_err() && + new_runners_up_ids_sorted.binary_search(c).is_err() + { + let (imbalance, _) = T::Currency::slash_reserved(c, *d); + T::LoserCandidate::on_unbalanced(imbalance); + Self::deposit_event(Event::CandidateSlashed { + candidate: c.clone(), + amount: *d, + }); + } }); - } - }); - // write final values to storage. - let deposit_of_candidate = |x: &T::AccountId| -> BalanceOf { - // defensive-only. This closure is used against the new members and new runners-up, - // both of which are phragmen winners and thus must have deposit. - candidates_and_deposit - .iter() - .find_map(|(c, d)| if c == x { Some(*d) } else { None }) - .defensive_unwrap_or_default() - }; - // fetch deposits from the one recorded one. This will make sure that a candidate who - // submitted candidacy before a change to candidacy deposit will have the correct amount - // recorded. - >::put( - new_members_sorted_by_id - .iter() - .map(|(who, stake)| SeatHolder { - deposit: deposit_of_candidate(&who), - who: who.clone(), - stake: stake.clone(), - }) - .collect::>(), - ); - >::put( - new_runners_up_sorted_by_rank - .into_iter() - .map(|(who, stake)| SeatHolder { - deposit: deposit_of_candidate(&who), - who, - stake, - }) - .collect::>(), - ); + // write final values to storage. + let deposit_of_candidate = |x: &T::AccountId| -> BalanceOf { + // defensive-only. This closure is used against the new members and new + // runners-up, both of which are phragmen winners and thus must have + // deposit. + candidates_and_deposit + .iter() + .find_map(|(c, d)| if c == x { Some(*d) } else { None }) + .defensive_unwrap_or_default() + }; + // fetch deposits from the one recorded one. This will make sure that a + // candidate who submitted candidacy before a change to candidacy deposit will + // have the correct amount recorded. + >::put( + new_members_sorted_by_id + .iter() + .map(|(who, stake)| SeatHolder { + deposit: deposit_of_candidate(who), + who: who.clone(), + stake: *stake, + }) + .collect::>(), + ); + >::put( + new_runners_up_sorted_by_rank + .into_iter() + .map(|(who, stake)| SeatHolder { + deposit: deposit_of_candidate(&who), + who, + stake, + }) + .collect::>(), + ); - // clean candidates. - >::kill(); + // clean candidates. + >::kill(); - Self::deposit_event(Event::NewTerm { new_members: new_members_sorted_by_id }); - >::mutate(|v| *v += 1); - }) - .map_err(|e| { - log::error!( - target: "runtime::elections-phragmen", - "Failed to run election [{:?}].", - e, - ); - Self::deposit_event(Event::ElectionError); - }); + Self::deposit_event(Event::NewTerm { new_members: new_members_sorted_by_id }); + >::mutate(|v| *v += 1); + }) + .map_err(|e| { + log::error!( + target: "runtime::elections-phragmen", + "Failed to run election [{:?}].", + e, + ); + Self::deposit_event(Event::ElectionError); + }); T::WeightInfo::election_phragmen(weight_candidates, weight_voters, weight_edges) } diff --git a/substrate/frame/elections-phragmen/src/migrations/v5.rs b/substrate/frame/elections-phragmen/src/migrations/v5.rs index 1898668cd0..a9fb018ba0 100644 --- a/substrate/frame/elections-phragmen/src/migrations/v5.rs +++ b/substrate/frame/elections-phragmen/src/migrations/v5.rs @@ -12,7 +12,7 @@ pub fn migrate(to_migrate: Vec) -> Weight { for who in to_migrate.iter() { if let Ok(mut voter) = Voting::::try_get(who) { - let free_balance = T::Currency::free_balance(&who); + let free_balance = T::Currency::free_balance(who); weight = weight.saturating_add(T::DbWeight::get().reads(2)); @@ -21,7 +21,7 @@ pub fn migrate(to_migrate: Vec) -> Weight { Voting::::insert(&who, voter); let pallet_id = T::PalletId::get(); - T::Currency::set_lock(pallet_id, &who, free_balance, WithdrawReasons::all()); + T::Currency::set_lock(pallet_id, who, free_balance, WithdrawReasons::all()); weight = weight.saturating_add(T::DbWeight::get().writes(2)); } @@ -38,7 +38,7 @@ pub fn pre_migrate_fn(to_migrate: Vec) -> Box::try_get(who) { - let free_balance = T::Currency::free_balance(&who); + let free_balance = T::Currency::free_balance(who); if voter.stake > free_balance { // all good diff --git a/substrate/frame/examples/basic/src/benchmarking.rs b/substrate/frame/examples/basic/src/benchmarking.rs index b823ccd072..d7b933577e 100644 --- a/substrate/frame/examples/basic/src/benchmarking.rs +++ b/substrate/frame/examples/basic/src/benchmarking.rs @@ -63,7 +63,7 @@ benchmarks! { } }: { // The benchmark execution phase could also be a closure with custom code - m.sort(); + m.sort_unstable(); } // This line generates test cases for benchmarking, and could be run by: diff --git a/substrate/frame/examples/basic/src/lib.rs b/substrate/frame/examples/basic/src/lib.rs index 56e8db6936..f8acc19623 100644 --- a/substrate/frame/examples/basic/src/lib.rs +++ b/substrate/frame/examples/basic/src/lib.rs @@ -758,8 +758,8 @@ where Some(Call::set_dummy { .. }) => { sp_runtime::print("set_dummy was received."); - let mut valid_tx = ValidTransaction::default(); - valid_tx.priority = Bounded::max_value(); + let valid_tx = + ValidTransaction { priority: Bounded::max_value(), ..Default::default() }; Ok(valid_tx) }, _ => Ok(Default::default()), diff --git a/substrate/frame/examples/offchain-worker/src/lib.rs b/substrate/frame/examples/offchain-worker/src/lib.rs index 3cf718217b..b403110515 100644 --- a/substrate/frame/examples/offchain-worker/src/lib.rs +++ b/substrate/frame/examples/offchain-worker/src/lib.rs @@ -446,7 +446,7 @@ impl Pallet { if !signer.can_sign() { return Err( "No local accounts available. Consider adding one via `author_insertKey` RPC.", - )? + ) } // Make an external HTTP request to fetch the current price. // Note this call will block until response is received. @@ -640,7 +640,7 @@ impl Pallet { _ => return None, }; - let exp = price.fraction_length.checked_sub(2).unwrap_or(0); + let exp = price.fraction_length.saturating_sub(2); Some(price.integer as u32 * 100 + (price.fraction / 10_u64.pow(exp)) as u32) } diff --git a/substrate/frame/executive/src/lib.rs b/substrate/frame/executive/src/lib.rs index 68b5e910ed..f1e7485d74 100644 --- a/substrate/frame/executive/src/lib.rs +++ b/substrate/frame/executive/src/lib.rs @@ -245,7 +245,7 @@ where let new_header = >::finalize(); let items_zip = header.digest().logs().iter().zip(new_header.digest().logs().iter()); for (header_item, computed_item) in items_zip { - header_item.check_equal(&computed_item); + header_item.check_equal(computed_item); assert!(header_item == computed_item, "Digest item must match that calculated."); } @@ -275,7 +275,7 @@ where pub fn initialize_block(header: &System::Header) { sp_io::init_tracing(); sp_tracing::enter_span!(sp_tracing::Level::TRACE, "init_block"); - let digests = Self::extract_pre_digest(&header); + let digests = Self::extract_pre_digest(header); Self::initialize_block_impl(header.number(), header.parent_hash(), &digests); } @@ -338,7 +338,7 @@ where let header = block.header(); // Check that `parent_hash` is correct. - let n = header.number().clone(); + let n = *header.number(); assert!( n > System::BlockNumber::zero() && >::block_hash(n - System::BlockNumber::one()) == @@ -478,13 +478,13 @@ where ); let items_zip = header.digest().logs().iter().zip(new_header.digest().logs().iter()); for (header_item, computed_item) in items_zip { - header_item.check_equal(&computed_item); + header_item.check_equal(computed_item); assert!(header_item == computed_item, "Digest item must match that calculated."); } // check storage root. let storage_root = new_header.state_root(); - header.state_root().check_equal(&storage_root); + header.state_root().check_equal(storage_root); assert!(header.state_root() == storage_root, "Storage root must match that calculated."); assert!( diff --git a/substrate/frame/gilt/src/lib.rs b/substrate/frame/gilt/src/lib.rs index 8956e04857..59522f9a10 100644 --- a/substrate/frame/gilt/src/lib.rs +++ b/substrate/frame/gilt/src/lib.rs @@ -399,7 +399,7 @@ pub mod pallet { qs[queue_index].0 += net.0; qs[queue_index].1 = qs[queue_index].1.saturating_add(net.1); }); - Self::deposit_event(Event::BidPlaced { who: who.clone(), amount, duration }); + Self::deposit_event(Event::BidPlaced { who, amount, duration }); Ok(().into()) } diff --git a/substrate/frame/grandpa/src/lib.rs b/substrate/frame/grandpa/src/lib.rs index 318f2f40ea..75244c72cf 100644 --- a/substrate/frame/grandpa/src/lib.rs +++ b/substrate/frame/grandpa/src/lib.rs @@ -77,7 +77,7 @@ const STORAGE_VERSION: StorageVersion = StorageVersion::new(4); #[frame_support::pallet] pub mod pallet { use super::*; - use frame_support::pallet_prelude::*; + use frame_support::{dispatch::DispatchResult, pallet_prelude::*}; use frame_system::pallet_prelude::*; #[pallet::pallet] @@ -244,10 +244,11 @@ pub mod pallet { origin: OriginFor, delay: T::BlockNumber, best_finalized_block_number: T::BlockNumber, - ) -> DispatchResultWithPostInfo { + ) -> DispatchResult { ensure_root(origin)?; - Ok(Self::on_stalled(delay, best_finalized_block_number).into()) + Self::on_stalled(delay, best_finalized_block_number); + Ok(()) } } @@ -423,7 +424,7 @@ impl Pallet { Ok(()) } else { - Err(Error::::PauseFailed)? + Err(Error::::PauseFailed.into()) } } @@ -435,7 +436,7 @@ impl Pallet { Ok(()) } else { - Err(Error::::ResumeFailed)? + Err(Error::::ResumeFailed.into()) } } @@ -461,9 +462,9 @@ impl Pallet { if !>::exists() { let scheduled_at = >::block_number(); - if let Some(_) = forced { + if forced.is_some() { if Self::next_forced().map_or(false, |next| next > scheduled_at) { - Err(Error::::TooSoon)? + return Err(Error::::TooSoon.into()) } // only allow the next forced change when twice the window has passed since @@ -488,7 +489,7 @@ impl Pallet { Ok(()) } else { - Err(Error::::ChangePending)? + Err(Error::::ChangePending.into()) } } @@ -544,14 +545,14 @@ impl Pallet { let previous_set_id_session_index = if set_id == 0 { None } else { - let session_index = Self::session_for_set(set_id - 1) - .ok_or_else(|| Error::::InvalidEquivocationProof)?; + let session_index = + Self::session_for_set(set_id - 1).ok_or(Error::::InvalidEquivocationProof)?; Some(session_index) }; let set_id_session_index = - Self::session_for_set(set_id).ok_or_else(|| Error::::InvalidEquivocationProof)?; + Self::session_for_set(set_id).ok_or(Error::::InvalidEquivocationProof)?; // check that the session id for the membership proof is within the // bounds of the set id reported in the equivocation. diff --git a/substrate/frame/identity/src/benchmarking.rs b/substrate/frame/identity/src/benchmarking.rs index 2145779ecf..b225db4edf 100644 --- a/substrate/frame/identity/src/benchmarking.rs +++ b/substrate/frame/identity/src/benchmarking.rs @@ -39,11 +39,7 @@ fn add_registrars(r: u32) -> Result<(), &'static str> { let registrar: T::AccountId = account("registrar", i, SEED); let _ = T::Currency::make_free_balance_be(®istrar, BalanceOf::::max_value()); Identity::::add_registrar(RawOrigin::Root.into(), registrar.clone())?; - Identity::::set_fee( - RawOrigin::Signed(registrar.clone()).into(), - i.into(), - 10u32.into(), - )?; + Identity::::set_fee(RawOrigin::Signed(registrar.clone()).into(), i, 10u32.into())?; let fields = IdentityFields( IdentityField::Display | @@ -52,7 +48,7 @@ fn add_registrars(r: u32) -> Result<(), &'static str> { IdentityField::PgpFingerprint | IdentityField::Image | IdentityField::Twitter, ); - Identity::::set_fields(RawOrigin::Signed(registrar.clone()).into(), i.into(), fields)?; + Identity::::set_fields(RawOrigin::Signed(registrar.clone()).into(), i, fields)?; } assert_eq!(Registrars::::get().len(), r as usize); @@ -75,9 +71,9 @@ fn create_sub_accounts( } // Set identity so `set_subs` does not fail. - let _ = T::Currency::make_free_balance_be(&who, BalanceOf::::max_value() / 2u32.into()); + let _ = T::Currency::make_free_balance_be(who, BalanceOf::::max_value() / 2u32.into()); let info = create_identity_info::(1); - Identity::::set_identity(who_origin.clone().into(), Box::new(info))?; + Identity::::set_identity(who_origin.into(), Box::new(info))?; Ok(subs) } @@ -101,7 +97,7 @@ fn add_sub_accounts( fn create_identity_info(num_fields: u32) -> IdentityInfo { let data = Data::Raw(vec![0; 32].try_into().unwrap()); - let info = IdentityInfo { + IdentityInfo { additional: vec![(data.clone(), data.clone()); num_fields as usize].try_into().unwrap(), display: data.clone(), legal: data.clone(), @@ -110,10 +106,8 @@ fn create_identity_info(num_fields: u32) -> IdentityInfo::add_registrar(RawOrigin::Root.into(), caller.clone())?; let registrars = Registrars::::get(); - ensure!(registrars[r as usize].as_ref().unwrap().account == caller.clone(), "id not set."); + ensure!(registrars[r as usize].as_ref().unwrap().account == caller, "id not set."); }: _(RawOrigin::Signed(caller), r, account("new", 0, SEED)) verify { let registrars = Registrars::::get(); @@ -325,7 +319,7 @@ benchmarks! { }; Identity::::add_registrar(RawOrigin::Root.into(), caller.clone())?; - Identity::::request_judgement(user_origin.clone(), r, 10u32.into())?; + Identity::::request_judgement(user_origin, r, 10u32.into())?; }: _(RawOrigin::Signed(caller), r, user_lookup, Judgement::Reasonable) verify { assert_last_event::(Event::::JudgementGiven { target: user, registrar_index: r }.into()) diff --git a/substrate/frame/identity/src/lib.rs b/substrate/frame/identity/src/lib.rs index 904b71654b..46f8476069 100644 --- a/substrate/frame/identity/src/lib.rs +++ b/substrate/frame/identity/src/lib.rs @@ -324,8 +324,8 @@ pub mod pallet { /// - One event. /// # #[pallet::weight( T::WeightInfo::set_identity( - T::MaxRegistrars::get().into(), // R - T::MaxAdditionalFields::get().into(), // X + T::MaxRegistrars::get(), // R + T::MaxAdditionalFields::get(), // X ))] pub fn set_identity( origin: OriginFor, @@ -416,7 +416,7 @@ pub mod pallet { let new_deposit = T::SubAccountDeposit::get() * >::from(subs.len() as u32); let not_other_sub = - subs.iter().filter_map(|i| SuperOf::::get(&i.0)).all(|i| &i.0 == &sender); + subs.iter().filter_map(|i| SuperOf::::get(&i.0)).all(|i| i.0 == sender); ensure!(not_other_sub, Error::::AlreadyClaimed); if old_deposit < new_deposit { @@ -470,9 +470,9 @@ pub mod pallet { /// - One event. /// # #[pallet::weight(T::WeightInfo::clear_identity( - T::MaxRegistrars::get().into(), // R - T::MaxSubAccounts::get().into(), // S - T::MaxAdditionalFields::get().into(), // X + T::MaxRegistrars::get(), // R + T::MaxSubAccounts::get(), // S + T::MaxAdditionalFields::get(), // X ))] pub fn clear_identity(origin: OriginFor) -> DispatchResultWithPostInfo { let sender = ensure_signed(origin)?; @@ -484,7 +484,7 @@ pub mod pallet { >::remove(sub); } - let err_amount = T::Currency::unreserve(&sender, deposit.clone()); + let err_amount = T::Currency::unreserve(&sender, deposit); debug_assert!(err_amount.is_zero()); Self::deposit_event(Event::IdentityCleared { who: sender, deposit }); @@ -521,8 +521,8 @@ pub mod pallet { /// - One event. /// # #[pallet::weight(T::WeightInfo::request_judgement( - T::MaxRegistrars::get().into(), // R - T::MaxAdditionalFields::get().into(), // X + T::MaxRegistrars::get(), // R + T::MaxAdditionalFields::get(), // X ))] pub fn request_judgement( origin: OriginFor, @@ -542,7 +542,7 @@ pub mod pallet { match id.judgements.binary_search_by_key(®_index, |x| x.0) { Ok(i) => if id.judgements[i].1.is_sticky() { - Err(Error::::StickyJudgement)? + return Err(Error::::StickyJudgement.into()) } else { id.judgements[i] = item }, @@ -583,8 +583,8 @@ pub mod pallet { /// - One event /// # #[pallet::weight(T::WeightInfo::cancel_request( - T::MaxRegistrars::get().into(), // R - T::MaxAdditionalFields::get().into(), // X + T::MaxRegistrars::get(), // R + T::MaxAdditionalFields::get(), // X ))] pub fn cancel_request( origin: OriginFor, @@ -600,7 +600,7 @@ pub mod pallet { let fee = if let Judgement::FeePaid(fee) = id.judgements.remove(pos).1 { fee } else { - Err(Error::::JudgementGiven)? + return Err(Error::::JudgementGiven.into()) }; let err_amount = T::Currency::unreserve(&sender, fee); @@ -754,8 +754,8 @@ pub mod pallet { /// - One event. /// # #[pallet::weight(T::WeightInfo::provide_judgement( - T::MaxRegistrars::get().into(), // R - T::MaxAdditionalFields::get().into(), // X + T::MaxRegistrars::get(), // R + T::MaxAdditionalFields::get(), // X ))] pub fn provide_judgement( origin: OriginFor, @@ -821,9 +821,9 @@ pub mod pallet { /// - One event. /// # #[pallet::weight(T::WeightInfo::kill_identity( - T::MaxRegistrars::get().into(), // R - T::MaxSubAccounts::get().into(), // S - T::MaxAdditionalFields::get().into(), // X + T::MaxRegistrars::get(), // R + T::MaxSubAccounts::get(), // S + T::MaxAdditionalFields::get(), // X ))] pub fn kill_identity( origin: OriginFor, diff --git a/substrate/frame/identity/src/types.rs b/substrate/frame/identity/src/types.rs index cb8091fe18..b1f15da3b1 100644 --- a/substrate/frame/identity/src/types.rs +++ b/substrate/frame/identity/src/types.rs @@ -217,20 +217,14 @@ impl bool { - match self { - Judgement::FeePaid(_) => true, - _ => false, - } + matches!(self, Judgement::FeePaid(_)) } /// Returns `true` if this judgement is one that should not be generally be replaced outside /// of specialized handlers. Examples include "malicious" judgements and deposit-holding /// judgements. pub(crate) fn is_sticky(&self) -> bool { - match self { - Judgement::FeePaid(_) | Judgement::Erroneous => true, - _ => false, - } + matches!(self, Judgement::FeePaid(_) | Judgement::Erroneous) } } diff --git a/substrate/frame/im-online/src/lib.rs b/substrate/frame/im-online/src/lib.rs index 5ef515db0b..05b7618b28 100644 --- a/substrate/frame/im-online/src/lib.rs +++ b/substrate/frame/im-online/src/lib.rs @@ -508,9 +508,9 @@ pub mod pallet { Ok(()) } else if exists { - Err(Error::::DuplicatedHeartbeat)? + Err(Error::::DuplicatedHeartbeat.into()) } else { - Err(Error::::InvalidKey)? + Err(Error::::InvalidKey.into()) } } } @@ -573,7 +573,7 @@ pub mod pallet { // check signature (this is expensive so we do it last). let signature_valid = heartbeat.using_encoded(|encoded_heartbeat| { - authority_id.verify(&encoded_heartbeat, &signature) + authority_id.verify(&encoded_heartbeat, signature) }); if !signature_valid { diff --git a/substrate/frame/indices/src/lib.rs b/substrate/frame/indices/src/lib.rs index db983a802c..ddc03c94b1 100644 --- a/substrate/frame/indices/src/lib.rs +++ b/substrate/frame/indices/src/lib.rs @@ -142,7 +142,7 @@ pub mod pallet { Accounts::::try_mutate(index, |maybe_value| -> DispatchResult { let (account, amount, perm) = maybe_value.take().ok_or(Error::::NotAssigned)?; ensure!(!perm, Error::::Permanent); - ensure!(&account == &who, Error::::NotOwner); + ensure!(account == who, Error::::NotOwner); let lost = T::Currency::repatriate_reserved(&who, &new, amount, Reserved)?; *maybe_value = Some((new.clone(), amount.saturating_sub(lost), false)); Ok(()) @@ -176,7 +176,7 @@ pub mod pallet { Accounts::::try_mutate(index, |maybe_value| -> DispatchResult { let (account, amount, perm) = maybe_value.take().ok_or(Error::::NotAssigned)?; ensure!(!perm, Error::::Permanent); - ensure!(&account == &who, Error::::NotOwner); + ensure!(account == who, Error::::NotOwner); T::Currency::unreserve(&who, amount); Ok(()) })?; @@ -249,7 +249,7 @@ pub mod pallet { Accounts::::try_mutate(index, |maybe_value| -> DispatchResult { let (account, amount, perm) = maybe_value.take().ok_or(Error::::NotAssigned)?; ensure!(!perm, Error::::Permanent); - ensure!(&account == &who, Error::::NotOwner); + ensure!(account == who, Error::::NotOwner); T::Currency::slash_reserved(&who, amount); *maybe_value = Some((account, Zero::zero(), true)); Ok(()) diff --git a/substrate/frame/lottery/src/lib.rs b/substrate/frame/lottery/src/lib.rs index c9a508372c..bc96a029a4 100644 --- a/substrate/frame/lottery/src/lib.rs +++ b/substrate/frame/lottery/src/lib.rs @@ -108,7 +108,7 @@ impl ValidateCall for () { impl ValidateCall for Pallet { fn validate_call(call: &::Call) -> bool { let valid_calls = CallIndices::::get(); - let call_index = match Self::call_to_index(&call) { + let call_index = match Self::call_to_index(call) { Ok(call_index) => call_index, Err(_) => return false, }; @@ -278,7 +278,7 @@ pub mod pallet { // but is not used if it is not relevant. } } - return T::DbWeight::get().reads(1) + T::DbWeight::get().reads(1) }) } } @@ -418,9 +418,9 @@ impl Pallet { fn call_to_index(call: &::Call) -> Result { let encoded_call = call.encode(); if encoded_call.len() < 2 { - Err(Error::::EncodingFailed)? + return Err(Error::::EncodingFailed.into()) } - return Ok((encoded_call[0], encoded_call[1])) + Ok((encoded_call[0], encoded_call[1])) } /// Logic for buying a ticket. diff --git a/substrate/frame/membership/src/lib.rs b/substrate/frame/membership/src/lib.rs index 5a9c0a461c..ad6273e78f 100644 --- a/substrate/frame/membership/src/lib.rs +++ b/substrate/frame/membership/src/lib.rs @@ -377,7 +377,7 @@ mod benchmark { let m in 1 .. T::MaxMembers::get(); let members = (0..m).map(|i| account("member", i, SEED)).collect::>(); - set_members::(members.clone(), None); + set_members::(members, None); let new_member = account::("add", m, SEED); }: { assert_ok!(>::add_member(T::AddOrigin::successful_origin(), new_member.clone())); diff --git a/substrate/frame/multisig/src/benchmarking.rs b/substrate/frame/multisig/src/benchmarking.rs index 43abb349b7..8201426f53 100644 --- a/substrate/frame/multisig/src/benchmarking.rs +++ b/substrate/frame/multisig/src/benchmarking.rs @@ -45,7 +45,7 @@ fn setup_multi( let call: ::Call = frame_system::Call::::remark { remark: vec![0; z as usize] }.into(); let call_data = OpaqueCall::::from_encoded(call.encode()); - return Ok((signatories, call_data)) + Ok((signatories, call_data)) } benchmarks! { @@ -74,7 +74,7 @@ benchmarks! { // Transaction Length let z in 0 .. 10_000; let (mut signatories, call) = setup_multi::(s, z)?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; // Whitelist caller account from further DB operations. @@ -92,7 +92,7 @@ benchmarks! { // Transaction Length let z in 0 .. 10_000; let (mut signatories, call) = setup_multi::(s, z)?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); @@ -111,7 +111,7 @@ benchmarks! { // Transaction Length let z in 0 .. 10_000; let (mut signatories, call) = setup_multi::(s, z)?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let mut signatories2 = signatories.clone(); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; @@ -136,7 +136,7 @@ benchmarks! { // Transaction Length let z in 0 .. 10_000; let (mut signatories, call) = setup_multi::(s, z)?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let mut signatories2 = signatories.clone(); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; @@ -162,7 +162,7 @@ benchmarks! { // Transaction Length let z in 0 .. 10_000; let (mut signatories, call) = setup_multi::(s, z)?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let mut signatories2 = signatories.clone(); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; @@ -195,7 +195,7 @@ benchmarks! { let (mut signatories, call) = setup_multi::(s, z)?; let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller); frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); @@ -214,16 +214,16 @@ benchmarks! { let mut signatories2 = signatories.clone(); let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); // before the call, get the timepoint let timepoint = Multisig::::timepoint(); // Create the multi Multisig::::as_multi( - RawOrigin::Signed(caller.clone()).into(), + RawOrigin::Signed(caller).into(), s as u16, signatories, None, - call.clone(), + call, false, 0 )?; @@ -247,7 +247,7 @@ benchmarks! { let mut signatories2 = signatories.clone(); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); // before the call, get the timepoint let timepoint = Multisig::::timepoint(); // Create the multi @@ -284,11 +284,11 @@ benchmarks! { let (mut signatories, call) = setup_multi::(s, z)?; let multi_account_id = Multisig::::multi_account_id(&signatories, s.try_into().unwrap()); let caller = signatories.pop().ok_or("signatories should have len 2 or more")?; - let call_hash = blake2_256(&call.encoded()); + let call_hash = blake2_256(call.encoded()); let timepoint = Multisig::::timepoint(); // Create the multi let o = RawOrigin::Signed(caller.clone()).into(); - Multisig::::as_multi(o, s as u16, signatories.clone(), None, call.clone(), true, 0)?; + Multisig::::as_multi(o, s as u16, signatories.clone(), None, call, true, 0)?; assert!(Multisigs::::contains_key(&multi_account_id, call_hash)); assert!(Calls::::contains_key(call_hash)); // Whitelist caller account from further DB operations. diff --git a/substrate/frame/multisig/src/lib.rs b/substrate/frame/multisig/src/lib.rs index cd59ea8817..d4ea041e58 100644 --- a/substrate/frame/multisig/src/lib.rs +++ b/substrate/frame/multisig/src/lib.rs @@ -295,8 +295,7 @@ pub mod pallet { let weight_used = T::WeightInfo::as_multi_threshold_1(call_len as u32) .saturating_add(actual_weight); let post_info = Some(weight_used).into(); - let error = err.error.into(); - DispatchErrorWithPostInfo { post_info, error } + DispatchErrorWithPostInfo { post_info, error: err.error } }, None => err, }) diff --git a/substrate/frame/nicks/src/lib.rs b/substrate/frame/nicks/src/lib.rs index 632ff7b0a8..5da06a24df 100644 --- a/substrate/frame/nicks/src/lib.rs +++ b/substrate/frame/nicks/src/lib.rs @@ -147,7 +147,7 @@ pub mod pallet { deposit } else { let deposit = T::ReservationFee::get(); - T::Currency::reserve(&sender, deposit.clone())?; + T::Currency::reserve(&sender, deposit)?; Self::deposit_event(Event::::NameSet { who: sender.clone() }); deposit }; @@ -172,7 +172,7 @@ pub mod pallet { let deposit = >::take(&sender).ok_or(Error::::Unnamed)?.1; - let err_amount = T::Currency::unreserve(&sender, deposit.clone()); + let err_amount = T::Currency::unreserve(&sender, deposit); debug_assert!(err_amount.is_zero()); Self::deposit_event(Event::::NameCleared { who: sender, deposit }); @@ -204,7 +204,7 @@ pub mod pallet { // Grab their deposit (and check that they have one). let deposit = >::take(&target).ok_or(Error::::Unnamed)?.1; // Slash their deposit from them. - T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit.clone()).0); + T::Slashed::on_unbalanced(T::Currency::slash_reserved(&target, deposit).0); Self::deposit_event(Event::::NameKilled { target, deposit }); Ok(()) diff --git a/substrate/frame/offences/benchmarking/src/lib.rs b/substrate/frame/offences/benchmarking/src/lib.rs index 8688090206..98c6390964 100644 --- a/substrate/frame/offences/benchmarking/src/lib.rs +++ b/substrate/frame/offences/benchmarking/src/lib.rs @@ -101,15 +101,14 @@ fn create_offender(n: u32, nominators: u32) -> Result, &' let controller: T::AccountId = account("controller", n, SEED); let controller_lookup: LookupSourceOf = T::Lookup::unlookup(controller.clone()); let reward_destination = RewardDestination::Staked; - let raw_amount = bond_amount::(); + let amount = bond_amount::(); // add twice as much balance to prevent the account from being killed. - let free_amount = raw_amount.saturating_mul(2u32.into()); + let free_amount = amount.saturating_mul(2u32.into()); T::Currency::make_free_balance_be(&stash, free_amount); - let amount: BalanceOf = raw_amount.into(); Staking::::bond( RawOrigin::Signed(stash.clone()).into(), controller_lookup.clone(), - amount.clone(), + amount, reward_destination.clone(), )?; @@ -127,12 +126,12 @@ fn create_offender(n: u32, nominators: u32) -> Result, &' account("nominator controller", n * MAX_NOMINATORS + i, SEED); let nominator_controller_lookup: LookupSourceOf = T::Lookup::unlookup(nominator_controller.clone()); - T::Currency::make_free_balance_be(&nominator_stash, free_amount.into()); + T::Currency::make_free_balance_be(&nominator_stash, free_amount); Staking::::bond( RawOrigin::Signed(nominator_stash.clone()).into(), nominator_controller_lookup.clone(), - amount.clone(), + amount, reward_destination.clone(), )?; @@ -143,14 +142,13 @@ fn create_offender(n: u32, nominators: u32) -> Result, &' )?; individual_exposures - .push(IndividualExposure { who: nominator_stash.clone(), value: amount.clone() }); + .push(IndividualExposure { who: nominator_stash.clone(), value: amount }); nominator_stashes.push(nominator_stash.clone()); } - let exposure = - Exposure { total: amount.clone() * n.into(), own: amount, others: individual_exposures }; + let exposure = Exposure { total: amount * n.into(), own: amount, others: individual_exposures }; let current_era = 0u32; - Staking::::add_era_stakers(current_era.into(), stash.clone().into(), exposure); + Staking::::add_era_stakers(current_era, stash.clone(), exposure); Ok(Offender { controller, stash, nominator_stashes }) } @@ -327,13 +325,13 @@ benchmarks! { .flat_map(|offender| { let nom_slashes = offender.nominator_stashes.into_iter().flat_map(|nom| { balance_slash(nom.clone()).map(Into::into) - .chain(slash(nom.clone()).map(Into::into)) - }).collect::>(); + .chain(slash(nom).map(Into::into)) + }); let mut events = chill(offender.stash.clone()).map(Into::into) .chain(balance_slash(offender.stash.clone()).map(Into::into)) - .chain(slash(offender.stash.clone()).map(Into::into)) - .chain(nom_slashes.into_iter()) + .chain(slash(offender.stash).map(Into::into)) + .chain(nom_slashes) .collect::>(); // the first deposit creates endowed events, see `endowed_reward_events` @@ -341,10 +339,10 @@ benchmarks! { first = false; let mut reward_events = reporters.clone().into_iter() .flat_map(|reporter| vec![ - balance_deposit(reporter.clone(), reward.into()).into(), + balance_deposit(reporter.clone(), reward).into(), frame_system::Event::::NewAccount { account: reporter.clone() }.into(), ::Event::from( - pallet_balances::Event::::Endowed{account: reporter.clone(), free_balance: reward.into()} + pallet_balances::Event::::Endowed{account: reporter, free_balance: reward.into()} ).into(), ]) .collect::>(); @@ -352,7 +350,7 @@ benchmarks! { events.into_iter() } else { let mut reward_events = reporters.clone().into_iter() - .map(|reporter| balance_deposit(reporter, reward.into()).into()) + .map(|reporter| balance_deposit(reporter, reward).into()) .collect::>(); events.append(&mut reward_events); events.into_iter() diff --git a/substrate/frame/offences/src/lib.rs b/substrate/frame/offences/src/lib.rs index 6119fce776..a6d69e2a5e 100644 --- a/substrate/frame/offences/src/lib.rs +++ b/substrate/frame/offences/src/lib.rs @@ -136,8 +136,7 @@ where // The amount new offenders are slashed let new_fraction = O::slash_fraction(offenders_count, validator_set_count); - let slash_perbill: Vec<_> = - (0..concurrent_offenders.len()).map(|_| new_fraction.clone()).collect(); + let slash_perbill: Vec<_> = (0..concurrent_offenders.len()).map(|_| new_fraction).collect(); T::OnOffenceHandler::on_offence( &concurrent_offenders, @@ -202,7 +201,7 @@ impl Pallet { let concurrent_offenders = storage .concurrent_reports .iter() - .filter_map(|report_id| >::get(report_id)) + .filter_map(>::get) .collect::>(); storage.save(); diff --git a/substrate/frame/offences/src/migration.rs b/substrate/frame/offences/src/migration.rs index 72c24ef7c3..0d6c98b564 100644 --- a/substrate/frame/offences/src/migration.rs +++ b/substrate/frame/offences/src/migration.rs @@ -42,8 +42,8 @@ pub fn remove_deferred_storage() -> Weight { log::info!(target: "runtime::offences", "have {} deferred offences, applying.", deferred.len()); for (offences, perbill, session) in deferred.iter() { let consumed = T::OnOffenceHandler::on_offence( - &offences, - &perbill, + offences, + perbill, *session, DisableStrategy::WhenSlashed, ); diff --git a/substrate/frame/preimage/src/benchmarking.rs b/substrate/frame/preimage/src/benchmarking.rs index 6432610842..e0d7e9614a 100644 --- a/substrate/frame/preimage/src/benchmarking.rs +++ b/substrate/frame/preimage/src/benchmarking.rs @@ -62,7 +62,7 @@ benchmarks! { let caller = funded_account::("caller", 0); whitelist_account!(caller); let (preimage, hash) = sized_preimage_and_hash::(s); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); }: note_preimage(RawOrigin::Signed(caller), preimage) verify { assert!(Preimage::::have_preimage(&hash)); @@ -71,7 +71,7 @@ benchmarks! { note_no_deposit_preimage { let s in 0 .. T::MaxSize::get(); let (preimage, hash) = sized_preimage_and_hash::(s); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); }: note_preimage(T::ManagerOrigin::successful_origin(), preimage) verify { assert!(Preimage::::have_preimage(&hash)); @@ -83,7 +83,7 @@ benchmarks! { whitelist_account!(caller); let (preimage, hash) = preimage_and_hash::(); assert_ok!(Preimage::::note_preimage(RawOrigin::Signed(caller.clone()).into(), preimage)); - }: _(RawOrigin::Signed(caller), hash.clone()) + }: _(RawOrigin::Signed(caller), hash) verify { assert!(!Preimage::::have_preimage(&hash)); } @@ -91,7 +91,7 @@ benchmarks! { unnote_no_deposit_preimage { let (preimage, hash) = preimage_and_hash::(); assert_ok!(Preimage::::note_preimage(T::ManagerOrigin::successful_origin(), preimage)); - }: unnote_preimage(T::ManagerOrigin::successful_origin(), hash.clone()) + }: unnote_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert!(!Preimage::::have_preimage(&hash)); } @@ -124,7 +124,7 @@ benchmarks! { // Cheap request - the preimage is already requested, so just a counter bump. request_requested_preimage { let (_, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); }: request_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(2))); @@ -133,26 +133,26 @@ benchmarks! { // Expensive unrequest - last reference and it's noted, so will destroy the preimage. unrequest_preimage { let (preimage, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); assert_ok!(Preimage::::note_preimage(T::ManagerOrigin::successful_origin(), preimage)); - }: _(T::ManagerOrigin::successful_origin(), hash.clone()) + }: _(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), None); } // Cheap unrequest - last reference, but it's not noted. unrequest_unnoted_preimage { let (_, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); - }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash.clone()) + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); + }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), None); } // Cheap unrequest - not the last reference. unrequest_multi_referenced_preimage { let (_, hash) = preimage_and_hash::(); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); - assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash.clone())); - }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash.clone()) + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); + assert_ok!(Preimage::::request_preimage(T::ManagerOrigin::successful_origin(), hash)); + }: unrequest_preimage(T::ManagerOrigin::successful_origin(), hash) verify { assert_eq!(StatusFor::::get(&hash), Some(RequestStatus::Requested(1))); } diff --git a/substrate/frame/preimage/src/lib.rs b/substrate/frame/preimage/src/lib.rs index a5d8ee28b5..09f6ecd52f 100644 --- a/substrate/frame/preimage/src/lib.rs +++ b/substrate/frame/preimage/src/lib.rs @@ -215,7 +215,8 @@ impl Pallet { // previously requested. This also allows the tx to pay no fee. let was_requested = match (StatusFor::::get(hash), maybe_depositor) { (Some(RequestStatus::Requested(..)), _) => true, - (Some(RequestStatus::Unrequested(..)), _) => Err(Error::::AlreadyNoted)?, + (Some(RequestStatus::Unrequested(..)), _) => + return Err(Error::::AlreadyNoted.into()), (None, None) => { StatusFor::::insert(hash, RequestStatus::Unrequested(None)); false @@ -256,7 +257,7 @@ impl Pallet { }); StatusFor::::insert(hash, RequestStatus::Requested(count)); if count == 1 { - Self::deposit_event(Event::Requested { hash: hash.clone() }); + Self::deposit_event(Event::Requested { hash: *hash }); } } @@ -270,20 +271,17 @@ impl Pallet { ) -> DispatchResult { match StatusFor::::get(hash).ok_or(Error::::NotNoted)? { RequestStatus::Unrequested(Some((owner, deposit))) => { - ensure!( - maybe_check_owner.map_or(true, |c| &c == &owner), - Error::::NotAuthorized - ); + ensure!(maybe_check_owner.map_or(true, |c| c == owner), Error::::NotAuthorized); T::Currency::unreserve(&owner, deposit); }, RequestStatus::Unrequested(None) => { ensure!(maybe_check_owner.is_none(), Error::::NotAuthorized); }, - RequestStatus::Requested(_) => Err(Error::::Requested)?, + RequestStatus::Requested(_) => return Err(Error::::Requested.into()), } StatusFor::::remove(hash); PreimageFor::::remove(hash); - Self::deposit_event(Event::Cleared { hash: hash.clone() }); + Self::deposit_event(Event::Cleared { hash: *hash }); Ok(()) } @@ -298,9 +296,9 @@ impl Pallet { debug_assert!(count == 1, "preimage request counter at zero?"); PreimageFor::::remove(hash); StatusFor::::remove(hash); - Self::deposit_event(Event::Cleared { hash: hash.clone() }); + Self::deposit_event(Event::Cleared { hash: *hash }); }, - RequestStatus::Unrequested(_) => Err(Error::::NotRequested)?, + RequestStatus::Unrequested(_) => return Err(Error::::NotRequested.into()), } Ok(()) } diff --git a/substrate/frame/proxy/src/benchmarking.rs b/substrate/frame/proxy/src/benchmarking.rs index f3098c6ad1..87017290a3 100644 --- a/substrate/frame/proxy/src/benchmarking.rs +++ b/substrate/frame/proxy/src/benchmarking.rs @@ -32,7 +32,7 @@ fn assert_last_event(generic_event: ::Event) { } fn add_proxies(n: u32, maybe_who: Option) -> Result<(), &'static str> { - let caller = maybe_who.unwrap_or_else(|| whitelisted_caller()); + let caller = maybe_who.unwrap_or_else(whitelisted_caller); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); for i in 0..n { Proxy::::add_proxy( @@ -77,7 +77,7 @@ fn add_announcements( benchmarks! { proxy { - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); @@ -91,7 +91,7 @@ benchmarks! { proxy_announced { let a in 0 .. T::MaxPending::get() - 1; - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("anonymous", 0, SEED); let delegate: T::AccountId = account("target", p - 1, SEED); @@ -112,7 +112,7 @@ benchmarks! { remove_announcement { let a in 0 .. T::MaxPending::get() - 1; - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); @@ -133,7 +133,7 @@ benchmarks! { reject_announcement { let a in 0 .. T::MaxPending::get() - 1; - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); @@ -154,7 +154,7 @@ benchmarks! { announce { let a in 0 .. T::MaxPending::get() - 1; - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; // In this case the caller is the "target" proxy let caller: T::AccountId = account("target", p - 1, SEED); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value() / 2u32.into()); @@ -169,11 +169,11 @@ benchmarks! { } add_proxy { - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; let caller: T::AccountId = whitelisted_caller(); }: _( RawOrigin::Signed(caller.clone()), - account("target", T::MaxProxies::get().into(), SEED), + account("target", T::MaxProxies::get(), SEED), T::ProxyType::default(), T::BlockNumber::zero() ) @@ -183,7 +183,7 @@ benchmarks! { } remove_proxy { - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; let caller: T::AccountId = whitelisted_caller(); }: _( RawOrigin::Signed(caller.clone()), @@ -197,7 +197,7 @@ benchmarks! { } remove_proxies { - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; let caller: T::AccountId = whitelisted_caller(); }: _(RawOrigin::Signed(caller.clone())) verify { @@ -206,7 +206,7 @@ benchmarks! { } anonymous { - let p in 1 .. (T::MaxProxies::get() - 1).into() => add_proxies::(p, None)?; + let p in 1 .. (T::MaxProxies::get() - 1) => add_proxies::(p, None)?; let caller: T::AccountId = whitelisted_caller(); }: _( RawOrigin::Signed(caller.clone()), @@ -225,7 +225,7 @@ benchmarks! { } kill_anonymous { - let p in 0 .. (T::MaxProxies::get() - 2).into(); + let p in 0 .. (T::MaxProxies::get() - 2); let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, BalanceOf::::max_value()); diff --git a/substrate/frame/proxy/src/lib.rs b/substrate/frame/proxy/src/lib.rs index 1bab3626fb..9945626efb 100644 --- a/substrate/frame/proxy/src/lib.rs +++ b/substrate/frame/proxy/src/lib.rs @@ -196,7 +196,7 @@ pub mod pallet { /// # #[pallet::weight({ let di = call.get_dispatch_info(); - (T::WeightInfo::proxy(T::MaxProxies::get().into()) + (T::WeightInfo::proxy(T::MaxProxies::get()) .saturating_add(di.weight) // AccountData for inner call origin accountdata. .saturating_add(T::DbWeight::get().reads_writes(1, 1)), @@ -230,7 +230,7 @@ pub mod pallet { /// # /// Weight is a function of the number of proxies the user has (P). /// # - #[pallet::weight(T::WeightInfo::add_proxy(T::MaxProxies::get().into()))] + #[pallet::weight(T::WeightInfo::add_proxy(T::MaxProxies::get()))] pub fn add_proxy( origin: OriginFor, delegate: T::AccountId, @@ -252,7 +252,7 @@ pub mod pallet { /// # /// Weight is a function of the number of proxies the user has (P). /// # - #[pallet::weight(T::WeightInfo::remove_proxy(T::MaxProxies::get().into()))] + #[pallet::weight(T::WeightInfo::remove_proxy(T::MaxProxies::get()))] pub fn remove_proxy( origin: OriginFor, delegate: T::AccountId, @@ -273,7 +273,7 @@ pub mod pallet { /// # /// Weight is a function of the number of proxies the user has (P). /// # - #[pallet::weight(T::WeightInfo::remove_proxies(T::MaxProxies::get().into()))] + #[pallet::weight(T::WeightInfo::remove_proxies(T::MaxProxies::get()))] pub fn remove_proxies(origin: OriginFor) -> DispatchResult { let who = ensure_signed(origin)?; let (_, old_deposit) = Proxies::::take(&who); @@ -305,7 +305,7 @@ pub mod pallet { /// Weight is a function of the number of proxies the user has (P). /// # /// TODO: Might be over counting 1 read - #[pallet::weight(T::WeightInfo::anonymous(T::MaxProxies::get().into()))] + #[pallet::weight(T::WeightInfo::anonymous(T::MaxProxies::get()))] pub fn anonymous( origin: OriginFor, proxy_type: T::ProxyType, @@ -356,7 +356,7 @@ pub mod pallet { /// # /// Weight is a function of the number of proxies the user has (P). /// # - #[pallet::weight(T::WeightInfo::kill_anonymous(T::MaxProxies::get().into()))] + #[pallet::weight(T::WeightInfo::kill_anonymous(T::MaxProxies::get()))] pub fn kill_anonymous( origin: OriginFor, spawner: T::AccountId, @@ -398,7 +398,7 @@ pub mod pallet { /// - A: the number of announcements made. /// - P: the number of proxies the user has. /// # - #[pallet::weight(T::WeightInfo::announce(T::MaxPending::get(), T::MaxProxies::get().into()))] + #[pallet::weight(T::WeightInfo::announce(T::MaxPending::get(), T::MaxProxies::get()))] pub fn announce( origin: OriginFor, real: T::AccountId, @@ -408,12 +408,12 @@ pub mod pallet { Proxies::::get(&real) .0 .into_iter() - .find(|x| &x.delegate == &who) + .find(|x| x.delegate == who) .ok_or(Error::::NotProxy)?; let announcement = Announcement { real: real.clone(), - call_hash: call_hash.clone(), + call_hash, height: system::Pallet::::block_number(), }; @@ -452,9 +452,10 @@ pub mod pallet { /// - A: the number of announcements made. /// - P: the number of proxies the user has. /// # - #[pallet::weight( - T::WeightInfo::remove_announcement(T::MaxPending::get(), T::MaxProxies::get().into()) - )] + #[pallet::weight(T::WeightInfo::remove_announcement( + T::MaxPending::get(), + T::MaxProxies::get() + ))] pub fn remove_announcement( origin: OriginFor, real: T::AccountId, @@ -482,9 +483,10 @@ pub mod pallet { /// - A: the number of announcements made. /// - P: the number of proxies the user has. /// # - #[pallet::weight( - T::WeightInfo::reject_announcement(T::MaxPending::get(), T::MaxProxies::get().into()) - )] + #[pallet::weight(T::WeightInfo::reject_announcement( + T::MaxPending::get(), + T::MaxProxies::get() + ))] pub fn reject_announcement( origin: OriginFor, delegate: T::AccountId, @@ -517,7 +519,7 @@ pub mod pallet { /// # #[pallet::weight({ let di = call.get_dispatch_info(); - (T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get().into()) + (T::WeightInfo::proxy_announced(T::MaxPending::get(), T::MaxProxies::get()) .saturating_add(di.weight) // AccountData for inner call origin accountdata. .saturating_add(T::DbWeight::get().reads_writes(1, 1)), @@ -759,9 +761,9 @@ impl Pallet { let new_deposit = if len == 0 { BalanceOf::::zero() } else { base + factor * (len as u32).into() }; if new_deposit > old_deposit { - T::Currency::reserve(&who, new_deposit - old_deposit)?; + T::Currency::reserve(who, new_deposit - old_deposit)?; } else if new_deposit < old_deposit { - T::Currency::unreserve(&who, old_deposit - new_deposit); + T::Currency::unreserve(who, old_deposit - new_deposit); } Ok(if len == 0 { None } else { Some(new_deposit) }) } @@ -816,7 +818,7 @@ impl Pallet { // has. Some(Call::add_proxy { ref proxy_type, .. }) | Some(Call::remove_proxy { ref proxy_type, .. }) - if !def.proxy_type.is_superset(&proxy_type) => + if !def.proxy_type.is_superset(proxy_type) => false, // Proxy call cannot remove all proxies or kill anonymous proxies unless it has full // permissions. diff --git a/substrate/frame/recovery/src/lib.rs b/substrate/frame/recovery/src/lib.rs index e75c902576..b839d25e32 100644 --- a/substrate/frame/recovery/src/lib.rs +++ b/substrate/frame/recovery/src/lib.rs @@ -388,7 +388,7 @@ pub mod pallet { let who = ensure_signed(origin)?; // Check `who` is allowed to make a call on behalf of `account` let target = Self::proxy(&who).ok_or(Error::::NotAllowed)?; - ensure!(&target == &account, Error::::NotAllowed); + ensure!(target == account, Error::::NotAllowed); call.dispatch(frame_system::RawOrigin::Signed(account).into()) .map(|_| ()) .map_err(|e| e.error) @@ -541,7 +541,7 @@ pub mod pallet { ensure!(Self::is_friend(&recovery_config.friends, &who), Error::::NotFriend); // Either insert the vouch, or return an error that the user already vouched. match active_recovery.friends.binary_search(&who) { - Ok(_pos) => Err(Error::::AlreadyVouched)?, + Ok(_pos) => return Err(Error::::AlreadyVouched.into()), Err(pos) => active_recovery .friends .try_insert(pos, who.clone()) diff --git a/substrate/frame/referenda/src/benchmarking.rs b/substrate/frame/referenda/src/benchmarking.rs index 08612e0614..87b13868db 100644 --- a/substrate/frame/referenda/src/benchmarking.rs +++ b/substrate/frame/referenda/src/benchmarking.rs @@ -57,10 +57,7 @@ fn create_referendum() -> (T::AccountId, ReferendumIndex) { fn place_deposit(index: ReferendumIndex) { let caller = funded_account::("caller", 0); whitelist_account!(caller); - assert_ok!(Referenda::::place_decision_deposit( - RawOrigin::Signed(caller.clone()).into(), - index, - )); + assert_ok!(Referenda::::place_decision_deposit(RawOrigin::Signed(caller).into(), index)); } fn nudge(index: ReferendumIndex) { @@ -265,7 +262,7 @@ benchmarks! { let track = Referenda::::ensure_ongoing(index).unwrap().track; assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), index)); assert_eq!(DecidingCount::::get(&track), 1); - }: one_fewer_deciding(RawOrigin::Root, track.clone()) + }: one_fewer_deciding(RawOrigin::Root, track) verify { assert_eq!(DecidingCount::::get(&track), 0); } @@ -278,7 +275,7 @@ benchmarks! { assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), queued[0])); assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); let deciding_count = DecidingCount::::get(&track); - }: one_fewer_deciding(RawOrigin::Root, track.clone()) + }: one_fewer_deciding(RawOrigin::Root, track) verify { assert_eq!(DecidingCount::::get(&track), deciding_count); assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get() - 1); @@ -297,7 +294,7 @@ benchmarks! { assert_ok!(Referenda::::cancel(T::CancelOrigin::successful_origin(), queued[0])); assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get()); let deciding_count = DecidingCount::::get(&track); - }: one_fewer_deciding(RawOrigin::Root, track.clone()) + }: one_fewer_deciding(RawOrigin::Root, track) verify { assert_eq!(DecidingCount::::get(&track), deciding_count); assert_eq!(TrackQueue::::get(&track).len() as u32, T::MaxQueued::get() - 1); diff --git a/substrate/frame/referenda/src/lib.rs b/substrate/frame/referenda/src/lib.rs index 067775fd33..b53be191d3 100644 --- a/substrate/frame/referenda/src/lib.rs +++ b/substrate/frame/referenda/src/lib.rs @@ -363,7 +363,7 @@ pub mod pallet { let status = ReferendumStatus { track, origin: proposal_origin, - proposal_hash: proposal_hash.clone(), + proposal_hash, enactment: enactment_moment, submitted: now, submission_deposit, @@ -643,7 +643,7 @@ impl, I: 'static> Polling for Pallet { .iter() .max_by_key(|(_, info)| info.max_deciding) .expect("Always one class"); - (r.0.clone(), r.1.max_deciding) + (r.0, r.1.max_deciding) } } @@ -730,8 +730,8 @@ impl, I: 'static> Pallet { Self::deposit_event(Event::::DecisionStarted { index, tally: status.tally.clone(), - proposal_hash: status.proposal_hash.clone(), - track: status.track.clone(), + proposal_hash: status.proposal_hash, + track: status.track, }); let confirming = if is_passing { Self::deposit_event(Event::::ConfirmStarted { index }); @@ -895,7 +895,7 @@ impl, I: 'static> Pallet { let prepare_end = status.submitted.saturating_add(track.prepare_period); if now >= prepare_end { let (maybe_alarm, branch) = - Self::ready_for_deciding(now, &track, index, &mut status); + Self::ready_for_deciding(now, track, index, &mut status); if let Some(set_alarm) = maybe_alarm { alarm = alarm.min(set_alarm); } @@ -934,7 +934,7 @@ impl, I: 'static> Pallet { &track.min_approval, ); branch = if is_passing { - match deciding.confirming.clone() { + match deciding.confirming { Some(t) if now >= t => { // Passed! Self::ensure_no_alarm(&mut status); @@ -996,7 +996,7 @@ impl, I: 'static> Pallet { ServiceBranch::ContinueNotConfirming } }; - alarm = Self::decision_time(&deciding, &status.tally, track); + alarm = Self::decision_time(deciding, &status.tally, track); }, } diff --git a/substrate/frame/referenda/src/types.rs b/substrate/frame/referenda/src/types.rs index 6220751006..5e0361c8fe 100644 --- a/substrate/frame/referenda/src/types.rs +++ b/substrate/frame/referenda/src/types.rs @@ -182,7 +182,7 @@ pub trait TracksInfo { /// Return the track info for track `id`, by default this just looks it up in `Self::tracks()`. fn info(id: Self::Id) -> Option<&'static TrackInfo> { - Self::tracks().iter().find(|x| &x.0 == &id).map(|x| &x.1) + Self::tracks().iter().find(|x| x.0 == id).map(|x| &x.1) } } @@ -309,9 +309,9 @@ impl Curve { match self { Self::LinearDecreasing { begin, delta } => if delta.is_zero() { - return *delta + *delta } else { - return (*begin - y.min(*begin)).min(*delta) / *delta + (*begin - y.min(*begin)).min(*delta) / *delta }, } } diff --git a/substrate/frame/scheduler/src/lib.rs b/substrate/frame/scheduler/src/lib.rs index ec60cedc28..9b0fc87587 100644 --- a/substrate/frame/scheduler/src/lib.rs +++ b/substrate/frame/scheduler/src/lib.rs @@ -727,7 +727,7 @@ impl Pallet { Self::deposit_event(Event::Canceled { when, index }); Ok(()) } else { - Err(Error::::NotFound)? + return Err(Error::::NotFound.into()) } } @@ -765,7 +765,7 @@ impl Pallet { ) -> Result, DispatchError> { // ensure id it is unique if Lookup::::contains_key(&id) { - return Err(Error::::FailedToSchedule)? + return Err(Error::::FailedToSchedule.into()) } let when = Self::resolve_time(when)?; @@ -817,7 +817,7 @@ impl Pallet { Self::deposit_event(Event::Canceled { when, index }); Ok(()) } else { - Err(Error::::NotFound)? + return Err(Error::::NotFound.into()) } }) } diff --git a/substrate/frame/scored-pool/src/lib.rs b/substrate/frame/scored-pool/src/lib.rs index 3f0674d720..abdb9b2acc 100644 --- a/substrate/frame/scored-pool/src/lib.rs +++ b/substrate/frame/scored-pool/src/lib.rs @@ -256,7 +256,7 @@ pub mod pallet { // reserve balance for each candidate in the pool. // panicking here is ok, since this just happens one time, pre-genesis. pool.iter().for_each(|(who, _)| { - T::Currency::reserve(&who, T::CandidateDeposit::get()) + T::Currency::reserve(who, T::CandidateDeposit::get()) .expect("balance too low to create candidacy"); >::insert(who, true); }); @@ -387,7 +387,7 @@ pub mod pallet { // if there is already an element with `score`, we insert // right before that. if not, the search returns a location // where we can insert while maintaining order. - let item = (who, Some(score.clone())); + let item = (who, Some(score)); let location = pool .binary_search_by_key(&Reverse(score), |(_, maybe_score)| { Reverse(maybe_score.unwrap_or_default()) diff --git a/substrate/frame/session/src/historical/shared.rs b/substrate/frame/session/src/historical/shared.rs index 9e19b9df6d..faa91f7919 100644 --- a/substrate/frame/session/src/historical/shared.rs +++ b/substrate/frame/session/src/historical/shared.rs @@ -27,13 +27,10 @@ pub(super) const LAST_PRUNE: &[u8] = b"session_historical_last_prune"; /// Derive the key used to store the list of validators pub(super) fn derive_key>(prefix: P, session_index: SessionIndex) -> Vec { - let prefix: &[u8] = prefix.as_ref(); session_index.using_encoded(|encoded_session_index| { - prefix - .into_iter() - .chain(b"/".into_iter()) - .chain(encoded_session_index.into_iter()) - .copied() - .collect::>() + let mut key = prefix.as_ref().to_owned(); + key.push(b'/'); + key.extend_from_slice(encoded_session_index); + key }) } diff --git a/substrate/frame/session/src/lib.rs b/substrate/frame/session/src/lib.rs index d6ecd17a8f..a460c650ec 100644 --- a/substrate/frame/session/src/lib.rs +++ b/substrate/frame/session/src/lib.rs @@ -184,7 +184,7 @@ impl< // (0% is never returned). let progress = if now >= offset { let current = (now - offset) % period.clone() + One::one(); - Some(Permill::from_rational(current.clone(), period.clone())) + Some(Permill::from_rational(current, period)) } else { Some(Permill::from_rational(now + One::one(), offset)) }; @@ -689,7 +689,6 @@ impl Pallet { if let Some(&(_, ref old_keys)) = now_session_keys.next() { if old_keys != keys { changed = true; - return } } }; @@ -803,10 +802,10 @@ impl Pallet { let who = T::ValidatorIdOf::convert(account.clone()) .ok_or(Error::::NoAssociatedValidatorId)?; - ensure!(frame_system::Pallet::::can_inc_consumer(&account), Error::::NoAccount); + ensure!(frame_system::Pallet::::can_inc_consumer(account), Error::::NoAccount); let old_keys = Self::inner_set_keys(&who, keys)?; if old_keys.is_none() { - let assertion = frame_system::Pallet::::inc_consumers(&account).is_ok(); + let assertion = frame_system::Pallet::::inc_consumers(account).is_ok(); debug_assert!(assertion, "can_inc_consumer() returned true; no change since; qed"); } @@ -866,7 +865,7 @@ impl Pallet { let key_data = old_keys.get_raw(*id); Self::clear_key_owner(*id, key_data); } - frame_system::Pallet::::dec_consumers(&account); + frame_system::Pallet::::dec_consumers(account); Ok(()) } @@ -949,6 +948,6 @@ impl> FindAuthor let i = Inner::find_author(digests)?; let validators = >::validators(); - validators.get(i as usize).map(|k| k.clone()) + validators.get(i as usize).cloned() } } diff --git a/substrate/frame/society/src/lib.rs b/substrate/frame/society/src/lib.rs index 6ad63d2102..645a0b8ba1 100644 --- a/substrate/frame/society/src/lib.rs +++ b/substrate/frame/society/src/lib.rs @@ -357,10 +357,10 @@ impl BidKind { if a == v { Ok(()) } else { - Err("incorrect identity")? + Err("incorrect identity".into()) } } else { - Err("not vouched")? + Err("not vouched".into()) } } } @@ -724,7 +724,7 @@ pub mod pallet { let deposit = T::CandidateDeposit::get(); T::Currency::reserve(&who, deposit)?; - Self::put_bid(bids, &who, value.clone(), BidKind::Deposit(deposit)); + Self::put_bid(bids, &who, value, BidKind::Deposit(deposit)); Self::deposit_event(Event::::Bid { candidate_id: who, offer: value }); Ok(()) } @@ -770,7 +770,7 @@ pub mod pallet { Self::deposit_event(Event::::Unbid { candidate: who }); Ok(()) } else { - Err(Error::::BadPosition)? + Err(Error::::BadPosition.into()) } }) } @@ -844,7 +844,7 @@ pub mod pallet { ensure!(!>::contains_key(&voucher), Error::::AlreadyVouching); >::insert(&voucher, VouchingStatus::Vouching); - Self::put_bid(bids, &who, value.clone(), BidKind::Vouch(voucher.clone(), tip)); + Self::put_bid(bids, &who, value, BidKind::Vouch(voucher.clone(), tip)); Self::deposit_event(Event::::Vouch { candidate_id: who, offer: value, @@ -887,7 +887,7 @@ pub mod pallet { Self::deposit_event(Event::::Unvouch { candidate: who }); Ok(()) } else { - Err(Error::::BadPosition)? + Err(Error::::BadPosition.into()) } }) } @@ -1001,7 +1001,7 @@ pub mod pallet { return Ok(()) } } - Err(Error::::NoPayout)? + Err(Error::::NoPayout.into()) } /// Found the society. @@ -1229,7 +1229,7 @@ pub mod pallet { // Remove suspended candidate >::remove(who); } else { - Err(Error::::NotSuspended)? + return Err(Error::::NotSuspended.into()) } Ok(()) } @@ -1392,8 +1392,8 @@ impl, I: 'static> Pallet { ensure!(Self::founder() != Some(m.clone()), Error::::Founder); let mut members = >::get(); - match members.binary_search(&m) { - Err(_) => Err(Error::::NotMember)?, + match members.binary_search(m) { + Err(_) => Err(Error::::NotMember.into()), Ok(i) => { members.remove(i); T::MembershipChanged::change_members_sorted(&[], &[m.clone()], &members[..]); @@ -1572,7 +1572,7 @@ impl, I: 'static> Pallet { >::put(&members[..]); >::put(&primary); - T::MembershipChanged::change_members_sorted(&accounts, &[], &members); + T::MembershipChanged::change_members_sorted(&accounts, &[], members); Self::deposit_event(Event::::Inducted { primary, candidates: accounts }); } @@ -1605,7 +1605,7 @@ impl, I: 'static> Pallet { if !payouts.is_empty() { let mut dropped = 0; for (_, amount) in payouts.iter_mut() { - if let Some(new_rest) = rest.checked_sub(&amount) { + if let Some(new_rest) = rest.checked_sub(amount) { // not yet totally slashed after this one; drop it completely. rest = new_rest; dropped += 1; @@ -1635,7 +1635,7 @@ impl, I: 'static> Pallet { /// Suspend a user, removing them from the member list. fn suspend_member(who: &T::AccountId) { - if Self::remove_member(&who).is_ok() { + if Self::remove_member(who).is_ok() { >::insert(who, true); >::remove(who); Self::deposit_event(Event::::MemberSuspended { member: who.clone() }); @@ -1683,12 +1683,10 @@ impl, I: 'static> Pallet { let mut approval_count = 0; let mut rejection_count = 0; // Tallies total number of approve and reject votes for the defender. - members.iter().filter_map(|m| >::take(m)).for_each( - |v| match v { - Vote::Approve => approval_count += 1, - _ => rejection_count += 1, - }, - ); + members.iter().filter_map(>::take).for_each(|v| match v { + Vote::Approve => approval_count += 1, + _ => rejection_count += 1, + }); if approval_count <= rejection_count { // User has failed the challenge diff --git a/substrate/frame/staking/reward-fn/src/lib.rs b/substrate/frame/staking/reward-fn/src/lib.rs index cb0b660bf5..cc9919c28c 100644 --- a/substrate/frame/staking/reward-fn/src/lib.rs +++ b/substrate/frame/staking/reward-fn/src/lib.rs @@ -137,20 +137,18 @@ fn compute_taylor_serie_part(p: &INPoSParam) -> BigUint { if taylor_sum_positive == last_taylor_term_positive { taylor_sum = taylor_sum.add(&last_taylor_term); + } else if taylor_sum >= last_taylor_term { + taylor_sum = taylor_sum + .sub(&last_taylor_term) + // NOTE: Should never happen as checked above + .unwrap_or_else(|e| e); } else { - if taylor_sum >= last_taylor_term { - taylor_sum = taylor_sum - .sub(&last_taylor_term) - // NOTE: Should never happen as checked above - .unwrap_or_else(|e| e); - } else { - taylor_sum_positive = !taylor_sum_positive; - taylor_sum = last_taylor_term - .clone() - .sub(&taylor_sum) - // NOTE: Should never happen as checked above - .unwrap_or_else(|e| e); - } + taylor_sum_positive = !taylor_sum_positive; + taylor_sum = last_taylor_term + .clone() + .sub(&taylor_sum) + // NOTE: Should never happen as checked above + .unwrap_or_else(|e| e); } } @@ -217,10 +215,10 @@ fn div_by_stripped(mut a: BigUint, b: &BigUint) -> BigUint { return new_a .div(b, false) .map(|res| res.0) - .unwrap_or_else(|| BigUint::zero()) + .unwrap_or_else(BigUint::zero) .div_unit(100_000) .div_unit(100_000) } - a.div(b, false).map(|res| res.0).unwrap_or_else(|| BigUint::zero()) + a.div(b, false).map(|res| res.0).unwrap_or_else(BigUint::zero) } diff --git a/substrate/frame/staking/src/benchmarking.rs b/substrate/frame/staking/src/benchmarking.rs index 7321740cfa..eb9129ac4b 100644 --- a/substrate/frame/staking/src/benchmarking.rs +++ b/substrate/frame/staking/src/benchmarking.rs @@ -183,8 +183,8 @@ impl ListScenario { Default::default(), )?; Staking::::nominate( - RawOrigin::Signed(origin_controller2.clone()).into(), - vec![T::Lookup::unlookup(account("random_validator", 0, SEED))].clone(), + RawOrigin::Signed(origin_controller2).into(), + vec![T::Lookup::unlookup(account("random_validator", 0, SEED))], )?; // find a destination weight that will trigger the worst case scenario @@ -239,10 +239,10 @@ benchmarks! { // the weight the nominator will start at. let scenario = ListScenario::::new(origin_weight, true)?; - let max_additional = scenario.dest_weight.clone() - origin_weight; + let max_additional = scenario.dest_weight - origin_weight; let stash = scenario.origin_stash1.clone(); - let controller = scenario.origin_controller1.clone(); + let controller = scenario.origin_controller1; let original_bonded: BalanceOf = Ledger::::get(&controller).map(|l| l.active).ok_or("ledger not created after")?; @@ -271,7 +271,7 @@ benchmarks! { let stash = scenario.origin_stash1.clone(); let controller = scenario.origin_controller1.clone(); - let amount = origin_weight - scenario.dest_weight.clone(); + let amount = origin_weight - scenario.dest_weight; let ledger = Ledger::::get(&controller).ok_or("ledger not created before")?; let original_bonded: BalanceOf = ledger.active; @@ -315,7 +315,7 @@ benchmarks! { // destination position because we are doing a removal from the list but no insert. let scenario = ListScenario::::new(origin_weight, true)?; let controller = scenario.origin_controller1.clone(); - let stash = scenario.origin_stash1.clone(); + let stash = scenario.origin_stash1; assert!(T::VoterList::contains(&stash)); let ed = T::Currency::minimum_balance(); @@ -450,7 +450,7 @@ benchmarks! { // destination position because we are doing a removal from the list but no insert. let scenario = ListScenario::::new(origin_weight, true)?; let controller = scenario.origin_controller1.clone(); - let stash = scenario.origin_stash1.clone(); + let stash = scenario.origin_stash1; assert!(T::VoterList::contains(&stash)); whitelist_account!(controller); @@ -518,7 +518,7 @@ benchmarks! { // destination position because we are doing a removal from the list but no insert. let scenario = ListScenario::::new(origin_weight, true)?; let controller = scenario.origin_controller1.clone(); - let stash = scenario.origin_stash1.clone(); + let stash = scenario.origin_stash1; assert!(T::VoterList::contains(&stash)); add_slashing_spans::(&stash, s); @@ -561,10 +561,10 @@ benchmarks! { let validator_controller = >::get(&validator).unwrap(); let balance_before = T::Currency::free_balance(&validator_controller); for (_, controller) in &nominators { - let balance = T::Currency::free_balance(&controller); + let balance = T::Currency::free_balance(controller); ensure!(balance.is_zero(), "Controller has balance, but should be dead."); } - }: payout_stakers(RawOrigin::Signed(caller), validator.clone(), current_era) + }: payout_stakers(RawOrigin::Signed(caller), validator, current_era) verify { let balance_after = T::Currency::free_balance(&validator_controller); ensure!( @@ -572,7 +572,7 @@ benchmarks! { "Balance of validator controller should have increased after payout.", ); for (_, controller) in &nominators { - let balance = T::Currency::free_balance(&controller); + let balance = T::Currency::free_balance(controller); ensure!(!balance.is_zero(), "Payout not given to controller."); } } @@ -594,7 +594,7 @@ benchmarks! { let balance_before = T::Currency::free_balance(&validator); let mut nominator_balances_before = Vec::new(); for (stash, _) in &nominators { - let balance = T::Currency::free_balance(&stash); + let balance = T::Currency::free_balance(stash); nominator_balances_before.push(balance); } }: payout_stakers(RawOrigin::Signed(caller), validator.clone(), current_era) @@ -605,7 +605,7 @@ benchmarks! { "Balance of validator stash should have increased after payout.", ); for ((stash, _), balance_before) in nominators.iter().zip(nominator_balances_before.iter()) { - let balance_after = T::Currency::free_balance(&stash); + let balance_after = T::Currency::free_balance(stash); ensure!( balance_before < &balance_after, "Balance of nominator stash should have increased after payout.", @@ -626,7 +626,7 @@ benchmarks! { // setup a worst case list scenario. let scenario = ListScenario::::new(origin_weight, true)?; - let dest_weight = scenario.dest_weight.clone(); + let dest_weight = scenario.dest_weight; // rebond an amount that will give the user dest_weight let rebond_amount = dest_weight - origin_weight; @@ -644,7 +644,7 @@ benchmarks! { }; let stash = scenario.origin_stash1.clone(); - let controller = scenario.origin_controller1.clone(); + let controller = scenario.origin_controller1; let mut staking_ledger = Ledger::::get(controller.clone()).unwrap(); for _ in 0 .. l { @@ -691,7 +691,7 @@ benchmarks! { // destination position because we are doing a removal from the list but no insert. let scenario = ListScenario::::new(origin_weight, true)?; let controller = scenario.origin_controller1.clone(); - let stash = scenario.origin_stash1.clone(); + let stash = scenario.origin_stash1; add_slashing_spans::(&stash, s); let l = StakingLedger { @@ -895,7 +895,7 @@ benchmarks! { // destination position because we are doing a removal from the list but no insert. let scenario = ListScenario::::new(origin_weight, true)?; let controller = scenario.origin_controller1.clone(); - let stash = scenario.origin_stash1.clone(); + let stash = scenario.origin_stash1; assert!(T::VoterList::contains(&stash)); Staking::::set_staking_configs( @@ -909,7 +909,7 @@ benchmarks! { )?; let caller = whitelisted_caller(); - }: _(RawOrigin::Signed(caller), controller.clone()) + }: _(RawOrigin::Signed(caller), controller) verify { assert!(!T::VoterList::contains(&stash)); } diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index 037dcc86ab..2d4c1ea9a3 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -321,7 +321,7 @@ pub use weights::WeightInfo; pub use pallet::{pallet::*, *}; -pub(crate) const LOG_TARGET: &'static str = "runtime::staking"; +pub(crate) const LOG_TARGET: &str = "runtime::staking"; // syntactic sugar for logging. #[macro_export] @@ -784,7 +784,7 @@ impl (Balance, Balance) { let (validator_payout, max_payout) = inflation::compute_total_payout( - &T::get(), + T::get(), total_staked, total_issuance, // Duration of era; more than u64::MAX is rewarded as u64::MAX. diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index 4665d956fd..0ac61e21fb 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -123,8 +123,9 @@ impl Pallet { .claimed_rewards .retain(|&x| x >= current_era.saturating_sub(history_depth)); match ledger.claimed_rewards.binary_search(&era) { - Ok(_) => Err(Error::::AlreadyClaimed - .with_weight(T::WeightInfo::payout_stakers_alive_staked(0)))?, + Ok(_) => + return Err(Error::::AlreadyClaimed + .with_weight(T::WeightInfo::payout_stakers_alive_staked(0))), Err(pos) => ledger.claimed_rewards.insert(pos, era), } @@ -146,8 +147,8 @@ impl Pallet { let validator_reward_points = era_reward_points .individual .get(&ledger.stash) - .map(|points| *points) - .unwrap_or_else(|| Zero::zero()); + .copied() + .unwrap_or_else(Zero::zero); // Nothing to do if they have no reward points. if validator_reward_points.is_zero() { @@ -260,8 +261,7 @@ impl Pallet { 0 }); - let era_length = - session_index.checked_sub(current_era_start_session_index).unwrap_or(0); // Must never happen. + let era_length = session_index.saturating_sub(current_era_start_session_index); // Must never happen. match ForceEra::::get() { // Will be set to `NotForcing` again if a new era has been triggered. @@ -1036,7 +1036,7 @@ impl ElectionDataProvider for Pallet { ); Self::do_add_nominator( &v, - Nominations { targets: t.try_into().unwrap(), submitted_in: 0, suppressed: false }, + Nominations { targets: t, submitted_in: 0, suppressed: false }, ); }); } diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index bf13786d64..117bc6e7c1 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -580,7 +580,7 @@ pub mod pallet { status ); assert!( - T::Currency::free_balance(&stash) >= balance, + T::Currency::free_balance(stash) >= balance, "Stash does not have enough balance to bond." ); frame_support::assert_ok!(>::bond( @@ -779,18 +779,18 @@ pub mod pallet { let stash = ensure_signed(origin)?; if >::contains_key(&stash) { - Err(Error::::AlreadyBonded)? + return Err(Error::::AlreadyBonded.into()) } let controller = T::Lookup::lookup(controller)?; if >::contains_key(&controller) { - Err(Error::::AlreadyPaired)? + return Err(Error::::AlreadyPaired.into()) } // Reject a bond which is considered to be _dust_. if value < T::Currency::minimum_balance() { - Err(Error::::InsufficientBond)? + return Err(Error::::InsufficientBond.into()) } frame_system::Pallet::::inc_consumers(&stash).map_err(|_| Error::::BadState)?; @@ -862,7 +862,7 @@ pub mod pallet { debug_assert_eq!(T::VoterList::sanity_check(), Ok(())); } - Self::deposit_event(Event::::Bonded(stash.clone(), extra)); + Self::deposit_event(Event::::Bonded(stash, extra)); } Ok(()) } @@ -1183,7 +1183,7 @@ pub mod pallet { let old_controller = Self::bonded(&stash).ok_or(Error::::NotStash)?; let controller = T::Lookup::lookup(controller)?; if >::contains_key(&controller) { - Err(Error::::AlreadyPaired)? + return Err(Error::::AlreadyPaired.into()) } if controller != old_controller { >::insert(&stash, &controller); @@ -1466,8 +1466,8 @@ pub mod pallet { ensure_root(origin)?; if let Some(current_era) = Self::current_era() { HistoryDepth::::mutate(|history_depth| { - let last_kept = current_era.checked_sub(*history_depth).unwrap_or(0); - let new_last_kept = current_era.checked_sub(new_history_depth).unwrap_or(0); + let last_kept = current_era.saturating_sub(*history_depth); + let new_last_kept = current_era.saturating_sub(new_history_depth); for era_index in last_kept..new_last_kept { Self::clear_era_information(era_index); } diff --git a/substrate/frame/staking/src/slashing.rs b/substrate/frame/staking/src/slashing.rs index 9fc50eaf53..0d55eb7fe0 100644 --- a/substrate/frame/staking/src/slashing.rs +++ b/substrate/frame/staking/src/slashing.rs @@ -389,7 +389,7 @@ fn slash_nominators( let mut era_slash = as Store>::NominatorSlashInEra::get(¶ms.slash_era, stash) - .unwrap_or_else(|| Zero::zero()); + .unwrap_or_else(Zero::zero); era_slash += own_slash_difference; @@ -646,7 +646,7 @@ pub(crate) fn apply_slash( for &(ref nominator, nominator_slash) in &unapplied_slash.others { do_slash::( - &nominator, + nominator, nominator_slash, &mut reward_payout, &mut slashed_imbalance, diff --git a/substrate/frame/staking/src/testing_utils.rs b/substrate/frame/staking/src/testing_utils.rs index 5f9f378b10..f30020597d 100644 --- a/substrate/frame/staking/src/testing_utils.rs +++ b/substrate/frame/staking/src/testing_utils.rs @@ -85,7 +85,7 @@ pub fn create_stash_controller( amount, destination, )?; - return Ok((stash, controller)) + Ok((stash, controller)) } /// Create a stash and controller pair with fixed balance. @@ -127,7 +127,7 @@ pub fn create_stash_and_dead_controller( amount, destination, )?; - return Ok((stash, controller)) + Ok((stash, controller)) } /// create `max` validators. diff --git a/substrate/frame/state-trie-migration/src/lib.rs b/substrate/frame/state-trie-migration/src/lib.rs index 3d66c6a66b..d78fd7d9ca 100644 --- a/substrate/frame/state-trie-migration/src/lib.rs +++ b/substrate/frame/state-trie-migration/src/lib.rs @@ -57,7 +57,7 @@ pub use pallet::*; -const LOG_TARGET: &'static str = "runtime::state-trie-migration"; +const LOG_TARGET: &str = "runtime::state-trie-migration"; #[macro_export] macro_rules! log { @@ -319,12 +319,12 @@ pub mod pallet { let (maybe_current_child, child_root) = match (&self.progress_child, &self.progress_top) { (Progress::LastKey(last_child), Progress::LastKey(last_top)) => { - let child_root = Pallet::::transform_child_key_or_halt(&last_top); - let maybe_current_child = child_io::next_key(child_root, &last_child); + let child_root = Pallet::::transform_child_key_or_halt(last_top); + let maybe_current_child = child_io::next_key(child_root, last_child); (maybe_current_child, child_root) }, (Progress::ToStart, Progress::LastKey(last_top)) => { - let child_root = Pallet::::transform_child_key_or_halt(&last_top); + let child_root = Pallet::::transform_child_key_or_halt(last_top); // Start with the empty key as first key. (Some(Vec::new()), child_root) }, @@ -336,7 +336,7 @@ pub mod pallet { }; if let Some(current_child) = maybe_current_child.as_ref() { - let added_size = if let Some(data) = child_io::get(child_root, ¤t_child) { + let added_size = if let Some(data) = child_io::get(child_root, current_child) { child_io::set(child_root, current_child, &data); data.len() as u32 } else { @@ -369,8 +369,8 @@ pub mod pallet { }; if let Some(current_top) = maybe_current_top.as_ref() { - let added_size = if let Some(data) = sp_io::storage::get(¤t_top) { - sp_io::storage::set(¤t_top, &data); + let added_size = if let Some(data) = sp_io::storage::get(current_top) { + sp_io::storage::set(current_top, &data); data.len() as u32 } else { Zero::zero() @@ -503,7 +503,7 @@ pub mod pallet { ) -> DispatchResult { T::ControlOrigin::ensure_origin(origin)?; AutoLimits::::put(maybe_config); - Ok(().into()) + Ok(()) } /// Continue the migration for the given `limits`. @@ -616,7 +616,7 @@ pub mod pallet { let mut dyn_size = 0u32; for key in &keys { - if let Some(data) = sp_io::storage::get(&key) { + if let Some(data) = sp_io::storage::get(key) { dyn_size = dyn_size.saturating_add(data.len() as u32); sp_io::storage::set(key, &data); } @@ -678,9 +678,9 @@ pub mod pallet { let mut dyn_size = 0u32; let transformed_child_key = Self::transform_child_key(&root).ok_or("bad child key")?; for child_key in &child_keys { - if let Some(data) = child_io::get(transformed_child_key, &child_key) { + if let Some(data) = child_io::get(transformed_child_key, child_key) { dyn_size = dyn_size.saturating_add(data.len() as u32); - child_io::set(transformed_child_key, &child_key, &data); + child_io::set(transformed_child_key, child_key, &data); } } @@ -839,7 +839,7 @@ mod benchmarks { // The size of the key seemingly makes no difference in the read/write time, so we make it // constant. - const KEY: &'static [u8] = b"key"; + const KEY: &[u8] = b"key"; frame_benchmarking::benchmarks! { continue_migrate { diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/config.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/config.rs index 79176fa738..a3d70f1852 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/config.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/config.rs @@ -43,12 +43,8 @@ pub fn expand_outer_config( types.extend(expand_config_types(runtime, decl, &config, part_is_generic)); fields.extend(quote!(pub #field_name: #config,)); - build_storage_calls.extend(expand_config_build_storage_call( - scrate, - runtime, - decl, - &field_name, - )); + build_storage_calls + .extend(expand_config_build_storage_call(scrate, runtime, decl, field_name)); query_genesis_config_part_macros.push(quote! { #path::__substrate_genesis_config_check::is_genesis_config_defined!(#pallet_name); #[cfg(feature = "std")] diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 2a86869382..7b4156a94d 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -201,7 +201,7 @@ fn construct_runtime_intermediary_expansion( ); } - Ok(expansion.into()) + Ok(expansion) } /// All pallets have explicit definition of parts, this will expand to the runtime declaration. @@ -225,16 +225,16 @@ fn construct_runtime_final_expansion( })?; let hidden_crate_name = "construct_runtime"; - let scrate = generate_crate_access(&hidden_crate_name, "frame-support"); - let scrate_decl = generate_hidden_includes(&hidden_crate_name, "frame-support"); + let scrate = generate_crate_access(hidden_crate_name, "frame-support"); + let scrate_decl = generate_hidden_includes(hidden_crate_name, "frame-support"); let outer_event = expand::expand_outer_event(&name, &pallets, &scrate)?; - let outer_origin = expand::expand_outer_origin(&name, &system_pallet, &pallets, &scrate)?; + let outer_origin = expand::expand_outer_origin(&name, system_pallet, &pallets, &scrate)?; let all_pallets = decl_all_pallets(&name, pallets.iter()); let pallet_to_index = decl_pallet_runtime_setup(&name, &pallets, &scrate); - let dispatch = expand::expand_outer_dispatch(&name, &system_pallet, &pallets, &scrate); + let dispatch = expand::expand_outer_dispatch(&name, system_pallet, &pallets, &scrate); let metadata = expand::expand_runtime_metadata(&name, &pallets, &scrate, &unchecked_extrinsic); let outer_config = expand::expand_outer_config(&name, &pallets, &scrate); let inherent = diff --git a/substrate/frame/support/procedural/src/pallet/expand/call.rs b/substrate/frame/support/procedural/src/pallet/expand/call.rs index 2d7c550a44..60546e1a96 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/call.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/call.rs @@ -68,7 +68,7 @@ pub fn expand_call(def: &mut Def) -> proc_macro2::TokenStream { .args .iter() .map(|(_, name, _)| { - syn::Ident::new(&name.to_string().trim_start_matches('_'), name.span()) + syn::Ident::new(name.to_string().trim_start_matches('_'), name.span()) }) .collect::>() }) diff --git a/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs b/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs index 18fa87a262..739e85e0d1 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/genesis_config.rs @@ -85,7 +85,7 @@ pub fn expand_genesis_config(def: &mut Def) -> proc_macro2::TokenStream { syn::Item::Enum(syn::ItemEnum { attrs, .. }) | syn::Item::Struct(syn::ItemStruct { attrs, .. }) | syn::Item::Type(syn::ItemType { attrs, .. }) => { - if get_doc_literals(&attrs).is_empty() { + if get_doc_literals(attrs).is_empty() { attrs.push(syn::parse_quote!( #[doc = r" Can be used to configure the diff --git a/substrate/frame/support/procedural/src/pallet/expand/storage.rs b/substrate/frame/support/procedural/src/pallet/expand/storage.rs index d59dd46051..657968e17a 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/storage.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/storage.rs @@ -74,9 +74,7 @@ fn check_prefix_duplicates( ), ); - if let Some(other_dup_err) = - used_prefixes.insert(counter_prefix.clone(), counter_dup_err.clone()) - { + if let Some(other_dup_err) = used_prefixes.insert(counter_prefix, counter_dup_err.clone()) { let mut err = counter_dup_err; err.combine(other_dup_err); return Err(err) @@ -113,7 +111,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { _ => unreachable!("Checked by def"), }; - let prefix_ident = prefix_ident(&storage_def); + let prefix_ident = prefix_ident(storage_def); let type_use_gen = if def.config.has_instance { quote::quote_spanned!(storage_def.attr_span => T, I) } else { @@ -215,7 +213,7 @@ pub fn process_generics(def: &mut Def) -> syn::Result<()> { /// * generate metadatas pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { if let Err(e) = process_generics(def) { - return e.into_compile_error().into() + return e.into_compile_error() } // Check for duplicate prefixes @@ -393,7 +391,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { let prefix_structs = def.storages.iter().map(|storage_def| { let type_impl_gen = &def.type_impl_generics(storage_def.attr_span); let type_use_gen = &def.type_use_generics(storage_def.attr_span); - let prefix_struct_ident = prefix_ident(&storage_def); + let prefix_struct_ident = prefix_ident(storage_def); let prefix_struct_vis = &storage_def.vis; let prefix_struct_const = storage_def.prefix(); let config_where_clause = &def.config.where_clause; diff --git a/substrate/frame/support/procedural/src/pallet/parse/call.rs b/substrate/frame/support/procedural/src/pallet/parse/call.rs index 5468b13521..f532d339f1 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/call.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/call.rs @@ -133,9 +133,10 @@ impl CallDef { return Err(syn::Error::new(item.span(), "Invalid pallet::call, expected item impl")) }; - let mut instances = vec![]; - instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?); - instances.push(helper::check_pallet_struct_usage(&item.self_ty)?); + let instances = vec![ + helper::check_impl_gen(&item.generics, item.impl_token.span())?, + helper::check_pallet_struct_usage(&item.self_ty)?, + ]; if let Some((_, _, for_)) = item.trait_ { let msg = "Invalid pallet::call, expected no trait ident as in \ diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 526c7eda2f..60888fc5dd 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -373,9 +373,10 @@ impl ConfigDef { let found = if item.supertraits.is_empty() { "none".to_string() } else { - let mut found = item.supertraits.iter().fold(String::new(), |acc, s| { - format!("{}`{}`, ", acc, quote::quote!(#s).to_string()) - }); + let mut found = item + .supertraits + .iter() + .fold(String::new(), |acc, s| format!("{}`{}`, ", acc, quote::quote!(#s))); found.pop(); found.pop(); found diff --git a/substrate/frame/support/procedural/src/pallet/parse/error.rs b/substrate/frame/support/procedural/src/pallet/parse/error.rs index 0ec49aa0ad..c6ce9b37c7 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/error.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/error.rs @@ -62,8 +62,8 @@ impl ErrorDef { return Err(syn::Error::new(item.span(), msg)) } - let mut instances = vec![]; - instances.push(helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?); + let instances = + vec![helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?]; if item.generics.where_clause.is_some() { let msg = "Invalid pallet::error, where clause is not allowed on pallet error item"; diff --git a/substrate/frame/support/procedural/src/pallet/parse/extra_constants.rs b/substrate/frame/support/procedural/src/pallet/parse/extra_constants.rs index 7163b4b632..d8622da084 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/extra_constants.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/extra_constants.rs @@ -87,9 +87,10 @@ impl ExtraConstantsDef { )) }; - let mut instances = vec![]; - instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?); - instances.push(helper::check_pallet_struct_usage(&item.self_ty)?); + let instances = vec![ + helper::check_impl_gen(&item.generics, item.impl_token.span())?, + helper::check_pallet_struct_usage(&item.self_ty)?, + ]; if let Some((_, _, for_)) = item.trait_ { let msg = "Invalid pallet::call, expected no trait ident as in \ diff --git a/substrate/frame/support/procedural/src/pallet/parse/genesis_build.rs b/substrate/frame/support/procedural/src/pallet/parse/genesis_build.rs index 79ee083069..9815b8d220 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/genesis_build.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/genesis_build.rs @@ -53,8 +53,7 @@ impl GenesisBuildDef { })? .1; - let mut instances = vec![]; - instances.push(helper::check_genesis_builder_usage(&item_trait)?); + let instances = vec![helper::check_genesis_builder_usage(item_trait)?]; Ok(Self { attr_span, index, instances, where_clause: item.generics.where_clause.clone() }) } diff --git a/substrate/frame/support/procedural/src/pallet/parse/genesis_config.rs b/substrate/frame/support/procedural/src/pallet/parse/genesis_config.rs index 875d15bdc0..45e765c018 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/genesis_config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/genesis_config.rs @@ -49,7 +49,7 @@ impl GenesisConfigDef { let mut instances = vec![]; // NOTE: GenesisConfig is not allowed to be only generic on I because it is not supported // by construct_runtime. - if let Some(u) = helper::check_type_def_optional_gen(&generics, ident.span())? { + if let Some(u) = helper::check_type_def_optional_gen(generics, ident.span())? { instances.push(u); } diff --git a/substrate/frame/support/procedural/src/pallet/parse/hooks.rs b/substrate/frame/support/procedural/src/pallet/parse/hooks.rs index cacc149e48..2dc8f4da47 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/hooks.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/hooks.rs @@ -45,9 +45,10 @@ impl HooksDef { return Err(syn::Error::new(item.span(), msg)) }; - let mut instances = vec![]; - instances.push(helper::check_pallet_struct_usage(&item.self_ty)?); - instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?); + let instances = vec![ + helper::check_pallet_struct_usage(&item.self_ty)?, + helper::check_impl_gen(&item.generics, item.impl_token.span())?, + ]; let item_trait = &item .trait_ diff --git a/substrate/frame/support/procedural/src/pallet/parse/inherent.rs b/substrate/frame/support/procedural/src/pallet/parse/inherent.rs index 2833b3ef5c..a485eed4c4 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/inherent.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/inherent.rs @@ -50,9 +50,10 @@ impl InherentDef { return Err(syn::Error::new(item.span(), msg)) } - let mut instances = vec![]; - instances.push(helper::check_pallet_struct_usage(&item.self_ty)?); - instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?); + let instances = vec![ + helper::check_pallet_struct_usage(&item.self_ty)?, + helper::check_impl_gen(&item.generics, item.impl_token.span())?, + ]; Ok(InherentDef { index, instances }) } diff --git a/substrate/frame/support/procedural/src/pallet/parse/origin.rs b/substrate/frame/support/procedural/src/pallet/parse/origin.rs index 2d729376f5..89929e3e8d 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/origin.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/origin.rs @@ -50,7 +50,7 @@ impl OriginDef { let is_generic = !generics.params.is_empty(); let mut instances = vec![]; - if let Some(u) = helper::check_type_def_optional_gen(&generics, item.span())? { + if let Some(u) = helper::check_type_def_optional_gen(generics, item.span())? { instances.push(u); } else { // construct_runtime only allow generic event for instantiable pallet. diff --git a/substrate/frame/support/procedural/src/pallet/parse/pallet_struct.rs b/substrate/frame/support/procedural/src/pallet/parse/pallet_struct.rs index d98862be8f..a96c310b6f 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/pallet_struct.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/pallet_struct.rs @@ -155,8 +155,8 @@ impl PalletStructDef { return Err(syn::Error::new(item.generics.where_clause.span(), msg)) } - let mut instances = vec![]; - instances.push(helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?); + let instances = + vec![helper::check_type_def_gen_no_bounds(&item.generics, item.ident.span())?]; Ok(Self { index, diff --git a/substrate/frame/support/procedural/src/pallet/parse/storage.rs b/substrate/frame/support/procedural/src/pallet/parse/storage.rs index effe0ce6c5..1f1bb5b2f2 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/storage.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/storage.rs @@ -272,7 +272,7 @@ fn check_generics( ); e.pop(); e.pop(); - e.push_str("."); + e.push('.'); e }; @@ -550,7 +550,7 @@ fn process_generics( let args_span = segment.arguments.span(); let args = match &segment.arguments { - syn::PathArguments::AngleBracketed(args) if args.args.len() != 0 => args, + syn::PathArguments::AngleBracketed(args) if !args.args.is_empty() => args, _ => { let msg = "Invalid pallet::storage, invalid number of generic generic arguments, \ expect more that 0 generic arguments."; @@ -646,13 +646,16 @@ impl StorageDef { self.rename_as .as_ref() .map(syn::LitStr::value) - .unwrap_or(self.ident.to_string()) + .unwrap_or_else(|| self.ident.to_string()) } /// Return either the span of the ident or the span of the literal in the /// #[storage_prefix] attribute pub fn prefix_span(&self) -> proc_macro2::Span { - self.rename_as.as_ref().map(syn::LitStr::span).unwrap_or(self.ident.span()) + self.rename_as + .as_ref() + .map(syn::LitStr::span) + .unwrap_or_else(|| self.ident.span()) } pub fn try_from( @@ -672,8 +675,7 @@ impl StorageDef { let cfg_attrs = helper::get_item_cfg_attrs(&item.attrs); - let mut instances = vec![]; - instances.push(helper::check_type_def_gen(&item.generics, item.ident.span())?); + let instances = vec![helper::check_type_def_gen(&item.generics, item.ident.span())?]; let where_clause = item.generics.where_clause.clone(); let docs = get_doc_literals(&item.attrs); diff --git a/substrate/frame/support/procedural/src/pallet/parse/validate_unsigned.rs b/substrate/frame/support/procedural/src/pallet/parse/validate_unsigned.rs index a58671d976..18d5a2dc44 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/validate_unsigned.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/validate_unsigned.rs @@ -52,9 +52,10 @@ impl ValidateUnsignedDef { return Err(syn::Error::new(item.span(), msg)) } - let mut instances = vec![]; - instances.push(helper::check_pallet_struct_usage(&item.self_ty)?); - instances.push(helper::check_impl_gen(&item.generics, item.impl_token.span())?); + let instances = vec![ + helper::check_pallet_struct_usage(&item.self_ty)?, + helper::check_impl_gen(&item.generics, item.impl_token.span())?, + ]; Ok(ValidateUnsignedDef { index, instances }) } diff --git a/substrate/frame/support/procedural/src/storage/genesis_config/builder_def.rs b/substrate/frame/support/procedural/src/storage/genesis_config/builder_def.rs index 975791881d..29e2560bc1 100644 --- a/substrate/frame/support/procedural/src/storage/genesis_config/builder_def.rs +++ b/substrate/frame/support/procedural/src/storage/genesis_config/builder_def.rs @@ -49,7 +49,7 @@ impl BuilderDef { let mut data = None; if let Some(builder) = &line.build { - is_generic |= ext::expr_contains_ident(&builder, &def.module_runtime_generic); + is_generic |= ext::expr_contains_ident(builder, &def.module_runtime_generic); is_generic |= line.is_generic; data = Some(match &line.storage_type { @@ -138,7 +138,7 @@ impl BuilderDef { } if let Some(builder) = def.extra_genesis_build.as_ref() { - is_generic |= ext::expr_contains_ident(&builder, &def.module_runtime_generic); + is_generic |= ext::expr_contains_ident(builder, &def.module_runtime_generic); blocks.push(quote_spanned! { builder.span() => let extra_genesis_builder: fn(&Self) = #builder; diff --git a/substrate/frame/support/procedural/src/storage/instance_trait.rs b/substrate/frame/support/procedural/src/storage/instance_trait.rs index 14e9681120..e9df02e3dc 100644 --- a/substrate/frame/support/procedural/src/storage/instance_trait.rs +++ b/substrate/frame/support/procedural/src/storage/instance_trait.rs @@ -116,7 +116,7 @@ fn create_and_impl_instance_struct( let instance_trait = quote!( #scrate::traits::Instance ); let instance_struct = &instance_def.instance_struct; - let prefix = format!("{}{}", instance_def.prefix, def.crate_name.to_string()); + let prefix = format!("{}{}", instance_def.prefix, def.crate_name); let doc = &instance_def.doc; let index = instance_def.index; diff --git a/substrate/frame/support/procedural/src/storage/mod.rs b/substrate/frame/support/procedural/src/storage/mod.rs index b89e756334..756653f7ba 100644 --- a/substrate/frame/support/procedural/src/storage/mod.rs +++ b/substrate/frame/support/procedural/src/storage/mod.rs @@ -259,7 +259,7 @@ impl StorageLineDefExt { ) -> Self { let is_generic = match &storage_def.storage_type { StorageLineTypeDef::Simple(value) => - ext::type_contains_ident(&value, &def.module_runtime_generic), + ext::type_contains_ident(value, &def.module_runtime_generic), StorageLineTypeDef::Map(map) => ext::type_contains_ident(&map.key, &def.module_runtime_generic) || ext::type_contains_ident(&map.value, &def.module_runtime_generic), diff --git a/substrate/frame/support/src/hash.rs b/substrate/frame/support/src/hash.rs index 9ce0968351..9bdad6d9d5 100644 --- a/substrate/frame/support/src/hash.rs +++ b/substrate/frame/support/src/hash.rs @@ -101,7 +101,7 @@ impl StorageHasher for Twox64Concat { const METADATA: metadata::StorageHasher = metadata::StorageHasher::Twox64Concat; type Output = Vec; fn hash(x: &[u8]) -> Vec { - twox_64(x).iter().chain(x.into_iter()).cloned().collect::>() + twox_64(x).iter().chain(x.iter()).cloned().collect::>() } fn max_len() -> usize { K::max_encoded_len().saturating_add(8) @@ -123,7 +123,7 @@ impl StorageHasher for Blake2_128Concat { const METADATA: metadata::StorageHasher = metadata::StorageHasher::Blake2_128Concat; type Output = Vec; fn hash(x: &[u8]) -> Vec { - blake2_128(x).iter().chain(x.into_iter()).cloned().collect::>() + blake2_128(x).iter().chain(x.iter()).cloned().collect::>() } fn max_len() -> usize { K::max_encoded_len().saturating_add(16) diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 2d2944cc9a..3e84c009b5 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -105,7 +105,7 @@ use scale_info::TypeInfo; use sp_runtime::TypeId; /// A unified log target for support operations. -pub const LOG_TARGET: &'static str = "runtime::frame-support"; +pub const LOG_TARGET: &str = "runtime::frame-support"; /// A type that cannot be instantiated. #[derive(Encode, Decode, Debug, PartialEq, Eq, Clone, TypeInfo)] diff --git a/substrate/frame/support/src/storage/child.rs b/substrate/frame/support/src/storage/child.rs index 949df84e7e..e20d4fe0cd 100644 --- a/substrate/frame/support/src/storage/child.rs +++ b/substrate/frame/support/src/storage/child.rs @@ -50,7 +50,7 @@ pub fn get(child_info: &ChildInfo, key: &[u8]) -> Option { /// Return the value of the item in storage under `key`, or the type's default if there is no /// explicit entry. pub fn get_or_default(child_info: &ChildInfo, key: &[u8]) -> T { - get(child_info, key).unwrap_or_else(Default::default) + get(child_info, key).unwrap_or_default() } /// Return the value of the item in storage under `key`, or `default_value` if there is no @@ -90,7 +90,7 @@ pub fn take(child_info: &ChildInfo, key: &[u8]) -> Option /// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage, /// the default for its type. pub fn take_or_default(child_info: &ChildInfo, key: &[u8]) -> T { - take(child_info, key).unwrap_or_else(Default::default) + take(child_info, key).unwrap_or_default() } /// Return the value of the item in storage under `key`, or `default_value` if there is no diff --git a/substrate/frame/support/src/storage/generator/double_map.rs b/substrate/frame/support/src/storage/generator/double_map.rs index 12e1764bfb..16fcaf940c 100644 --- a/substrate/frame/support/src/storage/generator/double_map.rs +++ b/substrate/frame/support/src/storage/generator/double_map.rs @@ -461,7 +461,7 @@ where }, }; - let mut key2_material = G::Hasher2::reverse(&key_material); + let mut key2_material = G::Hasher2::reverse(key_material); let key2 = match K2::decode(&mut key2_material) { Ok(key2) => key2, Err(_) => { diff --git a/substrate/frame/support/src/storage/hashed.rs b/substrate/frame/support/src/storage/hashed.rs index a07db73c94..19c9d73be8 100644 --- a/substrate/frame/support/src/storage/hashed.rs +++ b/substrate/frame/support/src/storage/hashed.rs @@ -28,7 +28,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::get(&hash(key).as_ref()) + unhashed::get(hash(key).as_ref()) } /// Return the value of the item in storage under `key`, or the type's default if there is no @@ -39,7 +39,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::get_or_default(&hash(key).as_ref()) + unhashed::get_or_default(hash(key).as_ref()) } /// Return the value of the item in storage under `key`, or `default_value` if there is no @@ -50,7 +50,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::get_or(&hash(key).as_ref(), default_value) + unhashed::get_or(hash(key).as_ref(), default_value) } /// Return the value of the item in storage under `key`, or `default_value()` if there is no @@ -62,7 +62,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::get_or_else(&hash(key).as_ref(), default_value) + unhashed::get_or_else(hash(key).as_ref(), default_value) } /// Put `value` in storage under `key`. @@ -72,7 +72,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::put(&hash(key).as_ref(), value) + unhashed::put(hash(key).as_ref(), value) } /// Remove `key` from storage, returning its value if it had an explicit entry or `None` otherwise. @@ -82,7 +82,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::take(&hash(key).as_ref()) + unhashed::take(hash(key).as_ref()) } /// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage, @@ -93,7 +93,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::take_or_default(&hash(key).as_ref()) + unhashed::take_or_default(hash(key).as_ref()) } /// Return the value of the item in storage under `key`, or `default_value` if there is no @@ -104,7 +104,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::take_or(&hash(key).as_ref(), default_value) + unhashed::take_or(hash(key).as_ref(), default_value) } /// Return the value of the item in storage under `key`, or `default_value()` if there is no @@ -116,7 +116,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::take_or_else(&hash(key).as_ref(), default_value) + unhashed::take_or_else(hash(key).as_ref(), default_value) } /// Check to see if `key` has an explicit entry in storage. @@ -125,7 +125,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::exists(&hash(key).as_ref()) + unhashed::exists(hash(key).as_ref()) } /// Ensure `key` has no explicit entry in storage. @@ -134,7 +134,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::kill(&hash(key).as_ref()) + unhashed::kill(hash(key).as_ref()) } /// Get a Vec of bytes from storage. @@ -143,7 +143,7 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::get_raw(&hash(key).as_ref()) + unhashed::get_raw(hash(key).as_ref()) } /// Put a raw byte slice into storage. @@ -152,5 +152,5 @@ where HashFn: Fn(&[u8]) -> R, R: AsRef<[u8]>, { - unhashed::put_raw(&hash(key).as_ref(), value) + unhashed::put_raw(hash(key).as_ref(), value) } diff --git a/substrate/frame/support/src/storage/mod.rs b/substrate/frame/support/src/storage/mod.rs index 066422ad45..115f179d80 100644 --- a/substrate/frame/support/src/storage/mod.rs +++ b/substrate/frame/support/src/storage/mod.rs @@ -1038,7 +1038,7 @@ impl Iterator for ChildTriePrefixIterator { Some(self.previous_key.clone()) } else { sp_io::default_child_storage::next_key( - &self.child_info.storage_key(), + self.child_info.storage_key(), &self.previous_key, ) .filter(|n| n.starts_with(&self.prefix)) diff --git a/substrate/frame/support/src/storage/types/counted_map.rs b/substrate/frame/support/src/storage/types/counted_map.rs index 9c48267af8..a2160ede52 100644 --- a/substrate/frame/support/src/storage/types/counted_map.rs +++ b/substrate/frame/support/src/storage/types/counted_map.rs @@ -217,8 +217,7 @@ where /// Take the value under a key. pub fn take + Clone>(key: KeyArg) -> QueryKind::Query { - let removed_value = - ::Map::mutate_exists(key, |value| core::mem::replace(value, None)); + let removed_value = ::Map::mutate_exists(key, |value| value.take()); if removed_value.is_some() { CounterFor::::mutate(|value| value.saturating_dec()); } @@ -429,7 +428,7 @@ where if cfg!(feature = "no-metadata-docs") { vec![] } else { - vec![&"Counter for the related counted storage map"] + vec!["Counter for the related counted storage map"] }, entries, ); diff --git a/substrate/frame/support/src/storage/types/nmap.rs b/substrate/frame/support/src/storage/types/nmap.rs index aff32f2110..16dc30ea03 100755 --- a/substrate/frame/support/src/storage/types/nmap.rs +++ b/substrate/frame/support/src/storage/types/nmap.rs @@ -481,7 +481,7 @@ where modifier: QueryKind::METADATA, ty: StorageEntryType::Map { key: scale_info::meta_type::(), - hashers: Key::HASHER_METADATA.iter().cloned().collect(), + hashers: Key::HASHER_METADATA.to_vec(), value: scale_info::meta_type::(), }, default: OnEmpty::get().encode(), diff --git a/substrate/frame/support/src/storage/unhashed.rs b/substrate/frame/support/src/storage/unhashed.rs index 96bccc6ae0..adabc9c14a 100644 --- a/substrate/frame/support/src/storage/unhashed.rs +++ b/substrate/frame/support/src/storage/unhashed.rs @@ -38,7 +38,7 @@ pub fn get(key: &[u8]) -> Option { /// Return the value of the item in storage under `key`, or the type's default if there is no /// explicit entry. pub fn get_or_default(key: &[u8]) -> T { - get(key).unwrap_or_else(Default::default) + get(key).unwrap_or_default() } /// Return the value of the item in storage under `key`, or `default_value` if there is no @@ -70,7 +70,7 @@ pub fn take(key: &[u8]) -> Option { /// Remove `key` from storage, returning its value, or, if there was no explicit entry in storage, /// the default for its type. pub fn take_or_default(key: &[u8]) -> T { - take(key).unwrap_or_else(Default::default) + take(key).unwrap_or_default() } /// Return the value of the item in storage under `key`, or `default_value` if there is no diff --git a/substrate/frame/support/src/traits/dispatch.rs b/substrate/frame/support/src/traits/dispatch.rs index 250a31ebfb..443941bd8d 100644 --- a/substrate/frame/support/src/traits/dispatch.rs +++ b/substrate/frame/support/src/traits/dispatch.rs @@ -157,7 +157,7 @@ impl, R: EnsureOrigin> type Success = Either; fn try_origin(o: OuterOrigin) -> Result { L::try_origin(o) - .map_or_else(|o| R::try_origin(o).map(|o| Either::Right(o)), |o| Ok(Either::Left(o))) + .map_or_else(|o| R::try_origin(o).map(Either::Right), |o| Ok(Either::Left(o))) } #[cfg(feature = "runtime-benchmarks")] diff --git a/substrate/frame/support/src/traits/members.rs b/substrate/frame/support/src/traits/members.rs index f3c586b64a..8c69a2aacc 100644 --- a/substrate/frame/support/src/traits/members.rs +++ b/substrate/frame/support/src/traits/members.rs @@ -299,7 +299,7 @@ pub trait ChangeMembers { /// This resets any previous value of prime. fn set_members_sorted(new_members: &[AccountId], old_members: &[AccountId]) { let (incoming, outgoing) = Self::compute_members_diff_sorted(new_members, old_members); - Self::change_members_sorted(&incoming[..], &outgoing[..], &new_members); + Self::change_members_sorted(&incoming[..], &outgoing[..], new_members); } /// Compute diff between new and old members; they **must already be sorted**. diff --git a/substrate/frame/support/src/traits/metadata.rs b/substrate/frame/support/src/traits/metadata.rs index c76c53dbe8..d3dc57e1ee 100644 --- a/substrate/frame/support/src/traits/metadata.rs +++ b/substrate/frame/support/src/traits/metadata.rs @@ -161,7 +161,7 @@ impl sp_std::cmp::Ord for CrateVersion { impl sp_std::cmp::PartialOrd for CrateVersion { fn partial_cmp(&self, other: &Self) -> Option { - Some(::cmp(&self, other)) + Some(::cmp(self, other)) } } diff --git a/substrate/frame/support/src/traits/misc.rs b/substrate/frame/support/src/traits/misc.rs index 7575aa8c19..b67eac2fbe 100644 --- a/substrate/frame/support/src/traits/misc.rs +++ b/substrate/frame/support/src/traits/misc.rs @@ -25,9 +25,9 @@ use sp_runtime::{traits::Block as BlockT, DispatchError}; use sp_std::{cmp::Ordering, prelude::*}; #[doc(hidden)] -pub const DEFENSIVE_OP_PUBLIC_ERROR: &'static str = "a defensive failure has been triggered; please report the block number at https://github.com/paritytech/substrate/issues"; +pub const DEFENSIVE_OP_PUBLIC_ERROR: &str = "a defensive failure has been triggered; please report the block number at https://github.com/paritytech/substrate/issues"; #[doc(hidden)] -pub const DEFENSIVE_OP_INTERNAL_ERROR: &'static str = "Defensive failure has been triggered!"; +pub const DEFENSIVE_OP_INTERNAL_ERROR: &str = "Defensive failure has been triggered!"; /// Generic function to mark an execution path as ONLY defensive. /// diff --git a/substrate/frame/support/src/traits/stored_map.rs b/substrate/frame/support/src/traits/stored_map.rs index 3c3ff2eb0e..2aae88096e 100644 --- a/substrate/frame/support/src/traits/stored_map.rs +++ b/substrate/frame/support/src/traits/stored_map.rs @@ -101,7 +101,7 @@ impl< } fn remove(k: &K) -> Result<(), DispatchError> { if S::contains_key(&k) { - L::killed(&k)?; + L::killed(k)?; S::remove(k); } Ok(()) diff --git a/substrate/frame/support/src/traits/tokens/currency.rs b/substrate/frame/support/src/traits/tokens/currency.rs index d4b5c0c184..9a1634fd89 100644 --- a/substrate/frame/support/src/traits/tokens/currency.rs +++ b/substrate/frame/support/src/traits/tokens/currency.rs @@ -83,7 +83,7 @@ pub trait Currency { /// This is just the same as burning and issuing the same amount and has no effect on the /// total issuance. fn pair(amount: Self::Balance) -> (Self::PositiveImbalance, Self::NegativeImbalance) { - (Self::burn(amount.clone()), Self::issue(amount)) + (Self::burn(amount), Self::issue(amount)) } /// The 'free' balance of a given account. diff --git a/substrate/frame/support/src/traits/tokens/fungible.rs b/substrate/frame/support/src/traits/tokens/fungible.rs index 7422a9d651..90aadb6d8d 100644 --- a/substrate/frame/support/src/traits/tokens/fungible.rs +++ b/substrate/frame/support/src/traits/tokens/fungible.rs @@ -92,7 +92,7 @@ pub trait Mutate: Inspect { let extra = Self::can_withdraw(&source, amount).into_result()?; // As we first burn and then mint, we don't need to check if `mint` fits into the supply. // If we can withdraw/burn it, we can also mint it again. - Self::can_deposit(&dest, amount.saturating_add(extra), false).into_result()?; + Self::can_deposit(dest, amount.saturating_add(extra), false).into_result()?; let actual = Self::burn_from(source, amount)?; debug_assert!( actual == amount.saturating_add(extra), diff --git a/substrate/frame/support/src/traits/tokens/fungible/balanced.rs b/substrate/frame/support/src/traits/tokens/fungible/balanced.rs index 196f3a3575..ed9c3a1afa 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/balanced.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/balanced.rs @@ -165,7 +165,7 @@ pub trait Unbalanced: Inspect { ) -> Result { let old_balance = Self::balance(who); let (mut new_balance, mut amount) = if old_balance < amount { - Err(TokenError::NoFunds)? + return Err(TokenError::NoFunds.into()) } else { (old_balance - amount, amount) }; @@ -225,7 +225,7 @@ pub trait Unbalanced: Inspect { let old_balance = Self::balance(who); let new_balance = old_balance.checked_add(&amount).ok_or(ArithmeticError::Overflow)?; if new_balance < Self::minimum_balance() { - Err(TokenError::BelowMinimum)? + return Err(TokenError::BelowMinimum.into()) } if old_balance != new_balance { Self::set_balance(who, new_balance)?; diff --git a/substrate/frame/support/src/traits/tokens/fungibles.rs b/substrate/frame/support/src/traits/tokens/fungibles.rs index 2abadf0376..dab50d5696 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles.rs @@ -145,7 +145,7 @@ pub trait Mutate: Inspect { let extra = Self::can_withdraw(asset, &source, amount).into_result()?; // As we first burn and then mint, we don't need to check if `mint` fits into the supply. // If we can withdraw/burn it, we can also mint it again. - Self::can_deposit(asset, &dest, amount.saturating_add(extra), false).into_result()?; + Self::can_deposit(asset, dest, amount.saturating_add(extra), false).into_result()?; let actual = Self::burn_from(asset, source, amount)?; debug_assert!( actual == amount.saturating_add(extra), diff --git a/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs b/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs index e07d45cc47..a75832e4c4 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/balanced.rs @@ -186,7 +186,7 @@ pub trait Unbalanced: Inspect { ) -> Result { let old_balance = Self::balance(asset, who); let (mut new_balance, mut amount) = if old_balance < amount { - Err(TokenError::NoFunds)? + return Err(TokenError::NoFunds.into()) } else { (old_balance - amount, amount) }; @@ -251,7 +251,7 @@ pub trait Unbalanced: Inspect { let old_balance = Self::balance(asset, who); let new_balance = old_balance.checked_add(&amount).ok_or(ArithmeticError::Overflow)?; if new_balance < Self::minimum_balance(asset) { - Err(TokenError::BelowMinimum)? + return Err(TokenError::BelowMinimum.into()) } if old_balance != new_balance { Self::set_balance(asset, who, new_balance)?; diff --git a/substrate/frame/support/src/weights.rs b/substrate/frame/support/src/weights.rs index 5b4a13e7f9..292c7d3e91 100644 --- a/substrate/frame/support/src/weights.rs +++ b/substrate/frame/support/src/weights.rs @@ -355,7 +355,7 @@ impl PostDispatchInfo { /// Extract the actual weight from a dispatch result if any or fall back to the default weight. pub fn extract_actual_weight(result: &DispatchResultWithPostInfo, info: &DispatchInfo) -> Weight { match result { - Ok(post_info) => &post_info, + Ok(post_info) => post_info, Err(err) => &err.post_info, } .calc_actual_weight(info) @@ -432,7 +432,7 @@ where impl WeighData for Weight { fn weigh_data(&self, _: T) -> Weight { - return *self + *self } } @@ -450,7 +450,7 @@ impl PaysFee for Weight { impl WeighData for (Weight, DispatchClass, Pays) { fn weigh_data(&self, _: T) -> Weight { - return self.0 + self.0 } } @@ -468,7 +468,7 @@ impl PaysFee for (Weight, DispatchClass, Pays) { impl WeighData for (Weight, DispatchClass) { fn weigh_data(&self, _: T) -> Weight { - return self.0 + self.0 } } @@ -486,7 +486,7 @@ impl PaysFee for (Weight, DispatchClass) { impl WeighData for (Weight, Pays) { fn weigh_data(&self, _: T) -> Weight { - return self.0 + self.0 } } diff --git a/substrate/frame/system/src/extensions/check_non_zero_sender.rs b/substrate/frame/system/src/extensions/check_non_zero_sender.rs index f517201fbe..9a6c4007b3 100644 --- a/substrate/frame/system/src/extensions/check_non_zero_sender.rs +++ b/substrate/frame/system/src/extensions/check_non_zero_sender.rs @@ -82,7 +82,7 @@ where _info: &DispatchInfoOf, _len: usize, ) -> TransactionValidity { - if who.using_encoded(|d| d.into_iter().all(|x| *x == 0)) { + if who.using_encoded(|d| d.iter().all(|x| *x == 0)) { return Err(TransactionValidityError::Invalid(InvalidTransaction::BadSigner)) } Ok(ValidTransaction::default()) diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index 774139054d..b59c36ecb5 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -188,7 +188,7 @@ where len: usize, ) -> Result<(), TransactionValidityError> { if info.class == DispatchClass::Mandatory { - Err(InvalidTransaction::MandatoryDispatch)? + return Err(InvalidTransaction::MandatoryDispatch.into()) } Self::do_pre_dispatch(info, len) } @@ -201,7 +201,7 @@ where len: usize, ) -> TransactionValidity { if info.class == DispatchClass::Mandatory { - Err(InvalidTransaction::MandatoryDispatch)? + return Err(InvalidTransaction::MandatoryDispatch.into()) } Self::do_validate(info, len) } @@ -234,7 +234,7 @@ where // extrinsics that result in error. if let (DispatchClass::Mandatory, Err(e)) = (info.class, result) { log::error!(target: "runtime::system", "Bad mandatory: {:?}", e); - Err(InvalidTransaction::BadMandatory)? + return Err(InvalidTransaction::BadMandatory.into()) } let unspent = post_info.calc_unspent(info); diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 14e67cfcd8..ba494dfbd9 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -456,7 +456,7 @@ pub mod pallet { pub fn kill_storage(origin: OriginFor, keys: Vec) -> DispatchResultWithPostInfo { ensure_root(origin)?; for key in &keys { - storage::unhashed::kill(&key); + storage::unhashed::kill(key); } Ok(().into()) } @@ -833,7 +833,7 @@ impl< Some(account) => account.clone(), None => zero_account_id, }; - O::from(RawOrigin::Signed(first_member.clone())) + O::from(RawOrigin::Signed(first_member)) } } @@ -1196,8 +1196,7 @@ impl Pallet { } let phase = ExecutionPhase::::get().unwrap_or_default(); - let event = - EventRecord { phase, event, topics: topics.iter().cloned().collect::>() }; + let event = EventRecord { phase, event, topics: topics.to_vec() }; // Index of the to be added event. let event_idx = { @@ -1522,16 +1521,16 @@ impl Pallet { /// of the old and new runtime has the same spec name and that the spec version is increasing. pub fn can_set_code(code: &[u8]) -> Result<(), sp_runtime::DispatchError> { let current_version = T::Version::get(); - let new_version = sp_io::misc::runtime_version(&code) + let new_version = sp_io::misc::runtime_version(code) .and_then(|v| RuntimeVersion::decode(&mut &v[..]).ok()) - .ok_or_else(|| Error::::FailedToExtractRuntimeVersion)?; + .ok_or(Error::::FailedToExtractRuntimeVersion)?; if new_version.spec_name != current_version.spec_name { - Err(Error::::InvalidSpecName)? + return Err(Error::::InvalidSpecName.into()) } if new_version.spec_version <= current_version.spec_version { - Err(Error::::SpecVersionNeedsToIncrease)? + return Err(Error::::SpecVersionNeedsToIncrease.into()) } Ok(()) diff --git a/substrate/frame/system/src/limits.rs b/substrate/frame/system/src/limits.rs index 4942a5dace..d3c108afb6 100644 --- a/substrate/frame/system/src/limits.rs +++ b/substrate/frame/system/src/limits.rs @@ -217,7 +217,7 @@ impl BlockWeights { /// Verifies correctness of this `BlockWeights` object. pub fn validate(self) -> ValidationResult { fn or_max(w: Option) -> Weight { - w.unwrap_or_else(|| Weight::max_value()) + w.unwrap_or_else(Weight::max_value) } let mut error = ValidationErrors::default(); @@ -246,7 +246,7 @@ impl BlockWeights { ); // Max extrinsic should not be 0 error_assert!( - weights.max_extrinsic.unwrap_or_else(|| Weight::max_value()) > 0, + weights.max_extrinsic.unwrap_or_else(Weight::max_value) > 0, &mut error, "[{:?}] {:?} (max_extrinsic) must not be 0. Check base cost and average initialization cost.", class, weights.max_extrinsic, diff --git a/substrate/frame/system/src/migrations/mod.rs b/substrate/frame/system/src/migrations/mod.rs index 358ba55b7c..872cf389d2 100644 --- a/substrate/frame/system/src/migrations/mod.rs +++ b/substrate/frame/system/src/migrations/mod.rs @@ -89,7 +89,7 @@ frame_support::generate_storage_alias!( pub fn migrate_from_single_u8_to_triple_ref_count() -> Weight { let mut translated: usize = 0; >::translate::<(T::Index, u8, T::AccountData), _>(|_key, (nonce, rc, data)| { - translated = translated + 1; + translated += 1; Some(AccountInfo { nonce, consumers: rc as RefCount, providers: 1, sufficients: 0, data }) }); log::info!( @@ -107,7 +107,7 @@ pub fn migrate_from_single_to_triple_ref_count() -> Weight { let mut translated: usize = 0; >::translate::<(T::Index, RefCount, T::AccountData), _>( |_key, (nonce, consumers, data)| { - translated = translated + 1; + translated += 1; Some(AccountInfo { nonce, consumers, providers: 1, sufficients: 0, data }) }, ); @@ -125,7 +125,7 @@ pub fn migrate_from_dual_to_triple_ref_count() -> Weight { let mut translated: usize = 0; >::translate::<(T::Index, RefCount, RefCount, T::AccountData), _>( |_key, (nonce, consumers, providers, data)| { - translated = translated + 1; + translated += 1; Some(AccountInfo { nonce, consumers, providers, sufficients: 0, data }) }, ); diff --git a/substrate/frame/system/src/offchain.rs b/substrate/frame/system/src/offchain.rs index bf52ab8e37..86440188a7 100644 --- a/substrate/frame/system/src/offchain.rs +++ b/substrate/frame/system/src/offchain.rs @@ -88,7 +88,7 @@ where call: >::OverarchingCall, signature: Option<::SignaturePayload>, ) -> Result<(), ()> { - let xt = T::Extrinsic::new(call.into(), signature).ok_or(())?; + let xt = T::Extrinsic::new(call, signature).ok_or(())?; sp_io::offchain::submit_transaction(xt.encode()) } @@ -163,7 +163,7 @@ impl, X> Signer keystore_accounts.map(|account| account.public).collect(); Box::new( - keys.into_iter() + keys.iter() .enumerate() .map(|(index, key)| { let account_id = key.clone().into_account(); diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index d8bfb405e5..c75a0ac976 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -229,7 +229,7 @@ pub mod pallet { let data = (*inherent_data).saturated_into::(); let next_time = cmp::max(data, Self::now() + T::MinimumPeriod::get()); - Some(Call::set { now: next_time.into() }) + Some(Call::set { now: next_time }) } fn check_inherent( @@ -240,7 +240,7 @@ pub mod pallet { sp_timestamp::Timestamp::new(30 * 1000); let t: u64 = match call { - Call::set { ref now } => now.clone().saturated_into::(), + Call::set { ref now } => (*now).saturated_into::(), _ => return Ok(()), }; diff --git a/substrate/frame/tips/src/benchmarking.rs b/substrate/frame/tips/src/benchmarking.rs index 7abee6192f..190ef60f3b 100644 --- a/substrate/frame/tips/src/benchmarking.rs +++ b/substrate/frame/tips/src/benchmarking.rs @@ -131,7 +131,7 @@ benchmarks! { let reason_hash = T::Hashing::hash(&reason[..]); let hash = T::Hashing::hash_of(&(&reason_hash, &beneficiary)); ensure!(Tips::::contains_key(hash), "tip does not exist"); - create_tips::(t - 1, hash.clone(), value)?; + create_tips::(t - 1, hash, value)?; let caller = account("member", t - 1, SEED); // Whitelist caller account from further DB operations. let caller_key = frame_system::Account::::hashed_key_for(&caller); @@ -159,7 +159,7 @@ benchmarks! { let hash = T::Hashing::hash_of(&(&reason_hash, &beneficiary)); ensure!(Tips::::contains_key(hash), "tip does not exist"); - create_tips::(t, hash.clone(), value)?; + create_tips::(t, hash, value)?; let caller = account("caller", t, SEED); // Whitelist caller account from further DB operations. diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index 4b7d78b90b..b9868dac43 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -340,7 +340,7 @@ pub mod pallet { let hash = T::Hashing::hash_of(&(&reason_hash, &who)); Reasons::::insert(&reason_hash, &reason); - Self::deposit_event(Event::NewTip { tip_hash: hash.clone() }); + Self::deposit_event(Event::NewTip { tip_hash: hash }); let tips = vec![(tipper.clone(), tip_value)]; let tip = OpenTip { reason: reason_hash, @@ -390,7 +390,7 @@ pub mod pallet { let mut tip = Tips::::get(hash).ok_or(Error::::UnknownTip)?; if Self::insert_tip_and_check_closing(&mut tip, tipper, tip_value) { - Self::deposit_event(Event::TipClosing { tip_hash: hash.clone() }); + Self::deposit_event(Event::TipClosing { tip_hash: hash }); } Tips::::insert(&hash, tip); Ok(()) diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs index 9eafc43fc2..394696cc18 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs @@ -127,15 +127,12 @@ where let converted_fee = CON::to_asset_balance(fee, asset_id) .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment))? .max(min_converted_fee); - let can_withdraw = >::can_withdraw( - asset_id.into(), - who, - converted_fee, - ); + let can_withdraw = + >::can_withdraw(asset_id, who, converted_fee); if !matches!(can_withdraw, WithdrawConsequence::Success) { return Err(InvalidTransaction::Payment.into()) } - >::withdraw(asset_id.into(), who, converted_fee) + >::withdraw(asset_id, who, converted_fee) .map_err(|_| TransactionValidityError::from(InvalidTransaction::Payment)) } @@ -153,7 +150,7 @@ where ) -> Result<(), TransactionValidityError> { let min_converted_fee = if corrected_fee.is_zero() { Zero::zero() } else { One::one() }; // Convert the corrected fee into the asset used for payment. - let converted_fee = CON::to_asset_balance(corrected_fee, paid.asset().into()) + let converted_fee = CON::to_asset_balance(corrected_fee, paid.asset()) .map_err(|_| -> TransactionValidityError { InvalidTransaction::Payment.into() })? .max(min_converted_fee); // Calculate how much refund we should return. diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index 1462faaa07..45c8b8f479 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -186,10 +186,8 @@ where let weights = T::BlockWeights::get(); // the computed ratio is only among the normal class. - let normal_max_weight = weights - .get(DispatchClass::Normal) - .max_total - .unwrap_or_else(|| weights.max_block); + let normal_max_weight = + weights.get(DispatchClass::Normal).max_total.unwrap_or(weights.max_block); let current_block_weight = >::block_weight(); let normal_block_weight = *current_block_weight.get(DispatchClass::Normal).min(&normal_max_weight); diff --git a/substrate/frame/transaction-payment/src/payment.rs b/substrate/frame/transaction-payment/src/payment.rs index 5b4a613102..3a5fad0d66 100644 --- a/substrate/frame/transaction-payment/src/payment.rs +++ b/substrate/frame/transaction-payment/src/payment.rs @@ -132,7 +132,7 @@ where // refund to the the account that paid the fees. If this fails, the // account might have dropped below the existential balance. In // that case we don't refund anything. - let refund_imbalance = C::deposit_into_existing(&who, refund_amount) + let refund_imbalance = C::deposit_into_existing(who, refund_amount) .unwrap_or_else(|_| C::PositiveImbalance::zero()); // merge the imbalance caused by paying the fees and refunding parts of it again. let adjusted_paid = paid diff --git a/substrate/frame/transaction-storage/src/lib.rs b/substrate/frame/transaction-storage/src/lib.rs index e9aa786766..a63b31f2f1 100644 --- a/substrate/frame/transaction-storage/src/lib.rs +++ b/substrate/frame/transaction-storage/src/lib.rs @@ -192,8 +192,8 @@ pub mod pallet { let root = sp_io::trie::blake2_256_ordered_root(chunks, sp_runtime::StateVersion::V1); let content_hash = sp_io::hashing::blake2_256(&data); - let extrinsic_index = >::extrinsic_index() - .ok_or_else(|| Error::::BadContext)?; + let extrinsic_index = + >::extrinsic_index().ok_or(Error::::BadContext)?; sp_io::transaction_index::index(extrinsic_index, data.len() as u32, content_hash); let mut index = 0; @@ -287,13 +287,12 @@ pub mod pallet { Ok(index) => index, Err(index) => index, }; - let info = - infos.get(index).ok_or_else(|| Error::::MissingStateData)?.clone(); + let info = infos.get(index).ok_or(Error::::MissingStateData)?.clone(); let chunks = num_chunks(info.size); let prev_chunks = info.block_chunks - chunks; (info, selected_chunk_index - prev_chunks) }, - None => Err(Error::::MissingStateData)?, + None => return Err(Error::::MissingStateData.into()), }; ensure!( sp_io::trie::blake2_256_verify_proof( diff --git a/substrate/frame/uniques/src/benchmarking.rs b/substrate/frame/uniques/src/benchmarking.rs index 19d3dfac6e..b743ca1291 100644 --- a/substrate/frame/uniques/src/benchmarking.rs +++ b/substrate/frame/uniques/src/benchmarking.rs @@ -176,7 +176,7 @@ benchmarks_instance_pallet! { let witness = Class::::get(class).unwrap().destroy_witness(); }: _(SystemOrigin::Signed(caller), class, witness) verify { - assert_last_event::(Event::Destroyed { class: class }.into()); + assert_last_event::(Event::Destroyed { class }.into()); } mint { @@ -216,7 +216,7 @@ benchmarks_instance_pallet! { caller_lookup.clone(), caller_lookup.clone(), caller_lookup.clone(), - caller_lookup.clone(), + caller_lookup, true, false, )?; @@ -268,7 +268,7 @@ benchmarks_instance_pallet! { let target_lookup = T::Lookup::unlookup(target.clone()); T::Currency::make_free_balance_be(&target, T::Currency::minimum_balance()); let origin = SystemOrigin::Signed(target.clone()).into(); - Uniques::::set_accept_ownership(origin, Some(class.clone()))?; + Uniques::::set_accept_ownership(origin, Some(class))?; }: _(SystemOrigin::Signed(caller), class, target_lookup) verify { assert_last_event::(Event::OwnerChanged { class, new_owner: target }.into()); @@ -279,7 +279,7 @@ benchmarks_instance_pallet! { let target0 = T::Lookup::unlookup(account("target", 0, SEED)); let target1 = T::Lookup::unlookup(account("target", 1, SEED)); let target2 = T::Lookup::unlookup(account("target", 2, SEED)); - }: _(SystemOrigin::Signed(caller), class, target0.clone(), target1.clone(), target2.clone()) + }: _(SystemOrigin::Signed(caller), class, target0, target1, target2) verify { assert_last_event::(Event::TeamChanged{ class, @@ -297,7 +297,7 @@ benchmarks_instance_pallet! { owner: caller_lookup.clone(), issuer: caller_lookup.clone(), admin: caller_lookup.clone(), - freezer: caller_lookup.clone(), + freezer: caller_lookup, free_holding: true, is_frozen: false, }; @@ -390,7 +390,7 @@ benchmarks_instance_pallet! { let caller: T::AccountId = whitelisted_caller(); T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); let class = T::Helper::class(0); - }: _(SystemOrigin::Signed(caller.clone()), Some(class.clone())) + }: _(SystemOrigin::Signed(caller.clone()), Some(class)) verify { assert_last_event::(Event::OwnershipAcceptanceChanged { who: caller, diff --git a/substrate/frame/uniques/src/functions.rs b/substrate/frame/uniques/src/functions.rs index 8b874997f2..ea9eecd767 100644 --- a/substrate/frame/uniques/src/functions.rs +++ b/substrate/frame/uniques/src/functions.rs @@ -73,7 +73,7 @@ impl, I: 'static> Pallet { owner: owner.clone(), issuer: admin.clone(), admin: admin.clone(), - freezer: admin.clone(), + freezer: admin, total_deposit: deposit, free_holding, instances: 0, @@ -135,7 +135,7 @@ impl, I: 'static> Pallet { Class::::try_mutate(&class, |maybe_class_details| -> DispatchResult { let class_details = maybe_class_details.as_mut().ok_or(Error::::UnknownClass)?; - with_details(&class_details)?; + with_details(class_details)?; let instances = class_details.instances.checked_add(1).ok_or(ArithmeticError::Overflow)?; @@ -171,7 +171,7 @@ impl, I: 'static> Pallet { maybe_class_details.as_mut().ok_or(Error::::UnknownClass)?; let details = Asset::::get(&class, &instance).ok_or(Error::::UnknownClass)?; - with_details(&class_details, &details)?; + with_details(class_details, &details)?; // Return the deposit. T::Currency::unreserve(&class_details.owner, details.deposit); diff --git a/substrate/frame/uniques/src/impl_nonfungibles.rs b/substrate/frame/uniques/src/impl_nonfungibles.rs index 89b95fb770..492befc469 100644 --- a/substrate/frame/uniques/src/impl_nonfungibles.rs +++ b/substrate/frame/uniques/src/impl_nonfungibles.rs @@ -93,12 +93,12 @@ impl, I: 'static> Create<::AccountId> for Pallet admin: &T::AccountId, ) -> DispatchResult { Self::do_create_class( - class.clone(), + *class, who.clone(), admin.clone(), T::ClassDeposit::get(), false, - Event::Created { class: class.clone(), creator: who.clone(), owner: admin.clone() }, + Event::Created { class: *class, creator: who.clone(), owner: admin.clone() }, ) } } @@ -125,7 +125,7 @@ impl, I: 'static> Mutate<::AccountId> for Pallet instance: &Self::InstanceId, who: &T::AccountId, ) -> DispatchResult { - Self::do_mint(class.clone(), instance.clone(), who.clone(), |_| Ok(())) + Self::do_mint(*class, *instance, who.clone(), |_| Ok(())) } fn burn( @@ -133,10 +133,10 @@ impl, I: 'static> Mutate<::AccountId> for Pallet instance: &Self::InstanceId, maybe_check_owner: Option<&T::AccountId>, ) -> DispatchResult { - Self::do_burn(class.clone(), instance.clone(), |_, d| { + Self::do_burn(*class, *instance, |_, d| { if let Some(check_owner) = maybe_check_owner { if &d.owner != check_owner { - Err(Error::::NoPermission)?; + return Err(Error::::NoPermission.into()) } } Ok(()) @@ -150,7 +150,7 @@ impl, I: 'static> Transfer for Pallet { instance: &Self::InstanceId, destination: &T::AccountId, ) -> DispatchResult { - Self::do_transfer(class.clone(), instance.clone(), destination.clone(), |_, _| Ok(())) + Self::do_transfer(*class, *instance, destination.clone(), |_, _| Ok(())) } } diff --git a/substrate/frame/uniques/src/lib.rs b/substrate/frame/uniques/src/lib.rs index d999acc4c9..a360a02ebc 100644 --- a/substrate/frame/uniques/src/lib.rs +++ b/substrate/frame/uniques/src/lib.rs @@ -720,7 +720,7 @@ pub mod pallet { Class::::try_mutate(class, |maybe_details| { let details = maybe_details.as_mut().ok_or(Error::::UnknownClass)?; - ensure!(&origin == &details.freezer, Error::::NoPermission); + ensure!(origin == details.freezer, Error::::NoPermission); details.is_frozen = true; @@ -744,7 +744,7 @@ pub mod pallet { Class::::try_mutate(class, |maybe_details| { let details = maybe_details.as_mut().ok_or(Error::::UnknownClass)?; - ensure!(&origin == &details.admin, Error::::NoPermission); + ensure!(origin == details.admin, Error::::NoPermission); details.is_frozen = false; @@ -778,7 +778,7 @@ pub mod pallet { Class::::try_mutate(class, |maybe_details| { let details = maybe_details.as_mut().ok_or(Error::::UnknownClass)?; - ensure!(&origin == &details.owner, Error::::NoPermission); + ensure!(origin == details.owner, Error::::NoPermission); if details.owner == owner { return Ok(()) } @@ -827,7 +827,7 @@ pub mod pallet { Class::::try_mutate(class, |maybe_details| { let details = maybe_details.as_mut().ok_or(Error::::UnknownClass)?; - ensure!(&origin == &details.owner, Error::::NoPermission); + ensure!(origin == details.owner, Error::::NoPermission); details.issuer = issuer.clone(); details.admin = admin.clone(); @@ -867,7 +867,7 @@ pub mod pallet { Asset::::get(&class, &instance).ok_or(Error::::UnknownClass)?; if let Some(check) = maybe_check { - let permitted = &check == &class_details.admin || &check == &details.owner; + let permitted = check == class_details.admin || check == details.owner; ensure!(permitted, Error::::NoPermission); } @@ -916,7 +916,7 @@ pub mod pallet { let mut details = Asset::::get(&class, &instance).ok_or(Error::::UnknownClass)?; if let Some(check) = maybe_check { - let permitted = &check == &class_details.admin || &check == &details.owner; + let permitted = check == class_details.admin || check == details.owner; ensure!(permitted, Error::::NoPermission); } let maybe_check_delegate = maybe_check_delegate.map(T::Lookup::lookup).transpose()?; diff --git a/substrate/frame/utility/src/benchmarking.rs b/substrate/frame/utility/src/benchmarking.rs index 402128d005..27f346f13f 100644 --- a/substrate/frame/utility/src/benchmarking.rs +++ b/substrate/frame/utility/src/benchmarking.rs @@ -70,7 +70,7 @@ benchmarks! { let call = Box::new(frame_system::Call::remark { remark: vec![] }.into()); let origin: T::Origin = RawOrigin::Signed(caller).into(); let pallets_origin: ::PalletsOrigin = origin.caller().clone(); - let pallets_origin = Into::::into(pallets_origin.clone()); + let pallets_origin = Into::::into(pallets_origin); }: _(RawOrigin::Root, Box::new(pallets_origin), call) impl_benchmark_test_suite!(Pallet, crate::tests::new_test_ext(), crate::tests::Test); diff --git a/substrate/frame/vesting/src/benchmarking.rs b/substrate/frame/vesting/src/benchmarking.rs index 1693fdd3f1..2b8150e995 100644 --- a/substrate/frame/vesting/src/benchmarking.rs +++ b/substrate/frame/vesting/src/benchmarking.rs @@ -72,7 +72,7 @@ fn add_vesting_schedules( T::Currency::make_free_balance_be(&source, BalanceOf::::max_value()); } - Ok(total_locked.into()) + Ok(total_locked) } benchmarks! { @@ -91,7 +91,7 @@ benchmarks! { assert_eq!(System::::block_number(), T::BlockNumber::zero()); assert_eq!( Vesting::::vesting_balance(&caller), - Some(expected_balance.into()), + Some(expected_balance), "Vesting schedule not added", ); }: vest(RawOrigin::Signed(caller.clone())) @@ -99,7 +99,7 @@ benchmarks! { // Nothing happened since everything is still vested. assert_eq!( Vesting::::vesting_balance(&caller), - Some(expected_balance.into()), + Some(expected_balance), "Vesting schedule was removed", ); } @@ -156,7 +156,7 @@ benchmarks! { // Nothing happened since everything is still vested. assert_eq!( Vesting::::vesting_balance(&other), - Some(expected_balance.into()), + Some(expected_balance), "Vesting schedule was removed", ); } @@ -260,7 +260,7 @@ benchmarks! { ); assert_eq!( Vesting::::vesting_balance(&target), - Some(expected_balance.into()), + Some(expected_balance), "Lock not correctly updated", ); } @@ -274,7 +274,7 @@ benchmarks! { // Give target existing locks. add_locks::(&caller, l as u8); // Add max vesting schedules. - let expected_balance = add_vesting_schedules::(caller_lookup.clone(), s)?; + let expected_balance = add_vesting_schedules::(caller_lookup, s)?; // Schedules are not vesting at block 0. assert_eq!(System::::block_number(), T::BlockNumber::zero()); @@ -324,7 +324,7 @@ benchmarks! { // Give target other locks. add_locks::(&caller, l as u8); // Add max vesting schedules. - let total_transferred = add_vesting_schedules::(caller_lookup.clone(), s)?; + let total_transferred = add_vesting_schedules::(caller_lookup, s)?; // Go to about half way through all the schedules duration. (They all start at 1, and have a duration of 20 or 21). System::::set_block_number(11u32.into()); diff --git a/substrate/frame/vesting/src/lib.rs b/substrate/frame/vesting/src/lib.rs index 13841a0443..23b7d23134 100644 --- a/substrate/frame/vesting/src/lib.rs +++ b/substrate/frame/vesting/src/lib.rs @@ -121,10 +121,10 @@ impl VestingAction { } /// Pick the schedules that this action dictates should continue vesting undisturbed. - fn pick_schedules<'a, T: Config>( - &'a self, + fn pick_schedules( + &self, schedules: Vec, T::BlockNumber>>, - ) -> impl Iterator, T::BlockNumber>> + 'a { + ) -> impl Iterator, T::BlockNumber>> + '_ { schedules.into_iter().enumerate().filter_map(move |(index, schedule)| { if self.should_remove(index) { None @@ -710,7 +710,7 @@ where let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), VestingAction::Passive)?; - Self::write_vesting(&who, schedules)?; + Self::write_vesting(who, schedules)?; Self::write_lock(who, locked_now); Ok(()) @@ -744,7 +744,7 @@ where let (schedules, locked_now) = Self::exec_action(schedules.to_vec(), remove_action)?; - Self::write_vesting(&who, schedules)?; + Self::write_vesting(who, schedules)?; Self::write_lock(who, locked_now); Ok(()) } diff --git a/substrate/frame/whitelist/src/benchmarking.rs b/substrate/frame/whitelist/src/benchmarking.rs index 50809ddef7..cafd166881 100644 --- a/substrate/frame/whitelist/src/benchmarking.rs +++ b/substrate/frame/whitelist/src/benchmarking.rs @@ -69,7 +69,7 @@ benchmarks! { let origin = T::DispatchWhitelistedOrigin::successful_origin(); // NOTE: we remove `10` because we need some bytes to encode the variants and vec length let remark_len = >::MaxSize::get() - 10; - let remark = sp_std::vec![1_8; remark_len as usize]; + let remark = sp_std::vec![1u8; remark_len as usize]; let call: ::Call = frame_system::Call::remark { remark }.into(); let call_weight = call.get_dispatch_info().weight; diff --git a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs index 2301f53159..b031c0f8bb 100644 --- a/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/decl_runtime_apis.rs @@ -188,7 +188,7 @@ fn generate_native_call_generators(decl: &ItemTrait) -> Result { // Generate a native call generator for each function of the given trait. for fn_ in fns { - let params = extract_parameter_names_types_and_borrows(&fn_, AllowSelfRefInParameters::No)?; + let params = extract_parameter_names_types_and_borrows(fn_, AllowSelfRefInParameters::No)?; let trait_fn_name = &fn_.ident; let function_name_str = fn_.ident.to_string(); let fn_name = generate_native_call_generator_fn_name(&fn_.ident); @@ -336,7 +336,7 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result { // Generate a native call generator for each function of the given trait. for (attrs, fn_) in fns { let trait_name = &decl.ident; - let trait_fn_name = prefix_function_with_trait(&trait_name, &fn_.ident); + let trait_fn_name = prefix_function_with_trait(trait_name, &fn_.ident); let fn_name = generate_call_api_at_fn_name(&fn_.ident); let attrs = remove_supported_attributes(&mut attrs.clone()); @@ -360,7 +360,7 @@ fn generate_call_api_at_calls(decl: &ItemTrait) -> Result { let mut renames = Vec::new(); if let Some((_, a)) = attrs.iter().find(|a| a.0 == &RENAMED_ATTRIBUTE) { let (old_name, version) = parse_renamed_attribute(a)?; - renames.push((version, prefix_function_with_trait(&trait_name, &old_name))); + renames.push((version, prefix_function_with_trait(trait_name, &old_name))); } renames.sort_by(|l, r| r.cmp(l)); @@ -582,7 +582,7 @@ impl<'a> ToClientSideDecl<'a> { Vec::new() }, }; - let name = generate_method_runtime_api_impl_name(&self.trait_, &method.sig.ident); + let name = generate_method_runtime_api_impl_name(self.trait_, &method.sig.ident); let block_id = self.block_id; let crate_ = self.crate_; @@ -619,9 +619,9 @@ impl<'a> ToClientSideDecl<'a> { let params2 = params.clone(); let ret_type = return_type_extract_type(&method.sig.output); - fold_fn_decl_for_client_side(&mut method.sig, &self.block_id, &self.crate_); + fold_fn_decl_for_client_side(&mut method.sig, self.block_id, self.crate_); - let name_impl = generate_method_runtime_api_impl_name(&self.trait_, &method.sig.ident); + let name_impl = generate_method_runtime_api_impl_name(self.trait_, &method.sig.ident); let crate_ = self.crate_; let found_attributes = remove_supported_attributes(&mut method.attrs); @@ -630,7 +630,7 @@ impl<'a> ToClientSideDecl<'a> { let (native_handling, param_tuple) = match get_changed_in(&found_attributes) { Ok(Some(version)) => { // Make sure that the `changed_in` version is at least the current `api_version`. - if get_api_version(&self.found_attributes).ok() < Some(version) { + if get_api_version(self.found_attributes).ok() < Some(version) { self.errors.push( Error::new( method.span(), @@ -972,7 +972,7 @@ pub fn decl_runtime_apis_impl(input: proc_macro::TokenStream) -> proc_macro::Tok } fn decl_runtime_apis_impl_inner(api_decls: &[ItemTrait]) -> Result { - check_trait_decls(&api_decls)?; + check_trait_decls(api_decls)?; let hidden_includes = generate_hidden_includes(HIDDEN_INCLUDES_ID); let runtime_decls = generate_runtime_decls(api_decls)?; diff --git a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs index f594a743fc..0ac3cfbe12 100644 --- a/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/impl_runtime_apis.rs @@ -491,7 +491,7 @@ impl<'a> Fold for ApiRuntimeImplToApiRuntimeApiImpl<'a> { }; input.sig.ident = - generate_method_runtime_api_impl_name(&self.impl_trait, &input.sig.ident); + generate_method_runtime_api_impl_name(self.impl_trait, &input.sig.ident); let ret_type = return_type_extract_type(&input.sig.output); // Generate the correct return type. @@ -593,7 +593,7 @@ fn generate_api_impl_for_runtime_api(impls: &[ItemImpl]) -> Result let mut result = Vec::with_capacity(impls.len()); for impl_ in impls { - let impl_trait_path = extract_impl_trait(&impl_, RequireQualifiedTraitPath::Yes)?; + let impl_trait_path = extract_impl_trait(impl_, RequireQualifiedTraitPath::Yes)?; let impl_trait = &impl_trait_path .segments .last() @@ -634,7 +634,7 @@ fn generate_runtime_api_versions(impls: &[ItemImpl]) -> Result { for impl_ in impls { let mut path = extend_with_runtime_decl_path( - extract_impl_trait(&impl_, RequireQualifiedTraitPath::Yes)?.clone(), + extract_impl_trait(impl_, RequireQualifiedTraitPath::Yes)?.clone(), ); // Remove the trait let trait_ = path @@ -723,7 +723,7 @@ fn impl_runtime_apis_impl_inner(api_impls: &[ItemImpl]) -> Result { // Filters all attributes except the cfg ones. fn filter_cfg_attrs(attrs: &[Attribute]) -> Vec { - attrs.into_iter().filter(|a| a.path.is_ident("cfg")).cloned().collect() + attrs.iter().filter(|a| a.path.is_ident("cfg")).cloned().collect() } #[cfg(test)] diff --git a/substrate/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs b/substrate/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs index ffc158ac94..6098f8d6bd 100644 --- a/substrate/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs +++ b/substrate/primitives/api/proc-macro/src/mock_impl_runtime_apis.rs @@ -283,7 +283,7 @@ impl<'a> Fold for FoldRuntimeApiImpl<'a> { }; input.sig.ident = - generate_method_runtime_api_impl_name(&self.impl_trait, &input.sig.ident); + generate_method_runtime_api_impl_name(self.impl_trait, &input.sig.ident); // When using advanced, the user needs to declare the correct return type on its own, // otherwise do it for the user. @@ -350,7 +350,7 @@ fn generate_runtime_api_impls(impls: &[ItemImpl]) -> Result> = None; for impl_ in impls { - let impl_trait_path = extract_impl_trait(&impl_, RequireQualifiedTraitPath::No)?; + let impl_trait_path = extract_impl_trait(impl_, RequireQualifiedTraitPath::No)?; let impl_trait = &impl_trait_path .segments .last() diff --git a/substrate/primitives/api/proc-macro/src/utils.rs b/substrate/primitives/api/proc-macro/src/utils.rs index 2aa6a657aa..97b456b62d 100644 --- a/substrate/primitives/api/proc-macro/src/utils.rs +++ b/substrate/primitives/api/proc-macro/src/utils.rs @@ -61,12 +61,11 @@ pub fn generate_crate_access(unique_id: &'static str) -> TokenStream { let mod_name = generate_hidden_includes_mod_name(unique_id); quote!( self::#mod_name::sp_api ) } - .into() } /// Generates the name of the module that contains the trait declaration for the runtime. pub fn generate_runtime_mod_name_for_trait(trait_: &Ident) -> Ident { - Ident::new(&format!("runtime_decl_for_{}", trait_.to_string()), Span::call_site()) + Ident::new(&format!("runtime_decl_for_{}", trait_), Span::call_site()) } /// Generates a name for a method that needs to be implemented in the runtime for the client side. @@ -169,17 +168,17 @@ pub fn extract_parameter_names_types_and_borrows( /// Generates the name for the native call generator function. pub fn generate_native_call_generator_fn_name(fn_name: &Ident) -> Ident { - Ident::new(&format!("{}_native_call_generator", fn_name.to_string()), Span::call_site()) + Ident::new(&format!("{}_native_call_generator", fn_name), Span::call_site()) } /// Generates the name for the call api at function. pub fn generate_call_api_at_fn_name(fn_name: &Ident) -> Ident { - Ident::new(&format!("{}_call_api_at", fn_name.to_string()), Span::call_site()) + Ident::new(&format!("{}_call_api_at", fn_name), Span::call_site()) } /// Prefix the given function with the trait name. pub fn prefix_function_with_trait(trait_: &Ident, function: &F) -> String { - format!("{}_{}", trait_.to_string(), function.to_string()) + format!("{}_{}", trait_, function.to_string()) } /// Extract all types that appear in signatures in the given `ImplItem`'s. @@ -250,10 +249,7 @@ pub enum RequireQualifiedTraitPath { } /// Extract the trait that is implemented by the given `ItemImpl`. -pub fn extract_impl_trait<'a>( - impl_: &'a ItemImpl, - require: RequireQualifiedTraitPath, -) -> Result<&'a Path> { +pub fn extract_impl_trait(impl_: &ItemImpl, require: RequireQualifiedTraitPath) -> Result<&Path> { impl_ .trait_ .as_ref() diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 964ef15ce5..2635c81948 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -422,7 +422,7 @@ pub trait ConstructRuntimeApi> { type RuntimeApi: ApiExt; /// Construct an instance of the runtime api. - fn construct_runtime_api<'a>(call: &'a C) -> ApiRef<'a, Self::RuntimeApi>; + fn construct_runtime_api(call: &C) -> ApiRef; } /// Init the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger). @@ -554,12 +554,11 @@ pub trait CallApiAt { /// Calls the given api function with the given encoded arguments at the given block and returns /// the encoded result. fn call_api_at< - 'a, R: Encode + Decode + PartialEq, NC: FnOnce() -> result::Result + UnwindSafe, >( &self, - params: CallApiAtParams<'a, Block, NC, Self::StateBackend>, + params: CallApiAtParams, ) -> Result, ApiError>; /// Returns the runtime version at the given block. @@ -604,7 +603,7 @@ pub trait ProvideRuntimeApi { /// call to an api function, will `commit` its changes to an internal buffer. Otherwise, /// the modifications will be `discarded`. The modifications will not be applied to the /// storage, even on a `commit`. - fn runtime_api<'a>(&'a self) -> ApiRef<'a, Self::Api>; + fn runtime_api(&self) -> ApiRef; } /// Something that provides information about a runtime api. diff --git a/substrate/primitives/application-crypto/src/ecdsa.rs b/substrate/primitives/application-crypto/src/ecdsa.rs index 6a0eb7ab2f..6356f54a0b 100644 --- a/substrate/primitives/application-crypto/src/ecdsa.rs +++ b/substrate/primitives/application-crypto/src/ecdsa.rs @@ -53,7 +53,7 @@ impl RuntimePublic for Public { } fn verify>(&self, msg: &M, signature: &Self::Signature) -> bool { - sp_io::crypto::ecdsa_verify(&signature, msg.as_ref(), self) + sp_io::crypto::ecdsa_verify(signature, msg.as_ref(), self) } fn to_raw_vec(&self) -> Vec { diff --git a/substrate/primitives/application-crypto/src/ed25519.rs b/substrate/primitives/application-crypto/src/ed25519.rs index f5ec40233c..199e55383b 100644 --- a/substrate/primitives/application-crypto/src/ed25519.rs +++ b/substrate/primitives/application-crypto/src/ed25519.rs @@ -53,7 +53,7 @@ impl RuntimePublic for Public { } fn verify>(&self, msg: &M, signature: &Self::Signature) -> bool { - sp_io::crypto::ed25519_verify(&signature, msg.as_ref(), self) + sp_io::crypto::ed25519_verify(signature, msg.as_ref(), self) } fn to_raw_vec(&self) -> Vec { diff --git a/substrate/primitives/application-crypto/src/sr25519.rs b/substrate/primitives/application-crypto/src/sr25519.rs index 81c5320efd..c96e7382eb 100644 --- a/substrate/primitives/application-crypto/src/sr25519.rs +++ b/substrate/primitives/application-crypto/src/sr25519.rs @@ -53,7 +53,7 @@ impl RuntimePublic for Public { } fn verify>(&self, msg: &M, signature: &Self::Signature) -> bool { - sp_io::crypto::sr25519_verify(&signature, msg.as_ref(), self) + sp_io::crypto::sr25519_verify(signature, msg.as_ref(), self) } fn to_raw_vec(&self) -> Vec { diff --git a/substrate/primitives/arithmetic/benches/bench.rs b/substrate/primitives/arithmetic/benches/bench.rs index 3e4fafe2a4..57556135f6 100644 --- a/substrate/primitives/arithmetic/benches/bench.rs +++ b/substrate/primitives/arithmetic/benches/bench.rs @@ -41,19 +41,19 @@ fn bench_op(c: &mut Criterion, name: &str, op: F) { fn bench_addition(c: &mut Criterion) { bench_op(c, "addition", |a, b| { - let _ = a.clone().add(&b); + let _ = a.clone().add(b); }); } fn bench_subtraction(c: &mut Criterion) { bench_op(c, "subtraction", |a, b| { - let _ = a.clone().sub(&b); + let _ = a.clone().sub(b); }); } fn bench_multiplication(c: &mut Criterion) { bench_op(c, "multiplication", |a, b| { - let _ = a.clone().mul(&b); + let _ = a.clone().mul(b); }); } diff --git a/substrate/primitives/arithmetic/fuzzer/src/normalize.rs b/substrate/primitives/arithmetic/fuzzer/src/normalize.rs index dd717115a5..3d2d6eb9ac 100644 --- a/substrate/primitives/arithmetic/fuzzer/src/normalize.rs +++ b/substrate/primitives/arithmetic/fuzzer/src/normalize.rs @@ -35,7 +35,7 @@ fn main() { loop { fuzz!(|data: (Vec, Ty)| { let (data, norm) = data; - if data.len() == 0 { + if data.is_empty() { return } let pre_sum: u128 = data.iter().map(|x| *x as u128).sum(); @@ -44,16 +44,14 @@ fn main() { // error cases. if pre_sum > sum_limit || data.len() > len_limit { assert!(normalized.is_err()) - } else { - if let Ok(normalized) = normalized { - // if sum goes beyond u128, panic. - let sum: u128 = normalized.iter().map(|x| *x as u128).sum(); + } else if let Ok(normalized) = normalized { + // if sum goes beyond u128, panic. + let sum: u128 = normalized.iter().map(|x| *x as u128).sum(); - // if this function returns Ok(), then it will ALWAYS be accurate. - assert_eq!(sum, norm as u128, "sums don't match {:?}, {}", normalized, norm); - } else { - panic!("Should have returned Ok for input = {:?}, target = {:?}", data, norm); - } + // if this function returns Ok(), then it will ALWAYS be accurate. + assert_eq!(sum, norm as u128, "sums don't match {:?}, {}", normalized, norm); + } else { + panic!("Should have returned Ok for input = {:?}, target = {:?}", data, norm); } }) } diff --git a/substrate/primitives/arithmetic/src/lib.rs b/substrate/primitives/arithmetic/src/lib.rs index 729da12375..e43e427635 100644 --- a/substrate/primitives/arithmetic/src/lib.rs +++ b/substrate/primitives/arithmetic/src/lib.rs @@ -65,7 +65,7 @@ where fn tcmp(&self, other: &T, threshold: T) -> Ordering { // early exit. if threshold.is_zero() { - return self.cmp(&other) + return self.cmp(other) } let upper_bound = other.saturating_add(threshold); @@ -73,7 +73,7 @@ where if upper_bound <= lower_bound { // defensive only. Can never happen. - self.cmp(&other) + self.cmp(other) } else { // upper_bound is guaranteed now to be bigger than lower. match (self.cmp(&lower_bound), self.cmp(&upper_bound)) { @@ -113,10 +113,7 @@ impl_normalize_for_numeric!(u8, u16, u32, u64, u128); impl Normalizable

for Vec

{ fn normalize(&self, targeted_sum: P) -> Result, &'static str> { - let uppers = self - .iter() - .map(|p| >::from(p.clone().deconstruct())) - .collect::>(); + let uppers = self.iter().map(|p| >::from(p.deconstruct())).collect::>(); let normalized = normalize(uppers.as_ref(), >::from(targeted_sum.deconstruct()))?; diff --git a/substrate/primitives/arithmetic/src/rational.rs b/substrate/primitives/arithmetic/src/rational.rs index 63ae6e65bc..1beafbe811 100644 --- a/substrate/primitives/arithmetic/src/rational.rs +++ b/substrate/primitives/arithmetic/src/rational.rs @@ -63,14 +63,14 @@ impl Ord for RationalInfinite { fn cmp(&self, other: &Self) -> Ordering { // handle some edge cases. if self.d() == other.d() { - self.n().cmp(&other.n()) + self.n().cmp(other.n()) } else if self.d().is_zero() { Ordering::Greater } else if other.d().is_zero() { Ordering::Less } else { // (a/b) cmp (c/d) => (a*d) cmp (c*b) - self.n().clone().mul(&other.d()).cmp(&other.n().clone().mul(&self.d())) + self.n().clone().mul(other.d()).cmp(&other.n().clone().mul(self.d())) } } } @@ -272,6 +272,7 @@ impl PartialEq for Rational128 { #[cfg(test)] mod tests { use super::{helpers_128bit::*, *}; + use static_assertions::const_assert; const MAX128: u128 = u128::MAX; const MAX64: u128 = u64::MAX as u128; @@ -349,8 +350,8 @@ mod tests { r(1_000_000_000, MAX64).lcm(&r(7_000_000_000, MAX64 - 1)), Ok(340282366920938463408034375210639556610), ); - assert!(340282366920938463408034375210639556610 < MAX128); - assert!(340282366920938463408034375210639556610 == MAX64 * (MAX64 - 1)); + const_assert!(340282366920938463408034375210639556610 < MAX128); + const_assert!(340282366920938463408034375210639556610 == MAX64 * (MAX64 - 1)); } #[test] diff --git a/substrate/primitives/blockchain/src/backend.rs b/substrate/primitives/blockchain/src/backend.rs index 84b34105e5..f80c6d0269 100644 --- a/substrate/primitives/blockchain/src/backend.rs +++ b/substrate/primitives/blockchain/src/backend.rs @@ -184,7 +184,7 @@ pub trait Backend: if let Some(max_number) = maybe_max_number { loop { let current_header = self - .header(BlockId::Hash(current_hash.clone()))? + .header(BlockId::Hash(current_hash))? .ok_or_else(|| Error::MissingHeader(current_hash.to_string()))?; if current_header.number() <= &max_number { @@ -204,7 +204,7 @@ pub trait Backend: } let current_header = self - .header(BlockId::Hash(current_hash.clone()))? + .header(BlockId::Hash(current_hash))? .ok_or_else(|| Error::MissingHeader(current_hash.to_string()))?; // stop search in this chain once we go below the target's block number diff --git a/substrate/primitives/blockchain/src/header_metadata.rs b/substrate/primitives/blockchain/src/header_metadata.rs index 858dcf6c92..46477a75b8 100644 --- a/substrate/primitives/blockchain/src/header_metadata.rs +++ b/substrate/primitives/blockchain/src/header_metadata.rs @@ -275,11 +275,11 @@ pub struct CachedHeaderMetadata { impl From<&Block::Header> for CachedHeaderMetadata { fn from(header: &Block::Header) -> Self { CachedHeaderMetadata { - hash: header.hash().clone(), - number: header.number().clone(), - parent: header.parent_hash().clone(), - state_root: header.state_root().clone(), - ancestor: header.parent_hash().clone(), + hash: header.hash(), + number: *header.number(), + parent: *header.parent_hash(), + state_root: *header.state_root(), + ancestor: *header.parent_hash(), } } } diff --git a/substrate/primitives/consensus/common/src/evaluation.rs b/substrate/primitives/consensus/common/src/evaluation.rs index d0ddbb6fab..6a6ca835f3 100644 --- a/substrate/primitives/consensus/common/src/evaluation.rs +++ b/substrate/primitives/consensus/common/src/evaluation.rs @@ -49,7 +49,7 @@ pub fn evaluate_initial( parent_number: <::Header as HeaderT>::Number, ) -> Result<()> { let encoded = Encode::encode(proposal); - let proposal = Block::decode(&mut &encoded[..]).map_err(|e| Error::BadProposalFormat(e))?; + let proposal = Block::decode(&mut &encoded[..]).map_err(Error::BadProposalFormat)?; if *parent_hash != *proposal.header().parent_hash() { return Err(Error::WrongParentHash { diff --git a/substrate/primitives/consensus/common/src/lib.rs b/substrate/primitives/consensus/common/src/lib.rs index 59bbf7618d..2743f434c2 100644 --- a/substrate/primitives/consensus/common/src/lib.rs +++ b/substrate/primitives/consensus/common/src/lib.rs @@ -169,7 +169,7 @@ impl ProofRecording for EnableProofRecording { const ENABLED: bool = true; fn into_proof(proof: Option) -> Result { - proof.ok_or_else(|| NoProofRecorded) + proof.ok_or(NoProofRecorded) } } diff --git a/substrate/primitives/core/benches/bench.rs b/substrate/primitives/core/benches/bench.rs index 44bcd657ba..53421278dc 100644 --- a/substrate/primitives/core/benches/bench.rs +++ b/substrate/primitives/core/benches/bench.rs @@ -79,7 +79,7 @@ fn bench_hash_128_dyn_size(c: &mut Criterion) { fn bench_ed25519(c: &mut Criterion) { let mut group = c.benchmark_group("ed25519"); - for msg_size in vec![32, 1024, 1024 * 1024] { + for &msg_size in &[32, 1024, 1024 * 1024] { let msg = (0..msg_size).map(|_| rand::random::()).collect::>(); let key = sp_core::ed25519::Pair::generate().0; group.bench_function(BenchmarkId::new("signing", format!("{}", msg_size)), |b| { @@ -87,7 +87,7 @@ fn bench_ed25519(c: &mut Criterion) { }); } - for msg_size in vec![32, 1024, 1024 * 1024] { + for &msg_size in &[32, 1024, 1024 * 1024] { let msg = (0..msg_size).map(|_| rand::random::()).collect::>(); let key = sp_core::ed25519::Pair::generate().0; let sig = key.sign(&msg); @@ -103,7 +103,7 @@ fn bench_ed25519(c: &mut Criterion) { fn bench_sr25519(c: &mut Criterion) { let mut group = c.benchmark_group("sr25519"); - for msg_size in vec![32, 1024, 1024 * 1024] { + for &msg_size in &[32, 1024, 1024 * 1024] { let msg = (0..msg_size).map(|_| rand::random::()).collect::>(); let key = sp_core::sr25519::Pair::generate().0; group.bench_function(BenchmarkId::new("signing", format!("{}", msg_size)), |b| { @@ -111,7 +111,7 @@ fn bench_sr25519(c: &mut Criterion) { }); } - for msg_size in vec![32, 1024, 1024 * 1024] { + for &msg_size in &[32, 1024, 1024 * 1024] { let msg = (0..msg_size).map(|_| rand::random::()).collect::>(); let key = sp_core::sr25519::Pair::generate().0; let sig = key.sign(&msg); @@ -127,7 +127,7 @@ fn bench_sr25519(c: &mut Criterion) { fn bench_ecdsa(c: &mut Criterion) { let mut group = c.benchmark_group("ecdsa"); - for msg_size in vec![32, 1024, 1024 * 1024] { + for &msg_size in &[32, 1024, 1024 * 1024] { let msg = (0..msg_size).map(|_| rand::random::()).collect::>(); let key = sp_core::ecdsa::Pair::generate().0; group.bench_function(BenchmarkId::new("signing", format!("{}", msg_size)), |b| { @@ -135,7 +135,7 @@ fn bench_ecdsa(c: &mut Criterion) { }); } - for msg_size in vec![32, 1024, 1024 * 1024] { + for &msg_size in &[32, 1024, 1024 * 1024] { let msg = (0..msg_size).map(|_| rand::random::()).collect::>(); let key = sp_core::ecdsa::Pair::generate().0; let sig = key.sign(&msg); diff --git a/substrate/primitives/core/hashing/proc-macro/src/impls.rs b/substrate/primitives/core/hashing/proc-macro/src/impls.rs index ff9593ea18..3058cf019b 100644 --- a/substrate/primitives/core/hashing/proc-macro/src/impls.rs +++ b/substrate/primitives/core/hashing/proc-macro/src/impls.rs @@ -26,7 +26,7 @@ pub(super) struct MultipleInputBytes(pub Vec>); impl MultipleInputBytes { pub(super) fn concatenated(mut self) -> Vec { - if self.0.len() == 0 { + if self.0.is_empty() { Vec::new() } else { let mut result = core::mem::take(&mut self.0[0]); diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index f994da1515..80b44449db 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -1172,7 +1172,7 @@ mod tests { impl ByteArray for TestPublic { const LEN: usize = 0; fn from_slice(bytes: &[u8]) -> Result { - if bytes.len() == 0 { + if bytes.is_empty() { Ok(Self) } else { Err(()) diff --git a/substrate/primitives/core/src/ecdsa.rs b/substrate/primitives/core/src/ecdsa.rs index 6343e3f4df..485e39d3a7 100644 --- a/substrate/primitives/core/src/ecdsa.rs +++ b/substrate/primitives/core/src/ecdsa.rs @@ -364,7 +364,7 @@ impl From for Signature { /// Derive a single hard junction. #[cfg(feature = "full_crypto")] fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed { - ("Secp256k1HDKD", secret_seed, cc).using_encoded(|data| sp_core_hashing::blake2_256(data)) + ("Secp256k1HDKD", secret_seed, cc).using_encoded(sp_core_hashing::blake2_256) } /// An error when deriving a key. @@ -763,12 +763,12 @@ mod test { set_default_ss58_version(Ss58AddressFormat::custom(200)); // custom addr encoded by version 200 let addr = "4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV"; - Public::from_ss58check(&addr).unwrap(); + Public::from_ss58check(addr).unwrap(); set_default_ss58_version(default_format); // set current ss58 version to default version let addr = "KWAfgC2aRG5UVD6CpbPQXCx4YZZUhvWqqAJE6qcYc9Rtr6g5C"; - Public::from_ss58check(&addr).unwrap(); + Public::from_ss58check(addr).unwrap(); println!("CUSTOM_FORMAT_SUCCESSFUL"); } else { diff --git a/substrate/primitives/core/src/ed25519.rs b/substrate/primitives/core/src/ed25519.rs index 0bde9e2e53..177af0651c 100644 --- a/substrate/primitives/core/src/ed25519.rs +++ b/substrate/primitives/core/src/ed25519.rs @@ -397,7 +397,7 @@ impl From<&Public> for CryptoTypePublicPair { /// Derive a single hard junction. #[cfg(feature = "full_crypto")] fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed { - ("Ed25519HDKD", secret_seed, cc).using_encoded(|data| sp_core_hashing::blake2_256(data)) + ("Ed25519HDKD", secret_seed, cc).using_encoded(sp_core_hashing::blake2_256) } /// An error when deriving a key. diff --git a/substrate/primitives/core/src/hexdisplay.rs b/substrate/primitives/core/src/hexdisplay.rs index e5262ba8f6..26c04c433b 100644 --- a/substrate/primitives/core/src/hexdisplay.rs +++ b/substrate/primitives/core/src/hexdisplay.rs @@ -69,13 +69,13 @@ impl AsBytesRef for &[u8] { impl AsBytesRef for [u8] { fn as_bytes_ref(&self) -> &[u8] { - &self + self } } impl AsBytesRef for sp_std::vec::Vec { fn as_bytes_ref(&self) -> &[u8] { - &self + self } } diff --git a/substrate/primitives/debug-derive/src/impls.rs b/substrate/primitives/debug-derive/src/impls.rs index 060997fe97..51a4d876c7 100644 --- a/substrate/primitives/debug-derive/src/impls.rs +++ b/substrate/primitives/debug-derive/src/impls.rs @@ -67,10 +67,9 @@ mod implementation { /// Derive the inner implementation of `Debug::fmt` function. pub fn derive(name_str: &str, data: &Data) -> TokenStream { match *data { - Data::Struct(ref s) => derive_struct(&name_str, &s.fields), - Data::Union(ref u) => - derive_fields(&name_str, Fields::new(u.fields.named.iter(), None)), - Data::Enum(ref e) => derive_enum(&name_str, &e), + Data::Struct(ref s) => derive_struct(name_str, &s.fields), + Data::Union(ref u) => derive_fields(name_str, Fields::new(u.fields.named.iter(), None)), + Data::Enum(ref e) => derive_enum(name_str, e), } } diff --git a/substrate/primitives/externalities/src/extensions.rs b/substrate/primitives/externalities/src/extensions.rs index d58edb749e..5db40f12c2 100644 --- a/substrate/primitives/externalities/src/extensions.rs +++ b/substrate/primitives/externalities/src/extensions.rs @@ -174,9 +174,7 @@ impl Extensions { } /// Returns a mutable iterator over all extensions. - pub fn iter_mut<'a>( - &'a mut self, - ) -> impl Iterator)> { + pub fn iter_mut(&mut self) -> impl Iterator)> { self.extensions.iter_mut() } } diff --git a/substrate/primitives/finality-grandpa/src/lib.rs b/substrate/primitives/finality-grandpa/src/lib.rs index dd5cef85a2..4be42c3d19 100644 --- a/substrate/primitives/finality-grandpa/src/lib.rs +++ b/substrate/primitives/finality-grandpa/src/lib.rs @@ -59,7 +59,7 @@ pub const GRANDPA_ENGINE_ID: ConsensusEngineId = *b"FRNK"; /// The storage key for the current set of weighted Grandpa authorities. /// The value stored is an encoded VersionedAuthorityList. -pub const GRANDPA_AUTHORITIES_KEY: &'static [u8] = b":grandpa_authorities"; +pub const GRANDPA_AUTHORITIES_KEY: &[u8] = b":grandpa_authorities"; /// The weight of an authority. pub type AuthorityWeight = u64; diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index 2ff49b5048..8f62b03b62 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -220,7 +220,7 @@ pub trait Storage { /// Get the next key in storage after the given one in lexicographic order. fn next_key(&mut self, key: &[u8]) -> Option> { - self.next_storage_key(&key) + self.next_storage_key(key) } /// Start a new nested transaction. @@ -629,7 +629,7 @@ pub trait Crypto { /// /// Returns the public key. fn ed25519_generate(&mut self, id: KeyTypeId, seed: Option>) -> ed25519::Public { - let seed = seed.as_ref().map(|s| std::str::from_utf8(&s).expect("Seed is valid utf8!")); + let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!")); let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); @@ -678,7 +678,7 @@ pub trait Crypto { pub_key: &ed25519::Public, ) -> bool { self.extension::() - .map(|extension| extension.push_ed25519(sig.clone(), pub_key.clone(), msg.to_vec())) + .map(|extension| extension.push_ed25519(sig.clone(), *pub_key, msg.to_vec())) .unwrap_or_else(|| ed25519_verify(sig, msg, pub_key)) } @@ -705,7 +705,7 @@ pub trait Crypto { pub_key: &sr25519::Public, ) -> bool { self.extension::() - .map(|extension| extension.push_sr25519(sig.clone(), pub_key.clone(), msg.to_vec())) + .map(|extension| extension.push_sr25519(sig.clone(), *pub_key, msg.to_vec())) .unwrap_or_else(|| sr25519_verify(sig, msg, pub_key)) } @@ -753,7 +753,7 @@ pub trait Crypto { /// /// Returns the public key. fn sr25519_generate(&mut self, id: KeyTypeId, seed: Option>) -> sr25519::Public { - let seed = seed.as_ref().map(|s| std::str::from_utf8(&s).expect("Seed is valid utf8!")); + let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!")); let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); @@ -803,7 +803,7 @@ pub trait Crypto { /// /// Returns the public key. fn ecdsa_generate(&mut self, id: KeyTypeId, seed: Option>) -> ecdsa::Public { - let seed = seed.as_ref().map(|s| std::str::from_utf8(&s).expect("Seed is valid utf8!")); + let seed = seed.as_ref().map(|s| std::str::from_utf8(s).expect("Seed is valid utf8!")); let keystore = &***self .extension::() .expect("No `keystore` associated for the current context!"); @@ -888,7 +888,7 @@ pub trait Crypto { pub_key: &ecdsa::Public, ) -> bool { self.extension::() - .map(|extension| extension.push_ecdsa(sig.clone(), pub_key.clone(), msg.to_vec())) + .map(|extension| extension.push_ecdsa(sig.clone(), *pub_key, msg.to_vec())) .unwrap_or_else(|| ecdsa_verify(sig, msg, pub_key)) } @@ -1504,14 +1504,7 @@ pub trait Sandbox { state_ptr: Pointer, ) -> u32 { self.sandbox() - .invoke( - instance_idx, - &function, - &args, - return_val_ptr, - return_val_len, - state_ptr.into(), - ) + .invoke(instance_idx, function, args, return_val_ptr, return_val_len, state_ptr.into()) .expect("Failed to invoke function with sandbox") } diff --git a/substrate/primitives/keyring/src/ed25519.rs b/substrate/primitives/keyring/src/ed25519.rs index 6d56062d34..404e4121e7 100644 --- a/substrate/primitives/keyring/src/ed25519.rs +++ b/substrate/primitives/keyring/src/ed25519.rs @@ -125,7 +125,7 @@ lazy_static! { impl From for Public { fn from(k: Keyring) -> Self { - (*PUBLIC_KEYS).get(&k).unwrap().clone() + *(*PUBLIC_KEYS).get(&k).unwrap() } } diff --git a/substrate/primitives/keyring/src/sr25519.rs b/substrate/primitives/keyring/src/sr25519.rs index 86bcac9d58..115a7fce70 100644 --- a/substrate/primitives/keyring/src/sr25519.rs +++ b/substrate/primitives/keyring/src/sr25519.rs @@ -168,7 +168,7 @@ impl From for AccountId32 { impl From for Public { fn from(k: Keyring) -> Self { - (*PUBLIC_KEYS).get(&k).unwrap().clone() + *(*PUBLIC_KEYS).get(&k).unwrap() } } diff --git a/substrate/primitives/keystore/src/testing.rs b/substrate/primitives/keystore/src/testing.rs index 2723b743c1..a9ec6709d9 100644 --- a/substrate/primitives/keystore/src/testing.rs +++ b/substrate/primitives/keystore/src/testing.rs @@ -316,7 +316,7 @@ impl SyncCryptoStore for KeyStore { fn has_keys(&self, public_keys: &[(Vec, KeyTypeId)]) -> bool { public_keys .iter() - .all(|(k, t)| self.keys.read().get(&t).and_then(|s| s.get(k)).is_some()) + .all(|(k, t)| self.keys.read().get(t).and_then(|s| s.get(k)).is_some()) } fn supported_keys( diff --git a/substrate/primitives/merkle-mountain-range/src/lib.rs b/substrate/primitives/merkle-mountain-range/src/lib.rs index a27536b8d3..60ef02c530 100644 --- a/substrate/primitives/merkle-mountain-range/src/lib.rs +++ b/substrate/primitives/merkle-mountain-range/src/lib.rs @@ -231,7 +231,7 @@ impl DataOrHash { pub fn hash(&self) -> H::Output { match *self { Self::Data(ref leaf) => leaf.using_encoded(::hash, true), - Self::Hash(ref hash) => hash.clone(), + Self::Hash(ref hash) => *hash, } } } diff --git a/substrate/primitives/npos-elections/fuzzer/src/common.rs b/substrate/primitives/npos-elections/fuzzer/src/common.rs index 1bef899d5e..6b89983c16 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/common.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/common.rs @@ -99,7 +99,7 @@ pub fn generate_random_npos_inputs( let mut chosen_candidates = Vec::with_capacity(n_candidates_chosen); chosen_candidates.extend(candidates.choose_multiple(&mut rng, n_candidates_chosen)); - chosen_candidates.sort(); + chosen_candidates.sort_unstable(); voters.push((id, vote_weight, chosen_candidates)); } diff --git a/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs b/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs index 76641fc2c7..cacf64e81c 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/phragmen_balancing.rs @@ -53,11 +53,9 @@ fn main() { let stake_of = |who: &AccountId| -> VoteWeight { *stake_of_tree.get(who).unwrap() }; let unbalanced_score = { - let staked = assignment_ratio_to_staked_normalized( - unbalanced.assignments.clone(), - &stake_of, - ) - .unwrap(); + let staked = + assignment_ratio_to_staked_normalized(unbalanced.assignments, &stake_of) + .unwrap(); let score = to_supports(staked.as_ref()).evaluate(); if score.minimal_stake == 0 { @@ -72,11 +70,9 @@ fn main() { seq_phragmen(to_elect, candidates, voters, Some((iterations, 0))).unwrap(); let balanced_score = { - let staked = assignment_ratio_to_staked_normalized( - balanced.assignments.clone(), - &stake_of, - ) - .unwrap(); + let staked = + assignment_ratio_to_staked_normalized(balanced.assignments, &stake_of) + .unwrap(); to_supports(staked.as_ref()).evaluate() }; diff --git a/substrate/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs b/substrate/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs index 09daf3f34d..988889428c 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/phragmms_balancing.rs @@ -53,11 +53,9 @@ fn main() { let stake_of = |who: &AccountId| -> VoteWeight { *stake_of_tree.get(who).unwrap() }; let unbalanced_score = { - let staked = assignment_ratio_to_staked_normalized( - unbalanced.assignments.clone(), - &stake_of, - ) - .unwrap(); + let staked = + assignment_ratio_to_staked_normalized(unbalanced.assignments, &stake_of) + .unwrap(); let score = to_supports(&staked).evaluate(); if score.minimal_stake == 0 { @@ -72,8 +70,7 @@ fn main() { let balanced_score = { let staked = - assignment_ratio_to_staked_normalized(balanced.assignments.clone(), &stake_of) - .unwrap(); + assignment_ratio_to_staked_normalized(balanced.assignments, &stake_of).unwrap(); to_supports(staked.as_ref()).evaluate() }; diff --git a/substrate/primitives/npos-elections/fuzzer/src/reduce.rs b/substrate/primitives/npos-elections/fuzzer/src/reduce.rs index a77b40ca56..605f2d6081 100644 --- a/substrate/primitives/npos-elections/fuzzer/src/reduce.rs +++ b/substrate/primitives/npos-elections/fuzzer/src/reduce.rs @@ -118,7 +118,7 @@ fn reduce_and_compare(assignment: &Vec>, winners: &V let n = assignment.len() as u32; let m = winners.len() as u32; - let edges_before = assignment_len(&assignment); + let edges_before = assignment_len(assignment); let num_changed = reduce(&mut altered_assignment); let edges_after = edges_before - num_changed; diff --git a/substrate/primitives/npos-elections/src/helpers.rs b/substrate/primitives/npos-elections/src/helpers.rs index 76cfd59de6..598eb3b2ec 100644 --- a/substrate/primitives/npos-elections/src/helpers.rs +++ b/substrate/primitives/npos-elections/src/helpers.rs @@ -49,13 +49,9 @@ where for<'r> FS: Fn(&'r A) -> VoteWeight, { let mut staked = assignment_ratio_to_staked(ratio, &stake_of); - staked - .iter_mut() - .map(|a| { - a.try_normalize(stake_of(&a.who).into()) - .map_err(|err| Error::ArithmeticError(err)) - }) - .collect::>()?; + staked.iter_mut().try_for_each(|a| { + a.try_normalize(stake_of(&a.who).into()).map_err(Error::ArithmeticError) + })?; Ok(staked) } @@ -74,7 +70,7 @@ pub fn assignment_staked_to_ratio_normalized( ) -> Result>, Error> { let mut ratio = staked.into_iter().map(|a| a.into_assignment()).collect::>(); for assignment in ratio.iter_mut() { - assignment.try_normalize().map_err(|err| Error::ArithmeticError(err))?; + assignment.try_normalize().map_err(Error::ArithmeticError)?; } Ok(ratio) } diff --git a/substrate/primitives/npos-elections/src/lib.rs b/substrate/primitives/npos-elections/src/lib.rs index 93fb24eb4a..63b9740b74 100644 --- a/substrate/primitives/npos-elections/src/lib.rs +++ b/substrate/primitives/npos-elections/src/lib.rs @@ -456,8 +456,8 @@ pub fn to_support_map( let mut supports = >>::new(); // build support struct. - for StakedAssignment { who, distribution } in assignments.into_iter() { - for (c, weight_extended) in distribution.into_iter() { + for StakedAssignment { who, distribution } in assignments.iter() { + for (c, weight_extended) in distribution.iter() { let mut support = supports.entry(c.clone()).or_default(); support.total = support.total.saturating_add(*weight_extended); support.voters.push((who.clone(), *weight_extended)); diff --git a/substrate/primitives/npos-elections/src/phragmen.rs b/substrate/primitives/npos-elections/src/phragmen.rs index e8e925935f..9b0bfa4221 100644 --- a/substrate/primitives/npos-elections/src/phragmen.rs +++ b/substrate/primitives/npos-elections/src/phragmen.rs @@ -97,8 +97,7 @@ pub fn seq_phragmen( voters.into_iter().filter_map(|v| v.into_assignment()).collect::>(); let _ = assignments .iter_mut() - .map(|a| a.try_normalize().map_err(|e| crate::Error::ArithmeticError(e))) - .collect::>()?; + .try_for_each(|a| a.try_normalize().map_err(crate::Error::ArithmeticError))?; let winners = winners .into_iter() .map(|w_ptr| (w_ptr.borrow().who.clone(), w_ptr.borrow().backed_stake)) @@ -200,7 +199,7 @@ pub fn seq_phragmen_core( // edge of all candidates that eventually have a non-zero weight must be elected. debug_assert!(voter.edges.iter().all(|e| e.candidate.borrow().elected)); // inc budget to sum the budget. - voter.try_normalize_elected().map_err(|e| crate::Error::ArithmeticError(e))?; + voter.try_normalize_elected().map_err(crate::Error::ArithmeticError)?; } Ok((candidates, voters)) diff --git a/substrate/primitives/npos-elections/src/phragmms.rs b/substrate/primitives/npos-elections/src/phragmms.rs index aa4c558bea..5d63517c8e 100644 --- a/substrate/primitives/npos-elections/src/phragmms.rs +++ b/substrate/primitives/npos-elections/src/phragmms.rs @@ -70,9 +70,8 @@ pub fn phragmms( voters.into_iter().filter_map(|v| v.into_assignment()).collect::>(); let _ = assignments .iter_mut() - .map(|a| a.try_normalize()) - .collect::>() - .map_err(|e| crate::Error::ArithmeticError(e))?; + .try_for_each(|a| a.try_normalize()) + .map_err(crate::Error::ArithmeticError)?; let winners = winners .into_iter() .map(|w_ptr| (w_ptr.borrow().who.clone(), w_ptr.borrow().backed_stake)) @@ -157,16 +156,14 @@ pub(crate) fn calculate_max_score( // `RationalInfinite` as the score type does not introduce significant overhead. Then we // can switch the score type to `RationalInfinite` and ensure compatibility with any // crazy token scale. - let score_n = candidate - .approval_stake - .checked_mul(one) - .unwrap_or_else(|| Bounded::max_value()); + let score_n = + candidate.approval_stake.checked_mul(one).unwrap_or_else(Bounded::max_value); candidate.score = Rational128::from(score_n, score_d); // check if we have a new winner. if !candidate.elected && candidate.score > best_score { best_score = candidate.score; - best_candidate = Some(Rc::clone(&c_ptr)); + best_candidate = Some(Rc::clone(c_ptr)); } } else { candidate.score = Rational128::zero(); diff --git a/substrate/primitives/npos-elections/src/pjr.rs b/substrate/primitives/npos-elections/src/pjr.rs index 2d58ca49c8..914834fbb2 100644 --- a/substrate/primitives/npos-elections/src/pjr.rs +++ b/substrate/primitives/npos-elections/src/pjr.rs @@ -212,7 +212,7 @@ fn validate_pjr_challenge_core( None => return false, Some(candidate) => candidate.clone(), }; - pre_score(candidate, &voters, threshold) >= threshold + pre_score(candidate, voters, threshold) >= threshold } /// Convert the data types that the user runtime has into ones that can be used by this module. @@ -351,7 +351,7 @@ fn pre_score( debug_assert!(!unelected.borrow().elected); voters .iter() - .filter(|ref v| v.votes_for(&unelected.borrow().who)) + .filter(|v| v.votes_for(&unelected.borrow().who)) .fold(Zero::zero(), |acc: ExtendedBalance, voter| acc.saturating_add(slack(voter, t))) } diff --git a/substrate/primitives/npos-elections/src/reduce.rs b/substrate/primitives/npos-elections/src/reduce.rs index f089a37e3f..c802a29504 100644 --- a/substrate/primitives/npos-elections/src/reduce.rs +++ b/substrate/primitives/npos-elections/src/reduce.rs @@ -94,7 +94,7 @@ fn merge(voter_root_path: Vec>, target_root_path: Vec shorter_path .iter() .zip(shorter_path.iter().skip(1)) - .for_each(|(voter, next)| Node::set_parent_of(&next, &voter)); + .for_each(|(voter, next)| Node::set_parent_of(next, voter)); Node::set_parent_of(&shorter_path[0], &longer_path[0]); } @@ -524,12 +524,10 @@ fn reduce_all(assignments: &mut Vec>) -> u32 } else { ass.distribution[idx].1.saturating_sub(min_value) } + } else if start_operation_add { + ass.distribution[idx].1.saturating_sub(min_value) } else { - if start_operation_add { - ass.distribution[idx].1.saturating_sub(min_value) - } else { - ass.distribution[idx].1.saturating_add(min_value) - } + ass.distribution[idx].1.saturating_add(min_value) }; if next_value.is_zero() { @@ -569,12 +567,10 @@ fn reduce_all(assignments: &mut Vec>) -> u32 } else { ass.distribution[idx].1.saturating_add(min_value) } + } else if start_operation_add { + ass.distribution[idx].1.saturating_add(min_value) } else { - if start_operation_add { - ass.distribution[idx].1.saturating_add(min_value) - } else { - ass.distribution[idx].1.saturating_sub(min_value) - } + ass.distribution[idx].1.saturating_sub(min_value) }; if next_value.is_zero() { diff --git a/substrate/primitives/panic-handler/src/lib.rs b/substrate/primitives/panic-handler/src/lib.rs index df1f78da1c..e06fe90ad6 100644 --- a/substrate/primitives/panic-handler/src/lib.rs +++ b/substrate/primitives/panic-handler/src/lib.rs @@ -158,7 +158,7 @@ fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) { }, }; - let msg = strip_control_codes(&msg); + let msg = strip_control_codes(msg); let thread = thread::current(); let name = thread.name().unwrap_or(""); @@ -167,13 +167,13 @@ fn panic_hook(info: &PanicInfo, report_url: &str, version: &str) { let mut stderr = io::stderr(); - let _ = writeln!(stderr, ""); + let _ = writeln!(stderr); let _ = writeln!(stderr, "===================="); - let _ = writeln!(stderr, ""); + let _ = writeln!(stderr); let _ = writeln!(stderr, "Version: {}", version); - let _ = writeln!(stderr, ""); + let _ = writeln!(stderr); let _ = writeln!(stderr, "{:?}", backtrace); - let _ = writeln!(stderr, ""); + let _ = writeln!(stderr); let _ = writeln!(stderr, "Thread '{}' panicked at '{}', {}:{}", name, msg, file, line); let _ = writeln!(stderr, ABOUT_PANIC!(), report_url); diff --git a/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs b/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs index 7c3f066f6c..e25295fdca 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs @@ -79,7 +79,7 @@ pub fn derive_impl(input: DeriveInput) -> Result { /// /// Returns an error if the number of variants is greater than `256`, the given `data` is not an /// enum or a variant is not an unit. -fn get_enum_field_idents<'a>(data: &'a Data) -> Result>> { +fn get_enum_field_idents(data: &Data) -> Result>> { match data { Data::Enum(d) => if d.variants.len() <= 256 { diff --git a/substrate/primitives/runtime-interface/proc-macro/src/utils.rs b/substrate/primitives/runtime-interface/proc-macro/src/utils.rs index 19f7fea023..386eef153f 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/utils.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/utils.rs @@ -65,13 +65,11 @@ impl RuntimeInterfaceFunction { } }); - if should_trap_on_return { - if !matches!(item.sig.output, syn::ReturnType::Default) { - return Err(Error::new( - item.sig.ident.span(), - "Methods marked as #[trap_on_return] cannot return anything", - )) - } + if should_trap_on_return && !matches!(item.sig.output, syn::ReturnType::Default) { + return Err(Error::new( + item.sig.ident.span(), + "Methods marked as #[trap_on_return] cannot return anything", + )) } Ok(Self { item, should_trap_on_return }) @@ -212,7 +210,7 @@ pub fn create_function_ident_with_version(name: &Ident, version: u32) -> Ident { } /// Returns the function arguments of the given `Signature`, minus any `self` arguments. -pub fn get_function_arguments<'a>(sig: &'a Signature) -> impl Iterator + 'a { +pub fn get_function_arguments(sig: &Signature) -> impl Iterator + '_ { sig.inputs .iter() .filter_map(|a| match a { @@ -234,20 +232,20 @@ pub fn get_function_arguments<'a>(sig: &'a Signature) -> impl Iterator(sig: &'a Signature) -> impl Iterator> + 'a { +pub fn get_function_argument_names(sig: &Signature) -> impl Iterator> + '_ { get_function_arguments(sig).map(|pt| pt.pat) } /// Returns the function argument types of the given `Signature`, minus any `Self` type. -pub fn get_function_argument_types<'a>(sig: &'a Signature) -> impl Iterator> + 'a { +pub fn get_function_argument_types(sig: &Signature) -> impl Iterator> + '_ { get_function_arguments(sig).map(|pt| pt.ty) } /// Returns the function argument types, minus any `Self` type. If any of the arguments /// is a reference, the underlying type without the ref is returned. -pub fn get_function_argument_types_without_ref<'a>( - sig: &'a Signature, -) -> impl Iterator> + 'a { +pub fn get_function_argument_types_without_ref( + sig: &Signature, +) -> impl Iterator> + '_ { get_function_arguments(sig).map(|pt| pt.ty).map(|ty| match *ty { Type::Reference(type_ref) => type_ref.elem, _ => ty, @@ -256,9 +254,9 @@ pub fn get_function_argument_types_without_ref<'a>( /// Returns the function argument names and types, minus any `self`. If any of the arguments /// is a reference, the underlying type without the ref is returned. -pub fn get_function_argument_names_and_types_without_ref<'a>( - sig: &'a Signature, -) -> impl Iterator, Box)> + 'a { +pub fn get_function_argument_names_and_types_without_ref( + sig: &Signature, +) -> impl Iterator, Box)> + '_ { get_function_arguments(sig).map(|pt| match *pt.ty { Type::Reference(type_ref) => (pt.pat, type_ref.elem), _ => (pt.pat, pt.ty), @@ -267,9 +265,9 @@ pub fn get_function_argument_names_and_types_without_ref<'a>( /// Returns the `&`/`&mut` for all function argument types, minus the `self` arg. If a function /// argument is not a reference, `None` is returned. -pub fn get_function_argument_types_ref_and_mut<'a>( - sig: &'a Signature, -) -> impl Iterator)>> + 'a { +pub fn get_function_argument_types_ref_and_mut( + sig: &Signature, +) -> impl Iterator)>> + '_ { get_function_arguments(sig).map(|pt| pt.ty).map(|ty| match *ty { Type::Reference(type_ref) => Some((type_ref.and_token, type_ref.mutability)), _ => None, @@ -277,7 +275,7 @@ pub fn get_function_argument_types_ref_and_mut<'a>( } /// Returns an iterator over all trait methods for the given trait definition. -fn get_trait_methods<'a>(trait_def: &'a ItemTrait) -> impl Iterator { +fn get_trait_methods(trait_def: &ItemTrait) -> impl Iterator { trait_def.items.iter().filter_map(|i| match i { TraitItem::Method(ref method) => Some(method), _ => None, diff --git a/substrate/primitives/runtime/src/generic/digest.rs b/substrate/primitives/runtime/src/generic/digest.rs index 55e0d69fad..ec74ebb0d4 100644 --- a/substrate/primitives/runtime/src/generic/digest.rs +++ b/substrate/primitives/runtime/src/generic/digest.rs @@ -321,7 +321,7 @@ impl<'a> DigestItemRef<'a> { /// Cast this digest item into `PreRuntime` pub fn as_pre_runtime(&self) -> Option<(ConsensusEngineId, &'a [u8])> { match *self { - Self::PreRuntime(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)), + Self::PreRuntime(consensus_engine_id, data) => Some((*consensus_engine_id, data)), _ => None, } } @@ -329,7 +329,7 @@ impl<'a> DigestItemRef<'a> { /// Cast this digest item into `Consensus` pub fn as_consensus(&self) -> Option<(ConsensusEngineId, &'a [u8])> { match *self { - Self::Consensus(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)), + Self::Consensus(consensus_engine_id, data) => Some((*consensus_engine_id, data)), _ => None, } } @@ -337,7 +337,7 @@ impl<'a> DigestItemRef<'a> { /// Cast this digest item into `Seal` pub fn as_seal(&self) -> Option<(ConsensusEngineId, &'a [u8])> { match *self { - Self::Seal(consensus_engine_id, ref data) => Some((*consensus_engine_id, data)), + Self::Seal(consensus_engine_id, data) => Some((*consensus_engine_id, data)), _ => None, } } @@ -345,7 +345,7 @@ impl<'a> DigestItemRef<'a> { /// Cast this digest item into `PreRuntime` pub fn as_other(&self) -> Option<&'a [u8]> { match *self { - Self::Other(ref data) => Some(data), + Self::Other(data) => Some(data), _ => None, } } diff --git a/substrate/primitives/runtime/src/offchain/http.rs b/substrate/primitives/runtime/src/offchain/http.rs index c479062de5..dede4db5dd 100644 --- a/substrate/primitives/runtime/src/offchain/http.rs +++ b/substrate/primitives/runtime/src/offchain/http.rs @@ -452,7 +452,7 @@ impl Headers { let raw = name.as_bytes(); for &(ref key, ref val) in &self.raw { if &**key == raw { - return str::from_utf8(&val).ok() + return str::from_utf8(val).ok() } } None diff --git a/substrate/primitives/runtime/src/offchain/storage_lock.rs b/substrate/primitives/runtime/src/offchain/storage_lock.rs index 90f8df7945..4ea9030745 100644 --- a/substrate/primitives/runtime/src/offchain/storage_lock.rs +++ b/substrate/primitives/runtime/src/offchain/storage_lock.rs @@ -134,7 +134,7 @@ impl Lockable for Time { fn snooze(deadline: &Self::Deadline) { let now = offchain::timestamp(); - let remainder: Duration = now.diff(&deadline); + let remainder: Duration = now.diff(deadline); // do not snooze the full duration, but instead snooze max 100ms // it might get unlocked in another thread use core::cmp::{max, min}; diff --git a/substrate/primitives/runtime/src/runtime_string.rs b/substrate/primitives/runtime/src/runtime_string.rs index fcbdd2e787..762af0acd9 100644 --- a/substrate/primitives/runtime/src/runtime_string.rs +++ b/substrate/primitives/runtime/src/runtime_string.rs @@ -98,8 +98,8 @@ impl std::ops::Deref for RuntimeString { fn deref(&self) -> &str { match self { - Self::Borrowed(val) => &val, - Self::Owned(val) => &val, + Self::Borrowed(val) => val, + Self::Owned(val) => val, } } } diff --git a/substrate/primitives/runtime/src/traits.rs b/substrate/primitives/runtime/src/traits.rs index 9c71b2023d..dc13567df5 100644 --- a/substrate/primitives/runtime/src/traits.rs +++ b/substrate/primitives/runtime/src/traits.rs @@ -159,7 +159,7 @@ where use sp_application_crypto::IsWrappedBy; let inner: &S = self.as_ref(); let inner_pubkey = - <::Public as sp_application_crypto::AppPublic>::Generic::from_ref(&signer); + <::Public as sp_application_crypto::AppPublic>::Generic::from_ref(signer); Verify::verify(inner, msg, inner_pubkey) } } @@ -1284,7 +1284,7 @@ impl AccountIdConversion fo fn try_from_sub_account(x: &T) -> Option<(Self, S)> { x.using_encoded(|d| { - if &d[0..4] != Id::TYPE_ID { + if d[0..4] != Id::TYPE_ID { return None } let mut cursor = &d[4..]; diff --git a/substrate/primitives/sandbox/src/embedded_executor.rs b/substrate/primitives/sandbox/src/embedded_executor.rs index 8a20cc1b39..4410e26c8d 100644 --- a/substrate/primitives/sandbox/src/embedded_executor.rs +++ b/substrate/primitives/sandbox/src/embedded_executor.rs @@ -266,7 +266,7 @@ impl super::SandboxInstance for Instance { let mut externals = GuestExternals { state, defined_host_functions: &self.defined_host_functions }; - let result = self.instance.invoke_export(&name, &args, &mut externals); + let result = self.instance.invoke_export(name, &args, &mut externals); match result { Ok(None) => Ok(ReturnValue::Unit), diff --git a/substrate/primitives/state-machine/src/backend.rs b/substrate/primitives/state-machine/src/backend.rs index 8d0ac2d136..e9d4ac0fb8 100644 --- a/substrate/primitives/state-machine/src/backend.rs +++ b/substrate/primitives/state-machine/src/backend.rs @@ -197,7 +197,7 @@ pub trait Backend: sp_std::fmt::Debug { // child first for (child_info, child_delta) in child_deltas { let (child_root, empty, child_txs) = - self.child_storage_root(&child_info, child_delta, state_version); + self.child_storage_root(child_info, child_delta, state_version); let prefixed_storage_key = child_info.prefixed_storage_key(); txs.consolidate(child_txs); if empty { @@ -311,7 +311,7 @@ pub struct BackendRuntimeCode<'a, B, H> { impl<'a, B: Backend, H: Hasher> sp_core::traits::FetchRuntimeCode for BackendRuntimeCode<'a, B, H> { - fn fetch_runtime_code<'b>(&'b self) -> Option> { + fn fetch_runtime_code(&self) -> Option> { self.backend .storage(sp_core::storage::well_known_keys::CODE) .ok() diff --git a/substrate/primitives/state-machine/src/basic.rs b/substrate/primitives/state-machine/src/basic.rs index 1f257550fb..f1c09251fa 100644 --- a/substrate/primitives/state-machine/src/basic.rs +++ b/substrate/primitives/state-machine/src/basic.rs @@ -288,7 +288,7 @@ impl Externalities for BasicExternalities { let empty_hash = empty_child_trie_root::>(); for (prefixed_storage_key, child_info) in prefixed_keys { let child_root = self.child_storage_root(&child_info, state_version); - if &empty_hash[..] == &child_root[..] { + if empty_hash[..] == child_root[..] { top.remove(prefixed_storage_key.as_slice()); } else { top.insert(prefixed_storage_key.into_inner(), child_root); diff --git a/substrate/primitives/state-machine/src/ext.rs b/substrate/primitives/state-machine/src/ext.rs index 7b7e4b47f1..e33569e2a1 100644 --- a/substrate/primitives/state-machine/src/ext.rs +++ b/substrate/primitives/state-machine/src/ext.rs @@ -316,8 +316,8 @@ where match (&next_backend_key, overlay_changes.peek()) { (_, None) => next_backend_key, (Some(_), Some(_)) => { - while let Some(overlay_key) = overlay_changes.next() { - let cmp = next_backend_key.as_deref().map(|v| v.cmp(&overlay_key.0)); + for overlay_key in overlay_changes { + let cmp = next_backend_key.as_deref().map(|v| v.cmp(overlay_key.0)); // If `backend_key` is less than the `overlay_key`, we found out next key. if cmp == Some(Ordering::Less) { @@ -332,7 +332,7 @@ where // this key. next_backend_key = self .backend - .next_storage_key(&overlay_key.0) + .next_storage_key(overlay_key.0) .expect(EXT_NOT_ALLOWED_TO_FAIL); } } @@ -357,8 +357,8 @@ where match (&next_backend_key, overlay_changes.peek()) { (_, None) => next_backend_key, (Some(_), Some(_)) => { - while let Some(overlay_key) = overlay_changes.next() { - let cmp = next_backend_key.as_deref().map(|v| v.cmp(&overlay_key.0)); + for overlay_key in overlay_changes { + let cmp = next_backend_key.as_deref().map(|v| v.cmp(overlay_key.0)); // If `backend_key` is less than the `overlay_key`, we found out next key. if cmp == Some(Ordering::Less) { @@ -373,7 +373,7 @@ where // this key. next_backend_key = self .backend - .next_child_storage_key(child_info, &overlay_key.0) + .next_child_storage_key(child_info, overlay_key.0) .expect(EXT_NOT_ALLOWED_TO_FAIL); } } @@ -546,7 +546,7 @@ where .storage(prefixed_storage_key.as_slice()) .and_then(|k| Decode::decode(&mut &k[..]).ok()) // V1 is equivalent to V0 on empty root. - .unwrap_or_else(|| empty_child_trie_root::>()); + .unwrap_or_else(empty_child_trie_root::>); trace!( target: "state", method = "ChildStorageRoot", @@ -593,7 +593,7 @@ where .storage(prefixed_storage_key.as_slice()) .and_then(|k| Decode::decode(&mut &k[..]).ok()) // V1 is equivalent to V0 on empty root. - .unwrap_or_else(|| empty_child_trie_root::>()); + .unwrap_or_else(empty_child_trie_root::>); trace!( target: "state", diff --git a/substrate/primitives/state-machine/src/in_memory_backend.rs b/substrate/primitives/state-machine/src/in_memory_backend.rs index 2d8173452a..457d89b8c5 100644 --- a/substrate/primitives/state-machine/src/in_memory_backend.rs +++ b/substrate/primitives/state-machine/src/in_memory_backend.rs @@ -94,7 +94,7 @@ where H::Out: Codec + Ord, { fn clone(&self) -> Self { - TrieBackend::new(self.backend_storage().clone(), self.root().clone()) + TrieBackend::new(self.backend_storage().clone(), *self.root()) } } diff --git a/substrate/primitives/state-machine/src/lib.rs b/substrate/primitives/state-machine/src/lib.rs index 1a69d51d58..97a9ae8d88 100644 --- a/substrate/primitives/state-machine/src/lib.rs +++ b/substrate/primitives/state-machine/src/lib.rs @@ -644,7 +644,7 @@ mod execution { H::Out: Ord + 'static + codec::Codec, Spawn: SpawnNamed + Send + 'static, { - let trie_backend = create_proof_check_backend::(root.into(), proof)?; + let trie_backend = create_proof_check_backend::(root, proof)?; execution_proof_check_on_trie_backend::<_, _, _>( &trie_backend, overlay, @@ -791,7 +791,7 @@ mod execution { self.0.last().and_then(|s| s.key_values.last().map(|kv| kv.0.clone())); if let Some(child_last) = child_last { - if last.len() == 0 { + if last.is_empty() { if let Some(top_last) = top_last { last.push(top_last) } else { @@ -866,7 +866,7 @@ mod execution { .storage(&storage_key) .map_err(|e| Box::new(e) as Box)? { - child_roots.insert(state_root.clone()); + child_roots.insert(state_root); } else { return Err(Box::new("Invalid range start child trie key.")) } @@ -880,7 +880,7 @@ mod execution { let (child_info, depth) = if let Some(storage_key) = child_key.as_ref() { let storage_key = PrefixedStorageKey::new_ref(storage_key); ( - Some(match ChildType::from_prefixed_key(&storage_key) { + Some(match ChildType::from_prefixed_key(storage_key) { Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key), None => return Err(Box::new("Invalid range start child trie key.")), @@ -900,15 +900,15 @@ mod execution { None, start_at_ref, |key, value| { - if first { - if start_at_ref + if first && + start_at_ref .as_ref() .map(|start| &key.as_slice() > start) .unwrap_or(true) - { - first = false; - } + { + first = false; } + if first { true } else if depth < MAX_NESTED_TRIE_DEPTH && @@ -938,12 +938,10 @@ mod execution { if switch_child_key.is_none() { if depth == 1 { break + } else if completed { + start_at = child_key.take(); } else { - if completed { - start_at = child_key.take(); - } else { - break - } + break } } else { child_key = switch_child_key; @@ -1269,7 +1267,7 @@ mod execution { let storage_key = PrefixedStorageKey::new_ref(storage_key); ( - Some(match ChildType::from_prefixed_key(&storage_key) { + Some(match ChildType::from_prefixed_key(storage_key) { Some((ChildType::ParentKeyId, storage_key)) => ChildInfo::new_default(storage_key), None => return Err(Box::new("Invalid range start child trie key.")), @@ -1294,15 +1292,15 @@ mod execution { None, start_at_ref, |key, value| { - if first { - if start_at_ref + if first && + start_at_ref .as_ref() .map(|start| &key.as_slice() > start) .unwrap_or(true) - { - first = false; - } + { + first = false; } + if !first { values.push((key.to_vec(), value.to_vec())); } @@ -1390,7 +1388,7 @@ mod tests { let using_native = use_native && self.native_available; match (using_native, self.native_succeeds, self.fallback_succeeds, native_call) { (true, true, _, Some(call)) => { - let res = sp_externalities::set_and_run_with_externalities(ext, || call()); + let res = sp_externalities::set_and_run_with_externalities(ext, call); (res.map(NativeOrEncoded::Native).map_err(|_| 0), true) }, (true, true, _, None) | (false, _, true, None) => ( @@ -1584,13 +1582,13 @@ mod tests { .map(|(k, v)| (k.clone(), v.value().cloned())) .collect::>(), map![ - b"abc".to_vec() => None.into(), - b"abb".to_vec() => None.into(), - b"aba".to_vec() => None.into(), - b"abd".to_vec() => None.into(), + b"abc".to_vec() => None, + b"abb".to_vec() => None, + b"aba".to_vec() => None, + b"abd".to_vec() => None, - b"bab".to_vec() => Some(b"228".to_vec()).into(), - b"bbd".to_vec() => Some(b"42".to_vec()).into() + b"bab".to_vec() => Some(b"228".to_vec()), + b"bbd".to_vec() => Some(b"42".to_vec()) ], ); @@ -1608,12 +1606,12 @@ mod tests { .map(|(k, v)| (k.clone(), v.value().cloned())) .collect::>(), map![ - b"abb".to_vec() => None.into(), - b"aba".to_vec() => None.into(), - b"abd".to_vec() => None.into(), + b"abb".to_vec() => None, + b"aba".to_vec() => None, + b"abd".to_vec() => None, - b"bab".to_vec() => Some(b"228".to_vec()).into(), - b"bbd".to_vec() => Some(b"42".to_vec()).into() + b"bab".to_vec() => Some(b"228".to_vec()), + b"bbd".to_vec() => Some(b"42".to_vec()) ], ); } @@ -1647,15 +1645,15 @@ mod tests { overlay .children() .flat_map(|(iter, _child_info)| iter) - .map(|(k, v)| (k.clone(), v.value().clone())) + .map(|(k, v)| (k.clone(), v.value())) .collect::>(), map![ - b"1".to_vec() => None.into(), - b"2".to_vec() => None.into(), - b"3".to_vec() => None.into(), - b"4".to_vec() => None.into(), - b"a".to_vec() => None.into(), - b"b".to_vec() => None.into(), + b"1".to_vec() => None, + b"2".to_vec() => None, + b"3".to_vec() => None, + b"4".to_vec() => None, + b"a".to_vec() => None, + b"b".to_vec() => None, ], ); } @@ -1796,7 +1794,7 @@ mod tests { fn test_compact(remote_proof: StorageProof, remote_root: &sp_core::H256) -> StorageProof { let compact_remote_proof = - remote_proof.into_compact_proof::(remote_root.clone()).unwrap(); + remote_proof.into_compact_proof::(*remote_root).unwrap(); compact_remote_proof .to_storage_proof::(Some(remote_root)) .unwrap() @@ -1823,8 +1821,7 @@ mod tests { read_proof_check::(remote_root, remote_proof.clone(), &[b"value2"]) .unwrap(); let local_result2 = - read_proof_check::(remote_root, remote_proof.clone(), &[&[0xff]]) - .is_ok(); + read_proof_check::(remote_root, remote_proof, &[&[0xff]]).is_ok(); // check that results are correct assert_eq!( local_result1.into_iter().collect::>(), @@ -1852,7 +1849,7 @@ mod tests { .unwrap(); let local_result3 = read_child_proof_check::( remote_root, - remote_proof.clone(), + remote_proof, missing_child_info, &[b"dummy"], ) @@ -1899,7 +1896,7 @@ mod tests { let trie: InMemoryBackend = (storage.clone(), StateVersion::default()).into(); - let trie_root = trie.root().clone(); + let trie_root = trie.root(); let backend = crate::ProvingBackend::new(&trie); let mut queries = Vec::new(); for c in 0..(5 + nb_child_trie / 2) { @@ -1948,7 +1945,7 @@ mod tests { let storage_proof = backend.extract_proof(); let remote_proof = test_compact(storage_proof, &trie_root); let proof_check = - create_proof_check_backend::(trie_root, remote_proof).unwrap(); + create_proof_check_backend::(*trie_root, remote_proof).unwrap(); for (child_info, key, expected) in queries { assert_eq!( @@ -1998,15 +1995,9 @@ mod tests { prove_range_read_with_size(remote_backend, None, None, 50000, Some(&[])).unwrap(); assert_eq!(proof.clone().into_memory_db::().drain().len(), 11); assert_eq!(count, 132); - let (results, completed) = read_range_proof_check::( - remote_root, - proof.clone(), - None, - None, - None, - None, - ) - .unwrap(); + let (results, completed) = + read_range_proof_check::(remote_root, proof, None, None, None, None) + .unwrap(); assert_eq!(results.len() as u32, count); assert_eq!(completed, true); } @@ -2041,11 +2032,11 @@ mod tests { remote_proof }; - let remote_proof = check_proof(mdb.clone(), root.clone(), state_version); + let remote_proof = check_proof(mdb.clone(), root, state_version); // check full values in proof assert!(remote_proof.encode().len() > 1_100); assert!(remote_proof.encoded_size() > 1_100); - let root1 = root.clone(); + let root1 = root; // do switch state_version = StateVersion::V1; @@ -2057,9 +2048,9 @@ mod tests { trie.insert(b"foo", vec![1u8; 1000].as_slice()) // inner hash .expect("insert failed"); } - let root3 = root.clone(); + let root3 = root; assert!(root1 != root3); - let remote_proof = check_proof(mdb.clone(), root.clone(), state_version); + let remote_proof = check_proof(mdb.clone(), root, state_version); // nodes foo is replaced by its hashed value form. assert!(remote_proof.encode().len() < 1000); assert!(remote_proof.encoded_size() < 1000); @@ -2159,7 +2150,7 @@ mod tests { let remote_proof = test_compact(remote_proof, &remote_root); let local_result1 = read_child_proof_check::( remote_root, - remote_proof.clone(), + remote_proof, &child_info1, &[b"key1"], ) diff --git a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs b/substrate/primitives/state-machine/src/overlayed_changes/mod.rs index 59f3e1cffa..2161b34371 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/mod.rs @@ -513,7 +513,7 @@ impl OverlayedChanges { pub fn drain_storage_changes, H: Hasher>( &mut self, backend: &B, - mut cache: &mut StorageTransactionCache, + cache: &mut StorageTransactionCache, state_version: StateVersion, ) -> Result, DefaultError> where @@ -521,7 +521,7 @@ impl OverlayedChanges { { // If the transaction does not exist, we generate it. if cache.transaction.is_none() { - self.storage_root(backend, &mut cache, state_version); + self.storage_root(backend, cache, state_version); } let (transaction, transaction_storage_root) = cache diff --git a/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs b/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs index 9845770001..a9643c265e 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs @@ -42,7 +42,7 @@ impl OffchainOverlayedChanges { } /// Iterate over all key value pairs by reference. - pub fn iter<'a>(&'a self) -> impl Iterator> { + pub fn iter(&self) -> impl Iterator { self.0.changes().map(|kv| (kv.0, kv.1.value_ref())) } diff --git a/substrate/primitives/state-machine/src/proving_backend.rs b/substrate/primitives/state-machine/src/proving_backend.rs index eeffcc8e47..b47e6c693a 100644 --- a/substrate/primitives/state-machine/src/proving_backend.rs +++ b/substrate/primitives/state-machine/src/proving_backend.rs @@ -77,7 +77,7 @@ where .storage(storage_key)? .and_then(|r| Decode::decode(&mut &r[..]).ok()) // V1 is equivalent to V0 on empty trie - .unwrap_or_else(|| empty_child_trie_root::>()); + .unwrap_or_else(empty_child_trie_root::>); let mut read_overlay = S::Overlay::default(); let eph = Ephemeral::new(self.backend.backend_storage(), &mut read_overlay); @@ -88,7 +88,7 @@ where read_child_trie_value_with::, _, _>( child_info.keyspace(), &eph, - &root.as_ref(), + root.as_ref(), key, &mut *self.proof_recorder, ) @@ -203,7 +203,7 @@ where proof_recorder: ProofRecorder, ) -> Self { let essence = backend.essence(); - let root = essence.root().clone(); + let root = *essence.root(); let recorder = ProofRecorderBackend { backend: essence.backend_storage(), proof_recorder }; ProvingBackend(TrieBackend::new(recorder, root)) } @@ -238,7 +238,7 @@ impl<'a, S: 'a + TrieBackendStorage, H: 'a + Hasher> TrieBackendStorage } let backend_value = self.backend.get(key, prefix)?; - self.proof_recorder.record(key.clone(), backend_value.clone()); + self.proof_recorder.record(*key, backend_value.clone()); Ok(backend_value) } } @@ -395,9 +395,9 @@ mod tests { use sp_runtime::traits::BlakeTwo256; use sp_trie::PrefixedMemoryDB; - fn test_proving<'a>( - trie_backend: &'a TrieBackend, BlakeTwo256>, - ) -> ProvingBackend<'a, PrefixedMemoryDB, BlakeTwo256> { + fn test_proving( + trie_backend: &TrieBackend, BlakeTwo256>, + ) -> ProvingBackend, BlakeTwo256> { ProvingBackend::new(trie_backend) } @@ -474,7 +474,6 @@ mod tests { let trie_root = trie.storage_root(std::iter::empty(), state_version).0; assert_eq!(in_memory_root, trie_root); value_range - .clone() .for_each(|i| assert_eq!(trie.storage(&[i]).unwrap().unwrap(), vec![i; size_content])); let proving = ProvingBackend::new(trie); @@ -482,8 +481,7 @@ mod tests { let proof = proving.extract_proof(); - let proof_check = - create_proof_check_backend::(in_memory_root.into(), proof).unwrap(); + let proof_check = create_proof_check_backend::(in_memory_root, proof).unwrap(); assert_eq!(proof_check.storage(&[42]).unwrap().unwrap(), vec![42; size_content]); } @@ -530,8 +528,7 @@ mod tests { let proof = proving.extract_proof(); - let proof_check = - create_proof_check_backend::(in_memory_root.into(), proof).unwrap(); + let proof_check = create_proof_check_backend::(in_memory_root, proof).unwrap(); assert!(proof_check.storage(&[0]).is_err()); assert_eq!(proof_check.storage(&[42]).unwrap().unwrap(), vec![42]); // note that it is include in root because proof close @@ -542,8 +539,7 @@ mod tests { assert_eq!(proving.child_storage(child_info_1, &[64]), Ok(Some(vec![64]))); let proof = proving.extract_proof(); - let proof_check = - create_proof_check_backend::(in_memory_root.into(), proof).unwrap(); + let proof_check = create_proof_check_backend::(in_memory_root, proof).unwrap(); assert_eq!(proof_check.child_storage(child_info_1, &[64]).unwrap().unwrap(), vec![64]); } diff --git a/substrate/primitives/state-machine/src/trie_backend_essence.rs b/substrate/primitives/state-machine/src/trie_backend_essence.rs index 418e6f3d2d..0bbea70048 100644 --- a/substrate/primitives/state-machine/src/trie_backend_essence.rs +++ b/substrate/primitives/state-machine/src/trie_backend_essence.rs @@ -521,7 +521,7 @@ where Ok(None) => default_root, Err(e) => { warn!(target: "trie", "Failed to read child storage root: {}", e); - default_root.clone() + default_root }, }; @@ -580,16 +580,12 @@ impl<'a, S: 'a + TrieBackendStorage, H: Hasher> hash_db::HashDB for Ephemeral<'a, S, H> { fn get(&self, key: &H::Out, prefix: Prefix) -> Option { - match HashDB::get(self.overlay, key, prefix) { - Some(val) => Some(val), - None => match self.storage.get(&key, prefix) { - Ok(x) => x, - Err(e) => { - warn!(target: "trie", "Failed to read from DB: {}", e); - None - }, - }, - } + HashDB::get(self.overlay, key, prefix).or_else(|| { + self.storage.get(key, prefix).unwrap_or_else(|e| { + warn!(target: "trie", "Failed to read from DB: {}", e); + None + }) + }) } fn contains(&self, key: &H::Out, prefix: Prefix) -> bool { @@ -664,7 +660,7 @@ impl, H: Hasher> HashDB for TrieBackendEsse if *key == self.empty { return Some([0u8].to_vec()) } - match self.storage.get(&key, prefix) { + match self.storage.get(key, prefix) { Ok(x) => x, Err(e) => { warn!(target: "trie", "Failed to read from DB: {}", e); diff --git a/substrate/primitives/storage/src/lib.rs b/substrate/primitives/storage/src/lib.rs index fecd2b24db..0948cf4311 100644 --- a/substrate/primitives/storage/src/lib.rs +++ b/substrate/primitives/storage/src/lib.rs @@ -189,21 +189,21 @@ pub mod well_known_keys { /// Wasm code of the runtime. /// /// Stored as a raw byte vector. Required by substrate. - pub const CODE: &'static [u8] = b":code"; + pub const CODE: &[u8] = b":code"; /// Number of wasm linear memory pages required for execution of the runtime. /// /// The type of this value is encoded `u64`. - pub const HEAP_PAGES: &'static [u8] = b":heappages"; + pub const HEAP_PAGES: &[u8] = b":heappages"; /// Current extrinsic index (u32) is stored under this key. - pub const EXTRINSIC_INDEX: &'static [u8] = b":extrinsic_index"; + pub const EXTRINSIC_INDEX: &[u8] = b":extrinsic_index"; /// Prefix of child storage keys. - pub const CHILD_STORAGE_KEY_PREFIX: &'static [u8] = b":child_storage:"; + pub const CHILD_STORAGE_KEY_PREFIX: &[u8] = b":child_storage:"; /// Prefix of the default child storage keys in the top trie. - pub const DEFAULT_CHILD_STORAGE_KEY_PREFIX: &'static [u8] = b":child_storage:default:"; + pub const DEFAULT_CHILD_STORAGE_KEY_PREFIX: &[u8] = b":child_storage:default:"; /// Whether a key is a default child storage key. /// @@ -359,7 +359,7 @@ impl ChildType { fn do_prefix_key(&self, key: &mut Vec) { let parent_prefix = self.parent_prefix(); let key_len = key.len(); - if parent_prefix.len() > 0 { + if !parent_prefix.is_empty() { key.resize(key_len + parent_prefix.len(), 0); key.copy_within(..key_len, parent_prefix.len()); key[..parent_prefix.len()].copy_from_slice(parent_prefix); diff --git a/substrate/primitives/tracing/src/types.rs b/substrate/primitives/tracing/src/types.rs index d175e1f8f1..e7d5abfb27 100644 --- a/substrate/primitives/tracing/src/types.rs +++ b/substrate/primitives/tracing/src/types.rs @@ -639,7 +639,7 @@ mod std_features { tracing::span::Span::child_of( a.parent_id.map(tracing_core::span::Id::from_u64), - &metadata, + metadata, &tracing::valueset! { metadata.fields(), target, name, file, line, module_path, ?params }, ) } @@ -658,7 +658,7 @@ mod std_features { tracing_core::Event::child_of( self.parent_id.map(tracing_core::span::Id::from_u64), - &metadata, + metadata, &tracing::valueset! { metadata.fields(), target, name, file, line, module_path, ?params }, ) } diff --git a/substrate/primitives/transaction-storage-proof/src/lib.rs b/substrate/primitives/transaction-storage-proof/src/lib.rs index 2e5aa3b2b9..ee0c8e4ec8 100644 --- a/substrate/primitives/transaction-storage-proof/src/lib.rs +++ b/substrate/primitives/transaction-storage-proof/src/lib.rs @@ -154,7 +154,7 @@ pub mod registration { B: BlockT, C: IndexedBody, { - let parent_number = client.number(parent.clone())?.unwrap_or(Zero::zero()); + let parent_number = client.number(*parent)?.unwrap_or(Zero::zero()); let number = parent_number .saturating_add(One::one()) .saturating_sub(DEFAULT_STORAGE_PERIOD.into()); @@ -214,10 +214,10 @@ pub mod registration { trie.commit(); } if target_chunk.is_some() && target_root == Default::default() { - target_root = transaction_root.clone(); + target_root = transaction_root; chunk_proof = sp_trie::generate_trie_proof::( &db, - transaction_root.clone(), + transaction_root, &[target_chunk_key.clone()], ) .map_err(|e| Error::Application(Box::new(e)))?; diff --git a/substrate/primitives/trie/src/lib.rs b/substrate/primitives/trie/src/lib.rs index c4d4c7210b..358cb43ab4 100644 --- a/substrate/primitives/trie/src/lib.rs +++ b/substrate/primitives/trie/src/lib.rs @@ -555,7 +555,7 @@ mod tests { for (x, y) in input.iter().rev() { t.insert(x, y).unwrap(); } - t.root().clone() + *t.root() }; assert_eq!(closed_form, persistent); } @@ -571,7 +571,7 @@ mod tests { } } { - let t = TrieDB::::new(&mut memdb, &root).unwrap(); + let t = TrieDB::::new(&memdb, &root).unwrap(); assert_eq!( input.iter().map(|(i, j)| (i.to_vec(), j.to_vec())).collect::>(), t.iter() @@ -752,7 +752,7 @@ mod tests { memtrie.commit(); if *memtrie.root() != real { println!("TRIE MISMATCH"); - println!(""); + println!(); println!("{:?} vs {:?}", memtrie.root(), real); for i in &x { println!("{:#x?} -> {:#x?}", i.0, i.1); @@ -764,7 +764,7 @@ mod tests { let hashed_null_node = hashed_null_node::(); if *memtrie.root() != hashed_null_node { println!("- TRIE MISMATCH"); - println!(""); + println!(); println!("{:?} vs {:?}", memtrie.root(), hashed_null_node); for i in &x { println!("{:#x?} -> {:#x?}", i.0, i.1); diff --git a/substrate/primitives/trie/src/trie_codec.rs b/substrate/primitives/trie/src/trie_codec.rs index a7f2922715..d29f5a98f3 100644 --- a/substrate/primitives/trie/src/trie_codec.rs +++ b/substrate/primitives/trie/src/trie_codec.rs @@ -71,7 +71,7 @@ where // Only check root if expected root is passed as argument. if let Some(expected_root) = expected_root { if expected_root != &top_root { - return Err(Error::RootMismatch(top_root.clone(), expected_root.clone())) + return Err(Error::RootMismatch(top_root, *expected_root)) } } diff --git a/substrate/primitives/trie/src/trie_stream.rs b/substrate/primitives/trie/src/trie_stream.rs index a17d7c25e1..ca798db47b 100644 --- a/substrate/primitives/trie/src/trie_stream.rs +++ b/substrate/primitives/trie/src/trie_stream.rs @@ -53,7 +53,7 @@ fn branch_node_bit_mask(has_children: impl Iterator) -> (u8, u8) { } /// Create a leaf/branch node, encoding a number of nibbles. -fn fuse_nibbles_node<'a>(nibbles: &'a [u8], kind: NodeKind) -> impl Iterator + 'a { +fn fuse_nibbles_node(nibbles: &[u8], kind: NodeKind) -> impl Iterator + '_ { let size = sp_std::cmp::min(trie_constants::NIBBLE_SIZE_BOUND, nibbles.len()); let iter_start = match kind { diff --git a/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs b/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs index 9ca1a67cc7..ee81940b53 100644 --- a/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs +++ b/substrate/primitives/version/proc-macro/src/decl_runtime_version.rs @@ -105,7 +105,7 @@ impl ParseRuntimeVersion { parser: impl FnOnce(&Expr) -> Result, ) -> Result<()> { if value.is_some() { - return Err(Error::new(field.span(), "field is already initialized before")) + Err(Error::new(field.span(), "field is already initialized before")) } else { *value = Some(parser(&field.expr)?); Ok(()) diff --git a/substrate/primitives/wasm-interface/src/wasmi_impl.rs b/substrate/primitives/wasm-interface/src/wasmi_impl.rs index 2239eb5f38..977b4fc606 100644 --- a/substrate/primitives/wasm-interface/src/wasmi_impl.rs +++ b/substrate/primitives/wasm-interface/src/wasmi_impl.rs @@ -73,7 +73,7 @@ impl From for wasmi::Signature { impl From<&wasmi::Signature> for Signature { fn from(sig: &wasmi::Signature) -> Self { Signature::new( - sig.params().into_iter().copied().map(Into::into).collect::>(), + sig.params().iter().copied().map(Into::into).collect::>(), sig.return_type().map(Into::into), ) } diff --git a/substrate/test-utils/client/src/lib.rs b/substrate/test-utils/client/src/lib.rs index 94a350b5f5..cdadfb0f10 100644 --- a/substrate/test-utils/client/src/lib.rs +++ b/substrate/test-utils/client/src/lib.rs @@ -342,7 +342,7 @@ impl RpcHandlersExt for RpcHandlers { extrinsic: OpaqueExtrinsic, ) -> Pin> + Send>> { let (tx, rx) = futures::channel::mpsc::unbounded(); - let mem = RpcSession::new(tx.into()); + let mem = RpcSession::new(tx); Box::pin( self.rpc_query( &mem, diff --git a/substrate/test-utils/runtime/src/genesismap.rs b/substrate/test-utils/runtime/src/genesismap.rs index 71118b4183..3ece5165e1 100644 --- a/substrate/test-utils/runtime/src/genesismap.rs +++ b/substrate/test-utils/runtime/src/genesismap.rs @@ -67,7 +67,7 @@ impl GenesisConfig { (well_known_keys::CODE.into(), wasm_runtime), ( well_known_keys::HEAP_PAGES.into(), - vec![].and(&(self.heap_pages_override.unwrap_or(16 as u64))), + vec![].and(&(self.heap_pages_override.unwrap_or(16_u64))), ), ] .into_iter(), @@ -80,8 +80,7 @@ impl GenesisConfig { // Assimilate the system genesis config. let mut storage = Storage { top: map, children_default: self.extra_storage.children_default.clone() }; - let mut config = system::GenesisConfig::default(); - config.authorities = self.authorities.clone(); + let config = system::GenesisConfig { authorities: self.authorities.clone() }; config .assimilate_storage(&mut storage) .expect("Adding `system::GensisConfig` to the genesis"); diff --git a/substrate/test-utils/runtime/src/system.rs b/substrate/test-utils/runtime/src/system.rs index 6df35421d3..77cd18c028 100644 --- a/substrate/test-utils/runtime/src/system.rs +++ b/substrate/test-utils/runtime/src/system.rs @@ -77,7 +77,7 @@ pub fn initialize_block(header: &Header) { // try to read something that depends on current header digest // so that it'll be included in execution proof if let Some(generic::DigestItem::Other(v)) = header.digest().logs().iter().next() { - let _: Option = storage::unhashed::get(&v); + let _: Option = storage::unhashed::get(v); } } diff --git a/substrate/utils/fork-tree/src/lib.rs b/substrate/utils/fork-tree/src/lib.rs index c23a4f55f4..b4985b7729 100644 --- a/substrate/utils/fork-tree/src/lib.rs +++ b/substrate/utils/fork-tree/src/lib.rs @@ -374,7 +374,7 @@ where let node = self.roots.swap_remove(position); self.roots = node.children; self.best_finalized_number = Some(node.number); - return node.data + node.data } /// Finalize a node in the tree. This method will make sure that the node @@ -539,18 +539,17 @@ where // tree, if we find a valid node that passes the predicate then we must // ensure that we're not finalizing past any of its child nodes. for node in self.node_iter() { - if predicate(&node.data) { - if node.hash == *hash || is_descendent_of(&node.hash, hash)? { - for child in node.children.iter() { - if child.number <= number && - (child.hash == *hash || is_descendent_of(&child.hash, hash)?) - { - return Err(Error::UnfinalizedAncestor) - } + if predicate(&node.data) && (node.hash == *hash || is_descendent_of(&node.hash, hash)?) + { + for child in node.children.iter() { + if child.number <= number && + (child.hash == *hash || is_descendent_of(&child.hash, hash)?) + { + return Err(Error::UnfinalizedAncestor) } - - return Ok(Some(self.roots.iter().any(|root| root.hash == node.hash))) } + + return Ok(Some(self.roots.iter().any(|root| root.hash == node.hash))) } } @@ -587,19 +586,18 @@ where // we're not finalizing past any children node. let mut position = None; for (i, root) in self.roots.iter().enumerate() { - if predicate(&root.data) { - if root.hash == *hash || is_descendent_of(&root.hash, hash)? { - for child in root.children.iter() { - if child.number <= number && - (child.hash == *hash || is_descendent_of(&child.hash, hash)?) - { - return Err(Error::UnfinalizedAncestor) - } + if predicate(&root.data) && (root.hash == *hash || is_descendent_of(&root.hash, hash)?) + { + for child in root.children.iter() { + if child.number <= number && + (child.hash == *hash || is_descendent_of(&child.hash, hash)?) + { + return Err(Error::UnfinalizedAncestor) } - - position = Some(i); - break } + + position = Some(i); + break } } @@ -1071,16 +1069,13 @@ mod test { let finalize_a = || { let (mut tree, ..) = test_fork_tree(); - assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), - vec![("A", 1)], - ); + assert_eq!(tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("A", 1)]); // finalizing "A" opens up three possible forks tree.finalize_root(&"A"); assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), + tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("B", 2), ("F", 2), ("J", 2)], ); @@ -1093,10 +1088,7 @@ mod test { // finalizing "B" will progress on its fork and remove any other competing forks tree.finalize_root(&"B"); - assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), - vec![("C", 3)], - ); + assert_eq!(tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("C", 3)],); // all the other forks have been pruned assert!(tree.roots.len() == 1); @@ -1108,10 +1100,7 @@ mod test { // finalizing "J" will progress on its fork and remove any other competing forks tree.finalize_root(&"J"); - assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), - vec![("K", 3)], - ); + assert_eq!(tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("K", 3)],); // all the other forks have been pruned assert!(tree.roots.len() == 1); @@ -1136,7 +1125,7 @@ mod test { ); assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), + tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("B", 2), ("F", 2), ("J", 2)], ); @@ -1160,7 +1149,7 @@ mod test { ); assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), + tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("L", 4), ("I", 4)], ); @@ -1194,7 +1183,7 @@ mod test { ); assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), + tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("B", 2), ("F", 2), ("J", 2)], ); @@ -1208,7 +1197,7 @@ mod test { ); assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), + tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("L", 4), ("I", 4)], ); @@ -1224,10 +1213,7 @@ mod test { Ok(FinalizationResult::Changed(None)), ); - assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), - vec![], - ); + assert_eq!(tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![],); assert_eq!(tree.best_finalized_number, Some(6)); } @@ -1306,10 +1292,7 @@ mod test { Ok(FinalizationResult::Changed(None)), ); - assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), - vec![("A0", 1)], - ); + assert_eq!(tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("A0", 1)],); // finalizing "C" will finalize the node "A0" and prune it out of the tree assert_eq!( @@ -1327,10 +1310,7 @@ mod test { Ok(FinalizationResult::Changed(Some(Change { effective: 5 }))), ); - assert_eq!( - tree.roots().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), - vec![("D", 10)], - ); + assert_eq!(tree.roots().map(|(h, n, _)| (*h, *n)).collect::>(), vec![("D", 10)],); // finalizing "F" will fail since it would finalize past "E" without finalizing "D" first assert_eq!( @@ -1359,7 +1339,7 @@ mod test { fn iter_iterates_in_preorder() { let (tree, ..) = test_fork_tree(); assert_eq!( - tree.iter().map(|(h, n, _)| (h.clone(), n.clone())).collect::>(), + tree.iter().map(|(h, n, _)| (*h, *n)).collect::>(), vec![ ("A", 1), ("B", 2), diff --git a/substrate/utils/frame/benchmarking-cli/src/overhead/template.rs b/substrate/utils/frame/benchmarking-cli/src/overhead/template.rs index d5f90d4873..44e2c1f02e 100644 --- a/substrate/utils/frame/benchmarking-cli/src/overhead/template.rs +++ b/substrate/utils/frame/benchmarking-cli/src/overhead/template.rs @@ -31,7 +31,7 @@ use crate::{ shared::{Stats, UnderscoreHelper}, }; -static VERSION: &'static str = env!("CARGO_PKG_VERSION"); +static VERSION: &str = env!("CARGO_PKG_VERSION"); static TEMPLATE: &str = include_str!("./weights.hbs"); /// Data consumed by Handlebar to fill out the `weights.hbs` template. @@ -93,13 +93,13 @@ impl TemplateData { let mut fd = fs::File::create(&out_path)?; info!("Writing weights to {:?}", fs::canonicalize(&out_path)?); handlebars - .render_template_to_write(&TEMPLATE, &self, &mut fd) + .render_template_to_write(TEMPLATE, &self, &mut fd) .map_err(|e| format!("HBS template write: {:?}", e).into()) } /// Build a path for the weight file. fn build_path(&self, weight_out: &Option) -> Result { - let mut path = weight_out.clone().unwrap_or(PathBuf::from(".")); + let mut path = weight_out.clone().unwrap_or_else(|| PathBuf::from(".")); if !path.is_dir() { return Err("Need directory as --weight-path".into()) diff --git a/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs b/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs index 89b8d018bc..660f31b8f1 100644 --- a/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs +++ b/substrate/utils/frame/benchmarking-cli/src/pallet/command.rs @@ -123,9 +123,9 @@ impl PalletCmd { let spec = config.chain_spec; let wasm_method = self.wasm_method.into(); let strategy = self.execution.unwrap_or(ExecutionStrategy::Native); - let pallet = self.pallet.clone().unwrap_or_else(|| String::new()); + let pallet = self.pallet.clone().unwrap_or_default(); let pallet = pallet.as_bytes(); - let extrinsic = self.extrinsic.clone().unwrap_or_else(|| String::new()); + let extrinsic = self.extrinsic.clone().unwrap_or_default(); let extrinsic_split: Vec<&str> = extrinsic.split(',').collect(); let extrinsics: Vec<_> = extrinsic_split.iter().map(|x| x.trim().as_bytes()).collect(); @@ -155,7 +155,7 @@ impl PalletCmd { extensions.register(OffchainWorkerExt::new(offchain.clone())); extensions.register(OffchainDbExt::new(offchain)); extensions.register(TransactionPoolExt::new(pool)); - return extensions + extensions }; // Get Benchmark List @@ -339,7 +339,7 @@ impl PalletCmd { batches.extend(batch); // Show progress information - if let Some(elapsed) = timer.elapsed().ok() { + if let Ok(elapsed) = timer.elapsed() { if elapsed >= time::Duration::from_secs(5) { timer = time::SystemTime::now(); log::info!( @@ -401,7 +401,7 @@ impl PalletCmd { batches: &Vec, storage_info: &Vec, ) { - for batch in batches.into_iter() { + for batch in batches.iter() { // Print benchmark metadata println!( "Pallet: {:?}, Extrinsic: {:?}, Lowest values: {:?}, Highest values: {:?}, Steps: {:?}, Repeat: {:?}", @@ -420,12 +420,12 @@ impl PalletCmd { if !self.no_storage_info { let mut comments: Vec = Default::default(); - writer::add_storage_comments(&mut comments, &batch.db_results, &storage_info); + writer::add_storage_comments(&mut comments, &batch.db_results, storage_info); println!("Raw Storage Info\n========"); for comment in comments { println!("{}", comment); } - println!(""); + println!(); } // Conduct analysis. @@ -446,7 +446,7 @@ impl PalletCmd { { println!("Writes = {:?}", analysis); } - println!(""); + println!(); } if !self.no_min_squares { println!("Min Squares Analysis\n========"); @@ -465,7 +465,7 @@ impl PalletCmd { { println!("Writes = {:?}", analysis); } - println!(""); + println!(); } } } diff --git a/substrate/utils/frame/benchmarking-cli/src/pallet/writer.rs b/substrate/utils/frame/benchmarking-cli/src/pallet/writer.rs index 81b20ad445..515582d8c6 100644 --- a/substrate/utils/frame/benchmarking-cli/src/pallet/writer.rs +++ b/substrate/utils/frame/benchmarking-cli/src/pallet/writer.rs @@ -35,7 +35,7 @@ use frame_support::traits::StorageInfo; use sp_core::hexdisplay::HexDisplay; use sp_runtime::traits::Zero; -const VERSION: &'static str = env!("CARGO_PKG_VERSION"); +const VERSION: &str = env!("CARGO_PKG_VERSION"); const TEMPLATE: &str = include_str!("./template.hbs"); // This is the final structure we will pass to the Handlebars template. @@ -280,12 +280,12 @@ pub fn write_results( // Which analysis function should be used when outputting benchmarks let analysis_choice: AnalysisChoice = - cmd.output_analysis.clone().try_into().map_err(|e| io_error(e))?; + cmd.output_analysis.clone().try_into().map_err(io_error)?; // Capture individual args let cmd_data = CmdData { - steps: cmd.steps.clone(), - repeat: cmd.repeat.clone(), + steps: cmd.steps, + repeat: cmd.repeat, lowest_range_values: cmd.lowest_range_values.clone(), highest_range_values: cmd.highest_range_values.clone(), execution: format!("{:?}", cmd.execution), @@ -374,7 +374,7 @@ pub(crate) fn add_storage_comments( // This tracks the keys we already identified, so we only generate a single comment. let mut identified = HashSet::>::new(); - for result in results.clone() { + for result in results { for (key, reads, writes, whitelisted) in &result.keys { // skip keys which are whitelisted if *whitelisted { diff --git a/substrate/utils/frame/benchmarking-cli/src/shared/stats.rs b/substrate/utils/frame/benchmarking-cli/src/shared/stats.rs index 7785965fed..3234d5f2f9 100644 --- a/substrate/utils/frame/benchmarking-cli/src/shared/stats.rs +++ b/substrate/utils/frame/benchmarking-cli/src/shared/stats.rs @@ -73,7 +73,7 @@ impl Stats { if xs.is_empty() { return Err("Empty input is invalid".into()) } - let (avg, stddev) = Self::avg_and_stddev(&xs); + let (avg, stddev) = Self::avg_and_stddev(xs); Ok(Self { sum: xs.iter().sum(), @@ -112,7 +112,7 @@ impl Stats { /// Returns the specified percentile for the given data. /// This is best effort since it ignores the interpolation case. fn percentile(mut xs: Vec, p: f64) -> u64 { - xs.sort(); + xs.sort_unstable(); let index = (xs.len() as f64 * p).ceil() as usize - 1; xs[index.clamp(0, xs.len() - 1)] } @@ -120,9 +120,9 @@ impl Stats { impl fmt::Debug for Stats { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "Total: {}\n", self.sum)?; - write!(f, "Min: {}, Max: {}\n", self.min, self.max)?; - write!(f, "Average: {}, Median: {}, Stddev: {}\n", self.avg, self.median, self.stddev)?; + writeln!(f, "Total: {}", self.sum)?; + writeln!(f, "Min: {}, Max: {}", self.min, self.max)?; + writeln!(f, "Average: {}, Median: {}, Stddev: {}", self.avg, self.median, self.stddev)?; write!(f, "Percentiles 99th, 95th, 75th: {}, {}, {}", self.p99, self.p95, self.p75) } } diff --git a/substrate/utils/frame/benchmarking-cli/src/storage/template.rs b/substrate/utils/frame/benchmarking-cli/src/storage/template.rs index 26aa8a9623..8365c3841d 100644 --- a/substrate/utils/frame/benchmarking-cli/src/storage/template.rs +++ b/substrate/utils/frame/benchmarking-cli/src/storage/template.rs @@ -25,7 +25,7 @@ use std::{env, fs, path::PathBuf}; use super::cmd::StorageParams; use crate::shared::{Stats, UnderscoreHelper}; -static VERSION: &'static str = env!("CARGO_PKG_VERSION"); +static VERSION: &str = env!("CARGO_PKG_VERSION"); static TEMPLATE: &str = include_str!("./weights.hbs"); /// Data consumed by Handlebar to fill out the `weights.hbs` template. diff --git a/substrate/utils/frame/frame-utilities-cli/src/pallet_id.rs b/substrate/utils/frame/frame-utilities-cli/src/pallet_id.rs index c39bee8b87..c0a221d4bc 100644 --- a/substrate/utils/frame/frame-utilities-cli/src/pallet_id.rs +++ b/substrate/utils/frame/frame-utilities-cli/src/pallet_id.rs @@ -64,7 +64,7 @@ impl PalletIdCmd { R::AccountId: Ss58Codec, { if self.id.len() != 8 { - Err("a module id must be a string of 8 characters")? + return Err("a module id must be a string of 8 characters".into()) } let password = self.keystore_params.read_password()?; @@ -80,7 +80,7 @@ impl PalletIdCmd { &account_id.to_ss58check_with_version(unwrap_or_default_ss58_version(self.network)), password, self.network, - self.output_scheme.output_type.clone() + self.output_scheme.output_type ) ); diff --git a/substrate/utils/frame/remote-externalities/src/lib.rs b/substrate/utils/frame/remote-externalities/src/lib.rs index a717a93f07..1d9dc5dcd1 100644 --- a/substrate/utils/frame/remote-externalities/src/lib.rs +++ b/substrate/utils/frame/remote-externalities/src/lib.rs @@ -275,8 +275,8 @@ impl Default for Builder { impl Builder { fn as_online(&self) -> &OnlineConfig { match &self.mode { - Mode::Online(config) => &config, - Mode::OfflineOrElseOnline(_, config) => &config, + Mode::Online(config) => config, + Mode::OfflineOrElseOnline(_, config) => config, _ => panic!("Unexpected mode: Online"), } } @@ -380,7 +380,7 @@ impl Builder { log::error!( target: LOG_TARGET, "failed to execute batch: {:?}. Error: {:?}", - chunk_keys.iter().map(|k| HexDisplay::from(k)).collect::>(), + chunk_keys.iter().map(HexDisplay::from).collect::>(), e ); "batch failed." @@ -388,7 +388,7 @@ impl Builder { assert_eq!(chunk_keys.len(), values.len()); - for (idx, key) in chunk_keys.into_iter().enumerate() { + for (idx, key) in chunk_keys.iter().enumerate() { let maybe_value = values[idx].clone(); let value = maybe_value.unwrap_or_else(|| { log::warn!(target: LOG_TARGET, "key {:?} had none corresponding value.", &key); @@ -452,7 +452,7 @@ impl Builder { assert_eq!(batch_child_key.len(), batch_response.len()); - for (idx, key) in batch_child_key.into_iter().enumerate() { + for (idx, key) in batch_child_key.iter().enumerate() { let maybe_value = batch_response[idx].clone(); let value = maybe_value.unwrap_or_else(|| { log::warn!(target: LOG_TARGET, "key {:?} had none corresponding value.", &key); @@ -571,7 +571,7 @@ impl Builder { &self, top_kv: &[KeyValue], ) -> Result { - let child_kv = self.load_child_remote(&top_kv).await?; + let child_kv = self.load_child_remote(top_kv).await?; if let Some(c) = &self.as_online().state_snapshot { self.save_child_snapshot(&child_kv, &c.path)?; } @@ -612,7 +612,7 @@ impl Builder { }, }; - child_kv.push((ChildInfo::new_default(&un_prefixed), child_kv_inner)); + child_kv.push((ChildInfo::new_default(un_prefixed), child_kv_inner)); } Ok(child_kv) @@ -624,8 +624,7 @@ impl Builder { let at = self .as_online() .at - .expect("online config must be initialized by this point; qed.") - .clone(); + .expect("online config must be initialized by this point; qed."); log::info!(target: LOG_TARGET, "scraping key-pairs from remote @ {:?}", at); let mut keys_and_values = if config.pallets.len() > 0 { @@ -848,7 +847,7 @@ impl Builder { info!( target: LOG_TARGET, "injecting a total of {} child keys", - child_kv.iter().flat_map(|(_, kv)| kv).count(), + child_kv.iter().flat_map(|(_, kv)| kv).count() ); for (info, key_values) in child_kv { diff --git a/substrate/utils/frame/rpc/state-trie-migration-rpc/src/lib.rs b/substrate/utils/frame/rpc/state-trie-migration-rpc/src/lib.rs index 98a3cf9648..2e3dd08a7d 100644 --- a/substrate/utils/frame/rpc/state-trie-migration-rpc/src/lib.rs +++ b/substrate/utils/frame/rpc/state-trie-migration-rpc/src/lib.rs @@ -73,7 +73,7 @@ where return Err("No access to trie from backend.".to_string()) }; let essence = trie_backend.essence(); - let (nb_to_migrate, trie) = count_migrate(essence, &essence.root())?; + let (nb_to_migrate, trie) = count_migrate(essence, essence.root())?; let mut nb_to_migrate_child = 0; let mut child_roots: Vec<(ChildInfo, Vec)> = Vec::new(); diff --git a/substrate/utils/frame/try-runtime/cli/src/commands/execute_block.rs b/substrate/utils/frame/try-runtime/cli/src/commands/execute_block.rs index b1a56f7e8f..12c36955c2 100644 --- a/substrate/utils/frame/try-runtime/cli/src/commands/execute_block.rs +++ b/substrate/utils/frame/try-runtime/cli/src/commands/execute_block.rs @@ -76,12 +76,12 @@ impl ExecuteBlockCmd { ::Err: Debug, { match (&self.block_at, &self.state) { - (Some(block_at), State::Snap { .. }) => hash_of::(&block_at), + (Some(block_at), State::Snap { .. }) => hash_of::(block_at), (Some(block_at), State::Live { .. }) => { log::warn!(target: LOG_TARGET, "--block-at is provided while state type is live. the `Live::at` will be ignored"); - hash_of::(&block_at) + hash_of::(block_at) }, - (None, State::Live { at: Some(at), .. }) => hash_of::(&at), + (None, State::Live { at: Some(at), .. }) => hash_of::(at), _ => { panic!("either `--block-at` must be provided, or state must be `live with a proper `--at``"); }, diff --git a/substrate/utils/frame/try-runtime/cli/src/commands/follow_chain.rs b/substrate/utils/frame/try-runtime/cli/src/commands/follow_chain.rs index db305fa590..e2e6bd7244 100644 --- a/substrate/utils/frame/try-runtime/cli/src/commands/follow_chain.rs +++ b/substrate/utils/frame/try-runtime/cli/src/commands/follow_chain.rs @@ -31,8 +31,8 @@ use sp_core::H256; use sp_runtime::traits::{Block as BlockT, Header, NumberFor}; use std::{fmt::Debug, str::FromStr}; -const SUB: &'static str = "chain_subscribeFinalizedHeads"; -const UN_SUB: &'static str = "chain_unsubscribeFinalizedHeads"; +const SUB: &str = "chain_subscribeFinalizedHeads"; +const UN_SUB: &str = "chain_unsubscribeFinalizedHeads"; /// Configurations of the [`Command::FollowChain`]. #[derive(Debug, Clone, clap::Parser)] @@ -68,7 +68,7 @@ where log::info!(target: LOG_TARGET, "subscribing to {:?} / {:?}", SUB, UN_SUB); let mut subscription: Subscription = - client.subscribe(&SUB, None, &UN_SUB).await.unwrap(); + client.subscribe(SUB, None, UN_SUB).await.unwrap(); let (code_key, code) = extract_code(&config.chain_spec)?; let executor = build_executor::(&shared, &config); @@ -104,7 +104,7 @@ where if maybe_state_ext.is_none() { let builder = Builder::::new().mode(Mode::Online(OnlineConfig { transport: command.uri.clone().into(), - at: Some(header.parent_hash().clone()), + at: Some(*header.parent_hash()), ..Default::default() })); @@ -136,7 +136,7 @@ where maybe_state_ext.as_mut().expect("state_ext either existed or was just created"); let (mut changes, encoded_result) = state_machine_call_with_proof::( - &state_ext, + state_ext, &executor, execution, "TryRuntime_execute_block_no_check", diff --git a/substrate/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs b/substrate/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs index 72136e9236..9aad901829 100644 --- a/substrate/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs +++ b/substrate/utils/frame/try-runtime/cli/src/commands/offchain_worker.rs @@ -68,12 +68,12 @@ impl OffchainWorkerCmd { ::Err: Debug, { match (&self.header_at, &self.state) { - (Some(header_at), State::Snap { .. }) => hash_of::(&header_at), + (Some(header_at), State::Snap { .. }) => hash_of::(header_at), (Some(header_at), State::Live { .. }) => { log::error!(target: LOG_TARGET, "--header-at is provided while state type is live, this will most likely lead to a nonsensical result."); - hash_of::(&header_at) + hash_of::(header_at) }, - (None, State::Live { at: Some(at), .. }) => hash_of::(&at), + (None, State::Live { at: Some(at), .. }) => hash_of::(at), _ => { panic!("either `--header-at` must be provided, or state must be `live` with a proper `--at`"); }, diff --git a/substrate/utils/frame/try-runtime/cli/src/lib.rs b/substrate/utils/frame/try-runtime/cli/src/lib.rs index a904725983..c13bbb3626 100644 --- a/substrate/utils/frame/try-runtime/cli/src/lib.rs +++ b/substrate/utils/frame/try-runtime/cli/src/lib.rs @@ -296,7 +296,7 @@ use std::{fmt::Debug, path::PathBuf, str::FromStr}; mod commands; pub(crate) mod parse; -pub(crate) const LOG_TARGET: &'static str = "try-runtime::cli"; +pub(crate) const LOG_TARGET: &str = "try-runtime::cli"; /// Possible commands of `try-runtime`. #[derive(Debug, Clone, clap::Subcommand)] @@ -738,7 +738,7 @@ pub(crate) fn state_machine_call_with_proof( executor: &NativeElseWasmExecutor, ) -> (String, u32, sp_core::storage::StateVersion) { let (_, encoded) = state_machine_call::( - &ext, - &executor, + ext, + executor, sc_cli::ExecutionStrategy::NativeElseWasm, "Core_version", &[], diff --git a/substrate/utils/wasm-builder/src/wasm_project.rs b/substrate/utils/wasm-builder/src/wasm_project.rs index e94703b610..005b428a3c 100644 --- a/substrate/utils/wasm-builder/src/wasm_project.rs +++ b/substrate/utils/wasm-builder/src/wasm_project.rs @@ -359,10 +359,11 @@ fn project_enabled_features( // this heuristic anymore. However, for the transition phase between now and namespaced // features already being present in nightly, we need this code to make // runtimes compile with all the possible rustc versions. - if v.len() == 1 && v.get(0).map_or(false, |v| *v == format!("dep:{}", f)) { - if std_enabled.as_ref().map(|e| e.iter().any(|ef| ef == *f)).unwrap_or(false) { - return false - } + if v.len() == 1 && + v.get(0).map_or(false, |v| *v == format!("dep:{}", f)) && + std_enabled.as_ref().map(|e| e.iter().any(|ef| ef == *f)).unwrap_or(false) + { + return false } // We don't want to enable the `std`/`default` feature for the wasm build and @@ -409,7 +410,7 @@ fn create_project( fs::create_dir_all(wasm_project_folder.join("src")) .expect("Wasm project dir create can not fail; qed"); - let mut enabled_features = project_enabled_features(&project_cargo_toml, &crate_metadata); + let mut enabled_features = project_enabled_features(project_cargo_toml, crate_metadata); if has_runtime_wasm_feature_declared(project_cargo_toml, crate_metadata) { enabled_features.push("runtime-wasm".into()); @@ -422,7 +423,7 @@ fn create_project( &wasm_project_folder, workspace_root_path, &crate_name, - &crate_path, + crate_path, &wasm_binary, enabled_features.into_iter(), ); @@ -788,7 +789,7 @@ fn package_rerun_if_changed(package: &DeduplicatePackage) { .filter(|p| { p.is_dir() || p.extension().map(|e| e == "rs" || e == "toml").unwrap_or_default() }) - .for_each(|p| rerun_if_changed(p)); + .for_each(rerun_if_changed); } /// Copy the WASM binary to the target directory set in `WASM_TARGET_DIRECTORY` environment