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

difftreelog

feat scheduler v2, priority change

Daniel Shiposha2022-10-21parent: #f1b93a3.patch.diff
in: master

3 files changed

modifiedpallets/scheduler-v2/src/lib.rsdiffbeforeafterboth
before · pallets/scheduler-v2/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//!   with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//!   that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![cfg_attr(not(feature = "std"), no_std)]6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72#[cfg(test)]73mod mock;74#[cfg(test)]75mod tests;76pub mod weights;7778use codec::{Codec, Decode, Encode, MaxEncodedLen};79use frame_support::{80	dispatch::{DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter},81	traits::{82		schedule::{self, DispatchTime},83		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,84		ConstU32, UnfilteredDispatchable,85	},86	weights::{Weight, PostDispatchInfo}, unsigned::TransactionValidityError,87};8889use frame_system::{self as system};90use scale_info::TypeInfo;91use sp_runtime::{92	traits::{BadOrigin, One, Saturating, Zero, Hash},93	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,94};95use sp_core::H160;96use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};97pub use weights::WeightInfo;9899pub use pallet::*;100101/// Just a simple index for naming period tasks.102pub type PeriodicIndex = u32;103/// The location of a scheduled task that can be used to remove it.104pub type TaskAddress<BlockNumber> = (BlockNumber, u32);105106pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;107108#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]109#[scale_info(skip_type_params(T))]110pub enum ScheduledCall<T: Config> {111	Inline(EncodedCall),112	PreimageLookup { hash: T::Hash, unbounded_len: u32 },113}114115impl<T: Config> ScheduledCall<T> {116	pub fn new(call: <T as Config>::Call) -> Result<Self, DispatchError> {117		let encoded = call.encode();118		let len = encoded.len();119120		match EncodedCall::try_from(encoded.clone()) {121			Ok(bounded) => Ok(Self::Inline(bounded)),122			Err(_) => {123				let hash = <T as system::Config>::Hashing::hash_of(&encoded);124				<T as Config>::Preimages::note_preimage(125					encoded126						.try_into()127						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,128				);129130				Ok(Self::PreimageLookup {131					hash,132					unbounded_len: len as u32,133				})134			}135		}136	}137138	/// The maximum length of the lookup that is needed to peek `Self`.139	pub fn lookup_len(&self) -> Option<u32> {140		match self {141			Self::Inline(..) => None,142			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),143		}144	}145146	/// Returns whether the image will require a lookup to be peeked.147	pub fn lookup_needed(&self) -> bool {148		match self {149			Self::Inline(_) => false,150			Self::PreimageLookup { .. } => true,151		}152	}153154	fn decode(mut data: &[u8]) -> Result<<T as Config>::Call, DispatchError> {155		<T as Config>::Call::decode(&mut data)156			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())157	}158}159160pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {161	fn drop(call: &ScheduledCall<T>);162163	fn peek(164		call: &ScheduledCall<T>,165	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError>;166167	/// Convert the given scheduled `call` value back into its original instance. If successful,168	/// `drop` any data backing it. This will not break the realisability of independently169	/// created instances of `ScheduledCall` which happen to have identical data.170	fn realize(171		call: &ScheduledCall<T>,172	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError>;173}174175impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {176	fn drop(call: &ScheduledCall<T>) {177		match call {178			ScheduledCall::Inline(_) => {}179			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),180		}181	}182183	fn peek(184		call: &ScheduledCall<T>,185	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError> {186		match call {187			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),188			ScheduledCall::PreimageLookup {189				hash,190				unbounded_len,191			} => {192				let (preimage, len) = Self::get_preimage(hash)193					.ok_or(<Error<T>>::PreimageNotFound)194					.map(|preimage| (preimage, *unbounded_len))?;195196				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))197			}198		}199	}200201	fn realize(202		call: &ScheduledCall<T>,203	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError> {204		let r = Self::peek(call)?;205		Self::drop(call);206		Ok(r)207	}208}209210pub enum ScheduledEnsureOriginSuccess<AccountId> {211	Root,212	Signed(AccountId),213	Unsigned,214}215216pub type TaskName = [u8; 32];217218/// Information regarding an item to be executed in the future.219#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]220#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]221pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {222	/// The unique identity for this task, if there is one.223	maybe_id: Option<Name>,224225	/// This task's priority.226	priority: schedule::Priority,227228	/// The call to be dispatched.229	call: Call,230231	/// If the call is periodic, then this points to the information concerning that.232	maybe_periodic: Option<schedule::Period<BlockNumber>>,233234	/// The origin with which to dispatch the call.235	origin: PalletsOrigin,236	_phantom: PhantomData<AccountId>,237}238239pub type ScheduledOf<T> = Scheduled<240	TaskName,241	ScheduledCall<T>,242	<T as frame_system::Config>::BlockNumber,243	<T as Config>::PalletsOrigin,244	<T as frame_system::Config>::AccountId,245>;246247struct WeightCounter {248	used: Weight,249	limit: Weight,250}251252impl WeightCounter {253	fn check_accrue(&mut self, w: Weight) -> bool {254		let test = self.used.saturating_add(w);255		if test > self.limit {256			false257		} else {258			self.used = test;259			true260		}261	}262263	fn can_accrue(&mut self, w: Weight) -> bool {264		self.used.saturating_add(w) <= self.limit265	}266}267268pub(crate) trait MarginalWeightInfo: WeightInfo {269	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {270		let base = Self::service_task_base();271		let mut total = match maybe_lookup_len {272			None => base,273			Some(l) => Self::service_task_fetched(l as u32),274		};275		if named {276			total.saturating_accrue(Self::service_task_named().saturating_sub(base));277		}278		if periodic {279			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));280		}281		total282	}283}284285impl<T: WeightInfo> MarginalWeightInfo for T {}286287#[frame_support::pallet]288pub mod pallet {289	use super::*;290	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};291	use system::pallet_prelude::*;292293	/// The current storage version.294	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);295296	#[pallet::pallet]297	#[pallet::generate_store(pub(super) trait Store)]298	#[pallet::storage_version(STORAGE_VERSION)]299	pub struct Pallet<T>(_);300301	#[pallet::config]302	pub trait Config: frame_system::Config {303		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;304305		/// The aggregated origin which the dispatch will take.306		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>307			+ From<Self::PalletsOrigin>308			+ IsType<<Self as system::Config>::Origin>309			+ Clone;310311		/// The caller origin, overarching type of all pallets origins.312		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>313			+ Codec314			+ Clone315			+ Eq316			+ TypeInfo317			+ MaxEncodedLen;318319		/// The aggregated call type.320		type Call: Parameter321			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>322			+ UnfilteredDispatchable<Origin = <Self as system::Config>::Origin>323			+ GetDispatchInfo324			+ From<system::Call<Self>>;325326		/// The maximum weight that may be scheduled per block for any dispatchables.327		#[pallet::constant]328		type MaximumWeight: Get<Weight>;329330		/// Required origin to schedule or cancel calls.331		type ScheduleOrigin: EnsureOrigin<332			<Self as system::Config>::Origin,333			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,334		>;335336		/// Compare the privileges of origins.337		///338		/// This will be used when canceling a task, to ensure that the origin that tries339		/// to cancel has greater or equal privileges as the origin that created the scheduled task.340		///341		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can342		/// be used. This will only check if two given origins are equal.343		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;344345		/// The maximum number of scheduled calls in the queue for a single block.346		#[pallet::constant]347		type MaxScheduledPerBlock: Get<u32>;348349		/// Weight information for extrinsics in this pallet.350		type WeightInfo: WeightInfo;351352		/// The preimage provider with which we look up call hashes to get the call.353		type Preimages: SchedulerPreimages<Self>;354355		/// The helper type used for custom transaction fee logic.356		type CallExecutor: DispatchCall<Self, H160>;357	}358359	#[pallet::storage]360	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;361362	/// Items to be executed, indexed by the block number that they should be executed on.363	#[pallet::storage]364	pub type Agenda<T: Config> = StorageMap<365		_,366		Twox64Concat,367		T::BlockNumber,368		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,369		ValueQuery,370	>;371372	/// Lookup from a name to the block number and index of the task.373	#[pallet::storage]374	pub(crate) type Lookup<T: Config> =375		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;376377	/// Events type.378	#[pallet::event]379	#[pallet::generate_deposit(pub(super) fn deposit_event)]380	pub enum Event<T: Config> {381		/// Scheduled some task.382		Scheduled { when: T::BlockNumber, index: u32 },383		/// Canceled some task.384		Canceled { when: T::BlockNumber, index: u32 },385		/// Dispatched some task.386		Dispatched {387			task: TaskAddress<T::BlockNumber>,388			id: Option<[u8; 32]>,389			result: DispatchResult,390		},391		/// The call for the provided hash was not found so the task has been aborted.392		CallUnavailable {393			task: TaskAddress<T::BlockNumber>,394			id: Option<[u8; 32]>,395		},396		/// The given task was unable to be renewed since the agenda is full at that block.397		PeriodicFailed {398			task: TaskAddress<T::BlockNumber>,399			id: Option<[u8; 32]>,400		},401		/// The given task can never be executed since it is overweight.402		PermanentlyOverweight {403			task: TaskAddress<T::BlockNumber>,404			id: Option<[u8; 32]>,405		},406	}407408	#[pallet::error]409	pub enum Error<T> {410		/// Failed to schedule a call411		FailedToSchedule,412		/// There is no place for a new task in the agenda413		AgendaIsExhausted,414		/// Scheduled call is corrupted415		ScheduledCallCorrupted,416		/// Scheduled call preimage is not found417		PreimageNotFound,418		/// Scheduled call is too big419		TooBigScheduledCall,420		/// Cannot find the scheduled call.421		NotFound,422		/// Given target block number is in the past.423		TargetBlockNumberInPast,424		/// Reschedule failed because it does not change scheduled time.425		RescheduleNoChange,426		/// Attempt to use a non-named function on a named task.427		Named,428	}429430	#[pallet::hooks]431	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {432		/// Execute the scheduled calls433		fn on_initialize(now: T::BlockNumber) -> Weight {434			let mut weight_counter = WeightCounter {435				used: Weight::zero(),436				limit: T::MaximumWeight::get(),437			};438			Self::service_agendas(&mut weight_counter, now, u32::max_value());439			weight_counter.used440		}441	}442443	#[pallet::call]444	impl<T: Config> Pallet<T> {445		/// Anonymously schedule a task.446		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]447		pub fn schedule(448			origin: OriginFor<T>,449			when: T::BlockNumber,450			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,451			priority: schedule::Priority,452			call: Box<<T as Config>::Call>,453		) -> DispatchResult {454			T::ScheduleOrigin::ensure_origin(origin.clone())?;455			let origin = <T as Config>::Origin::from(origin);456			Self::do_schedule(457				DispatchTime::At(when),458				maybe_periodic,459				priority,460				origin.caller().clone(),461				<ScheduledCall<T>>::new(*call)?,462			)?;463			Ok(())464		}465466		/// Cancel an anonymously scheduled task.467		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]468		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {469			T::ScheduleOrigin::ensure_origin(origin.clone())?;470			let origin = <T as Config>::Origin::from(origin);471			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;472			Ok(())473		}474475		/// Schedule a named task.476		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]477		pub fn schedule_named(478			origin: OriginFor<T>,479			id: TaskName,480			when: T::BlockNumber,481			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,482			priority: schedule::Priority,483			call: Box<<T as Config>::Call>,484		) -> DispatchResult {485			T::ScheduleOrigin::ensure_origin(origin.clone())?;486			let origin = <T as Config>::Origin::from(origin);487			Self::do_schedule_named(488				id,489				DispatchTime::At(when),490				maybe_periodic,491				priority,492				origin.caller().clone(),493				<ScheduledCall<T>>::new(*call)?,494			)?;495			Ok(())496		}497498		/// Cancel a named scheduled task.499		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]500		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {501			T::ScheduleOrigin::ensure_origin(origin.clone())?;502			let origin = <T as Config>::Origin::from(origin);503			Self::do_cancel_named(Some(origin.caller().clone()), id)?;504			Ok(())505		}506507		/// Anonymously schedule a task after a delay.508		///509		/// # <weight>510		/// Same as [`schedule`].511		/// # </weight>512		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]513		pub fn schedule_after(514			origin: OriginFor<T>,515			after: T::BlockNumber,516			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,517			priority: schedule::Priority,518			call: Box<<T as Config>::Call>,519		) -> DispatchResult {520			T::ScheduleOrigin::ensure_origin(origin.clone())?;521			let origin = <T as Config>::Origin::from(origin);522			Self::do_schedule(523				DispatchTime::After(after),524				maybe_periodic,525				priority,526				origin.caller().clone(),527				<ScheduledCall<T>>::new(*call)?,528			)?;529			Ok(())530		}531532		/// Schedule a named task after a delay.533		///534		/// # <weight>535		/// Same as [`schedule_named`](Self::schedule_named).536		/// # </weight>537		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]538		pub fn schedule_named_after(539			origin: OriginFor<T>,540			id: TaskName,541			after: T::BlockNumber,542			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,543			priority: schedule::Priority,544			call: Box<<T as Config>::Call>,545		) -> DispatchResult {546			T::ScheduleOrigin::ensure_origin(origin.clone())?;547			let origin = <T as Config>::Origin::from(origin);548			Self::do_schedule_named(549				id,550				DispatchTime::After(after),551				maybe_periodic,552				priority,553				origin.caller().clone(),554				<ScheduledCall<T>>::new(*call)?,555			)?;556			Ok(())557		}558	}559}560561impl<T: Config> Pallet<T> {562	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {563		let now = frame_system::Pallet::<T>::block_number();564565		let when = match when {566			DispatchTime::At(x) => x,567			// The current block has already completed it's scheduled tasks, so568			// Schedule the task at lest one block after this current block.569			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),570		};571572		if when <= now {573			return Err(Error::<T>::TargetBlockNumberInPast.into());574		}575576		Ok(when)577	}578579	fn place_task(580		when: T::BlockNumber,581		what: ScheduledOf<T>,582	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {583		let maybe_name = what.maybe_id;584		let index = Self::push_to_agenda(when, what)?;585		let address = (when, index);586		if let Some(name) = maybe_name {587			Lookup::<T>::insert(name, address)588		}589		Self::deposit_event(Event::Scheduled {590			when: address.0,591			index: address.1,592		});593		Ok(address)594	}595596	fn push_to_agenda(597		when: T::BlockNumber,598		what: ScheduledOf<T>,599	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {600		let mut agenda = Agenda::<T>::get(when);601		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {602			// will always succeed due to the above check.603			let _ = agenda.try_push(Some(what));604			agenda.len() as u32 - 1605		} else {606			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {607				agenda[hole_index] = Some(what);608				hole_index as u32609			} else {610				return Err((<Error<T>>::AgendaIsExhausted.into(), what));611			}612		};613		Agenda::<T>::insert(when, agenda);614		Ok(index)615	}616617	fn do_schedule(618		when: DispatchTime<T::BlockNumber>,619		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,620		priority: schedule::Priority,621		origin: T::PalletsOrigin,622		call: ScheduledCall<T>,623	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {624		let when = Self::resolve_time(when)?;625626		// sanitize maybe_periodic627		let maybe_periodic = maybe_periodic628			.filter(|p| p.1 > 1 && !p.0.is_zero())629			// Remove one from the number of repetitions since we will schedule one now.630			.map(|(p, c)| (p, c - 1));631		let task = Scheduled {632			maybe_id: None,633			priority,634			call,635			maybe_periodic,636			origin,637			_phantom: PhantomData,638		};639		Self::place_task(when, task).map_err(|x| x.0)640	}641642	fn do_cancel(643		origin: Option<T::PalletsOrigin>,644		(when, index): TaskAddress<T::BlockNumber>,645	) -> Result<(), DispatchError> {646		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {647			agenda.get_mut(index as usize).map_or(648				Ok(None),649				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {650					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {651						if matches!(652							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),653							Some(Ordering::Less) | None654						) {655							return Err(BadOrigin.into());656						}657					};658					Ok(s.take())659				},660			)661		})?;662		if let Some(s) = scheduled {663			T::Preimages::drop(&s.call);664665			if let Some(id) = s.maybe_id {666				Lookup::<T>::remove(id);667			}668			Self::deposit_event(Event::Canceled { when, index });669			Ok(())670		} else {671			return Err(Error::<T>::NotFound.into());672		}673	}674675	fn do_schedule_named(676		id: TaskName,677		when: DispatchTime<T::BlockNumber>,678		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,679		priority: schedule::Priority,680		origin: T::PalletsOrigin,681		call: ScheduledCall<T>,682	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {683		// ensure id it is unique684		if Lookup::<T>::contains_key(&id) {685			return Err(Error::<T>::FailedToSchedule.into());686		}687688		let when = Self::resolve_time(when)?;689690		// sanitize maybe_periodic691		let maybe_periodic = maybe_periodic692			.filter(|p| p.1 > 1 && !p.0.is_zero())693			// Remove one from the number of repetitions since we will schedule one now.694			.map(|(p, c)| (p, c - 1));695696		let task = Scheduled {697			maybe_id: Some(id),698			priority,699			call,700			maybe_periodic,701			origin,702			_phantom: Default::default(),703		};704		Self::place_task(when, task).map_err(|x| x.0)705	}706707	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {708		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {709			if let Some((when, index)) = lookup.take() {710				let i = index as usize;711				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {712					if let Some(s) = agenda.get_mut(i) {713						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {714							if matches!(715								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),716								Some(Ordering::Less) | None717							) {718								return Err(BadOrigin.into());719							}720							T::Preimages::drop(&s.call);721						}722						*s = None;723					}724					Ok(())725				})?;726				Self::deposit_event(Event::Canceled { when, index });727				Ok(())728			} else {729				return Err(Error::<T>::NotFound.into());730			}731		})732	}733}734735enum ServiceTaskError {736	/// Could not be executed due to missing preimage.737	Unavailable,738	/// Could not be executed due to weight limitations.739	Overweight,740}741use ServiceTaskError::*;742743/// A Scheduler-Runtime interface for finer payment handling.744pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {745	/// Resolve the call dispatch, including any post-dispatch operations.746	fn dispatch_call(747		signer: Option<T::AccountId>,748		function: <T as Config>::Call,749	) -> Result<750		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,751		TransactionValidityError,752	>;753}754755impl<T: Config> Pallet<T> {756	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.757	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {758		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {759			return;760		}761762		let mut incomplete_since = now + One::one();763		let mut when = IncompleteSince::<T>::take().unwrap_or(now);764		let mut executed = 0;765766		let max_items = T::MaxScheduledPerBlock::get();767		let mut count_down = max;768		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);769		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {770			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {771				incomplete_since = incomplete_since.min(when);772			}773			when.saturating_inc();774			count_down.saturating_dec();775		}776		incomplete_since = incomplete_since.min(when);777		if incomplete_since <= now {778			IncompleteSince::<T>::put(incomplete_since);779		}780	}781782	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a783	/// later block.784	fn service_agenda(785		weight: &mut WeightCounter,786		executed: &mut u32,787		now: T::BlockNumber,788		when: T::BlockNumber,789		max: u32,790	) -> bool {791		let mut agenda = Agenda::<T>::get(when);792		let mut ordered = agenda793			.iter()794			.enumerate()795			.filter_map(|(index, maybe_item)| {796				maybe_item797					.as_ref()798					.map(|item| (index as u32, item.priority))799			})800			.collect::<Vec<_>>();801		ordered.sort_by_key(|k| k.1);802		let within_limit =803			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));804		debug_assert!(805			within_limit,806			"weight limit should have been checked in advance"807		);808809		// Items which we know can be executed and have postponed for execution in a later block.810		let mut postponed = (ordered.len() as u32).saturating_sub(max);811		// Items which we don't know can ever be executed.812		let mut dropped = 0;813814		for (agenda_index, _) in ordered.into_iter().take(max as usize) {815			let task = match agenda[agenda_index as usize].take() {816				None => continue,817				Some(t) => t,818			};819			let base_weight = T::WeightInfo::service_task(820				task.call.lookup_len().map(|x| x as usize),821				task.maybe_id.is_some(),822				task.maybe_periodic.is_some(),823			);824			if !weight.can_accrue(base_weight) {825				postponed += 1;826				break;827			}828			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);829			agenda[agenda_index as usize] = match result {830				Err((Unavailable, slot)) => {831					dropped += 1;832					slot833				}834				Err((Overweight, slot)) => {835					postponed += 1;836					slot837				}838				Ok(()) => {839					*executed += 1;840					None841				}842			};843		}844		if postponed > 0 || dropped > 0 {845			Agenda::<T>::insert(when, agenda);846		} else {847			Agenda::<T>::remove(when);848		}849		postponed == 0850	}851852	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.853	///854	/// This involves:855	/// - removing and potentially replacing the `Lookup` entry for the task.856	/// - realizing the task's call which can include a preimage lookup.857	/// - Rescheduling the task for execution in a later agenda if periodic.858	fn service_task(859		weight: &mut WeightCounter,860		now: T::BlockNumber,861		when: T::BlockNumber,862		agenda_index: u32,863		is_first: bool,864		mut task: ScheduledOf<T>,865	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {866		let (call, lookup_len) = match T::Preimages::peek(&task.call) {867			Ok(c) => c,868			Err(_) => {869				if let Some(ref id) = task.maybe_id {870					Lookup::<T>::remove(id);871				}872873				return Err((Unavailable, Some(task)));874			},875		};876877		weight.check_accrue(T::WeightInfo::service_task(878			lookup_len.map(|x| x as usize),879			task.maybe_id.is_some(),880			task.maybe_periodic.is_some(),881		));882883		match Self::execute_dispatch(weight, task.origin.clone(), call) {884			Err(Unavailable) => {885				debug_assert!(false, "Checked to exist with `peek`");886887				if let Some(ref id) = task.maybe_id {888					Lookup::<T>::remove(id);889				}890891				Self::deposit_event(Event::CallUnavailable {892					task: (when, agenda_index),893					id: task.maybe_id,894				});895				Err((Unavailable, Some(task)))896			}897			Err(Overweight) if is_first => {898				T::Preimages::drop(&task.call);899900				if let Some(ref id) = task.maybe_id {901					Lookup::<T>::remove(id);902				}903904				Self::deposit_event(Event::PermanentlyOverweight {905					task: (when, agenda_index),906					id: task.maybe_id,907				});908				Err((Unavailable, Some(task)))909			}910			Err(Overweight) => {911				// Preserve Lookup -- the task will be postponed.912				Err((Overweight, Some(task)))913			},914			Ok(result) => {915				Self::deposit_event(Event::Dispatched {916					task: (when, agenda_index),917					id: task.maybe_id,918					result,919				});920921				let is_canceled = task.maybe_id.as_ref()922					.map(|id| !Lookup::<T>::contains_key(id))923					.unwrap_or(false);924925				match &task.maybe_periodic {926					&Some((period, count)) if !is_canceled => {927						if count > 1 {928							task.maybe_periodic = Some((period, count - 1));929						} else {930							task.maybe_periodic = None;931						}932						let wake = now.saturating_add(period);933						match Self::place_task(wake, task) {934							Ok(_) => {}935							Err((_, task)) => {936								// TODO: Leave task in storage somewhere for it to be rescheduled937								// manually.938								T::Preimages::drop(&task.call);939								Self::deposit_event(Event::PeriodicFailed {940									task: (when, agenda_index),941									id: task.maybe_id,942								});943							}944						}945					},946					_ => {947						if let Some(ref id) = task.maybe_id {948							Lookup::<T>::remove(id);949						}950951						T::Preimages::drop(&task.call)952					},953				}954				Ok(())955			}956		}957	}958959	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`960	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using961	/// post info if available).962	///963	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the964	/// call itself).965	fn execute_dispatch(966		weight: &mut WeightCounter,967		origin: T::PalletsOrigin,968		call: <T as Config>::Call,969	) -> Result<DispatchResult, ServiceTaskError> {970		let dispatch_origin: <T as Config>::Origin = origin.into();971		let base_weight = match dispatch_origin.clone().as_signed() {972			Some(_) => T::WeightInfo::execute_dispatch_signed(),973			_ => T::WeightInfo::execute_dispatch_unsigned(),974		};975		let call_weight = call.get_dispatch_info().weight;976		// We only allow a scheduled call if it cannot push the weight past the limit.977		let max_weight = base_weight.saturating_add(call_weight);978979		if !weight.can_accrue(max_weight) {980			return Err(Overweight);981		}982983		// let scheduled_origin =984		// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());985		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());986987		let r = match ensured_origin {988			Ok(ScheduledEnsureOriginSuccess::Root) => {989				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))990			},991			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {992				// Execute transaction via chain default pipeline993				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken994				T::CallExecutor::dispatch_call(Some(sender), call.clone())995			},996			Ok(ScheduledEnsureOriginSuccess::Unsigned) => {997				// Unsigned version of the above998				T::CallExecutor::dispatch_call(None, call.clone())999			}1000			Err(e) => Ok(Err(e.into())),1001		};10021003		let (maybe_actual_call_weight, result) = match r {1004			Ok(result) => match result {1005				Ok(post_info) => (post_info.actual_weight, Ok(())),1006				Err(error_and_info) => (1007					error_and_info.post_info.actual_weight,1008					Err(error_and_info.error),1009				),1010			},1011			Err(_) => {1012				log::error!(1013					target: "runtime::scheduler",1014					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1015					This block might have become invalid.");1016				(None, Err(DispatchError::CannotLookup))1017			}1018		};1019		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1020		weight.check_accrue(base_weight);1021		weight.check_accrue(call_weight);1022		Ok(result)1023	}1024}
after · pallets/scheduler-v2/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// 	http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! may be named or anonymous and may be canceled.47//!48//! **NOTE:** The scheduled calls will be dispatched with the default filter49//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin50//! except root which will get no filter. And not the filter contained in origin51//! use to call `fn schedule`.52//!53//! If a call is scheduled using proxy or whatever mecanism which adds filter,54//! then those filter will not be used when dispatching the schedule call.55//!56//! ## Interface57//!58//! ### Dispatchable Functions59//!60//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and61//!   with a specified priority.62//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.63//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter64//!   that can be used for identification.65//! * `cancel_named` - the named complement to the cancel function.6667// Ensure we're `no_std` when compiling for Wasm.68#![cfg_attr(not(feature = "std"), no_std)]6970#[cfg(feature = "runtime-benchmarks")]71mod benchmarking;72#[cfg(test)]73mod mock;74#[cfg(test)]75mod tests;76pub mod weights;7778use codec::{Codec, Decode, Encode, MaxEncodedLen};79use frame_support::{80	dispatch::{DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter},81	traits::{82		schedule::{self, DispatchTime, LOWEST_PRIORITY},83		EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,84		ConstU32, UnfilteredDispatchable,85	},86	weights::{Weight, PostDispatchInfo}, unsigned::TransactionValidityError,87};8889use frame_system::{self as system};90use scale_info::TypeInfo;91use sp_runtime::{92	traits::{BadOrigin, One, Saturating, Zero, Hash},93	BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,94};95use sp_core::H160;96use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};97pub use weights::WeightInfo;9899pub use pallet::*;100101/// Just a simple index for naming period tasks.102pub type PeriodicIndex = u32;103/// The location of a scheduled task that can be used to remove it.104pub type TaskAddress<BlockNumber> = (BlockNumber, u32);105106pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;107108#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]109#[scale_info(skip_type_params(T))]110pub enum ScheduledCall<T: Config> {111	Inline(EncodedCall),112	PreimageLookup { hash: T::Hash, unbounded_len: u32 },113}114115impl<T: Config> ScheduledCall<T> {116	pub fn new(call: <T as Config>::Call) -> Result<Self, DispatchError> {117		let encoded = call.encode();118		let len = encoded.len();119120		match EncodedCall::try_from(encoded.clone()) {121			Ok(bounded) => Ok(Self::Inline(bounded)),122			Err(_) => {123				let hash = <T as system::Config>::Hashing::hash_of(&encoded);124				<T as Config>::Preimages::note_preimage(125					encoded126						.try_into()127						.map_err(|_| <Error<T>>::TooBigScheduledCall)?,128				);129130				Ok(Self::PreimageLookup {131					hash,132					unbounded_len: len as u32,133				})134			}135		}136	}137138	/// The maximum length of the lookup that is needed to peek `Self`.139	pub fn lookup_len(&self) -> Option<u32> {140		match self {141			Self::Inline(..) => None,142			Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),143		}144	}145146	/// Returns whether the image will require a lookup to be peeked.147	pub fn lookup_needed(&self) -> bool {148		match self {149			Self::Inline(_) => false,150			Self::PreimageLookup { .. } => true,151		}152	}153154	fn decode(mut data: &[u8]) -> Result<<T as Config>::Call, DispatchError> {155		<T as Config>::Call::decode(&mut data)156			.map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())157	}158}159160pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {161	fn drop(call: &ScheduledCall<T>);162163	fn peek(164		call: &ScheduledCall<T>,165	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError>;166167	/// Convert the given scheduled `call` value back into its original instance. If successful,168	/// `drop` any data backing it. This will not break the realisability of independently169	/// created instances of `ScheduledCall` which happen to have identical data.170	fn realize(171		call: &ScheduledCall<T>,172	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError>;173}174175impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {176	fn drop(call: &ScheduledCall<T>) {177		match call {178			ScheduledCall::Inline(_) => {}179			ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),180		}181	}182183	fn peek(184		call: &ScheduledCall<T>,185	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError> {186		match call {187			ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),188			ScheduledCall::PreimageLookup {189				hash,190				unbounded_len,191			} => {192				let (preimage, len) = Self::get_preimage(hash)193					.ok_or(<Error<T>>::PreimageNotFound)194					.map(|preimage| (preimage, *unbounded_len))?;195196				Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))197			}198		}199	}200201	fn realize(202		call: &ScheduledCall<T>,203	) -> Result<(<T as pallet::Config>::Call, Option<u32>), DispatchError> {204		let r = Self::peek(call)?;205		Self::drop(call);206		Ok(r)207	}208}209210pub enum ScheduledEnsureOriginSuccess<AccountId> {211	Root,212	Signed(AccountId),213	Unsigned,214}215216pub type TaskName = [u8; 32];217218/// Information regarding an item to be executed in the future.219#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]220#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]221pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {222	/// The unique identity for this task, if there is one.223	maybe_id: Option<Name>,224225	/// This task's priority.226	priority: schedule::Priority,227228	/// The call to be dispatched.229	call: Call,230231	/// If the call is periodic, then this points to the information concerning that.232	maybe_periodic: Option<schedule::Period<BlockNumber>>,233234	/// The origin with which to dispatch the call.235	origin: PalletsOrigin,236	_phantom: PhantomData<AccountId>,237}238239pub type ScheduledOf<T> = Scheduled<240	TaskName,241	ScheduledCall<T>,242	<T as frame_system::Config>::BlockNumber,243	<T as Config>::PalletsOrigin,244	<T as frame_system::Config>::AccountId,245>;246247struct WeightCounter {248	used: Weight,249	limit: Weight,250}251252impl WeightCounter {253	fn check_accrue(&mut self, w: Weight) -> bool {254		let test = self.used.saturating_add(w);255		if test > self.limit {256			false257		} else {258			self.used = test;259			true260		}261	}262263	fn can_accrue(&mut self, w: Weight) -> bool {264		self.used.saturating_add(w) <= self.limit265	}266}267268pub(crate) trait MarginalWeightInfo: WeightInfo {269	fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {270		let base = Self::service_task_base();271		let mut total = match maybe_lookup_len {272			None => base,273			Some(l) => Self::service_task_fetched(l as u32),274		};275		if named {276			total.saturating_accrue(Self::service_task_named().saturating_sub(base));277		}278		if periodic {279			total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));280		}281		total282	}283}284285impl<T: WeightInfo> MarginalWeightInfo for T {}286287#[frame_support::pallet]288pub mod pallet {289	use super::*;290	use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};291	use system::pallet_prelude::*;292293	/// The current storage version.294	const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);295296	#[pallet::pallet]297	#[pallet::generate_store(pub(super) trait Store)]298	#[pallet::storage_version(STORAGE_VERSION)]299	pub struct Pallet<T>(_);300301	#[pallet::config]302	pub trait Config: frame_system::Config {303		type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;304305		/// The aggregated origin which the dispatch will take.306		type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>307			+ From<Self::PalletsOrigin>308			+ IsType<<Self as system::Config>::Origin>309			+ Clone;310311		/// The caller origin, overarching type of all pallets origins.312		type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>313			+ Codec314			+ Clone315			+ Eq316			+ TypeInfo317			+ MaxEncodedLen;318319		/// The aggregated call type.320		type Call: Parameter321			+ Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>322			+ UnfilteredDispatchable<Origin = <Self as system::Config>::Origin>323			+ GetDispatchInfo324			+ From<system::Call<Self>>;325326		/// The maximum weight that may be scheduled per block for any dispatchables.327		#[pallet::constant]328		type MaximumWeight: Get<Weight>;329330		/// Required origin to schedule or cancel calls.331		type ScheduleOrigin: EnsureOrigin<332			<Self as system::Config>::Origin,333			Success = ScheduledEnsureOriginSuccess<Self::AccountId>,334		>;335336		/// Compare the privileges of origins.337		///338		/// This will be used when canceling a task, to ensure that the origin that tries339		/// to cancel has greater or equal privileges as the origin that created the scheduled task.340		///341		/// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can342		/// be used. This will only check if two given origins are equal.343		type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;344345		/// The maximum number of scheduled calls in the queue for a single block.346		#[pallet::constant]347		type MaxScheduledPerBlock: Get<u32>;348349		/// Weight information for extrinsics in this pallet.350		type WeightInfo: WeightInfo;351352		/// The preimage provider with which we look up call hashes to get the call.353		type Preimages: SchedulerPreimages<Self>;354355		/// The helper type used for custom transaction fee logic.356		type CallExecutor: DispatchCall<Self, H160>;357358		/// Required origin to set/change calls' priority.359		type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::Origin>;360	}361362	#[pallet::storage]363	pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;364365	/// Items to be executed, indexed by the block number that they should be executed on.366	#[pallet::storage]367	pub type Agenda<T: Config> = StorageMap<368		_,369		Twox64Concat,370		T::BlockNumber,371		BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,372		ValueQuery,373	>;374375	/// Lookup from a name to the block number and index of the task.376	#[pallet::storage]377	pub(crate) type Lookup<T: Config> =378		StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;379380	/// Events type.381	#[pallet::event]382	#[pallet::generate_deposit(pub(super) fn deposit_event)]383	pub enum Event<T: Config> {384		/// Scheduled some task.385		Scheduled { when: T::BlockNumber, index: u32 },386		/// Canceled some task.387		Canceled { when: T::BlockNumber, index: u32 },388		/// Dispatched some task.389		Dispatched {390			task: TaskAddress<T::BlockNumber>,391			id: Option<[u8; 32]>,392			result: DispatchResult,393		},394		/// Scheduled task's priority has changed395		PriorityChanged {396			when: T::BlockNumber,397			index: u32,398			priority: schedule::Priority,399		},400		/// The call for the provided hash was not found so the task has been aborted.401		CallUnavailable {402			task: TaskAddress<T::BlockNumber>,403			id: Option<[u8; 32]>,404		},405		/// The given task was unable to be renewed since the agenda is full at that block.406		PeriodicFailed {407			task: TaskAddress<T::BlockNumber>,408			id: Option<[u8; 32]>,409		},410		/// The given task can never be executed since it is overweight.411		PermanentlyOverweight {412			task: TaskAddress<T::BlockNumber>,413			id: Option<[u8; 32]>,414		},415	}416417	#[pallet::error]418	pub enum Error<T> {419		/// Failed to schedule a call420		FailedToSchedule,421		/// There is no place for a new task in the agenda422		AgendaIsExhausted,423		/// Scheduled call is corrupted424		ScheduledCallCorrupted,425		/// Scheduled call preimage is not found426		PreimageNotFound,427		/// Scheduled call is too big428		TooBigScheduledCall,429		/// Cannot find the scheduled call.430		NotFound,431		/// Given target block number is in the past.432		TargetBlockNumberInPast,433		/// Reschedule failed because it does not change scheduled time.434		RescheduleNoChange,435		/// Attempt to use a non-named function on a named task.436		Named,437	}438439	#[pallet::hooks]440	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {441		/// Execute the scheduled calls442		fn on_initialize(now: T::BlockNumber) -> Weight {443			let mut weight_counter = WeightCounter {444				used: Weight::zero(),445				limit: T::MaximumWeight::get(),446			};447			Self::service_agendas(&mut weight_counter, now, u32::max_value());448			weight_counter.used449		}450	}451452	#[pallet::call]453	impl<T: Config> Pallet<T> {454		/// Anonymously schedule a task.455		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]456		pub fn schedule(457			origin: OriginFor<T>,458			when: T::BlockNumber,459			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,460			priority: Option<schedule::Priority>,461			call: Box<<T as Config>::Call>,462		) -> DispatchResult {463			T::ScheduleOrigin::ensure_origin(origin.clone())?;464465			if priority.is_some() {466				T::PrioritySetOrigin::ensure_origin(origin.clone())?;467			}468469			let origin = <T as Config>::Origin::from(origin);470			Self::do_schedule(471				DispatchTime::At(when),472				maybe_periodic,473				priority.unwrap_or(LOWEST_PRIORITY),474				origin.caller().clone(),475				<ScheduledCall<T>>::new(*call)?,476			)?;477			Ok(())478		}479480		/// Cancel an anonymously scheduled task.481		#[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]482		pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {483			T::ScheduleOrigin::ensure_origin(origin.clone())?;484			let origin = <T as Config>::Origin::from(origin);485			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;486			Ok(())487		}488489		/// Schedule a named task.490		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]491		pub fn schedule_named(492			origin: OriginFor<T>,493			id: TaskName,494			when: T::BlockNumber,495			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,496			priority: Option<schedule::Priority>,497			call: Box<<T as Config>::Call>,498		) -> DispatchResult {499			T::ScheduleOrigin::ensure_origin(origin.clone())?;500501			if priority.is_some() {502				T::PrioritySetOrigin::ensure_origin(origin.clone())?;503			}504505			let origin = <T as Config>::Origin::from(origin);506			Self::do_schedule_named(507				id,508				DispatchTime::At(when),509				maybe_periodic,510				priority.unwrap_or(LOWEST_PRIORITY),511				origin.caller().clone(),512				<ScheduledCall<T>>::new(*call)?,513			)?;514			Ok(())515		}516517		/// Cancel a named scheduled task.518		#[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]519		pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {520			T::ScheduleOrigin::ensure_origin(origin.clone())?;521			let origin = <T as Config>::Origin::from(origin);522			Self::do_cancel_named(Some(origin.caller().clone()), id)?;523			Ok(())524		}525526		/// Anonymously schedule a task after a delay.527		///528		/// # <weight>529		/// Same as [`schedule`].530		/// # </weight>531		#[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]532		pub fn schedule_after(533			origin: OriginFor<T>,534			after: T::BlockNumber,535			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,536			priority: Option<schedule::Priority>,537			call: Box<<T as Config>::Call>,538		) -> DispatchResult {539			T::ScheduleOrigin::ensure_origin(origin.clone())?;540541			if priority.is_some() {542				T::PrioritySetOrigin::ensure_origin(origin.clone())?;543			}544545			let origin = <T as Config>::Origin::from(origin);546			Self::do_schedule(547				DispatchTime::After(after),548				maybe_periodic,549				priority.unwrap_or(LOWEST_PRIORITY),550				origin.caller().clone(),551				<ScheduledCall<T>>::new(*call)?,552			)?;553			Ok(())554		}555556		/// Schedule a named task after a delay.557		///558		/// # <weight>559		/// Same as [`schedule_named`](Self::schedule_named).560		/// # </weight>561		#[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]562		pub fn schedule_named_after(563			origin: OriginFor<T>,564			id: TaskName,565			after: T::BlockNumber,566			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,567			priority: Option<schedule::Priority>,568			call: Box<<T as Config>::Call>,569		) -> DispatchResult {570			T::ScheduleOrigin::ensure_origin(origin.clone())?;571572			if priority.is_some() {573				T::PrioritySetOrigin::ensure_origin(origin.clone())?;574			}575576			let origin = <T as Config>::Origin::from(origin);577			Self::do_schedule_named(578				id,579				DispatchTime::After(after),580				maybe_periodic,581				priority.unwrap_or(LOWEST_PRIORITY),582				origin.caller().clone(),583				<ScheduledCall<T>>::new(*call)?,584			)?;585			Ok(())586		}587588		#[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]589		pub fn change_named_priority(590			origin: OriginFor<T>,591			id: TaskName,592			priority: schedule::Priority,593		) -> DispatchResult {594			T::PrioritySetOrigin::ensure_origin(origin.clone())?;595			let origin = <T as Config>::Origin::from(origin);596			Self::do_change_named_priority(origin.caller().clone(), id, priority)597		}598	}599}600601impl<T: Config> Pallet<T> {602	fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {603		let now = frame_system::Pallet::<T>::block_number();604605		let when = match when {606			DispatchTime::At(x) => x,607			// The current block has already completed it's scheduled tasks, so608			// Schedule the task at lest one block after this current block.609			DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),610		};611612		if when <= now {613			return Err(Error::<T>::TargetBlockNumberInPast.into());614		}615616		Ok(when)617	}618619	fn place_task(620		when: T::BlockNumber,621		what: ScheduledOf<T>,622	) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {623		let maybe_name = what.maybe_id;624		let index = Self::push_to_agenda(when, what)?;625		let address = (when, index);626		if let Some(name) = maybe_name {627			Lookup::<T>::insert(name, address)628		}629		Self::deposit_event(Event::Scheduled {630			when: address.0,631			index: address.1,632		});633		Ok(address)634	}635636	fn push_to_agenda(637		when: T::BlockNumber,638		what: ScheduledOf<T>,639	) -> Result<u32, (DispatchError, ScheduledOf<T>)> {640		let mut agenda = Agenda::<T>::get(when);641		let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {642			// will always succeed due to the above check.643			let _ = agenda.try_push(Some(what));644			agenda.len() as u32 - 1645		} else {646			if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {647				agenda[hole_index] = Some(what);648				hole_index as u32649			} else {650				return Err((<Error<T>>::AgendaIsExhausted.into(), what));651			}652		};653		Agenda::<T>::insert(when, agenda);654		Ok(index)655	}656657	fn do_schedule(658		when: DispatchTime<T::BlockNumber>,659		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,660		priority: schedule::Priority,661		origin: T::PalletsOrigin,662		call: ScheduledCall<T>,663	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {664		let when = Self::resolve_time(when)?;665666		// sanitize maybe_periodic667		let maybe_periodic = maybe_periodic668			.filter(|p| p.1 > 1 && !p.0.is_zero())669			// Remove one from the number of repetitions since we will schedule one now.670			.map(|(p, c)| (p, c - 1));671		let task = Scheduled {672			maybe_id: None,673			priority,674			call,675			maybe_periodic,676			origin,677			_phantom: PhantomData,678		};679		Self::place_task(when, task).map_err(|x| x.0)680	}681682	fn do_cancel(683		origin: Option<T::PalletsOrigin>,684		(when, index): TaskAddress<T::BlockNumber>,685	) -> Result<(), DispatchError> {686		let scheduled = Agenda::<T>::try_mutate(when, |agenda| {687			agenda.get_mut(index as usize).map_or(688				Ok(None),689				|s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {690					if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {691						if matches!(692							T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),693							Some(Ordering::Less) | None694						) {695							return Err(BadOrigin.into());696						}697					};698					Ok(s.take())699				},700			)701		})?;702		if let Some(s) = scheduled {703			T::Preimages::drop(&s.call);704705			if let Some(id) = s.maybe_id {706				Lookup::<T>::remove(id);707			}708			Self::deposit_event(Event::Canceled { when, index });709			Ok(())710		} else {711			return Err(Error::<T>::NotFound.into());712		}713	}714715	fn do_schedule_named(716		id: TaskName,717		when: DispatchTime<T::BlockNumber>,718		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,719		priority: schedule::Priority,720		origin: T::PalletsOrigin,721		call: ScheduledCall<T>,722	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {723		// ensure id it is unique724		if Lookup::<T>::contains_key(&id) {725			return Err(Error::<T>::FailedToSchedule.into());726		}727728		let when = Self::resolve_time(when)?;729730		// sanitize maybe_periodic731		let maybe_periodic = maybe_periodic732			.filter(|p| p.1 > 1 && !p.0.is_zero())733			// Remove one from the number of repetitions since we will schedule one now.734			.map(|(p, c)| (p, c - 1));735736		let task = Scheduled {737			maybe_id: Some(id),738			priority,739			call,740			maybe_periodic,741			origin,742			_phantom: Default::default(),743		};744		Self::place_task(when, task).map_err(|x| x.0)745	}746747	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {748		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {749			if let Some((when, index)) = lookup.take() {750				let i = index as usize;751				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {752					if let Some(s) = agenda.get_mut(i) {753						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {754							if matches!(755								T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),756								Some(Ordering::Less) | None757							) {758								return Err(BadOrigin.into());759							}760							T::Preimages::drop(&s.call);761						}762						*s = None;763					}764					Ok(())765				})?;766				Self::deposit_event(Event::Canceled { when, index });767				Ok(())768			} else {769				return Err(Error::<T>::NotFound.into());770			}771		})772	}773774	fn do_change_named_priority(775		origin: T::PalletsOrigin,776		id: TaskName,777		priority: schedule::Priority,778	) -> DispatchResult {779		match Lookup::<T>::get(id) {780			Some((when, index)) => {781				let i = index as usize;782				Agenda::<T>::try_mutate(when, |agenda| {783					if let Some(Some(s)) = agenda.get_mut(i) {784						if matches!(785							T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),786							Some(Ordering::Less) | None787						) {788							return Err(BadOrigin.into());789						}790791						s.priority = priority;792						Self::deposit_event(Event::PriorityChanged {793							when,794							index,795							priority,796						});797					}798					Ok(())799				})800			}801			None => Err(Error::<T>::NotFound.into()),802		}803	}804}805806enum ServiceTaskError {807	/// Could not be executed due to missing preimage.808	Unavailable,809	/// Could not be executed due to weight limitations.810	Overweight,811}812use ServiceTaskError::*;813814/// A Scheduler-Runtime interface for finer payment handling.815pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {816	/// Resolve the call dispatch, including any post-dispatch operations.817	fn dispatch_call(818		signer: Option<T::AccountId>,819		function: <T as Config>::Call,820	) -> Result<821		Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,822		TransactionValidityError,823	>;824}825826impl<T: Config> Pallet<T> {827	/// Service up to `max` agendas queue starting from earliest incompletely executed agenda.828	fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {829		if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {830			return;831		}832833		let mut incomplete_since = now + One::one();834		let mut when = IncompleteSince::<T>::take().unwrap_or(now);835		let mut executed = 0;836837		let max_items = T::MaxScheduledPerBlock::get();838		let mut count_down = max;839		let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);840		while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {841			if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {842				incomplete_since = incomplete_since.min(when);843			}844			when.saturating_inc();845			count_down.saturating_dec();846		}847		incomplete_since = incomplete_since.min(when);848		if incomplete_since <= now {849			IncompleteSince::<T>::put(incomplete_since);850		}851	}852853	/// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a854	/// later block.855	fn service_agenda(856		weight: &mut WeightCounter,857		executed: &mut u32,858		now: T::BlockNumber,859		when: T::BlockNumber,860		max: u32,861	) -> bool {862		let mut agenda = Agenda::<T>::get(when);863		let mut ordered = agenda864			.iter()865			.enumerate()866			.filter_map(|(index, maybe_item)| {867				maybe_item868					.as_ref()869					.map(|item| (index as u32, item.priority))870			})871			.collect::<Vec<_>>();872		ordered.sort_by_key(|k| k.1);873		let within_limit =874			weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));875		debug_assert!(876			within_limit,877			"weight limit should have been checked in advance"878		);879880		// Items which we know can be executed and have postponed for execution in a later block.881		let mut postponed = (ordered.len() as u32).saturating_sub(max);882		// Items which we don't know can ever be executed.883		let mut dropped = 0;884885		for (agenda_index, _) in ordered.into_iter().take(max as usize) {886			let task = match agenda[agenda_index as usize].take() {887				None => continue,888				Some(t) => t,889			};890			let base_weight = T::WeightInfo::service_task(891				task.call.lookup_len().map(|x| x as usize),892				task.maybe_id.is_some(),893				task.maybe_periodic.is_some(),894			);895			if !weight.can_accrue(base_weight) {896				postponed += 1;897				break;898			}899			let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);900			agenda[agenda_index as usize] = match result {901				Err((Unavailable, slot)) => {902					dropped += 1;903					slot904				}905				Err((Overweight, slot)) => {906					postponed += 1;907					slot908				}909				Ok(()) => {910					*executed += 1;911					None912				}913			};914		}915		if postponed > 0 || dropped > 0 {916			Agenda::<T>::insert(when, agenda);917		} else {918			Agenda::<T>::remove(when);919		}920		postponed == 0921	}922923	/// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.924	///925	/// This involves:926	/// - removing and potentially replacing the `Lookup` entry for the task.927	/// - realizing the task's call which can include a preimage lookup.928	/// - Rescheduling the task for execution in a later agenda if periodic.929	fn service_task(930		weight: &mut WeightCounter,931		now: T::BlockNumber,932		when: T::BlockNumber,933		agenda_index: u32,934		is_first: bool,935		mut task: ScheduledOf<T>,936	) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {937		let (call, lookup_len) = match T::Preimages::peek(&task.call) {938			Ok(c) => c,939			Err(_) => {940				if let Some(ref id) = task.maybe_id {941					Lookup::<T>::remove(id);942				}943944				return Err((Unavailable, Some(task)));945			},946		};947948		weight.check_accrue(T::WeightInfo::service_task(949			lookup_len.map(|x| x as usize),950			task.maybe_id.is_some(),951			task.maybe_periodic.is_some(),952		));953954		match Self::execute_dispatch(weight, task.origin.clone(), call) {955			Err(Unavailable) => {956				debug_assert!(false, "Checked to exist with `peek`");957958				if let Some(ref id) = task.maybe_id {959					Lookup::<T>::remove(id);960				}961962				Self::deposit_event(Event::CallUnavailable {963					task: (when, agenda_index),964					id: task.maybe_id,965				});966				Err((Unavailable, Some(task)))967			}968			Err(Overweight) if is_first => {969				T::Preimages::drop(&task.call);970971				if let Some(ref id) = task.maybe_id {972					Lookup::<T>::remove(id);973				}974975				Self::deposit_event(Event::PermanentlyOverweight {976					task: (when, agenda_index),977					id: task.maybe_id,978				});979				Err((Unavailable, Some(task)))980			}981			Err(Overweight) => {982				// Preserve Lookup -- the task will be postponed.983				Err((Overweight, Some(task)))984			},985			Ok(result) => {986				Self::deposit_event(Event::Dispatched {987					task: (when, agenda_index),988					id: task.maybe_id,989					result,990				});991992				let is_canceled = task.maybe_id.as_ref()993					.map(|id| !Lookup::<T>::contains_key(id))994					.unwrap_or(false);995996				match &task.maybe_periodic {997					&Some((period, count)) if !is_canceled => {998						if count > 1 {999							task.maybe_periodic = Some((period, count - 1));1000						} else {1001							task.maybe_periodic = None;1002						}1003						let wake = now.saturating_add(period);1004						match Self::place_task(wake, task) {1005							Ok(_) => {}1006							Err((_, task)) => {1007								// TODO: Leave task in storage somewhere for it to be rescheduled1008								// manually.1009								T::Preimages::drop(&task.call);1010								Self::deposit_event(Event::PeriodicFailed {1011									task: (when, agenda_index),1012									id: task.maybe_id,1013								});1014							}1015						}1016					},1017					_ => {1018						if let Some(ref id) = task.maybe_id {1019							Lookup::<T>::remove(id);1020						}10211022						T::Preimages::drop(&task.call)1023					},1024				}1025				Ok(())1026			}1027		}1028	}10291030	/// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1031	/// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1032	/// post info if available).1033	///1034	/// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1035	/// call itself).1036	fn execute_dispatch(1037		weight: &mut WeightCounter,1038		origin: T::PalletsOrigin,1039		call: <T as Config>::Call,1040	) -> Result<DispatchResult, ServiceTaskError> {1041		let dispatch_origin: <T as Config>::Origin = origin.into();1042		let base_weight = match dispatch_origin.clone().as_signed() {1043			Some(_) => T::WeightInfo::execute_dispatch_signed(),1044			_ => T::WeightInfo::execute_dispatch_unsigned(),1045		};1046		let call_weight = call.get_dispatch_info().weight;1047		// We only allow a scheduled call if it cannot push the weight past the limit.1048		let max_weight = base_weight.saturating_add(call_weight);10491050		if !weight.can_accrue(max_weight) {1051			return Err(Overweight);1052		}10531054		// let scheduled_origin =1055		// 	<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());1056		let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());10571058		let r = match ensured_origin {1059			Ok(ScheduledEnsureOriginSuccess::Root) => {1060				Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1061			},1062			Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1063				// Execute transaction via chain default pipeline1064				// That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1065				T::CallExecutor::dispatch_call(Some(sender), call.clone())1066			},1067			Ok(ScheduledEnsureOriginSuccess::Unsigned) => {1068				// Unsigned version of the above1069				T::CallExecutor::dispatch_call(None, call.clone())1070			}1071			Err(e) => Ok(Err(e.into())),1072		};10731074		let (maybe_actual_call_weight, result) = match r {1075			Ok(result) => match result {1076				Ok(post_info) => (post_info.actual_weight, Ok(())),1077				Err(error_and_info) => (1078					error_and_info.post_info.actual_weight,1079					Err(error_and_info.error),1080				),1081			},1082			Err(_) => {1083				log::error!(1084					target: "runtime::scheduler",1085					"Warning: Scheduler has failed to execute a post-dispatch transaction. \1086					This block might have become invalid.");1087				(None, Err(DispatchError::CannotLookup))1088			}1089		};1090		let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1091		weight.check_accrue(base_weight);1092		weight.check_accrue(call_weight);1093		Ok(result)1094	}1095}
modifiedpallets/scheduler-v2/src/weights.rsdiffbeforeafterboth
--- a/pallets/scheduler-v2/src/weights.rs
+++ b/pallets/scheduler-v2/src/weights.rs
@@ -75,6 +75,7 @@
 	fn cancel(s: u32, ) -> Weight;
 	fn schedule_named(s: u32, ) -> Weight;
 	fn cancel_named(s: u32, ) -> Weight;
