git.delta.rocks / unique-network / refs/commits / 940b0a339ab0

difftreelog

fix clippy warnings

Grigoriy Simonov2023-06-05parent: #e7cba9a.patch.diff
in: master

36 files changed

modifiednode/cli/src/chain_spec.rsdiffbeforeafterboth
--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -110,7 +110,7 @@
 
 /// Helper function to generate a crypto pair from seed
 pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
-	TPublic::Pair::from_string(&format!("//{}", seed), None)
+	TPublic::Pair::from_string(&format!("//{seed}"), None)
 		.expect("static values are valid; qed")
 		.public()
 }
modifiednode/cli/src/command.rsdiffbeforeafterboth
--- a/node/cli/src/command.rs
+++ b/node/cli/src/command.rs
@@ -83,7 +83,7 @@
 		"" | "local" => Box::new(chain_spec::local_testnet_config()),
 		path => {
 			let path = std::path::PathBuf::from(path);
-			let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path.clone())?)
+			let chain_spec = Box::new(chain_spec::OpalChainSpec::from_json_file(path)?)
 				as Box<dyn sc_service::ChainSpec>;
 
 			match chain_spec.runtime_id() {
@@ -352,7 +352,7 @@
 					&polkadot_cli,
 					config.tokio_handle.clone(),
 				)
-				.map_err(|err| format!("Relay chain argument error: {}", err))?;
+				.map_err(|err| format!("Relay chain argument error: {err}"))?;
 
 				cmd.run(config, polkadot_config)
 			})
@@ -464,7 +464,7 @@
 			runner.run_node_until_exit(|config| async move {
 				let hwbench = if !cli.no_hardware_benchmarks {
 					config.database.path().map(|database_path| {
-						let _ = std::fs::create_dir_all(&database_path);
+						let _ = std::fs::create_dir_all(database_path);
 						sc_sysinfo::gather_hwbench(Some(database_path))
 					})
 				} else {
@@ -513,7 +513,7 @@
 				let state_version =
 					RelayChainCli::native_runtime_version(&config.chain_spec).state_version();
 				let block: Block = generate_genesis_block(&*config.chain_spec, state_version)
-					.map_err(|e| format!("{:?}", e))?;
+					.map_err(|e| format!("{e:?}"))?;
 				let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode()));
 				let genesis_hash = format!("0x{:?}", HexDisplay::from(&block.header().hash().0));
 
@@ -522,7 +522,7 @@
 					&polkadot_cli,
 					config.tokio_handle.clone(),
 				)
-				.map_err(|err| format!("Relay chain argument error: {}", err))?;
+				.map_err(|err| format!("Relay chain argument error: {err}"))?;
 
 				info!("Parachain id: {:?}", para_id);
 				info!("Parachain Account: {}", parachain_account);
modifiednode/cli/src/service.rsdiffbeforeafterboth
--- a/node/cli/src/service.rs
+++ b/node/cli/src/service.rs
@@ -698,7 +698,7 @@
 {
 	let slot_duration = cumulus_client_consensus_aura::slot_duration(&*client)?;
 
-	let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
+	let block_import = ParachainBlockImport::new(client.clone(), backend);
 
 	cumulus_client_consensus_aura::import_queue::<
 		sp_consensus_aura::sr25519::AuthorityPair,
@@ -709,7 +709,7 @@
 		_,
 	>(cumulus_client_consensus_aura::ImportQueueParams {
 		block_import,
-		client: client.clone(),
+		client,
 		create_inherent_data_providers: move |_, _| async move {
 			let time = sp_timestamp::InherentDataProvider::from_system_time();
 
@@ -787,7 +787,7 @@
 				telemetry.clone(),
 			);
 
-			let block_import = ParachainBlockImport::new(client.clone(), backend.clone());
+			let block_import = ParachainBlockImport::new(client.clone(), backend);
 
 			Ok(AuraConsensus::build::<
 				sp_consensus_aura::sr25519::AuthorityPair,
@@ -864,7 +864,7 @@
 	ExecutorDispatch: NativeExecutionDispatch + 'static,
 {
 	Ok(sc_consensus_manual_seal::import_queue(
-		Box::new(client.clone()),
+		Box::new(client),
 		&task_manager.spawn_essential_handle(),
 		config.prometheus_registry(),
 	))
@@ -956,7 +956,7 @@
 
 	let collator = config.role.is_authority();
 
-	let select_chain = maybe_select_chain.clone();
+	let select_chain = maybe_select_chain;
 
 	if collator {
 		let block_import =
modifiednode/rpc/src/lib.rsdiffbeforeafterboth
--- a/node/rpc/src/lib.rs
+++ b/node/rpc/src/lib.rs
@@ -289,7 +289,7 @@
 	io.merge(
 		Net::new(
 			client.clone(),
-			network.clone(),
+			network,
 			// Whether to format the `peer_count` response as Hex (default) or not.
 			true,
 		)
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -296,7 +296,7 @@
 
 			if !block_pending.is_empty() {
 				block_pending.into_iter().for_each(|(staker, amount)| {
-					Self::get_frozen_balance(&staker).map(|b| {
+					if let Some(b) = Self::get_frozen_balance(&staker) {
 						let new_state = b.checked_sub(&amount).unwrap_or_default();
 
 						// In this case, setting a new state for the frozen funds cannot fail
@@ -305,7 +305,7 @@
 						// that we cannot (in the current implementation) unfreeze more funds
 						// than were originally frozen by the pallet. Either way, `on_initialize()` cannot fail.
 						Self::set_freeze_unchecked(&staker, new_state);
-					});
+					};
 				});
 			}
 
@@ -598,8 +598,8 @@
 			// this value is set for the stakers to whom the recalculation will be performed
 			let next_recalc_block = current_recalc_block + config.recalculation_interval;
 
-			let mut storage_iterator = Self::get_next_calculated_key()
-				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));
+			let storage_iterator =
+				Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);
 
 			PreviousCalculatedRecord::<T>::set(None);
 
@@ -658,10 +658,8 @@
 				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)
 				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out
 				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)
-				while let Some((
-					(current_id, staked_block),
-					(amount, next_recalc_block_for_stake),
-				)) = storage_iterator.next()
+				for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in
+					storage_iterator
 				{
 					// last_id is not equal current_id when we switch to handling a new staker address
 					// or just start handling the very first address. In the latter case last_id will be None and
@@ -859,11 +857,11 @@
 				if acc_amount < balance_per_block {
 					let res = (block, balance_per_block - acc_amount);
 					acc_amount = <BalanceOf<T>>::default();
-					return Some(res);
+					Some(res)
 				} else {
 					acc_amount -= balance_per_block;
 					will_deleted_stakes_count += 1;
-					return Some((block, <BalanceOf<T>>::default()));
+					Some((block, <BalanceOf<T>>::default()))
 				}
 			})
 			.collect::<Vec<_>>();
@@ -926,7 +924,7 @@
 		if amount.is_zero() {
 			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(
 				&T::FreezeIdentifier::get(),
-				&staker,
+				staker,
 			)
 		} else {
 			<<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(
@@ -1026,10 +1024,10 @@
 	) {
 		let income = Self::calculate_income(base, iters);
 
-		base.checked_add(&income).map(|res| {
+		if let Some(res) = base.checked_add(&income) {
 			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));
 			*income_acc += income;
-		});
+		};
 	}
 
 	fn calculate_income<I>(base: I, iters: u32) -> I
modifiedpallets/app-promotion/src/types.rsdiffbeforeafterboth
--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -149,16 +149,16 @@
 		Self {
 			recalculation_interval: config
 				.recalculation_interval
-				.unwrap_or_else(|| T::RecalculationInterval::get()),
+				.unwrap_or_else(T::RecalculationInterval::get),
 			pending_interval: config
 				.pending_interval
-				.unwrap_or_else(|| T::PendingInterval::get()),
+				.unwrap_or_else(T::PendingInterval::get),
 			interval_income: config
 				.interval_income
-				.unwrap_or_else(|| T::IntervalIncome::get()),
+				.unwrap_or_else(T::IntervalIncome::get),
 			max_stakers_per_calculation: config
 				.max_stakers_per_calculation
-				.unwrap_or_else(|| MAX_NUMBER_PAYOUTS),
+				.unwrap_or(MAX_NUMBER_PAYOUTS),
 		}
 	}
 }
modifiedpallets/balances-adapter/src/lib.rsdiffbeforeafterboth
--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -31,6 +31,12 @@
 	}
 }
 
+impl<T: Config> Default for NativeFungibleHandle<T> {
+	fn default() -> Self {
+		Self::new()
+	}
+}
+
 impl<T: Config> WithRecorder<T> for NativeFungibleHandle<T> {
 	fn recorder(&self) -> &pallet_evm_coder_substrate::SubstrateRecorder<T> {
 		&self.0
modifiedpallets/common/src/eth.rsdiffbeforeafterboth
--- a/pallets/common/src/eth.rs
+++ b/pallets/common/src/eth.rs
@@ -136,7 +136,7 @@
 
 	fn try_from(from: up_data_structs::Property) -> Result<Self, Self::Error> {
 		let key = evm_coder::types::String::from_utf8(from.key.into())
-			.map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {}", e)))?;
+			.map_err(|e| Self::Error::Revert(format!("utf8 conversion error: {e}")))?;
 		let value = evm_coder::types::Bytes(from.value.to_vec());
 		Ok(Property { key, value })
 	}
@@ -201,10 +201,7 @@
 	pub fn new(field: CollectionLimitField, value: Option<u32>) -> Self {
 		Self {
 			field,
-			value: match value {
-				Some(value) => Some(value.into()),
-				None => None,
-			},
+			value: value.map(|value| value.into()),
 		}
 	}
 	/// Whether the field contains a value.
@@ -222,8 +219,7 @@
 			.ok_or::<Self::Error>("can't convert `None` value to boolean".into())?;
 		let value = Some(value.try_into().map_err(|error| {
 			Self::Error::Revert(format!(
-				"can't convert value to u32 \"{}\" because: \"{error}\"",
-				value
+				"can't convert value to u32 \"{value}\" because: \"{error}\""
 			))
 		})?);
 
@@ -249,10 +245,8 @@
 				limits.sponsored_data_size = value;
 			}
 			CollectionLimitField::SponsoredDataRateLimit => {
-				limits.sponsored_data_rate_limit = match value {
-					Some(value) => Some(up_data_structs::SponsoringRateLimit::Blocks(value)),
-					None => None,
-				};
+				limits.sponsored_data_rate_limit =
+					value.map(up_data_structs::SponsoringRateLimit::Blocks);
 			}
 			CollectionLimitField::TokenLimit => {
 				limits.token_limit = value;
@@ -454,9 +448,9 @@
 	}
 }
 
