git.delta.rocks / unique-network / refs/commits / 12b8d3cee6e7

difftreelog

test(Scheduler) EVM test + amendments

Fahrrader2022-03-31parent: #c2a4d96.patch.diff
in: master

5 files changed

modifiedpallets/scheduler/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2022 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 Pallet for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! This Pallet 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 a specified block and44//!   with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.46//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter47//!   that can be used for identification.48//! * `cancel_named` - the named complement to the cancel function.4950// Ensure we're `no_std` when compiling for Wasm.51#![cfg_attr(not(feature = "std"), no_std)]5253#[cfg(feature = "runtime-benchmarks")]54mod benchmarking;5556pub mod weights;5758use codec::{Codec, Decode, Encode};59use frame_support::{60	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},61	traits::{62		schedule::{self, DispatchTime, MaybeHashed},63		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,64		StorageVersion,65	},66	weights::{GetDispatchInfo, Weight},67};68use frame_system::{self as system, ensure_signed};69pub use pallet::*;70use scale_info::TypeInfo;71use sp_runtime::{72	traits::{BadOrigin, One, Saturating, Zero},73	RuntimeDebug, DispatchErrorWithPostInfo,74};75use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};76use sp_core::H160;77pub use weights::WeightInfo;7879/// Just a simple index for naming period tasks.80pub type PeriodicIndex = u32;81/// The location of a scheduled task that can be used to remove it.82pub type TaskAddress<BlockNumber> = (BlockNumber, u32);83pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;8485type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];86pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;8788/// Information regarding an item to be executed in the future.89#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]90#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]91pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {92	/// The unique identity for this task, if there is one.93	maybe_id: Option<ScheduledId>,94	/// This task's priority.95	priority: schedule::Priority,96	/// The call to be dispatched.97	call: Call,98	/// If the call is periodic, then this points to the information concerning that.99	maybe_periodic: Option<schedule::Period<BlockNumber>>,100	/// The origin to dispatch the call.101	origin: PalletsOrigin,102	_phantom: PhantomData<AccountId>,103}104105pub type ScheduledV3Of<T> = ScheduledV3<106	CallOrHashOf<T>,107	<T as frame_system::Config>::BlockNumber,108	<T as Config>::PalletsOrigin,109	<T as frame_system::Config>::AccountId,110>;111112pub type ScheduledOf<T> = ScheduledV3Of<T>;113114/// The current version of Scheduled struct.115pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =116	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;117118#[cfg(feature = "runtime-benchmarks")]119mod preimage_provider {120	use frame_support::traits::PreimageRecipient;121	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}122	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}123}124125#[cfg(not(feature = "runtime-benchmarks"))]126mod preimage_provider {127	use frame_support::traits::PreimageProvider;128	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}129	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}130}131132pub use preimage_provider::PreimageProviderAndMaybeRecipient;133134pub(crate) trait MarginalWeightInfo: WeightInfo {135	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {136		match (periodic, named, resolved) {137			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),138			(_, true, None) => {139				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)140			}141			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),142			(false, true, Some(false)) => {143				Self::on_initialize_named(2) - Self::on_initialize_named(1)144			}145			(true, false, Some(false)) => {146				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)147			}148			(true, true, Some(false)) => {149				Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)150			}151			(false, false, Some(true)) => {152				Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)153			}154			(false, true, Some(true)) => {155				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)156			}157			(true, false, Some(true)) => {158				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)159			}160			(true, true, Some(true)) => {161				Self::on_initialize_periodic_named_resolved(2)162					- Self::on_initialize_periodic_named_resolved(1)163			}164		}165	}166}167impl<T: WeightInfo> MarginalWeightInfo for T {}168169#[frame_support::pallet]170pub mod pallet {171	use super::*;172	use frame_support::{173		dispatch::PostDispatchInfo,174		pallet_prelude::*,175		traits::{schedule::LookupError, PreimageProvider},176	};177	use frame_system::pallet_prelude::*;178179	/// The current storage version.180	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);181182	#[pallet::pallet]183	#[pallet::generate_store(pub(super) trait Store)]184	#[pallet::storage_version(STORAGE_VERSION)]185	#[pallet::without_storage_info]186	pub struct Pallet<T>(_);187188	/// `system::Config` should always be included in our implied traits.189	#[pallet::config]190	pub trait Config: frame_system::Config {191		/// The overarching event type.192		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;193194		/// The aggregated origin which the dispatch will take.195		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>196			+ From<Self::PalletsOrigin>197			+ IsType<<Self as system::Config>::Origin>;198199		/// The caller origin, overarching type of all pallets origins.200		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;201202		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;203204		/// The aggregated call type.205		type Call: Parameter206			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>207			+ GetDispatchInfo208			+ From<system::Call<Self>>;209210		/// The maximum weight that may be scheduled per block for any dispatchables of less211		/// priority than `schedule::HARD_DEADLINE`.212		#[pallet::constant]213		type MaximumWeight: Get<Weight>;214215		/// Required origin to schedule or cancel calls.216		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;217218		/// Compare the privileges of origins.219		///220		/// This will be used when canceling a task, to ensure that the origin that tries221		/// to cancel has greater or equal privileges as the origin that created the scheduled task.222		///223		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can224		/// be used. This will only check if two given origins are equal.225		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;226227		/// The maximum number of scheduled calls in the queue for a single block.228		/// Not strictly enforced, but used for weight estimation.229		#[pallet::constant]230		type MaxScheduledPerBlock: Get<u32>;231232		/// Weight information for extrinsics in this pallet.233		type WeightInfo: WeightInfo;234235		/// The preimage provider with which we look up call hashes to get the call.236		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;237238		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.239		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;240241		/// Sponsoring function.242		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;243244		/// The helper type used for custom transaction fee logic.245		type CallExecutor: DispatchCall<Self, H160>;246	}247248	/// A Scheduler-Runtime interface for finer payment handling.249	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {250		fn reserve_balance(251			id: ScheduledId,252			sponsor: <T as frame_system::Config>::AccountId,253			call: <T as Config>::Call,254			count: u32,255		) -> Result<(), DispatchError>;256257		fn pay_for_call(258			id: ScheduledId,259			sponsor: <T as frame_system::Config>::AccountId,260			call: <T as Config>::Call,261		) -> Result<u128, DispatchError>;262263		/// Resolve the call dispatch, including any post-dispatch operations.264		fn dispatch_call(265			signer: T::AccountId,266			function: <T as Config>::Call,267		) -> Result<268			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,269			TransactionValidityError,270		>;271272		fn cancel_reserve(273			id: ScheduledId,274			sponsor: <T as frame_system::Config>::AccountId,275		) -> Result<u128, DispatchError>;276	}277278	/// Items to be executed, indexed by the block number that they should be executed on.279	#[pallet::storage]280	pub type Agenda<T: Config> =281		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;282283	/// Lookup from identity to the block number and index of the task.284	#[pallet::storage]285	pub(crate) type Lookup<T: Config> =286		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;287288	/// Events type.289	#[pallet::event]290	#[pallet::generate_deposit(pub(super) fn deposit_event)]291	pub enum Event<T: Config> {292		/// Scheduled some task.293		Scheduled { when: T::BlockNumber, index: u32 },294		/// Canceled some task.295		Canceled { when: T::BlockNumber, index: u32 },296		/// Dispatched some task.297		Dispatched {298			task: TaskAddress<T::BlockNumber>,299			id: Option<ScheduledId>,300			result: DispatchResult,301		},302		/// The call for the provided hash was not found so the task has been aborted.303		CallLookupFailed {304			task: TaskAddress<T::BlockNumber>,305			id: Option<ScheduledId>,306			error: LookupError,307		},308	}309310	#[pallet::error]311	pub enum Error<T> {312		/// Failed to schedule a call313		FailedToSchedule,314		/// Cannot find the scheduled call.315		NotFound,316		/// Given target block number is in the past.317		TargetBlockNumberInPast,318		/// Reschedule failed because it does not change scheduled time.319		RescheduleNoChange,320	}321322	#[pallet::hooks]323	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {324		/// Execute the scheduled calls325		fn on_initialize(now: T::BlockNumber) -> Weight {326			let limit = T::MaximumWeight::get();327328			let mut queued = Agenda::<T>::take(now)329				.into_iter()330				.enumerate()331				.filter_map(|(index, s)| Some((index as u32, s?)))332				.collect::<Vec<_>>();333334			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {335				log::warn!(336					target: "runtime::scheduler",337					"Warning: This block has more items queued in Scheduler than \338					expected from the runtime configuration. An update might be needed."339				);340			}341342			queued.sort_by_key(|(_, s)| s.priority);343344			let next = now + One::one();345346			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);347			for (order, (index, mut s)) in queued.into_iter().enumerate() {348				let named = if let Some(ref id) = s.maybe_id {349					Lookup::<T>::remove(id);350					true351				} else {352					false353				};354355				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();356				s.call = call;357358				let resolved = if let Some(completed) = maybe_completed {359					T::PreimageProvider::unrequest_preimage(&completed);360					true361				} else {362					false363				};364365				let call = match s.call.as_value().cloned() {366					Some(c) => c,367					None => {368						// Preimage not available - postpone until some block.369						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));370						if let Some(delay) = T::NoPreimagePostponement::get() {371							let until = now.saturating_add(delay);372							if let Some(ref id) = s.maybe_id {373								let index = Agenda::<T>::decode_len(until).unwrap_or(0);374								Lookup::<T>::insert(id, (until, index as u32));375							}376							Agenda::<T>::append(until, Some(s));377						}378						continue;379					}380				};381382				let periodic = s.maybe_periodic.is_some();383				let call_weight = call.get_dispatch_info().weight;384				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));385				let origin =386					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())387						.into();388				if ensure_signed(origin).is_ok() {389					// Weights of Signed dispatches expect their signing account to be whitelisted.390					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));391				}392393				// We allow a scheduled call if any is true:394				// - It's priority is `HARD_DEADLINE`395				// - It does not push the weight past the limit.396				// - It is the first item in the schedule397				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;398				let test_weight = total_weight399					.saturating_add(call_weight)400					.saturating_add(item_weight);401				if !hard_deadline && order > 0 && test_weight > limit {402					// Cannot be scheduled this block - postpone until next.403					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));404					if let Some(ref id) = s.maybe_id {405						// NOTE: We could reasonably not do this (in which case there would be one406						// block where the named and delayed item could not be referenced by name),407						// but we will do it anyway since it should be mostly free in terms of408						// weight and it is slightly cleaner.409						let index = Agenda::<T>::decode_len(next).unwrap_or(0);410						Lookup::<T>::insert(id, (next, index as u32));411					}412					Agenda::<T>::append(next, Some(s));413					continue;414				}415416				let sender = ensure_signed(417					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())418						.into(),419				)420				.unwrap();421422				// if call have id and periodic, it was be reserved423				if s.maybe_id.is_some() && s.maybe_periodic.is_some() {424					let _ = T::CallExecutor::pay_for_call(425						s.maybe_id.unwrap(),426						sender.clone(),427						call.clone(),428					);429				}430431				let r = T::CallExecutor::dispatch_call(sender, call.clone());432433				let mut actual_call_weight: Weight = item_weight; //PostDispatchInfo;434				let result: Result<_, DispatchError> = match r {435					Ok(o) => match o {436						Ok(di) => {437							actual_call_weight = di.actual_weight.unwrap_or(item_weight);438							Ok(())439						}440						Err(err) => Err(err.error),441					},442					Err(_) => {443						log::info!(444							target: "runtime::scheduler",445							"Warning: Scheduler has failed to execute a post-dispatch transaction. \446							This block might have become invalid.");447						Err(DispatchError::CannotLookup)448					} // todo possibly force a skip/return here, do something with the error449				};450451				total_weight.saturating_accrue(item_weight);452				total_weight.saturating_accrue(actual_call_weight);453454				Self::deposit_event(Event::Dispatched {455					task: (now, index),456					id: s.maybe_id.clone(),457					result,458				});459460				if let &Some((period, count)) = &s.maybe_periodic {461					if count > 1 {462						s.maybe_periodic = Some((period, count - 1));463					} else {464						s.maybe_periodic = None;465					}466					let wake = now + period;467					// If scheduled is named, place its information in `Lookup`468					if let Some(ref id) = s.maybe_id {469						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);470						Lookup::<T>::insert(id, (wake, wake_index as u32));471					}472					Agenda::<T>::append(wake, Some(s));473				}474			}475			total_weight476		}477	}478479	#[pallet::call]480	impl<T: Config> Pallet<T> {481		/// Anonymously schedule a task.482		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]483		pub fn schedule(484			origin: OriginFor<T>,485			when: T::BlockNumber,486			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,487			priority: schedule::Priority,488			call: Box<CallOrHashOf<T>>,489		) -> DispatchResult {490			T::ScheduleOrigin::ensure_origin(origin.clone())?;491			let origin = <T as Config>::Origin::from(origin);492			Self::do_schedule(493				DispatchTime::At(when),494				maybe_periodic,495				priority,496				origin.caller().clone(),497				*call,498			)?;499			Ok(())500		}501502		/// Cancel an anonymously scheduled task.503		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]504		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {505			T::ScheduleOrigin::ensure_origin(origin.clone())?;506			let origin = <T as Config>::Origin::from(origin);507			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;508			Ok(())509		}510511		/// Schedule a named task.512		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]513		pub fn schedule_named(514			origin: OriginFor<T>,515			id: ScheduledId,516			when: T::BlockNumber,517			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,518			priority: schedule::Priority,519			call: Box<CallOrHashOf<T>>,520		) -> DispatchResult {521			T::ScheduleOrigin::ensure_origin(origin.clone())?;522			let origin = <T as Config>::Origin::from(origin);523			Self::do_schedule_named(524				id,525				DispatchTime::At(when),526				maybe_periodic,527				priority,528				origin.caller().clone(),529				*call,530			)?;531			Ok(())532		}533534		/// Cancel a named scheduled task.535		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]536		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {537			T::ScheduleOrigin::ensure_origin(origin.clone())?;538			let origin = <T as Config>::Origin::from(origin);539			Self::do_cancel_named(Some(origin.caller().clone()), id)?;540			Ok(())541		}542543		/// Anonymously schedule a task after a delay.544		///545		/// # <weight>546		/// Same as [`schedule`].547		/// # </weight>548		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]549		pub fn schedule_after(550			origin: OriginFor<T>,551			after: T::BlockNumber,552			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,553			priority: schedule::Priority,554			call: Box<CallOrHashOf<T>>,555		) -> DispatchResult {556			T::ScheduleOrigin::ensure_origin(origin.clone())?;557			let origin = <T as Config>::Origin::from(origin);558			Self::do_schedule(559				DispatchTime::After(after),560				maybe_periodic,561				priority,562				origin.caller().clone(),563				*call,564			)?;565			Ok(())566		}567568		/// Schedule a named task after a delay.569		///570		/// # <weight>571		/// Same as [`schedule_named`](Self::schedule_named).572		/// # </weight>573		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]574		pub fn schedule_named_after(575			origin: OriginFor<T>,576			id: ScheduledId,577			after: T::BlockNumber,578			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,579			priority: schedule::Priority,580			call: Box<CallOrHashOf<T>>,581		) -> DispatchResult {582			T::ScheduleOrigin::ensure_origin(origin.clone())?;583			let origin = <T as Config>::Origin::from(origin);584			Self::do_schedule_named(585				id,586				DispatchTime::After(after),587				maybe_periodic,588				priority,589				origin.caller().clone(),590				*call,591			)?;592			Ok(())593		}594	}595}596597impl<T: Config> Pallet<T> {598	#[cfg(feature = "try-runtime")]599	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {600		Ok(())601	}602603	#[cfg(feature = "try-runtime")]604	pub fn post_migrate_to_v3() -> Result<(), &'static str> {605		use frame_support::dispatch::GetStorageVersion;606607		assert!(Self::current_storage_version() == 3);608		for k in Agenda::<T>::iter_keys() {609			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;610		}611		Ok(())612	}613614	/// Helper to migrate scheduler when the pallet origin type has changed.615	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {616		Agenda::<T>::translate::<617			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,618			_,619		>(|_, agenda| {620			Some(621				agenda622					.into_iter()623					.map(|schedule| {624						schedule.map(|schedule| Scheduled {625							maybe_id: schedule.maybe_id,626							priority: schedule.priority,627							call: schedule.call,628							maybe_periodic: schedule.maybe_periodic,629							origin: schedule.origin.into(),630							_phantom: Default::default(),631						})632					})633					.collect::<Vec<_>>(),634			)635		});636	}637638	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {639		let now = frame_system::Pallet::<T>::block_number();640641		let when = match when {642			DispatchTime::At(x) => x,643			// The current block has already completed it's scheduled tasks, so644			// Schedule the task at lest one block after this current block.645			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),646		};647648		if when <= now {649			return Err(Error::<T>::TargetBlockNumberInPast.into());650		}651652		Ok(when)653	}654655	fn do_schedule(656		when: DispatchTime<T::BlockNumber>,657		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,658		priority: schedule::Priority,659		origin: T::PalletsOrigin,660		call: CallOrHashOf<T>,661	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662		let when = Self::resolve_time(when)?;663		call.ensure_requested::<T::PreimageProvider>();664665		// sanitize maybe_periodic666		let maybe_periodic = maybe_periodic667			.filter(|p| p.1 > 1 && !p.0.is_zero())668			// Remove one from the number of repetitions since we will schedule one now.669			.map(|(p, c)| (p, c - 1));670		let s = Some(Scheduled {671			maybe_id: None,672			priority,673			call,674			maybe_periodic,675			origin,676			_phantom: PhantomData::<T::AccountId>::default(),677		});678		Agenda::<T>::append(when, s);679		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;680		Self::deposit_event(Event::Scheduled { when, index });681682		Ok((when, index))683	}684685	fn do_cancel(686		origin: Option<T::PalletsOrigin>,687		(when, index): TaskAddress<T::BlockNumber>,688	) -> Result<(), DispatchError> {689		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {690			agenda.get_mut(index as usize).map_or(691				Ok(None),692				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {693					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {694						if matches!(695							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),696							Some(Ordering::Less) | None697						) {698							return Err(BadOrigin.into());699						}700					};701					Ok(s.take())702				},703			)704		})?;705		if let Some(s) = scheduled {706			s.call.ensure_unrequested::<T::PreimageProvider>();707			if let Some(id) = s.maybe_id {708				Lookup::<T>::remove(id);709			}710			Self::deposit_event(Event::Canceled { when, index });711			Ok(())712		} else {713			Err(Error::<T>::NotFound)?714		}715	}716717	fn do_reschedule(718		(when, index): TaskAddress<T::BlockNumber>,719		new_time: DispatchTime<T::BlockNumber>,720	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {721		let new_time = Self::resolve_time(new_time)?;722723		if new_time == when {724			return Err(Error::<T>::RescheduleNoChange.into());725		}726727		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {728			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;729			let task = task.take().ok_or(Error::<T>::NotFound)?;730			Agenda::<T>::append(new_time, Some(task));731			Ok(())732		})?;733734		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;735		Self::deposit_event(Event::Canceled { when, index });736		Self::deposit_event(Event::Scheduled {737			when: new_time,738			index: new_index,739		});740741		Ok((new_time, new_index))742	}743744	fn do_schedule_named(745		id: ScheduledId,746		when: DispatchTime<T::BlockNumber>,747		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,748		priority: schedule::Priority,749		origin: T::PalletsOrigin,750		call: CallOrHashOf<T>,751	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {752		// ensure id it is unique753		if Lookup::<T>::contains_key(&id) {754			return Err(Error::<T>::FailedToSchedule)?;755		}756757		let when = Self::resolve_time(when)?;758759		call.ensure_requested::<T::PreimageProvider>();760761		// sanitize maybe_periodic762		let maybe_periodic = maybe_periodic763			.filter(|p| p.1 > 1 && !p.0.is_zero())764			// Remove one from the number of repetitions since we will schedule one now.765			.map(|(p, c)| (p, c - 1));766767		let s = Scheduled {768			maybe_id: Some(id.clone()),769			priority,770			call: call.clone(),771			maybe_periodic,772			origin: origin.clone(),773			_phantom: Default::default(),774		};775776		// reserve balance for periodic execution777		let sender =778			ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;779		let repeats = match maybe_periodic {780			Some(p) => p.1,781			None => 0,782		};783		let _ = T::CallExecutor::reserve_balance(784			id.clone(),785			sender,786			call.as_value().unwrap().clone(),787			repeats,788		);789790		Agenda::<T>::append(when, Some(s));791		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;792		let address = (when, index);793		Lookup::<T>::insert(&id, &address);794		Self::deposit_event(Event::Scheduled { when, index });795796		Ok(address)797	}798799	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {800		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {801			if let Some((when, index)) = lookup.take() {802				let i = index as usize;803				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {804					if let Some(s) = agenda.get_mut(i) {805						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {806							if matches!(807								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),808								Some(Ordering::Less) | None809							) {810								return Err(BadOrigin.into());811							}812							// release balance reserve813							let sender = ensure_signed(814								<<T as Config>::Origin as From<T::PalletsOrigin>>::from(815									origin.unwrap(),816								)817								.into(),818							)?;819							let _ = T::CallExecutor::cancel_reserve(id, sender);820821							s.call.ensure_unrequested::<T::PreimageProvider>();822						}823						*s = None;824					}825					Ok(())826				})?;827828				Self::deposit_event(Event::Canceled { when, index });829				Ok(())830			} else {831				Err(Error::<T>::NotFound)?832			}833		})834	}835836	fn do_reschedule_named(837		id: ScheduledId,838		new_time: DispatchTime<T::BlockNumber>,839	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {840		let new_time = Self::resolve_time(new_time)?;841842		Lookup::<T>::try_mutate_exists(843			id,844			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {845				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;846847				if new_time == when {848					return Err(Error::<T>::RescheduleNoChange.into());849				}850851				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {852					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;853					let task = task.take().ok_or(Error::<T>::NotFound)?;854					Agenda::<T>::append(new_time, Some(task));855856					Ok(())857				})?;858859				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;860				Self::deposit_event(Event::Canceled { when, index });861				Self::deposit_event(Event::Scheduled {862					when: new_time,863					index: new_index,864				});865866				*lookup = Some((new_time, new_index));867868				Ok((new_time, new_index))869			},870		)871	}872}873874impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>875	for Pallet<T>876{877	type Address = TaskAddress<T::BlockNumber>;878	type Hash = T::Hash;879880	fn schedule(881		when: DispatchTime<T::BlockNumber>,882		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,883		priority: schedule::Priority,884		origin: T::PalletsOrigin,885		call: CallOrHashOf<T>,886	) -> Result<Self::Address, DispatchError> {887		Self::do_schedule(when, maybe_periodic, priority, origin, call)888	}889890	fn cancel((when, index): Self::Address) -> Result<(), ()> {891		Self::do_cancel(None, (when, index)).map_err(|_| ())892	}893894	fn reschedule(895		address: Self::Address,896		when: DispatchTime<T::BlockNumber>,897	) -> Result<Self::Address, DispatchError> {898		Self::do_reschedule(address, when)899	}900901	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {902		Agenda::<T>::get(when)903			.get(index as usize)904			.ok_or(())905			.map(|_| when)906	}907}908909impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>910	for Pallet<T>911{912	type Address = TaskAddress<T::BlockNumber>;913	type Hash = T::Hash;914915	fn schedule_named(916		id: Vec<u8>,917		when: DispatchTime<T::BlockNumber>,918		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,919		priority: schedule::Priority,920		origin: T::PalletsOrigin,921		call: CallOrHashOf<T>,922	) -> Result<Self::Address, ()> {923		let inner_id: ScheduledId = id924			.try_into()925			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);926		Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)927			.map_err(|_| ())928	}929930	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {931		let inner_id: ScheduledId = id932			.try_into()933			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);934		Self::do_cancel_named(None, inner_id).map_err(|_| ())935	}936937	fn reschedule_named(938		id: Vec<u8>,939		when: DispatchTime<T::BlockNumber>,940	) -> Result<Self::Address, DispatchError> {941		let inner_id: ScheduledId = id942			.try_into()943			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);944		Self::do_reschedule_named(inner_id, when)945	}946947	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {948		let inner_id: ScheduledId = id949			.try_into()950			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);951		Lookup::<T>::get(inner_id)952			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))953			.ok_or(())954	}955}
after · pallets/scheduler/src/lib.rs
1// This file is part of Substrate.23// Copyright (C) 2017-2022 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 Pallet for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Pallet`]24//!25//! ## Overview26//!27//! This Pallet 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 a specified block and44//!   with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.46//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter47//!   that can be used for identification.48//! * `cancel_named` - the named complement to the cancel function.4950// Ensure we're `no_std` when compiling for Wasm.51#![cfg_attr(not(feature = "std"), no_std)]5253#[cfg(feature = "runtime-benchmarks")]54mod benchmarking;5556pub mod weights;5758use codec::{Codec, Decode, Encode};59use frame_support::{60	dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},61	traits::{62		schedule::{self, DispatchTime, MaybeHashed},63		NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,64		StorageVersion,65	},66	weights::{GetDispatchInfo, Weight},67};68use frame_system::{self as system, ensure_signed};69pub use pallet::*;70use scale_info::TypeInfo;71use sp_runtime::{72	traits::{BadOrigin, One, Saturating, Zero},73	RuntimeDebug, DispatchErrorWithPostInfo,74};75use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};76use sp_core::H160;77pub use weights::WeightInfo;7879/// Just a simple index for naming period tasks.80pub type PeriodicIndex = u32;81/// The location of a scheduled task that can be used to remove it.82pub type TaskAddress<BlockNumber> = (BlockNumber, u32);83pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;8485type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];86pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;8788/// Information regarding an item to be executed in the future.89#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]90#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]91pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {92	/// The unique identity for this task, if there is one.93	maybe_id: Option<ScheduledId>,94	/// This task's priority.95	priority: schedule::Priority,96	/// The call to be dispatched.97	call: Call,98	/// If the call is periodic, then this points to the information concerning that.99	maybe_periodic: Option<schedule::Period<BlockNumber>>,100	/// The origin to dispatch the call.101	origin: PalletsOrigin,102	_phantom: PhantomData<AccountId>,103}104105pub type ScheduledV3Of<T> = ScheduledV3<106	CallOrHashOf<T>,107	<T as frame_system::Config>::BlockNumber,108	<T as Config>::PalletsOrigin,109	<T as frame_system::Config>::AccountId,110>;111112pub type ScheduledOf<T> = ScheduledV3Of<T>;113114/// The current version of Scheduled struct.115pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =116	ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;117118#[cfg(feature = "runtime-benchmarks")]119mod preimage_provider {120	use frame_support::traits::PreimageRecipient;121	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}122	impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}123}124125#[cfg(not(feature = "runtime-benchmarks"))]126mod preimage_provider {127	use frame_support::traits::PreimageProvider;128	pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}129	impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}130}131132pub use preimage_provider::PreimageProviderAndMaybeRecipient;133134pub(crate) trait MarginalWeightInfo: WeightInfo {135	fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {136		match (periodic, named, resolved) {137			(_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),138			(_, true, None) => {139				Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)140			}141			(false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),142			(false, true, Some(false)) => {143				Self::on_initialize_named(2) - Self::on_initialize_named(1)144			}145			(true, false, Some(false)) => {146				Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)147			}148			(true, true, Some(false)) => {149				Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)150			}151			(false, false, Some(true)) => {152				Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)153			}154			(false, true, Some(true)) => {155				Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)156			}157			(true, false, Some(true)) => {158				Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)159			}160			(true, true, Some(true)) => {161				Self::on_initialize_periodic_named_resolved(2)162					- Self::on_initialize_periodic_named_resolved(1)163			}164		}165	}166}167impl<T: WeightInfo> MarginalWeightInfo for T {}168169#[frame_support::pallet]170pub mod pallet {171	use super::*;172	use frame_support::{173		dispatch::PostDispatchInfo,174		pallet_prelude::*,175		traits::{schedule::LookupError, PreimageProvider},176	};177	use frame_system::pallet_prelude::*;178179	/// The current storage version.180	const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);181182	#[pallet::pallet]183	#[pallet::generate_store(pub(super) trait Store)]184	#[pallet::storage_version(STORAGE_VERSION)]185	#[pallet::without_storage_info]186	pub struct Pallet<T>(_);187188	/// `system::Config` should always be included in our implied traits.189	#[pallet::config]190	pub trait Config: frame_system::Config {191		/// The overarching event type.192		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;193194		/// The aggregated origin which the dispatch will take.195		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>196			+ From<Self::PalletsOrigin>197			+ IsType<<Self as system::Config>::Origin>;198199		/// The caller origin, overarching type of all pallets origins.200		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;201202		type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;203204		/// The aggregated call type.205		type Call: Parameter206			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>207			+ GetDispatchInfo208			+ From<system::Call<Self>>;209210		/// The maximum weight that may be scheduled per block for any dispatchables of less211		/// priority than `schedule::HARD_DEADLINE`.212		#[pallet::constant]213		type MaximumWeight: Get<Weight>;214215		/// Required origin to schedule or cancel calls.216		type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;217218		/// Compare the privileges of origins.219		///220		/// This will be used when canceling a task, to ensure that the origin that tries221		/// to cancel has greater or equal privileges as the origin that created the scheduled task.222		///223		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can224		/// be used. This will only check if two given origins are equal.225		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;226227		/// The maximum number of scheduled calls in the queue for a single block.228		/// Not strictly enforced, but used for weight estimation.229		#[pallet::constant]230		type MaxScheduledPerBlock: Get<u32>;231232		/// Weight information for extrinsics in this pallet.233		type WeightInfo: WeightInfo;234235		/// The preimage provider with which we look up call hashes to get the call.236		type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;237238		/// If `Some` then the number of blocks to postpone execution for when the item is delayed.239		type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;240241		/// Sponsoring function.242		// type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;243244		/// The helper type used for custom transaction fee logic.245		type CallExecutor: DispatchCall<Self, H160>;246	}247248	/// A Scheduler-Runtime interface for finer payment handling.249	pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {250		fn reserve_balance(251			id: ScheduledId,252			sponsor: <T as frame_system::Config>::AccountId,253			call: <T as Config>::Call,254			count: u32,255		) -> Result<(), DispatchError>;256257		fn pay_for_call(258			id: ScheduledId,259			sponsor: <T as frame_system::Config>::AccountId,260			call: <T as Config>::Call,261		) -> Result<u128, DispatchError>;262263		/// Resolve the call dispatch, including any post-dispatch operations.264		fn dispatch_call(265			signer: T::AccountId,266			function: <T as Config>::Call,267		) -> Result<268			Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,269			TransactionValidityError,270		>;271272		fn cancel_reserve(273			id: ScheduledId,274			sponsor: <T as frame_system::Config>::AccountId,275		) -> Result<u128, DispatchError>;276	}277278	/// Items to be executed, indexed by the block number that they should be executed on.279	#[pallet::storage]280	pub type Agenda<T: Config> =281		StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;282283	/// Lookup from identity to the block number and index of the task.284	#[pallet::storage]285	pub(crate) type Lookup<T: Config> =286		StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;287288	/// Events type.289	#[pallet::event]290	#[pallet::generate_deposit(pub(super) fn deposit_event)]291	pub enum Event<T: Config> {292		/// Scheduled some task.293		Scheduled { when: T::BlockNumber, index: u32 },294		/// Canceled some task.295		Canceled { when: T::BlockNumber, index: u32 },296		/// Dispatched some task.297		Dispatched {298			task: TaskAddress<T::BlockNumber>,299			id: Option<ScheduledId>,300			result: DispatchResult,301		},302		/// The call for the provided hash was not found so the task has been aborted.303		CallLookupFailed {304			task: TaskAddress<T::BlockNumber>,305			id: Option<ScheduledId>,306			error: LookupError,307		},308	}309310	#[pallet::error]311	pub enum Error<T> {312		/// Failed to schedule a call313		FailedToSchedule,314		/// Cannot find the scheduled call.315		NotFound,316		/// Given target block number is in the past.317		TargetBlockNumberInPast,318		/// Reschedule failed because it does not change scheduled time.319		RescheduleNoChange,320	}321322	#[pallet::hooks]323	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {324		/// Execute the scheduled calls325		fn on_initialize(now: T::BlockNumber) -> Weight {326			let limit = T::MaximumWeight::get();327328			let mut queued = Agenda::<T>::take(now)329				.into_iter()330				.enumerate()331				.filter_map(|(index, s)| Some((index as u32, s?)))332				.collect::<Vec<_>>();333334			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {335				log::warn!(336					target: "runtime::scheduler",337					"Warning: This block has more items queued in Scheduler than \338					expected from the runtime configuration. An update might be needed."339				);340			}341342			queued.sort_by_key(|(_, s)| s.priority);343344			let next = now + One::one();345346			let mut total_weight: Weight = T::WeightInfo::on_initialize(0);347			for (order, (index, mut s)) in queued.into_iter().enumerate() {348				let named = if let Some(ref id) = s.maybe_id {349					Lookup::<T>::remove(id);350					true351				} else {352					false353				};354355				let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();356				s.call = call;357358				let resolved = if let Some(completed) = maybe_completed {359					T::PreimageProvider::unrequest_preimage(&completed);360					true361				} else {362					false363				};364365				let call = match s.call.as_value().cloned() {366					Some(c) => c,367					None => {368						// Preimage not available - postpone until some block.369						total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));370						if let Some(delay) = T::NoPreimagePostponement::get() {371							let until = now.saturating_add(delay);372							if let Some(ref id) = s.maybe_id {373								let index = Agenda::<T>::decode_len(until).unwrap_or(0);374								Lookup::<T>::insert(id, (until, index as u32));375							}376							Agenda::<T>::append(until, Some(s));377						}378						continue;379					}380				};381382				let periodic = s.maybe_periodic.is_some();383				let call_weight = call.get_dispatch_info().weight;384				let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));385				let origin =386					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())387						.into();388				if ensure_signed(origin).is_ok() {389					// Weights of Signed dispatches expect their signing account to be whitelisted.390					item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));391				}392393				// We allow a scheduled call if any is true:394				// - It's priority is `HARD_DEADLINE`395				// - It does not push the weight past the limit.396				// - It is the first item in the schedule397				let hard_deadline = s.priority <= schedule::HARD_DEADLINE;398				let test_weight = total_weight399					.saturating_add(call_weight)400					.saturating_add(item_weight);401				if !hard_deadline && order > 0 && test_weight > limit {402					// Cannot be scheduled this block - postpone until next.403					total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));404					if let Some(ref id) = s.maybe_id {405						// NOTE: We could reasonably not do this (in which case there would be one406						// block where the named and delayed item could not be referenced by name),407						// but we will do it anyway since it should be mostly free in terms of408						// weight and it is slightly cleaner.409						let index = Agenda::<T>::decode_len(next).unwrap_or(0);410						Lookup::<T>::insert(id, (next, index as u32));411					}412					Agenda::<T>::append(next, Some(s));413					continue;414				}415416				let sender = ensure_signed(417					<<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())418						.into(),419				)420				.unwrap();421422				// if call have id and periodic, it was be reserved423				if s.maybe_id.is_some() && s.maybe_periodic.is_some() {424					let _ = T::CallExecutor::pay_for_call(425						s.maybe_id.unwrap(),426						sender.clone(),427						call.clone(),428					);429				}430431				let r = T::CallExecutor::dispatch_call(sender, call.clone());432433				let mut actual_call_weight: Weight = item_weight; //PostDispatchInfo;434				let result: Result<_, DispatchError> = match r {435					Ok(o) => match o {436						Ok(di) => {437							actual_call_weight = di.actual_weight.unwrap_or(item_weight);438							Ok(())439						}440						Err(err) => Err(err.error),441					},442					Err(_) => {443						log::error!(444							target: "runtime::scheduler",445							"Warning: Scheduler has failed to execute a post-dispatch transaction. \446							This block might have become invalid.");447						Err(DispatchError::CannotLookup)448					} // todo possibly force a skip/return here, do something with the error449				};450451				total_weight.saturating_accrue(item_weight);452				total_weight.saturating_accrue(actual_call_weight);453454				Self::deposit_event(Event::Dispatched {455					task: (now, index),456					id: s.maybe_id.clone(),457					result,458				});459460				if let &Some((period, count)) = &s.maybe_periodic {461					if count > 1 {462						s.maybe_periodic = Some((period, count - 1));463					} else {464						s.maybe_periodic = None;465					}466					let wake = now + period;467					// If scheduled is named, place its information in `Lookup`468					if let Some(ref id) = s.maybe_id {469						let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);470						Lookup::<T>::insert(id, (wake, wake_index as u32));471					}472					Agenda::<T>::append(wake, Some(s));473				}474			}475			total_weight476		}477	}478479	#[pallet::call]480	impl<T: Config> Pallet<T> {481		/// Anonymously schedule a task.482		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]483		pub fn schedule(484			origin: OriginFor<T>,485			when: T::BlockNumber,486			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,487			priority: schedule::Priority,488			call: Box<CallOrHashOf<T>>,489		) -> DispatchResult {490			T::ScheduleOrigin::ensure_origin(origin.clone())?;491			let origin = <T as Config>::Origin::from(origin);492			Self::do_schedule(493				DispatchTime::At(when),494				maybe_periodic,495				priority,496				origin.caller().clone(),497				*call,498			)?;499			Ok(())500		}501502		/// Cancel an anonymously scheduled task.503		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]504		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {505			T::ScheduleOrigin::ensure_origin(origin.clone())?;506			let origin = <T as Config>::Origin::from(origin);507			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;508			Ok(())509		}510511		/// Schedule a named task.512		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]513		pub fn schedule_named(514			origin: OriginFor<T>,515			id: ScheduledId,516			when: T::BlockNumber,517			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,518			priority: schedule::Priority,519			call: Box<CallOrHashOf<T>>,520		) -> DispatchResult {521			T::ScheduleOrigin::ensure_origin(origin.clone())?;522			let origin = <T as Config>::Origin::from(origin);523			Self::do_schedule_named(524				id,525				DispatchTime::At(when),526				maybe_periodic,527				priority,528				origin.caller().clone(),529				*call,530			)?;531			Ok(())532		}533534		/// Cancel a named scheduled task.535		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]536		pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {537			T::ScheduleOrigin::ensure_origin(origin.clone())?;538			let origin = <T as Config>::Origin::from(origin);539			Self::do_cancel_named(Some(origin.caller().clone()), id)?;540			Ok(())541		}542543		/// Anonymously schedule a task after a delay.544		///545		/// # <weight>546		/// Same as [`schedule`].547		/// # </weight>548		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]549		pub fn schedule_after(550			origin: OriginFor<T>,551			after: T::BlockNumber,552			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,553			priority: schedule::Priority,554			call: Box<CallOrHashOf<T>>,555		) -> DispatchResult {556			T::ScheduleOrigin::ensure_origin(origin.clone())?;557			let origin = <T as Config>::Origin::from(origin);558			Self::do_schedule(559				DispatchTime::After(after),560				maybe_periodic,561				priority,562				origin.caller().clone(),563				*call,564			)?;565			Ok(())566		}567568		/// Schedule a named task after a delay.569		///570		/// # <weight>571		/// Same as [`schedule_named`](Self::schedule_named).572		/// # </weight>573		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]574		pub fn schedule_named_after(575			origin: OriginFor<T>,576			id: ScheduledId,577			after: T::BlockNumber,578			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,579			priority: schedule::Priority,580			call: Box<CallOrHashOf<T>>,581		) -> DispatchResult {582			T::ScheduleOrigin::ensure_origin(origin.clone())?;583			let origin = <T as Config>::Origin::from(origin);584			Self::do_schedule_named(585				id,586				DispatchTime::After(after),587				maybe_periodic,588				priority,589				origin.caller().clone(),590				*call,591			)?;592			Ok(())593		}594	}595}596597impl<T: Config> Pallet<T> {598	#[cfg(feature = "try-runtime")]599	pub fn pre_migrate_to_v3() -> Result<(), &'static str> {600		Ok(())601	}602603	#[cfg(feature = "try-runtime")]604	pub fn post_migrate_to_v3() -> Result<(), &'static str> {605		use frame_support::dispatch::GetStorageVersion;606607		assert!(Self::current_storage_version() == 3);608		for k in Agenda::<T>::iter_keys() {609			let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;610		}611		Ok(())612	}613614	/// Helper to migrate scheduler when the pallet origin type has changed.615	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {616		Agenda::<T>::translate::<617			Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,618			_,619		>(|_, agenda| {620			Some(621				agenda622					.into_iter()623					.map(|schedule| {624						schedule.map(|schedule| Scheduled {625							maybe_id: schedule.maybe_id,626							priority: schedule.priority,627							call: schedule.call,628							maybe_periodic: schedule.maybe_periodic,629							origin: schedule.origin.into(),630							_phantom: Default::default(),631						})632					})633					.collect::<Vec<_>>(),634			)635		});636	}637638	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {639		let now = frame_system::Pallet::<T>::block_number();640641		let when = match when {642			DispatchTime::At(x) => x,643			// The current block has already completed it's scheduled tasks, so644			// Schedule the task at lest one block after this current block.645			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),646		};647648		if when <= now {649			return Err(Error::<T>::TargetBlockNumberInPast.into());650		}651652		Ok(when)653	}654655	fn do_schedule(656		when: DispatchTime<T::BlockNumber>,657		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,658		priority: schedule::Priority,659		origin: T::PalletsOrigin,660		call: CallOrHashOf<T>,661	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662		let when = Self::resolve_time(when)?;663		call.ensure_requested::<T::PreimageProvider>();664665		// sanitize maybe_periodic666		let maybe_periodic = maybe_periodic667			.filter(|p| p.1 > 1 && !p.0.is_zero())668			// Remove one from the number of repetitions since we will schedule one now.669			.map(|(p, c)| (p, c - 1));670		let s = Some(Scheduled {671			maybe_id: None,672			priority,673			call,674			maybe_periodic,675			origin,676			_phantom: PhantomData::<T::AccountId>::default(),677		});678		Agenda::<T>::append(when, s);679		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;680		Self::deposit_event(Event::Scheduled { when, index });681682		Ok((when, index))683	}684685	fn do_cancel(686		origin: Option<T::PalletsOrigin>,687		(when, index): TaskAddress<T::BlockNumber>,688	) -> Result<(), DispatchError> {689		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {690			agenda.get_mut(index as usize).map_or(691				Ok(None),692				|s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {693					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {694						if matches!(695							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),696							Some(Ordering::Less) | None697						) {698							return Err(BadOrigin.into());699						}700					};701					Ok(s.take())702				},703			)704		})?;705		if let Some(s) = scheduled {706			s.call.ensure_unrequested::<T::PreimageProvider>();707			if let Some(id) = s.maybe_id {708				Lookup::<T>::remove(id);709			}710			Self::deposit_event(Event::Canceled { when, index });711			Ok(())712		} else {713			Err(Error::<T>::NotFound)?714		}715	}716717	fn do_reschedule(718		(when, index): TaskAddress<T::BlockNumber>,719		new_time: DispatchTime<T::BlockNumber>,720	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {721		let new_time = Self::resolve_time(new_time)?;722723		if new_time == when {724			return Err(Error::<T>::RescheduleNoChange.into());725		}726727		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {728			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;729			let task = task.take().ok_or(Error::<T>::NotFound)?;730			Agenda::<T>::append(new_time, Some(task));731			Ok(())732		})?;733734		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;735		Self::deposit_event(Event::Canceled { when, index });736		Self::deposit_event(Event::Scheduled {737			when: new_time,738			index: new_index,739		});740741		Ok((new_time, new_index))742	}743744	fn do_schedule_named(745		id: ScheduledId,746		when: DispatchTime<T::BlockNumber>,747		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,748		priority: schedule::Priority,749		origin: T::PalletsOrigin,750		call: CallOrHashOf<T>,751	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {752		// ensure id it is unique753		if Lookup::<T>::contains_key(&id) {754			return Err(Error::<T>::FailedToSchedule)?;755		}756757		let when = Self::resolve_time(when)?;758759		call.ensure_requested::<T::PreimageProvider>();760761		// sanitize maybe_periodic762		let maybe_periodic = maybe_periodic763			.filter(|p| p.1 > 1 && !p.0.is_zero())764			// Remove one from the number of repetitions since we will schedule one now.765			.map(|(p, c)| (p, c - 1));766767		let s = Scheduled {768			maybe_id: Some(id.clone()),769			priority,770			call: call.clone(),771			maybe_periodic,772			origin: origin.clone(),773			_phantom: Default::default(),774		};775776		// reserve balance for periodic execution777		let sender =778			ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;779		let repeats = match maybe_periodic {780			Some(p) => p.1,781			None => 0,782		};783		let _ = T::CallExecutor::reserve_balance(784			id.clone(),785			sender,786			call.as_value().unwrap().clone(),787			repeats,788		);789790		Agenda::<T>::append(when, Some(s));791		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;792		let address = (when, index);793		Lookup::<T>::insert(&id, &address);794		Self::deposit_event(Event::Scheduled { when, index });795796		Ok(address)797	}798799	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {800		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {801			if let Some((when, index)) = lookup.take() {802				let i = index as usize;803				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {804					if let Some(s) = agenda.get_mut(i) {805						if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {806							if matches!(807								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),808								Some(Ordering::Less) | None809							) {810								return Err(BadOrigin.into());811							}812							// release balance reserve813							let sender = ensure_signed(814								<<T as Config>::Origin as From<T::PalletsOrigin>>::from(815									origin.unwrap(),816								)817								.into(),818							)?;819							let _ = T::CallExecutor::cancel_reserve(id, sender);820821							s.call.ensure_unrequested::<T::PreimageProvider>();822						}823						*s = None;824					}825					Ok(())826				})?;827828				Self::deposit_event(Event::Canceled { when, index });829				Ok(())830			} else {831				Err(Error::<T>::NotFound)?832			}833		})834	}835836	fn do_reschedule_named(837		id: ScheduledId,838		new_time: DispatchTime<T::BlockNumber>,839	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {840		let new_time = Self::resolve_time(new_time)?;841842		Lookup::<T>::try_mutate_exists(843			id,844			|lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {845				let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;846847				if new_time == when {848					return Err(Error::<T>::RescheduleNoChange.into());849				}850851				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {852					let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;853					let task = task.take().ok_or(Error::<T>::NotFound)?;854					Agenda::<T>::append(new_time, Some(task));855856					Ok(())857				})?;858859				let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;860				Self::deposit_event(Event::Canceled { when, index });861				Self::deposit_event(Event::Scheduled {862					when: new_time,863					index: new_index,864				});865866				*lookup = Some((new_time, new_index));867868				Ok((new_time, new_index))869			},870		)871	}872}873874impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>875	for Pallet<T>876{877	type Address = TaskAddress<T::BlockNumber>;878	type Hash = T::Hash;879880	fn schedule(881		when: DispatchTime<T::BlockNumber>,882		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,883		priority: schedule::Priority,884		origin: T::PalletsOrigin,885		call: CallOrHashOf<T>,886	) -> Result<Self::Address, DispatchError> {887		Self::do_schedule(when, maybe_periodic, priority, origin, call)888	}889890	fn cancel((when, index): Self::Address) -> Result<(), ()> {891		Self::do_cancel(None, (when, index)).map_err(|_| ())892	}893894	fn reschedule(895		address: Self::Address,896		when: DispatchTime<T::BlockNumber>,897	) -> Result<Self::Address, DispatchError> {898		Self::do_reschedule(address, when)899	}900901	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {902		Agenda::<T>::get(when)903			.get(index as usize)904			.ok_or(())905			.map(|_| when)906	}907}908909impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>910	for Pallet<T>911{912	type Address = TaskAddress<T::BlockNumber>;913	type Hash = T::Hash;914915	fn schedule_named(916		id: Vec<u8>,917		when: DispatchTime<T::BlockNumber>,918		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,919		priority: schedule::Priority,920		origin: T::PalletsOrigin,921		call: CallOrHashOf<T>,922	) -> Result<Self::Address, ()> {923		let inner_id: ScheduledId = id924			.try_into()925			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);926		Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)927			.map_err(|_| ())928	}929930	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {931		let inner_id: ScheduledId = id932			.try_into()933			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);934		Self::do_cancel_named(None, inner_id).map_err(|_| ())935	}936937	fn reschedule_named(938		id: Vec<u8>,939		when: DispatchTime<T::BlockNumber>,940	) -> Result<Self::Address, DispatchError> {941		let inner_id: ScheduledId = id942			.try_into()943			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);944		Self::do_reschedule_named(inner_id, when)945	}946947	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {948		let inner_id: ScheduledId = id949			.try_into()950			.unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);951		Lookup::<T>::get(inner_id)952			.and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))953			.ok_or(())954	}955}
modifiedtests/package.jsondiffbeforeafterboth
--- a/tests/package.json
+++ b/tests/package.json
@@ -64,6 +64,7 @@
     "testSetVariableMetadataSponsoringRateLimit": "mocha --timeout 9999999 -r ts-node/register ./**/setVariableMetadataSponsoringRateLimit.test.ts",
     "testInflation": "mocha --timeout 9999999 -r ts-node/register ./**/inflation.test.ts",
     "testScheduler": "mocha --timeout 9999999 -r ts-node/register ./**/scheduler.test.ts",
