git.delta.rocks / unique-network / refs/commits / 829f2bcebad6

difftreelog

fix scheduler warnings

Daniel Shiposha2022-10-25parent: #53db16c.patch.diff
in: master

3 files changed

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)]6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72#[cfg(test)]73mod mock;74#[cfg(test)]75mod tests;76pub mod weights;7778use codec::{Codec, Decode, Encode, MaxEncodedLen};79use frame_support::{80	dispatch::{DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter},81	traits::{82		schedule::{self, DispatchTime, LOWEST_PRIORITY},83		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,84		ConstU32, UnfilteredDispatchable,85	},86	weights::{Weight, PostDispatchInfo}, unsigned::TransactionValidityError,87};8889use frame_system::{self as system};90use scale_info::TypeInfo;91use sp_runtime::{92	traits::{BadOrigin, One, Saturating, Zero, Hash},93	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,94};95use sp_core::H160;96use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};97pub use weights::WeightInfo;9899pub use pallet::*;100101/// Just a simple index for naming period tasks.102pub type PeriodicIndex = u32;103/// The location of a scheduled task that can be used to remove it.104pub type TaskAddress<BlockNumber> = (BlockNumber, u32);105106pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;107108#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]109#[scale_info(skip_type_params(T))]110pub enum ScheduledCall<T: Config> {111	Inline(EncodedCall),112	PreimageLookup { hash: T::Hash, unbounded_len: u32 },113}114115impl<T: Config> ScheduledCall<T> {116	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {117		let encoded = call.encode();118		let len = encoded.len();119120		match EncodedCall::try_from(encoded.clone()) {121			Ok(bounded) => Ok(Self::Inline(bounded)),122			Err(_) => {123				let hash = <T as system::Config>::Hashing::hash_of(&encoded);124				<T as Config>::Preimages::note_preimage(125					encoded126						.try_into()127						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,128				);129130				Ok(Self::PreimageLookup {131					hash,132					unbounded_len: len as u32,133				})134			}135		}136	}137138	/// The maximum length of the lookup that is needed to peek `Self`.139	pub fn lookup_len(&self) -> Option<u32> {140		match self {141			Self::Inline(..) => None,142			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),143		}144	}145146	/// Returns whether the image will require a lookup to be peeked.147	pub fn lookup_needed(&self) -> bool {148		match self {149			Self::Inline(_) => false,150			Self::PreimageLookup { .. } => true,151		}152	}153154	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {155		<T as Config>::RuntimeCall::decode(&mut data)156			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())157	}158}159160pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {161	fn drop(call: &ScheduledCall<T>);162163	fn peek(164		call: &ScheduledCall<T>,165	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;166167	/// Convert the given scheduled `call` value back into its original instance. If successful,168	/// `drop` any data backing it. This will not break the realisability of independently169	/// created instances of `ScheduledCall` which happen to have identical data.170	fn realize(171		call: &ScheduledCall<T>,172	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;173}174175impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {176	fn drop(call: &ScheduledCall<T>) {177		match call {178			ScheduledCall::Inline(_) => {}179			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),180		}181	}182183	fn peek(184		call: &ScheduledCall<T>,185	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {186		match call {187			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),188			ScheduledCall::PreimageLookup {189				hash,190				unbounded_len,191			} => {192				let (preimage, len) = Self::get_preimage(hash)193					.ok_or(<Error<T>>::PreimageNotFound)194					.map(|preimage| (preimage, *unbounded_len))?;195196				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))197			}198		}199	}200201	fn realize(202		call: &ScheduledCall<T>,203	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {204		let r = Self::peek(call)?;205		Self::drop(call);206		Ok(r)207	}208}209210pub enum ScheduledEnsureOriginSuccess<AccountId> {211	Root,212	Signed(AccountId),213	Unsigned,214}215216pub type TaskName = [u8; 32];217218/// Information regarding an item to be executed in the future.219#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]220#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]221pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {222	/// The unique identity for this task, if there is one.223	maybe_id: Option<Name>,224225	/// This task's priority.226	priority: schedule::Priority,227228	/// The call to be dispatched.229	call: Call,230231	/// If the call is periodic, then this points to the information concerning that.232	maybe_periodic: Option<schedule::Period<BlockNumber>>,233234	/// The origin with which to dispatch the call.235	origin: PalletsOrigin,236	_phantom: PhantomData<AccountId>,237}238239pub type ScheduledOf<T> = Scheduled<240	TaskName,241	ScheduledCall<T>,242	<T as frame_system::Config>::BlockNumber,243	<T as Config>::PalletsOrigin,244	<T as frame_system::Config>::AccountId,245>;246247struct WeightCounter {248	used: Weight,249	limit: Weight,250}251252impl WeightCounter {253	fn check_accrue(&mut self, w: Weight) -> bool {254		let test = self.used.saturating_add(w);255		if test.any_gt(self.limit) {256			false257		} else {258			self.used = test;259			true260		}261	}262263	fn can_accrue(&mut self, w: Weight) -> bool {264		self.used.saturating_add(w).all_lte(self.limit)265	}266}267268pub(crate) trait MarginalWeightInfo: WeightInfo {269	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {270		let base = Self::service_task_base();271		let mut total = match maybe_lookup_len {272			None => base,273			Some(l) => Self::service_task_fetched(l as u32),274		};275		if named {276			total.saturating_accrue(Self::service_task_named().saturating_sub(base));277		}278		if periodic {279			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));280		}281		total282	}283}284285impl<T: WeightInfo> MarginalWeightInfo for T {}286287#[frame_support::pallet]288pub mod pallet {289	use super::*;290	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};291	use system::pallet_prelude::*;292293	/// The current storage version.294	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);295296	#[pallet::pallet]297	#[pallet::generate_store(pub(super) trait Store)]298	#[pallet::storage_version(STORAGE_VERSION)]299	pub struct Pallet<T>(_);300301	#[pallet::config]302	pub trait Config: frame_system::Config {303		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;304305		/// The aggregated origin which the dispatch will take.306		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>307			+ From<Self::PalletsOrigin>308			+ IsType<<Self as system::Config>::RuntimeOrigin>309			+ Clone;310311		/// The caller origin, overarching type of all pallets origins.312		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>313			+ Codec314			+ Clone315			+ Eq316			+ TypeInfo317			+ MaxEncodedLen;318319		/// The aggregated call type.320		type RuntimeCall: Parameter321			+ Dispatchable<RuntimeOrigin = <Self as Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>322			+ UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>323			+ GetDispatchInfo324			+ From<system::Call<Self>>;325326		/// The maximum weight that may be scheduled per block for any dispatchables.327		#[pallet::constant]328		type MaximumWeight: Get<Weight>;329330		/// Required origin to schedule or cancel calls.331		type ScheduleOrigin: EnsureOrigin<332			<Self as system::Config>::RuntimeOrigin,333			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,334		>;335336		/// Compare the privileges of origins.337		///338		/// This will be used when canceling a task, to ensure that the origin that tries339		/// to cancel has greater or equal privileges as the origin that created the scheduled task.340		///341		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can342		/// be used. This will only check if two given origins are equal.343		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;344345		/// The maximum number of scheduled calls in the queue for a single block.346		#[pallet::constant]347		type MaxScheduledPerBlock: Get<u32>;348349		/// Weight information for extrinsics in this pallet.350		type WeightInfo: WeightInfo;351352		/// The preimage provider with which we look up call hashes to get the call.353		type Preimages: SchedulerPreimages<Self>;354355		/// The helper type used for custom transaction fee logic.356		type CallExecutor: DispatchCall<Self, H160>;357358		/// Required origin to set/change calls' priority.359		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;360	}361362	#[pallet::storage]363	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;364365	/// Items to be executed, indexed by the block number that they should be executed on.366	#[pallet::storage]367	pub type Agenda<T: Config> = StorageMap<368		_,369		Twox64Concat,370		T::BlockNumber,371		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,372		ValueQuery,373	>;374375	/// Lookup from a name to the block number and index of the task.376	#[pallet::storage]377	pub(crate) type Lookup<T: Config> =378		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;379380	/// Events type.381	#[pallet::event]382	#[pallet::generate_deposit(pub(super) fn deposit_event)]383	pub enum Event<T: Config> {384		/// Scheduled some task.385		Scheduled { when: T::BlockNumber, index: u32 },386		/// Canceled some task.387		Canceled { when: T::BlockNumber, index: u32 },388		/// Dispatched some task.389		Dispatched {390			task: TaskAddress<T::BlockNumber>,391			id: Option<[u8; 32]>,392			result: DispatchResult,393		},394		/// Scheduled task's priority has changed395		PriorityChanged {396			when: T::BlockNumber,397			index: u32,398			priority: schedule::Priority,399		},400		/// The call for the provided hash was not found so the task has been aborted.401		CallUnavailable {402			task: TaskAddress<T::BlockNumber>,403			id: Option<[u8; 32]>,404		},405		/// The given task was unable to be renewed since the agenda is full at that block.406		PeriodicFailed {407			task: TaskAddress<T::BlockNumber>,408			id: Option<[u8; 32]>,409		},410		/// The given task can never be executed since it is overweight.411		PermanentlyOverweight {412			task: TaskAddress<T::BlockNumber>,413			id: Option<[u8; 32]>,414		},415	}416417	#[pallet::error]418	pub enum Error<T> {419		/// Failed to schedule a call420		FailedToSchedule,421		/// There is no place for a new task in the agenda422		AgendaIsExhausted,423		/// Scheduled call is corrupted424		ScheduledCallCorrupted,425		/// Scheduled call preimage is not found426		PreimageNotFound,427		/// Scheduled call is too big428		TooBigScheduledCall,429		/// Cannot find the scheduled call.430		NotFound,431		/// Given target block number is in the past.432		TargetBlockNumberInPast,433		/// Attempt to use a non-named function on a named task.434		Named,435	}436437	#[pallet::hooks]438	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {439		/// Execute the scheduled calls440		fn on_initialize(now: T::BlockNumber) -> Weight {441			let mut weight_counter = WeightCounter {442				used: Weight::zero(),443				limit: T::MaximumWeight::get(),444			};445			Self::service_agendas(&mut weight_counter, now, u32::max_value());446			weight_counter.used447		}448	}449450	#[pallet::call]451	impl<T: Config> Pallet<T> {452		/// Anonymously schedule a task.453		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]454		pub fn schedule(455			origin: OriginFor<T>,456			when: T::BlockNumber,457			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,458			priority: Option<schedule::Priority>,459			call: Box<<T as Config>::RuntimeCall>,460		) -> DispatchResult {461			T::ScheduleOrigin::ensure_origin(origin.clone())?;462463			if priority.is_some() {464				T::PrioritySetOrigin::ensure_origin(origin.clone())?;465			}466467			let origin = <T as Config>::RuntimeOrigin::from(origin);468			Self::do_schedule(469				DispatchTime::At(when),470				maybe_periodic,471				priority.unwrap_or(LOWEST_PRIORITY),472				origin.caller().clone(),473				<ScheduledCall<T>>::new(*call)?,474			)?;475			Ok(())476		}477478		/// Cancel an anonymously scheduled task.479		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]480		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {481			T::ScheduleOrigin::ensure_origin(origin.clone())?;482			let origin = <T as Config>::RuntimeOrigin::from(origin);483			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;484			Ok(())485		}486487		/// Schedule a named task.488		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]489		pub fn schedule_named(490			origin: OriginFor<T>,491			id: TaskName,492			when: T::BlockNumber,493			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,494			priority: Option<schedule::Priority>,495			call: Box<<T as Config>::RuntimeCall>,496		) -> DispatchResult {497			T::ScheduleOrigin::ensure_origin(origin.clone())?;498499			if priority.is_some() {500				T::PrioritySetOrigin::ensure_origin(origin.clone())?;501			}502503			let origin = <T as Config>::RuntimeOrigin::from(origin);504			Self::do_schedule_named(505				id,506				DispatchTime::At(when),507				maybe_periodic,508				priority.unwrap_or(LOWEST_PRIORITY),509				origin.caller().clone(),510				<ScheduledCall<T>>::new(*call)?,511			)?;512			Ok(())513		}514515		/// Cancel a named scheduled task.516		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]517		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {518			T::ScheduleOrigin::ensure_origin(origin.clone())?;519			let origin = <T as Config>::RuntimeOrigin::from(origin);520			Self::do_cancel_named(Some(origin.caller().clone()), id)?;521			Ok(())522		}523524		/// Anonymously schedule a task after a delay.525		///526		/// # <weight>527		/// Same as [`schedule`].528		/// # </weight>529		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]530		pub fn schedule_after(531			origin: OriginFor<T>,532			after: T::BlockNumber,533			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,534			priority: Option<schedule::Priority>,535			call: Box<<T as Config>::RuntimeCall>,536		) -> DispatchResult {537			T::ScheduleOrigin::ensure_origin(origin.clone())?;538539			if priority.is_some() {540				T::PrioritySetOrigin::ensure_origin(origin.clone())?;541			}542543			let origin = <T as Config>::RuntimeOrigin::from(origin);544			Self::do_schedule(545				DispatchTime::After(after),546				maybe_periodic,547				priority.unwrap_or(LOWEST_PRIORITY),548				origin.caller().clone(),549				<ScheduledCall<T>>::new(*call)?,550			)?;551			Ok(())552		}553554		/// Schedule a named task after a delay.555		///556		/// # <weight>557		/// Same as [`schedule_named`](Self::schedule_named).558		/// # </weight>559		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]560		pub fn schedule_named_after(561			origin: OriginFor<T>,562			id: TaskName,563			after: T::BlockNumber,564			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,565			priority: Option<schedule::Priority>,566			call: Box<<T as Config>::RuntimeCall>,567		) -> DispatchResult {568			T::ScheduleOrigin::ensure_origin(origin.clone())?;569570			if priority.is_some() {571				T::PrioritySetOrigin::ensure_origin(origin.clone())?;572			}573574			let origin = <T as Config>::RuntimeOrigin::from(origin);575			Self::do_schedule_named(576				id,577				DispatchTime::After(after),578				maybe_periodic,579				priority.unwrap_or(LOWEST_PRIORITY),580				origin.caller().clone(),581				<ScheduledCall<T>>::new(*call)?,582			)?;583			Ok(())584		}585586		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]587		pub fn change_named_priority(588			origin: OriginFor<T>,589			id: TaskName,590			priority: schedule::Priority,591		) -> DispatchResult {592			T::PrioritySetOrigin::ensure_origin(origin.clone())?;593			let origin = <T as Config>::RuntimeOrigin::from(origin);594			Self::do_change_named_priority(origin.caller().clone(), id, priority)595		}596	}597}598599impl<T: Config> Pallet<T> {600	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {601		let now = frame_system::Pallet::<T>::block_number();602603		let when = match when {604			DispatchTime::At(x) => x,605			// The current block has already completed it's scheduled tasks, so606			// Schedule the task at lest one block after this current block.607			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),608		};609610		if when <= now {611			return Err(Error::<T>::TargetBlockNumberInPast.into());612		}613614		Ok(when)615	}616617	fn place_task(618		when: T::BlockNumber,619		what: ScheduledOf<T>,620	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {621		let maybe_name = what.maybe_id;622		let index = Self::push_to_agenda(when, what)?;623		let address = (when, index);624		if let Some(name) = maybe_name {625			Lookup::<T>::insert(name, address)626		}627		Self::deposit_event(Event::Scheduled {628			when: address.0,629			index: address.1,630		});631		Ok(address)632	}633634	fn push_to_agenda(635		when: T::BlockNumber,636		what: ScheduledOf<T>,637	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {638		let mut agenda = Agenda::<T>::get(when);639		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {640			// will always succeed due to the above check.641			let _ = agenda.try_push(Some(what));642			agenda.len() as u32 - 1643		} else {644			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {645				agenda[hole_index] = Some(what);646				hole_index as u32647			} else {648				return Err((<Error<T>>::AgendaIsExhausted.into(), what));649			}650		};651		Agenda::<T>::insert(when, agenda);652		Ok(index)653	}654655	fn do_schedule(656		when: DispatchTime<T::BlockNumber>,657		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,658		priority: schedule::Priority,659		origin: T::PalletsOrigin,660		call: ScheduledCall<T>,661	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662		let when = Self::resolve_time(when)?;663664		// sanitize maybe_periodic665		let maybe_periodic = maybe_periodic666			.filter(|p| p.1 > 1 && !p.0.is_zero())667			// Remove one from the number of repetitions since we will schedule one now.668			.map(|(p, c)| (p, c - 1));669		let task = Scheduled {670			maybe_id: None,671			priority,672			call,673			maybe_periodic,674			origin,675			_phantom: PhantomData,676		};677		Self::place_task(when, task).map_err(|x| x.0)678	}679680	fn do_cancel(681		origin: Option<T::PalletsOrigin>,682		(when, index): TaskAddress<T::BlockNumber>,683	) -> Result<(), DispatchError> {684		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {685			agenda.get_mut(index as usize).map_or(686				Ok(None),687				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {688					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {689						if matches!(690							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),691							Some(Ordering::Less) | None692						) {693							return Err(BadOrigin.into());694						}695					};696					Ok(s.take())697				},698			)699		})?;700		if let Some(s) = scheduled {701			T::Preimages::drop(&s.call);702703			if let Some(id) = s.maybe_id {704				Lookup::<T>::remove(id);705			}706			Self::deposit_event(Event::Canceled { when, index });707			Ok(())708		} else {709			return Err(Error::<T>::NotFound.into());710		}711	}712713	fn do_schedule_named(714		id: TaskName,715		when: DispatchTime<T::BlockNumber>,716		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,717		priority: schedule::Priority,718		origin: T::PalletsOrigin,719		call: ScheduledCall<T>,720	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {721		// ensure id it is unique722		if Lookup::<T>::contains_key(&id) {723			return Err(Error::<T>::FailedToSchedule.into());724		}725726		let when = Self::resolve_time(when)?;727728		// sanitize maybe_periodic729		let maybe_periodic = maybe_periodic730			.filter(|p| p.1 > 1 && !p.0.is_zero())731			// Remove one from the number of repetitions since we will schedule one now.732			.map(|(p, c)| (p, c - 1));733734		let task = Scheduled {735			maybe_id: Some(id),736			priority,737			call,738			maybe_periodic,739			origin,740			_phantom: Default::default(),741		};742		Self::place_task(when, task).map_err(|x| x.0)743	}744745	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {746		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {747			if let Some((when, index)) = lookup.take() {748				let i = index as usize;749				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {750					if let Some(s) = agenda.get_mut(i) {751						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {752							if matches!(753								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),754								Some(Ordering::Less) | None755							) {756								return Err(BadOrigin.into());757							}758							T::Preimages::drop(&s.call);759						}760						*s = None;761					}762					Ok(())763				})?;764				Self::deposit_event(Event::Canceled { when, index });765				Ok(())766			} else {767				return Err(Error::<T>::NotFound.into());768			}769		})770	}771772	fn do_change_named_priority(773		origin: T::PalletsOrigin,774		id: TaskName,775		priority: schedule::Priority,776	) -> DispatchResult {777		match Lookup::<T>::get(id) {778			Some((when, index)) => {779				let i = index as usize;780				Agenda::<T>::try_mutate(when, |agenda| {781					if let Some(Some(s)) = agenda.get_mut(i) {782						if matches!(783							T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),784							Some(Ordering::Less) | None785						) {786							return Err(BadOrigin.into());787						}788789						s.priority = priority;790						Self::deposit_event(Event::PriorityChanged {791							when,792							index,793							priority,794						});795					}796					Ok(())797				})798			}799			None => Err(Error::<T>::NotFound.into()),800		}801	}802}803804enum ServiceTaskError {805	/// Could not be executed due to missing preimage.806	Unavailable,807	/// Could not be executed due to weight limitations.808	Overweight,809}810use ServiceTaskError::*;811812/// A Scheduler-Runtime interface for finer payment handling.813pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {814	/// Resolve the call dispatch, including any post-dispatch operations.815	fn dispatch_call(816		signer: Option<T::AccountId>,817		function: <T as Config>::RuntimeCall,818	) -> Result<819		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,820		TransactionValidityError,821	>;822}823824impl<T: Config> Pallet<T> {825	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.826	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {827		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {828			return;829		}830831		let mut incomplete_since = now + One::one();832		let mut when = IncompleteSince::<T>::take().unwrap_or(now);833		let mut executed = 0;834835		let max_items = T::MaxScheduledPerBlock::get();836		let mut count_down = max;837		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);838		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {839			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {840				incomplete_since = incomplete_since.min(when);841			}842			when.saturating_inc();843			count_down.saturating_dec();844		}845		incomplete_since = incomplete_since.min(when);846		if incomplete_since <= now {847			IncompleteSince::<T>::put(incomplete_since);848		}849	}850851	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a852	/// later block.853	fn service_agenda(854		weight: &mut WeightCounter,855		executed: &mut u32,856		now: T::BlockNumber,857		when: T::BlockNumber,858		max: u32,859	) -> bool {860		let mut agenda = Agenda::<T>::get(when);861		let mut ordered = agenda862			.iter()863			.enumerate()864			.filter_map(|(index, maybe_item)| {865				maybe_item866					.as_ref()867					.map(|item| (index as u32, item.priority))868			})869			.collect::<Vec<_>>();870		ordered.sort_by_key(|k| k.1);871		let within_limit =872			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));873		debug_assert!(874			within_limit,875			"weight limit should have been checked in advance"876		);877878		// Items which we know can be executed and have postponed for execution in a later block.879		let mut postponed = (ordered.len() as u32).saturating_sub(max);880		// Items which we don't know can ever be executed.881		let mut dropped = 0;882883		for (agenda_index, _) in ordered.into_iter().take(max as usize) {884			let task = match agenda[agenda_index as usize].take() {885				None => continue,886				Some(t) => t,887			};888			let base_weight = T::WeightInfo::service_task(889				task.call.lookup_len().map(|x| x as usize),890				task.maybe_id.is_some(),891				task.maybe_periodic.is_some(),892			);893			if !weight.can_accrue(base_weight) {894				postponed += 1;895				break;896			}897			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);898			agenda[agenda_index as usize] = match result {899				Err((Unavailable, slot)) => {900					dropped += 1;901					slot902				}903				Err((Overweight, slot)) => {904					postponed += 1;905					slot906				}907				Ok(()) => {908					*executed += 1;909					None910				}911			};912		}913		if postponed > 0 || dropped > 0 {914			Agenda::<T>::insert(when, agenda);915		} else {916			Agenda::<T>::remove(when);917		}918		postponed == 0919	}920921	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.922	///923	/// This involves:924	/// - removing and potentially replacing the `Lookup` entry for the task.925	/// - realizing the task's call which can include a preimage lookup.926	/// - Rescheduling the task for execution in a later agenda if periodic.927	fn service_task(928		weight: &mut WeightCounter,929		now: T::BlockNumber,930		when: T::BlockNumber,931		agenda_index: u32,932		is_first: bool,933		mut task: ScheduledOf<T>,934	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {935		let (call, lookup_len) = match T::Preimages::peek(&task.call) {936			Ok(c) => c,937			Err(_) => {938				if let Some(ref id) = task.maybe_id {939					Lookup::<T>::remove(id);940				}941942				return Err((Unavailable, Some(task)));943			},944		};945946		weight.check_accrue(T::WeightInfo::service_task(947			lookup_len.map(|x| x as usize),948			task.maybe_id.is_some(),949			task.maybe_periodic.is_some(),950		));951952		match Self::execute_dispatch(weight, task.origin.clone(), call) {953			Err(Unavailable) => {954				debug_assert!(false, "Checked to exist with `peek`");955956				if let Some(ref id) = task.maybe_id {957					Lookup::<T>::remove(id);958				}959960				Self::deposit_event(Event::CallUnavailable {961					task: (when, agenda_index),962					id: task.maybe_id,963				});964				Err((Unavailable, Some(task)))965			}966			Err(Overweight) if is_first => {967				T::Preimages::drop(&task.call);968969				if let Some(ref id) = task.maybe_id {970					Lookup::<T>::remove(id);971				}972973				Self::deposit_event(Event::PermanentlyOverweight {974					task: (when, agenda_index),975					id: task.maybe_id,976				});977				Err((Unavailable, Some(task)))978			}979			Err(Overweight) => {980				// Preserve Lookup -- the task will be postponed.981				Err((Overweight, Some(task)))982			},983			Ok(result) => {984				Self::deposit_event(Event::Dispatched {985					task: (when, agenda_index),986					id: task.maybe_id,987					result,988				});989990				let is_canceled = task.maybe_id.as_ref()991					.map(|id| !Lookup::<T>::contains_key(id))992					.unwrap_or(false);993994				match &task.maybe_periodic {995					&Some((period, count)) if !is_canceled => {996						if count > 1 {997							task.maybe_periodic = Some((period, count - 1));998						} else {999							task.maybe_periodic = None;1000						}1001						let wake = now.saturating_add(period);1002						match Self::place_task(wake, task) {1003							Ok(_) => {}1004							Err((_, task)) => {1005								// TODO: Leave task in storage somewhere for it to be rescheduled1006								// manually.1007								T::Preimages::drop(&task.call);1008								Self::deposit_event(Event::PeriodicFailed {1009									task: (when, agenda_index),1010									id: task.maybe_id,1011								});1012							}1013						}1014					},1015					_ => {1016						if let Some(ref id) = task.maybe_id {1017							Lookup::<T>::remove(id);1018						}10191020						T::Preimages::drop(&task.call)1021					},1022				}1023				Ok(())1024			}1025		}1026	}10271028	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1029	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1030	/// post info if available).1031	///1032	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1033	/// call itself).1034	fn execute_dispatch(1035		weight: &mut WeightCounter,1036		origin: T::PalletsOrigin,1037		call: <T as Config>::RuntimeCall,1038	) -> Result<DispatchResult, ServiceTaskError> {1039		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1040		let base_weight = match dispatch_origin.clone().as_signed() {1041			Some(_) => T::WeightInfo::execute_dispatch_signed(),1042			_ => T::WeightInfo::execute_dispatch_unsigned(),1043		};1044		let call_weight = call.get_dispatch_info().weight;1045		// We only allow a scheduled call if it cannot push the weight past the limit.1046		let max_weight = base_weight.saturating_add(call_weight);10471048		if !weight.can_accrue(max_weight) {1049			return Err(Overweight);1050		}10511052		// let scheduled_origin =1053		// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());1054		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());10551056		let r = match ensured_origin {1057			Ok(ScheduledEnsureOriginSuccess::Root) => {1058				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1059			},1060			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1061				// Execute transaction via chain default pipeline1062				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1063				T::CallExecutor::dispatch_call(Some(sender), call.clone())1064			},1065			Ok(ScheduledEnsureOriginSuccess::Unsigned) => {1066				// Unsigned version of the above1067				T::CallExecutor::dispatch_call(None, call.clone())1068			}1069			Err(e) => Ok(Err(e.into())),1070		};10711072		let (maybe_actual_call_weight, result) = match r {1073			Ok(result) => match result {1074				Ok(post_info) => (post_info.actual_weight, Ok(())),1075				Err(error_and_info) => (1076					error_and_info.post_info.actual_weight,1077					Err(error_and_info.error),1078				),1079			},1080			Err(_) => {1081				log::error!(1082					target: "runtime::scheduler",1083					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1084					This block might have become invalid.");1085				(None, Err(DispatchError::CannotLookup))1086			}1087		};1088		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1089		weight.check_accrue(base_weight);1090		weight.check_accrue(call_weight);1091		Ok(result)1092	}1093}
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)]6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72#[cfg(test)]73mod mock;74#[cfg(test)]75mod tests;76pub mod weights;7778use codec::{Codec, Decode, Encode, MaxEncodedLen};79use frame_support::{80	dispatch::{DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo},81	traits::{82		schedule::{self, DispatchTime, LOWEST_PRIORITY},83		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,84		ConstU32, UnfilteredDispatchable,85	},86	weights::Weight, unsigned::TransactionValidityError,87};8889use frame_system::{self as system};90use scale_info::TypeInfo;91use sp_runtime::{92	traits::{BadOrigin, One, Saturating, Zero, Hash},93	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,94};95use sp_core::H160;96use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};97pub use weights::WeightInfo;9899pub use pallet::*;100101/// Just a simple index for naming period tasks.102pub type PeriodicIndex = u32;103/// The location of a scheduled task that can be used to remove it.104pub type TaskAddress<BlockNumber> = (BlockNumber, u32);105106pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;107108#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]109#[scale_info(skip_type_params(T))]110pub enum ScheduledCall<T: Config> {111	Inline(EncodedCall),112	PreimageLookup { hash: T::Hash, unbounded_len: u32 },113}114115impl<T: Config> ScheduledCall<T> {116	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {117		let encoded = call.encode();118		let len = encoded.len();119120		match EncodedCall::try_from(encoded.clone()) {121			Ok(bounded) => Ok(Self::Inline(bounded)),122			Err(_) => {123				let hash = <T as system::Config>::Hashing::hash_of(&encoded);124				<T as Config>::Preimages::note_preimage(125					encoded126						.try_into()127						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,128				);129130				Ok(Self::PreimageLookup {131					hash,132					unbounded_len: len as u32,133				})134			}135		}136	}137138	/// The maximum length of the lookup that is needed to peek `Self`.139	pub fn lookup_len(&self) -> Option<u32> {140		match self {141			Self::Inline(..) => None,142			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),143		}144	}145146	/// Returns whether the image will require a lookup to be peeked.147	pub fn lookup_needed(&self) -> bool {148		match self {149			Self::Inline(_) => false,150			Self::PreimageLookup { .. } => true,151		}152	}153154	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {155		<T as Config>::RuntimeCall::decode(&mut data)156			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())157	}158}159160pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {161	fn drop(call: &ScheduledCall<T>);162163	fn peek(164		call: &ScheduledCall<T>,165	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;166167	/// Convert the given scheduled `call` value back into its original instance. If successful,168	/// `drop` any data backing it. This will not break the realisability of independently169	/// created instances of `ScheduledCall` which happen to have identical data.170	fn realize(171		call: &ScheduledCall<T>,172	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;173}174175impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {176	fn drop(call: &ScheduledCall<T>) {177		match call {178			ScheduledCall::Inline(_) => {}179			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),180		}181	}182183	fn peek(184		call: &ScheduledCall<T>,185	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {186		match call {187			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),188			ScheduledCall::PreimageLookup {189				hash,190				unbounded_len,191			} => {192				let (preimage, len) = Self::get_preimage(hash)193					.ok_or(<Error<T>>::PreimageNotFound)194					.map(|preimage| (preimage, *unbounded_len))?;195196				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))197			}198		}199	}200201	fn realize(202		call: &ScheduledCall<T>,203	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {204		let r = Self::peek(call)?;205		Self::drop(call);206		Ok(r)207	}208}209210pub enum ScheduledEnsureOriginSuccess<AccountId> {211	Root,212	Signed(AccountId),213	Unsigned,214}215216pub type TaskName = [u8; 32];217218/// Information regarding an item to be executed in the future.219#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]220#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]221pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {222	/// The unique identity for this task, if there is one.223	maybe_id: Option<Name>,224225	/// This task's priority.226	priority: schedule::Priority,227228	/// The call to be dispatched.229	call: Call,230231	/// If the call is periodic, then this points to the information concerning that.232	maybe_periodic: Option<schedule::Period<BlockNumber>>,233234	/// The origin with which to dispatch the call.235	origin: PalletsOrigin,236	_phantom: PhantomData<AccountId>,237}238239pub type ScheduledOf<T> = Scheduled<240	TaskName,241	ScheduledCall<T>,242	<T as frame_system::Config>::BlockNumber,243	<T as Config>::PalletsOrigin,244	<T as frame_system::Config>::AccountId,245>;246247struct WeightCounter {248	used: Weight,249	limit: Weight,250}251252impl WeightCounter {253	fn check_accrue(&mut self, w: Weight) -> bool {254		let test = self.used.saturating_add(w);255		if test.any_gt(self.limit) {256			false257		} else {258			self.used = test;259			true260		}261	}262263	fn can_accrue(&mut self, w: Weight) -> bool {264		self.used.saturating_add(w).all_lte(self.limit)265	}266}267268pub(crate) trait MarginalWeightInfo: WeightInfo {269	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {270		let base = Self::service_task_base();271		let mut total = match maybe_lookup_len {272			None => base,273			Some(l) => Self::service_task_fetched(l as u32),274		};275		if named {276			total.saturating_accrue(Self::service_task_named().saturating_sub(base));277		}278		if periodic {279			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));280		}281		total282	}283}284285impl<T: WeightInfo> MarginalWeightInfo for T {}286287#[frame_support::pallet]288pub mod pallet {289	use super::*;290	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};291	use system::pallet_prelude::*;292293	/// The current storage version.294	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);295296	#[pallet::pallet]297	#[pallet::generate_store(pub(super) trait Store)]298	#[pallet::storage_version(STORAGE_VERSION)]299	pub struct Pallet<T>(_);300301	#[pallet::config]302	pub trait Config: frame_system::Config {303		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;304305		/// The aggregated origin which the dispatch will take.306		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>307			+ From<Self::PalletsOrigin>308			+ IsType<<Self as system::Config>::RuntimeOrigin>309			+ Clone;310311		/// The caller origin, overarching type of all pallets origins.312		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>313			+ Codec314			+ Clone315			+ Eq316			+ TypeInfo317			+ MaxEncodedLen;318319		/// The aggregated call type.320		type RuntimeCall: Parameter321			+ Dispatchable<RuntimeOrigin = <Self as Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>322			+ UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>323			+ GetDispatchInfo324			+ From<system::Call<Self>>;325326		/// The maximum weight that may be scheduled per block for any dispatchables.327		#[pallet::constant]328		type MaximumWeight: Get<Weight>;329330		/// Required origin to schedule or cancel calls.331		type ScheduleOrigin: EnsureOrigin<332			<Self as system::Config>::RuntimeOrigin,333			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,334		>;335336		/// Compare the privileges of origins.337		///338		/// This will be used when canceling a task, to ensure that the origin that tries339		/// to cancel has greater or equal privileges as the origin that created the scheduled task.340		///341		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can342		/// be used. This will only check if two given origins are equal.343		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;344345		/// The maximum number of scheduled calls in the queue for a single block.346		#[pallet::constant]347		type MaxScheduledPerBlock: Get<u32>;348349		/// Weight information for extrinsics in this pallet.350		type WeightInfo: WeightInfo;351352		/// The preimage provider with which we look up call hashes to get the call.353		type Preimages: SchedulerPreimages<Self>;354355		/// The helper type used for custom transaction fee logic.356		type CallExecutor: DispatchCall<Self, H160>;357358		/// Required origin to set/change calls' priority.359		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;360	}361362	#[pallet::storage]363	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;364365	/// Items to be executed, indexed by the block number that they should be executed on.366	#[pallet::storage]367	pub type Agenda<T: Config> = StorageMap<368		_,369		Twox64Concat,370		T::BlockNumber,371		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,372		ValueQuery,373	>;374375	/// Lookup from a name to the block number and index of the task.376	#[pallet::storage]377	pub(crate) type Lookup<T: Config> =378		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;379380	/// Events type.381	#[pallet::event]382	#[pallet::generate_deposit(pub(super) fn deposit_event)]383	pub enum Event<T: Config> {384		/// Scheduled some task.385		Scheduled { when: T::BlockNumber, index: u32 },386		/// Canceled some task.387		Canceled { when: T::BlockNumber, index: u32 },388		/// Dispatched some task.389		Dispatched {390			task: TaskAddress<T::BlockNumber>,391			id: Option<[u8; 32]>,392			result: DispatchResult,393		},394		/// Scheduled task's priority has changed395		PriorityChanged {396			when: T::BlockNumber,397			index: u32,398			priority: schedule::Priority,399		},400		/// The call for the provided hash was not found so the task has been aborted.401		CallUnavailable {402			task: TaskAddress<T::BlockNumber>,403			id: Option<[u8; 32]>,404		},405		/// The given task was unable to be renewed since the agenda is full at that block.406		PeriodicFailed {407			task: TaskAddress<T::BlockNumber>,408			id: Option<[u8; 32]>,409		},410		/// The given task can never be executed since it is overweight.411		PermanentlyOverweight {412			task: TaskAddress<T::BlockNumber>,413			id: Option<[u8; 32]>,414		},415	}416417	#[pallet::error]418	pub enum Error<T> {419		/// Failed to schedule a call420		FailedToSchedule,421		/// There is no place for a new task in the agenda422		AgendaIsExhausted,423		/// Scheduled call is corrupted424		ScheduledCallCorrupted,425		/// Scheduled call preimage is not found426		PreimageNotFound,427		/// Scheduled call is too big428		TooBigScheduledCall,429		/// Cannot find the scheduled call.430		NotFound,431		/// Given target block number is in the past.432		TargetBlockNumberInPast,433		/// Attempt to use a non-named function on a named task.434		Named,435	}436437	#[pallet::hooks]438	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {439		/// Execute the scheduled calls440		fn on_initialize(now: T::BlockNumber) -> Weight {441			let mut weight_counter = WeightCounter {442				used: Weight::zero(),443				limit: T::MaximumWeight::get(),444			};445			Self::service_agendas(&mut weight_counter, now, u32::max_value());446			weight_counter.used447		}448	}449450	#[pallet::call]451	impl<T: Config> Pallet<T> {452		/// Anonymously schedule a task.453		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]454		pub fn schedule(455			origin: OriginFor<T>,456			when: T::BlockNumber,457			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,458			priority: Option<schedule::Priority>,459			call: Box<<T as Config>::RuntimeCall>,460		) -> DispatchResult {461			T::ScheduleOrigin::ensure_origin(origin.clone())?;462463			if priority.is_some() {464				T::PrioritySetOrigin::ensure_origin(origin.clone())?;465			}466467			let origin = <T as Config>::RuntimeOrigin::from(origin);468			Self::do_schedule(469				DispatchTime::At(when),470				maybe_periodic,471				priority.unwrap_or(LOWEST_PRIORITY),472				origin.caller().clone(),473				<ScheduledCall<T>>::new(*call)?,474			)?;475			Ok(())476		}477478		/// Cancel an anonymously scheduled task.479		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]480		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {481			T::ScheduleOrigin::ensure_origin(origin.clone())?;482			let origin = <T as Config>::RuntimeOrigin::from(origin);483			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;484			Ok(())485		}486487		/// Schedule a named task.488		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]489		pub fn schedule_named(490			origin: OriginFor<T>,491			id: TaskName,492			when: T::BlockNumber,493			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,494			priority: Option<schedule::Priority>,495			call: Box<<T as Config>::RuntimeCall>,496		) -> DispatchResult {497			T::ScheduleOrigin::ensure_origin(origin.clone())?;498499			if priority.is_some() {500				T::PrioritySetOrigin::ensure_origin(origin.clone())?;501			}502503			let origin = <T as Config>::RuntimeOrigin::from(origin);504			Self::do_schedule_named(505				id,506				DispatchTime::At(when),507				maybe_periodic,508				priority.unwrap_or(LOWEST_PRIORITY),509				origin.caller().clone(),510				<ScheduledCall<T>>::new(*call)?,511			)?;512			Ok(())513		}514515		/// Cancel a named scheduled task.516		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]517		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {518			T::ScheduleOrigin::ensure_origin(origin.clone())?;519			let origin = <T as Config>::RuntimeOrigin::from(origin);520			Self::do_cancel_named(Some(origin.caller().clone()), id)?;521			Ok(())522		}523524		/// Anonymously schedule a task after a delay.525		///526		/// # <weight>527		/// Same as [`schedule`].528		/// # </weight>529		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]530		pub fn schedule_after(531			origin: OriginFor<T>,532			after: T::BlockNumber,533			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,534			priority: Option<schedule::Priority>,535			call: Box<<T as Config>::RuntimeCall>,536		) -> DispatchResult {537			T::ScheduleOrigin::ensure_origin(origin.clone())?;538539			if priority.is_some() {540				T::PrioritySetOrigin::ensure_origin(origin.clone())?;541			}542543			let origin = <T as Config>::RuntimeOrigin::from(origin);544			Self::do_schedule(545				DispatchTime::After(after),546				maybe_periodic,547				priority.unwrap_or(LOWEST_PRIORITY),548				origin.caller().clone(),549				<ScheduledCall<T>>::new(*call)?,550			)?;551			Ok(())552		}553554		/// Schedule a named task after a delay.555		///556		/// # <weight>557		/// Same as [`schedule_named`](Self::schedule_named).558		/// # </weight>559		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]560		pub fn schedule_named_after(561			origin: OriginFor<T>,562			id: TaskName,563			after: T::BlockNumber,564			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,565			priority: Option<schedule::Priority>,566			call: Box<<T as Config>::RuntimeCall>,567		) -> DispatchResult {568			T::ScheduleOrigin::ensure_origin(origin.clone())?;569570			if priority.is_some() {571				T::PrioritySetOrigin::ensure_origin(origin.clone())?;572			}573574			let origin = <T as Config>::RuntimeOrigin::from(origin);575			Self::do_schedule_named(576				id,577				DispatchTime::After(after),578				maybe_periodic,579				priority.unwrap_or(LOWEST_PRIORITY),580				origin.caller().clone(),581				<ScheduledCall<T>>::new(*call)?,582			)?;583			Ok(())584		}585586		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]587		pub fn change_named_priority(588			origin: OriginFor<T>,589			id: TaskName,590			priority: schedule::Priority,591		) -> DispatchResult {592			T::PrioritySetOrigin::ensure_origin(origin.clone())?;593			let origin = <T as Config>::RuntimeOrigin::from(origin);594			Self::do_change_named_priority(origin.caller().clone(), id, priority)595		}596	}597}598599impl<T: Config> Pallet<T> {600	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {601		let now = frame_system::Pallet::<T>::block_number();602603		let when = match when {604			DispatchTime::At(x) => x,605			// The current block has already completed it's scheduled tasks, so606			// Schedule the task at lest one block after this current block.607			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),608		};609610		if when <= now {611			return Err(Error::<T>::TargetBlockNumberInPast.into());612		}613614		Ok(when)615	}616617	fn place_task(618		when: T::BlockNumber,619		what: ScheduledOf<T>,620	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {621		let maybe_name = what.maybe_id;622		let index = Self::push_to_agenda(when, what)?;623		let address = (when, index);624		if let Some(name) = maybe_name {625			Lookup::<T>::insert(name, address)626		}627		Self::deposit_event(Event::Scheduled {628			when: address.0,629			index: address.1,630		});631		Ok(address)632	}633634	fn push_to_agenda(635		when: T::BlockNumber,636		what: ScheduledOf<T>,637	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {638		let mut agenda = Agenda::<T>::get(when);639		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {640			// will always succeed due to the above check.641			let _ = agenda.try_push(Some(what));642			agenda.len() as u32 - 1643		} else {644			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {645				agenda[hole_index] = Some(what);646				hole_index as u32647			} else {648				return Err((<Error<T>>::AgendaIsExhausted.into(), what));649			}650		};651		Agenda::<T>::insert(when, agenda);652		Ok(index)653	}654655	fn do_schedule(656		when: DispatchTime<T::BlockNumber>,657		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,658		priority: schedule::Priority,659		origin: T::PalletsOrigin,660		call: ScheduledCall<T>,661	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662		let when = Self::resolve_time(when)?;663664		// sanitize maybe_periodic665		let maybe_periodic = maybe_periodic666			.filter(|p| p.1 > 1 && !p.0.is_zero())667			// Remove one from the number of repetitions since we will schedule one now.668			.map(|(p, c)| (p, c - 1));669		let task = Scheduled {670			maybe_id: None,671			priority,672			call,673			maybe_periodic,674			origin,675			_phantom: PhantomData,676		};677		Self::place_task(when, task).map_err(|x| x.0)678	}679680	fn do_cancel(681		origin: Option<T::PalletsOrigin>,682		(when, index): TaskAddress<T::BlockNumber>,683	) -> Result<(), DispatchError> {684		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {685			agenda.get_mut(index as usize).map_or(686				Ok(None),687				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {688					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {689						if matches!(690							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),691							Some(Ordering::Less) | None692						) {693							return Err(BadOrigin.into());694						}695					};696					Ok(s.take())697				},698			)699		})?;700		if let Some(s) = scheduled {701			T::Preimages::drop(&s.call);702703			if let Some(id) = s.maybe_id {704				Lookup::<T>::remove(id);705			}706			Self::deposit_event(Event::Canceled { when, index });707			Ok(())708		} else {709			return Err(Error::<T>::NotFound.into());710		}711	}712713	fn do_schedule_named(714		id: TaskName,715		when: DispatchTime<T::BlockNumber>,716		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,717		priority: schedule::Priority,718		origin: T::PalletsOrigin,719		call: ScheduledCall<T>,720	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {721		// ensure id it is unique722		if Lookup::<T>::contains_key(&id) {723			return Err(Error::<T>::FailedToSchedule.into());724		}725726		let when = Self::resolve_time(when)?;727728		// sanitize maybe_periodic729		let maybe_periodic = maybe_periodic730			.filter(|p| p.1 > 1 && !p.0.is_zero())731			// Remove one from the number of repetitions since we will schedule one now.732			.map(|(p, c)| (p, c - 1));733734		let task = Scheduled {735			maybe_id: Some(id),736			priority,737			call,738			maybe_periodic,739			origin,740			_phantom: Default::default(),741		};742		Self::place_task(when, task).map_err(|x| x.0)743	}744745	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {746		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {747			if let Some((when, index)) = lookup.take() {748				let i = index as usize;749				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {750					if let Some(s) = agenda.get_mut(i) {751						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {752							if matches!(753								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),754								Some(Ordering::Less) | None755							) {756								return Err(BadOrigin.into());757							}758							T::Preimages::drop(&s.call);759						}760						*s = None;761					}762					Ok(())763				})?;764				Self::deposit_event(Event::Canceled { when, index });765				Ok(())766			} else {767				return Err(Error::<T>::NotFound.into());768			}769		})770	}771772	fn do_change_named_priority(773		origin: T::PalletsOrigin,774		id: TaskName,775		priority: schedule::Priority,776	) -> DispatchResult {777		match Lookup::<T>::get(id) {778			Some((when, index)) => {779				let i = index as usize;780				Agenda::<T>::try_mutate(when, |agenda| {781					if let Some(Some(s)) = agenda.get_mut(i) {782						if matches!(783							T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),784							Some(Ordering::Less) | None785						) {786							return Err(BadOrigin.into());787						}788789						s.priority = priority;790						Self::deposit_event(Event::PriorityChanged {791							when,792							index,793							priority,794						});795					}796					Ok(())797				})798			}799			None => Err(Error::<T>::NotFound.into()),800		}801	}802}803804enum ServiceTaskError {805	/// Could not be executed due to missing preimage.806	Unavailable,807	/// Could not be executed due to weight limitations.808	Overweight,809}810use ServiceTaskError::*;811812/// A Scheduler-Runtime interface for finer payment handling.813pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {814	/// Resolve the call dispatch, including any post-dispatch operations.815	fn dispatch_call(816		signer: Option<T::AccountId>,817		function: <T as Config>::RuntimeCall,818	) -> Result<819		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,820		TransactionValidityError,821	>;822}823824impl<T: Config> Pallet<T> {825	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.826	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {827		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {828			return;829		}830831		let mut incomplete_since = now + One::one();832		let mut when = IncompleteSince::<T>::take().unwrap_or(now);833		let mut executed = 0;834835		let max_items = T::MaxScheduledPerBlock::get();836		let mut count_down = max;837		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);838		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {839			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {840				incomplete_since = incomplete_since.min(when);841			}842			when.saturating_inc();843			count_down.saturating_dec();844		}845		incomplete_since = incomplete_since.min(when);846		if incomplete_since <= now {847			IncompleteSince::<T>::put(incomplete_since);848		}849	}850851	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a852	/// later block.853	fn service_agenda(854		weight: &mut WeightCounter,855		executed: &mut u32,856		now: T::BlockNumber,857		when: T::BlockNumber,858		max: u32,859	) -> bool {860		let mut agenda = Agenda::<T>::get(when);861		let mut ordered = agenda862			.iter()863			.enumerate()864			.filter_map(|(index, maybe_item)| {865				maybe_item866					.as_ref()867					.map(|item| (index as u32, item.priority))868			})869			.collect::<Vec<_>>();870		ordered.sort_by_key(|k| k.1);871		let within_limit =872			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));873		debug_assert!(874			within_limit,875			"weight limit should have been checked in advance"876		);877878		// Items which we know can be executed and have postponed for execution in a later block.879		let mut postponed = (ordered.len() as u32).saturating_sub(max);880		// Items which we don't know can ever be executed.881		let mut dropped = 0;882883		for (agenda_index, _) in ordered.into_iter().take(max as usize) {884			let task = match agenda[agenda_index as usize].take() {885				None => continue,886				Some(t) => t,887			};888			let base_weight = T::WeightInfo::service_task(889				task.call.lookup_len().map(|x| x as usize),890				task.maybe_id.is_some(),891				task.maybe_periodic.is_some(),892			);893			if !weight.can_accrue(base_weight) {894				postponed += 1;895				break;896			}897			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);898			agenda[agenda_index as usize] = match result {899				Err((Unavailable, slot)) => {900					dropped += 1;901					slot902				}903				Err((Overweight, slot)) => {904					postponed += 1;905					slot906				}907				Ok(()) => {908					*executed += 1;909					None910				}911			};912		}913		if postponed > 0 || dropped > 0 {914			Agenda::<T>::insert(when, agenda);915		} else {916			Agenda::<T>::remove(when);917		}918		postponed == 0919	}920921	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.922	///923	/// This involves:924	/// - removing and potentially replacing the `Lookup` entry for the task.925	/// - realizing the task's call which can include a preimage lookup.926	/// - Rescheduling the task for execution in a later agenda if periodic.927	fn service_task(928		weight: &mut WeightCounter,929		now: T::BlockNumber,930		when: T::BlockNumber,931		agenda_index: u32,932		is_first: bool,933		mut task: ScheduledOf<T>,934	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {935		let (call, lookup_len) = match T::Preimages::peek(&task.call) {936			Ok(c) => c,937			Err(_) => {938				if let Some(ref id) = task.maybe_id {939					Lookup::<T>::remove(id);940				}941942				return Err((Unavailable, Some(task)));943			},944		};945946		weight.check_accrue(T::WeightInfo::service_task(947			lookup_len.map(|x| x as usize),948			task.maybe_id.is_some(),949			task.maybe_periodic.is_some(),950		));951952		match Self::execute_dispatch(weight, task.origin.clone(), call) {953			Err(Unavailable) => {954				debug_assert!(false, "Checked to exist with `peek`");955956				if let Some(ref id) = task.maybe_id {957					Lookup::<T>::remove(id);958				}959960				Self::deposit_event(Event::CallUnavailable {961					task: (when, agenda_index),962					id: task.maybe_id,963				});964				Err((Unavailable, Some(task)))965			}966			Err(Overweight) if is_first => {967				T::Preimages::drop(&task.call);968969				if let Some(ref id) = task.maybe_id {970					Lookup::<T>::remove(id);971				}972973				Self::deposit_event(Event::PermanentlyOverweight {974					task: (when, agenda_index),975					id: task.maybe_id,976				});977				Err((Unavailable, Some(task)))978			}979			Err(Overweight) => {980				// Preserve Lookup -- the task will be postponed.981				Err((Overweight, Some(task)))982			},983			Ok(result) => {984				Self::deposit_event(Event::Dispatched {985					task: (when, agenda_index),986					id: task.maybe_id,987					result,988				});989990				let is_canceled = task.maybe_id.as_ref()991					.map(|id| !Lookup::<T>::contains_key(id))992					.unwrap_or(false);993994				match &task.maybe_periodic {995					&Some((period, count)) if !is_canceled => {996						if count > 1 {997							task.maybe_periodic = Some((period, count - 1));998						} else {999							task.maybe_periodic = None;1000						}1001						let wake = now.saturating_add(period);1002						match Self::place_task(wake, task) {1003							Ok(_) => {}1004							Err((_, task)) => {1005								// TODO: Leave task in storage somewhere for it to be rescheduled1006								// manually.1007								T::Preimages::drop(&task.call);1008								Self::deposit_event(Event::PeriodicFailed {1009									task: (when, agenda_index),1010									id: task.maybe_id,1011								});1012							}1013						}1014					},1015					_ => {1016						if let Some(ref id) = task.maybe_id {1017							Lookup::<T>::remove(id);1018						}10191020						T::Preimages::drop(&task.call)1021					},1022				}1023				Ok(())1024			}1025		}1026	}10271028	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1029	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1030	/// post info if available).1031	///1032	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1033	/// call itself).1034	fn execute_dispatch(1035		weight: &mut WeightCounter,1036		origin: T::PalletsOrigin,1037		call: <T as Config>::RuntimeCall,1038	) -> Result<DispatchResult, ServiceTaskError> {1039		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1040		let base_weight = match dispatch_origin.clone().as_signed() {1041			Some(_) => T::WeightInfo::execute_dispatch_signed(),1042			_ => T::WeightInfo::execute_dispatch_unsigned(),1043		};1044		let call_weight = call.get_dispatch_info().weight;1045		// We only allow a scheduled call if it cannot push the weight past the limit.1046		let max_weight = base_weight.saturating_add(call_weight);10471048		if !weight.can_accrue(max_weight) {1049			return Err(Overweight);1050		}10511052		// let scheduled_origin =1053		// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());1054		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());10551056		let r = match ensured_origin {1057			Ok(ScheduledEnsureOriginSuccess::Root) => {1058				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1059			},1060			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1061				// Execute transaction via chain default pipeline1062				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1063				T::CallExecutor::dispatch_call(Some(sender), call.clone())1064			},1065			Ok(ScheduledEnsureOriginSuccess::Unsigned) => {1066				// Unsigned version of the above1067				T::CallExecutor::dispatch_call(None, call.clone())1068			}1069			Err(e) => Ok(Err(e.into())),1070		};10711072		let (maybe_actual_call_weight, result) = match r {1073			Ok(result) => match result {1074				Ok(post_info) => (post_info.actual_weight, Ok(())),1075				Err(error_and_info) => (1076					error_and_info.post_info.actual_weight,1077					Err(error_and_info.error),1078				),1079			},1080			Err(_) => {1081				log::error!(1082					target: "runtime::scheduler",1083					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1084					This block might have become invalid.");1085				(None, Err(DispatchError::CannotLookup))1086			}1087		};1088		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1089		weight.check_accrue(base_weight);1090		weight.check_accrue(call_weight);1091		Ok(result)1092	}1093}
modifiedpallets/scheduler-v2/src/mock.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/mock.rs
+++ b/pallets/scheduler-v2/src/mock.rs
@@ -40,11 +40,11 @@
 use frame_support::{
 	ord_parameter_types, parameter_types,
 	traits::{
-		ConstU32, ConstU64, Contains, EitherOfDiverse, EqualPrivilegeOnly, OnFinalize, OnInitialize,
+		ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize,
 	},
 	weights::constants::RocksDbWeight,
 };
-use frame_system::{EnsureRoot, EnsureSignedBy, RawOrigin};
+use frame_system::{EnsureRoot, RawOrigin};
 use sp_core::H256;
 use sp_runtime::{
 	testing::Header,
modifiedpallets/scheduler-v2/src/tests.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/tests.rs
+++ b/pallets/scheduler-v2/src/tests.rs
@@ -40,8 +40,7 @@
 };
 use frame_support::{
 	assert_noop, assert_ok,
-	traits::{Contains, GetStorageVersion, OnInitialize},
-	Hashable,
+	traits::{Contains, OnInitialize},
 };
 
 #[test]