difftreelog
Merge pull request #428 from UniqueNetwork/doc/scheduler
in: master
Doc/scheduler
1 file changed
pallets/scheduler/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617// Original license:18// This file is part of Substrate.1920// Copyright (C) 2017-2022 Parity Technologies (UK) Ltd.21// SPDX-License-Identifier: Apache-2.02223// Licensed under the Apache License, Version 2.0 (the "License");24// you may not use this file except in compliance with the License.25// You may obtain a copy of the License at26//27// http://www.apache.org/licenses/LICENSE-2.028//29// Unless required by applicable law or agreed to in writing, software30// distributed under the License is distributed on an "AS IS" BASIS,31// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.32// See the License for the specific language governing permissions and33// limitations under the License.3435//! # Unique scheduler36//! A Pallet for scheduling dispatches.37//!38//! - [`Config`]39//! - [`Call`]40//! - [`Pallet`]41//!42//! ## Overview43//!44//! This Pallet exposes capabilities for scheduling dispatches to occur at a45//! specified block number or at a specified period. These scheduled dispatches46//! should be named and may be canceled.47//!48//! **NOTE:** The unique scheduler is designed for deferred transaction calls by block number.49//! Any user can book a call of a certain transaction to a specific block number.50//! Also possible to book a call with a certain frequency.51//!52//! Key differences from the original pallet:53//! https://crates.io/crates/pallet-scheduler54//! Schedule Id restricted by 16 bytes. Identificator for booked call.55//! Priority limited by HARD DEADLINE (<= 63). Calls over maximum weight don't include to block.56//! The maximum weight that may be scheduled per block for any dispatchables of less priority than `schedule::HARD_DEADLINE`.57//! Maybe_periodic limit is 100 calls. Reserved for future sponsored transaction support.58//! At 100 calls reserved amount is not so much and this is avoid potential problems with balance locks.59//! Any account allowed to schedule any calls. Account withdraw implemented through default transaction logic.60//!61//! ## Interface62//!63//! ### Dispatchable Functions64//!65//! * `schedule_named` - augments the `schedule` interface with an additional `Vec<u8>` parameter66//! that can be used for identification.67//! * `cancel_named` - the named complement to the cancel function.6869// Ensure we're `no_std` when compiling for Wasm.70#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83 traits::{BadOrigin, One, Saturating, Zero},84 RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{GetDispatchInfo, Weight},96};9798pub use weights::WeightInfo;99100/// Just a simple index for naming period tasks.101pub type PeriodicIndex = u32;102/// The location of a scheduled task that can be used to remove it.103pub type TaskAddress<BlockNumber> = (BlockNumber, u32);104pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;105106type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];107pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;108109/// Information regarding an item to be executed in the future.110#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]111#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]112pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {113 /// The unique identity for this task, if there is one.114 maybe_id: Option<ScheduledId>,115 /// This task's priority.116 priority: schedule::Priority,117 /// The call to be dispatched.118 call: Call,119 /// If the call is periodic, then this points to the information concerning that.120 maybe_periodic: Option<schedule::Period<BlockNumber>>,121 /// The origin to dispatch the call.122 origin: PalletsOrigin,123 _phantom: PhantomData<AccountId>,124}125126pub type ScheduledV3Of<T> = ScheduledV3<127 CallOrHashOf<T>,128 <T as frame_system::Config>::BlockNumber,129 <T as Config>::PalletsOrigin,130 <T as frame_system::Config>::AccountId,131>;132133pub type ScheduledOf<T> = ScheduledV3Of<T>;134135/// The current version of Scheduled struct.136pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =137 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;138139#[cfg(feature = "runtime-benchmarks")]140mod preimage_provider {141 use frame_support::traits::PreimageRecipient;142 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}143 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}144}145146#[cfg(not(feature = "runtime-benchmarks"))]147mod preimage_provider {148 use frame_support::traits::PreimageProvider;149 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}150 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}151}152153pub use preimage_provider::PreimageProviderAndMaybeRecipient;154155pub(crate) trait MarginalWeightInfo: WeightInfo {156 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {157 match (periodic, named, resolved) {158 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),159 (_, true, None) => {160 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)161 }162 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),163 (false, true, Some(false)) => {164 Self::on_initialize_named(2) - Self::on_initialize_named(1)165 }166 (true, false, Some(false)) => {167 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)168 }169 (true, true, Some(false)) => {170 Self::on_initialize_periodic_named_resolved(2)171 - Self::on_initialize_periodic_named_resolved(1)172 }173 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),174 (false, true, Some(true)) => {175 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)176 }177 (true, false, Some(true)) => {178 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)179 }180 (true, true, Some(true)) => {181 Self::on_initialize_periodic_named_resolved(2)182 - Self::on_initialize_periodic_named_resolved(1)183 }184 }185 }186}187impl<T: WeightInfo> MarginalWeightInfo for T {}188189#[frame_support::pallet]190pub mod pallet {191 use super::*;192 use frame_support::{193 dispatch::PostDispatchInfo,194 pallet_prelude::*,195 traits::{schedule::LookupError, PreimageProvider},196 };197 use frame_system::pallet_prelude::*;198199 /// The current storage version.200 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);201202 #[pallet::pallet]203 #[pallet::generate_store(pub(super) trait Store)]204 #[pallet::storage_version(STORAGE_VERSION)]205 #[pallet::without_storage_info]206 pub struct Pallet<T>(_);207208 /// `system::Config` should always be included in our implied traits.209 #[pallet::config]210 pub trait Config: frame_system::Config {211 /// The overarching event type.212 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;213214 /// The aggregated origin which the dispatch will take.215 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>216 + From<Self::PalletsOrigin>217 + IsType<<Self as system::Config>::Origin>;218219 /// The caller origin, overarching type of all pallets origins.220 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;221222 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;223224 /// The aggregated call type.225 type Call: Parameter226 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>227 + GetDispatchInfo228 + From<system::Call<Self>>;229230 /// The maximum weight that may be scheduled per block for any dispatchables of less231 /// priority than `schedule::HARD_DEADLINE`.232 #[pallet::constant]233 type MaximumWeight: Get<Weight>;234235 /// Required origin to schedule or cancel calls.236 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;237238 /// Compare the privileges of origins.239 ///240 /// This will be used when canceling a task, to ensure that the origin that tries241 /// to cancel has greater or equal privileges as the origin that created the scheduled task.242 ///243 /// For simplicity the [`EqualPrivilegeOnly`](frame_support::traits::EqualPrivilegeOnly) can244 /// be used. This will only check if two given origins are equal.245 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;246247 /// The maximum number of scheduled calls in the queue for a single block.248 /// Not strictly enforced, but used for weight estimation.249 #[pallet::constant]250 type MaxScheduledPerBlock: Get<u32>;251252 /// Weight information for extrinsics in this pallet.253 type WeightInfo: WeightInfo;254255 /// The preimage provider with which we look up call hashes to get the call.256 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;257258 /// If `Some` then the number of blocks to postpone execution for when the item is delayed.259 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;260261 /// Sponsoring function.262 // type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;263264 /// The helper type used for custom transaction fee logic.265 type CallExecutor: DispatchCall<Self, H160>;266 }267268 /// A Scheduler-Runtime interface for finer payment handling.269 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {270 fn reserve_balance(271 id: ScheduledId,272 sponsor: <T as frame_system::Config>::AccountId,273 call: <T as Config>::Call,274 count: u32,275 ) -> Result<(), DispatchError>;276277 /// Unlock centain amount from payer278 fn pay_for_call(279 id: ScheduledId,280 sponsor: <T as frame_system::Config>::AccountId,281 call: <T as Config>::Call,282 ) -> Result<u128, DispatchError>;283284 /// Resolve the call dispatch, including any post-dispatch operations.285 fn dispatch_call(286 signer: T::AccountId,287 function: <T as Config>::Call,288 ) -> Result<289 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,290 TransactionValidityError,291 >;292293 fn cancel_reserve(294 id: ScheduledId,295 sponsor: <T as frame_system::Config>::AccountId,296 ) -> Result<u128, DispatchError>;297 }298299 /// Items to be executed, indexed by the block number that they should be executed on.300 #[pallet::storage]301 pub type Agenda<T: Config> =302 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;303304 /// Lookup from identity to the block number and index of the task.305 #[pallet::storage]306 pub(crate) type Lookup<T: Config> =307 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;308309 /// Events type.310 #[pallet::event]311 #[pallet::generate_deposit(pub(super) fn deposit_event)]312 pub enum Event<T: Config> {313 /// Scheduled some task.314 Scheduled { when: T::BlockNumber, index: u32 },315 /// Canceled some task.316 Canceled { when: T::BlockNumber, index: u32 },317 /// Dispatched some task.318 Dispatched {319 task: TaskAddress<T::BlockNumber>,320 id: Option<ScheduledId>,321 result: DispatchResult,322 },323 /// The call for the provided hash was not found so the task has been aborted.324 CallLookupFailed {325 task: TaskAddress<T::BlockNumber>,326 id: Option<ScheduledId>,327 error: LookupError,328 },329 }330331 #[pallet::error]332 pub enum Error<T> {333 /// Failed to schedule a call334 FailedToSchedule,335 /// Cannot find the scheduled call.336 NotFound,337 /// Given target block number is in the past.338 TargetBlockNumberInPast,339 /// Reschedule failed because it does not change scheduled time.340 RescheduleNoChange,341 }342343 #[pallet::hooks]344 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {345 /// Execute the scheduled calls346 fn on_initialize(now: T::BlockNumber) -> Weight {347 let limit = T::MaximumWeight::get();348349 let mut queued = Agenda::<T>::take(now)350 .into_iter()351 .enumerate()352 .filter_map(|(index, s)| Some((index as u32, s?)))353 .collect::<Vec<_>>();354355 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {356 log::warn!(357 target: "runtime::scheduler",358 "Warning: This block has more items queued in Scheduler than \359 expected from the runtime configuration. An update might be needed."360 );361 }362363 queued.sort_by_key(|(_, s)| s.priority);364365 let next = now + One::one();366367 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);368 for (order, (index, mut s)) in queued.into_iter().enumerate() {369 let named = if let Some(ref id) = s.maybe_id {370 Lookup::<T>::remove(id);371 true372 } else {373 false374 };375376 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();377 s.call = call;378379 let resolved = if let Some(completed) = maybe_completed {380 T::PreimageProvider::unrequest_preimage(&completed);381 true382 } else {383 false384 };385 let call = match s.call.as_value().cloned() {386 Some(c) => c,387 None => {388 // Preimage not available - postpone until some block.389 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));390 if let Some(delay) = T::NoPreimagePostponement::get() {391 let until = now.saturating_add(delay);392 if let Some(ref id) = s.maybe_id {393 let index = Agenda::<T>::decode_len(until).unwrap_or(0);394 Lookup::<T>::insert(id, (until, index as u32));395 }396 Agenda::<T>::append(until, Some(s));397 }398 continue;399 }400 };401402 let periodic = s.maybe_periodic.is_some();403 let call_weight = call.get_dispatch_info().weight;404 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));405 let origin =406 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())407 .into();408 if ensure_signed(origin).is_ok() {409 // Weights of Signed dispatches expect their signing account to be whitelisted.410 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));411 }412413 // We allow a scheduled call if any is true:414 // - It's priority is `HARD_DEADLINE`415 // - It does not push the weight past the limit.416 // - It is the first item in the schedule417 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;418 let test_weight = total_weight419 .saturating_add(call_weight)420 .saturating_add(item_weight);421 if !hard_deadline && order > 0 && test_weight > limit {422 // Cannot be scheduled this block - postpone until next.423 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));424 if let Some(ref id) = s.maybe_id {425 // NOTE: We could reasonably not do this (in which case there would be one426 // block where the named and delayed item could not be referenced by name),427 // but we will do it anyway since it should be mostly free in terms of428 // weight and it is slightly cleaner.429 let index = Agenda::<T>::decode_len(next).unwrap_or(0);430 Lookup::<T>::insert(id, (next, index as u32));431 }432 Agenda::<T>::append(next, Some(s));433 continue;434 }435436 let sender = ensure_signed(437 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())438 .into(),439 )440 .unwrap();441442 // // if call have id it was be reserved443 // if s.maybe_id.is_some() {444 // let _ = T::CallExecutor::pay_for_call(445 // s.maybe_id.unwrap(),446 // sender.clone(),447 // call.clone(),448 // );449 // }450451 // Execute transaction via chain default pipeline452 // That means dispatch will be processed like any user's extrinsic e.g. transaction fees will be taken453 let r = T::CallExecutor::dispatch_call(sender, call.clone());454455 let mut actual_call_weight: Weight = item_weight;456 let result: Result<_, DispatchError> = match r {457 Ok(o) => match o {458 Ok(di) => {459 actual_call_weight = di.actual_weight.unwrap_or(item_weight);460 Ok(())461 }462 Err(err) => Err(err.error),463 },464 Err(_) => {465 log::error!(466 target: "runtime::scheduler",467 "Warning: Scheduler has failed to execute a post-dispatch transaction. \468 This block might have become invalid.");469 Err(DispatchError::CannotLookup)470 } // todo possibly force a skip/return here, do something with the error471 };472473 total_weight.saturating_accrue(item_weight);474 total_weight.saturating_accrue(actual_call_weight);475476 Self::deposit_event(Event::Dispatched {477 task: (now, index),478 id: s.maybe_id.clone(),479 result,480 });481482 if let &Some((period, count)) = &s.maybe_periodic {483 if count > 1 {484 s.maybe_periodic = Some((period, count - 1));485 } else {486 s.maybe_periodic = None;487 }488 let wake = now + period;489 // If scheduled is named, place its information in `Lookup`490 if let Some(ref id) = s.maybe_id {491 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);492 Lookup::<T>::insert(id, (wake, wake_index as u32));493 }494 Agenda::<T>::append(wake, Some(s));495 }496 }497 /// Weight should be 0, because transaction already paid498 0499 //total_weight500 }501 }502503 #[pallet::call]504 impl<T: Config> Pallet<T> {505 /// Schedule a named task.506 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]507 pub fn schedule_named(508 origin: OriginFor<T>,509 id: ScheduledId,510 when: T::BlockNumber,511 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,512 priority: schedule::Priority,513 call: Box<CallOrHashOf<T>>,514 ) -> DispatchResult {515 T::ScheduleOrigin::ensure_origin(origin.clone())?;516 let origin = <T as Config>::Origin::from(origin);517 Self::do_schedule_named(518 id,519 DispatchTime::At(when),520 maybe_periodic,521 priority,522 origin.caller().clone(),523 *call,524 )?;525 Ok(())526 }527528 /// Cancel a named scheduled task.529 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]530 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {531 T::ScheduleOrigin::ensure_origin(origin.clone())?;532 let origin = <T as Config>::Origin::from(origin);533 Self::do_cancel_named(Some(origin.caller().clone()), id)?;534 Ok(())535 }536537 /// Schedule a named task after a delay.538 ///539 /// # <weight>540 /// Same as [`schedule_named`](Self::schedule_named).541 /// # </weight>542 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]543 pub fn schedule_named_after(544 origin: OriginFor<T>,545 id: ScheduledId,546 after: T::BlockNumber,547 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,548 priority: schedule::Priority,549 call: Box<CallOrHashOf<T>>,550 ) -> DispatchResult {551 T::ScheduleOrigin::ensure_origin(origin.clone())?;552 let origin = <T as Config>::Origin::from(origin);553 Self::do_schedule_named(554 id,555 DispatchTime::After(after),556 maybe_periodic,557 priority,558 origin.caller().clone(),559 *call,560 )?;561 Ok(())562 }563 }564}565566impl<T: Config> Pallet<T> {567 #[cfg(feature = "try-runtime")]568 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {569 Ok(())570 }571572 #[cfg(feature = "try-runtime")]573 pub fn post_migrate_to_v3() -> Result<(), &'static str> {574 use frame_support::dispatch::GetStorageVersion;575576 assert!(Self::current_storage_version() == 3);577 for k in Agenda::<T>::iter_keys() {578 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;579 }580 Ok(())581 }582583 /// Helper to migrate scheduler when the pallet origin type has changed.584 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {585 Agenda::<T>::translate::<586 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,587 _,588 >(|_, agenda| {589 Some(590 agenda591 .into_iter()592 .map(|schedule| {593 schedule.map(|schedule| Scheduled {594 maybe_id: schedule.maybe_id,595 priority: schedule.priority,596 call: schedule.call,597 maybe_periodic: schedule.maybe_periodic,598 origin: schedule.origin.into(),599 _phantom: Default::default(),600 })601 })602 .collect::<Vec<_>>(),603 )604 });605 }606607 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {608 let now = frame_system::Pallet::<T>::block_number();609610 let when = match when {611 DispatchTime::At(x) => x,612 // The current block has already completed it's scheduled tasks, so613 // Schedule the task at lest one block after this current block.614 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),615 };616617 if when <= now {618 return Err(Error::<T>::TargetBlockNumberInPast.into());619 }620621 Ok(when)622 }623624 fn do_schedule_named(625 id: ScheduledId,626 when: DispatchTime<T::BlockNumber>,627 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,628 priority: schedule::Priority,629 origin: T::PalletsOrigin,630 call: CallOrHashOf<T>,631 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {632 // ensure id it is unique633 if Lookup::<T>::contains_key(&id) {634 return Err(Error::<T>::FailedToSchedule)?;635 }636637 let when = Self::resolve_time(when)?;638639 call.ensure_requested::<T::PreimageProvider>();640641 // sanitize maybe_periodic642 let maybe_periodic = maybe_periodic643 .filter(|p| p.1 > 1 && !p.0.is_zero())644 // Remove one from the number of repetitions since we will schedule one now.645 .map(|(p, c)| (p, c - 1));646647 let s = Scheduled {648 maybe_id: Some(id.clone()),649 priority,650 call: call.clone(),651 maybe_periodic,652 origin: origin.clone(),653 _phantom: Default::default(),654 };655656 // reserve balance for periodic execution657 // let sender =658 // ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;659 // let repeats = match maybe_periodic {660 // Some(p) => p.1,661 // None => 1,662 // };663 // let _ = T::CallExecutor::reserve_balance(664 // id.clone(),665 // sender,666 // call.as_value().unwrap().clone(),667 // repeats,668 // );669670 Agenda::<T>::append(when, Some(s));671 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;672 let address = (when, index);673 Lookup::<T>::insert(&id, &address);674 Self::deposit_event(Event::Scheduled { when, index });675676 Ok(address)677 }678679 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {680 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {681 if let Some((when, index)) = lookup.take() {682 let i = index as usize;683 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {684 if let Some(s) = agenda.get_mut(i) {685 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {686 if matches!(687 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),688 Some(Ordering::Less) | None689 ) {690 return Err(BadOrigin.into());691 }692 // release balance reserve693 // let sender = ensure_signed(694 // <<T as Config>::Origin as From<T::PalletsOrigin>>::from(695 // origin.unwrap(),696 // )697 // .into(),698 // )?;699 // let _ = T::CallExecutor::cancel_reserve(id, sender);700701 s.call.ensure_unrequested::<T::PreimageProvider>();702 }703 *s = None;704 }705 Ok(())706 })?;707708 Self::deposit_event(Event::Canceled { when, index });709 Ok(())710 } else {711 Err(Error::<T>::NotFound)?712 }713 })714 }715}