difftreelog
Apply extrinsic custom trait
in: master
2 files changed
pallets/scheduler/src/lib.rsdiffbeforeafterboth1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//! specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//! index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//! `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating, SignedExtension},63};64use frame_support::{65 decl_module, decl_storage, decl_event, decl_error,66 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67 traits::{68 Get,69 schedule::{self, DispatchTime},70 OriginTrait, EnsureOrigin, IsType,71 },72 weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use up_sponsorship::SponsorshipHandler;77use scale_info::TypeInfo;7879/// Our pallet's configuration trait. All our types and constants go in here. If the80/// pallet is dependent on specific other pallets, then their configuration traits81/// should be added to our implied traits list.82///83/// `system::Config` should always be included in our implied traits.84/// //85pub trait Config: system::Config {86 /// The overarching event type.87 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;8889 /// The aggregated origin which the dispatch will take.90 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>91 + From<Self::PalletsOrigin>92 + IsType<<Self as system::Config>::Origin>;9394 /// The caller origin, overarching type of all pallets origins.95 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;9697 /// The aggregated call type.98 type Call: Parameter99 + Dispatchable<Origin = <Self as Config>::Origin>100 + GetDispatchInfo101 + From<system::Call<Self>>;102103 /// The maximum weight that may be scheduled per block for any dispatchables of less priority104 /// than `schedule::HARD_DEADLINE`.105 type MaximumWeight: Get<Weight>;106107 /// Required origin to schedule or cancel calls.108 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;109110 /// The maximum number of scheduled calls in the queue for a single block.111 /// Not strictly enforced, but used for weight estimation.112 type MaxScheduledPerBlock: Get<u32>;113114 /// Sponsoring function115 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;116117 /// Weight information for extrinsics in this pallet.118 type WeightInfo: WeightInfo;119120 /// Unchecked extrinsic type as expected by the runtime that uses this pallet.121 type PaymentHandler: SignedExtension;122}123124pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;125126pub const PERIODIC_CALLS_LIMIT: u32 = 100;127128// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;129130/// Just a simple index for naming period tasks.131pub type PeriodicIndex = u32;132/// The location of a scheduled task that can be used to remove it.133pub type TaskAddress<BlockNumber> = (BlockNumber, u32);134135#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]136#[derive(Clone, RuntimeDebug, Encode, Decode)]137struct ScheduledV1<Call, BlockNumber> {138 maybe_id: Option<Vec<u8>>,139 priority: schedule::Priority,140 call: Call,141 maybe_periodic: Option<schedule::Period<BlockNumber>>,142}143144/// Information regarding an item to be executed in the future.145#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]146#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]147pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {148 /// The unique identity for this task, if there is one.149 maybe_id: Option<Vec<u8>>,150 /// This task's priority.151 priority: schedule::Priority,152 /// The call to be dispatched.153 call: Call,154 /// If the call is periodic, then this points to the information concerning that.155 maybe_periodic: Option<schedule::Period<BlockNumber>>,156 /// The origin to dispatch the call.157 origin: PalletsOrigin,158 _phantom: PhantomData<AccountId>,159}160161/// The current version of Scheduled struct.162pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =163 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;164165// A value placed in storage that represents the current version of the Scheduler storage.166// This value is used by the `on_runtime_upgrade` logic to determine whether we run167// storage migration logic.168#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]169enum Releases {170 V1,171 V2,172}173174impl Default for Releases {175 fn default() -> Self {176 Releases::V1177 }178}179180#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]181pub struct CallSpec {182 module: u32,183 method: u32,184}185186decl_storage! {187 trait Store for Module<T: Config> as Scheduler {188 /// Items to be executed, indexed by the block number that they should be executed on.189 pub Agenda: map hasher(twox_64_concat) T::BlockNumber190 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;191192 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber193 => Vec<Option<CallSpec>>;194195 /// Lookup from identity to the block number and index of the task.196 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;197198 /// Storage version of the pallet.199 ///200 /// New networks start with last version.201 StorageVersion build(|_| Releases::V2): Releases;202 }203}204205decl_event!(206 pub enum Event<T> where <T as system::Config>::BlockNumber {207 /// Scheduled some task. \[when, index\]208 Scheduled(BlockNumber, u32),209 /// Canceled some task. \[when, index\]210 Canceled(BlockNumber, u32),211 /// Dispatched some task. \[task, id, result\]212 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),213 }214);215216decl_error! {217 pub enum Error for Module<T: Config> {218 /// Failed to schedule a call219 FailedToSchedule,220 /// Cannot find the scheduled call.221 NotFound,222 /// Given target block number is in the past.223 TargetBlockNumberInPast,224 /// Reschedule failed because it does not change scheduled time.225 RescheduleNoChange,226 }227}228229decl_module! {230 /// Scheduler module declaration.231 pub struct Module<T: Config> for enum Call232 where233 origin: <T as system::Config>::Origin234 {235 type Error = Error<T>;236 fn deposit_event() = default;237238239 /// Anonymously schedule a task.240 ///241 /// # <weight>242 /// - S = Number of already scheduled calls243 /// - Base Weight: 22.29 + .126 * S µs244 /// - DB Weight:245 /// - Read: Agenda246 /// - Write: Agenda247 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls248 /// # </weight>249 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]250 fn schedule(origin,251 when: T::BlockNumber,252 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,253 priority: schedule::Priority,254 call: Box<<T as Config>::Call>,255 )256 {257 let origin = <T as Config>::Origin::from(origin);258 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;259 }260261 /// Cancel an anonymously scheduled task.262 ///263 /// # <weight>264 /// - S = Number of already scheduled calls265 /// - Base Weight: 22.15 + 2.869 * S µs266 /// - DB Weight:267 /// - Read: Agenda268 /// - Write: Agenda, Lookup269 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls270 /// # </weight>271 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]272 fn cancel(origin, when: T::BlockNumber, index: u32) {273 T::ScheduleOrigin::ensure_origin(origin.clone())?;274 let origin = <T as Config>::Origin::from(origin);275 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;276 }277278 /// Schedule a named task.279 ///280 /// # <weight>281 /// - S = Number of already scheduled calls282 /// - Base Weight: 29.6 + .159 * S µs283 /// - DB Weight:284 /// - Read: Agenda, Lookup285 /// - Write: Agenda, Lookup286 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls287 /// # </weight>288 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]289 fn schedule_named(origin,290 id: Vec<u8>,291 when: T::BlockNumber,292 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,293 priority: schedule::Priority,294 call: Box<<T as Config>::Call>,295 ) {296 T::ScheduleOrigin::ensure_origin(origin.clone())?;297 let origin = <T as Config>::Origin::from(origin);298 Self::do_schedule_named(299 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call300 )?;301 }302303 /// Cancel a named scheduled task.304 ///305 /// # <weight>306 /// - S = Number of already scheduled calls307 /// - Base Weight: 24.91 + 2.907 * S µs308 /// - DB Weight:309 /// - Read: Agenda, Lookup310 /// - Write: Agenda, Lookup311 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls312 /// # </weight>313 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]314 fn cancel_named(origin, id: Vec<u8>) {315 T::ScheduleOrigin::ensure_origin(origin.clone())?;316 let origin = <T as Config>::Origin::from(origin);317 Self::do_cancel_named(Some(origin.caller().clone()), id)?;318 }319320 /// Anonymously schedule a task after a delay.321 ///322 /// # <weight>323 /// Same as [`schedule`].324 /// # </weight>325 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]326 fn schedule_after(origin,327 after: T::BlockNumber,328 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,329 priority: schedule::Priority,330 call: Box<<T as Config>::Call>,331 ) {332 T::ScheduleOrigin::ensure_origin(origin.clone())?;333 let origin = <T as Config>::Origin::from(origin);334 Self::do_schedule_nameless(335 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call336 )?;337 }338339 /// Schedule a named task after a delay.340 ///341 /// # <weight>342 /// Same as [`schedule_named`].343 /// # </weight>344 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]345 fn schedule_named_after(origin,346 id: Vec<u8>,347 after: T::BlockNumber,348 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,349 priority: schedule::Priority,350 call: Box<<T as Config>::Call>,351 ) {352 T::ScheduleOrigin::ensure_origin(origin.clone())?;353 let origin = <T as Config>::Origin::from(origin);354 Self::do_schedule_named(355 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call356 )?;357 }358359 /// Execute the scheduled calls360 ///361 /// # <weight>362 /// - S = Number of already scheduled calls363 /// - N = Named scheduled calls364 /// - P = Periodic Calls365 /// - Base Weight: 9.243 + 23.45 * S µs366 /// - DB Weight:367 /// - Read: Agenda + Lookup * N + Agenda(Future) * P368 /// - Write: Agenda + Lookup * N + Agenda(future) * P369 /// # </weight>370 fn on_initialize(now: T::BlockNumber) -> Weight {371 let limit = T::MaximumWeight::get();372 let mut queued = Agenda::<T>::take(now)373 .into_iter()374 .enumerate()375 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))376 .collect::<Vec<_>>();377 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {378 log::warn!(379 target: "runtime::scheduler",380 "Warning: This block has more items queued in Scheduler than \381 expected from the runtime configuration. An update might be needed."382 );383 }384 queued.sort_by_key(|(_, s)| s.priority);385 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)386 let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)387 queued.into_iter()388 .enumerate()389 .scan(base_weight, |cumulative_weight, (order, (index, s))| {390 *cumulative_weight = cumulative_weight391 .saturating_add(s.call.get_dispatch_info().weight);392393 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(394 s.origin.clone()395 ).into();396397 if ensure_signed(origin).is_ok() {398 // AccountData for inner call origin accountdata.399 *cumulative_weight = cumulative_weight400 .saturating_add(T::DbWeight::get().reads_writes(1, 1));401 }402403 if s.maybe_id.is_some() {404 // Remove/Modify Lookup405 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));406 }407 if s.maybe_periodic.is_some() {408 // Read/Write Agenda for future block409 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));410 }411412 Some((order, index, *cumulative_weight, s))413 })414 .filter_map(|(order, index, cumulative_weight, mut s)| {415 // We allow a scheduled call if any is true:416 // - It's priority is `HARD_DEADLINE`417 // - It does not push the weight past the limit.418 // - It is the first item in the schedule419 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {420421 // let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(422 // s.origin.clone()423 // ).into();424 // let sender = ensure_signed(origin).unwrap_or_default();425 // let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);426 // let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));427 // let r = s.call.clone().dispatch(sponsor.into());428 let maybe_id = s.maybe_id.clone();429 if let Some((period, count)) = s.maybe_periodic {430 if count > 1 {431 s.maybe_periodic = Some((period, count - 1));432 } else {433 s.maybe_periodic = None;434 }435 let next = now + period;436 // If scheduled is named, place it's information in `Lookup`437 if let Some(ref id) = s.maybe_id {438 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);439 Lookup::<T>::insert(id, (next, next_index as u32));440 }441 Agenda::<T>::append(next, Some(s));442 } else if let Some(ref id) = s.maybe_id {443 Lookup::<T>::remove(id);444 }445 Self::deposit_event(RawEvent::Dispatched(446 (now, index),447 maybe_id,448 Ok(())// r.map(|_| ()).map_err(|e| e.error)449 ));450 total_weight = cumulative_weight;451 None452 } else {453 Some(Some(s))454 }455 })456 .for_each(|unused| {457 let next = now + One::one();458 Agenda::<T>::append(next, unused);459 });460461 total_weight462 }463 }464}465466impl<T: Config> Module<T> {467 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {468 let now = frame_system::Pallet::<T>::block_number();469470 let when = match when {471 DispatchTime::At(x) => x,472 // The current block has already completed it's scheduled tasks, so473 // Schedule the task at lest one block after this current block.474 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),475 };476477 if when <= now {478 return Err(Error::<T>::TargetBlockNumberInPast.into());479 }480481 Ok(when)482 }483484 fn do_schedule(485 maybe_id: Option<Vec<u8>>,486 when: DispatchTime<T::BlockNumber>,487 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,488 priority: schedule::Priority,489 origin: T::PalletsOrigin,490 call: <T as Config>::Call,491 ) -> Result<(T::BlockNumber, u32), DispatchError> {492 let when = Self::resolve_time(when)?;493494 let sender = ensure_signed(495 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into()496 ).unwrap_or_default();497 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);498 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));499 let r = call.clone().dispatch(sponsor.into());500501 //T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch call502503 // sanitize maybe_periodic504 let maybe_periodic = maybe_periodic505 .filter(|p| p.1 > 1 && !p.0.is_zero())506 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.507 .map(|(p, c)| (p, std::cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));508 509 let s = Some(Scheduled {510 maybe_id,511 priority,512 call,513 maybe_periodic,514 origin,515 _phantom: PhantomData::<T::AccountId>::default(),516 });517 Agenda::<T>::append(when, s);518 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;519 if index > T::MaxScheduledPerBlock::get() {520 log::warn!(521 target: "runtime::scheduler",522 "Warning: There are more items queued in the Scheduler than \523 expected from the runtime configuration. An update might be needed.",524 );525 }526527 Ok((when, index))528 }529530 fn do_schedule_nameless(531 when: DispatchTime<T::BlockNumber>,532 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,533 priority: schedule::Priority,534 origin: T::PalletsOrigin,535 call: <T as Config>::Call,536 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {537 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;538 let (when, index) = address;539540 Self::deposit_event(RawEvent::Scheduled(when, index));541542 Ok(address)543 }544545 fn do_cancel(546 origin: Option<T::PalletsOrigin>,547 (when, index): TaskAddress<T::BlockNumber>,548 ) -> Result<(), DispatchError> {549 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {550 agenda.get_mut(index as usize).map_or(551 Ok(None),552 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {553 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {554 if *o != s.origin {555 return Err(BadOrigin.into());556 }557 };558 Ok(s.take())559 },560 )561 })?;562 if let Some(s) = scheduled {563 if let Some(id) = s.maybe_id {564 Lookup::<T>::remove(id);565 }566 Self::deposit_event(RawEvent::Canceled(when, index));567 Ok(())568 } else {569 Err(Error::<T>::NotFound.into())570 }571 }572573 fn do_reschedule(574 (when, index): TaskAddress<T::BlockNumber>,575 new_time: DispatchTime<T::BlockNumber>,576 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {577 let new_time = Self::resolve_time(new_time)?;578579 if new_time == when {580 return Err(Error::<T>::RescheduleNoChange.into());581 }582583 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {584 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;585 let task = task.take().ok_or(Error::<T>::NotFound)?;586 Agenda::<T>::append(new_time, Some(task));587 Ok(())588 })?;589590 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;591 Self::deposit_event(RawEvent::Canceled(when, index));592 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));593594 Ok((new_time, new_index))595 }596597 fn do_schedule_named(598 id: Vec<u8>,599 when: DispatchTime<T::BlockNumber>,600 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,601 priority: schedule::Priority,602 origin: T::PalletsOrigin,603 call: <T as Config>::Call,604 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {605 // ensure id length does not exceed expectations & is unique606 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()607 || Lookup::<T>::contains_key(&id)608 {609 return Err(Error::<T>::FailedToSchedule.into());610 }611612 let address = Self::do_schedule(Some(id.clone()), when, maybe_periodic, priority, origin, call)?;613 let (when, index) = address;614615 Lookup::<T>::insert(&id, &address);616 Self::deposit_event(RawEvent::Scheduled(when, index));617 Ok(address)618 }619620 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {621 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {622 if let Some((when, index)) = lookup.take() {623 let i = index as usize;624 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {625 if let Some(s) = agenda.get_mut(i) {626 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {627 if *o != s.origin {628 return Err(BadOrigin.into());629 }630 }631 *s = None;632 }633 Ok(())634 })?;635 Self::deposit_event(RawEvent::Canceled(when, index));636 Ok(())637 } else {638 Err(Error::<T>::NotFound.into())639 }640 })641 }642643 fn do_reschedule_named(644 id: Vec<u8>,645 new_time: DispatchTime<T::BlockNumber>,646 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {647 let new_time = Self::resolve_time(new_time)?;648649 Lookup::<T>::try_mutate_exists(650 id,651 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {652 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;653654 if new_time == when {655 return Err(Error::<T>::RescheduleNoChange.into());656 }657658 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {659 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;660 let task = task.take().ok_or(Error::<T>::NotFound)?;661 Agenda::<T>::append(new_time, Some(task));662663 Ok(())664 })?;665666 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;667 Self::deposit_event(RawEvent::Canceled(when, index));668 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));669670 *lookup = Some((new_time, new_index));671672 Ok((new_time, new_index))673 },674 )675 }676}677678impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>679 for Module<T>680{681 type Address = TaskAddress<T::BlockNumber>;682683 fn schedule(684 when: DispatchTime<T::BlockNumber>,685 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,686 priority: schedule::Priority,687 origin: T::PalletsOrigin,688 call: <T as Config>::Call,689 ) -> Result<Self::Address, DispatchError> {690 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)691 }692693 fn cancel((when, index): Self::Address) -> Result<(), ()> {694 Self::do_cancel(None, (when, index)).map_err(|_| ())695 }696697 fn reschedule(698 address: Self::Address,699 when: DispatchTime<T::BlockNumber>,700 ) -> Result<Self::Address, DispatchError> {701 Self::do_reschedule(address, when)702 }703704 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {705 Agenda::<T>::get(when)706 .get(index as usize)707 .ok_or(())708 .map(|_| when)709 }710}711712impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>713 for Module<T>714{715 type Address = TaskAddress<T::BlockNumber>;716717 fn schedule_named(718 id: Vec<u8>,719 when: DispatchTime<T::BlockNumber>,720 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,721 priority: schedule::Priority,722 origin: T::PalletsOrigin,723 call: <T as Config>::Call,724 ) -> Result<Self::Address, ()> {725 Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())726 }727728 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {729 Self::do_cancel_named(None, id).map_err(|_| ())730 }731732 fn reschedule_named(733 id: Vec<u8>,734 when: DispatchTime<T::BlockNumber>,735 ) -> Result<Self::Address, DispatchError> {736 Self::do_reschedule_named(id, when)737 }738739 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {740 Lookup::<T>::get(id)741 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))742 .ok_or(())743 }744}745746#[cfg(test)]747#[allow(clippy::from_over_into)]748mod tests {749 use super::*;750751 use frame_support::{752 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,753 };754 use sp_core::H256;755 use sp_runtime::{756 Perbill,757 testing::Header,758 traits::{BlakeTwo256, IdentityLookup},759 };760 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};761 use crate as scheduler;762763 mod logger {764 use super::*;765 use std::cell::RefCell;766767 thread_local! {768 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());769 }770 pub trait Config: system::Config {771 type Event: From<Event> + Into<<Self as system::Config>::Event>;772 }773 decl_event! {774 pub enum Event {775 Logged(u32, Weight),776 }777 }778 decl_module! {779 pub struct Module<T: Config> for enum Call780 where781 origin: <T as system::Config>::Origin,782 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>783 {784 fn deposit_event() = default;785786 #[weight = *weight]787 fn log(origin, i: u32, weight: Weight) {788 Self::deposit_event(Event::Logged(i, weight));789 LOG.with(|log| {790 log.borrow_mut().push((origin.caller().clone(), i));791 })792 }793794 #[weight = *weight]795 fn log_without_filter(origin, i: u32, weight: Weight) {796 Self::deposit_event(Event::Logged(i, weight));797 LOG.with(|log| {798 log.borrow_mut().push((origin.caller().clone(), i));799 })800 }801 }802 }803 }804805 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;806 type Block = frame_system::mocking::MockBlock<Test>;807808 frame_support::construct_runtime!(809 pub enum Test where810 Block = Block,811 NodeBlock = Block,812 UncheckedExtrinsic = UncheckedExtrinsic,813 {814 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},815 Logger: logger::{Pallet, Call, Event},816 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},817 }818 );819820 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.821 pub struct BaseFilter;822 impl Contains<Call> for BaseFilter {823 fn contains(call: &Call) -> bool {824 !matches!(call, Call::Logger(logger::Call::log { .. }))825 }826 }827828 parameter_types! {829 pub const BlockHashCount: u64 = 250;830 pub BlockWeights: frame_system::limits::BlockWeights =831 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);832 }833 impl system::Config for Test {834 type BaseCallFilter = BaseFilter;835 type BlockWeights = ();836 type BlockLength = ();837 type DbWeight = RocksDbWeight;838 type Origin = Origin;839 type Call = Call;840 type Index = u64;841 type BlockNumber = u64;842 type Hash = H256;843 type Hashing = BlakeTwo256;844 type AccountId = u64;845 type Lookup = IdentityLookup<Self::AccountId>;846 type Header = Header;847 type Event = Event;848 type BlockHashCount = BlockHashCount;849 type Version = ();850 type PalletInfo = PalletInfo;851 type AccountData = ();852 type OnNewAccount = ();853 type OnKilledAccount = ();854 type SystemWeightInfo = ();855 type SS58Prefix = ();856 type OnSetCode = ();857 }858 impl logger::Config for Test {859 type Event = Event;860 }861 parameter_types! {862 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;863 pub const MaxScheduledPerBlock: u32 = 10;864 }865 ord_parameter_types! {866 pub const One: u64 = 1;867 }868869 impl Config for Test {870 type Event = Event;871 type Origin = Origin;872 type PalletsOrigin = OriginCaller;873 type Call = Call;874 type MaximumWeight = MaximumSchedulerWeight;875 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;876 type MaxScheduledPerBlock = MaxScheduledPerBlock;877 type WeightInfo = ();878 type SponsorshipHandler = ();879 type PaymentHandler = ();880 }881}1// This file is part of Substrate.23// Copyright (C) 2017-2021 Parity Technologies (UK) Ltd.4// SPDX-License-Identifier: Apache-2.056// Licensed under the Apache License, Version 2.0 (the "License");7// you may not use this file except in compliance with the License.8// You may obtain a copy of the License at9//10// http://www.apache.org/licenses/LICENSE-2.011//12// Unless required by applicable law or agreed to in writing, software13// distributed under the License is distributed on an "AS IS" BASIS,14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.15// See the License for the specific language governing permissions and16// limitations under the License.1718//! # Scheduler19//! A module for scheduling dispatches.20//!21//! - [`Config`]22//! - [`Call`]23//! - [`Module`]24//!25//! ## Overview26//!27//! This module exposes capabilities for scheduling dispatches to occur at a28//! specified block number or at a specified period. These scheduled dispatches29//! may be named or anonymous and may be canceled.30//!31//! **NOTE:** The scheduled calls will be dispatched with the default filter32//! for the origin: namely `frame_system::Config::BaseCallFilter` for all origin33//! except root which will get no filter. And not the filter contained in origin34//! use to call `fn schedule`.35//!36//! If a call is scheduled using proxy or whatever mecanism which adds filter,37//! then those filter will not be used when dispatching the schedule call.38//!39//! ## Interface40//!41//! ### Dispatchable Functions42//!43//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a44//! specified block and with a specified priority.45//! * `cancel` - cancel a scheduled dispatch, specified by block number and46//! index.47//! * `schedule_named` - augments the `schedule` interface with an additional48//! `Vec<u8>` parameter that can be used for identification.49//! * `cancel_named` - the named complement to the cancel function.5051// Ensure we're `no_std` when compiling for Wasm.52#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{One, BadOrigin, Saturating},63};64use frame_support::{65 decl_module, decl_storage, decl_event, decl_error,66 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},67 traits::{68 Get,69 schedule::{self, DispatchTime},70 OriginTrait, EnsureOrigin, IsType,71 },72 weights::{GetDispatchInfo, Weight},73};74use frame_system::{self as system, ensure_signed};75pub use weights::WeightInfo;76use scale_info::TypeInfo;77use sp_runtime::ApplyExtrinsicResult;78use sp_runtime::traits::{IdentifyAccount, Verify};79use sp_runtime::{MultiSignature};8081pub trait ApplyExtrinsic<C: Dispatchable> {82 fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult;83}8485/// The address format for describing accounts.86pub type Signature = MultiSignature;87pub type Address = sp_runtime::MultiAddress<AccountId, ()>;88pub type AccountId = <<Signature as Verify>::Signer as IdentifyAccount>::AccountId;8990/// Our pallet's configuration trait. All our types and constants go in here. If the91/// pallet is dependent on specific other pallets, then their configuration traits92/// should be added to our implied traits list.93///94/// `system::Config` should always be included in our implied traits.95/// //96pub trait Config: system::Config {97 /// The overarching event type.98 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;99100 /// The aggregated origin which the dispatch will take.101 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>102 + From<Self::PalletsOrigin>103 + IsType<<Self as system::Config>::Origin>;104105 /// The caller origin, overarching type of all pallets origins.106 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;107108 /// The aggregated call type.109 type Call: Parameter110 + Dispatchable<Origin = <Self as Config>::Origin>111 + GetDispatchInfo112 + From<system::Call<Self>>;113114 /// The maximum weight that may be scheduled per block for any dispatchables of less priority115 /// than `schedule::HARD_DEADLINE`.116 type MaximumWeight: Get<Weight>;117118 /// Required origin to schedule or cancel calls.119 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;120121 /// The maximum number of scheduled calls in the queue for a single block.122 /// Not strictly enforced, but used for weight estimation.123 type MaxScheduledPerBlock: Get<u32>;124125 /// Weight information for extrinsics in this pallet.126 type WeightInfo: WeightInfo;127128 type Executor: ApplyExtrinsic<<Self as Config>::Call>;129}130131pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;132133pub const PERIODIC_CALLS_LIMIT: u32 = 100;134135// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;136137/// Just a simple index for naming period tasks.138pub type PeriodicIndex = u32;139/// The location of a scheduled task that can be used to remove it.140pub type TaskAddress<BlockNumber> = (BlockNumber, u32);141142#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]143#[derive(Clone, RuntimeDebug, Encode, Decode)]144struct ScheduledV1<Call, BlockNumber> {145 maybe_id: Option<Vec<u8>>,146 priority: schedule::Priority,147 call: Call,148 maybe_periodic: Option<schedule::Period<BlockNumber>>,149}150151/// Information regarding an item to be executed in the future.152#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]153#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]154pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {155 /// The unique identity for this task, if there is one.156 maybe_id: Option<Vec<u8>>,157 /// This task's priority.158 priority: schedule::Priority,159 /// The call to be dispatched.160 call: Call,161 /// If the call is periodic, then this points to the information concerning that.162 maybe_periodic: Option<schedule::Period<BlockNumber>>,163 /// The origin to dispatch the call.164 origin: PalletsOrigin,165 _phantom: PhantomData<AccountId>,166}167168/// The current version of Scheduled struct.169pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =170 ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;171172// A value placed in storage that represents the current version of the Scheduler storage.173// This value is used by the `on_runtime_upgrade` logic to determine whether we run174// storage migration logic.175#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug, TypeInfo)]176enum Releases {177 V1,178 V2,179}180181impl Default for Releases {182 fn default() -> Self {183 Releases::V1184 }185}186187#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]188pub struct CallSpec {189 module: u32,190 method: u32,191}192193decl_storage! {194 trait Store for Module<T: Config> as Scheduler {195 /// Items to be executed, indexed by the block number that they should be executed on.196 pub Agenda: map hasher(twox_64_concat) T::BlockNumber197 => Vec<Option<Scheduled<<T as Config>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;198199 pub SpecAgenda: map hasher(twox_64_concat) T::BlockNumber200 => Vec<Option<CallSpec>>;201202 /// Lookup from identity to the block number and index of the task.203 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;204205 /// Storage version of the pallet.206 ///207 /// New networks start with last version.208 StorageVersion build(|_| Releases::V2): Releases;209 }210}211212decl_event!(213 pub enum Event<T> where <T as system::Config>::BlockNumber {214 /// Scheduled some task. \[when, index\]215 Scheduled(BlockNumber, u32),216 /// Canceled some task. \[when, index\]217 Canceled(BlockNumber, u32),218 /// Dispatched some task. \[task, id, result\]219 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),220 }221);222223decl_error! {224 pub enum Error for Module<T: Config> {225 /// Failed to schedule a call226 FailedToSchedule,227 /// Cannot find the scheduled call.228 NotFound,229 /// Given target block number is in the past.230 TargetBlockNumberInPast,231 /// Reschedule failed because it does not change scheduled time.232 RescheduleNoChange,233 }234}235236decl_module! {237 /// Scheduler module declaration.238 pub struct Module<T: Config> for enum Call239 where240 origin: <T as system::Config>::Origin241 {242 type Error = Error<T>;243 fn deposit_event() = default;244245246 /// Anonymously schedule a task.247 ///248 /// # <weight>249 /// - S = Number of already scheduled calls250 /// - Base Weight: 22.29 + .126 * S µs251 /// - DB Weight:252 /// - Read: Agenda253 /// - Write: Agenda254 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls255 /// # </weight>256 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]257 fn schedule(origin,258 when: T::BlockNumber,259 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,260 priority: schedule::Priority,261 call: Box<<T as Config>::Call>,262 )263 {264 let origin = <T as Config>::Origin::from(origin);265 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;266 }267268 /// Cancel an anonymously scheduled task.269 ///270 /// # <weight>271 /// - S = Number of already scheduled calls272 /// - Base Weight: 22.15 + 2.869 * S µs273 /// - DB Weight:274 /// - Read: Agenda275 /// - Write: Agenda, Lookup276 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls277 /// # </weight>278 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]279 fn cancel(origin, when: T::BlockNumber, index: u32) {280 T::ScheduleOrigin::ensure_origin(origin.clone())?;281 let origin = <T as Config>::Origin::from(origin);282 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;283 }284285 /// Schedule a named task.286 ///287 /// # <weight>288 /// - S = Number of already scheduled calls289 /// - Base Weight: 29.6 + .159 * S µs290 /// - DB Weight:291 /// - Read: Agenda, Lookup292 /// - Write: Agenda, Lookup293 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls294 /// # </weight>295 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]296 fn schedule_named(origin,297 id: Vec<u8>,298 when: T::BlockNumber,299 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,300 priority: schedule::Priority,301 call: Box<<T as Config>::Call>,302 ) {303 T::ScheduleOrigin::ensure_origin(origin.clone())?;304 let origin = <T as Config>::Origin::from(origin);305 Self::do_schedule_named(306 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call307 )?;308 }309310 /// Cancel a named scheduled task.311 ///312 /// # <weight>313 /// - S = Number of already scheduled calls314 /// - Base Weight: 24.91 + 2.907 * S µs315 /// - DB Weight:316 /// - Read: Agenda, Lookup317 /// - Write: Agenda, Lookup318 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls319 /// # </weight>320 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]321 fn cancel_named(origin, id: Vec<u8>) {322 T::ScheduleOrigin::ensure_origin(origin.clone())?;323 let origin = <T as Config>::Origin::from(origin);324 Self::do_cancel_named(Some(origin.caller().clone()), id)?;325 }326327 /// Anonymously schedule a task after a delay.328 ///329 /// # <weight>330 /// Same as [`schedule`].331 /// # </weight>332 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]333 fn schedule_after(origin,334 after: T::BlockNumber,335 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,336 priority: schedule::Priority,337 call: Box<<T as Config>::Call>,338 ) {339 T::ScheduleOrigin::ensure_origin(origin.clone())?;340 let origin = <T as Config>::Origin::from(origin);341 Self::do_schedule_nameless(342 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call343 )?;344 }345346 /// Schedule a named task after a delay.347 ///348 /// # <weight>349 /// Same as [`schedule_named`].350 /// # </weight>351 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]352 fn schedule_named_after(origin,353 id: Vec<u8>,354 after: T::BlockNumber,355 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,356 priority: schedule::Priority,357 call: Box<<T as Config>::Call>,358 ) {359 T::ScheduleOrigin::ensure_origin(origin.clone())?;360 let origin = <T as Config>::Origin::from(origin);361 Self::do_schedule_named(362 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call363 )?;364 }365366 /// Execute the scheduled calls367 ///368 /// # <weight>369 /// - S = Number of already scheduled calls370 /// - N = Named scheduled calls371 /// - P = Periodic Calls372 /// - Base Weight: 9.243 + 23.45 * S µs373 /// - DB Weight:374 /// - Read: Agenda + Lookup * N + Agenda(Future) * P375 /// - Write: Agenda + Lookup * N + Agenda(future) * P376 /// # </weight>377 fn on_initialize(now: T::BlockNumber) -> Weight {378 let limit = T::MaximumWeight::get();379 let mut queued = Agenda::<T>::take(now)380 .into_iter()381 .enumerate()382 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))383 .collect::<Vec<_>>();384 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {385 log::warn!(386 target: "runtime::scheduler",387 "Warning: This block has more items queued in Scheduler than \388 expected from the runtime configuration. An update might be needed."389 );390 }391 queued.sort_by_key(|(_, s)| s.priority);392 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)393 let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)394 queued.into_iter()395 .enumerate()396 .scan(base_weight, |cumulative_weight, (order, (index, s))| {397 *cumulative_weight = cumulative_weight398 .saturating_add(s.call.get_dispatch_info().weight);399400 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(401 s.origin.clone()402 ).into();403404 if ensure_signed(origin).is_ok() {405 // AccountData for inner call origin accountdata.406 *cumulative_weight = cumulative_weight407 .saturating_add(T::DbWeight::get().reads_writes(1, 1));408 }409410 if s.maybe_id.is_some() {411 // Remove/Modify Lookup412 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));413 }414 if s.maybe_periodic.is_some() {415 // Read/Write Agenda for future block416 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));417 }418419 Some((order, index, *cumulative_weight, s))420 })421 .filter_map(|(order, index, cumulative_weight, mut s)| {422 // We allow a scheduled call if any is true:423 // - It's priority is `HARD_DEADLINE`424 // - It does not push the weight past the limit.425 // - It is the first item in the schedule426 if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {427428 // let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(429 // s.origin.clone()430 // ).into();431 // let sender = ensure_signed(origin).unwrap_or_default();432 // let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call).unwrap_or(sender);433 // let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));434 // let r = s.call.clone().dispatch(sponsor.into());435 let maybe_id = s.maybe_id.clone();436 if let Some((period, count)) = s.maybe_periodic {437 if count > 1 {438 s.maybe_periodic = Some((period, count - 1));439 } else {440 s.maybe_periodic = None;441 }442 let next = now + period;443 // If scheduled is named, place it's information in `Lookup`444 if let Some(ref id) = s.maybe_id {445 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);446 Lookup::<T>::insert(id, (next, next_index as u32));447 }448 Agenda::<T>::append(next, Some(s));449 } else if let Some(ref id) = s.maybe_id {450 Lookup::<T>::remove(id);451 }452 Self::deposit_event(RawEvent::Dispatched(453 (now, index),454 maybe_id,455 Ok(())// r.map(|_| ()).map_err(|e| e.error)456 ));457 total_weight = cumulative_weight;458 None459 } else {460 Some(Some(s))461 }462 })463 .for_each(|unused| {464 let next = now + One::one();465 Agenda::<T>::append(next, unused);466 });467468 total_weight469 }470 }471}472473impl<T: Config> Module<T> {474 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {475 let now = frame_system::Pallet::<T>::block_number();476477 let when = match when {478 DispatchTime::At(x) => x,479 // The current block has already completed it's scheduled tasks, so480 // Schedule the task at lest one block after this current block.481 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),482 };483484 if when <= now {485 return Err(Error::<T>::TargetBlockNumberInPast.into());486 }487488 Ok(when)489 }490491 fn do_schedule(492 maybe_id: Option<Vec<u8>>,493 when: DispatchTime<T::BlockNumber>,494 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,495 priority: schedule::Priority,496 origin: T::PalletsOrigin,497 call: <T as Config>::Call,498 ) -> Result<(T::BlockNumber, u32), DispatchError> {499 let when = Self::resolve_time(when)?;500501 let sender = ensure_signed(502 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),503 )504 .unwrap_or_default();505 let who_will_pay = sender; // T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);506 let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay));507 let r = call.clone().dispatch(sponsor.into());508509 //T::PaymentHandler::validate(sponsor.into(), call.clone(), ); todo dispatch call510511 // sanitize maybe_periodic512 let maybe_periodic = None;513 // let maybe_periodic = maybe_periodic514 // .filter(|p| p.1 > 1 && !p.0.is_zero())515 // // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.516 // .map(|(p, c)| (p, std::cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));517518 let s = Some(Scheduled {519 maybe_id,520 priority,521 call,522 maybe_periodic,523 origin,524 _phantom: PhantomData::<T::AccountId>::default(),525 });526 Agenda::<T>::append(when, s);527 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;528 if index > T::MaxScheduledPerBlock::get() {529 log::warn!(530 target: "runtime::scheduler",531 "Warning: There are more items queued in the Scheduler than \532 expected from the runtime configuration. An update might be needed.",533 );534 }535536 Ok((when, index))537 }538539 fn do_schedule_nameless(540 when: DispatchTime<T::BlockNumber>,541 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,542 priority: schedule::Priority,543 origin: T::PalletsOrigin,544 call: <T as Config>::Call,545 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {546 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;547 let (when, index) = address;548549 Self::deposit_event(RawEvent::Scheduled(when, index));550551 Ok(address)552 }553554 fn do_cancel(555 origin: Option<T::PalletsOrigin>,556 (when, index): TaskAddress<T::BlockNumber>,557 ) -> Result<(), DispatchError> {558 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {559 agenda.get_mut(index as usize).map_or(560 Ok(None),561 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {562 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {563 if *o != s.origin {564 return Err(BadOrigin.into());565 }566 };567 Ok(s.take())568 },569 )570 })?;571 if let Some(s) = scheduled {572 if let Some(id) = s.maybe_id {573 Lookup::<T>::remove(id);574 }575 Self::deposit_event(RawEvent::Canceled(when, index));576 Ok(())577 } else {578 Err(Error::<T>::NotFound.into())579 }580 }581582 fn do_reschedule(583 (when, index): TaskAddress<T::BlockNumber>,584 new_time: DispatchTime<T::BlockNumber>,585 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {586 let new_time = Self::resolve_time(new_time)?;587588 if new_time == when {589 return Err(Error::<T>::RescheduleNoChange.into());590 }591592 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {593 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;594 let task = task.take().ok_or(Error::<T>::NotFound)?;595 Agenda::<T>::append(new_time, Some(task));596 Ok(())597 })?;598599 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;600 Self::deposit_event(RawEvent::Canceled(when, index));601 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));602603 Ok((new_time, new_index))604 }605606 fn do_schedule_named(607 id: Vec<u8>,608 when: DispatchTime<T::BlockNumber>,609 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,610 priority: schedule::Priority,611 origin: T::PalletsOrigin,612 call: <T as Config>::Call,613 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {614 // ensure id length does not exceed expectations & is unique615 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()616 || Lookup::<T>::contains_key(&id)617 {618 return Err(Error::<T>::FailedToSchedule.into());619 }620621 let address = Self::do_schedule(622 Some(id.clone()),623 when,624 maybe_periodic,625 priority,626 origin,627 call,628 )?;629 let (when, index) = address;630631 Lookup::<T>::insert(&id, &address);632 Self::deposit_event(RawEvent::Scheduled(when, index));633 Ok(address)634 }635636 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {637 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {638 if let Some((when, index)) = lookup.take() {639 let i = index as usize;640 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {641 if let Some(s) = agenda.get_mut(i) {642 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {643 if *o != s.origin {644 return Err(BadOrigin.into());645 }646 }647 *s = None;648 }649 Ok(())650 })?;651 Self::deposit_event(RawEvent::Canceled(when, index));652 Ok(())653 } else {654 Err(Error::<T>::NotFound.into())655 }656 })657 }658659 fn do_reschedule_named(660 id: Vec<u8>,661 new_time: DispatchTime<T::BlockNumber>,662 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {663 let new_time = Self::resolve_time(new_time)?;664665 Lookup::<T>::try_mutate_exists(666 id,667 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {668 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;669670 if new_time == when {671 return Err(Error::<T>::RescheduleNoChange.into());672 }673674 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {675 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;676 let task = task.take().ok_or(Error::<T>::NotFound)?;677 Agenda::<T>::append(new_time, Some(task));678679 Ok(())680 })?;681682 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;683 Self::deposit_event(RawEvent::Canceled(when, index));684 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));685686 *lookup = Some((new_time, new_index));687688 Ok((new_time, new_index))689 },690 )691 }692}693694impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>695 for Module<T>696{697 type Address = TaskAddress<T::BlockNumber>;698699 fn schedule(700 when: DispatchTime<T::BlockNumber>,701 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,702 priority: schedule::Priority,703 origin: T::PalletsOrigin,704 call: <T as Config>::Call,705 ) -> Result<Self::Address, DispatchError> {706 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)707 }708709 fn cancel((when, index): Self::Address) -> Result<(), ()> {710 Self::do_cancel(None, (when, index)).map_err(|_| ())711 }712713 fn reschedule(714 address: Self::Address,715 when: DispatchTime<T::BlockNumber>,716 ) -> Result<Self::Address, DispatchError> {717 Self::do_reschedule(address, when)718 }719720 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {721 Agenda::<T>::get(when)722 .get(index as usize)723 .ok_or(())724 .map(|_| when)725 }726}727728impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>729 for Module<T>730{731 type Address = TaskAddress<T::BlockNumber>;732733 fn schedule_named(734 id: Vec<u8>,735 when: DispatchTime<T::BlockNumber>,736 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,737 priority: schedule::Priority,738 origin: T::PalletsOrigin,739 call: <T as Config>::Call,740 ) -> Result<Self::Address, ()> {741 Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())742 }743744 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {745 Self::do_cancel_named(None, id).map_err(|_| ())746 }747748 fn reschedule_named(749 id: Vec<u8>,750 when: DispatchTime<T::BlockNumber>,751 ) -> Result<Self::Address, DispatchError> {752 Self::do_reschedule_named(id, when)753 }754755 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {756 Lookup::<T>::get(id)757 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))758 .ok_or(())759 }760}761762#[cfg(test)]763#[allow(clippy::from_over_into)]764mod tests {765 use super::*;766767 use frame_support::{768 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,769 };770 use sp_core::H256;771 use sp_runtime::{772 Perbill,773 testing::Header,774 traits::{BlakeTwo256, IdentityLookup},775 };776 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};777 use crate as scheduler;778779 mod logger {780 use super::*;781 use std::cell::RefCell;782783 thread_local! {784 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());785 }786 pub trait Config: system::Config {787 type Event: From<Event> + Into<<Self as system::Config>::Event>;788 }789 decl_event! {790 pub enum Event {791 Logged(u32, Weight),792 }793 }794 decl_module! {795 pub struct Module<T: Config> for enum Call796 where797 origin: <T as system::Config>::Origin,798 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>799 {800 fn deposit_event() = default;801802 #[weight = *weight]803 fn log(origin, i: u32, weight: Weight) {804 Self::deposit_event(Event::Logged(i, weight));805 LOG.with(|log| {806 log.borrow_mut().push((origin.caller().clone(), i));807 })808 }809810 #[weight = *weight]811 fn log_without_filter(origin, i: u32, weight: Weight) {812 Self::deposit_event(Event::Logged(i, weight));813 LOG.with(|log| {814 log.borrow_mut().push((origin.caller().clone(), i));815 })816 }817 }818 }819 }820821 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;822 type Block = frame_system::mocking::MockBlock<Test>;823824 frame_support::construct_runtime!(825 pub enum Test where826 Block = Block,827 NodeBlock = Block,828 UncheckedExtrinsic = UncheckedExtrinsic,829 {830 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},831 Logger: logger::{Pallet, Call, Event},832 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},833 }834 );835836 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.837 pub struct BaseFilter;838 impl Contains<Call> for BaseFilter {839 fn contains(call: &Call) -> bool {840 !matches!(call, Call::Logger(logger::Call::log { .. }))841 }842 }843844 parameter_types! {845 pub const BlockHashCount: u64 = 250;846 pub BlockWeights: frame_system::limits::BlockWeights =847 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);848 }849 impl system::Config for Test {850 type BaseCallFilter = BaseFilter;851 type BlockWeights = ();852 type BlockLength = ();853 type DbWeight = RocksDbWeight;854 type Origin = Origin;855 type Call = Call;856 type Index = u64;857 type BlockNumber = u64;858 type Hash = H256;859 type Hashing = BlakeTwo256;860 type AccountId = u64;861 type Lookup = IdentityLookup<Self::AccountId>;862 type Header = Header;863 type Event = Event;864 type BlockHashCount = BlockHashCount;865 type Version = ();866 type PalletInfo = PalletInfo;867 type AccountData = ();868 type OnNewAccount = ();869 type OnKilledAccount = ();870 type SystemWeightInfo = ();871 type SS58Prefix = ();872 type OnSetCode = ();873 }874 impl logger::Config for Test {875 type Event = Event;876 }877 parameter_types! {878 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;879 pub const MaxScheduledPerBlock: u32 = 10;880 }881 ord_parameter_types! {882 pub const One: u64 = 1;883 }884885 impl Config for Test {886 type Event = Event;887 type Origin = Origin;888 type PalletsOrigin = OriginCaller;889 type Call = Call;890 type MaximumWeight = MaximumSchedulerWeight;891 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;892 type MaxScheduledPerBlock = MaxScheduledPerBlock;893 type WeightInfo = ();894 type SponsorshipHandler = ();895 type PaymentHandler = ();896 }897}runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -54,6 +54,7 @@
WeightToFeePolynomial, WeightToFeeCoefficient, WeightToFeeCoefficients,
},
};
+use pallet_unq_scheduler::ApplyExtrinsic;
use up_data_structs::*;
// use pallet_contracts::weights::WeightInfo;
// #[cfg(any(feature = "std", test))]
@@ -822,9 +823,24 @@
type MaximumWeight = MaximumSchedulerWeight;
type ScheduleOrigin = EnsureSigned<AccountId>;
type MaxScheduledPerBlock = MaxScheduledPerBlock;
- type SponsorshipHandler = SponsorshipHandler;
type WeightInfo = ();
- type PaymentHandler = pallet_charge_transaction::ChargeTransactionPayment<Runtime>;
+ type Executor = Ex;
+}
+
+// pub fn sign(xt: CheckedExtrinsic) -> UncheckedExtrinsic {
+// node_testing::keyring::sign(xt, SPEC_VERSION, TRANSACTION_VERSION, GENESIS_HASH)
+// }
+
+struct Ex;
+impl<C: Dispatchable> ApplyExtrinsic<C> for Ex {
+ fn apply_extrinsic(signer: Address, function: C) -> ApplyExtrinsicResult {
+ let extrinsic = sign(fp_self_contained::CheckedExtrinsic {
+ signed: fp_self_contained::CheckedSignature::SelfContained(None),
+ function: function,
+ });
+
+ Executive::apply_extrinsic(extrinsic)
+ }
}
impl pallet_evm_transaction_payment::Config for Runtime {