1#![doc = docify::embed!("src/tests.rs", basic_scheduling_works)]
48#![doc = docify::embed!("src/tests.rs", scheduling_with_preimages_works)]
50
51#![cfg_attr(not(feature = "std"), no_std)]
76
77#[cfg(feature = "runtime-benchmarks")]
78mod benchmarking;
79pub mod migration;
80#[cfg(test)]
81mod mock;
82#[cfg(test)]
83mod tests;
84pub mod weights;
85
86extern crate alloc;
87
88use alloc::{boxed::Box, vec::Vec};
89use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
90use core::{borrow::Borrow, cmp::Ordering, marker::PhantomData};
91use frame_support::{
92 dispatch::{DispatchResult, GetDispatchInfo, Parameter, RawOrigin},
93 ensure,
94 traits::{
95 schedule::{self, DispatchTime, MaybeHashed},
96 Bounded, CallerTrait, EnsureOrigin, Get, IsType, OriginTrait, PalletInfoAccess,
97 PrivilegeCmp, QueryPreimage, StorageVersion, StorePreimage,
98 },
99 weights::{Weight, WeightMeter},
100};
101use frame_system::{self as system};
102use scale_info::TypeInfo;
103use sp_io::hashing::blake2_256;
104use sp_runtime::{
105 traits::{BadOrigin, BlockNumberProvider, Dispatchable, One, Saturating, Zero},
106 BoundedVec, Debug, DispatchError,
107};
108
109pub use pallet::*;
110pub use weights::WeightInfo;
111
112pub type PeriodicIndex = u32;
114pub type TaskAddress<BlockNumber> = (BlockNumber, u32);
116
117pub type CallOrHashOf<T> =
118 MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;
119
120pub type BoundedCallOf<T> =
121 Bounded<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hashing>;
122
123pub type BlockNumberFor<T> =
124 <<T as Config>::BlockNumberProvider as BlockNumberProvider>::BlockNumber;
125
126#[derive(
128 Clone,
129 Copy,
130 Debug,
131 PartialEq,
132 Eq,
133 Encode,
134 Decode,
135 DecodeWithMemTracking,
136 MaxEncodedLen,
137 TypeInfo,
138)]
139pub struct RetryConfig<Period> {
140 pub total_retries: u8,
142 pub remaining: u8,
144 pub period: Period,
146}
147
148#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
149#[derive(Clone, Debug, Encode, Decode)]
150struct ScheduledV1<Call, BlockNumber> {
151 maybe_id: Option<Vec<u8>>,
152 priority: schedule::Priority,
153 call: Call,
154 maybe_periodic: Option<schedule::Period<BlockNumber>>,
155}
156
157#[derive(
159 Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo, DecodeWithMemTracking,
160)]
161pub struct Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId> {
162 pub maybe_id: Option<Name>,
164 pub priority: schedule::Priority,
166 pub call: Call,
168 pub maybe_periodic: Option<schedule::Period<BlockNumber>>,
170 pub origin: PalletsOrigin,
172 #[doc(hidden)]
173 pub _phantom: PhantomData<AccountId>,
174}
175
176impl<Name, Call, BlockNumber, PalletsOrigin, AccountId>
177 Scheduled<Name, Call, BlockNumber, PalletsOrigin, AccountId>
178where
179 Call: Clone,
180 PalletsOrigin: Clone,
181{
182 pub fn as_retry(&self) -> Self {
185 Self {
186 maybe_id: None,
187 priority: self.priority,
188 call: self.call.clone(),
189 maybe_periodic: None,
190 origin: self.origin.clone(),
191 _phantom: Default::default(),
192 }
193 }
194}
195
196use crate::{Scheduled as ScheduledV3, Scheduled as ScheduledV2};
197
198pub type ScheduledV2Of<T> = ScheduledV2<
199 Vec<u8>,
200 <T as Config>::RuntimeCall,
201 BlockNumberFor<T>,
202 <T as Config>::PalletsOrigin,
203 <T as frame_system::Config>::AccountId,
204>;
205
206pub type ScheduledV3Of<T> = ScheduledV3<
207 Vec<u8>,
208 CallOrHashOf<T>,
209 BlockNumberFor<T>,
210 <T as Config>::PalletsOrigin,
211 <T as frame_system::Config>::AccountId,
212>;
213
214pub type ScheduledOf<T> = Scheduled<
215 TaskName,
216 BoundedCallOf<T>,
217 BlockNumberFor<T>,
218 <T as Config>::PalletsOrigin,
219 <T as frame_system::Config>::AccountId,
220>;
221
222pub(crate) trait MarginalWeightInfo: WeightInfo {
223 fn service_task(maybe_lookup_len: Option<usize>, named: bool, periodic: bool) -> Weight {
224 let base = Self::service_task_base();
225 let mut total = match maybe_lookup_len {
226 None => base,
227 Some(l) => Self::service_task_fetched(l as u32),
228 };
229 if named {
230 total.saturating_accrue(Self::service_task_named().saturating_sub(base));
231 }
232 if periodic {
233 total.saturating_accrue(Self::service_task_periodic().saturating_sub(base));
234 }
235 total
236 }
237}
238impl<T: WeightInfo> MarginalWeightInfo for T {}
239
240#[frame_support::pallet]
241pub mod pallet {
242 use super::*;
243 use frame_support::{dispatch::PostDispatchInfo, pallet_prelude::*};
244 use frame_system::pallet_prelude::{BlockNumberFor as SystemBlockNumberFor, OriginFor};
245
246 const STORAGE_VERSION: StorageVersion = StorageVersion::new(4);
248
249 #[pallet::pallet]
250 #[pallet::storage_version(STORAGE_VERSION)]
251 pub struct Pallet<T>(_);
252
253 #[pallet::config]
255 pub trait Config: frame_system::Config {
256 #[allow(deprecated)]
258 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
259
260 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>
262 + From<Self::PalletsOrigin>
263 + IsType<<Self as system::Config>::RuntimeOrigin>;
264
265 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>>
267 + CallerTrait<Self::AccountId>
268 + MaxEncodedLen;
269
270 type RuntimeCall: Parameter
272 + Dispatchable<
273 RuntimeOrigin = <Self as Config>::RuntimeOrigin,
274 PostInfo = PostDispatchInfo,
275 > + GetDispatchInfo
276 + From<system::Call<Self>>;
277
278 #[pallet::constant]
280 type MaximumWeight: Get<Weight>;
281
282 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;
284
285 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;
293
294 #[pallet::constant]
300 type MaxScheduledPerBlock: Get<u32>;
301
302 type WeightInfo: WeightInfo;
304
305 type Preimages: QueryPreimage<H = Self::Hashing> + StorePreimage;
307
308 type BlockNumberProvider: BlockNumberProvider;
336 }
337
338 #[pallet::storage]
340 pub type IncompleteSince<T: Config> = StorageValue<_, BlockNumberFor<T>>;
341
342 #[pallet::storage]
344 pub type Agenda<T: Config> = StorageMap<
345 _,
346 Twox64Concat,
347 BlockNumberFor<T>,
348 BoundedVec<Option<ScheduledOf<T>>, T::MaxScheduledPerBlock>,
349 ValueQuery,
350 >;
351
352 #[pallet::storage]
354 pub type Retries<T: Config> = StorageMap<
355 _,
356 Blake2_128Concat,
357 TaskAddress<BlockNumberFor<T>>,
358 RetryConfig<BlockNumberFor<T>>,
359 OptionQuery,
360 >;
361
362 #[pallet::storage]
367 pub type Lookup<T: Config> =
368 StorageMap<_, Twox64Concat, TaskName, TaskAddress<BlockNumberFor<T>>>;
369
370 #[pallet::event]
372 #[pallet::generate_deposit(pub(super) fn deposit_event)]
373 pub enum Event<T: Config> {
374 Scheduled { when: BlockNumberFor<T>, index: u32 },
376 Canceled { when: BlockNumberFor<T>, index: u32 },
378 Dispatched {
380 task: TaskAddress<BlockNumberFor<T>>,
381 id: Option<TaskName>,
382 result: DispatchResult,
383 },
384 RetrySet {
386 task: TaskAddress<BlockNumberFor<T>>,
387 id: Option<TaskName>,
388 period: BlockNumberFor<T>,
389 retries: u8,
390 },
391 RetryCancelled { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
393 CallUnavailable { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
395 PeriodicFailed { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
397 RetryFailed { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
400 PermanentlyOverweight { task: TaskAddress<BlockNumberFor<T>>, id: Option<TaskName> },
402 AgendaIncomplete { when: BlockNumberFor<T> },
404 }
405
406 #[pallet::error]
407 pub enum Error<T> {
408 FailedToSchedule,
410 NotFound,
412 TargetBlockNumberInPast,
414 RescheduleNoChange,
416 Named,
418 }
419
420 #[pallet::hooks]
421 impl<T: Config> Hooks<SystemBlockNumberFor<T>> for Pallet<T> {
422 fn on_initialize(_now: SystemBlockNumberFor<T>) -> Weight {
424 let now = T::BlockNumberProvider::current_block_number();
425 let mut weight_counter = frame_system::Pallet::<T>::remaining_block_weight()
426 .limit_to(T::MaximumWeight::get());
427 Self::service_agendas(&mut weight_counter, now, u32::MAX);
428 weight_counter.consumed()
429 }
430
431 #[cfg(feature = "std")]
432 fn integrity_test() {
433 fn lookup_weight<T: Config>(s: usize) -> Weight {
435 T::WeightInfo::service_agendas_base() +
436 T::WeightInfo::service_agenda_base(T::MaxScheduledPerBlock::get()) +
437 T::WeightInfo::service_task(Some(s), true, true)
438 }
439
440 let limit = sp_runtime::Perbill::from_percent(90) * T::MaximumWeight::get();
441
442 let small_lookup = lookup_weight::<T>(128);
443 assert!(small_lookup.all_lte(limit), "Must be possible to submit a small lookup");
444
445 let medium_lookup = lookup_weight::<T>(1024);
446 assert!(medium_lookup.all_lte(limit), "Must be possible to submit a medium lookup");
447
448 let large_lookup = lookup_weight::<T>(1024 * 1024);
449 assert!(large_lookup.all_lte(limit), "Must be possible to submit a large lookup");
450 }
451 }
452
453 #[pallet::call]
454 impl<T: Config> Pallet<T> {
455 #[pallet::call_index(0)]
457 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
458 pub fn schedule(
459 origin: OriginFor<T>,
460 when: BlockNumberFor<T>,
461 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
462 priority: schedule::Priority,
463 call: Box<<T as Config>::RuntimeCall>,
464 ) -> DispatchResult {
465 T::ScheduleOrigin::ensure_origin(origin.clone())?;
466 let origin = <T as Config>::RuntimeOrigin::from(origin);
467 Self::do_schedule(
468 DispatchTime::At(when),
469 maybe_periodic,
470 priority,
471 origin.caller().clone(),
472 T::Preimages::bound(*call)?,
473 )?;
474 Ok(())
475 }
476
477 #[pallet::call_index(1)]
482 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]
483 pub fn cancel(origin: OriginFor<T>, when: BlockNumberFor<T>, index: u32) -> DispatchResult {
484 T::ScheduleOrigin::ensure_origin(origin.clone())?;
485 let origin = <T as Config>::RuntimeOrigin::from(origin);
486 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
487 Ok(())
488 }
489
490 #[pallet::call_index(2)]
492 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
493 pub fn schedule_named(
494 origin: OriginFor<T>,
495 id: TaskName,
496 when: BlockNumberFor<T>,
497 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
498 priority: schedule::Priority,
499 call: Box<<T as Config>::RuntimeCall>,
500 ) -> DispatchResult {
501 T::ScheduleOrigin::ensure_origin(origin.clone())?;
502 let origin = <T as Config>::RuntimeOrigin::from(origin);
503 Self::do_schedule_named(
504 id,
505 DispatchTime::At(when),
506 maybe_periodic,
507 priority,
508 origin.caller().clone(),
509 T::Preimages::bound(*call)?,
510 )?;
511 Ok(())
512 }
513
514 #[pallet::call_index(3)]
516 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]
517 pub fn cancel_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {
518 T::ScheduleOrigin::ensure_origin(origin.clone())?;
519 let origin = <T as Config>::RuntimeOrigin::from(origin);
520 Self::do_cancel_named(Some(origin.caller().clone()), id)?;
521 Ok(())
522 }
523
524 #[pallet::call_index(4)]
526 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]
527 pub fn schedule_after(
528 origin: OriginFor<T>,
529 after: BlockNumberFor<T>,
530 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
531 priority: schedule::Priority,
532 call: Box<<T as Config>::RuntimeCall>,
533 ) -> DispatchResult {
534 T::ScheduleOrigin::ensure_origin(origin.clone())?;
535 let origin = <T as Config>::RuntimeOrigin::from(origin);
536 Self::do_schedule(
537 DispatchTime::After(after),
538 maybe_periodic,
539 priority,
540 origin.caller().clone(),
541 T::Preimages::bound(*call)?,
542 )?;
543 Ok(())
544 }
545
546 #[pallet::call_index(5)]
548 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]
549 pub fn schedule_named_after(
550 origin: OriginFor<T>,
551 id: TaskName,
552 after: BlockNumberFor<T>,
553 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
554 priority: schedule::Priority,
555 call: Box<<T as Config>::RuntimeCall>,
556 ) -> DispatchResult {
557 T::ScheduleOrigin::ensure_origin(origin.clone())?;
558 let origin = <T as Config>::RuntimeOrigin::from(origin);
559 Self::do_schedule_named(
560 id,
561 DispatchTime::After(after),
562 maybe_periodic,
563 priority,
564 origin.caller().clone(),
565 T::Preimages::bound(*call)?,
566 )?;
567 Ok(())
568 }
569
570 #[pallet::call_index(6)]
585 #[pallet::weight(<T as Config>::WeightInfo::set_retry())]
586 pub fn set_retry(
587 origin: OriginFor<T>,
588 task: TaskAddress<BlockNumberFor<T>>,
589 retries: u8,
590 period: BlockNumberFor<T>,
591 ) -> DispatchResult {
592 T::ScheduleOrigin::ensure_origin(origin.clone())?;
593 let origin = <T as Config>::RuntimeOrigin::from(origin);
594 let (when, index) = task;
595 let agenda = Agenda::<T>::get(when);
596 let scheduled = agenda
597 .get(index as usize)
598 .and_then(Option::as_ref)
599 .ok_or(Error::<T>::NotFound)?;
600 Self::ensure_privilege(origin.caller(), &scheduled.origin)?;
601 Retries::<T>::insert(
602 (when, index),
603 RetryConfig { total_retries: retries, remaining: retries, period },
604 );
605 Self::deposit_event(Event::RetrySet { task, id: None, period, retries });
606 Ok(())
607 }
608
609 #[pallet::call_index(7)]
624 #[pallet::weight(<T as Config>::WeightInfo::set_retry_named())]
625 pub fn set_retry_named(
626 origin: OriginFor<T>,
627 id: TaskName,
628 retries: u8,
629 period: BlockNumberFor<T>,
630 ) -> DispatchResult {
631 T::ScheduleOrigin::ensure_origin(origin.clone())?;
632 let origin = <T as Config>::RuntimeOrigin::from(origin);
633 let (when, agenda_index) = Lookup::<T>::get(&id).ok_or(Error::<T>::NotFound)?;
634 let agenda = Agenda::<T>::get(when);
635 let scheduled = agenda
636 .get(agenda_index as usize)
637 .and_then(Option::as_ref)
638 .ok_or(Error::<T>::NotFound)?;
639 Self::ensure_privilege(origin.caller(), &scheduled.origin)?;
640 Retries::<T>::insert(
641 (when, agenda_index),
642 RetryConfig { total_retries: retries, remaining: retries, period },
643 );
644 Self::deposit_event(Event::RetrySet {
645 task: (when, agenda_index),
646 id: Some(id),
647 period,
648 retries,
649 });
650 Ok(())
651 }
652
653 #[pallet::call_index(8)]
655 #[pallet::weight(<T as Config>::WeightInfo::cancel_retry())]
656 pub fn cancel_retry(
657 origin: OriginFor<T>,
658 task: TaskAddress<BlockNumberFor<T>>,
659 ) -> DispatchResult {
660 T::ScheduleOrigin::ensure_origin(origin.clone())?;
661 let origin = <T as Config>::RuntimeOrigin::from(origin);
662 Self::do_cancel_retry(origin.caller(), task)?;
663 Self::deposit_event(Event::RetryCancelled { task, id: None });
664 Ok(())
665 }
666
667 #[pallet::call_index(9)]
669 #[pallet::weight(<T as Config>::WeightInfo::cancel_retry_named())]
670 pub fn cancel_retry_named(origin: OriginFor<T>, id: TaskName) -> DispatchResult {
671 T::ScheduleOrigin::ensure_origin(origin.clone())?;
672 let origin = <T as Config>::RuntimeOrigin::from(origin);
673 let task = Lookup::<T>::get(&id).ok_or(Error::<T>::NotFound)?;
674 Self::do_cancel_retry(origin.caller(), task)?;
675 Self::deposit_event(Event::RetryCancelled { task, id: Some(id) });
676 Ok(())
677 }
678 }
679}
680
681impl<T: Config> Pallet<T> {
682 pub fn migrate_v1_to_v4() -> Weight {
686 use migration::v1 as old;
687 let mut weight = T::DbWeight::get().reads_writes(1, 1);
688
689 let keys = old::Agenda::<T>::iter_keys().collect::<Vec<_>>();
692 for key in keys {
693 weight.saturating_accrue(T::DbWeight::get().reads(1));
694 if let Err(_) = old::Agenda::<T>::try_get(&key) {
695 weight.saturating_accrue(T::DbWeight::get().writes(1));
696 old::Agenda::<T>::remove(&key);
697 log::warn!("Deleted undecodable agenda");
698 }
699 }
700
701 Agenda::<T>::translate::<
702 Vec<Option<ScheduledV1<<T as Config>::RuntimeCall, BlockNumberFor<T>>>>,
703 _,
704 >(|_, agenda| {
705 Some(BoundedVec::truncate_from(
706 agenda
707 .into_iter()
708 .map(|schedule| {
709 weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
710
711 schedule.and_then(|schedule| {
712 if let Some(id) = schedule.maybe_id.as_ref() {
713 let name = blake2_256(id);
714 if let Some(item) = old::Lookup::<T>::take(id) {
715 Lookup::<T>::insert(name, item);
716 }
717 weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2));
718 }
719
720 let call = T::Preimages::bound(schedule.call).ok()?;
721
722 if call.lookup_needed() {
723 weight.saturating_accrue(T::DbWeight::get().reads_writes(0, 1));
724 }
725
726 Some(Scheduled {
727 maybe_id: schedule.maybe_id.map(|x| blake2_256(&x[..])),
728 priority: schedule.priority,
729 call,
730 maybe_periodic: schedule.maybe_periodic,
731 origin: system::RawOrigin::Root.into(),
732 _phantom: Default::default(),
733 })
734 })
735 })
736 .collect::<Vec<_>>(),
737 ))
738 });
739
740 let _ = frame_support::storage::migration::clear_storage_prefix(
741 Self::name().as_bytes(),
742 b"StorageVersion",
743 &[],
744 None,
745 None,
746 );
747
748 StorageVersion::new(4).put::<Self>();
749
750 weight + T::DbWeight::get().writes(2)
751 }
752
753 pub fn migrate_v2_to_v4() -> Weight {
757 use migration::v2 as old;
758 let mut weight = T::DbWeight::get().reads_writes(1, 1);
759
760 let keys = old::Agenda::<T>::iter_keys().collect::<Vec<_>>();
763 for key in keys {
764 weight.saturating_accrue(T::DbWeight::get().reads(1));
765 if let Err(_) = old::Agenda::<T>::try_get(&key) {
766 weight.saturating_accrue(T::DbWeight::get().writes(1));
767 old::Agenda::<T>::remove(&key);
768 log::warn!("Deleted undecodable agenda");
769 }
770 }
771
772 Agenda::<T>::translate::<Vec<Option<ScheduledV2Of<T>>>, _>(|_, agenda| {
773 Some(BoundedVec::truncate_from(
774 agenda
775 .into_iter()
776 .map(|schedule| {
777 weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
778 schedule.and_then(|schedule| {
779 if let Some(id) = schedule.maybe_id.as_ref() {
780 let name = blake2_256(id);
781 if let Some(item) = old::Lookup::<T>::take(id) {
782 Lookup::<T>::insert(name, item);
783 }
784 weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2));
785 }
786
787 let call = T::Preimages::bound(schedule.call).ok()?;
788 if call.lookup_needed() {
789 weight.saturating_accrue(T::DbWeight::get().reads_writes(0, 1));
790 }
791
792 Some(Scheduled {
793 maybe_id: schedule.maybe_id.map(|x| blake2_256(&x[..])),
794 priority: schedule.priority,
795 call,
796 maybe_periodic: schedule.maybe_periodic,
797 origin: schedule.origin,
798 _phantom: Default::default(),
799 })
800 })
801 })
802 .collect::<Vec<_>>(),
803 ))
804 });
805
806 let _ = frame_support::storage::migration::clear_storage_prefix(
807 Self::name().as_bytes(),
808 b"StorageVersion",
809 &[],
810 None,
811 None,
812 );
813
814 StorageVersion::new(4).put::<Self>();
815
816 weight + T::DbWeight::get().writes(2)
817 }
818
819 #[allow(deprecated)]
823 pub fn migrate_v3_to_v4() -> Weight {
824 use migration::v3 as old;
825 let mut weight = T::DbWeight::get().reads_writes(2, 1);
826
827 let blocks = old::Agenda::<T>::iter_keys().collect::<Vec<_>>();
830 for block in blocks {
831 weight.saturating_accrue(T::DbWeight::get().reads(1));
832 if let Err(_) = old::Agenda::<T>::try_get(&block) {
833 weight.saturating_accrue(T::DbWeight::get().writes(1));
834 old::Agenda::<T>::remove(&block);
835 log::warn!("Deleted undecodable agenda of block: {:?}", block);
836 }
837 }
838
839 Agenda::<T>::translate::<Vec<Option<ScheduledV3Of<T>>>, _>(|block, agenda| {
840 log::info!("Migrating agenda of block: {:?}", &block);
841 Some(BoundedVec::truncate_from(
842 agenda
843 .into_iter()
844 .map(|schedule| {
845 weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
846 schedule
847 .and_then(|schedule| {
848 if let Some(id) = schedule.maybe_id.as_ref() {
849 let name = blake2_256(id);
850 if let Some(item) = old::Lookup::<T>::take(id) {
851 Lookup::<T>::insert(name, item);
852 log::info!("Migrated name for id: {:?}", id);
853 } else {
854 log::error!("No name in Lookup for id: {:?}", &id);
855 }
856 weight.saturating_accrue(T::DbWeight::get().reads_writes(2, 2));
857 } else {
858 log::info!("Schedule is unnamed");
859 }
860
861 let call = match schedule.call {
862 MaybeHashed::Hash(h) => {
863 let bounded = Bounded::from_legacy_hash(h);
864 if let Err(err) = T::Preimages::peek::<
866 <T as Config>::RuntimeCall,
867 >(&bounded)
868 {
869 log::error!(
870 "Dropping undecodable call {:?}: {:?}",
871 &h,
872 &err
873 );
874 return None;
875 }
876 weight.saturating_accrue(T::DbWeight::get().reads(1));
877 log::info!("Migrated call by hash, hash: {:?}", h);
878 bounded
879 },
880 MaybeHashed::Value(v) => {
881 let call = T::Preimages::bound(v)
882 .map_err(|e| {
883 log::error!("Could not bound Call: {:?}", e)
884 })
885 .ok()?;
886 if call.lookup_needed() {
887 weight.saturating_accrue(
888 T::DbWeight::get().reads_writes(0, 1),
889 );
890 }
891 log::info!(
892 "Migrated call by value, hash: {:?}",
893 call.hash()
894 );
895 call
896 },
897 };
898
899 Some(Scheduled {
900 maybe_id: schedule.maybe_id.map(|x| blake2_256(&x[..])),
901 priority: schedule.priority,
902 call,
903 maybe_periodic: schedule.maybe_periodic,
904 origin: schedule.origin,
905 _phantom: Default::default(),
906 })
907 })
908 .or_else(|| {
909 log::info!("Schedule in agenda for block {:?} is empty - nothing to do here.", &block);
910 None
911 })
912 })
913 .collect::<Vec<_>>(),
914 ))
915 });
916
917 let _ = frame_support::storage::migration::clear_storage_prefix(
918 Self::name().as_bytes(),
919 b"StorageVersion",
920 &[],
921 None,
922 None,
923 );
924
925 StorageVersion::new(4).put::<Self>();
926
927 weight + T::DbWeight::get().writes(2)
928 }
929}
930
931impl<T: Config> Pallet<T> {
932 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {
934 Agenda::<T>::translate::<
935 Vec<
936 Option<
937 Scheduled<
938 TaskName,
939 BoundedCallOf<T>,
940 BlockNumberFor<T>,
941 OldOrigin,
942 T::AccountId,
943 >,
944 >,
945 >,
946 _,
947 >(|_, agenda| {
948 Some(BoundedVec::truncate_from(
949 agenda
950 .into_iter()
951 .map(|schedule| {
952 schedule.map(|schedule| Scheduled {
953 maybe_id: schedule.maybe_id,
954 priority: schedule.priority,
955 call: schedule.call,
956 maybe_periodic: schedule.maybe_periodic,
957 origin: schedule.origin.into(),
958 _phantom: Default::default(),
959 })
960 })
961 .collect::<Vec<_>>(),
962 ))
963 });
964 }
965
966 fn resolve_time(
967 when: DispatchTime<BlockNumberFor<T>>,
968 ) -> Result<BlockNumberFor<T>, DispatchError> {
969 let now = T::BlockNumberProvider::current_block_number();
970 let when = match when {
971 DispatchTime::At(x) => x,
972 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),
975 };
976
977 if when <= now {
978 return Err(Error::<T>::TargetBlockNumberInPast.into());
979 }
980
981 Ok(when)
982 }
983
984 fn place_task(
985 when: BlockNumberFor<T>,
986 what: ScheduledOf<T>,
987 ) -> Result<TaskAddress<BlockNumberFor<T>>, (DispatchError, ScheduledOf<T>)> {
988 let maybe_name = what.maybe_id;
989 let index = Self::push_to_agenda(when, what)?;
990 let address = (when, index);
991 if let Some(name) = maybe_name {
992 Lookup::<T>::insert(name, address)
993 }
994 Self::deposit_event(Event::Scheduled { when: address.0, index: address.1 });
995 Ok(address)
996 }
997
998 fn push_to_agenda(
999 when: BlockNumberFor<T>,
1000 what: ScheduledOf<T>,
1001 ) -> Result<u32, (DispatchError, ScheduledOf<T>)> {
1002 let mut agenda = Agenda::<T>::get(when);
1003 let index = if (agenda.len() as u32) < T::MaxScheduledPerBlock::get() {
1004 let _ = agenda.try_push(Some(what));
1006 agenda.len() as u32 - 1
1007 } else {
1008 if let Some(hole_index) = agenda.iter().position(|i| i.is_none()) {
1009 agenda[hole_index] = Some(what);
1010 hole_index as u32
1011 } else {
1012 return Err((DispatchError::Exhausted, what));
1013 }
1014 };
1015 Agenda::<T>::insert(when, agenda);
1016 Ok(index)
1017 }
1018
1019 fn cleanup_agenda(when: BlockNumberFor<T>) {
1022 let mut agenda = Agenda::<T>::get(when);
1023 match agenda.iter().rposition(|i| i.is_some()) {
1024 Some(i) if agenda.len() > i + 1 => {
1027 agenda.truncate(i + 1);
1028 Agenda::<T>::insert(when, agenda);
1029 },
1030 Some(_) => {},
1033 None => {
1035 Agenda::<T>::remove(when);
1036 },
1037 }
1038 }
1039
1040 fn do_schedule(
1041 when: DispatchTime<BlockNumberFor<T>>,
1042 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1043 priority: schedule::Priority,
1044 origin: T::PalletsOrigin,
1045 call: BoundedCallOf<T>,
1046 ) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1047 let when = Self::resolve_time(when)?;
1048
1049 let lookup_hash = call.lookup_hash();
1050
1051 let maybe_periodic = maybe_periodic
1053 .filter(|p| p.1 > 1 && !p.0.is_zero())
1054 .map(|(p, c)| (p, c - 1));
1056 let task = Scheduled {
1057 maybe_id: None,
1058 priority,
1059 call,
1060 maybe_periodic,
1061 origin,
1062 _phantom: PhantomData,
1063 };
1064 let res = Self::place_task(when, task).map_err(|x| x.0)?;
1065
1066 if let Some(hash) = lookup_hash {
1067 T::Preimages::request(&hash);
1069 }
1070
1071 Ok(res)
1072 }
1073
1074 fn do_cancel(
1075 origin: Option<T::PalletsOrigin>,
1076 (when, index): TaskAddress<BlockNumberFor<T>>,
1077 ) -> Result<(), DispatchError> {
1078 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {
1079 agenda.get_mut(index as usize).map_or(
1080 Ok(None),
1081 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {
1082 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
1083 Self::ensure_privilege(o, &s.origin)?;
1084 };
1085 Ok(s.take())
1086 },
1087 )
1088 })?;
1089 if let Some(s) = scheduled {
1090 T::Preimages::drop(&s.call);
1091 if let Some(id) = s.maybe_id {
1092 Lookup::<T>::remove(id);
1093 }
1094 Retries::<T>::remove((when, index));
1095 Self::cleanup_agenda(when);
1096 Self::deposit_event(Event::Canceled { when, index });
1097 Ok(())
1098 } else {
1099 return Err(Error::<T>::NotFound.into());
1100 }
1101 }
1102
1103 fn do_reschedule(
1104 (when, index): TaskAddress<BlockNumberFor<T>>,
1105 new_time: DispatchTime<BlockNumberFor<T>>,
1106 ) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1107 let new_time = Self::resolve_time(new_time)?;
1108
1109 if new_time == when {
1110 return Err(Error::<T>::RescheduleNoChange.into());
1111 }
1112
1113 let task = Agenda::<T>::try_mutate(when, |agenda| {
1114 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;
1115 ensure!(!matches!(task, Some(Scheduled { maybe_id: Some(_), .. })), Error::<T>::Named);
1116 task.take().ok_or(Error::<T>::NotFound)
1117 })?;
1118 Self::cleanup_agenda(when);
1119 Self::deposit_event(Event::Canceled { when, index });
1120
1121 Self::place_task(new_time, task).map_err(|x| x.0)
1122 }
1123
1124 fn do_schedule_named(
1125 id: TaskName,
1126 when: DispatchTime<BlockNumberFor<T>>,
1127 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1128 priority: schedule::Priority,
1129 origin: T::PalletsOrigin,
1130 call: BoundedCallOf<T>,
1131 ) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1132 if Lookup::<T>::contains_key(&id) {
1134 return Err(Error::<T>::FailedToSchedule.into());
1135 }
1136
1137 let when = Self::resolve_time(when)?;
1138
1139 let lookup_hash = call.lookup_hash();
1140
1141 let maybe_periodic = maybe_periodic
1143 .filter(|p| p.1 > 1 && !p.0.is_zero())
1144 .map(|(p, c)| (p, c - 1));
1146
1147 let task = Scheduled {
1148 maybe_id: Some(id),
1149 priority,
1150 call,
1151 maybe_periodic,
1152 origin,
1153 _phantom: Default::default(),
1154 };
1155 let res = Self::place_task(when, task).map_err(|x| x.0)?;
1156
1157 if let Some(hash) = lookup_hash {
1158 T::Preimages::request(&hash);
1160 }
1161
1162 Ok(res)
1163 }
1164
1165 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: TaskName) -> DispatchResult {
1166 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
1167 if let Some((when, index)) = lookup.take() {
1168 let i = index as usize;
1169 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
1170 if let Some(s) = agenda.get_mut(i) {
1171 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
1172 Self::ensure_privilege(o, &s.origin)?;
1173 Retries::<T>::remove((when, index));
1174 T::Preimages::drop(&s.call);
1175 }
1176 *s = None;
1177 }
1178 Ok(())
1179 })?;
1180 Self::cleanup_agenda(when);
1181 Self::deposit_event(Event::Canceled { when, index });
1182 Ok(())
1183 } else {
1184 return Err(Error::<T>::NotFound.into());
1185 }
1186 })
1187 }
1188
1189 fn do_reschedule_named(
1190 id: TaskName,
1191 new_time: DispatchTime<BlockNumberFor<T>>,
1192 ) -> Result<TaskAddress<BlockNumberFor<T>>, DispatchError> {
1193 let new_time = Self::resolve_time(new_time)?;
1194
1195 let lookup = Lookup::<T>::get(id);
1196 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;
1197
1198 if new_time == when {
1199 return Err(Error::<T>::RescheduleNoChange.into());
1200 }
1201
1202 let task = Agenda::<T>::try_mutate(when, |agenda| {
1203 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;
1204 task.take().ok_or(Error::<T>::NotFound)
1205 })?;
1206 Self::cleanup_agenda(when);
1207 Self::deposit_event(Event::Canceled { when, index });
1208 Self::place_task(new_time, task).map_err(|x| x.0)
1209 }
1210
1211 fn do_cancel_retry(
1212 origin: &T::PalletsOrigin,
1213 (when, index): TaskAddress<BlockNumberFor<T>>,
1214 ) -> Result<(), DispatchError> {
1215 let agenda = Agenda::<T>::get(when);
1216 let scheduled = agenda
1217 .get(index as usize)
1218 .and_then(Option::as_ref)
1219 .ok_or(Error::<T>::NotFound)?;
1220 Self::ensure_privilege(origin, &scheduled.origin)?;
1221 Retries::<T>::remove((when, index));
1222 Ok(())
1223 }
1224}
1225
1226enum ServiceTaskError {
1227 Unavailable,
1229 Overweight,
1231}
1232use ServiceTaskError::*;
1233
1234impl<T: Config> Pallet<T> {
1235 fn service_agendas(weight: &mut WeightMeter, now: BlockNumberFor<T>, max: u32) {
1237 if weight.try_consume(T::WeightInfo::service_agendas_base()).is_err() {
1238 return;
1239 }
1240
1241 let mut incomplete_since = now + One::one();
1242 let mut when = IncompleteSince::<T>::take().unwrap_or(now);
1243 let mut is_first = true; let max_items = T::MaxScheduledPerBlock::get();
1246 let mut count_down = max;
1247 let service_agenda_base_weight = T::WeightInfo::service_agenda_base(max_items);
1248 while count_down > 0 && when <= now && weight.can_consume(service_agenda_base_weight) {
1249 if !Self::service_agenda(weight, is_first, now, when, u32::MAX) {
1250 incomplete_since = incomplete_since.min(when);
1251 }
1252 is_first = false;
1253 when.saturating_inc();
1254 count_down.saturating_dec();
1255 }
1256 incomplete_since = incomplete_since.min(when);
1257 if incomplete_since <= now {
1258 Self::deposit_event(Event::AgendaIncomplete { when: incomplete_since });
1259 IncompleteSince::<T>::put(incomplete_since);
1260 } else {
1261 IncompleteSince::<T>::put(now + One::one());
1266 }
1267 }
1268
1269 fn service_agenda(
1272 weight: &mut WeightMeter,
1273 mut is_first: bool,
1274 now: BlockNumberFor<T>,
1275 when: BlockNumberFor<T>,
1276 max: u32,
1277 ) -> bool {
1278 let mut agenda = Agenda::<T>::get(when);
1279 let mut ordered = agenda
1280 .iter()
1281 .enumerate()
1282 .filter_map(|(index, maybe_item)| {
1283 maybe_item.as_ref().map(|item| (index as u32, item.priority))
1284 })
1285 .collect::<Vec<_>>();
1286 ordered.sort_by_key(|k| k.1);
1287 let within_limit = weight
1288 .try_consume(T::WeightInfo::service_agenda_base(ordered.len() as u32))
1289 .is_ok();
1290 debug_assert!(within_limit, "weight limit should have been checked in advance");
1291
1292 let mut postponed = (ordered.len() as u32).saturating_sub(max);
1294 let mut dropped = 0;
1296
1297 for (agenda_index, _) in ordered.into_iter().take(max as usize) {
1298 let Some(task) = agenda[agenda_index as usize].take() else { continue };
1299 let base_weight = T::WeightInfo::service_task(
1300 task.call.lookup_len().map(|x| x as usize),
1301 task.maybe_id.is_some(),
1302 task.maybe_periodic.is_some(),
1303 );
1304 if !weight.can_consume(base_weight) {
1305 postponed += 1;
1306 agenda[agenda_index as usize] = Some(task);
1307 break;
1308 }
1309 let result = Self::service_task(weight, now, when, agenda_index, is_first, task);
1310 agenda[agenda_index as usize] = match result {
1311 Err((Unavailable, slot)) => {
1312 dropped += 1;
1313 slot
1314 },
1315 Err((Overweight, slot)) => {
1316 postponed += 1;
1317 slot
1318 },
1319 Ok(()) => {
1320 is_first = false;
1321 None
1322 },
1323 };
1324 }
1325 if postponed > 0 || dropped > 0 {
1326 Agenda::<T>::insert(when, agenda);
1327 } else {
1328 Agenda::<T>::remove(when);
1329 }
1330
1331 postponed == 0
1332 }
1333
1334 fn service_task(
1341 weight: &mut WeightMeter,
1342 now: BlockNumberFor<T>,
1343 when: BlockNumberFor<T>,
1344 agenda_index: u32,
1345 is_first: bool,
1346 mut task: ScheduledOf<T>,
1347 ) -> Result<(), (ServiceTaskError, Option<ScheduledOf<T>>)> {
1348 if let Some(ref id) = task.maybe_id {
1349 Lookup::<T>::remove(id);
1350 }
1351
1352 let (call, lookup_len) = match T::Preimages::peek(&task.call) {
1353 Ok(c) => c,
1354 Err(_) => {
1355 Self::deposit_event(Event::CallUnavailable {
1356 task: (when, agenda_index),
1357 id: task.maybe_id,
1358 });
1359
1360 T::Preimages::drop(&task.call);
1363
1364 let _ = weight.try_consume(T::WeightInfo::service_task(
1366 task.call.lookup_len().map(|x| x as usize),
1367 task.maybe_id.is_some(),
1368 task.maybe_periodic.is_some(),
1369 ));
1370
1371 return Err((Unavailable, Some(task)));
1372 },
1373 };
1374
1375 let _ = weight.try_consume(T::WeightInfo::service_task(
1376 lookup_len.map(|x| x as usize),
1377 task.maybe_id.is_some(),
1378 task.maybe_periodic.is_some(),
1379 ));
1380
1381 match Self::execute_dispatch(weight, task.origin.clone(), call) {
1382 Err(()) if is_first => {
1383 T::Preimages::drop(&task.call);
1384 Self::deposit_event(Event::PermanentlyOverweight {
1385 task: (when, agenda_index),
1386 id: task.maybe_id,
1387 });
1388 Err((Unavailable, Some(task)))
1389 },
1390 Err(()) => Err((Overweight, Some(task))),
1391 Ok(result) => {
1392 let failed = result.is_err();
1393 let maybe_retry_config = Retries::<T>::take((when, agenda_index));
1394 Self::deposit_event(Event::Dispatched {
1395 task: (when, agenda_index),
1396 id: task.maybe_id,
1397 result,
1398 });
1399
1400 match maybe_retry_config {
1401 Some(retry_config) if failed => {
1402 Self::schedule_retry(weight, now, when, agenda_index, &task, retry_config);
1403 },
1404 _ => {},
1405 }
1406
1407 if let &Some((period, count)) = &task.maybe_periodic {
1408 if count > 1 {
1409 task.maybe_periodic = Some((period, count - 1));
1410 } else {
1411 task.maybe_periodic = None;
1412 }
1413 let wake = now.saturating_add(period);
1414 match Self::place_task(wake, task) {
1415 Ok(new_address) => {
1416 if let Some(retry_config) = maybe_retry_config {
1417 Retries::<T>::insert(new_address, retry_config);
1418 }
1419 },
1420 Err((_, task)) => {
1421 T::Preimages::drop(&task.call);
1424 Self::deposit_event(Event::PeriodicFailed {
1425 task: (when, agenda_index),
1426 id: task.maybe_id,
1427 });
1428 },
1429 }
1430 } else {
1431 T::Preimages::drop(&task.call);
1432 }
1433 Ok(())
1434 },
1435 }
1436 }
1437
1438 fn execute_dispatch(
1447 weight: &mut WeightMeter,
1448 origin: T::PalletsOrigin,
1449 call: <T as Config>::RuntimeCall,
1450 ) -> Result<DispatchResult, ()> {
1451 let base_weight = match origin.as_system_ref() {
1452 Some(&RawOrigin::Signed(_)) => T::WeightInfo::execute_dispatch_signed(),
1453 _ => T::WeightInfo::execute_dispatch_unsigned(),
1454 };
1455 let call_weight = call.get_dispatch_info().call_weight;
1456 let max_weight = base_weight.saturating_add(call_weight);
1458
1459 if !weight.can_consume(max_weight) {
1460 return Err(());
1461 }
1462
1463 let dispatch_origin = origin.into();
1464 let (maybe_actual_call_weight, result) = match call.dispatch(dispatch_origin) {
1465 Ok(post_info) => (post_info.actual_weight, Ok(())),
1466 Err(error_and_info) => {
1467 (error_and_info.post_info.actual_weight, Err(error_and_info.error))
1468 },
1469 };
1470 let call_weight = maybe_actual_call_weight.unwrap_or(call_weight);
1471 let _ = weight.try_consume(base_weight);
1472 let _ = weight.try_consume(call_weight);
1473 Ok(result)
1474 }
1475
1476 fn schedule_retry(
1484 weight: &mut WeightMeter,
1485 now: BlockNumberFor<T>,
1486 when: BlockNumberFor<T>,
1487 agenda_index: u32,
1488 task: &ScheduledOf<T>,
1489 retry_config: RetryConfig<BlockNumberFor<T>>,
1490 ) {
1491 if weight
1492 .try_consume(T::WeightInfo::schedule_retry(T::MaxScheduledPerBlock::get()))
1493 .is_err()
1494 {
1495 Self::deposit_event(Event::RetryFailed {
1496 task: (when, agenda_index),
1497 id: task.maybe_id,
1498 });
1499 return;
1500 }
1501
1502 let RetryConfig { total_retries, mut remaining, period } = retry_config;
1503 remaining = match remaining.checked_sub(1) {
1504 Some(n) => n,
1505 None => return,
1506 };
1507 let wake = now.saturating_add(period);
1508 match Self::place_task(wake, task.as_retry()) {
1509 Ok(address) => {
1510 Retries::<T>::insert(address, RetryConfig { total_retries, remaining, period });
1513 },
1514 Err((_, task)) => {
1515 T::Preimages::drop(&task.call);
1518 Self::deposit_event(Event::RetryFailed {
1519 task: (when, agenda_index),
1520 id: task.maybe_id,
1521 });
1522 },
1523 }
1524 }
1525
1526 fn ensure_privilege(
1530 left: &<T as Config>::PalletsOrigin,
1531 right: &<T as Config>::PalletsOrigin,
1532 ) -> Result<(), DispatchError> {
1533 if matches!(T::OriginPrivilegeCmp::cmp_privilege(left, right), Some(Ordering::Less) | None)
1534 {
1535 return Err(BadOrigin.into());
1536 }
1537 Ok(())
1538 }
1539}
1540
1541impl<T: Config> schedule::v3::Anon<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin>
1542 for Pallet<T>
1543{
1544 type Address = TaskAddress<BlockNumberFor<T>>;
1545 type Hasher = T::Hashing;
1546
1547 fn schedule(
1548 when: DispatchTime<BlockNumberFor<T>>,
1549 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1550 priority: schedule::Priority,
1551 origin: T::PalletsOrigin,
1552 call: BoundedCallOf<T>,
1553 ) -> Result<Self::Address, DispatchError> {
1554 Self::do_schedule(when, maybe_periodic, priority, origin, call)
1555 }
1556
1557 fn cancel((when, index): Self::Address) -> Result<(), DispatchError> {
1558 Self::do_cancel(None, (when, index)).map_err(map_err_to_v3_err::<T>)
1559 }
1560
1561 fn reschedule(
1562 address: Self::Address,
1563 when: DispatchTime<BlockNumberFor<T>>,
1564 ) -> Result<Self::Address, DispatchError> {
1565 Self::do_reschedule(address, when).map_err(map_err_to_v3_err::<T>)
1566 }
1567
1568 fn next_dispatch_time(
1569 (when, index): Self::Address,
1570 ) -> Result<BlockNumberFor<T>, DispatchError> {
1571 Agenda::<T>::get(when)
1572 .get(index as usize)
1573 .ok_or(DispatchError::Unavailable)
1574 .map(|_| when)
1575 }
1576}
1577
1578use schedule::v3::TaskName;
1579
1580impl<T: Config> schedule::v3::Named<BlockNumberFor<T>, <T as Config>::RuntimeCall, T::PalletsOrigin>
1581 for Pallet<T>
1582{
1583 type Address = TaskAddress<BlockNumberFor<T>>;
1584 type Hasher = T::Hashing;
1585
1586 fn schedule_named(
1587 id: TaskName,
1588 when: DispatchTime<BlockNumberFor<T>>,
1589 maybe_periodic: Option<schedule::Period<BlockNumberFor<T>>>,
1590 priority: schedule::Priority,
1591 origin: T::PalletsOrigin,
1592 call: BoundedCallOf<T>,
1593 ) -> Result<Self::Address, DispatchError> {
1594 Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call)
1595 }
1596
1597 fn cancel_named(id: TaskName) -> Result<(), DispatchError> {
1598 Self::do_cancel_named(None, id).map_err(map_err_to_v3_err::<T>)
1599 }
1600
1601 fn reschedule_named(
1602 id: TaskName,
1603 when: DispatchTime<BlockNumberFor<T>>,
1604 ) -> Result<Self::Address, DispatchError> {
1605 Self::do_reschedule_named(id, when).map_err(map_err_to_v3_err::<T>)
1606 }
1607
1608 fn next_dispatch_time(id: TaskName) -> Result<BlockNumberFor<T>, DispatchError> {
1609 Lookup::<T>::get(id)
1610 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))
1611 .ok_or(DispatchError::Unavailable)
1612 }
1613}
1614
1615fn map_err_to_v3_err<T: Config>(err: DispatchError) -> DispatchError {
1617 if err == DispatchError::from(Error::<T>::NotFound) {
1618 DispatchError::Unavailable
1619 } else {
1620 err
1621 }
1622}