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

difftreelog

source

pallets/scheduler/src/lib.rs25.9 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 license18// This file is part of Substrate.1920// Copyright (C) 2017-2021 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//! # Scheduler36//! A module for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Module`]41//!42//! ## Overview43//!44//! This module exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a61//!   specified block and with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and63//!   index.64//! * `schedule_named` - augments the `schedule` interface with an additional65//!   `Vec<u8>` parameter that can be used for identification.66//! * `cancel_named` - the named complement to the cancel function.6768// Ensure we're `no_std` when compiling for Wasm.69#![cfg_attr(not(feature = "std"), no_std)]70#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]7172mod benchmarking;73pub mod weights;7475use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};76use codec::{Encode, Decode, Codec};77use sp_runtime::{78	RuntimeDebug,79	traits::{Zero, One, BadOrigin, Saturating},80};81use frame_support::{82	decl_module, decl_storage, decl_event, decl_error,83	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},84	traits::{85		Get,86		schedule::{self, DispatchTime},87		OriginTrait, EnsureOrigin, IsType,88	},89	weights::{GetDispatchInfo, Weight},90};91use frame_system::{self as system, ensure_signed};92pub use weights::WeightInfo;93use up_sponsorship::SponsorshipHandler;94use scale_info::TypeInfo;9596/// Our pallet's configuration trait. All our types and constants go in here. If the97/// pallet is dependent on specific other pallets, then their configuration traits98/// should be added to our implied traits list.99///100/// `system::Config` should always be included in our implied traits.101/// //102pub trait Config: system::Config {103	/// The overarching event type.104	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;105106	/// The aggregated origin which the dispatch will take.107	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>108		+ From<Self::PalletsOrigin>109		+ IsType<<Self as system::Config>::Origin>;110111	/// The caller origin, overarching type of all pallets origins.112	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;113114	/// The aggregated call type.115	type Call: Parameter116		+ Dispatchable<Origin = <Self as Config>::Origin>117		+ GetDispatchInfo118		+ From<system::Call<Self>>;119120	/// The maximum weight that may be scheduled per block for any dispatchables of less priority121	/// than `schedule::HARD_DEADLINE`.122	type MaximumWeight: Get<Weight>;123124	/// Required origin to schedule or cancel calls.125	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;126127	/// The maximum number of scheduled calls in the queue for a single block.128	/// Not strictly enforced, but used for weight estimation.129	type MaxScheduledPerBlock: Get<u32>;130131	/// Sponsoring function132	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;133134	/// Weight information for extrinsics in this pallet.135	type WeightInfo: WeightInfo;136}137138// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;139140/// Just a simple index for naming period tasks.141pub type PeriodicIndex = u32;142/// The location of a scheduled task that can be used to remove it.143pub type TaskAddress<BlockNumber> = (BlockNumber, u32);144145#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]146#[derive(Clone, RuntimeDebug, Encode, Decode)]147struct ScheduledV1<Call, BlockNumber> {148	maybe_id: Option<Vec<u8>>,149	priority: schedule::Priority,150	call: Call,151	maybe_periodic: Option<schedule::Period<BlockNumber>>,152}153154/// Information regarding an item to be executed in the future.155#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]156#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]157pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {158	/// The unique identity for this task, if there is one.159	maybe_id: Option<Vec<u8>>,160	/// This task's priority.161	priority: schedule::Priority,162	/// The call to be dispatched.163	call: Call,164	/// If the call is periodic, then this points to the information concerning that.165	maybe_periodic: Option<schedule::Period<BlockNumber>>,166	/// The origin to dispatch the call.167	origin: PalletsOrigin,168	_phantom: PhantomData<AccountId>,169}170171/// The current version of Scheduled struct.172pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =173	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;174175// A value placed in storage that represents the current version of the Scheduler storage.176// This value is used by the `on_runtime_upgrade` logic to determine whether we run177// storage migration logic.178#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]179enum Releases {180	V1,181	V2,182}183184impl Default for Releases {185	fn default() -> Self {186		Releases::V1187	}188}189190#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]191pub struct CallSpec {192	module: u32,193	method: u32,194}195196decl_storage! {197	trait Store for Module<T: Config> as Scheduler {198		/// Items to be executed, indexed by the block number that they should be executed on.199		pub Agenda: map hasher(twox_64_concat) T::BlockNumber200			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;201202		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber203			=> Vec<Option<CallSpec>>;204205		/// Lookup from identity to the block number and index of the task.206		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;207208		/// Storage version of the pallet.209		///210		/// New networks start with last version.211		StorageVersion build(|_| Releases::V2): Releases;212	}213}214215decl_event!(216	pub enum Event<T> where <T as system::Config>::BlockNumber {217		/// Scheduled some task. \[when, index\]218		Scheduled(BlockNumber, u32),219		/// Canceled some task. \[when, index\]220		Canceled(BlockNumber, u32),221		/// Dispatched some task. \[task, id, result\]222		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),223	}224);225226decl_error! {227	pub enum Error for Module<T: Config> {228		/// Failed to schedule a call229		FailedToSchedule,230		/// Cannot find the scheduled call.231		NotFound,232		/// Given target block number is in the past.233		TargetBlockNumberInPast,234		/// Reschedule failed because it does not change scheduled time.235		RescheduleNoChange,236	}237}238239decl_module! {240	/// Scheduler module declaration.241	pub struct Module<T: Config> for enum Call242	where243		origin: <T as system::Config>::Origin244	{245		type Error = Error<T>;246		fn deposit_event() = default;247248249		/// Anonymously schedule a task.250		///251		/// # <weight>252		/// - S = Number of already scheduled calls253		/// - Base Weight: 22.29 + .126 * S µs254		/// - DB Weight:255		///     - Read: Agenda256		///     - Write: Agenda257		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls258		/// # </weight>259		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]260		fn schedule(origin,261			when: T::BlockNumber,262			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,263			priority: schedule::Priority,264			call: Box<<T as Config>::Call>,265		)266		{267			let origin = <T as Config>::Origin::from(origin);268			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;269		}270271		/// Cancel an anonymously scheduled task.272		///273		/// # <weight>274		/// - S = Number of already scheduled calls275		/// - Base Weight: 22.15 + 2.869 * S µs276		/// - DB Weight:277		///     - Read: Agenda278		///     - Write: Agenda, Lookup279		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls280		/// # </weight>281		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]282		fn cancel(origin, when: T::BlockNumber, index: u32) {283			T::ScheduleOrigin::ensure_origin(origin.clone())?;284			let origin = <T as Config>::Origin::from(origin);285			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;286		}287288		/// Schedule a named task.289		///290		/// # <weight>291		/// - S = Number of already scheduled calls292		/// - Base Weight: 29.6 + .159 * S µs293		/// - DB Weight:294		///     - Read: Agenda, Lookup295		///     - Write: Agenda, Lookup296		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls297		/// # </weight>298		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]299		fn schedule_named(origin,300			id: Vec<u8>,301			when: T::BlockNumber,302			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,303			priority: schedule::Priority,304			call: Box<<T as Config>::Call>,305		) {306			T::ScheduleOrigin::ensure_origin(origin.clone())?;307			let origin = <T as Config>::Origin::from(origin);308			Self::do_schedule_named(309				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call310			)?;311		}312313		/// Cancel a named scheduled task.314		///315		/// # <weight>316		/// - S = Number of already scheduled calls317		/// - Base Weight: 24.91 + 2.907 * S µs318		/// - DB Weight:319		///     - Read: Agenda, Lookup320		///     - Write: Agenda, Lookup321		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls322		/// # </weight>323		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]324		fn cancel_named(origin, id: Vec<u8>) {325			T::ScheduleOrigin::ensure_origin(origin.clone())?;326			let origin = <T as Config>::Origin::from(origin);327			Self::do_cancel_named(Some(origin.caller().clone()), id)?;328		}329330		/// Anonymously schedule a task after a delay.331		///332		/// # <weight>333		/// Same as [`schedule`].334		/// # </weight>335		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]336		fn schedule_after(origin,337			after: T::BlockNumber,338			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,339			priority: schedule::Priority,340			call: Box<<T as Config>::Call>,341		) {342			T::ScheduleOrigin::ensure_origin(origin.clone())?;343			let origin = <T as Config>::Origin::from(origin);344			Self::do_schedule(345				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call346			)?;347		}348349		/// Schedule a named task after a delay.350		///351		/// # <weight>352		/// Same as [`schedule_named`].353		/// # </weight>354		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]355		fn schedule_named_after(origin,356			id: Vec<u8>,357			after: T::BlockNumber,358			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,359			priority: schedule::Priority,360			call: Box<<T as Config>::Call>,361		) {362			T::ScheduleOrigin::ensure_origin(origin.clone())?;363			let origin = <T as Config>::Origin::from(origin);364			Self::do_schedule_named(365				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call366			)?;367		}368369		/// Execute the scheduled calls370		///371		/// # <weight>372		/// - S = Number of already scheduled calls373		/// - N = Named scheduled calls374		/// - P = Periodic Calls375		/// - Base Weight: 9.243 + 23.45 * S µs376		/// - DB Weight:377		///     - Read: Agenda + Lookup * N + Agenda(Future) * P378		///     - Write: Agenda + Lookup * N  + Agenda(future) * P379		/// # </weight>380		fn on_initialize(now: T::BlockNumber) -> Weight {381			let limit = T::MaximumWeight::get();382			let mut queued = Agenda::<T>::take(now).into_iter()383				.enumerate()384				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))385				.collect::<Vec<_>>();386			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {387				log::warn!(388					target: "runtime::scheduler",389					"Warning: This block has more items queued in Scheduler than \390					expected from the runtime configuration. An update might be needed."391				);392			}393			queued.sort_by_key(|(_, s)| s.priority);394			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)395			let mut total_weight: Weight = 0;396			queued.into_iter()397				.enumerate()398				.scan(base_weight, |cumulative_weight, (order, (index, s))| {399					*cumulative_weight = cumulative_weight400						.saturating_add(s.call.get_dispatch_info().weight);401402					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(403						s.origin.clone()404					).into();405406					if ensure_signed(origin).is_ok() {407						 // AccountData for inner call origin accountdata.408						*cumulative_weight = cumulative_weight409							.saturating_add(T::DbWeight::get().reads_writes(1, 1));410					}411412					if s.maybe_id.is_some() {413						// Remove/Modify Lookup414						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));415					}416					if s.maybe_periodic.is_some() {417						// Read/Write Agenda for future block418						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));419					}420421					Some((order, index, *cumulative_weight, s))422				})423				.filter_map(|(order, index, cumulative_weight, mut s)| {424					// We allow a scheduled call if any is true:425					// - It's priority is `HARD_DEADLINE`426					// - It does not push the weight past the limit.427					// - It is the first item in the schedule428					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {429430						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(431							s.origin.clone()432						).into();433						let sender = match ensure_signed(origin) {434							Ok(v) => v,435							// TODO: Support for unsigned extrinsics?436							Err(_) => return Some(Some(s))437						};438						let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);439						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));440						let r = s.call.clone().dispatch(sponsor.into());441						let maybe_id = s.maybe_id.clone();442						if let Some((period, count)) = s.maybe_periodic {443							if count > 1 {444								s.maybe_periodic = Some((period, count - 1));445							} else {446								s.maybe_periodic = None;447							}448							let next = now + period;449							// If scheduled is named, place it's information in `Lookup`450							if let Some(ref id) = s.maybe_id {451								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);452								Lookup::<T>::insert(id, (next, next_index as u32));453							}454							Agenda::<T>::append(next, Some(s));455						} else if let Some(ref id) = s.maybe_id {456									  Lookup::<T>::remove(id);457								  }458						Self::deposit_event(RawEvent::Dispatched(459							(now, index),460							maybe_id,461							r.map(|_| ()).map_err(|e| e.error)462						));463						total_weight = cumulative_weight;464						None465					} else {466						Some(Some(s))467					}468				})469				.for_each(|unused| {470					let next = now + One::one();471					Agenda::<T>::append(next, unused);472				});473474			total_weight475		}476	}477}478479impl<T: Config> Module<T> {480	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {481		let now = frame_system::Pallet::<T>::block_number();482483		let when = match when {484			DispatchTime::At(x) => x,485			// The current block has already completed it's scheduled tasks, so486			// Schedule the task at lest one block after this current block.487			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),488		};489490		if when <= now {491			return Err(Error::<T>::TargetBlockNumberInPast.into());492		}493494		Ok(when)495	}496497	fn do_schedule(498		when: DispatchTime<T::BlockNumber>,499		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,500		priority: schedule::Priority,501		origin: T::PalletsOrigin,502		call: <T as Config>::Call,503	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {504		let when = Self::resolve_time(when)?;505506		// sanitize maybe_periodic507		let maybe_periodic = maybe_periodic508			.filter(|p| p.1 > 1 && !p.0.is_zero())509			// Remove one from the number of repetitions since we will schedule one now.510			.map(|(p, c)| (p, c - 1));511		let s = Some(Scheduled {512			maybe_id: None,513			priority,514			call,515			maybe_periodic,516			origin,517			_phantom: PhantomData::<T::AccountId>::default(),518		});519		Agenda::<T>::append(when, s);520		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;521		if index > T::MaxScheduledPerBlock::get() {522			log::warn!(523				target: "runtime::scheduler",524				"Warning: There are more items queued in the Scheduler than \525				expected from the runtime configuration. An update might be needed.",526			);527		}528		Self::deposit_event(RawEvent::Scheduled(when, index));529530		Ok((when, index))531	}532533	fn do_cancel(534		origin: Option<T::PalletsOrigin>,535		(when, index): TaskAddress<T::BlockNumber>,536	) -> Result<(), DispatchError> {537		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {538			agenda.get_mut(index as usize).map_or(539				Ok(None),540				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {541					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {542						if *o != s.origin {543							return Err(BadOrigin.into());544						}545					};546					Ok(s.take())547				},548			)549		})?;550		if let Some(s) = scheduled {551			if let Some(id) = s.maybe_id {552				Lookup::<T>::remove(id);553			}554			Self::deposit_event(RawEvent::Canceled(when, index));555			Ok(())556		} else {557			Err(Error::<T>::NotFound.into())558		}559	}560561	fn do_reschedule(562		(when, index): TaskAddress<T::BlockNumber>,563		new_time: DispatchTime<T::BlockNumber>,564	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {565		let new_time = Self::resolve_time(new_time)?;566567		if new_time == when {568			return Err(Error::<T>::RescheduleNoChange.into());569		}570571		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {572			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;573			let task = task.take().ok_or(Error::<T>::NotFound)?;574			Agenda::<T>::append(new_time, Some(task));575			Ok(())576		})?;577578		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;579		Self::deposit_event(RawEvent::Canceled(when, index));580		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));581582		Ok((new_time, new_index))583	}584585	fn do_schedule_named(586		id: Vec<u8>,587		when: DispatchTime<T::BlockNumber>,588		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,589		priority: schedule::Priority,590		origin: T::PalletsOrigin,591		call: <T as Config>::Call,592	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {593		// ensure id it is unique594		if Lookup::<T>::contains_key(&id) {595			return Err(Error::<T>::FailedToSchedule.into());596		}597598		let when = Self::resolve_time(when)?;599600		// sanitize maybe_periodic601		let maybe_periodic = maybe_periodic602			.filter(|p| p.1 > 1 && !p.0.is_zero())603			// Remove one from the number of repetitions since we will schedule one now.604			.map(|(p, c)| (p, c - 1));605606		let s = Scheduled {607			maybe_id: Some(id.clone()),608			priority,609			call,610			maybe_periodic,611			origin,612			_phantom: Default::default(),613		};614		Agenda::<T>::append(when, Some(s));615		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;616		if index > T::MaxScheduledPerBlock::get() {617			log::warn!(618				target: "runtime::scheduler",619				"Warning: There are more items queued in the Scheduler than \620				expected from the runtime configuration. An update might be needed.",621			);622		}623		let address = (when, index);624		Lookup::<T>::insert(&id, &address);625		Self::deposit_event(RawEvent::Scheduled(when, index));626627		Ok(address)628	}629630	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {631		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {632			if let Some((when, index)) = lookup.take() {633				let i = index as usize;634				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {635					if let Some(s) = agenda.get_mut(i) {636						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {637							if *o != s.origin {638								return Err(BadOrigin.into());639							}640						}641						*s = None;642					}643					Ok(())644				})?;645				Self::deposit_event(RawEvent::Canceled(when, index));646				Ok(())647			} else {648				Err(Error::<T>::NotFound.into())649			}650		})651	}652653	fn do_reschedule_named(654		id: Vec<u8>,655		new_time: DispatchTime<T::BlockNumber>,656	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {657		let new_time = Self::resolve_time(new_time)?;658659		Lookup::<T>::try_mutate_exists(660			id,661			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;663664				if new_time == when {665					return Err(Error::<T>::RescheduleNoChange.into());666				}667668				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {669					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;670					let task = task.take().ok_or(Error::<T>::NotFound)?;671					Agenda::<T>::append(new_time, Some(task));672673					Ok(())674				})?;675676				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;677				Self::deposit_event(RawEvent::Canceled(when, index));678				Self::deposit_event(RawEvent::Scheduled(new_time, new_index));679680				*lookup = Some((new_time, new_index));681682				Ok((new_time, new_index))683			},684		)685	}686}687688#[cfg(test)]689#[allow(clippy::from_over_into)]690mod tests {691	use super::*;692693	use frame_support::{694		ord_parameter_types, parameter_types,695		traits::{Contains, ConstU32, EnsureOneOf},696		weights::constants::RocksDbWeight,697	};698	use sp_core::H256;699	use sp_runtime::{700		Perbill,701		testing::Header,702		traits::{BlakeTwo256, IdentityLookup},703	};704	use frame_system::{EnsureRoot, EnsureSignedBy};705	use crate as scheduler;706707	mod logger {708		use super::*;709		use std::cell::RefCell;710711		thread_local! {712			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());713		}714		pub trait Config: system::Config {715			type Event: From<Event> + Into<<Self as system::Config>::Event>;716		}717		decl_event! {718			pub enum Event {719				Logged(u32, Weight),720			}721		}722		decl_module! {723			pub struct Module<T: Config> for enum Call724			where725				origin: <T as system::Config>::Origin,726				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>727			{728				fn deposit_event() = default;729730				#[weight = *weight]731				fn log(origin, i: u32, weight: Weight) {732					Self::deposit_event(Event::Logged(i, weight));733					LOG.with(|log| {734						log.borrow_mut().push((origin.caller().clone(), i));735					})736				}737738				#[weight = *weight]739				fn log_without_filter(origin, i: u32, weight: Weight) {740					Self::deposit_event(Event::Logged(i, weight));741					LOG.with(|log| {742						log.borrow_mut().push((origin.caller().clone(), i));743					})744				}745			}746		}747	}748749	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;750	type Block = frame_system::mocking::MockBlock<Test>;751752	frame_support::construct_runtime!(753		pub enum Test where754			Block = Block,755			NodeBlock = Block,756			UncheckedExtrinsic = UncheckedExtrinsic,757		{758			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},759			Logger: logger::{Pallet, Call, Event},760			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},761		}762	);763764	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.765	pub struct BaseFilter;766	impl Contains<Call> for BaseFilter {767		fn contains(call: &Call) -> bool {768			!matches!(call, Call::Logger(logger::Call::log { .. }))769		}770	}771772	parameter_types! {773		pub const BlockHashCount: u64 = 250;774		pub BlockWeights: frame_system::limits::BlockWeights =775			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);776	}777	impl system::Config for Test {778		type BaseCallFilter = BaseFilter;779		type BlockWeights = ();780		type BlockLength = ();781		type DbWeight = RocksDbWeight;782		type Origin = Origin;783		type Call = Call;784		type Index = u64;785		type BlockNumber = u64;786		type Hash = H256;787		type Hashing = BlakeTwo256;788		type AccountId = u64;789		type Lookup = IdentityLookup<Self::AccountId>;790		type Header = Header;791		type Event = Event;792		type BlockHashCount = BlockHashCount;793		type Version = ();794		type PalletInfo = PalletInfo;795		type AccountData = ();796		type OnNewAccount = ();797		type OnKilledAccount = ();798		type SystemWeightInfo = ();799		type SS58Prefix = ();800		type OnSetCode = ();801		type MaxConsumers = ConstU32<16>;802	}803	impl logger::Config for Test {804		type Event = Event;805	}806	parameter_types! {807		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;808		pub const MaxScheduledPerBlock: u32 = 10;809	}810	ord_parameter_types! {811		pub const One: u64 = 1;812	}813814	impl Config for Test {815		type Event = Event;816		type Origin = Origin;817		type PalletsOrigin = OriginCaller;818		type Call = Call;819		type MaximumWeight = MaximumSchedulerWeight;820		type ScheduleOrigin = EnsureOneOf<EnsureRoot<u64>, EnsureSignedBy<One, u64>>;821		type MaxScheduledPerBlock = MaxScheduledPerBlock;822		type WeightInfo = ();823		type SponsorshipHandler = ();824	}825}