git.delta.rocks / unique-network / refs/commits / 3bed4e0e0176

difftreelog

Duplicate lines removed

Dev2022-07-12parent: #e5ffee6.patch.diff
in: master

1 file changed

modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Unique scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.57//! Any user can book a call of a certain transaction to a specific block number.58//! Also possible to book a call with a certain frequency.59//! Key differences from original pallet:60//! Id restricted by 16 bytes61//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block62//! Maybe_periodic limit is 100 calls63//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.64//!65//! ## Interface66//!67//! ### Dispatchable Functions68//!69//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and70//!   with a specified priority.71//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.72//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter73//!   that can be used for identification.74//! * `cancel_named` - the named complement to the cancel function.75//!76//! ## Interface77//!78//! ### Dispatchable Functions79//!80//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and81//!   with a specified priority.82//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.83//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter84//!   that can be used for identification.85//! * `cancel_named` - the named complement to the cancel function.8687// Ensure we're `no_std` when compiling for Wasm.88#![cfg_attr(not(feature = "std"), no_std)]8990#[cfg(feature = "runtime-benchmarks")]91mod benchmarking;9293pub mod weights;9495use sp_core::H160;96use codec::{Codec, Decode, Encode};97use frame_system::{self as system, ensure_signed};98pub use pallet::*;99use scale_info::TypeInfo;100use sp_runtime::{101	traits::{BadOrigin, One, Saturating, Zero},102	RuntimeDebug, DispatchErrorWithPostInfo,103};104use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};105106use frame_support::{107	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},108	traits::{109		schedule::{self, DispatchTime, MaybeHashed},110		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,111		StorageVersion,112	},113	weights::{GetDispatchInfo, Weight},114};115116pub use weights::WeightInfo;117118/// Just a simple index for naming period tasks.119pub type PeriodicIndex = u32;120/// The location of a scheduled task that can be used to remove it.121pub type TaskAddress<BlockNumber> = (BlockNumber, u32);122pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;123124type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];125pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;126127/// Information regarding an item to be executed in the future.128#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]129#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]130pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {131	/// The unique identity for this task, if there is one.132	maybe_id: Option<ScheduledId>,133	/// This task's priority.134	priority: schedule::Priority,135	/// The call to be dispatched.136	call: Call,137	/// If the call is periodic, then this points to the information concerning that.138	maybe_periodic: Option<schedule::Period<BlockNumber>>,139	/// The origin to dispatch the call.140	origin: PalletsOrigin,141	_phantom: PhantomData<AccountId>,142}143144pub type ScheduledV3Of<T> = ScheduledV3<145	CallOrHashOf<T>,146	<T as frame_system::Config>::BlockNumber,147	<T as Config>::PalletsOrigin,148	<T as frame_system::Config>::AccountId,149>;150151pub type ScheduledOf<T> = ScheduledV3Of<T>;152153/// The current version of Scheduled struct.154pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =155	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;156157#[cfg(feature = "runtime-benchmarks")]158mod preimage_provider {159	use frame_support::traits::PreimageRecipient;160	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}161	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}162}163164#[cfg(not(feature = "runtime-benchmarks"))]165mod preimage_provider {166	use frame_support::traits::PreimageProvider;167	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}168	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}169}170171pub use preimage_provider::PreimageProviderAndMaybeRecipient;172173/// Weight templates for calculating actual fees174pub(crate) trait MarginalWeightInfo: WeightInfo {175	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {176		match (periodic, named, resolved) {177			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),178			(_, true, None) => {179				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)180			}181			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),182			(false, true, Some(false)) => {183				Self::on_initialize_named(2) - Self::on_initialize_named(1)184			}185			(true, false, Some(false)) => {186				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)187			}188			(true, true, Some(false)) => {189				Self::on_initialize_periodic_named_resolved(2)190					- Self::on_initialize_periodic_named_resolved(1)191			}192			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),193			(false, true, Some(true)) => {194				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)195			}196			(true, false, Some(true)) => {197				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)198			}199			(true, true, Some(true)) => {200				Self::on_initialize_periodic_named_resolved(2)201					- Self::on_initialize_periodic_named_resolved(1)202			}203		}204	}205}206impl<T: WeightInfo> MarginalWeightInfo for T {}207208#[frame_support::pallet]209pub mod pallet {210	use super::*;211	use frame_support::{212		dispatch::PostDispatchInfo,213		pallet_prelude::*,214		traits::{schedule::LookupError, PreimageProvider},215	};216	use frame_system::pallet_prelude::*;217218	/// The current storage version.219	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);220221	#[pallet::pallet]222	#[pallet::generate_store(pub(super) trait Store)]223	#[pallet::storage_version(STORAGE_VERSION)]224	#[pallet::without_storage_info]225	pub struct Pallet<T>(_);226227	/// `system::Config` should always be included in our implied traits.228	#[pallet::config]229	pub trait Config: frame_system::Config {230		/// The overarching event type.231		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;232233		/// The aggregated origin which the dispatch will take.234		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>235			+ From<Self::PalletsOrigin>236			+ IsType<<Self as system::Config>::Origin>;237238		/// The caller origin, overarching type of all pallets origins.239		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;240241		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;242243		/// The aggregated call type.244		type Call: Parameter245			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>246			+ GetDispatchInfo247			+ From<system::Call<Self>>;248249		/// The maximum weight that may be scheduled per block for any dispatchables of less250		/// priority than `schedule::HARD_DEADLINE`.251		#[pallet::constant]252		type MaximumWeight: Get<Weight>;253254		/// Required origin to schedule or cancel calls.255		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;256257		/// Compare the privileges of origins.258		///259		/// This will be used when canceling a task, to ensure that the origin that tries260		/// to cancel has greater or equal privileges as the origin that created the scheduled task.261		///262		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can263		/// be used. This will only check if two given origins are equal.264		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;265266		/// The maximum number of scheduled calls in the queue for a single block.267		/// Not strictly enforced, but used for weight estimation.268		#[pallet::constant]269		type MaxScheduledPerBlock: Get<u32>;270271		/// Weight information for extrinsics in this pallet.272		type WeightInfo: WeightInfo;273274		/// The preimage provider with which we look up call hashes to get the call.275		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;276277		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.278		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;279280		/// Sponsoring function. In this version sposorship is disabled281		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;282283		/// The helper type used for custom transaction fee logic.284		type CallExecutor: DispatchCall<Self, H160>;285	}286287	/// A Scheduler-Runtime interface for finer payment handling.288	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {289		/// Lock balance required for transaction payment290		fn reserve_balance(291			id: ScheduledId,292			sponsor: <T as frame_system::Config>::AccountId,293			call: <T as Config>::Call,294			count: u32,295		) -> Result<(), DispatchError>;296297		/// Unlock centain amount from payer298		fn pay_for_call(299			id: ScheduledId,300			sponsor: <T as frame_system::Config>::AccountId,301			call: <T as Config>::Call,302		) -> Result<u128, DispatchError>;303304		/// Resolve the call dispatch, including any post-dispatch operations.305		fn dispatch_call(306			signer: T::AccountId,307			function: <T as Config>::Call,308		) -> Result<309			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,310			TransactionValidityError,311		>;312313		/// Cancel schedule reservation and unlock balance314		fn cancel_reserve(315			id: ScheduledId,316			sponsor: <T as frame_system::Config>::AccountId,317		) -> Result<u128, DispatchError>;318	}319320	/// Items to be executed, indexed by the block number that they should be executed on.321	#[pallet::storage]322	pub type Agenda<T: Config> =323		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;324325	/// Lookup from identity to the block number and index of the task.326	#[pallet::storage]327	pub(crate) type Lookup<T: Config> =328		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;329330	/// Events type.331	#[pallet::event]332	#[pallet::generate_deposit(pub(super) fn deposit_event)]333	pub enum Event<T: Config> {334		/// Scheduled some task.335		Scheduled { when: T::BlockNumber, index: u32 },336		/// Canceled some task.337		Canceled { when: T::BlockNumber, index: u32 },338		/// Dispatched some task.339		Dispatched {340			task: TaskAddress<T::BlockNumber>,341			id: Option<ScheduledId>,342			result: DispatchResult,343		},344		/// The call for the provided hash was not found so the task has been aborted.345		CallLookupFailed {346			task: TaskAddress<T::BlockNumber>,347			id: Option<ScheduledId>,348			error: LookupError,349		},350	}351352	#[pallet::error]353	pub enum Error<T> {354		/// Failed to schedule a call355		FailedToSchedule,356		/// Cannot find the scheduled call.357		NotFound,358		/// Given target block number is in the past.359		TargetBlockNumberInPast,360		/// Reschedule failed because it does not change scheduled time.361		RescheduleNoChange,362	}363364	#[pallet::hooks]365	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {366		/// Execute the scheduled calls367		fn on_initialize(now: T::BlockNumber) -> Weight {368			let limit = T::MaximumWeight::get();369370			let mut queued = Agenda::<T>::take(now)371				.into_iter()372				.enumerate()373				.filter_map(|(index, s)| Some((index as u32, s?)))374				.collect::<Vec<_>>();375376			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {377				log::warn!(378					target: "runtime::scheduler",379					"Warning: This block has more items queued in Scheduler than \380					expected from the runtime configuration. An update might be needed."381				);382			}383384			queued.sort_by_key(|(_, s)| s.priority);385386			let next = now + One::one();387388			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);389			for (order, (index, mut s)) in queued.into_iter().enumerate() {390				let named = if let Some(ref id) = s.maybe_id {391					Lookup::<T>::remove(id);392					true393				} else {394					false395				};396397				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();398				s.call = call;399400				let resolved = if let Some(completed) = maybe_completed {401					T::PreimageProvider::unrequest_preimage(&completed);402					true403				} else {404					false405				};406				let call = match s.call.as_value().cloned() {407					Some(c) => c,408					None => {409						// Preimage not available - postpone until some block.410						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));411						if let Some(delay) = T::NoPreimagePostponement::get() {412							let until = now.saturating_add(delay);413							if let Some(ref id) = s.maybe_id {414								let index = Agenda::<T>::decode_len(until).unwrap_or(0);415								Lookup::<T>::insert(id, (until, index as u32));416							}417							Agenda::<T>::append(until, Some(s));418						}419						continue;420					}421				};422423				let periodic = s.maybe_periodic.is_some();424				let call_weight = call.get_dispatch_info().weight;425				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));426				let origin =427					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())428						.into();429				if ensure_signed(origin).is_ok() {430					// Weights of Signed dispatches expect their signing account to be whitelisted.431					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));432				}433434				// We allow a scheduled call if any is true:435				// - It's priority is `HARD_DEADLINE`436				// - It does not push the weight past the limit.437				// - It is the first item in the schedule438				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;439				let test_weight = total_weight440					.saturating_add(call_weight)441					.saturating_add(item_weight);442				if !hard_deadline && order > 0 && test_weight > limit {443					// Cannot be scheduled this block - postpone until next.444					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));445					if let Some(ref id) = s.maybe_id {446						// NOTE: We could reasonably not do this (in which case there would be one447						// block where the named and delayed item could not be referenced by name),448						// but we will do it anyway since it should be mostly free in terms of449						// weight and it is slightly cleaner.450						let index = Agenda::<T>::decode_len(next).unwrap_or(0);451						Lookup::<T>::insert(id, (next, index as u32));452					}453					Agenda::<T>::append(next, Some(s));454					continue;455				}456457				// Sender is the account who signed transaction458				let sender = ensure_signed(459					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())460						.into(),461				)462				.unwrap();463464				// // if call have id it was be reserved465				// if s.maybe_id.is_some() {466				// 	let _ = T::CallExecutor::pay_for_call(467				// 		s.maybe_id.unwrap(),468				// 		sender.clone(),469				// 		call.clone(),470				// 	);471				// }472473				// Execute transaction via chain default pipeline474				let r = T::CallExecutor::dispatch_call(sender, call.clone());475476				let mut actual_call_weight: Weight = item_weight;477				let result: Result<_, DispatchError> = match r {478					Ok(o) => match o {479						Ok(di) => {480							actual_call_weight = di.actual_weight.unwrap_or(item_weight);481							Ok(())482						}483						Err(err) => Err(err.error),484					},485					Err(_) => {486						log::error!(487							target: "runtime::scheduler",488							"Warning: Scheduler has failed to execute a post-dispatch transaction. \489							This block might have become invalid.");490						Err(DispatchError::CannotLookup)491					} // todo possibly force a skip/return here, do something with the error492				};493494				total_weight.saturating_accrue(item_weight);495				total_weight.saturating_accrue(actual_call_weight);496497				Self::deposit_event(Event::Dispatched {498					task: (now, index),499					id: s.maybe_id.clone(),500					result,501				});502503				if let &Some((period, count)) = &s.maybe_periodic {504					if count > 1 {505						s.maybe_periodic = Some((period, count - 1));506					} else {507						s.maybe_periodic = None;508					}509					let wake = now + period;510					// If scheduled is named, place its information in `Lookup`511					if let Some(ref id) = s.maybe_id {512						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);513						Lookup::<T>::insert(id, (wake, wake_index as u32));514					}515					Agenda::<T>::append(wake, Some(s));516				}517			}518			/// Weight should be 0, because transaction already paid519			0520		}521	}522523	#[pallet::call]524	impl<T: Config> Pallet<T> {525		/// Schedule a named task.526		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]527		pub fn schedule_named(528			origin: OriginFor<T>,529			id: ScheduledId,530			when: T::BlockNumber,531			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,532			priority: schedule::Priority,533			call: Box<CallOrHashOf<T>>,534		) -> DispatchResult {535			T::ScheduleOrigin::ensure_origin(origin.clone())?;536			let origin = <T as Config>::Origin::from(origin);537			Self::do_schedule_named(538				id,539				DispatchTime::At(when),540				maybe_periodic,541				priority,542				origin.caller().clone(),543				*call,544			)?;545			Ok(())546		}547548		/// Cancel a named scheduled task.549		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]550		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {551			T::ScheduleOrigin::ensure_origin(origin.clone())?;552			let origin = <T as Config>::Origin::from(origin);553			Self::do_cancel_named(Some(origin.caller().clone()), id)?;554			Ok(())555		}556557		/// Schedule a named task after a delay.558		///559		/// # <weight>560		/// Same as [`schedule_named`](Self::schedule_named).561		/// # </weight>562		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]563		pub fn schedule_named_after(564			origin: OriginFor<T>,565			id: ScheduledId,566			after: T::BlockNumber,567			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,568			priority: schedule::Priority,569			call: Box<CallOrHashOf<T>>,570		) -> DispatchResult {571			T::ScheduleOrigin::ensure_origin(origin.clone())?;572			let origin = <T as Config>::Origin::from(origin);573			Self::do_schedule_named(574				id,575				DispatchTime::After(after),576				maybe_periodic,577				priority,578				origin.caller().clone(),579				*call,580			)?;581			Ok(())582		}583	}584}585586impl<T: Config> Pallet<T> {587	#[cfg(feature = "try-runtime")]588	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {589		Ok(())590	}591592	#[cfg(feature = "try-runtime")]593	pub fn post_migrate_to_v3() -> Result<(), &'static str> {594		use frame_support::dispatch::GetStorageVersion;595596		assert!(Self::current_storage_version() == 3);597		for k in Agenda::<T>::iter_keys() {598			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;599		}600		Ok(())601	}602603	/// Helper to migrate scheduler when the pallet origin type has changed.604	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {605		Agenda::<T>::translate::<606			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,607			_,608		>(|_, agenda| {609			Some(610				agenda611					.into_iter()612					.map(|schedule| {613						schedule.map(|schedule| Scheduled {614							maybe_id: schedule.maybe_id,615							priority: schedule.priority,616							call: schedule.call,617							maybe_periodic: schedule.maybe_periodic,618							origin: schedule.origin.into(),619							_phantom: Default::default(),620						})621					})622					.collect::<Vec<_>>(),623			)624		});625	}626627	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {628		let now = frame_system::Pallet::<T>::block_number();629630		let when = match when {631			DispatchTime::At(x) => x,632			// The current block has already completed it's scheduled tasks, so633			// Schedule the task at lest one block after this current block.634			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),635		};636637		if when <= now {638			return Err(Error::<T>::TargetBlockNumberInPast.into());639		}640641		Ok(when)642	}643644	fn do_schedule_named(645		id: ScheduledId,646		when: DispatchTime<T::BlockNumber>,647		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,648		priority: schedule::Priority,649		origin: T::PalletsOrigin,650		call: CallOrHashOf<T>,651	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {652		// ensure id it is unique653		if Lookup::<T>::contains_key(&id) {654			return Err(Error::<T>::FailedToSchedule)?;655		}656657		let when = Self::resolve_time(when)?;658659		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));666667		let s = Scheduled {668			maybe_id: Some(id.clone()),669			priority,670			call: call.clone(),671			maybe_periodic,672			origin: origin.clone(),673			_phantom: Default::default(),674		};675676		// reserve balance for periodic execution677		// let sender =678		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;679		// let repeats = match maybe_periodic {680		// 	Some(p) => p.1,681		// 	None => 1,682		// };683		// let _ = T::CallExecutor::reserve_balance(684		// 	id.clone(),685		// 	sender,686		// 	call.as_value().unwrap().clone(),687		// 	repeats,688		// );689690		Agenda::<T>::append(when, Some(s));691		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;692		let address = (when, index);693		Lookup::<T>::insert(&id, &address);694		Self::deposit_event(Event::Scheduled { when, index });695696		Ok(address)697	}698699	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {700		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {701			if let Some((when, index)) = lookup.take() {702				let i = index as usize;703				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {704					if let Some(s) = agenda.get_mut(i) {705						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {706							if matches!(707								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),708								Some(Ordering::Less) | None709							) {710								return Err(BadOrigin.into());711							}712							// release balance reserve713							// let sender = ensure_signed(714							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(715							// 		origin.unwrap(),716							// 	)717							// 	.into(),718							// )?;719							// let _ = T::CallExecutor::cancel_reserve(id, sender);720721							s.call.ensure_unrequested::<T::PreimageProvider>();722						}723						*s = None;724					}725					Ok(())726				})?;727728				Self::deposit_event(Event::Canceled { when, index });729				Ok(())730			} else {731				Err(Error::<T>::NotFound)?732			}733		})734	}735}
after · pallets/scheduler/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Unique scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.57//! Any user can book a call of a certain transaction to a specific block number.58//! Also possible to book a call with a certain frequency.59//! Key differences from original pallet:60//! Id restricted by 16 bytes61//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block62//! Maybe_periodic limit is 100 calls63//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.64//!65//! ## Interface66//!67//! ### Dispatchable Functions68//!69//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and70//!   with a specified priority.71//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.72//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter73//!   that can be used for identification.74//! * `cancel_named` - the named complement to the cancel function.7576// Ensure we're `no_std` when compiling for Wasm.77#![cfg_attr(not(feature = "std"), no_std)]7879#[cfg(feature = "runtime-benchmarks")]80mod benchmarking;8182pub mod weights;8384use sp_core::H160;85use codec::{Codec, Decode, Encode};86use frame_system::{self as system, ensure_signed};87pub use pallet::*;88use scale_info::TypeInfo;89use sp_runtime::{90	traits::{BadOrigin, One, Saturating, Zero},91	RuntimeDebug, DispatchErrorWithPostInfo,92};93use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};9495use frame_support::{96	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},97	traits::{98		schedule::{self, DispatchTime, MaybeHashed},99		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,100		StorageVersion,101	},102	weights::{GetDispatchInfo, Weight},103};104105pub use weights::WeightInfo;106107/// Just a simple index for naming period tasks.108pub type PeriodicIndex = u32;109/// The location of a scheduled task that can be used to remove it.110pub type TaskAddress<BlockNumber> = (BlockNumber, u32);111pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;112113type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];114pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;115116/// Information regarding an item to be executed in the future.117#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]118#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]119pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {120	/// The unique identity for this task, if there is one.121	maybe_id: Option<ScheduledId>,122	/// This task's priority.123	priority: schedule::Priority,124	/// The call to be dispatched.125	call: Call,126	/// If the call is periodic, then this points to the information concerning that.127	maybe_periodic: Option<schedule::Period<BlockNumber>>,128	/// The origin to dispatch the call.129	origin: PalletsOrigin,130	_phantom: PhantomData<AccountId>,131}132133pub type ScheduledV3Of<T> = ScheduledV3<134	CallOrHashOf<T>,135	<T as frame_system::Config>::BlockNumber,136	<T as Config>::PalletsOrigin,137	<T as frame_system::Config>::AccountId,138>;139140pub type ScheduledOf<T> = ScheduledV3Of<T>;141142/// The current version of Scheduled struct.143pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =144	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;145146#[cfg(feature = "runtime-benchmarks")]147mod preimage_provider {148	use frame_support::traits::PreimageRecipient;149	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}150	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}151}152153#[cfg(not(feature = "runtime-benchmarks"))]154mod preimage_provider {155	use frame_support::traits::PreimageProvider;156	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}157	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}158}159160pub use preimage_provider::PreimageProviderAndMaybeRecipient;161162/// Weight templates for calculating actual fees163pub(crate) trait MarginalWeightInfo: WeightInfo {164	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {165		match (periodic, named, resolved) {166			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),167			(_, true, None) => {168				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)169			}170			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),171			(false, true, Some(false)) => {172				Self::on_initialize_named(2) - Self::on_initialize_named(1)173			}174			(true, false, Some(false)) => {175				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)176			}177			(true, true, Some(false)) => {178				Self::on_initialize_periodic_named_resolved(2)179					- Self::on_initialize_periodic_named_resolved(1)180			}181			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),182			(false, true, Some(true)) => {183				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)184			}185			(true, false, Some(true)) => {186				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)187			}188			(true, true, Some(true)) => {189				Self::on_initialize_periodic_named_resolved(2)190					- Self::on_initialize_periodic_named_resolved(1)191			}192		}193	}194}195impl<T: WeightInfo> MarginalWeightInfo for T {}196197#[frame_support::pallet]198pub mod pallet {199	use super::*;200	use frame_support::{201		dispatch::PostDispatchInfo,202		pallet_prelude::*,203		traits::{schedule::LookupError, PreimageProvider},204	};205	use frame_system::pallet_prelude::*;206207	/// The current storage version.208	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);209210	#[pallet::pallet]211	#[pallet::generate_store(pub(super) trait Store)]212	#[pallet::storage_version(STORAGE_VERSION)]213	#[pallet::without_storage_info]214	pub struct Pallet<T>(_);215216	/// `system::Config` should always be included in our implied traits.217	#[pallet::config]218	pub trait Config: frame_system::Config {219		/// The overarching event type.220		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;221222		/// The aggregated origin which the dispatch will take.223		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>224			+ From<Self::PalletsOrigin>225			+ IsType<<Self as system::Config>::Origin>;226227		/// The caller origin, overarching type of all pallets origins.228		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;229230		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;231232		/// The aggregated call type.233		type Call: Parameter234			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>235			+ GetDispatchInfo236			+ From<system::Call<Self>>;237238		/// The maximum weight that may be scheduled per block for any dispatchables of less239		/// priority than `schedule::HARD_DEADLINE`.240		#[pallet::constant]241		type MaximumWeight: Get<Weight>;242243		/// Required origin to schedule or cancel calls.244		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;245246		/// Compare the privileges of origins.247		///248		/// This will be used when canceling a task, to ensure that the origin that tries249		/// to cancel has greater or equal privileges as the origin that created the scheduled task.250		///251		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can252		/// be used. This will only check if two given origins are equal.253		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;254255		/// The maximum number of scheduled calls in the queue for a single block.256		/// Not strictly enforced, but used for weight estimation.257		#[pallet::constant]258		type MaxScheduledPerBlock: Get<u32>;259260		/// Weight information for extrinsics in this pallet.261		type WeightInfo: WeightInfo;262263		/// The preimage provider with which we look up call hashes to get the call.264		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;265266		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.267		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;268269		/// Sponsoring function. In this version sposorship is disabled270		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;271272		/// The helper type used for custom transaction fee logic.273		type CallExecutor: DispatchCall<Self, H160>;274	}275276	/// A Scheduler-Runtime interface for finer payment handling.277	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {278		/// Lock balance required for transaction payment279		fn reserve_balance(280			id: ScheduledId,281			sponsor: <T as frame_system::Config>::AccountId,282			call: <T as Config>::Call,283			count: u32,284		) -> Result<(), DispatchError>;285286		/// Unlock centain amount from payer287		fn pay_for_call(288			id: ScheduledId,289			sponsor: <T as frame_system::Config>::AccountId,290			call: <T as Config>::Call,291		) -> Result<u128, DispatchError>;292293		/// Resolve the call dispatch, including any post-dispatch operations.294		fn dispatch_call(295			signer: T::AccountId,296			function: <T as Config>::Call,297		) -> Result<298			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,299			TransactionValidityError,300		>;301302		/// Cancel schedule reservation and unlock balance303		fn cancel_reserve(304			id: ScheduledId,305			sponsor: <T as frame_system::Config>::AccountId,306		) -> Result<u128, DispatchError>;307	}308309	/// Items to be executed, indexed by the block number that they should be executed on.310	#[pallet::storage]311	pub type Agenda<T: Config> =312		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;313314	/// Lookup from identity to the block number and index of the task.315	#[pallet::storage]316	pub(crate) type Lookup<T: Config> =317		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;318319	/// Events type.320	#[pallet::event]321	#[pallet::generate_deposit(pub(super) fn deposit_event)]322	pub enum Event<T: Config> {323		/// Scheduled some task.324		Scheduled { when: T::BlockNumber, index: u32 },325		/// Canceled some task.326		Canceled { when: T::BlockNumber, index: u32 },327		/// Dispatched some task.328		Dispatched {329			task: TaskAddress<T::BlockNumber>,330			id: Option<ScheduledId>,331			result: DispatchResult,332		},333		/// The call for the provided hash was not found so the task has been aborted.334		CallLookupFailed {335			task: TaskAddress<T::BlockNumber>,336			id: Option<ScheduledId>,337			error: LookupError,338		},339	}340341	#[pallet::error]342	pub enum Error<T> {343		/// Failed to schedule a call344		FailedToSchedule,345		/// Cannot find the scheduled call.346		NotFound,347		/// Given target block number is in the past.348		TargetBlockNumberInPast,349		/// Reschedule failed because it does not change scheduled time.350		RescheduleNoChange,351	}352353	#[pallet::hooks]354	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {355		/// Execute the scheduled calls356		fn on_initialize(now: T::BlockNumber) -> Weight {357			let limit = T::MaximumWeight::get();358359			let mut queued = Agenda::<T>::take(now)360				.into_iter()361				.enumerate()362				.filter_map(|(index, s)| Some((index as u32, s?)))363				.collect::<Vec<_>>();364365			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {366				log::warn!(367					target: "runtime::scheduler",368					"Warning: This block has more items queued in Scheduler than \369					expected from the runtime configuration. An update might be needed."370				);371			}372373			queued.sort_by_key(|(_, s)| s.priority);374375			let next = now + One::one();376377			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);378			for (order, (index, mut s)) in queued.into_iter().enumerate() {379				let named = if let Some(ref id) = s.maybe_id {380					Lookup::<T>::remove(id);381					true382				} else {383					false384				};385386				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();387				s.call = call;388389				let resolved = if let Some(completed) = maybe_completed {390					T::PreimageProvider::unrequest_preimage(&completed);391					true392				} else {393					false394				};395				let call = match s.call.as_value().cloned() {396					Some(c) => c,397					None => {398						// Preimage not available - postpone until some block.399						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));400						if let Some(delay) = T::NoPreimagePostponement::get() {401							let until = now.saturating_add(delay);402							if let Some(ref id) = s.maybe_id {403								let index = Agenda::<T>::decode_len(until).unwrap_or(0);404								Lookup::<T>::insert(id, (until, index as u32));405							}406							Agenda::<T>::append(until, Some(s));407						}408						continue;409					}410				};411412				let periodic = s.maybe_periodic.is_some();413				let call_weight = call.get_dispatch_info().weight;414				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));415				let origin =416					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())417						.into();418				if ensure_signed(origin).is_ok() {419					// Weights of Signed dispatches expect their signing account to be whitelisted.420					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));421				}422423				// We allow a scheduled call if any is true:424				// - It's priority is `HARD_DEADLINE`425				// - It does not push the weight past the limit.426				// - It is the first item in the schedule427				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;428				let test_weight = total_weight429					.saturating_add(call_weight)430					.saturating_add(item_weight);431				if !hard_deadline && order > 0 && test_weight > limit {432					// Cannot be scheduled this block - postpone until next.433					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));434					if let Some(ref id) = s.maybe_id {435						// NOTE: We could reasonably not do this (in which case there would be one436						// block where the named and delayed item could not be referenced by name),437						// but we will do it anyway since it should be mostly free in terms of438						// weight and it is slightly cleaner.439						let index = Agenda::<T>::decode_len(next).unwrap_or(0);440						Lookup::<T>::insert(id, (next, index as u32));441					}442					Agenda::<T>::append(next, Some(s));443					continue;444				}445446				// Sender is the account who signed transaction447				let sender = ensure_signed(448					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())449						.into(),450				)451				.unwrap();452453				// // if call have id it was be reserved454				// if s.maybe_id.is_some() {455				// 	let _ = T::CallExecutor::pay_for_call(456				// 		s.maybe_id.unwrap(),457				// 		sender.clone(),458				// 		call.clone(),459				// 	);460				// }461462				// Execute transaction via chain default pipeline463				let r = T::CallExecutor::dispatch_call(sender, call.clone());464465				let mut actual_call_weight: Weight = item_weight;466				let result: Result<_, DispatchError> = match r {467					Ok(o) => match o {468						Ok(di) => {469							actual_call_weight = di.actual_weight.unwrap_or(item_weight);470							Ok(())471						}472						Err(err) => Err(err.error),473					},474					Err(_) => {475						log::error!(476							target: "runtime::scheduler",477							"Warning: Scheduler has failed to execute a post-dispatch transaction. \478							This block might have become invalid.");479						Err(DispatchError::CannotLookup)480					} // todo possibly force a skip/return here, do something with the error481				};482483				total_weight.saturating_accrue(item_weight);484				total_weight.saturating_accrue(actual_call_weight);485486				Self::deposit_event(Event::Dispatched {487					task: (now, index),488					id: s.maybe_id.clone(),489					result,490				});491492				if let &Some((period, count)) = &s.maybe_periodic {493					if count > 1 {494						s.maybe_periodic = Some((period, count - 1));495					} else {496						s.maybe_periodic = None;497					}498					let wake = now + period;499					// If scheduled is named, place its information in `Lookup`500					if let Some(ref id) = s.maybe_id {501						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);502						Lookup::<T>::insert(id, (wake, wake_index as u32));503					}504					Agenda::<T>::append(wake, Some(s));505				}506			}507			/// Weight should be 0, because transaction already paid508			0509		}510	}511512	#[pallet::call]513	impl<T: Config> Pallet<T> {514		/// Schedule a named task.515		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]516		pub fn schedule_named(517			origin: OriginFor<T>,518			id: ScheduledId,519			when: T::BlockNumber,520			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,521			priority: schedule::Priority,522			call: Box<CallOrHashOf<T>>,523		) -> DispatchResult {524			T::ScheduleOrigin::ensure_origin(origin.clone())?;525			let origin = <T as Config>::Origin::from(origin);526			Self::do_schedule_named(527				id,528				DispatchTime::At(when),529				maybe_periodic,530				priority,531				origin.caller().clone(),532				*call,533			)?;534			Ok(())535		}536537		/// Cancel a named scheduled task.538		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]539		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {540			T::ScheduleOrigin::ensure_origin(origin.clone())?;541			let origin = <T as Config>::Origin::from(origin);542			Self::do_cancel_named(Some(origin.caller().clone()), id)?;543			Ok(())544		}545546		/// Schedule a named task after a delay.547		///548		/// # <weight>549		/// Same as [`schedule_named`](Self::schedule_named).550		/// # </weight>551		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]552		pub fn schedule_named_after(553			origin: OriginFor<T>,554			id: ScheduledId,555			after: T::BlockNumber,556			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,557			priority: schedule::Priority,558			call: Box<CallOrHashOf<T>>,559		) -> DispatchResult {560			T::ScheduleOrigin::ensure_origin(origin.clone())?;561			let origin = <T as Config>::Origin::from(origin);562			Self::do_schedule_named(563				id,564				DispatchTime::After(after),565				maybe_periodic,566				priority,567				origin.caller().clone(),568				*call,569			)?;570			Ok(())571		}572	}573}574575impl<T: Config> Pallet<T> {576	#[cfg(feature = "try-runtime")]577	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {578		Ok(())579	}580581	#[cfg(feature = "try-runtime")]582	pub fn post_migrate_to_v3() -> Result<(), &'static str> {583		use frame_support::dispatch::GetStorageVersion;584585		assert!(Self::current_storage_version() == 3);586		for k in Agenda::<T>::iter_keys() {587			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;588		}589		Ok(())590	}591592	/// Helper to migrate scheduler when the pallet origin type has changed.593	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {594		Agenda::<T>::translate::<595			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,596			_,597		>(|_, agenda| {598			Some(599				agenda600					.into_iter()601					.map(|schedule| {602						schedule.map(|schedule| Scheduled {603							maybe_id: schedule.maybe_id,604							priority: schedule.priority,605							call: schedule.call,606							maybe_periodic: schedule.maybe_periodic,607							origin: schedule.origin.into(),608							_phantom: Default::default(),609						})610					})611					.collect::<Vec<_>>(),612			)613		});614	}615616	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {617		let now = frame_system::Pallet::<T>::block_number();618619		let when = match when {620			DispatchTime::At(x) => x,621			// The current block has already completed it's scheduled tasks, so622			// Schedule the task at lest one block after this current block.623			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),624		};625626		if when <= now {627			return Err(Error::<T>::TargetBlockNumberInPast.into());628		}629630		Ok(when)631	}632633	fn do_schedule_named(634		id: ScheduledId,635		when: DispatchTime<T::BlockNumber>,636		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,637		priority: schedule::Priority,638		origin: T::PalletsOrigin,639		call: CallOrHashOf<T>,640	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {641		// ensure id it is unique642		if Lookup::<T>::contains_key(&id) {643			return Err(Error::<T>::FailedToSchedule)?;644		}645646		let when = Self::resolve_time(when)?;647648		call.ensure_requested::<T::PreimageProvider>();649650		// sanitize maybe_periodic651		let maybe_periodic = maybe_periodic652			.filter(|p| p.1 > 1 && !p.0.is_zero())653			// Remove one from the number of repetitions since we will schedule one now.654			.map(|(p, c)| (p, c - 1));655656		let s = Scheduled {657			maybe_id: Some(id.clone()),658			priority,659			call: call.clone(),660			maybe_periodic,661			origin: origin.clone(),662			_phantom: Default::default(),663		};664665		// reserve balance for periodic execution666		// let sender =667		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;668		// let repeats = match maybe_periodic {669		// 	Some(p) => p.1,670		// 	None => 1,671		// };672		// let _ = T::CallExecutor::reserve_balance(673		// 	id.clone(),674		// 	sender,675		// 	call.as_value().unwrap().clone(),676		// 	repeats,677		// );678679		Agenda::<T>::append(when, Some(s));680		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;681		let address = (when, index);682		Lookup::<T>::insert(&id, &address);683		Self::deposit_event(Event::Scheduled { when, index });684685		Ok(address)686	}687688	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {689		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {690			if let Some((when, index)) = lookup.take() {691				let i = index as usize;692				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {693					if let Some(s) = agenda.get_mut(i) {694						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {695							if matches!(696								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),697								Some(Ordering::Less) | None698							) {699								return Err(BadOrigin.into());700							}701							// release balance reserve702							// let sender = ensure_signed(703							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(704							// 		origin.unwrap(),705							// 	)706							// 	.into(),707							// )?;708							// let _ = T::CallExecutor::cancel_reserve(id, sender);709710							s.call.ensure_unrequested::<T::PreimageProvider>();711						}712						*s = None;713					}714					Ok(())715				})?;716717				Self::deposit_event(Event::Canceled { when, index });718				Ok(())719			} else {720				Err(Error::<T>::NotFound)?721			}722		})723	}724}