-impl Into<up_data_structs::AccessMode> for AccessMode {
-	fn into(self) -> up_data_structs::AccessMode {
-		match self {
+impl From<AccessMode> for up_data_structs::AccessMode {
+	fn from(value: AccessMode) -> Self {
+		match value {
 			AccessMode::Normal => up_data_structs::AccessMode::Normal,
 			AccessMode::AllowList => up_data_structs::AccessMode::AllowList,
 		}
modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -260,9 +260,9 @@
 			message: Some(msg), ..
 		}) => ExError::Revert(msg.into()),
 		DispatchError::Module(ModuleError { index, error, .. }) => {
-			ExError::Revert(format!("error {:?} in pallet {}", error, index))
+			ExError::Revert(format!("error {error:?} in pallet {index}"))
 		}
-		e => ExError::Revert(format!("substrate error: {:?}", e)),
+		e => ExError::Revert(format!("substrate error: {e:?}")),
 	}
 }
 
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -184,10 +184,9 @@
 	/// @param contractAddress The contract for which a sponsor is requested.
 	/// @return Tuble with sponsor address and his substrate mirror. If there is no confirmed sponsor error "Contract has no sponsor" throw.
 	fn sponsor(&self, contract_address: Address) -> Result<Option<eth::CrossAddress>> {
-		Ok(match Pallet::<T>::get_sponsor(contract_address) {
-			Some(ref value) => Some(eth::CrossAddress::from_sub_cross_account::<T>(value)),
-			None => None,
-		})
+		Ok(Pallet::<T>::get_sponsor(contract_address)
+			.as_ref()
+			.map(eth::CrossAddress::from_sub_cross_account::<T>))
 	}
 
 	/// Check tat contract has confirmed sponsor.
@@ -275,7 +274,7 @@
 		self.recorder().consume_sstore()?;
 
 		<Pallet<T>>::ensure_owner(contract_address, caller).map_err(dispatch_to_evm::<T>)?;
-		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit.into())
+		<Pallet<T>>::set_sponsoring_fee_limit(contract_address, fee_limit)
 			.map_err(dispatch_to_evm::<T>)?;
 		Ok(())
 	}
modifiedpallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -376,7 +376,7 @@
 			<SponsoringMode<T>>::get(contract)
 				.or_else(|| {
 					#[allow(deprecated)]
-					<SelfSponsoring<T>>::get(contract).then(|| SponsoringModeT::Allowlisted)
+					<SelfSponsoring<T>>::get(contract).then_some(SponsoringModeT::Allowlisted)
 				})
 				.unwrap_or_default()
 		}
@@ -410,7 +410,7 @@
 
 		/// Is user added to allowlist, or he is owner of specified contract
 		pub fn allowed(contract: H160, user: H160) -> bool {
-			<Allowlist<T>>::get(&contract, &user) || <Owner<T>>::get(&contract) == user
+			<Allowlist<T>>::get(contract, user) || <Owner<T>>::get(contract) == user
 		}
 
 		/// Toggle contract allowlist access
@@ -425,7 +425,7 @@
 
 		/// Throw error if user is not allowed to reconfigure target contract
 		pub fn ensure_owner(contract: H160, user: H160) -> DispatchResult {
-			ensure!(<Owner<T>>::get(&contract) == user, Error::<T>::NoPermission);
+			ensure!(<Owner<T>>::get(contract) == user, Error::<T>::NoPermission);
 			Ok(())
 		}
 	}
modifiedpallets/evm-migration/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-migration/src/lib.rs
+++ b/pallets/evm-migration/src/lib.rs
@@ -78,7 +78,7 @@
 		pub fn begin(origin: OriginFor<T>, address: H160) -> DispatchResult {
 			ensure_root(origin)?;
 			ensure!(
-				<PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(&address),
+				<PalletEvm<T>>::is_account_empty(&address) && !<MigrationPending<T>>::get(address),
 				<Error<T>>::AccountNotEmpty,
 			);
 
@@ -97,12 +97,12 @@
 		) -> DispatchResult {
 			ensure_root(origin)?;
 			ensure!(
-				<MigrationPending<T>>::get(&address),
+				<MigrationPending<T>>::get(address),
 				<Error<T>>::AccountIsNotMigrating,
 			);
 
 			for (k, v) in data {
-				<pallet_evm::AccountStorages<T>>::insert(&address, k, v);
+				<pallet_evm::AccountStorages<T>>::insert(address, k, v);
 			}
 			Ok(())
 		}
@@ -115,11 +115,11 @@
 		pub fn finish(origin: OriginFor<T>, address: H160, code: Vec<u8>) -> DispatchResult {
 			ensure_root(origin)?;
 			ensure!(
-				<MigrationPending<T>>::get(&address),
+				<MigrationPending<T>>::get(address),
 				<Error<T>>::AccountIsNotMigrating,
 			);
 
-			<pallet_evm::AccountCodes<T>>::insert(&address, code);
+			<pallet_evm::AccountCodes<T>>::insert(address, code);
 			<MigrationPending<T>>::remove(address);
 			Ok(())
 		}
@@ -166,7 +166,7 @@
 	pub struct OnMethodCall<T>(PhantomData<T>);
 	impl<T: Config> pallet_evm::OnMethodCall<T> for OnMethodCall<T> {
 		fn is_reserved(contract: &H160) -> bool {
-			<MigrationPending<T>>::get(&contract)
+			<MigrationPending<T>>::get(contract)
 		}
 
 		fn is_used(_contract: &H160) -> bool {
modifiedpallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -333,7 +333,7 @@
 					&Value::new(0),
 				)?;
 
-				Ok(amount.into())
+				Ok(amount)
 			}
 		}
 	}
modifiedpallets/foreign-assets/src/lib.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/lib.rs
+++ b/pallets/foreign-assets/src/lib.rs
@@ -161,7 +161,7 @@
 
 	fn get_currency_id(multi_location: MultiLocation) -> Option<CurrencyId> {
 		log::trace!(target: "fassets::get_currency_id", "call");
-		Pallet::<T>::location_to_currency_ids(multi_location).map(|id| AssetIds::ForeignAssetId(id))
+		Pallet::<T>::location_to_currency_ids(multi_location).map(AssetIds::ForeignAssetId)
 	}
 }
 
