git.delta.rocks / unique-network / refs/commits / ccd56ff0f661

difftreelog

feat track free places inside the agenda

Daniel Shiposha2022-10-26parent: #1768418.patch.diff
in: master

1 file 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::{81		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,82	},83	traits::{84		schedule::{self, DispatchTime, LOWEST_PRIORITY},85		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,86		ConstU32, UnfilteredDispatchable,87	},88	weights::Weight,89	unsigned::TransactionValidityError,90};9192use frame_system::{self as system};93use scale_info::TypeInfo;94use sp_runtime::{95	traits::{BadOrigin, One, Saturating, Zero, Hash},96	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,97};98use sp_core::H160;99use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};100pub use weights::WeightInfo;101102pub use pallet::*;103104/// Just a simple index for naming period tasks.105pub type PeriodicIndex = u32;106/// The location of a scheduled task that can be used to remove it.107pub type TaskAddress<BlockNumber> = (BlockNumber, u32);108109pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;110111#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]112#[scale_info(skip_type_params(T))]113pub enum ScheduledCall<T: Config> {114	Inline(EncodedCall),115	PreimageLookup { hash: T::Hash, unbounded_len: u32 },116}117118impl<T: Config> ScheduledCall<T> {119	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {120		let encoded = call.encode();121		let len = encoded.len();122123		match EncodedCall::try_from(encoded.clone()) {124			Ok(bounded) => Ok(Self::Inline(bounded)),125			Err(_) => {126				let hash = <T as system::Config>::Hashing::hash_of(&encoded);127				<T as Config>::Preimages::note_preimage(128					encoded129						.try_into()130						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,131				);132133				Ok(Self::PreimageLookup {134					hash,135					unbounded_len: len as u32,136				})137			}138		}139	}140141	/// The maximum length of the lookup that is needed to peek `Self`.142	pub fn lookup_len(&self) -> Option<u32> {143		match self {144			Self::Inline(..) => None,145			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),146		}147	}148149	/// Returns whether the image will require a lookup to be peeked.150	pub fn lookup_needed(&self) -> bool {151		match self {152			Self::Inline(_) => false,153			Self::PreimageLookup { .. } => true,154		}155	}156157	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {158		<T as Config>::RuntimeCall::decode(&mut data)159			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())160	}161}162163pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {164	fn drop(call: &ScheduledCall<T>);165166	fn peek(167		call: &ScheduledCall<T>,168	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;169170	/// Convert the given scheduled `call` value back into its original instance. If successful,171	/// `drop` any data backing it. This will not break the realisability of independently172	/// created instances of `ScheduledCall` which happen to have identical data.173	fn realize(174		call: &ScheduledCall<T>,175	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;176}177178impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {179	fn drop(call: &ScheduledCall<T>) {180		match call {181			ScheduledCall::Inline(_) => {}182			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),183		}184	}185186	fn peek(187		call: &ScheduledCall<T>,188	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {189		match call {190			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),191			ScheduledCall::PreimageLookup {192				hash,193				unbounded_len,194			} => {195				let (preimage, len) = Self::get_preimage(hash)196					.ok_or(<Error<T>>::PreimageNotFound)197					.map(|preimage| (preimage, *unbounded_len))?;198199				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))200			}201		}202	}203204	fn realize(205		call: &ScheduledCall<T>,206	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {207		let r = Self::peek(call)?;208		Self::drop(call);209		Ok(r)210	}211}212213pub enum ScheduledEnsureOriginSuccess<AccountId> {214	Root,215	Signed(AccountId),216}217218pub type TaskName = [u8; 32];219220/// Information regarding an item to be executed in the future.221#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]222#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]223pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {224	/// The unique identity for this task, if there is one.225	maybe_id: Option<Name>,226227	/// This task's priority.228	priority: schedule::Priority,229230	/// The call to be dispatched.231	call: Call,232233	/// If the call is periodic, then this points to the information concerning that.234	maybe_periodic: Option<schedule::Period<BlockNumber>>,235236	/// The origin with which to dispatch the call.237	origin: PalletsOrigin,238	_phantom: PhantomData<AccountId>,239}240241pub type ScheduledOf<T> = Scheduled<242	TaskName,243	ScheduledCall<T>,244	<T as frame_system::Config>::BlockNumber,245	<T as Config>::PalletsOrigin,246	<T as frame_system::Config>::AccountId,247>;248249struct WeightCounter {250	used: Weight,251	limit: Weight,252}253254impl WeightCounter {255	fn check_accrue(&mut self, w: Weight) -> bool {256		let test = self.used.saturating_add(w);257		if test.any_gt(self.limit) {258			false259		} else {260			self.used = test;261			true262		}263	}264265	fn can_accrue(&mut self, w: Weight) -> bool {266		self.used.saturating_add(w).all_lte(self.limit)267	}268}269270pub(crate) trait MarginalWeightInfo: WeightInfo {271	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {272		let base = Self::service_task_base();273		let mut total = match maybe_lookup_len {274			None => base,275			Some(l) => Self::service_task_fetched(l as u32),276		};277		if named {278			total.saturating_accrue(Self::service_task_named().saturating_sub(base));279		}280		if periodic {281			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));282		}283		total284	}285}286287impl<T: WeightInfo> MarginalWeightInfo for T {}288289#[frame_support::pallet]290pub mod pallet {291	use super::*;292	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};293	use system::pallet_prelude::*;294295	/// The current storage version.296	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);297298	#[pallet::pallet]299	#[pallet::generate_store(pub(super) trait Store)]300	#[pallet::storage_version(STORAGE_VERSION)]301	pub struct Pallet<T>(_);302303	#[pallet::config]304	pub trait Config: frame_system::Config {305		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;306307		/// The aggregated origin which the dispatch will take.308		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>309			+ From<Self::PalletsOrigin>310			+ IsType<<Self as system::Config>::RuntimeOrigin>311			+ Clone;312313		/// The caller origin, overarching type of all pallets origins.314		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>315			+ Codec316			+ Clone317			+ Eq318			+ TypeInfo319			+ MaxEncodedLen;320321		/// The aggregated call type.322		type RuntimeCall: Parameter323			+ Dispatchable<324				RuntimeOrigin = <Self as Config>::RuntimeOrigin,325				PostInfo = PostDispatchInfo,326			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>327			+ GetDispatchInfo328			+ From<system::Call<Self>>;329330		/// The maximum weight that may be scheduled per block for any dispatchables.331		#[pallet::constant]332		type MaximumWeight: Get<Weight>;333334		/// Required origin to schedule or cancel calls.335		type ScheduleOrigin: EnsureOrigin<336			<Self as system::Config>::RuntimeOrigin,337			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,338		>;339340		/// Compare the privileges of origins.341		///342		/// This will be used when canceling a task, to ensure that the origin that tries343		/// to cancel has greater or equal privileges as the origin that created the scheduled task.344		///345		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can346		/// be used. This will only check if two given origins are equal.347		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;348349		/// The maximum number of scheduled calls in the queue for a single block.350		#[pallet::constant]351		type MaxScheduledPerBlock: Get<u32>;352353		/// Weight information for extrinsics in this pallet.354		type WeightInfo: WeightInfo;355356		/// The preimage provider with which we look up call hashes to get the call.357		type Preimages: SchedulerPreimages<Self>;358359		/// The helper type used for custom transaction fee logic.360		type CallExecutor: DispatchCall<Self, H160>;361362		/// Required origin to set/change calls' priority.363		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;364	}365366	#[pallet::storage]367	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;368369	/// Items to be executed, indexed by the block number that they should be executed on.370	#[pallet::storage]371	pub type Agenda<T: Config> = StorageMap<372		_,373		Twox64Concat,374		T::BlockNumber,375		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,376		ValueQuery,377	>;378379	/// Lookup from a name to the block number and index of the task.380	#[pallet::storage]381	pub(crate) type Lookup<T: Config> =382		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;383384	/// Events type.385	#[pallet::event]386	#[pallet::generate_deposit(pub(super) fn deposit_event)]387	pub enum Event<T: Config> {388		/// Scheduled some task.389		Scheduled { when: T::BlockNumber, index: u32 },390		/// Canceled some task.391		Canceled { when: T::BlockNumber, index: u32 },392		/// Dispatched some task.393		Dispatched {394			task: TaskAddress<T::BlockNumber>,395			id: Option<[u8; 32]>,396			result: DispatchResult,397		},398		/// Scheduled task's priority has changed399		PriorityChanged {400			when: T::BlockNumber,401			index: u32,402			priority: schedule::Priority,403		},404		/// The call for the provided hash was not found so the task has been aborted.405		CallUnavailable {406			task: TaskAddress<T::BlockNumber>,407			id: Option<[u8; 32]>,408		},409		/// The given task was unable to be renewed since the agenda is full at that block.410		PeriodicFailed {411			task: TaskAddress<T::BlockNumber>,412			id: Option<[u8; 32]>,413		},414		/// The given task can never be executed since it is overweight.415		PermanentlyOverweight {416			task: TaskAddress<T::BlockNumber>,417			id: Option<[u8; 32]>,418		},419	}420421	#[pallet::error]422	pub enum Error<T> {423		/// Failed to schedule a call424		FailedToSchedule,425		/// There is no place for a new task in the agenda426		AgendaIsExhausted,427		/// Scheduled call is corrupted428		ScheduledCallCorrupted,429		/// Scheduled call preimage is not found430		PreimageNotFound,431		/// Scheduled call is too big432		TooBigScheduledCall,433		/// Cannot find the scheduled call.434		NotFound,435		/// Given target block number is in the past.436		TargetBlockNumberInPast,437		/// Attempt to use a non-named function on a named task.438		Named,439	}440441	#[pallet::hooks]442	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {443		/// Execute the scheduled calls444		fn on_initialize(now: T::BlockNumber) -> Weight {445			let mut weight_counter = WeightCounter {446				used: Weight::zero(),447				limit: T::MaximumWeight::get(),448			};449			Self::service_agendas(&mut weight_counter, now, u32::max_value());450			weight_counter.used451		}452	}453454	#[pallet::call]455	impl<T: Config> Pallet<T> {456		/// Anonymously schedule a task.457		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]458		pub fn schedule(459			origin: OriginFor<T>,460			when: T::BlockNumber,461			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,462			priority: Option<schedule::Priority>,463			call: Box<<T as Config>::RuntimeCall>,464		) -> DispatchResult {465			T::ScheduleOrigin::ensure_origin(origin.clone())?;466467			if priority.is_some() {468				T::PrioritySetOrigin::ensure_origin(origin.clone())?;469			}470471			let origin = <T as Config>::RuntimeOrigin::from(origin);472			Self::do_schedule(473				DispatchTime::At(when),474				maybe_periodic,475				priority.unwrap_or(LOWEST_PRIORITY),476				origin.caller().clone(),477				<ScheduledCall<T>>::new(*call)?,478			)?;479			Ok(())480		}481482		/// Cancel an anonymously scheduled task.483		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]484		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {485			T::ScheduleOrigin::ensure_origin(origin.clone())?;486			let origin = <T as Config>::RuntimeOrigin::from(origin);487			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;488			Ok(())489		}490491		/// Schedule a named task.492		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]493		pub fn schedule_named(494			origin: OriginFor<T>,495			id: TaskName,496			when: T::BlockNumber,497			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,498			priority: Option<schedule::Priority>,499			call: Box<<T as Config>::RuntimeCall>,500		) -> DispatchResult {501			T::ScheduleOrigin::ensure_origin(origin.clone())?;502503			if priority.is_some() {504				T::PrioritySetOrigin::ensure_origin(origin.clone())?;505			}506507			let origin = <T as Config>::RuntimeOrigin::from(origin);508			Self::do_schedule_named(509				id,510				DispatchTime::At(when),511				maybe_periodic,512				priority.unwrap_or(LOWEST_PRIORITY),513				origin.caller().clone(),514				<ScheduledCall<T>>::new(*call)?,515			)?;516			Ok(())517		}518519		/// Cancel a named scheduled task.520		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]521		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {522			T::ScheduleOrigin::ensure_origin(origin.clone())?;523			let origin = <T as Config>::RuntimeOrigin::from(origin);524			Self::do_cancel_named(Some(origin.caller().clone()), id)?;525			Ok(())526		}527528		/// Anonymously schedule a task after a delay.529		///530		/// # <weight>531		/// Same as [`schedule`].532		/// # </weight>533		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]534		pub fn schedule_after(535			origin: OriginFor<T>,536			after: T::BlockNumber,537			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,538			priority: Option<schedule::Priority>,539			call: Box<<T as Config>::RuntimeCall>,540		) -> DispatchResult {541			T::ScheduleOrigin::ensure_origin(origin.clone())?;542543			if priority.is_some() {544				T::PrioritySetOrigin::ensure_origin(origin.clone())?;545			}546547			let origin = <T as Config>::RuntimeOrigin::from(origin);548			Self::do_schedule(549				DispatchTime::After(after),550				maybe_periodic,551				priority.unwrap_or(LOWEST_PRIORITY),552				origin.caller().clone(),553				<ScheduledCall<T>>::new(*call)?,554			)?;555			Ok(())556		}557558		/// Schedule a named task after a delay.559		///560		/// # <weight>561		/// Same as [`schedule_named`](Self::schedule_named).562		/// # </weight>563		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]564		pub fn schedule_named_after(565			origin: OriginFor<T>,566			id: TaskName,567			after: T::BlockNumber,568			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,569			priority: Option<schedule::Priority>,570			call: Box<<T as Config>::RuntimeCall>,571		) -> DispatchResult {572			T::ScheduleOrigin::ensure_origin(origin.clone())?;573574			if priority.is_some() {575				T::PrioritySetOrigin::ensure_origin(origin.clone())?;576			}577578			let origin = <T as Config>::RuntimeOrigin::from(origin);579			Self::do_schedule_named(580				id,581				DispatchTime::After(after),582				maybe_periodic,583				priority.unwrap_or(LOWEST_PRIORITY),584				origin.caller().clone(),585				<ScheduledCall<T>>::new(*call)?,586			)?;587			Ok(())588		}589590		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]591		pub fn change_named_priority(592			origin: OriginFor<T>,593			id: TaskName,594			priority: schedule::Priority,595		) -> DispatchResult {596			T::PrioritySetOrigin::ensure_origin(origin.clone())?;597			let origin = <T as Config>::RuntimeOrigin::from(origin);598			Self::do_change_named_priority(origin.caller().clone(), id, priority)599		}600	}601}602603impl<T: Config> Pallet<T> {604	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {605		let now = frame_system::Pallet::<T>::block_number();606607		let when = match when {608			DispatchTime::At(x) => x,609			// The current block has already completed it's scheduled tasks, so610			// Schedule the task at lest one block after this current block.611			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),612		};613614		if when <= now {615			return Err(Error::<T>::TargetBlockNumberInPast.into());616		}617618		Ok(when)619	}620621	fn place_task(622		when: T::BlockNumber,623		what: ScheduledOf<T>,624	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {625		let maybe_name = what.maybe_id;626		let index = Self::push_to_agenda(when, what)?;627		let address = (when, index);628		if let Some(name) = maybe_name {629			Lookup::<T>::insert(name, address)630		}631		Self::deposit_event(Event::Scheduled {632			when: address.0,633			index: address.1,634		});635		Ok(address)636	}637638	fn push_to_agenda(639		when: T::BlockNumber,640		what: ScheduledOf<T>,641	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {642		let mut agenda = Agenda::<T>::get(when);643		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {644			// will always succeed due to the above check.645			let _ = agenda.try_push(Some(what));646			agenda.len() as u32 - 1647		} else {648			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {649				agenda[hole_index] = Some(what);650				hole_index as u32651			} else {652				return Err((<Error<T>>::AgendaIsExhausted.into(), what));653			}654		};655		Agenda::<T>::insert(when, agenda);656		Ok(index)657	}658659	fn do_schedule(660		when: DispatchTime<T::BlockNumber>,661		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,662		priority: schedule::Priority,663		origin: T::PalletsOrigin,664		call: ScheduledCall<T>,665	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {666		let when = Self::resolve_time(when)?;667668		// sanitize maybe_periodic669		let maybe_periodic = maybe_periodic670			.filter(|p| p.1 > 1 && !p.0.is_zero())671			// Remove one from the number of repetitions since we will schedule one now.672			.map(|(p, c)| (p, c - 1));673		let task = Scheduled {674			maybe_id: None,675			priority,676			call,677			maybe_periodic,678			origin,679			_phantom: PhantomData,680		};681		Self::place_task(when, task).map_err(|x| x.0)682	}683684	fn do_cancel(685		origin: Option<T::PalletsOrigin>,686		(when, index): TaskAddress<T::BlockNumber>,687	) -> Result<(), DispatchError> {688		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {689			agenda.get_mut(index as usize).map_or(690				Ok(None),691				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {692					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {693						if matches!(694							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),695							Some(Ordering::Less) | None696						) {697							return Err(BadOrigin.into());698						}699					};700					Ok(s.take())701				},702			)703		})?;704		if let Some(s) = scheduled {705			T::Preimages::drop(&s.call);706707			if let Some(id) = s.maybe_id {708				Lookup::<T>::remove(id);709			}710			Self::deposit_event(Event::Canceled { when, index });711			Ok(())712		} else {713			return Err(Error::<T>::NotFound.into());714		}715	}716717	fn do_schedule_named(718		id: TaskName,719		when: DispatchTime<T::BlockNumber>,720		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,721		priority: schedule::Priority,722		origin: T::PalletsOrigin,723		call: ScheduledCall<T>,724	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {725		// ensure id it is unique726		if Lookup::<T>::contains_key(&id) {727			return Err(Error::<T>::FailedToSchedule.into());728		}729730		let when = Self::resolve_time(when)?;731732		// sanitize maybe_periodic733		let maybe_periodic = maybe_periodic734			.filter(|p| p.1 > 1 && !p.0.is_zero())735			// Remove one from the number of repetitions since we will schedule one now.736			.map(|(p, c)| (p, c - 1));737738		let task = Scheduled {739			maybe_id: Some(id),740			priority,741			call,742			maybe_periodic,743			origin,744			_phantom: Default::default(),745		};746		Self::place_task(when, task).map_err(|x| x.0)747	}748749	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {750		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {751			if let Some((when, index)) = lookup.take() {752				let i = index as usize;753				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {754					if let Some(s) = agenda.get_mut(i) {755						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {756							if matches!(757								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),758								Some(Ordering::Less) | None759							) {760								return Err(BadOrigin.into());761							}762							T::Preimages::drop(&s.call);763						}764						*s = None;765					}766					Ok(())767				})?;768				Self::deposit_event(Event::Canceled { when, index });769				Ok(())770			} else {771				return Err(Error::<T>::NotFound.into());772			}773		})774	}775776	fn do_change_named_priority(777		origin: T::PalletsOrigin,778		id: TaskName,779		priority: schedule::Priority,780	) -> DispatchResult {781		match Lookup::<T>::get(id) {782			Some((when, index)) => {783				let i = index as usize;784				Agenda::<T>::try_mutate(when, |agenda| {785					if let Some(Some(s)) = agenda.get_mut(i) {786						if matches!(787							T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),788							Some(Ordering::Less) | None789						) {790							return Err(BadOrigin.into());791						}792793						s.priority = priority;794						Self::deposit_event(Event::PriorityChanged {795							when,796							index,797							priority,798						});799					}800					Ok(())801				})802			}803			None => Err(Error::<T>::NotFound.into()),804		}805	}806}807808enum ServiceTaskError {809	/// Could not be executed due to missing preimage.810	Unavailable,811	/// Could not be executed due to weight limitations.812	Overweight,813}814use ServiceTaskError::*;815816/// A Scheduler-Runtime interface for finer payment handling.817pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {818	/// Resolve the call dispatch, including any post-dispatch operations.819	fn dispatch_call(820		signer: Option<T::AccountId>,821		function: <T as Config>::RuntimeCall,822	) -> Result<823		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,824		TransactionValidityError,825	>;826}827828impl<T: Config> Pallet<T> {829	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.830	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {831		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {832			return;833		}834835		let mut incomplete_since = now + One::one();836		let mut when = IncompleteSince::<T>::take().unwrap_or(now);837		let mut executed = 0;838839		let max_items = T::MaxScheduledPerBlock::get();840		let mut count_down = max;841		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);842		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {843			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {844				incomplete_since = incomplete_since.min(when);845			}846			when.saturating_inc();847			count_down.saturating_dec();848		}849		incomplete_since = incomplete_since.min(when);850		if incomplete_since <= now {851			IncompleteSince::<T>::put(incomplete_since);852		}853	}854855	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a856	/// later block.857	fn service_agenda(858		weight: &mut WeightCounter,859		executed: &mut u32,860		now: T::BlockNumber,861		when: T::BlockNumber,862		max: u32,863	) -> bool {864		let mut agenda = Agenda::<T>::get(when);865		let mut ordered = agenda866			.iter()867			.enumerate()868			.filter_map(|(index, maybe_item)| {869				maybe_item870					.as_ref()871					.map(|item| (index as u32, item.priority))872			})873			.collect::<Vec<_>>();874		ordered.sort_by_key(|k| k.1);875		let within_limit =876			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));877		debug_assert!(878			within_limit,879			"weight limit should have been checked in advance"880		);881882		// Items which we know can be executed and have postponed for execution in a later block.883		let mut postponed = (ordered.len() as u32).saturating_sub(max);884		// Items which we don't know can ever be executed.885		let mut dropped = 0;886887		for (agenda_index, _) in ordered.into_iter().take(max as usize) {888			let task = match agenda[agenda_index as usize].take() {889				None => continue,890				Some(t) => t,891			};892			let base_weight = T::WeightInfo::service_task(893				task.call.lookup_len().map(|x| x as usize),894				task.maybe_id.is_some(),895				task.maybe_periodic.is_some(),896			);897			if !weight.can_accrue(base_weight) {898				postponed += 1;899				break;900			}901			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);902			agenda[agenda_index as usize] = match result {903				Err((Unavailable, slot)) => {904					dropped += 1;905					slot906				}907				Err((Overweight, slot)) => {908					postponed += 1;909					slot910				}911				Ok(()) => {912					*executed += 1;913					None914				}915			};916		}917		if postponed > 0 || dropped > 0 {918			Agenda::<T>::insert(when, agenda);919		} else {920			Agenda::<T>::remove(when);921		}922		postponed == 0923	}924925	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.926	///927	/// This involves:928	/// - removing and potentially replacing the `Lookup` entry for the task.929	/// - realizing the task's call which can include a preimage lookup.930	/// - Rescheduling the task for execution in a later agenda if periodic.931	fn service_task(932		weight: &mut WeightCounter,933		now: T::BlockNumber,934		when: T::BlockNumber,935		agenda_index: u32,936		is_first: bool,937		mut task: ScheduledOf<T>,938	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {939		let (call, lookup_len) = match T::Preimages::peek(&task.call) {940			Ok(c) => c,941			Err(_) => {942				if let Some(ref id) = task.maybe_id {943					Lookup::<T>::remove(id);944				}945946				return Err((Unavailable, Some(task)));947			}948		};949950		weight.check_accrue(T::WeightInfo::service_task(951			lookup_len.map(|x| x as usize),952			task.maybe_id.is_some(),953			task.maybe_periodic.is_some(),954		));955956		match Self::execute_dispatch(weight, task.origin.clone(), call) {957			Err(Unavailable) => {958				debug_assert!(false, "Checked to exist with `peek`");959960				if let Some(ref id) = task.maybe_id {961					Lookup::<T>::remove(id);962				}963964				Self::deposit_event(Event::CallUnavailable {965					task: (when, agenda_index),966					id: task.maybe_id,967				});968				Err((Unavailable, Some(task)))969			}970			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {971				T::Preimages::drop(&task.call);972973				if let Some(ref id) = task.maybe_id {974					Lookup::<T>::remove(id);975				}976977				Self::deposit_event(Event::PermanentlyOverweight {978					task: (when, agenda_index),979					id: task.maybe_id,980				});981				Err((Unavailable, Some(task)))982			}983			Err(Overweight) => {984				// Preserve Lookup -- the task will be postponed.985				Err((Overweight, Some(task)))986			}987			Ok(result) => {988				Self::deposit_event(Event::Dispatched {989					task: (when, agenda_index),990					id: task.maybe_id,991					result,992				});993994				let is_canceled = task995					.maybe_id996					.as_ref()997					.map(|id| !Lookup::<T>::contains_key(id))998					.unwrap_or(false);9991000				match &task.maybe_periodic {1001					&Some((period, count)) if !is_canceled => {1002						if count > 1 {1003							task.maybe_periodic = Some((period, count - 1));1004						} else {1005							task.maybe_periodic = None;1006						}1007						let wake = now.saturating_add(period);1008						match Self::place_task(wake, task) {1009							Ok(_) => {}1010							Err((_, task)) => {1011								// TODO: Leave task in storage somewhere for it to be rescheduled1012								// manually.1013								T::Preimages::drop(&task.call);1014								Self::deposit_event(Event::PeriodicFailed {1015									task: (when, agenda_index),1016									id: task.maybe_id,1017								});1018							}1019						}1020					}1021					_ => {1022						if let Some(ref id) = task.maybe_id {1023							Lookup::<T>::remove(id);1024						}10251026						T::Preimages::drop(&task.call)1027					}1028				}1029				Ok(())1030			}1031		}1032	}10331034	fn is_runtime_upgraded() -> bool {1035		let last = system::LastRuntimeUpgrade::<T>::get();1036		let current = T::Version::get();10371038		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)1039	}10401041	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1042	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1043	/// post info if available).1044	///1045	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1046	/// call itself).1047	fn execute_dispatch(1048		weight: &mut WeightCounter,1049		origin: T::PalletsOrigin,1050		call: <T as Config>::RuntimeCall,1051	) -> Result<DispatchResult, ServiceTaskError> {1052		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1053		let base_weight = match dispatch_origin.clone().as_signed() {1054			Some(_) => T::WeightInfo::execute_dispatch_signed(),1055			_ => T::WeightInfo::execute_dispatch_unsigned(),1056		};1057		let call_weight = call.get_dispatch_info().weight;1058		// We only allow a scheduled call if it cannot push the weight past the limit.1059		let max_weight = base_weight.saturating_add(call_weight);10601061		if !weight.can_accrue(max_weight) {1062			return Err(Overweight);1063		}10641065		// let scheduled_origin =1066		// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());1067		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());10681069		let r = match ensured_origin {1070			Ok(ScheduledEnsureOriginSuccess::Root) => {1071				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1072			}1073			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1074				// Execute transaction via chain default pipeline1075				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1076				T::CallExecutor::dispatch_call(Some(sender), call.clone())1077			}1078			Err(e) => Ok(Err(e.into())),1079		};10801081		let (maybe_actual_call_weight, result) = match r {1082			Ok(result) => match result {1083				Ok(post_info) => (post_info.actual_weight, Ok(())),1084				Err(error_and_info) => (1085					error_and_info.post_info.actual_weight,1086					Err(error_and_info.error),1087				),1088			},1089			Err(_) => {1090				log::error!(1091					target: "runtime::scheduler",1092					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1093					This block might have become invalid.");1094				(None, Err(DispatchError::CannotLookup))1095			}1096		};1097		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1098		weight.check_accrue(base_weight);1099		weight.check_accrue(call_weight);1100		Ok(result)1101	}1102}
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::{81		DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,82	},83	traits::{84		schedule::{self, DispatchTime, LOWEST_PRIORITY},85		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,86		ConstU32, UnfilteredDispatchable,87	},88	weights::Weight,89	unsigned::TransactionValidityError,90};9192use frame_system::{self as system};93use scale_info::TypeInfo;94use sp_runtime::{95	traits::{BadOrigin, One, Saturating, Zero, Hash},96	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,97};98use sp_core::H160;99use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};100pub use weights::WeightInfo;101102pub use pallet::*;103104/// Just a simple index for naming period tasks.105pub type PeriodicIndex = u32;106/// The location of a scheduled task that can be used to remove it.107pub type TaskAddress<BlockNumber> = (BlockNumber, u32);108109pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;110111#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]112#[scale_info(skip_type_params(T))]113pub enum ScheduledCall<T: Config> {114	Inline(EncodedCall),115	PreimageLookup { hash: T::Hash, unbounded_len: u32 },116}117118impl<T: Config> ScheduledCall<T> {119	pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {120		let encoded = call.encode();121		let len = encoded.len();122123		match EncodedCall::try_from(encoded.clone()) {124			Ok(bounded) => Ok(Self::Inline(bounded)),125			Err(_) => {126				let hash = <T as system::Config>::Hashing::hash_of(&encoded);127				<T as Config>::Preimages::note_preimage(128					encoded129						.try_into()130						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,131				);132133				Ok(Self::PreimageLookup {134					hash,135					unbounded_len: len as u32,136				})137			}138		}139	}140141	/// The maximum length of the lookup that is needed to peek `Self`.142	pub fn lookup_len(&self) -> Option<u32> {143		match self {144			Self::Inline(..) => None,145			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),146		}147	}148149	/// Returns whether the image will require a lookup to be peeked.150	pub fn lookup_needed(&self) -> bool {151		match self {152			Self::Inline(_) => false,153			Self::PreimageLookup { .. } => true,154		}155	}156157	fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {158		<T as Config>::RuntimeCall::decode(&mut data)159			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())160	}161}162163pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {164	fn drop(call: &ScheduledCall<T>);165166	fn peek(167		call: &ScheduledCall<T>,168	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;169170	/// Convert the given scheduled `call` value back into its original instance. If successful,171	/// `drop` any data backing it. This will not break the realisability of independently172	/// created instances of `ScheduledCall` which happen to have identical data.173	fn realize(174		call: &ScheduledCall<T>,175	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;176}177178impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {179	fn drop(call: &ScheduledCall<T>) {180		match call {181			ScheduledCall::Inline(_) => {}182			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),183		}184	}185186	fn peek(187		call: &ScheduledCall<T>,188	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {189		match call {190			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),191			ScheduledCall::PreimageLookup {192				hash,193				unbounded_len,194			} => {195				let (preimage, len) = Self::get_preimage(hash)196					.ok_or(<Error<T>>::PreimageNotFound)197					.map(|preimage| (preimage, *unbounded_len))?;198199				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))200			}201		}202	}203204	fn realize(205		call: &ScheduledCall<T>,206	) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {207		let r = Self::peek(call)?;208		Self::drop(call);209		Ok(r)210	}211}212213pub enum ScheduledEnsureOriginSuccess<AccountId> {214	Root,215	Signed(AccountId),216}217218pub type TaskName = [u8; 32];219220/// Information regarding an item to be executed in the future.221#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]222#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]223pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {224	/// The unique identity for this task, if there is one.225	maybe_id: Option<Name>,226227	/// This task's priority.228	priority: schedule::Priority,229230	/// The call to be dispatched.231	call: Call,232233	/// If the call is periodic, then this points to the information concerning that.234	maybe_periodic: Option<schedule::Period<BlockNumber>>,235236	/// The origin with which to dispatch the call.237	origin: PalletsOrigin,238	_phantom: PhantomData<AccountId>,239}240241pub type ScheduledOf<T> = Scheduled<242	TaskName,243	ScheduledCall<T>,244	<T as frame_system::Config>::BlockNumber,245	<T as Config>::PalletsOrigin,246	<T as frame_system::Config>::AccountId,247>;248249#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]250#[scale_info(skip_type_params(T))]251pub struct BlockAgenda<T: Config> {252	agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,253	free_places: u32,254}255256impl<T: Config> BlockAgenda<T> {257	fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Option<u32> {258		if self.free_places == 0 {259			return None;260		}261262		self.free_places = self.free_places.saturating_sub(1);263264		if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {265			// will always succeed due to the above check.266			let _ = self.agenda.try_push(Some(scheduled));267			Some((self.agenda.len() - 1) as u32)268		} else {269			match self.agenda.iter().position(|i| i.is_none()) {270				Some(hole_index) => {271					self.agenda[hole_index] = Some(scheduled);272					Some(hole_index as u32)273				}274				None => unreachable!("free_places > 0; qed"),275			}276		}277	}278279	fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {280		self.agenda[index as usize] = slot;281	}282283	fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {284		self.agenda.iter()285	}286287	fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {288		match self.agenda.get(index as usize) {289			Some(Some(scheduled)) => Some(scheduled),290			_ => None,291		}292	}293294	fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {295		match self.agenda.get_mut(index as usize) {296			Some(Some(scheduled)) => Some(scheduled),297			_ => None,298		}299	}300301	fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {302		let removed = self.agenda.get_mut(index as usize)?.take();303304		if removed.is_some() {305			self.free_places = self.free_places.saturating_add(1);306		}307308		removed309	}310}311312impl<T: Config> Default for BlockAgenda<T> {313	fn default() -> Self {314		let agenda = Default::default();315		let free_places = T::MaxScheduledPerBlock::get();316317		Self {318			agenda,319			free_places,320		}321	}322}323324struct WeightCounter {325	used: Weight,326	limit: Weight,327}328329impl WeightCounter {330	fn check_accrue(&mut self, w: Weight) -> bool {331		let test = self.used.saturating_add(w);332		if test.any_gt(self.limit) {333			false334		} else {335			self.used = test;336			true337		}338	}339340	fn can_accrue(&mut self, w: Weight) -> bool {341		self.used.saturating_add(w).all_lte(self.limit)342	}343}344345pub(crate) trait MarginalWeightInfo: WeightInfo {346	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {347		let base = Self::service_task_base();348		let mut total = match maybe_lookup_len {349			None => base,350			Some(l) => Self::service_task_fetched(l as u32),351		};352		if named {353			total.saturating_accrue(Self::service_task_named().saturating_sub(base));354		}355		if periodic {356			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));357		}358		total359	}360}361362impl<T: WeightInfo> MarginalWeightInfo for T {}363364#[frame_support::pallet]365pub mod pallet {366	use super::*;367	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};368	use system::pallet_prelude::*;369370	/// The current storage version.371	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);372373	#[pallet::pallet]374	#[pallet::generate_store(pub(super) trait Store)]375	#[pallet::storage_version(STORAGE_VERSION)]376	pub struct Pallet<T>(_);377378	#[pallet::config]379	pub trait Config: frame_system::Config {380		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;381382		/// The aggregated origin which the dispatch will take.383		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>384			+ From<Self::PalletsOrigin>385			+ IsType<<Self as system::Config>::RuntimeOrigin>386			+ Clone;387388		/// The caller origin, overarching type of all pallets origins.389		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>390			+ Codec391			+ Clone392			+ Eq393			+ TypeInfo394			+ MaxEncodedLen;395396		/// The aggregated call type.397		type RuntimeCall: Parameter398			+ Dispatchable<399				RuntimeOrigin = <Self as Config>::RuntimeOrigin,400				PostInfo = PostDispatchInfo,401			> + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>402			+ GetDispatchInfo403			+ From<system::Call<Self>>;404405		/// The maximum weight that may be scheduled per block for any dispatchables.406		#[pallet::constant]407		type MaximumWeight: Get<Weight>;408409		/// Required origin to schedule or cancel calls.410		type ScheduleOrigin: EnsureOrigin<411			<Self as system::Config>::RuntimeOrigin,412			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,413		>;414415		/// Compare the privileges of origins.416		///417		/// This will be used when canceling a task, to ensure that the origin that tries418		/// to cancel has greater or equal privileges as the origin that created the scheduled task.419		///420		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can421		/// be used. This will only check if two given origins are equal.422		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;423424		/// The maximum number of scheduled calls in the queue for a single block.425		#[pallet::constant]426		type MaxScheduledPerBlock: Get<u32>;427428		/// Weight information for extrinsics in this pallet.429		type WeightInfo: WeightInfo;430431		/// The preimage provider with which we look up call hashes to get the call.432		type Preimages: SchedulerPreimages<Self>;433434		/// The helper type used for custom transaction fee logic.435		type CallExecutor: DispatchCall<Self, H160>;436437		/// Required origin to set/change calls' priority.438		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;439	}440441	#[pallet::storage]442	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;443444	/// Items to be executed, indexed by the block number that they should be executed on.445	#[pallet::storage]446	pub type Agenda<T: Config> =447		StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;448449	/// Lookup from a name to the block number and index of the task.450	#[pallet::storage]451	pub(crate) type Lookup<T: Config> =452		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;453454	/// Events type.455	#[pallet::event]456	#[pallet::generate_deposit(pub(super) fn deposit_event)]457	pub enum Event<T: Config> {458		/// Scheduled some task.459		Scheduled { when: T::BlockNumber, index: u32 },460		/// Canceled some task.461		Canceled { when: T::BlockNumber, index: u32 },462		/// Dispatched some task.463		Dispatched {464			task: TaskAddress<T::BlockNumber>,465			id: Option<[u8; 32]>,466			result: DispatchResult,467		},468		/// Scheduled task's priority has changed469		PriorityChanged {470			when: T::BlockNumber,471			index: u32,472			priority: schedule::Priority,473		},474		/// The call for the provided hash was not found so the task has been aborted.475		CallUnavailable {476			task: TaskAddress<T::BlockNumber>,477			id: Option<[u8; 32]>,478		},479		/// The given task was unable to be renewed since the agenda is full at that block.480		PeriodicFailed {481			task: TaskAddress<T::BlockNumber>,482			id: Option<[u8; 32]>,483		},484		/// The given task can never be executed since it is overweight.485		PermanentlyOverweight {486			task: TaskAddress<T::BlockNumber>,487			id: Option<[u8; 32]>,488		},489	}490491	#[pallet::error]492	pub enum Error<T> {493		/// Failed to schedule a call494		FailedToSchedule,495		/// There is no place for a new task in the agenda496		AgendaIsExhausted,497		/// Scheduled call is corrupted498		ScheduledCallCorrupted,499		/// Scheduled call preimage is not found500		PreimageNotFound,501		/// Scheduled call is too big502		TooBigScheduledCall,503		/// Cannot find the scheduled call.504		NotFound,505		/// Given target block number is in the past.506		TargetBlockNumberInPast,507		/// Attempt to use a non-named function on a named task.508		Named,509	}510511	#[pallet::hooks]512	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {513		/// Execute the scheduled calls514		fn on_initialize(now: T::BlockNumber) -> Weight {515			let mut weight_counter = WeightCounter {516				used: Weight::zero(),517				limit: T::MaximumWeight::get(),518			};519			Self::service_agendas(&mut weight_counter, now, u32::max_value());520			weight_counter.used521		}522	}523524	#[pallet::call]525	impl<T: Config> Pallet<T> {526		/// Anonymously schedule a task.527		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]528		pub fn schedule(529			origin: OriginFor<T>,530			when: T::BlockNumber,531			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,532			priority: Option<schedule::Priority>,533			call: Box<<T as Config>::RuntimeCall>,534		) -> DispatchResult {535			T::ScheduleOrigin::ensure_origin(origin.clone())?;536537			if priority.is_some() {538				T::PrioritySetOrigin::ensure_origin(origin.clone())?;539			}540541			let origin = <T as Config>::RuntimeOrigin::from(origin);542			Self::do_schedule(543				DispatchTime::At(when),544				maybe_periodic,545				priority.unwrap_or(LOWEST_PRIORITY),546				origin.caller().clone(),547				<ScheduledCall<T>>::new(*call)?,548			)?;549			Ok(())550		}551552		/// Cancel an anonymously scheduled task.553		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]554		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {555			T::ScheduleOrigin::ensure_origin(origin.clone())?;556			let origin = <T as Config>::RuntimeOrigin::from(origin);557			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;558			Ok(())559		}560561		/// Schedule a named task.562		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]563		pub fn schedule_named(564			origin: OriginFor<T>,565			id: TaskName,566			when: T::BlockNumber,567			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,568			priority: Option<schedule::Priority>,569			call: Box<<T as Config>::RuntimeCall>,570		) -> DispatchResult {571			T::ScheduleOrigin::ensure_origin(origin.clone())?;572573			if priority.is_some() {574				T::PrioritySetOrigin::ensure_origin(origin.clone())?;575			}576577			let origin = <T as Config>::RuntimeOrigin::from(origin);578			Self::do_schedule_named(579				id,580				DispatchTime::At(when),581				maybe_periodic,582				priority.unwrap_or(LOWEST_PRIORITY),583				origin.caller().clone(),584				<ScheduledCall<T>>::new(*call)?,585			)?;586			Ok(())587		}588589		/// Cancel a named scheduled task.590		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]591		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {592			T::ScheduleOrigin::ensure_origin(origin.clone())?;593			let origin = <T as Config>::RuntimeOrigin::from(origin);594			Self::do_cancel_named(Some(origin.caller().clone()), id)?;595			Ok(())596		}597598		/// Anonymously schedule a task after a delay.599		///600		/// # <weight>601		/// Same as [`schedule`].602		/// # </weight>603		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]604		pub fn schedule_after(605			origin: OriginFor<T>,606			after: T::BlockNumber,607			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,608			priority: Option<schedule::Priority>,609			call: Box<<T as Config>::RuntimeCall>,610		) -> DispatchResult {611			T::ScheduleOrigin::ensure_origin(origin.clone())?;612613			if priority.is_some() {614				T::PrioritySetOrigin::ensure_origin(origin.clone())?;615			}616617			let origin = <T as Config>::RuntimeOrigin::from(origin);618			Self::do_schedule(619				DispatchTime::After(after),620				maybe_periodic,621				priority.unwrap_or(LOWEST_PRIORITY),622				origin.caller().clone(),623				<ScheduledCall<T>>::new(*call)?,624			)?;625			Ok(())626		}627628		/// Schedule a named task after a delay.629		///630		/// # <weight>631		/// Same as [`schedule_named`](Self::schedule_named).632		/// # </weight>633		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]634		pub fn schedule_named_after(635			origin: OriginFor<T>,636			id: TaskName,637			after: T::BlockNumber,638			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,639			priority: Option<schedule::Priority>,640			call: Box<<T as Config>::RuntimeCall>,641		) -> DispatchResult {642			T::ScheduleOrigin::ensure_origin(origin.clone())?;643644			if priority.is_some() {645				T::PrioritySetOrigin::ensure_origin(origin.clone())?;646			}647648			let origin = <T as Config>::RuntimeOrigin::from(origin);649			Self::do_schedule_named(650				id,651				DispatchTime::After(after),652				maybe_periodic,653				priority.unwrap_or(LOWEST_PRIORITY),654				origin.caller().clone(),655				<ScheduledCall<T>>::new(*call)?,656			)?;657			Ok(())658		}659660		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]661		pub fn change_named_priority(662			origin: OriginFor<T>,663			id: TaskName,664			priority: schedule::Priority,665		) -> DispatchResult {666			T::PrioritySetOrigin::ensure_origin(origin.clone())?;667			let origin = <T as Config>::RuntimeOrigin::from(origin);668			Self::do_change_named_priority(origin.caller().clone(), id, priority)669		}670	}671}672673impl<T: Config> Pallet<T> {674	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {675		let now = frame_system::Pallet::<T>::block_number();676677		let when = match when {678			DispatchTime::At(x) => x,679			// The current block has already completed it's scheduled tasks, so680			// Schedule the task at lest one block after this current block.681			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),682		};683684		if when <= now {685			return Err(Error::<T>::TargetBlockNumberInPast.into());686		}687688		Ok(when)689	}690691	fn place_task(692		when: T::BlockNumber,693		what: ScheduledOf<T>,694	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {695		let maybe_name = what.maybe_id;696		let index = Self::push_to_agenda(when, what)?;697		let address = (when, index);698		if let Some(name) = maybe_name {699			Lookup::<T>::insert(name, address)700		}701		Self::deposit_event(Event::Scheduled {702			when: address.0,703			index: address.1,704		});705		Ok(address)706	}707708	fn push_to_agenda(709		when: T::BlockNumber,710		what: ScheduledOf<T>,711	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {712		let mut agenda = Agenda::<T>::get(when);713		let index = agenda714			.try_push(what.clone())715			.ok_or((<Error<T>>::AgendaIsExhausted.into(), what))?;716717		Agenda::<T>::insert(when, agenda);718		Ok(index)719	}720721	fn do_schedule(722		when: DispatchTime<T::BlockNumber>,723		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,724		priority: schedule::Priority,725		origin: T::PalletsOrigin,726		call: ScheduledCall<T>,727	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {728		let when = Self::resolve_time(when)?;729730		// sanitize maybe_periodic731		let maybe_periodic = maybe_periodic732			.filter(|p| p.1 > 1 && !p.0.is_zero())733			// Remove one from the number of repetitions since we will schedule one now.734			.map(|(p, c)| (p, c - 1));735		let task = Scheduled {736			maybe_id: None,737			priority,738			call,739			maybe_periodic,740			origin,741			_phantom: PhantomData,742		};743		Self::place_task(when, task).map_err(|x| x.0)744	}745746	fn do_cancel(747		origin: Option<T::PalletsOrigin>,748		(when, index): TaskAddress<T::BlockNumber>,749	) -> Result<(), DispatchError> {750		let scheduled = Agenda::<T>::try_mutate(751			when,752			|agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {753				let scheduled = match agenda.get(index) {754					Some(scheduled) => scheduled,755					None => return Ok(None),756				};757758				if let Some(ref o) = origin {759					if matches!(760						T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),761						Some(Ordering::Less) | None762					) {763						return Err(BadOrigin.into());764					}765				}766767				Ok(agenda.take(index))768			},769		)?;770		if let Some(s) = scheduled {771			T::Preimages::drop(&s.call);772773			if let Some(id) = s.maybe_id {774				Lookup::<T>::remove(id);775			}776			Self::deposit_event(Event::Canceled { when, index });777			Ok(())778		} else {779			return Err(Error::<T>::NotFound.into());780		}781	}782783	fn do_schedule_named(784		id: TaskName,785		when: DispatchTime<T::BlockNumber>,786		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,787		priority: schedule::Priority,788		origin: T::PalletsOrigin,789		call: ScheduledCall<T>,790	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {791		// ensure id it is unique792		if Lookup::<T>::contains_key(&id) {793			return Err(Error::<T>::FailedToSchedule.into());794		}795796		let when = Self::resolve_time(when)?;797798		// sanitize maybe_periodic799		let maybe_periodic = maybe_periodic800			.filter(|p| p.1 > 1 && !p.0.is_zero())801			// Remove one from the number of repetitions since we will schedule one now.802			.map(|(p, c)| (p, c - 1));803804		let task = Scheduled {805			maybe_id: Some(id),806			priority,807			call,808			maybe_periodic,809			origin,810			_phantom: Default::default(),811		};812		Self::place_task(when, task).map_err(|x| x.0)813	}814815	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {816		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {817			if let Some((when, index)) = lookup.take() {818				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {819					let scheduled = match agenda.get(index) {820						Some(scheduled) => scheduled,821						None => return Ok(()),822					};823824					if let Some(ref o) = origin {825						if matches!(826							T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),827							Some(Ordering::Less) | None828						) {829							return Err(BadOrigin.into());830						}831						T::Preimages::drop(&scheduled.call);832					}833834					agenda.take(index);835836					Ok(())837				})?;838				Self::deposit_event(Event::Canceled { when, index });839				Ok(())840			} else {841				return Err(Error::<T>::NotFound.into());842			}843		})844	}845846	fn do_change_named_priority(847		origin: T::PalletsOrigin,848		id: TaskName,849		priority: schedule::Priority,850	) -> DispatchResult {851		match Lookup::<T>::get(id) {852			Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {853				let scheduled = match agenda.get_mut(index) {854					Some(scheduled) => scheduled,855					None => return Ok(()),856				};857858				if matches!(859					T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),860					Some(Ordering::Less) | None861				) {862					return Err(BadOrigin.into());863				}864865				scheduled.priority = priority;866				Self::deposit_event(Event::PriorityChanged {867					when,868					index,869					priority,870				});871872				Ok(())873			}),874			None => Err(Error::<T>::NotFound.into()),875		}876	}877}878879enum ServiceTaskError {880	/// Could not be executed due to missing preimage.881	Unavailable,882	/// Could not be executed due to weight limitations.883	Overweight,884}885use ServiceTaskError::*;886887/// A Scheduler-Runtime interface for finer payment handling.888pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {889	/// Resolve the call dispatch, including any post-dispatch operations.890	fn dispatch_call(891		signer: Option<T::AccountId>,892		function: <T as Config>::RuntimeCall,893	) -> Result<894		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,895		TransactionValidityError,896	>;897}898899impl<T: Config> Pallet<T> {900	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.901	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {902		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {903			return;904		}905906		let mut incomplete_since = now + One::one();907		let mut when = IncompleteSince::<T>::take().unwrap_or(now);908		let mut executed = 0;909910		let max_items = T::MaxScheduledPerBlock::get();911		let mut count_down = max;912		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);913		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {914			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {915				incomplete_since = incomplete_since.min(when);916			}917			when.saturating_inc();918			count_down.saturating_dec();919		}920		incomplete_since = incomplete_since.min(when);921		if incomplete_since <= now {922			IncompleteSince::<T>::put(incomplete_since);923		}924	}925926	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a927	/// later block.928	fn service_agenda(929		weight: &mut WeightCounter,930		executed: &mut u32,931		now: T::BlockNumber,932		when: T::BlockNumber,933		max: u32,934	) -> bool {935		let mut agenda = Agenda::<T>::get(when);936		let mut ordered = agenda937			.iter()938			.enumerate()939			.filter_map(|(index, maybe_item)| {940				maybe_item941					.as_ref()942					.map(|item| (index as u32, item.priority))943			})944			.collect::<Vec<_>>();945		ordered.sort_by_key(|k| k.1);946		let within_limit =947			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));948		debug_assert!(949			within_limit,950			"weight limit should have been checked in advance"951		);952953		// Items which we know can be executed and have postponed for execution in a later block.954		let mut postponed = (ordered.len() as u32).saturating_sub(max);955		// Items which we don't know can ever be executed.956		let mut dropped = 0;957958		for (agenda_index, _) in ordered.into_iter().take(max as usize) {959			let task = match agenda.take(agenda_index).take() {960				None => continue,961				Some(t) => t,962			};963			let base_weight = T::WeightInfo::service_task(964				task.call.lookup_len().map(|x| x as usize),965				task.maybe_id.is_some(),966				task.maybe_periodic.is_some(),967			);968			if !weight.can_accrue(base_weight) {969				postponed += 1;970				break;971			}972			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);973			match result {974				Err((Unavailable, slot)) => {975					dropped += 1;976					agenda.set_slot(agenda_index, slot);977				}978				Err((Overweight, slot)) => {979					postponed += 1;980					agenda.set_slot(agenda_index, slot);981				}982				Ok(()) => {983					*executed += 1;984				}985			};986		}987		if postponed > 0 || dropped > 0 {988			Agenda::<T>::insert(when, agenda);989		} else {990			Agenda::<T>::remove(when);991		}992		postponed == 0993	}994995	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.996	///997	/// This involves:998	/// - removing and potentially replacing the `Lookup` entry for the task.999	/// - realizing the task's call which can include a preimage lookup.1000	/// - Rescheduling the task for execution in a later agenda if periodic.1001	fn service_task(1002		weight: &mut WeightCounter,1003		now: T::BlockNumber,1004		when: T::BlockNumber,1005		agenda_index: u32,1006		is_first: bool,1007		mut task: ScheduledOf<T>,1008	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1009		let (call, lookup_len) = match T::Preimages::peek(&task.call) {1010			Ok(c) => c,1011			Err(_) => {1012				if let Some(ref id) = task.maybe_id {1013					Lookup::<T>::remove(id);1014				}10151016				return Err((Unavailable, Some(task)));1017			}1018		};10191020		weight.check_accrue(T::WeightInfo::service_task(1021			lookup_len.map(|x| x as usize),1022			task.maybe_id.is_some(),1023			task.maybe_periodic.is_some(),1024		));10251026		match Self::execute_dispatch(weight, task.origin.clone(), call) {1027			Err(Unavailable) => {1028				debug_assert!(false, "Checked to exist with `peek`");10291030				if let Some(ref id) = task.maybe_id {1031					Lookup::<T>::remove(id);1032				}10331034				Self::deposit_event(Event::CallUnavailable {1035					task: (when, agenda_index),1036					id: task.maybe_id,1037				});1038				Err((Unavailable, Some(task)))1039			}1040			Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1041				T::Preimages::drop(&task.call);10421043				if let Some(ref id) = task.maybe_id {1044					Lookup::<T>::remove(id);1045				}10461047				Self::deposit_event(Event::PermanentlyOverweight {1048					task: (when, agenda_index),1049					id: task.maybe_id,1050				});1051				Err((Unavailable, Some(task)))1052			}1053			Err(Overweight) => {1054				// Preserve Lookup -- the task will be postponed.1055				Err((Overweight, Some(task)))1056			}1057			Ok(result) => {1058				Self::deposit_event(Event::Dispatched {1059					task: (when, agenda_index),1060					id: task.maybe_id,1061					result,1062				});10631064				let is_canceled = task1065					.maybe_id1066					.as_ref()1067					.map(|id| !Lookup::<T>::contains_key(id))1068					.unwrap_or(false);10691070				match &task.maybe_periodic {1071					&Some((period, count)) if !is_canceled => {1072						if count > 1 {1073							task.maybe_periodic = Some((period, count - 1));1074						} else {1075							task.maybe_periodic = None;1076						}1077						let wake = now.saturating_add(period);1078						match Self::place_task(wake, task) {1079							Ok(_) => {}1080							Err((_, task)) => {1081								// TODO: Leave task in storage somewhere for it to be rescheduled1082								// manually.1083								T::Preimages::drop(&task.call);1084								Self::deposit_event(Event::PeriodicFailed {1085									task: (when, agenda_index),1086									id: task.maybe_id,1087								});1088							}1089						}1090					}1091					_ => {1092						if let Some(ref id) = task.maybe_id {1093							Lookup::<T>::remove(id);1094						}10951096						T::Preimages::drop(&task.call)1097					}1098				}1099				Ok(())1100			}1101		}1102	}11031104	fn is_runtime_upgraded() -> bool {1105		let last = system::LastRuntimeUpgrade::<T>::get();1106		let current = T::Version::get();11071108		last.map(|v| v.was_upgraded(&current)).unwrap_or(true)1109	}11101111	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1112	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1113	/// post info if available).1114	///1115	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1116	/// call itself).1117	fn execute_dispatch(1118		weight: &mut WeightCounter,1119		origin: T::PalletsOrigin,1120		call: <T as Config>::RuntimeCall,1121	) -> Result<DispatchResult, ServiceTaskError> {1122		let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1123		let base_weight = match dispatch_origin.clone().as_signed() {1124			Some(_) => T::WeightInfo::execute_dispatch_signed(),1125			_ => T::WeightInfo::execute_dispatch_unsigned(),1126		};1127		let call_weight = call.get_dispatch_info().weight;1128		// We only allow a scheduled call if it cannot push the weight past the limit.1129		let max_weight = base_weight.saturating_add(call_weight);11301131		if !weight.can_accrue(max_weight) {1132			return Err(Overweight);1133		}11341135		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());11361137		let r = match ensured_origin {1138			Ok(ScheduledEnsureOriginSuccess::Root) => {1139				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1140			}1141			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1142				// Execute transaction via chain default pipeline1143				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1144				T::CallExecutor::dispatch_call(Some(sender), call.clone())1145			}1146			Err(e) => Ok(Err(e.into())),1147		};11481149		let (maybe_actual_call_weight, result) = match r {1150			Ok(result) => match result {1151				Ok(post_info) => (post_info.actual_weight, Ok(())),1152				Err(error_and_info) => (1153					error_and_info.post_info.actual_weight,1154					Err(error_and_info.error),1155				),1156			},1157			Err(_) => {1158				log::error!(1159					target: "runtime::scheduler",1160					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1161					This block might have become invalid.");1162				(None, Err(DispatchError::CannotLookup))1163			}1164		};1165		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1166		weight.check_accrue(base_weight);1167		weight.check_accrue(call_weight);1168		Ok(result)1169	}1170}