123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051#![cfg_attr(not(feature = "std"), no_std)]5253#[cfg(feature = "runtime-benchmarks")]54mod benchmarking;5556pub mod weights;5758use codec::{Codec, Decode, Encode};59use frame_support::{60 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter},61 traits::{62 schedule::{self, DispatchTime, MaybeHashed},63 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,64 StorageVersion,65 },66 weights::{GetDispatchInfo, Weight},67};68use frame_system::{self as system, ensure_signed};69pub use pallet::*;70use scale_info::TypeInfo;71use sp_runtime::{72 traits::{BadOrigin, One, Saturating, Zero},73 RuntimeDebug, DispatchErrorWithPostInfo,74};75use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};76use sp_core::H160;77pub use weights::WeightInfo;787980pub type PeriodicIndex = u32;8182pub type TaskAddress<BlockNumber> = (BlockNumber, u32);83pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;8485type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];86pub type CallOrHashOf<T> = MaybeHashed<<T as Config>::Call, <T as frame_system::Config>::Hash>;878889#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]90#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]91pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {92 93 maybe_id: Option<ScheduledId>,94 95 priority: schedule::Priority,96 97 call: Call,98 99 maybe_periodic: Option<schedule::Period<BlockNumber>>,100 101 origin: PalletsOrigin,102 _phantom: PhantomData<AccountId>,103}104105pub type ScheduledV3Of<T> = ScheduledV3<106 CallOrHashOf<T>,107 <T as frame_system::Config>::BlockNumber,108 <T as Config>::PalletsOrigin,109 <T as frame_system::Config>::AccountId,110>;111112pub type ScheduledOf<T> = ScheduledV3Of<T>;113114115pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =116 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;117118#[cfg(feature = "runtime-benchmarks")]119mod preimage_provider {120 use frame_support::traits::PreimageRecipient;121 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}122 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}123}124125#[cfg(not(feature = "runtime-benchmarks"))]126mod preimage_provider {127 use frame_support::traits::PreimageProvider;128 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}129 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}130}131132pub use preimage_provider::PreimageProviderAndMaybeRecipient;133134pub(crate) trait MarginalWeightInfo: WeightInfo {135 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {136 match (periodic, named, resolved) {137 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),138 (_, true, None) => {139 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)140 }141 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),142 (false, true, Some(false)) => {143 Self::on_initialize_named(2) - Self::on_initialize_named(1)144 }145 (true, false, Some(false)) => {146 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)147 }148 (true, true, Some(false)) => {149 Self::on_initialize_periodic_named(2) - Self::on_initialize_periodic_named(1)150 }151 (false, false, Some(true)) => {152 Self::on_initialize_resolved(2) - Self::on_initialize_resolved(1)153 }154 (false, true, Some(true)) => {155 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)156 }157 (true, false, Some(true)) => {158 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)159 }160 (true, true, Some(true)) => {161 Self::on_initialize_periodic_named_resolved(2)162 - Self::on_initialize_periodic_named_resolved(1)163 }164 }165 }166}167impl<T: WeightInfo> MarginalWeightInfo for T {}168169#[frame_support::pallet]170pub mod pallet {171 use super::*;172 use frame_support::{173 dispatch::PostDispatchInfo,174 pallet_prelude::*,175 traits::{schedule::LookupError, PreimageProvider},176 };177 use frame_system::pallet_prelude::*;178179 180 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);181182 #[pallet::pallet]183 #[pallet::generate_store(pub(super) trait Store)]184 #[pallet::storage_version(STORAGE_VERSION)]185 #[pallet::without_storage_info]186 pub struct Pallet<T>(_);187188 189 #[pallet::config]190 pub trait Config: frame_system::Config {191 192 type Event: From<Event<Self>> + IsType<<Self as frame_system::Config>::Event>;193194 195 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>196 + From<Self::PalletsOrigin>197 + IsType<<Self as system::Config>::Origin>;198199 200 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;201202 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;203204 205 type Call: Parameter206 + Dispatchable<Origin = <Self as Config>::Origin, PostInfo = PostDispatchInfo>207 + GetDispatchInfo208 + From<system::Call<Self>>;209210 211 212 #[pallet::constant]213 type MaximumWeight: Get<Weight>;214215 216 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;217218 219 220 221 222 223 224 225 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;226227 228 229 #[pallet::constant]230 type MaxScheduledPerBlock: Get<u32>;231232 233 type WeightInfo: WeightInfo;234235 236 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;237238 239 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;240241 242 243244 245 type CallExecutor: DispatchCall<Self, H160>;246 }247248 249 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {250 fn reserve_balance(251 id: ScheduledId,252 sponsor: <T as frame_system::Config>::AccountId,253 call: <T as Config>::Call,254 count: u32,255 ) -> Result<(), DispatchError>;256257 fn pay_for_call(258 id: ScheduledId,259 sponsor: <T as frame_system::Config>::AccountId,260 call: <T as Config>::Call,261 ) -> Result<u128, DispatchError>;262263 264 fn dispatch_call(265 signer: T::AccountId,266 function: <T as Config>::Call,267 ) -> Result<268 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,269 TransactionValidityError,270 >;271272 fn cancel_reserve(273 id: ScheduledId,274 sponsor: <T as frame_system::Config>::AccountId,275 ) -> Result<u128, DispatchError>;276 }277278 279 #[pallet::storage]280 pub type Agenda<T: Config> =281 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;282283 284 #[pallet::storage]285 pub(crate) type Lookup<T: Config> =286 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;287288 289 #[pallet::event]290 #[pallet::generate_deposit(pub(super) fn deposit_event)]291 pub enum Event<T: Config> {292 293 Scheduled { when: T::BlockNumber, index: u32 },294 295 Canceled { when: T::BlockNumber, index: u32 },296 297 Dispatched {298 task: TaskAddress<T::BlockNumber>,299 id: Option<ScheduledId>,300 result: DispatchResult,301 },302 303 CallLookupFailed {304 task: TaskAddress<T::BlockNumber>,305 id: Option<ScheduledId>,306 error: LookupError,307 },308 }309310 #[pallet::error]311 pub enum Error<T> {312 313 FailedToSchedule,314 315 NotFound,316 317 TargetBlockNumberInPast,318 319 RescheduleNoChange,320 }321322 #[pallet::hooks]323 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {324 325 fn on_initialize(now: T::BlockNumber) -> Weight {326 let limit = T::MaximumWeight::get();327328 let mut queued = Agenda::<T>::take(now)329 .into_iter()330 .enumerate()331 .filter_map(|(index, s)| Some((index as u32, s?)))332 .collect::<Vec<_>>();333334 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {335 log::warn!(336 target: "runtime::scheduler",337 "Warning: This block has more items queued in Scheduler than \338 expected from the runtime configuration. An update might be needed."339 );340 }341342 queued.sort_by_key(|(_, s)| s.priority);343344 let next = now + One::one();345346 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);347 for (order, (index, mut s)) in queued.into_iter().enumerate() {348 let named = if let Some(ref id) = s.maybe_id {349 Lookup::<T>::remove(id);350 true351 } else {352 false353 };354355 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();356 s.call = call;357358 let resolved = if let Some(completed) = maybe_completed {359 T::PreimageProvider::unrequest_preimage(&completed);360 true361 } else {362 false363 };364365 let call = match s.call.as_value().cloned() {366 Some(c) => c,367 None => {368 369 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));370 if let Some(delay) = T::NoPreimagePostponement::get() {371 let until = now.saturating_add(delay);372 if let Some(ref id) = s.maybe_id {373 let index = Agenda::<T>::decode_len(until).unwrap_or(0);374 Lookup::<T>::insert(id, (until, index as u32));375 }376 Agenda::<T>::append(until, Some(s));377 }378 continue;379 }380 };381382 let periodic = s.maybe_periodic.is_some();383 let call_weight = call.get_dispatch_info().weight;384 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));385 let origin =386 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())387 .into();388 if ensure_signed(origin).is_ok() {389 390 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));391 }392393 394 395 396 397 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;398 let test_weight = total_weight399 .saturating_add(call_weight)400 .saturating_add(item_weight);401 if !hard_deadline && order > 0 && test_weight > limit {402 403 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));404 if let Some(ref id) = s.maybe_id {405 406 407 408 409 let index = Agenda::<T>::decode_len(next).unwrap_or(0);410 Lookup::<T>::insert(id, (next, index as u32));411 }412 Agenda::<T>::append(next, Some(s));413 continue;414 }415416 let sender = ensure_signed(417 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone())418 .into(),419 )420 .unwrap();421422 423 if s.maybe_id.is_some() && s.maybe_periodic.is_some() {424 let _ = T::CallExecutor::pay_for_call(425 s.maybe_id.unwrap(),426 sender.clone(),427 call.clone(),428 );429 }430431 let r = T::CallExecutor::dispatch_call(sender, call.clone());432433 let mut actual_call_weight: Weight = item_weight; 434 let result: Result<_, DispatchError> = match r {435 Ok(o) => match o {436 Ok(di) => {437 actual_call_weight = di.actual_weight.unwrap_or(item_weight);438 Ok(())439 }440 Err(err) => Err(err.error),441 },442 Err(_) => {443 log::info!(444 target: "runtime::scheduler",445 "Warning: Scheduler has failed to execute a post-dispatch transaction. \446 This block might have become invalid.");447 Err(DispatchError::CannotLookup)448 } 449 };450451 total_weight.saturating_accrue(item_weight);452 total_weight.saturating_accrue(actual_call_weight);453454 Self::deposit_event(Event::Dispatched {455 task: (now, index),456 id: s.maybe_id.clone(),457 result,458 });459460 if let &Some((period, count)) = &s.maybe_periodic {461 if count > 1 {462 s.maybe_periodic = Some((period, count - 1));463 } else {464 s.maybe_periodic = None;465 }466 let wake = now + period;467 468 if let Some(ref id) = s.maybe_id {469 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);470 Lookup::<T>::insert(id, (wake, wake_index as u32));471 }472 Agenda::<T>::append(wake, Some(s));473 }474 }475 total_weight476 }477 }478479 #[pallet::call]480 impl<T: Config> Pallet<T> {481 482 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]483 pub fn schedule(484 origin: OriginFor<T>,485 when: T::BlockNumber,486 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,487 priority: schedule::Priority,488 call: Box<CallOrHashOf<T>>,489 ) -> DispatchResult {490 T::ScheduleOrigin::ensure_origin(origin.clone())?;491 let origin = <T as Config>::Origin::from(origin);492 Self::do_schedule(493 DispatchTime::At(when),494 maybe_periodic,495 priority,496 origin.caller().clone(),497 *call,498 )?;499 Ok(())500 }501502 503 #[pallet::weight(<T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get()))]504 pub fn cancel(origin: OriginFor<T>, when: T::BlockNumber, index: u32) -> DispatchResult {505 T::ScheduleOrigin::ensure_origin(origin.clone())?;506 let origin = <T as Config>::Origin::from(origin);507 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;508 Ok(())509 }510511 512 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]513 pub fn schedule_named(514 origin: OriginFor<T>,515 id: ScheduledId,516 when: T::BlockNumber,517 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,518 priority: schedule::Priority,519 call: Box<CallOrHashOf<T>>,520 ) -> DispatchResult {521 T::ScheduleOrigin::ensure_origin(origin.clone())?;522 let origin = <T as Config>::Origin::from(origin);523 Self::do_schedule_named(524 id,525 DispatchTime::At(when),526 maybe_periodic,527 priority,528 origin.caller().clone(),529 *call,530 )?;531 Ok(())532 }533534 535 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]536 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {537 T::ScheduleOrigin::ensure_origin(origin.clone())?;538 let origin = <T as Config>::Origin::from(origin);539 Self::do_cancel_named(Some(origin.caller().clone()), id)?;540 Ok(())541 }542543 544 545 546 547 548 #[pallet::weight(<T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get()))]549 pub fn schedule_after(550 origin: OriginFor<T>,551 after: T::BlockNumber,552 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,553 priority: schedule::Priority,554 call: Box<CallOrHashOf<T>>,555 ) -> DispatchResult {556 T::ScheduleOrigin::ensure_origin(origin.clone())?;557 let origin = <T as Config>::Origin::from(origin);558 Self::do_schedule(559 DispatchTime::After(after),560 maybe_periodic,561 priority,562 origin.caller().clone(),563 *call,564 )?;565 Ok(())566 }567568 569 570 571 572 573 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]574 pub fn schedule_named_after(575 origin: OriginFor<T>,576 id: ScheduledId,577 after: T::BlockNumber,578 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,579 priority: schedule::Priority,580 call: Box<CallOrHashOf<T>>,581 ) -> DispatchResult {582 T::ScheduleOrigin::ensure_origin(origin.clone())?;583 let origin = <T as Config>::Origin::from(origin);584 Self::do_schedule_named(585 id,586 DispatchTime::After(after),587 maybe_periodic,588 priority,589 origin.caller().clone(),590 *call,591 )?;592 Ok(())593 }594 }595}596597impl<T: Config> Pallet<T> {598 #[cfg(feature = "try-runtime")]599 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {600 Ok(())601 }602603 #[cfg(feature = "try-runtime")]604 pub fn post_migrate_to_v3() -> Result<(), &'static str> {605 use frame_support::dispatch::GetStorageVersion;606607 assert!(Self::current_storage_version() == 3);608 for k in Agenda::<T>::iter_keys() {609 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;610 }611 Ok(())612 }613614 615 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {616 Agenda::<T>::translate::<617 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,618 _,619 >(|_, agenda| {620 Some(621 agenda622 .into_iter()623 .map(|schedule| {624 schedule.map(|schedule| Scheduled {625 maybe_id: schedule.maybe_id,626 priority: schedule.priority,627 call: schedule.call,628 maybe_periodic: schedule.maybe_periodic,629 origin: schedule.origin.into(),630 _phantom: Default::default(),631 })632 })633 .collect::<Vec<_>>(),634 )635 });636 }637638 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {639 let now = frame_system::Pallet::<T>::block_number();640641 let when = match when {642 DispatchTime::At(x) => x,643 644 645 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),646 };647648 if when <= now {649 return Err(Error::<T>::TargetBlockNumberInPast.into());650 }651652 Ok(when)653 }654655 fn do_schedule(656 when: DispatchTime<T::BlockNumber>,657 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,658 priority: schedule::Priority,659 origin: T::PalletsOrigin,660 call: CallOrHashOf<T>,661 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {662 let when = Self::resolve_time(when)?;663 call.ensure_requested::<T::PreimageProvider>();664665 666 let maybe_periodic = maybe_periodic667 .filter(|p| p.1 > 1 && !p.0.is_zero())668 669 .map(|(p, c)| (p, c - 1));670 let s = Some(Scheduled {671 maybe_id: None,672 priority,673 call,674 maybe_periodic,675 origin,676 _phantom: PhantomData::<T::AccountId>::default(),677 });678 Agenda::<T>::append(when, s);679 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;680 Self::deposit_event(Event::Scheduled { when, index });681682 Ok((when, index))683 }684685 fn do_cancel(686 origin: Option<T::PalletsOrigin>,687 (when, index): TaskAddress<T::BlockNumber>,688 ) -> Result<(), DispatchError> {689 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {690 agenda.get_mut(index as usize).map_or(691 Ok(None),692 |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {693 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {694 if matches!(695 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),696 Some(Ordering::Less) | None697 ) {698 return Err(BadOrigin.into());699 }700 };701 Ok(s.take())702 },703 )704 })?;705 if let Some(s) = scheduled {706 s.call.ensure_unrequested::<T::PreimageProvider>();707 if let Some(id) = s.maybe_id {708 Lookup::<T>::remove(id);709 }710 Self::deposit_event(Event::Canceled { when, index });711 Ok(())712 } else {713 Err(Error::<T>::NotFound)?714 }715 }716717 fn do_reschedule(718 (when, index): TaskAddress<T::BlockNumber>,719 new_time: DispatchTime<T::BlockNumber>,720 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {721 let new_time = Self::resolve_time(new_time)?;722723 if new_time == when {724 return Err(Error::<T>::RescheduleNoChange.into());725 }726727 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {728 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;729 let task = task.take().ok_or(Error::<T>::NotFound)?;730 Agenda::<T>::append(new_time, Some(task));731 Ok(())732 })?;733734 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;735 Self::deposit_event(Event::Canceled { when, index });736 Self::deposit_event(Event::Scheduled {737 when: new_time,738 index: new_index,739 });740741 Ok((new_time, new_index))742 }743744 fn do_schedule_named(745 id: ScheduledId,746 when: DispatchTime<T::BlockNumber>,747 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,748 priority: schedule::Priority,749 origin: T::PalletsOrigin,750 call: CallOrHashOf<T>,751 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {752 753 if Lookup::<T>::contains_key(&id) {754 return Err(Error::<T>::FailedToSchedule)?;755 }756757 let when = Self::resolve_time(when)?;758759 call.ensure_requested::<T::PreimageProvider>();760761 762 let maybe_periodic = maybe_periodic763 .filter(|p| p.1 > 1 && !p.0.is_zero())764 765 .map(|(p, c)| (p, c - 1));766767 let s = Scheduled {768 maybe_id: Some(id.clone()),769 priority,770 call: call.clone(),771 maybe_periodic,772 origin: origin.clone(),773 _phantom: Default::default(),774 };775776 777 let sender =778 ensure_signed(<<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin).into())?;779 let repeats = match maybe_periodic {780 Some(p) => p.1,781 None => 0,782 };783 let _ = T::CallExecutor::reserve_balance(784 id.clone(),785 sender,786 call.as_value().unwrap().clone(),787 repeats,788 );789790 Agenda::<T>::append(when, Some(s));791 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;792 let address = (when, index);793 Lookup::<T>::insert(&id, &address);794 Self::deposit_event(Event::Scheduled { when, index });795796 Ok(address)797 }798799 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {800 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {801 if let Some((when, index)) = lookup.take() {802 let i = index as usize;803 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {804 if let Some(s) = agenda.get_mut(i) {805 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {806 if matches!(807 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),808 Some(Ordering::Less) | None809 ) {810 return Err(BadOrigin.into());811 }812 813 let sender = ensure_signed(814 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(815 origin.unwrap(),816 )817 .into(),818 )?;819 let _ = T::CallExecutor::cancel_reserve(id, sender);820821 s.call.ensure_unrequested::<T::PreimageProvider>();822 }823 *s = None;824 }825 Ok(())826 })?;827828 Self::deposit_event(Event::Canceled { when, index });829 Ok(())830 } else {831 Err(Error::<T>::NotFound)?832 }833 })834 }835836 fn do_reschedule_named(837 id: ScheduledId,838 new_time: DispatchTime<T::BlockNumber>,839 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {840 let new_time = Self::resolve_time(new_time)?;841842 Lookup::<T>::try_mutate_exists(843 id,844 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {845 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;846847 if new_time == when {848 return Err(Error::<T>::RescheduleNoChange.into());849 }850851 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {852 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;853 let task = task.take().ok_or(Error::<T>::NotFound)?;854 Agenda::<T>::append(new_time, Some(task));855856 Ok(())857 })?;858859 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;860 Self::deposit_event(Event::Canceled { when, index });861 Self::deposit_event(Event::Scheduled {862 when: new_time,863 index: new_index,864 });865866 *lookup = Some((new_time, new_index));867868 Ok((new_time, new_index))869 },870 )871 }872}873874impl<T: Config> schedule::v2::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>875 for Pallet<T>876{877 type Address = TaskAddress<T::BlockNumber>;878 type Hash = T::Hash;879880 fn schedule(881 when: DispatchTime<T::BlockNumber>,882 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,883 priority: schedule::Priority,884 origin: T::PalletsOrigin,885 call: CallOrHashOf<T>,886 ) -> Result<Self::Address, DispatchError> {887 Self::do_schedule(when, maybe_periodic, priority, origin, call)888 }889890 fn cancel((when, index): Self::Address) -> Result<(), ()> {891 Self::do_cancel(None, (when, index)).map_err(|_| ())892 }893894 fn reschedule(895 address: Self::Address,896 when: DispatchTime<T::BlockNumber>,897 ) -> Result<Self::Address, DispatchError> {898 Self::do_reschedule(address, when)899 }900901 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {902 Agenda::<T>::get(when)903 .get(index as usize)904 .ok_or(())905 .map(|_| when)906 }907}908909impl<T: Config> schedule::v2::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>910 for Pallet<T>911{912 type Address = TaskAddress<T::BlockNumber>;913 type Hash = T::Hash;914915 fn schedule_named(916 id: Vec<u8>,917 when: DispatchTime<T::BlockNumber>,918 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,919 priority: schedule::Priority,920 origin: T::PalletsOrigin,921 call: CallOrHashOf<T>,922 ) -> Result<Self::Address, ()> {923 let inner_id: ScheduledId = id924 .try_into()925 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);926 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call)927 .map_err(|_| ())928 }929930 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {931 let inner_id: ScheduledId = id932 .try_into()933 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);934 Self::do_cancel_named(None, inner_id).map_err(|_| ())935 }936937 fn reschedule_named(938 id: Vec<u8>,939 when: DispatchTime<T::BlockNumber>,940 ) -> Result<Self::Address, DispatchError> {941 let inner_id: ScheduledId = id942 .try_into()943 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);944 Self::do_reschedule_named(inner_id, when)945 }946947 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {948 let inner_id: ScheduledId = id949 .try_into()950 .unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);951 Lookup::<T>::get(inner_id)952 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))953 .ok_or(())954 }955}