difftreelog
Scheduler sponsoring balance reserve
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, cmp};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63 transaction_validity::TransactionValidityError,64 DispatchErrorWithPostInfo,65};66use frame_support::{67 decl_module, decl_storage, decl_event, decl_error,68 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},69 traits::{70 Get,71 schedule::{self, DispatchTime},72 OriginTrait, EnsureOrigin, IsType,73 },74 weights::{GetDispatchInfo, Weight, PostDispatchInfo},75};76use frame_system::{self as system, ensure_signed};77pub use weights::WeightInfo;78use up_sponsorship::SponsorshipHandler;79use scale_info::TypeInfo;80use sp_core::H160;8182/// Our pallet's configuration trait. All our types and constants go in here. If the83/// pallet is dependent on specific other pallets, then their configuration traits84/// should be added to our implied traits list.85///86/// `system::Config` should always be included in our implied traits.87/// //88pub trait Config: system::Config {89 /// The overarching event type.90 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;9192 /// The aggregated origin which the dispatch will take.93 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>94 + From<Self::PalletsOrigin>95 + IsType<<Self as system::Config>::Origin>;9697 /// The caller origin, overarching type of all pallets origins.98 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;99100 /// The aggregated call type.101 type Call: Parameter102 + Dispatchable<Origin = <Self as Config>::Origin>103 + GetDispatchInfo104 + From<system::Call<Self>>;105106 /// The maximum weight that may be scheduled per block for any dispatchables of less priority107 /// than `schedule::HARD_DEADLINE`.108 type MaximumWeight: Get<Weight>;109110 /// Required origin to schedule or cancel calls.111 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;112113 /// The maximum number of scheduled calls in the queue for a single block.114 /// Not strictly enforced, but used for weight estimation.115 type MaxScheduledPerBlock: Get<u32>;116117 /// Sponsoring function.118 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;119120 /// Weight information for extrinsics in this pallet.121 type WeightInfo: WeightInfo;122123 /// The helper type used for custom transaction fee logic.124 type CallExecutor: DispatchCall<Self, H160>;125}126127/// A Scheduler-Runtime interface for finer payment handling.128pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {129 /// The type that encodes information that can be passed from pre_dispatch to post-dispatch.130 type Pre: Default + Codec + Clone + TypeInfo;131132 /// Resolve the call dispatch, including any post-dispatch operations.133 fn dispatch_call(134 pre_dispatch: Self::Pre,135 function: <T as Config>::Call,136 ) -> Result<137 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,138 TransactionValidityError,139 >;140141 /// Prepare for the scheduled call (e.g. by withdrawing the fee in advance).142 fn pre_dispatch(143 signer: T::AccountId,144 function: <T as Config>::Call,145 ) -> Result<Self::Pre, TransactionValidityError>;146147 /// Perform a clean-up after a cancelled call (e.g. by returning the remaining fee).148 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;149}150151pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;152153pub const PERIODIC_CALLS_LIMIT: u32 = 100;154155// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;156157/// Just a simple index for naming period tasks.158pub type PeriodicIndex = u32;159/// The location of a scheduled task that can be used to remove it.160pub type TaskAddress<BlockNumber> = (BlockNumber, u32);161162/// Information regarding an item to be executed in the future.163#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]164#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]165pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {166 /// The unique identity for this task, if there is one.167 maybe_id: Option<Vec<u8>>,168 /// This task's priority.169 priority: schedule::Priority,170 /// The call to be dispatched.171 call: Call,172 /// If the call is periodic, then this points to the information concerning that.173 maybe_periodic: Option<schedule::Period<BlockNumber>>,174 /// The origin to dispatch the call.175 origin: PalletsOrigin,176 /// The information regarding the call's preparation for dispatch, in particular the fee, to be sent to post-dispatch.177 pre_dispatch: PreDispatch,178 _phantom: PhantomData<AccountId>,179}180181#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]182pub struct CallSpec {183 module: u32,184 method: u32,185}186187decl_storage! {188 trait Store for Module<T: Config> as Scheduler {189 /// Items to be executed, indexed by the block number that they should be executed on.190 pub Agenda: map hasher(twox_64_concat) T::BlockNumber191 => Vec<Option<Scheduled<192 <T as Config>::Call,193 T::BlockNumber,194 T::PalletsOrigin,195 T::AccountId,196 <<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre197 >>>;198 199 /// Lookup from identity to the block number and index of the task.200 Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;201 }202}203204decl_event!(205 pub enum Event<T> where <T as system::Config>::BlockNumber {206 /// Scheduled some task. \[when, index\]207 Scheduled(BlockNumber, u32),208 /// Canceled some task. \[when, index\]209 Canceled(BlockNumber, u32),210 /// Dispatched some task. \[task, id, result\]211 Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),212 }213);214215decl_error! {216 pub enum Error for Module<T: Config> {217 /// Failed to schedule a call218 FailedToSchedule,219 /// Cannot find the scheduled call.220 NotFound,221 /// Given target block number is in the past.222 TargetBlockNumberInPast,223 /// Reschedule failed because it does not change scheduled time.224 RescheduleNoChange,225 }226}227228decl_module! {229 /// Scheduler module declaration.230 pub struct Module<T: Config> for enum Call231 where232 origin: <T as system::Config>::Origin233 {234 type Error = Error<T>;235 fn deposit_event() = default;236237 /// Anonymously schedule a task.238 ///239 /// # <weight>240 /// - S = Number of already scheduled calls241 /// - Base Weight: 22.29 + .126 * S µs242 /// - DB Weight:243 /// - Read: Agenda244 /// - Write: Agenda245 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls246 /// # </weight>247 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]248 fn schedule(origin,249 when: T::BlockNumber,250 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,251 priority: schedule::Priority,252 call: Box<<T as Config>::Call>,253 )254 {255 let origin = <T as Config>::Origin::from(origin);256 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;257 }258259 /// Cancel an anonymously scheduled task.260 ///261 /// # <weight>262 /// - S = Number of already scheduled calls263 /// - Base Weight: 22.15 + 2.869 * S µs264 /// - DB Weight:265 /// - Read: Agenda266 /// - Write: Agenda, Lookup267 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls268 /// # </weight>269 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]270 fn cancel(origin, when: T::BlockNumber, index: u32) {271 T::ScheduleOrigin::ensure_origin(origin.clone())?;272 let origin = <T as Config>::Origin::from(origin);273 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;274 }275276 /// Schedule a named task.277 ///278 /// # <weight>279 /// - S = Number of already scheduled calls280 /// - Base Weight: 29.6 + .159 * S µs281 /// - DB Weight:282 /// - Read: Agenda, Lookup283 /// - Write: Agenda, Lookup284 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls285 /// # </weight>286 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]287 fn schedule_named(origin,288 id: Vec<u8>,289 when: T::BlockNumber,290 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,291 priority: schedule::Priority,292 call: Box<<T as Config>::Call>,293 ) {294 T::ScheduleOrigin::ensure_origin(origin.clone())?;295 let origin = <T as Config>::Origin::from(origin);296 Self::do_schedule_named(297 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call298 )?;299 }300301 /// Cancel a named scheduled task.302 ///303 /// # <weight>304 /// - S = Number of already scheduled calls305 /// - Base Weight: 24.91 + 2.907 * S µs306 /// - DB Weight:307 /// - Read: Agenda, Lookup308 /// - Write: Agenda, Lookup309 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls310 /// # </weight>311 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]312 fn cancel_named(origin, id: Vec<u8>) {313 T::ScheduleOrigin::ensure_origin(origin.clone())?;314 let origin = <T as Config>::Origin::from(origin);315 Self::do_cancel_named(Some(origin.caller().clone()), id)?;316 }317318 /// Anonymously schedule a task after a delay.319 ///320 /// # <weight>321 /// Same as [`schedule`].322 /// # </weight>323 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]324 fn schedule_after(origin,325 after: T::BlockNumber,326 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,327 priority: schedule::Priority,328 call: Box<<T as Config>::Call>,329 ) {330 T::ScheduleOrigin::ensure_origin(origin.clone())?;331 let origin = <T as Config>::Origin::from(origin);332 Self::do_schedule_nameless(333 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call334 )?;335 }336337 /// Schedule a named task after a delay.338 ///339 /// # <weight>340 /// Same as [`schedule_named`].341 /// # </weight>342 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]343 fn schedule_named_after(origin,344 id: Vec<u8>,345 after: T::BlockNumber,346 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,347 priority: schedule::Priority,348 call: Box<<T as Config>::Call>,349 ) {350 T::ScheduleOrigin::ensure_origin(origin.clone())?;351 let origin = <T as Config>::Origin::from(origin);352 Self::do_schedule_named(353 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call354 )?;355 }356357 /// Execute the scheduled calls358 ///359 /// # <weight>360 /// - S = Number of already scheduled calls361 /// - N = Named scheduled calls362 /// - P = Periodic Calls363 /// - Base Weight: 9.243 + 23.45 * S µs364 /// - DB Weight:365 /// - Read: Agenda + Lookup * N + Agenda(Future) * P366 /// - Write: Agenda + Lookup * N + Agenda(future) * P367 /// # </weight>368 fn on_initialize(now: T::BlockNumber) -> Weight {369 let limit = T::MaximumWeight::get();370 let mut queued = Agenda::<T>::take(now)371 .into_iter()372 .enumerate()373 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))374 .collect::<Vec<_>>();375 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {376 log::warn!(377 target: "runtime::scheduler",378 "Warning: This block has more items queued in Scheduler than \379 expected from the runtime configuration. An update might be needed."380 );381 }382 queued.sort_by_key(|(_, s)| s.priority);383 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)384 let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)385 queued.into_iter()386 .enumerate()387 .scan(base_weight, |cumulative_weight, (order, (index, s))| {388 *cumulative_weight = cumulative_weight389 .saturating_add(s.call.get_dispatch_info().weight);390391 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(392 s.origin.clone()393 ).into();394395 if ensure_signed(origin).is_ok() {396 // AccountData for inner call origin accountdata.397 *cumulative_weight = cumulative_weight398 .saturating_add(T::DbWeight::get().reads_writes(1, 1));399 }400401 if s.maybe_id.is_some() {402 // Remove/Modify Lookup403 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));404 }405 if s.maybe_periodic.is_some() {406 // Read/Write Agenda for future block407 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));408 }409410 Some((order, index, *cumulative_weight, s))411 })412 .filter_map(|(order, index, cumulative_weight, mut s)| {413 // We allow a scheduled call if:414 // - It's priority is `HARD_DEADLINE`415 // - It does not push the weight past the limit416 // or, alternatively,417 // - It is the first item in the schedule418 if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {419 let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());420421 if let Err(_) = r {422 log::warn!(423 target: "runtime::scheduler",424 "Warning: Scheduler has failed to execute a post-dispatch transaction. \425 This block might have become invalid.",426 );427 // todo possibly force a skip/return here, do something with the error428 }429430 let r = r.unwrap(); // todo dangerous! but it shouldn't come to that, and if it does, the error is critical, is it safe to panic?431432 let maybe_id = s.maybe_id.clone();433 if let Some((period, count)) = s.maybe_periodic {434 if count > 1 {435 s.maybe_periodic = Some((period, count - 1));436 } else {437 s.maybe_periodic = None;438 }439 let next = now + period;440 // If scheduled is named, place it's information in `Lookup`441 if let Some(ref id) = s.maybe_id {442 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);443 Lookup::<T>::insert(id, (next, next_index as u32));444 }445 Agenda::<T>::append(next, Some(s));446 } else if let Some(ref id) = s.maybe_id {447 Lookup::<T>::remove(id);448 }449 Self::deposit_event(RawEvent::Dispatched(450 (now, index),451 maybe_id,452 r.map(|_| ()).map_err(|e| e.error)453 ));454 total_weight = cumulative_weight;455 None456 } else {457 Some(Some(s))458 }459 })460 .for_each(|unused| {461 let next = now + One::one();462 Agenda::<T>::append(next, unused);463 });464465 total_weight466 }467 }468}469470impl<T: Config> Module<T> {471 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {472 let now = frame_system::Pallet::<T>::block_number();473474 let when = match when {475 DispatchTime::At(x) => x,476 // The current block has already completed it's scheduled tasks, so477 // Schedule the task at lest one block after this current block.478 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),479 };480481 if when <= now {482 return Err(Error::<T>::TargetBlockNumberInPast.into());483 }484485 Ok(when)486 }487488 fn do_schedule(489 maybe_id: Option<Vec<u8>>,490 when: DispatchTime<T::BlockNumber>,491 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,492 priority: schedule::Priority,493 origin: T::PalletsOrigin,494 call: <T as Config>::Call,495 ) -> Result<(T::BlockNumber, u32), DispatchError> {496 let when = Self::resolve_time(when)?;497498 let sender = ensure_signed(499 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),500 )501 .unwrap_or_default(); // todo sponsoring doesn't work with the line below -- found sponsoring is already checked for in transaction_payment502 //let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);503 //let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay.clone()));504 //let r = call.clone().dispatch(sponsor.into());505506 let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {507 Ok(pre_dispatch) => pre_dispatch,508 Err(_) => return Err(Error::<T>::FailedToSchedule.into()),509 };510511 // todo continually pre-dispatch according to maybe_periodic -- but it's called only once?512 // no, reschedule and cancel rely on scheduled being only the next instance513 // actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee514515 // sanitize maybe_periodic516 let maybe_periodic = maybe_periodic517 .filter(|p| p.1 > 1 && !p.0.is_zero())518 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.519 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));520521 if let Some(periodic) = maybe_periodic {522 for _i in 0..=periodic.1 {523 // displace to runtime and count the total required fee, then deduct. find a way to use OnChargePayment524 // send constants and priority to runtime for fee computation, too. should create constants here or just declare them in runtime?525 // roadblock - they will return on post_dispatch -- oh! tips?526 }527 }528529 let s = Some(Scheduled {530 maybe_id,531 priority,532 call,533 maybe_periodic,534 origin,535 pre_dispatch,536 _phantom: PhantomData::<T::AccountId>::default(),537 });538 Agenda::<T>::append(when, s);539 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;540 if index > T::MaxScheduledPerBlock::get() {541 log::warn!(542 target: "runtime::scheduler",543 "Warning: There are more items queued in the Scheduler than \544 expected from the runtime configuration. An update might be needed.",545 );546 }547548 Ok((when, index))549 }550551 fn do_schedule_nameless(552 when: DispatchTime<T::BlockNumber>,553 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,554 priority: schedule::Priority,555 origin: T::PalletsOrigin,556 call: <T as Config>::Call,557 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {558 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;559 let (when, index) = address;560561 Self::deposit_event(RawEvent::Scheduled(when, index));562563 Ok(address)564 }565566 fn do_cancel(567 origin: Option<T::PalletsOrigin>,568 (when, index): TaskAddress<T::BlockNumber>,569 ) -> Result<(), DispatchError> {570 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {571 agenda.get_mut(index as usize).map_or(572 Ok(None),573 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {574 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {575 if *o != s.origin {576 return Err(BadOrigin.into());577 }578 };579 Ok(s.take())580 },581 )582 })?;583 if let Some(s) = scheduled {584 if let Some(id) = s.maybe_id {585 Lookup::<T>::remove(id);586 }587 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {588 log::warn!(589 target: "runtime::scheduler",590 "Warning: Scheduler has failed to execute a post-dispatch transaction. \591 This block might have become invalid.",592 );593 } // maybe do something with the error?594 Self::deposit_event(RawEvent::Canceled(when, index));595 Ok(())596 } else {597 Err(Error::<T>::NotFound.into())598 }599 }600601 fn do_reschedule(602 (when, index): TaskAddress<T::BlockNumber>,603 new_time: DispatchTime<T::BlockNumber>,604 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {605 let new_time = Self::resolve_time(new_time)?;606607 if new_time == when {608 return Err(Error::<T>::RescheduleNoChange.into());609 }610611 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {612 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;613 let task = task.take().ok_or(Error::<T>::NotFound)?;614 Agenda::<T>::append(new_time, Some(task));615 Ok(())616 })?;617618 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;619 Self::deposit_event(RawEvent::Canceled(when, index));620 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));621622 Ok((new_time, new_index))623 }624625 fn do_schedule_named(626 id: Vec<u8>,627 when: DispatchTime<T::BlockNumber>,628 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,629 priority: schedule::Priority,630 origin: T::PalletsOrigin,631 call: <T as Config>::Call,632 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {633 // ensure id length does not exceed expectations & is unique634 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()635 || Lookup::<T>::contains_key(&id)636 {637 return Err(Error::<T>::FailedToSchedule.into());638 }639640 let address = Self::do_schedule(641 Some(id.clone()),642 when,643 maybe_periodic,644 priority,645 origin,646 call,647 )?;648 let (when, index) = address;649650 Lookup::<T>::insert(&id, &address);651 Self::deposit_event(RawEvent::Scheduled(when, index));652 Ok(address)653 }654655 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {656 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {657 if let Some((when, index)) = lookup.take() {658 let i = index as usize;659 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {660 if let Some(s) = agenda.get_mut(i) {661 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {662 if *o != s.origin {663 return Err(BadOrigin.into());664 }665 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())666 {667 log::warn!(668 target: "runtime::scheduler",669 "Warning: Scheduler has failed to execute a post-dispatch transaction. \670 This block might have become invalid.",671 );672 } // maybe do something with the error?673 }674 *s = None;675 }676 Ok(())677 })?;678 Self::deposit_event(RawEvent::Canceled(when, index));679 Ok(())680 } else {681 Err(Error::<T>::NotFound.into())682 }683 })684 }685686 fn do_reschedule_named(687 id: Vec<u8>,688 new_time: DispatchTime<T::BlockNumber>,689 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {690 let new_time = Self::resolve_time(new_time)?;691692 Lookup::<T>::try_mutate_exists(693 id,694 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {695 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;696697 if new_time == when {698 return Err(Error::<T>::RescheduleNoChange.into());699 }700701 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {702 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;703 let task = task.take().ok_or(Error::<T>::NotFound)?;704 Agenda::<T>::append(new_time, Some(task));705706 Ok(())707 })?;708709 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;710 Self::deposit_event(RawEvent::Canceled(when, index));711 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));712713 *lookup = Some((new_time, new_index));714715 Ok((new_time, new_index))716 },717 )718 }719}720721impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>722 for Module<T>723{724 type Address = TaskAddress<T::BlockNumber>;725726 fn schedule(727 when: DispatchTime<T::BlockNumber>,728 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,729 priority: schedule::Priority,730 origin: T::PalletsOrigin,731 call: <T as Config>::Call,732 ) -> Result<Self::Address, DispatchError> {733 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)734 }735736 fn cancel((when, index): Self::Address) -> Result<(), ()> {737 Self::do_cancel(None, (when, index)).map_err(|_| ())738 }739740 fn reschedule(741 address: Self::Address,742 when: DispatchTime<T::BlockNumber>,743 ) -> Result<Self::Address, DispatchError> {744 Self::do_reschedule(address, when)745 }746747 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {748 Agenda::<T>::get(when)749 .get(index as usize)750 .ok_or(())751 .map(|_| when)752 }753}754755impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>756 for Module<T>757{758 type Address = TaskAddress<T::BlockNumber>;759760 fn schedule_named(761 id: Vec<u8>,762 when: DispatchTime<T::BlockNumber>,763 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,764 priority: schedule::Priority,765 origin: T::PalletsOrigin,766 call: <T as Config>::Call,767 ) -> Result<Self::Address, ()> {768 Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())769 }770771 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {772 Self::do_cancel_named(None, id).map_err(|_| ())773 }774775 fn reschedule_named(776 id: Vec<u8>,777 when: DispatchTime<T::BlockNumber>,778 ) -> Result<Self::Address, DispatchError> {779 Self::do_reschedule_named(id, when)780 }781782 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {783 Lookup::<T>::get(id)784 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))785 .ok_or(())786 }787}788789#[cfg(test)]790#[allow(clippy::from_over_into)]791mod tests {792 use super::*;793794 use frame_support::{795 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,796 };797 use sp_core::H256;798 use sp_runtime::{799 Perbill,800 testing::Header,801 traits::{BlakeTwo256, IdentityLookup},802 };803 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};804 use crate as scheduler;805806 mod logger {807 use super::*;808 use std::cell::RefCell;809810 thread_local! {811 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());812 }813 pub trait Config: system::Config {814 type Event: From<Event> + Into<<Self as system::Config>::Event>;815 }816 decl_event! {817 pub enum Event {818 Logged(u32, Weight),819 }820 }821 decl_module! {822 pub struct Module<T: Config> for enum Call823 where824 origin: <T as system::Config>::Origin,825 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>826 {827 fn deposit_event() = default;828829 #[weight = *weight]830 fn log(origin, i: u32, weight: Weight) {831 Self::deposit_event(Event::Logged(i, weight));832 LOG.with(|log| {833 log.borrow_mut().push((origin.caller().clone(), i));834 })835 }836837 #[weight = *weight]838 fn log_without_filter(origin, i: u32, weight: Weight) {839 Self::deposit_event(Event::Logged(i, weight));840 LOG.with(|log| {841 log.borrow_mut().push((origin.caller().clone(), i));842 })843 }844 }845 }846 }847848 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;849 type Block = frame_system::mocking::MockBlock<Test>;850851 frame_support::construct_runtime!(852 pub enum Test where853 Block = Block,854 NodeBlock = Block,855 UncheckedExtrinsic = UncheckedExtrinsic,856 {857 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},858 Logger: logger::{Pallet, Call, Event},859 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},860 }861 );862863 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.864 pub struct BaseFilter;865 impl Contains<Call> for BaseFilter {866 fn contains(call: &Call) -> bool {867 !matches!(call, Call::Logger(logger::Call::log { .. }))868 }869 }870871 pub struct DummyExecutor;872 impl<T: frame_system::Config + Config, SelfContainedSignedInfo>873 DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor874 {875 type Pre = ();876877 fn dispatch_call(878 _pre: Self::Pre,879 _call: <T as Config>::Call,880 ) -> Result<881 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,882 TransactionValidityError,883 > {884 todo!()885 }886887 fn pre_dispatch(888 _signer: <T as frame_system::Config>::AccountId,889 _call: <T as Config>::Call,890 ) -> Result<Self::Pre, TransactionValidityError> {891 todo!()892 }893894 fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {895 todo!()896 }897 }898899 parameter_types! {900 pub const BlockHashCount: u64 = 250;901 pub BlockWeights: frame_system::limits::BlockWeights =902 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);903 }904 impl system::Config for Test {905 type BaseCallFilter = BaseFilter;906 type BlockWeights = ();907 type BlockLength = ();908 type DbWeight = RocksDbWeight;909 type Origin = Origin;910 type Call = Call;911 type Index = u64;912 type BlockNumber = u64;913 type Hash = H256;914 type Hashing = BlakeTwo256;915 type AccountId = u64;916 type Lookup = IdentityLookup<Self::AccountId>;917 type Header = Header;918 type Event = Event;919 type BlockHashCount = BlockHashCount;920 type Version = ();921 type PalletInfo = PalletInfo;922 type AccountData = ();923 type OnNewAccount = ();924 type OnKilledAccount = ();925 type SystemWeightInfo = ();926 type SS58Prefix = ();927 type OnSetCode = ();928 }929 impl logger::Config for Test {930 type Event = Event;931 }932 parameter_types! {933 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;934 pub const MaxScheduledPerBlock: u32 = 10;935 }936 ord_parameter_types! {937 pub const One: u64 = 1;938 }939940 impl Config for Test {941 type Event = Event;942 type Origin = Origin;943 type PalletsOrigin = OriginCaller;944 type Call = Call;945 type MaximumWeight = MaximumSchedulerWeight;946 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;947 type MaxScheduledPerBlock = MaxScheduledPerBlock;948 type SponsorshipHandler = ();949 type WeightInfo = ();950 type CallExecutor = DummyExecutor;951 }952}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, cmp};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63 transaction_validity::TransactionValidityError,64 DispatchErrorWithPostInfo,65};66use frame_support::{67 decl_module, decl_storage, decl_event, decl_error,68 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},69 traits::{70 Get,71 schedule::{self, DispatchTime},72 OriginTrait, EnsureOrigin, IsType,73 },74 weights::{GetDispatchInfo, Weight, PostDispatchInfo},75};76use frame_system::{self as system, ensure_signed};77pub use weights::WeightInfo;78use up_sponsorship::SponsorshipHandler;79use scale_info::TypeInfo;80use sp_core::H160;81use frame_support::traits::NamedReservableCurrency;8283type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];8485/// Our pallet's configuration trait. All our types and constants go in here. If the86/// pallet is dependent on specific other pallets, then their configuration traits87/// should be added to our implied traits list.88///89/// `system::Config` should always be included in our implied traits.90/// //91pub trait Config: system::Config {92 /// The overarching event type.93 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;9495 /// The aggregated origin which the dispatch will take.96 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>97 + From<Self::PalletsOrigin>98 + IsType<<Self as system::Config>::Origin>;99100 /// The caller origin, overarching type of all pallets origins.101 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;102103 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;104105 /// The aggregated call type.106 type Call: Parameter107 + Dispatchable<Origin = <Self as Config>::Origin>108 + GetDispatchInfo109 + From<system::Call<Self>>;110111 /// The maximum weight that may be scheduled per block for any dispatchables of less priority112 /// than `schedule::HARD_DEADLINE`.113 type MaximumWeight: Get<Weight>;114115 /// Required origin to schedule or cancel calls.116 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;117118 /// The maximum number of scheduled calls in the queue for a single block.119 /// Not strictly enforced, but used for weight estimation.120 type MaxScheduledPerBlock: Get<u32>;121122 /// Sponsoring function.123 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;124125 /// Weight information for extrinsics in this pallet.126 type WeightInfo: WeightInfo;127128 /// The helper type used for custom transaction fee logic.129 type CallExecutor: DispatchCall<Self, H160>;130}131132/// A Scheduler-Runtime interface for finer payment handling.133pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {134 /// The type that encodes information that can be passed from pre_dispatch to post-dispatch.135 type Pre: Default + Codec + Clone + TypeInfo;136137 fn reserve_balance(138 id: ScheduledId,139 sponsor: <T as frame_system::Config>::AccountId,140 call: <T as Config>::Call,141 count: u32,142 ) -> Result<(), DispatchError>;143144 fn pay_for_call(145 id: ScheduledId,146 sponsor: <T as frame_system::Config>::AccountId,147 call: <T as Config>::Call,148 ) -> Result<u128, DispatchError>;149150 /// Resolve the call dispatch, including any post-dispatch operations.151 fn dispatch_call(152 pre_dispatch: Self::Pre,153 function: <T as Config>::Call,154 ) -> Result<155 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,156 TransactionValidityError,157 >;158159 /// Prepare for the scheduled call (e.g. by withdrawing the fee in advance).160 fn pre_dispatch(161 signer: T::AccountId,162 function: <T as Config>::Call,163 ) -> Result<Self::Pre, TransactionValidityError>;164165 /// Perform a clean-up after a cancelled call (e.g. by returning the remaining fee).166 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;167}168169pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;170171pub const PERIODIC_CALLS_LIMIT: u32 = 100;172173// pub type SelfWeightInfo<T> = <T as system::Config>::WeightInfo;174175/// Just a simple index for naming period tasks.176pub type PeriodicIndex = u32;177/// The location of a scheduled task that can be used to remove it.178pub type TaskAddress<BlockNumber> = (BlockNumber, u32);179180/// Information regarding an item to be executed in the future.181#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]182#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]183pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {184 /// The unique identity for this task, if there is one.185 maybe_id: Option<ScheduledId>,186 /// This task's priority.187 priority: schedule::Priority,188 /// The call to be dispatched.189 call: Call,190 /// If the call is periodic, then this points to the information concerning that.191 maybe_periodic: Option<schedule::Period<BlockNumber>>,192 /// The origin to dispatch the call.193 origin: PalletsOrigin,194 /// The information regarding the call's preparation for dispatch, in particular the fee, to be sent to post-dispatch.195 pre_dispatch: PreDispatch,196 _phantom: PhantomData<AccountId>,197}198199#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]200pub struct CallSpec {201 module: u32,202 method: u32,203}204205decl_storage! {206 trait Store for Module<T: Config> as Scheduler {207 /// Items to be executed, indexed by the block number that they should be executed on.208 pub Agenda: map hasher(twox_64_concat) T::BlockNumber209 => Vec<Option<Scheduled<210 <T as Config>::Call,211 T::BlockNumber,212 T::PalletsOrigin,213 T::AccountId,214 <<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre215 >>>;216 217 /// Lookup from identity to the block number and index of the task.218 Lookup: map hasher(twox_64_concat) ScheduledId => Option<TaskAddress<T::BlockNumber>>;219 }220}221222decl_event!(223 pub enum Event<T> where <T as system::Config>::BlockNumber {224 /// Scheduled some task. \[when, index\]225 Scheduled(BlockNumber, u32),226 /// Canceled some task. \[when, index\]227 Canceled(BlockNumber, u32),228 /// Dispatched some task. \[task, id, result\]229 Dispatched(TaskAddress<BlockNumber>, Option<ScheduledId>, DispatchResult),230 }231);232233decl_error! {234 pub enum Error for Module<T: Config> {235 /// Failed to schedule a call236 FailedToSchedule,237 /// Cannot find the scheduled call.238 NotFound,239 /// Given target block number is in the past.240 TargetBlockNumberInPast,241 /// Reschedule failed because it does not change scheduled time.242 RescheduleNoChange,243 }244}245246decl_module! {247 /// Scheduler module declaration.248 pub struct Module<T: Config> for enum Call249 where250 origin: <T as system::Config>::Origin251 {252 type Error = Error<T>;253 fn deposit_event() = default;254255 /// Anonymously schedule a task.256 ///257 /// # <weight>258 /// - S = Number of already scheduled calls259 /// - Base Weight: 22.29 + .126 * S µs260 /// - DB Weight:261 /// - Read: Agenda262 /// - Write: Agenda263 /// - Will use base weight of 25 which should be good for up to 30 scheduled calls264 /// # </weight>265 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]266 fn schedule(origin,267 when: T::BlockNumber,268 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,269 priority: schedule::Priority,270 call: Box<<T as Config>::Call>,271 )272 {273 let origin = <T as Config>::Origin::from(origin);274 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;275 }276277 /// Cancel an anonymously scheduled task.278 ///279 /// # <weight>280 /// - S = Number of already scheduled calls281 /// - Base Weight: 22.15 + 2.869 * S µs282 /// - DB Weight:283 /// - Read: Agenda284 /// - Write: Agenda, Lookup285 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls286 /// # </weight>287 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]288 fn cancel(origin, when: T::BlockNumber, index: u32) {289 T::ScheduleOrigin::ensure_origin(origin.clone())?;290 let origin = <T as Config>::Origin::from(origin);291 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;292 }293294 /// Schedule a named task.295 ///296 /// # <weight>297 /// - S = Number of already scheduled calls298 /// - Base Weight: 29.6 + .159 * S µs299 /// - DB Weight:300 /// - Read: Agenda, Lookup301 /// - Write: Agenda, Lookup302 /// - Will use base weight of 35 which should be good for more than 30 scheduled calls303 /// # </weight>304 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]305 fn schedule_named(origin,306 id: ScheduledId,307 when: T::BlockNumber,308 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,309 priority: schedule::Priority,310 call: Box<<T as Config>::Call>,311 ) {312 T::ScheduleOrigin::ensure_origin(origin.clone())?;313 let origin = <T as Config>::Origin::from(origin);314 Self::do_schedule_named(315 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call316 )?;317 }318319 /// Cancel a named scheduled task.320 ///321 /// # <weight>322 /// - S = Number of already scheduled calls323 /// - Base Weight: 24.91 + 2.907 * S µs324 /// - DB Weight:325 /// - Read: Agenda, Lookup326 /// - Write: Agenda, Lookup327 /// - Will use base weight of 100 which should be good for up to 30 scheduled calls328 /// # </weight>329 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]330 fn cancel_named(origin, id: ScheduledId) {331 T::ScheduleOrigin::ensure_origin(origin.clone())?;332 let origin = <T as Config>::Origin::from(origin);333 Self::do_cancel_named(Some(origin.caller().clone()), id)?;334 }335336 /// Anonymously schedule a task after a delay.337 ///338 /// # <weight>339 /// Same as [`schedule`].340 /// # </weight>341 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]342 fn schedule_after(origin,343 after: T::BlockNumber,344 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,345 priority: schedule::Priority,346 call: Box<<T as Config>::Call>,347 ) {348 T::ScheduleOrigin::ensure_origin(origin.clone())?;349 let origin = <T as Config>::Origin::from(origin);350 Self::do_schedule_nameless(351 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call352 )?;353 }354355 /// Schedule a named task after a delay.356 ///357 /// # <weight>358 /// Same as [`schedule_named`].359 /// # </weight>360 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]361 fn schedule_named_after(origin,362 id: ScheduledId,363 after: T::BlockNumber,364 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,365 priority: schedule::Priority,366 call: Box<<T as Config>::Call>,367 ) {368 T::ScheduleOrigin::ensure_origin(origin.clone())?;369 let origin = <T as Config>::Origin::from(origin);370 Self::do_schedule_named(371 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call372 )?;373 }374375 /// Execute the scheduled calls376 ///377 /// # <weight>378 /// - S = Number of already scheduled calls379 /// - N = Named scheduled calls380 /// - P = Periodic Calls381 /// - Base Weight: 9.243 + 23.45 * S µs382 /// - DB Weight:383 /// - Read: Agenda + Lookup * N + Agenda(Future) * P384 /// - Write: Agenda + Lookup * N + Agenda(future) * P385 /// # </weight>386 fn on_initialize(now: T::BlockNumber) -> Weight {387 let limit = T::MaximumWeight::get();388 let mut queued = Agenda::<T>::take(now)389 .into_iter()390 .enumerate()391 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))392 .collect::<Vec<_>>();393 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {394 log::warn!(395 target: "runtime::scheduler",396 "Warning: This block has more items queued in Scheduler than \397 expected from the runtime configuration. An update might be needed."398 );399 }400 queued.sort_by_key(|(_, s)| s.priority);401 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)402 let mut total_weight: Weight = 0; // T::WeightInfo::on_initialize(0)403 queued.into_iter()404 .enumerate()405 .scan(base_weight, |cumulative_weight, (order, (index, s))| {406 *cumulative_weight = cumulative_weight407 .saturating_add(s.call.get_dispatch_info().weight);408409 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(410 s.origin.clone()411 ).into();412413 if ensure_signed(origin).is_ok() {414 // AccountData for inner call origin accountdata.415 *cumulative_weight = cumulative_weight416 .saturating_add(T::DbWeight::get().reads_writes(1, 1));417 }418419 if s.maybe_id.is_some() {420 // Remove/Modify Lookup421 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));422 }423 if s.maybe_periodic.is_some() {424 // Read/Write Agenda for future block425 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));426 }427428 Some((order, index, *cumulative_weight, s))429 })430 .filter_map(|(order, index, cumulative_weight, mut s)| {431432 // if call have id and periodic, it was be reserved 433 if s.maybe_id.is_some() && s.maybe_periodic.is_some()434 {435 let sender = ensure_signed(436 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone()).into(),437 )438 .unwrap_or_default();439 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call.clone())440 .unwrap_or(sender.clone());441442 T::CallExecutor::pay_for_call(443 s.maybe_id.unwrap(),444 who_will_pay.clone(),445 s.call.clone(),446 );447 }448449 // We allow a scheduled call if:450 // - It's priority is `HARD_DEADLINE`451 // - It does not push the weight past the limit452 // or, alternatively,453 // - It is the first item in the schedule454 if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {455 let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());456457 if let Err(_) = r {458 log::info!(459 target: "runtime::scheduler",460 "Warning: Scheduler has failed to execute a post-dispatch transaction. \461 This block might have become invalid.",462 );463 // todo possibly force a skip/return here, do something with the error464 }465466 let r = r.unwrap(); // todo dangerous! but it shouldn't come to that, and if it does, the error is critical, is it safe to panic?467468 let maybe_id = s.maybe_id.clone();469 if let Some((period, count)) = s.maybe_periodic {470 if count > 1 {471 s.maybe_periodic = Some((period, count - 1));472 } else {473 s.maybe_periodic = None;474 }475 let next = now + period;476 // If scheduled is named, place it's information in `Lookup`477 if let Some(ref id) = s.maybe_id {478 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);479 Lookup::<T>::insert(id, (next, next_index as u32));480 }481 Agenda::<T>::append(next, Some(s));482 } else if let Some(ref id) = s.maybe_id {483 Lookup::<T>::remove(id);484 }485 Self::deposit_event(RawEvent::Dispatched(486 (now, index),487 maybe_id,488 r.map(|_| ()).map_err(|e| e.error)489 ));490 total_weight = cumulative_weight;491 None492 } else {493 Some(Some(s))494 }495 })496 .for_each(|unused| {497 let next = now + One::one();498 Agenda::<T>::append(next, unused);499 });500501 total_weight502 }503 }504}505506impl<T: Config> Module<T> {507 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {508 let now = frame_system::Pallet::<T>::block_number();509510 let when = match when {511 DispatchTime::At(x) => x,512 // The current block has already completed it's scheduled tasks, so513 // Schedule the task at lest one block after this current block.514 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),515 };516517 if when <= now {518 return Err(Error::<T>::TargetBlockNumberInPast.into());519 }520521 Ok(when)522 }523524 fn do_schedule(525 maybe_id: Option<ScheduledId>,526 when: DispatchTime<T::BlockNumber>,527 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,528 priority: schedule::Priority,529 origin: T::PalletsOrigin,530 call: <T as Config>::Call,531 ) -> Result<(T::BlockNumber, u32), DispatchError> {532 let when = Self::resolve_time(when)?;533534 let sender = ensure_signed(535 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),536 )537 .unwrap_or_default(); // todo sponsoring doesn't work with the line below -- found sponsoring is already checked for in transaction_payment538 //let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call).unwrap_or(sender);539 //let sponsor = T::PalletsOrigin::from(system::RawOrigin::Signed(who_will_pay.clone()));540 //let r = call.clone().dispatch(sponsor.into());541542 let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {543 Ok(pre_dispatch) => pre_dispatch,544 Err(_) => return Err(Error::<T>::FailedToSchedule.into()),545 };546547 // todo continually pre-dispatch according to maybe_periodic -- but it's called only once?548 // no, reschedule and cancel rely on scheduled being only the next instance549 // actually can count with OnChargePayment, so no need to run around. expand Pre with unspent_total_fee and single_fee, deduct single_fee550551 // sanitize maybe_periodic552 let maybe_periodic = maybe_periodic553 .filter(|p| p.1 > 1 && !p.0.is_zero())554 // Limit the repetitions to 100 calls and remove one from the number of repetitions since we will schedule one now.555 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));556557 if let Some(periodic) = maybe_periodic {558559 // reserve balance for periodic execution 560 if maybe_id.is_some()561 { 562 let sender = ensure_signed(563 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),564 )565 .unwrap_or_default();566 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call.clone())567 .unwrap_or(sender.clone());568 T::CallExecutor::reserve_balance(maybe_id.unwrap(), who_will_pay.clone(), call.clone(), periodic.1); 569 }570571 //for _i in 0..=periodic.1 {572 // displace to runtime and count the total required fee, then deduct. find a way to use OnChargePayment573 // send constants and priority to runtime for fee computation, too. should create constants here or just declare them in runtime?574 // roadblock - they will return on post_dispatch -- oh! tips?575 //}576 }577578 let s = Some(Scheduled {579 maybe_id,580 priority,581 call,582 maybe_periodic,583 origin,584 pre_dispatch,585 _phantom: PhantomData::<T::AccountId>::default(),586 });587 Agenda::<T>::append(when, s);588 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;589 if index > T::MaxScheduledPerBlock::get() {590 log::warn!(591 target: "runtime::scheduler",592 "Warning: There are more items queued in the Scheduler than \593 expected from the runtime configuration. An update might be needed.",594 );595 }596597 Ok((when, index))598 }599600 fn do_schedule_nameless(601 when: DispatchTime<T::BlockNumber>,602 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,603 priority: schedule::Priority,604 origin: T::PalletsOrigin,605 call: <T as Config>::Call,606 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {607 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;608 let (when, index) = address;609610 Self::deposit_event(RawEvent::Scheduled(when, index));611612 Ok(address)613 }614615 fn do_cancel(616 origin: Option<T::PalletsOrigin>,617 (when, index): TaskAddress<T::BlockNumber>,618 ) -> Result<(), DispatchError> {619 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {620 agenda.get_mut(index as usize).map_or(621 Ok(None),622 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {623 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {624 if *o != s.origin {625 return Err(BadOrigin.into());626 }627 };628 Ok(s.take())629 },630 )631 })?;632 if let Some(s) = scheduled {633 if let Some(id) = s.maybe_id {634 Lookup::<T>::remove(id);635 }636 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {637 log::warn!(638 target: "runtime::scheduler",639 "Warning: Scheduler has failed to execute a post-dispatch transaction. \640 This block might have become invalid.",641 );642 } // maybe do something with the error?643 Self::deposit_event(RawEvent::Canceled(when, index));644 Ok(())645 } else {646 Err(Error::<T>::NotFound.into())647 }648 }649650 fn do_reschedule(651 (when, index): TaskAddress<T::BlockNumber>,652 new_time: DispatchTime<T::BlockNumber>,653 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {654 let new_time = Self::resolve_time(new_time)?;655656 if new_time == when {657 return Err(Error::<T>::RescheduleNoChange.into());658 }659660 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {661 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;662 let task = task.take().ok_or(Error::<T>::NotFound)?;663 Agenda::<T>::append(new_time, Some(task));664 Ok(())665 })?;666667 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;668 Self::deposit_event(RawEvent::Canceled(when, index));669 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));670671 Ok((new_time, new_index))672 }673674 fn do_schedule_named(675 id: ScheduledId,676 when: DispatchTime<T::BlockNumber>,677 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,678 priority: schedule::Priority,679 origin: T::PalletsOrigin,680 call: <T as Config>::Call,681 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {682 // ensure id length does not exceed expectations & is unique683 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()684 || Lookup::<T>::contains_key(&id)685 {686 return Err(Error::<T>::FailedToSchedule.into());687 }688689 let address = Self::do_schedule(690 Some(id.clone()),691 when,692 maybe_periodic,693 priority,694 origin,695 call,696 )?;697 let (when, index) = address;698699 Lookup::<T>::insert(&id, &address);700 Self::deposit_event(RawEvent::Scheduled(when, index));701 Ok(address)702 }703704 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {705 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {706 if let Some((when, index)) = lookup.take() {707 let i = index as usize;708 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {709 if let Some(s) = agenda.get_mut(i) {710 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {711 if *o != s.origin {712 return Err(BadOrigin.into());713 }714 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())715 {716 log::warn!(717 target: "runtime::scheduler",718 "Warning: Scheduler has failed to execute a post-dispatch transaction. \719 This block might have become invalid.",720 );721 } // maybe do something with the error?722 }723 *s = None;724 }725 Ok(())726 })?;727 Self::deposit_event(RawEvent::Canceled(when, index));728 Ok(())729 } else {730 Err(Error::<T>::NotFound.into())731 }732 })733 }734735 fn do_reschedule_named(736 id: ScheduledId,737 new_time: DispatchTime<T::BlockNumber>,738 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {739 let new_time = Self::resolve_time(new_time)?;740741 Lookup::<T>::try_mutate_exists(742 id,743 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {744 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;745746 if new_time == when {747 return Err(Error::<T>::RescheduleNoChange.into());748 }749750 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {751 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;752 let task = task.take().ok_or(Error::<T>::NotFound)?;753 Agenda::<T>::append(new_time, Some(task));754755 Ok(())756 })?;757758 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;759 Self::deposit_event(RawEvent::Canceled(when, index));760 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));761762 *lookup = Some((new_time, new_index));763764 Ok((new_time, new_index))765 },766 )767 }768}769770impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>771 for Module<T>772{773 type Address = TaskAddress<T::BlockNumber>;774775 fn schedule(776 when: DispatchTime<T::BlockNumber>,777 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,778 priority: schedule::Priority,779 origin: T::PalletsOrigin,780 call: <T as Config>::Call,781 ) -> Result<Self::Address, DispatchError> {782 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)783 }784785 fn cancel((when, index): Self::Address) -> Result<(), ()> {786 Self::do_cancel(None, (when, index)).map_err(|_| ())787 }788789 fn reschedule(790 address: Self::Address,791 when: DispatchTime<T::BlockNumber>,792 ) -> Result<Self::Address, DispatchError> {793 Self::do_reschedule(address, when)794 }795796 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {797 Agenda::<T>::get(when)798 .get(index as usize)799 .ok_or(())800 .map(|_| when)801 }802}803804impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>805 for Module<T>806{807 type Address = TaskAddress<T::BlockNumber>;808809 fn schedule_named(810 id: Vec<u8>,811 when: DispatchTime<T::BlockNumber>,812 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,813 priority: schedule::Priority,814 origin: T::PalletsOrigin,815 call: <T as Config>::Call,816 ) -> Result<Self::Address, ()> {817818 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);819 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call).map_err(|_| ())820 }821822 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {823 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);824 Self::do_cancel_named(None, inner_id).map_err(|_| ())825 }826827 fn reschedule_named(828 id: Vec<u8>,829 when: DispatchTime<T::BlockNumber>,830 ) -> Result<Self::Address, DispatchError> {831 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);832 Self::do_reschedule_named(inner_id, when)833 }834835 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {836 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);837 Lookup::<T>::get(inner_id)838 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))839 .ok_or(())840 }841}842843#[cfg(test)]844#[allow(clippy::from_over_into)]845mod tests {846 use super::*;847848 use frame_support::{849 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,850 };851 use sp_core::H256;852 use sp_runtime::{853 Perbill,854 testing::Header,855 traits::{BlakeTwo256, IdentityLookup},856 };857 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};858 use crate as scheduler;859860 mod logger {861 use super::*;862 use std::cell::RefCell;863864 thread_local! {865 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());866 }867 pub trait Config: system::Config {868 type Event: From<Event> + Into<<Self as system::Config>::Event>;869 }870 decl_event! {871 pub enum Event {872 Logged(u32, Weight),873 }874 }875 decl_module! {876 pub struct Module<T: Config> for enum Call877 where878 origin: <T as system::Config>::Origin,879 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>880 {881 fn deposit_event() = default;882883 #[weight = *weight]884 fn log(origin, i: u32, weight: Weight) {885 Self::deposit_event(Event::Logged(i, weight));886 LOG.with(|log| {887 log.borrow_mut().push((origin.caller().clone(), i));888 })889 }890891 #[weight = *weight]892 fn log_without_filter(origin, i: u32, weight: Weight) {893 Self::deposit_event(Event::Logged(i, weight));894 LOG.with(|log| {895 log.borrow_mut().push((origin.caller().clone(), i));896 })897 }898 }899 }900 }901902 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;903 type Block = frame_system::mocking::MockBlock<Test>;904905 frame_support::construct_runtime!(906 pub enum Test where907 Block = Block,908 NodeBlock = Block,909 UncheckedExtrinsic = UncheckedExtrinsic,910 {911 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},912 Logger: logger::{Pallet, Call, Event},913 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},914 }915 );916917 // Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.918 pub struct BaseFilter;919 impl Contains<Call> for BaseFilter {920 fn contains(call: &Call) -> bool {921 !matches!(call, Call::Logger(logger::Call::log { .. }))922 }923 }924925 pub struct DummyExecutor;926 impl<T: frame_system::Config + Config, SelfContainedSignedInfo>927 DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor928 {929 type Pre = ();930931 fn dispatch_call(932 _pre: Self::Pre,933 _call: <T as Config>::Call,934 ) -> Result<935 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,936 TransactionValidityError,937 > {938 todo!()939 }940941 fn pre_dispatch(942 _signer: <T as frame_system::Config>::AccountId,943 _call: <T as Config>::Call,944 ) -> Result<Self::Pre, TransactionValidityError> {945 todo!()946 }947948 fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {949 todo!()950 }951 }952953 parameter_types! {954 pub const BlockHashCount: u64 = 250;955 pub BlockWeights: frame_system::limits::BlockWeights =956 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);957 }958 impl system::Config for Test {959 type BaseCallFilter = BaseFilter;960 type BlockWeights = ();961 type BlockLength = ();962 type DbWeight = RocksDbWeight;963 type Origin = Origin;964 type Call = Call;965 type Index = u64;966 type BlockNumber = u64;967 type Hash = H256;968 type Hashing = BlakeTwo256;969 type AccountId = u64;970 type Lookup = IdentityLookup<Self::AccountId>;971 type Header = Header;972 type Event = Event;973 type BlockHashCount = BlockHashCount;974 type Version = ();975 type PalletInfo = PalletInfo;976 type AccountData = ();977 type OnNewAccount = ();978 type OnKilledAccount = ();979 type SystemWeightInfo = ();980 type SS58Prefix = ();981 type OnSetCode = ();982 }983 impl logger::Config for Test {984 type Event = Event;985 }986 parameter_types! {987 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;988 pub const MaxScheduledPerBlock: u32 = 10;989 }990 ord_parameter_types! {991 pub const One: u64 = 1;992 }993994 impl Config for Test {995 type Event = Event;996 type Origin = Origin;997 type PalletsOrigin = OriginCaller;998 type Call = Call;999 type MaximumWeight = MaximumSchedulerWeight;1000 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;1001 type MaxScheduledPerBlock = MaxScheduledPerBlock;1002 type SponsorshipHandler = ();1003 type WeightInfo = ();1004 type CallExecutor = DummyExecutor;1005 }1006}runtime/src/lib.rsdiffbeforeafterboth--- a/runtime/src/lib.rs
+++ b/runtime/src/lib.rs
@@ -393,12 +393,13 @@
// pub const ExistentialDeposit: u128 = 500;
pub const ExistentialDeposit: u128 = 0;
pub const MaxLocks: u32 = 50;
+ pub const MaxReserves: u32 = 50;
}
impl pallet_balances::Config for Runtime {
type MaxLocks = MaxLocks;
- type MaxReserves = ();
- type ReserveIdentifier = [u8; 8];
+ type MaxReserves = MaxReserves;
+ type ReserveIdentifier = [u8; 16];
/// The type for recording an account's balance.
type Balance = Balance;
/// The ubiquitous event type.
@@ -818,6 +819,9 @@
fee: Option<Balance>,
}
+
+use frame_support::traits::NamedReservableCurrency;
+
pub struct SchedulerPaymentExecutor;
impl<T: frame_system::Config + pallet_unq_scheduler::Config, SelfContainedSignedInfo>
DispatchCall<T, SelfContainedSignedInfo> for SchedulerPaymentExecutor
@@ -865,6 +869,54 @@
Ok(res)
}
+ fn reserve_balance(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ count: u32,
+ ) -> Result<(), DispatchError>
+ {
+ let dispatch_info = call.get_dispatch_info();
+ let fee_charger = ChargeTransactionPayment::new(
+ 0
+ );
+ let pre = match fee_charger.pre_dispatch(&sponsor.clone().into(), &call.into(), &dispatch_info, 0) {
+ Ok(p) => p,
+ Err(_) => fail!("failed to get pre dispatch info")
+ };
+
+ let count: u128 = count.into();
+ let total_fee: u128 = pre.2.map(|imbalance| imbalance.peek()).unwrap() * count;
+ <Balances as NamedReservableCurrency<AccountId>>::reserve_named(
+ &id,
+ &(sponsor.into()),
+ total_fee)
+ }
+
+ fn pay_for_call(
+ id: [u8; 16],
+ sponsor: <T as frame_system::Config>::AccountId,
+ call: <T as pallet_unq_scheduler::Config>::Call,
+ )
+ -> Result<u128, DispatchError>
+ {
+ let dispatch_info = call.get_dispatch_info();
+ let fee_charger = ChargeTransactionPayment::new(
+ 0
+ );
+ let pre = match fee_charger.pre_dispatch(&sponsor.clone().into(), &call.into(), &dispatch_info, 0) {
+ Ok(p) => p,
+ Err(_) => fail!("failed to get pre dispatch info")
+ };
+
+ let single_fee: u128 = pre.2.map(|imbalance| imbalance.peek()).unwrap();
+
+ Ok(<Balances as NamedReservableCurrency<AccountId>>::unreserve_named(
+ &id,
+ &(sponsor.into()),
+ single_fee))
+ }
+
fn pre_dispatch(
signer: <T as frame_system::Config>::AccountId,
call: <T as pallet_unq_scheduler::Config>::Call,
@@ -893,6 +945,7 @@
impl pallet_unq_scheduler::Config for Runtime {
type Event = Event;
type Origin = Origin;
+ type Currency = Balances;
type PalletsOrigin = OriginCaller;
type Call = Call;
type MaximumWeight = MaximumSchedulerWeight;