12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970#![cfg_attr(not(feature = "std"), no_std)]7172#[cfg(feature = "runtime-benchmarks")]73mod benchmarking;7475pub mod weights;7677use sp_core::H160;78use codec::{Codec, Decode, Encode};79use frame_system::{self as system, ensure_signed};80pub use pallet::*;81use scale_info::TypeInfo;82use sp_runtime::{83 traits::{BadOrigin, One, Saturating, Zero},84 RuntimeDebug, DispatchErrorWithPostInfo,85};86use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*};8788use frame_support::{89 dispatch::{DispatchError, DispatchResult, Dispatchable, Parameter, GetDispatchInfo},90 traits::{91 schedule::{self, DispatchTime, MaybeHashed},92 NamedReservableCurrency, EnsureOrigin, Get, IsType, OriginTrait, PrivilegeCmp,93 StorageVersion,94 },95 weights::{Weight},96};9798pub use weights::WeightInfo;99100101pub type TaskAddress<BlockNumber> = (BlockNumber, u32);102pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;103104type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];105pub type CallOrHashOf<T> =106 MaybeHashed<<T as Config>::RuntimeCall, <T as frame_system::Config>::Hash>;107108109#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]110#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]111pub struct ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId> {112 113 maybe_id: Option<ScheduledId>,114 115 priority: schedule::Priority,116 117 call: Call,118 119 maybe_periodic: Option<schedule::Period<BlockNumber>>,120 121 origin: PalletsOrigin,122 _phantom: PhantomData<AccountId>,123}124125pub type ScheduledV3Of<T> = ScheduledV3<126 CallOrHashOf<T>,127 <T as frame_system::Config>::BlockNumber,128 <T as Config>::PalletsOrigin,129 <T as frame_system::Config>::AccountId,130>;131132pub type ScheduledOf<T> = ScheduledV3Of<T>;133134135pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> =136 ScheduledV3<Call, BlockNumber, PalletsOrigin, AccountId>;137138#[cfg(feature = "runtime-benchmarks")]139mod preimage_provider {140 use frame_support::traits::PreimageRecipient;141 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageRecipient<H> {}142 impl<H, T: PreimageRecipient<H>> PreimageProviderAndMaybeRecipient<H> for T {}143}144145#[cfg(not(feature = "runtime-benchmarks"))]146mod preimage_provider {147 use frame_support::traits::PreimageProvider;148 pub trait PreimageProviderAndMaybeRecipient<H>: PreimageProvider<H> {}149 impl<H, T: PreimageProvider<H>> PreimageProviderAndMaybeRecipient<H> for T {}150}151152pub use preimage_provider::PreimageProviderAndMaybeRecipient;153154pub(crate) trait MarginalWeightInfo: WeightInfo {155 fn item(periodic: bool, named: bool, resolved: Option<bool>) -> Weight {156 match (periodic, named, resolved) {157 (_, false, None) => Self::on_initialize_aborted(2) - Self::on_initialize_aborted(1),158 (_, true, None) => {159 Self::on_initialize_named_aborted(2) - Self::on_initialize_named_aborted(1)160 }161 (false, false, Some(false)) => Self::on_initialize(2) - Self::on_initialize(1),162 (false, true, Some(false)) => {163 Self::on_initialize_named(2) - Self::on_initialize_named(1)164 }165 (true, false, Some(false)) => {166 Self::on_initialize_periodic(2) - Self::on_initialize_periodic(1)167 }168 (true, true, Some(false)) => {169 Self::on_initialize_periodic_named_resolved(2)170 - Self::on_initialize_periodic_named_resolved(1)171 }172 (false, false, Some(true)) => Self::on_initialize(2) - Self::on_initialize(1),173 (false, true, Some(true)) => {174 Self::on_initialize_named_resolved(2) - Self::on_initialize_named_resolved(1)175 }176 (true, false, Some(true)) => {177 Self::on_initialize_periodic_resolved(2) - Self::on_initialize_periodic_resolved(1)178 }179 (true, true, Some(true)) => {180 Self::on_initialize_periodic_named_resolved(2)181 - Self::on_initialize_periodic_named_resolved(1)182 }183 }184 }185}186impl<T: WeightInfo> MarginalWeightInfo for T {}187188#[frame_support::pallet]189pub mod pallet {190 use super::*;191 use frame_support::{192 dispatch::PostDispatchInfo,193 pallet_prelude::*,194 traits::{schedule::LookupError, PreimageProvider},195 };196 use frame_system::pallet_prelude::*;197198 199 const STORAGE_VERSION: StorageVersion = StorageVersion::new(3);200201 #[pallet::pallet]202 #[pallet::generate_store(pub(super) trait Store)]203 #[pallet::storage_version(STORAGE_VERSION)]204 #[pallet::without_storage_info]205 pub struct Pallet<T>(_);206207 208 #[pallet::config]209 pub trait Config: frame_system::Config {210 211 type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;212213 214 type RuntimeOrigin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>215 + From<Self::PalletsOrigin>216 + IsType<<Self as system::Config>::RuntimeOrigin>;217218 219 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq + TypeInfo;220221 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;222223 224 type RuntimeCall: Parameter225 + Dispatchable<226 RuntimeOrigin = <Self as Config>::RuntimeOrigin,227 PostInfo = PostDispatchInfo,228 > + GetDispatchInfo229 + From<system::Call<Self>>;230231 232 233 #[pallet::constant]234 type MaximumWeight: Get<Weight>;235236 237 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::RuntimeOrigin>;238239 240 241 242 243 244 245 246 type OriginPrivilegeCmp: PrivilegeCmp<Self::PalletsOrigin>;247248 249 250 #[pallet::constant]251 type MaxScheduledPerBlock: Get<u32>;252253 254 type WeightInfo: WeightInfo;255256 257 type PreimageProvider: PreimageProviderAndMaybeRecipient<Self::Hash>;258259 260 type NoPreimagePostponement: Get<Option<Self::BlockNumber>>;261262 263 264265 266 type CallExecutor: DispatchCall<Self, H160>;267 }268269 270 pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {271 272 fn reserve_balance(273 id: ScheduledId,274 sponsor: <T as frame_system::Config>::AccountId,275 call: <T as Config>::RuntimeCall,276 count: u32,277 ) -> Result<(), DispatchError>;278279 280 fn pay_for_call(281 id: ScheduledId,282 sponsor: <T as frame_system::Config>::AccountId,283 call: <T as Config>::RuntimeCall,284 ) -> Result<u128, DispatchError>;285286 287 fn dispatch_call(288 signer: T::AccountId,289 function: <T as Config>::RuntimeCall,290 ) -> Result<291 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,292 TransactionValidityError,293 >;294295 296 fn cancel_reserve(297 id: ScheduledId,298 sponsor: <T as frame_system::Config>::AccountId,299 ) -> Result<u128, DispatchError>;300 }301302 303 #[pallet::storage]304 pub type Agenda<T: Config> =305 StorageMap<_, Twox64Concat, T::BlockNumber, Vec<Option<ScheduledV3Of<T>>>, ValueQuery>;306307 308 #[pallet::storage]309 pub(crate) type Lookup<T: Config> =310 StorageMap<_, Twox64Concat, ScheduledId, TaskAddress<T::BlockNumber>>;311312 313 #[pallet::event]314 #[pallet::generate_deposit(pub(super) fn deposit_event)]315 pub enum Event<T: Config> {316 317 Scheduled { when: T::BlockNumber, index: u32 },318 319 Canceled { when: T::BlockNumber, index: u32 },320 321 Dispatched {322 task: TaskAddress<T::BlockNumber>,323 id: Option<ScheduledId>,324 result: DispatchResult,325 },326 327 CallLookupFailed {328 task: TaskAddress<T::BlockNumber>,329 id: Option<ScheduledId>,330 error: LookupError,331 },332 }333334 #[pallet::error]335 pub enum Error<T> {336 337 FailedToSchedule,338 339 NotFound,340 341 TargetBlockNumberInPast,342 343 RescheduleNoChange,344 }345346 #[pallet::hooks]347 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {348 349 fn on_initialize(now: T::BlockNumber) -> Weight {350 let limit = T::MaximumWeight::get();351352 let mut queued = Agenda::<T>::take(now)353 .into_iter()354 .enumerate()355 .filter_map(|(index, s)| Some((index as u32, s?)))356 .collect::<Vec<_>>();357358 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {359 log::warn!(360 target: "runtime::scheduler",361 "Warning: This block has more items queued in Scheduler than \362 expected from the runtime configuration. An update might be needed."363 );364 }365366 queued.sort_by_key(|(_, s)| s.priority);367368 let next = now + One::one();369370 let mut total_weight: Weight = T::WeightInfo::on_initialize(0);371 for (order, (index, mut s)) in queued.into_iter().enumerate() {372 let named = if let Some(ref id) = s.maybe_id {373 Lookup::<T>::remove(id);374 true375 } else {376 false377 };378379 let (call, maybe_completed) = s.call.resolved::<T::PreimageProvider>();380 s.call = call;381382 let resolved = if let Some(completed) = maybe_completed {383 T::PreimageProvider::unrequest_preimage(&completed);384 true385 } else {386 false387 };388 let call = match s.call.as_value().cloned() {389 Some(c) => c,390 None => {391 392 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));393 if let Some(delay) = T::NoPreimagePostponement::get() {394 let until = now.saturating_add(delay);395 if let Some(ref id) = s.maybe_id {396 let index = Agenda::<T>::decode_len(until).unwrap_or(0);397 Lookup::<T>::insert(id, (until, index as u32));398 }399 Agenda::<T>::append(until, Some(s));400 }401 continue;402 }403 };404405 let periodic = s.maybe_periodic.is_some();406 let call_weight = call.get_dispatch_info().weight;407 let mut item_weight = T::WeightInfo::item(periodic, named, Some(resolved));408 let origin = <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(409 s.origin.clone(),410 )411 .into();412 if ensure_signed(origin).is_ok() {413 414 item_weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));415 }416417 418 419 420 421 let hard_deadline = s.priority <= schedule::HARD_DEADLINE;422 let test_weight = total_weight423 .saturating_add(call_weight)424 .saturating_add(item_weight);425 if !hard_deadline && order > 0 && test_weight.all_gt(limit) {426 427 total_weight.saturating_accrue(T::WeightInfo::item(false, named, None));428 if let Some(ref id) = s.maybe_id {429 430 431 432 433 let index = Agenda::<T>::decode_len(next).unwrap_or(0);434 Lookup::<T>::insert(id, (next, index as u32));435 }436 Agenda::<T>::append(next, Some(s));437 continue;438 }439440 let sender = ensure_signed(441 <<T as Config>::RuntimeOrigin as From<T::PalletsOrigin>>::from(442 s.origin.clone(),443 )444 .into(),445 )446 .unwrap();447448 449 450 451 452 453 454 455 456457 458 459 let r = T::CallExecutor::dispatch_call(sender, call.clone());460461 let mut actual_call_weight: Weight = item_weight;462 let result: Result<_, DispatchError> = match r {463 Ok(o) => match o {464 Ok(di) => {465 actual_call_weight = di.actual_weight.unwrap_or(item_weight);466 Ok(())467 }468 Err(err) => Err(err.error),469 },470 Err(_) => {471 log::error!(472 target: "runtime::scheduler",473 "Warning: Scheduler has failed to execute a post-dispatch transaction. \474 This block might have become invalid.");475 Err(DispatchError::CannotLookup)476 } 477 };478479 total_weight.saturating_accrue(item_weight);480 total_weight.saturating_accrue(actual_call_weight);481482 Self::deposit_event(Event::Dispatched {483 task: (now, index),484 id: s.maybe_id.clone(),485 result,486 });487488 if let &Some((period, count)) = &s.maybe_periodic {489 if count > 1 {490 s.maybe_periodic = Some((period, count - 1));491 } else {492 s.maybe_periodic = None;493 }494 let wake = now + period;495 496 if let Some(ref id) = s.maybe_id {497 let wake_index = Agenda::<T>::decode_len(wake).unwrap_or(0);498 Lookup::<T>::insert(id, (wake, wake_index as u32));499 }500 Agenda::<T>::append(wake, Some(s));501 }502 }503 504 Weight::zero()505 }506 }507508 #[pallet::call]509 impl<T: Config> Pallet<T> {510 511 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]512 pub fn schedule_named(513 origin: OriginFor<T>,514 id: ScheduledId,515 when: T::BlockNumber,516 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,517 priority: schedule::Priority,518 call: Box<CallOrHashOf<T>>,519 ) -> DispatchResult {520 T::ScheduleOrigin::ensure_origin(origin.clone())?;521 let origin = <T as Config>::RuntimeOrigin::from(origin);522 Self::do_schedule_named(523 id,524 DispatchTime::At(when),525 maybe_periodic,526 priority,527 origin.caller().clone(),528 *call,529 )?;530 Ok(())531 }532533 534 #[pallet::weight(<T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get()))]535 pub fn cancel_named(origin: OriginFor<T>, id: ScheduledId) -> DispatchResult {536 T::ScheduleOrigin::ensure_origin(origin.clone())?;537 let origin = <T as Config>::RuntimeOrigin::from(origin);538 Self::do_cancel_named(Some(origin.caller().clone()), id)?;539 Ok(())540 }541542 543 544 545 546 547 #[pallet::weight(<T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get()))]548 pub fn schedule_named_after(549 origin: OriginFor<T>,550 id: ScheduledId,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>::RuntimeOrigin::from(origin);558 Self::do_schedule_named(559 id,560 DispatchTime::After(after),561 maybe_periodic,562 priority,563 origin.caller().clone(),564 *call,565 )?;566 Ok(())567 }568 }569}570571impl<T: Config> Pallet<T> {572 #[cfg(feature = "try-runtime")]573 pub fn pre_migrate_to_v3() -> Result<(), &'static str> {574 Ok(())575 }576577 #[cfg(feature = "try-runtime")]578 pub fn post_migrate_to_v3() -> Result<(), &'static str> {579 use frame_support::dispatch::GetStorageVersion;580581 assert!(Self::current_storage_version() == 3);582 for k in Agenda::<T>::iter_keys() {583 let _ = Agenda::<T>::try_get(k).map_err(|()| "Invalid item in Agenda")?;584 }585 Ok(())586 }587588 589 pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {590 Agenda::<T>::translate::<591 Vec<Option<Scheduled<CallOrHashOf<T>, T::BlockNumber, OldOrigin, T::AccountId>>>,592 _,593 >(|_, agenda| {594 Some(595 agenda596 .into_iter()597 .map(|schedule| {598 schedule.map(|schedule| Scheduled {599 maybe_id: schedule.maybe_id,600 priority: schedule.priority,601 call: schedule.call,602 maybe_periodic: schedule.maybe_periodic,603 origin: schedule.origin.into(),604 _phantom: Default::default(),605 })606 })607 .collect::<Vec<_>>(),608 )609 });610 }611612 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {613 let now = frame_system::Pallet::<T>::block_number();614615 let when = match when {616 DispatchTime::At(x) => x,617 618 619 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),620 };621622 if when <= now {623 return Err(Error::<T>::TargetBlockNumberInPast.into());624 }625626 Ok(when)627 }628629 fn do_schedule_named(630 id: ScheduledId,631 when: DispatchTime<T::BlockNumber>,632 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,633 priority: schedule::Priority,634 origin: T::PalletsOrigin,635 call: CallOrHashOf<T>,636 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {637 638 if Lookup::<T>::contains_key(&id) {639 return Err(Error::<T>::FailedToSchedule)?;640 }641642 let when = Self::resolve_time(when)?;643644 call.ensure_requested::<T::PreimageProvider>();645646 647 let maybe_periodic = maybe_periodic648 .filter(|p| p.1 > 1 && !p.0.is_zero())649 650 .map(|(p, c)| (p, c - 1));651652 let s = Scheduled {653 maybe_id: Some(id.clone()),654 priority,655 call: call.clone(),656 maybe_periodic,657 origin: origin.clone(),658 _phantom: Default::default(),659 };660661 662 663 664 665 666 667 668 669 670 671 672 673 674675 Agenda::<T>::append(when, Some(s));676 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;677 let address = (when, index);678 Lookup::<T>::insert(&id, &address);679 Self::deposit_event(Event::Scheduled { when, index });680681 Ok(address)682 }683684 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {685 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {686 if let Some((when, index)) = lookup.take() {687 let i = index as usize;688 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {689 if let Some(s) = agenda.get_mut(i) {690 if let (Some(ref o), Some(ref s)) = (origin.clone(), s.borrow()) {691 if matches!(692 T::OriginPrivilegeCmp::cmp_privilege(o, &s.origin),693 Some(Ordering::Less) | None694 ) {695 return Err(BadOrigin.into());696 }697 698 699 700 701 702 703 704 705706 s.call.ensure_unrequested::<T::PreimageProvider>();707 }708 *s = None;709 }710 Ok(())711 })?;712713 Self::deposit_event(Event::Canceled { when, index });714 Ok(())715 } else {716 Err(Error::<T>::NotFound)?717 }718 })719 }720}