+	fn change_named_priority(s: u32, ) -> Weight;
 }
 
 /// Weights for pallet_scheduler using the Substrate node and recommended hardware.
@@ -161,6 +162,16 @@
 			.saturating_add(T::DbWeight::get().reads(2 as u64))
 			.saturating_add(T::DbWeight::get().writes(2 as u64))
 	}
+
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn change_named_priority(s: u32, ) -> Weight {
+		Weight::from_ref_time(8_642_000)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
+			.saturating_add(T::DbWeight::get().reads(2 as u64))
+			.saturating_add(T::DbWeight::get().writes(2 as u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -246,4 +257,14 @@
 			.saturating_add(RocksDbWeight::get().reads(2 as u64))
 			.saturating_add(RocksDbWeight::get().writes(2 as u64))
 	}
+
+	// Storage: Scheduler Lookup (r:1 w:1)
+	// Storage: Scheduler Agenda (r:1 w:1)
+	fn change_named_priority(s: u32, ) -> Weight {
+		Weight::from_ref_time(8_642_000)
+			// Standard Error: 0
+			.saturating_add(Weight::from_ref_time(431_000).saturating_mul(s as u64))
+			.saturating_add(RocksDbWeight::get().reads(2 as u64))
+			.saturating_add(RocksDbWeight::get().writes(2 as u64))
+	}
 }
modifiedruntime/common/config/pallets/scheduler.rsdiffbeforeafterboth
--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -99,4 +99,5 @@
 	type WeightInfo = ();
 	type Preimages = ();
 	type CallExecutor = SchedulerPaymentExecutor;
+	type PrioritySetOrigin = EnsureRoot<AccountId>;
 }