+    "testSchedulingEVM": "mocha --timeout 9999999 -r ts-node/register ./**/eth/scheduling.test.ts",
     "testXcmTransfer": "mocha --timeout 9999999 -r ts-node/register ./**/xcmTransfer.test.ts",
     "testPalletPresence": "mocha --timeout 9999999 -r ts-node/register ./**/pallet-presence.test.ts",
     "testBlockProduction": "mocha --timeout 9999999 -r ts-node/register ./**/block-production.test.ts",
addedtests/src/eth/scheduling.test.tsdiffbeforeafterboth
--- /dev/null
+++ b/tests/src/eth/scheduling.test.ts
@@ -0,0 +1,55 @@
+// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.
+// This file is part of Unique Network.
+
+// Unique Network is free software: you can redistribute it and/or modify
+// it under the terms of the GNU General Public License as published by
+// the Free Software Foundation, either version 3 of the License, or
+// (at your option) any later version.
+
+// Unique Network is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License
+// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
+
+import {expect} from 'chai';
+import {createEthAccountWithBalance, deployFlipper, GAS_ARGS, itWeb3, subToEth, transferBalanceToEth} from './util/helpers';
+import {scheduleExpectSuccess, waitNewBlocks} from '../util/helpers';
+import privateKey from '../substrate/privateKey';
+
+describe('Scheduing EVM smart contracts', () => {
+  itWeb3('Successfully schedules and periodically executes an EVM contract', async ({api, web3}) => {
+    const deployer = await createEthAccountWithBalance(api, web3);
+    const flipper = await deployFlipper(web3, deployer);
+    const initialValue = await flipper.methods.getValue().call();
+    const alice = privateKey('//Alice');
+    await transferBalanceToEth(api, alice, subToEth(alice.address));
+
+    {
+      const tx = api.tx.evm.call(
+        subToEth(alice.address),
+        flipper.options.address,
+        flipper.methods.flip().encodeABI(),
+        '0',
+        GAS_ARGS.gas,
+        await web3.eth.getGasPrice(),
+        null,
+        null,
+        [],
+      );
+      const waitForBlocks = 4;
+      const periodBlocks = 2;
+
+      await scheduleExpectSuccess(tx, alice, waitForBlocks, '0x' + '0'.repeat(32), periodBlocks, 2);
+      expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+      
+      await waitNewBlocks(waitForBlocks - 1);
+      expect(await flipper.methods.getValue().call()).to.be.not.equal(initialValue);
+  
+      await waitNewBlocks(periodBlocks);
+      expect(await flipper.methods.getValue().call()).to.be.equal(initialValue);
+    }
+  });
+});
\ No newline at end of file
modifiedtests/src/scheduler.test.tsdiffbeforeafterboth
--- a/tests/src/scheduler.test.ts
+++ b/tests/src/scheduler.test.ts
@@ -20,7 +20,6 @@
 import {
   default as usingApi, 
   submitTransactionAsync,
-  submitTransactionExpectFailAsync,
 } from './substrate/substrate-api';
 import {
   createItemExpectSuccess,
@@ -40,49 +39,58 @@
   scheduleTransferFundsPeriodicExpectSuccess,
   getFreeBalance,
   confirmSponsorshipByKeyExpectSuccess,
+  scheduleExpectFailure,
 } from './util/helpers';
 import {IKeyringPair} from '@polkadot/types/types';
