1#![cfg_attr(not(feature = "std"), no_std)]
23#![allow(clippy::string_lit_as_bytes)]
25#![allow(clippy::boxed_local)]
26#![allow(clippy::borrowed_box)]
27#![allow(clippy::unused_unit)]
28#![allow(clippy::useless_conversion)]
29
30use frame_support::{
31 dispatch::PostDispatchInfo,
32 dispatch::{DispatchClass, GetDispatchInfo, Pays},
33 pallet_prelude::*,
34 traits::{
35 schedule::{DispatchTime, Priority},
36 Bounded, EitherOfDiverse, EnsureOrigin, Get, IsType, OriginTrait,
37 },
38};
39use frame_system::{pallet_prelude::*, EnsureRoot, EnsureSigned};
40use parity_scale_codec::MaxEncodedLen;
41use scale_info::TypeInfo;
42use sp_core::defer;
43use sp_io::hashing::blake2_256;
44use sp_runtime::{
45 traits::{CheckedSub, Dispatchable, Hash, Saturating},
46 ArithmeticError, DispatchError, DispatchResult, Either, RuntimeDebug,
47};
48use sp_std::prelude::*;
49
50use frame_support::traits::schedule::v3::Named as ScheduleNamed;
51
52mod mock;
53mod tests;
54mod weights;
55
56pub use weights::WeightInfo;
57
58#[derive(PartialEq, Eq, Clone, RuntimeDebug, Encode, Decode, TypeInfo, DecodeWithMemTracking)]
60pub struct DelayedOrigin<BlockNumber, PalletsOrigin> {
61 pub(crate) delay: BlockNumber,
63 pub(crate) origin: Box<PalletsOrigin>,
65}
66
67#[cfg(any(feature = "std", feature = "runtime-benchmarks", test))]
68impl<BlockNumber, PalletsOrigin> DelayedOrigin<BlockNumber, PalletsOrigin> {
69 pub fn new(delay: BlockNumber, origin: Box<PalletsOrigin>) -> Self {
70 Self { delay, origin }
71 }
72}
73
74#[cfg(feature = "std")]
75mod helper {
76 use std::cell::RefCell;
77
78 thread_local! {
79 static NESTED_MAX_ENCODED_LEN: RefCell<bool> = const {
80 RefCell::new(false)
81 };
82 }
83
84 pub fn set_nested_max_encoded_len(val: bool) {
85 NESTED_MAX_ENCODED_LEN.with(|v| *v.borrow_mut() = val);
86 }
87
88 pub fn nested_max_encoded_len() -> bool {
89 NESTED_MAX_ENCODED_LEN.with(|v| *v.borrow())
90 }
91}
92
93#[cfg(not(feature = "std"))]
94mod helper {
95 static mut NESTED_MAX_ENCODED_LEN: bool = false;
96
97 pub fn set_nested_max_encoded_len(val: bool) {
98 unsafe {
99 NESTED_MAX_ENCODED_LEN = val;
100 }
101 }
102
103 pub fn nested_max_encoded_len() -> bool {
104 unsafe { NESTED_MAX_ENCODED_LEN }
105 }
106}
107
108impl<BlockNumber: MaxEncodedLen, PalletsOrigin: MaxEncodedLen> MaxEncodedLen
114 for DelayedOrigin<BlockNumber, PalletsOrigin>
115{
116 fn max_encoded_len() -> usize {
117 if helper::nested_max_encoded_len() {
118 return 0;
119 }
120
121 helper::set_nested_max_encoded_len(true);
122 defer!(helper::set_nested_max_encoded_len(false));
123
124 BlockNumber::max_encoded_len() + PalletsOrigin::max_encoded_len()
125 }
126}
127
128pub struct EnsureDelayed<Delay, Inner, BlockNumber, PalletsOrigin>(
130 sp_std::marker::PhantomData<(Delay, Inner, BlockNumber, PalletsOrigin)>,
131);
132impl<
133 PalletsOrigin: Into<O>,
134 O: Into<Result<DelayedOrigin<BlockNumber, PalletsOrigin>, O>> + From<DelayedOrigin<BlockNumber, PalletsOrigin>>,
135 Delay: Get<BlockNumber>,
136 Inner: EnsureOrigin<O>,
137 BlockNumber: PartialOrd,
138 > EnsureOrigin<O> for EnsureDelayed<Delay, Inner, BlockNumber, PalletsOrigin>
139{
140 type Success = Inner::Success;
141
142 fn try_origin(o: O) -> Result<Self::Success, O> {
143 o.into().and_then(|delayed_origin| {
144 if delayed_origin.delay >= Delay::get() {
145 let pallets_origin = *delayed_origin.origin;
146 Inner::try_origin(pallets_origin.into())
147 } else {
148 Err(delayed_origin.into())
149 }
150 })
151 }
152
153 #[cfg(feature = "runtime-benchmarks")]
154 fn try_successful_origin() -> Result<O, ()> {
155 unimplemented!()
156 }
157}
158
159pub trait AuthorityConfig<Origin, PalletsOrigin, BlockNumber> {
161 fn check_schedule_dispatch(origin: Origin, priority: Priority) -> DispatchResult;
164 fn check_fast_track_schedule(
169 origin: Origin,
170 initial_origin: &PalletsOrigin,
171 new_delay: BlockNumber,
172 ) -> DispatchResult;
173 fn check_delay_schedule(origin: Origin, initial_origin: &PalletsOrigin) -> DispatchResult;
176 fn check_cancel_schedule(origin: Origin, initial_origin: &PalletsOrigin) -> DispatchResult;
179}
180
181pub trait AsOriginId<Origin, PalletsOrigin> {
184 fn into_origin(self) -> PalletsOrigin;
186 fn check_dispatch_from(&self, origin: Origin) -> DispatchResult;
189}
190
191pub type ScheduleTaskIndex = u32;
193
194pub use module::*;
195
196#[frame_support::pallet]
197pub mod module {
198 use super::*;
199
200 #[pallet::origin]
202 pub type Origin<T> = DelayedOrigin<BlockNumberFor<T>, <T as Config>::PalletsOrigin>;
203 pub(crate) type CallOf<T> = <T as Config>::RuntimeCall;
204 pub(crate) type BoundedCallOf<T> = Bounded<CallOf<T>, <T as frame_system::Config>::Hashing>;
205
206 #[pallet::config]
207 pub trait Config: frame_system::Config {
208 type RuntimeOrigin: From<DelayedOrigin<BlockNumberFor<Self>, <Self as Config>::PalletsOrigin>>
210 + IsType<<Self as frame_system::Config>::RuntimeOrigin>
211 + OriginTrait<PalletsOrigin = Self::PalletsOrigin>;
212
213 type PalletsOrigin: Parameter + Into<<Self as frame_system::Config>::RuntimeOrigin>;
215
216 type RuntimeCall: Parameter
218 + Dispatchable<RuntimeOrigin = <Self as frame_system::Config>::RuntimeOrigin, PostInfo = PostDispatchInfo>
219 + GetDispatchInfo;
220
221 type Scheduler: ScheduleNamed<
223 BlockNumberFor<Self>,
224 <Self as Config>::RuntimeCall,
225 Self::PalletsOrigin,
226 Hasher = Self::Hashing,
227 >;
228
229 type AsOriginId: Parameter + AsOriginId<<Self as frame_system::Config>::RuntimeOrigin, Self::PalletsOrigin>;
231
232 type AuthorityConfig: AuthorityConfig<
234 <Self as frame_system::Config>::RuntimeOrigin,
235 Self::PalletsOrigin,
236 BlockNumberFor<Self>,
237 >;
238
239 type WeightInfo: WeightInfo;
241 }
242
243 #[pallet::error]
244 pub enum Error<T> {
245 FailedToSchedule,
247 FailedToCancel,
249 FailedToFastTrack,
251 FailedToDelay,
253 CallNotAuthorized,
255 TriggerCallNotPermitted,
257 WrongCallWeightBound,
259 }
260
261 #[pallet::event]
262 #[pallet::generate_deposit(fn deposit_event)]
263 pub enum Event<T: Config> {
264 Dispatched { result: DispatchResult },
266 Scheduled {
268 origin: T::PalletsOrigin,
269 index: ScheduleTaskIndex,
270 },
271 FastTracked {
273 origin: T::PalletsOrigin,
274 index: ScheduleTaskIndex,
275 when: BlockNumberFor<T>,
276 },
277 Delayed {
279 origin: T::PalletsOrigin,
280 index: ScheduleTaskIndex,
281 when: BlockNumberFor<T>,
282 },
283 Cancelled {
285 origin: T::PalletsOrigin,
286 index: ScheduleTaskIndex,
287 },
288 AuthorizedCall {
290 hash: T::Hash,
291 caller: Option<T::AccountId>,
292 },
293 RemovedAuthorizedCall { hash: T::Hash },
295 TriggeredCallBy { hash: T::Hash, caller: T::AccountId },
297 }
298
299 #[pallet::storage]
300 #[pallet::getter(fn next_task_index)]
301 pub type NextTaskIndex<T: Config> = StorageValue<_, ScheduleTaskIndex, ValueQuery>;
302
303 #[pallet::storage]
304 #[pallet::getter(fn saved_calls)]
305 pub type SavedCalls<T: Config> = StorageMap<_, Identity, T::Hash, (CallOf<T>, Option<T::AccountId>), OptionQuery>;
306
307 #[pallet::pallet]
308 #[pallet::without_storage_info]
309 pub struct Pallet<T>(_);
310
311 #[pallet::hooks]
312 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
313
314 #[pallet::call]
315 impl<T: Config> Pallet<T> {
316 #[pallet::call_index(0)]
318 #[pallet::weight({
319 let info = call.get_dispatch_info();
320 (T::WeightInfo::dispatch_as().saturating_add(info.total_weight()), info.class)
321 })]
322 pub fn dispatch_as(origin: OriginFor<T>, as_origin: T::AsOriginId, call: Box<CallOf<T>>) -> DispatchResult {
323 as_origin.check_dispatch_from(origin)?;
324
325 let e = call.dispatch(as_origin.into_origin().into());
326
327 Self::deposit_event(Event::Dispatched {
328 result: e.map(|_| ()).map_err(|e| e.error),
329 });
330 Ok(())
331 }
332
333 #[pallet::call_index(1)]
336 #[pallet::weight(T::WeightInfo::schedule_dispatch_without_delay())]
337 pub fn schedule_dispatch(
338 origin: OriginFor<T>,
339 when: DispatchTime<BlockNumberFor<T>>,
340 priority: Priority,
341 with_delayed_origin: bool,
342 call: Box<BoundedCallOf<T>>,
343 ) -> DispatchResult {
344 T::AuthorityConfig::check_schedule_dispatch(origin.clone(), priority)?;
345
346 let id = NextTaskIndex::<T>::mutate(|id| -> sp_std::result::Result<ScheduleTaskIndex, DispatchError> {
347 let current_id = *id;
348 *id = id.checked_add(1).ok_or(ArithmeticError::Overflow)?;
349 Ok(current_id)
350 })?;
351 let now = frame_system::Pallet::<T>::block_number();
352 let delay = match when {
353 DispatchTime::At(x) => x.checked_sub(&now).ok_or(ArithmeticError::Overflow)?,
354 DispatchTime::After(x) => x,
355 };
356 let schedule_origin = if with_delayed_origin {
357 let origin: <T as Config>::RuntimeOrigin = From::from(origin);
358 let origin: <T as Config>::RuntimeOrigin =
359 From::from(DelayedOrigin::<BlockNumberFor<T>, T::PalletsOrigin> {
360 delay,
361 origin: Box::new(origin.caller().clone()),
362 });
363 origin
364 } else {
365 <T as Config>::RuntimeOrigin::from(origin)
366 };
367 let pallets_origin = schedule_origin.caller().clone();
368
369 let task_name = (&pallets_origin, id).using_encoded(blake2_256);
370 T::Scheduler::schedule_named(task_name, when, None, priority, pallets_origin.clone(), *call)
371 .map_err(|_| Error::<T>::FailedToSchedule)?;
372
373 Self::deposit_event(Event::Scheduled {
374 origin: pallets_origin,
375 index: id,
376 });
377 Ok(())
378 }
379
380 #[pallet::call_index(2)]
382 #[pallet::weight(T::WeightInfo::fast_track_scheduled_dispatch())]
383 pub fn fast_track_scheduled_dispatch(
384 origin: OriginFor<T>,
385 initial_origin: Box<T::PalletsOrigin>,
386 task_id: ScheduleTaskIndex,
387 when: DispatchTime<BlockNumberFor<T>>,
388 ) -> DispatchResult {
389 let now = frame_system::Pallet::<T>::block_number();
390 let new_delay = match when {
391 DispatchTime::At(x) => x.checked_sub(&now).ok_or(ArithmeticError::Overflow)?,
392 DispatchTime::After(x) => x,
393 };
394 let dispatch_at = match when {
395 DispatchTime::At(x) => x,
396 DispatchTime::After(x) => now.saturating_add(x),
397 };
398
399 T::AuthorityConfig::check_fast_track_schedule(origin, &initial_origin, new_delay)?;
400 let task_name = (&initial_origin, task_id).using_encoded(blake2_256);
401 T::Scheduler::reschedule_named(task_name, when).map_err(|_| Error::<T>::FailedToFastTrack)?;
402
403 Self::deposit_event(Event::FastTracked {
404 origin: *initial_origin,
405 index: task_id,
406 when: dispatch_at,
407 });
408 Ok(())
409 }
410
411 #[pallet::call_index(3)]
413 #[pallet::weight(T::WeightInfo::delay_scheduled_dispatch())]
414 pub fn delay_scheduled_dispatch(
415 origin: OriginFor<T>,
416 initial_origin: Box<T::PalletsOrigin>,
417 task_id: ScheduleTaskIndex,
418 additional_delay: BlockNumberFor<T>,
419 ) -> DispatchResult {
420 T::AuthorityConfig::check_delay_schedule(origin, &initial_origin)?;
421
422 let task_name = (&initial_origin, task_id).using_encoded(blake2_256);
423 T::Scheduler::reschedule_named(task_name, DispatchTime::After(additional_delay))
424 .map_err(|_| Error::<T>::FailedToDelay)?;
425
426 let now = frame_system::Pallet::<T>::block_number();
427 let dispatch_at = now.saturating_add(additional_delay);
428
429 Self::deposit_event(Event::Delayed {
430 origin: *initial_origin,
431 index: task_id,
432 when: dispatch_at,
433 });
434 Ok(())
435 }
436
437 #[pallet::call_index(4)]
439 #[pallet::weight(T::WeightInfo::cancel_scheduled_dispatch())]
440 pub fn cancel_scheduled_dispatch(
441 origin: OriginFor<T>,
442 initial_origin: Box<T::PalletsOrigin>,
443 task_id: ScheduleTaskIndex,
444 ) -> DispatchResult {
445 T::AuthorityConfig::check_cancel_schedule(origin, &initial_origin)?;
446
447 let task_name = (&initial_origin, task_id).using_encoded(blake2_256);
448 T::Scheduler::cancel_named(task_name).map_err(|_| Error::<T>::FailedToCancel)?;
449
450 Self::deposit_event(Event::Cancelled {
451 origin: *initial_origin,
452 index: task_id,
453 });
454 Ok(())
455 }
456
457 #[pallet::call_index(5)]
458 #[pallet::weight(T::WeightInfo::authorize_call())]
459 pub fn authorize_call(
460 origin: OriginFor<T>,
461 call: Box<CallOf<T>>,
462 caller: Option<T::AccountId>,
463 ) -> DispatchResult {
464 ensure_root(origin)?;
465 let hash = T::Hashing::hash_of(&call);
466 SavedCalls::<T>::insert(hash, (call, caller.clone()));
467 Self::deposit_event(Event::AuthorizedCall { hash, caller });
468 Ok(())
469 }
470
471 #[pallet::call_index(6)]
472 #[pallet::weight(T::WeightInfo::remove_authorized_call())]
473 pub fn remove_authorized_call(origin: OriginFor<T>, hash: T::Hash) -> DispatchResult {
474 let root_or_signed =
475 EitherOfDiverse::<EnsureRoot<T::AccountId>, EnsureSigned<T::AccountId>>::ensure_origin(origin)?;
476
477 SavedCalls::<T>::try_mutate_exists(hash, |maybe_call| {
478 let (_, maybe_caller) = maybe_call.take().ok_or(Error::<T>::CallNotAuthorized)?;
479 match root_or_signed {
480 Either::Left(_) => {} Either::Right(who) => {
482 let caller = maybe_caller.ok_or(Error::<T>::CallNotAuthorized)?;
484 ensure!(who == caller, Error::<T>::CallNotAuthorized);
485 }
486 }
487 Self::deposit_event(Event::RemovedAuthorizedCall { hash });
488 Ok(())
489 })
490 }
491
492 #[pallet::call_index(8)]
493 #[pallet::weight((
494 T::WeightInfo::trigger_call().saturating_add(*call_weight_bound),
495 DispatchClass::Operational,
496 ))]
497 pub fn trigger_call(
498 origin: OriginFor<T>,
499 hash: T::Hash,
500 call_weight_bound: Weight,
501 ) -> DispatchResultWithPostInfo {
502 let who = ensure_signed(origin)?;
503 SavedCalls::<T>::try_mutate_exists(hash, |maybe_call| {
504 let (call, maybe_caller) = maybe_call.take().ok_or(Error::<T>::CallNotAuthorized)?;
505 if let Some(caller) = maybe_caller {
506 ensure!(who == caller, Error::<T>::TriggerCallNotPermitted);
507 }
508 ensure!(
509 call_weight_bound.all_gte(call.get_dispatch_info().total_weight()),
510 Error::<T>::WrongCallWeightBound
511 );
512 let result = call.dispatch(OriginFor::<T>::root());
513 Self::deposit_event(Event::TriggeredCallBy { hash, caller: who });
514 Self::deposit_event(Event::Dispatched {
515 result: result.map(|_| ()).map_err(|e| e.error),
516 });
517 Ok(Pays::No.into())
518 })
519 }
520 }
521}