@@ -378,7 +378,7 @@
 				foreign_asset_id,
 				|maybe_location| -> DispatchResult {
 					ensure!(maybe_location.is_none(), Error::<T>::MultiLocationExisted);
-					*maybe_location = Some(location.clone());
+					*maybe_location = Some(*location);
 
 					AssetMetadatas::<T>::try_mutate(
 						AssetIds::ForeignAssetId(foreign_asset_id),
@@ -422,7 +422,7 @@
 
 						// modify location
 						if location != old_multi_locations {
-							LocationToCurrencyIds::<T>::remove(old_multi_locations.clone());
+							LocationToCurrencyIds::<T>::remove(*old_multi_locations);
 							LocationToCurrencyIds::<T>::try_mutate(
 								location,
 								|maybe_currency_ids| -> DispatchResult {
@@ -437,7 +437,7 @@
 							)?;
 						}
 						*maybe_asset_metadatas = Some(metadata.clone());
-						*old_multi_locations = location.clone();
+						*old_multi_locations = *location;
 						Ok(())
 					},
 				)
modifiedpallets/identity/src/types.rsdiffbeforeafterboth
before · pallets/identity/src/types.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use super::*;36use codec::{Decode, Encode, MaxEncodedLen};37use enumflags2::{bitflags, BitFlags};38use frame_support::{39	traits::{ConstU32, Get},40	BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound,41};42use scale_info::{43	build::{Fields, Variants},44	meta_type, Path, Type, TypeInfo, TypeParameter,45};46use sp_runtime::{traits::Zero, RuntimeDebug};47use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*};4849/// Either underlying data blob if it is at most 32 bytes, or a hash of it. If the data is greater50/// than 32-bytes then it will be truncated when encoding.51///52/// Can also be `None`.53#[derive(Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]54pub enum Data {55	/// No data here.56	None,57	/// The data is stored directly.58	Raw(BoundedVec<u8, ConstU32<32>>),59	/// Only the Blake2 hash of the data is stored. The preimage of the hash may be retrieved60	/// through some hash-lookup service.61	BlakeTwo256([u8; 32]),62	/// Only the SHA2-256 hash of the data is stored. The preimage of the hash may be retrieved63	/// through some hash-lookup service.64	Sha256([u8; 32]),65	/// Only the Keccak-256 hash of the data is stored. The preimage of the hash may be retrieved66	/// through some hash-lookup service.67	Keccak256([u8; 32]),68	/// Only the SHA3-256 hash of the data is stored. The preimage of the hash may be retrieved69	/// through some hash-lookup service.70	ShaThree256([u8; 32]),71}7273impl Data {74	pub fn is_none(&self) -> bool {75		self == &Data::None76	}77}7879impl Decode for Data {80	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {81		let b = input.read_byte()?;82		Ok(match b {83			0 => Data::None,84			n @ 1..=33 => {85				let mut r: BoundedVec<_, _> = vec![0u8; n as usize - 1]86					.try_into()87					.expect("bound checked in match arm condition; qed");88				input.read(&mut r[..])?;89				Data::Raw(r)90			}91			34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?),92			35 => Data::Sha256(<[u8; 32]>::decode(input)?),93			36 => Data::Keccak256(<[u8; 32]>::decode(input)?),94			37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),95			_ => return Err(codec::Error::from("invalid leading byte")),96		})97	}98}99100impl Encode for Data {101	fn encode(&self) -> Vec<u8> {102		match self {103			Data::None => vec![0u8; 1],104			Data::Raw(ref x) => {105				let l = x.len().min(32);106				let mut r = vec![l as u8 + 1; l + 1];107				r[1..].copy_from_slice(&x[..l as usize]);108				r109			}110			Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),111			Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(),112			Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(),113			Data::ShaThree256(ref h) => once(37u8).chain(h.iter().cloned()).collect(),114		}115	}116}117impl codec::EncodeLike for Data {}118119/// Add a Raw variant with the given index and a fixed sized byte array120macro_rules! data_raw_variants {121    ($variants:ident, $(($index:literal, $size:literal)),* ) => {122		$variants123		$(124			.variant(concat!("Raw", stringify!($size)), |v| v125				.index($index)126				.fields(Fields::unnamed().field(|f| f.ty::<[u8; $size]>()))127			)128		)*129    }130}131132impl TypeInfo for Data {133	type Identity = Self;134135	fn type_info() -> Type {136		let variants = Variants::new().variant("None", |v| v.index(0));137138		// create a variant for all sizes of Raw data from 0-32139		let variants = data_raw_variants!(140			variants,141			(1, 0),142			(2, 1),143			(3, 2),144			(4, 3),145			(5, 4),146			(6, 5),147			(7, 6),148			(8, 7),149			(9, 8),150			(10, 9),151			(11, 10),152			(12, 11),153			(13, 12),154			(14, 13),155			(15, 14),156			(16, 15),157			(17, 16),158			(18, 17),159			(19, 18),160			(20, 19),161			(21, 20),162			(22, 21),163			(23, 22),164			(24, 23),165			(25, 24),166			(26, 25),167			(27, 26),168			(28, 27),169			(29, 28),170			(30, 29),171			(31, 30),172			(32, 31),173			(33, 32)174		);175176		let variants = variants177			.variant("BlakeTwo256", |v| {178				v.index(34)179					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))180			})181			.variant("Sha256", |v| {182				v.index(35)183					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))184			})185			.variant("Keccak256", |v| {186				v.index(36)187					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))188			})189			.variant("ShaThree256", |v| {190				v.index(37)191					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))192			});193194		Type::builder()195			.path(Path::new("Data", module_path!()))196			.variant(variants)197	}198}199200impl Default for Data {201	fn default() -> Self {202		Self::None203	}204}205206/// An identifier for a single name registrar/identity verification service.207pub type RegistrarIndex = u32;208209/// An attestation of a registrar over how accurate some `IdentityInfo` is in describing an account.210///211/// NOTE: Registrars may pay little attention to some fields. Registrars may want to make clear212/// which fields their attestation is relevant for by off-chain means.213#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]214pub enum Judgement<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>215{216	/// The default value; no opinion is held.217	Unknown,218	/// No judgement is yet in place, but a deposit is reserved as payment for providing one.219	FeePaid(Balance),220	/// The data appears to be reasonably acceptable in terms of its accuracy, however no in depth221	/// checks (such as in-person meetings or formal KYC) have been conducted.222	Reasonable,223	/// The target is known directly by the registrar and the registrar can fully attest to the224	/// the data's accuracy.225	KnownGood,226	/// The data was once good but is currently out of date. There is no malicious intent in the227	/// inaccuracy. This judgement can be removed through updating the data.228	OutOfDate,229	/// The data is imprecise or of sufficiently low-quality to be problematic. It is not230	/// indicative of malicious intent. This judgement can be removed through updating the data.231	LowQuality,232	/// The data is erroneous. This may be indicative of malicious intent. This cannot be removed233	/// except by the registrar.234	Erroneous,235}236237impl<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>238	Judgement<Balance>239{240	/// Returns `true` if this judgement is indicative of a deposit being currently held. This means241	/// it should not be cleared or replaced except by an operation which utilizes the deposit.242	pub(crate) fn has_deposit(&self) -> bool {243		matches!(self, Judgement::FeePaid(_))244	}245246	/// Returns `true` if this judgement is one that should not be generally be replaced outside247	/// of specialized handlers. Examples include "malicious" judgements and deposit-holding248	/// judgements.249	pub(crate) fn is_sticky(&self) -> bool {250		matches!(self, Judgement::FeePaid(_) | Judgement::Erroneous)251	}252}253254/// The fields that we use to identify the owner of an account with. Each corresponds to a field255/// in the `IdentityInfo` struct.256#[bitflags]257#[repr(u64)]258#[derive(Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]259pub enum IdentityField {260	Display = 0b0000000000000000000000000000000000000000000000000000000000000001,261	Legal = 0b0000000000000000000000000000000000000000000000000000000000000010,262	Web = 0b0000000000000000000000000000000000000000000000000000000000000100,263	Riot = 0b0000000000000000000000000000000000000000000000000000000000001000,264	Email = 0b0000000000000000000000000000000000000000000000000000000000010000,265	PgpFingerprint = 0b0000000000000000000000000000000000000000000000000000000000100000,266	Image = 0b0000000000000000000000000000000000000000000000000000000001000000,267	Twitter = 0b0000000000000000000000000000000000000000000000000000000010000000,268}269270/// Wrapper type for `BitFlags<IdentityField>` that implements `Codec`.271#[derive(Clone, Copy, PartialEq, Default, RuntimeDebug)]272pub struct IdentityFields(pub BitFlags<IdentityField>);273274impl MaxEncodedLen for IdentityFields {275	fn max_encoded_len() -> usize {276		u64::max_encoded_len()277	}278}279280impl Eq for IdentityFields {}281impl Encode for IdentityFields {282	fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {283		self.0.bits().using_encoded(f)284	}285}286impl Decode for IdentityFields {287	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {288		let field = u64::decode(input)?;289		Ok(Self(290			<BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,291		))292	}293}294impl TypeInfo for IdentityFields {295	type Identity = Self;296297	fn type_info() -> Type {298		Type::builder()299			.path(Path::new("BitFlags", module_path!()))300			.type_params(vec![TypeParameter::new(301				"T",302				Some(meta_type::<IdentityField>()),303			)])304			.composite(Fields::unnamed().field(|f| f.ty::<u64>().type_name("IdentityField")))305	}306}307308/// Information concerning the identity of the controller of an account.309///310/// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra311/// fields in a backwards compatible way through a specialized `Decode` impl.312#[derive(313	CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,314)]315#[codec(mel_bound())]316#[cfg_attr(test, derive(frame_support::DefaultNoBound))]317#[scale_info(skip_type_params(FieldLimit))]318pub struct IdentityInfo<FieldLimit: Get<u32>> {319	/// Additional fields of the identity that are not catered for with the struct's explicit320	/// fields.321	pub additional: BoundedVec<(Data, Data), FieldLimit>,322323	/// A reasonable display name for the controller of the account. This should be whatever it is324	/// that it is typically known as and should not be confusable with other entities, given325	/// reasonable context.326	///327	/// Stored as UTF-8.328	pub display: Data,329330	/// The full legal name in the local jurisdiction of the entity. This might be a bit331	/// long-winded.332	///333	/// Stored as UTF-8.334	pub legal: Data,335336	/// A representative website held by the controller of the account.337	///338	/// NOTE: `https://` is automatically prepended.339	///340	/// Stored as UTF-8.341	pub web: Data,342343	/// The Riot/Matrix handle held by the controller of the account.344	///345	/// Stored as UTF-8.346	pub riot: Data,347348	/// The email address of the controller of the account.349	///350	/// Stored as UTF-8.351	pub email: Data,352353	/// The PGP/GPG public key of the controller of the account.354	pub pgp_fingerprint: Option<[u8; 20]>,355356	/// A graphic image representing the controller of the account. Should be a company,357	/// organization or project logo or a headshot in the case of a human.358	pub image: Data,359360	/// The Twitter identity. The leading `@` character may be elided.361	pub twitter: Data,362}363364impl<FieldLimit: Get<u32>> IdentityInfo<FieldLimit> {365	pub(crate) fn fields(&self) -> IdentityFields {366		let mut res = <BitFlags<IdentityField>>::empty();367		if !self.display.is_none() {368			res.insert(IdentityField::Display);369		}370		if !self.legal.is_none() {371			res.insert(IdentityField::Legal);372		}373		if !self.web.is_none() {374			res.insert(IdentityField::Web);375		}376		if !self.riot.is_none() {377			res.insert(IdentityField::Riot);378		}379		if !self.email.is_none() {380			res.insert(IdentityField::Email);381		}382		if self.pgp_fingerprint.is_some() {383			res.insert(IdentityField::PgpFingerprint);384		}385		if !self.image.is_none() {386			res.insert(IdentityField::Image);387		}388		if !self.twitter.is_none() {389			res.insert(IdentityField::Twitter);390		}391		IdentityFields(res)392	}393}394395/// Information concerning the identity of the controller of an account.396///397/// NOTE: This is stored separately primarily to facilitate the addition of extra fields in a398/// backwards compatible way through a specialized `Decode` impl.399#[derive(400	CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,401)]402#[codec(mel_bound())]403#[scale_info(skip_type_params(MaxJudgements, MaxAdditionalFields))]404pub struct Registration<405	Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,406	MaxJudgements: Get<u32>,407	MaxAdditionalFields: Get<u32>,408> {409	/// Judgements from the registrars on this identity. Stored ordered by `RegistrarIndex`. There410	/// may be only a single judgement from each registrar.411	pub judgements: BoundedVec<(RegistrarIndex, Judgement<Balance>), MaxJudgements>,412413	/// Amount held on deposit for this information.414	pub deposit: Balance,415416	/// Information on the identity.417	pub info: IdentityInfo<MaxAdditionalFields>,418}419420impl<421		Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,422		MaxJudgements: Get<u32>,423		MaxAdditionalFields: Get<u32>,424	> Registration<Balance, MaxJudgements, MaxAdditionalFields>425{426	pub(crate) fn total_deposit(&self) -> Balance {427		self.deposit428			+ self429				.judgements430				.iter()431				.map(|(_, ref j)| {432					if let Judgement::FeePaid(fee) = j {433						*fee434					} else {435						Zero::zero()436					}437				})438				.fold(Zero::zero(), |a, i| a + i)439	}440}441442impl<443		Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,444		MaxJudgements: Get<u32>,445		MaxAdditionalFields: Get<u32>,446	> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>447{448	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {449		let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;450		Ok(Self {451			judgements,452			deposit,453			info,454		})455	}456}457458/// Information concerning a registrar.459#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]460pub struct RegistrarInfo<461	Balance: Encode + Decode + Clone + Debug + Eq + PartialEq,462	AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq,463> {464	/// The account of the registrar.465	pub account: AccountId,466467	/// Amount required to be given to the registrar for them to provide judgement.468	pub fee: Balance,469470	/// Relevant fields for this registrar. Registrar judgements are limited to attestations on471	/// these fields.472	pub fields: IdentityFields,473}474475#[cfg(test)]476mod tests {477	use super::*;478479	#[test]480	fn manual_data_type_info() {481		let mut registry = scale_info::Registry::new();482		let type_id = registry.register_type(&scale_info::meta_type::<Data>());483		let registry: scale_info::PortableRegistry = registry.into();484		let type_info = registry.resolve(type_id.id()).unwrap();485486		let check_type_info = |data: &Data| {487			let variant_name = match data {488				Data::None => "None".to_string(),489				Data::BlakeTwo256(_) => "BlakeTwo256".to_string(),490				Data::Sha256(_) => "Sha256".to_string(),491				Data::Keccak256(_) => "Keccak256".to_string(),492				Data::ShaThree256(_) => "ShaThree256".to_string(),493				Data::Raw(bytes) => format!("Raw{}", bytes.len()),494			};495			if let scale_info::TypeDef::Variant(variant) = type_info.type_def() {496				let variant = variant497					.variants()498					.iter()499					.find(|v| v.name() == &variant_name)500					.expect(&format!("Expected to find variant {}", variant_name));501502				let field_arr_len = variant503					.fields()504					.first()505					.and_then(|f| registry.resolve(f.ty().id()))506					.map(|ty| {507						if let scale_info::TypeDef::Array(arr) = ty.type_def() {508							arr.len()509						} else {510							panic!("Should be an array type")511						}512					})513					.unwrap_or(0);514515				let encoded = data.encode();516				assert_eq!(encoded[0], variant.index());517				assert_eq!(encoded.len() as u32 - 1, field_arr_len);518			} else {519				panic!("Should be a variant type")520			};521		};522523		let mut data = vec![524			Data::None,525			Data::BlakeTwo256(Default::default()),526			Data::Sha256(Default::default()),527			Data::Keccak256(Default::default()),528			Data::ShaThree256(Default::default()),529		];530531		// A Raw instance for all possible sizes of the Raw data532		for n in 0..32 {533			data.push(Data::Raw(vec![0u8; n as usize].try_into().unwrap()))534		}535536		for d in data.iter() {537			check_type_info(d);538		}539	}540}
after · pallets/identity/src/types.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2021-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435use super::*;36use codec::{Decode, Encode, MaxEncodedLen};37use enumflags2::{bitflags, BitFlags};38use frame_support::{39	traits::{ConstU32, Get},40	BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound,41};42use scale_info::{43	build::{Fields, Variants},44	meta_type, Path, Type, TypeInfo, TypeParameter,45};46use sp_runtime::{traits::Zero, RuntimeDebug};47use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*};4849/// Either underlying data blob if it is at most 32 bytes, or a hash of it. If the data is greater50/// than 32-bytes then it will be truncated when encoding.51///52/// Can also be `None`.53#[derive(Clone, Eq, PartialEq, RuntimeDebug, MaxEncodedLen)]54pub enum Data {55	/// No data here.56	None,57	/// The data is stored directly.58	Raw(BoundedVec<u8, ConstU32<32>>),59	/// Only the Blake2 hash of the data is stored. The preimage of the hash may be retrieved60	/// through some hash-lookup service.61	BlakeTwo256([u8; 32]),62	/// Only the SHA2-256 hash of the data is stored. The preimage of the hash may be retrieved63	/// through some hash-lookup service.64	Sha256([u8; 32]),65	/// Only the Keccak-256 hash of the data is stored. The preimage of the hash may be retrieved66	/// through some hash-lookup service.67	Keccak256([u8; 32]),68	/// Only the SHA3-256 hash of the data is stored. The preimage of the hash may be retrieved69	/// through some hash-lookup service.70	ShaThree256([u8; 32]),71}7273impl Data {74	pub fn is_none(&self) -> bool {75		self == &Data::None76	}77}7879impl Decode for Data {80	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {81		let b = input.read_byte()?;82		Ok(match b {83			0 => Data::None,84			n @ 1..=33 => {85				let mut r: BoundedVec<_, _> = vec![0u8; n as usize - 1]86					.try_into()87					.expect("bound checked in match arm condition; qed");88				input.read(&mut r[..])?;89				Data::Raw(r)90			}91			34 => Data::BlakeTwo256(<[u8; 32]>::decode(input)?),92			35 => Data::Sha256(<[u8; 32]>::decode(input)?),93			36 => Data::Keccak256(<[u8; 32]>::decode(input)?),94			37 => Data::ShaThree256(<[u8; 32]>::decode(input)?),95			_ => return Err(codec::Error::from("invalid leading byte")),96		})97	}98}99100impl Encode for Data {101	fn encode(&self) -> Vec<u8> {102		match self {103			Data::None => vec![0u8; 1],104			Data::Raw(ref x) => {105				let l = x.len().min(32);106				let mut r = vec![l as u8 + 1; l + 1];107				r[1..].copy_from_slice(&x[..l]);108				r109			}110			Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),111			Data::Sha256(ref h) => once(35u8).chain(h.iter().cloned()).collect(),112			Data::Keccak256(ref h) => once(36u8).chain(h.iter().cloned()).collect(),113			Data::ShaThree256(ref h) => once(37u8).chain(h.iter().cloned()).collect(),114		}115	}116}117impl codec::EncodeLike for Data {}118119/// Add a Raw variant with the given index and a fixed sized byte array120macro_rules! data_raw_variants {121    ($variants:ident, $(($index:literal, $size:literal)),* ) => {122		$variants123		$(124			.variant(concat!("Raw", stringify!($size)), |v| v125				.index($index)126				.fields(Fields::unnamed().field(|f| f.ty::<[u8; $size]>()))127			)128		)*129    }130}131132impl TypeInfo for Data {133	type Identity = Self;134135	fn type_info() -> Type {136		let variants = Variants::new().variant("None", |v| v.index(0));137138		// create a variant for all sizes of Raw data from 0-32139		let variants = data_raw_variants!(140			variants,141			(1, 0),142			(2, 1),143			(3, 2),144			(4, 3),145			(5, 4),146			(6, 5),147			(7, 6),148			(8, 7),149			(9, 8),150			(10, 9),151			(11, 10),152			(12, 11),153			(13, 12),154			(14, 13),155			(15, 14),156			(16, 15),157			(17, 16),158			(18, 17),159			(19, 18),160			(20, 19),161			(21, 20),162			(22, 21),163			(23, 22),164			(24, 23),165			(25, 24),166			(26, 25),167			(27, 26),168			(28, 27),169			(29, 28),170			(30, 29),171			(31, 30),172			(32, 31),173			(33, 32)174		);175176		let variants = variants177			.variant("BlakeTwo256", |v| {178				v.index(34)179					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))180			})181			.variant("Sha256", |v| {182				v.index(35)183					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))184			})185			.variant("Keccak256", |v| {186				v.index(36)187					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))188			})189			.variant("ShaThree256", |v| {190				v.index(37)191					.fields(Fields::unnamed().field(|f| f.ty::<[u8; 32]>()))192			});193194		Type::builder()195			.path(Path::new("Data", module_path!()))196			.variant(variants)197	}198}199200impl Default for Data {201	fn default() -> Self {202		Self::None203	}204}205206/// An identifier for a single name registrar/identity verification service.207pub type RegistrarIndex = u32;208209/// An attestation of a registrar over how accurate some `IdentityInfo` is in describing an account.210///211/// NOTE: Registrars may pay little attention to some fields. Registrars may want to make clear212/// which fields their attestation is relevant for by off-chain means.213#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]214pub enum Judgement<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>215{216	/// The default value; no opinion is held.217	Unknown,218	/// No judgement is yet in place, but a deposit is reserved as payment for providing one.219	FeePaid(Balance),220	/// The data appears to be reasonably acceptable in terms of its accuracy, however no in depth221	/// checks (such as in-person meetings or formal KYC) have been conducted.222	Reasonable,223	/// The target is known directly by the registrar and the registrar can fully attest to the224	/// the data's accuracy.225	KnownGood,226	/// The data was once good but is currently out of date. There is no malicious intent in the227	/// inaccuracy. This judgement can be removed through updating the data.228	OutOfDate,229	/// The data is imprecise or of sufficiently low-quality to be problematic. It is not230	/// indicative of malicious intent. This judgement can be removed through updating the data.231	LowQuality,232	/// The data is erroneous. This may be indicative of malicious intent. This cannot be removed233	/// except by the registrar.234	Erroneous,235}236237impl<Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq>238	Judgement<Balance>239{240	/// Returns `true` if this judgement is indicative of a deposit being currently held. This means241	/// it should not be cleared or replaced except by an operation which utilizes the deposit.242	pub(crate) fn has_deposit(&self) -> bool {243		matches!(self, Judgement::FeePaid(_))244	}245246	/// Returns `true` if this judgement is one that should not be generally be replaced outside247	/// of specialized handlers. Examples include "malicious" judgements and deposit-holding248	/// judgements.249	pub(crate) fn is_sticky(&self) -> bool {250		matches!(self, Judgement::FeePaid(_) | Judgement::Erroneous)251	}252}253254/// The fields that we use to identify the owner of an account with. Each corresponds to a field255/// in the `IdentityInfo` struct.256#[bitflags]257#[repr(u64)]258#[derive(Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]259pub enum IdentityField {260	Display = 0b0000000000000000000000000000000000000000000000000000000000000001,261	Legal = 0b0000000000000000000000000000000000000000000000000000000000000010,262	Web = 0b0000000000000000000000000000000000000000000000000000000000000100,263	Riot = 0b0000000000000000000000000000000000000000000000000000000000001000,264	Email = 0b0000000000000000000000000000000000000000000000000000000000010000,265	PgpFingerprint = 0b0000000000000000000000000000000000000000000000000000000000100000,266	Image = 0b0000000000000000000000000000000000000000000000000000000001000000,267	Twitter = 0b0000000000000000000000000000000000000000000000000000000010000000,268}269270/// Wrapper type for `BitFlags<IdentityField>` that implements `Codec`.271#[derive(Clone, Copy, PartialEq, Default, RuntimeDebug)]272pub struct IdentityFields(pub BitFlags<IdentityField>);273274impl MaxEncodedLen for IdentityFields {275	fn max_encoded_len() -> usize {276		u64::max_encoded_len()277	}278}279280impl Eq for IdentityFields {}281impl Encode for IdentityFields {282	fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {283		self.0.bits().using_encoded(f)284	}285}286impl Decode for IdentityFields {287	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {288		let field = u64::decode(input)?;289		Ok(Self(290			<BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,291		))292	}293}294impl TypeInfo for IdentityFields {295	type Identity = Self;296297	fn type_info() -> Type {298		Type::builder()299			.path(Path::new("BitFlags", module_path!()))300			.type_params(vec![TypeParameter::new(301				"T",302				Some(meta_type::<IdentityField>()),303			)])304			.composite(Fields::unnamed().field(|f| f.ty::<u64>().type_name("IdentityField")))305	}306}307308/// Information concerning the identity of the controller of an account.309///310/// NOTE: This should be stored at the end of the storage item to facilitate the addition of extra311/// fields in a backwards compatible way through a specialized `Decode` impl.312#[derive(313	CloneNoBound, Encode, Decode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,314)]315#[codec(mel_bound())]316#[cfg_attr(test, derive(frame_support::DefaultNoBound))]317#[scale_info(skip_type_params(FieldLimit))]318pub struct IdentityInfo<FieldLimit: Get<u32>> {319	/// Additional fields of the identity that are not catered for with the struct's explicit320	/// fields.321	pub additional: BoundedVec<(Data, Data), FieldLimit>,322323	/// A reasonable display name for the controller of the account. This should be whatever it is324	/// that it is typically known as and should not be confusable with other entities, given325	/// reasonable context.326	///327	/// Stored as UTF-8.328	pub display: Data,329330	/// The full legal name in the local jurisdiction of the entity. This might be a bit331	/// long-winded.332	///333	/// Stored as UTF-8.334	pub legal: Data,335336	/// A representative website held by the controller of the account.337	///338	/// NOTE: `https://` is automatically prepended.339	///340	/// Stored as UTF-8.341	pub web: Data,342343	/// The Riot/Matrix handle held by the controller of the account.344	///345	/// Stored as UTF-8.346	pub riot: Data,347348	/// The email address of the controller of the account.349	///350	/// Stored as UTF-8.351	pub email: Data,352353	/// The PGP/GPG public key of the controller of the account.354	pub pgp_fingerprint: Option<[u8; 20]>,355356	/// A graphic image representing the controller of the account. Should be a company,357	/// organization or project logo or a headshot in the case of a human.358	pub image: Data,359360	/// The Twitter identity. The leading `@` character may be elided.361	pub twitter: Data,362}363364impl<FieldLimit: Get<u32>> IdentityInfo<FieldLimit> {365	pub(crate) fn fields(&self) -> IdentityFields {366		let mut res = <BitFlags<IdentityField>>::empty();367		if !self.display.is_none() {368			res.insert(IdentityField::Display);369		}370		if !self.legal.is_none() {371			res.insert(IdentityField::Legal);372		}373		if !self.web.is_none() {374			res.insert(IdentityField::Web);375		}376		if !self.riot.is_none() {377			res.insert(IdentityField::Riot);378		}379		if !self.email.is_none() {380			res.insert(IdentityField::Email);381		}382		if self.pgp_fingerprint.is_some() {383			res.insert(IdentityField::PgpFingerprint);384		}385		if !self.image.is_none() {386			res.insert(IdentityField::Image);387		}388		if !self.twitter.is_none() {389			res.insert(IdentityField::Twitter);390		}391		IdentityFields(res)392	}393}394395/// Information concerning the identity of the controller of an account.396///397/// NOTE: This is stored separately primarily to facilitate the addition of extra fields in a398/// backwards compatible way through a specialized `Decode` impl.399#[derive(400	CloneNoBound, Encode, Eq, MaxEncodedLen, PartialEqNoBound, RuntimeDebugNoBound, TypeInfo,401)]402#[codec(mel_bound())]403#[scale_info(skip_type_params(MaxJudgements, MaxAdditionalFields))]404pub struct Registration<405	Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,406	MaxJudgements: Get<u32>,407	MaxAdditionalFields: Get<u32>,408> {409	/// Judgements from the registrars on this identity. Stored ordered by `RegistrarIndex`. There410	/// may be only a single judgement from each registrar.411	pub judgements: BoundedVec<(RegistrarIndex, Judgement<Balance>), MaxJudgements>,412413	/// Amount held on deposit for this information.414	pub deposit: Balance,415416	/// Information on the identity.417	pub info: IdentityInfo<MaxAdditionalFields>,418}419420impl<421		Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq + Zero + Add,422		MaxJudgements: Get<u32>,423		MaxAdditionalFields: Get<u32>,424	> Registration<Balance, MaxJudgements, MaxAdditionalFields>425{426	pub(crate) fn total_deposit(&self) -> Balance {427		self.deposit428			+ self429				.judgements430				.iter()431				.map(|(_, ref j)| {432					if let Judgement::FeePaid(fee) = j {433						*fee434					} else {435						Zero::zero()436					}437				})438				.fold(Zero::zero(), |a, i| a + i)439	}440}441442impl<443		Balance: Encode + Decode + MaxEncodedLen + Copy + Clone + Debug + Eq + PartialEq,444		MaxJudgements: Get<u32>,445		MaxAdditionalFields: Get<u32>,446	> Decode for Registration<Balance, MaxJudgements, MaxAdditionalFields>447{448	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {449		let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?;450		Ok(Self {451			judgements,452			deposit,453			info,454		})455	}456}457458/// Information concerning a registrar.459#[derive(Clone, Encode, Decode, Eq, PartialEq, RuntimeDebug, MaxEncodedLen, TypeInfo)]460pub struct RegistrarInfo<461	Balance: Encode + Decode + Clone + Debug + Eq + PartialEq,462	AccountId: Encode + Decode + Clone + Debug + Eq + PartialEq,463> {464	/// The account of the registrar.465	pub account: AccountId,466467	/// Amount required to be given to the registrar for them to provide judgement.468	pub fee: Balance,469470	/// Relevant fields for this registrar. Registrar judgements are limited to attestations on471	/// these fields.472	pub fields: IdentityFields,473}474475#[cfg(test)]476mod tests {477	use super::*;478479	#[test]480	fn manual_data_type_info() {481		let mut registry = scale_info::Registry::new();482		let type_id = registry.register_type(&scale_info::meta_type::<Data>());483		let registry: scale_info::PortableRegistry = registry.into();484		let type_info = registry.resolve(type_id.id()).unwrap();485486		let check_type_info = |data: &Data| {487			let variant_name = match data {488				Data::None => "None".to_string(),489				Data::BlakeTwo256(_) => "BlakeTwo256".to_string(),490				Data::Sha256(_) => "Sha256".to_string(),491				Data::Keccak256(_) => "Keccak256".to_string(),492				Data::ShaThree256(_) => "ShaThree256".to_string(),493				Data::Raw(bytes) => format!("Raw{}", bytes.len()),494			};495			if let scale_info::TypeDef::Variant(variant) = type_info.type_def() {496				let variant = variant497					.variants()498					.iter()499					.find(|v| v.name() == &variant_name)500					.expect(&format!("Expected to find variant {}", variant_name));501502				let field_arr_len = variant503					.fields()504					.first()505					.and_then(|f| registry.resolve(f.ty().id()))506					.map(|ty| {507						if let scale_info::TypeDef::Array(arr) = ty.type_def() {508							arr.len()509						} else {510							panic!("Should be an array type")511						}512					})513					.unwrap_or(0);514515				let encoded = data.encode();516				assert_eq!(encoded[0], variant.index());517				assert_eq!(encoded.len() as u32 - 1, field_arr_len);518			} else {519				panic!("Should be a variant type")520			};521		};522523		let mut data = vec![524			Data::None,525			Data::BlakeTwo256(Default::default()),526			Data::Sha256(Default::default()),527			Data::Keccak256(Default::default()),528			Data::ShaThree256(Default::default()),529		];530531		// A Raw instance for all possible sizes of the Raw data532		for n in 0..32 {533			data.push(Data::Raw(vec![0u8; n as usize].try_into().unwrap()))534		}535536		for d in data.iter() {537			check_type_info(d);538		}539	}540}
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -20,6 +20,8 @@
 //! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
 
 extern crate alloc;
