difftreelog
fix cargo fmt
in: master
3 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::{schedule::{LookupError, LOWEST_PRIORITY}, PreimageProvider},201 };202 use frame_system::pallet_prelude::*;203204 /// The current storage version.205 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);206207 #[pallet::pallet]208 #[pallet::generate_store(pub(super) trait Store)]209 #[pallet::storage_version(STORAGE_VERSION)]210 #[pallet::without_storage_info]211 pub struct Pallet<T>(_);212213 /// `system::Config` should always be included in our implied traits.214 #[pallet::config]215 pub trait Config: frame_system::Config {216 /// The overarching event type.217 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;218219 /// The aggregated origin which the dispatch will take.220 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>221 + From<Self::PalletsOrigin>222 + IsType<<Self as system::Config>::RuntimeOrigin>;223224 /// The caller origin, overarching type of all pallets origins.225 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;226227 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;228229 /// The aggregated call type.230 type RuntimeCall: Parameter231 + Dispatchable<Origin = <Self as Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>232 + UnfilteredDispatchable<Origin = <Self as system::Config>::RuntimeOrigin>233 + GetDispatchInfo234 + From<system::RuntimeCall<Self>>;235236 /// The maximum weight that may be scheduled per block for any dispatchables of less237 /// priority than `schedule::HARD_DEADLINE`.238 #[pallet::constant]239 type MaximumWeight: Get<Weight>;240241 /// Required origin to schedule or cancel calls.242 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin, Success = ScheduledEnsureOriginSuccess<Self::AccountId>>;243244 /// Required origin to set/change calls' priority.245 type PrioritySetOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;246247 /// Compare the privileges of origins.248 ///249 /// This will be used when canceling a task, to ensure that the origin that tries250 /// to cancel has greater or equal privileges as the origin that created the scheduled task.251 ///252 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can253 /// be used. This will only check if two given origins are equal.254 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;255256 /// The maximum number of scheduled calls in the queue for a single block.257 /// Not strictly enforced, but used for weight estimation.258 #[pallet::constant]259 type MaxScheduledPerBlock: Get<u32>;260261 /// Weight information for extrinsics in this pallet.262 type WeightInfo: WeightInfo;263264 /// The preimage provider with which we look up call hashes to get the call.265 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;266267 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.268 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;269270 /// Sponsoring function.271 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;272273 /// The helper type used for custom transaction fee logic.274 type CallExecutor: DispatchCall<Self, H160>;275 }276277 /// A Scheduler-Runtime interface for finer payment handling.278 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {279 /// Reserve (lock) the maximum spendings on a call, calculated from its weight and the repetition count.280 fn reserve_balance(281 id: ScheduledId,282 sponsor: <T as frame_system::Config>::AccountId,283 call: <T as Config>::RuntimeCall,284 count: u32,285 ) -> Result<(), DispatchError>;286287 /// Unreserve (unlock) a certain amount from the payer's reserved funds, returning the change.288 fn pay_for_call(289 id: ScheduledId,290 sponsor: <T as frame_system::Config>::AccountId,291 call: <T as Config>::RuntimeCall,292 ) -> Result<u128, DispatchError>;293294 /// Resolve the call dispatch, including any post-dispatch operations.295 fn dispatch_call(296 signer: Option<T::AccountId>,297 function: <T as Config>::RuntimeCall,298 ) -> Result<299 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,300 TransactionValidityError,301 >;302303 /// Release unspent reserved funds in case of a schedule cancel.304 fn cancel_reserve(305 id: ScheduledId,306 sponsor: <T as frame_system::Config>::AccountId,307 ) -> Result<u128, DispatchError>;308 }309310 /// Items to be executed, indexed by the block number that they should be executed on.311 #[pallet::storage]312 pub type Agenda<T: Config> =313 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;314315 /// Lookup from identity to the block number and index of the task.316 #[pallet::storage]317 pub(crate) type Lookup<T: Config> =318 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;319320 /// Events type.321 #[pallet::event]322 #[pallet::generate_deposit(pub(super) fn deposit_event)]323 pub enum Event<T: Config> {324 /// Scheduled some task.325 Scheduled { when: T::BlockNumber, index: u32 },326 /// Canceled some task.327 Canceled { when: T::BlockNumber, index: u32 },328 /// Scheduled task's priority has changed329 PriorityChanged { 330 when: T::BlockNumber,331 index: u32,332 priority: schedule::Priority,333 },334 /// Dispatched some task.335 Dispatched {336 task: TaskAddress<T::BlockNumber>,337 id: Option<ScheduledId>,338 result: DispatchResult,339 },340 /// The call for the provided hash was not found so the task has been aborted.341 CallLookupFailed {342 task: TaskAddress<T::BlockNumber>,343 id: Option<ScheduledId>,344 error: LookupError,345 },346 }347348 #[pallet::error]349 pub enum Error<T> {350 /// Failed to schedule a call351 FailedToSchedule,352 /// Cannot find the scheduled call.353 NotFound,354 /// Given target block number is in the past.355 TargetBlockNumberInPast,356 /// Reschedule failed because it does not change scheduled time.357 RescheduleNoChange,358 }359360 #[pallet::hooks]361 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {362 /// Execute the scheduled calls363 fn on_initialize(now: T::BlockNumber) -> Weight {364 let limit = T::MaximumWeight::get();365366 let mut queued = Agenda::<T>::take(now)367 .into_iter()368 .enumerate()369 .filter_map(|(index, s)| Some((index as u32, s?)))370 .collect::<Vec<_>>();371372 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {373 log::warn!(374 target: "runtime::scheduler",375 "Warning: This block has more items queued in Scheduler than \376 expected from the runtime configuration. An update might be needed."377 );378 }379380 queued.sort_by_key(|(_, s)| s.priority);381382 let next = now + One::one();383384 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);385 for (order, (index, mut s)) in queued.into_iter().enumerate() {386 let named = s.maybe_id.is_some();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 = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(418 s.origin.clone(),419 )420 .into();421 if ensure_signed(origin).is_ok() {422 // Weights of Signed dispatches expect their signing account to be whitelisted.423 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));424 }425426 // We allow a scheduled call if any is true:427 // - It's priority is `HARD_DEADLINE`428 // - It does not push the weight past the limit.429 // - It is the first item in the schedule430 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;431 let test_weight = total_weight432 .saturating_add(call_weight)433 .saturating_add(item_weight);434 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {435 // Cannot be scheduled this block - postpone until next.436 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));437 if let Some(ref id) = s.maybe_id {438 // NOTE: We could reasonably not do this (in which case there would be one439 // block where the named and delayed item could not be referenced by name),440 // but we will do it anyway since it should be mostly free in terms of441 // weight and it is slightly cleaner.442 let index = Agenda::<T>::decode_len(next).unwrap_or(0);443 Lookup::<T>::insert(id, (next, index as u32));444 }445 Agenda::<T>::append(next, Some(s));446 continue;447 }448449 let scheduled_origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(s.origin.clone());450 let ensured_origin = T::ScheduleOrigin::ensure_origin(scheduled_origin.into()).unwrap();451452 let r;453 match ensured_origin {454 ScheduledEnsureOriginSuccess::Root => {455 r = Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()));456 },457 ScheduledEnsureOriginSuccess::Signed(sender) => {458 // Execute transaction via chain default pipeline459 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken460 r = T::CallExecutor::dispatch_call(Some(sender), call.clone());461 },462 ScheduledEnsureOriginSuccess::Unsigned => {463 // Unsigned version of the above464 r = T::CallExecutor::dispatch_call(None, call.clone());465 }466 }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 let is_canceled;503504 // If scheduled is named, place its information in `Lookup`505 if let Some(ref id) = s.maybe_id {506 is_canceled = Lookup::<T>::get(id).is_none();507 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);508509 if !is_canceled {510 Lookup::<T>::insert(id, (wake, wake_index as u32));511 }512 } else {513 is_canceled = false;514 }515516 if !is_canceled {517 Agenda::<T>::append(wake, Some(s));518 }519 } else if let Some(ref id) = s.maybe_id {520 Lookup::<T>::remove(id);521 }522 }523 total_weight524 }525 }526527 #[pallet::call]528 impl<T: Config> Pallet<T> {529 /// Schedule a named task.530 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]531 pub fn schedule_named(532 origin: OriginFor<T>,533 id: ScheduledId,534 when: T::BlockNumber,535 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,536 priority: Option<schedule::Priority>,537 call: Box<CallOrHashOf<T>>,538 ) -> DispatchResult {539 T::ScheduleOrigin::ensure_origin(origin.clone())?;540541 if priority.is_some() {542 T::PrioritySetOrigin::ensure_origin(origin.clone())?;543 }544545 let origin = <T as Config>::RuntimeOrigin::from(origin);546 Self::do_schedule_named(547 id,548 DispatchTime::At(when),549 maybe_periodic,550 priority.unwrap_or(LOWEST_PRIORITY),551 origin.caller().clone(),552 *call,553 )?;554 Ok(())555 }556557 /// Cancel a named scheduled task.558 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]559 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {560 T::ScheduleOrigin::ensure_origin(origin.clone())?;561 let origin = <T as Config>::RuntimeOrigin::from(origin);562 Self::do_cancel_named(Some(origin.caller().clone()), id)?;563 Ok(())564 }565566 /// Schedule a named task after a delay.567 ///568 /// # <weight>569 /// Same as [`schedule_named`](Self::schedule_named).570 /// # </weight>571 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]572 pub fn schedule_named_after(573 origin: OriginFor<T>,574 id: ScheduledId,575 after: T::BlockNumber,576 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,577 priority: Option<schedule::Priority>,578 call: Box<CallOrHashOf<T>>,579 ) -> DispatchResult {580 T::ScheduleOrigin::ensure_origin(origin.clone())?;581582 if priority.is_some() {583 T::PrioritySetOrigin::ensure_origin(origin.clone())?;584 }585586 let origin = <T as Config>::RuntimeOrigin::from(origin);587 Self::do_schedule_named(588 id,589 DispatchTime::After(after),590 maybe_periodic,591 priority.unwrap_or(LOWEST_PRIORITY),592 origin.caller().clone(),593 *call,594 )?;595 Ok(())596 }597598 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]599 pub fn change_named_priority(600 origin: OriginFor<T>,601 id: ScheduledId,602 priority: schedule::Priority,603 ) -> DispatchResult {604 T::PrioritySetOrigin::ensure_origin(origin.clone())?;605 let origin = <T as Config>::Origin::from(origin);606 Self::do_change_named_priority(origin.caller().clone(), id, priority)607 }608 }609}610611impl<T: Config> Pallet<T> {612 #[cfg(feature = "try-runtime")]613 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {614 Ok(())615 }616617 #[cfg(feature = "try-runtime")]618 pub fn post_migrate_to_v3() -> Result<(), &'static str> {619 use frame_support::dispatch::GetStorageVersion;620621 assert!(Self::current_storage_version() == 3);622 for k in Agenda::<T>::iter_keys() {623 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;624 }625 Ok(())626 }627628 /// Helper to migrate scheduler when the pallet origin type has changed.629 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {630 Agenda::<T>::translate::<631 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,632 _,633 >(|_, agenda| {634 Some(635 agenda636 .into_iter()637 .map(|schedule| {638 schedule.map(|schedule| Scheduled {639 maybe_id: schedule.maybe_id,640 priority: schedule.priority,641 call: schedule.call,642 maybe_periodic: schedule.maybe_periodic,643 origin: schedule.origin.into(),644 _phantom: Default::default(),645 })646 })647 .collect::<Vec<_>>(),648 )649 });650 }651652 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {653 let now = frame_system::Pallet::<T>::block_number();654655 let when = match when {656 DispatchTime::At(x) => x,657 // The current block has already completed it's scheduled tasks, so658 // Schedule the task at lest one block after this current block.659 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),660 };661662 if when <= now {663 return Err(Error::<T>::TargetBlockNumberInPast.into());664 }665666 Ok(when)667 }668669 fn do_schedule_named(670 id: ScheduledId,671 when: DispatchTime<T::BlockNumber>,672 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,673 priority: schedule::Priority,674 origin: T::PalletsOrigin,675 call: CallOrHashOf<T>,676 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {677 // ensure id it is unique678 if Lookup::<T>::contains_key(&id) {679 return Err(Error::<T>::FailedToSchedule)?;680 }681682 let when = Self::resolve_time(when)?;683684 call.ensure_requested::<T::PreimageProvider>();685686 // sanitize maybe_periodic687 let maybe_periodic = maybe_periodic688 .filter(|p| p.1 > 1 && !p.0.is_zero())689 // Remove one from the number of repetitions since we will schedule one now.690 .map(|(p, c)| (p, c - 1));691692 let s = Scheduled {693 maybe_id: Some(id.clone()),694 priority,695 call: call.clone(),696 maybe_periodic,697 origin: origin.clone(),698 _phantom: Default::default(),699 };700701 // reserve balance for periodic execution702 // let sender =703 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;704 // let repeats = match maybe_periodic {705 // Some(p) => p.1,706 // None => 1,707 // };708 // let _ = T::CallExecutor::reserve_balance(709 // id.clone(),710 // sender,711 // call.as_value().unwrap().clone(),712 // repeats,713 // );714715 Agenda::<T>::append(when, Some(s));716 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;717 let address = (when, index);718 Lookup::<T>::insert(&id, &address);719 Self::deposit_event(Event::Scheduled { when, index });720721 Ok(address)722 }723724 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {725 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {726 if let Some((when, index)) = lookup.take() {727 let i = index as usize;728 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {729 if let Some(s) = agenda.get_mut(i) {730 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {731 if matches!(732 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),733 Some(Ordering::Less) | None734 ) {735 return Err(BadOrigin.into());736 }737 // release balance reserve738 // let sender = ensure_signed(739 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(740 // origin.unwrap(),741 // )742 // .into(),743 // )?;744 // let _ = T::CallExecutor::cancel_reserve(id, sender);745746 s.call.ensure_unrequested::<T::PreimageProvider>();747 }748 *s = None;749 }750 Ok(())751 })?;752753 Self::deposit_event(Event::Canceled { when, index });754 Ok(())755 } else {756 Err(Error::<T>::NotFound)?757 }758 })759 }760761 fn do_change_named_priority(762 origin: T::PalletsOrigin,763 id: ScheduledId,764 priority: schedule::Priority,765 ) -> DispatchResult {766 match Lookup::<T>::get(id) {767 Some((when, index)) => {768 let i = index as usize;769 Agenda::<T>::try_mutate(when, |agenda| {770 if let Some(Some(s)) = agenda.get_mut(i) {771 if matches!(772 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),773 Some(Ordering::Less) | None774 ) {775 return Err(BadOrigin.into());776 }777778 s.priority = priority;779 Self::deposit_event(Event::PriorityChanged { when, index, priority });780 }781 Ok(())782 })783 },784 None => Err(Error::<T>::NotFound.into())785 }786 }787}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 }416 continue;417 }418 };419420 let periodic = s.maybe_periodic.is_some();421 let call_weight = call.get_dispatch_info().weight;422 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));423 let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(424 s.origin.clone(),425 )426 .into();427 if ensure_signed(origin).is_ok() {428 // Weights of Signed dispatches expect their signing account to be whitelisted.429 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));430 }431432 // We allow a scheduled call if any is true:433 // - It's priority is `HARD_DEADLINE`434 // - It does not push the weight past the limit.435 // - It is the first item in the schedule436 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;437 let test_weight = total_weight438 .saturating_add(call_weight)439 .saturating_add(item_weight);440 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {441 // Cannot be scheduled this block - postpone until next.442 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));443 if let Some(ref id) = s.maybe_id {444 // NOTE: We could reasonably not do this (in which case there would be one445 // block where the named and delayed item could not be referenced by name),446 // but we will do it anyway since it should be mostly free in terms of447 // weight and it is slightly cleaner.448 let index = Agenda::<T>::decode_len(next).unwrap_or(0);449 Lookup::<T>::insert(id, (next, index as u32));450 }451 Agenda::<T>::append(next, Some(s));452 continue;453 }454455 let scheduled_origin =456 <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(s.origin.clone());457 let ensured_origin =458 T::ScheduleOrigin::ensure_origin(scheduled_origin.into()).unwrap();459460 let r;461 match ensured_origin {462 ScheduledEnsureOriginSuccess::Root => {463 r = Ok(call.dispatch_bypass_filter(frame_system::RawOrigin::Root.into()));464 }465 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 r = T::CallExecutor::dispatch_call(Some(sender), call.clone());469 }470 ScheduledEnsureOriginSuccess::Unsigned => {471 // Unsigned version of the above472 r = T::CallExecutor::dispatch_call(None, call.clone());473 }474 }475476 let mut actual_call_weight: Weight = item_weight;477 let result: Result<_, DispatchError> = match r {478 Ok(o) => match o {479 Ok(di) => {480 actual_call_weight = di.actual_weight.unwrap_or(item_weight);481 Ok(())482 }483 Err(err) => Err(err.error),484 },485 Err(_) => {486 log::error!(487 target: "runtime::scheduler",488 "Warning: Scheduler has failed to execute a post-dispatch transaction. \489 This block might have become invalid.");490 Err(DispatchError::CannotLookup)491 } // todo possibly force a skip/return here, do something with the error492 };493494 total_weight.saturating_accrue(item_weight);495 total_weight.saturating_accrue(actual_call_weight);496497 Self::deposit_event(Event::Dispatched {498 task: (now, index),499 id: s.maybe_id.clone(),500 result,501 });502503 if let &Some((period, count)) = &s.maybe_periodic {504 if count > 1 {505 s.maybe_periodic = Some((period, count - 1));506 } else {507 s.maybe_periodic = None;508 }509 let wake = now + period;510 let is_canceled;511512 // If scheduled is named, place its information in `Lookup`513 if let Some(ref id) = s.maybe_id {514 is_canceled = Lookup::<T>::get(id).is_none();515 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);516517 if !is_canceled {518 Lookup::<T>::insert(id, (wake, wake_index as u32));519 }520 } else {521 is_canceled = false;522 }523524 if !is_canceled {525 Agenda::<T>::append(wake, Some(s));526 }527 } else if let Some(ref id) = s.maybe_id {528 Lookup::<T>::remove(id);529 }530 }531 total_weight532 }533 }534535 #[pallet::call]536 impl<T: Config> Pallet<T> {537 /// Schedule a named task.538 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]539 pub fn schedule_named(540 origin: OriginFor<T>,541 id: ScheduledId,542 when: T::BlockNumber,543 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,544 priority: Option<schedule::Priority>,545 call: Box<CallOrHashOf<T>>,546 ) -> DispatchResult {547 T::ScheduleOrigin::ensure_origin(origin.clone())?;548549 if priority.is_some() {550 T::PrioritySetOrigin::ensure_origin(origin.clone())?;551 }552553 let origin = <T as Config>::RuntimeOrigin::from(origin);554 Self::do_schedule_named(555 id,556 DispatchTime::At(when),557 maybe_periodic,558 priority.unwrap_or(LOWEST_PRIORITY),559 origin.caller().clone(),560 *call,561 )?;562 Ok(())563 }564565 /// Cancel a named scheduled task.566 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]567 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {568 T::ScheduleOrigin::ensure_origin(origin.clone())?;569 let origin = <T as Config>::RuntimeOrigin::from(origin);570 Self::do_cancel_named(Some(origin.caller().clone()), id)?;571 Ok(())572 }573574 /// Schedule a named task after a delay.575 ///576 /// # <weight>577 /// Same as [`schedule_named`](Self::schedule_named).578 /// # </weight>579 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]580 pub fn schedule_named_after(581 origin: OriginFor<T>,582 id: ScheduledId,583 after: T::BlockNumber,584 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,585 priority: Option<schedule::Priority>,586 call: Box<CallOrHashOf<T>>,587 ) -> DispatchResult {588 T::ScheduleOrigin::ensure_origin(origin.clone())?;589590 if priority.is_some() {591 T::PrioritySetOrigin::ensure_origin(origin.clone())?;592 }593594 let origin = <T as Config>::RuntimeOrigin::from(origin);595 Self::do_schedule_named(596 id,597 DispatchTime::After(after),598 maybe_periodic,599 priority.unwrap_or(LOWEST_PRIORITY),600 origin.caller().clone(),601 *call,602 )?;603 Ok(())604 }605606 #[pallet::weight(<T as Config>::WeightInfo::change_named_priority(T::MaxScheduledPerBlock::get()))]607 pub fn change_named_priority(608 origin: OriginFor<T>,609 id: ScheduledId,610 priority: schedule::Priority,611 ) -> DispatchResult {612 T::PrioritySetOrigin::ensure_origin(origin.clone())?;613 let origin = <T as Config>::Origin::from(origin);614 Self::do_change_named_priority(origin.caller().clone(), id, priority)615 }616 }617}618619impl<T: Config> Pallet<T> {620 #[cfg(feature = "try-runtime")]621 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {622 Ok(())623 }624625 #[cfg(feature = "try-runtime")]626 pub fn post_migrate_to_v3() -> Result<(), &'static str> {627 use frame_support::dispatch::GetStorageVersion;628629 assert!(Self::current_storage_version() == 3);630 for k in Agenda::<T>::iter_keys() {631 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;632 }633 Ok(())634 }635636 /// Helper to migrate scheduler when the pallet origin type has changed.637 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {638 Agenda::<T>::translate::<639 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,640 _,641 >(|_, agenda| {642 Some(643 agenda644 .into_iter()645 .map(|schedule| {646 schedule.map(|schedule| Scheduled {647 maybe_id: schedule.maybe_id,648 priority: schedule.priority,649 call: schedule.call,650 maybe_periodic: schedule.maybe_periodic,651 origin: schedule.origin.into(),652 _phantom: Default::default(),653 })654 })655 .collect::<Vec<_>>(),656 )657 });658 }659660 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {661 let now = frame_system::Pallet::<T>::block_number();662663 let when = match when {664 DispatchTime::At(x) => x,665 // The current block has already completed it's scheduled tasks, so666 // Schedule the task at lest one block after this current block.667 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),668 };669670 if when <= now {671 return Err(Error::<T>::TargetBlockNumberInPast.into());672 }673674 Ok(when)675 }676677 fn do_schedule_named(678 id: ScheduledId,679 when: DispatchTime<T::BlockNumber>,680 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,681 priority: schedule::Priority,682 origin: T::PalletsOrigin,683 call: CallOrHashOf<T>,684 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {685 // ensure id it is unique686 if Lookup::<T>::contains_key(&id) {687 return Err(Error::<T>::FailedToSchedule)?;688 }689690 let when = Self::resolve_time(when)?;691692 call.ensure_requested::<T::PreimageProvider>();693694 // sanitize maybe_periodic695 let maybe_periodic = maybe_periodic696 .filter(|p| p.1 > 1 && !p.0.is_zero())697 // Remove one from the number of repetitions since we will schedule one now.698 .map(|(p, c)| (p, c - 1));699700 let s = Scheduled {701 maybe_id: Some(id.clone()),702 priority,703 call: call.clone(),704 maybe_periodic,705 origin: origin.clone(),706 _phantom: Default::default(),707 };708709 // reserve balance for periodic execution710 // let sender =711 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;712 // let repeats = match maybe_periodic {713 // Some(p) => p.1,714 // None => 1,715 // };716 // let _ = T::CallExecutor::reserve_balance(717 // id.clone(),718 // sender,719 // call.as_value().unwrap().clone(),720 // repeats,721 // );722723 Agenda::<T>::append(when, Some(s));724 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;725 let address = (when, index);726 Lookup::<T>::insert(&id, &address);727 Self::deposit_event(Event::Scheduled { when, index });728729 Ok(address)730 }731732 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {733 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {734 if let Some((when, index)) = lookup.take() {735 let i = index as usize;736 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {737 if let Some(s) = agenda.get_mut(i) {738 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {739 if matches!(740 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),741 Some(Ordering::Less) | None742 ) {743 return Err(BadOrigin.into());744 }745 // release balance reserve746 // let sender = ensure_signed(747 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(748 // origin.unwrap(),749 // )750 // .into(),751 // )?;752 // let _ = T::CallExecutor::cancel_reserve(id, sender);753754 s.call.ensure_unrequested::<T::PreimageProvider>();755 }756 *s = None;757 }758 Ok(())759 })?;760761 Self::deposit_event(Event::Canceled { when, index });762 Ok(())763 } else {764 Err(Error::<T>::NotFound)?765 }766 })767 }768769 fn do_change_named_priority(770 origin: T::PalletsOrigin,771 id: ScheduledId,772 priority: schedule::Priority,773 ) -> DispatchResult {774 match Lookup::<T>::get(id) {775 Some((when, index)) => {776 let i = index as usize;777 Agenda::<T>::try_mutate(when, |agenda| {778 if let Some(Some(s)) = agenda.get_mut(i) {779 if matches!(780 T::OriginPrivilegeCmp::cmp_privilege(&origin, &s.origin),781 Some(Ordering::Less) | None782 ) {783 return Err(BadOrigin.into());784 }785786 s.priority = priority;787 Self::deposit_event(Event::PriorityChanged {788 when,789 index,790 priority,791 });792 }793 Ok(())794 })795 }796 None => Err(Error::<T>::NotFound.into()),797 }798 }799}runtime/common/config/pallets/scheduler.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/scheduler.rs
+++ b/runtime/common/config/pallets/scheduler.rs
@@ -14,7 +14,11 @@
// You should have received a copy of the GNU General Public License
// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.
-use frame_support::{traits::{PrivilegeCmp, EnsureOrigin}, weights::Weight, parameter_types};
+use frame_support::{
+ traits::{PrivilegeCmp, EnsureOrigin},
+ weights::Weight,
+ parameter_types,
+};
use frame_system::{EnsureRoot, RawOrigin};
use sp_runtime::Perbill;
use core::cmp::Ordering;
@@ -37,7 +41,8 @@
pub struct EnsureSignedOrRoot<AccountId>(sp_std::marker::PhantomData<AccountId>);
impl<O: Into<Result<RawOrigin<AccountId>, O>> + From<RawOrigin<AccountId>>, AccountId: Decode>
- EnsureOrigin<O> for EnsureSignedOrRoot<AccountId> {
+ EnsureOrigin<O> for EnsureSignedOrRoot<AccountId>
+{
type Success = ScheduledEnsureOriginSuccess<AccountId>;
fn try_origin(o: O) -> Result<Self::Success, O> {
o.into().and_then(|o| match o {
@@ -60,7 +65,7 @@
(Root, Root) => Some(Ordering::Equal),
(Root, _) => Some(Ordering::Greater),
(_, Root) => Some(Ordering::Less),
- lr @ _ => (lr.0 == lr.1).then(|| Ordering::Equal)
+ lr @ _ => (lr.0 == lr.1).then(|| Ordering::Equal),
}
}
}
runtime/common/scheduler.rsdiffbeforeafterboth--- a/runtime/common/scheduler.rs
+++ b/runtime/common/scheduler.rs
@@ -84,10 +84,13 @@
let len = call.encoded_size();
let signed = match signer {
- Some(signer) => fp_self_contained::CheckedSignature::Signed(signer.clone().into(), get_signed_extras(signer.into())),
+ Some(signer) => fp_self_contained::CheckedSignature::Signed(
+ signer.clone().into(),
+ get_signed_extras(signer.into()),
+ ),
None => fp_self_contained::CheckedSignature::Unsigned,
};
-
+
let extrinsic = fp_self_contained::CheckedExtrinsic::<
AccountId,
Call,