git.delta.rocks / unique-network / refs/commits / 58ec388f36ff

difftreelog

Scheduler uses default runtime logic when applying call instead dispatch method

str-mv2022-02-10parent: #a807587.patch.diff
in: master

2 files changed

modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//!   specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//!   index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//!   `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61	RuntimeDebug,62	traits::{One, BadOrigin, Saturating},63};64use frame_support::{65	decl_module, decl_storage, decl_event, decl_error,66	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67	traits::{68		Get,69		schedule::{self, DispatchTime},70		OriginTrait, EnsureOrigin, IsType,71	},72	weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use scale_info::TypeInfo;77use sp_runtime::ApplyExtrinsicResult;78use sp_runtime::traits::{IdentifyAccount, Verify};79use sp_runtime::{MultiSignature};80use sp_core::{H160};8182pub trait ApplyCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {83	fn apply_call(signer: T::AccountId, function: <T as Config>::Call); //<T as system::Config>84}8586/// The address format for describing accounts.87//pub type Signature = MultiSignature;88// pub type Address = sp_runtime::MultiAddress<AccountId, ()>;89//pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;9091/// Our pallet's configuration trait. All our types and constants go in here. If the92/// pallet is dependent on specific other pallets, then their configuration traits93/// should be added to our implied traits list.94///95/// `system::Config` should always be included in our implied traits.96/// //97pub trait Config: system::Config {98	/// The overarching event type.99	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;100101	/// The aggregated origin which the dispatch will take.102	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>103		+ From<Self::PalletsOrigin>104		+ IsType<<Self as system::Config>::Origin>;105106	/// The caller origin, overarching type of all pallets origins.107	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;108109	/// The aggregated call type.110	type Call: Parameter111		+ Dispatchable<Origin = <Self as Config>::Origin>112		+ GetDispatchInfo113		+ From<system::Call<Self>>;114115	/// The maximum weight that may be scheduled per block for any dispatchables of less priority116	/// than `schedule::HARD_DEADLINE`.117	type MaximumWeight: Get<Weight>;118119	/// Required origin to schedule or cancel calls.120	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;121122	/// The maximum number of scheduled calls in the queue for a single block.123	/// Not strictly enforced, but used for weight estimation.124	type MaxScheduledPerBlock: Get<u32>;125126	/// Weight information for extrinsics in this pallet.127	type WeightInfo: WeightInfo;128129	/// A type that allows you to use SignedExtra additional logic when dispatching call130	type Executor: ApplyCall<Self, H160>;131}132133pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;134135pub const PERIODIC_CALLS_LIMIT: u32 = 100;136137// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;138139/// Just a simple index for naming period tasks.140pub type PeriodicIndex = u32;141/// The location of a scheduled task that can be used to remove it.142pub type TaskAddress<BlockNumber> = (BlockNumber, u32);143144#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]145#[derive(Clone, RuntimeDebug, Encode, Decode)]146struct ScheduledV1<Call, BlockNumber> {147	maybe_id: Option<Vec<u8>>,148	priority: schedule::Priority,149	call: Call,150	maybe_periodic: Option<schedule::Period<BlockNumber>>,151}152153/// Information regarding an item to be executed in the future.154#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]155#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]156pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {157	/// The unique identity for this task, if there is one.158	maybe_id: Option<Vec<u8>>,159	/// This task's priority.160	priority: schedule::Priority,161	/// The call to be dispatched.162	call: Call,163	/// If the call is periodic, then this points to the information concerning that.164	maybe_periodic: Option<schedule::Period<BlockNumber>>,165	/// The origin to dispatch the call.166	origin: PalletsOrigin,167	_phantom: PhantomData<AccountId>,168}169170/// The current version of Scheduled struct.171pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =172	ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;173174// A value placed in storage that represents the current version of the Scheduler storage.175// This value is used by the `on_runtime_upgrade` logic to determine whether we run176// storage migration logic.177#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]178enum Releases {179	V1,180	V2,181}182183impl Default for Releases {184	fn default() -> Self {185		Releases::V1186	}187}188189#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]190pub struct CallSpec {191	module: u32,192	method: u32,193}194195decl_storage! {196	trait Store for Module<T: Config> as Scheduler {197		/// Items to be executed, indexed by the block number that they should be executed on.198		pub Agenda: map hasher(twox_64_concat) T::BlockNumber199			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;200201		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber202			=> Vec<Option<CallSpec>>;203204		/// Lookup from identity to the block number and index of the task.205		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;206207		/// Storage version of the pallet.208		///209		/// New networks start with last version.210		StorageVersion build(|_| Releases::V2): Releases;211	}212}213214decl_event!(215	pub enum Event<T> where <T as system::Config>::BlockNumber {216		/// Scheduled some task. \[when, index\]217		Scheduled(BlockNumber, u32),218		/// Canceled some task. \[when, index\]219		Canceled(BlockNumber, u32),220		/// Dispatched some task. \[task, id, result\]221		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),222	}223);224225decl_error! {226	pub enum Error for Module<T: Config> {227		/// Failed to schedule a call228		FailedToSchedule,229		/// Cannot find the scheduled call.230		NotFound,231		/// Given target block number is in the past.232		TargetBlockNumberInPast,233		/// Reschedule failed because it does not change scheduled time.234		RescheduleNoChange,235	}236}237238decl_module! {239	/// Scheduler module declaration.240	pub struct Module<T: Config> for enum Call241	where242		origin: <T as system::Config>::Origin243	{244		type Error = Error<T>;245		fn deposit_event() = default;246247248		/// Anonymously schedule a task.249		///250		/// # <weight>251		/// - S = Number of already scheduled calls252		/// - Base Weight: 22.29 + .126 * S µs253		/// - DB Weight:254		///     - Read: Agenda255		///     - Write: Agenda256		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls257		/// # </weight>258		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]259		fn schedule(origin,260			when: T::BlockNumber,261			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,262			priority: schedule::Priority,263			call: Box<<T as Config>::Call>,264		)265		{266			let origin = <T as Config>::Origin::from(origin);267			Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;268		}269270		/// Cancel an anonymously scheduled task.271		///272		/// # <weight>273		/// - S = Number of already scheduled calls274		/// - Base Weight: 22.15 + 2.869 * S µs275		/// - DB Weight:276		///     - Read: Agenda277		///     - Write: Agenda, Lookup278		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls279		/// # </weight>280		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]281		fn cancel(origin, when: T::BlockNumber, index: u32) {282			T::ScheduleOrigin::ensure_origin(origin.clone())?;283			let origin = <T as Config>::Origin::from(origin);284			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;285		}286287		/// Schedule a named task.288		///289		/// # <weight>290		/// - S = Number of already scheduled calls291		/// - Base Weight: 29.6 + .159 * S µs292		/// - DB Weight:293		///     - Read: Agenda, Lookup294		///     - Write: Agenda, Lookup295		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls296		/// # </weight>297		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]298		fn schedule_named(origin,299			id: Vec<u8>,300			when: T::BlockNumber,301			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,302			priority: schedule::Priority,303			call: Box<<T as Config>::Call>,304		) {305			T::ScheduleOrigin::ensure_origin(origin.clone())?;306			let origin = <T as Config>::Origin::from(origin);307			Self::do_schedule_named(308				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call309			)?;310		}311312		/// Cancel a named scheduled task.313		///314		/// # <weight>315		/// - S = Number of already scheduled calls316		/// - Base Weight: 24.91 + 2.907 * S µs317		/// - DB Weight:318		///     - Read: Agenda, Lookup319		///     - Write: Agenda, Lookup320		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls321		/// # </weight>322		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]323		fn cancel_named(origin, id: Vec<u8>) {324			T::ScheduleOrigin::ensure_origin(origin.clone())?;325			let origin = <T as Config>::Origin::from(origin);326			Self::do_cancel_named(Some(origin.caller().clone()), id)?;327		}328329		/// Anonymously schedule a task after a delay.330		///331		/// # <weight>332		/// Same as [`schedule`].333		/// # </weight>334		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]335		fn schedule_after(origin,336			after: T::BlockNumber,337			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,338			priority: schedule::Priority,339			call: Box<<T as Config>::Call>,340		) {341			T::ScheduleOrigin::ensure_origin(origin.clone())?;342			let origin = <T as Config>::Origin::from(origin);343			Self::do_schedule_nameless(344				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call345			)?;346		}347348		/// Schedule a named task after a delay.349		///350		/// # <weight>351		/// Same as [`schedule_named`].352		/// # </weight>353		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]354		fn schedule_named_after(origin,355			id: Vec<u8>,356			after: T::BlockNumber,357			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,358			priority: schedule::Priority,359			call: Box<<T as Config>::Call>,360		) {361			T::ScheduleOrigin::ensure_origin(origin.clone())?;362			let origin = <T as Config>::Origin::from(origin);363			Self::do_schedule_named(364				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call365			)?;366		}367368		/// Execute the scheduled calls369		///370		/// # <weight>371		/// - S = Number of already scheduled calls372		/// - N = Named scheduled calls373		/// - P = Periodic Calls374		/// - Base Weight: 9.243 + 23.45 * S µs375		/// - DB Weight:376		///     - Read: Agenda + Lookup * N + Agenda(Future) * P377		///     - Write: Agenda + Lookup * N  + Agenda(future) * P378		/// # </weight>379		fn on_initialize(now: T::BlockNumber) -> Weight {380			let limit = T::MaximumWeight::get();381			let mut queued = Agenda::<T>::take(now)382				.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; // T::WeightInfo::on_initialize(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 = ensure_signed(origin).unwrap_or_default();434						// let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);435						// let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));436						// let r = s.call.clone().dispatch(sponsor.into());437438439						let sender = ensure_signed(origin).unwrap_or_default();440						T::Executor::apply_call(sender.clone(), s.call.clone());441442						let maybe_id = s.maybe_id.clone();443						if let Some((period, count)) = s.maybe_periodic {444							if count > 1 {445								s.maybe_periodic = Some((period, count - 1));446							} else {447								s.maybe_periodic = None;448							}449							let next = now + period;450							// If scheduled is named, place it's information in `Lookup`451							if let Some(ref id) = s.maybe_id {452								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);453								Lookup::<T>::insert(id, (next, next_index as u32));454							}455							Agenda::<T>::append(next, Some(s));456						} else if let Some(ref id) = s.maybe_id {457									  Lookup::<T>::remove(id);458								  }459						Self::deposit_event(RawEvent::Dispatched(460							(now, index),461							maybe_id,462							Ok(())// r.map(|_| ()).map_err(|e| e.error)463						));464						total_weight = cumulative_weight;465						None466					} else {467						Some(Some(s))468					}469				})470				.for_each(|unused| {471					let next = now + One::one();472					Agenda::<T>::append(next, unused);473				});474475			total_weight476		}477	}478}479480impl<T: Config> Module<T> {481	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {482		let now = frame_system::Pallet::<T>::block_number();483484		let when = match when {485			DispatchTime::At(x) => x,486			// The current block has already completed it's scheduled tasks, so487			// Schedule the task at lest one block after this current block.488			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),489		};490491		if when <= now {492			return Err(Error::<T>::TargetBlockNumberInPast.into());493		}494495		Ok(when)496	}497498	fn do_schedule(499		maybe_id: Option<Vec<u8>>,500		when: DispatchTime<T::BlockNumber>,501		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,502		priority: schedule::Priority,503		origin: T::PalletsOrigin,504		call: <T as Config>::Call,505	) -> Result<(T::BlockNumber, u32), DispatchError> {506		let when = Self::resolve_time(when)?;507508		let sender = ensure_signed(509			<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),510		)511		.unwrap_or_default();512		let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);513		let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));514		let r = call.clone().dispatch(sponsor.into());515516		//T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch call517518		// sanitize maybe_periodic519		let maybe_periodic = None;520		// let maybe_periodic = maybe_periodic521		// 	.filter(|p| p.1 > 1 && !p.0.is_zero())522		// 	// Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.523		// 	.map(|(p, c)| (p, std::cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));524525		let s = Some(Scheduled {526			maybe_id,527			priority,528			call,529			maybe_periodic,530			origin,531			_phantom: PhantomData::<T::AccountId>::default(),532		});533		Agenda::<T>::append(when, s);534		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;535		if index > T::MaxScheduledPerBlock::get() {536			log::warn!(537				target: "runtime::scheduler",538				"Warning: There are more items queued in the Scheduler than \539				expected from the runtime configuration. An update might be needed.",540			);541		}542543		Ok((when, index))544	}545546	fn do_schedule_nameless(547		when: DispatchTime<T::BlockNumber>,548		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,549		priority: schedule::Priority,550		origin: T::PalletsOrigin,551		call: <T as Config>::Call,552	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {553		let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;554		let (when, index) = address;555556		Self::deposit_event(RawEvent::Scheduled(when, index));557558		Ok(address)559	}560561	fn do_cancel(562		origin: Option<T::PalletsOrigin>,563		(when, index): TaskAddress<T::BlockNumber>,564	) -> Result<(), DispatchError> {565		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {566			agenda.get_mut(index as usize).map_or(567				Ok(None),568				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {569					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {570						if *o != s.origin {571							return Err(BadOrigin.into());572						}573					};574					Ok(s.take())575				},576			)577		})?;578		if let Some(s) = scheduled {579			if let Some(id) = s.maybe_id {580				Lookup::<T>::remove(id);581			}582			Self::deposit_event(RawEvent::Canceled(when, index));583			Ok(())584		} else {585			Err(Error::<T>::NotFound.into())586		}587	}588589	fn do_reschedule(590		(when, index): TaskAddress<T::BlockNumber>,591		new_time: DispatchTime<T::BlockNumber>,592	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {593		let new_time = Self::resolve_time(new_time)?;594595		if new_time == when {596			return Err(Error::<T>::RescheduleNoChange.into());597		}598599		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {600			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;601			let task = task.take().ok_or(Error::<T>::NotFound)?;602			Agenda::<T>::append(new_time, Some(task));603			Ok(())604		})?;605606		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;607		Self::deposit_event(RawEvent::Canceled(when, index));608		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));609610		Ok((new_time, new_index))611	}612613	fn do_schedule_named(614		id: Vec<u8>,615		when: DispatchTime<T::BlockNumber>,616		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,617		priority: schedule::Priority,618		origin: T::PalletsOrigin,619		call: <T as Config>::Call,620	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {621		// ensure id length does not exceed expectations & is unique622		if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()623			|| Lookup::<T>::contains_key(&id)624		{625			return Err(Error::<T>::FailedToSchedule.into());626		}627628		let address = Self::do_schedule(629			Some(id.clone()),630			when,631			maybe_periodic,632			priority,633			origin,634			call,635		)?;636		let (when, index) = address;637638		Lookup::<T>::insert(&id, &address);639		Self::deposit_event(RawEvent::Scheduled(when, index));640		Ok(address)641	}642643	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {644		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {645			if let Some((when, index)) = lookup.take() {646				let i = index as usize;647				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {648					if let Some(s) = agenda.get_mut(i) {649						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {650							if *o != s.origin {651								return Err(BadOrigin.into());652							}653						}654						*s = None;655					}656					Ok(())657				})?;658				Self::deposit_event(RawEvent::Canceled(when, index));659				Ok(())660			} else {661				Err(Error::<T>::NotFound.into())662			}663		})664	}665666	fn do_reschedule_named(667		id: Vec<u8>,668		new_time: DispatchTime<T::BlockNumber>,669	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {670		let new_time = Self::resolve_time(new_time)?;671672		Lookup::<T>::try_mutate_exists(673			id,674			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {675				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;676677				if new_time == when {678					return Err(Error::<T>::RescheduleNoChange.into());679				}680681				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {682					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;683					let task = task.take().ok_or(Error::<T>::NotFound)?;684					Agenda::<T>::append(new_time, Some(task));685686					Ok(())687				})?;688689				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;690				Self::deposit_event(RawEvent::Canceled(when, index));691				Self::deposit_event(RawEvent::Scheduled(new_time, new_index));692693				*lookup = Some((new_time, new_index));694695				Ok((new_time, new_index))696			},697		)698	}699}700701impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>702	for Module<T>703{704	type Address = TaskAddress<T::BlockNumber>;705706	fn schedule(707		when: DispatchTime<T::BlockNumber>,708		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,709		priority: schedule::Priority,710		origin: T::PalletsOrigin,711		call: <T as Config>::Call,712	) -> Result<Self::Address, DispatchError> {713		Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)714	}715716	fn cancel((when, index): Self::Address) -> Result<(), ()> {717		Self::do_cancel(None, (when, index)).map_err(|_| ())718	}719720	fn reschedule(721		address: Self::Address,722		when: DispatchTime<T::BlockNumber>,723	) -> Result<Self::Address, DispatchError> {724		Self::do_reschedule(address, when)725	}726727	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {728		Agenda::<T>::get(when)729			.get(index as usize)730			.ok_or(())731			.map(|_| when)732	}733}734735impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>736	for Module<T>737{738	type Address = TaskAddress<T::BlockNumber>;739740	fn schedule_named(741		id: Vec<u8>,742		when: DispatchTime<T::BlockNumber>,743		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,744		priority: schedule::Priority,745		origin: T::PalletsOrigin,746		call: <T as Config>::Call,747	) -> Result<Self::Address, ()> {748		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())749	}750751	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {752		Self::do_cancel_named(None, id).map_err(|_| ())753	}754755	fn reschedule_named(756		id: Vec<u8>,757		when: DispatchTime<T::BlockNumber>,758	) -> Result<Self::Address, DispatchError> {759		Self::do_reschedule_named(id, when)760	}761762	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {763		Lookup::<T>::get(id)764			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))765			.ok_or(())766	}767}768769#[cfg(test)]770#[allow(clippy::from_over_into)]771mod tests {772	use super::*;773774	use frame_support::{775		ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,776	};777	use sp_core::H256;778	use sp_runtime::{779		Perbill,780		testing::Header,781		traits::{BlakeTwo256, IdentityLookup},782	};783	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};784	use crate as scheduler;785786	mod logger {787		use super::*;788		use std::cell::RefCell;789790		thread_local! {791			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());792		}793		pub trait Config: system::Config {794			type Event: From<Event> + Into<<Self as system::Config>::Event>;795		}796		decl_event! {797			pub enum Event {798				Logged(u32, Weight),799			}800		}801		decl_module! {802			pub struct Module<T: Config> for enum Call803			where804				origin: <T as system::Config>::Origin,805				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>806			{807				fn deposit_event() = default;808809				#[weight = *weight]810				fn log(origin, i: u32, weight: Weight) {811					Self::deposit_event(Event::Logged(i, weight));812					LOG.with(|log| {813						log.borrow_mut().push((origin.caller().clone(), i));814					})815				}816817				#[weight = *weight]818				fn log_without_filter(origin, i: u32, weight: Weight) {819					Self::deposit_event(Event::Logged(i, weight));820					LOG.with(|log| {821						log.borrow_mut().push((origin.caller().clone(), i));822					})823				}824			}825		}826	}827828	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;829	type Block = frame_system::mocking::MockBlock<Test>;830831	frame_support::construct_runtime!(832		pub enum Test where833			Block = Block,834			NodeBlock = Block,835			UncheckedExtrinsic = UncheckedExtrinsic,836		{837			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},838			Logger: logger::{Pallet, Call, Event},839			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},840		}841	);842843	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.844	pub struct BaseFilter;845	impl Contains<Call> for BaseFilter {846		fn contains(call: &Call) -> bool {847			!matches!(call, Call::Logger(logger::Call::log { .. }))848		}849	}850851	parameter_types! {852		pub const BlockHashCount: u64 = 250;853		pub BlockWeights: frame_system::limits::BlockWeights =854			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);855	}856	impl system::Config for Test {857		type BaseCallFilter = BaseFilter;858		type BlockWeights = ();859		type BlockLength = ();860		type DbWeight = RocksDbWeight;861		type Origin = Origin;862		type Call = Call;863		type Index = u64;864		type BlockNumber = u64;865		type Hash = H256;866		type Hashing = BlakeTwo256;867		type AccountId = u64;868		type Lookup = IdentityLookup<Self::AccountId>;869		type Header = Header;870		type Event = Event;871		type BlockHashCount = BlockHashCount;872		type Version = ();873		type PalletInfo = PalletInfo;874		type AccountData = ();875		type OnNewAccount = ();876		type OnKilledAccount = ();877		type SystemWeightInfo = ();878		type SS58Prefix = ();879		type OnSetCode = ();880	}881	impl logger::Config for Test {882		type Event = Event;883	}884	parameter_types! {885		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;886		pub const MaxScheduledPerBlock: u32 = 10;887	}888	ord_parameter_types! {889		pub const One: u64 = 1;890	}891892	impl Config for Test {893		type Event = Event;894		type Origin = Origin;895		type PalletsOrigin = OriginCaller;896		type Call = Call;897		type MaximumWeight = MaximumSchedulerWeight;898		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;899		type MaxScheduledPerBlock = MaxScheduledPerBlock;900		type WeightInfo = ();901		type SponsorshipHandler = ();902		type PaymentHandler = ();903	}904}
after · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// 	http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//!   specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//!   index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//!   `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow, cmp};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61	RuntimeDebug,62	traits::{Zero, One, BadOrigin, Saturating},63};64use frame_support::{65	decl_module, decl_storage, decl_event, decl_error,66	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67	traits::{68		Get,69		schedule::{self, DispatchTime},70		OriginTrait, EnsureOrigin, IsType,71	},72	weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use scale_info::TypeInfo;77use sp_core::{H160};78use sp_runtime::transaction_validity::TransactionValidityError;79use frame_support::weights::PostDispatchInfo;80use sp_runtime::DispatchErrorWithPostInfo;8182pub trait ApplyCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {83	fn apply_call(84		signer: T::AccountId,85		function: <T as Config>::Call,86	) -> Result<87		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,88		TransactionValidityError,89	>;90}9192/// Our pallet's configuration trait. All our types and constants go in here. If the93/// pallet is dependent on specific other pallets, then their configuration traits94/// should be added to our implied traits list.95///96/// `system::Config` should always be included in our implied traits.97/// //98pub trait Config: system::Config {99	/// The overarching event type.100	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;101102	/// The aggregated origin which the dispatch will take.103	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>104		+ From<Self::PalletsOrigin>105		+ IsType<<Self as system::Config>::Origin>;106107	/// The caller origin, overarching type of all pallets origins.108	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;109110	/// The aggregated call type.111	type Call: Parameter112		+ Dispatchable<Origin = <Self as Config>::Origin>113		+ GetDispatchInfo114		+ From<system::Call<Self>>;115116	/// The maximum weight that may be scheduled per block for any dispatchables of less priority117	/// than `schedule::HARD_DEADLINE`.118	type MaximumWeight: Get<Weight>;119120	/// Required origin to schedule or cancel calls.121	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;122123	/// The maximum number of scheduled calls in the queue for a single block.124	/// Not strictly enforced, but used for weight estimation.125	type MaxScheduledPerBlock: Get<u32>;126127	/// Weight information for extrinsics in this pallet.128	type WeightInfo: WeightInfo;129130	/// A type that allows you to use SignedExtra additional logic when dispatching call131	type Executor: ApplyCall<Self, H160>;132}133134pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;135136pub const PERIODIC_CALLS_LIMIT: u32 = 100;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_nameless(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_nameless(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)383				.into_iter()384				.enumerate()385				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))386				.collect::<Vec<_>>();387			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {388				log::warn!(389					target: "runtime::scheduler",390					"Warning: This block has more items queued in Scheduler than \391					expected from the runtime configuration. An update might be needed."392				);393			}394			queued.sort_by_key(|(_, s)| s.priority);395			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)396			let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)397			queued.into_iter()398				.enumerate()399				.scan(base_weight, |cumulative_weight, (order, (index, s))| {400					*cumulative_weight = cumulative_weight401						.saturating_add(s.call.get_dispatch_info().weight);402403					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(404						s.origin.clone()405					).into();406407					if ensure_signed(origin).is_ok() {408						 // AccountData for inner call origin accountdata.409						*cumulative_weight = cumulative_weight410							.saturating_add(T::DbWeight::get().reads_writes(1, 1));411					}412413					if s.maybe_id.is_some() {414						// Remove/Modify Lookup415						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));416					}417					if s.maybe_periodic.is_some() {418						// Read/Write Agenda for future block419						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));420					}421422					Some((order, index, *cumulative_weight, s))423				})424				.filter_map(|(order, index, cumulative_weight, mut s)| {425					// We allow a scheduled call if any is true:426					// - It's priority is `HARD_DEADLINE`427					// - It does not push the weight past the limit.428					// - It is the first item in the schedule429					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {430431						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(432							 s.origin.clone()433						).into();434						// let sender = ensure_signed(origin).unwrap_or_default();435						// let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);436						// let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));437						// let r = s.call.clone().dispatch(sponsor.into());438439440						let sender = ensure_signed(origin).unwrap_or_default();441						let apply_result = T::Executor::apply_call(sender.clone(), s.call.clone());442443						let maybe_id = s.maybe_id.clone();444						if let Some((period, count)) = s.maybe_periodic {445							if count > 1 {446								s.maybe_periodic = Some((period, count - 1));447							} else {448								s.maybe_periodic = None;449							}450							let next = now + period;451							// If scheduled is named, place it's information in `Lookup`452							if let Some(ref id) = s.maybe_id {453								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);454								Lookup::<T>::insert(id, (next, next_index as u32));455							}456							Agenda::<T>::append(next, Some(s));457						} else if let Some(ref id) = s.maybe_id {458									  Lookup::<T>::remove(id);459								  }460						Self::deposit_event(RawEvent::Dispatched(461							(now, index),462							maybe_id,463							Ok(())// r.map(|_| ()).map_err(|e| e.error)464						));465						total_weight = cumulative_weight;466						None467					} else {468						Some(Some(s))469					}470				})471				.for_each(|unused| {472					let next = now + One::one();473					Agenda::<T>::append(next, unused);474				});475476			total_weight477		}478	}479}480481impl<T: Config> Module<T> {482	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {483		let now = frame_system::Pallet::<T>::block_number();484485		let when = match when {486			DispatchTime::At(x) => x,487			// The current block has already completed it's scheduled tasks, so488			// Schedule the task at lest one block after this current block.489			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),490		};491492		if when <= now {493			return Err(Error::<T>::TargetBlockNumberInPast.into());494		}495496		Ok(when)497	}498499	fn do_schedule(500		maybe_id: Option<Vec<u8>>,501		when: DispatchTime<T::BlockNumber>,502		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,503		priority: schedule::Priority,504		origin: T::PalletsOrigin,505		call: <T as Config>::Call,506	) -> Result<(T::BlockNumber, u32), DispatchError> {507		let when = Self::resolve_time(when)?;508509		let sender = ensure_signed(510			<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),511		)512		.unwrap_or_default();513		//let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);514		//let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));515		//let r = call.clone().dispatch(sponsor.into());516517		//let sender = ensure_signed(origin).unwrap_or_default();518		let apply_result = T::Executor::apply_call(sender.clone(), call.clone());519520		//T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch call521522		// sanitize maybe_periodic523		let maybe_periodic = maybe_periodic524			.filter(|p| p.1 > 1 && !p.0.is_zero())525			// Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.526			.map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));527528		let s = Some(Scheduled {529			maybe_id,530			priority,531			call,532			maybe_periodic,533			origin,534			_phantom: PhantomData::<T::AccountId>::default(),535		});536		Agenda::<T>::append(when, s);537		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;538		if index > T::MaxScheduledPerBlock::get() {539			log::warn!(540				target: "runtime::scheduler",541				"Warning: There are more items queued in the Scheduler than \542				expected from the runtime configuration. An update might be needed.",543			);544		}545546		Ok((when, index))547	}548549	fn do_schedule_nameless(550		when: DispatchTime<T::BlockNumber>,551		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,552		priority: schedule::Priority,553		origin: T::PalletsOrigin,554		call: <T as Config>::Call,555	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {556		let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;557		let (when, index) = address;558559		Self::deposit_event(RawEvent::Scheduled(when, index));560561		Ok(address)562	}563564	fn do_cancel(565		origin: Option<T::PalletsOrigin>,566		(when, index): TaskAddress<T::BlockNumber>,567	) -> Result<(), DispatchError> {568		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {569			agenda.get_mut(index as usize).map_or(570				Ok(None),571				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {572					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {573						if *o != s.origin {574							return Err(BadOrigin.into());575						}576					};577					Ok(s.take())578				},579			)580		})?;581		if let Some(s) = scheduled {582			if let Some(id) = s.maybe_id {583				Lookup::<T>::remove(id);584				// todo add back money / displace to another function for consistency585			}586			Self::deposit_event(RawEvent::Canceled(when, index));587			Ok(())588		} else {589			Err(Error::<T>::NotFound.into())590		}591	}592593	fn do_reschedule(594		(when, index): TaskAddress<T::BlockNumber>,595		new_time: DispatchTime<T::BlockNumber>,596	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {597		let new_time = Self::resolve_time(new_time)?;598599		if new_time == when {600			return Err(Error::<T>::RescheduleNoChange.into());601		}602603		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {604			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;605			let task = task.take().ok_or(Error::<T>::NotFound)?;606			Agenda::<T>::append(new_time, Some(task));607			Ok(())608		})?;609610		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;611		Self::deposit_event(RawEvent::Canceled(when, index));612		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));613614		Ok((new_time, new_index))615	}616617	fn do_schedule_named(618		id: Vec<u8>,619		when: DispatchTime<T::BlockNumber>,620		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,621		priority: schedule::Priority,622		origin: T::PalletsOrigin,623		call: <T as Config>::Call,624	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {625		// ensure id length does not exceed expectations & is unique626		if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()627			|| Lookup::<T>::contains_key(&id)628		{629			return Err(Error::<T>::FailedToSchedule.into());630		}631632		let address = Self::do_schedule(633			Some(id.clone()),634			when,635			maybe_periodic,636			priority,637			origin,638			call,639		)?;640		let (when, index) = address;641642		Lookup::<T>::insert(&id, &address);643		Self::deposit_event(RawEvent::Scheduled(when, index));644		Ok(address)645	}646647	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {648		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {649			if let Some((when, index)) = lookup.take() {650				let i = index as usize;651				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {652					if let Some(s) = agenda.get_mut(i) {653						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {654							if *o != s.origin {655								return Err(BadOrigin.into());656							}657						}658						*s = None;659					}660					Ok(())661				})?;662				Self::deposit_event(RawEvent::Canceled(when, index));663				Ok(())664			} else {665				Err(Error::<T>::NotFound.into())666			}667		})668	}669670	fn do_reschedule_named(671		id: Vec<u8>,672		new_time: DispatchTime<T::BlockNumber>,673	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {674		let new_time = Self::resolve_time(new_time)?;675676		Lookup::<T>::try_mutate_exists(677			id,678			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {679				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;680681				if new_time == when {682					return Err(Error::<T>::RescheduleNoChange.into());683				}684685				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {686					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;687					let task = task.take().ok_or(Error::<T>::NotFound)?;688					Agenda::<T>::append(new_time, Some(task));689690					Ok(())691				})?;692693				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;694				Self::deposit_event(RawEvent::Canceled(when, index));695				Self::deposit_event(RawEvent::Scheduled(new_time, new_index));696697				*lookup = Some((new_time, new_index));698699				Ok((new_time, new_index))700			},701		)702	}703}704705impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>706	for Module<T>707{708	type Address = TaskAddress<T::BlockNumber>;709710	fn schedule(711		when: DispatchTime<T::BlockNumber>,712		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,713		priority: schedule::Priority,714		origin: T::PalletsOrigin,715		call: <T as Config>::Call,716	) -> Result<Self::Address, DispatchError> {717		Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)718	}719720	fn cancel((when, index): Self::Address) -> Result<(), ()> {721		Self::do_cancel(None, (when, index)).map_err(|_| ())722	}723724	fn reschedule(725		address: Self::Address,726		when: DispatchTime<T::BlockNumber>,727	) -> Result<Self::Address, DispatchError> {728		Self::do_reschedule(address, when)729	}730731	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {732		Agenda::<T>::get(when)733			.get(index as usize)734			.ok_or(())735			.map(|_| when)736	}737}738739impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>740	for Module<T>741{742	type Address = TaskAddress<T::BlockNumber>;743744	fn schedule_named(745		id: Vec<u8>,746		when: DispatchTime<T::BlockNumber>,747		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,748		priority: schedule::Priority,749		origin: T::PalletsOrigin,750		call: <T as Config>::Call,751	) -> Result<Self::Address, ()> {752		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())753	}754755	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {756		Self::do_cancel_named(None, id).map_err(|_| ())757	}758759	fn reschedule_named(760		id: Vec<u8>,761		when: DispatchTime<T::BlockNumber>,762	) -> Result<Self::Address, DispatchError> {763		Self::do_reschedule_named(id, when)764	}765766	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {767		Lookup::<T>::get(id)768			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))769			.ok_or(())770	}771}772773#[cfg(test)]774#[allow(clippy::from_over_into)]775mod tests {776	use super::*;777778	use frame_support::{779		ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,780	};781	use sp_core::H256;782	use sp_runtime::{783		Perbill,784		testing::Header,785		traits::{BlakeTwo256, IdentityLookup},786	};787	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};788	use crate as scheduler;789790	mod logger {791		use super::*;792		use std::cell::RefCell;793794		thread_local! {795			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());796		}797		pub trait Config: system::Config {798			type Event: From<Event> + Into<<Self as system::Config>::Event>;799		}800		decl_event! {801			pub enum Event {802				Logged(u32, Weight),803			}804		}805		decl_module! {806			pub struct Module<T: Config> for enum Call807			where808				origin: <T as system::Config>::Origin,809				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>810			{811				fn deposit_event() = default;812813				#[weight = *weight]814				fn log(origin, i: u32, weight: Weight) {815					Self::deposit_event(Event::Logged(i, weight));816					LOG.with(|log| {817						log.borrow_mut().push((origin.caller().clone(), i));818					})819				}820821				#[weight = *weight]822				fn log_without_filter(origin, i: u32, weight: Weight) {823					Self::deposit_event(Event::Logged(i, weight));824					LOG.with(|log| {825						log.borrow_mut().push((origin.caller().clone(), i));826					})827				}828			}829		}830	}831832	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;833	type Block = frame_system::mocking::MockBlock<Test>;834835	frame_support::construct_runtime!(836		pub enum Test where837			Block = Block,838			NodeBlock = Block,839			UncheckedExtrinsic = UncheckedExtrinsic,840		{841			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},842			Logger: logger::{Pallet, Call, Event},843			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},844		}845	);846847	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.848	pub struct BaseFilter;849	impl Contains<Call> for BaseFilter {850		fn contains(call: &Call) -> bool {851			!matches!(call, Call::Logger(logger::Call::log { .. }))852		}853	}854855	parameter_types! {856		pub const BlockHashCount: u64 = 250;857		pub BlockWeights: frame_system::limits::BlockWeights =858			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);859	}860	impl system::Config for Test {861		type BaseCallFilter = BaseFilter;862		type BlockWeights = ();863		type BlockLength = ();864		type DbWeight = RocksDbWeight;865		type Origin = Origin;866		type Call = Call;867		type Index = u64;868		type BlockNumber = u64;869		type Hash = H256;870		type Hashing = BlakeTwo256;871		type AccountId = u64;872		type Lookup = IdentityLookup<Self::AccountId>;873		type Header = Header;874		type Event = Event;875		type BlockHashCount = BlockHashCount;876		type Version = ();877		type PalletInfo = PalletInfo;878		type AccountData = ();879		type OnNewAccount = ();880		type OnKilledAccount = ();881		type SystemWeightInfo = ();882		type SS58Prefix = ();883		type OnSetCode = ();884	}885	impl logger::Config for Test {886		type Event = Event;887	}888	parameter_types! {889		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;890		pub const MaxScheduledPerBlock: u32 = 10;891	}892	ord_parameter_types! {893		pub const One: u64 = 1;894	}895896	impl Config for Test {897		type Event = Event;898		type Origin = Origin;899		type PalletsOrigin = OriginCaller;900		type Call = Call;901		type MaximumWeight = MaximumSchedulerWeight;902		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;903		type MaxScheduledPerBlock = MaxScheduledPerBlock;904		type WeightInfo = ();905		type SponsorshipHandler = ();906		type PaymentHandler = ();907	}908}
modifiedruntime/src/lib.rsdiffbeforeafterboth
--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -74,7 +74,9 @@
 use sp_core::crypto::Public;
 use sp_runtime::{
 	traits::{BlockNumberProvider, Dispatchable, PostDispatchInfoOf},
+	generic::Era,
 	transaction_validity::TransactionValidityError,
+	DispatchErrorWithPostInfo,
 };
 
 // pub use pallet_timestamp::Call as TimestampCall;