+
+use alloc::string::ToString;
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
@@ -356,8 +358,7 @@
 				.transpose()
 				.map_err(|e| {
 					Error::Revert(alloc::format!(
-						"Can not convert value \"baseURI\" to string with error \"{}\"",
-						e
+						"Can not convert value \"baseURI\" to string with error \"{e}\""
 					))
 				})?;
 
@@ -675,7 +676,7 @@
 					.try_into()
 					.map_err(|_| "token uri is too long")?,
 			})
-			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
 
 		<Pallet<T>>::create_item(
 			self,
@@ -717,7 +718,7 @@
 		.map(Clone::clone)
 		.ok_or_else(|| {
 			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
-			Error::Revert(alloc::format!("No permission for key {}", key))
+			Error::Revert(alloc::format!("No permission for key {key}"))
 		})?;
 	Ok(a)
 }
@@ -752,14 +753,14 @@
 	/// @param tokenId Id for the token.
 	#[solidity(hide)]
 	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
-		Self::owner_of_cross(&self, token_id)
+		Self::owner_of_cross(self, token_id)
 	}
 
 	/// Returns the owner (in cross format) of the token.
 	///
 	/// @param tokenId Id for the token.
 	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
-		Self::token_owner(&self, token_id.try_into()?)
+		Self::token_owner(self, token_id.try_into()?)
 			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
 			.map_err(|_| Error::Revert("token not found".into()))
 	}
