12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061#![cfg_attr(not(feature = "std"), no_std)]626364656667pub mod weights;6869use sp_core::H160;70use codec::{Codec, Decode, Encode};71use frame_system::{self as system, ensure_signed};72pub use pallet::*;73use scale_info::TypeInfo;74use sp_runtime::{75 traits::{BadOrigin, One, Saturating, Zero},76 RuntimeDebug, DispatchErrorWithPostInfo,77};78use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};7980use frame_support::{81 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},82 traits::{83 schedule::{self, DispatchTime, MaybeHashed},84 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,85 StorageVersion,86 },87 weights::{GetDispatchInfo, Weight},88};8990pub use weights::WeightInfo;919293pub type PeriodicIndex = u32;9495pub type TaskAddress<BlockNumber> = (BlockNumber, u32);96pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;9798type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];99pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;100101102#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]103#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]104pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {105 106 maybe_id: Option<ScheduledId>,107 108 priority: schedule::Priority,109 110 call: Call,111 112 maybe_periodic: Option<schedule::Period<BlockNumber>>,113 114 origin: PalletsOrigin,115 _phantom: PhantomData<AccountId>,116}117118pub type ScheduledV3Of<T> = ScheduledV3<119 CallOrHashOf<T>,120 <T as frame_system::Config>::BlockNumber,121 <T as Config>::PalletsOrigin,122 <T as frame_system::Config>::AccountId,123>;124125pub type ScheduledOf<T> = ScheduledV3Of<T>;126127128pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =129 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;130131#[cfg(feature = "runtime-benchmarks")]132mod preimage_provider {133 use frame_support::traits::PreimageRecipient;134 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}135 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}136}137138#[cfg(not(feature = "runtime-benchmarks"))]139mod preimage_provider {140 use frame_support::traits::PreimageProvider;141 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}142 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}143}144145pub use preimage_provider::PreimageProviderAndMaybeRecipient;146147pub(crate) trait MarginalWeightInfo: WeightInfo {148 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {149 match (periodic, named, resolved) {150 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),151 (_, true, None) => {152 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)153 }154 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),155 (false, true, Some(false)) => {156 Self::on_initialize_named(2) - Self::on_initialize_named(1)157 }158 (true, false, Some(false)) => {159 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)160 }161 (true, true, Some(false)) => {162 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)163 }164 (false, false, Some(true)) => {165 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)166 }167 (false, true, Some(true)) => {168 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)169 }170 (true, false, Some(true)) => {171 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)172 }173 (true, true, Some(true)) => {174 Self::on_initialize_periodic_named_resolved(2)175 - Self::on_initialize_periodic_named_resolved(1)176 }177 }178 }179}180impl<T: WeightInfo> MarginalWeightInfo for T {}181182#[frame_support::pallet]183pub mod pallet {184 use super::*;185 use frame_support::{186 dispatch::PostDispatchInfo,187 pallet_prelude::*,188 traits::{schedule::LookupError, PreimageProvider},189 };190 use frame_system::pallet_prelude::*;191192 193 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);194195 #[pallet::pallet]196 #[pallet::generate_store(pub(super) trait Store)]197 #[pallet::storage_version(STORAGE_VERSION)]198 #[pallet::without_storage_info]199 pub struct Pallet<T>(_);200201 202 #[pallet::config]203 pub trait Config: frame_system::Config {204 205 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;206207 208 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>209 + From<Self::PalletsOrigin>210 + IsType<<Self as system::Config>::Origin>;211212 213 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;214215 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;216217 218 type Call: Parameter219 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>220 + GetDispatchInfo221 + From<system::Call<Self>>;222223 224 225 #[pallet::constant]226 type MaximumWeight: Get<Weight>;227228 229 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;230231 232 233 234 235 236 237 238 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;239240 241 242 #[pallet::constant]243 type MaxScheduledPerBlock: Get<u32>;244245 246 type WeightInfo: WeightInfo;247248 249 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;250251 252 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;253254 255 256257 258 type CallExecutor: DispatchCall<Self, H160>;259 }260261 262 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {263 fn reserve_balance(264 id: ScheduledId,265 sponsor: <T as frame_system::Config>::AccountId,266 call: <T as Config>::Call,267 count: u32,268 ) -> Result<(), DispatchError>;269270 fn pay_for_call(271 id: ScheduledId,272 sponsor: <T as frame_system::Config>::AccountId,273 call: <T as Config>::Call,274 ) -> Result<u128, DispatchError>;275276 277 fn dispatch_call(278 signer: T::AccountId,279 function: <T as Config>::Call,280 ) -> Result<281 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,282 TransactionValidityError,283 >;284285 fn cancel_reserve(286 id: ScheduledId,287 sponsor: <T as frame_system::Config>::AccountId,288 ) -> Result<u128, DispatchError>;289 }290291 292 #[pallet::storage]293 pub type Agenda<T: Config> =294 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;295296 297 #[pallet::storage]298 pub(crate) type Lookup<T: Config> =299 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;300301 302 #[pallet::event]303 #[pallet::generate_deposit(pub(super) fn deposit_event)]304 pub enum Event<T: Config> {305 306 Scheduled { when: T::BlockNumber, index: u32 },307 308 Canceled { when: T::BlockNumber, index: u32 },309 310 Dispatched {311 task: TaskAddress<T::BlockNumber>,312 id: Option<ScheduledId>,313 result: DispatchResult,314 },315 316 CallLookupFailed {317 task: TaskAddress<T::BlockNumber>,318 id: Option<ScheduledId>,319 error: LookupError,320 },321 }322323 #[pallet::error]324 pub enum Error<T> {325 326 FailedToSchedule,327 328 NotFound,329 330 TargetBlockNumberInPast,331 332 RescheduleNoChange,333 }334335 #[pallet::hooks]336 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {337 338 fn on_initialize(now: T::BlockNumber) -> Weight {339 let limit = T::MaximumWeight::get();340341 let mut queued = Agenda::<T>::take(now)342 .into_iter()343 .enumerate()344 .filter_map(|(index, s)| Some((index as u32, s?)))345 .collect::<Vec<_>>();346347 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {348 log::warn!(349 target: "runtime::scheduler",350 "Warning: This block has more items queued in Scheduler than \351 expected from the runtime configuration. An update might be needed."352 );353 }354355 queued.sort_by_key(|(_, s)| s.priority);356357 let next = now + One::one();358359 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);360 for (order, (index, mut s)) in queued.into_iter().enumerate() {361 let named = if let Some(ref id) = s.maybe_id {362 Lookup::<T>::remove(id);363 true364 } else {365 false366 };367368 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();369 s.call = call;370371 let resolved = if let Some(completed) = maybe_completed {372 T::PreimageProvider::unrequest_preimage(&completed);373 true374 } else {375 false376 };377 let call = match s.call.as_value().cloned() {378 Some(c) => c,379 None => {380 381 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));382 if let Some(delay) = T::NoPreimagePostponement::get() {383 let until = now.saturating_add(delay);384 if let Some(ref id) = s.maybe_id {385 let index = Agenda::<T>::decode_len(until).unwrap_or(0);386 Lookup::<T>::insert(id, (until, index as u32));387 }388 Agenda::<T>::append(until, Some(s));389 }390 continue;391 }392 };393394 let periodic = s.maybe_periodic.is_some();395 let call_weight = call.get_dispatch_info().weight;396 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));397 let origin =398 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())399 .into();400 if ensure_signed(origin).is_ok() {401 402 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));403 }404405 406 407 408 409 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;410 let test_weight = total_weight411 .saturating_add(call_weight)412 .saturating_add(item_weight);413 if !hard_deadline && order > 0 && test_weight > limit {414 415 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));416 if let Some(ref id) = s.maybe_id {417 418 419 420 421 let index = Agenda::<T>::decode_len(next).unwrap_or(0);422 Lookup::<T>::insert(id, (next, index as u32));423 }424 Agenda::<T>::append(next, Some(s));425 continue;426 }427428 let sender = ensure_signed(429 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())430 .into(),431 )432 .unwrap();433434 435 436 437 438 439 440 441 442443 let r = T::CallExecutor::dispatch_call(sender, call.clone());444445 let mut actual_call_weight: Weight = item_weight;446 let result: Result<_, DispatchError> = match r {447 Ok(o) => match o {448 Ok(di) => {449 actual_call_weight = di.actual_weight.unwrap_or(item_weight);450 Ok(())451 }452 Err(err) => Err(err.error),453 },454 Err(_) => {455 log::error!(456 target: "runtime::scheduler",457 "Warning: Scheduler has failed to execute a post-dispatch transaction. \458 This block might have become invalid.");459 Err(DispatchError::CannotLookup)460 } 461 };462463 total_weight.saturating_accrue(item_weight);464 total_weight.saturating_accrue(actual_call_weight);465466 Self::deposit_event(Event::Dispatched {467 task: (now, index),468 id: s.maybe_id.clone(),469 result,470 });471472 if let &Some((period, count)) = &s.maybe_periodic {473 if count > 1 {474 s.maybe_periodic = Some((period, count - 1));475 } else {476 s.maybe_periodic = None;477 }478 let wake = now + period;479 480 if let Some(ref id) = s.maybe_id {481 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);482 Lookup::<T>::insert(id, (wake, wake_index as u32));483 }484 Agenda::<T>::append(wake, Some(s));485 }486 }487 0488 489 }490 }491492 #[pallet::call]493 impl<T: Config> Pallet<T> {494 495 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]496 pub fn schedule_named(497 origin: OriginFor<T>,498 id: ScheduledId,499 when: T::BlockNumber,500 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,501 priority: schedule::Priority,502 call: Box<CallOrHashOf<T>>,503 ) -> DispatchResult {504 T::ScheduleOrigin::ensure_origin(origin.clone())?;505 let origin = <T as Config>::Origin::from(origin);506 Self::do_schedule_named(507 id,508 DispatchTime::At(when),509 maybe_periodic,510 priority,511 origin.caller().clone(),512 *call,513 )?;514 Ok(())515 }516517 518 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]519 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {520 T::ScheduleOrigin::ensure_origin(origin.clone())?;521 let origin = <T as Config>::Origin::from(origin);522 Self::do_cancel_named(Some(origin.caller().clone()), id)?;523 Ok(())524 }525526 527 528 529 530 531 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]532 pub fn schedule_named_after(533 origin: OriginFor<T>,534 id: ScheduledId,535 after: T::BlockNumber,536 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,537 priority: schedule::Priority,538 call: Box<CallOrHashOf<T>>,539 ) -> DispatchResult {540 T::ScheduleOrigin::ensure_origin(origin.clone())?;541 let origin = <T as Config>::Origin::from(origin);542 Self::do_schedule_named(543 id,544 DispatchTime::After(after),545 maybe_periodic,546 priority,547 origin.caller().clone(),548 *call,549 )?;550 Ok(())551 }552 }553}554555impl<T: Config> Pallet<T> {556 #[cfg(feature = "try-runtime")]557 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {558 Ok(())559 }560561 #[cfg(feature = "try-runtime")]562 pub fn post_migrate_to_v3() -> Result<(), &'static str> {563 use frame_support::dispatch::GetStorageVersion;564565 assert!(Self::current_storage_version() == 3);566 for k in Agenda::<T>::iter_keys() {567 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;568 }569 Ok(())570 }571572 573 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {574 Agenda::<T>::translate::<575 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,576 _,577 >(|_, agenda| {578 Some(579 agenda580 .into_iter()581 .map(|schedule| {582 schedule.map(|schedule| Scheduled {583 maybe_id: schedule.maybe_id,584 priority: schedule.priority,585 call: schedule.call,586 maybe_periodic: schedule.maybe_periodic,587 origin: schedule.origin.into(),588 _phantom: Default::default(),589 })590 })591 .collect::<Vec<_>>(),592 )593 });594 }595596 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {597 let now = frame_system::Pallet::<T>::block_number();598599 let when = match when {600 DispatchTime::At(x) => x,601 602 603 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),604 };605606 if when <= now {607 return Err(Error::<T>::TargetBlockNumberInPast.into());608 }609610 Ok(when)611 }612613 fn do_schedule(614 when: DispatchTime<T::BlockNumber>,615 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,616 priority: schedule::Priority,617 origin: T::PalletsOrigin,618 call: CallOrHashOf<T>,619 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {620 let when = Self::resolve_time(when)?;621 call.ensure_requested::<T::PreimageProvider>();622623 624 let maybe_periodic = maybe_periodic625 .filter(|p| p.1 > 1 && !p.0.is_zero())626 627 .map(|(p, c)| (p, c - 1));628 let s = Some(Scheduled {629 maybe_id: None,630 priority,631 call,632 maybe_periodic,633 origin,634 _phantom: PhantomData::<T::AccountId>::default(),635 });636 Agenda::<T>::append(when, s);637 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;638 Self::deposit_event(Event::Scheduled { when, index });639640 Ok((when, index))641 }642643 fn do_cancel(644 origin: Option<T::PalletsOrigin>,645 (when, index): TaskAddress<T::BlockNumber>,646 ) -> Result<(), DispatchError> {647 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {648 agenda.get_mut(index as usize).map_or(649 Ok(None),650 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {651 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {652 if matches!(653 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),654 Some(Ordering::Less) | None655 ) {656 return Err(BadOrigin.into());657 }658 };659 Ok(s.take())660 },661 )662 })?;663 if let Some(s) = scheduled {664 s.call.ensure_unrequested::<T::PreimageProvider>();665 if let Some(id) = s.maybe_id {666 Lookup::<T>::remove(id);667 }668 Self::deposit_event(Event::Canceled { when, index });669 Ok(())670 } else {671 Err(Error::<T>::NotFound)?672 }673 }674675 fn do_reschedule(676 (when, index): TaskAddress<T::BlockNumber>,677 new_time: DispatchTime<T::BlockNumber>,678 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {679 let new_time = Self::resolve_time(new_time)?;680681 if new_time == when {682 return Err(Error::<T>::RescheduleNoChange.into());683 }684685 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {686 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;687 let task = task.take().ok_or(Error::<T>::NotFound)?;688 Agenda::<T>::append(new_time, Some(task));689 Ok(())690 })?;691692 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;693 Self::deposit_event(Event::Canceled { when, index });694 Self::deposit_event(Event::Scheduled {695 when: new_time,696 index: new_index,697 });698699 Ok((new_time, new_index))700 }701702 fn do_schedule_named(703 id: ScheduledId,704 when: DispatchTime<T::BlockNumber>,705 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,706 priority: schedule::Priority,707 origin: T::PalletsOrigin,708 call: CallOrHashOf<T>,709 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {710 711 if Lookup::<T>::contains_key(&id) {712 return Err(Error::<T>::FailedToSchedule)?;713 }714715 let when = Self::resolve_time(when)?;716717 call.ensure_requested::<T::PreimageProvider>();718719 720 let maybe_periodic = maybe_periodic721 .filter(|p| p.1 > 1 && !p.0.is_zero())722 723 .map(|(p, c)| (p, c - 1));724725 let s = Scheduled {726 maybe_id: Some(id.clone()),727 priority,728 call: call.clone(),729 maybe_periodic,730 origin: origin.clone(),731 _phantom: Default::default(),732 };733734 735 736 737 738 739 740 741 742 743 744 745 746 747748 Agenda::<T>::append(when, Some(s));749 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;750 let address = (when, index);751 Lookup::<T>::insert(&id, &address);752 Self::deposit_event(Event::Scheduled { when, index });753754 Ok(address)755 }756757 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {758 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {759 if let Some((when, index)) = lookup.take() {760 let i = index as usize;761 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {762 if let Some(s) = agenda.get_mut(i) {763 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {764 if matches!(765 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),766 Some(Ordering::Less) | None767 ) {768 return Err(BadOrigin.into());769 }770 771 772 773 774 775 776 777 778779 s.call.ensure_unrequested::<T::PreimageProvider>();780 }781 *s = None;782 }783 Ok(())784 })?;785786 Self::deposit_event(Event::Canceled { when, index });787 Ok(())788 } else {789 Err(Error::<T>::NotFound)?790 }791 })792 }793794 fn do_reschedule_named(795 id: ScheduledId,796 new_time: DispatchTime<T::BlockNumber>,797 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {798 let new_time = Self::resolve_time(new_time)?;799800 Lookup::<T>::try_mutate_exists(801 id,802 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {803 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;804805 if new_time == when {806 return Err(Error::<T>::RescheduleNoChange.into());807 }808809 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {810 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;811 let task = task.take().ok_or(Error::<T>::NotFound)?;812 Agenda::<T>::append(new_time, Some(task));813814 Ok(())815 })?;816817 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;818 Self::deposit_event(Event::Canceled { when, index });819 Self::deposit_event(Event::Scheduled {820 when: new_time,821 index: new_index,822 });823824 *lookup = Some((new_time, new_index));825826 Ok((new_time, new_index))827 },828 )829 }830}831832impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>833 for Pallet<T>834{835 type Address = TaskAddress<T::BlockNumber>;836 type Hash = T::Hash;837838 fn schedule(839 when: DispatchTime<T::BlockNumber>,840 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,841 priority: schedule::Priority,842 origin: T::PalletsOrigin,843 call: CallOrHashOf<T>,844 ) -> Result<Self::Address, DispatchError> {845 Self::do_schedule(when, maybe_periodic, priority, origin, call)846 }847848 fn cancel((when, index): Self::Address) -> Result<(), ()> {849 Self::do_cancel(None, (when, index)).map_err(|_| ())850 }851852 fn reschedule(853 address: Self::Address,854 when: DispatchTime<T::BlockNumber>,855 ) -> Result<Self::Address, DispatchError> {856 Self::do_reschedule(address, when)857 }858859 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {860 Agenda::<T>::get(when)861 .get(index as usize)862 .ok_or(())863 .map(|_| when)864 }865}866867impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>868 for Pallet<T>869{870 type Address = TaskAddress<T::BlockNumber>;871 type Hash = T::Hash;872873 fn schedule_named(874 id: Vec<u8>,875 when: DispatchTime<T::BlockNumber>,876 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,877 priority: schedule::Priority,878 origin: T::PalletsOrigin,879 call: CallOrHashOf<T>,880 ) -> Result<Self::Address, ()> {881 let inner_id: ScheduledId = id882 .try_into()883 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);884 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)885 .map_err(|_| ())886 }887888 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {889 let inner_id: ScheduledId = id890 .try_into()891 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);892 Self::do_cancel_named(None, inner_id).map_err(|_| ())893 }894895 fn reschedule_named(896 id: Vec<u8>,897 when: DispatchTime<T::BlockNumber>,898 ) -> Result<Self::Address, DispatchError> {899 let inner_id: ScheduledId = id900 .try_into()901 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);902 Self::do_reschedule_named(inner_id, when)903 }904905 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {906 let inner_id: ScheduledId = id907 .try_into()908 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);909 Lookup::<T>::get(inner_id)910 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))911 .ok_or(())912 }913}