@@ -826,11 +828,25 @@
 	type ScheduleOrigin = EnsureSigned<AccountId>;
 	type MaxScheduledPerBlock = MaxScheduledPerBlock;
 	type WeightInfo = ();
-	type Executor = Executor;
+	type Executor = SchedulerPaymentExecutor;
 }
 
-pub struct Executor;
-impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo> ApplyCall<T, SelfContainedSignedInfo> for Executor
+fn get_signed_extras(from: <Runtime as frame_system::Config>::AccountId) -> SignedExtra {
+	(
+		frame_system::CheckSpecVersion::<Runtime>::new(),
+		frame_system::CheckGenesis::<Runtime>::new(),
+		frame_system::CheckEra::<Runtime>::from(Era::Immortal),
+		frame_system::CheckNonce::<Runtime>::from(frame_system::Pallet::<Runtime>::account_nonce(
+			from,
+		)),
+		frame_system::CheckWeight::<Runtime>::new(),
+		pallet_charge_transaction::ChargeTransactionPayment::<Runtime>::new(0),
+	)
+}
+
+pub struct SchedulerPaymentExecutor;
+impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
+	ApplyCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
 where
 	<T as frame_system::Config>::Call: Member
 		+ Dispatchable<Origin = Origin, Info = DispatchInfo>