-import {getBalanceSingle} from './substrate/get-balance';
 
 chai.use(chaiAsPromised);
 
 describe('Scheduling token and balance transfers', () => {
   let alice: IKeyringPair;
   let bob: IKeyringPair;
+  let scheduledIdBase: string;
+  let scheduledIdSlider: number;
 
   before(async() => {
     await usingApi(async () => {
       alice = privateKey('//Alice');
       bob = privateKey('//Bob');
     });
+
+    scheduledIdBase = '0x' + '0'.repeat(31);
+    scheduledIdSlider = 0;
   });
 
+  // Loop scheduledId around 10. Unless there are concurrent tasks with long periods/repetitions, tests' tasks' ids shouldn't ovelap.
+  function makeScheduledId(): string {
+    return scheduledIdBase + ((scheduledIdSlider++) % 10);
+  }
+
   it('Can schedule a transfer of an owned token with delay', async () => {
     await usingApi(async () => {
-      // nft
       const nftCollectionId = await createCollectionExpectSuccess();
       const newNftTokenId = await createItemExpectSuccess(alice, nftCollectionId, 'NFT');
       await setCollectionSponsorExpectSuccess(nftCollectionId, alice.address);
       await confirmSponsorshipExpectSuccess(nftCollectionId);
 
-      await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4);
+      await scheduleTransferAndWaitExpectSuccess(nftCollectionId, newNftTokenId, alice, bob, 1, 4, makeScheduledId());
     });
   });
 
   it('Can transfer funds periodically', async () => {
-    await usingApi(async (api) => {
+    await usingApi(async () => {
       const waitForBlocks = 4;
       const period = 2;
-      await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, period, 2);
-      const bobsBalanceBefore = await getBalanceSingle(api, bob.address);
+      await scheduleTransferFundsPeriodicExpectSuccess(1n * UNIQUE, alice, bob, waitForBlocks, makeScheduledId(), period, 2);
+      const bobsBalanceBefore = await getFreeBalance(bob);
 
       // discounting already waited-for operations
       await waitNewBlocks(waitForBlocks - 2);
-      const bobsBalanceAfterFirst = await getBalanceSingle(api, bob.address);
+      const bobsBalanceAfterFirst = await getFreeBalance(bob);
       expect(bobsBalanceAfterFirst > bobsBalanceBefore).to.be.true;
 
       await waitNewBlocks(period);
-      const bobsBalanceAfterSecond = await getBalanceSingle(api, bob.address);
+      const bobsBalanceAfterSecond = await getFreeBalance(bob);
       expect(bobsBalanceAfterSecond > bobsBalanceAfterFirst).to.be.true;
     });
   });
@@ -95,28 +103,18 @@
     await usingApi(async () => {
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
 
-      const aliceBalanceBefore = await getFreeBalance(alice);
+      const bobBalanceBefore = await getFreeBalance(bob);
+      const waitForBlocks = 4;
       // no need to wait to check, fees must be deducted on scheduling, immediately
-      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, 4);
-      const aliceBalanceAfter = await getFreeBalance(alice);
-      expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, bob, 0, waitForBlocks, makeScheduledId());
+      const bobBalanceAfter = await getFreeBalance(bob);
+      // expect(aliceBalanceAfter == aliceBalanceBefore).to.be.true;
+      expect(bobBalanceAfter < bobBalanceBefore).to.be.true;
+      // wait for sequentiality matters
+      await waitNewBlocks(waitForBlocks - 1);
     });
   });
 
