123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#![cfg_attr(not(feature = "std"), no_std)]5253#[cfg(feature = "runtime-benchmarks")]54mod benchmarking;55#[cfg(test)]56mod mock;57#[cfg(test)]58mod tests;59pub mod weights;6061use codec::{Codec, Decode, Encode};62use frame_support::{63 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},64 traits::{65 schedule::{self, DispatchTime, MaybeHashed}, NamedReservableCurrency,66 EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp, StorageVersion,67 },68 weights::{GetDispatchInfo, Weight},69};70use frame_system::{self as system, ensure_signed};71pub use pallet::*;72use scale_info::TypeInfo;73use sp_runtime::{74 traits::{BadOrigin, One, Saturating, Zero},75 RuntimeDebug,76 DispatchErrorWithPostInfo,77};78use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};79use sp_core::H160;80pub use weights::WeightInfo;818283pub type PeriodicIndex = u32;8485pub type TaskAddress<BlockNumber> = (BlockNumber, u32);86pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;8788type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];89pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;909192#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]93#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]94pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {95 96 maybe_id: Option<ScheduledId>,97 98 priority: schedule::Priority,99 100 call: Call,101 102 maybe_periodic: Option<schedule::Period<BlockNumber>>,103 104 origin: PalletsOrigin,105 _phantom: PhantomData<AccountId>,106}107108pub type ScheduledV3Of<T> = ScheduledV3<109 CallOrHashOf<T>,110 <T as frame_system::Config>::BlockNumber,111 <T as Config>::PalletsOrigin,112 <T as frame_system::Config>::AccountId,113>;114115pub type ScheduledOf<T> = ScheduledV3Of<T>;116117118pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =119 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;120121#[cfg(feature = "runtime-benchmarks")]122mod preimage_provider {123 use frame_support::traits::PreimageRecipient;124 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}125 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}126}127128#[cfg(not(feature = "runtime-benchmarks"))]129mod preimage_provider {130 use frame_support::traits::PreimageProvider;131 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}132 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}133}134135pub use preimage_provider::PreimageProviderAndMaybeRecipient;136137pub(crate) trait MarginalWeightInfo: WeightInfo {138 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {139 match (periodic, named, resolved) {140 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),141 (_, true, None) =>142 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1),143 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),144 (false, true, Some(false)) =>145 Self::on_initialize_named(2) - Self::on_initialize_named(1),146 (true, false, Some(false)) =>147 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1),148 (true, true, Some(false)) =>149 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1),150 (false, false, Some(true)) =>151 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1),152 (false, true, Some(true)) =>153 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1),154 (true, false, Some(true)) =>155 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1),156 (true, true, Some(true)) =>157 Self::on_initialize_periodic_named_resolved(2) -158 Self::on_initialize_periodic_named_resolved(1),159 }160 }161}162impl<T: WeightInfo> MarginalWeightInfo for T {}163164#[frame_support::pallet]165pub mod pallet {166 use super::*;167 use frame_support::{168 dispatch::PostDispatchInfo,169 pallet_prelude::*,170 traits::{schedule::LookupError, PreimageProvider},171 };172 use frame_system::pallet_prelude::*;173174 175 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);176177 #[pallet::pallet]178 #[pallet::generate_store(pub(super) trait Store)]179 #[pallet::storage_version(STORAGE_VERSION)]180 #[pallet::without_storage_info]181 pub struct Pallet<T>(_);182183 184 #[pallet::config]185 pub trait Config: frame_system::Config {186 187 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;188189 190 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>191 + From<Self::PalletsOrigin>192 + IsType<<Self as system::Config>::Origin>;193194 195 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;196197 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;198199 200 type Call: Parameter201 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>202 + GetDispatchInfo203 + From<system::Call<Self>>;204205 206 207 #[pallet::constant]208 type MaximumWeight: Get<Weight>;209210 211 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;212213 214 215 216 217 218 219 220 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;221222 223 224 #[pallet::constant]225 type MaxScheduledPerBlock: Get<u32>;226227 228 type WeightInfo: WeightInfo;229230 231 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;232233 234 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;235236 237 238239 240 type CallExecutor: DispatchCall<Self, H160>; 241 }242243 244 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {245246 fn reserve_balance(247 id: ScheduledId,248 sponsor: <T as frame_system::Config>::AccountId,249 call: <T as Config>::Call,250 count: u32,251 ) -> Result<(), DispatchError>;252253 fn pay_for_call(254 id: ScheduledId,255 sponsor: <T as frame_system::Config>::AccountId,256 call: <T as Config>::Call,257 ) -> Result<u128, DispatchError>;258259 260 fn dispatch_call(261 signer: T::AccountId,262 function: <T as Config>::Call,263 ) -> Result<264 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,265 TransactionValidityError,266 >;267268 fn cancel_reserve(269 id: ScheduledId,270 sponsor: <T as frame_system::Config>::AccountId,271 ) -> Result<u128, DispatchError>;272 }273274 275 #[pallet::storage]276 pub type Agenda<T: Config> =277 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;278279 280 #[pallet::storage]281 pub(crate) type Lookup<T: Config> =282 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;283284 285 #[pallet::event]286 #[pallet::generate_deposit(pub(super) fn deposit_event)]287 pub enum Event<T: Config> {288 289 Scheduled { when: T::BlockNumber, index: u32 },290 291 Canceled { when: T::BlockNumber, index: u32 },292 293 Dispatched {294 task: TaskAddress<T::BlockNumber>,295 id: Option<ScheduledId>,296 result: DispatchResult,297 },298 299 CallLookupFailed {300 task: TaskAddress<T::BlockNumber>,301 id: Option<ScheduledId>,302 error: LookupError,303 },304 }305306 #[pallet::error]307 pub enum Error<T> {308 309 FailedToSchedule,310 311 NotFound,312 313 TargetBlockNumberInPast,314 315 RescheduleNoChange,316 }317318 #[pallet::hooks]319 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {320 321 fn on_initialize(now: T::BlockNumber) -> Weight {322 let limit = T::MaximumWeight::get();323324 let mut queued = Agenda::<T>::take(now)325 .into_iter()326 .enumerate()327 .filter_map(|(index, s)| Some((index as u32, s?)))328 .collect::<Vec<_>>();329330 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {331 log::warn!(332 target: "runtime::scheduler",333 "Warning: This block has more items queued in Scheduler than \334 expected from the runtime configuration. An update might be needed."335 );336 }337338 queued.sort_by_key(|(_, s)| s.priority);339340 let next = now + One::one();341342 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);343 for (order, (index, mut s)) in queued.into_iter().enumerate() {344 let named = if let Some(ref id) = s.maybe_id {345 Lookup::<T>::remove(id);346 true347 } else {348 false349 };350351 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();352 s.call = call;353354 let resolved = if let Some(completed) = maybe_completed {355 T::PreimageProvider::unrequest_preimage(&completed);356 true357 } else {358 false359 };360361 let call = match s.call.as_value().cloned() {362 Some(c) => c,363 None => {364 365 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));366 if let Some(delay) = T::NoPreimagePostponement::get() {367 let until = now.saturating_add(delay);368 if let Some(ref id) = s.maybe_id {369 let index = Agenda::<T>::decode_len(until).unwrap_or(0);370 Lookup::<T>::insert(id, (until, index as u32));371 }372 Agenda::<T>::append(until, Some(s));373 }374 continue375 },376 };377378 let periodic = s.maybe_periodic.is_some();379 let call_weight = call.get_dispatch_info().weight;380 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));381 let origin =382 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())383 .into();384 if ensure_signed(origin).is_ok() {385 386 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));387 }388389 390 391 392 393 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;394 let test_weight =395 total_weight.saturating_add(call_weight).saturating_add(item_weight);396 if !hard_deadline && order > 0 && test_weight > limit {397 398 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));399 if let Some(ref id) = s.maybe_id {400 401 402 403 404 let index = Agenda::<T>::decode_len(next).unwrap_or(0);405 Lookup::<T>::insert(id, (next, index as u32));406 }407 Agenda::<T>::append(next, Some(s));408 continue409 }410411 let sender = ensure_signed(412 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone()).into(),413 ).unwrap();414415 416 if s.maybe_id.is_some() && s.maybe_periodic.is_some()417 {418 let _ = T::CallExecutor::pay_for_call(419 s.maybe_id.unwrap(),420 sender.clone(),421 call.clone(),422 );423 } 424425 let r = T::CallExecutor::dispatch_call(sender, call.clone());426427 let mut actual_call_weight: Weight = item_weight; 428 let result: Result<_, DispatchError> = match r {429 Ok(o) => { match o {430 Ok(di) => {431 actual_call_weight = di.actual_weight.unwrap_or(item_weight);432 Ok(())433 },434 Err(err) => Err(err.error),435 }},436 Err(_) => { 437 log::info!(438 target: "runtime::scheduler",439 "Warning: Scheduler has failed to execute a post-dispatch transaction. \440 This block might have become invalid.");441 Err(DispatchError::CannotLookup)442 }443 444 }; 445446 total_weight.saturating_accrue(item_weight);447 total_weight.saturating_accrue(actual_call_weight);448449 Self::deposit_event(Event::Dispatched {450 task: (now, index),451 id: s.maybe_id.clone(),452 result,453 });454455 if let &Some((period, count)) = &s.maybe_periodic {456 if count > 1 {457 s.maybe_periodic = Some((period, count - 1));458 } else {459 s.maybe_periodic = None;460 }461 let wake = now + period;462 463 if let Some(ref id) = s.maybe_id {464 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);465 Lookup::<T>::insert(id, (wake, wake_index as u32));466 }467 Agenda::<T>::append(wake, Some(s));468 }469 }470 total_weight471 }472 }473474 #[pallet::call]475 impl<T: Config> Pallet<T> {476 477 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]478 pub fn schedule(479 origin: OriginFor<T>,480 when: T::BlockNumber,481 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,482 priority: schedule::Priority,483 call: Box<CallOrHashOf<T>>,484 ) -> DispatchResult {485 T::ScheduleOrigin::ensure_origin(origin.clone())?;486 let origin = <T as Config>::Origin::from(origin);487 Self::do_schedule(488 DispatchTime::At(when),489 maybe_periodic,490 priority,491 origin.caller().clone(),492 *call,493 )?;494 Ok(())495 }496497 498 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]499 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {500 T::ScheduleOrigin::ensure_origin(origin.clone())?;501 let origin = <T as Config>::Origin::from(origin);502 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;503 Ok(())504 }505506 507 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]508 pub fn schedule_named(509 origin: OriginFor<T>,510 id: ScheduledId,511 when: T::BlockNumber,512 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,513 priority: schedule::Priority,514 call: Box<CallOrHashOf<T>>,515 ) -> DispatchResult {516 T::ScheduleOrigin::ensure_origin(origin.clone())?;517 let origin = <T as Config>::Origin::from(origin);518 Self::do_schedule_named(519 id,520 DispatchTime::At(when),521 maybe_periodic,522 priority,523 origin.caller().clone(),524 *call,525 )?;526 Ok(())527 }528529 530 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]531 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {532 T::ScheduleOrigin::ensure_origin(origin.clone())?;533 let origin = <T as Config>::Origin::from(origin);534 Self::do_cancel_named(Some(origin.caller().clone()), id)?;535 Ok(())536 }537538 539 540 541 542 543 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]544 pub fn schedule_after(545 origin: OriginFor<T>,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(554 DispatchTime::After(after),555 maybe_periodic,556 priority,557 origin.caller().clone(),558 *call,559 )?;560 Ok(())561 }562563 564 565 566 567 568 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]569 pub fn schedule_named_after(570 origin: OriginFor<T>,571 id: ScheduledId,572 after: T::BlockNumber,573 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,574 priority: schedule::Priority,575 call: Box<CallOrHashOf<T>>,576 ) -> DispatchResult {577 T::ScheduleOrigin::ensure_origin(origin.clone())?;578 let origin = <T as Config>::Origin::from(origin);579 Self::do_schedule_named(580 id,581 DispatchTime::After(after),582 maybe_periodic,583 priority,584 origin.caller().clone(),585 *call,586 )?;587 Ok(())588 }589 }590}591592impl<T: Config> Pallet<T> {593594 #[cfg(feature = "try-runtime")]595 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {596 Ok(())597 }598599 #[cfg(feature = "try-runtime")]600 pub fn post_migrate_to_v3() -> Result<(), &'static str> {601 use frame_support::dispatch::GetStorageVersion;602603 assert!(Self::current_storage_version() == 3);604 for k in Agenda::<T>::iter_keys() {605 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;606 }607 Ok(())608 }609610 611 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {612 Agenda::<T>::translate::<613 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,614 _,615 >(|_, agenda| {616 Some(617 agenda618 .into_iter()619 .map(|schedule| {620 schedule.map(|schedule| Scheduled {621 maybe_id: schedule.maybe_id,622 priority: schedule.priority,623 call: schedule.call,624 maybe_periodic: schedule.maybe_periodic,625 origin: schedule.origin.into(),626 _phantom: Default::default(),627 })628 })629 .collect::<Vec<_>>(),630 )631 });632 }633634 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {635 let now = frame_system::Pallet::<T>::block_number();636637 let when = match when {638 DispatchTime::At(x) => x,639 640 641 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),642 };643644 if when <= now {645 return Err(Error::<T>::TargetBlockNumberInPast.into())646 }647648 Ok(when)649 }650651 fn do_schedule(652 when: DispatchTime<T::BlockNumber>,653 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,654 priority: schedule::Priority,655 origin: T::PalletsOrigin,656 call: CallOrHashOf<T>,657 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {658 let when = Self::resolve_time(when)?;659 call.ensure_requested::<T::PreimageProvider>();660661 662 let maybe_periodic = maybe_periodic663 .filter(|p| p.1 > 1 && !p.0.is_zero())664 665 .map(|(p, c)| (p, c - 1));666 let s = Some(Scheduled {667 maybe_id: None,668 priority,669 call,670 maybe_periodic,671 origin,672 _phantom: PhantomData::<T::AccountId>::default(),673 });674 Agenda::<T>::append(when, s);675 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;676 Self::deposit_event(Event::Scheduled { when, index });677678 Ok((when, index))679 }680681 fn do_cancel(682 origin: Option<T::PalletsOrigin>,683 (when, index): TaskAddress<T::BlockNumber>,684 ) -> Result<(), DispatchError> {685 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {686 agenda.get_mut(index as usize).map_or(687 Ok(None),688 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {689 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {690 if matches!(691 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),692 Some(Ordering::Less) | None693 ) {694 return Err(BadOrigin.into())695 }696 };697 Ok(s.take())698 },699 )700 })?;701 if let Some(s) = scheduled {702 s.call.ensure_unrequested::<T::PreimageProvider>();703 if let Some(id) = s.maybe_id {704 Lookup::<T>::remove(id);705 }706 Self::deposit_event(Event::Canceled { when, index });707 Ok(())708 } else {709 Err(Error::<T>::NotFound)?710 }711 }712713 fn do_reschedule(714 (when, index): TaskAddress<T::BlockNumber>,715 new_time: DispatchTime<T::BlockNumber>,716 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {717 let new_time = Self::resolve_time(new_time)?;718719 if new_time == when {720 return Err(Error::<T>::RescheduleNoChange.into())721 }722723 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {724 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;725 let task = task.take().ok_or(Error::<T>::NotFound)?;726 Agenda::<T>::append(new_time, Some(task));727 Ok(())728 })?;729730 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;731 Self::deposit_event(Event::Canceled { when, index });732 Self::deposit_event(Event::Scheduled { when: new_time, index: new_index });733734 Ok((new_time, new_index))735 }736737 fn do_schedule_named(738 id: ScheduledId,739 when: DispatchTime<T::BlockNumber>,740 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,741 priority: schedule::Priority,742 origin: T::PalletsOrigin,743 call: CallOrHashOf<T>,744 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {745 746 if Lookup::<T>::contains_key(&id) {747 return Err(Error::<T>::FailedToSchedule)?748 }749750 let when = Self::resolve_time(when)?;751752 call.ensure_requested::<T::PreimageProvider>();753754 755 let maybe_periodic = maybe_periodic756 .filter(|p| p.1 > 1 && !p.0.is_zero())757 758 .map(|(p, c)| (p, c - 1));759760 let s = Scheduled {761 maybe_id: Some(id.clone()),762 priority,763 call: call.clone(),764 maybe_periodic,765 origin: origin.clone(),766 _phantom: Default::default(),767 };768769 770 let sender = ensure_signed(771 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into(),772 )?;773 let repeats = match maybe_periodic {774 Some(p) => p.1,775 None => 0,776 };777 let _ = T::CallExecutor::reserve_balance(id.clone(), sender, call.as_value().unwrap().clone(), repeats); 778779 Agenda::<T>::append(when, Some(s));780 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;781 let address = (when, index);782 Lookup::<T>::insert(&id, &address);783 Self::deposit_event(Event::Scheduled { when, index });784785 Ok(address)786 }787788 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {789 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {790 if let Some((when, index)) = lookup.take() {791 let i = index as usize;792 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {793 if let Some(s) = agenda.get_mut(i) {794 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {795 if matches!(796 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),797 Some(Ordering::Less) | None798 ) {799 return Err(BadOrigin.into())800 }801 802 let sender = ensure_signed(803 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.unwrap()).into(),804 )?;805 let _ = T::CallExecutor::cancel_reserve(id, sender);806807 s.call.ensure_unrequested::<T::PreimageProvider>();808 }809 *s = None;810 }811 Ok(())812 })?;813814 Self::deposit_event(Event::Canceled { when, index });815 Ok(())816 } else {817 Err(Error::<T>::NotFound)?818 }819 })820 }821822 fn do_reschedule_named(823 id: ScheduledId,824 new_time: DispatchTime<T::BlockNumber>,825 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {826 let new_time = Self::resolve_time(new_time)?;827828 Lookup::<T>::try_mutate_exists(829 id,830 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {831 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;832833 if new_time == when {834 return Err(Error::<T>::RescheduleNoChange.into())835 }836837 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {838 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;839 let task = task.take().ok_or(Error::<T>::NotFound)?;840 Agenda::<T>::append(new_time, Some(task));841842 Ok(())843 })?;844845 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;846 Self::deposit_event(Event::Canceled { when, index });847 Self::deposit_event(Event::Scheduled { when: new_time, index: new_index });848849 *lookup = Some((new_time, new_index));850851 Ok((new_time, new_index))852 },853 )854 }855}856857impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>858 for Pallet<T>859{860 type Address = TaskAddress<T::BlockNumber>;861 type Hash = T::Hash;862863 fn schedule(864 when: DispatchTime<T::BlockNumber>,865 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,866 priority: schedule::Priority,867 origin: T::PalletsOrigin,868 call: CallOrHashOf<T>,869 ) -> Result<Self::Address, DispatchError> {870 Self::do_schedule(when, maybe_periodic, priority, origin, call)871 }872873 fn cancel((when, index): Self::Address) -> Result<(), ()> {874 Self::do_cancel(None, (when, index)).map_err(|_| ())875 }876877 fn reschedule(878 address: Self::Address,879 when: DispatchTime<T::BlockNumber>,880 ) -> Result<Self::Address, DispatchError> {881 Self::do_reschedule(address, when)882 }883884 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {885 Agenda::<T>::get(when).get(index as usize).ok_or(()).map(|_| when)886 }887}888889impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>890 for Pallet<T>891{892 type Address = TaskAddress<T::BlockNumber>;893 type Hash = T::Hash;894895 fn schedule_named(896 id: Vec<u8>,897 when: DispatchTime<T::BlockNumber>,898 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,899 priority: schedule::Priority,900 origin: T::PalletsOrigin,901 call: CallOrHashOf<T>,902 ) -> Result<Self::Address, ()> {903 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);904 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call).map_err(|_| ())905 }906907 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {908 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);909 Self::do_cancel_named(None, inner_id).map_err(|_| ())910 }911912 fn reschedule_named(913 id: Vec<u8>,914 when: DispatchTime<T::BlockNumber>,915 ) -> Result<Self::Address, DispatchError> {916 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);917 Self::do_reschedule_named(inner_id, when)918 }919920 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {921 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);922 Lookup::<T>::get(inner_id)923 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))924 .ok_or(())925 }926}