difftreelog
fix cargo fmt
in: master
4 files changed
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::{borrow::Borrow, 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 Unsigned,217}218219pub type TaskName = [u8; 32];220221/// Information regarding an item to be executed in the future.222#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]223#[derive(Clone, RuntimeDebug, Encode, Decode, MaxEncodedLen, TypeInfo)]224pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {225 /// The unique identity for this task, if there is one.226 maybe_id: Option<Name>,227228 /// This task's priority.229 priority: schedule::Priority,230231 /// The call to be dispatched.232 call: Call,233234 /// If the call is periodic, then this points to the information concerning that.235 maybe_periodic: Option<schedule::Period<BlockNumber>>,236237 /// The origin with which to dispatch the call.238 origin: PalletsOrigin,239 _phantom: PhantomData<AccountId>,240}241242pub type ScheduledOf<T> = Scheduled<243 TaskName,244 ScheduledCall<T>,245 <T as frame_system::Config>::BlockNumber,246 <T as Config>::PalletsOrigin,247 <T as frame_system::Config>::AccountId,248>;249250struct WeightCounter {251 used: Weight,252 limit: Weight,253}254255impl WeightCounter {256 fn check_accrue(&mut self, w: Weight) -> bool {257 let test = self.used.saturating_add(w);258 if test.any_gt(self.limit) {259 false260 } else {261 self.used = test;262 true263 }264 }265266 fn can_accrue(&mut self, w: Weight) -> bool {267 self.used.saturating_add(w).all_lte(self.limit)268 }269}270271pub(crate) trait MarginalWeightInfo: WeightInfo {272 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {273 let base = Self::service_task_base();274 let mut total = match maybe_lookup_len {275 None => base,276 Some(l) => Self::service_task_fetched(l as u32),277 };278 if named {279 total.saturating_accrue(Self::service_task_named().saturating_sub(base));280 }281 if periodic {282 total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));283 }284 total285 }286}287288impl<T: WeightInfo> MarginalWeightInfo for T {}289290#[frame_support::pallet]291pub mod pallet {292 use super::*;293 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};294 use system::pallet_prelude::*;295296 /// The current storage version.297 const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);298299 #[pallet::pallet]300 #[pallet::generate_store(pub(super) trait Store)]301 #[pallet::storage_version(STORAGE_VERSION)]302 pub struct Pallet<T>(_);303304 #[pallet::config]305 pub trait Config: frame_system::Config {306 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;307308 /// The aggregated origin which the dispatch will take.309 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>310 + From<Self::PalletsOrigin>311 + IsType<<Self as system::Config>::RuntimeOrigin>312 + Clone;313314 /// The caller origin, overarching type of all pallets origins.315 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>316 + Codec317 + Clone318 + Eq319 + TypeInfo320 + MaxEncodedLen;321322 /// The aggregated call type.323 type RuntimeCall: Parameter324 + Dispatchable<325 RuntimeOrigin = <Self as Config>::RuntimeOrigin,326 PostInfo = PostDispatchInfo,327 > + UnfilteredDispatchable<RuntimeOrigin = <Self as system::Config>::RuntimeOrigin>328 + GetDispatchInfo329 + From<system::Call<Self>>;330331 /// The maximum weight that may be scheduled per block for any dispatchables.332 #[pallet::constant]333 type MaximumWeight: Get<Weight>;334335 /// Required origin to schedule or cancel calls.336 type ScheduleOrigin: EnsureOrigin<337 <Self as system::Config>::RuntimeOrigin,338 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,339 >;340341 /// Compare the privileges of origins.342 ///343 /// This will be used when canceling a task, to ensure that the origin that tries344 /// to cancel has greater or equal privileges as the origin that created the scheduled task.345 ///346 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can347 /// be used. This will only check if two given origins are equal.348 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;349350 /// The maximum number of scheduled calls in the queue for a single block.351 #[pallet::constant]352 type MaxScheduledPerBlock: Get<u32>;353354 /// Weight information for extrinsics in this pallet.355 type WeightInfo: WeightInfo;356357 /// The preimage provider with which we look up call hashes to get the call.358 type Preimages: SchedulerPreimages<Self>;359360 /// The helper type used for custom transaction fee logic.361 type CallExecutor: DispatchCall<Self, H160>;362363 /// Required origin to set/change calls' priority.364 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;365 }366367 #[pallet::storage]368 pub type IncompleteSince<T: Config> = StorageValue<_, T::BlockNumber>;369370 /// Items to be executed, indexed by the block number that they should be executed on.371 #[pallet::storage]372 pub type Agenda<T: Config> = StorageMap<373 _,374 Twox64Concat,375 T::BlockNumber,376 BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,377 ValueQuery,378 >;379380 /// Lookup from a name to the block number and index of the task.381 #[pallet::storage]382 pub(crate) type Lookup<T: Config> =383 StorageMap<_, Twox64Concat, TaskName, TaskAddress<T::BlockNumber>>;384385 /// Events type.386 #[pallet::event]387 #[pallet::generate_deposit(pub(super) fn deposit_event)]388 pub enum Event<T: Config> {389 /// Scheduled some task.390 Scheduled { when: T::BlockNumber, index: u32 },391 /// Canceled some task.392 Canceled { when: T::BlockNumber, index: u32 },393 /// Dispatched some task.394 Dispatched {395 task: TaskAddress<T::BlockNumber>,396 id: Option<[u8; 32]>,397 result: DispatchResult,398 },399 /// Scheduled task's priority has changed400 PriorityChanged {401 when: T::BlockNumber,402 index: u32,403 priority: schedule::Priority,404 },405 /// The call for the provided hash was not found so the task has been aborted.406 CallUnavailable {407 task: TaskAddress<T::BlockNumber>,408 id: Option<[u8; 32]>,409 },410 /// The given task was unable to be renewed since the agenda is full at that block.411 PeriodicFailed {412 task: TaskAddress<T::BlockNumber>,413 id: Option<[u8; 32]>,414 },415 /// The given task can never be executed since it is overweight.416 PermanentlyOverweight {417 task: TaskAddress<T::BlockNumber>,418 id: Option<[u8; 32]>,419 },420 }421422 #[pallet::error]423 pub enum Error<T> {424 /// Failed to schedule a call425 FailedToSchedule,426 /// There is no place for a new task in the agenda427 AgendaIsExhausted,428 /// Scheduled call is corrupted429 ScheduledCallCorrupted,430 /// Scheduled call preimage is not found431 PreimageNotFound,432 /// Scheduled call is too big433 TooBigScheduledCall,434 /// Cannot find the scheduled call.435 NotFound,436 /// Given target block number is in the past.437 TargetBlockNumberInPast,438 /// Attempt to use a non-named function on a named task.439 Named,440 }441442 #[pallet::hooks]443 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {444 /// Execute the scheduled calls445 fn on_initialize(now: T::BlockNumber) -> Weight {446 let mut weight_counter = WeightCounter {447 used: Weight::zero(),448 limit: T::MaximumWeight::get(),449 };450 Self::service_agendas(&mut weight_counter, now, u32::max_value());451 weight_counter.used452 }453 }454455 #[pallet::call]456 impl<T: Config> Pallet<T> {457 /// Anonymously schedule a task.458 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]459 pub fn schedule(460 origin: OriginFor<T>,461 when: T::BlockNumber,462 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,463 priority: Option<schedule::Priority>,464 call: Box<<T as Config>::RuntimeCall>,465 ) -> DispatchResult {466 T::ScheduleOrigin::ensure_origin(origin.clone())?;467468 if priority.is_some() {469 T::PrioritySetOrigin::ensure_origin(origin.clone())?;470 }471472 let origin = <T as Config>::RuntimeOrigin::from(origin);473 Self::do_schedule(474 DispatchTime::At(when),475 maybe_periodic,476 priority.unwrap_or(LOWEST_PRIORITY),477 origin.caller().clone(),478 <ScheduledCall<T>>::new(*call)?,479 )?;480 Ok(())481 }482483 /// Cancel an anonymously scheduled task.484 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]485 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {486 T::ScheduleOrigin::ensure_origin(origin.clone())?;487 let origin = <T as Config>::RuntimeOrigin::from(origin);488 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;489 Ok(())490 }491492 /// Schedule a named task.493 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]494 pub fn schedule_named(495 origin: OriginFor<T>,496 id: TaskName,497 when: T::BlockNumber,498 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,499 priority: Option<schedule::Priority>,500 call: Box<<T as Config>::RuntimeCall>,501 ) -> DispatchResult {502 T::ScheduleOrigin::ensure_origin(origin.clone())?;503504 if priority.is_some() {505 T::PrioritySetOrigin::ensure_origin(origin.clone())?;506 }507508 let origin = <T as Config>::RuntimeOrigin::from(origin);509 Self::do_schedule_named(510 id,511 DispatchTime::At(when),512 maybe_periodic,513 priority.unwrap_or(LOWEST_PRIORITY),514 origin.caller().clone(),515 <ScheduledCall<T>>::new(*call)?,516 )?;517 Ok(())518 }519520 /// Cancel a named scheduled task.521 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]522 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {523 T::ScheduleOrigin::ensure_origin(origin.clone())?;524 let origin = <T as Config>::RuntimeOrigin::from(origin);525 Self::do_cancel_named(Some(origin.caller().clone()), id)?;526 Ok(())527 }528529 /// Anonymously schedule a task after a delay.530 ///531 /// # <weight>532 /// Same as [`schedule`].533 /// # </weight>534 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]535 pub fn schedule_after(536 origin: OriginFor<T>,537 after: T::BlockNumber,538 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,539 priority: Option<schedule::Priority>,540 call: Box<<T as Config>::RuntimeCall>,541 ) -> DispatchResult {542 T::ScheduleOrigin::ensure_origin(origin.clone())?;543544 if priority.is_some() {545 T::PrioritySetOrigin::ensure_origin(origin.clone())?;546 }547548 let origin = <T as Config>::RuntimeOrigin::from(origin);549 Self::do_schedule(550 DispatchTime::After(after),551 maybe_periodic,552 priority.unwrap_or(LOWEST_PRIORITY),553 origin.caller().clone(),554 <ScheduledCall<T>>::new(*call)?,555 )?;556 Ok(())557 }558559 /// Schedule a named task after a delay.560 ///561 /// # <weight>562 /// Same as [`schedule_named`](Self::schedule_named).563 /// # </weight>564 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]565 pub fn schedule_named_after(566 origin: OriginFor<T>,567 id: TaskName,568 after: T::BlockNumber,569 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,570 priority: Option<schedule::Priority>,571 call: Box<<T as Config>::RuntimeCall>,572 ) -> DispatchResult {573 T::ScheduleOrigin::ensure_origin(origin.clone())?;574575 if priority.is_some() {576 T::PrioritySetOrigin::ensure_origin(origin.clone())?;577 }578579 let origin = <T as Config>::RuntimeOrigin::from(origin);580 Self::do_schedule_named(581 id,582 DispatchTime::After(after),583 maybe_periodic,584 priority.unwrap_or(LOWEST_PRIORITY),585 origin.caller().clone(),586 <ScheduledCall<T>>::new(*call)?,587 )?;588 Ok(())589 }590591 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]592 pub fn change_named_priority(593 origin: OriginFor<T>,594 id: TaskName,595 priority: schedule::Priority,596 ) -> DispatchResult {597 T::PrioritySetOrigin::ensure_origin(origin.clone())?;598 let origin = <T as Config>::RuntimeOrigin::from(origin);599 Self::do_change_named_priority(origin.caller().clone(), id, priority)600 }601 }602}603604impl<T: Config> Pallet<T> {605 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {606 let now = frame_system::Pallet::<T>::block_number();607608 let when = match when {609 DispatchTime::At(x) => x,610 // The current block has already completed it's scheduled tasks, so611 // Schedule the task at lest one block after this current block.612 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),613 };614615 if when <= now {616 return Err(Error::<T>::TargetBlockNumberInPast.into());617 }618619 Ok(when)620 }621622 fn place_task(623 when: T::BlockNumber,624 what: ScheduledOf<T>,625 ) -> Result<TaskAddress<T::BlockNumber>, (DispatchError, ScheduledOf<T>)> {626 let maybe_name = what.maybe_id;627 let index = Self::push_to_agenda(when, what)?;628 let address = (when, index);629 if let Some(name) = maybe_name {630 Lookup::<T>::insert(name, address)631 }632 Self::deposit_event(Event::Scheduled {633 when: address.0,634 index: address.1,635 });636 Ok(address)637 }638639 fn push_to_agenda(640 when: T::BlockNumber,641 what: ScheduledOf<T>,642 ) -> Result<u32, (DispatchError, ScheduledOf<T>)> {643 let mut agenda = Agenda::<T>::get(when);644 let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {645 // will always succeed due to the above check.646 let _ = agenda.try_push(Some(what));647 agenda.len() as u32 - 1648 } else {649 if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {650 agenda[hole_index] = Some(what);651 hole_index as u32652 } else {653 return Err((<Error<T>>::AgendaIsExhausted.into(), what));654 }655 };656 Agenda::<T>::insert(when, agenda);657 Ok(index)658 }659660 fn do_schedule(661 when: DispatchTime<T::BlockNumber>,662 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,663 priority: schedule::Priority,664 origin: T::PalletsOrigin,665 call: ScheduledCall<T>,666 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {667 let when = Self::resolve_time(when)?;668669 // sanitize maybe_periodic670 let maybe_periodic = maybe_periodic671 .filter(|p| p.1 > 1 && !p.0.is_zero())672 // Remove one from the number of repetitions since we will schedule one now.673 .map(|(p, c)| (p, c - 1));674 let task = Scheduled {675 maybe_id: None,676 priority,677 call,678 maybe_periodic,679 origin,680 _phantom: PhantomData,681 };682 Self::place_task(when, task).map_err(|x| x.0)683 }684685 fn do_cancel(686 origin: Option<T::PalletsOrigin>,687 (when, index): TaskAddress<T::BlockNumber>,688 ) -> Result<(), DispatchError> {689 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {690 agenda.get_mut(index as usize).map_or(691 Ok(None),692 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {693 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {694 if matches!(695 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),696 Some(Ordering::Less) | None697 ) {698 return Err(BadOrigin.into());699 }700 };701 Ok(s.take())702 },703 )704 })?;705 if let Some(s) = scheduled {706 T::Preimages::drop(&s.call);707708 if let Some(id) = s.maybe_id {709 Lookup::<T>::remove(id);710 }711 Self::deposit_event(Event::Canceled { when, index });712 Ok(())713 } else {714 return Err(Error::<T>::NotFound.into());715 }716 }717718 fn do_schedule_named(719 id: TaskName,720 when: DispatchTime<T::BlockNumber>,721 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,722 priority: schedule::Priority,723 origin: T::PalletsOrigin,724 call: ScheduledCall<T>,725 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {726 // ensure id it is unique727 if Lookup::<T>::contains_key(&id) {728 return Err(Error::<T>::FailedToSchedule.into());729 }730731 let when = Self::resolve_time(when)?;732733 // sanitize maybe_periodic734 let maybe_periodic = maybe_periodic735 .filter(|p| p.1 > 1 && !p.0.is_zero())736 // Remove one from the number of repetitions since we will schedule one now.737 .map(|(p, c)| (p, c - 1));738739 let task = Scheduled {740 maybe_id: Some(id),741 priority,742 call,743 maybe_periodic,744 origin,745 _phantom: Default::default(),746 };747 Self::place_task(when, task).map_err(|x| x.0)748 }749750 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {751 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {752 if let Some((when, index)) = lookup.take() {753 let i = index as usize;754 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {755 if let Some(s) = agenda.get_mut(i) {756 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {757 if matches!(758 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),759 Some(Ordering::Less) | None760 ) {761 return Err(BadOrigin.into());762 }763 T::Preimages::drop(&s.call);764 }765 *s = None;766 }767 Ok(())768 })?;769 Self::deposit_event(Event::Canceled { when, index });770 Ok(())771 } else {772 return Err(Error::<T>::NotFound.into());773 }774 })775 }776777 fn do_change_named_priority(778 origin: T::PalletsOrigin,779 id: TaskName,780 priority: schedule::Priority,781 ) -> DispatchResult {782 match Lookup::<T>::get(id) {783 Some((when, index)) => {784 let i = index as usize;785 Agenda::<T>::try_mutate(when, |agenda| {786 if let Some(Some(s)) = agenda.get_mut(i) {787 if matches!(788 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),789 Some(Ordering::Less) | None790 ) {791 return Err(BadOrigin.into());792 }793794 s.priority = priority;795 Self::deposit_event(Event::PriorityChanged {796 when,797 index,798 priority,799 });800 }801 Ok(())802 })803 }804 None => Err(Error::<T>::NotFound.into()),805 }806 }807}808809enum ServiceTaskError {810 /// Could not be executed due to missing preimage.811 Unavailable,812 /// Could not be executed due to weight limitations.813 Overweight,814}815use ServiceTaskError::*;816817/// A Scheduler-Runtime interface for finer payment handling.818pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {819 /// Resolve the call dispatch, including any post-dispatch operations.820 fn dispatch_call(821 signer: Option<T::AccountId>,822 function: <T as Config>::RuntimeCall,823 ) -> Result<824 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,825 TransactionValidityError,826 >;827}828829impl<T: Config> Pallet<T> {830 /// Service up to `max` agendas queue starting from earliest incompletely executed agenda.831 fn service_agendas(weight: &mut WeightCounter, now: T::BlockNumber, max: u32) {832 if !weight.check_accrue(T::WeightInfo::service_agendas_base()) {833 return;834 }835836 let mut incomplete_since = now + One::one();837 let mut when = IncompleteSince::<T>::take().unwrap_or(now);838 let mut executed = 0;839840 let max_items = T::MaxScheduledPerBlock::get();841 let mut count_down = max;842 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);843 while count_down > 0 && when <= now && weight.can_accrue(service_agenda_base_weight) {844 if !Self::service_agenda(weight, &mut executed, now, when, u32::max_value()) {845 incomplete_since = incomplete_since.min(when);846 }847 when.saturating_inc();848 count_down.saturating_dec();849 }850 incomplete_since = incomplete_since.min(when);851 if incomplete_since <= now {852 IncompleteSince::<T>::put(incomplete_since);853 }854 }855856 /// Returns `true` if the agenda was fully completed, `false` if it should be revisited at a857 /// later block.858 fn service_agenda(859 weight: &mut WeightCounter,860 executed: &mut u32,861 now: T::BlockNumber,862 when: T::BlockNumber,863 max: u32,864 ) -> bool {865 let mut agenda = Agenda::<T>::get(when);866 let mut ordered = agenda867 .iter()868 .enumerate()869 .filter_map(|(index, maybe_item)| {870 maybe_item871 .as_ref()872 .map(|item| (index as u32, item.priority))873 })874 .collect::<Vec<_>>();875 ordered.sort_by_key(|k| k.1);876 let within_limit =877 weight.check_accrue(T::WeightInfo::service_agenda_base(ordered.len() as u32));878 debug_assert!(879 within_limit,880 "weight limit should have been checked in advance"881 );882883 // Items which we know can be executed and have postponed for execution in a later block.884 let mut postponed = (ordered.len() as u32).saturating_sub(max);885 // Items which we don't know can ever be executed.886 let mut dropped = 0;887888 for (agenda_index, _) in ordered.into_iter().take(max as usize) {889 let task = match agenda[agenda_index as usize].take() {890 None => continue,891 Some(t) => t,892 };893 let base_weight = T::WeightInfo::service_task(894 task.call.lookup_len().map(|x| x as usize),895 task.maybe_id.is_some(),896 task.maybe_periodic.is_some(),897 );898 if !weight.can_accrue(base_weight) {899 postponed += 1;900 break;901 }902 let result = Self::service_task(weight, now, when, agenda_index, *executed == 0, task);903 agenda[agenda_index as usize] = match result {904 Err((Unavailable, slot)) => {905 dropped += 1;906 slot907 }908 Err((Overweight, slot)) => {909 postponed += 1;910 slot911 }912 Ok(()) => {913 *executed += 1;914 None915 }916 };917 }918 if postponed > 0 || dropped > 0 {919 Agenda::<T>::insert(when, agenda);920 } else {921 Agenda::<T>::remove(when);922 }923 postponed == 0924 }925926 /// Service (i.e. execute) the given task, being careful not to overflow the `weight` counter.927 ///928 /// This involves:929 /// - removing and potentially replacing the `Lookup` entry for the task.930 /// - realizing the task's call which can include a preimage lookup.931 /// - Rescheduling the task for execution in a later agenda if periodic.932 fn service_task(933 weight: &mut WeightCounter,934 now: T::BlockNumber,935 when: T::BlockNumber,936 agenda_index: u32,937 is_first: bool,938 mut task: ScheduledOf<T>,939 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {940 let (call, lookup_len) = match T::Preimages::peek(&task.call) {941 Ok(c) => c,942 Err(_) => {943 if let Some(ref id) = task.maybe_id {944 Lookup::<T>::remove(id);945 }946947 return Err((Unavailable, Some(task)));948 }949 };950951 weight.check_accrue(T::WeightInfo::service_task(952 lookup_len.map(|x| x as usize),953 task.maybe_id.is_some(),954 task.maybe_periodic.is_some(),955 ));956957 match Self::execute_dispatch(weight, task.origin.clone(), call) {958 Err(Unavailable) => {959 debug_assert!(false, "Checked to exist with `peek`");960961 if let Some(ref id) = task.maybe_id {962 Lookup::<T>::remove(id);963 }964965 Self::deposit_event(Event::CallUnavailable {966 task: (when, agenda_index),967 id: task.maybe_id,968 });969 Err((Unavailable, Some(task)))970 }971 Err(Overweight) if is_first => {972 T::Preimages::drop(&task.call);973974 if let Some(ref id) = task.maybe_id {975 Lookup::<T>::remove(id);976 }977978 Self::deposit_event(Event::PermanentlyOverweight {979 task: (when, agenda_index),980 id: task.maybe_id,981 });982 Err((Unavailable, Some(task)))983 }984 Err(Overweight) => {985 // Preserve Lookup -- the task will be postponed.986 Err((Overweight, Some(task)))987 }988 Ok(result) => {989 Self::deposit_event(Event::Dispatched {990 task: (when, agenda_index),991 id: task.maybe_id,992 result,993 });994995 let is_canceled = task996 .maybe_id997 .as_ref()998 .map(|id| !Lookup::<T>::contains_key(id))999 .unwrap_or(false);10001001 match &task.maybe_periodic {1002 &Some((period, count)) if !is_canceled => {1003 if count > 1 {1004 task.maybe_periodic = Some((period, count - 1));1005 } else {1006 task.maybe_periodic = None;1007 }1008 let wake = now.saturating_add(period);1009 match Self::place_task(wake, task) {1010 Ok(_) => {}1011 Err((_, task)) => {1012 // TODO: Leave task in storage somewhere for it to be rescheduled1013 // manually.1014 T::Preimages::drop(&task.call);1015 Self::deposit_event(Event::PeriodicFailed {1016 task: (when, agenda_index),1017 id: task.maybe_id,1018 });1019 }1020 }1021 }1022 _ => {1023 if let Some(ref id) = task.maybe_id {1024 Lookup::<T>::remove(id);1025 }10261027 T::Preimages::drop(&task.call)1028 }1029 }1030 Ok(())1031 }1032 }1033 }10341035 /// Make a dispatch to the given `call` from the given `origin`, ensuring that the `weight`1036 /// counter does not exceed its limit and that it is counted accurately (e.g. accounted using1037 /// post info if available).1038 ///1039 /// NOTE: Only the weight for this function will be counted (origin lookup, dispatch and the1040 /// call itself).1041 fn execute_dispatch(1042 weight: &mut WeightCounter,1043 origin: T::PalletsOrigin,1044 call: <T as Config>::RuntimeCall,1045 ) -> Result<DispatchResult, ServiceTaskError> {1046 let dispatch_origin: <T as Config>::RuntimeOrigin = origin.into();1047 let base_weight = match dispatch_origin.clone().as_signed() {1048 Some(_) => T::WeightInfo::execute_dispatch_signed(),1049 _ => T::WeightInfo::execute_dispatch_unsigned(),1050 };1051 let call_weight = call.get_dispatch_info().weight;1052 // We only allow a scheduled call if it cannot push the weight past the limit.1053 let max_weight = base_weight.saturating_add(call_weight);10541055 if !weight.can_accrue(max_weight) {1056 return Err(Overweight);1057 }10581059 // let scheduled_origin =1060 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone());1061 let ensured_origin = T::ScheduleOrigin::ensure_origin(dispatch_origin.into());10621063 let r = match ensured_origin {1064 Ok(ScheduledEnsureOriginSuccess::Root) => {1065 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))1066 }1067 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {1068 // Execute transaction via chain default pipeline1069 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken1070 T::CallExecutor::dispatch_call(Some(sender), call.clone())1071 }1072 Ok(ScheduledEnsureOriginSuccess::Unsigned) => {1073 // Unsigned version of the above1074 T::CallExecutor::dispatch_call(None, call.clone())1075 }1076 Err(e) => Ok(Err(e.into())),1077 };10781079 let (maybe_actual_call_weight, result) = match r {1080 Ok(result) => match result {1081 Ok(post_info) => (post_info.actual_weight, Ok(())),1082 Err(error_and_info) => (1083 error_and_info.post_info.actual_weight,1084 Err(error_and_info.error),1085 ),1086 },1087 Err(_) => {1088 log::error!(1089 target: "runtime::scheduler",1090 "Warning: Scheduler has failed to execute a post-dispatch transaction. \1091 This block might have become invalid.");1092 (None, Err(DispatchError::CannotLookup))1093 }1094 };1095 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);1096 weight.check_accrue(base_weight);1097 weight.check_accrue(call_weight);1098 Ok(result)1099 }1100}pallets/scheduler-v2/src/mock.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/mock.rs
+++ b/pallets/scheduler-v2/src/mock.rs
@@ -39,9 +39,7 @@
use crate as scheduler;
use frame_support::{
ord_parameter_types, parameter_types,
- traits::{
- ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize,
- },
+ traits::{ConstU32, ConstU64, Contains, EqualPrivilegeOnly, OnFinalize, OnInitialize},
weights::constants::RocksDbWeight,
};
use frame_system::{EnsureRoot, RawOrigin};
@@ -136,7 +134,7 @@
pub BlockWeights: frame_system::limits::BlockWeights =
frame_system::limits::BlockWeights::simple_max(
Weight::from_ref_time(2_000_000_000_000)
- // .set_proof_size(u64::MAX),
+ // .set_proof_size(u64::MAX),
);
}
impl system::Config for Test {
@@ -210,9 +208,9 @@
fn cancel_named(_s: u32) -> Weight {
Weight::from_ref_time(50)
}
- fn change_named_priority(_s: u32, ) -> Weight {
- Weight::from_ref_time(50)
- }
+ fn change_named_priority(_s: u32) -> Weight {
+ Weight::from_ref_time(50)
+ }
}
parameter_types! {
pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) *
@@ -220,8 +218,8 @@
}
pub struct EnsureSignedOneOrRoot;
-impl<O: Into<Result<RawOrigin<u64>, O>> + From<RawOrigin<u64>>>
- EnsureOrigin<O> for EnsureSignedOneOrRoot
+impl<O: Into<Result<RawOrigin<u64>, O>> + From<RawOrigin<u64>>> EnsureOrigin<O>
+ for EnsureSignedOneOrRoot
{
type Success = ScheduledEnsureOriginSuccess<u64>;
fn try_origin(o: O) -> Result<Self::Success, O> {
@@ -235,19 +233,19 @@
pub struct Executor;
impl DispatchCall<Test, sp_core::H160> for Executor {
- fn dispatch_call(
- signer: Option<u64>,
- function: RuntimeCall,
- ) -> Result<
- Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
- TransactionValidityError,
- > {
- let origin = match signer {
- Some(who) => RuntimeOrigin::signed(who),
- None => RuntimeOrigin::none(),
- };
- Ok(function.dispatch(origin))
- }
+ fn dispatch_call(
+ signer: Option<u64>,
+ function: RuntimeCall,
+ ) -> Result<
+ Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,
+ TransactionValidityError,
+ > {
+ let origin = match signer {
+ Some(who) => RuntimeOrigin::signed(who),
+ None => RuntimeOrigin::none(),
+ };
+ Ok(function.dispatch(origin))
+ }
}
impl Config for Test {
@@ -261,14 +259,16 @@
type WeightInfo = TestWeightInfo;
type OriginPrivilegeCmp = EqualPrivilegeOnly;
type Preimages = ();
- type PrioritySetOrigin = EnsureRoot<u64>;
- type CallExecutor = Executor;
+ type PrioritySetOrigin = EnsureRoot<u64>;
+ type CallExecutor = Executor;
}
pub type LoggerCall = logger::Call<Test>;
pub fn new_test_ext() -> sp_io::TestExternalities {
- let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
+ let t = system::GenesisConfig::default()
+ .build_storage::<Test>()
+ .unwrap();
t.into()
}
pallets/scheduler-v2/src/tests.rsdiffbeforeafterboth--- a/pallets/scheduler-v2/src/tests.rs
+++ b/pallets/scheduler-v2/src/tests.rs
@@ -46,15 +46,19 @@
#[test]
fn basic_scheduling_works() {
new_test_ext().execute_with(|| {
- let call =
- RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(10) });
- assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(&call));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+ &call
+ ));
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
127,
root(),
- <ScheduledCall<Test>>::new(call).unwrap(),
+ <ScheduledCall<Test>>::new(call).unwrap(),
));
run_to_block(3);
assert!(logger::log().is_empty());
@@ -69,9 +73,13 @@
fn schedule_after_works() {
new_test_ext().execute_with(|| {
run_to_block(2);
- let call =
- RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(10) });
- assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(&call));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+ &call
+ ));
// This will schedule the call 3 blocks after the next block... so block 3 + 3 = 6
assert_ok!(Scheduler::do_schedule(
DispatchTime::After(3),
@@ -93,9 +101,13 @@
fn schedule_after_zero_works() {
new_test_ext().execute_with(|| {
run_to_block(2);
- let call =
- RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(10) });
- assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(&call));
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
+ assert!(!<Test as frame_system::Config>::BaseCallFilter::contains(
+ &call
+ ));
assert_ok!(Scheduler::do_schedule(
DispatchTime::After(0),
None,
@@ -120,7 +132,7 @@
Some((3, 3)),
127,
root(),
- <ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {
+ <ScheduledCall<Test>>::new(RuntimeCall::Logger(logger::Call::log {
i: 42,
weight: Weight::from_ref_time(10)
}))
@@ -137,9 +149,15 @@
run_to_block(9);
assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
run_to_block(10);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
+ );
run_to_block(100);
- assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]
+ );
});
}
@@ -241,7 +259,10 @@
fn scheduler_respects_weight_limits() {
let max_weight: Weight = <Test as Config>::MaximumWeight::get();
new_test_ext().execute_with(|| {
- let call = RuntimeCall::Logger(LoggerCall::log { i: 42, weight: max_weight / 3 * 2 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight / 3 * 2,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -249,7 +270,10 @@
root(),
<ScheduledCall<Test>>::new(call).unwrap(),
));
- let call = RuntimeCall::Logger(LoggerCall::log { i: 69, weight: max_weight / 3 * 2 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: max_weight / 3 * 2,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -270,7 +294,10 @@
fn scheduler_does_not_delete_permanently_overweight_call() {
let max_weight: Weight = <Test as Config>::MaximumWeight::get();
new_test_ext().execute_with(|| {
- let call = RuntimeCall::Logger(LoggerCall::log { i: 42, weight: max_weight });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -285,7 +312,11 @@
// Assert the `PermanentlyOverweight` event.
assert_eq!(
System::events().last().unwrap().event,
- crate::Event::PermanentlyOverweight { task: (4, 0), id: None }.into(),
+ crate::Event::PermanentlyOverweight {
+ task: (4, 0),
+ id: None
+ }
+ .into(),
);
// The call is still in the agenda.
assert!(Agenda::<Test>::get(4)[0].is_some());
@@ -298,7 +329,10 @@
let max_per_block = <Test as Config>::MaxScheduledPerBlock::get();
new_test_ext().execute_with(|| {
- let call = RuntimeCall::Logger(LoggerCall::log { i: 42, weight: (max_weight / 3) * 2 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: (max_weight / 3) * 2,
+ });
let call = <ScheduledCall<Test>>::new(call).unwrap();
assert_ok!(Scheduler::do_schedule(
@@ -329,7 +363,11 @@
assert_eq!(
System::events().last().unwrap().event,
- crate::Event::PeriodicFailed { task: (24, 0), id: None }.into(),
+ crate::Event::PeriodicFailed {
+ task: (24, 0),
+ id: None
+ }
+ .into(),
);
});
}
@@ -338,7 +376,10 @@
fn scheduler_respects_priority_ordering() {
let max_weight: Weight = <Test as Config>::MaximumWeight::get();
new_test_ext().execute_with(|| {
- let call = RuntimeCall::Logger(LoggerCall::log { i: 42, weight: max_weight / 3 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight / 3,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -346,7 +387,10 @@
root(),
<ScheduledCall<Test>>::new(call).unwrap(),
));
- let call = RuntimeCall::Logger(LoggerCall::log { i: 69, weight: max_weight / 3 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: max_weight / 3,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -363,7 +407,10 @@
fn scheduler_respects_priority_ordering_with_soft_deadlines() {
new_test_ext().execute_with(|| {
let max_weight: Weight = <Test as Config>::MaximumWeight::get();
- let call = RuntimeCall::Logger(LoggerCall::log { i: 42, weight: max_weight / 5 * 2 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: max_weight / 5 * 2,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -371,7 +418,10 @@
root(),
<ScheduledCall<Test>>::new(call).unwrap(),
));
- let call = RuntimeCall::Logger(LoggerCall::log { i: 69, weight: max_weight / 5 * 2 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 69,
+ weight: max_weight / 5 * 2,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -379,7 +429,10 @@
root(),
<ScheduledCall<Test>>::new(call).unwrap(),
));
- let call = RuntimeCall::Logger(LoggerCall::log { i: 2600, weight: max_weight / 5 * 4 });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 2600,
+ weight: max_weight / 5 * 4,
+ });
assert_ok!(Scheduler::do_schedule(
DispatchTime::At(4),
None,
@@ -393,7 +446,10 @@
assert_eq!(logger::log(), vec![(root(), 2600u32)]);
// 69 and 42 fit together
run_to_block(5);
- assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
+ );
});
}
@@ -456,11 +512,11 @@
// Will include the named periodic only
assert_eq!(
Scheduler::on_initialize(1),
- TestWeightInfo::service_agendas_base() +
- TestWeightInfo::service_agenda_base(1) +
- <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, true) +
- TestWeightInfo::execute_dispatch_unsigned() +
- call_weight + Weight::from_ref_time(4)
+ TestWeightInfo::service_agendas_base()
+ + TestWeightInfo::service_agenda_base(1)
+ + <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, true)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(4)
);
assert_eq!(IncompleteSince::<Test>::get(), None);
assert_eq!(logger::log(), vec![(root(), 2600u32)]);
@@ -468,31 +524,39 @@
// Will include anon and anon periodic
assert_eq!(
Scheduler::on_initialize(2),
- TestWeightInfo::service_agendas_base() +
- TestWeightInfo::service_agenda_base(2) +
- <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, true) +
- TestWeightInfo::execute_dispatch_unsigned() +
- call_weight + Weight::from_ref_time(3) +
- <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, false) +
- TestWeightInfo::execute_dispatch_unsigned() +
- call_weight + Weight::from_ref_time(2)
+ TestWeightInfo::service_agendas_base()
+ + TestWeightInfo::service_agenda_base(2)
+ + <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, true)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(3)
+ + <TestWeightInfo as MarginalWeightInfo>::service_task(None, false, false)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(2)
);
assert_eq!(IncompleteSince::<Test>::get(), None);
- assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);
+ assert_eq!(
+ logger::log(),
+ vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]
+ );
// Will include named only
assert_eq!(
Scheduler::on_initialize(3),
- TestWeightInfo::service_agendas_base() +
- TestWeightInfo::service_agenda_base(1) +
- <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, false) +
- TestWeightInfo::execute_dispatch_unsigned() +
- call_weight + Weight::from_ref_time(1)
+ TestWeightInfo::service_agendas_base()
+ + TestWeightInfo::service_agenda_base(1)
+ + <TestWeightInfo as MarginalWeightInfo>::service_task(None, true, false)
+ + TestWeightInfo::execute_dispatch_unsigned()
+ + call_weight + Weight::from_ref_time(1)
);
assert_eq!(IncompleteSince::<Test>::get(), None);
assert_eq!(
logger::log(),
- vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32), (root(), 3u32)]
+ vec![
+ (root(), 2600u32),
+ (root(), 69u32),
+ (root(), 42u32),
+ (root(), 3u32)
+ ]
);
// Will contain none
@@ -515,10 +579,21 @@
i: 42,
weight: Weight::from_ref_time(10),
}));
- assert_ok!(
- Scheduler::schedule_named(RuntimeOrigin::root(), [1u8; 32], 4, None, Some(127), call,)
- );
- assert_ok!(Scheduler::schedule(RuntimeOrigin::root(), 4, None, Some(127), call2));
+ assert_ok!(Scheduler::schedule_named(
+ RuntimeOrigin::root(),
+ [1u8; 32],
+ 4,
+ None,
+ Some(127),
+ call,
+ ));
+ assert_ok!(Scheduler::schedule(
+ RuntimeOrigin::root(),
+ 4,
+ None,
+ Some(127),
+ call2
+ ));
run_to_block(3);
// Scheduled calls are in the agenda.
assert_eq!(Agenda::<Test>::get(4).len(), 2);
@@ -585,12 +660,21 @@
None,
call,
));
- assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, None, call2,));
+ assert_ok!(Scheduler::schedule(
+ system::RawOrigin::Signed(1).into(),
+ 4,
+ None,
+ None,
+ call2,
+ ));
run_to_block(3);
// Scheduled calls are in the agenda.
assert_eq!(Agenda::<Test>::get(4).len(), 2);
assert!(logger::log().is_empty());
- assert_ok!(Scheduler::cancel_named(system::RawOrigin::Signed(1).into(), [1u8; 32]));
+ assert_ok!(Scheduler::cancel_named(
+ system::RawOrigin::Signed(1).into(),
+ [1u8; 32]
+ ));
assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
// Scheduled calls are made NONE, so should not effect state
run_to_block(100);
@@ -646,7 +730,13 @@
None,
call,
));
- assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, None, call2,));
+ assert_ok!(Scheduler::schedule(
+ system::RawOrigin::Signed(1).into(),
+ 4,
+ None,
+ None,
+ call2,
+ ));
run_to_block(3);
// Scheduled calls are in the agenda.
assert_eq!(Agenda::<Test>::get(4).len(), 2);
@@ -655,9 +745,18 @@
Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), [1u8; 32]),
BadOrigin
);
- assert_noop!(Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1), BadOrigin);
- assert_noop!(Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]), BadOrigin);
- assert_noop!(Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1), BadOrigin);
+ assert_noop!(
+ Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1),
+ BadOrigin
+ );
+ assert_noop!(
+ Scheduler::cancel_named(system::RawOrigin::Root.into(), [1u8; 32]),
+ BadOrigin
+ );
+ assert_noop!(
+ Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1),
+ BadOrigin
+ );
run_to_block(5);
assert_eq!(
logger::log(),
@@ -674,8 +773,10 @@
#[test]
fn schedule_does_not_resuse_addr() {
new_test_ext().execute_with(|| {
- let call =
- RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(10) });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
// Schedule both calls.
let addr_1 = Scheduler::do_schedule(
@@ -707,20 +808,15 @@
let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
new_test_ext().execute_with(|| {
- let call =
- RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(10) });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
let call = <ScheduledCall<Test>>::new(call).unwrap();
// Schedule the maximal number allowed per block.
for _ in 0..max {
- Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call.clone(),
- )
- .unwrap();
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone()).unwrap();
}
// One more time and it errors.
@@ -739,25 +835,24 @@
#[test]
fn cancel_and_schedule_fills_holes() {
let max: u32 = <Test as Config>::MaxScheduledPerBlock::get();
- assert!(max > 3, "This test only makes sense for MaxScheduledPerBlock > 3");
+ assert!(
+ max > 3,
+ "This test only makes sense for MaxScheduledPerBlock > 3"
+ );
new_test_ext().execute_with(|| {
- let call =
- RuntimeCall::Logger(LoggerCall::log { i: 42, weight: Weight::from_ref_time(10) });
+ let call = RuntimeCall::Logger(LoggerCall::log {
+ i: 42,
+ weight: Weight::from_ref_time(10),
+ });
let call = <ScheduledCall<Test>>::new(call).unwrap();
let mut addrs = Vec::<_>::default();
// Schedule the maximal number allowed per block.
for _ in 0..max {
addrs.push(
- Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call.clone(),
- )
- .unwrap(),
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
+ .unwrap(),
);
}
// Cancel three of them.
@@ -766,14 +861,9 @@
}
// Schedule three new ones.
for i in 0..3 {
- let (_block, index) = Scheduler::do_schedule(
- DispatchTime::At(4),
- None,
- 127,
- root(),
- call.clone(),
- )
- .unwrap();
+ let (_block, index) =
+ Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call.clone())
+ .unwrap();
assert_eq!(i, index);
}
runtime/common/scheduler.rsdiffbeforeafterboth--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -105,7 +105,6 @@
}
}
-
// impl<T: frame_system::Config + pallet_unique_scheduler::Config, SelfContainedSignedInfo>
// DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
// where