difftreelog
fix(scheduler-v2) fix benchmarks
in: master
5 files changed
Makefilediffbeforeafterboth--- a/Makefile
+++ b/Makefile
@@ -118,7 +118,7 @@
.PHONY: bench-scheduler
bench-scheduler:
- make _bench PALLET=unique-scheduler PALLET_DIR=scheduler
+ make _bench PALLET=unique-scheduler-v2 PALLET_DIR=scheduler-v2
.PHONY: bench-rmrk-core
bench-rmrk-core:
pallets/scheduler-v2/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/benchmarking.rs
+++ b/pallets/scheduler-v2/src/benchmarking.rs
@@ -51,7 +51,7 @@
const BLOCK_NUMBER: u32 = 2;
-type SystemOrigin<T> = <T as frame_system::Config>::Origin;
+type SystemOrigin<T> = <T as frame_system::Config>::RuntimeOrigin;
/// Add `n` items to the schedule.
///
@@ -70,7 +70,7 @@
Scheduler::<T>::do_schedule_named(name, t, period, 0, origin.clone(), call)?;
}
ensure!(
- Agenda::<T>::get(when).len() == n as usize,
+ Agenda::<T>::get(when).agenda.len() == n as usize,
"didn't fill schedule"
);
Ok(())
@@ -108,7 +108,7 @@
}
fn bounded<T: Config>(len: u32) -> Option<ScheduledCall<T>> {
- let call = <<T as Config>::Call>::from(SystemCall::remark {
+ let call = <<T as Config>::RuntimeCall>::from(SystemCall::remark {
remark: vec![0; len as usize],
});
ScheduledCall::new(call).ok()
@@ -197,18 +197,19 @@
//assert_eq!(result, Ok(()));
}
- // `service_task` when the task is a non-periodic, non-named, fetched call (with a known
- // preimage length) and which is not dispatched (e.g. due to being overweight).
- service_task_fetched {
- let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());
- let now = BLOCK_NUMBER.into();
- let task = make_task::<T>(false, false, false, Some(s), 0);
- // prevent any tasks from actually being executed as we only want the surrounding weight.
- let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
- }: {
- let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
- } verify {
- }
+ // TODO uncomment if we will use the Preimages
+ // // `service_task` when the task is a non-periodic, non-named, fetched call (with a known
+ // // preimage length) and which is not dispatched (e.g. due to being overweight).
+ // service_task_fetched {
+ // let s in (EncodedCall::bound() as u32) .. (<T::Preimages as PreimageRecipient<T::Hash>>::MaxSize::get());
+ // let now = BLOCK_NUMBER.into();
+ // let task = make_task::<T>(false, false, false, Some(s), 0);
+ // // prevent any tasks from actually being executed as we only want the surrounding weight.
+ // let mut counter = WeightCounter { used: Weight::zero(), limit: Weight::zero() };
+ // }: {
+ // let result = Scheduler::<T>::service_task(&mut counter, now, now, 0, true, task);
+ // } verify {
+ // }
// `service_task` when the task is a non-periodic, named, non-fetched call which is not
// dispatched (e.g. due to being overweight).
@@ -268,7 +269,7 @@
}: _(RawOrigin::Root, when, periodic, priority, call)
verify {
ensure!(
- Agenda::<T>::get(when).len() == (s + 1) as usize,
+ Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,
"didn't add to schedule"
);
}
@@ -278,7 +279,7 @@
let when = BLOCK_NUMBER.into();
fill_schedule::<T>(when, s)?;
- assert_eq!(Agenda::<T>::get(when).len(), s as usize);
+ assert_eq!(Agenda::<T>::get(when).agenda.len(), s as usize);
let schedule_origin = T::ScheduleOrigin::successful_origin();
}: _<SystemOrigin<T>>(schedule_origin, when, 0)
verify {
@@ -288,7 +289,7 @@
);
// Removed schedule is NONE
ensure!(
- Agenda::<T>::get(when)[0].is_none(),
+ Agenda::<T>::get(when).agenda[0].is_none(),
"didn't remove from schedule"
);
}
@@ -306,7 +307,7 @@
}: _(RawOrigin::Root, id, when, periodic, priority, call)
verify {
ensure!(
- Agenda::<T>::get(when).len() == (s + 1) as usize,
+ Agenda::<T>::get(when).agenda.len() == (s + 1) as usize,
"didn't add to schedule"
);
}
@@ -324,7 +325,7 @@
);
// Removed schedule is NONE
ensure!(
- Agenda::<T>::get(when)[0].is_none(),
+ Agenda::<T>::get(when).agenda[0].is_none(),
"didn't remove from schedule"
);
}
@@ -340,7 +341,7 @@
}: _(origin, id, priority)
verify {
ensure!(
- Agenda::<T>::get(when)[idx as usize].clone().unwrap().priority == priority,
+ Agenda::<T>::get(when).agenda[idx as usize].clone().unwrap().priority == priority,
"didn't change the priority"
);
}
pallets/scheduler-v2/src/lib.rsdiffbeforeafterboth1// 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::{81 DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,82 },83 traits::{84 schedule::{self, DispatchTime, LOWEST_PRIORITY},85 EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,86 ConstU32, UnfilteredDispatchable,87 },88 weights::Weight,89 unsigned::TransactionValidityError,90};9192use frame_system::{self as system};93use scale_info::TypeInfo;94use sp_runtime::{95 traits::{BadOrigin, One, Saturating, Zero, Hash},96 BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,97};98use sp_core::H160;99use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};100pub use weights::WeightInfo;101102pub use pallet::*;103104/// Just a simple index for naming period tasks.105pub type PeriodicIndex = u32;106/// The location of a scheduled task that can be used to remove it.107pub type TaskAddress<BlockNumber> = (BlockNumber, u32);108109pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;110111#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]112#[scale_info(skip_type_params(T))]113pub enum ScheduledCall<T: Config> {114 Inline(EncodedCall),115 PreimageLookup { hash: T::Hash, unbounded_len: u32 },116}117118impl<T: Config> ScheduledCall<T> {119 pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {120 let encoded = call.encode();121 let len = encoded.len();122123 match EncodedCall::try_from(encoded.clone()) {124 Ok(bounded) => Ok(Self::Inline(bounded)),125 Err(_) => {126 let hash = <T as system::Config>::Hashing::hash_of(&encoded);127 <T as Config>::Preimages::note_preimage(128 encoded129 .try_into()130 .map_err(|_| <Error<T>>::TooBigScheduledCall)?,131 );132133 Ok(Self::PreimageLookup {134 hash,135 unbounded_len: len as u32,136 })137 }138 }139 }140141 /// The maximum length of the lookup that is needed to peek `Self`.142 pub fn lookup_len(&self) -> Option<u32> {143 match self {144 Self::Inline(..) => None,145 Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),146 }147 }148149 /// Returns whether the image will require a lookup to be peeked.150 pub fn lookup_needed(&self) -> bool {151 match self {152 Self::Inline(_) => false,153 Self::PreimageLookup { .. } => true,154 }155 }156157 fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {158 <T as Config>::RuntimeCall::decode(&mut data)159 .map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())160 }161}162163pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {164 fn drop(call: &ScheduledCall<T>);165166 fn peek(167 call: &ScheduledCall<T>,168 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;169170 /// Convert the given scheduled `call` value back into its original instance. If successful,171 /// `drop` any data backing it. This will not break the realisability of independently172 /// created instances of `ScheduledCall` which happen to have identical data.173 fn realize(174 call: &ScheduledCall<T>,175 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;176}177178impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {179 fn drop(call: &ScheduledCall<T>) {180 match call {181 ScheduledCall::Inline(_) => {}182 ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),183 }184 }185186 fn peek(187 call: &ScheduledCall<T>,188 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {189 match call {190 ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),191 ScheduledCall::PreimageLookup {192 hash,193 unbounded_len,194 } => {195 let (preimage, len) = Self::get_preimage(hash)196 .ok_or(<Error<T>>::PreimageNotFound)197 .map(|preimage| (preimage, *unbounded_len))?;198199 Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))200 }201 }202 }203204 fn realize(205 call: &ScheduledCall<T>,206 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {207 let r = Self::peek(call)?;208 Self::drop(call);209 Ok(r)210 }211}212213pub enum ScheduledEnsureOriginSuccess<AccountId> {214 Root,215 Signed(AccountId),216}217218pub type TaskName = [u8; 32];219220/// Information regarding an item to be executed in the future.221#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]222#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]223pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {224 /// The unique identity for this task, if there is one.225 maybe_id: Option<Name>,226227 /// This task's priority.228 priority: schedule::Priority,229230 /// The call to be dispatched.231 call: Call,232233 /// If the call is periodic, then this points to the information concerning that.234 maybe_periodic: Option<schedule::Period<BlockNumber>>,235236 /// The origin with which to dispatch the call.237 origin: PalletsOrigin,238 _phantom: PhantomData<AccountId>,239}240241pub type ScheduledOf<T> = Scheduled<242 TaskName,243 ScheduledCall<T>,244 <T as frame_system::Config>::BlockNumber,245 <T as Config>::PalletsOrigin,246 <T as frame_system::Config>::AccountId,247>;248249#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]250#[scale_info(skip_type_params(T))]251pub struct BlockAgenda<T: Config> {252 agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,253 free_places: u32,254}255256impl<T: Config> BlockAgenda<T> {257 fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {258 if self.free_places == 0 {259 return Err(scheduled);260 }261262 self.free_places = self.free_places.saturating_sub(1);263264 if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {265 // will always succeed due to the above check.266 let _ = self.agenda.try_push(Some(scheduled));267 Ok((self.agenda.len() - 1) as u32)268 } else {269 match self.agenda.iter().position(|i| i.is_none()) {270 Some(hole_index) => {271 self.agenda[hole_index] = Some(scheduled);272 Ok(hole_index as u32)273 }274 None => unreachable!("free_places was greater than 0; qed"),275 }276 }277 }278279 fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {280 self.agenda[index as usize] = slot;281 }282283 fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {284 self.agenda.iter()285 }286287 fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {288 match self.agenda.get(index as usize) {289 Some(Some(scheduled)) => Some(scheduled),290 _ => None,291 }292 }293294 fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {295 match self.agenda.get_mut(index as usize) {296 Some(Some(scheduled)) => Some(scheduled),297 _ => None,298 }299 }300301 fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {302 let removed = self.agenda.get_mut(index as usize)?.take();303304 if removed.is_some() {305 self.free_places = self.free_places.saturating_add(1);306 }307308 removed309 }310}311312impl<T: Config> Default for BlockAgenda<T> {313 fn default() -> Self {314 let agenda = Default::default();315 let free_places = T::MaxScheduledPerBlock::get();316317 Self {318 agenda,319 free_places,320 }321 }322}323324struct WeightCounter {325 used: Weight,326 limit: Weight,327}328329impl WeightCounter {330 fn check_accrue(&mut self, w: Weight) -> bool {331 let test = self.used.saturating_add(w);332 if test.any_gt(self.limit) {333 false334 } else {335 self.used = test;336 true337 }338 }339340 fn can_accrue(&mut self, w: Weight) -> bool {341 self.used.saturating_add(w).all_lte(self.limit)342 }343}344345pub(crate) trait MarginalWeightInfo: WeightInfo {346 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {347 let base = Self::service_task_base();348 let mut total = match maybe_lookup_len {349 None => base,350 Some(l) => Self::service_task_fetched(l as u32),351 };352 if named {353 total.saturating_accrue(Self::service_task_named().saturating_sub(base));354 }355 if periodic {356 total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));357 }358 total359 }360}361362impl<T: WeightInfo> MarginalWeightInfo for T {}363364#[frame_support::pallet]365pub mod pallet {366 use super::*;367 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};368 use system::pallet_prelude::*;369370 /// The current storage version.371 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);372373 #[pallet::pallet]374 #[pallet::generate_store(pub(super) trait Store)]375 #[pallet::storage_version(STORAGE_VERSION)]376 pub struct Pallet<T>(_);377378 #[pallet::config]379 pub trait Config: frame_system::Config {380 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;381382 /// The aggregated origin which the dispatch will take.383 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>384 + From<Self::PalletsOrigin>385 + IsType<<Self as system::Config>::RuntimeOrigin>386 + Clone;387388 /// The caller origin, overarching type of all pallets origins.389 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>390 + Codec391 + Clone392 + Eq393 + TypeInfo394 + MaxEncodedLen;395396 /// The aggregated call type.397 type RuntimeCall: Parameter398 + Dispatchable<399 RuntimeOrigin = <Self as Config>::RuntimeOrigin,400 PostInfo = PostDispatchInfo,401 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>402 + GetDispatchInfo403 + From<system::Call<Self>>;404405 /// The maximum weight that may be scheduled per block for any dispatchables.406 #[pallet::constant]407 type MaximumWeight: Get<Weight>;408409 /// Required origin to schedule or cancel calls.410 type ScheduleOrigin: EnsureOrigin<411 <Self as system::Config>::RuntimeOrigin,412 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,413 >;414415 /// Compare the privileges of origins.416 ///417 /// This will be used when canceling a task, to ensure that the origin that tries418 /// to cancel has greater or equal privileges as the origin that created the scheduled task.419 ///420 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can421 /// be used. This will only check if two given origins are equal.422 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;423424 /// The maximum number of scheduled calls in the queue for a single block.425 #[pallet::constant]426 type MaxScheduledPerBlock: Get<u32>;427428 /// Weight information for extrinsics in this pallet.429 type WeightInfo: WeightInfo;430431 /// The preimage provider with which we look up call hashes to get the call.432 type Preimages: SchedulerPreimages<Self>;433434 /// The helper type used for custom transaction fee logic.435 type CallExecutor: DispatchCall<Self, H160>;436437 /// Required origin to set/change calls' priority.438 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;439 }440441 #[pallet::storage]442 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;443444 /// Items to be executed, indexed by the block number that they should be executed on.445 #[pallet::storage]446 pub type Agenda<T: Config> =447 StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;448449 /// Lookup from a name to the block number and index of the task.450 #[pallet::storage]451 pub(crate) type Lookup<T: Config> =452 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;453454 /// Events type.455 #[pallet::event]456 #[pallet::generate_deposit(pub(super) fn deposit_event)]457 pub enum Event<T: Config> {458 /// Scheduled some task.459 Scheduled { when: T::BlockNumber, index: u32 },460 /// Canceled some task.461 Canceled { when: T::BlockNumber, index: u32 },462 /// Dispatched some task.463 Dispatched {464 task: TaskAddress<T::BlockNumber>,465 id: Option<[u8; 32]>,466 result: DispatchResult,467 },468 /// Scheduled task's priority has changed469 PriorityChanged {470 when: T::BlockNumber,471 index: u32,472 priority: schedule::Priority,473 },474 /// The call for the provided hash was not found so the task has been aborted.475 CallUnavailable {476 task: TaskAddress<T::BlockNumber>,477 id: Option<[u8; 32]>,478 },479 /// The given task can never be executed since it is overweight.480 PermanentlyOverweight {481 task: TaskAddress<T::BlockNumber>,482 id: Option<[u8; 32]>,483 },484 }485486 #[pallet::error]487 pub enum Error<T> {488 /// Failed to schedule a call489 FailedToSchedule,490 /// There is no place for a new task in the agenda491 AgendaIsExhausted,492 /// Scheduled call is corrupted493 ScheduledCallCorrupted,494 /// Scheduled call preimage is not found495 PreimageNotFound,496 /// Scheduled call is too big497 TooBigScheduledCall,498 /// Cannot find the scheduled call.499 NotFound,500 /// Given target block number is in the past.501 TargetBlockNumberInPast,502 /// Attempt to use a non-named function on a named task.503 Named,504 }505506 #[pallet::hooks]507 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {508 /// Execute the scheduled calls509 fn on_initialize(now: T::BlockNumber) -> Weight {510 let mut weight_counter = WeightCounter {511 used: Weight::zero(),512 limit: T::MaximumWeight::get(),513 };514 Self::service_agendas(&mut weight_counter, now, u32::max_value());515 weight_counter.used516 }517 }518519 #[pallet::call]520 impl<T: Config> Pallet<T> {521 /// Anonymously schedule a task.522 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]523 pub fn schedule(524 origin: OriginFor<T>,525 when: T::BlockNumber,526 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,527 priority: Option<schedule::Priority>,528 call: Box<<T as Config>::RuntimeCall>,529 ) -> DispatchResult {530 T::ScheduleOrigin::ensure_origin(origin.clone())?;531532 if priority.is_some() {533 T::PrioritySetOrigin::ensure_origin(origin.clone())?;534 }535536 let origin = <T as Config>::RuntimeOrigin::from(origin);537 Self::do_schedule(538 DispatchTime::At(when),539 maybe_periodic,540 priority.unwrap_or(LOWEST_PRIORITY),541 origin.caller().clone(),542 <ScheduledCall<T>>::new(*call)?,543 )?;544 Ok(())545 }546547 /// Cancel an anonymously scheduled task.548 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]549 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {550 T::ScheduleOrigin::ensure_origin(origin.clone())?;551 let origin = <T as Config>::RuntimeOrigin::from(origin);552 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;553 Ok(())554 }555556 /// Schedule a named task.557 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]558 pub fn schedule_named(559 origin: OriginFor<T>,560 id: TaskName,561 when: T::BlockNumber,562 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,563 priority: Option<schedule::Priority>,564 call: Box<<T as Config>::RuntimeCall>,565 ) -> DispatchResult {566 T::ScheduleOrigin::ensure_origin(origin.clone())?;567568 if priority.is_some() {569 T::PrioritySetOrigin::ensure_origin(origin.clone())?;570 }571572 let origin = <T as Config>::RuntimeOrigin::from(origin);573 Self::do_schedule_named(574 id,575 DispatchTime::At(when),576 maybe_periodic,577 priority.unwrap_or(LOWEST_PRIORITY),578 origin.caller().clone(),579 <ScheduledCall<T>>::new(*call)?,580 )?;581 Ok(())582 }583584 /// Cancel a named scheduled task.585 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]586 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {587 T::ScheduleOrigin::ensure_origin(origin.clone())?;588 let origin = <T as Config>::RuntimeOrigin::from(origin);589 Self::do_cancel_named(Some(origin.caller().clone()), id)?;590 Ok(())591 }592593 /// Anonymously schedule a task after a delay.594 ///595 /// # <weight>596 /// Same as [`schedule`].597 /// # </weight>598 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]599 pub fn schedule_after(600 origin: OriginFor<T>,601 after: T::BlockNumber,602 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,603 priority: Option<schedule::Priority>,604 call: Box<<T as Config>::RuntimeCall>,605 ) -> DispatchResult {606 T::ScheduleOrigin::ensure_origin(origin.clone())?;607608 if priority.is_some() {609 T::PrioritySetOrigin::ensure_origin(origin.clone())?;610 }611612 let origin = <T as Config>::RuntimeOrigin::from(origin);613 Self::do_schedule(614 DispatchTime::After(after),615 maybe_periodic,616 priority.unwrap_or(LOWEST_PRIORITY),617 origin.caller().clone(),618 <ScheduledCall<T>>::new(*call)?,619 )?;620 Ok(())621 }622623 /// Schedule a named task after a delay.624 ///625 /// # <weight>626 /// Same as [`schedule_named`](Self::schedule_named).627 /// # </weight>628 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]629 pub fn schedule_named_after(630 origin: OriginFor<T>,631 id: TaskName,632 after: T::BlockNumber,633 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,634 priority: Option<schedule::Priority>,635 call: Box<<T as Config>::RuntimeCall>,636 ) -> DispatchResult {637 T::ScheduleOrigin::ensure_origin(origin.clone())?;638639 if priority.is_some() {640 T::PrioritySetOrigin::ensure_origin(origin.clone())?;641 }642643 let origin = <T as Config>::RuntimeOrigin::from(origin);644 Self::do_schedule_named(645 id,646 DispatchTime::After(after),647 maybe_periodic,648 priority.unwrap_or(LOWEST_PRIORITY),649 origin.caller().clone(),650 <ScheduledCall<T>>::new(*call)?,651 )?;652 Ok(())653 }654655 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]656 pub fn change_named_priority(657 origin: OriginFor<T>,658 id: TaskName,659 priority: schedule::Priority,660 ) -> DispatchResult {661 T::PrioritySetOrigin::ensure_origin(origin.clone())?;662 let origin = <T as Config>::RuntimeOrigin::from(origin);663 Self::do_change_named_priority(origin.caller().clone(), id, priority)664 }665 }666}667668impl<T: Config> Pallet<T> {669 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {670 let now = frame_system::Pallet::<T>::block_number();671672 let when = match when {673 DispatchTime::At(x) => x,674 // The current block has already completed it's scheduled tasks, so675 // Schedule the task at lest one block after this current block.676 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),677 };678679 if when <= now {680 return Err(Error::<T>::TargetBlockNumberInPast.into());681 }682683 Ok(when)684 }685686 fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {687 Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");688 }689690 fn try_place_task(691 when: T::BlockNumber,692 what: ScheduledOf<T>,693 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {694 Self::place_task(when, what, false)695 }696697 fn place_task(698 mut when: T::BlockNumber,699 what: ScheduledOf<T>,700 is_mandatory: bool,701 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {702 let maybe_name = what.maybe_id;703 let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;704 let address = (when, index);705 if let Some(name) = maybe_name {706 Lookup::<T>::insert(name, address)707 }708 Self::deposit_event(Event::Scheduled {709 when: address.0,710 index: address.1,711 });712 Ok(address)713 }714715 fn push_to_agenda(716 when: &mut T::BlockNumber,717 mut what: ScheduledOf<T>,718 is_mandatory: bool,719 ) -> Result<u32, DispatchError> {720 let mut agenda;721722 let index = loop {723 agenda = Agenda::<T>::get(*when);724725 match agenda.try_push(what) {726 Ok(index) => break index,727 Err(returned_what) if is_mandatory => {728 what = returned_what;729 when.saturating_inc();730 }731 Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),732 }733 };734735 Agenda::<T>::insert(when, agenda);736 Ok(index)737 }738739 fn do_schedule(740 when: DispatchTime<T::BlockNumber>,741 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,742 priority: schedule::Priority,743 origin: T::PalletsOrigin,744 call: ScheduledCall<T>,745 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {746 let when = Self::resolve_time(when)?;747748 // sanitize maybe_periodic749 let maybe_periodic = maybe_periodic750 .filter(|p| p.1 > 1 && !p.0.is_zero())751 // Remove one from the number of repetitions since we will schedule one now.752 .map(|(p, c)| (p, c - 1));753 let task = Scheduled {754 maybe_id: None,755 priority,756 call,757 maybe_periodic,758 origin,759 _phantom: PhantomData,760 };761 Self::try_place_task(when, task)762 }763764 fn do_cancel(765 origin: Option<T::PalletsOrigin>,766 (when, index): TaskAddress<T::BlockNumber>,767 ) -> Result<(), DispatchError> {768 let scheduled = Agenda::<T>::try_mutate(769 when,770 |agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {771 let scheduled = match agenda.get(index) {772 Some(scheduled) => scheduled,773 None => return Ok(None),774 };775776 if let Some(ref o) = origin {777 if matches!(778 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),779 Some(Ordering::Less) | None780 ) {781 return Err(BadOrigin.into());782 }783 }784785 Ok(agenda.take(index))786 },787 )?;788 if let Some(s) = scheduled {789 T::Preimages::drop(&s.call);790791 if let Some(id) = s.maybe_id {792 Lookup::<T>::remove(id);793 }794 Self::deposit_event(Event::Canceled { when, index });795 Ok(())796 } else {797 Err(Error::<T>::NotFound.into())798 }799 }800801 fn do_schedule_named(802 id: TaskName,803 when: DispatchTime<T::BlockNumber>,804 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,805 priority: schedule::Priority,806 origin: T::PalletsOrigin,807 call: ScheduledCall<T>,808 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {809 // ensure id it is unique810 if Lookup::<T>::contains_key(&id) {811 return Err(Error::<T>::FailedToSchedule.into());812 }813814 let when = Self::resolve_time(when)?;815816 // sanitize maybe_periodic817 let maybe_periodic = maybe_periodic818 .filter(|p| p.1 > 1 && !p.0.is_zero())819 // Remove one from the number of repetitions since we will schedule one now.820 .map(|(p, c)| (p, c - 1));821822 let task = Scheduled {823 maybe_id: Some(id),824 priority,825 call,826 maybe_periodic,827 origin,828 _phantom: Default::default(),829 };830 Self::try_place_task(when, task)831 }832833 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {834 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {835 if let Some((when, index)) = lookup.take() {836 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {837 let scheduled = match agenda.get(index) {838 Some(scheduled) => scheduled,839 None => return Ok(()),840 };841842 if let Some(ref o) = origin {843 if matches!(844 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),845 Some(Ordering::Less) | None846 ) {847 return Err(BadOrigin.into());848 }849 T::Preimages::drop(&scheduled.call);850 }851852 agenda.take(index);853854 Ok(())855 })?;856 Self::deposit_event(Event::Canceled { when, index });857 Ok(())858 } else {859 Err(Error::<T>::NotFound.into())860 }861 })862 }863864 fn do_change_named_priority(865 origin: T::PalletsOrigin,866 id: TaskName,867 priority: schedule::Priority,868 ) -> DispatchResult {869 match Lookup::<T>::get(id) {870 Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {871 let scheduled = match agenda.get_mut(index) {872 Some(scheduled) => scheduled,873 None => return Ok(()),874 };875876 if matches!(877 T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),878 Some(Ordering::Less) | None879 ) {880 return Err(BadOrigin.into());881 }882883 scheduled.priority = priority;884 Self::deposit_event(Event::PriorityChanged {885 when,886 index,887 priority,888 });889890 Ok(())891 }),892 None => Err(Error::<T>::NotFound.into()),893 }894 }895}896897enum ServiceTaskError {898 /// Could not be executed due to missing preimage.899 Unavailable,900 /// Could not be executed due to weight limitations.901 Overweight,902}903use ServiceTaskError::*;904905/// A Scheduler-Runtime interface for finer payment handling.906pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {907 /// Resolve the call dispatch, including any post-dispatch operations.908 fn dispatch_call(909 signer: Option<T::AccountId>,910 function: <T as Config>::RuntimeCall,911 ) -> Result<912 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,913 TransactionValidityError,914 >;915}916917impl<T: Config> Pallet<T> {918 /// Service up to `max` agendas queue starting from earliest incompletely executed agenda.919 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {920 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {921 return;922 }923924 let mut incomplete_since = now + One::one();925 let mut when = IncompleteSince::<T>::take().unwrap_or(now);926 let mut executed = 0;927928 let max_items = T::MaxScheduledPerBlock::get();929 let mut count_down = max;930 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);931 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {932 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {933 incomplete_since = incomplete_since.min(when);934 }935 when.saturating_inc();936 count_down.saturating_dec();937 }938 incomplete_since = incomplete_since.min(when);939 if incomplete_since <= now {940 IncompleteSince::<T>::put(incomplete_since);941 }942 }943944 /// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a945 /// later block.946 fn service_agenda(947 weight: &mut WeightCounter,948 executed: &mut u32,949 now: T::BlockNumber,950 when: T::BlockNumber,951 max: u32,952 ) -> bool {953 let mut agenda = Agenda::<T>::get(when);954 let mut ordered = agenda955 .iter()956 .enumerate()957 .filter_map(|(index, maybe_item)| {958 maybe_item959 .as_ref()960 .map(|item| (index as u32, item.priority))961 })962 .collect::<Vec<_>>();963 ordered.sort_by_key(|k| k.1);964 let within_limit =965 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));966 debug_assert!(967 within_limit,968 "weight limit should have been checked in advance"969 );970971 // Items which we know can be executed and have postponed for execution in a later block.972 let mut postponed = (ordered.len() as u32).saturating_sub(max);973 // Items which we don't know can ever be executed.974 let mut dropped = 0;975976 for (agenda_index, _) in ordered.into_iter().take(max as usize) {977 let task = match agenda.take(agenda_index).take() {978 None => continue,979 Some(t) => t,980 };981 let base_weight = T::WeightInfo::service_task(982 task.call.lookup_len().map(|x| x as usize),983 task.maybe_id.is_some(),984 task.maybe_periodic.is_some(),985 );986 if !weight.can_accrue(base_weight) {987 postponed += 1;988 break;989 }990 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);991 match result {992 Err((Unavailable, slot)) => {993 dropped += 1;994 agenda.set_slot(agenda_index, slot);995 }996 Err((Overweight, slot)) => {997 postponed += 1;998 agenda.set_slot(agenda_index, slot);999 }1000 Ok(()) => {1001 *executed += 1;1002 }1003 };1004 }1005 if postponed > 0 || dropped > 0 {1006 Agenda::<T>::insert(when, agenda);1007 } else {1008 Agenda::<T>::remove(when);1009 }1010 postponed == 01011 }10121013 /// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.1014 ///1015 /// This involves:1016 /// - removing and potentially replacing the `Lookup` entry for the task.1017 /// - realizing the task's call which can include a preimage lookup.1018 /// - Rescheduling the task for execution in a later agenda if periodic.1019 fn service_task(1020 weight: &mut WeightCounter,1021 now: T::BlockNumber,1022 when: T::BlockNumber,1023 agenda_index: u32,1024 is_first: bool,1025 mut task: ScheduledOf<T>,1026 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1027 let (call, lookup_len) = match T::Preimages::peek(&task.call) {1028 Ok(c) => c,1029 Err(_) => {1030 if let Some(ref id) = task.maybe_id {1031 Lookup::<T>::remove(id);1032 }10331034 return Err((Unavailable, Some(task)));1035 }1036 };10371038 weight.check_accrue(T::WeightInfo::service_task(1039 lookup_len.map(|x| x as usize),1040 task.maybe_id.is_some(),1041 task.maybe_periodic.is_some(),1042 ));10431044 match Self::execute_dispatch(weight, task.origin.clone(), call) {1045 Err(Unavailable) => {1046 debug_assert!(false, "Checked to exist with `peek`");10471048 if let Some(ref id) = task.maybe_id {1049 Lookup::<T>::remove(id);1050 }10511052 Self::deposit_event(Event::CallUnavailable {1053 task: (when, agenda_index),1054 id: task.maybe_id,1055 });1056 Err((Unavailable, Some(task)))1057 }1058 Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1059 T::Preimages::drop(&task.call);10601061 if let Some(ref id) = task.maybe_id {1062 Lookup::<T>::remove(id);1063 }10641065 Self::deposit_event(Event::PermanentlyOverweight {1066 task: (when, agenda_index),1067 id: task.maybe_id,1068 });1069 Err((Unavailable, Some(task)))1070 }1071 Err(Overweight) => {1072 // Preserve Lookup -- the task will be postponed.1073 Err((Overweight, Some(task)))1074 }1075 Ok(result) => {1076 Self::deposit_event(Event::Dispatched {1077 task: (when, agenda_index),1078 id: task.maybe_id,1079 result,1080 });10811082 let is_canceled = task1083 .maybe_id1084 .as_ref()1085 .map(|id| !Lookup::<T>::contains_key(id))1086 .unwrap_or(false);10871088 match &task.maybe_periodic {1089 &Some((period, count)) if !is_canceled => {1090 if count > 1 {1091 task.maybe_periodic = Some((period, count - 1));1092 } else {1093 task.maybe_periodic = None;1094 }1095 let wake = now.saturating_add(period);1096 Self::mandatory_place_task(wake, task);1097 }1098 _ => {1099 if let Some(ref id) = task.maybe_id {1100 Lookup::<T>::remove(id);1101 }11021103 T::Preimages::drop(&task.call)1104 }1105 }1106 Ok(())1107 }1108 }1109 }11101111 fn is_runtime_upgraded() -> bool {1112 let last = system::LastRuntimeUpgrade::<T>::get();1113 let current = T::Version::get();11141115 last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)1116 }11171118 /// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1119 /// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1120 /// post info if available).1121 ///1122 /// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1123 /// call itself).1124 fn execute_dispatch(1125 weight: &mut WeightCounter,1126 origin: T::PalletsOrigin,1127 call: <T as Config>::RuntimeCall,1128 ) -> Result<DispatchResult, ServiceTaskError> {1129 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1130 let base_weight = match dispatch_origin.clone().as_signed() {1131 Some(_) => T::WeightInfo::execute_dispatch_signed(),1132 _ => T::WeightInfo::execute_dispatch_unsigned(),1133 };1134 let call_weight = call.get_dispatch_info().weight;1135 // We only allow a scheduled call if it cannot push the weight past the limit.1136 let max_weight = base_weight.saturating_add(call_weight);11371138 if !weight.can_accrue(max_weight) {1139 return Err(Overweight);1140 }11411142 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());11431144 let r = match ensured_origin {1145 Ok(ScheduledEnsureOriginSuccess::Root) => {1146 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1147 }1148 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1149 // Execute transaction via chain default pipeline1150 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1151 T::CallExecutor::dispatch_call(Some(sender), call)1152 }1153 Err(e) => Ok(Err(e.into())),1154 };11551156 let (maybe_actual_call_weight, result) = match r {1157 Ok(result) => match result {1158 Ok(post_info) => (post_info.actual_weight, Ok(())),1159 Err(error_and_info) => (1160 error_and_info.post_info.actual_weight,1161 Err(error_and_info.error),1162 ),1163 },1164 Err(_) => {1165 log::error!(1166 target: "runtime::scheduler",1167 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1168 This block might have become invalid.");1169 (None, Err(DispatchError::CannotLookup))1170 }1171 };1172 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1173 weight.check_accrue(base_weight);1174 weight.check_accrue(call_weight);1175 Ok(result)1176 }1177}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::{81 DispatchError, DispatchResult, Dispatchable, GetDispatchInfo, Parameter, PostDispatchInfo,82 },83 traits::{84 schedule::{self, DispatchTime, LOWEST_PRIORITY},85 EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion, PreimageRecipient,86 ConstU32, UnfilteredDispatchable,87 },88 weights::Weight,89 unsigned::TransactionValidityError,90};9192use frame_system::{self as system};93use scale_info::TypeInfo;94use sp_runtime::{95 traits::{BadOrigin, One, Saturating, Zero, Hash},96 BoundedVec, RuntimeDebug, DispatchErrorWithPostInfo,97};98use sp_core::H160;99use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*};100pub use weights::WeightInfo;101102pub use pallet::*;103104/// Just a simple index for naming period tasks.105pub type PeriodicIndex = u32;106/// The location of a scheduled task that can be used to remove it.107pub type TaskAddress<BlockNumber> = (BlockNumber, u32);108109pub type EncodedCall = BoundedVec<u8, ConstU32<128>>;110111#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo, MaxEncodedLen)]112#[scale_info(skip_type_params(T))]113pub enum ScheduledCall<T: Config> {114 Inline(EncodedCall),115 PreimageLookup { hash: T::Hash, unbounded_len: u32 },116}117118impl<T: Config> ScheduledCall<T> {119 pub fn new(call: <T as Config>::RuntimeCall) -> Result<Self, DispatchError> {120 let encoded = call.encode();121 let len = encoded.len();122123 match EncodedCall::try_from(encoded.clone()) {124 Ok(bounded) => Ok(Self::Inline(bounded)),125 Err(_) => {126 let hash = <T as system::Config>::Hashing::hash_of(&encoded);127 <T as Config>::Preimages::note_preimage(128 encoded129 .try_into()130 .map_err(|_| <Error<T>>::TooBigScheduledCall)?,131 );132133 Ok(Self::PreimageLookup {134 hash,135 unbounded_len: len as u32,136 })137 }138 }139 }140141 /// The maximum length of the lookup that is needed to peek `Self`.142 pub fn lookup_len(&self) -> Option<u32> {143 match self {144 Self::Inline(..) => None,145 Self::PreimageLookup { unbounded_len, .. } => Some(*unbounded_len),146 }147 }148149 /// Returns whether the image will require a lookup to be peeked.150 pub fn lookup_needed(&self) -> bool {151 match self {152 Self::Inline(_) => false,153 Self::PreimageLookup { .. } => true,154 }155 }156157 fn decode(mut data: &[u8]) -> Result<<T as Config>::RuntimeCall, DispatchError> {158 <T as Config>::RuntimeCall::decode(&mut data)159 .map_err(|_| <Error<T>>::ScheduledCallCorrupted.into())160 }161}162163pub trait SchedulerPreimages<T: Config>: PreimageRecipient<T::Hash> {164 fn drop(call: &ScheduledCall<T>);165166 fn peek(167 call: &ScheduledCall<T>,168 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;169170 /// Convert the given scheduled `call` value back into its original instance. If successful,171 /// `drop` any data backing it. This will not break the realisability of independently172 /// created instances of `ScheduledCall` which happen to have identical data.173 fn realize(174 call: &ScheduledCall<T>,175 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError>;176}177178impl<T: Config, PP: PreimageRecipient<T::Hash>> SchedulerPreimages<T> for PP {179 fn drop(call: &ScheduledCall<T>) {180 match call {181 ScheduledCall::Inline(_) => {}182 ScheduledCall::PreimageLookup { hash, .. } => Self::unrequest_preimage(hash),183 }184 }185186 fn peek(187 call: &ScheduledCall<T>,188 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {189 match call {190 ScheduledCall::Inline(data) => Ok((ScheduledCall::<T>::decode(data)?, None)),191 ScheduledCall::PreimageLookup {192 hash,193 unbounded_len,194 } => {195 let (preimage, len) = Self::get_preimage(hash)196 .ok_or(<Error<T>>::PreimageNotFound)197 .map(|preimage| (preimage, *unbounded_len))?;198199 Ok((ScheduledCall::<T>::decode(preimage.as_slice())?, Some(len)))200 }201 }202 }203204 fn realize(205 call: &ScheduledCall<T>,206 ) -> Result<(<T as pallet::Config>::RuntimeCall, Option<u32>), DispatchError> {207 let r = Self::peek(call)?;208 Self::drop(call);209 Ok(r)210 }211}212213pub enum ScheduledEnsureOriginSuccess<AccountId> {214 Root,215 Signed(AccountId),216}217218pub type TaskName = [u8; 32];219220/// Information regarding an item to be executed in the future.221#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]222#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]223pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {224 /// The unique identity for this task, if there is one.225 maybe_id: Option<Name>,226227 /// This task's priority.228 priority: schedule::Priority,229230 /// The call to be dispatched.231 call: Call,232233 /// If the call is periodic, then this points to the information concerning that.234 maybe_periodic: Option<schedule::Period<BlockNumber>>,235236 /// The origin with which to dispatch the call.237 origin: PalletsOrigin,238 _phantom: PhantomData<AccountId>,239}240241pub type ScheduledOf<T> = Scheduled<242 TaskName,243 ScheduledCall<T>,244 <T as frame_system::Config>::BlockNumber,245 <T as Config>::PalletsOrigin,246 <T as frame_system::Config>::AccountId,247>;248249#[derive(Encode, Decode, MaxEncodedLen, TypeInfo)]250#[scale_info(skip_type_params(T))]251pub struct BlockAgenda<T: Config> {252 agenda: BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,253 free_places: u32,254}255256impl<T: Config> BlockAgenda<T> {257 fn try_push(&mut self, scheduled: ScheduledOf<T>) -> Result<u32, ScheduledOf<T>> {258 if self.free_places == 0 {259 return Err(scheduled);260 }261262 self.free_places = self.free_places.saturating_sub(1);263264 if (self.agenda.len() as u32) < T::MaxScheduledPerBlock::get() {265 // will always succeed due to the above check.266 let _ = self.agenda.try_push(Some(scheduled));267 Ok((self.agenda.len() - 1) as u32)268 } else {269 match self.agenda.iter().position(|i| i.is_none()) {270 Some(hole_index) => {271 self.agenda[hole_index] = Some(scheduled);272 Ok(hole_index as u32)273 }274 None => unreachable!("free_places was greater than 0; qed"),275 }276 }277 }278279 fn set_slot(&mut self, index: u32, slot: Option<ScheduledOf<T>>) {280 self.agenda[index as usize] = slot;281 }282283 fn iter(&self) -> impl Iterator<Item = &'_ Option<ScheduledOf<T>>> + '_ {284 self.agenda.iter()285 }286287 fn get(&self, index: u32) -> Option<&ScheduledOf<T>> {288 match self.agenda.get(index as usize) {289 Some(Some(scheduled)) => Some(scheduled),290 _ => None,291 }292 }293294 fn get_mut(&mut self, index: u32) -> Option<&mut ScheduledOf<T>> {295 match self.agenda.get_mut(index as usize) {296 Some(Some(scheduled)) => Some(scheduled),297 _ => None,298 }299 }300301 fn take(&mut self, index: u32) -> Option<ScheduledOf<T>> {302 let removed = self.agenda.get_mut(index as usize)?.take();303304 if removed.is_some() {305 self.free_places = self.free_places.saturating_add(1);306 }307308 removed309 }310}311312impl<T: Config> Default for BlockAgenda<T> {313 fn default() -> Self {314 let agenda = Default::default();315 let free_places = T::MaxScheduledPerBlock::get();316317 Self {318 agenda,319 free_places,320 }321 }322}323324struct WeightCounter {325 used: Weight,326 limit: Weight,327}328329impl WeightCounter {330 fn check_accrue(&mut self, w: Weight) -> bool {331 let test = self.used.saturating_add(w);332 if test.any_gt(self.limit) {333 false334 } else {335 self.used = test;336 true337 }338 }339340 fn can_accrue(&mut self, w: Weight) -> bool {341 self.used.saturating_add(w).all_lte(self.limit)342 }343}344345pub(crate) trait MarginalWeightInfo: WeightInfo {346 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {347 let base = Self::service_task_base();348 let mut total = match maybe_lookup_len {349 None => base,350 Some(_l) => {351 // TODO uncomment if we will use the Preimages352 // Self::service_task_fetched(l as u32)353 base354 },355 };356 if named {357 total.saturating_accrue(Self::service_task_named().saturating_sub(base));358 }359 if periodic {360 total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));361 }362 total363 }364}365366impl<T: WeightInfo> MarginalWeightInfo for T {}367368#[frame_support::pallet]369pub mod pallet {370 use super::*;371 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};372 use system::pallet_prelude::*;373374 /// The current storage version.375 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);376377 #[pallet::pallet]378 #[pallet::generate_store(pub(super) trait Store)]379 #[pallet::storage_version(STORAGE_VERSION)]380 pub struct Pallet<T>(_);381382 #[pallet::config]383 pub trait Config: frame_system::Config {384 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;385386 /// The aggregated origin which the dispatch will take.387 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>388 + From<Self::PalletsOrigin>389 + IsType<<Self as system::Config>::RuntimeOrigin>390 + Clone;391392 /// The caller origin, overarching type of all pallets origins.393 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>394 + Codec395 + Clone396 + Eq397 + TypeInfo398 + MaxEncodedLen;399400 /// The aggregated call type.401 type RuntimeCall: Parameter402 + Dispatchable<403 RuntimeOrigin = <Self as Config>::RuntimeOrigin,404 PostInfo = PostDispatchInfo,405 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>406 + GetDispatchInfo407 + From<system::Call<Self>>;408409 /// The maximum weight that may be scheduled per block for any dispatchables.410 #[pallet::constant]411 type MaximumWeight: Get<Weight>;412413 /// Required origin to schedule or cancel calls.414 type ScheduleOrigin: EnsureOrigin<415 <Self as system::Config>::RuntimeOrigin,416 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,417 >;418419 /// Compare the privileges of origins.420 ///421 /// This will be used when canceling a task, to ensure that the origin that tries422 /// to cancel has greater or equal privileges as the origin that created the scheduled task.423 ///424 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can425 /// be used. This will only check if two given origins are equal.426 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;427428 /// The maximum number of scheduled calls in the queue for a single block.429 #[pallet::constant]430 type MaxScheduledPerBlock: Get<u32>;431432 /// Weight information for extrinsics in this pallet.433 type WeightInfo: WeightInfo;434435 /// The preimage provider with which we look up call hashes to get the call.436 type Preimages: SchedulerPreimages<Self>;437438 /// The helper type used for custom transaction fee logic.439 type CallExecutor: DispatchCall<Self, H160>;440441 /// Required origin to set/change calls' priority.442 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;443 }444445 #[pallet::storage]446 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;447448 /// Items to be executed, indexed by the block number that they should be executed on.449 #[pallet::storage]450 pub type Agenda<T: Config> =451 StorageMap<_, Twox64Concat, T::BlockNumber, BlockAgenda<T>, ValueQuery>;452453 /// Lookup from a name to the block number and index of the task.454 #[pallet::storage]455 pub(crate) type Lookup<T: Config> =456 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;457458 /// Events type.459 #[pallet::event]460 #[pallet::generate_deposit(pub(super) fn deposit_event)]461 pub enum Event<T: Config> {462 /// Scheduled some task.463 Scheduled { when: T::BlockNumber, index: u32 },464 /// Canceled some task.465 Canceled { when: T::BlockNumber, index: u32 },466 /// Dispatched some task.467 Dispatched {468 task: TaskAddress<T::BlockNumber>,469 id: Option<[u8; 32]>,470 result: DispatchResult,471 },472 /// Scheduled task's priority has changed473 PriorityChanged {474 when: T::BlockNumber,475 index: u32,476 priority: schedule::Priority,477 },478 /// The call for the provided hash was not found so the task has been aborted.479 CallUnavailable {480 task: TaskAddress<T::BlockNumber>,481 id: Option<[u8; 32]>,482 },483 /// The given task can never be executed since it is overweight.484 PermanentlyOverweight {485 task: TaskAddress<T::BlockNumber>,486 id: Option<[u8; 32]>,487 },488 }489490 #[pallet::error]491 pub enum Error<T> {492 /// Failed to schedule a call493 FailedToSchedule,494 /// There is no place for a new task in the agenda495 AgendaIsExhausted,496 /// Scheduled call is corrupted497 ScheduledCallCorrupted,498 /// Scheduled call preimage is not found499 PreimageNotFound,500 /// Scheduled call is too big501 TooBigScheduledCall,502 /// Cannot find the scheduled call.503 NotFound,504 /// Given target block number is in the past.505 TargetBlockNumberInPast,506 /// Attempt to use a non-named function on a named task.507 Named,508 }509510 #[pallet::hooks]511 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {512 /// Execute the scheduled calls513 fn on_initialize(now: T::BlockNumber) -> Weight {514 let mut weight_counter = WeightCounter {515 used: Weight::zero(),516 limit: T::MaximumWeight::get(),517 };518 Self::service_agendas(&mut weight_counter, now, u32::max_value());519 weight_counter.used520 }521 }522523 #[pallet::call]524 impl<T: Config> Pallet<T> {525 /// Anonymously schedule a task.526 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]527 pub fn schedule(528 origin: OriginFor<T>,529 when: T::BlockNumber,530 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,531 priority: Option<schedule::Priority>,532 call: Box<<T as Config>::RuntimeCall>,533 ) -> DispatchResult {534 T::ScheduleOrigin::ensure_origin(origin.clone())?;535536 if priority.is_some() {537 T::PrioritySetOrigin::ensure_origin(origin.clone())?;538 }539540 let origin = <T as Config>::RuntimeOrigin::from(origin);541 Self::do_schedule(542 DispatchTime::At(when),543 maybe_periodic,544 priority.unwrap_or(LOWEST_PRIORITY),545 origin.caller().clone(),546 <ScheduledCall<T>>::new(*call)?,547 )?;548 Ok(())549 }550551 /// Cancel an anonymously scheduled task.552 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]553 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {554 T::ScheduleOrigin::ensure_origin(origin.clone())?;555 let origin = <T as Config>::RuntimeOrigin::from(origin);556 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;557 Ok(())558 }559560 /// Schedule a named task.561 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]562 pub fn schedule_named(563 origin: OriginFor<T>,564 id: TaskName,565 when: T::BlockNumber,566 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,567 priority: Option<schedule::Priority>,568 call: Box<<T as Config>::RuntimeCall>,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>::RuntimeOrigin::from(origin);577 Self::do_schedule_named(578 id,579 DispatchTime::At(when),580 maybe_periodic,581 priority.unwrap_or(LOWEST_PRIORITY),582 origin.caller().clone(),583 <ScheduledCall<T>>::new(*call)?,584 )?;585 Ok(())586 }587588 /// Cancel a named scheduled task.589 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]590 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {591 T::ScheduleOrigin::ensure_origin(origin.clone())?;592 let origin = <T as Config>::RuntimeOrigin::from(origin);593 Self::do_cancel_named(Some(origin.caller().clone()), id)?;594 Ok(())595 }596597 /// Anonymously schedule a task after a delay.598 ///599 /// # <weight>600 /// Same as [`schedule`].601 /// # </weight>602 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]603 pub fn schedule_after(604 origin: OriginFor<T>,605 after: T::BlockNumber,606 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,607 priority: Option<schedule::Priority>,608 call: Box<<T as Config>::RuntimeCall>,609 ) -> DispatchResult {610 T::ScheduleOrigin::ensure_origin(origin.clone())?;611612 if priority.is_some() {613 T::PrioritySetOrigin::ensure_origin(origin.clone())?;614 }615616 let origin = <T as Config>::RuntimeOrigin::from(origin);617 Self::do_schedule(618 DispatchTime::After(after),619 maybe_periodic,620 priority.unwrap_or(LOWEST_PRIORITY),621 origin.caller().clone(),622 <ScheduledCall<T>>::new(*call)?,623 )?;624 Ok(())625 }626627 /// Schedule a named task after a delay.628 ///629 /// # <weight>630 /// Same as [`schedule_named`](Self::schedule_named).631 /// # </weight>632 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]633 pub fn schedule_named_after(634 origin: OriginFor<T>,635 id: TaskName,636 after: T::BlockNumber,637 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,638 priority: Option<schedule::Priority>,639 call: Box<<T as Config>::RuntimeCall>,640 ) -> DispatchResult {641 T::ScheduleOrigin::ensure_origin(origin.clone())?;642643 if priority.is_some() {644 T::PrioritySetOrigin::ensure_origin(origin.clone())?;645 }646647 let origin = <T as Config>::RuntimeOrigin::from(origin);648 Self::do_schedule_named(649 id,650 DispatchTime::After(after),651 maybe_periodic,652 priority.unwrap_or(LOWEST_PRIORITY),653 origin.caller().clone(),654 <ScheduledCall<T>>::new(*call)?,655 )?;656 Ok(())657 }658659 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]660 pub fn change_named_priority(661 origin: OriginFor<T>,662 id: TaskName,663 priority: schedule::Priority,664 ) -> DispatchResult {665 T::PrioritySetOrigin::ensure_origin(origin.clone())?;666 let origin = <T as Config>::RuntimeOrigin::from(origin);667 Self::do_change_named_priority(origin.caller().clone(), id, priority)668 }669 }670}671672impl<T: Config> Pallet<T> {673 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {674 let now = frame_system::Pallet::<T>::block_number();675676 let when = match when {677 DispatchTime::At(x) => x,678 // The current block has already completed it's scheduled tasks, so679 // Schedule the task at lest one block after this current block.680 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),681 };682683 if when <= now {684 return Err(Error::<T>::TargetBlockNumberInPast.into());685 }686687 Ok(when)688 }689690 fn mandatory_place_task(when: T::BlockNumber, what: ScheduledOf<T>) {691 Self::place_task(when, what, true).expect("mandatory place task always succeeds; qed");692 }693694 fn try_place_task(695 when: T::BlockNumber,696 what: ScheduledOf<T>,697 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {698 Self::place_task(when, what, false)699 }700701 fn place_task(702 mut when: T::BlockNumber,703 what: ScheduledOf<T>,704 is_mandatory: bool,705 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {706 let maybe_name = what.maybe_id;707 let index = Self::push_to_agenda(&mut when, what, is_mandatory)?;708 let address = (when, index);709 if let Some(name) = maybe_name {710 Lookup::<T>::insert(name, address)711 }712 Self::deposit_event(Event::Scheduled {713 when: address.0,714 index: address.1,715 });716 Ok(address)717 }718719 fn push_to_agenda(720 when: &mut T::BlockNumber,721 mut what: ScheduledOf<T>,722 is_mandatory: bool,723 ) -> Result<u32, DispatchError> {724 let mut agenda;725726 let index = loop {727 agenda = Agenda::<T>::get(*when);728729 match agenda.try_push(what) {730 Ok(index) => break index,731 Err(returned_what) if is_mandatory => {732 what = returned_what;733 when.saturating_inc();734 }735 Err(_) => return Err(<Error<T>>::AgendaIsExhausted.into()),736 }737 };738739 Agenda::<T>::insert(when, agenda);740 Ok(index)741 }742743 fn do_schedule(744 when: DispatchTime<T::BlockNumber>,745 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,746 priority: schedule::Priority,747 origin: T::PalletsOrigin,748 call: ScheduledCall<T>,749 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {750 let when = Self::resolve_time(when)?;751752 // sanitize maybe_periodic753 let maybe_periodic = maybe_periodic754 .filter(|p| p.1 > 1 && !p.0.is_zero())755 // Remove one from the number of repetitions since we will schedule one now.756 .map(|(p, c)| (p, c - 1));757 let task = Scheduled {758 maybe_id: None,759 priority,760 call,761 maybe_periodic,762 origin,763 _phantom: PhantomData,764 };765 Self::try_place_task(when, task)766 }767768 fn do_cancel(769 origin: Option<T::PalletsOrigin>,770 (when, index): TaskAddress<T::BlockNumber>,771 ) -> Result<(), DispatchError> {772 let scheduled = Agenda::<T>::try_mutate(773 when,774 |agenda| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {775 let scheduled = match agenda.get(index) {776 Some(scheduled) => scheduled,777 None => return Ok(None),778 };779780 if let Some(ref o) = origin {781 if matches!(782 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),783 Some(Ordering::Less) | None784 ) {785 return Err(BadOrigin.into());786 }787 }788789 Ok(agenda.take(index))790 },791 )?;792 if let Some(s) = scheduled {793 T::Preimages::drop(&s.call);794795 if let Some(id) = s.maybe_id {796 Lookup::<T>::remove(id);797 }798 Self::deposit_event(Event::Canceled { when, index });799 Ok(())800 } else {801 Err(Error::<T>::NotFound.into())802 }803 }804805 fn do_schedule_named(806 id: TaskName,807 when: DispatchTime<T::BlockNumber>,808 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,809 priority: schedule::Priority,810 origin: T::PalletsOrigin,811 call: ScheduledCall<T>,812 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {813 // ensure id it is unique814 if Lookup::<T>::contains_key(&id) {815 return Err(Error::<T>::FailedToSchedule.into());816 }817818 let when = Self::resolve_time(when)?;819820 // sanitize maybe_periodic821 let maybe_periodic = maybe_periodic822 .filter(|p| p.1 > 1 && !p.0.is_zero())823 // Remove one from the number of repetitions since we will schedule one now.824 .map(|(p, c)| (p, c - 1));825826 let task = Scheduled {827 maybe_id: Some(id),828 priority,829 call,830 maybe_periodic,831 origin,832 _phantom: Default::default(),833 };834 Self::try_place_task(when, task)835 }836837 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {838 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {839 if let Some((when, index)) = lookup.take() {840 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {841 let scheduled = match agenda.get(index) {842 Some(scheduled) => scheduled,843 None => return Ok(()),844 };845846 if let Some(ref o) = origin {847 if matches!(848 T::OriginPrivilegeCmp::cmp_privilege(o, &scheduled.origin),849 Some(Ordering::Less) | None850 ) {851 return Err(BadOrigin.into());852 }853 T::Preimages::drop(&scheduled.call);854 }855856 agenda.take(index);857858 Ok(())859 })?;860 Self::deposit_event(Event::Canceled { when, index });861 Ok(())862 } else {863 Err(Error::<T>::NotFound.into())864 }865 })866 }867868 fn do_change_named_priority(869 origin: T::PalletsOrigin,870 id: TaskName,871 priority: schedule::Priority,872 ) -> DispatchResult {873 match Lookup::<T>::get(id) {874 Some((when, index)) => Agenda::<T>::try_mutate(when, |agenda| {875 let scheduled = match agenda.get_mut(index) {876 Some(scheduled) => scheduled,877 None => return Ok(()),878 };879880 if matches!(881 T::OriginPrivilegeCmp::cmp_privilege(&origin, &scheduled.origin),882 Some(Ordering::Less) | None883 ) {884 return Err(BadOrigin.into());885 }886887 scheduled.priority = priority;888 Self::deposit_event(Event::PriorityChanged {889 when,890 index,891 priority,892 });893894 Ok(())895 }),896 None => Err(Error::<T>::NotFound.into()),897 }898 }899}900901enum ServiceTaskError {902 /// Could not be executed due to missing preimage.903 Unavailable,904 /// Could not be executed due to weight limitations.905 Overweight,906}907use ServiceTaskError::*;908909/// A Scheduler-Runtime interface for finer payment handling.910pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {911 /// Resolve the call dispatch, including any post-dispatch operations.912 fn dispatch_call(913 signer: Option<T::AccountId>,914 function: <T as Config>::RuntimeCall,915 ) -> Result<916 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,917 TransactionValidityError,918 >;919}920921impl<T: Config> Pallet<T> {922 /// Service up to `max` agendas queue starting from earliest incompletely executed agenda.923 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {924 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {925 return;926 }927928 let mut incomplete_since = now + One::one();929 let mut when = IncompleteSince::<T>::take().unwrap_or(now);930 let mut executed = 0;931932 let max_items = T::MaxScheduledPerBlock::get();933 let mut count_down = max;934 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);935 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {936 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {937 incomplete_since = incomplete_since.min(when);938 }939 when.saturating_inc();940 count_down.saturating_dec();941 }942 incomplete_since = incomplete_since.min(when);943 if incomplete_since <= now {944 IncompleteSince::<T>::put(incomplete_since);945 }946 }947948 /// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a949 /// later block.950 fn service_agenda(951 weight: &mut WeightCounter,952 executed: &mut u32,953 now: T::BlockNumber,954 when: T::BlockNumber,955 max: u32,956 ) -> bool {957 let mut agenda = Agenda::<T>::get(when);958 let mut ordered = agenda959 .iter()960 .enumerate()961 .filter_map(|(index, maybe_item)| {962 maybe_item963 .as_ref()964 .map(|item| (index as u32, item.priority))965 })966 .collect::<Vec<_>>();967 ordered.sort_by_key(|k| k.1);968 let within_limit =969 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));970 debug_assert!(971 within_limit,972 "weight limit should have been checked in advance"973 );974975 // Items which we know can be executed and have postponed for execution in a later block.976 let mut postponed = (ordered.len() as u32).saturating_sub(max);977 // Items which we don't know can ever be executed.978 let mut dropped = 0;979980 for (agenda_index, _) in ordered.into_iter().take(max as usize) {981 let task = match agenda.take(agenda_index).take() {982 None => continue,983 Some(t) => t,984 };985 let base_weight = T::WeightInfo::service_task(986 task.call.lookup_len().map(|x| x as usize),987 task.maybe_id.is_some(),988 task.maybe_periodic.is_some(),989 );990 if !weight.can_accrue(base_weight) {991 postponed += 1;992 break;993 }994 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);995 match result {996 Err((Unavailable, slot)) => {997 dropped += 1;998 agenda.set_slot(agenda_index, slot);999 }1000 Err((Overweight, slot)) => {1001 postponed += 1;1002 agenda.set_slot(agenda_index, slot);1003 }1004 Ok(()) => {1005 *executed += 1;1006 }1007 };1008 }1009 if postponed > 0 || dropped > 0 {1010 Agenda::<T>::insert(when, agenda);1011 } else {1012 Agenda::<T>::remove(when);1013 }1014 postponed == 01015 }10161017 /// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.1018 ///1019 /// This involves:1020 /// - removing and potentially replacing the `Lookup` entry for the task.1021 /// - realizing the task's call which can include a preimage lookup.1022 /// - Rescheduling the task for execution in a later agenda if periodic.1023 fn service_task(1024 weight: &mut WeightCounter,1025 now: T::BlockNumber,1026 when: T::BlockNumber,1027 agenda_index: u32,1028 is_first: bool,1029 mut task: ScheduledOf<T>,1030 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {1031 let (call, lookup_len) = match T::Preimages::peek(&task.call) {1032 Ok(c) => c,1033 Err(_) => {1034 if let Some(ref id) = task.maybe_id {1035 Lookup::<T>::remove(id);1036 }10371038 return Err((Unavailable, Some(task)));1039 }1040 };10411042 weight.check_accrue(T::WeightInfo::service_task(1043 lookup_len.map(|x| x as usize),1044 task.maybe_id.is_some(),1045 task.maybe_periodic.is_some(),1046 ));10471048 match Self::execute_dispatch(weight, task.origin.clone(), call) {1049 Err(Unavailable) => {1050 debug_assert!(false, "Checked to exist with `peek`");10511052 if let Some(ref id) = task.maybe_id {1053 Lookup::<T>::remove(id);1054 }10551056 Self::deposit_event(Event::CallUnavailable {1057 task: (when, agenda_index),1058 id: task.maybe_id,1059 });1060 Err((Unavailable, Some(task)))1061 }1062 Err(Overweight) if is_first && !Self::is_runtime_upgraded() => {1063 T::Preimages::drop(&task.call);10641065 if let Some(ref id) = task.maybe_id {1066 Lookup::<T>::remove(id);1067 }10681069 Self::deposit_event(Event::PermanentlyOverweight {1070 task: (when, agenda_index),1071 id: task.maybe_id,1072 });1073 Err((Unavailable, Some(task)))1074 }1075 Err(Overweight) => {1076 // Preserve Lookup -- the task will be postponed.1077 Err((Overweight, Some(task)))1078 }1079 Ok(result) => {1080 Self::deposit_event(Event::Dispatched {1081 task: (when, agenda_index),1082 id: task.maybe_id,1083 result,1084 });10851086 let is_canceled = task1087 .maybe_id1088 .as_ref()1089 .map(|id| !Lookup::<T>::contains_key(id))1090 .unwrap_or(false);10911092 match &task.maybe_periodic {1093 &Some((period, count)) if !is_canceled => {1094 if count > 1 {1095 task.maybe_periodic = Some((period, count - 1));1096 } else {1097 task.maybe_periodic = None;1098 }1099 let wake = now.saturating_add(period);1100 Self::mandatory_place_task(wake, task);1101 }1102 _ => {1103 if let Some(ref id) = task.maybe_id {1104 Lookup::<T>::remove(id);1105 }11061107 T::Preimages::drop(&task.call)1108 }1109 }1110 Ok(())1111 }1112 }1113 }11141115 fn is_runtime_upgraded() -> bool {1116 let last = system::LastRuntimeUpgrade::<T>::get();1117 let current = T::Version::get();11181119 last.map(|v| v.was_upgraded(¤t)).unwrap_or(true)1120 }11211122 /// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1123 /// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1124 /// post info if available).1125 ///1126 /// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1127 /// call itself).1128 fn execute_dispatch(1129 weight: &mut WeightCounter,1130 origin: T::PalletsOrigin,1131 call: <T as Config>::RuntimeCall,1132 ) -> Result<DispatchResult, ServiceTaskError> {1133 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1134 let base_weight = match dispatch_origin.clone().as_signed() {1135 Some(_) => T::WeightInfo::execute_dispatch_signed(),1136 _ => T::WeightInfo::execute_dispatch_unsigned(),1137 };1138 let call_weight = call.get_dispatch_info().weight;1139 // We only allow a scheduled call if it cannot push the weight past the limit.1140 let max_weight = base_weight.saturating_add(call_weight);11411142 if !weight.can_accrue(max_weight) {1143 return Err(Overweight);1144 }11451146 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());11471148 let r = match ensured_origin {1149 Ok(ScheduledEnsureOriginSuccess::Root) => {1150 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1151 }1152 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1153 // Execute transaction via chain default pipeline1154 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1155 T::CallExecutor::dispatch_call(Some(sender), call)1156 }1157 Err(e) => Ok(Err(e.into())),1158 };11591160 let (maybe_actual_call_weight, result) = match r {1161 Ok(result) => match result {1162 Ok(post_info) => (post_info.actual_weight, Ok(())),1163 Err(error_and_info) => (1164 error_and_info.post_info.actual_weight,1165 Err(error_and_info.error),1166 ),1167 },1168 Err(_) => {1169 log::error!(1170 target: "runtime::scheduler",1171 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1172 This block might have become invalid.");1173 (None, Err(DispatchError::CannotLookup))1174 }1175 };1176 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1177 weight.check_accrue(base_weight);1178 weight.check_accrue(call_weight);1179 Ok(result)1180 }1181}runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -57,8 +57,8 @@
Inflation: pallet_inflation::{Pallet, Call, Storage} = 60,
Unique: pallet_unique::{Pallet, Call, Storage, Event<T>} = 61,
- // #[runtimes(opal)]
- // Scheduler: pallet_unique_scheduler::{Pallet, Call, Storage, Event<T>} = 62,
+ #[runtimes(opal)]
+ Scheduler: pallet_unique_scheduler_v2::{Pallet, Call, Storage, Event<T>} = 62,
Configuration: pallet_configuration::{Pallet, Call, Storage} = 63,
@@ -95,9 +95,6 @@
EvmMigration: pallet_evm_migration::{Pallet, Call, Storage} = 153,
Maintenance: pallet_maintenance::{Pallet, Call, Storage, Event<T>} = 154,
-
- #[runtimes(opal)]
- Scheduler: pallet_unique_scheduler_v2::{Pallet, Call, Storage, Event<T>} = 154,
#[runtimes(opal)]
TestUtils: pallet_test_utils = 255,
runtime/common/runtime_apis.rsdiffbeforeafterboth--- a/runtime/common/runtime_apis.rs
+++ b/runtime/common/runtime_apis.rs
@@ -683,8 +683,8 @@
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
list_benchmark!(list, extra, pallet_refungible, Refungible);
- // #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
- // list_benchmark!(list, extra, pallet_unique_scheduler, Scheduler);
+ #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
+ list_benchmark!(list, extra, pallet_unique_scheduler_v2, Scheduler);
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
list_benchmark!(list, extra, pallet_proxy_rmrk_core, RmrkCore);
@@ -743,8 +743,8 @@
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
add_benchmark!(params, batches, pallet_refungible, Refungible);
- // #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
- // add_benchmark!(params, batches, pallet_unique_scheduler, Scheduler);
+ #[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
+ add_benchmark!(params, batches, pallet_unique_scheduler_v2, Scheduler);
#[cfg(not(any(feature = "unique-runtime", feature = "quartz-runtime")))]
add_benchmark!(params, batches, pallet_proxy_rmrk_core, RmrkCore);