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

difftreelog

source

pallets/scheduler/src/lib.rs23.7 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},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;154155pub(crate) trait MarginalWeightInfo: WeightInfo {156	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {157		match (periodic, named, resolved) {158			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),159			(_, true, None) => {160				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)161			}162			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),163			(false, true, Some(false)) => {164				Self::on_initialize_named(2) - Self::on_initialize_named(1)165			}166			(true, false, Some(false)) => {167				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)168			}169			(true, true, Some(false)) => {170				Self::on_initialize_periodic_named_resolved(2)171					- Self::on_initialize_periodic_named_resolved(1)172			}173			(false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),174			(false, true, Some(true)) => {175				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)176			}177			(true, false, Some(true)) => {178				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)179			}180			(true, true, Some(true)) => {181				Self::on_initialize_periodic_named_resolved(2)182					- Self::on_initialize_periodic_named_resolved(1)183			}184		}185	}186}187impl<T: WeightInfo> MarginalWeightInfo for T {}188189#[frame_support::pallet]190pub mod pallet {191	use super::*;192	use frame_support::{193		dispatch::PostDispatchInfo,194		pallet_prelude::*,195		traits::{schedule::LookupError, PreimageProvider},196	};197	use frame_system::pallet_prelude::*;198199	/// The current storage version.200	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);201202	#[pallet::pallet]203	#[pallet::generate_store(pub(super) trait Store)]204	#[pallet::storage_version(STORAGE_VERSION)]205	#[pallet::without_storage_info]206	pub struct Pallet<T>(_);207208	/// `system::Config` should always be included in our implied traits.209	#[pallet::config]210	pub trait Config: frame_system::Config {211		/// The overarching event type.212		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;213214		/// The aggregated origin which the dispatch will take.215		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>216			+ From<Self::PalletsOrigin>217			+ IsType<<Self as system::Config>::Origin>;218219		/// The caller origin, overarching type of all pallets origins.220		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;221222		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;223224		/// The aggregated call type.225		type Call: Parameter226			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>227			+ GetDispatchInfo228			+ From<system::Call<Self>>;229230		/// The maximum weight that may be scheduled per block for any dispatchables of less231		/// priority than `schedule::HARD_DEADLINE`.232		#[pallet::constant]233		type MaximumWeight: Get<Weight>;234235		/// Required origin to schedule or cancel calls.236		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;237238		/// Compare the privileges of origins.239		///240		/// This will be used when canceling a task, to ensure that the origin that tries241		/// to cancel has greater or equal privileges as the origin that created the scheduled task.242		///243		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can244		/// be used. This will only check if two given origins are equal.245		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;246247		/// The maximum number of scheduled calls in the queue for a single block.248		/// Not strictly enforced, but used for weight estimation.249		#[pallet::constant]250		type MaxScheduledPerBlock: Get<u32>;251252		/// Weight information for extrinsics in this pallet.253		type WeightInfo: WeightInfo;254255		/// The preimage provider with which we look up call hashes to get the call.256		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;257258		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.259		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;260261		/// Sponsoring function.262		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;263264		/// The helper type used for custom transaction fee logic.265		type CallExecutor: DispatchCall<Self, H160>;266	}267268	/// A Scheduler-Runtime interface for finer payment handling.269	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {270		/// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.271		fn reserve_balance(272			id: ScheduledId,273			sponsor: <T as frame_system::Config>::AccountId,274			call: <T as Config>::Call,275			count: u32,276		) -> Result<(), DispatchError>;277278		/// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.279		fn pay_for_call(280			id: ScheduledId,281			sponsor: <T as frame_system::Config>::AccountId,282			call: <T as Config>::Call,283		) -> Result<u128, DispatchError>;284285		/// Resolve the call dispatch, including any post-dispatch operations.286		fn dispatch_call(287			signer: T::AccountId,288			function: <T as Config>::Call,289		) -> Result<290			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,291			TransactionValidityError,292		>;293294		/// Release unspent reserved funds in case of a schedule cancel.295		fn cancel_reserve(296			id: ScheduledId,297			sponsor: <T as frame_system::Config>::AccountId,298		) -> Result<u128, DispatchError>;299	}300301	/// Items to be executed, indexed by the block number that they should be executed on.302	#[pallet::storage]303	pub type Agenda<T: Config> =304		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;305306	/// Lookup from identity to the block number and index of the task.307	#[pallet::storage]308	pub(crate) type Lookup<T: Config> =309		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;310311	/// Events type.312	#[pallet::event]313	#[pallet::generate_deposit(pub(super) fn deposit_event)]314	pub enum Event<T: Config> {315		/// Scheduled some task.316		Scheduled { when: T::BlockNumber, index: u32 },317		/// Canceled some task.318		Canceled { when: T::BlockNumber, index: u32 },319		/// Dispatched some task.320		Dispatched {321			task: TaskAddress<T::BlockNumber>,322			id: Option<ScheduledId>,323			result: DispatchResult,324		},325		/// The call for the provided hash was not found so the task has been aborted.326		CallLookupFailed {327			task: TaskAddress<T::BlockNumber>,328			id: Option<ScheduledId>,329			error: LookupError,330		},331	}332333	#[pallet::error]334	pub enum Error<T> {335		/// Failed to schedule a call336		FailedToSchedule,337		/// Cannot find the scheduled call.338		NotFound,339		/// Given target block number is in the past.340		TargetBlockNumberInPast,341		/// Reschedule failed because it does not change scheduled time.342		RescheduleNoChange,343	}344345	#[pallet::hooks]346	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {347		/// Execute the scheduled calls348		fn on_initialize(now: T::BlockNumber) -> Weight {349			let limit = T::MaximumWeight::get();350351			let mut queued = Agenda::<T>::take(now)352				.into_iter()353				.enumerate()354				.filter_map(|(index, s)| Some((index as u32, s?)))355				.collect::<Vec<_>>();356357			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {358				log::warn!(359					target: "runtime::scheduler",360					"Warning: This block has more items queued in Scheduler than \361					expected from the runtime configuration. An update might be needed."362				);363			}364365			queued.sort_by_key(|(_, s)| s.priority);366367			let next = now + One::one();368369			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);370			for (order, (index, mut s)) in queued.into_iter().enumerate() {371				let named = if let Some(ref id) = s.maybe_id {372					Lookup::<T>::remove(id);373					true374				} else {375					false376				};377378				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();379				s.call = call;380381				let resolved = if let Some(completed) = maybe_completed {382					T::PreimageProvider::unrequest_preimage(&completed);383					true384				} else {385					false386				};387				let call = match s.call.as_value().cloned() {388					Some(c) => c,389					None => {390						// Preimage not available - postpone until some block.391						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));392						if let Some(delay) = T::NoPreimagePostponement::get() {393							let until = now.saturating_add(delay);394							if let Some(ref id) = s.maybe_id {395								let index = Agenda::<T>::decode_len(until).unwrap_or(0);396								Lookup::<T>::insert(id, (until, index as u32));397							}398							Agenda::<T>::append(until, Some(s));399						}400						continue;401					}402				};403404				let periodic = s.maybe_periodic.is_some();405				let call_weight = call.get_dispatch_info().weight;406				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));407				let origin =408					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())409						.into();410				if ensure_signed(origin).is_ok() {411					// Weights of Signed dispatches expect their signing account to be whitelisted.412					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));413				}414415				// We allow a scheduled call if any is true:416				// - It's priority is `HARD_DEADLINE`417				// - It does not push the weight past the limit.418				// - It is the first item in the schedule419				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;420				let test_weight = total_weight421					.saturating_add(call_weight)422					.saturating_add(item_weight);423				if !hard_deadline && order > 0 && test_weight > limit {424					// Cannot be scheduled this block - postpone until next.425					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));426					if let Some(ref id) = s.maybe_id {427						// NOTE: We could reasonably not do this (in which case there would be one428						// block where the named and delayed item could not be referenced by name),429						// but we will do it anyway since it should be mostly free in terms of430						// weight and it is slightly cleaner.431						let index = Agenda::<T>::decode_len(next).unwrap_or(0);432						Lookup::<T>::insert(id, (next, index as u32));433					}434					Agenda::<T>::append(next, Some(s));435					continue;436				}437438				let sender = ensure_signed(439					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())440						.into(),441				)442				.unwrap();443444				// // if call have id it was be reserved445				// if s.maybe_id.is_some() {446				// 	let _ = T::CallExecutor::pay_for_call(447				// 		s.maybe_id.unwrap(),448				// 		sender.clone(),449				// 		call.clone(),450				// 	);451				// }452453				// Execute transaction via chain default pipeline454				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken455				let r = T::CallExecutor::dispatch_call(sender, call.clone());456457				let mut actual_call_weight: Weight = item_weight;458				let result: Result<_, DispatchError> = match r {459					Ok(o) => match o {460						Ok(di) => {461							actual_call_weight = di.actual_weight.unwrap_or(item_weight);462							Ok(())463						}464						Err(err) => Err(err.error),465					},466					Err(_) => {467						log::error!(468							target: "runtime::scheduler",469							"Warning: Scheduler has failed to execute a post-dispatch transaction. \470							This block might have become invalid.");471						Err(DispatchError::CannotLookup)472					} // todo possibly force a skip/return here, do something with the error473				};474475				total_weight.saturating_accrue(item_weight);476				total_weight.saturating_accrue(actual_call_weight);477478				Self::deposit_event(Event::Dispatched {479					task: (now, index),480					id: s.maybe_id.clone(),481					result,482				});483484				if let &Some((period, count)) = &s.maybe_periodic {485					if count > 1 {486						s.maybe_periodic = Some((period, count - 1));487					} else {488						s.maybe_periodic = None;489					}490					let wake = now + period;491					// If scheduled is named, place its information in `Lookup`492					if let Some(ref id) = s.maybe_id {493						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);494						Lookup::<T>::insert(id, (wake, wake_index as u32));495					}496					Agenda::<T>::append(wake, Some(s));497				}498			}499			// Total weight should be 0, because the transaction is already paid for500			0501		}502	}503504	#[pallet::call]505	impl<T: Config> Pallet<T> {506		/// Schedule a named task.507		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]508		pub fn schedule_named(509			origin: OriginFor<T>,510			id: ScheduledId,511			when: T::BlockNumber,512			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,513			priority: schedule::Priority,514			call: Box<CallOrHashOf<T>>,515		) -> DispatchResult {516			T::ScheduleOrigin::ensure_origin(origin.clone())?;517			let origin = <T as Config>::Origin::from(origin);518			Self::do_schedule_named(519				id,520				DispatchTime::At(when),521				maybe_periodic,522				priority,523				origin.caller().clone(),524				*call,525			)?;526			Ok(())527		}528529		/// Cancel a named scheduled task.530		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]531		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {532			T::ScheduleOrigin::ensure_origin(origin.clone())?;533			let origin = <T as Config>::Origin::from(origin);534			Self::do_cancel_named(Some(origin.caller().clone()), id)?;535			Ok(())536		}537538		/// Schedule a named task after a delay.539		///540		/// # <weight>541		/// Same as [`schedule_named`](Self::schedule_named).542		/// # </weight>543		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]544		pub fn schedule_named_after(545			origin: OriginFor<T>,546			id: ScheduledId,547			after: T::BlockNumber,548			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,549			priority: schedule::Priority,550			call: Box<CallOrHashOf<T>>,551		) -> DispatchResult {552			T::ScheduleOrigin::ensure_origin(origin.clone())?;553			let origin = <T as Config>::Origin::from(origin);554			Self::do_schedule_named(555				id,556				DispatchTime::After(after),557				maybe_periodic,558				priority,559				origin.caller().clone(),560				*call,561			)?;562			Ok(())563		}564	}565}566567impl<T: Config> Pallet<T> {568	#[cfg(feature = "try-runtime")]569	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {570		Ok(())571	}572573	#[cfg(feature = "try-runtime")]574	pub fn post_migrate_to_v3() -> Result<(), &'static str> {575		use frame_support::dispatch::GetStorageVersion;576577		assert!(Self::current_storage_version() == 3);578		for k in Agenda::<T>::iter_keys() {579			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;580		}581		Ok(())582	}583584	/// Helper to migrate scheduler when the pallet origin type has changed.585	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {586		Agenda::<T>::translate::<587			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,588			_,589		>(|_, agenda| {590			Some(591				agenda592					.into_iter()593					.map(|schedule| {594						schedule.map(|schedule| Scheduled {595							maybe_id: schedule.maybe_id,596							priority: schedule.priority,597							call: schedule.call,598							maybe_periodic: schedule.maybe_periodic,599							origin: schedule.origin.into(),600							_phantom: Default::default(),601						})602					})603					.collect::<Vec<_>>(),604			)605		});606	}607608	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {609		let now = frame_system::Pallet::<T>::block_number();610611		let when = match when {612			DispatchTime::At(x) => x,613			// The current block has already completed it's scheduled tasks, so614			// Schedule the task at lest one block after this current block.615			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),616		};617618		if when <= now {619			return Err(Error::<T>::TargetBlockNumberInPast.into());620		}621622		Ok(when)623	}624625	fn do_schedule_named(626		id: ScheduledId,627		when: DispatchTime<T::BlockNumber>,628		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,629		priority: schedule::Priority,630		origin: T::PalletsOrigin,631		call: CallOrHashOf<T>,632	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {633		// ensure id it is unique634		if Lookup::<T>::contains_key(&id) {635			return Err(Error::<T>::FailedToSchedule)?;636		}637638		let when = Self::resolve_time(when)?;639640		call.ensure_requested::<T::PreimageProvider>();641642		// sanitize maybe_periodic643		let maybe_periodic = maybe_periodic644			.filter(|p| p.1 > 1 && !p.0.is_zero())645			// Remove one from the number of repetitions since we will schedule one now.646			.map(|(p, c)| (p, c - 1));647648		let s = Scheduled {649			maybe_id: Some(id.clone()),650			priority,651			call: call.clone(),652			maybe_periodic,653			origin: origin.clone(),654			_phantom: Default::default(),655		};656657		// reserve balance for periodic execution658		// let sender =659		// 	ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;660		// let repeats = match maybe_periodic {661		// 	Some(p) => p.1,662		// 	None => 1,663		// };664		// let _ = T::CallExecutor::reserve_balance(665		// 	id.clone(),666		// 	sender,667		// 	call.as_value().unwrap().clone(),668		// 	repeats,669		// );670671		Agenda::<T>::append(when, Some(s));672		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;673		let address = (when, index);674		Lookup::<T>::insert(&id, &address);675		Self::deposit_event(Event::Scheduled { when, index });676677		Ok(address)678	}679680	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {681		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {682			if let Some((when, index)) = lookup.take() {683				let i = index as usize;684				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {685					if let Some(s) = agenda.get_mut(i) {686						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {687							if matches!(688								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),689								Some(Ordering::Less) | None690							) {691								return Err(BadOrigin.into());692							}693							// release balance reserve694							// let sender = ensure_signed(695							// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(696							// 		origin.unwrap(),697							// 	)698							// 	.into(),699							// )?;700							// let _ = T::CallExecutor::cancel_reserve(id, sender);701702							s.call.ensure_unrequested::<T::PreimageProvider>();703						}704						*s = None;705					}706					Ok(())707				})?;708709				Self::deposit_event(Event::Canceled { when, index });710				Ok(())711			} else {712				Err(Error::<T>::NotFound)?713			}714		})715	}716}