referrerpolicy=no-referrer-when-downgrade

pallet_scheduler/
lib.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! > Made with *Substrate*, for *Polkadot*.
19//!
20//! [![github]](https://github.com/paritytech/polkadot-sdk/tree/master/substrate/frame/scheduler) -
21//! [![polkadot]](https://polkadot.com)
22//!
23//! [polkadot]: https://img.shields.io/badge/polkadot-E6007A?style=for-the-badge&logo=polkadot&logoColor=white
24//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
25//!
26//! # Scheduler Pallet
27//!
28//! A Pallet for scheduling runtime calls.
29//!
30//! ## Overview
31//!
32//! This Pallet exposes capabilities for scheduling runtime calls to occur at a specified block
33//! number or at a specified period. These scheduled runtime calls may be named or anonymous and may
34//! be canceled.
35//!
36//! __NOTE:__ Instead of using the filter contained in the origin to call `fn schedule`, scheduled
37//! runtime calls will be dispatched with the default filter for the origin: namely
38//! `frame_system::Config::BaseCallFilter` for all origin types (except root which will get no
39//! filter).
40//!
41//! If a call is scheduled using proxy or whatever mechanism which adds filter, then those filter
42//! will not be used when dispatching the schedule runtime call.
43//!
44//! ### Examples
45//!
46//! 1. Scheduling a runtime call at a specific block.
47#![doc = docify::embed!("src/tests.rs", basic_scheduling_works)]
48//! 2. Scheduling a preimage hash of a runtime call at a specific block
49#![doc = docify::embed!("src/tests.rs", scheduling_with_preimages_works)]
50
51//! ## Pallet API
52//!
53//! See the [`pallet`] module for more information about the interfaces this pallet exposes,
54//! including its configuration trait, dispatchables, storage items, events and errors.
55//!
56//! ## Warning
57//!
58//! This Pallet executes all scheduled runtime calls in the [`on_initialize`] hook. Do not execute
59//! any runtime calls which should not be considered mandatory.
60//!
61//! Please be aware that any scheduled runtime calls executed in a future block may __fail__ or may
62//! result in __undefined behavior__ since the runtime could have upgraded between the time of
63//! scheduling and execution. For example, the runtime upgrade could have:
64//!
65//! * Modified the implementation of the runtime call (runtime specification upgrade).
66//!     * Could lead to undefined behavior.
67//! * Removed or changed the ordering/index of the runtime call.
68//!     * Could fail due to the runtime call index not being part of the `Call`.
69//!     * Could lead to undefined behavior, such as executing another runtime call with the same
70//!       index.
71//!
72//! [`on_initialize`]: frame_support::traits::Hooks::on_initialize
73
74// Ensure we're `no_std` when compiling for Wasm.
75#![cfg_attr(not(feature = "std"), no_std)]
76
77#[cfg(feature = "runtime-benchmarks")]
78mod benchmarking;
79pub mod migration;
80#[cfg(test)]
81mod mock;
82#[cfg(test)]
83mod tests;
84pub mod weights;
85
86extern crate alloc;
87
88use alloc::{boxed::Box, vec::Vec};
89use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
90use core::{borrow::Borrow, cmp::Ordering, marker::PhantomData};
91use frame_support::{
92	dispatch::{DispatchResult, GetDispatchInfo, Parameter, RawOrigin},
93	ensure,
94	traits::{
95		schedule::{self, DispatchTime, MaybeHashed},
96		Bounded, CallerTrait, EnsureOrigin, Get, IsType, OriginTrait, PalletInfoAccess,
97		PrivilegeCmp, QueryPreimage, StorageVersion, StorePreimage,
98	},
99	weights::{Weight, WeightMeter},
100};
101use frame_system::{self as system};
102use scale_info::TypeInfo;
103use sp_io::hashing::blake2_256;
104use sp_runtime::{
105	traits::{BadOrigin, BlockNumberProvider, Dispatchable, One, Saturating, Zero},
106	BoundedVec, Debug, DispatchError,
107};
108
109pub use pallet::*;
110pub use weights::WeightInfo;
111
112/// Just a simple index for naming period tasks.
113pub type PeriodicIndex = u32;
114/// The location of a scheduled task that can be used to remove it.
115pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
116
117pub type CallOrHashOf<T> =
118	MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;
119
120pub type BoundedCallOf<T> =
121	Bounded<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hashing>;
122
123pub type BlockNumberFor<T> =
124	<<T as Config>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
125
126/// The configuration of the retry mechanism for a given task along with its current state.
127#[derive(
128	Clone,
129	Copy,
130	Debug,
131	PartialEq,
132	Eq,
133	Encode,
134	Decode,
135	DecodeWithMemTracking,
136	MaxEncodedLen,
137	TypeInfo,
138)]
139pub struct RetryConfig<Period> {
140	/// Initial amount of retries allowed.
141	pub total_retries: u8,
142	/// Amount of retries left.
143	pub remaining: u8,
144	/// Period of time between retry attempts.
145	pub period: Period,
146}
147
148#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
149#[derive(Clone, Debug, Encode, Decode)]
150struct ScheduledV1<Call, BlockNumber> {
151	maybe_id: Option<Vec<u8>>,
152	priority: schedule::Priority,
153	call: Call,
154	maybe_periodic: Option<schedule::Period<BlockNumber>>,
155}
156
157/// Information regarding an item to be executed in the future.
158#[derive(
159	Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking,
160)]
161pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {
162	/// The unique identity for this task, if there is one.
163	pub maybe_id: Option<Name>,
164	/// This task's priority.
165	pub priority: schedule::Priority,
166	/// The call to be dispatched.
167	pub call: Call,
168	/// If the call is periodic, then this points to the information concerning that.
169	pub maybe_periodic: Option<schedule::Period<BlockNumber>>,
170	/// The origin with which to dispatch the call.
171	pub origin: PalletsOrigin,
172	#[doc(hidden)]
173	pub _phantom: PhantomData<AccountId>,
174}
175
176impl<Name, Call, BlockNumber, PalletsOrigin, AccountId>
177	Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId>
178where
179	Call: Clone,
180	PalletsOrigin: Clone,
181{
182	/// Create a new task to be used for retry attempts of the original one. The cloned task will
183	/// have the same `priority`, `call` and `origin`, but will always be non-periodic and unnamed.
184	pub fn as_retry(&self) -> Self {
185		Self {
186			maybe_id: None,
187			priority: self.priority,
188			call: self.call.clone(),
189			maybe_periodic: None,
190			origin: self.origin.clone(),
191			_phantom: Default::default(),
192		}
193	}
194}
195
196use crate::{Scheduled as ScheduledV3, Scheduled as ScheduledV2};
197
198pub type ScheduledV2Of<T> = ScheduledV2<
199	Vec<u8>,
200	<T as Config>::RuntimeCall,
201	BlockNumberFor<T>,
202	<T as Config>::PalletsOrigin,
203	<T as frame_system::Config>::AccountId,
204>;
205
206pub type ScheduledV3Of<T> = ScheduledV3<
207	Vec<u8>,
208	CallOrHashOf<T>,
209	BlockNumberFor<T>,
210	<T as Config>::PalletsOrigin,
211	<T as frame_system::Config>::AccountId,
212>;
213
214pub type ScheduledOf<T> = Scheduled<
215	TaskName,
216	BoundedCallOf<T>,
217	BlockNumberFor<T>,
218	<T as Config>::PalletsOrigin,
219	<T as frame_system::Config>::AccountId,
220>;
221
222pub(crate) trait MarginalWeightInfo: WeightInfo {
223	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {
224		let base = Self::service_task_base();
225		let mut total = match maybe_lookup_len {
226			None => base,
227			Some(l) => Self::service_task_fetched(l as u32),
228		};
229		if named {
230			total.saturating_accrue(Self::service_task_named().saturating_sub(base));
231		}
232		if periodic {
233			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));
234		}
235		total
236	}
237}
238impl<T: WeightInfo> MarginalWeightInfo for T {}
239
240#[frame_support::pallet]
241pub mod pallet {
242	use super::*;
243	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};
244	use frame_system::pallet_prelude::{BlockNumberFor as SystemBlockNumberFor, OriginFor};
245
246	/// The in-code storage version.
247	const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
248
249	#[pallet::pallet]
250	#[pallet::storage_version(STORAGE_VERSION)]
251	pub struct Pallet<T>(_);
252
253	/// `system::Config` should always be included in our implied traits.
254	#[pallet::config]
255	pub trait Config: frame_system::Config {
256		/// The overarching event type.
257		#[allow(deprecated)]
258		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
259
260		/// The aggregated origin which the dispatch will take.
261		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
262			+ From<Self::PalletsOrigin>
263			+ IsType<<Self as system::Config>::RuntimeOrigin>;
264
265		/// The caller origin, overarching type of all pallets origins.
266		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>
267			+ CallerTrait<Self::AccountId>
268			+ MaxEncodedLen;
269
270		/// The aggregated call type.
271		type RuntimeCall: Parameter
272			+ Dispatchable<
273				RuntimeOrigin = <Self as Config>::RuntimeOrigin,
274				PostInfo = PostDispatchInfo,
275			> + GetDispatchInfo
276			+ From<system::Call<Self>>;
277
278		/// The maximum weight that may be scheduled per block for any dispatchables.
279		#[pallet::constant]
280		type MaximumWeight: Get<Weight>;
281
282		/// Required origin to schedule or cancel calls.
283		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
284
285		/// Compare the privileges of origins.
286		///
287		/// This will be used when canceling a task, to ensure that the origin that tries
288		/// to cancel has greater or equal privileges as the origin that created the scheduled task.
289		///
290		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can
291		/// be used. This will only check if two given origins are equal.
292		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;
293
294		/// The maximum number of scheduled calls in the queue for a single block.
295		///
296		/// NOTE:
297		/// + Dependent pallets' benchmarks might require a higher limit for the setting. Set a
298		/// higher limit under `runtime-benchmarks` feature.
299		#[pallet::constant]
300		type MaxScheduledPerBlock: Get<u32>;
301
302		/// Weight information for extrinsics in this pallet.
303		type WeightInfo: WeightInfo;
304
305		/// The preimage provider with which we look up call hashes to get the call.
306		type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
307
308		/// Query the current block number.
309		///
310		/// Must return monotonically increasing values when called from consecutive blocks. It is
311		/// generally expected that the values also do not differ "too much" between consecutive
312		/// blocks. A future addition to this pallet will allow bigger difference between
313		/// consecutive blocks to make it possible to be utilized by parachains with *Agile
314		/// Coretime*. *Agile Coretime* parachains are currently not supported and must continue to
315		/// use their local block number provider.
316		///
317		/// Can be configured to return either:
318		/// - the local block number of the runtime via `frame_system::Pallet`
319		/// - a remote block number, eg from the relay chain through `RelaychainDataProvider`
320		/// - an arbitrary value through a custom implementation of the trait
321		///
322		/// Suggested values:
323		/// - Solo- and Relay-chains should use `frame_system::Pallet`. There are no concerns with
324		///   this configuration.
325		/// - Parachains should also use `frame_system::Pallet` for the time being. The scheduler
326		///   pallet is not yet ready for the case that big numbers of blocks are skipped. In an
327		///   *Agile Coretime* chain with relay chain number provider configured, it could otherwise
328		///   happen that the scheduler will not be able to catch up to its agendas, since too many
329		///   relay blocks are missing if the parachain only produces blocks rarely.
330		///
331		/// There is currently no migration provided to "hot-swap" block number providers and it is
332		/// therefore highly advised to stay with the default (local) values. If you still want to
333		/// swap block number providers on the fly, then please at least ensure that you do not run
334		/// any pallet migration in the same runtime upgrade.
335		type BlockNumberProvider: BlockNumberProvider;
336	}
337
338	/// Block number at which the agenda began incomplete execution.
339	#[pallet::storage]
340	pub type IncompleteSince<T: Config> = StorageValue<_, BlockNumberFor<T>>;
341
342	/// Items to be executed, indexed by the block number that they should be executed on.
343	#[pallet::storage]
344	pub type Agenda<T: Config> = StorageMap<
345		_,
346		Twox64Concat,
347		BlockNumberFor<T>,
348		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,
349		ValueQuery,
350	>;
351
352	/// Retry configurations for items to be executed, indexed by task address.
353	#[pallet::storage]
354	pub type Retries<T: Config> = StorageMap<
355		_,
356		Blake2_128Concat,
357		TaskAddress<BlockNumberFor<T>>,
358		RetryConfig<BlockNumberFor<T>>,
359		OptionQuery,
360	>;
361
362	/// Lookup from a name to the block number and index of the task.
363	///
364	/// For v3 -> v4 the previously unbounded identities are Blake2-256 hashed to form the v4
365	/// identities.
366	#[pallet::storage]
367	pub type Lookup<T: Config> =
368		StorageMap<_, Twox64Concat, TaskName, TaskAddress<BlockNumberFor<T>>>;
369
370	/// Events type.
371	#[pallet::event]
372	#[pallet::generate_deposit(pub(super) fn deposit_event)]
373	pub enum Event<T: Config> {
374		/// Scheduled some task.
375		Scheduled { when: BlockNumberFor<T>, index: u32 },
376		/// Canceled some task.
377		Canceled { when: BlockNumberFor<T>, index: u32 },
378		/// Dispatched some task.
379		Dispatched {
380			task: TaskAddress<BlockNumberFor<T>>,
381			id: Option<TaskName>,
382			result: DispatchResult,
383		},
384		/// Set a retry configuration for some task.
385		RetrySet {
386			task: TaskAddress<BlockNumberFor<T>>,
387			id: Option<TaskName>,
388			period: BlockNumberFor<T>,
389			retries: u8,
390		},
391		/// Cancel a retry configuration for some task.
392		RetryCancelled { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
393		/// The call for the provided hash was not found so the task has been aborted.
394		CallUnavailable { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
395		/// The given task was unable to be renewed since the agenda is full at that block.
396		PeriodicFailed { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
397		/// The given task was unable to be retried since the agenda is full at that block or there
398		/// was not enough weight to reschedule it.
399		RetryFailed { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
400		/// The given task can never be executed since it is overweight.
401		PermanentlyOverweight { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
402		/// Agenda is incomplete from `when`.
403		AgendaIncomplete { when: BlockNumberFor<T> },
404	}
405
406	#[pallet::error]
407	pub enum Error<T> {
408		/// Failed to schedule a call
409		FailedToSchedule,
410		/// Cannot find the scheduled call.
411		NotFound,
412		/// Given target block number is in the past.
413		TargetBlockNumberInPast,
414		/// Reschedule failed because it does not change scheduled time.
415		RescheduleNoChange,
416		/// Attempt to use a non-named function on a named task.
417		Named,
418	}
419
420	#[pallet::hooks]
421	impl<T: Config> Hooks<SystemBlockNumberFor<T>> for Pallet<T> {
422		/// Execute the scheduled calls
423		fn on_initialize(_now: SystemBlockNumberFor<T>) -> Weight {
424			let now = T::BlockNumberProvider::current_block_number();
425			let mut weight_counter = frame_system::Pallet::<T>::remaining_block_weight()
426				.limit_to(T::MaximumWeight::get());
427			Self::service_agendas(&mut weight_counter, now, u32::MAX);
428			weight_counter.consumed()
429		}
430
431		#[cfg(feature = "std")]
432		fn integrity_test() {
433			/// Calculate the maximum weight that a lookup of a given size can take.
434			fn lookup_weight<T: Config>(s: usize) -> Weight {
435				T::WeightInfo::service_agendas_base() +
436					T::WeightInfo::service_agenda_base(T::MaxScheduledPerBlock::get()) +
437					T::WeightInfo::service_task(Some(s), true, true)
438			}
439
440			let limit = sp_runtime::Perbill::from_percent(90) * T::MaximumWeight::get();
441
442			let small_lookup = lookup_weight::<T>(128);
443			assert!(small_lookup.all_lte(limit), "Must be possible to submit a small lookup");
444
445			let medium_lookup = lookup_weight::<T>(1024);
446			assert!(medium_lookup.all_lte(limit), "Must be possible to submit a medium lookup");
447
448			let large_lookup = lookup_weight::<T>(1024 * 1024);
449			assert!(large_lookup.all_lte(limit), "Must be possible to submit a large lookup");
450		}
451	}
452
453	#[pallet::call]
454	impl<T: Config> Pallet<T> {
455		/// Anonymously schedule a task.
456		#[pallet::call_index(0)]
457		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
458		pub fn schedule(
459			origin: OriginFor<T>,
460			when: BlockNumberFor<T>,
461			maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
462			priority: schedule::Priority,
463			call: Box<<T as Config>::RuntimeCall>,
464		) -> DispatchResult {
465			T::ScheduleOrigin::ensure_origin(origin.clone())?;
466			let origin = <T as Config>::RuntimeOrigin::from(origin);
467			Self::do_schedule(
468				DispatchTime::At(when),
469				maybe_periodic,
470				priority,
471				origin.caller().clone(),
472				T::Preimages::bound(*call)?,
473			)?;
474			Ok(())
475		}
476
477		/// Cancel a scheduled task (named or anonymous), by providing the block it is scheduled for
478		/// execution in, as well as the index of the task in that block's agenda.
479		///
480		/// In the case of a named task, it will remove it from the lookup table as well.
481		#[pallet::call_index(1)]
482		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]
483		pub fn cancel(origin: OriginFor<T>, when: BlockNumberFor<T>, index: u32) -> DispatchResult {
484			T::ScheduleOrigin::ensure_origin(origin.clone())?;
485			let origin = <T as Config>::RuntimeOrigin::from(origin);
486			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
487			Ok(())
488		}
489
490		/// Schedule a named task.
491		#[pallet::call_index(2)]
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: BlockNumberFor<T>,
497			maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
498			priority: schedule::Priority,
499			call: Box<<T as Config>::RuntimeCall>,
500		) -> DispatchResult {
501			T::ScheduleOrigin::ensure_origin(origin.clone())?;
502			let origin = <T as Config>::RuntimeOrigin::from(origin);
503			Self::do_schedule_named(
504				id,
505				DispatchTime::At(when),
506				maybe_periodic,
507				priority,
508				origin.caller().clone(),
509				T::Preimages::bound(*call)?,
510			)?;
511			Ok(())
512		}
513
514		/// Cancel a named scheduled task.
515		#[pallet::call_index(3)]
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		}
523
524		/// Anonymously schedule a task after a delay.
525		#[pallet::call_index(4)]
526		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
527		pub fn schedule_after(
528			origin: OriginFor<T>,
529			after: BlockNumberFor<T>,
530			maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
531			priority: schedule::Priority,
532			call: Box<<T as Config>::RuntimeCall>,
533		) -> DispatchResult {
534			T::ScheduleOrigin::ensure_origin(origin.clone())?;
535			let origin = <T as Config>::RuntimeOrigin::from(origin);
536			Self::do_schedule(
537				DispatchTime::After(after),
538				maybe_periodic,
539				priority,
540				origin.caller().clone(),
541				T::Preimages::bound(*call)?,
542			)?;
543			Ok(())
544		}
545
546		/// Schedule a named task after a delay.
547		#[pallet::call_index(5)]
548		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
549		pub fn schedule_named_after(
550			origin: OriginFor<T>,
551			id: TaskName,
552			after: BlockNumberFor<T>,
553			maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
554			priority: schedule::Priority,
555			call: Box<<T as Config>::RuntimeCall>,
556		) -> DispatchResult {
557			T::ScheduleOrigin::ensure_origin(origin.clone())?;
558			let origin = <T as Config>::RuntimeOrigin::from(origin);
559			Self::do_schedule_named(
560				id,
561				DispatchTime::After(after),
562				maybe_periodic,
563				priority,
564				origin.caller().clone(),
565				T::Preimages::bound(*call)?,
566			)?;
567			Ok(())
568		}
569
570		/// Set a retry configuration for a task so that, in case its scheduled run fails, it will
571		/// be retried after `period` blocks, for a total amount of `retries` retries or until it
572		/// succeeds.
573		///
574		/// Tasks which need to be scheduled for a retry are still subject to weight metering and
575		/// agenda space, same as a regular task. If a periodic task fails, it will be scheduled
576		/// normally while the task is retrying.
577		///
578		/// Tasks scheduled as a result of a retry for a periodic task are unnamed, non-periodic
579		/// clones of the original task. Their retry configuration will be derived from the
580		/// original task's configuration, but will have a lower value for `remaining` than the
581		/// original `total_retries`.
582		///
583		/// This call **cannot** be used to set a retry configuration for a named task.
584		#[pallet::call_index(6)]
585		#[pallet::weight(<T as Config>::WeightInfo::set_retry())]
586		pub fn set_retry(
587			origin: OriginFor<T>,
588			task: TaskAddress<BlockNumberFor<T>>,
589			retries: u8,
590			period: BlockNumberFor<T>,
591		) -> DispatchResult {
592			T::ScheduleOrigin::ensure_origin(origin.clone())?;
593			let origin = <T as Config>::RuntimeOrigin::from(origin);
594			let (when, index) = task;
595			let agenda = Agenda::<T>::get(when);
596			let scheduled = agenda
597				.get(index as usize)
598				.and_then(Option::as_ref)
599				.ok_or(Error::<T>::NotFound)?;
600			Self::ensure_privilege(origin.caller(), &scheduled.origin)?;
601			Retries::<T>::insert(
602				(when, index),
603				RetryConfig { total_retries: retries, remaining: retries, period },
604			);
605			Self::deposit_event(Event::RetrySet { task, id: None, period, retries });
606			Ok(())
607		}
608
609		/// Set a retry configuration for a named task so that, in case its scheduled run fails, it
610		/// will be retried after `period` blocks, for a total amount of `retries` retries or until
611		/// it succeeds.
612		///
613		/// Tasks which need to be scheduled for a retry are still subject to weight metering and
614		/// agenda space, same as a regular task. If a periodic task fails, it will be scheduled
615		/// normally while the task is retrying.
616		///
617		/// Tasks scheduled as a result of a retry for a periodic task are unnamed, non-periodic
618		/// clones of the original task. Their retry configuration will be derived from the
619		/// original task's configuration, but will have a lower value for `remaining` than the
620		/// original `total_retries`.
621		///
622		/// This is the only way to set a retry configuration for a named task.
623		#[pallet::call_index(7)]
624		#[pallet::weight(<T as Config>::WeightInfo::set_retry_named())]
625		pub fn set_retry_named(
626			origin: OriginFor<T>,
627			id: TaskName,
628			retries: u8,
629			period: BlockNumberFor<T>,
630		) -> DispatchResult {
631			T::ScheduleOrigin::ensure_origin(origin.clone())?;
632			let origin = <T as Config>::RuntimeOrigin::from(origin);
633			let (when, agenda_index) = Lookup::<T>::get(&id).ok_or(Error::<T>::NotFound)?;
634			let agenda = Agenda::<T>::get(when);
635			let scheduled = agenda
636				.get(agenda_index as usize)
637				.and_then(Option::as_ref)
638				.ok_or(Error::<T>::NotFound)?;
639			Self::ensure_privilege(origin.caller(), &scheduled.origin)?;
640			Retries::<T>::insert(
641				(when, agenda_index),
642				RetryConfig { total_retries: retries, remaining: retries, period },
643			);
644			Self::deposit_event(Event::RetrySet {
645				task: (when, agenda_index),
646				id: Some(id),
647				period,
648				retries,
649			});
650			Ok(())
651		}
652
653		/// Removes the retry configuration of a task.
654		#[pallet::call_index(8)]
655		#[pallet::weight(<T as Config>::WeightInfo::cancel_retry())]
656		pub fn cancel_retry(
657			origin: OriginFor<T>,
658			task: TaskAddress<BlockNumberFor<T>>,
659		) -> DispatchResult {
660			T::ScheduleOrigin::ensure_origin(origin.clone())?;
661			let origin = <T as Config>::RuntimeOrigin::from(origin);
662			Self::do_cancel_retry(origin.caller(), task)?;
663			Self::deposit_event(Event::RetryCancelled { task, id: None });
664			Ok(())
665		}
666
667		/// Cancel the retry configuration of a named task.
668		#[pallet::call_index(9)]
669		#[pallet::weight(<T as Config>::WeightInfo::cancel_retry_named())]
670		pub fn cancel_retry_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {
671			T::ScheduleOrigin::ensure_origin(origin.clone())?;
672			let origin = <T as Config>::RuntimeOrigin::from(origin);
673			let task = Lookup::<T>::get(&id).ok_or(Error::<T>::NotFound)?;
674			Self::do_cancel_retry(origin.caller(), task)?;
675			Self::deposit_event(Event::RetryCancelled { task, id: Some(id) });
676			Ok(())
677		}
678	}
679}
680
681impl<T: Config> Pallet<T> {
682	/// Migrate storage format from V1 to V4.
683	///
684	/// Returns the weight consumed by this migration.
685	pub fn migrate_v1_to_v4() -> Weight {
686		use migration::v1 as old;
687		let mut weight = T::DbWeight::get().reads_writes(1, 1);
688
689		// Delete all undecodable values.
690		// `StorageMap::translate` is not enough since it just skips them and leaves the keys in.
691		let keys = old::Agenda::<T>::iter_keys().collect::<Vec<_>>();
692		for key in keys {
693			weight.saturating_accrue(T::DbWeight::get().reads(1));
694			if let Err(_) = old::Agenda::<T>::try_get(&key) {
695				weight.saturating_accrue(T::DbWeight::get().writes(1));
696				old::Agenda::<T>::remove(&key);
697				log::warn!("Deleted undecodable agenda");
698			}
699		}
700
701		Agenda::<T>::translate::<
702			Vec<Option<ScheduledV1<<T as Config>::RuntimeCall, BlockNumberFor<T>>>>,
703			_,
704		>(|_, agenda| {
705			Some(BoundedVec::truncate_from(
706				agenda
707					.into_iter()
708					.map(|schedule| {
709						weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
710
711						schedule.and_then(|schedule| {
712							if let Some(id) = schedule.maybe_id.as_ref() {
713								let name = blake2_256(id);
714								if let Some(item) = old::Lookup::<T>::take(id) {
715									Lookup::<T>::insert(name, item);
716								}
717								weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2));
718							}
719
720							let call = T::Preimages::bound(schedule.call).ok()?;
721
722							if call.lookup_needed() {
723								weight.saturating_accrue(T::DbWeight::get().reads_writes(0, 1));
724							}
725
726							Some(Scheduled {
727								maybe_id: schedule.maybe_id.map(|x| blake2_256(&x[..])),
728								priority: schedule.priority,
729								call,
730								maybe_periodic: schedule.maybe_periodic,
731								origin: system::RawOrigin::Root.into(),
732								_phantom: Default::default(),
733							})
734						})
735					})
736					.collect::<Vec<_>>(),
737			))
738		});
739
740		let _ = frame_support::storage::migration::clear_storage_prefix(
741			Self::name().as_bytes(),
742			b"StorageVersion",
743			&[],
744			None,
745			None,
746		);
747
748		StorageVersion::new(4).put::<Self>();
749
750		weight + T::DbWeight::get().writes(2)
751	}
752
753	/// Migrate storage format from V2 to V4.
754	///
755	/// Returns the weight consumed by this migration.
756	pub fn migrate_v2_to_v4() -> Weight {
757		use migration::v2 as old;
758		let mut weight = T::DbWeight::get().reads_writes(1, 1);
759
760		// Delete all undecodable values.
761		// `StorageMap::translate` is not enough since it just skips them and leaves the keys in.
762		let keys = old::Agenda::<T>::iter_keys().collect::<Vec<_>>();
763		for key in keys {
764			weight.saturating_accrue(T::DbWeight::get().reads(1));
765			if let Err(_) = old::Agenda::<T>::try_get(&key) {
766				weight.saturating_accrue(T::DbWeight::get().writes(1));
767				old::Agenda::<T>::remove(&key);
768				log::warn!("Deleted undecodable agenda");
769			}
770		}
771
772		Agenda::<T>::translate::<Vec<Option<ScheduledV2Of<T>>>, _>(|_, agenda| {
773			Some(BoundedVec::truncate_from(
774				agenda
775					.into_iter()
776					.map(|schedule| {
777						weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
778						schedule.and_then(|schedule| {
779							if let Some(id) = schedule.maybe_id.as_ref() {
780								let name = blake2_256(id);
781								if let Some(item) = old::Lookup::<T>::take(id) {
782									Lookup::<T>::insert(name, item);
783								}
784								weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2));
785							}
786
787							let call = T::Preimages::bound(schedule.call).ok()?;
788							if call.lookup_needed() {
789								weight.saturating_accrue(T::DbWeight::get().reads_writes(0, 1));
790							}
791
792							Some(Scheduled {
793								maybe_id: schedule.maybe_id.map(|x| blake2_256(&x[..])),
794								priority: schedule.priority,
795								call,
796								maybe_periodic: schedule.maybe_periodic,
797								origin: schedule.origin,
798								_phantom: Default::default(),
799							})
800						})
801					})
802					.collect::<Vec<_>>(),
803			))
804		});
805
806		let _ = frame_support::storage::migration::clear_storage_prefix(
807			Self::name().as_bytes(),
808			b"StorageVersion",
809			&[],
810			None,
811			None,
812		);
813
814		StorageVersion::new(4).put::<Self>();
815
816		weight + T::DbWeight::get().writes(2)
817	}
818
819	/// Migrate storage format from V3 to V4.
820	///
821	/// Returns the weight consumed by this migration.
822	#[allow(deprecated)]
823	pub fn migrate_v3_to_v4() -> Weight {
824		use migration::v3 as old;
825		let mut weight = T::DbWeight::get().reads_writes(2, 1);
826
827		// Delete all undecodable values.
828		// `StorageMap::translate` is not enough since it just skips them and leaves the keys in.
829		let blocks = old::Agenda::<T>::iter_keys().collect::<Vec<_>>();
830		for block in blocks {
831			weight.saturating_accrue(T::DbWeight::get().reads(1));
832			if let Err(_) = old::Agenda::<T>::try_get(&block) {
833				weight.saturating_accrue(T::DbWeight::get().writes(1));
834				old::Agenda::<T>::remove(&block);
835				log::warn!("Deleted undecodable agenda of block: {:?}", block);
836			}
837		}
838
839		Agenda::<T>::translate::<Vec<Option<ScheduledV3Of<T>>>, _>(|block, agenda| {
840			log::info!("Migrating agenda of block: {:?}", &block);
841			Some(BoundedVec::truncate_from(
842				agenda
843					.into_iter()
844					.map(|schedule| {
845						weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
846						schedule
847							.and_then(|schedule| {
848								if let Some(id) = schedule.maybe_id.as_ref() {
849									let name = blake2_256(id);
850									if let Some(item) = old::Lookup::<T>::take(id) {
851										Lookup::<T>::insert(name, item);
852										log::info!("Migrated name for id: {:?}", id);
853									} else {
854										log::error!("No name in Lookup for id: {:?}", &id);
855									}
856									weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2));
857								} else {
858									log::info!("Schedule is unnamed");
859								}
860
861								let call = match schedule.call {
862									MaybeHashed::Hash(h) => {
863										let bounded = Bounded::from_legacy_hash(h);
864										// Check that the call can be decoded in the new runtime.
865										if let Err(err) = T::Preimages::peek::<
866											<T as Config>::RuntimeCall,
867										>(&bounded)
868										{
869											log::error!(
870												"Dropping undecodable call {:?}: {:?}",
871												&h,
872												&err
873											);
874											return None;
875										}
876										weight.saturating_accrue(T::DbWeight::get().reads(1));
877										log::info!("Migrated call by hash, hash: {:?}", h);
878										bounded
879									},
880									MaybeHashed::Value(v) => {
881										let call = T::Preimages::bound(v)
882											.map_err(|e| {
883												log::error!("Could not bound Call: {:?}", e)
884											})
885											.ok()?;
886										if call.lookup_needed() {
887											weight.saturating_accrue(
888												T::DbWeight::get().reads_writes(0, 1),
889											);
890										}
891										log::info!(
892											"Migrated call by value, hash: {:?}",
893											call.hash()
894										);
895										call
896									},
897								};
898
899								Some(Scheduled {
900									maybe_id: schedule.maybe_id.map(|x| blake2_256(&x[..])),
901									priority: schedule.priority,
902									call,
903									maybe_periodic: schedule.maybe_periodic,
904									origin: schedule.origin,
905									_phantom: Default::default(),
906								})
907							})
908							.or_else(|| {
909								log::info!("Schedule in agenda for block {:?} is empty - nothing to do here.", &block);
910								None
911							})
912					})
913					.collect::<Vec<_>>(),
914			))
915		});
916
917		let _ = frame_support::storage::migration::clear_storage_prefix(
918			Self::name().as_bytes(),
919			b"StorageVersion",
920			&[],
921			None,
922			None,
923		);
924
925		StorageVersion::new(4).put::<Self>();
926
927		weight + T::DbWeight::get().writes(2)
928	}
929}
930
931impl<T: Config> Pallet<T> {
932	/// Helper to migrate scheduler when the pallet origin type has changed.
933	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {
934		Agenda::<T>::translate::<
935			Vec<
936				Option<
937					Scheduled<
938						TaskName,
939						BoundedCallOf<T>,
940						BlockNumberFor<T>,
941						OldOrigin,
942						T::AccountId,
943					>,
944				>,
945			>,
946			_,
947		>(|_, agenda| {
948			Some(BoundedVec::truncate_from(
949				agenda
950					.into_iter()
951					.map(|schedule| {
952						schedule.map(|schedule| Scheduled {
953							maybe_id: schedule.maybe_id,
954							priority: schedule.priority,
955							call: schedule.call,
956							maybe_periodic: schedule.maybe_periodic,
957							origin: schedule.origin.into(),
958							_phantom: Default::default(),
959						})
960					})
961					.collect::<Vec<_>>(),
962			))
963		});
964	}
965
966	fn resolve_time(
967		when: DispatchTime<BlockNumberFor<T>>,
968	) -> Result<BlockNumberFor<T>, DispatchError> {
969		let now = T::BlockNumberProvider::current_block_number();
970		let when = match when {
971			DispatchTime::At(x) => x,
972			// The current block has already completed it's scheduled tasks, so
973			// Schedule the task at lest one block after this current block.
974			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),
975		};
976
977		if when <= now {
978			return Err(Error::<T>::TargetBlockNumberInPast.into());
979		}
980
981		Ok(when)
982	}
983
984	fn place_task(
985		when: BlockNumberFor<T>,
986		what: ScheduledOf<T>,
987	) -> Result<TaskAddress<BlockNumberFor<T>>, (DispatchError, ScheduledOf<T>)> {
988		let maybe_name = what.maybe_id;
989		let index = Self::push_to_agenda(when, what)?;
990		let address = (when, index);
991		if let Some(name) = maybe_name {
992			Lookup::<T>::insert(name, address)
993		}
994		Self::deposit_event(Event::Scheduled { when: address.0, index: address.1 });
995		Ok(address)
996	}
997
998	fn push_to_agenda(
999		when: BlockNumberFor<T>,
1000		what: ScheduledOf<T>,
1001	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {
1002		let mut agenda = Agenda::<T>::get(when);
1003		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {
1004			// will always succeed due to the above check.
1005			let _ = agenda.try_push(Some(what));
1006			agenda.len() as u32 - 1
1007		} else {
1008			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {
1009				agenda[hole_index] = Some(what);
1010				hole_index as u32
1011			} else {
1012				return Err((DispatchError::Exhausted, what));
1013			}
1014		};
1015		Agenda::<T>::insert(when, agenda);
1016		Ok(index)
1017	}
1018
1019	/// Remove trailing `None` items of an agenda at `when`. If all items are `None` remove the
1020	/// agenda record entirely.
1021	fn cleanup_agenda(when: BlockNumberFor<T>) {
1022		let mut agenda = Agenda::<T>::get(when);
1023		match agenda.iter().rposition(|i| i.is_some()) {
1024			// Note that `agenda.len() > i + 1` implies that the agenda ends on a sequence of at
1025			// least one `None` item(s).
1026			Some(i) if agenda.len() > i + 1 => {
1027				agenda.truncate(i + 1);
1028				Agenda::<T>::insert(when, agenda);
1029			},
1030			// This branch is taken if `agenda.len() <= i + 1 ==> agenda.len() == i + 1 <==>
1031			// agenda.len() - 1 == i` i.e. the agenda's last item is `Some`.
1032			Some(_) => {},
1033			// All items in the agenda are `None`.
1034			None => {
1035				Agenda::<T>::remove(when);
1036			},
1037		}
1038	}
1039
1040	fn do_schedule(
1041		when: DispatchTime<BlockNumberFor<T>>,
1042		maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1043		priority: schedule::Priority,
1044		origin: T::PalletsOrigin,
1045		call: BoundedCallOf<T>,
1046	) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1047		let when = Self::resolve_time(when)?;
1048
1049		let lookup_hash = call.lookup_hash();
1050
1051		// sanitize maybe_periodic
1052		let maybe_periodic = maybe_periodic
1053			.filter(|p| p.1 > 1 && !p.0.is_zero())
1054			// Remove one from the number of repetitions since we will schedule one now.
1055			.map(|(p, c)| (p, c - 1));
1056		let task = Scheduled {
1057			maybe_id: None,
1058			priority,
1059			call,
1060			maybe_periodic,
1061			origin,
1062			_phantom: PhantomData,
1063		};
1064		let res = Self::place_task(when, task).map_err(|x| x.0)?;
1065
1066		if let Some(hash) = lookup_hash {
1067			// Request the call to be made available.
1068			T::Preimages::request(&hash);
1069		}
1070
1071		Ok(res)
1072	}
1073
1074	fn do_cancel(
1075		origin: Option<T::PalletsOrigin>,
1076		(when, index): TaskAddress<BlockNumberFor<T>>,
1077	) -> Result<(), DispatchError> {
1078		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {
1079			agenda.get_mut(index as usize).map_or(
1080				Ok(None),
1081				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
1082					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
1083						Self::ensure_privilege(o, &s.origin)?;
1084					};
1085					Ok(s.take())
1086				},
1087			)
1088		})?;
1089		if let Some(s) = scheduled {
1090			T::Preimages::drop(&s.call);
1091			if let Some(id) = s.maybe_id {
1092				Lookup::<T>::remove(id);
1093			}
1094			Retries::<T>::remove((when, index));
1095			Self::cleanup_agenda(when);
1096			Self::deposit_event(Event::Canceled { when, index });
1097			Ok(())
1098		} else {
1099			return Err(Error::<T>::NotFound.into());
1100		}
1101	}
1102
1103	fn do_reschedule(
1104		(when, index): TaskAddress<BlockNumberFor<T>>,
1105		new_time: DispatchTime<BlockNumberFor<T>>,
1106	) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1107		let new_time = Self::resolve_time(new_time)?;
1108
1109		if new_time == when {
1110			return Err(Error::<T>::RescheduleNoChange.into());
1111		}
1112
1113		let task = Agenda::<T>::try_mutate(when, |agenda| {
1114			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;
1115			ensure!(!matches!(task, Some(Scheduled { maybe_id: Some(_), .. })), Error::<T>::Named);
1116			task.take().ok_or(Error::<T>::NotFound)
1117		})?;
1118		Self::cleanup_agenda(when);
1119		Self::deposit_event(Event::Canceled { when, index });
1120
1121		Self::place_task(new_time, task).map_err(|x| x.0)
1122	}
1123
1124	fn do_schedule_named(
1125		id: TaskName,
1126		when: DispatchTime<BlockNumberFor<T>>,
1127		maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1128		priority: schedule::Priority,
1129		origin: T::PalletsOrigin,
1130		call: BoundedCallOf<T>,
1131	) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1132		// ensure id it is unique
1133		if Lookup::<T>::contains_key(&id) {
1134			return Err(Error::<T>::FailedToSchedule.into());
1135		}
1136
1137		let when = Self::resolve_time(when)?;
1138
1139		let lookup_hash = call.lookup_hash();
1140
1141		// sanitize maybe_periodic
1142		let maybe_periodic = maybe_periodic
1143			.filter(|p| p.1 > 1 && !p.0.is_zero())
1144			// Remove one from the number of repetitions since we will schedule one now.
1145			.map(|(p, c)| (p, c - 1));
1146
1147		let task = Scheduled {
1148			maybe_id: Some(id),
1149			priority,
1150			call,
1151			maybe_periodic,
1152			origin,
1153			_phantom: Default::default(),
1154		};
1155		let res = Self::place_task(when, task).map_err(|x| x.0)?;
1156
1157		if let Some(hash) = lookup_hash {
1158			// Request the call to be made available.
1159			T::Preimages::request(&hash);
1160		}
1161
1162		Ok(res)
1163	}
1164
1165	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {
1166		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
1167			if let Some((when, index)) = lookup.take() {
1168				let i = index as usize;
1169				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
1170					if let Some(s) = agenda.get_mut(i) {
1171						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
1172							Self::ensure_privilege(o, &s.origin)?;
1173							Retries::<T>::remove((when, index));
1174							T::Preimages::drop(&s.call);
1175						}
1176						*s = None;
1177					}
1178					Ok(())
1179				})?;
1180				Self::cleanup_agenda(when);
1181				Self::deposit_event(Event::Canceled { when, index });
1182				Ok(())
1183			} else {
1184				return Err(Error::<T>::NotFound.into());
1185			}
1186		})
1187	}
1188
1189	fn do_reschedule_named(
1190		id: TaskName,
1191		new_time: DispatchTime<BlockNumberFor<T>>,
1192	) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1193		let new_time = Self::resolve_time(new_time)?;
1194
1195		let lookup = Lookup::<T>::get(id);
1196		let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;
1197
1198		if new_time == when {
1199			return Err(Error::<T>::RescheduleNoChange.into());
1200		}
1201
1202		let task = Agenda::<T>::try_mutate(when, |agenda| {
1203			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;
1204			task.take().ok_or(Error::<T>::NotFound)
1205		})?;
1206		Self::cleanup_agenda(when);
1207		Self::deposit_event(Event::Canceled { when, index });
1208		Self::place_task(new_time, task).map_err(|x| x.0)
1209	}
1210
1211	fn do_cancel_retry(
1212		origin: &T::PalletsOrigin,
1213		(when, index): TaskAddress<BlockNumberFor<T>>,
1214	) -> Result<(), DispatchError> {
1215		let agenda = Agenda::<T>::get(when);
1216		let scheduled = agenda
1217			.get(index as usize)
1218			.and_then(Option::as_ref)
1219			.ok_or(Error::<T>::NotFound)?;
1220		Self::ensure_privilege(origin, &scheduled.origin)?;
1221		Retries::<T>::remove((when, index));
1222		Ok(())
1223	}
1224}
1225
1226enum ServiceTaskError {
1227	/// Could not be executed due to missing preimage.
1228	Unavailable,
1229	/// Could not be executed due to weight limitations.
1230	Overweight,
1231}
1232use ServiceTaskError::*;
1233
1234impl<T: Config> Pallet<T> {
1235	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.
1236	fn service_agendas(weight: &mut WeightMeter, now: BlockNumberFor<T>, max: u32) {
1237		if weight.try_consume(T::WeightInfo::service_agendas_base()).is_err() {
1238			return;
1239		}
1240
1241		let mut incomplete_since = now + One::one();
1242		let mut when = IncompleteSince::<T>::take().unwrap_or(now);
1243		let mut is_first = true; // first task from the first agenda.
1244
1245		let max_items = T::MaxScheduledPerBlock::get();
1246		let mut count_down = max;
1247		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);
1248		while count_down > 0 && when <= now && weight.can_consume(service_agenda_base_weight) {
1249			if !Self::service_agenda(weight, is_first, now, when, u32::MAX) {
1250				incomplete_since = incomplete_since.min(when);
1251			}
1252			is_first = false;
1253			when.saturating_inc();
1254			count_down.saturating_dec();
1255		}
1256		incomplete_since = incomplete_since.min(when);
1257		if incomplete_since <= now {
1258			Self::deposit_event(Event::AgendaIncomplete { when: incomplete_since });
1259			IncompleteSince::<T>::put(incomplete_since);
1260		} else {
1261			// The next scheduler iteration should typically start from `now + 1` (`next_iter_now`).
1262			// However, if the [`Config::BlockNumberProvider`] is not a local block number provider,
1263			// then `next_iter_now` could be `now + n` where `n > 1`. In this case, we want to start
1264			// from `now + 1` to ensure we don't miss any agendas.
1265			IncompleteSince::<T>::put(now + One::one());
1266		}
1267	}
1268
1269	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a
1270	/// later block.
1271	fn service_agenda(
1272		weight: &mut WeightMeter,
1273		mut is_first: bool,
1274		now: BlockNumberFor<T>,
1275		when: BlockNumberFor<T>,
1276		max: u32,
1277	) -> bool {
1278		let mut agenda = Agenda::<T>::get(when);
1279		let mut ordered = agenda
1280			.iter()
1281			.enumerate()
1282			.filter_map(|(index, maybe_item)| {
1283				maybe_item.as_ref().map(|item| (index as u32, item.priority))
1284			})
1285			.collect::<Vec<_>>();
1286		ordered.sort_by_key(|k| k.1);
1287		let within_limit = weight
1288			.try_consume(T::WeightInfo::service_agenda_base(ordered.len() as u32))
1289			.is_ok();
1290		debug_assert!(within_limit, "weight limit should have been checked in advance");
1291
1292		// Items which we know can be executed and have postponed for execution in a later block.
1293		let mut postponed = (ordered.len() as u32).saturating_sub(max);
1294		// Items which we don't know can ever be executed.
1295		let mut dropped = 0;
1296
1297		for (agenda_index, _) in ordered.into_iter().take(max as usize) {
1298			let Some(task) = agenda[agenda_index as usize].take() else { continue };
1299			let base_weight = T::WeightInfo::service_task(
1300				task.call.lookup_len().map(|x| x as usize),
1301				task.maybe_id.is_some(),
1302				task.maybe_periodic.is_some(),
1303			);
1304			if !weight.can_consume(base_weight) {
1305				postponed += 1;
1306				agenda[agenda_index as usize] = Some(task);
1307				break;
1308			}
1309			let result = Self::service_task(weight, now, when, agenda_index, is_first, task);
1310			agenda[agenda_index as usize] = match result {
1311				Err((Unavailable, slot)) => {
1312					dropped += 1;
1313					slot
1314				},
1315				Err((Overweight, slot)) => {
1316					postponed += 1;
1317					slot
1318				},
1319				Ok(()) => {
1320					is_first = false;
1321					None
1322				},
1323			};
1324		}
1325		if postponed > 0 || dropped > 0 {
1326			Agenda::<T>::insert(when, agenda);
1327		} else {
1328			Agenda::<T>::remove(when);
1329		}
1330
1331		postponed == 0
1332	}
1333
1334	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.
1335	///
1336	/// This involves:
1337	/// - removing and potentially replacing the `Lookup` entry for the task.
1338	/// - realizing the task's call which can include a preimage lookup.
1339	/// - Rescheduling the task for execution in a later agenda if periodic.
1340	fn service_task(
1341		weight: &mut WeightMeter,
1342		now: BlockNumberFor<T>,
1343		when: BlockNumberFor<T>,
1344		agenda_index: u32,
1345		is_first: bool,
1346		mut task: ScheduledOf<T>,
1347	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {
1348		if let Some(ref id) = task.maybe_id {
1349			Lookup::<T>::remove(id);
1350		}
1351
1352		let (call, lookup_len) = match T::Preimages::peek(&task.call) {
1353			Ok(c) => c,
1354			Err(_) => {
1355				Self::deposit_event(Event::CallUnavailable {
1356					task: (when, agenda_index),
1357					id: task.maybe_id,
1358				});
1359
1360				// It was not available when we needed it, so we don't need to have requested it
1361				// anymore.
1362				T::Preimages::drop(&task.call);
1363
1364				// We don't know why `peek` failed, thus we most account here for the "full weight".
1365				let _ = weight.try_consume(T::WeightInfo::service_task(
1366					task.call.lookup_len().map(|x| x as usize),
1367					task.maybe_id.is_some(),
1368					task.maybe_periodic.is_some(),
1369				));
1370
1371				return Err((Unavailable, Some(task)));
1372			},
1373		};
1374
1375		let _ = weight.try_consume(T::WeightInfo::service_task(
1376			lookup_len.map(|x| x as usize),
1377			task.maybe_id.is_some(),
1378			task.maybe_periodic.is_some(),
1379		));
1380
1381		match Self::execute_dispatch(weight, task.origin.clone(), call) {
1382			Err(()) if is_first => {
1383				T::Preimages::drop(&task.call);
1384				Self::deposit_event(Event::PermanentlyOverweight {
1385					task: (when, agenda_index),
1386					id: task.maybe_id,
1387				});
1388				Err((Unavailable, Some(task)))
1389			},
1390			Err(()) => Err((Overweight, Some(task))),
1391			Ok(result) => {
1392				let failed = result.is_err();
1393				let maybe_retry_config = Retries::<T>::take((when, agenda_index));
1394				Self::deposit_event(Event::Dispatched {
1395					task: (when, agenda_index),
1396					id: task.maybe_id,
1397					result,
1398				});
1399
1400				match maybe_retry_config {
1401					Some(retry_config) if failed => {
1402						Self::schedule_retry(weight, now, when, agenda_index, &task, retry_config);
1403					},
1404					_ => {},
1405				}
1406
1407				if let &Some((period, count)) = &task.maybe_periodic {
1408					if count > 1 {
1409						task.maybe_periodic = Some((period, count - 1));
1410					} else {
1411						task.maybe_periodic = None;
1412					}
1413					let wake = now.saturating_add(period);
1414					match Self::place_task(wake, task) {
1415						Ok(new_address) => {
1416							if let Some(retry_config) = maybe_retry_config {
1417								Retries::<T>::insert(new_address, retry_config);
1418							}
1419						},
1420						Err((_, task)) => {
1421							// TODO: Leave task in storage somewhere for it to be rescheduled
1422							// manually.
1423							T::Preimages::drop(&task.call);
1424							Self::deposit_event(Event::PeriodicFailed {
1425								task: (when, agenda_index),
1426								id: task.maybe_id,
1427							});
1428						},
1429					}
1430				} else {
1431					T::Preimages::drop(&task.call);
1432				}
1433				Ok(())
1434			},
1435		}
1436	}
1437
1438	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`
1439	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using
1440	/// post info if available).
1441	///
1442	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the
1443	/// call itself).
1444	///
1445	/// Returns an error if the call is overweight.
1446	fn execute_dispatch(
1447		weight: &mut WeightMeter,
1448		origin: T::PalletsOrigin,
1449		call: <T as Config>::RuntimeCall,
1450	) -> Result<DispatchResult, ()> {
1451		let base_weight = match origin.as_system_ref() {
1452			Some(&RawOrigin::Signed(_)) => T::WeightInfo::execute_dispatch_signed(),
1453			_ => T::WeightInfo::execute_dispatch_unsigned(),
1454		};
1455		let call_weight = call.get_dispatch_info().call_weight;
1456		// We only allow a scheduled call if it cannot push the weight past the limit.
1457		let max_weight = base_weight.saturating_add(call_weight);
1458
1459		if !weight.can_consume(max_weight) {
1460			return Err(());
1461		}
1462
1463		let dispatch_origin = origin.into();
1464		let (maybe_actual_call_weight, result) = match call.dispatch(dispatch_origin) {
1465			Ok(post_info) => (post_info.actual_weight, Ok(())),
1466			Err(error_and_info) => {
1467				(error_and_info.post_info.actual_weight, Err(error_and_info.error))
1468			},
1469		};
1470		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);
1471		let _ = weight.try_consume(base_weight);
1472		let _ = weight.try_consume(call_weight);
1473		Ok(result)
1474	}
1475
1476	/// Check if a task has a retry configuration in place and, if so, try to reschedule it.
1477	///
1478	/// Possible causes for failure to schedule a retry for a task:
1479	/// - there wasn't enough weight to run the task reschedule logic
1480	/// - there was no retry configuration in place
1481	/// - there were no more retry attempts left
1482	/// - the agenda was full.
1483	fn schedule_retry(
1484		weight: &mut WeightMeter,
1485		now: BlockNumberFor<T>,
1486		when: BlockNumberFor<T>,
1487		agenda_index: u32,
1488		task: &ScheduledOf<T>,
1489		retry_config: RetryConfig<BlockNumberFor<T>>,
1490	) {
1491		if weight
1492			.try_consume(T::WeightInfo::schedule_retry(T::MaxScheduledPerBlock::get()))
1493			.is_err()
1494		{
1495			Self::deposit_event(Event::RetryFailed {
1496				task: (when, agenda_index),
1497				id: task.maybe_id,
1498			});
1499			return;
1500		}
1501
1502		let RetryConfig { total_retries, mut remaining, period } = retry_config;
1503		remaining = match remaining.checked_sub(1) {
1504			Some(n) => n,
1505			None => return,
1506		};
1507		let wake = now.saturating_add(period);
1508		match Self::place_task(wake, task.as_retry()) {
1509			Ok(address) => {
1510				// Reinsert the retry config to the new address of the task after it was
1511				// placed.
1512				Retries::<T>::insert(address, RetryConfig { total_retries, remaining, period });
1513			},
1514			Err((_, task)) => {
1515				// TODO: Leave task in storage somewhere for it to be
1516				// rescheduled manually.
1517				T::Preimages::drop(&task.call);
1518				Self::deposit_event(Event::RetryFailed {
1519					task: (when, agenda_index),
1520					id: task.maybe_id,
1521				});
1522			},
1523		}
1524	}
1525
1526	/// Ensure that `left` has at least the same level of privilege or higher than `right`.
1527	///
1528	/// Returns an error if `left` has a lower level of privilege or the two cannot be compared.
1529	fn ensure_privilege(
1530		left: &<T as Config>::PalletsOrigin,
1531		right: &<T as Config>::PalletsOrigin,
1532	) -> Result<(), DispatchError> {
1533		if matches!(T::OriginPrivilegeCmp::cmp_privilege(left, right), Some(Ordering::Less) | None)
1534		{
1535			return Err(BadOrigin.into());
1536		}
1537		Ok(())
1538	}
1539}
1540
1541impl<T: Config> schedule::v3::Anon<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin>
1542	for Pallet<T>
1543{
1544	type Address = TaskAddress<BlockNumberFor<T>>;
1545	type Hasher = T::Hashing;
1546
1547	fn schedule(
1548		when: DispatchTime<BlockNumberFor<T>>,
1549		maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1550		priority: schedule::Priority,
1551		origin: T::PalletsOrigin,
1552		call: BoundedCallOf<T>,
1553	) -> Result<Self::Address, DispatchError> {
1554		Self::do_schedule(when, maybe_periodic, priority, origin, call)
1555	}
1556
1557	fn cancel((when, index): Self::Address) -> Result<(), DispatchError> {
1558		Self::do_cancel(None, (when, index)).map_err(map_err_to_v3_err::<T>)
1559	}
1560
1561	fn reschedule(
1562		address: Self::Address,
1563		when: DispatchTime<BlockNumberFor<T>>,
1564	) -> Result<Self::Address, DispatchError> {
1565		Self::do_reschedule(address, when).map_err(map_err_to_v3_err::<T>)
1566	}
1567
1568	fn next_dispatch_time(
1569		(when, index): Self::Address,
1570	) -> Result<BlockNumberFor<T>, DispatchError> {
1571		Agenda::<T>::get(when)
1572			.get(index as usize)
1573			.ok_or(DispatchError::Unavailable)
1574			.map(|_| when)
1575	}
1576}
1577
1578use schedule::v3::TaskName;
1579
1580impl<T: Config> schedule::v3::Named<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin>
1581	for Pallet<T>
1582{
1583	type Address = TaskAddress<BlockNumberFor<T>>;
1584	type Hasher = T::Hashing;
1585
1586	fn schedule_named(
1587		id: TaskName,
1588		when: DispatchTime<BlockNumberFor<T>>,
1589		maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1590		priority: schedule::Priority,
1591		origin: T::PalletsOrigin,
1592		call: BoundedCallOf<T>,
1593	) -> Result<Self::Address, DispatchError> {
1594		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call)
1595	}
1596
1597	fn cancel_named(id: TaskName) -> Result<(), DispatchError> {
1598		Self::do_cancel_named(None, id).map_err(map_err_to_v3_err::<T>)
1599	}
1600
1601	fn reschedule_named(
1602		id: TaskName,
1603		when: DispatchTime<BlockNumberFor<T>>,
1604	) -> Result<Self::Address, DispatchError> {
1605		Self::do_reschedule_named(id, when).map_err(map_err_to_v3_err::<T>)
1606	}
1607
1608	fn next_dispatch_time(id: TaskName) -> Result<BlockNumberFor<T>, DispatchError> {
1609		Lookup::<T>::get(id)
1610			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))
1611			.ok_or(DispatchError::Unavailable)
1612	}
1613}
1614
1615/// Maps a pallet error to an `schedule::v3` error.
1616fn map_err_to_v3_err<T: Config>(err: DispatchError) -> DispatchError {
1617	if err == DispatchError::from(Error::<T>::NotFound) {
1618		DispatchError::Unavailable
1619	} else {
1620		err
1621	}
1622}