@@ -789,7 +790,7 @@
 			.collect::<Result<Vec<_>>>()?;
 
 		<Self as CommonCollectionOperations<T>>::token_properties(
-			&self,
+			self,
 			token_id.try_into()?,
 			if keys.is_empty() { None } else { Some(keys) },
 		)
@@ -1021,7 +1022,7 @@
 						.try_into()
 						.map_err(|_| "token uri is too long")?,
 				})
-				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
 
 			data.push(CreateItemData::<T> {
 				properties,
@@ -1056,7 +1057,7 @@
 			.map(eth::Property::try_into)
 			.collect::<Result<Vec<_>>>()?
 			.try_into()
-			.map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+			.map_err(|_| Error::Revert("too many properties".to_string()))?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -166,10 +166,7 @@
 
 	#[pallet::config]
 	pub trait Config:
-		frame_system::Config
-		+ pallet_common::Config
-		+ pallet_structure::Config
-		+ pallet_evm::Config
+		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config
 	{
 		type WeightInfo: WeightInfo;
 	}
@@ -860,13 +857,7 @@
 
 		<PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);
 
-		<TokenData<T>>::insert(
-			(collection.id, token),
-			ItemData {
-				owner: to.clone(),
-				..token_data
-			},
-		);
+		<TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });
 
 		if let Some(balance_to) = balance_to {
 			// from != to
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,6 +21,7 @@
 
 extern crate alloc;
 
+use alloc::string::ToString;
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
@@ -353,8 +354,7 @@
 				.transpose()
 				.map_err(|e| {
 					Error::Revert(alloc::format!(
-						"Can not convert value \"baseURI\" to string with error \"{}\"",
-						e
+						"Can not convert value \"baseURI\" to string with error \"{e}\""
 					))
 				})?;
 
@@ -482,8 +482,8 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		let balance = balance(&self, token, &from)?;
-		ensure_single_owner(&self, token, balance)?;
+		let balance = balance(self, token, &from)?;
+		ensure_single_owner(self, token, balance)?;
 
 		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, balance, &budget)
 			.map_err(dispatch_to_evm::<T>)?;
