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

difftreelog

source

pallets/scheduler/src/lib.rs24.0 KiBsourcehistory
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.0>28//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//! should be named and may be canceled.47//!48//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.49//! Any user can book a call of a certain transaction to a specific block number.50//! Also possible to book a call with a certain frequency.51//!52//! Key differences from the original pallet:53//! <https://crates.io/crates/pallet-scheduler>54//! Schedule Id restricted by 16 bytes. Identificator for booked call.55//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block.56//! The maximum weight that may be scheduled per block for any dispatchables of less priority than `schedule::HARD_DEADLINE`.57//! Maybe_periodic limit is 100 calls. Reserved for future sponsored transaction support.58//! At 100 calls reserved amount is not so much and this is avoid potential problems with balance locks.59//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.60//!61//! ## Interface62//!63//! ### Dispatchable Functions64//!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, GetDispatchInfo},90	traits::{91		schedule::{self, DispatchTime, MaybeHashed},92		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93		StorageVersion,94	},95	weights::{Weight},96};9798pub use weights::WeightInfo;99100/// The location of a scheduled task that can be used to remove it.101pub type TaskAddress<BlockNumber> = (BlockNumber, u32);102pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;103104type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];105pub type CallOrHashOf<T> =106	MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;107108/// Information regarding an item to be executed in the future.109#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]110#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]111pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {112	/// The unique identity for this task, if there is one.113	maybe_id: Option<ScheduledId>,114	/// This task's priority.115	priority: schedule::Priority,116	/// The call to be dispatched.117	call: Call,118	/// If the call is periodic, then this points to the information concerning that.119	maybe_periodic: Option<schedule::Period<BlockNumber>>,120	/// The origin to dispatch the call.121	origin: PalletsOrigin,122	_phantom: PhantomData<AccountId>,123}124125pub type ScheduledV3Of<T> = ScheduledV3<126	CallOrHashOf<T>,127	<T as frame_system::Config>::BlockNumber,128	<T as Config>::PalletsOrigin,129	<T as frame_system::Config>::AccountId,130>;131132pub type ScheduledOf<T> = ScheduledV3Of<T>;133134/// The current version of Scheduled struct.135pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =136	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;137138#[cfg(feature = "runtime-benchmarks")]139mod preimage_provider {140	use frame_support::traits::PreimageRecipient;141	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}142	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}143}144145#[cfg(not(feature = "runtime-benchmarks"))]146mod preimage_provider {147	use frame_support::traits::PreimageProvider;148	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}149	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}150}151152pub use preimage_provider::PreimageProviderAndMaybeRecipient;153154pub(crate) trait MarginalWeightInfo: WeightInfo {155	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {156		match (periodic, named, resolved) {157			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),158			(_, true, None) => {159				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)160			}161			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),162			(false, true, Some(false)) => {163				Self::on_initialize_named(2) - Self::on_initialize_named(1)164			}165			(true, false, Some(false)) => {166				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)167			}168			(true, true, Some(false)) => {169				Self::on_initialize_periodic_named_resolved(2)170					- Self::on_initialize_periodic_named_resolved(1)171			}172			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),173			(false, true, Some(true)) => {174				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)175			}176			(true, false, Some(true)) => {177				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)178			}179			(true, true, Some(true)) => {180				Self::on_initialize_periodic_named_resolved(2)181					- Self::on_initialize_periodic_named_resolved(1)182			}183		}184	}185}186impl<T: WeightInfo> MarginalWeightInfo for T {}187188#[frame_support::pallet]189pub mod pallet {190	use super::*;191	use frame_support::{192		dispatch::PostDispatchInfo,193		pallet_prelude::*,194		traits::{schedule::LookupError, PreimageProvider},195	};196	use frame_system::pallet_prelude::*;197198	/// The current storage version.199	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);200201	#[pallet::pallet]202	#[pallet::generate_store(pub(super) trait Store)]203	#[pallet::storage_version(STORAGE_VERSION)]204	#[pallet::without_storage_info]205	pub struct Pallet<T>(_);206207	/// `system::Config` should always be included in our implied traits.208	#[pallet::config]209	pub trait Config: frame_system::Config {210		/// The overarching event type.211		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;212213		/// The aggregated origin which the dispatch will take.214		type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>215			+ From<Self::PalletsOrigin>216			+ IsType<<Self as system::Config>::RuntimeOrigin>;217218		/// The caller origin, overarching type of all pallets origins.219		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;220221		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;222223		/// The aggregated call type.224		type RuntimeCall: Parameter225			+ Dispatchable<226				RuntimeOrigin = <Self as Config>::RuntimeOrigin,227				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>::RuntimeOrigin>;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.263		// 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		/// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.272		fn reserve_balance(273			id: ScheduledId,274			sponsor: <T as frame_system::Config>::AccountId,275			call: <T as Config>::RuntimeCall,276			count: u32,277		) -> Result<(), DispatchError>;278279		/// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.280		fn pay_for_call(281			id: ScheduledId,282			sponsor: <T as frame_system::Config>::AccountId,283			call: <T as Config>::RuntimeCall,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>::RuntimeCall,290		) -> Result<291			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,292			TransactionValidityError,293		>;294295		/// Release unspent reserved funds in case of a schedule cancel.296		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 = s.maybe_id.is_some();373374				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();375				s.call = call;376377				let resolved = if let Some(completed) = maybe_completed {378					T::PreimageProvider::unrequest_preimage(&completed);379					true380				} else {381					false382				};383				let call = match s.call.as_value().cloned() {384					Some(c) => c,385					None => {386						// Preimage not available - postpone until some block.387						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));388						if let Some(delay) = T::NoPreimagePostponement::get() {389							let until = now.saturating_add(delay);390							if let Some(ref id) = s.maybe_id {391								let index = Agenda::<T>::decode_len(until).unwrap_or(0);392								Lookup::<T>::insert(id, (until, index as u32));393							}394							Agenda::<T>::append(until, Some(s));395						}396						continue;397					}398				};399400				let periodic = s.maybe_periodic.is_some();401				let call_weight = call.get_dispatch_info().weight;402				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));403				let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(404					s.origin.clone(),405				)406				.into();407				if ensure_signed(origin).is_ok() {408					// Weights of Signed dispatches expect their signing account to be whitelisted.409					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));410				}411412				// We allow a scheduled call if any is true:413				// - It's priority is `HARD_DEADLINE`414				// - It does not push the weight past the limit.415				// - It is the first item in the schedule416				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;417				let test_weight = total_weight418					.saturating_add(call_weight)419					.saturating_add(item_weight);420				if !hard_deadline && order > 0 && test_weight.all_gt(limit) {421					// Cannot be scheduled this block - postpone until next.422					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));423					if let Some(ref id) = s.maybe_id {424						// NOTE: We could reasonably not do this (in which case there would be one425						// block where the named and delayed item could not be referenced by name),426						// but we will do it anyway since it should be mostly free in terms of427						// weight and it is slightly cleaner.428						let index = Agenda::<T>::decode_len(next).unwrap_or(0);429						Lookup::<T>::insert(id, (next, index as u32));430					}431					Agenda::<T>::append(next, Some(s));432					continue;433				}434435				let sender = ensure_signed(436					<<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(437						s.origin.clone(),438					)439					.into(),440				)441				.unwrap();442443				// // if call have id it was be reserved444				// if s.maybe_id.is_some() {445				// 	let _ = T::CallExecutor::pay_for_call(446				// 		s.maybe_id.unwrap(),447				// 		sender.clone(),448				// 		call.clone(),449				// 	);450				// }451452				// Execute transaction via chain default pipeline453				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken454				let r = T::CallExecutor::dispatch_call(sender, call.clone());455456				let mut actual_call_weight: Weight = item_weight;457				let result: Result<_, DispatchError> = match r {458					Ok(o) => match o {459						Ok(di) => {460							actual_call_weight = di.actual_weight.unwrap_or(item_weight);461							Ok(())462						}463						Err(err) => Err(err.error),464					},465					Err(_) => {466						log::error!(467							target: "runtime::scheduler",468							"Warning: Scheduler has failed to execute a post-dispatch transaction. \469							This block might have become invalid.");470						Err(DispatchError::CannotLookup)471					} // todo possibly force a skip/return here, do something with the error472				};473474				total_weight.saturating_accrue(item_weight);475				total_weight.saturating_accrue(actual_call_weight);476477				Self::deposit_event(Event::Dispatched {478					task: (now, index),479					id: s.maybe_id.clone(),480					result,481				});482483				if let &Some((period, count)) = &s.maybe_periodic {484					if count > 1 {485						s.maybe_periodic = Some((period, count - 1));486					} else {487						s.maybe_periodic = None;488					}489					let wake = now + period;490					let is_canceled;491492					// If scheduled is named, place its information in `Lookup`493					if let Some(ref id) = s.maybe_id {494						is_canceled = Lookup::<T>::get(id).is_none();495						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);496497						if !is_canceled {498							Lookup::<T>::insert(id, (wake, wake_index as u32));499						}500					} else {501						is_canceled = false;502					}503504					if !is_canceled {505						Agenda::<T>::append(wake, Some(s));506					}507				} else if let Some(ref id) = s.maybe_id {508					Lookup::<T>::remove(id);509				}510			}511			// Total weight should be 0, because the transaction is already paid for512			Weight::zero()513		}514	}515516	#[pallet::call]517	impl<T: Config> Pallet<T> {518		/// Schedule a named task.519		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]520		pub fn schedule_named(521			origin: OriginFor<T>,522			id: ScheduledId,523			when: T::BlockNumber,524			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,525			priority: schedule::Priority,526			call: Box<CallOrHashOf<T>>,527		) -> DispatchResult {528			T::ScheduleOrigin::ensure_origin(origin.clone())?;529			let origin = <T as Config>::RuntimeOrigin::from(origin);530			Self::do_schedule_named(531				id,532				DispatchTime::At(when),533				maybe_periodic,534				priority,535				origin.caller().clone(),536				*call,537			)?;538			Ok(())539		}540541		/// Cancel a named scheduled task.542		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]543		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {544			T::ScheduleOrigin::ensure_origin(origin.clone())?;545			let origin = <T as Config>::RuntimeOrigin::from(origin);546			Self::do_cancel_named(Some(origin.caller().clone()), id)?;547			Ok(())548		}549550		/// Schedule a named task after a delay.551		///552		/// # <weight>553		/// Same as [`schedule_named`](Self::schedule_named).554		/// # </weight>555		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]556		pub fn schedule_named_after(557			origin: OriginFor<T>,558			id: ScheduledId,559			after: T::BlockNumber,560			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,561			priority: schedule::Priority,562			call: Box<CallOrHashOf<T>>,563		) -> DispatchResult {564			T::ScheduleOrigin::ensure_origin(origin.clone())?;565			let origin = <T as Config>::RuntimeOrigin::from(origin);566			Self::do_schedule_named(567				id,568				DispatchTime::After(after),569				maybe_periodic,570				priority,571				origin.caller().clone(),572				*call,573			)?;574			Ok(())575		}576	}577}578579impl<T: Config> Pallet<T> {580	#[cfg(feature = "try-runtime")]581	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {582		Ok(())583	}584585	#[cfg(feature = "try-runtime")]586	pub fn post_migrate_to_v3() -> Result<(), &'static str> {587		use frame_support::dispatch::GetStorageVersion;588589		assert!(Self::current_storage_version() == 3);590		for k in Agenda::<T>::iter_keys() {591			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;592		}593		Ok(())594	}595596	/// Helper to migrate scheduler when the pallet origin type has changed.597	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {598		Agenda::<T>::translate::<599			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,600			_,601		>(|_, agenda| {602			Some(603				agenda604					.into_iter()605					.map(|schedule| {606						schedule.map(|schedule| Scheduled {607							maybe_id: schedule.maybe_id,608							priority: schedule.priority,609							call: schedule.call,610							maybe_periodic: schedule.maybe_periodic,611							origin: schedule.origin.into(),612							_phantom: Default::default(),613						})614					})615					.collect::<Vec<_>>(),616			)617		});618	}619620	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {621		let now = frame_system::Pallet::<T>::block_number();622623		let when = match when {624			DispatchTime::At(x) => x,625			// The current block has already completed it's scheduled tasks, so626			// Schedule the task at lest one block after this current block.627			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),628		};629630		if when <= now {631			return Err(Error::<T>::TargetBlockNumberInPast.into());632		}633634		Ok(when)635	}636637	fn do_schedule_named(638		id: ScheduledId,639		when: DispatchTime<T::BlockNumber>,640		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,641		priority: schedule::Priority,642		origin: T::PalletsOrigin,643		call: CallOrHashOf<T>,644	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {645		// ensure id it is unique646		if Lookup::<T>::contains_key(&id) {647			return Err(Error::<T>::FailedToSchedule)?;648		}649650		let when = Self::resolve_time(when)?;651652		call.ensure_requested::<T::PreimageProvider>();653654		// sanitize maybe_periodic655		let maybe_periodic = maybe_periodic656			.filter(|p| p.1 > 1 && !p.0.is_zero())657			// Remove one from the number of repetitions since we will schedule one now.658			.map(|(p, c)| (p, c - 1));659660		let s = Scheduled {661			maybe_id: Some(id.clone()),662			priority,663			call: call.clone(),664			maybe_periodic,665			origin: origin.clone(),666			_phantom: Default::default(),667		};668669		// reserve balance for periodic execution670		// let sender =671		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;672		// let repeats = match maybe_periodic {673		// 	Some(p) => p.1,674		// 	None => 1,675		// };676		// let _ = T::CallExecutor::reserve_balance(677		// 	id.clone(),678		// 	sender,679		// 	call.as_value().unwrap().clone(),680		// 	repeats,681		// );682683		Agenda::<T>::append(when, Some(s));684		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;685		let address = (when, index);686		Lookup::<T>::insert(&id, &address);687		Self::deposit_event(Event::Scheduled { when, index });688689		Ok(address)690	}691692	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {693		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {694			if let Some((when, index)) = lookup.take() {695				let i = index as usize;696				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {697					if let Some(s) = agenda.get_mut(i) {698						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {699							if matches!(700								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),701								Some(Ordering::Less) | None702							) {703								return Err(BadOrigin.into());704							}705							// release balance reserve706							// let sender = ensure_signed(707							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(708							// 		origin.unwrap(),709							// 	)710							// 	.into(),711							// )?;712							// let _ = T::CallExecutor::cancel_reserve(id, sender);713714							s.call.ensure_unrequested::<T::PreimageProvider>();715						}716						*s = None;717					}718					Ok(())719				})?;720721				Self::deposit_event(Event::Canceled { when, index });722				Ok(())723			} else {724				Err(Error::<T>::NotFound)?725			}726		})727	}728}