git.delta.rocks / unique-network / refs/commits / 8b54ea00d9b8

difftreelog

Fmt code style

str-mv2022-03-27parent: #b53b23a.patch.diff
in: master

1 file changed

modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// 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 at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// 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 and16// limitations under the License.1718//! # Scheduler19//! A Pallet for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! This Pallet exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and44//!   with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.46//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter47//!   that can be used for identification.48//! * `cancel_named` - the named complement to the cancel function.4950// Ensure we're `no_std` when compiling for Wasm.51#![cfg_attr(not(feature = "std"), no_std)]5253#[cfg(feature = "runtime-benchmarks")]54mod benchmarking;55#[cfg(test)]56mod mock;57#[cfg(test)]58mod tests;59pub mod weights;6061use codec::{Codec, Decode, Encode};62use frame_support::{63	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},64	traits::{65		schedule::{self, DispatchTime, MaybeHashed}, NamedReservableCurrency,66		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion,67	},68	weights::{GetDispatchInfo, Weight},69};70use frame_system::{self as system, ensure_signed};71pub use pallet::*;72use scale_info::TypeInfo;73use sp_runtime::{74	traits::{BadOrigin, One, Saturating, Zero},75	RuntimeDebug,76	DispatchErrorWithPostInfo,77};78use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};79use sp_core::H160;80pub use weights::WeightInfo;8182/// Just a simple index for naming period tasks.83pub type PeriodicIndex = u32;84/// The location of a scheduled task that can be used to remove it.85pub type TaskAddress<BlockNumber> = (BlockNumber, u32);86pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;8788type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];89pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;9091/// Information regarding an item to be executed in the future.92#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]93#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]94pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {95	/// The unique identity for this task, if there is one.96	maybe_id: Option<ScheduledId>,97	/// This task's priority.98	priority: schedule::Priority,99	/// The call to be dispatched.100	call: Call,101	/// If the call is periodic, then this points to the information concerning that.102	maybe_periodic: Option<schedule::Period<BlockNumber>>,103	/// The origin to dispatch the call.104	origin: PalletsOrigin,105	_phantom: PhantomData<AccountId>,106}107108pub type ScheduledV3Of<T> = ScheduledV3<109	CallOrHashOf<T>,110	<T as frame_system::Config>::BlockNumber,111	<T as Config>::PalletsOrigin,112	<T as frame_system::Config>::AccountId,113>;114115pub type ScheduledOf<T> = ScheduledV3Of<T>;116117/// The current version of Scheduled struct.118pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =119	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;120121#[cfg(feature = "runtime-benchmarks")]122mod preimage_provider {123	use frame_support::traits::PreimageRecipient;124	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}125	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}126}127128#[cfg(not(feature = "runtime-benchmarks"))]129mod preimage_provider {130	use frame_support::traits::PreimageProvider;131	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}132	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}133}134135pub use preimage_provider::PreimageProviderAndMaybeRecipient;136137pub(crate) trait MarginalWeightInfo: WeightInfo {138	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {139		match (periodic, named, resolved) {140			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),141			(_, true, None) =>142				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1),143			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),144			(false, true, Some(false)) =>145				Self::on_initialize_named(2) - Self::on_initialize_named(1),146			(true, false, Some(false)) =>147				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1),148			(true, true, Some(false)) =>149				Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1),150			(false, false, Some(true)) =>151				Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1),152			(false, true, Some(true)) =>153				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1),154			(true, false, Some(true)) =>155				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1),156			(true, true, Some(true)) =>157				Self::on_initialize_periodic_named_resolved(2) -158					Self::on_initialize_periodic_named_resolved(1),159		}160	}161}162impl<T: WeightInfo> MarginalWeightInfo for T {}163164#[frame_support::pallet]165pub mod pallet {166	use super::*;167	use frame_support::{168		dispatch::PostDispatchInfo,169		pallet_prelude::*,170		traits::{schedule::LookupError, PreimageProvider},171	};172	use frame_system::pallet_prelude::*;173174	/// The current storage version.175	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);176177	#[pallet::pallet]178	#[pallet::generate_store(pub(super) trait Store)]179	#[pallet::storage_version(STORAGE_VERSION)]180	#[pallet::without_storage_info]181	pub struct Pallet<T>(_);182183	/// `system::Config` should always be included in our implied traits.184	#[pallet::config]185	pub trait Config: frame_system::Config {186		/// The overarching event type.187		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;188189		/// The aggregated origin which the dispatch will take.190		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>191			+ From<Self::PalletsOrigin>192			+ IsType<<Self as system::Config>::Origin>;193194		/// The caller origin, overarching type of all pallets origins.195		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;196197		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;198199		/// The aggregated call type.200		type Call: Parameter201			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>202			+ GetDispatchInfo203			+ From<system::Call<Self>>;204205		/// The maximum weight that may be scheduled per block for any dispatchables of less206		/// priority than `schedule::HARD_DEADLINE`.207		#[pallet::constant]208		type MaximumWeight: Get<Weight>;209210		/// Required origin to schedule or cancel calls.211		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;212213		/// Compare the privileges of origins.214		///215		/// This will be used when canceling a task, to ensure that the origin that tries216		/// to cancel has greater or equal privileges as the origin that created the scheduled task.217		///218		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can219		/// be used. This will only check if two given origins are equal.220		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;221222		/// The maximum number of scheduled calls in the queue for a single block.223		/// Not strictly enforced, but used for weight estimation.224		#[pallet::constant]225		type MaxScheduledPerBlock: Get<u32>;226227		/// Weight information for extrinsics in this pallet.228		type WeightInfo: WeightInfo;229230		/// The preimage provider with which we look up call hashes to get the call.231		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;232233		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.234		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;235236		/// Sponsoring function.237		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;238239		/// The helper type used for custom transaction fee logic.240		type CallExecutor: DispatchCall<Self, H160>;		241	}242243	/// A Scheduler-Runtime interface for finer payment handling.244	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {245246		fn reserve_balance(247			id: ScheduledId,248			sponsor: <T as frame_system::Config>::AccountId,249			call: <T as Config>::Call,250			count: u32,251		) -> Result<(), DispatchError>;252253		fn pay_for_call(254			id: ScheduledId,255			sponsor: <T as frame_system::Config>::AccountId,256			call: <T as Config>::Call,257		) -> Result<u128, DispatchError>;258259		/// Resolve the call dispatch, including any post-dispatch operations.260		fn dispatch_call(261			signer: T::AccountId,262			function: <T as Config>::Call,263		) -> Result<264			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,265			TransactionValidityError,266		>;267268		fn cancel_reserve(269			id: ScheduledId,270			sponsor: <T as frame_system::Config>::AccountId,271		) -> Result<u128, DispatchError>;272	}273274	/// Items to be executed, indexed by the block number that they should be executed on.275	#[pallet::storage]276	pub type Agenda<T: Config> =277		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;278279	/// Lookup from identity to the block number and index of the task.280	#[pallet::storage]281	pub(crate) type Lookup<T: Config> =282		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;283284	/// Events type.285	#[pallet::event]286	#[pallet::generate_deposit(pub(super) fn deposit_event)]287	pub enum Event<T: Config> {288		/// Scheduled some task.289		Scheduled { when: T::BlockNumber, index: u32 },290		/// Canceled some task.291		Canceled { when: T::BlockNumber, index: u32 },292		/// Dispatched some task.293		Dispatched {294			task: TaskAddress<T::BlockNumber>,295			id: Option<ScheduledId>,296			result: DispatchResult,297		},298		/// The call for the provided hash was not found so the task has been aborted.299		CallLookupFailed {300			task: TaskAddress<T::BlockNumber>,301			id: Option<ScheduledId>,302			error: LookupError,303		},304	}305306	#[pallet::error]307	pub enum Error<T> {308		/// Failed to schedule a call309		FailedToSchedule,310		/// Cannot find the scheduled call.311		NotFound,312		/// Given target block number is in the past.313		TargetBlockNumberInPast,314		/// Reschedule failed because it does not change scheduled time.315		RescheduleNoChange,316	}317318	#[pallet::hooks]319	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {320		/// Execute the scheduled calls321		fn on_initialize(now: T::BlockNumber) -> Weight {322			let limit = T::MaximumWeight::get();323324			let mut queued = Agenda::<T>::take(now)325				.into_iter()326				.enumerate()327				.filter_map(|(index, s)| Some((index as u32, s?)))328				.collect::<Vec<_>>();329330			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {331				log::warn!(332					target: "runtime::scheduler",333					"Warning: This block has more items queued in Scheduler than \334					expected from the runtime configuration. An update might be needed."335				);336			}337338			queued.sort_by_key(|(_, s)| s.priority);339340			let next = now + One::one();341342			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);343			for (order, (index, mut s)) in queued.into_iter().enumerate() {344				let named = if let Some(ref id) = s.maybe_id {345					Lookup::<T>::remove(id);346					true347				} else {348					false349				};350351				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();352				s.call = call;353354				let resolved = if let Some(completed) = maybe_completed {355					T::PreimageProvider::unrequest_preimage(&completed);356					true357				} else {358					false359				};360361				let call = match s.call.as_value().cloned() {362					Some(c) => c,363					None => {364						// Preimage not available - postpone until some block.365						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));366						if let Some(delay) = T::NoPreimagePostponement::get() {367							let until = now.saturating_add(delay);368							if let Some(ref id) = s.maybe_id {369								let index = Agenda::<T>::decode_len(until).unwrap_or(0);370								Lookup::<T>::insert(id, (until, index as u32));371							}372							Agenda::<T>::append(until, Some(s));373						}374						continue375					},376				};377378				let periodic = s.maybe_periodic.is_some();379				let call_weight = call.get_dispatch_info().weight;380				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));381				let origin =382					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())383						.into();384				if ensure_signed(origin).is_ok() {385					// Weights of Signed dispatches expect their signing account to be whitelisted.386					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));387				}388389				// We allow a scheduled call if any is true:390				// - It's priority is `HARD_DEADLINE`391				// - It does not push the weight past the limit.392				// - It is the first item in the schedule393				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;394				let test_weight =395					total_weight.saturating_add(call_weight).saturating_add(item_weight);396				if !hard_deadline && order > 0 && test_weight > limit {397					// Cannot be scheduled this block - postpone until next.398					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));399					if let Some(ref id) = s.maybe_id {400						// NOTE: We could reasonably not do this (in which case there would be one401						// block where the named and delayed item could not be referenced by name),402						// but we will do it anyway since it should be mostly free in terms of403						// weight and it is slightly cleaner.404						let index = Agenda::<T>::decode_len(next).unwrap_or(0);405						Lookup::<T>::insert(id, (next, index as u32));406					}407					Agenda::<T>::append(next, Some(s));408					continue409				}410411				let sender = ensure_signed(412					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone()).into(),413				).unwrap();414415				// if call have id and periodic, it was be reserved 416				if s.maybe_id.is_some() && s.maybe_periodic.is_some()417				{418					let _ = T::CallExecutor::pay_for_call(419						s.maybe_id.unwrap(),420						sender.clone(),421						call.clone(),422					);423				}				424425				let r = T::CallExecutor::dispatch_call(sender, call.clone());426427				let mut actual_call_weight: Weight = item_weight; //PostDispatchInfo;428				let result: Result<_, DispatchError> = match r {429					Ok(o) => { match o {430						Ok(di) => {431							actual_call_weight = di.actual_weight.unwrap_or(item_weight);432							Ok(())433						},434						Err(err) => Err(err.error),435					}},436					Err(_) => { 437						log::info!(438							target: "runtime::scheduler",439							"Warning: Scheduler has failed to execute a post-dispatch transaction. \440							This block might have become invalid.");441						Err(DispatchError::CannotLookup)442					}443					// todo possibly force a skip/return here, do something with the error444				};				445446				total_weight.saturating_accrue(item_weight);447				total_weight.saturating_accrue(actual_call_weight);448449				Self::deposit_event(Event::Dispatched {450					task: (now, index),451					id: s.maybe_id.clone(),452					result,453				});454455				if let &Some((period, count)) = &s.maybe_periodic {456					if count > 1 {457						s.maybe_periodic = Some((period, count - 1));458					} else {459						s.maybe_periodic = None;460					}461					let wake = now + period;462					// If scheduled is named, place its information in `Lookup`463					if let Some(ref id) = s.maybe_id {464						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);465						Lookup::<T>::insert(id, (wake, wake_index as u32));466					}467					Agenda::<T>::append(wake, Some(s));468				}469			}470			total_weight471		}472	}473474	#[pallet::call]475	impl<T: Config> Pallet<T> {476		/// Anonymously schedule a task.477		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]478		pub fn schedule(479			origin: OriginFor<T>,480			when: T::BlockNumber,481			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,482			priority: schedule::Priority,483			call: Box<CallOrHashOf<T>>,484		) -> DispatchResult {485			T::ScheduleOrigin::ensure_origin(origin.clone())?;486			let origin = <T as Config>::Origin::from(origin);487			Self::do_schedule(488				DispatchTime::At(when),489				maybe_periodic,490				priority,491				origin.caller().clone(),492				*call,493			)?;494			Ok(())495		}496497		/// Cancel an anonymously scheduled task.498		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]499		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {500			T::ScheduleOrigin::ensure_origin(origin.clone())?;501			let origin = <T as Config>::Origin::from(origin);502			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;503			Ok(())504		}505506		/// Schedule a named task.507		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]508		pub fn schedule_named(509			origin: OriginFor<T>,510			id: ScheduledId,511			when: T::BlockNumber,512			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,513			priority: schedule::Priority,514			call: Box<CallOrHashOf<T>>,515		) -> DispatchResult {516			T::ScheduleOrigin::ensure_origin(origin.clone())?;517			let origin = <T as Config>::Origin::from(origin);518			Self::do_schedule_named(519				id,520				DispatchTime::At(when),521				maybe_periodic,522				priority,523				origin.caller().clone(),524				*call,525			)?;526			Ok(())527		}528529		/// Cancel a named scheduled task.530		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]531		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {532			T::ScheduleOrigin::ensure_origin(origin.clone())?;533			let origin = <T as Config>::Origin::from(origin);534			Self::do_cancel_named(Some(origin.caller().clone()), id)?;535			Ok(())536		}537538		/// Anonymously schedule a task after a delay.539		///540		/// # <weight>541		/// Same as [`schedule`].542		/// # </weight>543		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]544		pub fn schedule_after(545			origin: OriginFor<T>,546			after: T::BlockNumber,547			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,548			priority: schedule::Priority,549			call: Box<CallOrHashOf<T>>,550		) -> DispatchResult {551			T::ScheduleOrigin::ensure_origin(origin.clone())?;552			let origin = <T as Config>::Origin::from(origin);553			Self::do_schedule(554				DispatchTime::After(after),555				maybe_periodic,556				priority,557				origin.caller().clone(),558				*call,559			)?;560			Ok(())561		}562563		/// Schedule a named task after a delay.564		///565		/// # <weight>566		/// Same as [`schedule_named`](Self::schedule_named).567		/// # </weight>568		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]569		pub fn schedule_named_after(570			origin: OriginFor<T>,571			id: ScheduledId,572			after: T::BlockNumber,573			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,574			priority: schedule::Priority,575			call: Box<CallOrHashOf<T>>,576		) -> DispatchResult {577			T::ScheduleOrigin::ensure_origin(origin.clone())?;578			let origin = <T as Config>::Origin::from(origin);579			Self::do_schedule_named(580				id,581				DispatchTime::After(after),582				maybe_periodic,583				priority,584				origin.caller().clone(),585				*call,586			)?;587			Ok(())588		}589	}590}591592impl<T: Config> Pallet<T> {593594	#[cfg(feature = "try-runtime")]595	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {596		Ok(())597	}598599	#[cfg(feature = "try-runtime")]600	pub fn post_migrate_to_v3() -> Result<(), &'static str> {601		use frame_support::dispatch::GetStorageVersion;602603		assert!(Self::current_storage_version() == 3);604		for k in Agenda::<T>::iter_keys() {605			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;606		}607		Ok(())608	}609610	/// Helper to migrate scheduler when the pallet origin type has changed.611	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {612		Agenda::<T>::translate::<613			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,614			_,615		>(|_, agenda| {616			Some(617				agenda618					.into_iter()619					.map(|schedule| {620						schedule.map(|schedule| Scheduled {621							maybe_id: schedule.maybe_id,622							priority: schedule.priority,623							call: schedule.call,624							maybe_periodic: schedule.maybe_periodic,625							origin: schedule.origin.into(),626							_phantom: Default::default(),627						})628					})629					.collect::<Vec<_>>(),630			)631		});632	}633634	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {635		let now = frame_system::Pallet::<T>::block_number();636637		let when = match when {638			DispatchTime::At(x) => x,639			// The current block has already completed it's scheduled tasks, so640			// Schedule the task at lest one block after this current block.641			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),642		};643644		if when <= now {645			return Err(Error::<T>::TargetBlockNumberInPast.into())646		}647648		Ok(when)649	}650651	fn do_schedule(652		when: DispatchTime<T::BlockNumber>,653		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,654		priority: schedule::Priority,655		origin: T::PalletsOrigin,656		call: CallOrHashOf<T>,657	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {658		let when = Self::resolve_time(when)?;659		call.ensure_requested::<T::PreimageProvider>();660661		// sanitize maybe_periodic662		let maybe_periodic = maybe_periodic663			.filter(|p| p.1 > 1 && !p.0.is_zero())664			// Remove one from the number of repetitions since we will schedule one now.665			.map(|(p, c)| (p, c - 1));666		let s = Some(Scheduled {667			maybe_id: None,668			priority,669			call,670			maybe_periodic,671			origin,672			_phantom: PhantomData::<T::AccountId>::default(),673		});674		Agenda::<T>::append(when, s);675		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;676		Self::deposit_event(Event::Scheduled { when, index });677678		Ok((when, index))679	}680681	fn do_cancel(682		origin: Option<T::PalletsOrigin>,683		(when, index): TaskAddress<T::BlockNumber>,684	) -> Result<(), DispatchError> {685		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {686			agenda.get_mut(index as usize).map_or(687				Ok(None),688				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {689					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {690						if matches!(691							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),692							Some(Ordering::Less) | None693						) {694							return Err(BadOrigin.into())695						}696					};697					Ok(s.take())698				},699			)700		})?;701		if let Some(s) = scheduled {702			s.call.ensure_unrequested::<T::PreimageProvider>();703			if let Some(id) = s.maybe_id {704				Lookup::<T>::remove(id);705			}706			Self::deposit_event(Event::Canceled { when, index });707			Ok(())708		} else {709			Err(Error::<T>::NotFound)?710		}711	}712713	fn do_reschedule(714		(when, index): TaskAddress<T::BlockNumber>,715		new_time: DispatchTime<T::BlockNumber>,716	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {717		let new_time = Self::resolve_time(new_time)?;718719		if new_time == when {720			return Err(Error::<T>::RescheduleNoChange.into())721		}722723		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {724			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;725			let task = task.take().ok_or(Error::<T>::NotFound)?;726			Agenda::<T>::append(new_time, Some(task));727			Ok(())728		})?;729730		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;731		Self::deposit_event(Event::Canceled { when, index });732		Self::deposit_event(Event::Scheduled { when: new_time, index: new_index });733734		Ok((new_time, new_index))735	}736737	fn do_schedule_named(738		id: ScheduledId,739		when: DispatchTime<T::BlockNumber>,740		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,741		priority: schedule::Priority,742		origin: T::PalletsOrigin,743		call: CallOrHashOf<T>,744	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {745		// ensure id it is unique746		if Lookup::<T>::contains_key(&id) {747			return Err(Error::<T>::FailedToSchedule)?748		}749750		let when = Self::resolve_time(when)?;751752		call.ensure_requested::<T::PreimageProvider>();753754		// sanitize maybe_periodic755		let maybe_periodic = maybe_periodic756			.filter(|p| p.1 > 1 && !p.0.is_zero())757			// Remove one from the number of repetitions since we will schedule one now.758			.map(|(p, c)| (p, c - 1));759760		let s = Scheduled {761			maybe_id: Some(id.clone()),762			priority,763			call: call.clone(),764			maybe_periodic,765			origin: origin.clone(),766			_phantom: Default::default(),767		};768769		// reserve balance for periodic execution 		770		let sender = ensure_signed(771			<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into(),772		)?;773		let repeats = match maybe_periodic {774			Some(p) => p.1,775			None => 0,776		};777		let _ = T::CallExecutor::reserve_balance(id.clone(), sender, call.as_value().unwrap().clone(), repeats);	778779		Agenda::<T>::append(when, Some(s));780		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;781		let address = (when, index);782		Lookup::<T>::insert(&id, &address);783		Self::deposit_event(Event::Scheduled { when, index });784785		Ok(address)786	}787788	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {789		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {790			if let Some((when, index)) = lookup.take() {791				let i = index as usize;792				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {793					if let Some(s) = agenda.get_mut(i) {794						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {795							if matches!(796								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),797								Some(Ordering::Less) | None798							) {799								return Err(BadOrigin.into())800							}801							// release balance reserve802							let sender = ensure_signed(803								<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.unwrap()).into(),804							)?;805							let _ = T::CallExecutor::cancel_reserve(id, sender);806807							s.call.ensure_unrequested::<T::PreimageProvider>();808						}809						*s = None;810					}811					Ok(())812				})?;813814				Self::deposit_event(Event::Canceled { when, index });815				Ok(())816			} else {817				Err(Error::<T>::NotFound)?818			}819		})820	}821822	fn do_reschedule_named(823		id: ScheduledId,824		new_time: DispatchTime<T::BlockNumber>,825	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {826		let new_time = Self::resolve_time(new_time)?;827828		Lookup::<T>::try_mutate_exists(829			id,830			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {831				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;832833				if new_time == when {834					return Err(Error::<T>::RescheduleNoChange.into())835				}836837				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {838					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;839					let task = task.take().ok_or(Error::<T>::NotFound)?;840					Agenda::<T>::append(new_time, Some(task));841842					Ok(())843				})?;844845				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;846				Self::deposit_event(Event::Canceled { when, index });847				Self::deposit_event(Event::Scheduled { when: new_time, index: new_index });848849				*lookup = Some((new_time, new_index));850851				Ok((new_time, new_index))852			},853		)854	}855}856857impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>858	for Pallet<T>859{860	type Address = TaskAddress<T::BlockNumber>;861	type Hash = T::Hash;862863	fn schedule(864		when: DispatchTime<T::BlockNumber>,865		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,866		priority: schedule::Priority,867		origin: T::PalletsOrigin,868		call: CallOrHashOf<T>,869	) -> Result<Self::Address, DispatchError> {870		Self::do_schedule(when, maybe_periodic, priority, origin, call)871	}872873	fn cancel((when, index): Self::Address) -> Result<(), ()> {874		Self::do_cancel(None, (when, index)).map_err(|_| ())875	}876877	fn reschedule(878		address: Self::Address,879		when: DispatchTime<T::BlockNumber>,880	) -> Result<Self::Address, DispatchError> {881		Self::do_reschedule(address, when)882	}883884	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {885		Agenda::<T>::get(when).get(index as usize).ok_or(()).map(|_| when)886	}887}888889impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>890	for Pallet<T>891{892	type Address = TaskAddress<T::BlockNumber>;893	type Hash = T::Hash;894895	fn schedule_named(896		id: Vec<u8>,897		when: DispatchTime<T::BlockNumber>,898		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,899		priority: schedule::Priority,900		origin: T::PalletsOrigin,901		call: CallOrHashOf<T>,902	) -> Result<Self::Address, ()> {903		let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);904		Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call).map_err(|_| ())905	}906907	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {908		let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);909		Self::do_cancel_named(None, inner_id).map_err(|_| ())910	}911912	fn reschedule_named(913		id: Vec<u8>,914		when: DispatchTime<T::BlockNumber>,915	) -> Result<Self::Address, DispatchError> {916		let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);917		Self::do_reschedule_named(inner_id, when)918	}919920	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {921		let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);922		Lookup::<T>::get(inner_id)923			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))924			.ok_or(())925	}926}
after · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// 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 at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// 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 and16// limitations under the License.1718//! # Scheduler19//! A Pallet for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! This Pallet exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and44//!   with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.46//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter47//!   that can be used for identification.48//! * `cancel_named` - the named complement to the cancel function.4950// Ensure we're `no_std` when compiling for Wasm.51#![cfg_attr(not(feature = "std"), no_std)]5253#[cfg(feature = "runtime-benchmarks")]54mod benchmarking;5556pub mod weights;5758use codec::{Codec, Decode, Encode};59use frame_support::{60	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},61	traits::{62		schedule::{self, DispatchTime, MaybeHashed},63		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,64		StorageVersion,65	},66	weights::{GetDispatchInfo, Weight},67};68use frame_system::{self as system, ensure_signed};69pub use pallet::*;70use scale_info::TypeInfo;71use sp_runtime::{72	traits::{BadOrigin, One, Saturating, Zero},73	RuntimeDebug, DispatchErrorWithPostInfo,74};75use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};76use sp_core::H160;77pub use weights::WeightInfo;7879/// Just a simple index for naming period tasks.80pub type PeriodicIndex = u32;81/// The location of a scheduled task that can be used to remove it.82pub type TaskAddress<BlockNumber> = (BlockNumber, u32);83pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;8485type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];86pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;8788/// Information regarding an item to be executed in the future.89#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]90#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]91pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {92	/// The unique identity for this task, if there is one.93	maybe_id: Option<ScheduledId>,94	/// This task's priority.95	priority: schedule::Priority,96	/// The call to be dispatched.97	call: Call,98	/// If the call is periodic, then this points to the information concerning that.99	maybe_periodic: Option<schedule::Period<BlockNumber>>,100	/// The origin to dispatch the call.101	origin: PalletsOrigin,102	_phantom: PhantomData<AccountId>,103}104105pub type ScheduledV3Of<T> = ScheduledV3<106	CallOrHashOf<T>,107	<T as frame_system::Config>::BlockNumber,108	<T as Config>::PalletsOrigin,109	<T as frame_system::Config>::AccountId,110>;111112pub type ScheduledOf<T> = ScheduledV3Of<T>;113114/// The current version of Scheduled struct.115pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =116	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;117118#[cfg(feature = "runtime-benchmarks")]119mod preimage_provider {120	use frame_support::traits::PreimageRecipient;121	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}122	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}123}124125#[cfg(not(feature = "runtime-benchmarks"))]126mod preimage_provider {127	use frame_support::traits::PreimageProvider;128	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}129	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}130}131132pub use preimage_provider::PreimageProviderAndMaybeRecipient;133134pub(crate) trait MarginalWeightInfo: WeightInfo {135	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {136		match (periodic, named, resolved) {137			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),138			(_, true, None) => {139				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)140			}141			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),142			(false, true, Some(false)) => {143				Self::on_initialize_named(2) - Self::on_initialize_named(1)144			}145			(true, false, Some(false)) => {146				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)147			}148			(true, true, Some(false)) => {149				Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)150			}151			(false, false, Some(true)) => {152				Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)153			}154			(false, true, Some(true)) => {155				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)156			}157			(true, false, Some(true)) => {158				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)159			}160			(true, true, Some(true)) => {161				Self::on_initialize_periodic_named_resolved(2)162					- Self::on_initialize_periodic_named_resolved(1)163			}164		}165	}166}167impl<T: WeightInfo> MarginalWeightInfo for T {}168169#[frame_support::pallet]170pub mod pallet {171	use super::*;172	use frame_support::{173		dispatch::PostDispatchInfo,174		pallet_prelude::*,175		traits::{schedule::LookupError, PreimageProvider},176	};177	use frame_system::pallet_prelude::*;178179	/// The current storage version.180	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);181182	#[pallet::pallet]183	#[pallet::generate_store(pub(super) trait Store)]184	#[pallet::storage_version(STORAGE_VERSION)]185	#[pallet::without_storage_info]186	pub struct Pallet<T>(_);187188	/// `system::Config` should always be included in our implied traits.189	#[pallet::config]190	pub trait Config: frame_system::Config {191		/// The overarching event type.192		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;193194		/// The aggregated origin which the dispatch will take.195		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>196			+ From<Self::PalletsOrigin>197			+ IsType<<Self as system::Config>::Origin>;198199		/// The caller origin, overarching type of all pallets origins.200		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;201202		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;203204		/// The aggregated call type.205		type Call: Parameter206			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>207			+ GetDispatchInfo208			+ From<system::Call<Self>>;209210		/// The maximum weight that may be scheduled per block for any dispatchables of less211		/// priority than `schedule::HARD_DEADLINE`.212		#[pallet::constant]213		type MaximumWeight: Get<Weight>;214215		/// Required origin to schedule or cancel calls.216		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;217218		/// Compare the privileges of origins.219		///220		/// This will be used when canceling a task, to ensure that the origin that tries221		/// to cancel has greater or equal privileges as the origin that created the scheduled task.222		///223		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can224		/// be used. This will only check if two given origins are equal.225		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;226227		/// The maximum number of scheduled calls in the queue for a single block.228		/// Not strictly enforced, but used for weight estimation.229		#[pallet::constant]230		type MaxScheduledPerBlock: Get<u32>;231232		/// Weight information for extrinsics in this pallet.233		type WeightInfo: WeightInfo;234235		/// The preimage provider with which we look up call hashes to get the call.236		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;237238		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.239		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;240241		/// Sponsoring function.242		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;243244		/// The helper type used for custom transaction fee logic.245		type CallExecutor: DispatchCall<Self, H160>;246	}247248	/// A Scheduler-Runtime interface for finer payment handling.249	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {250		fn reserve_balance(251			id: ScheduledId,252			sponsor: <T as frame_system::Config>::AccountId,253			call: <T as Config>::Call,254			count: u32,255		) -> Result<(), DispatchError>;256257		fn pay_for_call(258			id: ScheduledId,259			sponsor: <T as frame_system::Config>::AccountId,260			call: <T as Config>::Call,261		) -> Result<u128, DispatchError>;262263		/// Resolve the call dispatch, including any post-dispatch operations.264		fn dispatch_call(265			signer: T::AccountId,266			function: <T as Config>::Call,267		) -> Result<268			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,269			TransactionValidityError,270		>;271272		fn cancel_reserve(273			id: ScheduledId,274			sponsor: <T as frame_system::Config>::AccountId,275		) -> Result<u128, DispatchError>;276	}277278	/// Items to be executed, indexed by the block number that they should be executed on.279	#[pallet::storage]280	pub type Agenda<T: Config> =281		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;282283	/// Lookup from identity to the block number and index of the task.284	#[pallet::storage]285	pub(crate) type Lookup<T: Config> =286		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;287288	/// Events type.289	#[pallet::event]290	#[pallet::generate_deposit(pub(super) fn deposit_event)]291	pub enum Event<T: Config> {292		/// Scheduled some task.293		Scheduled { when: T::BlockNumber, index: u32 },294		/// Canceled some task.295		Canceled { when: T::BlockNumber, index: u32 },296		/// Dispatched some task.297		Dispatched {298			task: TaskAddress<T::BlockNumber>,299			id: Option<ScheduledId>,300			result: DispatchResult,301		},302		/// The call for the provided hash was not found so the task has been aborted.303		CallLookupFailed {304			task: TaskAddress<T::BlockNumber>,305			id: Option<ScheduledId>,306			error: LookupError,307		},308	}309310	#[pallet::error]311	pub enum Error<T> {312		/// Failed to schedule a call313		FailedToSchedule,314		/// Cannot find the scheduled call.315		NotFound,316		/// Given target block number is in the past.317		TargetBlockNumberInPast,318		/// Reschedule failed because it does not change scheduled time.319		RescheduleNoChange,320	}321322	#[pallet::hooks]323	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {324		/// Execute the scheduled calls325		fn on_initialize(now: T::BlockNumber) -> Weight {326			let limit = T::MaximumWeight::get();327328			let mut queued = Agenda::<T>::take(now)329				.into_iter()330				.enumerate()331				.filter_map(|(index, s)| Some((index as u32, s?)))332				.collect::<Vec<_>>();333334			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {335				log::warn!(336					target: "runtime::scheduler",337					"Warning: This block has more items queued in Scheduler than \338					expected from the runtime configuration. An update might be needed."339				);340			}341342			queued.sort_by_key(|(_, s)| s.priority);343344			let next = now + One::one();345346			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);347			for (order, (index, mut s)) in queued.into_iter().enumerate() {348				let named = if let Some(ref id) = s.maybe_id {349					Lookup::<T>::remove(id);350					true351				} else {352					false353				};354355				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();356				s.call = call;357358				let resolved = if let Some(completed) = maybe_completed {359					T::PreimageProvider::unrequest_preimage(&completed);360					true361				} else {362					false363				};364365				let call = match s.call.as_value().cloned() {366					Some(c) => c,367					None => {368						// Preimage not available - postpone until some block.369						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));370						if let Some(delay) = T::NoPreimagePostponement::get() {371							let until = now.saturating_add(delay);372							if let Some(ref id) = s.maybe_id {373								let index = Agenda::<T>::decode_len(until).unwrap_or(0);374								Lookup::<T>::insert(id, (until, index as u32));375							}376							Agenda::<T>::append(until, Some(s));377						}378						continue;379					}380				};381382				let periodic = s.maybe_periodic.is_some();383				let call_weight = call.get_dispatch_info().weight;384				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));385				let origin =386					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())387						.into();388				if ensure_signed(origin).is_ok() {389					// Weights of Signed dispatches expect their signing account to be whitelisted.390					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));391				}392393				// We allow a scheduled call if any is true:394				// - It's priority is `HARD_DEADLINE`395				// - It does not push the weight past the limit.396				// - It is the first item in the schedule397				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;398				let test_weight = total_weight399					.saturating_add(call_weight)400					.saturating_add(item_weight);401				if !hard_deadline && order > 0 && test_weight > limit {402					// Cannot be scheduled this block - postpone until next.403					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));404					if let Some(ref id) = s.maybe_id {405						// NOTE: We could reasonably not do this (in which case there would be one406						// block where the named and delayed item could not be referenced by name),407						// but we will do it anyway since it should be mostly free in terms of408						// weight and it is slightly cleaner.409						let index = Agenda::<T>::decode_len(next).unwrap_or(0);410						Lookup::<T>::insert(id, (next, index as u32));411					}412					Agenda::<T>::append(next, Some(s));413					continue;414				}415416				let sender = ensure_signed(417					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())418						.into(),419				)420				.unwrap();421422				// if call have id and periodic, it was be reserved423				if s.maybe_id.is_some() && s.maybe_periodic.is_some() {424					let _ = T::CallExecutor::pay_for_call(425						s.maybe_id.unwrap(),426						sender.clone(),427						call.clone(),428					);429				}430431				let r = T::CallExecutor::dispatch_call(sender, call.clone());432433				let mut actual_call_weight: Weight = item_weight; //PostDispatchInfo;434				let result: Result<_, DispatchError> = match r {435					Ok(o) => match o {436						Ok(di) => {437							actual_call_weight = di.actual_weight.unwrap_or(item_weight);438							Ok(())439						}440						Err(err) => Err(err.error),441					},442					Err(_) => {443						log::info!(444							target: "runtime::scheduler",445							"Warning: Scheduler has failed to execute a post-dispatch transaction. \446							This block might have become invalid.");447						Err(DispatchError::CannotLookup)448					} // todo possibly force a skip/return here, do something with the error449				};450451				total_weight.saturating_accrue(item_weight);452				total_weight.saturating_accrue(actual_call_weight);453454				Self::deposit_event(Event::Dispatched {455					task: (now, index),456					id: s.maybe_id.clone(),457					result,458				});459460				if let &Some((period, count)) = &s.maybe_periodic {461					if count > 1 {462						s.maybe_periodic = Some((period, count - 1));463					} else {464						s.maybe_periodic = None;465					}466					let wake = now + period;467					// If scheduled is named, place its information in `Lookup`468					if let Some(ref id) = s.maybe_id {469						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);470						Lookup::<T>::insert(id, (wake, wake_index as u32));471					}472					Agenda::<T>::append(wake, Some(s));473				}474			}475			total_weight476		}477	}478479	#[pallet::call]480	impl<T: Config> Pallet<T> {481		/// Anonymously schedule a task.482		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]483		pub fn schedule(484			origin: OriginFor<T>,485			when: T::BlockNumber,486			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,487			priority: schedule::Priority,488			call: Box<CallOrHashOf<T>>,489		) -> DispatchResult {490			T::ScheduleOrigin::ensure_origin(origin.clone())?;491			let origin = <T as Config>::Origin::from(origin);492			Self::do_schedule(493				DispatchTime::At(when),494				maybe_periodic,495				priority,496				origin.caller().clone(),497				*call,498			)?;499			Ok(())500		}501502		/// Cancel an anonymously scheduled task.503		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]504		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {505			T::ScheduleOrigin::ensure_origin(origin.clone())?;506			let origin = <T as Config>::Origin::from(origin);507			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;508			Ok(())509		}510511		/// Schedule a named task.512		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]513		pub fn schedule_named(514			origin: OriginFor<T>,515			id: ScheduledId,516			when: T::BlockNumber,517			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,518			priority: schedule::Priority,519			call: Box<CallOrHashOf<T>>,520		) -> DispatchResult {521			T::ScheduleOrigin::ensure_origin(origin.clone())?;522			let origin = <T as Config>::Origin::from(origin);523			Self::do_schedule_named(524				id,525				DispatchTime::At(when),526				maybe_periodic,527				priority,528				origin.caller().clone(),529				*call,530			)?;531			Ok(())532		}533534		/// Cancel a named scheduled task.535		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]536		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {537			T::ScheduleOrigin::ensure_origin(origin.clone())?;538			let origin = <T as Config>::Origin::from(origin);539			Self::do_cancel_named(Some(origin.caller().clone()), id)?;540			Ok(())541		}542543		/// Anonymously schedule a task after a delay.544		///545		/// # <weight>546		/// Same as [`schedule`].547		/// # </weight>548		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]549		pub fn schedule_after(550			origin: OriginFor<T>,551			after: T::BlockNumber,552			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,553			priority: schedule::Priority,554			call: Box<CallOrHashOf<T>>,555		) -> DispatchResult {556			T::ScheduleOrigin::ensure_origin(origin.clone())?;557			let origin = <T as Config>::Origin::from(origin);558			Self::do_schedule(559				DispatchTime::After(after),560				maybe_periodic,561				priority,562				origin.caller().clone(),563				*call,564			)?;565			Ok(())566		}567568		/// Schedule a named task after a delay.569		///570		/// # <weight>571		/// Same as [`schedule_named`](Self::schedule_named).572		/// # </weight>573		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]574		pub fn schedule_named_after(575			origin: OriginFor<T>,576			id: ScheduledId,577			after: T::BlockNumber,578			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,579			priority: schedule::Priority,580			call: Box<CallOrHashOf<T>>,581		) -> DispatchResult {582			T::ScheduleOrigin::ensure_origin(origin.clone())?;583			let origin = <T as Config>::Origin::from(origin);584			Self::do_schedule_named(585				id,586				DispatchTime::After(after),587				maybe_periodic,588				priority,589				origin.caller().clone(),590				*call,591			)?;592			Ok(())593		}594	}595}596597impl<T: Config> Pallet<T> {598	#[cfg(feature = "try-runtime")]599	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {600		Ok(())601	}602603	#[cfg(feature = "try-runtime")]604	pub fn post_migrate_to_v3() -> Result<(), &'static str> {605		use frame_support::dispatch::GetStorageVersion;606607		assert!(Self::current_storage_version() == 3);608		for k in Agenda::<T>::iter_keys() {609			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;610		}611		Ok(())612	}613614	/// Helper to migrate scheduler when the pallet origin type has changed.615	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {616		Agenda::<T>::translate::<617			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,618			_,619		>(|_, agenda| {620			Some(621				agenda622					.into_iter()623					.map(|schedule| {624						schedule.map(|schedule| Scheduled {625							maybe_id: schedule.maybe_id,626							priority: schedule.priority,627							call: schedule.call,628							maybe_periodic: schedule.maybe_periodic,629							origin: schedule.origin.into(),630							_phantom: Default::default(),631						})632					})633					.collect::<Vec<_>>(),634			)635		});636	}637638	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {639		let now = frame_system::Pallet::<T>::block_number();640641		let when = match when {642			DispatchTime::At(x) => x,643			// The current block has already completed it's scheduled tasks, so644			// Schedule the task at lest one block after this current block.645			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),646		};647648		if when <= now {649			return Err(Error::<T>::TargetBlockNumberInPast.into());650		}651652		Ok(when)653	}654655	fn do_schedule(656		when: DispatchTime<T::BlockNumber>,657		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,658		priority: schedule::Priority,659		origin: T::PalletsOrigin,660		call: CallOrHashOf<T>,661	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662		let when = Self::resolve_time(when)?;663		call.ensure_requested::<T::PreimageProvider>();664665		// sanitize maybe_periodic666		let maybe_periodic = maybe_periodic667			.filter(|p| p.1 > 1 && !p.0.is_zero())668			// Remove one from the number of repetitions since we will schedule one now.669			.map(|(p, c)| (p, c - 1));670		let s = Some(Scheduled {671			maybe_id: None,672			priority,673			call,674			maybe_periodic,675			origin,676			_phantom: PhantomData::<T::AccountId>::default(),677		});678		Agenda::<T>::append(when, s);679		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;680		Self::deposit_event(Event::Scheduled { when, index });681682		Ok((when, index))683	}684685	fn do_cancel(686		origin: Option<T::PalletsOrigin>,687		(when, index): TaskAddress<T::BlockNumber>,688	) -> Result<(), DispatchError> {689		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {690			agenda.get_mut(index as usize).map_or(691				Ok(None),692				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {693					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {694						if matches!(695							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),696							Some(Ordering::Less) | None697						) {698							return Err(BadOrigin.into());699						}700					};701					Ok(s.take())702				},703			)704		})?;705		if let Some(s) = scheduled {706			s.call.ensure_unrequested::<T::PreimageProvider>();707			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			Err(Error::<T>::NotFound)?714		}715	}716717	fn do_reschedule(718		(when, index): TaskAddress<T::BlockNumber>,719		new_time: DispatchTime<T::BlockNumber>,720	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {721		let new_time = Self::resolve_time(new_time)?;722723		if new_time == when {724			return Err(Error::<T>::RescheduleNoChange.into());725		}726727		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {728			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;729			let task = task.take().ok_or(Error::<T>::NotFound)?;730			Agenda::<T>::append(new_time, Some(task));731			Ok(())732		})?;733734		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;735		Self::deposit_event(Event::Canceled { when, index });736		Self::deposit_event(Event::Scheduled {737			when: new_time,738			index: new_index,739		});740741		Ok((new_time, new_index))742	}743744	fn do_schedule_named(745		id: ScheduledId,746		when: DispatchTime<T::BlockNumber>,747		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,748		priority: schedule::Priority,749		origin: T::PalletsOrigin,750		call: CallOrHashOf<T>,751	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {752		// ensure id it is unique753		if Lookup::<T>::contains_key(&id) {754			return Err(Error::<T>::FailedToSchedule)?;755		}756757		let when = Self::resolve_time(when)?;758759		call.ensure_requested::<T::PreimageProvider>();760761		// sanitize maybe_periodic762		let maybe_periodic = maybe_periodic763			.filter(|p| p.1 > 1 && !p.0.is_zero())764			// Remove one from the number of repetitions since we will schedule one now.765			.map(|(p, c)| (p, c - 1));766767		let s = Scheduled {768			maybe_id: Some(id.clone()),769			priority,770			call: call.clone(),771			maybe_periodic,772			origin: origin.clone(),773			_phantom: Default::default(),774		};775776		// reserve balance for periodic execution777		let sender =778			ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;779		let repeats = match maybe_periodic {780			Some(p) => p.1,781			None => 0,782		};783		let _ = T::CallExecutor::reserve_balance(784			id.clone(),785			sender,786			call.as_value().unwrap().clone(),787			repeats,788		);789790		Agenda::<T>::append(when, Some(s));791		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;792		let address = (when, index);793		Lookup::<T>::insert(&id, &address);794		Self::deposit_event(Event::Scheduled { when, index });795796		Ok(address)797	}798799	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {800		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {801			if let Some((when, index)) = lookup.take() {802				let i = index as usize;803				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {804					if let Some(s) = agenda.get_mut(i) {805						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {806							if matches!(807								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),808								Some(Ordering::Less) | None809							) {810								return Err(BadOrigin.into());811							}812							// release balance reserve813							let sender = ensure_signed(814								<<T as Config>::Origin as From<T::PalletsOrigin>>::from(815									origin.unwrap(),816								)817								.into(),818							)?;819							let _ = T::CallExecutor::cancel_reserve(id, sender);820821							s.call.ensure_unrequested::<T::PreimageProvider>();822						}823						*s = None;824					}825					Ok(())826				})?;827828				Self::deposit_event(Event::Canceled { when, index });829				Ok(())830			} else {831				Err(Error::<T>::NotFound)?832			}833		})834	}835836	fn do_reschedule_named(837		id: ScheduledId,838		new_time: DispatchTime<T::BlockNumber>,839	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {840		let new_time = Self::resolve_time(new_time)?;841842		Lookup::<T>::try_mutate_exists(843			id,844			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {845				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;846847				if new_time == when {848					return Err(Error::<T>::RescheduleNoChange.into());849				}850851				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {852					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;853					let task = task.take().ok_or(Error::<T>::NotFound)?;854					Agenda::<T>::append(new_time, Some(task));855856					Ok(())857				})?;858859				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;860				Self::deposit_event(Event::Canceled { when, index });861				Self::deposit_event(Event::Scheduled {862					when: new_time,863					index: new_index,864				});865866				*lookup = Some((new_time, new_index));867868				Ok((new_time, new_index))869			},870		)871	}872}873874impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>875	for Pallet<T>876{877	type Address = TaskAddress<T::BlockNumber>;878	type Hash = T::Hash;879880	fn schedule(881		when: DispatchTime<T::BlockNumber>,882		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,883		priority: schedule::Priority,884		origin: T::PalletsOrigin,885		call: CallOrHashOf<T>,886	) -> Result<Self::Address, DispatchError> {887		Self::do_schedule(when, maybe_periodic, priority, origin, call)888	}889890	fn cancel((when, index): Self::Address) -> Result<(), ()> {891		Self::do_cancel(None, (when, index)).map_err(|_| ())892	}893894	fn reschedule(895		address: Self::Address,896		when: DispatchTime<T::BlockNumber>,897	) -> Result<Self::Address, DispatchError> {898		Self::do_reschedule(address, when)899	}900901	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {902		Agenda::<T>::get(when)903			.get(index as usize)904			.ok_or(())905			.map(|_| when)906	}907}908909impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>910	for Pallet<T>911{912	type Address = TaskAddress<T::BlockNumber>;913	type Hash = T::Hash;914915	fn schedule_named(916		id: Vec<u8>,917		when: DispatchTime<T::BlockNumber>,918		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,919		priority: schedule::Priority,920		origin: T::PalletsOrigin,921		call: CallOrHashOf<T>,922	) -> Result<Self::Address, ()> {923		let inner_id: ScheduledId = id924			.try_into()925			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);926		Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)927			.map_err(|_| ())928	}929930	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {931		let inner_id: ScheduledId = id932			.try_into()933			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);934		Self::do_cancel_named(None, inner_id).map_err(|_| ())935	}936937	fn reschedule_named(938		id: Vec<u8>,939		when: DispatchTime<T::BlockNumber>,940	) -> Result<Self::Address, DispatchError> {941		let inner_id: ScheduledId = id942			.try_into()943			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);944		Self::do_reschedule_named(inner_id, when)945	}946947	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {948		let inner_id: ScheduledId = id949			.try_into()950			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);951		Lookup::<T>::get(inner_id)952			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))953			.ok_or(())954	}955}