difftreelog
fix cargo fmt
in: master
2 files changed
pallets/scheduler/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.0>28//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//! # Unique 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//! should be named and may be canceled.47//!48//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.49//! Any user can book a call of a certain transaction to a specific block number.50//! Also possible to book a call with a certain frequency.51//!52//! Key differences from the original pallet:53//! <https://crates.io/crates/pallet-scheduler>54//! Schedule Id restricted by 16 bytes. Identificator for booked call.55//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block.56//! The maximum weight that may be scheduled per block for any dispatchables of less priority than `schedule::HARD_DEADLINE`.57//! Maybe_periodic limit is 100 calls. Reserved for future sponsored transaction support.58//! At 100 calls reserved amount is not so much and this is avoid potential problems with balance locks.59//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.60//!61//! ## Interface62//!63//! ### Dispatchable Functions64//!65//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter66//! that can be used for identification.67//! * `cancel_named` - the named complement to the cancel function.6869// Ensure we're `no_std` when compiling for Wasm.70#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83 traits::{BadOrigin, One, Saturating, Zero},84 RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89 dispatch::{DispatchError, DispatchResult, Dispatchable, UnfilteredDispatchable, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{Weight},96};9798pub use weights::WeightInfo;99100/// The location of a scheduled task that can be used to remove it.101pub type TaskAddress<BlockNumber> = (BlockNumber, u32);102pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;103104type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];105pub type CallOrHashOf<T> =106 MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;107108/// Information regarding an item to be executed in the future.109#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]110#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]111pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {112 /// The unique identity for this task, if there is one.113 maybe_id: Option<ScheduledId>,114 /// This task's priority.115 priority: schedule::Priority,116 /// The call to be dispatched.117 call: Call,118 /// If the call is periodic, then this points to the information concerning that.119 maybe_periodic: Option<schedule::Period<BlockNumber>>,120 /// The origin to dispatch the call.121 origin: PalletsOrigin,122 _phantom: PhantomData<AccountId>,123}124125pub type ScheduledV3Of<T> = ScheduledV3<126 CallOrHashOf<T>,127 <T as frame_system::Config>::BlockNumber,128 <T as Config>::PalletsOrigin,129 <T as frame_system::Config>::AccountId,130>;131132pub type ScheduledOf<T> = ScheduledV3Of<T>;133134/// The current version of Scheduled struct.135pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =136 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;137138pub enum ScheduledEnsureOriginSuccess<AccountId> {139 Root,140 Signed(AccountId),141 Unsigned,142}143144#[cfg(feature = "runtime-benchmarks")]145mod preimage_provider {146 use frame_support::traits::PreimageRecipient;147 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}148 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}149}150151#[cfg(not(feature = "runtime-benchmarks"))]152mod preimage_provider {153 use frame_support::traits::PreimageProvider;154 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}155 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}156}157158pub use preimage_provider::PreimageProviderAndMaybeRecipient;159160pub(crate) trait MarginalWeightInfo: WeightInfo {161 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {162 match (periodic, named, resolved) {163 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),164 (_, true, None) => {165 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)166 }167 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),168 (false, true, Some(false)) => {169 Self::on_initialize_named(2) - Self::on_initialize_named(1)170 }171 (true, false, Some(false)) => {172 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)173 }174 (true, true, Some(false)) => {175 Self::on_initialize_periodic_named_resolved(2)176 - Self::on_initialize_periodic_named_resolved(1)177 }178 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),179 (false, true, Some(true)) => {180 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)181 }182 (true, false, Some(true)) => {183 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)184 }185 (true, true, Some(true)) => {186 Self::on_initialize_periodic_named_resolved(2)187 - Self::on_initialize_periodic_named_resolved(1)188 }189 }190 }191}192impl<T: WeightInfo> MarginalWeightInfo for T {}193194#[frame_support::pallet]195pub mod pallet {196 use super::*;197 use frame_support::{198 dispatch::PostDispatchInfo,199 pallet_prelude::*,200 traits::{201 schedule::{LookupError, LOWEST_PRIORITY},202 PreimageProvider,203 },204 };205 use frame_system::pallet_prelude::*;206207 /// The current storage version.208 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);209210 #[pallet::pallet]211 #[pallet::generate_store(pub(super) trait Store)]212 #[pallet::storage_version(STORAGE_VERSION)]213 #[pallet::without_storage_info]214 pub struct Pallet<T>(_);215216 /// `system::Config` should always be included in our implied traits.217 #[pallet::config]218 pub trait Config: frame_system::Config {219 /// The overarching event type.220 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;221222 /// The aggregated origin which the dispatch will take.223 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>224 + From<Self::PalletsOrigin>225 + IsType<<Self as system::Config>::RuntimeOrigin>;226227 /// The caller origin, overarching type of all pallets origins.228 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;229230 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;231232 /// The aggregated call type.233 type RuntimeCall: Parameter234 + Dispatchable<Origin = <Self as Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>235 + UnfilteredDispatchable<Origin = <Self as system::Config>::RuntimeOrigin>236 + GetDispatchInfo237 + From<system::RuntimeCall<Self>>;238239 /// The maximum weight that may be scheduled per block for any dispatchables of less240 /// priority than `schedule::HARD_DEADLINE`.241 #[pallet::constant]242 type MaximumWeight: Get<Weight>;243244 /// Required origin to schedule or cancel calls.245 type ScheduleOrigin: EnsureOrigin<246 <Self as system::Config>::RuntimeOrigin,247 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,248 >;249250 /// Required origin to set/change calls' priority.251 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;252253 /// Compare the privileges of origins.254 ///255 /// This will be used when canceling a task, to ensure that the origin that tries256 /// to cancel has greater or equal privileges as the origin that created the scheduled task.257 ///258 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can259 /// be used. This will only check if two given origins are equal.260 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;261262 /// The maximum number of scheduled calls in the queue for a single block.263 /// Not strictly enforced, but used for weight estimation.264 #[pallet::constant]265 type MaxScheduledPerBlock: Get<u32>;266267 /// Weight information for extrinsics in this pallet.268 type WeightInfo: WeightInfo;269270 /// The preimage provider with which we look up call hashes to get the call.271 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;272273 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.274 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;275276 /// Sponsoring function.277 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;278279 /// The helper type used for custom transaction fee logic.280 type CallExecutor: DispatchCall<Self, H160>;281 }282283 /// A Scheduler-Runtime interface for finer payment handling.284 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {285 /// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.286 fn reserve_balance(287 id: ScheduledId,288 sponsor: <T as frame_system::Config>::AccountId,289 call: <T as Config>::RuntimeCall,290 count: u32,291 ) -> Result<(), DispatchError>;292293 /// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.294 fn pay_for_call(295 id: ScheduledId,296 sponsor: <T as frame_system::Config>::AccountId,297 call: <T as Config>::RuntimeCall,298 ) -> Result<u128, DispatchError>;299300 /// Resolve the call dispatch, including any post-dispatch operations.301 fn dispatch_call(302 signer: Option<T::AccountId>,303 function: <T as Config>::RuntimeCall,304 ) -> Result<305 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,306 TransactionValidityError,307 >;308309 /// Release unspent reserved funds in case of a schedule cancel.310 fn cancel_reserve(311 id: ScheduledId,312 sponsor: <T as frame_system::Config>::AccountId,313 ) -> Result<u128, DispatchError>;314 }315316 /// Items to be executed, indexed by the block number that they should be executed on.317 #[pallet::storage]318 pub type Agenda<T: Config> =319 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;320321 /// Lookup from identity to the block number and index of the task.322 #[pallet::storage]323 pub(crate) type Lookup<T: Config> =324 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;325326 /// Events type.327 #[pallet::event]328 #[pallet::generate_deposit(pub(super) fn deposit_event)]329 pub enum Event<T: Config> {330 /// Scheduled some task.331 Scheduled { when: T::BlockNumber, index: u32 },332 /// Canceled some task.333 Canceled { when: T::BlockNumber, index: u32 },334 /// Scheduled task's priority has changed335 PriorityChanged {336 when: T::BlockNumber,337 index: u32,338 priority: schedule::Priority,339 },340 /// Dispatched some task.341 Dispatched {342 task: TaskAddress<T::BlockNumber>,343 id: Option<ScheduledId>,344 result: DispatchResult,345 },346 /// The call for the provided hash was not found so the task has been aborted.347 CallLookupFailed {348 task: TaskAddress<T::BlockNumber>,349 id: Option<ScheduledId>,350 error: LookupError,351 },352 }353354 #[pallet::error]355 pub enum Error<T> {356 /// Failed to schedule a call357 FailedToSchedule,358 /// Cannot find the scheduled call.359 NotFound,360 /// Given target block number is in the past.361 TargetBlockNumberInPast,362 /// Reschedule failed because it does not change scheduled time.363 RescheduleNoChange,364 }365366 #[pallet::hooks]367 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {368 /// Execute the scheduled calls369 fn on_initialize(now: T::BlockNumber) -> Weight {370 let limit = T::MaximumWeight::get();371372 let mut queued = Agenda::<T>::take(now)373 .into_iter()374 .enumerate()375 .filter_map(|(index, s)| Some((index as u32, s?)))376 .collect::<Vec<_>>();377378 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {379 log::warn!(380 target: "runtime::scheduler",381 "Warning: This block has more items queued in Scheduler than \382 expected from the runtime configuration. An update might be needed."383 );384 }385386 queued.sort_by_key(|(_, s)| s.priority);387388 let next = now + One::one();389390 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);391 for (order, (index, mut s)) in queued.into_iter().enumerate() {392 let named = s.maybe_id.is_some();393394 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();395 s.call = call;396397 let resolved = if let Some(completed) = maybe_completed {398 T::PreimageProvider::unrequest_preimage(&completed);399 true400 } else {401 false402 };403 let call = match s.call.as_value().cloned() {404 Some(c) => c,405 None => {406 // Preimage not available - postpone until some block.407 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));408 if let Some(delay) = T::NoPreimagePostponement::get() {409 let until = now.saturating_add(delay);410 if let Some(ref id) = s.maybe_id {411 let index = Agenda::<T>::decode_len(until).unwrap_or(0);412 Lookup::<T>::insert(id, (until, index as u32));413 }414 Agenda::<T>::append(until, Some(s));415 } else if let Some(ref id) = s.maybe_id {416 Lookup::<T>::remove(id);417 }418 continue;419 }420 };421422 let periodic = s.maybe_periodic.is_some();423 let call_weight = call.get_dispatch_info().weight;424 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));425 let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(426 s.origin.clone(),427 )428 .into();429 if ensure_signed(origin).is_ok() {430 // Weights of Signed dispatches expect their signing account to be whitelisted.431 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));432 }433434 // We allow a scheduled call if any is true:435 // - It's priority is `HARD_DEADLINE`436 // - It does not push the weight past the limit.437 // - It is the first item in the schedule438 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;439 let test_weight = total_weight440 .saturating_add(call_weight)441 .saturating_add(item_weight);442 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {443 // Cannot be scheduled this block - postpone until next.444 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));445 if let Some(ref id) = s.maybe_id {446 // NOTE: We could reasonably not do this (in which case there would be one447 // block where the named and delayed item could not be referenced by name),448 // but we will do it anyway since it should be mostly free in terms of449 // weight and it is slightly cleaner.450 let index = Agenda::<T>::decode_len(next).unwrap_or(0);451 Lookup::<T>::insert(id, (next, index as u32));452 }453 Agenda::<T>::append(next, Some(s));454 continue;455 }456457 let scheduled_origin =458 <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(s.origin.clone());459 let ensured_origin =460 T::ScheduleOrigin::ensure_origin(scheduled_origin.into());461462 let r = match ensured_origin {463 Ok(ScheduledEnsureOriginSuccess::Root) => {464 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))465 }466 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {467 // Execute transaction via chain default pipeline468 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken469 T::CallExecutor::dispatch_call(Some(sender), call.clone())470 }471 Ok(ScheduledEnsureOriginSuccess::Unsigned) => {472 // Unsigned version of the above473 T::CallExecutor::dispatch_call(None, call.clone())474 },475 Err(e) => Ok(Err(e.into())),476 };477478 let mut actual_call_weight: Weight = item_weight;479 let result: Result<_, DispatchError> = match r {480 Ok(o) => match o {481 Ok(di) => {482 actual_call_weight = di.actual_weight.unwrap_or(item_weight);483 Ok(())484 }485 Err(err) => Err(err.error),486 },487 Err(_) => {488 log::error!(489 target: "runtime::scheduler",490 "Warning: Scheduler has failed to execute a post-dispatch transaction. \491 This block might have become invalid.");492 Err(DispatchError::CannotLookup)493 } // todo possibly force a skip/return here, do something with the error494 };495496 total_weight.saturating_accrue(item_weight);497 total_weight.saturating_accrue(actual_call_weight);498499 Self::deposit_event(Event::Dispatched {500 task: (now, index),501 id: s.maybe_id.clone(),502 result,503 });504505 if let &Some((period, count)) = &s.maybe_periodic {506 if count > 1 {507 s.maybe_periodic = Some((period, count - 1));508 } else {509 s.maybe_periodic = None;510 }511 let wake = now + period;512 let is_canceled;513514 // If scheduled is named, place its information in `Lookup`515 if let Some(ref id) = s.maybe_id {516 is_canceled = Lookup::<T>::get(id).is_none();517 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);518519 if !is_canceled {520 Lookup::<T>::insert(id, (wake, wake_index as u32));521 }522 } else {523 is_canceled = false;524 }525526 if !is_canceled {527 Agenda::<T>::append(wake, Some(s));528 }529 } else if let Some(ref id) = s.maybe_id {530 Lookup::<T>::remove(id);531 }532 }533 total_weight534 }535 }536537 #[pallet::call]538 impl<T: Config> Pallet<T> {539 /// Schedule a named task.540 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]541 pub fn schedule_named(542 origin: OriginFor<T>,543 id: ScheduledId,544 when: T::BlockNumber,545 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,546 priority: Option<schedule::Priority>,547 call: Box<CallOrHashOf<T>>,548 ) -> DispatchResult {549 T::ScheduleOrigin::ensure_origin(origin.clone())?;550551 if priority.is_some() {552 T::PrioritySetOrigin::ensure_origin(origin.clone())?;553 }554555 let origin = <T as Config>::RuntimeOrigin::from(origin);556 Self::do_schedule_named(557 id,558 DispatchTime::At(when),559 maybe_periodic,560 priority.unwrap_or(LOWEST_PRIORITY),561 origin.caller().clone(),562 *call,563 )?;564 Ok(())565 }566567 /// Cancel a named scheduled task.568 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]569 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {570 T::ScheduleOrigin::ensure_origin(origin.clone())?;571 let origin = <T as Config>::RuntimeOrigin::from(origin);572 Self::do_cancel_named(Some(origin.caller().clone()), id)?;573 Ok(())574 }575576 /// Schedule a named task after a delay.577 ///578 /// # <weight>579 /// Same as [`schedule_named`](Self::schedule_named).580 /// # </weight>581 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]582 pub fn schedule_named_after(583 origin: OriginFor<T>,584 id: ScheduledId,585 after: T::BlockNumber,586 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,587 priority: Option<schedule::Priority>,588 call: Box<CallOrHashOf<T>>,589 ) -> DispatchResult {590 T::ScheduleOrigin::ensure_origin(origin.clone())?;591592 if priority.is_some() {593 T::PrioritySetOrigin::ensure_origin(origin.clone())?;594 }595596 let origin = <T as Config>::RuntimeOrigin::from(origin);597 Self::do_schedule_named(598 id,599 DispatchTime::After(after),600 maybe_periodic,601 priority.unwrap_or(LOWEST_PRIORITY),602 origin.caller().clone(),603 *call,604 )?;605 Ok(())606 }607608 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]609 pub fn change_named_priority(610 origin: OriginFor<T>,611 id: ScheduledId,612 priority: schedule::Priority,613 ) -> DispatchResult {614 T::PrioritySetOrigin::ensure_origin(origin.clone())?;615 let origin = <T as Config>::Origin::from(origin);616 Self::do_change_named_priority(origin.caller().clone(), id, priority)617 }618 }619}620621impl<T: Config> Pallet<T> {622 #[cfg(feature = "try-runtime")]623 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {624 Ok(())625 }626627 #[cfg(feature = "try-runtime")]628 pub fn post_migrate_to_v3() -> Result<(), &'static str> {629 use frame_support::dispatch::GetStorageVersion;630631 assert!(Self::current_storage_version() == 3);632 for k in Agenda::<T>::iter_keys() {633 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;634 }635 Ok(())636 }637638 /// Helper to migrate scheduler when the pallet origin type has changed.639 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {640 Agenda::<T>::translate::<641 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,642 _,643 >(|_, agenda| {644 Some(645 agenda646 .into_iter()647 .map(|schedule| {648 schedule.map(|schedule| Scheduled {649 maybe_id: schedule.maybe_id,650 priority: schedule.priority,651 call: schedule.call,652 maybe_periodic: schedule.maybe_periodic,653 origin: schedule.origin.into(),654 _phantom: Default::default(),655 })656 })657 .collect::<Vec<_>>(),658 )659 });660 }661662 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {663 let now = frame_system::Pallet::<T>::block_number();664665 let when = match when {666 DispatchTime::At(x) => x,667 // The current block has already completed it's scheduled tasks, so668 // Schedule the task at lest one block after this current block.669 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),670 };671672 if when <= now {673 return Err(Error::<T>::TargetBlockNumberInPast.into());674 }675676 Ok(when)677 }678679 fn do_schedule_named(680 id: ScheduledId,681 when: DispatchTime<T::BlockNumber>,682 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,683 priority: schedule::Priority,684 origin: T::PalletsOrigin,685 call: CallOrHashOf<T>,686 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {687 // ensure id it is unique688 if Lookup::<T>::contains_key(&id) {689 return Err(Error::<T>::FailedToSchedule)?;690 }691692 let when = Self::resolve_time(when)?;693694 call.ensure_requested::<T::PreimageProvider>();695696 // sanitize maybe_periodic697 let maybe_periodic = maybe_periodic698 .filter(|p| p.1 > 1 && !p.0.is_zero())699 // Remove one from the number of repetitions since we will schedule one now.700 .map(|(p, c)| (p, c - 1));701702 let s = Scheduled {703 maybe_id: Some(id.clone()),704 priority,705 call: call.clone(),706 maybe_periodic,707 origin: origin.clone(),708 _phantom: Default::default(),709 };710711 // reserve balance for periodic execution712 // let sender =713 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;714 // let repeats = match maybe_periodic {715 // Some(p) => p.1,716 // None => 1,717 // };718 // let _ = T::CallExecutor::reserve_balance(719 // id.clone(),720 // sender,721 // call.as_value().unwrap().clone(),722 // repeats,723 // );724725 Agenda::<T>::append(when, Some(s));726 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;727 let address = (when, index);728 Lookup::<T>::insert(&id, &address);729 Self::deposit_event(Event::Scheduled { when, index });730731 Ok(address)732 }733734 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {735 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {736 if let Some((when, index)) = lookup.take() {737 let i = index as usize;738 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {739 if let Some(s) = agenda.get_mut(i) {740 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {741 if matches!(742 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),743 Some(Ordering::Less) | None744 ) {745 return Err(BadOrigin.into());746 }747 // release balance reserve748 // let sender = ensure_signed(749 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(750 // origin.unwrap(),751 // )752 // .into(),753 // )?;754 // let _ = T::CallExecutor::cancel_reserve(id, sender);755756 s.call.ensure_unrequested::<T::PreimageProvider>();757 }758 *s = None;759 }760 Ok(())761 })?;762763 Self::deposit_event(Event::Canceled { when, index });764 Ok(())765 } else {766 Err(Error::<T>::NotFound)?767 }768 })769 }770771 fn do_change_named_priority(772 origin: T::PalletsOrigin,773 id: ScheduledId,774 priority: schedule::Priority,775 ) -> DispatchResult {776 match Lookup::<T>::get(id) {777 Some((when, index)) => {778 let i = index as usize;779 Agenda::<T>::try_mutate(when, |agenda| {780 if let Some(Some(s)) = agenda.get_mut(i) {781 if matches!(782 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),783 Some(Ordering::Less) | None784 ) {785 return Err(BadOrigin.into());786 }787788 s.priority = priority;789 Self::deposit_event(Event::PriorityChanged {790 when,791 index,792 priority,793 });794 }795 Ok(())796 })797 }798 None => Err(Error::<T>::NotFound.into()),799 }800 }801}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.0>28//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//! # Unique 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//! should be named and may be canceled.47//!48//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.49//! Any user can book a call of a certain transaction to a specific block number.50//! Also possible to book a call with a certain frequency.51//!52//! Key differences from the original pallet:53//! <https://crates.io/crates/pallet-scheduler>54//! Schedule Id restricted by 16 bytes. Identificator for booked call.55//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block.56//! The maximum weight that may be scheduled per block for any dispatchables of less priority than `schedule::HARD_DEADLINE`.57//! Maybe_periodic limit is 100 calls. Reserved for future sponsored transaction support.58//! At 100 calls reserved amount is not so much and this is avoid potential problems with balance locks.59//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.60//!61//! ## Interface62//!63//! ### Dispatchable Functions64//!65//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter66//! that can be used for identification.67//! * `cancel_named` - the named complement to the cancel function.6869// Ensure we're `no_std` when compiling for Wasm.70#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83 traits::{BadOrigin, One, Saturating, Zero},84 RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89 dispatch::{DispatchError, DispatchResult, Dispatchable, UnfilteredDispatchable, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{Weight},96};9798pub use weights::WeightInfo;99100/// The location of a scheduled task that can be used to remove it.101pub type TaskAddress<BlockNumber> = (BlockNumber, u32);102pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;103104type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];105pub type CallOrHashOf<T> =106 MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;107108/// Information regarding an item to be executed in the future.109#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]110#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]111pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {112 /// The unique identity for this task, if there is one.113 maybe_id: Option<ScheduledId>,114 /// This task's priority.115 priority: schedule::Priority,116 /// The call to be dispatched.117 call: Call,118 /// If the call is periodic, then this points to the information concerning that.119 maybe_periodic: Option<schedule::Period<BlockNumber>>,120 /// The origin to dispatch the call.121 origin: PalletsOrigin,122 _phantom: PhantomData<AccountId>,123}124125pub type ScheduledV3Of<T> = ScheduledV3<126 CallOrHashOf<T>,127 <T as frame_system::Config>::BlockNumber,128 <T as Config>::PalletsOrigin,129 <T as frame_system::Config>::AccountId,130>;131132pub type ScheduledOf<T> = ScheduledV3Of<T>;133134/// The current version of Scheduled struct.135pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =136 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;137138pub enum ScheduledEnsureOriginSuccess<AccountId> {139 Root,140 Signed(AccountId),141 Unsigned,142}143144#[cfg(feature = "runtime-benchmarks")]145mod preimage_provider {146 use frame_support::traits::PreimageRecipient;147 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}148 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}149}150151#[cfg(not(feature = "runtime-benchmarks"))]152mod preimage_provider {153 use frame_support::traits::PreimageProvider;154 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}155 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}156}157158pub use preimage_provider::PreimageProviderAndMaybeRecipient;159160pub(crate) trait MarginalWeightInfo: WeightInfo {161 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {162 match (periodic, named, resolved) {163 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),164 (_, true, None) => {165 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)166 }167 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),168 (false, true, Some(false)) => {169 Self::on_initialize_named(2) - Self::on_initialize_named(1)170 }171 (true, false, Some(false)) => {172 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)173 }174 (true, true, Some(false)) => {175 Self::on_initialize_periodic_named_resolved(2)176 - Self::on_initialize_periodic_named_resolved(1)177 }178 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),179 (false, true, Some(true)) => {180 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)181 }182 (true, false, Some(true)) => {183 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)184 }185 (true, true, Some(true)) => {186 Self::on_initialize_periodic_named_resolved(2)187 - Self::on_initialize_periodic_named_resolved(1)188 }189 }190 }191}192impl<T: WeightInfo> MarginalWeightInfo for T {}193194#[frame_support::pallet]195pub mod pallet {196 use super::*;197 use frame_support::{198 dispatch::PostDispatchInfo,199 pallet_prelude::*,200 traits::{201 schedule::{LookupError, LOWEST_PRIORITY},202 PreimageProvider,203 },204 };205 use frame_system::pallet_prelude::*;206207 /// The current storage version.208 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);209210 #[pallet::pallet]211 #[pallet::generate_store(pub(super) trait Store)]212 #[pallet::storage_version(STORAGE_VERSION)]213 #[pallet::without_storage_info]214 pub struct Pallet<T>(_);215216 /// `system::Config` should always be included in our implied traits.217 #[pallet::config]218 pub trait Config: frame_system::Config {219 /// The overarching event type.220 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;221222 /// The aggregated origin which the dispatch will take.223 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>224 + From<Self::PalletsOrigin>225 + IsType<<Self as system::Config>::RuntimeOrigin>;226227 /// The caller origin, overarching type of all pallets origins.228 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;229230 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;231232 /// The aggregated call type.233 type RuntimeCall: Parameter234 + Dispatchable<Origin = <Self as Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>235 + UnfilteredDispatchable<Origin = <Self as system::Config>::RuntimeOrigin>236 + GetDispatchInfo237 + From<system::RuntimeCall<Self>>;238239 /// The maximum weight that may be scheduled per block for any dispatchables of less240 /// priority than `schedule::HARD_DEADLINE`.241 #[pallet::constant]242 type MaximumWeight: Get<Weight>;243244 /// Required origin to schedule or cancel calls.245 type ScheduleOrigin: EnsureOrigin<246 <Self as system::Config>::RuntimeOrigin,247 Success = ScheduledEnsureOriginSuccess<Self::AccountId>,248 >;249250 /// Required origin to set/change calls' priority.251 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;252253 /// Compare the privileges of origins.254 ///255 /// This will be used when canceling a task, to ensure that the origin that tries256 /// to cancel has greater or equal privileges as the origin that created the scheduled task.257 ///258 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can259 /// be used. This will only check if two given origins are equal.260 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;261262 /// The maximum number of scheduled calls in the queue for a single block.263 /// Not strictly enforced, but used for weight estimation.264 #[pallet::constant]265 type MaxScheduledPerBlock: Get<u32>;266267 /// Weight information for extrinsics in this pallet.268 type WeightInfo: WeightInfo;269270 /// The preimage provider with which we look up call hashes to get the call.271 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;272273 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.274 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;275276 /// Sponsoring function.277 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;278279 /// The helper type used for custom transaction fee logic.280 type CallExecutor: DispatchCall<Self, H160>;281 }282283 /// A Scheduler-Runtime interface for finer payment handling.284 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {285 /// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.286 fn reserve_balance(287 id: ScheduledId,288 sponsor: <T as frame_system::Config>::AccountId,289 call: <T as Config>::RuntimeCall,290 count: u32,291 ) -> Result<(), DispatchError>;292293 /// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.294 fn pay_for_call(295 id: ScheduledId,296 sponsor: <T as frame_system::Config>::AccountId,297 call: <T as Config>::RuntimeCall,298 ) -> Result<u128, DispatchError>;299300 /// Resolve the call dispatch, including any post-dispatch operations.301 fn dispatch_call(302 signer: Option<T::AccountId>,303 function: <T as Config>::RuntimeCall,304 ) -> Result<305 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,306 TransactionValidityError,307 >;308309 /// Release unspent reserved funds in case of a schedule cancel.310 fn cancel_reserve(311 id: ScheduledId,312 sponsor: <T as frame_system::Config>::AccountId,313 ) -> Result<u128, DispatchError>;314 }315316 /// Items to be executed, indexed by the block number that they should be executed on.317 #[pallet::storage]318 pub type Agenda<T: Config> =319 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;320321 /// Lookup from identity to the block number and index of the task.322 #[pallet::storage]323 pub(crate) type Lookup<T: Config> =324 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;325326 /// Events type.327 #[pallet::event]328 #[pallet::generate_deposit(pub(super) fn deposit_event)]329 pub enum Event<T: Config> {330 /// Scheduled some task.331 Scheduled { when: T::BlockNumber, index: u32 },332 /// Canceled some task.333 Canceled { when: T::BlockNumber, index: u32 },334 /// Scheduled task's priority has changed335 PriorityChanged {336 when: T::BlockNumber,337 index: u32,338 priority: schedule::Priority,339 },340 /// Dispatched some task.341 Dispatched {342 task: TaskAddress<T::BlockNumber>,343 id: Option<ScheduledId>,344 result: DispatchResult,345 },346 /// The call for the provided hash was not found so the task has been aborted.347 CallLookupFailed {348 task: TaskAddress<T::BlockNumber>,349 id: Option<ScheduledId>,350 error: LookupError,351 },352 }353354 #[pallet::error]355 pub enum Error<T> {356 /// Failed to schedule a call357 FailedToSchedule,358 /// Cannot find the scheduled call.359 NotFound,360 /// Given target block number is in the past.361 TargetBlockNumberInPast,362 /// Reschedule failed because it does not change scheduled time.363 RescheduleNoChange,364 }365366 #[pallet::hooks]367 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {368 /// Execute the scheduled calls369 fn on_initialize(now: T::BlockNumber) -> Weight {370 let limit = T::MaximumWeight::get();371372 let mut queued = Agenda::<T>::take(now)373 .into_iter()374 .enumerate()375 .filter_map(|(index, s)| Some((index as u32, s?)))376 .collect::<Vec<_>>();377378 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {379 log::warn!(380 target: "runtime::scheduler",381 "Warning: This block has more items queued in Scheduler than \382 expected from the runtime configuration. An update might be needed."383 );384 }385386 queued.sort_by_key(|(_, s)| s.priority);387388 let next = now + One::one();389390 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);391 for (order, (index, mut s)) in queued.into_iter().enumerate() {392 let named = s.maybe_id.is_some();393394 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();395 s.call = call;396397 let resolved = if let Some(completed) = maybe_completed {398 T::PreimageProvider::unrequest_preimage(&completed);399 true400 } else {401 false402 };403 let call = match s.call.as_value().cloned() {404 Some(c) => c,405 None => {406 // Preimage not available - postpone until some block.407 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));408 if let Some(delay) = T::NoPreimagePostponement::get() {409 let until = now.saturating_add(delay);410 if let Some(ref id) = s.maybe_id {411 let index = Agenda::<T>::decode_len(until).unwrap_or(0);412 Lookup::<T>::insert(id, (until, index as u32));413 }414 Agenda::<T>::append(until, Some(s));415 } else if let Some(ref id) = s.maybe_id {416 Lookup::<T>::remove(id);417 }418 continue;419 }420 };421422 let periodic = s.maybe_periodic.is_some();423 let call_weight = call.get_dispatch_info().weight;424 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));425 let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(426 s.origin.clone(),427 )428 .into();429 if ensure_signed(origin).is_ok() {430 // Weights of Signed dispatches expect their signing account to be whitelisted.431 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));432 }433434 // We allow a scheduled call if any is true:435 // - It's priority is `HARD_DEADLINE`436 // - It does not push the weight past the limit.437 // - It is the first item in the schedule438 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;439 let test_weight = total_weight440 .saturating_add(call_weight)441 .saturating_add(item_weight);442 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {443 // Cannot be scheduled this block - postpone until next.444 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));445 if let Some(ref id) = s.maybe_id {446 // NOTE: We could reasonably not do this (in which case there would be one447 // block where the named and delayed item could not be referenced by name),448 // but we will do it anyway since it should be mostly free in terms of449 // weight and it is slightly cleaner.450 let index = Agenda::<T>::decode_len(next).unwrap_or(0);451 Lookup::<T>::insert(id, (next, index as u32));452 }453 Agenda::<T>::append(next, Some(s));454 continue;455 }456457 let scheduled_origin =458 <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(s.origin.clone());459 let ensured_origin = T::ScheduleOrigin::ensure_origin(scheduled_origin.into());460461 let r = match ensured_origin {462 Ok(ScheduledEnsureOriginSuccess::Root) => {463 Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()))464 }465 Ok(ScheduledEnsureOriginSuccess::Signed(sender)) => {466 // Execute transaction via chain default pipeline467 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken468 T::CallExecutor::dispatch_call(Some(sender), call.clone())469 }470 Ok(ScheduledEnsureOriginSuccess::Unsigned) => {471 // Unsigned version of the above472 T::CallExecutor::dispatch_call(None, call.clone())473 }474 Err(e) => Ok(Err(e.into())),475 };476477 let mut actual_call_weight: Weight = item_weight;478 let result: Result<_, DispatchError> = match r {479 Ok(o) => match o {480 Ok(di) => {481 actual_call_weight = di.actual_weight.unwrap_or(item_weight);482 Ok(())483 }484 Err(err) => Err(err.error),485 },486 Err(_) => {487 log::error!(488 target: "runtime::scheduler",489 "Warning: Scheduler has failed to execute a post-dispatch transaction. \490 This block might have become invalid.");491 Err(DispatchError::CannotLookup)492 } // todo possibly force a skip/return here, do something with the error493 };494495 total_weight.saturating_accrue(item_weight);496 total_weight.saturating_accrue(actual_call_weight);497498 Self::deposit_event(Event::Dispatched {499 task: (now, index),500 id: s.maybe_id.clone(),501 result,502 });503504 if let &Some((period, count)) = &s.maybe_periodic {505 if count > 1 {506 s.maybe_periodic = Some((period, count - 1));507 } else {508 s.maybe_periodic = None;509 }510 let wake = now + period;511 let is_canceled;512513 // If scheduled is named, place its information in `Lookup`514 if let Some(ref id) = s.maybe_id {515 is_canceled = Lookup::<T>::get(id).is_none();516 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);517518 if !is_canceled {519 Lookup::<T>::insert(id, (wake, wake_index as u32));520 }521 } else {522 is_canceled = false;523 }524525 if !is_canceled {526 Agenda::<T>::append(wake, Some(s));527 }528 } else if let Some(ref id) = s.maybe_id {529 Lookup::<T>::remove(id);530 }531 }532 total_weight533 }534 }535536 #[pallet::call]537 impl<T: Config> Pallet<T> {538 /// Schedule a named task.539 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]540 pub fn schedule_named(541 origin: OriginFor<T>,542 id: ScheduledId,543 when: T::BlockNumber,544 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,545 priority: Option<schedule::Priority>,546 call: Box<CallOrHashOf<T>>,547 ) -> DispatchResult {548 T::ScheduleOrigin::ensure_origin(origin.clone())?;549550 if priority.is_some() {551 T::PrioritySetOrigin::ensure_origin(origin.clone())?;552 }553554 let origin = <T as Config>::RuntimeOrigin::from(origin);555 Self::do_schedule_named(556 id,557 DispatchTime::At(when),558 maybe_periodic,559 priority.unwrap_or(LOWEST_PRIORITY),560 origin.caller().clone(),561 *call,562 )?;563 Ok(())564 }565566 /// Cancel a named scheduled task.567 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]568 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {569 T::ScheduleOrigin::ensure_origin(origin.clone())?;570 let origin = <T as Config>::RuntimeOrigin::from(origin);571 Self::do_cancel_named(Some(origin.caller().clone()), id)?;572 Ok(())573 }574575 /// Schedule a named task after a delay.576 ///577 /// # <weight>578 /// Same as [`schedule_named`](Self::schedule_named).579 /// # </weight>580 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]581 pub fn schedule_named_after(582 origin: OriginFor<T>,583 id: ScheduledId,584 after: T::BlockNumber,585 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,586 priority: Option<schedule::Priority>,587 call: Box<CallOrHashOf<T>>,588 ) -> DispatchResult {589 T::ScheduleOrigin::ensure_origin(origin.clone())?;590591 if priority.is_some() {592 T::PrioritySetOrigin::ensure_origin(origin.clone())?;593 }594595 let origin = <T as Config>::RuntimeOrigin::from(origin);596 Self::do_schedule_named(597 id,598 DispatchTime::After(after),599 maybe_periodic,600 priority.unwrap_or(LOWEST_PRIORITY),601 origin.caller().clone(),602 *call,603 )?;604 Ok(())605 }606607 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]608 pub fn change_named_priority(609 origin: OriginFor<T>,610 id: ScheduledId,611 priority: schedule::Priority,612 ) -> DispatchResult {613 T::PrioritySetOrigin::ensure_origin(origin.clone())?;614 let origin = <T as Config>::Origin::from(origin);615 Self::do_change_named_priority(origin.caller().clone(), id, priority)616 }617 }618}619620impl<T: Config> Pallet<T> {621 #[cfg(feature = "try-runtime")]622 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {623 Ok(())624 }625626 #[cfg(feature = "try-runtime")]627 pub fn post_migrate_to_v3() -> Result<(), &'static str> {628 use frame_support::dispatch::GetStorageVersion;629630 assert!(Self::current_storage_version() == 3);631 for k in Agenda::<T>::iter_keys() {632 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;633 }634 Ok(())635 }636637 /// Helper to migrate scheduler when the pallet origin type has changed.638 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {639 Agenda::<T>::translate::<640 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,641 _,642 >(|_, agenda| {643 Some(644 agenda645 .into_iter()646 .map(|schedule| {647 schedule.map(|schedule| Scheduled {648 maybe_id: schedule.maybe_id,649 priority: schedule.priority,650 call: schedule.call,651 maybe_periodic: schedule.maybe_periodic,652 origin: schedule.origin.into(),653 _phantom: Default::default(),654 })655 })656 .collect::<Vec<_>>(),657 )658 });659 }660661 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {662 let now = frame_system::Pallet::<T>::block_number();663664 let when = match when {665 DispatchTime::At(x) => x,666 // The current block has already completed it's scheduled tasks, so667 // Schedule the task at lest one block after this current block.668 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),669 };670671 if when <= now {672 return Err(Error::<T>::TargetBlockNumberInPast.into());673 }674675 Ok(when)676 }677678 fn do_schedule_named(679 id: ScheduledId,680 when: DispatchTime<T::BlockNumber>,681 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,682 priority: schedule::Priority,683 origin: T::PalletsOrigin,684 call: CallOrHashOf<T>,685 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {686 // ensure id it is unique687 if Lookup::<T>::contains_key(&id) {688 return Err(Error::<T>::FailedToSchedule)?;689 }690691 let when = Self::resolve_time(when)?;692693 call.ensure_requested::<T::PreimageProvider>();694695 // sanitize maybe_periodic696 let maybe_periodic = maybe_periodic697 .filter(|p| p.1 > 1 && !p.0.is_zero())698 // Remove one from the number of repetitions since we will schedule one now.699 .map(|(p, c)| (p, c - 1));700701 let s = Scheduled {702 maybe_id: Some(id.clone()),703 priority,704 call: call.clone(),705 maybe_periodic,706 origin: origin.clone(),707 _phantom: Default::default(),708 };709710 // reserve balance for periodic execution711 // let sender =712 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;713 // let repeats = match maybe_periodic {714 // Some(p) => p.1,715 // None => 1,716 // };717 // let _ = T::CallExecutor::reserve_balance(718 // id.clone(),719 // sender,720 // call.as_value().unwrap().clone(),721 // repeats,722 // );723724 Agenda::<T>::append(when, Some(s));725 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;726 let address = (when, index);727 Lookup::<T>::insert(&id, &address);728 Self::deposit_event(Event::Scheduled { when, index });729730 Ok(address)731 }732733 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {734 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {735 if let Some((when, index)) = lookup.take() {736 let i = index as usize;737 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {738 if let Some(s) = agenda.get_mut(i) {739 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {740 if matches!(741 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),742 Some(Ordering::Less) | None743 ) {744 return Err(BadOrigin.into());745 }746 // release balance reserve747 // let sender = ensure_signed(748 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(749 // origin.unwrap(),750 // )751 // .into(),752 // )?;753 // let _ = T::CallExecutor::cancel_reserve(id, sender);754755 s.call.ensure_unrequested::<T::PreimageProvider>();756 }757 *s = None;758 }759 Ok(())760 })?;761762 Self::deposit_event(Event::Canceled { when, index });763 Ok(())764 } else {765 Err(Error::<T>::NotFound)?766 }767 })768 }769770 fn do_change_named_priority(771 origin: T::PalletsOrigin,772 id: ScheduledId,773 priority: schedule::Priority,774 ) -> DispatchResult {775 match Lookup::<T>::get(id) {776 Some((when, index)) => {777 let i = index as usize;778 Agenda::<T>::try_mutate(when, |agenda| {779 if let Some(Some(s)) = agenda.get_mut(i) {780 if matches!(781 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),782 Some(Ordering::Less) | None783 ) {784 return Err(BadOrigin.into());785 }786787 s.priority = priority;788 Self::deposit_event(Event::PriorityChanged {789 when,790 index,791 priority,792 });793 }794 Ok(())795 })796 }797 None => Err(Error::<T>::NotFound.into()),798 }799 }800}test-pallets/utils/src/lib.rsdiffbeforeafterboth--- a/test-pallets/utils/src/lib.rs
+++ b/test-pallets/utils/src/lib.rs
@@ -119,6 +119,8 @@
impl<T: Config> Pallet<T> {
fn ensure_origin_and_enabled(origin: OriginFor<T>) -> DispatchResult {
ensure_signed(origin)?;
- <Enabled<T>>::get().then(|| ()).ok_or(<Error<T>>::TestPalletDisabled.into())
+ <Enabled<T>>::get()
+ .then(|| ())
+ .ok_or(<Error<T>>::TestPalletDisabled.into())
}
}