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
--- a/pallets/identity/src/types.rs
+++ b/pallets/identity/src/types.rs
@@ -104,7 +104,7 @@
 			Data::Raw(ref x) => {
 				let l = x.len().min(32);
 				let mut r = vec![l as u8 + 1; l + 1];
-				r[1..].copy_from_slice(&x[..l as usize]);
+				r[1..].copy_from_slice(&x[..l]);
 				r
 			}
 			Data::BlakeTwo256(ref h) => once(34u8).chain(h.iter().cloned()).collect(),
@@ -287,7 +287,7 @@
 	fn decode<I: codec::Input>(input: &mut I) -> sp_std::result::Result<Self, codec::Error> {
 		let field = u64::decode(input)?;
 		Ok(Self(
-			<BitFlags<IdentityField>>::from_bits(field as u64).map_err(|_| "invalid value")?,
+			<BitFlags<IdentityField>>::from_bits(field).map_err(|_| "invalid value")?,
 		))
 	}
 }
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
before · pallets/scheduler-v2/src/lib.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) 2017-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.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//!   with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//!   that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![cfg_attr(not(feature = "std"), no_std)]69#![deny(missing_docs)]7071#[cfg(feature = "runtime-benchmarks")]72mod benchmarking;73#[cfg(test)]74mod mock;75#[cfg(test)]76mod tests;77// We dont use this pallet right now78#[allow(deprecated)]79pub mod weights;8081use codec::{Codec, Decode, Encode, MaxEncodedLen};82use frame_support::{83	dispatch::{84		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,85	},86	traits::{87		schedule::{self, DispatchTime, LOWEST_PRIORITY},88		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,89		ConstU32, UnfilteredDispatchable,90	},91	weights::Weight,92	unsigned::TransactionValidityError,93};9495use frame_system::{self as system};96use scale_info::TypeInfo;97use sp_runtime::{98	traits::{BadOrigin, One, Saturating, Zero, Hash},99	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,100};101use sp_core::H160;102use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};103pub use weights::WeightInfo;104105pub use pallet::*;106107/// Just a simple index for naming period tasks.108pub type PeriodicIndex = u32;109/// The location of a scheduled task that can be used to remove it.110pub type TaskAddress<BlockNumber> = (BlockNumber, u32);111112/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.113pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;114115#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]116#[scale_info(skip_type_params(T))]117/// A scheduled call is stored as is or as a preimage hash to lookup.118/// This enum represents both variants.119pub enum ScheduledCall<T: Config> {120	/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.121	Inline(EncodedCall),122123	/// A Blake2-256 hash of the call together with an upper limit for its size.124	PreimageLookup {125		/// A call hash to lookup126		hash: T::Hash,127128		/// The length of the decoded call129		unbounded_len: u32,130	},131}132133impl<T: Config> ScheduledCall<T> {134	/// Convert an otherwise unbounded or large value into a type ready for placing in storage.135	///136	/// NOTE: Once this API is used, you should use either `drop` or `realize`.137	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {138		let encoded = call.encode();139		let len = encoded.len();140141		match EncodedCall::try_from(encoded.clone()) {142			Ok(bounded) => Ok(Self::Inline(bounded)),143			Err(_) => {144				let hash = <T as system::Config>::Hashing::hash_of(&encoded);145				<T as Config>::Preimages::note_preimage(146					encoded147						.try_into()148						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,149				);150151				Ok(Self::PreimageLookup {152					hash,153					unbounded_len: len as u32,154				})155			}156		}157	}158159	/// The maximum length of the lookup that is needed to peek `Self`.160	pub fn lookup_len(&self) -> Option<u32> {161		match self {162			Self::Inline(..) => None,163			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),164		}165	}166167	/// Returns whether the image will require a lookup to be peeked.168	pub fn lookup_needed(&self) -> bool {169		match self {170			Self::Inline(_) => false,171			Self::PreimageLookup { .. } => true,172		}173	}174175	// Decodes a runtime call176	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {177		<T as Config>::RuntimeCall::decode(&mut data)178			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())179	}180}181182/// Weight Info for the Preimages fetches.183pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {184	/// Get the weight of a task fetches with a given decoded length.185	fn service_task_fetched(call_length: u32) -> Weight;186}187188impl<W: WeightInfo> SchedulerPreimagesWeightInfo<W> for () {189	fn service_task_fetched(_call_length: u32) -> Weight {190		W::service_task_base()191	}192}193194/// A scheduler's interface for managing preimages to hashes195/// and looking up preimages from their hash on-chain.196pub trait SchedulerPreimages<T: Config>:197	PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>198{199	/// No longer request that the data for decoding the given `call` is available.200	fn drop(call: &ScheduledCall<T>);201202	/// Convert the given `call` instance back into its original instance, also returning the203	/// exact size of its encoded form if it needed to be looked-up from a stored preimage.204	///205	/// NOTE: This does not remove any data needed for realization. If you will no longer use the206	/// `call`, use `realize` instead or use `drop` afterwards.207	fn peek(208		call: &ScheduledCall<T>,209	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;210211	/// Convert the given scheduled `call` value back into its original instance. If successful,212	/// `drop` any data backing it. This will not break the realisability of independently213	/// created instances of `ScheduledCall` which happen to have identical data.214	fn realize(215		call: &ScheduledCall<T>,216	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;217}218219impl<T: Config, PP: PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>>220	SchedulerPreimages<T> for PP221{222	fn drop(call: &ScheduledCall<T>) {223		match call {224			ScheduledCall::Inline(_) => {}225			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),226		}227	}228229	fn peek(230		call: &ScheduledCall<T>,231	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {232		match call {233			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),234			ScheduledCall::PreimageLookup {235				hash,236				unbounded_len,237			} => {238				let (preimage, len) = Self::get_preimage(hash)239					.ok_or(<Error<T>>::PreimageNotFound)240					.map(|preimage| (preimage, *unbounded_len))?;241242				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))243			}244		}245	}246247	fn realize(248		call: &ScheduledCall<T>,249	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {250		let r = Self::peek(call)?;251		Self::drop(call);252		Ok(r)253	}254}255256/// Scheduler's supported origins.257pub enum ScheduledEnsureOriginSuccess<AccountId> {258	/// A scheduled transaction has the Root origin.259	Root,260261	/// A specific account has signed a scheduled transaction.262	Signed(AccountId),263}264265/// An identifier of a scheduled task.266pub type TaskName = [u8; 32];267268/// Information regarding an item to be executed in the future.269#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]270#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]271pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {272	/// The unique identity for this task, if there is one.273	maybe_id: Option<Name>,274275	/// This task's priority.276	priority: schedule::Priority,277278	/// The call to be dispatched.279	call: Call,280281	/// If the call is periodic, then this points to the information concerning that.282	maybe_periodic: Option<schedule::Period<BlockNumber>>,283284	/// The origin with which to dispatch the call.285	origin: PalletsOrigin,286	_phantom: PhantomData<AccountId>,287}288289/// Information regarding an item to be executed in the future.290pub type ScheduledOf<T> = Scheduled<291	TaskName,292	ScheduledCall<T>,293	<T as frame_system::Config>::BlockNumber,294	<T as Config>::PalletsOrigin,295	<T as frame_system::Config>::AccountId,296>;297298#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]299#[scale_info(skip_type_params(T))]300/// A structure for storing scheduled tasks in a block.301/// The `BlockAgenda` tracks the available free space for a new task in a block.4302///303/// The agenda's maximum amount of tasks is `T::MaxScheduledPerBlock`.304pub struct BlockAgenda<T: Config> {305	agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,306	free_places: u32,307}308309impl<T: Config> BlockAgenda<T> {310	/// Tries to push a new scheduled task into the block's agenda.311	/// If there is a free place, the new task will take it,312	/// and the `BlockAgenda` will record that the number of free places has decreased.313	///314	/// An error containing the scheduled task will be returned if there are no free places.315	///316	/// The complexity of the check for the *existence* of a free place is O(1).317	/// The complexity of *finding* the free slot is O(n).318	fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {319		if self.free_places == 0 {320			return Err(scheduled);321		}322323		self.free_places = self.free_places.saturating_sub(1);324325		if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {326			// will always succeed due to the above check.327			let _ = self.agenda.try_push(Some(scheduled));328			Ok((self.agenda.len() - 1) as u32)329		} else {330			match self.agenda.iter().position(|i| i.is_none()) {331				Some(hole_index) => {332					self.agenda[hole_index] = Some(scheduled);333					Ok(hole_index as u32)334				}335				None => unreachable!("free_places was greater than 0; qed"),336			}337		}338	}339340	/// Sets a slot by the given index and the slot value.341	///342	/// ### Panics343	/// If the index is out of range, the function will panic.344	fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {345		self.agenda[index as usize] = slot;346	}347348	/// Returns an iterator containing references to the agenda's slots.349	fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {350		self.agenda.iter()351	}352353	/// Returns an immutable reference to a scheduled task if there is one under the given index.354	///355	///  The function returns `None` if:356	/// * The `index` is out of range357	/// * No scheduled task occupies the agenda slot under the given index.358	fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {359		match self.agenda.get(index as usize) {360			Some(Some(scheduled)) => Some(scheduled),361			_ => None,362		}363	}364365	/// Returns a mutable reference to a scheduled task if there is one under the given index.366	///367	///  The function returns `None` if:368	/// * The `index` is out of range369	/// * No scheduled task occupies the agenda slot under the given index.370	fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {371		match self.agenda.get_mut(index as usize) {372			Some(Some(scheduled)) => Some(scheduled),373			_ => None,374		}375	}376377	/// Take a scheduled task by the given index.378	///379	/// If there is a task under the index, the function will:380	/// * Free the corresponding agenda slot.381	/// * Decrease the number of free places.382	/// * Return the scheduled task.383	///384	/// The function returns `None` if there is no task under the index.385	fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {386		let removed = self.agenda.get_mut(index as usize)?.take();387388		if removed.is_some() {389			self.free_places = self.free_places.saturating_add(1);390		}391392		removed393	}394}395396impl<T: Config> Default for BlockAgenda<T> {397	fn default() -> Self {398		let agenda = Default::default();399		let free_places = T::MaxScheduledPerBlock::get();400401		Self {402			agenda,403			free_places,404		}405	}406}407/// A structure for tracking the used weight408/// and checking if it does not exceed the weight limit.409struct WeightCounter {410	used: Weight,411	limit: Weight,412}413414impl WeightCounter {415	/// Checks if the weight `w` can be accommodated by the counter.416	///417	/// If there is room for the additional weight `w`,418	/// the function will update the used weight and return true.419	fn check_accrue(&mut self, w: Weight) -> bool {420		let test = self.used.saturating_add(w);421		if test.any_gt(self.limit) {422			false423		} else {424			self.used = test;425			true426		}427	}428429	/// Checks if the weight `w` can be accommodated by the counter.430	fn can_accrue(&mut self, w: Weight) -> bool {431		self.used.saturating_add(w).all_lte(self.limit)432	}433}434435pub(crate) struct MarginalWeightInfo<T: Config>(sp_std::marker::PhantomData<T>);436437impl<T: Config> MarginalWeightInfo<T> {438	/// Return the weight of servicing a single task.439	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {440		let base = T::WeightInfo::service_task_base();441		let mut total = match maybe_lookup_len {442			None => base,443			Some(l) => T::Preimages::service_task_fetched(l as u32),444		};445		if named {446			total.saturating_accrue(T::WeightInfo::service_task_named().saturating_sub(base));447		}448		if periodic {449			total.saturating_accrue(T::WeightInfo::service_task_periodic().saturating_sub(base));450		}451		total452	}453}454455#[frame_support::pallet]456pub mod pallet {457	use super::*;458	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};459	use system::pallet_prelude::*;460461	/// The current storage version.462	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);463464	#[pallet::pallet]465	#[pallet::storage_version(STORAGE_VERSION)]466	pub struct Pallet<T>(_);467468	#[pallet::config]469	pub trait Config: frame_system::Config {470		/// The overarching event type.471		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;472473		/// The aggregated origin which the dispatch will take.474		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>475			+ From<Self::PalletsOrigin>476			+ IsType<<Self as system::Config>::RuntimeOrigin>477			+ Clone;478479		/// The caller origin, overarching type of all pallets origins.480		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>481			+ Codec482			+ Clone483			+ Eq484			+ TypeInfo485			+ MaxEncodedLen;486487		/// The aggregated call type.488		type RuntimeCall: Parameter489			+ Dispatchable<490				RuntimeOrigin = <Self as Config>::RuntimeOrigin,491				PostInfo = PostDispatchInfo,492			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>493			+ GetDispatchInfo494			+ From<system::Call<Self>>;495496		/// The maximum weight that may be scheduled per block for any dispatchables.497		#[pallet::constant]498		type MaximumWeight: Get<Weight>;499500		/// Required origin to schedule or cancel calls.501		type ScheduleOrigin: EnsureOrigin<502			<Self as system::Config>::RuntimeOrigin,503			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,504		>;505506		/// Compare the privileges of origins.507		///508		/// This will be used when canceling a task, to ensure that the origin that tries509		/// to cancel has greater or equal privileges as the origin that created the scheduled task.510		///511		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can512		/// be used. This will only check if two given origins are equal.513		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;514515		/// The maximum number of scheduled calls in the queue for a single block.516		#[pallet::constant]517		type MaxScheduledPerBlock: Get<u32>;518519		/// Weight information for extrinsics in this pallet.520		type WeightInfo: WeightInfo;521522		/// The preimage provider with which we look up call hashes to get the call.523		type Preimages: SchedulerPreimages<Self>;524525		/// The helper type used for custom transaction fee logic.526		type CallExecutor: DispatchCall<Self, H160>;527528		/// Required origin to set/change calls' priority.529		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;530	}531532	/// It contains the block number from which we should service tasks.533	/// It's used for delaying the servicing of future blocks' agendas if we had overweight tasks.534	#[pallet::storage]535	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;536537	/// Items to be executed, indexed by the block number that they should be executed on.538	#[pallet::storage]539	pub type Agenda<T: Config> =540		StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;541542	/// Lookup from a name to the block number and index of the task.543	#[pallet::storage]544	pub(crate) type Lookup<T: Config> =545		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;546547	/// Events type.548	#[pallet::event]549	#[pallet::generate_deposit(pub(super) fn deposit_event)]550	pub enum Event<T: Config> {551		/// Scheduled some task.552		Scheduled {553			/// The block number in which the scheduled task should be executed.554			when: T::BlockNumber,555556			/// The index of the block's agenda slot.557			index: u32,558		},559		/// Canceled some task.560		Canceled {561			/// The block number in which the canceled task has been.562			when: T::BlockNumber,563564			/// The index of the block's agenda slot that had become available.565			index: u32,566		},567		/// Dispatched some task.568		Dispatched {569			/// The task's address - the block number and the block's agenda index.570			task: TaskAddress<T::BlockNumber>,571572			/// The task's name if it is not anonymous.573			id: Option<[u8; 32]>,574575			/// The task's execution result.576			result: DispatchResult,577		},578		/// Scheduled task's priority has changed579		PriorityChanged {580			/// The task's address - the block number and the block's agenda index.581			task: TaskAddress<T::BlockNumber>,582583			/// The new priority of the task.584			priority: schedule::Priority,585		},586		/// The call for the provided hash was not found so the task has been aborted.587		CallUnavailable {588			/// The task's address - the block number and the block's agenda index.589			task: TaskAddress<T::BlockNumber>,590591			/// The task's name if it is not anonymous.592			id: Option<[u8; 32]>,593		},594		/// The given task can never be executed since it is overweight.595		PermanentlyOverweight {596			/// The task's address - the block number and the block's agenda index.597			task: TaskAddress<T::BlockNumber>,598599			/// The task's name if it is not anonymous.600			id: Option<[u8; 32]>,601		},602	}603604	#[pallet::error]605	pub enum Error<T> {606		/// Failed to schedule a call607		FailedToSchedule,608		/// There is no place for a new task in the agenda609		AgendaIsExhausted,610		/// Scheduled call is corrupted611		ScheduledCallCorrupted,612		/// Scheduled call preimage is not found613		PreimageNotFound,614		/// Scheduled call is too big615		TooBigScheduledCall,616		/// Cannot find the scheduled call.617		NotFound,618		/// Given target block number is in the past.619		TargetBlockNumberInPast,620		/// Attempt to use a non-named function on a named task.621		Named,622	}623624	#[pallet::hooks]625	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {626		/// Execute the scheduled calls627		fn on_initialize(now: T::BlockNumber) -> Weight {628			let mut weight_counter = WeightCounter {629				used: Weight::zero(),630				limit: T::MaximumWeight::get(),631			};632			Self::service_agendas(&mut weight_counter, now, u32::max_value());633			weight_counter.used634		}635	}636637	#[pallet::call]638	impl<T: Config> Pallet<T> {639		/// Anonymously schedule a task.640		///641		/// Only `T::ScheduleOrigin` is allowed to schedule a task.642		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.643		#[pallet::call_index(0)]644		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]645		pub fn schedule(646			origin: OriginFor<T>,647			when: T::BlockNumber,648			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,649			priority: Option<schedule::Priority>,650			call: Box<<T as Config>::RuntimeCall>,651		) -> DispatchResult {652			T::ScheduleOrigin::ensure_origin(origin.clone())?;653654			if priority.is_some() {655				T::PrioritySetOrigin::ensure_origin(origin.clone())?;656			}657658			let origin = <T as Config>::RuntimeOrigin::from(origin);659			Self::do_schedule(660				DispatchTime::At(when),661				maybe_periodic,662				priority.unwrap_or(LOWEST_PRIORITY),663				origin.caller().clone(),664				<ScheduledCall<T>>::new(*call)?,665			)?;666			Ok(())667		}668669		/// Cancel an anonymously scheduled task.670		///671		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.672		#[pallet::call_index(1)]673		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]674		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {675			T::ScheduleOrigin::ensure_origin(origin.clone())?;676			let origin = <T as Config>::RuntimeOrigin::from(origin);677			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;678			Ok(())679		}680681		/// Schedule a named task.682		///683		/// Only `T::ScheduleOrigin` is allowed to schedule a task.684		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.685		#[pallet::call_index(2)]686		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]687		pub fn schedule_named(688			origin: OriginFor<T>,689			id: TaskName,690			when: T::BlockNumber,691			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,692			priority: Option<schedule::Priority>,693			call: Box<<T as Config>::RuntimeCall>,694		) -> DispatchResult {695			T::ScheduleOrigin::ensure_origin(origin.clone())?;696697			if priority.is_some() {698				T::PrioritySetOrigin::ensure_origin(origin.clone())?;699			}700701			let origin = <T as Config>::RuntimeOrigin::from(origin);702			Self::do_schedule_named(703				id,704				DispatchTime::At(when),705				maybe_periodic,706				priority.unwrap_or(LOWEST_PRIORITY),707				origin.caller().clone(),708				<ScheduledCall<T>>::new(*call)?,709			)?;710			Ok(())711		}712713		/// Cancel a named scheduled task.714		///715		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.716		#[pallet::call_index(3)]717		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]718		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {719			T::ScheduleOrigin::ensure_origin(origin.clone())?;720			let origin = <T as Config>::RuntimeOrigin::from(origin);721			Self::do_cancel_named(Some(origin.caller().clone()), id)?;722			Ok(())723		}724725		/// Anonymously schedule a task after a delay.726		///727		/// # <weight>728		/// Same as [`schedule`].729		/// # </weight>730		#[pallet::call_index(4)]731		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]732		pub fn schedule_after(733			origin: OriginFor<T>,734			after: T::BlockNumber,735			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,736			priority: Option<schedule::Priority>,737			call: Box<<T as Config>::RuntimeCall>,738		) -> DispatchResult {739			T::ScheduleOrigin::ensure_origin(origin.clone())?;740741			if priority.is_some() {742				T::PrioritySetOrigin::ensure_origin(origin.clone())?;743			}744745			let origin = <T as Config>::RuntimeOrigin::from(origin);746			Self::do_schedule(747				DispatchTime::After(after),748				maybe_periodic,749				priority.unwrap_or(LOWEST_PRIORITY),750				origin.caller().clone(),751				<ScheduledCall<T>>::new(*call)?,752			)?;753			Ok(())754		}755756		/// Schedule a named task after a delay.757		///758		/// Only `T::ScheduleOrigin` is allowed to schedule a task.759		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.760		///761		/// # <weight>762		/// Same as [`schedule_named`](Self::schedule_named).763		/// # </weight>764		#[pallet::call_index(5)]765		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]766		pub fn schedule_named_after(767			origin: OriginFor<T>,768			id: TaskName,769			after: T::BlockNumber,770			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,771			priority: Option<schedule::Priority>,772			call: Box<<T as Config>::RuntimeCall>,773		) -> DispatchResult {774			T::ScheduleOrigin::ensure_origin(origin.clone())?;775776			if priority.is_some() {777				T::PrioritySetOrigin::ensure_origin(origin.clone())?;778			}779780			let origin = <T as Config>::RuntimeOrigin::from(origin);781			Self::do_schedule_named(782				id,783				DispatchTime::After(after),784				maybe_periodic,785				priority.unwrap_or(LOWEST_PRIORITY),786				origin.caller().clone(),787				<ScheduledCall<T>>::new(*call)?,788			)?;789			Ok(())790		}791792		/// Change a named task's priority.793		///794		/// Only the `T::PrioritySetOrigin` is allowed to change the task's priority.795		#[pallet::call_index(6)]796		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]797		pub fn change_named_priority(798			origin: OriginFor<T>,799			id: TaskName,800			priority: schedule::Priority,801		) -> DispatchResult {802			T::PrioritySetOrigin::ensure_origin(origin.clone())?;803			let origin = <T as Config>::RuntimeOrigin::from(origin);804			Self::do_change_named_priority(origin.caller().clone(), id, priority)805		}806	}807}808809impl<T: Config> Pallet<T> {810	/// Converts the `DispatchTime` to the `BlockNumber`.811	///812	/// Returns an error if the block number is in the past.813	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {814		let now = frame_system::Pallet::<T>::block_number();815816		let when = match when {817			DispatchTime::At(x) => x,818			// The current block has already completed it's scheduled tasks, so819			// Schedule the task at lest one block after this current block.820			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),821		};822823		if when <= now {824			return Err(Error::<T>::TargetBlockNumberInPast.into());825		}826827		Ok(when)828	}829830	/// Places the mandatory task.831	///832	/// It will try to place the task into the block pointed by the `when` parameter.833	///834	/// If the block has no room for a task,835	/// the function will search for a future block that can accommodate the task.836	fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {837		Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");838	}839840	/// Tries to place a task `what` into the given block `when`.841	///842	/// Returns an error if the block has no room for the task.843	fn try_place_task(844		when: T::BlockNumber,845		what: ScheduledOf<T>,846	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {847		Self::place_task(when, what, false)848	}849850	/// If `is_mandatory` is true, the function behaves like [`mandatory_place_task`](Self::mandatory_place_task);851	/// otherwise it acts like [`try_place_task`](Self::try_place_task).852	///853	/// The function also updates the `Lookup` storage.854	fn place_task(855		mut when: T::BlockNumber,856		what: ScheduledOf<T>,857		is_mandatory: bool,858	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {859		let maybe_name = what.maybe_id;860		let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;861		let address = (when, index);862		if let Some(name) = maybe_name {863			Lookup::<T>::insert(name, address)864		}865		Self::deposit_event(Event::Scheduled {866			when: address.0,867			index: address.1,868		});869		Ok(address)870	}871872	/// Pushes the scheduled task into the block's agenda.873	///874	/// If `is_mandatory` is true, it searches for a block with a free slot for the given task.875	///876	/// If `is_mandatory` is false and there is no free slot, the function returns an error.877	fn push_to_agenda(878		when: &mut T::BlockNumber,879		mut what: ScheduledOf<T>,880		is_mandatory: bool,881	) -> Result<u32, DispatchError> {882		let mut agenda;883884		let index = loop {885			agenda = Agenda::<T>::get(*when);886887			match agenda.try_push(what) {888				Ok(index) => break index,889				Err(returned_what) if is_mandatory => {890					what = returned_what;891					when.saturating_inc();892				}893				Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),894			}895		};896897		Agenda::<T>::insert(when, agenda);898		Ok(index)899	}900901	fn do_schedule(902		when: DispatchTime<T::BlockNumber>,903		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,904		priority: schedule::Priority,905		origin: T::PalletsOrigin,906		call: ScheduledCall<T>,907	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {908		let when = Self::resolve_time(when)?;909910		// sanitize maybe_periodic911		let maybe_periodic = maybe_periodic912			.filter(|p| p.1 > 1 && !p.0.is_zero())913			// Remove one from the number of repetitions since we will schedule one now.914			.map(|(p, c)| (p, c - 1));915		let task = Scheduled {916			maybe_id: None,917			priority,918			call,919			maybe_periodic,920			origin,921			_phantom: PhantomData,922		};923		Self::try_place_task(when, task)924	}925926	fn do_cancel(927		origin: Option<T::PalletsOrigin>,928		(when, index): TaskAddress<T::BlockNumber>,929	) -> Result<(), DispatchError> {930		let scheduled = Agenda::<T>::try_mutate(931			when,932			|agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {933				let scheduled = match agenda.get(index) {934					Some(scheduled) => scheduled,935					None => return Ok(None),936				};937938				if let Some(ref o) = origin {939					if matches!(940						T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),941						Some(Ordering::Less) | None942					) {943						return Err(BadOrigin.into());944					}945				}946947				Ok(agenda.take(index))948			},949		)?;950		if let Some(s) = scheduled {951			T::Preimages::drop(&s.call);952953			if let Some(id) = s.maybe_id {954				Lookup::<T>::remove(id);955			}956			Self::deposit_event(Event::Canceled { when, index });957			Ok(())958		} else {959			Err(Error::<T>::NotFound.into())960		}961	}962963	fn do_schedule_named(964		id: TaskName,965		when: DispatchTime<T::BlockNumber>,966		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,967		priority: schedule::Priority,968		origin: T::PalletsOrigin,969		call: ScheduledCall<T>,970	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {971		// ensure id it is unique972		if Lookup::<T>::contains_key(&id) {973			return Err(Error::<T>::FailedToSchedule.into());974		}975976		let when = Self::resolve_time(when)?;977978		// sanitize maybe_periodic979		let maybe_periodic = maybe_periodic980			.filter(|p| p.1 > 1 && !p.0.is_zero())981			// Remove one from the number of repetitions since we will schedule one now.982			.map(|(p, c)| (p, c - 1));983984		let task = Scheduled {985			maybe_id: Some(id),986			priority,987			call,988			maybe_periodic,989			origin,990			_phantom: Default::default(),991		};992		Self::try_place_task(when, task)993	}994995	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {996		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {997			if let Some((when, index)) = lookup.take() {998				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {999					let scheduled = match agenda.get(index) {1000						Some(scheduled) => scheduled,1001						None => return Ok(()),1002					};10031004					if let Some(ref o) = origin {1005						if matches!(1006							T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),1007							Some(Ordering::Less) | None1008						) {1009							return Err(BadOrigin.into());1010						}1011						T::Preimages::drop(&scheduled.call);1012					}10131014					agenda.take(index);10151016					Ok(())1017				})?;1018				Self::deposit_event(Event::Canceled { when, index });1019				Ok(())1020			} else {1021				Err(Error::<T>::NotFound.into())1022			}1023		})1024	}10251026	fn do_change_named_priority(1027		origin: T::PalletsOrigin,1028		id: TaskName,1029		priority: schedule::Priority,1030	) -> DispatchResult {1031		match Lookup::<T>::get(id) {1032			Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {1033				let scheduled = match agenda.get_mut(index) {1034					Some(scheduled) => scheduled,1035					None => return Ok(()),1036				};10371038				if matches!(1039					T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),1040					Some(Ordering::Less) | None1041				) {1042					return Err(BadOrigin.into());1043				}10441045				scheduled.priority = priority;1046				Self::deposit_event(Event::PriorityChanged {1047					task: (when, index),1048					priority,1049				});10501051				Ok(())1052			}),1053			None => Err(Error::<T>::NotFound.into()),1054		}1055	}1056}10571058enum ServiceTaskError {1059	/// Could not be executed due to missing preimage.1060	Unavailable,1061	/// Could not be executed due to weight limitations.1062	Overweight,1063}1064use ServiceTaskError::*;10651066/// A Scheduler-Runtime interface for finer payment handling.1067pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {1068	/// Resolve the call dispatch, including any post-dispatch operations.1069	fn dispatch_call(1070		signer: Option<T::AccountId>,1071		function: <T as Config>::RuntimeCall,1072	) -> Result<1073		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,1074		TransactionValidityError,1075	>;1076}10771078impl<T: Config> Pallet<T> {1079	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.1080	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {1081		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {1082			return;1083		}10841085		let mut incomplete_since = now + One::one();1086		let mut when = IncompleteSince::<T>::take().unwrap_or(now);1087		let mut executed = 0;10881089		let max_items = T::MaxScheduledPerBlock::get();1090		let mut count_down = max;1091		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);1092		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {1093			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {1094				incomplete_since = incomplete_since.min(when);1095			}1096			when.saturating_inc();1097			count_down.saturating_dec();1098		}1099		incomplete_since = incomplete_since.min(when);1100		if incomplete_since <= now {1101			IncompleteSince::<T>::put(incomplete_since);1102		}1103	}11041105	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a1106	/// later block.1107	fn service_agenda(1108		weight: &mut WeightCounter,1109		executed: &mut u32,1110		now: T::BlockNumber,1111		when: T::BlockNumber,1112		max: u32,1113	) -> bool {1114		let mut agenda = Agenda::<T>::get(when);1115		let mut ordered = agenda1116			.iter()1117			.enumerate()1118			.filter_map(|(index, maybe_item)| {1119				maybe_item1120					.as_ref()1121					.map(|item| (index as u32, item.priority))1122			})1123			.collect::<Vec<_>>();1124		ordered.sort_by_key(|k| k.1);1125		let within_limit =1126			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));1127		debug_assert!(1128			within_limit,1129			"weight limit should have been checked in advance"1130		);11311132		// Items which we know can be executed and have postponed for execution in a later block.1133		let mut postponed = (ordered.len() as u32).saturating_sub(max);1134		// Items which we don't know can ever be executed.1135		let mut dropped = 0;11361137		for (agenda_index, _) in ordered.into_iter().take(max as usize) {1138			let task = match agenda.take(agenda_index).take() {1139				None => continue,1140				Some(t) => t,1141			};1142			let base_weight = MarginalWeightInfo::<T>::service_task(1143				task.call.lookup_len().map(|x| x as usize),1144				task.maybe_id.is_some(),1145				task.maybe_periodic.is_some(),1146			);1147			if !weight.can_accrue(base_weight) {1148				postponed += 1;1149				break;1150			}1151			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);1152			match result {1153				Err((Unavailable, slot)) => {1154					dropped += 1;1155					agenda.set_slot(agenda_index, slot);1156				}1157				Err((Overweight, slot)) => {1158					postponed += 1;1159					agenda.set_slot(agenda_index, slot);1160				}1161				Ok(()) => {1162					*executed += 1;1163				}1164			};1165		}1166		if postponed > 0 || dropped > 0 {1167			Agenda::<T>::insert(when, agenda);1168		} else {1169			Agenda::<T>::remove(when);1170		}1171		postponed == 01172	}11731174	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.1175	///1176	/// This involves:1177	/// - removing and potentially replacing the `Lookup` entry for the task.1178	/// - realizing the task's call which can include a preimage lookup.1179	/// - Rescheduling the task for execution in a later agenda if periodic.1180	fn service_task(1181		weight: &mut WeightCounter,1182		now: T::BlockNumber,1183		when: T::BlockNumber,1184		agenda_index: u32,1185		is_first: bool,1186		mut task: ScheduledOf<T>,1187	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1188		let (call, lookup_len) = match T::Preimages::peek(&task.call) {1189			Ok(c) => c,1190			Err(_) => {1191				if let Some(ref id) = task.maybe_id {1192					Lookup::<T>::remove(id);1193				}11941195				return Err((Unavailable, Some(task)));1196			}1197		};11981199		weight.check_accrue(MarginalWeightInfo::<T>::service_task(1200			lookup_len.map(|x| x as usize),1201			task.maybe_id.is_some(),1202			task.maybe_periodic.is_some(),1203		));12041205		match Self::execute_dispatch(weight, task.origin.clone(), call) {1206			Err(Unavailable) => {1207				debug_assert!(false, "Checked to exist with `peek`");12081209				if let Some(ref id) = task.maybe_id {1210					Lookup::<T>::remove(id);1211				}12121213				Self::deposit_event(Event::CallUnavailable {1214					task: (when, agenda_index),1215					id: task.maybe_id,1216				});1217				Err((Unavailable, Some(task)))1218			}1219			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1220				T::Preimages::drop(&task.call);12211222				if let Some(ref id) = task.maybe_id {1223					Lookup::<T>::remove(id);1224				}12251226				Self::deposit_event(Event::PermanentlyOverweight {1227					task: (when, agenda_index),1228					id: task.maybe_id,1229				});1230				Err((Unavailable, Some(task)))1231			}1232			Err(Overweight) => {1233				// Preserve Lookup -- the task will be postponed.1234				Err((Overweight, Some(task)))1235			}1236			Ok(result) => {1237				Self::deposit_event(Event::Dispatched {1238					task: (when, agenda_index),1239					id: task.maybe_id,1240					result,1241				});12421243				let is_canceled = task1244					.maybe_id1245					.as_ref()1246					.map(|id| !Lookup::<T>::contains_key(id))1247					.unwrap_or(false);12481249				match &task.maybe_periodic {1250					&Some((period, count)) if !is_canceled => {1251						if count > 1 {1252							task.maybe_periodic = Some((period, count - 1));1253						} else {1254							task.maybe_periodic = None;1255						}1256						let wake = now.saturating_add(period);1257						Self::mandatory_place_task(wake, task);1258					}1259					_ => {1260						if let Some(ref id) = task.maybe_id {1261							Lookup::<T>::remove(id);1262						}12631264						T::Preimages::drop(&task.call)1265					}1266				}1267				Ok(())1268			}1269		}1270	}12711272	fn is_runtime_upgraded() -> bool {1273		let last = system::LastRuntimeUpgrade::<T>::get();1274		let current = T::Version::get();12751276		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)1277	}12781279	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1280	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1281	/// post info if available).1282	///1283	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1284	/// call itself).1285	fn execute_dispatch(1286		weight: &mut WeightCounter,1287		origin: T::PalletsOrigin,1288		call: <T as Config>::RuntimeCall,1289	) -> Result<DispatchResult, ServiceTaskError> {1290		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1291		let base_weight = match dispatch_origin.clone().as_signed() {1292			Some(_) => T::WeightInfo::execute_dispatch_signed(),1293			_ => T::WeightInfo::execute_dispatch_unsigned(),1294		};1295		let call_weight = call.get_dispatch_info().weight;1296		// We only allow a scheduled call if it cannot push the weight past the limit.1297		let max_weight = base_weight.saturating_add(call_weight);12981299		if !weight.can_accrue(max_weight) {1300			return Err(Overweight);1301		}13021303		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());13041305		let r = match ensured_origin {1306			Ok(ScheduledEnsureOriginSuccess::Root) => {1307				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1308			}1309			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1310				// Execute transaction via chain default pipeline1311				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1312				T::CallExecutor::dispatch_call(Some(sender), call)1313			}1314			Err(e) => Ok(Err(e.into())),1315		};13161317		let (maybe_actual_call_weight, result) = match r {1318			Ok(result) => match result {1319				Ok(post_info) => (post_info.actual_weight, Ok(())),1320				Err(error_and_info) => (1321					error_and_info.post_info.actual_weight,1322					Err(error_and_info.error),1323				),1324			},1325			Err(_) => {1326				log::error!(1327					target: "runtime::scheduler",1328					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1329					This block might have become invalid.");1330				(None, Err(DispatchError::CannotLookup))1331			}1332		};1333		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1334		weight.check_accrue(base_weight);1335		weight.check_accrue(call_weight);1336		Ok(result)1337	}1338}
after · pallets/scheduler-v2/src/lib.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) 2017-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.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//!   with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//!   that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![cfg_attr(not(feature = "std"), no_std)]69#![deny(missing_docs)]7071#[cfg(feature = "runtime-benchmarks")]72mod benchmarking;73#[cfg(test)]74mod mock;75#[cfg(test)]76mod tests;77// We dont use this pallet right now78#[allow(deprecated)]79pub mod weights;8081use codec::{Codec, Decode, Encode, MaxEncodedLen};82use frame_support::{83	dispatch::{84		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,85	},86	traits::{87		schedule::{self, DispatchTime, LOWEST_PRIORITY},88		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,89		ConstU32, UnfilteredDispatchable,90	},91	weights::Weight,92	unsigned::TransactionValidityError,93};9495use frame_system::{self as system};96use scale_info::TypeInfo;97use sp_runtime::{98	traits::{BadOrigin, One, Saturating, Zero, Hash},99	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,100};101use sp_core::H160;102use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};103pub use weights::WeightInfo;104105pub use pallet::*;106107/// Just a simple index for naming period tasks.108pub type PeriodicIndex = u32;109/// The location of a scheduled task that can be used to remove it.110pub type TaskAddress<BlockNumber> = (BlockNumber, u32);111112/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.113pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;114115#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]116#[scale_info(skip_type_params(T))]117/// A scheduled call is stored as is or as a preimage hash to lookup.118/// This enum represents both variants.119pub enum ScheduledCall<T: Config> {120	/// A an encoded bounded `Call`. Its encoding must be at most 128 bytes.121	Inline(EncodedCall),122123	/// A Blake2-256 hash of the call together with an upper limit for its size.124	PreimageLookup {125		/// A call hash to lookup126		hash: T::Hash,127128		/// The length of the decoded call129		unbounded_len: u32,130	},131}132133impl<T: Config> ScheduledCall<T> {134	/// Convert an otherwise unbounded or large value into a type ready for placing in storage.135	///136	/// NOTE: Once this API is used, you should use either `drop` or `realize`.137	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {138		let encoded = call.encode();139		let len = encoded.len();140141		match EncodedCall::try_from(encoded.clone()) {142			Ok(bounded) => Ok(Self::Inline(bounded)),143			Err(_) => {144				let hash = <T as system::Config>::Hashing::hash_of(&encoded);145				<T as Config>::Preimages::note_preimage(146					encoded147						.try_into()148						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,149				);150151				Ok(Self::PreimageLookup {152					hash,153					unbounded_len: len as u32,154				})155			}156		}157	}158159	/// The maximum length of the lookup that is needed to peek `Self`.160	pub fn lookup_len(&self) -> Option<u32> {161		match self {162			Self::Inline(..) => None,163			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),164		}165	}166167	/// Returns whether the image will require a lookup to be peeked.168	pub fn lookup_needed(&self) -> bool {169		match self {170			Self::Inline(_) => false,171			Self::PreimageLookup { .. } => true,172		}173	}174175	// Decodes a runtime call176	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {177		<T as Config>::RuntimeCall::decode(&mut data)178			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())179	}180}181182/// Weight Info for the Preimages fetches.183pub trait SchedulerPreimagesWeightInfo<W: WeightInfo> {184	/// Get the weight of a task fetches with a given decoded length.185	fn service_task_fetched(call_length: u32) -> Weight;186}187188impl<W: WeightInfo> SchedulerPreimagesWeightInfo<W> for () {189	fn service_task_fetched(_call_length: u32) -> Weight {190		W::service_task_base()191	}192}193194/// A scheduler's interface for managing preimages to hashes195/// and looking up preimages from their hash on-chain.196pub trait SchedulerPreimages<T: Config>:197	PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>198{199	/// No longer request that the data for decoding the given `call` is available.200	fn drop(call: &ScheduledCall<T>);201202	/// Convert the given `call` instance back into its original instance, also returning the203	/// exact size of its encoded form if it needed to be looked-up from a stored preimage.204	///205	/// NOTE: This does not remove any data needed for realization. If you will no longer use the206	/// `call`, use `realize` instead or use `drop` afterwards.207	fn peek(208		call: &ScheduledCall<T>,209	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;210211	/// Convert the given scheduled `call` value back into its original instance. If successful,212	/// `drop` any data backing it. This will not break the realisability of independently213	/// created instances of `ScheduledCall` which happen to have identical data.214	fn realize(215		call: &ScheduledCall<T>,216	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;217}218219impl<T: Config, PP: PreimageRecipient<T::Hash> + SchedulerPreimagesWeightInfo<T::WeightInfo>>220	SchedulerPreimages<T> for PP221{222	fn drop(call: &ScheduledCall<T>) {223		match call {224			ScheduledCall::Inline(_) => {}225			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),226		}227	}228229	fn peek(230		call: &ScheduledCall<T>,231	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {232		match call {233			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),234			ScheduledCall::PreimageLookup {235				hash,236				unbounded_len,237			} => {238				let (preimage, len) = Self::get_preimage(hash)239					.ok_or(<Error<T>>::PreimageNotFound)240					.map(|preimage| (preimage, *unbounded_len))?;241242				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))243			}244		}245	}246247	fn realize(248		call: &ScheduledCall<T>,249	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {250		let r = Self::peek(call)?;251		Self::drop(call);252		Ok(r)253	}254}255256/// Scheduler's supported origins.257pub enum ScheduledEnsureOriginSuccess<AccountId> {258	/// A scheduled transaction has the Root origin.259	Root,260261	/// A specific account has signed a scheduled transaction.262	Signed(AccountId),263}264265/// An identifier of a scheduled task.266pub type TaskName = [u8; 32];267268/// Information regarding an item to be executed in the future.269#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]270#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]271pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {272	/// The unique identity for this task, if there is one.273	maybe_id: Option<Name>,274275	/// This task's priority.276	priority: schedule::Priority,277278	/// The call to be dispatched.279	call: Call,280281	/// If the call is periodic, then this points to the information concerning that.282	maybe_periodic: Option<schedule::Period<BlockNumber>>,283284	/// The origin with which to dispatch the call.285	origin: PalletsOrigin,286	_phantom: PhantomData<AccountId>,287}288289/// Information regarding an item to be executed in the future.290pub type ScheduledOf<T> = Scheduled<291	TaskName,292	ScheduledCall<T>,293	<T as frame_system::Config>::BlockNumber,294	<T as Config>::PalletsOrigin,295	<T as frame_system::Config>::AccountId,296>;297298#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]299#[scale_info(skip_type_params(T))]300/// A structure for storing scheduled tasks in a block.301/// The `BlockAgenda` tracks the available free space for a new task in a block.4302///303/// The agenda's maximum amount of tasks is `T::MaxScheduledPerBlock`.304pub struct BlockAgenda<T: Config> {305	agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,306	free_places: u32,307}308309impl<T: Config> BlockAgenda<T> {310	/// Tries to push a new scheduled task into the block's agenda.311	/// If there is a free place, the new task will take it,312	/// and the `BlockAgenda` will record that the number of free places has decreased.313	///314	/// An error containing the scheduled task will be returned if there are no free places.315	///316	/// The complexity of the check for the *existence* of a free place is O(1).317	/// The complexity of *finding* the free slot is O(n).318	fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {319		if self.free_places == 0 {320			return Err(scheduled);321		}322323		self.free_places = self.free_places.saturating_sub(1);324325		if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {326			// will always succeed due to the above check.327			let _ = self.agenda.try_push(Some(scheduled));328			Ok((self.agenda.len() - 1) as u32)329		} else {330			match self.agenda.iter().position(|i| i.is_none()) {331				Some(hole_index) => {332					self.agenda[hole_index] = Some(scheduled);333					Ok(hole_index as u32)334				}335				None => unreachable!("free_places was greater than 0; qed"),336			}337		}338	}339340	/// Sets a slot by the given index and the slot value.341	///342	/// ### Panics343	/// If the index is out of range, the function will panic.344	fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {345		self.agenda[index as usize] = slot;346	}347348	/// Returns an iterator containing references to the agenda's slots.349	fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {350		self.agenda.iter()351	}352353	/// Returns an immutable reference to a scheduled task if there is one under the given index.354	///355	///  The function returns `None` if:356	/// * The `index` is out of range357	/// * No scheduled task occupies the agenda slot under the given index.358	fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {359		match self.agenda.get(index as usize) {360			Some(Some(scheduled)) => Some(scheduled),361			_ => None,362		}363	}364365	/// Returns a mutable reference to a scheduled task if there is one under the given index.366	///367	///  The function returns `None` if:368	/// * The `index` is out of range369	/// * No scheduled task occupies the agenda slot under the given index.370	fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {371		match self.agenda.get_mut(index as usize) {372			Some(Some(scheduled)) => Some(scheduled),373			_ => None,374		}375	}376377	/// Take a scheduled task by the given index.378	///379	/// If there is a task under the index, the function will:380	/// * Free the corresponding agenda slot.381	/// * Decrease the number of free places.382	/// * Return the scheduled task.383	///384	/// The function returns `None` if there is no task under the index.385	fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {386		let removed = self.agenda.get_mut(index as usize)?.take();387388		if removed.is_some() {389			self.free_places = self.free_places.saturating_add(1);390		}391392		removed393	}394}395396impl<T: Config> Default for BlockAgenda<T> {397	fn default() -> Self {398		let agenda = Default::default();399		let free_places = T::MaxScheduledPerBlock::get();400401		Self {402			agenda,403			free_places,404		}405	}406}407/// A structure for tracking the used weight408/// and checking if it does not exceed the weight limit.409struct WeightCounter {410	used: Weight,411	limit: Weight,412}413414impl WeightCounter {415	/// Checks if the weight `w` can be accommodated by the counter.416	///417	/// If there is room for the additional weight `w`,418	/// the function will update the used weight and return true.419	fn check_accrue(&mut self, w: Weight) -> bool {420		let test = self.used.saturating_add(w);421		if test.any_gt(self.limit) {422			false423		} else {424			self.used = test;425			true426		}427	}428429	/// Checks if the weight `w` can be accommodated by the counter.430	fn can_accrue(&mut self, w: Weight) -> bool {431		self.used.saturating_add(w).all_lte(self.limit)432	}433}434435pub(crate) struct MarginalWeightInfo<T: Config>(sp_std::marker::PhantomData<T>);436437impl<T: Config> MarginalWeightInfo<T> {438	/// Return the weight of servicing a single task.439	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {440		let base = T::WeightInfo::service_task_base();441		let mut total = match maybe_lookup_len {442			None => base,443			Some(l) => T::Preimages::service_task_fetched(l as u32),444		};445		if named {446			total.saturating_accrue(T::WeightInfo::service_task_named().saturating_sub(base));447		}448		if periodic {449			total.saturating_accrue(T::WeightInfo::service_task_periodic().saturating_sub(base));450		}451		total452	}453}454455#[frame_support::pallet]456pub mod pallet {457	use super::*;458	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};459	use system::pallet_prelude::*;460461	/// The current storage version.462	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);463464	#[pallet::pallet]465	#[pallet::storage_version(STORAGE_VERSION)]466	pub struct Pallet<T>(_);467468	#[pallet::config]469	pub trait Config: frame_system::Config {470		/// The overarching event type.471		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;472473		/// The aggregated origin which the dispatch will take.474		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>475			+ From<Self::PalletsOrigin>476			+ IsType<<Self as system::Config>::RuntimeOrigin>477			+ Clone;478479		/// The caller origin, overarching type of all pallets origins.480		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>481			+ Codec482			+ Clone483			+ Eq484			+ TypeInfo485			+ MaxEncodedLen;486487		/// The aggregated call type.488		type RuntimeCall: Parameter489			+ Dispatchable<490				RuntimeOrigin = <Self as Config>::RuntimeOrigin,491				PostInfo = PostDispatchInfo,492			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>493			+ GetDispatchInfo494			+ From<system::Call<Self>>;495496		/// The maximum weight that may be scheduled per block for any dispatchables.497		#[pallet::constant]498		type MaximumWeight: Get<Weight>;499500		/// Required origin to schedule or cancel calls.501		type ScheduleOrigin: EnsureOrigin<502			<Self as system::Config>::RuntimeOrigin,503			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,504		>;505506		/// Compare the privileges of origins.507		///508		/// This will be used when canceling a task, to ensure that the origin that tries509		/// to cancel has greater or equal privileges as the origin that created the scheduled task.510		///511		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can512		/// be used. This will only check if two given origins are equal.513		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;514515		/// The maximum number of scheduled calls in the queue for a single block.516		#[pallet::constant]517		type MaxScheduledPerBlock: Get<u32>;518519		/// Weight information for extrinsics in this pallet.520		type WeightInfo: WeightInfo;521522		/// The preimage provider with which we look up call hashes to get the call.523		type Preimages: SchedulerPreimages<Self>;524525		/// The helper type used for custom transaction fee logic.526		type CallExecutor: DispatchCall<Self, H160>;527528		/// Required origin to set/change calls' priority.529		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;530	}531532	/// It contains the block number from which we should service tasks.533	/// It's used for delaying the servicing of future blocks' agendas if we had overweight tasks.534	#[pallet::storage]535	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;536537	/// Items to be executed, indexed by the block number that they should be executed on.538	#[pallet::storage]539	pub type Agenda<T: Config> =540		StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;541542	/// Lookup from a name to the block number and index of the task.543	#[pallet::storage]544	pub(crate) type Lookup<T: Config> =545		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;546547	/// Events type.548	#[pallet::event]549	#[pallet::generate_deposit(pub(super) fn deposit_event)]550	pub enum Event<T: Config> {551		/// Scheduled some task.552		Scheduled {553			/// The block number in which the scheduled task should be executed.554			when: T::BlockNumber,555556			/// The index of the block's agenda slot.557			index: u32,558		},559		/// Canceled some task.560		Canceled {561			/// The block number in which the canceled task has been.562			when: T::BlockNumber,563564			/// The index of the block's agenda slot that had become available.565			index: u32,566		},567		/// Dispatched some task.568		Dispatched {569			/// The task's address - the block number and the block's agenda index.570			task: TaskAddress<T::BlockNumber>,571572			/// The task's name if it is not anonymous.573			id: Option<[u8; 32]>,574575			/// The task's execution result.576			result: DispatchResult,577		},578		/// Scheduled task's priority has changed579		PriorityChanged {580			/// The task's address - the block number and the block's agenda index.581			task: TaskAddress<T::BlockNumber>,582583			/// The new priority of the task.584			priority: schedule::Priority,585		},586		/// The call for the provided hash was not found so the task has been aborted.587		CallUnavailable {588			/// The task's address - the block number and the block's agenda index.589			task: TaskAddress<T::BlockNumber>,590591			/// The task's name if it is not anonymous.592			id: Option<[u8; 32]>,593		},594		/// The given task can never be executed since it is overweight.595		PermanentlyOverweight {596			/// The task's address - the block number and the block's agenda index.597			task: TaskAddress<T::BlockNumber>,598599			/// The task's name if it is not anonymous.600			id: Option<[u8; 32]>,601		},602	}603604	#[pallet::error]605	pub enum Error<T> {606		/// Failed to schedule a call607		FailedToSchedule,608		/// There is no place for a new task in the agenda609		AgendaIsExhausted,610		/// Scheduled call is corrupted611		ScheduledCallCorrupted,612		/// Scheduled call preimage is not found613		PreimageNotFound,614		/// Scheduled call is too big615		TooBigScheduledCall,616		/// Cannot find the scheduled call.617		NotFound,618		/// Given target block number is in the past.619		TargetBlockNumberInPast,620		/// Attempt to use a non-named function on a named task.621		Named,622	}623624	#[pallet::hooks]625	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {626		/// Execute the scheduled calls627		fn on_initialize(now: T::BlockNumber) -> Weight {628			let mut weight_counter = WeightCounter {629				used: Weight::zero(),630				limit: T::MaximumWeight::get(),631			};632			Self::service_agendas(&mut weight_counter, now, u32::max_value());633			weight_counter.used634		}635	}636637	#[pallet::call]638	impl<T: Config> Pallet<T> {639		/// Anonymously schedule a task.640		///641		/// Only `T::ScheduleOrigin` is allowed to schedule a task.642		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.643		#[pallet::call_index(0)]644		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]645		pub fn schedule(646			origin: OriginFor<T>,647			when: T::BlockNumber,648			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,649			priority: Option<schedule::Priority>,650			call: Box<<T as Config>::RuntimeCall>,651		) -> DispatchResult {652			T::ScheduleOrigin::ensure_origin(origin.clone())?;653654			if priority.is_some() {655				T::PrioritySetOrigin::ensure_origin(origin.clone())?;656			}657658			let origin = <T as Config>::RuntimeOrigin::from(origin);659			Self::do_schedule(660				DispatchTime::At(when),661				maybe_periodic,662				priority.unwrap_or(LOWEST_PRIORITY),663				origin.caller().clone(),664				<ScheduledCall<T>>::new(*call)?,665			)?;666			Ok(())667		}668669		/// Cancel an anonymously scheduled task.670		///671		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.672		#[pallet::call_index(1)]673		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]674		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {675			T::ScheduleOrigin::ensure_origin(origin.clone())?;676			let origin = <T as Config>::RuntimeOrigin::from(origin);677			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;678			Ok(())679		}680681		/// Schedule a named task.682		///683		/// Only `T::ScheduleOrigin` is allowed to schedule a task.684		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.685		#[pallet::call_index(2)]686		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]687		pub fn schedule_named(688			origin: OriginFor<T>,689			id: TaskName,690			when: T::BlockNumber,691			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,692			priority: Option<schedule::Priority>,693			call: Box<<T as Config>::RuntimeCall>,694		) -> DispatchResult {695			T::ScheduleOrigin::ensure_origin(origin.clone())?;696697			if priority.is_some() {698				T::PrioritySetOrigin::ensure_origin(origin.clone())?;699			}700701			let origin = <T as Config>::RuntimeOrigin::from(origin);702			Self::do_schedule_named(703				id,704				DispatchTime::At(when),705				maybe_periodic,706				priority.unwrap_or(LOWEST_PRIORITY),707				origin.caller().clone(),708				<ScheduledCall<T>>::new(*call)?,709			)?;710			Ok(())711		}712713		/// Cancel a named scheduled task.714		///715		/// The `T::OriginPrivilegeCmp` decides whether the given origin is allowed to cancel the task or not.716		#[pallet::call_index(3)]717		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]718		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {719			T::ScheduleOrigin::ensure_origin(origin.clone())?;720			let origin = <T as Config>::RuntimeOrigin::from(origin);721			Self::do_cancel_named(Some(origin.caller().clone()), id)?;722			Ok(())723		}724725		/// Anonymously schedule a task after a delay.726		///727		/// # <weight>728		/// Same as [`schedule`].729		/// # </weight>730		#[pallet::call_index(4)]731		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]732		pub fn schedule_after(733			origin: OriginFor<T>,734			after: T::BlockNumber,735			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,736			priority: Option<schedule::Priority>,737			call: Box<<T as Config>::RuntimeCall>,738		) -> DispatchResult {739			T::ScheduleOrigin::ensure_origin(origin.clone())?;740741			if priority.is_some() {742				T::PrioritySetOrigin::ensure_origin(origin.clone())?;743			}744745			let origin = <T as Config>::RuntimeOrigin::from(origin);746			Self::do_schedule(747				DispatchTime::After(after),748				maybe_periodic,749				priority.unwrap_or(LOWEST_PRIORITY),750				origin.caller().clone(),751				<ScheduledCall<T>>::new(*call)?,752			)?;753			Ok(())754		}755756		/// Schedule a named task after a delay.757		///758		/// Only `T::ScheduleOrigin` is allowed to schedule a task.759		/// Only `T::PrioritySetOrigin` is allowed to set the task's priority.760		///761		/// # <weight>762		/// Same as [`schedule_named`](Self::schedule_named).763		/// # </weight>764		#[pallet::call_index(5)]765		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]766		pub fn schedule_named_after(767			origin: OriginFor<T>,768			id: TaskName,769			after: T::BlockNumber,770			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,771			priority: Option<schedule::Priority>,772			call: Box<<T as Config>::RuntimeCall>,773		) -> DispatchResult {774			T::ScheduleOrigin::ensure_origin(origin.clone())?;775776			if priority.is_some() {777				T::PrioritySetOrigin::ensure_origin(origin.clone())?;778			}779780			let origin = <T as Config>::RuntimeOrigin::from(origin);781			Self::do_schedule_named(782				id,783				DispatchTime::After(after),784				maybe_periodic,785				priority.unwrap_or(LOWEST_PRIORITY),786				origin.caller().clone(),787				<ScheduledCall<T>>::new(*call)?,788			)?;789			Ok(())790		}791792		/// Change a named task's priority.793		///794		/// Only the `T::PrioritySetOrigin` is allowed to change the task's priority.795		#[pallet::call_index(6)]796		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]797		pub fn change_named_priority(798			origin: OriginFor<T>,799			id: TaskName,800			priority: schedule::Priority,801		) -> DispatchResult {802			T::PrioritySetOrigin::ensure_origin(origin.clone())?;803			let origin = <T as Config>::RuntimeOrigin::from(origin);804			Self::do_change_named_priority(origin.caller().clone(), id, priority)805		}806	}807}808809impl<T: Config> Pallet<T> {810	/// Converts the `DispatchTime` to the `BlockNumber`.811	///812	/// Returns an error if the block number is in the past.813	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {814		let now = frame_system::Pallet::<T>::block_number();815816		let when = match when {817			DispatchTime::At(x) => x,818			// The current block has already completed it's scheduled tasks, so819			// Schedule the task at lest one block after this current block.820			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),821		};822823		if when <= now {824			return Err(Error::<T>::TargetBlockNumberInPast.into());825		}826827		Ok(when)828	}829830	/// Places the mandatory task.831	///832	/// It will try to place the task into the block pointed by the `when` parameter.833	///834	/// If the block has no room for a task,835	/// the function will search for a future block that can accommodate the task.836	fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {837		Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");838	}839840	/// Tries to place a task `what` into the given block `when`.841	///842	/// Returns an error if the block has no room for the task.843	fn try_place_task(844		when: T::BlockNumber,845		what: ScheduledOf<T>,846	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {847		Self::place_task(when, what, false)848	}849850	/// If `is_mandatory` is true, the function behaves like [`mandatory_place_task`](Self::mandatory_place_task);851	/// otherwise it acts like [`try_place_task`](Self::try_place_task).852	///853	/// The function also updates the `Lookup` storage.854	fn place_task(855		mut when: T::BlockNumber,856		what: ScheduledOf<T>,857		is_mandatory: bool,858	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {859		let maybe_name = what.maybe_id;860		let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;861		let address = (when, index);862		if let Some(name) = maybe_name {863			Lookup::<T>::insert(name, address)864		}865		Self::deposit_event(Event::Scheduled {866			when: address.0,867			index: address.1,868		});869		Ok(address)870	}871872	/// Pushes the scheduled task into the block's agenda.873	///874	/// If `is_mandatory` is true, it searches for a block with a free slot for the given task.875	///876	/// If `is_mandatory` is false and there is no free slot, the function returns an error.877	fn push_to_agenda(878		when: &mut T::BlockNumber,879		mut what: ScheduledOf<T>,880		is_mandatory: bool,881	) -> Result<u32, DispatchError> {882		let mut agenda;883884		let index = loop {885			agenda = Agenda::<T>::get(*when);886887			match agenda.try_push(what) {888				Ok(index) => break index,889				Err(returned_what) if is_mandatory => {890					what = returned_what;891					when.saturating_inc();892				}893				Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),894			}895		};896897		Agenda::<T>::insert(when, agenda);898		Ok(index)899	}900901	fn do_schedule(902		when: DispatchTime<T::BlockNumber>,903		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,904		priority: schedule::Priority,905		origin: T::PalletsOrigin,906		call: ScheduledCall<T>,907	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {908		let when = Self::resolve_time(when)?;909910		// sanitize maybe_periodic911		let maybe_periodic = maybe_periodic912			.filter(|p| p.1 > 1 && !p.0.is_zero())913			// Remove one from the number of repetitions since we will schedule one now.914			.map(|(p, c)| (p, c - 1));915		let task = Scheduled {916			maybe_id: None,917			priority,918			call,919			maybe_periodic,920			origin,921			_phantom: PhantomData,922		};923		Self::try_place_task(when, task)924	}925926	fn do_cancel(927		origin: Option<T::PalletsOrigin>,928		(when, index): TaskAddress<T::BlockNumber>,929	) -> Result<(), DispatchError> {930		let scheduled = Agenda::<T>::try_mutate(931			when,932			|agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {933				let scheduled = match agenda.get(index) {934					Some(scheduled) => scheduled,935					None => return Ok(None),936				};937938				if let Some(ref o) = origin {939					if matches!(940						T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),941						Some(Ordering::Less) | None942					) {943						return Err(BadOrigin.into());944					}945				}946947				Ok(agenda.take(index))948			},949		)?;950		if let Some(s) = scheduled {951			T::Preimages::drop(&s.call);952953			if let Some(id) = s.maybe_id {954				Lookup::<T>::remove(id);955			}956			Self::deposit_event(Event::Canceled { when, index });957			Ok(())958		} else {959			Err(Error::<T>::NotFound.into())960		}961	}962963	fn do_schedule_named(964		id: TaskName,965		when: DispatchTime<T::BlockNumber>,966		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,967		priority: schedule::Priority,968		origin: T::PalletsOrigin,969		call: ScheduledCall<T>,970	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {971		// ensure id it is unique972		if Lookup::<T>::contains_key(id) {973			return Err(Error::<T>::FailedToSchedule.into());974		}975976		let when = Self::resolve_time(when)?;977978		// sanitize maybe_periodic979		let maybe_periodic = maybe_periodic980			.filter(|p| p.1 > 1 && !p.0.is_zero())981			// Remove one from the number of repetitions since we will schedule one now.982			.map(|(p, c)| (p, c - 1));983984		let task = Scheduled {985			maybe_id: Some(id),986			priority,987			call,988			maybe_periodic,989			origin,990			_phantom: Default::default(),991		};992		Self::try_place_task(when, task)993	}994995	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {996		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {997			if let Some((when, index)) = lookup.take() {998				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {999					let scheduled = match agenda.get(index) {1000						Some(scheduled) => scheduled,1001						None => return Ok(()),1002					};10031004					if let Some(ref o) = origin {1005						if matches!(1006							T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),1007							Some(Ordering::Less) | None1008						) {1009							return Err(BadOrigin.into());1010						}1011						T::Preimages::drop(&scheduled.call);1012					}10131014					agenda.take(index);10151016					Ok(())1017				})?;1018				Self::deposit_event(Event::Canceled { when, index });1019				Ok(())1020			} else {1021				Err(Error::<T>::NotFound.into())1022			}1023		})1024	}10251026	fn do_change_named_priority(1027		origin: T::PalletsOrigin,1028		id: TaskName,1029		priority: schedule::Priority,1030	) -> DispatchResult {1031		match Lookup::<T>::get(id) {1032			Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {1033				let scheduled = match agenda.get_mut(index) {1034					Some(scheduled) => scheduled,1035					None => return Ok(()),1036				};10371038				if matches!(1039					T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),1040					Some(Ordering::Less) | None1041				) {1042					return Err(BadOrigin.into());1043				}10441045				scheduled.priority = priority;1046				Self::deposit_event(Event::PriorityChanged {1047					task: (when, index),1048					priority,1049				});10501051				Ok(())1052			}),1053			None => Err(Error::<T>::NotFound.into()),1054		}1055	}1056}10571058enum ServiceTaskError {1059	/// Could not be executed due to missing preimage.1060	Unavailable,1061	/// Could not be executed due to weight limitations.1062	Overweight,1063}1064use ServiceTaskError::*;10651066/// A Scheduler-Runtime interface for finer payment handling.1067pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {1068	/// Resolve the call dispatch, including any post-dispatch operations.1069	fn dispatch_call(1070		signer: Option<T::AccountId>,1071		function: <T as Config>::RuntimeCall,1072	) -> Result<1073		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,1074		TransactionValidityError,1075	>;1076}10771078impl<T: Config> Pallet<T> {1079	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.1080	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {1081		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {1082			return;1083		}10841085		let mut incomplete_since = now + One::one();1086		let mut when = IncompleteSince::<T>::take().unwrap_or(now);1087		let mut executed = 0;10881089		let max_items = T::MaxScheduledPerBlock::get();1090		let mut count_down = max;1091		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);1092		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {1093			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {1094				incomplete_since = incomplete_since.min(when);1095			}1096			when.saturating_inc();1097			count_down.saturating_dec();1098		}1099		incomplete_since = incomplete_since.min(when);1100		if incomplete_since <= now {1101			IncompleteSince::<T>::put(incomplete_since);1102		}1103	}11041105	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a1106	/// later block.1107	fn service_agenda(1108		weight: &mut WeightCounter,1109		executed: &mut u32,1110		now: T::BlockNumber,1111		when: T::BlockNumber,1112		max: u32,1113	) -> bool {1114		let mut agenda = Agenda::<T>::get(when);1115		let mut ordered = agenda1116			.iter()1117			.enumerate()1118			.filter_map(|(index, maybe_item)| {1119				maybe_item1120					.as_ref()1121					.map(|item| (index as u32, item.priority))1122			})1123			.collect::<Vec<_>>();1124		ordered.sort_by_key(|k| k.1);1125		let within_limit =1126			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));1127		debug_assert!(1128			within_limit,1129			"weight limit should have been checked in advance"1130		);11311132		// Items which we know can be executed and have postponed for execution in a later block.1133		let mut postponed = (ordered.len() as u32).saturating_sub(max);1134		// Items which we don't know can ever be executed.1135		let mut dropped = 0;11361137		for (agenda_index, _) in ordered.into_iter().take(max as usize) {1138			let task = match agenda.take(agenda_index).take() {1139				None => continue,1140				Some(t) => t,1141			};1142			let base_weight = MarginalWeightInfo::<T>::service_task(1143				task.call.lookup_len().map(|x| x as usize),1144				task.maybe_id.is_some(),1145				task.maybe_periodic.is_some(),1146			);1147			if !weight.can_accrue(base_weight) {1148				postponed += 1;1149				break;1150			}1151			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);1152			match result {1153				Err((Unavailable, slot)) => {1154					dropped += 1;1155					agenda.set_slot(agenda_index, slot);1156				}1157				Err((Overweight, slot)) => {1158					postponed += 1;1159					agenda.set_slot(agenda_index, slot);1160				}1161				Ok(()) => {1162					*executed += 1;1163				}1164			};1165		}1166		if postponed > 0 || dropped > 0 {1167			Agenda::<T>::insert(when, agenda);1168		} else {1169			Agenda::<T>::remove(when);1170		}1171		postponed == 01172	}11731174	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.1175	///1176	/// This involves:1177	/// - removing and potentially replacing the `Lookup` entry for the task.1178	/// - realizing the task's call which can include a preimage lookup.1179	/// - Rescheduling the task for execution in a later agenda if periodic.1180	fn service_task(1181		weight: &mut WeightCounter,1182		now: T::BlockNumber,1183		when: T::BlockNumber,1184		agenda_index: u32,1185		is_first: bool,1186		mut task: ScheduledOf<T>,1187	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1188		let (call, lookup_len) = match T::Preimages::peek(&task.call) {1189			Ok(c) => c,1190			Err(_) => {1191				if let Some(ref id) = task.maybe_id {1192					Lookup::<T>::remove(id);1193				}11941195				return Err((Unavailable, Some(task)));1196			}1197		};11981199		weight.check_accrue(MarginalWeightInfo::<T>::service_task(1200			lookup_len.map(|x| x as usize),1201			task.maybe_id.is_some(),1202			task.maybe_periodic.is_some(),1203		));12041205		match Self::execute_dispatch(weight, task.origin.clone(), call) {1206			Err(Unavailable) => {1207				debug_assert!(false, "Checked to exist with `peek`");12081209				if let Some(ref id) = task.maybe_id {1210					Lookup::<T>::remove(id);1211				}12121213				Self::deposit_event(Event::CallUnavailable {1214					task: (when, agenda_index),1215					id: task.maybe_id,1216				});1217				Err((Unavailable, Some(task)))1218			}1219			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1220				T::Preimages::drop(&task.call);12211222				if let Some(ref id) = task.maybe_id {1223					Lookup::<T>::remove(id);1224				}12251226				Self::deposit_event(Event::PermanentlyOverweight {1227					task: (when, agenda_index),1228					id: task.maybe_id,1229				});1230				Err((Unavailable, Some(task)))1231			}1232			Err(Overweight) => {1233				// Preserve Lookup -- the task will be postponed.1234				Err((Overweight, Some(task)))1235			}1236			Ok(result) => {1237				Self::deposit_event(Event::Dispatched {1238					task: (when, agenda_index),1239					id: task.maybe_id,1240					result,1241				});12421243				let is_canceled = task1244					.maybe_id1245					.as_ref()1246					.map(|id| !Lookup::<T>::contains_key(id))1247					.unwrap_or(false);12481249				match &task.maybe_periodic {1250					&Some((period, count)) if !is_canceled => {1251						if count > 1 {1252							task.maybe_periodic = Some((period, count - 1));1253						} else {1254							task.maybe_periodic = None;1255						}1256						let wake = now.saturating_add(period);1257						Self::mandatory_place_task(wake, task);1258					}1259					_ => {1260						if let Some(ref id) = task.maybe_id {1261							Lookup::<T>::remove(id);1262						}12631264						T::Preimages::drop(&task.call)1265					}1266				}1267				Ok(())1268			}1269		}1270	}12711272	fn is_runtime_upgraded() -> bool {1273		let last = system::LastRuntimeUpgrade::<T>::get();1274		let current = T::Version::get();12751276		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)1277	}12781279	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1280	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1281	/// post info if available).1282	///1283	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1284	/// call itself).1285	fn execute_dispatch(1286		weight: &mut WeightCounter,1287		origin: T::PalletsOrigin,1288		call: <T as Config>::RuntimeCall,1289	) -> Result<DispatchResult, ServiceTaskError> {1290		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1291		let base_weight = match dispatch_origin.clone().as_signed() {1292			Some(_) => T::WeightInfo::execute_dispatch_signed(),1293			_ => T::WeightInfo::execute_dispatch_unsigned(),1294		};1295		let call_weight = call.get_dispatch_info().weight;1296		// We only allow a scheduled call if it cannot push the weight past the limit.1297		let max_weight = base_weight.saturating_add(call_weight);12981299		if !weight.can_accrue(max_weight) {1300			return Err(Overweight);1301		}13021303		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());13041305		let r = match ensured_origin {1306			Ok(ScheduledEnsureOriginSuccess::Root) => {1307				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1308			}1309			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1310				// Execute transaction via chain default pipeline1311				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1312				T::CallExecutor::dispatch_call(Some(sender), call)1313			}1314			Err(e) => Ok(Err(e.into())),1315		};13161317		let (maybe_actual_call_weight, result) = match r {1318			Ok(result) => match result {1319				Ok(post_info) => (post_info.actual_weight, Ok(())),1320				Err(error_and_info) => (1321					error_and_info.post_info.actual_weight,1322					Err(error_and_info.error),1323				),1324			},1325			Err(_) => {1326				log::error!(1327					target: "runtime::scheduler",1328					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1329					This block might have become invalid.");1330				(None, Err(DispatchError::CannotLookup))1331			}1332		};1333		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1334		weight.check_accrue(base_weight);1335		weight.check_accrue(call_weight);1336		Ok(result)1337	}1338}
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())
 	}
 }