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

difftreelog

Comments and code description added

Dev2022-07-11parent: #788534b.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//! # Schedulerdo_reschedule36//!37//! This Pallet exposes capabilities for scheduling dispatches to occur at a38//! specified block number or at a specified period. These scheduled dispatches39//! may be named or anonymous and may be canceled.40//!41//! **NOTE:** The scheduled calls will be dispatched with the default filter42//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin43//! except root which will get no filter. And not the filter contained in origin44//! use to call `fn schedule`.45//!46//! If a call is scheduled using proxy or whatever mecanism which adds filter,47//! then those filter will not be used when dispatching the schedule call.48//!49//! ## Interface50//!51//! ### Dispatchable Functions52//!53//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and54//!   with a specified priority.55//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.56//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter57//!   that can be used for identification.58//! * `cancel_named` - the named complement to the cancel function.5960// Ensure we're `no_std` when compiling for Wasm.61#![cfg_attr(not(feature = "std"), no_std)]6263#[cfg(feature = "runtime-benchmarks")]64mod benchmarking;6566pub mod weights;6768use sp_core::H160;69use codec::{Codec, Decode, Encode};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, DispatchErrorWithPostInfo,76};77use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};7879use frame_support::{80	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},81	traits::{82		schedule::{self, DispatchTime, MaybeHashed},83		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,84		StorageVersion,85	},86	weights::{GetDispatchInfo, Weight},87};8889pub use weights::WeightInfo;9091/// Just a simple index for naming period tasks.92pub type PeriodicIndex = u32;93/// The location of a scheduled task that can be used to remove it.94pub type TaskAddress<BlockNumber> = (BlockNumber, u32);95pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;9697type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];98pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;99100/// Information regarding an item to be executed in the future.101#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]102#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]103pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {104	/// The unique identity for this task, if there is one.105	maybe_id: Option<ScheduledId>,106	/// This task's priority.107	priority: schedule::Priority,108	/// The call to be dispatched.109	call: Call,110	/// If the call is periodic, then this points to the information concerning that.111	maybe_periodic: Option<schedule::Period<BlockNumber>>,112	/// The origin to dispatch the call.113	origin: PalletsOrigin,114	_phantom: PhantomData<AccountId>,115}116117pub type ScheduledV3Of<T> = ScheduledV3<118	CallOrHashOf<T>,119	<T as frame_system::Config>::BlockNumber,120	<T as Config>::PalletsOrigin,121	<T as frame_system::Config>::AccountId,122>;123124pub type ScheduledOf<T> = ScheduledV3Of<T>;125126/// The current version of Scheduled struct.127pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =128	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;129130#[cfg(feature = "runtime-benchmarks")]131mod preimage_provider {132	use frame_support::traits::PreimageRecipient;133	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}134	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}135}136137#[cfg(not(feature = "runtime-benchmarks"))]138mod preimage_provider {139	use frame_support::traits::PreimageProvider;140	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}141	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}142}143144pub use preimage_provider::PreimageProviderAndMaybeRecipient;145146pub(crate) trait MarginalWeightInfo: WeightInfo {147	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {148		match (periodic, named, resolved) {149			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),150			(_, true, None) => {151				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)152			}153			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),154			(false, true, Some(false)) => {155				Self::on_initialize_named(2) - Self::on_initialize_named(1)156			}157			(true, false, Some(false)) => {158				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)159			}160			(true, true, Some(false)) => {161				Self::on_initialize_periodic_named_resolved(2)162					- Self::on_initialize_periodic_named_resolved(1)163			}164			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),165			(false, true, Some(true)) => {166				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)167			}168			(true, false, Some(true)) => {169				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)170			}171			(true, true, Some(true)) => {172				Self::on_initialize_periodic_named_resolved(2)173					- Self::on_initialize_periodic_named_resolved(1)174			}175		}176	}177}178impl<T: WeightInfo> MarginalWeightInfo for T {}179180#[frame_support::pallet]181pub mod pallet {182	use super::*;183	use frame_support::{184		dispatch::PostDispatchInfo,185		pallet_prelude::*,186		traits::{schedule::LookupError, PreimageProvider},187	};188	use frame_system::pallet_prelude::*;189190	/// The current storage version.191	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);192193	#[pallet::pallet]194	#[pallet::generate_store(pub(super) trait Store)]195	#[pallet::storage_version(STORAGE_VERSION)]196	#[pallet::without_storage_info]197	pub struct Pallet<T>(_);198199	/// `system::Config` should always be included in our implied traits.200	#[pallet::config]201	pub trait Config: frame_system::Config {202		/// The overarching event type.203		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;204205		/// The aggregated origin which the dispatch will take.206		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>207			+ From<Self::PalletsOrigin>208			+ IsType<<Self as system::Config>::Origin>;209210		/// The caller origin, overarching type of all pallets origins.211		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;212213		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;214215		/// The aggregated call type.216		type Call: Parameter217			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>218			+ GetDispatchInfo219			+ From<system::Call<Self>>;220221		/// The maximum weight that may be scheduled per block for any dispatchables of less222		/// priority than `schedule::HARD_DEADLINE`.223		#[pallet::constant]224		type MaximumWeight: Get<Weight>;225226		/// Required origin to schedule or cancel calls.227		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;228229		/// Compare the privileges of origins.230		///231		/// This will be used when canceling a task, to ensure that the origin that tries232		/// to cancel has greater or equal privileges as the origin that created the scheduled task.233		///234		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can235		/// be used. This will only check if two given origins are equal.236		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;237238		/// The maximum number of scheduled calls in the queue for a single block.239		/// Not strictly enforced, but used for weight estimation.240		#[pallet::constant]241		type MaxScheduledPerBlock: Get<u32>;242243		/// Weight information for extrinsics in this pallet.244		type WeightInfo: WeightInfo;245246		/// The preimage provider with which we look up call hashes to get the call.247		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;248249		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.250		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;251252		/// Sponsoring function.253		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;254255		/// The helper type used for custom transaction fee logic.256		type CallExecutor: DispatchCall<Self, H160>;257	}258259	/// A Scheduler-Runtime interface for finer payment handling.260	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {261		fn reserve_balance(262			id: ScheduledId,263			sponsor: <T as frame_system::Config>::AccountId,264			call: <T as Config>::Call,265			count: u32,266		) -> Result<(), DispatchError>;267268		fn pay_for_call(269			id: ScheduledId,270			sponsor: <T as frame_system::Config>::AccountId,271			call: <T as Config>::Call,272		) -> Result<u128, DispatchError>;273274		/// Resolve the call dispatch, including any post-dispatch operations.275		fn dispatch_call(276			signer: T::AccountId,277			function: <T as Config>::Call,278		) -> Result<279			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,280			TransactionValidityError,281		>;282283		fn cancel_reserve(284			id: ScheduledId,285			sponsor: <T as frame_system::Config>::AccountId,286		) -> Result<u128, DispatchError>;287	}288289	/// Items to be executed, indexed by the block number that they should be executed on.290	#[pallet::storage]291	pub type Agenda<T: Config> =292		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;293294	/// Lookup from identity to the block number and index of the task.295	#[pallet::storage]296	pub(crate) type Lookup<T: Config> =297		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;298299	/// Events type.300	#[pallet::event]301	#[pallet::generate_deposit(pub(super) fn deposit_event)]302	pub enum Event<T: Config> {303		/// Scheduled some task.304		Scheduled { when: T::BlockNumber, index: u32 },305		/// Canceled some task.306		Canceled { when: T::BlockNumber, index: u32 },307		/// Dispatched some task.308		Dispatched {309			task: TaskAddress<T::BlockNumber>,310			id: Option<ScheduledId>,311			result: DispatchResult,312		},313		/// The call for the provided hash was not found so the task has been aborted.314		CallLookupFailed {315			task: TaskAddress<T::BlockNumber>,316			id: Option<ScheduledId>,317			error: LookupError,318		},319	}320321	#[pallet::error]322	pub enum Error<T> {323		/// Failed to schedule a call324		FailedToSchedule,325		/// Cannot find the scheduled call.326		NotFound,327		/// Given target block number is in the past.328		TargetBlockNumberInPast,329		/// Reschedule failed because it does not change scheduled time.330		RescheduleNoChange,331	}332333	#[pallet::hooks]334	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {335		/// Execute the scheduled calls336		fn on_initialize(now: T::BlockNumber) -> Weight {337			let limit = T::MaximumWeight::get();338339			let mut queued = Agenda::<T>::take(now)340				.into_iter()341				.enumerate()342				.filter_map(|(index, s)| Some((index as u32, s?)))343				.collect::<Vec<_>>();344345			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {346				log::warn!(347					target: "runtime::scheduler",348					"Warning: This block has more items queued in Scheduler than \349					expected from the runtime configuration. An update might be needed."350				);351			}352353			queued.sort_by_key(|(_, s)| s.priority);354355			let next = now + One::one();356357			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);358			for (order, (index, mut s)) in queued.into_iter().enumerate() {359				let named = if let Some(ref id) = s.maybe_id {360					Lookup::<T>::remove(id);361					true362				} else {363					false364				};365366				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();367				s.call = call;368369				let resolved = if let Some(completed) = maybe_completed {370					T::PreimageProvider::unrequest_preimage(&completed);371					true372				} else {373					false374				};375				let call = match s.call.as_value().cloned() {376					Some(c) => c,377					None => {378						// Preimage not available - postpone until some block.379						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));380						if let Some(delay) = T::NoPreimagePostponement::get() {381							let until = now.saturating_add(delay);382							if let Some(ref id) = s.maybe_id {383								let index = Agenda::<T>::decode_len(until).unwrap_or(0);384								Lookup::<T>::insert(id, (until, index as u32));385							}386							Agenda::<T>::append(until, Some(s));387						}388						continue;389					}390				};391392				let periodic = s.maybe_periodic.is_some();393				let call_weight = call.get_dispatch_info().weight;394				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));395				let origin =396					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())397						.into();398				if ensure_signed(origin).is_ok() {399					// Weights of Signed dispatches expect their signing account to be whitelisted.400					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));401				}402403				// We allow a scheduled call if any is true:404				// - It's priority is `HARD_DEADLINE`405				// - It does not push the weight past the limit.406				// - It is the first item in the schedule407				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;408				let test_weight = total_weight409					.saturating_add(call_weight)410					.saturating_add(item_weight);411				if !hard_deadline && order > 0 && test_weight > limit {412					// Cannot be scheduled this block - postpone until next.413					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));414					if let Some(ref id) = s.maybe_id {415						// NOTE: We could reasonably not do this (in which case there would be one416						// block where the named and delayed item could not be referenced by name),417						// but we will do it anyway since it should be mostly free in terms of418						// weight and it is slightly cleaner.419						let index = Agenda::<T>::decode_len(next).unwrap_or(0);420						Lookup::<T>::insert(id, (next, index as u32));421					}422					Agenda::<T>::append(next, Some(s));423					continue;424				}425426				let sender = ensure_signed(427					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())428						.into(),429				)430				.unwrap();431432				// // if call have id it was be reserved433				// if s.maybe_id.is_some() {434				// 	let _ = T::CallExecutor::pay_for_call(435				// 		s.maybe_id.unwrap(),436				// 		sender.clone(),437				// 		call.clone(),438				// 	);439				// }440441				let r = T::CallExecutor::dispatch_call(sender, call.clone());442443				let mut actual_call_weight: Weight = item_weight;444				let result: Result<_, DispatchError> = match r {445					Ok(o) => match o {446						Ok(di) => {447							actual_call_weight = di.actual_weight.unwrap_or(item_weight);448							Ok(())449						}450						Err(err) => Err(err.error),451					},452					Err(_) => {453						log::error!(454							target: "runtime::scheduler",455							"Warning: Scheduler has failed to execute a post-dispatch transaction. \456							This block might have become invalid.");457						Err(DispatchError::CannotLookup)458					} // todo possibly force a skip/return here, do something with the error459				};460461				total_weight.saturating_accrue(item_weight);462				total_weight.saturating_accrue(actual_call_weight);463464				Self::deposit_event(Event::Dispatched {465					task: (now, index),466					id: s.maybe_id.clone(),467					result,468				});469470				if let &Some((period, count)) = &s.maybe_periodic {471					if count > 1 {472						s.maybe_periodic = Some((period, count - 1));473					} else {474						s.maybe_periodic = None;475					}476					let wake = now + period;477					// If scheduled is named, place its information in `Lookup`478					if let Some(ref id) = s.maybe_id {479						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);480						Lookup::<T>::insert(id, (wake, wake_index as u32));481					}482					Agenda::<T>::append(wake, Some(s));483				}484			}485			0486			//total_weight487		}488	}489490	#[pallet::call]491	impl<T: Config> Pallet<T> {492		/// Schedule a named task.493		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]494		pub fn schedule_named(495			origin: OriginFor<T>,496			id: ScheduledId,497			when: T::BlockNumber,498			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,499			priority: schedule::Priority,500			call: Box<CallOrHashOf<T>>,501		) -> DispatchResult {502			T::ScheduleOrigin::ensure_origin(origin.clone())?;503			let origin = <T as Config>::Origin::from(origin);504			Self::do_schedule_named(505				id,506				DispatchTime::At(when),507				maybe_periodic,508				priority,509				origin.caller().clone(),510				*call,511			)?;512			Ok(())513		}514515		/// Cancel a named scheduled task.516		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]517		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {518			T::ScheduleOrigin::ensure_origin(origin.clone())?;519			let origin = <T as Config>::Origin::from(origin);520			Self::do_cancel_named(Some(origin.caller().clone()), id)?;521			Ok(())522		}523524		/// Schedule a named task after a delay.525		///526		/// # <weight>527		/// Same as [`schedule_named`](Self::schedule_named).528		/// # </weight>529		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]530		pub fn schedule_named_after(531			origin: OriginFor<T>,532			id: ScheduledId,533			after: T::BlockNumber,534			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,535			priority: schedule::Priority,536			call: Box<CallOrHashOf<T>>,537		) -> DispatchResult {538			T::ScheduleOrigin::ensure_origin(origin.clone())?;539			let origin = <T as Config>::Origin::from(origin);540			Self::do_schedule_named(541				id,542				DispatchTime::After(after),543				maybe_periodic,544				priority,545				origin.caller().clone(),546				*call,547			)?;548			Ok(())549		}550	}551}552553impl<T: Config> Pallet<T> {554	#[cfg(feature = "try-runtime")]555	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {556		Ok(())557	}558559	#[cfg(feature = "try-runtime")]560	pub fn post_migrate_to_v3() -> Result<(), &'static str> {561		use frame_support::dispatch::GetStorageVersion;562563		assert!(Self::current_storage_version() == 3);564		for k in Agenda::<T>::iter_keys() {565			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;566		}567		Ok(())568	}569570	/// Helper to migrate scheduler when the pallet origin type has changed.571	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {572		Agenda::<T>::translate::<573			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,574			_,575		>(|_, agenda| {576			Some(577				agenda578					.into_iter()579					.map(|schedule| {580						schedule.map(|schedule| Scheduled {581							maybe_id: schedule.maybe_id,582							priority: schedule.priority,583							call: schedule.call,584							maybe_periodic: schedule.maybe_periodic,585							origin: schedule.origin.into(),586							_phantom: Default::default(),587						})588					})589					.collect::<Vec<_>>(),590			)591		});592	}593594	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {595		let now = frame_system::Pallet::<T>::block_number();596597		let when = match when {598			DispatchTime::At(x) => x,599			// The current block has already completed it's scheduled tasks, so600			// Schedule the task at lest one block after this current block.601			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),602		};603604		if when <= now {605			return Err(Error::<T>::TargetBlockNumberInPast.into());606		}607608		Ok(when)609	}610611	fn do_schedule_named(612		id: ScheduledId,613		when: DispatchTime<T::BlockNumber>,614		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,615		priority: schedule::Priority,616		origin: T::PalletsOrigin,617		call: CallOrHashOf<T>,618	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {619		// ensure id it is unique620		if Lookup::<T>::contains_key(&id) {621			return Err(Error::<T>::FailedToSchedule)?;622		}623624		let when = Self::resolve_time(when)?;625626		call.ensure_requested::<T::PreimageProvider>();627628		// sanitize maybe_periodic629		let maybe_periodic = maybe_periodic630			.filter(|p| p.1 > 1 && !p.0.is_zero())631			// Remove one from the number of repetitions since we will schedule one now.632			.map(|(p, c)| (p, c - 1));633634		let s = Scheduled {635			maybe_id: Some(id.clone()),636			priority,637			call: call.clone(),638			maybe_periodic,639			origin: origin.clone(),640			_phantom: Default::default(),641		};642643		// reserve balance for periodic execution644		// let sender =645		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;646		// let repeats = match maybe_periodic {647		// 	Some(p) => p.1,648		// 	None => 1,649		// };650		// let _ = T::CallExecutor::reserve_balance(651		// 	id.clone(),652		// 	sender,653		// 	call.as_value().unwrap().clone(),654		// 	repeats,655		// );656657		Agenda::<T>::append(when, Some(s));658		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;659		let address = (when, index);660		Lookup::<T>::insert(&id, &address);661		Self::deposit_event(Event::Scheduled { when, index });662663		Ok(address)664	}665666	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {667		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {668			if let Some((when, index)) = lookup.take() {669				let i = index as usize;670				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {671					if let Some(s) = agenda.get_mut(i) {672						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {673							if matches!(674								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),675								Some(Ordering::Less) | None676							) {677								return Err(BadOrigin.into());678							}679							// release balance reserve680							// let sender = ensure_signed(681							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(682							// 		origin.unwrap(),683							// 	)684							// 	.into(),685							// )?;686							// let _ = T::CallExecutor::cancel_reserve(id, sender);687688							s.call.ensure_unrequested::<T::PreimageProvider>();689						}690						*s = None;691					}692					Ok(())693				})?;694695				Self::deposit_event(Event::Canceled { when, index });696				Ok(())697			} else {698				Err(Error::<T>::NotFound)?699			}700		})701	}702}
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//! # Schedulerdo_reschedule36//!37//! This Pallet exposes capabilities for scheduling dispatches to occur at a38//! specified block number or at a specified period. These scheduled dispatches39//! may be named or anonymous and may be canceled.40//!41//! **NOTE:** The scheduled calls will be dispatched with the default filter42//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin43//! except root which will get no filter. And not the filter contained in origin44//! use to call `fn schedule`.45//!46//! If a call is scheduled using proxy or whatever mecanism which adds filter,47//! then those filter will not be used when dispatching the schedule call.48//!49//! The scheduler is designed for deferred transaction calls by block number.50//! Any user can book a call of a certain transaction to a specific block number.51//! Also possible to book a call with a certain frequency.52//! Key differences from original pallet:53//! Id restricted by 16 bytes54//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block55//! Maybe_periodic limit is 100 calls56//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.57//! 58//! ## Interface59//!60//! ### Dispatchable Functions61//!62//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and63//!   with a specified priority.64//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.65//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter66//!   that can be used for identification.67//! * `cancel_named` - the named complement to the cancel function.6869// Ensure we're `no_std` when compiling for Wasm.70#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83	traits::{BadOrigin, One, Saturating, Zero},84	RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},90	traits::{91		schedule::{self, DispatchTime, MaybeHashed},92		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93		StorageVersion,94	},95	weights::{GetDispatchInfo, Weight},96};9798pub use weights::WeightInfo;99100/// Just a simple index for naming period tasks.101pub type PeriodicIndex = u32;102/// The location of a scheduled task that can be used to remove it.103pub type TaskAddress<BlockNumber> = (BlockNumber, u32);104pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;105106type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];107pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;108109/// Information regarding an item to be executed in the future.110#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]111#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]112pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {113	/// The unique identity for this task, if there is one.114	maybe_id: Option<ScheduledId>,115	/// This task's priority.116	priority: schedule::Priority,117	/// The call to be dispatched.118	call: Call,119	/// If the call is periodic, then this points to the information concerning that.120	maybe_periodic: Option<schedule::Period<BlockNumber>>,121	/// The origin to dispatch the call.122	origin: PalletsOrigin,123	_phantom: PhantomData<AccountId>,124}125126pub type ScheduledV3Of<T> = ScheduledV3<127	CallOrHashOf<T>,128	<T as frame_system::Config>::BlockNumber,129	<T as Config>::PalletsOrigin,130	<T as frame_system::Config>::AccountId,131>;132133pub type ScheduledOf<T> = ScheduledV3Of<T>;134135/// The current version of Scheduled struct.136pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =137	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;138139#[cfg(feature = "runtime-benchmarks")]140mod preimage_provider {141	use frame_support::traits::PreimageRecipient;142	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}143	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}144}145146#[cfg(not(feature = "runtime-benchmarks"))]147mod preimage_provider {148	use frame_support::traits::PreimageProvider;149	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}150	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}151}152153pub use preimage_provider::PreimageProviderAndMaybeRecipient;154155/// Weight templates for calculating actual fees156pub(crate) trait MarginalWeightInfo: WeightInfo {157	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {158		match (periodic, named, resolved) {159			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),160			(_, true, None) => {161				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)162			}163			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),164			(false, true, Some(false)) => {165				Self::on_initialize_named(2) - Self::on_initialize_named(1)166			}167			(true, false, Some(false)) => {168				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)169			}170			(true, true, Some(false)) => {171				Self::on_initialize_periodic_named_resolved(2)172					- Self::on_initialize_periodic_named_resolved(1)173			}174			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),175			(false, true, Some(true)) => {176				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)177			}178			(true, false, Some(true)) => {179				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)180			}181			(true, true, Some(true)) => {182				Self::on_initialize_periodic_named_resolved(2)183					- Self::on_initialize_periodic_named_resolved(1)184			}185		}186	}187}188impl<T: WeightInfo> MarginalWeightInfo for T {}189190#[frame_support::pallet]191pub mod pallet {192	use super::*;193	use frame_support::{194		dispatch::PostDispatchInfo,195		pallet_prelude::*,196		traits::{schedule::LookupError, PreimageProvider},197	};198	use frame_system::pallet_prelude::*;199200	/// The current storage version.201	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);202203	#[pallet::pallet]204	#[pallet::generate_store(pub(super) trait Store)]205	#[pallet::storage_version(STORAGE_VERSION)]206	#[pallet::without_storage_info]207	pub struct Pallet<T>(_);208209	/// `system::Config` should always be included in our implied traits.210	#[pallet::config]211	pub trait Config: frame_system::Config {212		/// The overarching event type.213		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;214215		/// The aggregated origin which the dispatch will take.216		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>217			+ From<Self::PalletsOrigin>218			+ IsType<<Self as system::Config>::Origin>;219220		/// The caller origin, overarching type of all pallets origins.221		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;222223		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;224225		/// The aggregated call type.226		type Call: Parameter227			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>228			+ GetDispatchInfo229			+ From<system::Call<Self>>;230231		/// The maximum weight that may be scheduled per block for any dispatchables of less232		/// priority than `schedule::HARD_DEADLINE`.233		#[pallet::constant]234		type MaximumWeight: Get<Weight>;235236		/// Required origin to schedule or cancel calls.237		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;238239		/// Compare the privileges of origins.240		///241		/// This will be used when canceling a task, to ensure that the origin that tries242		/// to cancel has greater or equal privileges as the origin that created the scheduled task.243		///244		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can245		/// be used. This will only check if two given origins are equal.246		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;247248		/// The maximum number of scheduled calls in the queue for a single block.249		/// Not strictly enforced, but used for weight estimation.250		#[pallet::constant]251		type MaxScheduledPerBlock: Get<u32>;252253		/// Weight information for extrinsics in this pallet.254		type WeightInfo: WeightInfo;255256		/// The preimage provider with which we look up call hashes to get the call.257		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;258259		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.260		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;261262		/// Sponsoring function. In this version sposorship is disabled263		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;264265		/// The helper type used for custom transaction fee logic.266		type CallExecutor: DispatchCall<Self, H160>;267	}268269	/// A Scheduler-Runtime interface for finer payment handling.270	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {271		/// Lock balance required for transaction payment272		fn reserve_balance(273			id: ScheduledId,274			sponsor: <T as frame_system::Config>::AccountId,275			call: <T as Config>::Call,276			count: u32,277		) -> Result<(), DispatchError>;278279		/// Unlock centain amount from payer 280		fn pay_for_call(281			id: ScheduledId,282			sponsor: <T as frame_system::Config>::AccountId,283			call: <T as Config>::Call,284		) -> Result<u128, DispatchError>;285286		/// Resolve the call dispatch, including any post-dispatch operations.287		fn dispatch_call(288			signer: T::AccountId,289			function: <T as Config>::Call,290		) -> Result<291			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,292			TransactionValidityError,293		>;294295		/// Cancel schedule reservation and unlock balance296		fn cancel_reserve(297			id: ScheduledId,298			sponsor: <T as frame_system::Config>::AccountId,299		) -> Result<u128, DispatchError>;300	}301302	/// Items to be executed, indexed by the block number that they should be executed on.303	#[pallet::storage]304	pub type Agenda<T: Config> =305		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;306307	/// Lookup from identity to the block number and index of the task.308	#[pallet::storage]309	pub(crate) type Lookup<T: Config> =310		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;311312	/// Events type.313	#[pallet::event]314	#[pallet::generate_deposit(pub(super) fn deposit_event)]315	pub enum Event<T: Config> {316		/// Scheduled some task.317		Scheduled { when: T::BlockNumber, index: u32 },318		/// Canceled some task.319		Canceled { when: T::BlockNumber, index: u32 },320		/// Dispatched some task.321		Dispatched {322			task: TaskAddress<T::BlockNumber>,323			id: Option<ScheduledId>,324			result: DispatchResult,325		},326		/// The call for the provided hash was not found so the task has been aborted.327		CallLookupFailed {328			task: TaskAddress<T::BlockNumber>,329			id: Option<ScheduledId>,330			error: LookupError,331		},332	}333334	#[pallet::error]335	pub enum Error<T> {336		/// Failed to schedule a call337		FailedToSchedule,338		/// Cannot find the scheduled call.339		NotFound,340		/// Given target block number is in the past.341		TargetBlockNumberInPast,342		/// Reschedule failed because it does not change scheduled time.343		RescheduleNoChange,344	}345346	#[pallet::hooks]347	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {348		/// Execute the scheduled calls349		fn on_initialize(now: T::BlockNumber) -> Weight {350			let limit = T::MaximumWeight::get();351352			let mut queued = Agenda::<T>::take(now)353				.into_iter()354				.enumerate()355				.filter_map(|(index, s)| Some((index as u32, s?)))356				.collect::<Vec<_>>();357358			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {359				log::warn!(360					target: "runtime::scheduler",361					"Warning: This block has more items queued in Scheduler than \362					expected from the runtime configuration. An update might be needed."363				);364			}365366			queued.sort_by_key(|(_, s)| s.priority);367368			let next = now + One::one();369370			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);371			for (order, (index, mut s)) in queued.into_iter().enumerate() {372				let named = if let Some(ref id) = s.maybe_id {373					Lookup::<T>::remove(id);374					true375				} else {376					false377				};378379				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();380				s.call = call;381382				let resolved = if let Some(completed) = maybe_completed {383					T::PreimageProvider::unrequest_preimage(&completed);384					true385				} else {386					false387				};388				let call = match s.call.as_value().cloned() {389					Some(c) => c,390					None => {391						// Preimage not available - postpone until some block.392						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));393						if let Some(delay) = T::NoPreimagePostponement::get() {394							let until = now.saturating_add(delay);395							if let Some(ref id) = s.maybe_id {396								let index = Agenda::<T>::decode_len(until).unwrap_or(0);397								Lookup::<T>::insert(id, (until, index as u32));398							}399							Agenda::<T>::append(until, Some(s));400						}401						continue;402					}403				};404405				let periodic = s.maybe_periodic.is_some();406				let call_weight = call.get_dispatch_info().weight;407				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));408				let origin =409					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())410						.into();411				if ensure_signed(origin).is_ok() {412					// Weights of Signed dispatches expect their signing account to be whitelisted.413					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));414				}415416				// We allow a scheduled call if any is true:417				// - It's priority is `HARD_DEADLINE`418				// - It does not push the weight past the limit.419				// - It is the first item in the schedule420				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;421				let test_weight = total_weight422					.saturating_add(call_weight)423					.saturating_add(item_weight);424				if !hard_deadline && order > 0 && test_weight > limit {425					// Cannot be scheduled this block - postpone until next.426					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));427					if let Some(ref id) = s.maybe_id {428						// NOTE: We could reasonably not do this (in which case there would be one429						// block where the named and delayed item could not be referenced by name),430						// but we will do it anyway since it should be mostly free in terms of431						// weight and it is slightly cleaner.432						let index = Agenda::<T>::decode_len(next).unwrap_or(0);433						Lookup::<T>::insert(id, (next, index as u32));434					}435					Agenda::<T>::append(next, Some(s));436					continue;437				}438439				// Sender is the account who signed transaction440				let sender = ensure_signed(441					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())442						.into(),443				)444				.unwrap();445446				// // if call have id it was be reserved447				// if s.maybe_id.is_some() {448				// 	let _ = T::CallExecutor::pay_for_call(449				// 		s.maybe_id.unwrap(),450				// 		sender.clone(),451				// 		call.clone(),452				// 	);453				// }454455				// Execute transaction via chain default pipeline456				let r = T::CallExecutor::dispatch_call(sender, call.clone());457458				let mut actual_call_weight: Weight = item_weight;459				let result: Result<_, DispatchError> = match r {460					Ok(o) => match o {461						Ok(di) => {462							actual_call_weight = di.actual_weight.unwrap_or(item_weight);463							Ok(())464						}465						Err(err) => Err(err.error),466					},467					Err(_) => {468						log::error!(469							target: "runtime::scheduler",470							"Warning: Scheduler has failed to execute a post-dispatch transaction. \471							This block might have become invalid.");472						Err(DispatchError::CannotLookup)473					} // todo possibly force a skip/return here, do something with the error474				};475476				total_weight.saturating_accrue(item_weight);477				total_weight.saturating_accrue(actual_call_weight);478479				Self::deposit_event(Event::Dispatched {480					task: (now, index),481					id: s.maybe_id.clone(),482					result,483				});484485				if let &Some((period, count)) = &s.maybe_periodic {486					if count > 1 {487						s.maybe_periodic = Some((period, count - 1));488					} else {489						s.maybe_periodic = None;490					}491					let wake = now + period;492					// If scheduled is named, place its information in `Lookup`493					if let Some(ref id) = s.maybe_id {494						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);495						Lookup::<T>::insert(id, (wake, wake_index as u32));496					}497					Agenda::<T>::append(wake, Some(s));498				}499			}500			/// Weight should be 0, because transaction already paid 501			0502		}503	}504505	#[pallet::call]506	impl<T: Config> Pallet<T> {507		/// Schedule a named task.508		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]509		pub fn schedule_named(510			origin: OriginFor<T>,511			id: ScheduledId,512			when: T::BlockNumber,513			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,514			priority: schedule::Priority,515			call: Box<CallOrHashOf<T>>,516		) -> DispatchResult {517			T::ScheduleOrigin::ensure_origin(origin.clone())?;518			let origin = <T as Config>::Origin::from(origin);519			Self::do_schedule_named(520				id,521				DispatchTime::At(when),522				maybe_periodic,523				priority,524				origin.caller().clone(),525				*call,526			)?;527			Ok(())528		}529530		/// Cancel a named scheduled task.531		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]532		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {533			T::ScheduleOrigin::ensure_origin(origin.clone())?;534			let origin = <T as Config>::Origin::from(origin);535			Self::do_cancel_named(Some(origin.caller().clone()), id)?;536			Ok(())537		}538539		/// Schedule a named task after a delay.540		///541		/// # <weight>542		/// Same as [`schedule_named`](Self::schedule_named).543		/// # </weight>544		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]545		pub fn schedule_named_after(546			origin: OriginFor<T>,547			id: ScheduledId,548			after: T::BlockNumber,549			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,550			priority: schedule::Priority,551			call: Box<CallOrHashOf<T>>,552		) -> DispatchResult {553			T::ScheduleOrigin::ensure_origin(origin.clone())?;554			let origin = <T as Config>::Origin::from(origin);555			Self::do_schedule_named(556				id,557				DispatchTime::After(after),558				maybe_periodic,559				priority,560				origin.caller().clone(),561				*call,562			)?;563			Ok(())564		}565	}566}567568impl<T: Config> Pallet<T> {569	#[cfg(feature = "try-runtime")]570	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {571		Ok(())572	}573574	#[cfg(feature = "try-runtime")]575	pub fn post_migrate_to_v3() -> Result<(), &'static str> {576		use frame_support::dispatch::GetStorageVersion;577578		assert!(Self::current_storage_version() == 3);579		for k in Agenda::<T>::iter_keys() {580			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;581		}582		Ok(())583	}584585	/// Helper to migrate scheduler when the pallet origin type has changed.586	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {587		Agenda::<T>::translate::<588			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,589			_,590		>(|_, agenda| {591			Some(592				agenda593					.into_iter()594					.map(|schedule| {595						schedule.map(|schedule| Scheduled {596							maybe_id: schedule.maybe_id,597							priority: schedule.priority,598							call: schedule.call,599							maybe_periodic: schedule.maybe_periodic,600							origin: schedule.origin.into(),601							_phantom: Default::default(),602						})603					})604					.collect::<Vec<_>>(),605			)606		});607	}608609	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {610		let now = frame_system::Pallet::<T>::block_number();611612		let when = match when {613			DispatchTime::At(x) => x,614			// The current block has already completed it's scheduled tasks, so615			// Schedule the task at lest one block after this current block.616			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),617		};618619		if when <= now {620			return Err(Error::<T>::TargetBlockNumberInPast.into());621		}622623		Ok(when)624	}625626	fn do_schedule_named(627		id: ScheduledId,628		when: DispatchTime<T::BlockNumber>,629		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,630		priority: schedule::Priority,631		origin: T::PalletsOrigin,632		call: CallOrHashOf<T>,633	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {634		// ensure id it is unique635		if Lookup::<T>::contains_key(&id) {636			return Err(Error::<T>::FailedToSchedule)?;637		}638639		let when = Self::resolve_time(when)?;640641		call.ensure_requested::<T::PreimageProvider>();642643		// sanitize maybe_periodic644		let maybe_periodic = maybe_periodic645			.filter(|p| p.1 > 1 && !p.0.is_zero())646			// Remove one from the number of repetitions since we will schedule one now.647			.map(|(p, c)| (p, c - 1));648649		let s = Scheduled {650			maybe_id: Some(id.clone()),651			priority,652			call: call.clone(),653			maybe_periodic,654			origin: origin.clone(),655			_phantom: Default::default(),656		};657658		// reserve balance for periodic execution659		// let sender =660		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;661		// let repeats = match maybe_periodic {662		// 	Some(p) => p.1,663		// 	None => 1,664		// };665		// let _ = T::CallExecutor::reserve_balance(666		// 	id.clone(),667		// 	sender,668		// 	call.as_value().unwrap().clone(),669		// 	repeats,670		// );671672		Agenda::<T>::append(when, Some(s));673		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;674		let address = (when, index);675		Lookup::<T>::insert(&id, &address);676		Self::deposit_event(Event::Scheduled { when, index });677678		Ok(address)679	}680681	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {682		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {683			if let Some((when, index)) = lookup.take() {684				let i = index as usize;685				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {686					if let Some(s) = agenda.get_mut(i) {687						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {688							if matches!(689								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),690								Some(Ordering::Less) | None691							) {692								return Err(BadOrigin.into());693							}694							// release balance reserve695							// let sender = ensure_signed(696							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(697							// 		origin.unwrap(),698							// 	)699							// 	.into(),700							// )?;701							// let _ = T::CallExecutor::cancel_reserve(id, sender);702703							s.call.ensure_unrequested::<T::PreimageProvider>();704						}705						*s = None;706					}707					Ok(())708				})?;709710				Self::deposit_event(Event::Canceled { when, index });711				Ok(())712			} else {713				Err(Error::<T>::NotFound)?714			}715		})716	}717}