@@ -838,9 +854,18 @@
 		+ GetDispatchInfo
 		+ From<frame_system::Call<Runtime>>,
 	SelfContainedSignedInfo: Send + Sync + 'static,
-	Call: From<<T as frame_system::Config>::Call> + From<<T as pallet_unq_scheduler::Config>::Call> + SelfContainedCall<SignedInfo = SelfContainedSignedInfo>
+	Call: From<<T as frame_system::Config>::Call>
+		+ From<<T as pallet_unq_scheduler::Config>::Call>
+		+ SelfContainedCall<SignedInfo = SelfContainedSignedInfo>,
+	sp_runtime::AccountId32: From<<T as frame_system::Config>::AccountId>,
 {
-	fn apply_call(signer: <T as frame_system::Config>::AccountId, call: <T as pallet_unq_scheduler::Config>::Call) {
+	fn apply_call(
+		signer: <T as frame_system::Config>::AccountId,
+		call: <T as pallet_unq_scheduler::Config>::Call,
+	) -> Result<
+		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+		TransactionValidityError,
+	> {
 		let dispatch_info = call.get_dispatch_info();
 		let extrinsic = fp_self_contained::CheckedExtrinsic::<
 			AccountId,
@@ -848,11 +873,14 @@
 			SignedExtra,
 			SelfContainedSignedInfo,
 		> {
-			signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Unsigned, // change to signer
+			signed: CheckedSignature::<AccountId, SignedExtra, SelfContainedSignedInfo>::Signed(
+				signer.clone().into(),
+				get_signed_extras(signer.into()),
+			),
 			function: call.into(),
 		};
 
-		extrinsic.apply::<Runtime>(&dispatch_info, 0);
+		extrinsic.apply::<Runtime>(&dispatch_info, 0)
 	}
 }