@@ -575,8 +575,8 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let token = token_id.try_into()?;
 
-		let balance = balance(&self, token, &caller)?;
-		ensure_single_owner(&self, token, balance)?;
+		let balance = balance(self, token, &caller)?;
+		ensure_single_owner(self, token, balance)?;
 
 		<Pallet<T>>::burn(self, &caller, token, balance).map_err(dispatch_to_evm::<T>)?;
 		Ok(())
@@ -622,7 +622,7 @@
 			return Err("item id should be next".into());
 		}
 
-		let users = [(to.clone(), 1)]
+		let users = [(to, 1)]
 			.into_iter()
 			.collect::<BTreeMap<_, _>>()
 			.try_into()
@@ -706,9 +706,9 @@
 					.try_into()
 					.map_err(|_| "token uri is too long")?,
 			})
-			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+			.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
 
-		let users = [(to.clone(), 1)]
+		let users = [(to, 1)]
 			.into_iter()
 			.collect::<BTreeMap<_, _>>()
 			.try_into()
@@ -750,7 +750,7 @@
 		.map(Clone::clone)
 		.ok_or_else(|| {
 			let key = String::from_utf8(key.clone().into_inner()).unwrap_or_default();
-			Error::Revert(alloc::format!("No permission for key {}", key))
+			Error::Revert(alloc::format!("No permission for key {key}"))
 		})?;
 	Ok(a)
 }
@@ -785,14 +785,14 @@
 	/// @param tokenId Id for the token.
 	#[solidity(hide)]
 	fn cross_owner_of(&self, token_id: U256) -> Result<eth::CrossAddress> {
-		Self::owner_of_cross(&self, token_id)
+		Self::owner_of_cross(self, token_id)
 	}
 
 	/// Returns the owner (in cross format) of the token.
 	///
 	/// @param tokenId Id for the token.
 	fn owner_of_cross(&self, token_id: U256) -> Result<eth::CrossAddress> {
-		Self::token_owner(&self, token_id.try_into()?)
+		Self::token_owner(self, token_id.try_into()?)
 			.map(|o| eth::CrossAddress::from_sub_cross_account::<T>(&o))
 			.or_else(|err| match err {
 				TokenOwnerError::NotFound => Err(Error::Revert("token not found".into())),
@@ -827,7 +827,7 @@
 			.collect::<Result<Vec<_>>>()?;
 
 		<Self as CommonCollectionOperations<T>>::token_properties(
-			&self,
+			self,
 			token_id.try_into()?,
 			if keys.is_empty() { None } else { Some(keys) },
 		)
@@ -1004,7 +1004,7 @@
 			}
 			expected_index = expected_index.checked_add(1).ok_or("item id overflow")?;
 		}
-		let users = [(to.clone(), 1)]
+		let users = [(to, 1)]
 			.into_iter()
 			.collect::<BTreeMap<_, _>>()
 			.try_into()
@@ -1046,7 +1046,7 @@
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		let mut data = Vec::with_capacity(tokens.len());
-		let users: BoundedBTreeMap<_, _, _> = [(to.clone(), 1)]
+		let users: BoundedBTreeMap<_, _, _> = [(to, 1)]
 			.into_iter()
 			.collect::<BTreeMap<_, _>>()
 			.try_into()
@@ -1067,7 +1067,7 @@
 						.try_into()
 						.map_err(|_| "token uri is too long")?,
 				})
-				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {:?}", e)))?;
+				.map_err(|e| Error::Revert(alloc::format!("Can't add property: {e:?}")))?;
 
 			let create_item_data = CreateItemData::<T> {
 				users: users.clone(),
@@ -1103,7 +1103,7 @@
 			.map(eth::Property::try_into)
 			.collect::<Result<Vec<_>>>()?
 			.try_into()
-			.map_err(|_| Error::Revert(alloc::format!("too many properties")))?;
+			.map_err(|_| Error::Revert("too many properties".to_string()))?;
 
 		let caller = T::CrossAccountId::from_eth(caller);
 
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -1124,7 +1124,7 @@
 
 		if collection.ignores_token_restrictions(spender) {
 			return Ok(Self::compute_allowance_decrease(
-				collection, token, from, &spender, amount,
+				collection, token, from, spender, amount,
 			));
 		}
 
@@ -1143,7 +1143,7 @@
 			return Ok(None);
 		}
 
-		let allowance = Self::compute_allowance_decrease(collection, token, from, &spender, amount);
+		let allowance = Self::compute_allowance_decrease(collection, token, from, spender, amount);
 		if allowance.is_some() {
 			return Ok(allowance);
 		}
