-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathlib.rs
1573 lines (1412 loc) · 51.6 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is part of OAK Blockchain.
// Copyright (C) 2022 OAK Network
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//! # Automation time pallet
//!
//! DISCLAIMER: This pallet is still in it's early stages. At this point
//! we only support scheduling two tasks per hour, and sending an on-chain
//! with a custom message.
//!
//! This pallet allows a user to schedule tasks. Tasks can scheduled for any whole hour in the future.
//! In order to run tasks this pallet consumes up to a certain amount of weight during `on_initialize`.
//!
//! The pallet supports the following tasks:
//! * On-chain events with custom text
//!
#![cfg_attr(not(feature = "std"), no_std)]
pub use pallet::*;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod benchmarking;
pub mod migrations;
pub mod weights;
mod fees;
pub use fees::*;
mod autocompounding;
pub use autocompounding::*;
mod types;
pub use types::*;
use codec::Decode;
use core::convert::TryInto;
use cumulus_primitives_core::ParaId;
use frame_support::{
dispatch::{DispatchErrorWithPostInfo, GetDispatchInfo, PostDispatchInfo},
pallet_prelude::*,
sp_runtime::traits::Hash,
storage::{
with_transaction,
TransactionOutcome::{Commit, Rollback},
},
traits::{Contains, Currency, ExistenceRequirement, IsSubType, OriginTrait},
weights::constants::WEIGHT_REF_TIME_PER_SECOND,
};
use frame_system::pallet_prelude::*;
use orml_traits::{FixedConversionRateProvider, MultiCurrency};
use pallet_parachain_staking::DelegatorActions;
use pallet_timestamp::{self as timestamp};
pub use pallet_xcmp_handler::InstructionSequence;
use pallet_xcmp_handler::XcmpTransactor;
use primitives::EnsureProxy;
//use scale_info::TypeInfo;
use scale_info::{prelude::format, TypeInfo};
use sp_runtime::{
traits::{CheckedConversion, Convert, Dispatchable, SaturatedConversion, Saturating},
ArithmeticError, DispatchError, Perbill,
};
use sp_std::{boxed::Box, vec, vec::Vec};
pub use weights::WeightInfo;
use xcm::{latest::prelude::*, VersionedMultiLocation};
use scale_info::prelude::string::String;
#[frame_support::pallet]
pub mod pallet {
use super::*;
pub type AccountOf<T> = <T as frame_system::Config>::AccountId;
pub type BalanceOf<T> =
<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;
pub type MultiBalanceOf<T> = <<T as Config>::MultiCurrency as MultiCurrency<
<T as frame_system::Config>::AccountId,
>>::Balance;
pub type TaskIdV2 = Vec<u8>;
pub type AccountTaskId<T> = (AccountOf<T>, TaskIdV2);
pub type ActionOf<T> = Action<AccountOf<T>, BalanceOf<T>>;
pub type TaskOf<T> = Task<AccountOf<T>, BalanceOf<T>>;
pub type MissedTaskV2Of<T> = MissedTaskV2<AccountOf<T>, TaskIdV2>;
pub type ScheduledTasksOf<T> = ScheduledTasks<AccountOf<T>, TaskIdV2>;
pub type MultiCurrencyId<T> = <<T as Config>::MultiCurrency as MultiCurrency<
<T as frame_system::Config>::AccountId,
>>::CurrencyId;
#[pallet::config]
pub trait Config: frame_system::Config + pallet_timestamp::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
/// Weight information for the extrinsics in this module.
type WeightInfo: WeightInfo;
/// The maximum number of tasks that can be scheduled for a time slot.
#[pallet::constant]
type MaxTasksPerSlot: Get<u32>;
/// The maximum number of times that a task can be scheduled for.
#[pallet::constant]
type MaxExecutionTimes: Get<u32>;
/// The farthest out a task can be scheduled.
#[pallet::constant]
type MaxScheduleSeconds: Get<u64>;
/// The maximum weight per block.
#[pallet::constant]
type MaxBlockWeight: Get<u64>;
/// The maximum percentage of weight per block used for scheduled tasks.
#[pallet::constant]
type MaxWeightPercentage: Get<Perbill>;
/// The maximum supported execution weight per automation slot
#[pallet::constant]
type MaxWeightPerSlot: Get<u128>;
/// The maximum percentage of weight per block used for scheduled tasks.
#[pallet::constant]
type UpdateQueueRatio: Get<Perbill>;
#[pallet::constant]
type ExecutionWeightFee: Get<BalanceOf<Self>>;
/// The Currency type for interacting with balances
type Currency: Currency<Self::AccountId>;
/// The MultiCurrency type for interacting with balances
type MultiCurrency: MultiCurrency<Self::AccountId>;
/// The currencyIds that our chain supports.
type CurrencyId: Parameter
+ Member
+ Copy
+ MaybeSerializeDeserialize
+ Ord
+ TypeInfo
+ MaxEncodedLen
+ From<MultiCurrencyId<Self>>
+ Into<MultiCurrencyId<Self>>
+ From<u32>;
/// Utility for sending XCM messages
type XcmpTransactor: XcmpTransactor<Self::AccountId, Self::CurrencyId>;
/// Converts CurrencyId to Multiloc
type CurrencyIdConvert: Convert<Self::CurrencyId, Option<MultiLocation>>
+ Convert<MultiLocation, Option<Self::CurrencyId>>;
/// Converts between comparable currencies
type FeeConversionRateProvider: FixedConversionRateProvider;
/// Handler for fees
type FeeHandler: HandleFees<Self>;
type DelegatorActions: DelegatorActions<Self::AccountId, BalanceOf<Self>>;
/// The overarching call type.
type Call: Parameter
+ Dispatchable<RuntimeOrigin = Self::RuntimeOrigin, PostInfo = PostDispatchInfo>
+ GetDispatchInfo
+ From<frame_system::Call<Self>>
+ IsSubType<Call<Self>>
+ IsType<<Self as frame_system::Config>::RuntimeCall>;
type ScheduleAllowList: Contains<<Self as frame_system::Config>::RuntimeCall>;
/// Ensure proxy
type EnsureProxy: primitives::EnsureProxy<Self::AccountId>;
/// This chain's Universal Location.
type UniversalLocation: Get<InteriorMultiLocation>;
//The paraId of this chain.
type SelfParaId: Get<ParaId>;
}
#[pallet::pallet]
#[pallet::without_storage_info]
#[pallet::generate_store(pub(super) trait Store)]
pub struct Pallet<T>(_);
#[pallet::storage]
#[pallet::getter(fn get_scheduled_tasks)]
pub type ScheduledTasksV3<T: Config> =
StorageMap<_, Twox64Concat, UnixTime, ScheduledTasksOf<T>>;
#[pallet::storage]
#[pallet::getter(fn get_account_task)]
pub type AccountTasks<T: Config> =
StorageDoubleMap<_, Twox64Concat, AccountOf<T>, Twox64Concat, TaskIdV2, TaskOf<T>>;
#[pallet::storage]
#[pallet::getter(fn get_task_queue)]
pub type TaskQueueV2<T: Config> = StorageValue<_, Vec<AccountTaskId<T>>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn get_missed_queue)]
pub type MissedQueueV2<T: Config> = StorageValue<_, Vec<MissedTaskV2Of<T>>, ValueQuery>;
#[pallet::storage]
#[pallet::getter(fn get_last_slot)]
// NOTE: The 2 UnixTime stamps represent (last_time_slot, last_missed_slot).
// `last_time_slot` represents the last time slot that the task queue was updated.
// `last_missed_slot` represents the last scheduled slot where the missed queue has checked for missed tasks.
pub type LastTimeSlot<T: Config> = StorageValue<_, (UnixTime, UnixTime)>;
#[pallet::storage]
#[pallet::getter(fn is_shutdown)]
pub type Shutdown<T: Config> = StorageValue<_, bool, ValueQuery>;
#[pallet::error]
#[derive(PartialEq)]
pub enum Error<T> {
/// Time must end in a whole hour.
InvalidTime,
/// Time must be in the future.
PastTime,
/// Time cannot be too far in the future.
TimeTooFarOut,
/// The message cannot be empty.
EmptyMessage,
/// There can be no duplicate tasks.
DuplicateTask,
/// Time slot is full. No more tasks can be scheduled for this time.
TimeSlotFull,
/// The task does not exist.
TaskDoesNotExist,
/// Block time not set.
BlockTimeNotSet,
/// Amount has to be larger than 0.1 OAK.
InvalidAmount,
/// Sender cannot transfer money to self.
TransferToSelf,
/// Insufficient balance to pay execution fee.
InsufficientBalance,
/// Account liquidity restrictions prevent withdrawal.
LiquidityRestrictions,
/// Too many execution times provided.
TooManyExecutionsTimes,
/// The call can no longer be decoded.
CallCannotBeDecoded,
/// Incoverible currency ID.
IncoveribleCurrencyId,
/// The version of the `VersionedMultiLocation` value used is not able
/// to be interpreted.
BadVersion,
UnsupportedFeePayment,
CannotReanchor,
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
/// Schedule task success.
TaskScheduled {
who: AccountOf<T>,
task_id: TaskIdV2,
schedule_as: Option<AccountOf<T>>,
},
/// Cancelled a task.
TaskCancelled {
who: AccountOf<T>,
task_id: TaskIdV2,
},
/// Notify event for the task.
Notify {
message: Vec<u8>,
},
/// A Task was not found.
TaskNotFound {
who: AccountOf<T>,
task_id: TaskIdV2,
},
/// Successfully transferred funds
SuccessfullyTransferredFunds {
task_id: TaskIdV2,
},
/// Successfully sent XCMP
XcmpTaskSucceeded {
task_id: TaskIdV2,
destination: MultiLocation,
},
/// Failed to send XCMP
XcmpTaskFailed {
task_id: TaskIdV2,
destination: MultiLocation,
error: DispatchError,
},
/// Transfer Failed
TransferFailed {
task_id: TaskIdV2,
error: DispatchError,
},
SuccesfullyAutoCompoundedDelegatorStake {
task_id: TaskIdV2,
amount: BalanceOf<T>,
},
AutoCompoundDelegatorStakeFailed {
task_id: TaskIdV2,
error_message: Vec<u8>,
error: DispatchErrorWithPostInfo,
},
/// The task could not be run at the scheduled time.
TaskMissed {
who: AccountOf<T>,
task_id: TaskIdV2,
execution_time: UnixTime,
},
/// The result of the DynamicDispatch action.
DynamicDispatchResult {
who: AccountOf<T>,
task_id: TaskIdV2,
result: DispatchResult,
},
/// The call for the DynamicDispatch action can no longer be decoded.
CallCannotBeDecoded {
who: AccountOf<T>,
task_id: TaskIdV2,
},
/// A recurring task was rescheduled
TaskRescheduled {
who: AccountOf<T>,
task_id: TaskIdV2,
schedule_as: Option<AccountOf<T>>,
},
/// A recurring task was not rescheduled
TaskNotRescheduled {
who: AccountOf<T>,
task_id: TaskIdV2,
error: DispatchError,
},
/// A recurring task attempted but failed to be rescheduled
TaskFailedToReschedule {
who: AccountOf<T>,
task_id: TaskIdV2,
error: DispatchError,
},
TaskCompleted {
who: AccountOf<T>,
task_id: TaskIdV2,
},
}
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
fn on_initialize(_block: T::BlockNumber) -> Weight {
if Self::is_shutdown() == true {
return T::DbWeight::get().reads(1u64)
}
let max_weight: Weight = Weight::from_ref_time(
T::MaxWeightPercentage::get().mul_floor(T::MaxBlockWeight::get()),
);
Self::trigger_tasks(max_weight)
}
}
#[pallet::call]
impl<T: Config> Pallet<T> {
/// Schedule a task through XCMP to fire an XCMP message with a provided call.
///
/// Before the task can be scheduled the task must past validation checks.
/// * The transaction is signed
/// * The times are valid
/// * The given asset location is supported
///
/// # Parameters
/// * `schedule`: The triggering rules for recurring task or the list of unix standard times in seconds for when the task should run.
/// * `destination`: Destination the XCMP call will be sent to.
/// * `schedule_fee`: The payment asset location required for scheduling automation task.
/// * `execution_fee`: The fee will be paid for XCMP execution.
/// * `encoded_call`: Call that will be sent via XCMP to the parachain id provided.
/// * `encoded_call_weight`: Required weight at most the provided call will take.
/// * `overall_weight`: The overall weight in which fees will be paid for XCM instructions.
///
/// # Errors
/// * `InvalidTime`: Time must end in a whole hour.
/// * `PastTime`: Time must be in the future.
/// * `DuplicateTask`: There can be no duplicate tasks.
/// * `TimeTooFarOut`: Execution time or frequency are past the max time horizon.
/// * `TimeSlotFull`: Time slot is full. No more tasks can be scheduled for this time.
/// * `UnsupportedFeePayment`: Time slot is full. No more tasks can be scheduled for this time.
#[pallet::call_index(2)]
#[pallet::weight(<T as Config>::WeightInfo::schedule_xcmp_task_full(schedule.number_of_executions()))]
pub fn schedule_xcmp_task(
origin: OriginFor<T>,
schedule: ScheduleParam,
destination: Box<VersionedMultiLocation>,
schedule_fee: Box<VersionedMultiLocation>,
execution_fee: Box<AssetPayment>,
encoded_call: Vec<u8>,
encoded_call_weight: Weight,
overall_weight: Weight,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let destination =
MultiLocation::try_from(*destination).map_err(|()| Error::<T>::BadVersion)?;
let schedule_fee =
MultiLocation::try_from(*schedule_fee).map_err(|()| Error::<T>::BadVersion)?;
let action = Action::XCMP {
destination,
schedule_fee,
execution_fee: *execution_fee,
encoded_call,
encoded_call_weight,
overall_weight,
schedule_as: None,
instruction_sequence: InstructionSequence::PayThroughSovereignAccount,
};
let schedule = schedule.validated_into::<T>()?;
Self::validate_and_schedule_task(action, who, schedule)?;
Ok(().into())
}
/// Schedule a task through XCMP through proxy account to fire an XCMP message with a provided call.
///
/// Before the task can be scheduled the task must past validation checks.
/// * The transaction is signed
/// * The times are valid
/// * The given asset location is supported
///
/// # Parameters
/// * `schedule`: The triggering rules for recurring task or the list of unix standard times in seconds for when the task should run.
/// * `destination`: Destination the XCMP call will be sent to.
/// * `schedule_fee`: The payment asset location required for scheduling automation task.
/// * `execution_fee`: The fee will be paid for XCMP execution.
/// * `encoded_call`: Call that will be sent via XCMP to the parachain id provided.
/// * `encoded_call_weight`: Required weight at most the provided call will take.
/// * `overall_weight`: The overall weight in which fees will be paid for XCM instructions.
///
/// # Errors
/// * `InvalidTime`: Time must end in a whole hour.
/// * `PastTime`: Time must be in the future.
/// * `DuplicateTask`: There can be no duplicate tasks.
/// * `TimeTooFarOut`: Execution time or frequency are past the max time horizon.
/// * `TimeSlotFull`: Time slot is full. No more tasks can be scheduled for this time.
/// * `UnsupportedFeePayment`: Time slot is full. No more tasks can be scheduled for this time.
/// * `Other("proxy error: expected `ProxyType::Any`")`: schedule_as must be a proxy account of type "any" for the caller.
#[pallet::call_index(3)]
#[pallet::weight(<T as Config>::WeightInfo::schedule_xcmp_task_full(schedule.number_of_executions()).saturating_add(T::DbWeight::get().reads(1)))]
pub fn schedule_xcmp_task_through_proxy(
origin: OriginFor<T>,
schedule: ScheduleParam,
destination: Box<VersionedMultiLocation>,
schedule_fee: Box<VersionedMultiLocation>,
execution_fee: Box<AssetPayment>,
encoded_call: Vec<u8>,
encoded_call_weight: Weight,
overall_weight: Weight,
schedule_as: T::AccountId,
) -> DispatchResult {
let who = ensure_signed(origin)?;
// Make sure the owner is the proxy account of the user account.
T::EnsureProxy::ensure_ok(schedule_as.clone(), who.clone())?;
let destination =
MultiLocation::try_from(*destination).map_err(|()| Error::<T>::BadVersion)?;
let schedule_fee =
MultiLocation::try_from(*schedule_fee).map_err(|()| Error::<T>::BadVersion)?;
let action = Action::XCMP {
destination,
schedule_fee,
execution_fee: *execution_fee,
encoded_call,
encoded_call_weight,
overall_weight,
schedule_as: Some(schedule_as),
instruction_sequence: InstructionSequence::PayThroughRemoteDerivativeAccount,
};
let schedule = schedule.validated_into::<T>()?;
Self::validate_and_schedule_task(action, who, schedule)?;
Ok(().into())
}
/// Schedule a task to increase delegation to a specified up to a minimum balance
/// Task will reschedule itself to run on a given frequency until a failure occurs
///
/// # Parameters
/// * `execution_time`: The unix timestamp when the task should run for the first time
/// * `frequency`: Number of seconds to wait inbetween task executions
/// * `collator_id`: Account ID of the target collator
/// * `account_minimum`: The minimum amount of funds that should be left in the wallet
///
/// # Errors
/// * `InvalidTime`: Execution time and frequency must end in a whole hour.
/// * `PastTime`: Time must be in the future.
/// * `DuplicateTask`: There can be no duplicate tasks.
/// * `TimeSlotFull`: Time slot is full. No more tasks can be scheduled for this time.
/// * `TimeTooFarOut`: Execution time or frequency are past the max time horizon.
/// * `InsufficientBalance`: Not enough funds to pay execution fee.
#[pallet::call_index(4)]
#[pallet::weight(<T as Config>::WeightInfo::schedule_auto_compound_delegated_stake_task_full())]
pub fn schedule_auto_compound_delegated_stake_task(
origin: OriginFor<T>,
execution_time: UnixTime,
frequency: Seconds,
collator_id: AccountOf<T>,
account_minimum: BalanceOf<T>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let action = Action::AutoCompoundDelegatedStake {
delegator: who.clone(),
collator: collator_id,
account_minimum,
};
let schedule = Schedule::new_recurring_schedule::<T>(execution_time, frequency)?;
Self::validate_and_schedule_task(action, who, schedule)?;
Ok(().into())
}
/// Schedule a task that will dispatch a call.
/// ** This is currently limited to calls from the System and Balances pallets.
///
/// # Parameters
/// * `execution_times`: The list of unix standard times in seconds for when the task should run.
/// * `call`: The call that will be dispatched.
///
/// # Errors
/// * `InvalidTime`: Execution time and frequency must end in a whole hour.
/// * `PastTime`: Time must be in the future.
/// * `DuplicateTask`: There can be no duplicate tasks.
/// * `TimeSlotFull`: Time slot is full. No more tasks can be scheduled for this time.
/// * `TimeTooFarOut`: Execution time or frequency are past the max time horizon.
#[pallet::call_index(5)]
#[pallet::weight(<T as Config>::WeightInfo::schedule_dynamic_dispatch_task_full(schedule.number_of_executions()))]
pub fn schedule_dynamic_dispatch_task(
origin: OriginFor<T>,
schedule: ScheduleParam,
call: Box<<T as Config>::Call>,
) -> DispatchResult {
let who = ensure_signed(origin)?;
let encoded_call = call.encode();
let action = Action::DynamicDispatch { encoded_call };
let schedule = schedule.validated_into::<T>()?;
Self::validate_and_schedule_task(action, who, schedule)?;
Ok(().into())
}
/// Cancel a task.
///
/// Tasks can only can be cancelled by their owners.
///
/// # Parameters
/// * `task_id`: The id of the task.
///
/// # Errors
/// * `TaskDoesNotExist`: The task does not exist.
#[pallet::call_index(6)]
#[pallet::weight(<T as Config>::WeightInfo::cancel_scheduled_task_full())]
pub fn cancel_task(origin: OriginFor<T>, task_id: TaskIdV2) -> DispatchResult {
let who = ensure_signed(origin)?;
AccountTasks::<T>::get(who, task_id.clone())
.ok_or(Error::<T>::TaskDoesNotExist)
.map(|task| Self::remove_task(task_id.clone(), task))?;
Ok(().into())
}
/// Sudo can force cancel a task.
///
/// # Parameters
/// * `owner_id`: The owner of the task.
/// * `task_id`: The id of the task.
///
/// # Errors
/// * `TaskDoesNotExist`: The task does not exist.
#[pallet::call_index(7)]
#[pallet::weight(<T as Config>::WeightInfo::force_cancel_scheduled_task_full())]
pub fn force_cancel_task(
origin: OriginFor<T>,
owner_id: AccountOf<T>,
task_id: TaskIdV2,
) -> DispatchResult {
ensure_root(origin)?;
AccountTasks::<T>::get(owner_id, task_id.clone())
.ok_or(Error::<T>::TaskDoesNotExist)
.map(|task| Self::remove_task(task_id.clone(), task))?;
Ok(().into())
}
}
impl<T: Config> Pallet<T> {
/// Based on the block time, return the time slot.
///
/// In order to do this we:
/// * Get the most recent timestamp from the block.
/// * Convert the ms unix timestamp to seconds.
/// * Bring the timestamp down to the last whole hour.
pub fn get_current_time_slot() -> Result<UnixTime, DispatchError> {
let now = <timestamp::Pallet<T>>::get()
.checked_into::<UnixTime>()
.ok_or(ArithmeticError::Overflow)?;
if now == 0 {
Err(Error::<T>::BlockTimeNotSet)?
}
let now = now.checked_div(1000).ok_or(ArithmeticError::Overflow)?;
let diff_to_hour = now.checked_rem(3600).ok_or(ArithmeticError::Overflow)?;
Ok(now.checked_sub(diff_to_hour).ok_or(ArithmeticError::Overflow)?)
}
/// Checks to see if the scheduled time is valid.
///
/// In order for a time to be valid it must
/// - End in a whole hour
/// - Be in the future
/// - Not be more than MaxScheduleSeconds out
pub fn is_valid_time(scheduled_time: UnixTime) -> DispatchResult {
#[cfg(feature = "dev-queue")]
if scheduled_time == 0 {
return Ok(())
}
let remainder = scheduled_time.checked_rem(3600).ok_or(ArithmeticError::Overflow)?;
if remainder != 0 {
Err(<Error<T>>::InvalidTime)?;
}
let current_time_slot = Self::get_current_time_slot()?;
if scheduled_time <= current_time_slot {
Err(<Error<T>>::PastTime)?;
}
let max_schedule_time = current_time_slot
.checked_add(T::MaxScheduleSeconds::get())
.ok_or(ArithmeticError::Overflow)?;
if scheduled_time > max_schedule_time {
Err(Error::<T>::TimeTooFarOut)?;
}
Ok(())
}
/// Cleans the executions times by removing duplicates and putting in ascending order.
pub fn clean_execution_times_vector(execution_times: &mut Vec<UnixTime>) {
execution_times.sort_unstable();
execution_times.dedup();
}
/// Trigger tasks for the block time.
///
/// Complete as many tasks as possible given the maximum weight.
pub fn trigger_tasks(max_weight: Weight) -> Weight {
let mut weight_left: Weight = max_weight;
// The last_missed_slot might not be caught up within just 1 block.
// It might take multiple blocks to fully catch up, so we limit update to a max weight.
let max_update_weight: Weight =
Weight::from_ref_time(T::UpdateQueueRatio::get().mul_floor(weight_left.ref_time()));
let update_weight = Self::update_task_queue(max_update_weight);
weight_left = weight_left.saturating_sub(update_weight);
// need to calculate the weight of running just 1 task below.
let run_task_weight = <T as Config>::WeightInfo::run_tasks_many_found(1)
.saturating_add(T::DbWeight::get().reads(1u64))
.saturating_add(T::DbWeight::get().writes(1u64));
if weight_left.ref_time() < run_task_weight.ref_time() {
return weight_left
}
// run as many scheduled tasks as we can
let task_queue = Self::get_task_queue();
weight_left = weight_left.saturating_sub(T::DbWeight::get().reads(1u64));
if task_queue.len() > 0 {
let (tasks_left, new_weight_left) = Self::run_tasks(task_queue, weight_left);
TaskQueueV2::<T>::put(tasks_left);
weight_left = new_weight_left.saturating_sub(T::DbWeight::get().writes(1u64));
}
// if there is weight left we need to handled the missed tasks
let run_missed_task_weight = <T as Config>::WeightInfo::run_missed_tasks_many_found(1)
.saturating_add(T::DbWeight::get().reads(1u64))
.saturating_add(T::DbWeight::get().writes(1u64));
if weight_left.ref_time() >= run_missed_task_weight.ref_time() {
let missed_queue = Self::get_missed_queue();
weight_left = weight_left.saturating_sub(T::DbWeight::get().reads(1u64));
if missed_queue.len() > 0 {
let (tasks_left, new_weight_left) =
Self::run_missed_tasks(missed_queue, weight_left);
MissedQueueV2::<T>::put(tasks_left);
weight_left = new_weight_left.saturating_sub(T::DbWeight::get().writes(1u64));
}
}
max_weight.saturating_sub(weight_left)
}
/// Update the task queue.
///
/// This function checks to see if we are in a new time slot, and if so it updates the task queue and missing queue by doing the following.
/// 1. (update_scheduled_task_queue) If new slot, append the current task queue to the missed queue and remove tasks from task queue.
/// 2. (update_scheduled_task_queue) Move all tasks from the new slot into the task queue and remove the slot from Scheduled tasks map.
/// 3. (update_missed_queue) If we skipped any time slots (due to an outage) move those tasks to the missed queue.
/// 4. (update_missed_queue) Remove all missed time slots that were moved to missed queue from the Scheduled tasks map.
///
pub fn update_task_queue(allotted_weight: Weight) -> Weight {
let mut total_weight = <T as Config>::WeightInfo::update_task_queue_overhead();
let current_time_slot = match Self::get_current_time_slot() {
Ok(time_slot) => time_slot,
Err(_) => return total_weight,
};
if let Some((last_time_slot, last_missed_slot)) = Self::get_last_slot() {
let missed_queue_allotted_weight = allotted_weight
.saturating_sub(T::DbWeight::get().reads(1u64))
.saturating_sub(T::DbWeight::get().writes(1u64))
.saturating_sub(<T as Config>::WeightInfo::update_scheduled_task_queue());
let (updated_last_time_slot, scheduled_queue_update_weight) =
Self::update_scheduled_task_queue(current_time_slot, last_time_slot);
let (updated_last_missed_slot, missed_queue_update_weight) =
Self::update_missed_queue(
current_time_slot,
last_missed_slot,
missed_queue_allotted_weight,
);
LastTimeSlot::<T>::put((updated_last_time_slot, updated_last_missed_slot));
total_weight = total_weight
.saturating_add(missed_queue_update_weight)
.saturating_add(scheduled_queue_update_weight)
.saturating_add(T::DbWeight::get().reads(1u64));
} else {
LastTimeSlot::<T>::put((current_time_slot, current_time_slot));
total_weight = total_weight
.saturating_add(T::DbWeight::get().writes(1u64))
.saturating_add(T::DbWeight::get().reads(1u64));
}
total_weight
}
/// Update the task queue with scheduled tasks for the current slot
///
/// 1. If new slot, append the current task queue to the missed queue and remove tasks from task queue.
/// 2. Move all tasks from the new slot into the task queue and remove the slot from Scheduled tasks map.
pub fn update_scheduled_task_queue(
current_time_slot: u64,
last_time_slot: u64,
) -> (u64, Weight) {
if current_time_slot != last_time_slot {
let missed_tasks = Self::get_task_queue();
let mut missed_queue = Self::get_missed_queue();
for (account_id, task_id) in missed_tasks {
let new_missed_task =
MissedTaskV2Of::<T>::new(account_id, task_id, last_time_slot);
missed_queue.push(new_missed_task);
}
MissedQueueV2::<T>::put(missed_queue);
// move current time slot to task queue or clear the task queue
if let Some(ScheduledTasksOf::<T> { tasks: account_task_ids, .. }) =
Self::get_scheduled_tasks(current_time_slot)
{
TaskQueueV2::<T>::put(account_task_ids);
ScheduledTasksV3::<T>::remove(current_time_slot);
} else {
let empty_queue: Vec<AccountTaskId<T>> = vec![];
TaskQueueV2::<T>::put(empty_queue);
}
}
let weight_used = <T as Config>::WeightInfo::update_scheduled_task_queue();
(current_time_slot, weight_used)
}
/// Checks if append_to_missed_tasks needs to run and then runs and measures weight as needed
pub fn update_missed_queue(
current_time_slot: u64,
last_missed_slot: u64,
allotted_weight: Weight,
) -> (u64, Weight) {
if current_time_slot != last_missed_slot {
// will need to move missed time slots into missed queue
let (append_weight, missed_slots_moved) = Self::append_to_missed_tasks(
current_time_slot,
last_missed_slot,
allotted_weight,
);
let last_missed_slot_tracker =
last_missed_slot.saturating_add(missed_slots_moved.saturating_mul(3600));
let used_weight = append_weight;
(last_missed_slot_tracker, used_weight)
} else {
(last_missed_slot, Weight::zero())
}
}
/// Checks each previous time slots to move any missed tasks into the missed_queue
///
/// 1. If we skipped any time slots (due to an outage) move those tasks to the missed queue.
/// 2. Remove all missed time slots that were moved to missed queue from the Scheduled tasks map.
pub fn append_to_missed_tasks(
current_time_slot: UnixTime,
last_missed_slot: UnixTime,
mut allotted_weight: Weight,
) -> (Weight, u64) {
// will need to move task queue into missed queue
let mut missed_tasks = vec![];
let mut diff =
(current_time_slot.saturating_sub(last_missed_slot) / 3600).saturating_sub(1);
for i in 0..diff {
if allotted_weight.ref_time() <
<T as Config>::WeightInfo::shift_missed_tasks().ref_time()
{
diff = i;
break
}
let mut slot_missed_tasks = Self::shift_missed_tasks(last_missed_slot, i);
missed_tasks.append(&mut slot_missed_tasks);
allotted_weight =
allotted_weight.saturating_sub(<T as Config>::WeightInfo::shift_missed_tasks());
}
// Update the missed queue
let mut missed_queue = Self::get_missed_queue();
missed_queue.append(&mut missed_tasks);
MissedQueueV2::<T>::put(missed_queue);
let weight = <T as Config>::WeightInfo::append_to_missed_tasks(diff.saturated_into());
(weight, diff)
}
/// Grabs all of the missed tasks from a time slot.
/// The time slot to grab missed tasks is calculated given:
/// 1. last missed slot that was stored
/// 2. the number of slots that it should skip after that
pub fn shift_missed_tasks(
last_missed_slot: UnixTime,
number_of_missed_slots: u64,
) -> Vec<MissedTaskV2Of<T>> {
let mut tasks = vec![];
let seconds_in_slot = 3600;
let shift = seconds_in_slot.saturating_mul(number_of_missed_slots + 1);
let new_time_slot = last_missed_slot.saturating_add(shift);
if let Some(ScheduledTasksOf::<T> { tasks: account_task_ids, .. }) =
Self::get_scheduled_tasks(new_time_slot)
{
ScheduledTasksV3::<T>::remove(new_time_slot);
for (account_id, task_id) in account_task_ids {
let new_missed_task =
MissedTaskV2Of::<T>::new(account_id, task_id, new_time_slot);
tasks.push(new_missed_task);
}
}
return tasks
}
/// Runs as many tasks as the weight allows from the provided vec of task_ids.
///
/// Returns a vec with the tasks that were not run and the remaining weight.
pub fn run_tasks(
mut account_task_ids: Vec<AccountTaskId<T>>,
mut weight_left: Weight,
) -> (Vec<AccountTaskId<T>>, Weight) {
let mut consumed_task_index: usize = 0;
for (account_id, task_id) in account_task_ids.iter() {
consumed_task_index.saturating_inc();
let action_weight = match AccountTasks::<T>::get(account_id.clone(), task_id) {
None => {
Self::deposit_event(Event::TaskNotFound {
who: account_id.clone(),
task_id: task_id.clone(),
});
<T as Config>::WeightInfo::run_tasks_many_missing(1)
},
Some(task) => {
let (task_action_weight, dispatch_error) = match task.action.clone() {
Action::Notify { message } => Self::run_notify_task(message),
Action::NativeTransfer { sender, recipient, amount } =>
Self::run_native_transfer_task(
sender,
recipient,
amount,
task_id.clone(),
),
Action::XCMP {
destination,
execution_fee,
schedule_as,
encoded_call,
encoded_call_weight,
overall_weight,
instruction_sequence,
..
} => Self::run_xcmp_task(
destination,
schedule_as.unwrap_or(task.owner_id.clone()),
execution_fee,
encoded_call,
encoded_call_weight,
overall_weight,
task_id.clone(),
instruction_sequence,
),
Action::AutoCompoundDelegatedStake {
delegator,
collator,
account_minimum,
} => Self::run_auto_compound_delegated_stake_task(
delegator,
collator,
account_minimum,
task_id.clone(),
&task,
),
Action::DynamicDispatch { encoded_call } =>
Self::run_dynamic_dispatch_action(
task.owner_id.clone(),
encoded_call,
task_id.clone(),
),
};
Self::handle_task_post_processing(task_id.clone(), task, dispatch_error);
task_action_weight
.saturating_add(T::DbWeight::get().writes(1u64))
.saturating_add(T::DbWeight::get().reads(1u64))
},
};
weight_left = weight_left.saturating_sub(action_weight);
if weight_left.ref_time() <
<T as Config>::WeightInfo::run_tasks_many_found(1).ref_time()
{
break
}
}
if consumed_task_index == account_task_ids.len() {
return (vec![], weight_left)
} else {
return (account_task_ids.split_off(consumed_task_index), weight_left)
}
}
/// Send events for as many missed tasks as the weight allows from the provided vec of task_ids.
///
/// Returns a vec with the tasks that were not run and the remaining weight.
pub fn run_missed_tasks(
mut missed_tasks: Vec<MissedTaskV2Of<T>>,
mut weight_left: Weight,
) -> (Vec<MissedTaskV2Of<T>>, Weight) {
let mut consumed_task_index: usize = 0;
for missed_task in missed_tasks.iter() {
consumed_task_index += 1;
let action_weight = match AccountTasks::<T>::get(
missed_task.owner_id.clone(),
missed_task.task_id.clone(),
) {
None => {
Self::deposit_event(Event::TaskNotFound {
who: missed_task.owner_id.clone(),
task_id: missed_task.task_id.clone(),
});
<T as Config>::WeightInfo::run_missed_tasks_many_missing(1)
},
Some(task) => {
Self::deposit_event(Event::TaskMissed {
who: task.owner_id.clone(),
task_id: missed_task.task_id.clone(),
execution_time: missed_task.execution_time,