12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152#![cfg_attr(not(feature = "std"), no_std)]53#![allow(clippy::type_complexity, clippy::boxed_local, clippy::unused_unit)]5455mod benchmarking;56pub mod weights;5758use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow, cmp};59use codec::{Encode, Decode, Codec};60use sp_runtime::{61 RuntimeDebug,62 traits::{Zero, One, BadOrigin, Saturating},63 transaction_validity::TransactionValidityError,64 DispatchErrorWithPostInfo,65};66use frame_support::{67 decl_module, decl_storage, decl_event, decl_error,68 dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},69 traits::{70 Get,71 schedule::{self, DispatchTime},72 OriginTrait, EnsureOrigin, IsType,73 },74 weights::{GetDispatchInfo, Weight, PostDispatchInfo},75};76use frame_system::{self as system, ensure_signed};77pub use weights::WeightInfo;78use up_sponsorship::SponsorshipHandler;79use scale_info::TypeInfo;80use sp_core::H160;81use frame_support::traits::NamedReservableCurrency;8283type ScheduledId = [u8; MAX_TASK_ID_LENGTH_IN_BYTES as usize];8485868788899091pub trait Config: system::Config {92 93 type Event: From<Event<Self>> + Into<<Self as system::Config>::Event>;9495 96 type Origin: OriginTrait<PalletsOrigin = Self::PalletsOrigin>97 + From<Self::PalletsOrigin>98 + IsType<<Self as system::Config>::Origin>;99100 101 type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + TypeInfo + Clone + Eq;102103 type Currency: NamedReservableCurrency<Self::AccountId, ReserveIdentifier = ScheduledId>;104105 106 type Call: Parameter107 + Dispatchable<Origin = <Self as Config>::Origin>108 + GetDispatchInfo109 + From<system::Call<Self>>;110111 112 113 type MaximumWeight: Get<Weight>;114115 116 type ScheduleOrigin: EnsureOrigin<<Self as system::Config>::Origin>;117118 119 120 type MaxScheduledPerBlock: Get<u32>;121122 123 type SponsorshipHandler: SponsorshipHandler<Self::AccountId, <Self as Config>::Call>;124125 126 type WeightInfo: WeightInfo;127128 129 type CallExecutor: DispatchCall<Self, H160>;130}131132133pub trait DispatchCall<T: frame_system::Config + Config, SelfContainedSignedInfo> {134 135 type Pre: Default + Codec + Clone + TypeInfo;136137 fn reserve_balance(138 id: ScheduledId,139 sponsor: <T as frame_system::Config>::AccountId,140 call: <T as Config>::Call,141 count: u32,142 ) -> Result<(), DispatchError>;143144 fn pay_for_call(145 id: ScheduledId,146 sponsor: <T as frame_system::Config>::AccountId,147 call: <T as Config>::Call,148 ) -> Result<u128, DispatchError>;149150 151 fn dispatch_call(152 pre_dispatch: Self::Pre,153 function: <T as Config>::Call,154 ) -> Result<155 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,156 TransactionValidityError,157 >;158159 160 fn pre_dispatch(161 signer: T::AccountId,162 function: <T as Config>::Call,163 ) -> Result<Self::Pre, TransactionValidityError>;164165 166 fn cancel_dispatch(pre_dispatch: Self::Pre) -> Result<(), TransactionValidityError>;167}168169pub const MAX_TASK_ID_LENGTH_IN_BYTES: u8 = 16;170171pub const PERIODIC_CALLS_LIMIT: u32 = 100;172173174175176pub type PeriodicIndex = u32;177178pub type TaskAddress<BlockNumber> = (BlockNumber, u32);179180181#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]182#[derive(Clone, RuntimeDebug, Encode, Decode, TypeInfo)]183pub struct Scheduled<Call, BlockNumber, PalletsOrigin, AccountId, PreDispatch> {184 185 maybe_id: Option<ScheduledId>,186 187 priority: schedule::Priority,188 189 call: Call,190 191 maybe_periodic: Option<schedule::Period<BlockNumber>>,192 193 origin: PalletsOrigin,194 195 pre_dispatch: PreDispatch,196 _phantom: PhantomData<AccountId>,197}198199#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, TypeInfo)]200pub struct CallSpec {201 module: u32,202 method: u32,203}204205decl_storage! {206 trait Store for Module<T: Config> as Scheduler {207 208 pub Agenda: map hasher(twox_64_concat) T::BlockNumber209 => Vec<Option<Scheduled<210 <T as Config>::Call,211 T::BlockNumber,212 T::PalletsOrigin,213 T::AccountId,214 <<T as Config>::CallExecutor as DispatchCall<T, H160>>::Pre215 >>>;216 217 218 Lookup: map hasher(twox_64_concat) ScheduledId => Option<TaskAddress<T::BlockNumber>>;219 }220}221222decl_event!(223 pub enum Event<T> where <T as system::Config>::BlockNumber {224 225 Scheduled(BlockNumber, u32),226 227 Canceled(BlockNumber, u32),228 229 Dispatched(TaskAddress<BlockNumber>, Option<ScheduledId>, DispatchResult),230 }231);232233decl_error! {234 pub enum Error for Module<T: Config> {235 236 FailedToSchedule,237 238 NotFound,239 240 TargetBlockNumberInPast,241 242 RescheduleNoChange,243 }244}245246decl_module! {247 248 pub struct Module<T: Config> for enum Call249 where250 origin: <T as system::Config>::Origin251 {252 type Error = Error<T>;253 fn deposit_event() = default;254255 256 257 258 259 260 261 262 263 264 265 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]266 fn schedule(origin,267 when: T::BlockNumber,268 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,269 priority: schedule::Priority,270 call: Box<<T as Config>::Call>,271 )272 {273 let origin = <T as Config>::Origin::from(origin);274 Self::do_schedule_nameless(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;275 }276277 278 279 280 281 282 283 284 285 286 287 #[weight = <T as Config>::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]288 fn cancel(origin, when: T::BlockNumber, index: u32) {289 T::ScheduleOrigin::ensure_origin(origin.clone())?;290 let origin = <T as Config>::Origin::from(origin);291 Self::do_cancel(Some(origin.caller().clone()), (when, index))?;292 }293294 295 296 297 298 299 300 301 302 303 304 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]305 fn schedule_named(origin,306 id: ScheduledId,307 when: T::BlockNumber,308 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,309 priority: schedule::Priority,310 call: Box<<T as Config>::Call>,311 ) {312 T::ScheduleOrigin::ensure_origin(origin.clone())?;313 let origin = <T as Config>::Origin::from(origin);314 Self::do_schedule_named(315 id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call316 )?;317 }318319 320 321 322 323 324 325 326 327 328 329 #[weight = <T as Config>::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]330 fn cancel_named(origin, id: ScheduledId) {331 T::ScheduleOrigin::ensure_origin(origin.clone())?;332 let origin = <T as Config>::Origin::from(origin);333 Self::do_cancel_named(Some(origin.caller().clone()), id)?;334 }335336 337 338 339 340 341 #[weight = <T as Config>::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]342 fn schedule_after(origin,343 after: T::BlockNumber,344 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,345 priority: schedule::Priority,346 call: Box<<T as Config>::Call>,347 ) {348 T::ScheduleOrigin::ensure_origin(origin.clone())?;349 let origin = <T as Config>::Origin::from(origin);350 Self::do_schedule_nameless(351 DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call352 )?;353 }354355 356 357 358 359 360 #[weight = <T as Config>::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]361 fn schedule_named_after(origin,362 id: ScheduledId,363 after: T::BlockNumber,364 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,365 priority: schedule::Priority,366 call: Box<<T as Config>::Call>,367 ) {368 T::ScheduleOrigin::ensure_origin(origin.clone())?;369 let origin = <T as Config>::Origin::from(origin);370 Self::do_schedule_named(371 id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call372 )?;373 }374375 376 377 378 379 380 381 382 383 384 385 386 fn on_initialize(now: T::BlockNumber) -> Weight {387 let limit = T::MaximumWeight::get();388 let mut queued = Agenda::<T>::take(now)389 .into_iter()390 .enumerate()391 .filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))392 .collect::<Vec<_>>();393 if queued.len() as u32 > T::MaxScheduledPerBlock::get() {394 log::warn!(395 target: "runtime::scheduler",396 "Warning: This block has more items queued in Scheduler than \397 expected from the runtime configuration. An update might be needed."398 );399 }400 queued.sort_by_key(|(_, s)| s.priority);401 let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); 402 let mut total_weight: Weight = 0; 403 queued.into_iter()404 .enumerate()405 .scan(base_weight, |cumulative_weight, (order, (index, s))| {406 *cumulative_weight = cumulative_weight407 .saturating_add(s.call.get_dispatch_info().weight);408409 let origin = <<T as Config>::Origin as From<T::PalletsOrigin>>::from(410 s.origin.clone()411 ).into();412413 if ensure_signed(origin).is_ok() {414 415 *cumulative_weight = cumulative_weight416 .saturating_add(T::DbWeight::get().reads_writes(1, 1));417 }418419 if s.maybe_id.is_some() {420 421 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));422 }423 if s.maybe_periodic.is_some() {424 425 *cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));426 }427428 Some((order, index, *cumulative_weight, s))429 })430 .filter_map(|(order, index, cumulative_weight, mut s)| {431432 433 if s.maybe_id.is_some() && s.maybe_periodic.is_some()434 {435 let sender = ensure_signed(436 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(s.origin.clone()).into(),437 )438 .unwrap_or_default();439 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &s.call.clone())440 .unwrap_or(sender.clone());441442 T::CallExecutor::pay_for_call(443 s.maybe_id.unwrap(),444 who_will_pay.clone(),445 s.call.clone(),446 );447 }448449 450 451 452 453 454 if s.priority <= schedule::HARD_DEADLINE && cumulative_weight <= limit || order == 0 {455 let r = T::CallExecutor::dispatch_call(s.pre_dispatch.clone(), s.call.clone());456457 if let Err(_) = r {458 log::info!(459 target: "runtime::scheduler",460 "Warning: Scheduler has failed to execute a post-dispatch transaction. \461 This block might have become invalid.",462 );463 464 }465466 let r = r.unwrap(); 467468 let maybe_id = s.maybe_id.clone();469 if let Some((period, count)) = s.maybe_periodic {470 if count > 1 {471 s.maybe_periodic = Some((period, count - 1));472 } else {473 s.maybe_periodic = None;474 }475 let next = now + period;476 477 if let Some(ref id) = s.maybe_id {478 let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);479 Lookup::<T>::insert(id, (next, next_index as u32));480 }481 Agenda::<T>::append(next, Some(s));482 } else if let Some(ref id) = s.maybe_id {483 Lookup::<T>::remove(id);484 }485 Self::deposit_event(RawEvent::Dispatched(486 (now, index),487 maybe_id,488 r.map(|_| ()).map_err(|e| e.error)489 ));490 total_weight = cumulative_weight;491 None492 } else {493 Some(Some(s))494 }495 })496 .for_each(|unused| {497 let next = now + One::one();498 Agenda::<T>::append(next, unused);499 });500501 total_weight502 }503 }504}505506impl<T: Config> Module<T> {507 fn resolve_time(when: DispatchTime<T::BlockNumber>) -> Result<T::BlockNumber, DispatchError> {508 let now = frame_system::Pallet::<T>::block_number();509510 let when = match when {511 DispatchTime::At(x) => x,512 513 514 DispatchTime::After(x) => now.saturating_add(x).saturating_add(One::one()),515 };516517 if when <= now {518 return Err(Error::<T>::TargetBlockNumberInPast.into());519 }520521 Ok(when)522 }523524 fn do_schedule(525 maybe_id: Option<ScheduledId>,526 when: DispatchTime<T::BlockNumber>,527 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,528 priority: schedule::Priority,529 origin: T::PalletsOrigin,530 call: <T as Config>::Call,531 ) -> Result<(T::BlockNumber, u32), DispatchError> {532 let when = Self::resolve_time(when)?;533534 let sender = ensure_signed(535 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),536 )537 .unwrap_or_default(); 538 539 540 541542 let pre_dispatch = match T::CallExecutor::pre_dispatch(sender.clone(), call.clone()) {543 Ok(pre_dispatch) => pre_dispatch,544 Err(_) => return Err(Error::<T>::FailedToSchedule.into()),545 };546547 548 549 550551 552 let maybe_periodic = maybe_periodic553 .filter(|p| p.1 > 1 && !p.0.is_zero())554 555 .map(|(p, c)| (p, cmp::min(c, PERIODIC_CALLS_LIMIT) - 1));556557 if let Some(periodic) = maybe_periodic {558559 560 if maybe_id.is_some()561 { 562 let sender = ensure_signed(563 <<T as Config>::Origin as From<T::PalletsOrigin>>::from(origin.clone()).into(),564 )565 .unwrap_or_default();566 let who_will_pay = T::SponsorshipHandler::get_sponsor(&sender, &call.clone())567 .unwrap_or(sender.clone());568 T::CallExecutor::reserve_balance(maybe_id.unwrap(), who_will_pay.clone(), call.clone(), periodic.1); 569 }570571 572 573 574 575 576 }577578 let s = Some(Scheduled {579 maybe_id,580 priority,581 call,582 maybe_periodic,583 origin,584 pre_dispatch,585 _phantom: PhantomData::<T::AccountId>::default(),586 });587 Agenda::<T>::append(when, s);588 let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;589 if index > T::MaxScheduledPerBlock::get() {590 log::warn!(591 target: "runtime::scheduler",592 "Warning: There are more items queued in the Scheduler than \593 expected from the runtime configuration. An update might be needed.",594 );595 }596597 Ok((when, index))598 }599600 fn do_schedule_nameless(601 when: DispatchTime<T::BlockNumber>,602 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,603 priority: schedule::Priority,604 origin: T::PalletsOrigin,605 call: <T as Config>::Call,606 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {607 let address = Self::do_schedule(None, when, maybe_periodic, priority, origin, call)?;608 let (when, index) = address;609610 Self::deposit_event(RawEvent::Scheduled(when, index));611612 Ok(address)613 }614615 fn do_cancel(616 origin: Option<T::PalletsOrigin>,617 (when, index): TaskAddress<T::BlockNumber>,618 ) -> Result<(), DispatchError> {619 let scheduled = Agenda::<T>::try_mutate(when, |agenda| {620 agenda.get_mut(index as usize).map_or(621 Ok(None),622 |s| -> Result<Option<Scheduled<_, _, _, _, _>>, DispatchError> {623 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {624 if *o != s.origin {625 return Err(BadOrigin.into());626 }627 };628 Ok(s.take())629 },630 )631 })?;632 if let Some(s) = scheduled {633 if let Some(id) = s.maybe_id {634 Lookup::<T>::remove(id);635 }636 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone()) {637 log::warn!(638 target: "runtime::scheduler",639 "Warning: Scheduler has failed to execute a post-dispatch transaction. \640 This block might have become invalid.",641 );642 } 643 Self::deposit_event(RawEvent::Canceled(when, index));644 Ok(())645 } else {646 Err(Error::<T>::NotFound.into())647 }648 }649650 fn do_reschedule(651 (when, index): TaskAddress<T::BlockNumber>,652 new_time: DispatchTime<T::BlockNumber>,653 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {654 let new_time = Self::resolve_time(new_time)?;655656 if new_time == when {657 return Err(Error::<T>::RescheduleNoChange.into());658 }659660 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {661 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;662 let task = task.take().ok_or(Error::<T>::NotFound)?;663 Agenda::<T>::append(new_time, Some(task));664 Ok(())665 })?;666667 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;668 Self::deposit_event(RawEvent::Canceled(when, index));669 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));670671 Ok((new_time, new_index))672 }673674 fn do_schedule_named(675 id: ScheduledId,676 when: DispatchTime<T::BlockNumber>,677 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,678 priority: schedule::Priority,679 origin: T::PalletsOrigin,680 call: <T as Config>::Call,681 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {682 683 if id.len() > MAX_TASK_ID_LENGTH_IN_BYTES.try_into().unwrap()684 || Lookup::<T>::contains_key(&id)685 {686 return Err(Error::<T>::FailedToSchedule.into());687 }688689 let address = Self::do_schedule(690 Some(id.clone()),691 when,692 maybe_periodic,693 priority,694 origin,695 call,696 )?;697 let (when, index) = address;698699 Lookup::<T>::insert(&id, &address);700 Self::deposit_event(RawEvent::Scheduled(when, index));701 Ok(address)702 }703704 fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: ScheduledId) -> DispatchResult {705 Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {706 if let Some((when, index)) = lookup.take() {707 let i = index as usize;708 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {709 if let Some(s) = agenda.get_mut(i) {710 if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {711 if *o != s.origin {712 return Err(BadOrigin.into());713 }714 if let Err(_) = T::CallExecutor::cancel_dispatch(s.pre_dispatch.clone())715 {716 log::warn!(717 target: "runtime::scheduler",718 "Warning: Scheduler has failed to execute a post-dispatch transaction. \719 This block might have become invalid.",720 );721 } 722 }723 *s = None;724 }725 Ok(())726 })?;727 Self::deposit_event(RawEvent::Canceled(when, index));728 Ok(())729 } else {730 Err(Error::<T>::NotFound.into())731 }732 })733 }734735 fn do_reschedule_named(736 id: ScheduledId,737 new_time: DispatchTime<T::BlockNumber>,738 ) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {739 let new_time = Self::resolve_time(new_time)?;740741 Lookup::<T>::try_mutate_exists(742 id,743 |lookup| -> Result<TaskAddress<T::BlockNumber>, DispatchError> {744 let (when, index) = lookup.ok_or(Error::<T>::NotFound)?;745746 if new_time == when {747 return Err(Error::<T>::RescheduleNoChange.into());748 }749750 Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {751 let task = agenda.get_mut(index as usize).ok_or(Error::<T>::NotFound)?;752 let task = task.take().ok_or(Error::<T>::NotFound)?;753 Agenda::<T>::append(new_time, Some(task));754755 Ok(())756 })?;757758 let new_index = Agenda::<T>::decode_len(new_time).unwrap_or(1) as u32 - 1;759 Self::deposit_event(RawEvent::Canceled(when, index));760 Self::deposit_event(RawEvent::Scheduled(new_time, new_index));761762 *lookup = Some((new_time, new_index));763764 Ok((new_time, new_index))765 },766 )767 }768}769770impl<T: Config> schedule::Anon<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>771 for Module<T>772{773 type Address = TaskAddress<T::BlockNumber>;774775 fn schedule(776 when: DispatchTime<T::BlockNumber>,777 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,778 priority: schedule::Priority,779 origin: T::PalletsOrigin,780 call: <T as Config>::Call,781 ) -> Result<Self::Address, DispatchError> {782 Self::do_schedule_nameless(when, maybe_periodic, priority, origin, call)783 }784785 fn cancel((when, index): Self::Address) -> Result<(), ()> {786 Self::do_cancel(None, (when, index)).map_err(|_| ())787 }788789 fn reschedule(790 address: Self::Address,791 when: DispatchTime<T::BlockNumber>,792 ) -> Result<Self::Address, DispatchError> {793 Self::do_reschedule(address, when)794 }795796 fn next_dispatch_time((when, index): Self::Address) -> Result<T::BlockNumber, ()> {797 Agenda::<T>::get(when)798 .get(index as usize)799 .ok_or(())800 .map(|_| when)801 }802}803804impl<T: Config> schedule::Named<T::BlockNumber, <T as Config>::Call, T::PalletsOrigin>805 for Module<T>806{807 type Address = TaskAddress<T::BlockNumber>;808809 fn schedule_named(810 id: Vec<u8>,811 when: DispatchTime<T::BlockNumber>,812 maybe_periodic: Option<schedule::Period<T::BlockNumber>>,813 priority: schedule::Priority,814 origin: T::PalletsOrigin,815 call: <T as Config>::Call,816 ) -> Result<Self::Address, ()> {817818 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);819 Self::do_schedule_named(inner_id, when, maybe_periodic, priority, origin, call).map_err(|_| ())820 }821822 fn cancel_named(id: Vec<u8>) -> Result<(), ()> {823 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);824 Self::do_cancel_named(None, inner_id).map_err(|_| ())825 }826827 fn reschedule_named(828 id: Vec<u8>,829 when: DispatchTime<T::BlockNumber>,830 ) -> Result<Self::Address, DispatchError> {831 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);832 Self::do_reschedule_named(inner_id, when)833 }834835 fn next_dispatch_time(id: Vec<u8>) -> Result<T::BlockNumber, ()> {836 let inner_id: ScheduledId = id.try_into().unwrap_or([0; MAX_TASK_ID_LENGTH_IN_BYTES as usize]);837 Lookup::<T>::get(inner_id)838 .and_then(|(when, index)| Agenda::<T>::get(when).get(index as usize).map(|_| when))839 .ok_or(())840 }841}842843#[cfg(test)]844#[allow(clippy::from_over_into)]845mod tests {846 use super::*;847848 use frame_support::{849 ord_parameter_types, parameter_types, traits::Contains, weights::constants::RocksDbWeight,850 };851 use sp_core::H256;852 use sp_runtime::{853 Perbill,854 testing::Header,855 traits::{BlakeTwo256, IdentityLookup},856 };857 use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};858 use crate as scheduler;859860 mod logger {861 use super::*;862 use std::cell::RefCell;863864 thread_local! {865 static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());866 }867 pub trait Config: system::Config {868 type Event: From<Event> + Into<<Self as system::Config>::Event>;869 }870 decl_event! {871 pub enum Event {872 Logged(u32, Weight),873 }874 }875 decl_module! {876 pub struct Module<T: Config> for enum Call877 where878 origin: <T as system::Config>::Origin,879 <T as system::Config>::Origin: OriginTrait<PalletsOrigin = OriginCaller>880 {881 fn deposit_event() = default;882883 #[weight = *weight]884 fn log(origin, i: u32, weight: Weight) {885 Self::deposit_event(Event::Logged(i, weight));886 LOG.with(|log| {887 log.borrow_mut().push((origin.caller().clone(), i));888 })889 }890891 #[weight = *weight]892 fn log_without_filter(origin, i: u32, weight: Weight) {893 Self::deposit_event(Event::Logged(i, weight));894 LOG.with(|log| {895 log.borrow_mut().push((origin.caller().clone(), i));896 })897 }898 }899 }900 }901902 type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<Test>;903 type Block = frame_system::mocking::MockBlock<Test>;904905 frame_support::construct_runtime!(906 pub enum Test where907 Block = Block,908 NodeBlock = Block,909 UncheckedExtrinsic = UncheckedExtrinsic,910 {911 System: frame_system::{Pallet, Call, Config, Storage, Event<T>},912 Logger: logger::{Pallet, Call, Event},913 Scheduler: scheduler::{Pallet, Call, Storage, Event<T>},914 }915 );916917 918 pub struct BaseFilter;919 impl Contains<Call> for BaseFilter {920 fn contains(call: &Call) -> bool {921 !matches!(call, Call::Logger(logger::Call::log { .. }))922 }923 }924925 pub struct DummyExecutor;926 impl<T: frame_system::Config + Config, SelfContainedSignedInfo>927 DispatchCall<T, SelfContainedSignedInfo> for DummyExecutor928 {929 type Pre = ();930931 fn dispatch_call(932 _pre: Self::Pre,933 _call: <T as Config>::Call,934 ) -> Result<935 Result<PostDispatchInfo, DispatchErrorWithPostInfo<PostDispatchInfo>>,936 TransactionValidityError,937 > {938 todo!()939 }940941 fn pre_dispatch(942 _signer: <T as frame_system::Config>::AccountId,943 _call: <T as Config>::Call,944 ) -> Result<Self::Pre, TransactionValidityError> {945 todo!()946 }947948 fn cancel_dispatch(_pre: Self::Pre) -> Result<(), TransactionValidityError> {949 todo!()950 }951 }952953 parameter_types! {954 pub const BlockHashCount: u64 = 250;955 pub BlockWeights: frame_system::limits::BlockWeights =956 frame_system::limits::BlockWeights::simple_max(2_000_000_000_000);957 }958 impl system::Config for Test {959 type BaseCallFilter = BaseFilter;960 type BlockWeights = ();961 type BlockLength = ();962 type DbWeight = RocksDbWeight;963 type Origin = Origin;964 type Call = Call;965 type Index = u64;966 type BlockNumber = u64;967 type Hash = H256;968 type Hashing = BlakeTwo256;969 type AccountId = u64;970 type Lookup = IdentityLookup<Self::AccountId>;971 type Header = Header;972 type Event = Event;973 type BlockHashCount = BlockHashCount;974 type Version = ();975 type PalletInfo = PalletInfo;976 type AccountData = ();977 type OnNewAccount = ();978 type OnKilledAccount = ();979 type SystemWeightInfo = ();980 type SS58Prefix = ();981 type OnSetCode = ();982 }983 impl logger::Config for Test {984 type Event = Event;985 }986 parameter_types! {987 pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * BlockWeights::get().max_block;988 pub const MaxScheduledPerBlock: u32 = 10;989 }990 ord_parameter_types! {991 pub const One: u64 = 1;992 }993994 impl Config for Test {995 type Event = Event;996 type Origin = Origin;997 type PalletsOrigin = OriginCaller;998 type Call = Call;999 type MaximumWeight = MaximumSchedulerWeight;1000 type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;1001 type MaxScheduledPerBlock = MaxScheduledPerBlock;1002 type SponsorshipHandler = ();1003 type WeightInfo = ();1004 type CallExecutor = DummyExecutor;1005 }1006}