modifiedpallets/scheduler-v2/src/lib.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/lib.rs
+++ b/pallets/scheduler-v2/src/lib.rs
@@ -969,7 +969,7 @@
 		call: ScheduledCall<T>,
 	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
 		// ensure id it is unique
-		if Lookup::<T>::contains_key(&id) {
+		if Lookup::<T>::contains_key(id) {
 			return Err(Error::<T>::FailedToSchedule.into());
 		}
 
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -280,7 +280,7 @@
 	) -> DispatchResultWithPostInfo {
 		let dispatch = T::CollectionDispatch::dispatch(collection)?;
 		let dispatch = dispatch.as_dyn();
-		dispatch.burn_item_recursively(from.clone(), token, self_budget, breadth_budget)
+		dispatch.burn_item_recursively(from, token, self_budget, breadth_budget)
 	}
 
 	/// Check if `token` indirectly owned by `user`
@@ -396,7 +396,7 @@
 		account: &T::CrossAccountId,
 		action: impl FnOnce(&dyn CommonCollectionOperations<T>, TokenId) -> DispatchResult,
 	) -> DispatchResult {
-		if is_collection(&account.as_eth()) {
+		if is_collection(account.as_eth()) {
 			fail!(<Error<T>>::CantNestTokenUnderCollection);
 		}
 		let Some((collection, token)) = T::CrossTokenAddressMapping::address_to_token(account) else {
modifiedpallets/unique/src/eth/mod.rsdiffbeforeafterboth
--- a/pallets/unique/src/eth/mod.rs
+++ b/pallets/unique/src/eth/mod.rs
@@ -113,13 +113,9 @@
 	let collection_helpers_address =
 		T::CrossAccountId::from_eth(<T as pallet_common::Config>::ContractAddress::get());
 
-	let collection_id = T::CollectionDispatch::create(
-		caller.clone(),
-		collection_helpers_address,
-		data,
-		Default::default(),
-	)
-	.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
+	let collection_id =
+		T::CollectionDispatch::create(caller, collection_helpers_address, data, Default::default())
+			.map_err(pallet_evm_coder_substrate::dispatch_to_evm::<T>)?;
 	let address = pallet_common::eth::collection_id_to_address(collection_id);
 	Ok(address)
 }
@@ -132,8 +128,7 @@
 		.expect("Collection creation price should be convertible to u128");
 	if value != creation_price {
 		return Err(format!(
-			"Sent amount not equals to collection creation price ({0})",
-			creation_price
+			"Sent amount not equals to collection creation price ({creation_price})",
 		)
 		.into());
 	}
@@ -383,8 +378,7 @@
 		map_eth_to_id(&collection_address)
 			.map(|id| id.0)
 			.ok_or(Error::Revert(format!(
-				"failed to convert address {} into collectionId.",
-				collection_address
+				"failed to convert address {collection_address} into collectionId."
 			)))
 	}
 }
@@ -422,5 +416,5 @@
 generate_stubgen!(collection_helper_iface, CollectionHelpersCall<()>, false);
 
 fn error_field_too_long(feild: &str, bound: usize) -> Error {
-	Error::Revert(format!("{} is too long. Max length is {}.", feild, bound))
+	Error::Revert(format!("{feild} is too long. Max length is {bound}."))
 }
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -507,7 +507,7 @@
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
 			let new_owner = T::CrossAccountId::from_sub(new_owner);
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.change_owner(sender, new_owner.clone())
+			target_collection.change_owner(sender, new_owner)
 		}
 
 		/// Add an admin to a collection.
@@ -667,7 +667,7 @@
 		/// * `owner`: Address of the initial owner of the item.
 		/// * `data`: Token data describing the item to store on chain.
 		#[pallet::call_index(11)]
-		#[pallet::weight(T::CommonWeightInfo::create_item(&data))]
+		#[pallet::weight(T::CommonWeightInfo::create_item(data))]
 		pub fn create_item(
 			origin: OriginFor<T>,
 			collection_id: CollectionId,
@@ -701,7 +701,7 @@
 		/// * `owner`: Address of the initial owner of the tokens.
 		/// * `items_data`: Vector of data describing each item to be created.
 		#[pallet::call_index(12)]
-		#[pallet::weight(T::CommonWeightInfo::create_multiple_items(&items_data))]
+		#[pallet::weight(T::CommonWeightInfo::create_multiple_items(items_data))]
 		pub fn create_multiple_items(
 			origin: OriginFor<T>,
 			collection_id: CollectionId,
@@ -889,7 +889,7 @@
 		/// * `collection_id`: ID of the collection to which the tokens would belong.
 		/// * `data`: Explicit item creation data.
 		#[pallet::call_index(18)]
-		#[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(&data))]
+		#[pallet::weight(T::CommonWeightInfo::create_multiple_items_ex(data))]
 		pub fn create_multiple_items_ex(
 			origin: OriginFor<T>,
 			collection_id: CollectionId,
@@ -1313,7 +1313,7 @@
 			collection_id: CollectionId,
 		) -> DispatchResult {
 			let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
-			target_collection.force_set_sponsor(sponsor.clone())
+			target_collection.force_set_sponsor(sponsor)
 		}
 
 		/// Force remove `sponsor` for `collection`.
modifiedprimitives/data-structs/src/bounded.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/bounded.rs
+++ b/primitives/data-structs/src/bounded.rs
@@ -63,7 +63,7 @@
 	V: fmt::Debug,
 {
 	use core::fmt::Debug;
-	(&v as &Vec<V>).fmt(f)
+	(v as &Vec<V>).fmt(f)
 }
 
 #[cfg(feature = "serde1")]
@@ -114,7 +114,7 @@
 	V: fmt::Debug,
 {
 	use core::fmt::Debug;
-	(&v as &BTreeMap<K, V>).fmt(f)
+	(v as &BTreeMap<K, V>).fmt(f)
 }
 
 #[cfg(feature = "serde1")]
@@ -157,5 +157,5 @@
 	K: fmt::Debug + Ord,
 {
 	use core::fmt::Debug;
-	(&v as &BTreeSet<K>).fmt(f)
+	(v as &BTreeSet<K>).fmt(f)
 }
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -536,7 +536,7 @@
 	type Target = Vec<u8>;
 
 	fn deref(&self) -> &Self::Target {
-		return &self.0;
+		&self.0
 	}
 }
 
@@ -816,6 +816,11 @@
 		Self(Default::default())
 	}
 }