-  /*it('Can\'t schedule a transaction with no funds', async () => {
-    await usingApi(async (api) => {
-      // Find an empty, unused account
-      const zeroBalance = await findUnusedAddress(api);
-
-      const collectionId = await createCollectionExpectSuccess();
-      const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT');
-
-      await transferExpectSuccess(collectionId, tokenId, alice, zeroBalance);
-
-      await scheduleTransferAndWaitExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, 4);
-    });
-  });*/
-
   it('Schedules and dispatches a transaction even if the caller has no funds at the time of the dispatch', async () => {
     await usingApi(async (api) => {
       // Find an empty, unused account
@@ -137,13 +135,16 @@
 
       // Schedule transfer of the NFT a few blocks ahead
       const waitForBlocks = 5;
-      await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks);
+      await scheduleTransferExpectSuccess(collectionId, tokenId, zeroBalance, alice, 1, waitForBlocks, makeScheduledId());
 
       // Get rid of the account's funds before the scheduled transaction takes place
-      const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
+      const balanceTx2 = api.tx.balances.transfer(alice.address, UNIQUE * 68n / 100n);
+      const events = await submitTransactionAsync(zeroBalance, balanceTx2);
+      expect(getGenericResult(events).success).to.be.true;
+      /*const emptyBalanceTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0); // do not null reserved?
       const sudoTx = api.tx.sudo.sudo(emptyBalanceTx as any);
       const events = await submitTransactionAsync(alice, sudoTx);
-      expect(getGenericResult(events).success).to.be.true;
+      expect(getGenericResult(events).success).to.be.true;*/
 
       // Wait for a certain number of blocks, discarding the ones that already happened while accepting the late transactions
       await waitNewBlocks(waitForBlocks - 3);
@@ -157,11 +158,6 @@
 
     await usingApi(async (api) => {
       const zeroBalance = await findUnusedAddress(api);
-
-      /*await setCollectionLimitsExpectSuccess(alice, nftCollectionId, {
-        sponsoredDataRateLimit: 2,
-      });*/
-      //console.log(await getDetailedCollectionInfo(api, nftCollectionId));
       const balanceTx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
       await submitTransactionAsync(alice, balanceTx);
 
@@ -170,7 +166,8 @@
 
       const tokenId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
 
-      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, 5);
+      const waitForBlocks = 5;
+      await scheduleTransferExpectSuccess(collectionId, tokenId, alice, zeroBalance, 1, waitForBlocks, makeScheduledId());
 
       const emptyBalanceSponsorTx = api.tx.balances.setBalance(zeroBalance.address, 0, 0);
       const sudoTx = api.tx.sudo.sudo(emptyBalanceSponsorTx as any);
@@ -178,61 +175,36 @@
       expect(getGenericResult(events).success).to.be.true;
 
       // Wait for a certain number of blocks, save for the ones that already happened while accepting the late transactions
-      await waitNewBlocks(2);
+      await waitNewBlocks(waitForBlocks - 3);
 
       expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(zeroBalance.address));
     });
   });
