difftreelog
Reworked
in: master
1 file 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.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//! # 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//! 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//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.57//! Any user can book a call of a certain transaction to a specific block number.58//! Also possible to book a call with a certain frequency.59//!60//! Key differences from original pallet:61//! https://crates.io/crates/pallet-scheduler62//! Schedule Id restricted by 16 bytes63//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block64//! Maybe_periodic limit is 100 calls65//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.66//!67//! ## Interface68//!69//! ### Dispatchable Functions70//!71//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a specified block and72//! with a specified priority.73//! * `cancel` - cancel a scheduled dispatch, specified by block number and index.74//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter75//! that can be used for identification.76//! * `cancel_named` - the named complement to the cancel function.7778// Ensure we're `no_std` when compiling for Wasm.79#![cfg_attr(not(feature = "std"), no_std)]8081#[cfg(feature = "runtime-benchmarks")]82mod benchmarking;8384pub mod weights;8586use sp_core::H160;87use codec::{Codec, Decode, Encode};88use frame_system::{self as system, ensure_signed};89pub use pallet::*;90use scale_info::TypeInfo;91use sp_runtime::{92 traits::{BadOrigin, One, Saturating, Zero},93 RuntimeDebug, DispatchErrorWithPostInfo,94};95use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};9697use frame_support::{98 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},99 traits::{100 schedule::{self, DispatchTime, MaybeHashed},101 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,102 StorageVersion,103 },104 weights::{GetDispatchInfo, Weight},105};106107pub use weights::WeightInfo;108109/// Just a simple index for naming period tasks.110pub type PeriodicIndex = u32;111/// The location of a scheduled task that can be used to remove it.112pub type TaskAddress<BlockNumber> = (BlockNumber, u32);113pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;114115type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];116pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;117118/// Information regarding an item to be executed in the future.119#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]120#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]121pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {122 /// The unique identity for this task, if there is one.123 maybe_id: Option<ScheduledId>,124 /// This task's priority.125 priority: schedule::Priority,126 /// The call to be dispatched.127 call: Call,128 /// If the call is periodic, then this points to the information concerning that.129 maybe_periodic: Option<schedule::Period<BlockNumber>>,130 /// The origin to dispatch the call.131 origin: PalletsOrigin,132 _phantom: PhantomData<AccountId>,133}134135pub type ScheduledV3Of<T> = ScheduledV3<136 CallOrHashOf<T>,137 <T as frame_system::Config>::BlockNumber,138 <T as Config>::PalletsOrigin,139 <T as frame_system::Config>::AccountId,140>;141142pub type ScheduledOf<T> = ScheduledV3Of<T>;143144/// The current version of Scheduled struct.145pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =146 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;147148#[cfg(feature = "runtime-benchmarks")]149mod preimage_provider {150 use frame_support::traits::PreimageRecipient;151 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}152 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}153}154155#[cfg(not(feature = "runtime-benchmarks"))]156mod preimage_provider {157 use frame_support::traits::PreimageProvider;158 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}159 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}160}161162pub use preimage_provider::PreimageProviderAndMaybeRecipient;163164/// Weight templates for calculating actual fees165pub(crate) trait MarginalWeightInfo: WeightInfo {166 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {167 match (periodic, named, resolved) {168 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),169 (_, true, None) => {170 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)171 }172 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),173 (false, true, Some(false)) => {174 Self::on_initialize_named(2) - Self::on_initialize_named(1)175 }176 (true, false, Some(false)) => {177 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)178 }179 (true, true, Some(false)) => {180 Self::on_initialize_periodic_named_resolved(2)181 - Self::on_initialize_periodic_named_resolved(1)182 }183 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),184 (false, true, Some(true)) => {185 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)186 }187 (true, false, Some(true)) => {188 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)189 }190 (true, true, Some(true)) => {191 Self::on_initialize_periodic_named_resolved(2)192 - Self::on_initialize_periodic_named_resolved(1)193 }194 }195 }196}197impl<T: WeightInfo> MarginalWeightInfo for T {}198199#[frame_support::pallet]200pub mod pallet {201 use super::*;202 use frame_support::{203 dispatch::PostDispatchInfo,204 pallet_prelude::*,205 traits::{schedule::LookupError, PreimageProvider},206 };207 use frame_system::pallet_prelude::*;208209 /// The current storage version.210 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);211212 #[pallet::pallet]213 #[pallet::generate_store(pub(super) trait Store)]214 #[pallet::storage_version(STORAGE_VERSION)]215 #[pallet::without_storage_info]216 pub struct Pallet<T>(_);217218 /// `system::Config` should always be included in our implied traits.219 #[pallet::config]220 pub trait Config: frame_system::Config {221 /// The overarching event type.222 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;223224 /// The aggregated origin which the dispatch will take.225 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>226 + From<Self::PalletsOrigin>227 + IsType<<Self as system::Config>::Origin>;228229 /// The caller origin, overarching type of all pallets origins.230 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;231232 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;233234 /// The aggregated call type.235 type Call: Parameter236 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>237 + GetDispatchInfo238 + From<system::Call<Self>>;239240 /// The maximum weight that may be scheduled per block for any dispatchables of less241 /// priority than `schedule::HARD_DEADLINE`.242 #[pallet::constant]243 type MaximumWeight: Get<Weight>;244245 /// Required origin to schedule or cancel calls.246 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;247248 /// Compare the privileges of origins.249 ///250 /// This will be used when canceling a task, to ensure that the origin that tries251 /// to cancel has greater or equal privileges as the origin that created the scheduled task.252 ///253 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can254 /// be used. This will only check if two given origins are equal.255 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;256257 /// The maximum number of scheduled calls in the queue for a single block.258 /// Not strictly enforced, but used for weight estimation.259 #[pallet::constant]260 type MaxScheduledPerBlock: Get<u32>;261262 /// Weight information for extrinsics in this pallet.263 type WeightInfo: WeightInfo;264265 /// The preimage provider with which we look up call hashes to get the call.266 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;267268 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.269 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;270271 /// Sponsoring function. In this version sposorship is disabled272 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;273274 /// The helper type used for custom transaction fee logic.275 type CallExecutor: DispatchCall<Self, H160>;276 }277278 /// A Scheduler-Runtime interface for finer payment handling.279 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {280 /// Lock balance required for transaction payment281 fn reserve_balance(282 id: ScheduledId,283 sponsor: <T as frame_system::Config>::AccountId,284 call: <T as Config>::Call,285 count: u32,286 ) -> Result<(), DispatchError>;287288 /// Unlock centain amount from payer289 fn pay_for_call(290 id: ScheduledId,291 sponsor: <T as frame_system::Config>::AccountId,292 call: <T as Config>::Call,293 ) -> Result<u128, DispatchError>;294295 /// Resolve the call dispatch, including any post-dispatch operations.296 fn dispatch_call(297 signer: T::AccountId,298 function: <T as Config>::Call,299 ) -> Result<300 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,301 TransactionValidityError,302 >;303304 /// Cancel schedule reservation and unlock balance305 fn cancel_reserve(306 id: ScheduledId,307 sponsor: <T as frame_system::Config>::AccountId,308 ) -> Result<u128, DispatchError>;309 }310311 /// Items to be executed, indexed by the block number that they should be executed on.312 #[pallet::storage]313 pub type Agenda<T: Config> =314 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;315316 /// Lookup from identity to the block number and index of the task.317 #[pallet::storage]318 pub(crate) type Lookup<T: Config> =319 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;320321 /// Events type.322 #[pallet::event]323 #[pallet::generate_deposit(pub(super) fn deposit_event)]324 pub enum Event<T: Config> {325 /// Scheduled some task.326 Scheduled { when: T::BlockNumber, index: u32 },327 /// Canceled some task.328 Canceled { when: T::BlockNumber, index: u32 },329 /// Dispatched some task.330 Dispatched {331 task: TaskAddress<T::BlockNumber>,332 id: Option<ScheduledId>,333 result: DispatchResult,334 },335 /// The call for the provided hash was not found so the task has been aborted.336 CallLookupFailed {337 task: TaskAddress<T::BlockNumber>,338 id: Option<ScheduledId>,339 error: LookupError,340 },341 }342343 #[pallet::error]344 pub enum Error<T> {345 /// Failed to schedule a call346 FailedToSchedule,347 /// Cannot find the scheduled call.348 NotFound,349 /// Given target block number is in the past.350 TargetBlockNumberInPast,351 /// Reschedule failed because it does not change scheduled time.352 RescheduleNoChange,353 }354355 #[pallet::hooks]356 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {357 /// Execute the scheduled calls358 fn on_initialize(now: T::BlockNumber) -> Weight {359 let limit = T::MaximumWeight::get();360361 let mut queued = Agenda::<T>::take(now)362 .into_iter()363 .enumerate()364 .filter_map(|(index, s)| Some((index as u32, s?)))365 .collect::<Vec<_>>();366367 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {368 log::warn!(369 target: "runtime::scheduler",370 "Warning: This block has more items queued in Scheduler than \371 expected from the runtime configuration. An update might be needed."372 );373 }374375 queued.sort_by_key(|(_, s)| s.priority);376377 let next = now + One::one();378379 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);380 for (order, (index, mut s)) in queued.into_iter().enumerate() {381 let named = if let Some(ref id) = s.maybe_id {382 Lookup::<T>::remove(id);383 true384 } else {385 false386 };387388 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();389 s.call = call;390391 let resolved = if let Some(completed) = maybe_completed {392 T::PreimageProvider::unrequest_preimage(&completed);393 true394 } else {395 false396 };397 let call = match s.call.as_value().cloned() {398 Some(c) => c,399 None => {400 // Preimage not available - postpone until some block.401 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));402 if let Some(delay) = T::NoPreimagePostponement::get() {403 let until = now.saturating_add(delay);404 if let Some(ref id) = s.maybe_id {405 let index = Agenda::<T>::decode_len(until).unwrap_or(0);406 Lookup::<T>::insert(id, (until, index as u32));407 }408 Agenda::<T>::append(until, Some(s));409 }410 continue;411 }412 };413414 let periodic = s.maybe_periodic.is_some();415 let call_weight = call.get_dispatch_info().weight;416 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));417 let origin =418 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())419 .into();420 if ensure_signed(origin).is_ok() {421 // Weights of Signed dispatches expect their signing account to be whitelisted.422 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));423 }424425 // We allow a scheduled call if any is true:426 // - It's priority is `HARD_DEADLINE`427 // - It does not push the weight past the limit.428 // - It is the first item in the schedule429 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;430 let test_weight = total_weight431 .saturating_add(call_weight)432 .saturating_add(item_weight);433 if !hard_deadline && order > 0 && test_weight > limit {434 // Cannot be scheduled this block - postpone until next.435 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));436 if let Some(ref id) = s.maybe_id {437 // NOTE: We could reasonably not do this (in which case there would be one438 // block where the named and delayed item could not be referenced by name),439 // but we will do it anyway since it should be mostly free in terms of440 // weight and it is slightly cleaner.441 let index = Agenda::<T>::decode_len(next).unwrap_or(0);442 Lookup::<T>::insert(id, (next, index as u32));443 }444 Agenda::<T>::append(next, Some(s));445 continue;446 }447448 // Sender is the account who signed transaction449 let sender = ensure_signed(450 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())451 .into(),452 )453 .unwrap();454455 // // if call have id it was be reserved456 // if s.maybe_id.is_some() {457 // let _ = T::CallExecutor::pay_for_call(458 // s.maybe_id.unwrap(),459 // sender.clone(),460 // call.clone(),461 // );462 // }463464 // Execute transaction via chain default pipeline465 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken466 let r = T::CallExecutor::dispatch_call(sender, call.clone());467468 let mut actual_call_weight: Weight = item_weight;469 let result: Result<_, DispatchError> = match r {470 Ok(o) => match o {471 Ok(di) => {472 actual_call_weight = di.actual_weight.unwrap_or(item_weight);473 Ok(())474 }475 Err(err) => Err(err.error),476 },477 Err(_) => {478 log::error!(479 target: "runtime::scheduler",480 "Warning: Scheduler has failed to execute a post-dispatch transaction. \481 This block might have become invalid.");482 Err(DispatchError::CannotLookup)483 } // todo possibly force a skip/return here, do something with the error484 };485486 total_weight.saturating_accrue(item_weight);487 total_weight.saturating_accrue(actual_call_weight);488489 Self::deposit_event(Event::Dispatched {490 task: (now, index),491 id: s.maybe_id.clone(),492 result,493 });494495 if let &Some((period, count)) = &s.maybe_periodic {496 if count > 1 {497 s.maybe_periodic = Some((period, count - 1));498 } else {499 s.maybe_periodic = None;500 }501 let wake = now + period;502 // If scheduled is named, place its information in `Lookup`503 if let Some(ref id) = s.maybe_id {504 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);505 Lookup::<T>::insert(id, (wake, wake_index as u32));506 }507 Agenda::<T>::append(wake, Some(s));508 }509 }510 /// Weight should be 0, because transaction already paid511 0512 }513 }514515 #[pallet::call]516 impl<T: Config> Pallet<T> {517 /// Schedule a named task.518 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]519 pub fn schedule_named(520 origin: OriginFor<T>,521 id: ScheduledId,522 when: T::BlockNumber,523 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,524 priority: schedule::Priority,525 call: Box<CallOrHashOf<T>>,526 ) -> DispatchResult {527 T::ScheduleOrigin::ensure_origin(origin.clone())?;528 let origin = <T as Config>::Origin::from(origin);529 Self::do_schedule_named(530 id,531 DispatchTime::At(when),532 maybe_periodic,533 priority,534 origin.caller().clone(),535 *call,536 )?;537 Ok(())538 }539540 /// Cancel a named scheduled task.541 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]542 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {543 T::ScheduleOrigin::ensure_origin(origin.clone())?;544 let origin = <T as Config>::Origin::from(origin);545 Self::do_cancel_named(Some(origin.caller().clone()), id)?;546 Ok(())547 }548549 /// Schedule a named task after a delay.550 ///551 /// # <weight>552 /// Same as [`schedule_named`](Self::schedule_named).553 /// # </weight>554 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]555 pub fn schedule_named_after(556 origin: OriginFor<T>,557 id: ScheduledId,558 after: T::BlockNumber,559 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,560 priority: schedule::Priority,561 call: Box<CallOrHashOf<T>>,562 ) -> DispatchResult {563 T::ScheduleOrigin::ensure_origin(origin.clone())?;564 let origin = <T as Config>::Origin::from(origin);565 Self::do_schedule_named(566 id,567 DispatchTime::After(after),568 maybe_periodic,569 priority,570 origin.caller().clone(),571 *call,572 )?;573 Ok(())574 }575 }576}577578impl<T: Config> Pallet<T> {579 #[cfg(feature = "try-runtime")]580 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {581 Ok(())582 }583584 #[cfg(feature = "try-runtime")]585 pub fn post_migrate_to_v3() -> Result<(), &'static str> {586 use frame_support::dispatch::GetStorageVersion;587588 assert!(Self::current_storage_version() == 3);589 for k in Agenda::<T>::iter_keys() {590 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;591 }592 Ok(())593 }594595 /// Helper to migrate scheduler when the pallet origin type has changed.596 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {597 Agenda::<T>::translate::<598 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,599 _,600 >(|_, agenda| {601 Some(602 agenda603 .into_iter()604 .map(|schedule| {605 schedule.map(|schedule| Scheduled {606 maybe_id: schedule.maybe_id,607 priority: schedule.priority,608 call: schedule.call,609 maybe_periodic: schedule.maybe_periodic,610 origin: schedule.origin.into(),611 _phantom: Default::default(),612 })613 })614 .collect::<Vec<_>>(),615 )616 });617 }618619 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {620 let now = frame_system::Pallet::<T>::block_number();621622 let when = match when {623 DispatchTime::At(x) => x,624 // The current block has already completed it's scheduled tasks, so625 // Schedule the task at lest one block after this current block.626 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),627 };628629 if when <= now {630 return Err(Error::<T>::TargetBlockNumberInPast.into());631 }632633 Ok(when)634 }635636 fn do_schedule_named(637 id: ScheduledId,638 when: DispatchTime<T::BlockNumber>,639 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,640 priority: schedule::Priority,641 origin: T::PalletsOrigin,642 call: CallOrHashOf<T>,643 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {644 // ensure id it is unique645 if Lookup::<T>::contains_key(&id) {646 return Err(Error::<T>::FailedToSchedule)?;647 }648649 let when = Self::resolve_time(when)?;650651 call.ensure_requested::<T::PreimageProvider>();652653 // sanitize maybe_periodic654 let maybe_periodic = maybe_periodic655 .filter(|p| p.1 > 1 && !p.0.is_zero())656 // Remove one from the number of repetitions since we will schedule one now.657 .map(|(p, c)| (p, c - 1));658659 let s = Scheduled {660 maybe_id: Some(id.clone()),661 priority,662 call: call.clone(),663 maybe_periodic,664 origin: origin.clone(),665 _phantom: Default::default(),666 };667668 // reserve balance for periodic execution669 // let sender =670 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;671 // let repeats = match maybe_periodic {672 // Some(p) => p.1,673 // None => 1,674 // };675 // let _ = T::CallExecutor::reserve_balance(676 // id.clone(),677 // sender,678 // call.as_value().unwrap().clone(),679 // repeats,680 // );681682 Agenda::<T>::append(when, Some(s));683 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;684 let address = (when, index);685 Lookup::<T>::insert(&id, &address);686 Self::deposit_event(Event::Scheduled { when, index });687688 Ok(address)689 }690691 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {692 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {693 if let Some((when, index)) = lookup.take() {694 let i = index as usize;695 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {696 if let Some(s) = agenda.get_mut(i) {697 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {698 if matches!(699 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),700 Some(Ordering::Less) | None701 ) {702 return Err(BadOrigin.into());703 }704 // release balance reserve705 // let sender = ensure_signed(706 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(707 // origin.unwrap(),708 // )709 // .into(),710 // )?;711 // let _ = T::CallExecutor::cancel_reserve(id, sender);712713 s.call.ensure_unrequested::<T::PreimageProvider>();714 }715 *s = None;716 }717 Ok(())718 })?;719720 Self::deposit_event(Event::Canceled { when, index });721 Ok(())722 } else {723 Err(Error::<T>::NotFound)?724 }725 })726 }727}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # 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-scheduler54//! 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, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{GetDispatchInfo, Weight},96};9798pub use weights::WeightInfo;99100/// Just a simple index for naming period tasks.101pub type PeriodicIndex = u32;102/// The location of a scheduled task that can be used to remove it.103pub type TaskAddress<BlockNumber> = (BlockNumber, u32);104pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;105106type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];107pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;108109/// Information regarding an item to be executed in the future.110#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]111#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]112pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {113 /// The unique identity for this task, if there is one.114 maybe_id: Option<ScheduledId>,115 /// This task's priority.116 priority: schedule::Priority,117 /// The call to be dispatched.118 call: Call,119 /// If the call is periodic, then this points to the information concerning that.120 maybe_periodic: Option<schedule::Period<BlockNumber>>,121 /// The origin to dispatch the call.122 origin: PalletsOrigin,123 _phantom: PhantomData<AccountId>,124}125126pub type ScheduledV3Of<T> = ScheduledV3<127 CallOrHashOf<T>,128 <T as frame_system::Config>::BlockNumber,129 <T as Config>::PalletsOrigin,130 <T as frame_system::Config>::AccountId,131>;132133pub type ScheduledOf<T> = ScheduledV3Of<T>;134135/// The current version of Scheduled struct.136pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =137 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;138139#[cfg(feature = "runtime-benchmarks")]140mod preimage_provider {141 use frame_support::traits::PreimageRecipient;142 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}143 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}144}145146#[cfg(not(feature = "runtime-benchmarks"))]147mod preimage_provider {148 use frame_support::traits::PreimageProvider;149 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}150 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}151}152153pub use preimage_provider::PreimageProviderAndMaybeRecipient;154155/// Weight templates for calculating actual fees156pub(crate) trait MarginalWeightInfo: WeightInfo {157 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {158 match (periodic, named, resolved) {159 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),160 (_, true, None) => {161 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)162 }163 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),164 (false, true, Some(false)) => {165 Self::on_initialize_named(2) - Self::on_initialize_named(1)166 }167 (true, false, Some(false)) => {168 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)169 }170 (true, true, Some(false)) => {171 Self::on_initialize_periodic_named_resolved(2)172 - Self::on_initialize_periodic_named_resolved(1)173 }174 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),175 (false, true, Some(true)) => {176 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)177 }178 (true, false, Some(true)) => {179 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)180 }181 (true, true, Some(true)) => {182 Self::on_initialize_periodic_named_resolved(2)183 - Self::on_initialize_periodic_named_resolved(1)184 }185 }186 }187}188impl<T: WeightInfo> MarginalWeightInfo for T {}189190#[frame_support::pallet]191pub mod pallet {192 use super::*;193 use frame_support::{194 dispatch::PostDispatchInfo,195 pallet_prelude::*,196 traits::{schedule::LookupError, PreimageProvider},197 };198 use frame_system::pallet_prelude::*;199200 /// The current storage version.201 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);202203 #[pallet::pallet]204 #[pallet::generate_store(pub(super) trait Store)]205 #[pallet::storage_version(STORAGE_VERSION)]206 #[pallet::without_storage_info]207 pub struct Pallet<T>(_);208209 /// `system::Config` should always be included in our implied traits.210 #[pallet::config]211 pub trait Config: frame_system::Config {212 /// The overarching event type.213 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;214215 /// The aggregated origin which the dispatch will take.216 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>217 + From<Self::PalletsOrigin>218 + IsType<<Self as system::Config>::Origin>;219220 /// The caller origin, overarching type of all pallets origins.221 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;222223 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;224225 /// The aggregated call type.226 type Call: Parameter227 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>228 + GetDispatchInfo229 + From<system::Call<Self>>;230231 /// The maximum weight that may be scheduled per block for any dispatchables of less232 /// priority than `schedule::HARD_DEADLINE`.233 #[pallet::constant]234 type MaximumWeight: Get<Weight>;235236 /// Required origin to schedule or cancel calls.237 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;238239 /// Compare the privileges of origins.240 ///241 /// This will be used when canceling a task, to ensure that the origin that tries242 /// to cancel has greater or equal privileges as the origin that created the scheduled task.243 ///244 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can245 /// be used. This will only check if two given origins are equal.246 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;247248 /// The maximum number of scheduled calls in the queue for a single block.249 /// Not strictly enforced, but used for weight estimation.250 #[pallet::constant]251 type MaxScheduledPerBlock: Get<u32>;252253 /// Weight information for extrinsics in this pallet.254 type WeightInfo: WeightInfo;255256 /// The preimage provider with which we look up call hashes to get the call.257 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;258259 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.260 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;261262 /// Sponsoring function. In this version sposorship is disabled263 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;264265 /// The helper type used for custom transaction fee logic.266 type CallExecutor: DispatchCall<Self, H160>;267 }268269 /// A Scheduler-Runtime interface for finer payment handling.270 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {271 /// Lock balance required for transaction payment272 fn reserve_balance(273 id: ScheduledId,274 sponsor: <T as frame_system::Config>::AccountId,275 call: <T as Config>::Call,276 count: u32,277 ) -> Result<(), DispatchError>;278279 /// Unlock centain amount from payer280 fn pay_for_call(281 id: ScheduledId,282 sponsor: <T as frame_system::Config>::AccountId,283 call: <T as Config>::Call,284 ) -> Result<u128, DispatchError>;285286 /// Resolve the call dispatch, including any post-dispatch operations.287 fn dispatch_call(288 signer: T::AccountId,289 function: <T as Config>::Call,290 ) -> Result<291 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,292 TransactionValidityError,293 >;294295 /// Cancel schedule reservation and unlock balance296 fn cancel_reserve(297 id: ScheduledId,298 sponsor: <T as frame_system::Config>::AccountId,299 ) -> Result<u128, DispatchError>;300 }301302 /// Items to be executed, indexed by the block number that they should be executed on.303 #[pallet::storage]304 pub type Agenda<T: Config> =305 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;306307 /// Lookup from identity to the block number and index of the task.308 #[pallet::storage]309 pub(crate) type Lookup<T: Config> =310 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;311312 /// Events type.313 #[pallet::event]314 #[pallet::generate_deposit(pub(super) fn deposit_event)]315 pub enum Event<T: Config> {316 /// Scheduled some task.317 Scheduled { when: T::BlockNumber, index: u32 },318 /// Canceled some task.319 Canceled { when: T::BlockNumber, index: u32 },320 /// Dispatched some task.321 Dispatched {322 task: TaskAddress<T::BlockNumber>,323 id: Option<ScheduledId>,324 result: DispatchResult,325 },326 /// The call for the provided hash was not found so the task has been aborted.327 CallLookupFailed {328 task: TaskAddress<T::BlockNumber>,329 id: Option<ScheduledId>,330 error: LookupError,331 },332 }333334 #[pallet::error]335 pub enum Error<T> {336 /// Failed to schedule a call337 FailedToSchedule,338 /// Cannot find the scheduled call.339 NotFound,340 /// Given target block number is in the past.341 TargetBlockNumberInPast,342 /// Reschedule failed because it does not change scheduled time.343 RescheduleNoChange,344 }345346 #[pallet::hooks]347 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {348 /// Execute the scheduled calls349 fn on_initialize(now: T::BlockNumber) -> Weight {350 let limit = T::MaximumWeight::get();351352 let mut queued = Agenda::<T>::take(now)353 .into_iter()354 .enumerate()355 .filter_map(|(index, s)| Some((index as u32, s?)))356 .collect::<Vec<_>>();357358 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {359 log::warn!(360 target: "runtime::scheduler",361 "Warning: This block has more items queued in Scheduler than \362 expected from the runtime configuration. An update might be needed."363 );364 }365366 queued.sort_by_key(|(_, s)| s.priority);367368 let next = now + One::one();369370 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);371 for (order, (index, mut s)) in queued.into_iter().enumerate() {372 let named = if let Some(ref id) = s.maybe_id {373 Lookup::<T>::remove(id);374 true375 } else {376 false377 };378379 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();380 s.call = call;381382 let resolved = if let Some(completed) = maybe_completed {383 T::PreimageProvider::unrequest_preimage(&completed);384 true385 } else {386 false387 };388 let call = match s.call.as_value().cloned() {389 Some(c) => c,390 None => {391 // Preimage not available - postpone until some block.392 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));393 if let Some(delay) = T::NoPreimagePostponement::get() {394 let until = now.saturating_add(delay);395 if let Some(ref id) = s.maybe_id {396 let index = Agenda::<T>::decode_len(until).unwrap_or(0);397 Lookup::<T>::insert(id, (until, index as u32));398 }399 Agenda::<T>::append(until, Some(s));400 }401 continue;402 }403 };404405 let periodic = s.maybe_periodic.is_some();406 let call_weight = call.get_dispatch_info().weight;407 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));408 let origin =409 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())410 .into();411 if ensure_signed(origin).is_ok() {412 // Weights of Signed dispatches expect their signing account to be whitelisted.413 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));414 }415416 // We allow a scheduled call if any is true:417 // - It's priority is `HARD_DEADLINE`418 // - It does not push the weight past the limit.419 // - It is the first item in the schedule420 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;421 let test_weight = total_weight422 .saturating_add(call_weight)423 .saturating_add(item_weight);424 if !hard_deadline && order > 0 && test_weight > limit {425 // Cannot be scheduled this block - postpone until next.426 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));427 if let Some(ref id) = s.maybe_id {428 // NOTE: We could reasonably not do this (in which case there would be one429 // block where the named and delayed item could not be referenced by name),430 // but we will do it anyway since it should be mostly free in terms of431 // weight and it is slightly cleaner.432 let index = Agenda::<T>::decode_len(next).unwrap_or(0);433 Lookup::<T>::insert(id, (next, index as u32));434 }435 Agenda::<T>::append(next, Some(s));436 continue;437 }438439 // Sender is the account who signed transaction440 let sender = ensure_signed(441 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())442 .into(),443 )444 .unwrap();445446 // // if call have id it was be reserved447 // if s.maybe_id.is_some() {448 // let _ = T::CallExecutor::pay_for_call(449 // s.maybe_id.unwrap(),450 // sender.clone(),451 // call.clone(),452 // );453 // }454455 // Execute transaction via chain default pipeline456 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken457 let r = T::CallExecutor::dispatch_call(sender, call.clone());458459 let mut actual_call_weight: Weight = item_weight;460 let result: Result<_, DispatchError> = match r {461 Ok(o) => match o {462 Ok(di) => {463 actual_call_weight = di.actual_weight.unwrap_or(item_weight);464 Ok(())465 }466 Err(err) => Err(err.error),467 },468 Err(_) => {469 log::error!(470 target: "runtime::scheduler",471 "Warning: Scheduler has failed to execute a post-dispatch transaction. \472 This block might have become invalid.");473 Err(DispatchError::CannotLookup)474 } // todo possibly force a skip/return here, do something with the error475 };476477 total_weight.saturating_accrue(item_weight);478 total_weight.saturating_accrue(actual_call_weight);479480 Self::deposit_event(Event::Dispatched {481 task: (now, index),482 id: s.maybe_id.clone(),483 result,484 });485486 if let &Some((period, count)) = &s.maybe_periodic {487 if count > 1 {488 s.maybe_periodic = Some((period, count - 1));489 } else {490 s.maybe_periodic = None;491 }492 let wake = now + period;493 // If scheduled is named, place its information in `Lookup`494 if let Some(ref id) = s.maybe_id {495 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);496 Lookup::<T>::insert(id, (wake, wake_index as u32));497 }498 Agenda::<T>::append(wake, Some(s));499 }500 }501 /// Weight should be 0, because transaction already paid502 0503 }504 }505506 #[pallet::call]507 impl<T: Config> Pallet<T> {508 /// Schedule a named task.509 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]510 pub fn schedule_named(511 origin: OriginFor<T>,512 id: ScheduledId,513 when: T::BlockNumber,514 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,515 priority: schedule::Priority,516 call: Box<CallOrHashOf<T>>,517 ) -> DispatchResult {518 T::ScheduleOrigin::ensure_origin(origin.clone())?;519 let origin = <T as Config>::Origin::from(origin);520 Self::do_schedule_named(521 id,522 DispatchTime::At(when),523 maybe_periodic,524 priority,525 origin.caller().clone(),526 *call,527 )?;528 Ok(())529 }530531 /// Cancel a named scheduled task.532 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]533 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {534 T::ScheduleOrigin::ensure_origin(origin.clone())?;535 let origin = <T as Config>::Origin::from(origin);536 Self::do_cancel_named(Some(origin.caller().clone()), id)?;537 Ok(())538 }539540 /// Schedule a named task after a delay.541 ///542 /// # <weight>543 /// Same as [`schedule_named`](Self::schedule_named).544 /// # </weight>545 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]546 pub fn schedule_named_after(547 origin: OriginFor<T>,548 id: ScheduledId,549 after: T::BlockNumber,550 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,551 priority: schedule::Priority,552 call: Box<CallOrHashOf<T>>,553 ) -> DispatchResult {554 T::ScheduleOrigin::ensure_origin(origin.clone())?;555 let origin = <T as Config>::Origin::from(origin);556 Self::do_schedule_named(557 id,558 DispatchTime::After(after),559 maybe_periodic,560 priority,561 origin.caller().clone(),562 *call,563 )?;564 Ok(())565 }566 }567}568569impl<T: Config> Pallet<T> {570 #[cfg(feature = "try-runtime")]571 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {572 Ok(())573 }574575 #[cfg(feature = "try-runtime")]576 pub fn post_migrate_to_v3() -> Result<(), &'static str> {577 use frame_support::dispatch::GetStorageVersion;578579 assert!(Self::current_storage_version() == 3);580 for k in Agenda::<T>::iter_keys() {581 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;582 }583 Ok(())584 }585586 /// Helper to migrate scheduler when the pallet origin type has changed.587 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {588 Agenda::<T>::translate::<589 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,590 _,591 >(|_, agenda| {592 Some(593 agenda594 .into_iter()595 .map(|schedule| {596 schedule.map(|schedule| Scheduled {597 maybe_id: schedule.maybe_id,598 priority: schedule.priority,599 call: schedule.call,600 maybe_periodic: schedule.maybe_periodic,601 origin: schedule.origin.into(),602 _phantom: Default::default(),603 })604 })605 .collect::<Vec<_>>(),606 )607 });608 }609610 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {611 let now = frame_system::Pallet::<T>::block_number();612613 let when = match when {614 DispatchTime::At(x) => x,615 // The current block has already completed it's scheduled tasks, so616 // Schedule the task at lest one block after this current block.617 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),618 };619620 if when <= now {621 return Err(Error::<T>::TargetBlockNumberInPast.into());622 }623624 Ok(when)625 }626627 fn do_schedule_named(628 id: ScheduledId,629 when: DispatchTime<T::BlockNumber>,630 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,631 priority: schedule::Priority,632 origin: T::PalletsOrigin,633 call: CallOrHashOf<T>,634 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {635 // ensure id it is unique636 if Lookup::<T>::contains_key(&id) {637 return Err(Error::<T>::FailedToSchedule)?;638 }639640 let when = Self::resolve_time(when)?;641642 call.ensure_requested::<T::PreimageProvider>();643644 // sanitize maybe_periodic645 let maybe_periodic = maybe_periodic646 .filter(|p| p.1 > 1 && !p.0.is_zero())647 // Remove one from the number of repetitions since we will schedule one now.648 .map(|(p, c)| (p, c - 1));649650 let s = Scheduled {651 maybe_id: Some(id.clone()),652 priority,653 call: call.clone(),654 maybe_periodic,655 origin: origin.clone(),656 _phantom: Default::default(),657 };658659 // reserve balance for periodic execution660 // let sender =661 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;662 // let repeats = match maybe_periodic {663 // Some(p) => p.1,664 // None => 1,665 // };666 // let _ = T::CallExecutor::reserve_balance(667 // id.clone(),668 // sender,669 // call.as_value().unwrap().clone(),670 // repeats,671 // );672673 Agenda::<T>::append(when, Some(s));674 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;675 let address = (when, index);676 Lookup::<T>::insert(&id, &address);677 Self::deposit_event(Event::Scheduled { when, index });678679 Ok(address)680 }681682 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {683 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {684 if let Some((when, index)) = lookup.take() {685 let i = index as usize;686 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {687 if let Some(s) = agenda.get_mut(i) {688 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {689 if matches!(690 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),691 Some(Ordering::Less) | None692 ) {693 return Err(BadOrigin.into());694 }695 // release balance reserve696 // let sender = ensure_signed(697 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(698 // origin.unwrap(),699 // )700 // .into(),701 // )?;702 // let _ = T::CallExecutor::cancel_reserve(id, sender);703704 s.call.ensure_unrequested::<T::PreimageProvider>();705 }706 *s = None;707 }708 Ok(())709 })?;710711 Self::deposit_event(Event::Canceled { when, index });712 Ok(())713 } else {714 Err(Error::<T>::NotFound)?715 }716 })717 }718}