git.delta.rocks / unique-network / refs/commits / 900dc0450c74

difftreelog

reafactor: switch scheduler to sponsoring primitive

Yaroslav Bolyukin2021-06-24parent: #afcf32a.patch.diff
in: master

2 files changed

modifiedpallets/scheduler/Cargo.tomldiffbeforeafterboth
--- a/pallets/scheduler/Cargo.toml
+++ b/pallets/scheduler/Cargo.toml
@@ -14,15 +14,12 @@
 codec = { package = "parity-scale-codec", version = "2.0.0", default-features = false }
 frame-support = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-system = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
-pallet-contracts = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-runtime = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-std = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 sp-io = { default-features = false, version = '3.0.0', git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 frame-benchmarking = { default-features = false, version = '3.0.0', optional = true, git = 'https://github.com/paritytech/substrate.git', branch = 'polkadot-v0.9.3' }
 
-pallet-nft-transaction-payment = { default-features = false, path = "../nft-transaction-payment" }
-pallet-nft = { default-features = false, path = "../nft" }
-nft-data-structs = { path = '../../primitives', default-features = false }
+up-sponsorship = { default-features = false, path = "../../primitives/sponsorship", version = "0.1.0" }
 log = { version = "0.4.14", default-features = false }
 
 [dev-dependencies]
@@ -37,10 +34,7 @@
 	"frame-benchmarking/std",
 	"frame-support/std",
 	"frame-system/std",
-	"pallet-nft-transaction-payment/std",
-	"pallet-nft/std",
-	"pallet-contracts/std",
-	"nft-data-structs/std",
+	"up-sponsorship/std",
 	"sp-io/std",
 	"sp-std/std",
 	"log/std",
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)]5354mod benchmarking;55pub mod weights;5657use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};58use codec::{Encode, Decode, Codec};59use sp_runtime::{RuntimeDebug, traits::{Zero, One, BadOrigin, Saturating}};60use frame_support::{61	decl_module, decl_storage, decl_event, decl_error, IterableStorageMap,62	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},63	traits::{Get, schedule::{self, DispatchTime}, OriginTrait, EnsureOrigin, IsType},64	weights::{GetDispatchInfo, Weight},65};66use frame_system::{self as system, ensure_signed};67use pallet_nft::*;68// use pallet_nft_transaction_payment::{self as nft_transaction_payment};69use nft_data_structs::*;70pub use weights::WeightInfo;7172/// Our pallet's configuration trait. All our types and constants go in here. If the73/// pallet is dependent on specific other pallets, then their configuration traits74/// should be added to our implied traits list.75///76/// `system::Config` should always be included in our implied traits.77/// // 78pub trait Config: system::Config79{ 8081	/// The overarching event type.82	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;8384	/// The aggregated origin which the dispatch will take.85	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>86		+ From<Self::PalletsOrigin> + IsType<<Self as system::Config>::Origin>;8788	/// The caller origin, overarching type of all pallets origins.89	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq;9091	/// The aggregated call type.92	type Call: Parameter + Dispatchable<Origin=<Self as Config>::Origin> + GetDispatchInfo + From<system::Call<Self>>;9394	/// The maximum weight that may be scheduled per block for any dispatchables of less priority95	/// than `schedule::HARD_DEADLINE`.96	type MaximumWeight: Get<Weight>;9798	/// Required origin to schedule or cancel calls.99	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;100101	/// The maximum number of scheduled calls in the queue for a single block.102	/// Not strictly enforced, but used for weight estimation.103	type MaxScheduledPerBlock: Get<u32>;104105	/// Sponsoring function106	type Sponsoring: SponsoringResolve<Self::AccountId, <Self as Config>::Call>;107108	/// Weight information for extrinsics in this pallet.109	type WeightInfo: WeightInfo;110}111112// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;113114/// Just a simple index for naming period tasks.115pub type PeriodicIndex = u32;116/// The location of a scheduled task that can be used to remove it.117pub type TaskAddress<BlockNumber> = (BlockNumber, u32);118119#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]120#[derive(Clone, RuntimeDebug, Encode, Decode)]121struct ScheduledV1<Call, BlockNumber> {122	maybe_id: Option<Vec<u8>>,123	priority: schedule::Priority,124	call: Call,125	maybe_periodic: Option<schedule::Period<BlockNumber>>,126}127128/// Information regarding an item to be executed in the future.129#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]130#[derive(Clone, RuntimeDebug, Encode, Decode)]131pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {132	/// The unique identity for this task, if there is one.133	maybe_id: Option<Vec<u8>>,134	/// This task's priority.135	priority: schedule::Priority,136	/// The call to be dispatched.137	call: Call,138	/// If the call is periodic, then this points to the information concerning that.139	maybe_periodic: Option<schedule::Period<BlockNumber>>,140	/// The origin to dispatch the call.141	origin: PalletsOrigin,142	_phantom: PhantomData<AccountId>,143}144145/// The current version of Scheduled struct.146pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> = ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;147148// A value placed in storage that represents the current version of the Scheduler storage.149// This value is used by the `on_runtime_upgrade` logic to determine whether we run150// storage migration logic.151#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]152enum Releases {153	V1,154	V2,155}156157impl Default for Releases {158	fn default() -> Self {159		Releases::V1160	}161}162163#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]164pub struct CallSpec {165166	module: u32,167	method: u32,168}169170decl_storage! {171	trait Store for Module<T: Config> as Scheduler {172		/// Items to be executed, indexed by the block number that they should be executed on.173		pub Agenda: map hasher(twox_64_concat) T::BlockNumber174			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;175176		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber177			=> Vec<Option<CallSpec>>;			178179		/// Lookup from identity to the block number and index of the task.180		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;181182		/// Storage version of the pallet.183		///184		/// New networks start with last version.185		StorageVersion build(|_| Releases::V2): Releases;186	}187}188189decl_event!(190	pub enum Event<T> where <T as system::Config>::BlockNumber {191		/// Scheduled some task. \[when, index\]192		Scheduled(BlockNumber, u32),193		/// Canceled some task. \[when, index\]194		Canceled(BlockNumber, u32),195		/// Dispatched some task. \[task, id, result\]196		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),197	}198);199200decl_error! {201	pub enum Error for Module<T: Config> {202		/// Failed to schedule a call203		FailedToSchedule,204		/// Cannot find the scheduled call.205		NotFound,206		/// Given target block number is in the past.207		TargetBlockNumberInPast,208		/// Reschedule failed because it does not change scheduled time.209		RescheduleNoChange,210	}211}212213decl_module! {214	/// Scheduler module declaration.215	pub struct Module<T: Config> for enum Call 216	where 217		origin: <T as system::Config>::Origin218	{219		type Error = Error<T>;220		fn deposit_event() = default;221222223		/// Anonymously schedule a task.224		///225		/// # <weight>226		/// - S = Number of already scheduled calls227		/// - Base Weight: 22.29 + .126 * S µs228		/// - DB Weight:229		///     - Read: Agenda230		///     - Write: Agenda231		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls232		/// # </weight>233		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]234		fn schedule(origin,235			when: T::BlockNumber,236			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,237			priority: schedule::Priority,238			call: Box<<T as Config>::Call>,239		) 240		{241			let origin = <T as Config>::Origin::from(origin);242			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;243		}244245		/// Cancel an anonymously scheduled task.246		///247		/// # <weight>248		/// - S = Number of already scheduled calls249		/// - Base Weight: 22.15 + 2.869 * S µs250		/// - DB Weight:251		///     - Read: Agenda252		///     - Write: Agenda, Lookup253		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls254		/// # </weight>255		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]256		fn cancel(origin, when: T::BlockNumber, index: u32) {257			T::ScheduleOrigin::ensure_origin(origin.clone())?;258			let origin = <T as Config>::Origin::from(origin);259			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;260		}261262		/// Schedule a named task.263		///264		/// # <weight>265		/// - S = Number of already scheduled calls266		/// - Base Weight: 29.6 + .159 * S µs267		/// - DB Weight:268		///     - Read: Agenda, Lookup269		///     - Write: Agenda, Lookup270		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls271		/// # </weight>272		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]273		fn schedule_named(origin,274			id: Vec<u8>,275			when: T::BlockNumber,276			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,277			priority: schedule::Priority,278			call: Box<<T as Config>::Call>,279		) {280			T::ScheduleOrigin::ensure_origin(origin.clone())?;281			let origin = <T as Config>::Origin::from(origin);282			Self::do_schedule_named(283				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call284			)?;285		}286287		/// Cancel a named scheduled task.288		///289		/// # <weight>290		/// - S = Number of already scheduled calls291		/// - Base Weight: 24.91 + 2.907 * S µs292		/// - DB Weight:293		///     - Read: Agenda, Lookup294		///     - Write: Agenda, Lookup295		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls296		/// # </weight>297		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]298		fn cancel_named(origin, id: Vec<u8>) {299			T::ScheduleOrigin::ensure_origin(origin.clone())?;300			let origin = <T as Config>::Origin::from(origin);301			Self::do_cancel_named(Some(origin.caller().clone()), id)?;302		}303304		/// Anonymously schedule a task after a delay.305		///306		/// # <weight>307		/// Same as [`schedule`].308		/// # </weight>309		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]310		fn schedule_after(origin,311			after: T::BlockNumber,312			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,313			priority: schedule::Priority,314			call: Box<<T as Config>::Call>,315		) {316			T::ScheduleOrigin::ensure_origin(origin.clone())?;317			let origin = <T as Config>::Origin::from(origin);318			Self::do_schedule(319				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call320			)?;321		}322323		/// Schedule a named task after a delay.324		///325		/// # <weight>326		/// Same as [`schedule_named`].327		/// # </weight>328		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]329		fn schedule_named_after(origin,330			id: Vec<u8>,331			after: T::BlockNumber,332			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,333			priority: schedule::Priority,334			call: Box<<T as Config>::Call>,335		) {336			T::ScheduleOrigin::ensure_origin(origin.clone())?;337			let origin = <T as Config>::Origin::from(origin);338			Self::do_schedule_named(339				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call340			)?;341		}342343		/// Execute the scheduled calls344		///345		/// # <weight>346		/// - S = Number of already scheduled calls347		/// - N = Named scheduled calls348		/// - P = Periodic Calls349		/// - Base Weight: 9.243 + 23.45 * S µs350		/// - DB Weight:351		///     - Read: Agenda + Lookup * N + Agenda(Future) * P352		///     - Write: Agenda + Lookup * N  + Agenda(future) * P353		/// # </weight>354		fn on_initialize(now: T::BlockNumber) -> Weight {355			let limit = T::MaximumWeight::get();356			let mut queued = Agenda::<T>::take(now).into_iter()357				.enumerate()358				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))359				.collect::<Vec<_>>();360			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {361				log::warn!(362					target: "runtime::scheduler",363					"Warning: This block has more items queued in Scheduler than \364					expected from the runtime configuration. An update might be needed."365				);366			}367			queued.sort_by_key(|(_, s)| s.priority);368			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)369			let mut total_weight: Weight = 0;370			queued.into_iter()371				.enumerate()372				.scan(base_weight, |cumulative_weight, (order, (index, s))| {373					*cumulative_weight = cumulative_weight374						.saturating_add(s.call.get_dispatch_info().weight);375376					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(377						s.origin.clone()378					).into();379380					if ensure_signed(origin).is_ok() {381						 // AccountData for inner call origin accountdata.382						*cumulative_weight = cumulative_weight383							.saturating_add(T::DbWeight::get().reads_writes(1, 1));384					}385386					if s.maybe_id.is_some() {387						// Remove/Modify Lookup388						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));389					}390					if s.maybe_periodic.is_some() {391						// Read/Write Agenda for future block392						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));393					}394395					Some((order, index, *cumulative_weight, s))396				})397				.filter_map(|(order, index, cumulative_weight, mut s)| {398					// We allow a scheduled call if any is true:399					// - It's priority is `HARD_DEADLINE`400					// - It does not push the weight past the limit.401					// - It is the first item in the schedule402					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {403404						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(405							s.origin.clone()406						).into();407						let sender = ensure_signed(origin).unwrap_or(T::AccountId::default());408						let who_will_pay = T::Sponsoring::resolve(&sender, &s.call.clone()).unwrap_or(409							sender);410						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));411						let r = s.call.clone().dispatch(sponsor.into());412						let maybe_id = s.maybe_id.clone();413						if let &Some((period, count)) = &s.maybe_periodic {414							if count > 1 {415								s.maybe_periodic = Some((period, count - 1));416							} else {417								s.maybe_periodic = None;418							}419							let next = now + period;420							// If scheduled is named, place it's information in `Lookup`421							if let Some(ref id) = s.maybe_id {422								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);423								Lookup::<T>::insert(id, (next, next_index as u32));424							}425							Agenda::<T>::append(next, Some(s));426						} else {427							if let Some(ref id) = s.maybe_id {428								Lookup::<T>::remove(id);429							}430						}431						Self::deposit_event(RawEvent::Dispatched(432							(now, index),433							maybe_id,434							r.map(|_| ()).map_err(|e| e.error)435						));436						total_weight = cumulative_weight;437						None438					} else {439						Some(Some(s))440					}441				})442				.for_each(|unused| {443					let next = now + One::one();444					Agenda::<T>::append(next, unused);445				});446447			total_weight448		}449	}450}451452impl<T: Config> Module<T> {453	/// Migrate storage format from V1 to V2.454	/// Return true if migration is performed.455	pub fn migrate_v1_to_t2() -> bool {456		if StorageVersion::get() == Releases::V1 {457			StorageVersion::put(Releases::V2);458459			Agenda::<T>::translate::<460				Vec<Option<ScheduledV1<<T as Config>::Call, T::BlockNumber>>>, _461			>(|_, agenda| Some(462				agenda463					.into_iter()464					.map(|schedule| schedule.map(|schedule| ScheduledV2 {465						maybe_id: schedule.maybe_id,466						priority: schedule.priority,467						call: schedule.call,468						maybe_periodic: schedule.maybe_periodic,469						origin: system::RawOrigin::Root.into(),470						_phantom: Default::default(),471					}))472					.collect::<Vec<_>>()473			));474475			true476		} else {477			false478		}479	}480481	/// Helper to migrate scheduler when the pallet origin type has changed.482	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {483		Agenda::<T>::translate::<484			Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, OldOrigin, T::AccountId>>>, _485		>(|_, agenda| Some(486			agenda487				.into_iter()488				.map(|schedule| schedule.map(|schedule| Scheduled {489					maybe_id: schedule.maybe_id,490					priority: schedule.priority,491					call: schedule.call,492					maybe_periodic: schedule.maybe_periodic,493					origin: schedule.origin.into(),494					_phantom: Default::default(),495				}))496				.collect::<Vec<_>>()497		));498	}499500	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {501		let now = frame_system::Pallet::<T>::block_number();502503		let when = match when {504			DispatchTime::At(x) => x,505			// The current block has already completed it's scheduled tasks, so506			// Schedule the task at lest one block after this current block.507			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one())508		};509510		if when <= now {511			return Err(Error::<T>::TargetBlockNumberInPast.into())512		}513514		Ok(when)515	}516517	fn do_schedule(518		when: DispatchTime<T::BlockNumber>,519		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,520		priority: schedule::Priority,521		origin: T::PalletsOrigin,522		call: <T as Config>::Call523	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {524		let when = Self::resolve_time(when)?;525526		// sanitize maybe_periodic527		let maybe_periodic = maybe_periodic528			.filter(|p| p.1 > 1 && !p.0.is_zero())529			// Remove one from the number of repetitions since we will schedule one now.530			.map(|(p, c)| (p, c - 1));531		let s = Some(Scheduled {532			maybe_id: None, priority, call, maybe_periodic, origin, _phantom: PhantomData::<T::AccountId>::default(),533		});534		Agenda::<T>::append(when, s);535		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;536		if index > T::MaxScheduledPerBlock::get() {537			log::warn!(538				target: "runtime::scheduler",539				"Warning: There are more items queued in the Scheduler than \540				expected from the runtime configuration. An update might be needed.",541			);542		}543		Self::deposit_event(RawEvent::Scheduled(when, index));544545		Ok((when, index))546	}547548	fn do_cancel(549		origin: Option<T::PalletsOrigin>,550		(when, index): TaskAddress<T::BlockNumber>551	) -> Result<(), DispatchError> {552		let scheduled = Agenda::<T>::try_mutate(553			when,554			|agenda| {555				agenda.get_mut(index as usize)556					.map_or(Ok(None), |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {557						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {558							if *o != s.origin {559								return Err(BadOrigin.into());560							}561						};562						Ok(s.take())563					})564			},565		)?;566		if let Some(s) = scheduled {567			if let Some(id) = s.maybe_id {568				Lookup::<T>::remove(id);569			}570			Self::deposit_event(RawEvent::Canceled(when, index));571			Ok(())572		} else {573			Err(Error::<T>::NotFound)?574		}575	}576577	fn do_reschedule(578		(when, index): TaskAddress<T::BlockNumber>,579		new_time: DispatchTime<T::BlockNumber>,580	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {581		let new_time = Self::resolve_time(new_time)?;582583		if new_time == when {584			return Err(Error::<T>::RescheduleNoChange.into());585		}586587		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {588			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;589			let task = task.take().ok_or(Error::<T>::NotFound)?;590			Agenda::<T>::append(new_time, Some(task));591			Ok(())592		})?;593594		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;595		Self::deposit_event(RawEvent::Canceled(when, index));596		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));597598		Ok((new_time, new_index))599	}600601	fn do_schedule_named(602		id: Vec<u8>,603		when: DispatchTime<T::BlockNumber>,604		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,605		priority: schedule::Priority,606		origin: T::PalletsOrigin,607		call: <T as Config>::Call,608	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {609		// ensure id it is unique610		if Lookup::<T>::contains_key(&id) {611			return Err(Error::<T>::FailedToSchedule)?612		}613614		let when = Self::resolve_time(when)?;615616		// sanitize maybe_periodic617		let maybe_periodic = maybe_periodic618			.filter(|p| p.1 > 1 && !p.0.is_zero())619			// Remove one from the number of repetitions since we will schedule one now.620			.map(|(p, c)| (p, c - 1));621622		let s = Scheduled {623			maybe_id: Some(id.clone()), priority, call, maybe_periodic, origin, _phantom: Default::default()624		};625		Agenda::<T>::append(when, Some(s));626		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;627		if index > T::MaxScheduledPerBlock::get() {628			log::warn!(629				target: "runtime::scheduler",630				"Warning: There are more items queued in the Scheduler than \631				expected from the runtime configuration. An update might be needed.",632			);633		}634		let address = (when, index);635		Lookup::<T>::insert(&id, &address);636		Self::deposit_event(RawEvent::Scheduled(when, index));637638		Ok(address)639	}640641	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {642		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {643			if let Some((when, index)) = lookup.take() {644				let i = index as usize;645				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {646					if let Some(s) = agenda.get_mut(i) {647						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {648							if *o != s.origin {649								return Err(BadOrigin.into());650							}651						}652						*s = None;653					}654					Ok(())655				})?;656				Self::deposit_event(RawEvent::Canceled(when, index));657				Ok(())658			} else {659				Err(Error::<T>::NotFound)?660			}661		})662	}663664	fn do_reschedule_named(665		id: Vec<u8>,666		new_time: DispatchTime<T::BlockNumber>,667	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {668		let new_time = Self::resolve_time(new_time)?;669670		Lookup::<T>::try_mutate_exists(id, |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {671			let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;672673			if new_time == when {674				return Err(Error::<T>::RescheduleNoChange.into());675			}676677			Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {678				let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;679				let task = task.take().ok_or(Error::<T>::NotFound)?;680				Agenda::<T>::append(new_time, Some(task));681682				Ok(())683			})?;684685			let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;686			Self::deposit_event(RawEvent::Canceled(when, index));687			Self::deposit_event(RawEvent::Scheduled(new_time, new_index));688689			*lookup = Some((new_time, new_index));690691			Ok((new_time, new_index))692		})693	}694}695696impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin> for Module<T> {697	type Address = TaskAddress<T::BlockNumber>;698699	fn schedule(700		when: DispatchTime<T::BlockNumber>,701		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,702		priority: schedule::Priority,703		origin: T::PalletsOrigin,704		call: <T as Config>::Call705	) -> Result<Self::Address, DispatchError> {706		Self::do_schedule(when, maybe_periodic, priority, origin, call)707	}708709	fn cancel((when, index): Self::Address) -> Result<(), ()> {710		Self::do_cancel(None, (when, index)).map_err(|_| ())711	}712713	fn reschedule(714		address: Self::Address,715		when: DispatchTime<T::BlockNumber>,716	) -> Result<Self::Address, DispatchError> {717		Self::do_reschedule(address, when)718	}719720	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {721		Agenda::<T>::get(when).get(index as usize).ok_or(()).map(|_| when)722	}723}724725impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin> for Module<T> {726	type Address = TaskAddress<T::BlockNumber>;727728	fn schedule_named(729		id: Vec<u8>,730		when: DispatchTime<T::BlockNumber>,731		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,732		priority: schedule::Priority,733		origin: T::PalletsOrigin,734		call: <T as Config>::Call,735	) -> Result<Self::Address, ()> {736		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())737	}738739	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {740		Self::do_cancel_named(None, id).map_err(|_| ())741	}742743	fn reschedule_named(744		id: Vec<u8>,745		when: DispatchTime<T::BlockNumber>,746	) -> Result<Self::Address, DispatchError> {747		Self::do_reschedule_named(id, when)748	}749750	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {751		Lookup::<T>::get(id).and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when)).ok_or(())752	}753}754755#[cfg(test)]756mod tests {757	use super::*;758759	use frame_support::{760		parameter_types, assert_ok, ord_parameter_types,761		assert_noop, assert_err, Hashable,762		traits::{OnInitialize, OnFinalize, Filter},763		weights::constants::RocksDbWeight,764	};765	use sp_core::H256;766	use sp_runtime::{767		Perbill,768		testing::Header,769		traits::{BlakeTwo256, IdentityLookup},770	};771	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};772	use substrate_test_utils::assert_eq_uvec;773	use crate as scheduler;774775	mod logger {776		use super::*;777		use std::cell::RefCell;778779		thread_local! {780			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());781		}782		pub fn log() -> Vec<(OriginCaller, u32)> {783			LOG.with(|log| log.borrow().clone())784		}785		pub trait Config: system::Config {786			type Event: From<Event> + Into<<Self as system::Config>::Event>;787		}788		decl_event! {789			pub enum Event {790				Logged(u32, Weight),791			}792		}793		decl_module! {794			pub struct Module<T: Config> for enum Call795			where796				origin: <T as system::Config>::Origin,797				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>798			{799				fn deposit_event() = default;800801				#[weight = *weight]802				fn log(origin, i: u32, weight: Weight) {803					Self::deposit_event(Event::Logged(i, weight));804					LOG.with(|log| {805						log.borrow_mut().push((origin.caller().clone(), i));806					})807				}808809				#[weight = *weight]810				fn log_without_filter(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				}816			}817		}818	}819820	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;821	type Block = frame_system::mocking::MockBlock<Test>;822823	frame_support::construct_runtime!(824		pub enum Test where825			Block = Block,826			NodeBlock = Block,827			UncheckedExtrinsic = UncheckedExtrinsic,828		{829			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},830			Logger: logger::{Pallet, Call, Event},831			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},832		}833	);834835	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.836	pub struct BaseFilter;837	impl Filter<Call> for BaseFilter {838		fn filter(call: &Call) -> bool {839			!matches!(call, Call::Logger(logger::Call::log(_, _)))840		}841	}842843	parameter_types! {844		pub const BlockHashCount: u64 = 250;845		pub BlockWeights: frame_system::limits::BlockWeights =846			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);847	}848	impl system::Config for Test {849		type BaseCallFilter = BaseFilter;850		type BlockWeights = ();851		type BlockLength = ();852		type DbWeight = RocksDbWeight;853		type Origin = Origin;854		type Call = Call;855		type Index = u64;856		type BlockNumber = u64;857		type Hash = H256;858		type Hashing = BlakeTwo256;859		type AccountId = u64;860		type Lookup = IdentityLookup<Self::AccountId>;861		type Header = Header;862		type Event = Event;863		type BlockHashCount = BlockHashCount;864		type Version = ();865		type PalletInfo = PalletInfo;866		type AccountData = ();867		type OnNewAccount = ();868		type OnKilledAccount = ();869		type SystemWeightInfo = ();870		type SS58Prefix = ();871		type OnSetCode = ();872	}873	impl logger::Config for Test {874		type Event = Event;875	}876	parameter_types! {877		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;878		pub const MaxScheduledPerBlock: u32 = 10;879	}880	ord_parameter_types! {881		pub const One: u64 = 1;882	}883884	impl Config for Test {885		type Event = Event;886		type Origin = Origin;887		type PalletsOrigin = OriginCaller;888		type Call = Call;889		type MaximumWeight = MaximumSchedulerWeight;890		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;891		type MaxScheduledPerBlock = MaxScheduledPerBlock;892		type WeightInfo = ();893	}894895	pub fn new_test_ext() -> sp_io::TestExternalities {896		let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();897		t.into()898	}899900	fn run_to_block(n: u64) {901		while System::block_number() < n {902			Scheduler::on_finalize(System::block_number());903			System::set_block_number(System::block_number() + 1);904			Scheduler::on_initialize(System::block_number());905		}906	}907908	fn root() -> OriginCaller {909		system::RawOrigin::Root.into()910	}911912	#[test]913	fn basic_scheduling_works() {914		new_test_ext().execute_with(|| {915			let call = Call::Logger(logger::Call::log(42, 1000));916			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));917			assert_ok!(Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call));918			run_to_block(3);919			assert!(logger::log().is_empty());920			run_to_block(4);921			assert_eq!(logger::log(), vec![(root(), 42u32)]);922			run_to_block(100);923			assert_eq!(logger::log(), vec![(root(), 42u32)]);924		});925	}926927	#[test]928	fn schedule_after_works() {929		new_test_ext().execute_with(|| {930			run_to_block(2);931			let call = Call::Logger(logger::Call::log(42, 1000));932			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));933			// This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6934			assert_ok!(Scheduler::do_schedule(DispatchTime::After(3), None, 127, root(), call));935			run_to_block(5);936			assert!(logger::log().is_empty());937			run_to_block(6);938			assert_eq!(logger::log(), vec![(root(), 42u32)]);939			run_to_block(100);940			assert_eq!(logger::log(), vec![(root(), 42u32)]);941		});942	}943944	#[test]945	fn schedule_after_zero_works() {946		new_test_ext().execute_with(|| {947			run_to_block(2);948			let call = Call::Logger(logger::Call::log(42, 1000));949			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));950			assert_ok!(Scheduler::do_schedule(DispatchTime::After(0), None, 127, root(), call));951			// Will trigger on the next block.952			run_to_block(3);953			assert_eq!(logger::log(), vec![(root(), 42u32)]);954			run_to_block(100);955			assert_eq!(logger::log(), vec![(root(), 42u32)]);956		});957	}958959	#[test]960	fn periodic_scheduling_works() {961		new_test_ext().execute_with(|| {962			// at #4, every 3 blocks, 3 times.963			assert_ok!(Scheduler::do_schedule(964				DispatchTime::At(4), Some((3, 3)), 127, root(), Call::Logger(logger::Call::log(42, 1000))965			));966			run_to_block(3);967			assert!(logger::log().is_empty());968			run_to_block(4);969			assert_eq!(logger::log(), vec![(root(), 42u32)]);970			run_to_block(6);971			assert_eq!(logger::log(), vec![(root(), 42u32)]);972			run_to_block(7);973			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);974			run_to_block(9);975			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);976			run_to_block(10);977			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);978			run_to_block(100);979			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);980		});981	}982983	#[test]984	fn reschedule_works() {985		new_test_ext().execute_with(|| {986			let call = Call::Logger(logger::Call::log(42, 1000));987			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));988			assert_eq!(Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call).unwrap(), (4, 0));989990			run_to_block(3);991			assert!(logger::log().is_empty());992993			assert_eq!(Scheduler::do_reschedule((4, 0), DispatchTime::At(6)).unwrap(), (6, 0));994995			assert_noop!(Scheduler::do_reschedule((6, 0), DispatchTime::At(6)), Error::<Test>::RescheduleNoChange);996997			run_to_block(4);998			assert!(logger::log().is_empty());9991000			run_to_block(6);1001			assert_eq!(logger::log(), vec![(root(), 42u32)]);10021003			run_to_block(100);1004			assert_eq!(logger::log(), vec![(root(), 42u32)]);1005		});1006	}10071008	#[test]1009	fn reschedule_named_works() {1010		new_test_ext().execute_with(|| {1011			let call = Call::Logger(logger::Call::log(42, 1000));1012			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));1013			assert_eq!(Scheduler::do_schedule_named(1014				1u32.encode(), DispatchTime::At(4), None, 127, root(), call1015			).unwrap(), (4, 0));10161017			run_to_block(3);1018			assert!(logger::log().is_empty());10191020			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(), (6, 0));10211022			assert_noop!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)), Error::<Test>::RescheduleNoChange);10231024			run_to_block(4);1025			assert!(logger::log().is_empty());10261027			run_to_block(6);1028			assert_eq!(logger::log(), vec![(root(), 42u32)]);10291030			run_to_block(100);1031			assert_eq!(logger::log(), vec![(root(), 42u32)]);1032		});1033	}10341035	#[test]1036	fn reschedule_named_perodic_works() {1037		new_test_ext().execute_with(|| {1038			let call = Call::Logger(logger::Call::log(42, 1000));1039			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));1040			assert_eq!(Scheduler::do_schedule_named(1041				1u32.encode(), DispatchTime::At(4), Some((3, 3)), 127, root(), call1042			).unwrap(), (4, 0));10431044			run_to_block(3);1045			assert!(logger::log().is_empty());10461047			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(5)).unwrap(), (5, 0));1048			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(), (6, 0));10491050			run_to_block(5);1051			assert!(logger::log().is_empty());10521053			run_to_block(6);1054			assert_eq!(logger::log(), vec![(root(), 42u32)]);10551056			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(10)).unwrap(), (10, 0));10571058			run_to_block(9);1059			assert_eq!(logger::log(), vec![(root(), 42u32)]);10601061			run_to_block(10);1062			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);10631064			run_to_block(13);1065			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);10661067			run_to_block(100);1068			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);1069		});1070	}10711072	#[test]1073	fn cancel_named_scheduling_works_with_normal_cancel() {1074		new_test_ext().execute_with(|| {1075			// at #4.1076			Scheduler::do_schedule_named(1077				1u32.encode(), DispatchTime::At(4), None, 127, root(), Call::Logger(logger::Call::log(69, 1000))1078			).unwrap();1079			let i = Scheduler::do_schedule(1080				DispatchTime::At(4), None, 127, root(), Call::Logger(logger::Call::log(42, 1000))1081			).unwrap();1082			run_to_block(3);1083			assert!(logger::log().is_empty());1084			assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));1085			assert_ok!(Scheduler::do_cancel(None, i));1086			run_to_block(100);1087			assert!(logger::log().is_empty());1088		});1089	}10901091	#[test]1092	fn cancel_named_periodic_scheduling_works() {1093		new_test_ext().execute_with(|| {1094			// at #4, every 3 blocks, 3 times.1095			Scheduler::do_schedule_named(1096				1u32.encode(),1097				DispatchTime::At(4),1098				Some((3, 3)),1099				127,1100				root(),1101				Call::Logger(logger::Call::log(42, 1000))1102			).unwrap();1103			// same id results in error.1104			assert!(Scheduler::do_schedule_named(1105				1u32.encode(),1106				DispatchTime::At(4),1107				None,1108				127,1109				root(),1110				Call::Logger(logger::Call::log(69, 1000))1111			).is_err());1112			// different id is ok.1113			Scheduler::do_schedule_named(1114				2u32.encode(), DispatchTime::At(8), None, 127, root(), Call::Logger(logger::Call::log(69, 1000))1115			).unwrap();1116			run_to_block(3);1117			assert!(logger::log().is_empty());1118			run_to_block(4);1119			assert_eq!(logger::log(), vec![(root(), 42u32)]);1120			run_to_block(6);1121			assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));1122			run_to_block(100);1123			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);1124		});1125	}11261127	#[test]1128	fn scheduler_respects_weight_limits() {1129		new_test_ext().execute_with(|| {1130			assert_ok!(Scheduler::do_schedule(1131				DispatchTime::At(4),1132				None,1133				127,1134				root(),1135				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))1136			));1137			assert_ok!(Scheduler::do_schedule(1138				DispatchTime::At(4),1139				None,1140				127,1141				root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1142			));1143			// 69 and 42 do not fit together1144			run_to_block(4);1145			assert_eq!(logger::log(), vec![(root(), 42u32)]);1146			run_to_block(5);1147			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);1148		});1149	}11501151	#[test]1152	fn scheduler_respects_hard_deadlines_more() {1153		new_test_ext().execute_with(|| {1154			assert_ok!(Scheduler::do_schedule(1155				DispatchTime::At(4),1156				None,1157				0,1158				root(),1159				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))1160			));1161			assert_ok!(Scheduler::do_schedule(1162				DispatchTime::At(4),1163				None,1164				0,1165				root(),1166				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1167			));1168			// With base weights, 69 and 42 should not fit together, but do because of hard deadlines1169			run_to_block(4);1170			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);1171		});1172	}11731174	#[test]1175	fn scheduler_respects_priority_ordering() {1176		new_test_ext().execute_with(|| {1177			assert_ok!(Scheduler::do_schedule(1178				DispatchTime::At(4),1179				None,1180				1,1181				root(),1182				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))1183			));1184			assert_ok!(Scheduler::do_schedule(1185				DispatchTime::At(4),1186				None,1187				0,1188				root(),1189				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1190			));1191			run_to_block(4);1192			assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);1193		});1194	}11951196	#[test]1197	fn scheduler_respects_priority_ordering_with_soft_deadlines() {1198		new_test_ext().execute_with(|| {1199			assert_ok!(Scheduler::do_schedule(1200				DispatchTime::At(4),1201				None,1202				255,1203				root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))1204			));1205			assert_ok!(Scheduler::do_schedule(1206				DispatchTime::At(4),1207				None,1208				127,1209				root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1210			));1211			assert_ok!(Scheduler::do_schedule(1212				DispatchTime::At(4),1213				None,1214				126,1215				root(), Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))1216			));12171218			// 2600 does not fit with 69 or 42, but has higher priority, so will go through1219			run_to_block(4);1220			assert_eq!(logger::log(), vec![(root(), 2600u32)]);1221			// 69 and 42 fit together1222			run_to_block(5);1223			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);1224		});1225	}12261227	#[test]1228	fn on_initialize_weight_is_correct() {1229		new_test_ext().execute_with(|| {1230			let base_weight: Weight = <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 2);1231			let base_multiplier = 0;1232			let named_multiplier = <Test as frame_system::Config>::DbWeight::get().writes(1);1233			let periodic_multiplier = <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 1);12341235			// Named1236			assert_ok!(1237				Scheduler::do_schedule_named(1238					1u32.encode(), DispatchTime::At(1), None, 255, root(),1239					Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3))1240				)1241			);1242			// Anon Periodic1243			assert_ok!(Scheduler::do_schedule(1244				DispatchTime::At(1),1245				Some((1000, 3)),1246				128,1247				root(),1248				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))1249			));1250			// Anon1251			assert_ok!(Scheduler::do_schedule(1252				DispatchTime::At(1),1253				None,1254				127,1255				root(),1256				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1257			));1258			// Named Periodic1259			assert_ok!(Scheduler::do_schedule_named(1260				2u32.encode(), DispatchTime::At(1), Some((1000, 3)), 126, root(),1261				Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2)))1262			);12631264			// Will include the named periodic only1265			let actual_weight = Scheduler::on_initialize(1);1266			let call_weight = MaximumSchedulerWeight::get() / 2;1267			assert_eq!(1268				actual_weight, call_weight + base_weight + base_multiplier + named_multiplier + periodic_multiplier1269			);1270			assert_eq!(logger::log(), vec![(root(), 2600u32)]);12711272			// Will include anon and anon periodic1273			let actual_weight = Scheduler::on_initialize(2);1274			let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3;1275			assert_eq!(actual_weight, call_weight + base_weight + base_multiplier * 2 + periodic_multiplier);1276			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);12771278			// Will include named only1279			let actual_weight = Scheduler::on_initialize(3);1280			let call_weight = MaximumSchedulerWeight::get() / 3;1281			assert_eq!(actual_weight, call_weight + base_weight + base_multiplier + named_multiplier);1282			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32), (root(), 3u32)]);12831284			// Will contain none1285			let actual_weight = Scheduler::on_initialize(4);1286			assert_eq!(actual_weight, 0);1287		});1288	}12891290	#[test]1291	fn root_calls_works() {1292		new_test_ext().execute_with(|| {1293			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1294			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));1295			assert_ok!(Scheduler::schedule_named(Origin::root(), 1u32.encode(), 4, None, 127, call));1296			assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2));1297			run_to_block(3);1298			// Scheduled calls are in the agenda.1299			assert_eq!(Agenda::<Test>::get(4).len(), 2);1300			assert!(logger::log().is_empty());1301			assert_ok!(Scheduler::cancel_named(Origin::root(), 1u32.encode()));1302			assert_ok!(Scheduler::cancel(Origin::root(), 4, 1));1303			// Scheduled calls are made NONE, so should not effect state1304			run_to_block(100);1305			assert!(logger::log().is_empty());1306		});1307	}13081309	#[test]1310	fn fails_to_schedule_task_in_the_past() {1311		new_test_ext().execute_with(|| {1312			run_to_block(3);13131314			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1315			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));13161317			assert_err!(1318				Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call),1319				Error::<Test>::TargetBlockNumberInPast,1320			);13211322			assert_err!(1323				Scheduler::schedule(Origin::root(), 2, None, 127, call2.clone()),1324				Error::<Test>::TargetBlockNumberInPast,1325			);13261327			assert_err!(1328				Scheduler::schedule(Origin::root(), 3, None, 127, call2),1329				Error::<Test>::TargetBlockNumberInPast,1330			);1331		});1332	}13331334	#[test]1335	fn should_use_orign() {1336		new_test_ext().execute_with(|| {1337			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1338			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));1339			assert_ok!(1340				Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)1341			);1342			assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));1343			run_to_block(3);1344			// Scheduled calls are in the agenda.1345			assert_eq!(Agenda::<Test>::get(4).len(), 2);1346			assert!(logger::log().is_empty());1347			assert_ok!(Scheduler::cancel_named(system::RawOrigin::Signed(1).into(), 1u32.encode()));1348			assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));1349			// Scheduled calls are made NONE, so should not effect state1350			run_to_block(100);1351			assert!(logger::log().is_empty());1352		});1353	}13541355	#[test]1356	fn should_check_orign() {1357		new_test_ext().execute_with(|| {1358			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1359			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));1360			assert_noop!(1361				Scheduler::schedule_named(system::RawOrigin::Signed(2).into(), 1u32.encode(), 4, None, 127, call),1362				BadOrigin1363			);1364			assert_noop!(Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, 127, call2), BadOrigin);1365		});1366	}13671368	#[test]1369	fn should_check_orign_for_cancel() {1370		new_test_ext().execute_with(|| {1371			let call = Box::new(Call::Logger(logger::Call::log_without_filter(69, 1000)));1372			let call2 = Box::new(Call::Logger(logger::Call::log_without_filter(42, 1000)));1373			assert_ok!(1374				Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)1375			);1376			assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));1377			run_to_block(3);1378			// Scheduled calls are in the agenda.1379			assert_eq!(Agenda::<Test>::get(4).len(), 2);1380			assert!(logger::log().is_empty());1381			assert_noop!(Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), 1u32.encode()), BadOrigin);1382			assert_noop!(Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1), BadOrigin);1383			assert_noop!(Scheduler::cancel_named(system::RawOrigin::Root.into(), 1u32.encode()), BadOrigin);1384			assert_noop!(Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1), BadOrigin);1385			run_to_block(5);1386			assert_eq!(1387				logger::log(),1388				vec![(system::RawOrigin::Signed(1).into(), 69u32), (system::RawOrigin::Signed(1).into(), 42u32)]1389			);1390		});1391	}13921393	#[test]1394	fn migration_to_v2_works() {1395		new_test_ext().execute_with(|| {1396			for i in 0..3u64 {1397				let k = i.twox_64_concat();1398				let old = vec![1399					Some(ScheduledV1 {1400						maybe_id: None,1401						priority: i as u8 + 10,1402						call: Call::Logger(logger::Call::log(96, 100)),1403						maybe_periodic: None,1404					}),1405					None,1406					Some(ScheduledV1 {1407						maybe_id: Some(b"test".to_vec()),1408						priority: 123,1409						call: Call::Logger(logger::Call::log(69, 1000)),1410						maybe_periodic: Some((456u64, 10)),1411					}),1412				];1413				frame_support::migration::put_storage_value(1414					b"Scheduler",1415					b"Agenda",1416					&k,1417					old,1418				);1419			}14201421			assert_eq!(StorageVersion::get(), Releases::V1);14221423			assert!(Scheduler::migrate_v1_to_t2());14241425			assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![1426				(1427					0,1428					vec![1429					Some(ScheduledV2 {1430						maybe_id: None,1431						priority: 10,1432						call: Call::Logger(logger::Call::log(96, 100)),1433						maybe_periodic: None,1434						origin: root(),1435						_phantom: PhantomData::<u64>::default(),1436					}),1437					None,1438					Some(ScheduledV2 {1439						maybe_id: Some(b"test".to_vec()),1440						priority: 123,1441						call: Call::Logger(logger::Call::log(69, 1000)),1442						maybe_periodic: Some((456u64, 10)),1443						origin: root(),1444						_phantom: PhantomData::<u64>::default(),1445					}),1446				]),1447				(1448					1,1449					vec![1450						Some(ScheduledV2 {1451							maybe_id: None,1452							priority: 11,1453							call: Call::Logger(logger::Call::log(96, 100)),1454							maybe_periodic: None,1455							origin: root(),1456							_phantom: PhantomData::<u64>::default(),1457						}),1458						None,1459						Some(ScheduledV2 {1460							maybe_id: Some(b"test".to_vec()),1461							priority: 123,1462							call: Call::Logger(logger::Call::log(69, 1000)),1463							maybe_periodic: Some((456u64, 10)),1464							origin: root(),1465							_phantom: PhantomData::<u64>::default(),1466						}),1467					]1468				),1469				(1470					2,1471					vec![1472						Some(ScheduledV2 {1473							maybe_id: None,1474							priority: 12,1475							call: Call::Logger(logger::Call::log(96, 100)),1476							maybe_periodic: None,1477							origin: root(),1478							_phantom: PhantomData::<u64>::default(),1479						}),1480						None,1481						Some(ScheduledV2 {1482							maybe_id: Some(b"test".to_vec()),1483							priority: 123,1484							call: Call::Logger(logger::Call::log(69, 1000)),1485							maybe_periodic: Some((456u64, 10)),1486							origin: root(),1487							_phantom: PhantomData::<u64>::default(),1488						}),1489					]1490				)1491			]);14921493			assert_eq!(StorageVersion::get(), Releases::V2);1494		});1495	}14961497	#[test]1498	fn test_migrate_origin() {1499		new_test_ext().execute_with(|| {1500			for i in 0..3u64 {1501				let k = i.twox_64_concat();1502				let old: Vec<Option<Scheduled<_, _, u32, u64>>> = vec![1503					Some(Scheduled {1504						maybe_id: None,1505						priority: i as u8 + 10,1506						call: Call::Logger(logger::Call::log(96, 100)),1507						origin: 3u32,1508						maybe_periodic: None,1509						_phantom: Default::default(),1510					}),1511					None,1512					Some(Scheduled {1513						maybe_id: Some(b"test".to_vec()),1514						priority: 123,1515						origin: 2u32,1516						call: Call::Logger(logger::Call::log(69, 1000)),1517						maybe_periodic: Some((456u64, 10)),1518						_phantom: Default::default(),1519					}),1520				];1521				frame_support::migration::put_storage_value(1522					b"Scheduler",1523					b"Agenda",1524					&k,1525					old,1526				);1527			}15281529			impl Into<OriginCaller> for u32 {1530				fn into(self) -> OriginCaller {1531					match self {1532						3u32 => system::RawOrigin::Root.into(),1533						2u32 => system::RawOrigin::None.into(),1534						_ => unreachable!("test make no use of it"),1535					}1536				}1537			}15381539			Scheduler::migrate_origin::<u32>();15401541			assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![1542				(1543					0,1544					vec![1545					Some(ScheduledV2::<_, _, OriginCaller, u64> {1546						maybe_id: None,1547						priority: 10,1548						call: Call::Logger(logger::Call::log(96, 100)),1549						maybe_periodic: None,1550						origin: system::RawOrigin::Root.into(),1551						_phantom: PhantomData::<u64>::default(),1552					}),1553					None,1554					Some(ScheduledV2 {1555						maybe_id: Some(b"test".to_vec()),1556						priority: 123,1557						call: Call::Logger(logger::Call::log(69, 1000)),1558						maybe_periodic: Some((456u64, 10)),1559						origin: system::RawOrigin::None.into(),1560						_phantom: PhantomData::<u64>::default(),1561					}),1562				]),1563				(1564					1,1565					vec![1566						Some(ScheduledV2 {1567							maybe_id: None,1568							priority: 11,1569							call: Call::Logger(logger::Call::log(96, 100)),1570							maybe_periodic: None,1571							origin: system::RawOrigin::Root.into(),1572							_phantom: PhantomData::<u64>::default(),1573						}),1574						None,1575						Some(ScheduledV2 {1576							maybe_id: Some(b"test".to_vec()),1577							priority: 123,1578							call: Call::Logger(logger::Call::log(69, 1000)),1579							maybe_periodic: Some((456u64, 10)),1580							origin: system::RawOrigin::None.into(),1581							_phantom: PhantomData::<u64>::default(),1582						}),1583					]1584				),1585				(1586					2,1587					vec![1588						Some(ScheduledV2 {1589							maybe_id: None,1590							priority: 12,1591							call: Call::Logger(logger::Call::log(96, 100)),1592							maybe_periodic: None,1593							origin: system::RawOrigin::Root.into(),1594							_phantom: PhantomData::<u64>::default(),1595						}),1596						None,1597						Some(ScheduledV2 {1598							maybe_id: Some(b"test".to_vec()),1599							priority: 123,1600							call: Call::Logger(logger::Call::log(69, 1000)),1601							maybe_periodic: Some((456u64, 10)),1602							origin: system::RawOrigin::None.into(),1603							_phantom: PhantomData::<u64>::default(),1604						}),1605					]1606				)1607			]);1608		});1609	}1610}
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)]5354mod benchmarking;55pub mod weights;5657use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};58use codec::{Encode, Decode, Codec};59use sp_runtime::{RuntimeDebug, traits::{Zero, One, BadOrigin, Saturating}};60use frame_support::{61	decl_module, decl_storage, decl_event, decl_error, IterableStorageMap,62	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},63	traits::{Get, schedule::{self, DispatchTime}, OriginTrait, EnsureOrigin, IsType},64	weights::{GetDispatchInfo, Weight},65};66use frame_system::{self as system, ensure_signed};67pub use weights::WeightInfo;68use up_sponsorship::SponsorshipHandler;6970/// Our pallet's configuration trait. All our types and constants go in here. If the71/// pallet is dependent on specific other pallets, then their configuration traits72/// should be added to our implied traits list.73///74/// `system::Config` should always be included in our implied traits.75/// // 76pub trait Config: system::Config77{ 7879	/// The overarching event type.80	type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;8182	/// The aggregated origin which the dispatch will take.83	type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>84		+ From<Self::PalletsOrigin> + IsType<<Self as system::Config>::Origin>;8586	/// The caller origin, overarching type of all pallets origins.87	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq;8889	/// The aggregated call type.90	type Call: Parameter + Dispatchable<Origin=<Self as Config>::Origin> + GetDispatchInfo + From<system::Call<Self>>;9192	/// The maximum weight that may be scheduled per block for any dispatchables of less priority93	/// than `schedule::HARD_DEADLINE`.94	type MaximumWeight: Get<Weight>;9596	/// Required origin to schedule or cancel calls.97	type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;9899	/// The maximum number of scheduled calls in the queue for a single block.100	/// Not strictly enforced, but used for weight estimation.101	type MaxScheduledPerBlock: Get<u32>;102103	/// Sponsoring function104	type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;105106	/// Weight information for extrinsics in this pallet.107	type WeightInfo: WeightInfo;108}109110// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;111112/// Just a simple index for naming period tasks.113pub type PeriodicIndex = u32;114/// The location of a scheduled task that can be used to remove it.115pub type TaskAddress<BlockNumber> = (BlockNumber, u32);116117#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]118#[derive(Clone, RuntimeDebug, Encode, Decode)]119struct ScheduledV1<Call, BlockNumber> {120	maybe_id: Option<Vec<u8>>,121	priority: schedule::Priority,122	call: Call,123	maybe_periodic: Option<schedule::Period<BlockNumber>>,124}125126/// Information regarding an item to be executed in the future.127#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]128#[derive(Clone, RuntimeDebug, Encode, Decode)]129pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {130	/// The unique identity for this task, if there is one.131	maybe_id: Option<Vec<u8>>,132	/// This task's priority.133	priority: schedule::Priority,134	/// The call to be dispatched.135	call: Call,136	/// If the call is periodic, then this points to the information concerning that.137	maybe_periodic: Option<schedule::Period<BlockNumber>>,138	/// The origin to dispatch the call.139	origin: PalletsOrigin,140	_phantom: PhantomData<AccountId>,141}142143/// The current version of Scheduled struct.144pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> = ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;145146// A value placed in storage that represents the current version of the Scheduler storage.147// This value is used by the `on_runtime_upgrade` logic to determine whether we run148// storage migration logic.149#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]150enum Releases {151	V1,152	V2,153}154155impl Default for Releases {156	fn default() -> Self {157		Releases::V1158	}159}160161#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug)]162pub struct CallSpec {163164	module: u32,165	method: u32,166}167168decl_storage! {169	trait Store for Module<T: Config> as Scheduler {170		/// Items to be executed, indexed by the block number that they should be executed on.171		pub Agenda: map hasher(twox_64_concat) T::BlockNumber172			=> Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;173174		pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber175			=> Vec<Option<CallSpec>>;			176177		/// Lookup from identity to the block number and index of the task.178		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;179180		/// Storage version of the pallet.181		///182		/// New networks start with last version.183		StorageVersion build(|_| Releases::V2): Releases;184	}185}186187decl_event!(188	pub enum Event<T> where <T as system::Config>::BlockNumber {189		/// Scheduled some task. \[when, index\]190		Scheduled(BlockNumber, u32),191		/// Canceled some task. \[when, index\]192		Canceled(BlockNumber, u32),193		/// Dispatched some task. \[task, id, result\]194		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),195	}196);197198decl_error! {199	pub enum Error for Module<T: Config> {200		/// Failed to schedule a call201		FailedToSchedule,202		/// Cannot find the scheduled call.203		NotFound,204		/// Given target block number is in the past.205		TargetBlockNumberInPast,206		/// Reschedule failed because it does not change scheduled time.207		RescheduleNoChange,208	}209}210211decl_module! {212	/// Scheduler module declaration.213	pub struct Module<T: Config> for enum Call 214	where 215		origin: <T as system::Config>::Origin216	{217		type Error = Error<T>;218		fn deposit_event() = default;219220221		/// Anonymously schedule a task.222		///223		/// # <weight>224		/// - S = Number of already scheduled calls225		/// - Base Weight: 22.29 + .126 * S µs226		/// - DB Weight:227		///     - Read: Agenda228		///     - Write: Agenda229		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls230		/// # </weight>231		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]232		fn schedule(origin,233			when: T::BlockNumber,234			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,235			priority: schedule::Priority,236			call: Box<<T as Config>::Call>,237		) 238		{239			let origin = <T as Config>::Origin::from(origin);240			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;241		}242243		/// Cancel an anonymously scheduled task.244		///245		/// # <weight>246		/// - S = Number of already scheduled calls247		/// - Base Weight: 22.15 + 2.869 * S µs248		/// - DB Weight:249		///     - Read: Agenda250		///     - Write: Agenda, Lookup251		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls252		/// # </weight>253		#[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]254		fn cancel(origin, when: T::BlockNumber, index: u32) {255			T::ScheduleOrigin::ensure_origin(origin.clone())?;256			let origin = <T as Config>::Origin::from(origin);257			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;258		}259260		/// Schedule a named task.261		///262		/// # <weight>263		/// - S = Number of already scheduled calls264		/// - Base Weight: 29.6 + .159 * S µs265		/// - DB Weight:266		///     - Read: Agenda, Lookup267		///     - Write: Agenda, Lookup268		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls269		/// # </weight>270		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]271		fn schedule_named(origin,272			id: Vec<u8>,273			when: T::BlockNumber,274			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,275			priority: schedule::Priority,276			call: Box<<T as Config>::Call>,277		) {278			T::ScheduleOrigin::ensure_origin(origin.clone())?;279			let origin = <T as Config>::Origin::from(origin);280			Self::do_schedule_named(281				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call282			)?;283		}284285		/// Cancel a named scheduled task.286		///287		/// # <weight>288		/// - S = Number of already scheduled calls289		/// - Base Weight: 24.91 + 2.907 * S µs290		/// - DB Weight:291		///     - Read: Agenda, Lookup292		///     - Write: Agenda, Lookup293		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls294		/// # </weight>295		#[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]296		fn cancel_named(origin, id: Vec<u8>) {297			T::ScheduleOrigin::ensure_origin(origin.clone())?;298			let origin = <T as Config>::Origin::from(origin);299			Self::do_cancel_named(Some(origin.caller().clone()), id)?;300		}301302		/// Anonymously schedule a task after a delay.303		///304		/// # <weight>305		/// Same as [`schedule`].306		/// # </weight>307		#[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]308		fn schedule_after(origin,309			after: T::BlockNumber,310			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,311			priority: schedule::Priority,312			call: Box<<T as Config>::Call>,313		) {314			T::ScheduleOrigin::ensure_origin(origin.clone())?;315			let origin = <T as Config>::Origin::from(origin);316			Self::do_schedule(317				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call318			)?;319		}320321		/// Schedule a named task after a delay.322		///323		/// # <weight>324		/// Same as [`schedule_named`].325		/// # </weight>326		#[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]327		fn schedule_named_after(origin,328			id: Vec<u8>,329			after: T::BlockNumber,330			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,331			priority: schedule::Priority,332			call: Box<<T as Config>::Call>,333		) {334			T::ScheduleOrigin::ensure_origin(origin.clone())?;335			let origin = <T as Config>::Origin::from(origin);336			Self::do_schedule_named(337				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call338			)?;339		}340341		/// Execute the scheduled calls342		///343		/// # <weight>344		/// - S = Number of already scheduled calls345		/// - N = Named scheduled calls346		/// - P = Periodic Calls347		/// - Base Weight: 9.243 + 23.45 * S µs348		/// - DB Weight:349		///     - Read: Agenda + Lookup * N + Agenda(Future) * P350		///     - Write: Agenda + Lookup * N  + Agenda(future) * P351		/// # </weight>352		fn on_initialize(now: T::BlockNumber) -> Weight {353			let limit = T::MaximumWeight::get();354			let mut queued = Agenda::<T>::take(now).into_iter()355				.enumerate()356				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))357				.collect::<Vec<_>>();358			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {359				log::warn!(360					target: "runtime::scheduler",361					"Warning: This block has more items queued in Scheduler than \362					expected from the runtime configuration. An update might be needed."363				);364			}365			queued.sort_by_key(|(_, s)| s.priority);366			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)367			let mut total_weight: Weight = 0;368			queued.into_iter()369				.enumerate()370				.scan(base_weight, |cumulative_weight, (order, (index, s))| {371					*cumulative_weight = cumulative_weight372						.saturating_add(s.call.get_dispatch_info().weight);373374					let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(375						s.origin.clone()376					).into();377378					if ensure_signed(origin).is_ok() {379						 // AccountData for inner call origin accountdata.380						*cumulative_weight = cumulative_weight381							.saturating_add(T::DbWeight::get().reads_writes(1, 1));382					}383384					if s.maybe_id.is_some() {385						// Remove/Modify Lookup386						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));387					}388					if s.maybe_periodic.is_some() {389						// Read/Write Agenda for future block390						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));391					}392393					Some((order, index, *cumulative_weight, s))394				})395				.filter_map(|(order, index, cumulative_weight, mut s)| {396					// We allow a scheduled call if any is true:397					// - It's priority is `HARD_DEADLINE`398					// - It does not push the weight past the limit.399					// - It is the first item in the schedule400					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {401402						let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(403							s.origin.clone()404						).into();405						let sender = ensure_signed(origin).unwrap_or(T::AccountId::default());406						let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);407						let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));408						let r = s.call.clone().dispatch(sponsor.into());409						let maybe_id = s.maybe_id.clone();410						if let &Some((period, count)) = &s.maybe_periodic {411							if count > 1 {412								s.maybe_periodic = Some((period, count - 1));413							} else {414								s.maybe_periodic = None;415							}416							let next = now + period;417							// If scheduled is named, place it's information in `Lookup`418							if let Some(ref id) = s.maybe_id {419								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);420								Lookup::<T>::insert(id, (next, next_index as u32));421							}422							Agenda::<T>::append(next, Some(s));423						} else {424							if let Some(ref id) = s.maybe_id {425								Lookup::<T>::remove(id);426							}427						}428						Self::deposit_event(RawEvent::Dispatched(429							(now, index),430							maybe_id,431							r.map(|_| ()).map_err(|e| e.error)432						));433						total_weight = cumulative_weight;434						None435					} else {436						Some(Some(s))437					}438				})439				.for_each(|unused| {440					let next = now + One::one();441					Agenda::<T>::append(next, unused);442				});443444			total_weight445		}446	}447}448449impl<T: Config> Module<T> {450	/// Migrate storage format from V1 to V2.451	/// Return true if migration is performed.452	pub fn migrate_v1_to_t2() -> bool {453		if StorageVersion::get() == Releases::V1 {454			StorageVersion::put(Releases::V2);455456			Agenda::<T>::translate::<457				Vec<Option<ScheduledV1<<T as Config>::Call, T::BlockNumber>>>, _458			>(|_, agenda| Some(459				agenda460					.into_iter()461					.map(|schedule| schedule.map(|schedule| ScheduledV2 {462						maybe_id: schedule.maybe_id,463						priority: schedule.priority,464						call: schedule.call,465						maybe_periodic: schedule.maybe_periodic,466						origin: system::RawOrigin::Root.into(),467						_phantom: Default::default(),468					}))469					.collect::<Vec<_>>()470			));471472			true473		} else {474			false475		}476	}477478	/// Helper to migrate scheduler when the pallet origin type has changed.479	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {480		Agenda::<T>::translate::<481			Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, OldOrigin, T::AccountId>>>, _482		>(|_, agenda| Some(483			agenda484				.into_iter()485				.map(|schedule| schedule.map(|schedule| Scheduled {486					maybe_id: schedule.maybe_id,487					priority: schedule.priority,488					call: schedule.call,489					maybe_periodic: schedule.maybe_periodic,490					origin: schedule.origin.into(),491					_phantom: Default::default(),492				}))493				.collect::<Vec<_>>()494		));495	}496497	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {498		let now = frame_system::Pallet::<T>::block_number();499500		let when = match when {501			DispatchTime::At(x) => x,502			// The current block has already completed it's scheduled tasks, so503			// Schedule the task at lest one block after this current block.504			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one())505		};506507		if when <= now {508			return Err(Error::<T>::TargetBlockNumberInPast.into())509		}510511		Ok(when)512	}513514	fn do_schedule(515		when: DispatchTime<T::BlockNumber>,516		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,517		priority: schedule::Priority,518		origin: T::PalletsOrigin,519		call: <T as Config>::Call520	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {521		let when = Self::resolve_time(when)?;522523		// sanitize maybe_periodic524		let maybe_periodic = maybe_periodic525			.filter(|p| p.1 > 1 && !p.0.is_zero())526			// Remove one from the number of repetitions since we will schedule one now.527			.map(|(p, c)| (p, c - 1));528		let s = Some(Scheduled {529			maybe_id: None, priority, call, maybe_periodic, origin, _phantom: PhantomData::<T::AccountId>::default(),530		});531		Agenda::<T>::append(when, s);532		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;533		if index > T::MaxScheduledPerBlock::get() {534			log::warn!(535				target: "runtime::scheduler",536				"Warning: There are more items queued in the Scheduler than \537				expected from the runtime configuration. An update might be needed.",538			);539		}540		Self::deposit_event(RawEvent::Scheduled(when, index));541542		Ok((when, index))543	}544545	fn do_cancel(546		origin: Option<T::PalletsOrigin>,547		(when, index): TaskAddress<T::BlockNumber>548	) -> Result<(), DispatchError> {549		let scheduled = Agenda::<T>::try_mutate(550			when,551			|agenda| {552				agenda.get_mut(index as usize)553					.map_or(Ok(None), |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {554						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {555							if *o != s.origin {556								return Err(BadOrigin.into());557							}558						};559						Ok(s.take())560					})561			},562		)?;563		if let Some(s) = scheduled {564			if let Some(id) = s.maybe_id {565				Lookup::<T>::remove(id);566			}567			Self::deposit_event(RawEvent::Canceled(when, index));568			Ok(())569		} else {570			Err(Error::<T>::NotFound)?571		}572	}573574	fn do_reschedule(575		(when, index): TaskAddress<T::BlockNumber>,576		new_time: DispatchTime<T::BlockNumber>,577	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {578		let new_time = Self::resolve_time(new_time)?;579580		if new_time == when {581			return Err(Error::<T>::RescheduleNoChange.into());582		}583584		Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {585			let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;586			let task = task.take().ok_or(Error::<T>::NotFound)?;587			Agenda::<T>::append(new_time, Some(task));588			Ok(())589		})?;590591		let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;592		Self::deposit_event(RawEvent::Canceled(when, index));593		Self::deposit_event(RawEvent::Scheduled(new_time, new_index));594595		Ok((new_time, new_index))596	}597598	fn do_schedule_named(599		id: Vec<u8>,600		when: DispatchTime<T::BlockNumber>,601		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,602		priority: schedule::Priority,603		origin: T::PalletsOrigin,604		call: <T as Config>::Call,605	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {606		// ensure id it is unique607		if Lookup::<T>::contains_key(&id) {608			return Err(Error::<T>::FailedToSchedule)?609		}610611		let when = Self::resolve_time(when)?;612613		// sanitize maybe_periodic614		let maybe_periodic = maybe_periodic615			.filter(|p| p.1 > 1 && !p.0.is_zero())616			// Remove one from the number of repetitions since we will schedule one now.617			.map(|(p, c)| (p, c - 1));618619		let s = Scheduled {620			maybe_id: Some(id.clone()), priority, call, maybe_periodic, origin, _phantom: Default::default()621		};622		Agenda::<T>::append(when, Some(s));623		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;624		if index > T::MaxScheduledPerBlock::get() {625			log::warn!(626				target: "runtime::scheduler",627				"Warning: There are more items queued in the Scheduler than \628				expected from the runtime configuration. An update might be needed.",629			);630		}631		let address = (when, index);632		Lookup::<T>::insert(&id, &address);633		Self::deposit_event(RawEvent::Scheduled(when, index));634635		Ok(address)636	}637638	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {639		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {640			if let Some((when, index)) = lookup.take() {641				let i = index as usize;642				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {643					if let Some(s) = agenda.get_mut(i) {644						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {645							if *o != s.origin {646								return Err(BadOrigin.into());647							}648						}649						*s = None;650					}651					Ok(())652				})?;653				Self::deposit_event(RawEvent::Canceled(when, index));654				Ok(())655			} else {656				Err(Error::<T>::NotFound)?657			}658		})659	}660661	fn do_reschedule_named(662		id: Vec<u8>,663		new_time: DispatchTime<T::BlockNumber>,664	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {665		let new_time = Self::resolve_time(new_time)?;666667		Lookup::<T>::try_mutate_exists(id, |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {668			let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;669670			if new_time == when {671				return Err(Error::<T>::RescheduleNoChange.into());672			}673674			Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {675				let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;676				let task = task.take().ok_or(Error::<T>::NotFound)?;677				Agenda::<T>::append(new_time, Some(task));678679				Ok(())680			})?;681682			let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;683			Self::deposit_event(RawEvent::Canceled(when, index));684			Self::deposit_event(RawEvent::Scheduled(new_time, new_index));685686			*lookup = Some((new_time, new_index));687688			Ok((new_time, new_index))689		})690	}691}692693impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin> for Module<T> {694	type Address = TaskAddress<T::BlockNumber>;695696	fn schedule(697		when: DispatchTime<T::BlockNumber>,698		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,699		priority: schedule::Priority,700		origin: T::PalletsOrigin,701		call: <T as Config>::Call702	) -> Result<Self::Address, DispatchError> {703		Self::do_schedule(when, maybe_periodic, priority, origin, call)704	}705706	fn cancel((when, index): Self::Address) -> Result<(), ()> {707		Self::do_cancel(None, (when, index)).map_err(|_| ())708	}709710	fn reschedule(711		address: Self::Address,712		when: DispatchTime<T::BlockNumber>,713	) -> Result<Self::Address, DispatchError> {714		Self::do_reschedule(address, when)715	}716717	fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {718		Agenda::<T>::get(when).get(index as usize).ok_or(()).map(|_| when)719	}720}721722impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin> for Module<T> {723	type Address = TaskAddress<T::BlockNumber>;724725	fn schedule_named(726		id: Vec<u8>,727		when: DispatchTime<T::BlockNumber>,728		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,729		priority: schedule::Priority,730		origin: T::PalletsOrigin,731		call: <T as Config>::Call,732	) -> Result<Self::Address, ()> {733		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())734	}735736	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {737		Self::do_cancel_named(None, id).map_err(|_| ())738	}739740	fn reschedule_named(741		id: Vec<u8>,742		when: DispatchTime<T::BlockNumber>,743	) -> Result<Self::Address, DispatchError> {744		Self::do_reschedule_named(id, when)745	}746747	fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {748		Lookup::<T>::get(id).and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when)).ok_or(())749	}750}751752#[cfg(test)]753mod tests {754	use super::*;755756	use frame_support::{757		parameter_types, assert_ok, ord_parameter_types,758		assert_noop, assert_err, Hashable,759		traits::{OnInitialize, OnFinalize, Filter},760		weights::constants::RocksDbWeight,761	};762	use sp_core::H256;763	use sp_runtime::{764		Perbill,765		testing::Header,766		traits::{BlakeTwo256, IdentityLookup},767	};768	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};769	use substrate_test_utils::assert_eq_uvec;770	use crate as scheduler;771772	mod logger {773		use super::*;774		use std::cell::RefCell;775776		thread_local! {777			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());778		}779		pub fn log() -> Vec<(OriginCaller, u32)> {780			LOG.with(|log| log.borrow().clone())781		}782		pub trait Config: system::Config {783			type Event: From<Event> + Into<<Self as system::Config>::Event>;784		}785		decl_event! {786			pub enum Event {787				Logged(u32, Weight),788			}789		}790		decl_module! {791			pub struct Module<T: Config> for enum Call792			where793				origin: <T as system::Config>::Origin,794				<T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>795			{796				fn deposit_event() = default;797798				#[weight = *weight]799				fn log(origin, i: u32, weight: Weight) {800					Self::deposit_event(Event::Logged(i, weight));801					LOG.with(|log| {802						log.borrow_mut().push((origin.caller().clone(), i));803					})804				}805806				#[weight = *weight]807				fn log_without_filter(origin, i: u32, weight: Weight) {808					Self::deposit_event(Event::Logged(i, weight));809					LOG.with(|log| {810						log.borrow_mut().push((origin.caller().clone(), i));811					})812				}813			}814		}815	}816817	type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;818	type Block = frame_system::mocking::MockBlock<Test>;819820	frame_support::construct_runtime!(821		pub enum Test where822			Block = Block,823			NodeBlock = Block,824			UncheckedExtrinsic = UncheckedExtrinsic,825		{826			System: frame_system::{Pallet, Call, Config, Storage, Event<T>},827			Logger: logger::{Pallet, Call, Event},828			Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},829		}830	);831832	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.833	pub struct BaseFilter;834	impl Filter<Call> for BaseFilter {835		fn filter(call: &Call) -> bool {836			!matches!(call, Call::Logger(logger::Call::log(_, _)))837		}838	}839840	parameter_types! {841		pub const BlockHashCount: u64 = 250;842		pub BlockWeights: frame_system::limits::BlockWeights =843			frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);844	}845	impl system::Config for Test {846		type BaseCallFilter = BaseFilter;847		type BlockWeights = ();848		type BlockLength = ();849		type DbWeight = RocksDbWeight;850		type Origin = Origin;851		type Call = Call;852		type Index = u64;853		type BlockNumber = u64;854		type Hash = H256;855		type Hashing = BlakeTwo256;856		type AccountId = u64;857		type Lookup = IdentityLookup<Self::AccountId>;858		type Header = Header;859		type Event = Event;860		type BlockHashCount = BlockHashCount;861		type Version = ();862		type PalletInfo = PalletInfo;863		type AccountData = ();864		type OnNewAccount = ();865		type OnKilledAccount = ();866		type SystemWeightInfo = ();867		type SS58Prefix = ();868		type OnSetCode = ();869	}870	impl logger::Config for Test {871		type Event = Event;872	}873	parameter_types! {874		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;875		pub const MaxScheduledPerBlock: u32 = 10;876	}877	ord_parameter_types! {878		pub const One: u64 = 1;879	}880881	impl Config for Test {882		type Event = Event;883		type Origin = Origin;884		type PalletsOrigin = OriginCaller;885		type Call = Call;886		type MaximumWeight = MaximumSchedulerWeight;887		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;888		type MaxScheduledPerBlock = MaxScheduledPerBlock;889		type WeightInfo = ();890	}891892	pub fn new_test_ext() -> sp_io::TestExternalities {893		let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();894		t.into()895	}896897	fn run_to_block(n: u64) {898		while System::block_number() < n {899			Scheduler::on_finalize(System::block_number());900			System::set_block_number(System::block_number() + 1);901			Scheduler::on_initialize(System::block_number());902		}903	}904905	fn root() -> OriginCaller {906		system::RawOrigin::Root.into()907	}908909	#[test]910	fn basic_scheduling_works() {911		new_test_ext().execute_with(|| {912			let call = Call::Logger(logger::Call::log(42, 1000));913			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));914			assert_ok!(Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call));915			run_to_block(3);916			assert!(logger::log().is_empty());917			run_to_block(4);918			assert_eq!(logger::log(), vec![(root(), 42u32)]);919			run_to_block(100);920			assert_eq!(logger::log(), vec![(root(), 42u32)]);921		});922	}923924	#[test]925	fn schedule_after_works() {926		new_test_ext().execute_with(|| {927			run_to_block(2);928			let call = Call::Logger(logger::Call::log(42, 1000));929			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));930			// This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6931			assert_ok!(Scheduler::do_schedule(DispatchTime::After(3), None, 127, root(), call));932			run_to_block(5);933			assert!(logger::log().is_empty());934			run_to_block(6);935			assert_eq!(logger::log(), vec![(root(), 42u32)]);936			run_to_block(100);937			assert_eq!(logger::log(), vec![(root(), 42u32)]);938		});939	}940941	#[test]942	fn schedule_after_zero_works() {943		new_test_ext().execute_with(|| {944			run_to_block(2);945			let call = Call::Logger(logger::Call::log(42, 1000));946			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));947			assert_ok!(Scheduler::do_schedule(DispatchTime::After(0), None, 127, root(), call));948			// Will trigger on the next block.949			run_to_block(3);950			assert_eq!(logger::log(), vec![(root(), 42u32)]);951			run_to_block(100);952			assert_eq!(logger::log(), vec![(root(), 42u32)]);953		});954	}955956	#[test]957	fn periodic_scheduling_works() {958		new_test_ext().execute_with(|| {959			// at #4, every 3 blocks, 3 times.960			assert_ok!(Scheduler::do_schedule(961				DispatchTime::At(4), Some((3, 3)), 127, root(), Call::Logger(logger::Call::log(42, 1000))962			));963			run_to_block(3);964			assert!(logger::log().is_empty());965			run_to_block(4);966			assert_eq!(logger::log(), vec![(root(), 42u32)]);967			run_to_block(6);968			assert_eq!(logger::log(), vec![(root(), 42u32)]);969			run_to_block(7);970			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);971			run_to_block(9);972			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);973			run_to_block(10);974			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);975			run_to_block(100);976			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);977		});978	}979980	#[test]981	fn reschedule_works() {982		new_test_ext().execute_with(|| {983			let call = Call::Logger(logger::Call::log(42, 1000));984			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));985			assert_eq!(Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call).unwrap(), (4, 0));986987			run_to_block(3);988			assert!(logger::log().is_empty());989990			assert_eq!(Scheduler::do_reschedule((4, 0), DispatchTime::At(6)).unwrap(), (6, 0));991992			assert_noop!(Scheduler::do_reschedule((6, 0), DispatchTime::At(6)), Error::<Test>::RescheduleNoChange);993994			run_to_block(4);995			assert!(logger::log().is_empty());996997			run_to_block(6);998			assert_eq!(logger::log(), vec![(root(), 42u32)]);9991000			run_to_block(100);1001			assert_eq!(logger::log(), vec![(root(), 42u32)]);1002		});1003	}10041005	#[test]1006	fn reschedule_named_works() {1007		new_test_ext().execute_with(|| {1008			let call = Call::Logger(logger::Call::log(42, 1000));1009			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));1010			assert_eq!(Scheduler::do_schedule_named(1011				1u32.encode(), DispatchTime::At(4), None, 127, root(), call1012			).unwrap(), (4, 0));10131014			run_to_block(3);1015			assert!(logger::log().is_empty());10161017			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(), (6, 0));10181019			assert_noop!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)), Error::<Test>::RescheduleNoChange);10201021			run_to_block(4);1022			assert!(logger::log().is_empty());10231024			run_to_block(6);1025			assert_eq!(logger::log(), vec![(root(), 42u32)]);10261027			run_to_block(100);1028			assert_eq!(logger::log(), vec![(root(), 42u32)]);1029		});1030	}10311032	#[test]1033	fn reschedule_named_perodic_works() {1034		new_test_ext().execute_with(|| {1035			let call = Call::Logger(logger::Call::log(42, 1000));1036			assert!(!<Test as frame_system::Config>::BaseCallFilter::filter(&call));1037			assert_eq!(Scheduler::do_schedule_named(1038				1u32.encode(), DispatchTime::At(4), Some((3, 3)), 127, root(), call1039			).unwrap(), (4, 0));10401041			run_to_block(3);1042			assert!(logger::log().is_empty());10431044			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(5)).unwrap(), (5, 0));1045			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(6)).unwrap(), (6, 0));10461047			run_to_block(5);1048			assert!(logger::log().is_empty());10491050			run_to_block(6);1051			assert_eq!(logger::log(), vec![(root(), 42u32)]);10521053			assert_eq!(Scheduler::do_reschedule_named(1u32.encode(), DispatchTime::At(10)).unwrap(), (10, 0));10541055			run_to_block(9);1056			assert_eq!(logger::log(), vec![(root(), 42u32)]);10571058			run_to_block(10);1059			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);10601061			run_to_block(13);1062			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);10631064			run_to_block(100);1065			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);1066		});1067	}10681069	#[test]1070	fn cancel_named_scheduling_works_with_normal_cancel() {1071		new_test_ext().execute_with(|| {1072			// at #4.1073			Scheduler::do_schedule_named(1074				1u32.encode(), DispatchTime::At(4), None, 127, root(), Call::Logger(logger::Call::log(69, 1000))1075			).unwrap();1076			let i = Scheduler::do_schedule(1077				DispatchTime::At(4), None, 127, root(), Call::Logger(logger::Call::log(42, 1000))1078			).unwrap();1079			run_to_block(3);1080			assert!(logger::log().is_empty());1081			assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));1082			assert_ok!(Scheduler::do_cancel(None, i));1083			run_to_block(100);1084			assert!(logger::log().is_empty());1085		});1086	}10871088	#[test]1089	fn cancel_named_periodic_scheduling_works() {1090		new_test_ext().execute_with(|| {1091			// at #4, every 3 blocks, 3 times.1092			Scheduler::do_schedule_named(1093				1u32.encode(),1094				DispatchTime::At(4),1095				Some((3, 3)),1096				127,1097				root(),1098				Call::Logger(logger::Call::log(42, 1000))1099			).unwrap();1100			// same id results in error.1101			assert!(Scheduler::do_schedule_named(1102				1u32.encode(),1103				DispatchTime::At(4),1104				None,1105				127,1106				root(),1107				Call::Logger(logger::Call::log(69, 1000))1108			).is_err());1109			// different id is ok.1110			Scheduler::do_schedule_named(1111				2u32.encode(), DispatchTime::At(8), None, 127, root(), Call::Logger(logger::Call::log(69, 1000))1112			).unwrap();1113			run_to_block(3);1114			assert!(logger::log().is_empty());1115			run_to_block(4);1116			assert_eq!(logger::log(), vec![(root(), 42u32)]);1117			run_to_block(6);1118			assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));1119			run_to_block(100);1120			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);1121		});1122	}11231124	#[test]1125	fn scheduler_respects_weight_limits() {1126		new_test_ext().execute_with(|| {1127			assert_ok!(Scheduler::do_schedule(1128				DispatchTime::At(4),1129				None,1130				127,1131				root(),1132				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))1133			));1134			assert_ok!(Scheduler::do_schedule(1135				DispatchTime::At(4),1136				None,1137				127,1138				root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1139			));1140			// 69 and 42 do not fit together1141			run_to_block(4);1142			assert_eq!(logger::log(), vec![(root(), 42u32)]);1143			run_to_block(5);1144			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);1145		});1146	}11471148	#[test]1149	fn scheduler_respects_hard_deadlines_more() {1150		new_test_ext().execute_with(|| {1151			assert_ok!(Scheduler::do_schedule(1152				DispatchTime::At(4),1153				None,1154				0,1155				root(),1156				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))1157			));1158			assert_ok!(Scheduler::do_schedule(1159				DispatchTime::At(4),1160				None,1161				0,1162				root(),1163				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1164			));1165			// With base weights, 69 and 42 should not fit together, but do because of hard deadlines1166			run_to_block(4);1167			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);1168		});1169	}11701171	#[test]1172	fn scheduler_respects_priority_ordering() {1173		new_test_ext().execute_with(|| {1174			assert_ok!(Scheduler::do_schedule(1175				DispatchTime::At(4),1176				None,1177				1,1178				root(),1179				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))1180			));1181			assert_ok!(Scheduler::do_schedule(1182				DispatchTime::At(4),1183				None,1184				0,1185				root(),1186				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1187			));1188			run_to_block(4);1189			assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);1190		});1191	}11921193	#[test]1194	fn scheduler_respects_priority_ordering_with_soft_deadlines() {1195		new_test_ext().execute_with(|| {1196			assert_ok!(Scheduler::do_schedule(1197				DispatchTime::At(4),1198				None,1199				255,1200				root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))1201			));1202			assert_ok!(Scheduler::do_schedule(1203				DispatchTime::At(4),1204				None,1205				127,1206				root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1207			));1208			assert_ok!(Scheduler::do_schedule(1209				DispatchTime::At(4),1210				None,1211				126,1212				root(), Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))1213			));12141215			// 2600 does not fit with 69 or 42, but has higher priority, so will go through1216			run_to_block(4);1217			assert_eq!(logger::log(), vec![(root(), 2600u32)]);1218			// 69 and 42 fit together1219			run_to_block(5);1220			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);1221		});1222	}12231224	#[test]1225	fn on_initialize_weight_is_correct() {1226		new_test_ext().execute_with(|| {1227			let base_weight: Weight = <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 2);1228			let base_multiplier = 0;1229			let named_multiplier = <Test as frame_system::Config>::DbWeight::get().writes(1);1230			let periodic_multiplier = <Test as frame_system::Config>::DbWeight::get().reads_writes(1, 1);12311232			// Named1233			assert_ok!(1234				Scheduler::do_schedule_named(1235					1u32.encode(), DispatchTime::At(1), None, 255, root(),1236					Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3))1237				)1238			);1239			// Anon Periodic1240			assert_ok!(Scheduler::do_schedule(1241				DispatchTime::At(1),1242				Some((1000, 3)),1243				128,1244				root(),1245				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))1246			));1247			// Anon1248			assert_ok!(Scheduler::do_schedule(1249				DispatchTime::At(1),1250				None,1251				127,1252				root(),1253				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))1254			));1255			// Named Periodic1256			assert_ok!(Scheduler::do_schedule_named(1257				2u32.encode(), DispatchTime::At(1), Some((1000, 3)), 126, root(),1258				Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2)))1259			);12601261			// Will include the named periodic only1262			let actual_weight = Scheduler::on_initialize(1);1263			let call_weight = MaximumSchedulerWeight::get() / 2;1264			assert_eq!(1265				actual_weight, call_weight + base_weight + base_multiplier + named_multiplier + periodic_multiplier1266			);1267			assert_eq!(logger::log(), vec![(root(), 2600u32)]);12681269			// Will include anon and anon periodic1270			let actual_weight = Scheduler::on_initialize(2);1271			let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3;1272			assert_eq!(actual_weight, call_weight + base_weight + base_multiplier * 2 + periodic_multiplier);1273			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);12741275			// Will include named only1276			let actual_weight = Scheduler::on_initialize(3);1277			let call_weight = MaximumSchedulerWeight::get() / 3;1278			assert_eq!(actual_weight, call_weight + base_weight + base_multiplier + named_multiplier);1279			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32), (root(), 3u32)]);12801281			// Will contain none1282			let actual_weight = Scheduler::on_initialize(4);1283			assert_eq!(actual_weight, 0);1284		});1285	}12861287	#[test]1288	fn root_calls_works() {1289		new_test_ext().execute_with(|| {1290			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1291			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));1292			assert_ok!(Scheduler::schedule_named(Origin::root(), 1u32.encode(), 4, None, 127, call));1293			assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2));1294			run_to_block(3);1295			// Scheduled calls are in the agenda.1296			assert_eq!(Agenda::<Test>::get(4).len(), 2);1297			assert!(logger::log().is_empty());1298			assert_ok!(Scheduler::cancel_named(Origin::root(), 1u32.encode()));1299			assert_ok!(Scheduler::cancel(Origin::root(), 4, 1));1300			// Scheduled calls are made NONE, so should not effect state1301			run_to_block(100);1302			assert!(logger::log().is_empty());1303		});1304	}13051306	#[test]1307	fn fails_to_schedule_task_in_the_past() {1308		new_test_ext().execute_with(|| {1309			run_to_block(3);13101311			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1312			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));13131314			assert_err!(1315				Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call),1316				Error::<Test>::TargetBlockNumberInPast,1317			);13181319			assert_err!(1320				Scheduler::schedule(Origin::root(), 2, None, 127, call2.clone()),1321				Error::<Test>::TargetBlockNumberInPast,1322			);13231324			assert_err!(1325				Scheduler::schedule(Origin::root(), 3, None, 127, call2),1326				Error::<Test>::TargetBlockNumberInPast,1327			);1328		});1329	}13301331	#[test]1332	fn should_use_orign() {1333		new_test_ext().execute_with(|| {1334			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1335			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));1336			assert_ok!(1337				Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)1338			);1339			assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));1340			run_to_block(3);1341			// Scheduled calls are in the agenda.1342			assert_eq!(Agenda::<Test>::get(4).len(), 2);1343			assert!(logger::log().is_empty());1344			assert_ok!(Scheduler::cancel_named(system::RawOrigin::Signed(1).into(), 1u32.encode()));1345			assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));1346			// Scheduled calls are made NONE, so should not effect state1347			run_to_block(100);1348			assert!(logger::log().is_empty());1349		});1350	}13511352	#[test]1353	fn should_check_orign() {1354		new_test_ext().execute_with(|| {1355			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));1356			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));1357			assert_noop!(1358				Scheduler::schedule_named(system::RawOrigin::Signed(2).into(), 1u32.encode(), 4, None, 127, call),1359				BadOrigin1360			);1361			assert_noop!(Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, 127, call2), BadOrigin);1362		});1363	}13641365	#[test]1366	fn should_check_orign_for_cancel() {1367		new_test_ext().execute_with(|| {1368			let call = Box::new(Call::Logger(logger::Call::log_without_filter(69, 1000)));1369			let call2 = Box::new(Call::Logger(logger::Call::log_without_filter(42, 1000)));1370			assert_ok!(1371				Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)1372			);1373			assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));1374			run_to_block(3);1375			// Scheduled calls are in the agenda.1376			assert_eq!(Agenda::<Test>::get(4).len(), 2);1377			assert!(logger::log().is_empty());1378			assert_noop!(Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), 1u32.encode()), BadOrigin);1379			assert_noop!(Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1), BadOrigin);1380			assert_noop!(Scheduler::cancel_named(system::RawOrigin::Root.into(), 1u32.encode()), BadOrigin);1381			assert_noop!(Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1), BadOrigin);1382			run_to_block(5);1383			assert_eq!(1384				logger::log(),1385				vec![(system::RawOrigin::Signed(1).into(), 69u32), (system::RawOrigin::Signed(1).into(), 42u32)]1386			);1387		});1388	}13891390	#[test]1391	fn migration_to_v2_works() {1392		new_test_ext().execute_with(|| {1393			for i in 0..3u64 {1394				let k = i.twox_64_concat();1395				let old = vec![1396					Some(ScheduledV1 {1397						maybe_id: None,1398						priority: i as u8 + 10,1399						call: Call::Logger(logger::Call::log(96, 100)),1400						maybe_periodic: None,1401					}),1402					None,1403					Some(ScheduledV1 {1404						maybe_id: Some(b"test".to_vec()),1405						priority: 123,1406						call: Call::Logger(logger::Call::log(69, 1000)),1407						maybe_periodic: Some((456u64, 10)),1408					}),1409				];1410				frame_support::migration::put_storage_value(1411					b"Scheduler",1412					b"Agenda",1413					&k,1414					old,1415				);1416			}14171418			assert_eq!(StorageVersion::get(), Releases::V1);14191420			assert!(Scheduler::migrate_v1_to_t2());14211422			assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![1423				(1424					0,1425					vec![1426					Some(ScheduledV2 {1427						maybe_id: None,1428						priority: 10,1429						call: Call::Logger(logger::Call::log(96, 100)),1430						maybe_periodic: None,1431						origin: root(),1432						_phantom: PhantomData::<u64>::default(),1433					}),1434					None,1435					Some(ScheduledV2 {1436						maybe_id: Some(b"test".to_vec()),1437						priority: 123,1438						call: Call::Logger(logger::Call::log(69, 1000)),1439						maybe_periodic: Some((456u64, 10)),1440						origin: root(),1441						_phantom: PhantomData::<u64>::default(),1442					}),1443				]),1444				(1445					1,1446					vec![1447						Some(ScheduledV2 {1448							maybe_id: None,1449							priority: 11,1450							call: Call::Logger(logger::Call::log(96, 100)),1451							maybe_periodic: None,1452							origin: root(),1453							_phantom: PhantomData::<u64>::default(),1454						}),1455						None,1456						Some(ScheduledV2 {1457							maybe_id: Some(b"test".to_vec()),1458							priority: 123,1459							call: Call::Logger(logger::Call::log(69, 1000)),1460							maybe_periodic: Some((456u64, 10)),1461							origin: root(),1462							_phantom: PhantomData::<u64>::default(),1463						}),1464					]1465				),1466				(1467					2,1468					vec![1469						Some(ScheduledV2 {1470							maybe_id: None,1471							priority: 12,1472							call: Call::Logger(logger::Call::log(96, 100)),1473							maybe_periodic: None,1474							origin: root(),1475							_phantom: PhantomData::<u64>::default(),1476						}),1477						None,1478						Some(ScheduledV2 {1479							maybe_id: Some(b"test".to_vec()),1480							priority: 123,1481							call: Call::Logger(logger::Call::log(69, 1000)),1482							maybe_periodic: Some((456u64, 10)),1483							origin: root(),1484							_phantom: PhantomData::<u64>::default(),1485						}),1486					]1487				)1488			]);14891490			assert_eq!(StorageVersion::get(), Releases::V2);1491		});1492	}14931494	#[test]1495	fn test_migrate_origin() {1496		new_test_ext().execute_with(|| {1497			for i in 0..3u64 {1498				let k = i.twox_64_concat();1499				let old: Vec<Option<Scheduled<_, _, u32, u64>>> = vec![1500					Some(Scheduled {1501						maybe_id: None,1502						priority: i as u8 + 10,1503						call: Call::Logger(logger::Call::log(96, 100)),1504						origin: 3u32,1505						maybe_periodic: None,1506						_phantom: Default::default(),1507					}),1508					None,1509					Some(Scheduled {1510						maybe_id: Some(b"test".to_vec()),1511						priority: 123,1512						origin: 2u32,1513						call: Call::Logger(logger::Call::log(69, 1000)),1514						maybe_periodic: Some((456u64, 10)),1515						_phantom: Default::default(),1516					}),1517				];1518				frame_support::migration::put_storage_value(1519					b"Scheduler",1520					b"Agenda",1521					&k,1522					old,1523				);1524			}15251526			impl Into<OriginCaller> for u32 {1527				fn into(self) -> OriginCaller {1528					match self {1529						3u32 => system::RawOrigin::Root.into(),1530						2u32 => system::RawOrigin::None.into(),1531						_ => unreachable!("test make no use of it"),1532					}1533				}1534			}15351536			Scheduler::migrate_origin::<u32>();15371538			assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![1539				(1540					0,1541					vec![1542					Some(ScheduledV2::<_, _, OriginCaller, u64> {1543						maybe_id: None,1544						priority: 10,1545						call: Call::Logger(logger::Call::log(96, 100)),1546						maybe_periodic: None,1547						origin: system::RawOrigin::Root.into(),1548						_phantom: PhantomData::<u64>::default(),1549					}),1550					None,1551					Some(ScheduledV2 {1552						maybe_id: Some(b"test".to_vec()),1553						priority: 123,1554						call: Call::Logger(logger::Call::log(69, 1000)),1555						maybe_periodic: Some((456u64, 10)),1556						origin: system::RawOrigin::None.into(),1557						_phantom: PhantomData::<u64>::default(),1558					}),1559				]),1560				(1561					1,1562					vec![1563						Some(ScheduledV2 {1564							maybe_id: None,1565							priority: 11,1566							call: Call::Logger(logger::Call::log(96, 100)),1567							maybe_periodic: None,1568							origin: system::RawOrigin::Root.into(),1569							_phantom: PhantomData::<u64>::default(),1570						}),1571						None,1572						Some(ScheduledV2 {1573							maybe_id: Some(b"test".to_vec()),1574							priority: 123,1575							call: Call::Logger(logger::Call::log(69, 1000)),1576							maybe_periodic: Some((456u64, 10)),1577							origin: system::RawOrigin::None.into(),1578							_phantom: PhantomData::<u64>::default(),1579						}),1580					]1581				),1582				(1583					2,1584					vec![1585						Some(ScheduledV2 {1586							maybe_id: None,1587							priority: 12,1588							call: Call::Logger(logger::Call::log(96, 100)),1589							maybe_periodic: None,1590							origin: system::RawOrigin::Root.into(),1591							_phantom: PhantomData::<u64>::default(),1592						}),1593						None,1594						Some(ScheduledV2 {1595							maybe_id: Some(b"test".to_vec()),1596							priority: 123,1597							call: Call::Logger(logger::Call::log(69, 1000)),1598							maybe_periodic: Some((456u64, 10)),1599							origin: system::RawOrigin::None.into(),1600							_phantom: PhantomData::<u64>::default(),1601						}),1602					]1603				)1604			]);1605		});1606	}1607}