-});
 
-describe.skip('Scheduling EVM smart contracts', () => {
-  let alice: IKeyringPair;
-  let bob: IKeyringPair;
-
-  before(async() => {
-    await usingApi(async () => {
-      alice = privateKey('//Alice');
-      bob = privateKey('//Bob');
-    });
-  });
-
-  // todo contract testing
-  it.skip('NFT: Sponsoring of transfers is rate limited', async () => {
+  it.skip('Exceeding sponsor rate limit without having enough funds prevents scheduling a periodic transaction', async () => {
     const collectionId = await createCollectionExpectSuccess();
     await setCollectionSponsorExpectSuccess(collectionId, bob.address);
     await confirmSponsorshipExpectSuccess(collectionId, '//Bob');
 
     await usingApi(async (api) => {
-      // Find unused address
       const zeroBalance = await findUnusedAddress(api);
 
-      // Mint token for alice
-      const itemId = await createItemExpectSuccess(alice, collectionId, 'NFT', alice.address);
+      await enablePublicMintingExpectSuccess(alice, collectionId);
+      await addToAllowListExpectSuccess(alice, collectionId, zeroBalance.address);
 
-      // Transfer this token from Alice to unused address and back
-      // Alice to Zero gets sponsored
-      const aliceToZero = api.tx.unique.transfer(normalizeAccountId(zeroBalance.address), collectionId, itemId, 0);
-      const events1 = await submitTransactionAsync(alice, aliceToZero);
-      const result1 = getGenericResult(events1);
+      const bobBalanceBefore = await getFreeBalance(bob);
+
+      const createData = {nft: {const_data: [], variable_data: []}};
+      const creationTx = api.tx.unique.createItem(collectionId, normalizeAccountId(zeroBalance), createData as any);
 
-      // Second transfer should fail
-      const sponsorBalanceBefore = (await api.query.system.account(bob.address)).data.free.toBigInt();
-      const zeroToAlice = api.tx.unique.transfer(normalizeAccountId(alice.address), collectionId, itemId, 0);
-      const badTransaction = async function () {
+      /*const badTransaction = async function () {
         await submitTransactionExpectFailAsync(zeroBalance, zeroToAlice);
       };
-      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');
-      const sponsorBalanceAfter = (await api.query.system.account(bob.address)).data.free.toBigInt();
+      await expect(badTransaction()).to.be.rejectedWith('Inability to pay some fees');*/
 
-      // Try again after Zero gets some balance - now it should succeed
-      const balancetx = api.tx.balances.transfer(zeroBalance.address, 1n * UNIQUE);
-      await submitTransactionAsync(alice, balancetx);
-      const events2 = await submitTransactionAsync(zeroBalance, zeroToAlice);
-      const result2 = getGenericResult(events2);
+      await scheduleExpectFailure(creationTx, zeroBalance, 3, makeScheduledId(), 1, 3);
 
-      expect(result1.success).to.be.true;
-      expect(result2.success).to.be.true;
-      expect(sponsorBalanceAfter).to.be.equal(sponsorBalanceBefore);
+      expect(await getFreeBalance(bob)).to.be.equal(bobBalanceBefore);
     });
   });
 });
modifiedtests/src/util/helpers.tsdiffbeforeafterboth
--- a/tests/src/util/helpers.ts
+++ b/tests/src/util/helpers.ts
@@ -846,6 +846,61 @@
 }
 
 export async function
+scheduleExpectSuccess(
+  operationTx: any,
+  sender: IKeyringPair,
+  blockSchedule: number,
+  scheduledId: string,
+  period = 1,
+  repetitions = 1,
+) {
+  await usingApi(async (api: ApiPromise) => {
+    const blockNumber: number | undefined = await getBlockNumber(api);
+    const expectedBlockNumber = blockNumber + blockSchedule;
+
+    expect(blockNumber).to.be.greaterThan(0);
+    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+      scheduledId,
+      expectedBlockNumber, 
+      repetitions > 1 ? [period, repetitions] : null, 
+      0, 
+      {value: operationTx as any},
+    );
+
+    const events = await submitTransactionAsync(sender, scheduleTx);
+    expect(getGenericResult(events).success).to.be.true;
+  });
+}
+
+export async function
+scheduleExpectFailure(
+  operationTx: any,
+  sender: IKeyringPair,
+  blockSchedule: number,
+  scheduledId: string,
+  period = 1,
+  repetitions = 1,
+) {
+  await usingApi(async (api: ApiPromise) => {
+    const blockNumber: number | undefined = await getBlockNumber(api);
+    const expectedBlockNumber = blockNumber + blockSchedule;
+
+    expect(blockNumber).to.be.greaterThan(0);
+    const scheduleTx = api.tx.scheduler.scheduleNamed( // schedule
+      scheduledId,
+      expectedBlockNumber, 
+      repetitions <= 1 ? null : [period, repetitions], 
+      0, 
+      {value: operationTx as any},
+    );
+
+    //const events = 
+    await expect(submitTransactionExpectFailAsync(sender, scheduleTx)).to.be.rejected;
+    //expect(getGenericResult(events).success).to.be.false;
+  });
+}
+
+export async function
 scheduleTransferAndWaitExpectSuccess(
   collectionId: number,
   tokenId: number,
@@ -853,12 +908,12 @@
   recipient: IKeyringPair,
   value: number | bigint = 1,
   blockSchedule: number,
+  scheduledId: string,
 ) {
   await usingApi(async (api: ApiPromise) => {
-    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule);
+    await scheduleTransferExpectSuccess(collectionId, tokenId, sender, recipient, value, blockSchedule, scheduledId);
 
     const recipientBalanceBefore = (await api.query.system.account(recipient.address)).data.free.toBigInt();
-    console.log(await getFreeBalance(sender));
 
     // sleep for n + 1 blocks
     await waitNewBlocks(blockSchedule + 1);
@@ -878,17 +933,12 @@
   recipient: IKeyringPair,
   value: number | bigint = 1,
   blockSchedule: number,
+  scheduledId: string,
 ) {
   await usingApi(async (api: ApiPromise) => {
-    const blockNumber: number | undefined = await getBlockNumber(api);
-    const expectedBlockNumber = blockNumber + blockSchedule;
-
-    expect(blockNumber).to.be.greaterThan(0);
     const transferTx = api.tx.unique.transfer(normalizeAccountId(recipient.address), collectionId, tokenId, value);
-    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, null, 0, transferTx as any);
 
-    const events = await submitTransactionAsync(sender, scheduleTx);
-    expect(getGenericResult(events).success).to.be.true;
+    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId);
 
     expect(await getTokenOwner(api, collectionId, tokenId)).to.be.deep.equal(normalizeAccountId(sender.address));
   });
@@ -900,26 +950,20 @@
   sender: IKeyringPair,
   recipient: IKeyringPair,
   blockSchedule: number,
+  scheduledId: string,
   period: number,
   repetitions: number,
 ) {
   await usingApi(async (api: ApiPromise) => {
-    const blockNumber: number | undefined = await getBlockNumber(api);
-    const expectedBlockNumber = blockNumber + blockSchedule;
+    const transferTx = api.tx.balances.transfer(recipient.address, amount);
 
     const balanceBefore = await getFreeBalance(recipient);
     
-    expect(blockNumber).to.be.greaterThan(0);
-    const transferTx = api.tx.balances.transfer(recipient.address, amount);
-    const scheduleTx = api.tx.scheduler.schedule(expectedBlockNumber, [period, repetitions], 0, transferTx as any);
+    await scheduleExpectSuccess(transferTx, sender, blockSchedule, scheduledId, period, repetitions);
 
-    const events = await submitTransactionAsync(sender, scheduleTx);
-    expect(getGenericResult(events).success).to.be.true;
-
     expect(await getFreeBalance(recipient)).to.be.equal(balanceBefore);
   });
 }
-
 
 export async function
 transferExpectSuccess(