+impl Default for OwnerRestrictedSet {
+	fn default() -> Self {
+		Self::new()
+	}
+}
 impl core::ops::Deref for OwnerRestrictedSet {
 	type Target = OwnerRestrictedSetInner;
 	fn deref(&self) -> &Self::Target {
@@ -1098,9 +1103,9 @@
 	pub value: PropertyValue,
 }
 
-impl Into<(PropertyKey, PropertyValue)> for Property {
-	fn into(self) -> (PropertyKey, PropertyValue) {
-		(self.key, self.value)
+impl From<Property> for (PropertyKey, PropertyValue) {
+	fn from(value: Property) -> Self {
+		(value.key, value.value)
 	}
 }
 
@@ -1116,9 +1121,9 @@
 	pub permission: PropertyPermission,
 }
 
-impl Into<(PropertyKey, PropertyPermission)> for PropertyKeyPermission {
-	fn into(self) -> (PropertyKey, PropertyPermission) {
-		(self.key, self.permission)
+impl From<PropertyKeyPermission> for (PropertyKey, PropertyPermission) {
+	fn from(value: PropertyKeyPermission) -> Self {
+		(value.key, value.permission)
 	}
 }
 
@@ -1415,7 +1420,7 @@
 		value: Self::Value,
 	) -> Result<Option<Self::Value>, PropertiesError> {
 		let key_size = scoped_slice_size(scope, &key);
-		let value_size = slice_size(&value) as u32;
+		let value_size = slice_size(&value);
 
 		if self.consumed_space + value_size + key_size > S && !cfg!(feature = "runtime-benchmarks")
 		{
@@ -1425,7 +1430,7 @@
 		let old_value = self.map.try_scoped_set(scope, key, value)?;
 
 		if let Some(old_value) = old_value.as_ref() {
-			let old_value_size = slice_size(&old_value);
+			let old_value_size = slice_size(old_value);
 			self.consumed_space = self.consumed_space.saturating_sub(old_value_size) + value_size;
 		} else {
 			self.consumed_space += key_size + value_size;
modifiedruntime/common/config/xcm/foreignassets.rsdiffbeforeafterboth
--- a/runtime/common/config/xcm/foreignassets.rs
+++ b/runtime/common/config/xcm/foreignassets.rs
@@ -65,7 +65,7 @@
 			return ConvertAssetId::convert_ref(AssetIds::NativeAssetId(NativeCurrency::Here));
 		}
 
-		match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(id.clone()) {
+		match XcmForeignAssetIdMapping::<Runtime>::get_currency_id(*id) {
 			Some(AssetIds::ForeignAssetId(foreign_asset_id)) => {
 				ConvertAssetId::convert_ref(AssetIds::ForeignAssetId(foreign_asset_id))
 			}
@@ -206,9 +206,7 @@
 			return Some(AssetIds::NativeAssetId(NativeCurrency::Parent));
 		}
 
-		if let Some(currency_id) =
-			XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location.clone())
-		{
+		if let Some(currency_id) = XcmForeignAssetIdMapping::<Runtime>::get_currency_id(location) {
 			return Some(currency_id);
 		}
 
modifiedruntime/common/ethereum/precompiles/mod.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/precompiles/mod.rs
+++ b/runtime/common/ethereum/precompiles/mod.rs
@@ -37,6 +37,16 @@
 		[hash(1), hash(20482)]
 	}
 }
+
+impl<R> Default for UniquePrecompiles<R>
+where
+	R: pallet_evm::Config,
+{
+	fn default() -> Self {
+		Self::new()
+	}
+}
+
 impl<R> PrecompileSet for UniquePrecompiles<R>
 where
 	R: pallet_evm::Config,
modifiedruntime/common/ethereum/precompiles/sr25519.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/precompiles/sr25519.rs
+++ b/runtime/common/ethereum/precompiles/sr25519.rs
@@ -64,7 +64,7 @@
 
 		// Parse arguments
 		let public: sr25519::Public =
-			sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?).into();
+			sr25519::Public::unchecked_from(input.read::<H256>(gasometer)?);
 		let signature_bytes: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
 		let message: Vec<u8> = input.read::<Bytes>(gasometer)?.into();
 
modifiedruntime/common/ethereum/precompiles/utils/data.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/precompiles/utils/data.rs
+++ b/runtime/common/ethereum/precompiles/utils/data.rs
@@ -60,7 +60,7 @@
 }
 
 impl Into<Vec<u8>> for Bytes {
-	fn into(self: Self) -> Vec<u8> {
+	fn into(self) -> Vec<u8> {
 		self.0
 	}
 }
modifiedruntime/common/ethereum/precompiles/utils/mod.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/precompiles/utils/mod.rs
+++ b/runtime/common/ethereum/precompiles/utils/mod.rs
@@ -73,7 +73,6 @@
 		}
 	}
 
-	#[must_use]
 	/// Check that a function call is compatible with the context it is
 	/// called into.
 	pub fn check_function_modifier(
modifiedruntime/common/ethereum/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring.rs
+++ b/runtime/common/ethereum/sponsoring.rs
@@ -78,7 +78,7 @@
 							let token_id: TokenId = token_id.try_into().ok()?;
 							withdraw_set_token_property::<T>(
 								&collection,
-								&who,
+								who,
 								&token_id,
 								key.len() + value.len(),
 							)
@@ -88,7 +88,7 @@
 							ERC721UniqueExtensionsCall::Transfer { token_id, .. },
 						) => {
 							let token_id: TokenId = token_id.try_into().ok()?;
-							withdraw_transfer::<T>(&collection, &who, &token_id).map(|()| sponsor)
+							withdraw_transfer::<T>(&collection, who, &token_id).map(|()| sponsor)
 						}
 						UniqueNFTCall::ERC721UniqueMintable(
 							ERC721UniqueMintableCall::Mint { .. }
@@ -97,7 +97,7 @@
 							| ERC721UniqueMintableCall::MintWithTokenUriCheckId { .. },
 						) => withdraw_create_item::<T>(
 							&collection,
-							&who,
+							who,
 							&CreateItemData::NFT(CreateNftData::default()),
 						)
 						.map(|()| sponsor),
modifiedruntime/common/ethereum/sponsoring/refungible.rsdiffbeforeafterboth
--- a/runtime/common/ethereum/sponsoring/refungible.rs
+++ b/runtime/common/ethereum/sponsoring/refungible.rs
@@ -16,7 +16,6 @@
 
 //! Implements EVM sponsoring logic via TransactionValidityHack
 
-use core::convert::TryInto;
 use pallet_common::CollectionHandle;
 use pallet_evm::account::CrossAccountId;
 use pallet_fungible::Config as FungibleConfig;
@@ -95,7 +94,7 @@
 			..
 		} => {
 			let token_id = TokenId::try_from(token_id).ok()?;
-			withdraw_set_token_property::<T>(&collection, &who, &token_id, key.len() + value.len())
+			withdraw_set_token_property::<T>(&collection, who, &token_id, key.len() + value.len())
 		}
 	}
 }
@@ -242,7 +241,7 @@
 
 			MintCross { .. } => withdraw_create_item::<T>(
 				&collection,
-				&who,
+				who,
 				&CreateItemData::NFT(CreateNftData::default()),
 			),
 
@@ -250,7 +249,7 @@
 			| TransferFromCross { token_id, .. }
 			| Transfer { token_id, .. } => {
 				let token_id = TokenId::try_from(token_id).ok()?;
-				withdraw_transfer::<T>(&collection, &who, &token_id)
+				withdraw_transfer::<T>(&collection, who, &token_id)
 			}
 		}
 	}
@@ -275,7 +274,7 @@
 			| MintWithTokenUri { .. }
 			| MintWithTokenUriCheckId { .. } => withdraw_create_item::<T>(
 				&collection,
-				&who,
+				who,
 				&CreateItemData::NFT(CreateNftData::default()),
 			),
 		}
@@ -311,18 +310,15 @@
 
 			Transfer { .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
-				let token_id = token_id.try_into().ok()?;
-				withdraw_transfer::<T>(&handle, &who, &token_id)
+				withdraw_transfer::<T>(&handle, who, &token_id)
 			}
 			TransferFrom { from, .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
-				let token_id = token_id.try_into().ok()?;
 				let from = T::CrossAccountId::from_eth(from);
 				withdraw_transfer::<T>(&handle, &from, &token_id)
 			}
 			Approve { .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
-				let token_id = token_id.try_into().ok()?;
 				withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
 			}
 		}
@@ -351,13 +347,11 @@
 
 			TransferCross { .. } | TransferFromCross { .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
-				let token_id = token_id.try_into().ok()?;
-				withdraw_transfer::<T>(&handle, &who, &token_id)
+				withdraw_transfer::<T>(&handle, who, &token_id)
 			}
 
 			ApproveCross { .. } => {
 				let RefungibleTokenHandle(handle, token_id) = token;
-				let token_id = token_id.try_into().ok()?;
 				withdraw_approve::<T>(&handle, who.as_sub(), &token_id)
 			}
 		}
modifiedruntime/common/mod.rsdiffbeforeafterboth
--- a/runtime/common/mod.rs
+++ b/runtime/common/mod.rs
@@ -204,10 +204,7 @@
 				&[],
 			);
 
-			let should_upgrade = match version {
-				None => true,
-				Some(_) => false,
-			};
+			let should_upgrade = version.is_none();
 
 			if should_upgrade {
 				log::info!(
@@ -220,7 +217,7 @@
 					.cloned()
 					.filter_map(|authority_id| {
 						weight.saturating_accrue(<Runtime as frame_system::Config>::DbWeight::get().reads_writes(1, 1));
-						let vec = authority_id.clone().to_raw_vec();
+						let vec = authority_id.to_raw_vec();
 						let slice = vec.as_slice();
 						let array: Option<[u8; 32]> = match slice.try_into() {
 							Ok(a) => Some(a),
@@ -248,20 +245,20 @@
 					.into_iter()
 					.map(|(acc, aura)| {
 						(
-							acc.clone(),                        // account id
-							acc,                                // validator id
-							SessionKeys { aura: aura.clone() }, // session keys
+							acc.clone(),          // account id
+							acc,                  // validator id
+							SessionKeys { aura }, // session keys
 						)
 					})
 					.collect::<Vec<_>>();
 
-				for (account, val, keys) in keys.iter().cloned() {
+				for (account, val, keys) in keys.iter() {
 					for id in <Runtime as pallet_session::Config>::Keys::key_ids() {
-						<pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), &val)
+						<pallet_session::KeyOwner<Runtime>>::insert((*id, keys.get_raw(*id)), val)
 					}
-					<pallet_session::NextKeys<Runtime>>::insert(&val, &keys);
+					<pallet_session::NextKeys<Runtime>>::insert(val, keys);
 					// todo exercise caution, the following is taken from genesis
-					if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(&account)
+					if frame_system::Pallet::<Runtime>::inc_consumers_without_limit(account)
 						.is_err()
 					{
 						log::warn!(
@@ -271,7 +268,7 @@
 						// genesis) so it's really not a big deal and we assume that the user wants to
 						// do this since it's the only way a non-endowed account can contain a session
 						// key.
-						frame_system::Pallet::<Runtime>::inc_providers(&account);
+						frame_system::Pallet::<Runtime>::inc_providers(account);
 					}
 				}
 
modifiedruntime/common/runtime_apis.rsdiffbeforeafterboth
--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -84,7 +84,7 @@
                 fn topmost_token_owner(collection: CollectionId, token: TokenId) -> Result<Option<CrossAccountId>, DispatchError> {
                     let budget = up_data_structs::budget::Value::new(10);
 
-                    Ok(<pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)?)
+                    <pallet_structure::Pallet<Runtime>>::find_topmost_owner(collection, token, &budget)
                 }
                 fn token_children(collection: CollectionId, token: TokenId) -> Result<Vec<TokenChild>, DispatchError> {
                     Ok(<pallet_nonfungible::Pallet<Runtime>>::token_children_ids(collection, token))
modifiedruntime/common/sponsoring.rsdiffbeforeafterboth
--- a/runtime/common/sponsoring.rs
+++ b/runtime/common/sponsoring.rs
@@ -240,7 +240,7 @@
 				withdraw_set_token_property(
 					&collection,
 					&T::CrossAccountId::from_sub(who.clone()),
-					&token_id,
+					token_id,
 					// No overflow may happen, as data larger than usize can't reach here
 					properties.iter().map(|p| p.key.len() + p.value.len()).sum(),
 				)
modifiedtest-pallets/utils/src/lib.rsdiffbeforeafterboth
--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -170,7 +170,7 @@
 	fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {
 		ensure_signed(origin)?;
 		<Enabled<T>>::get()
-			.then(|| ())
+			.then_some(())
 			.ok_or(<Error<T>>::TestPalletDisabled.into())
 	}
 }