-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathscheduler.ts
More file actions
1954 lines (1660 loc) · 70 KB
/
scheduler.ts
File metadata and controls
1954 lines (1660 loc) · 70 KB
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
import { sendTransaction } from '@acala-network/chopsticks-testing'
import { type Chain, testAccounts } from '@e2e-test/networks'
import { type Client, type RootTestTree, setupNetworks } from '@e2e-test/shared'
import type { SubmittableExtrinsic } from '@polkadot/api/types'
import type { PalletSchedulerScheduled, SpWeightsWeightV2Weight } from '@polkadot/types/lookup'
import type { ISubmittableResult } from '@polkadot/types/types'
import { sha256AsU8a } from '@polkadot/util-crypto'
import { assert, expect } from 'vitest'
import { match } from 'ts-pattern'
import {
blockProviderOffset,
check,
checkEvents,
checkSystemEvents,
getBlockNumber,
nextSchedulableBlockNum,
scheduleInlineCallWithOrigin,
scheduleLookupCallWithOrigin,
type TestConfig,
} from './helpers/index.js'
/**
* Note on manually injecting tasks into the scheduler pallet's agenda storage.
*
* Scheduling extrinsics usually require supra-signed origins.
*
* The manual injection of tasks into the scheduler pallet's agenda storage could be used to simulate the execution of
* the scheduling extrinsics themselves by placing into the agenda what the scheduling extrinsics themselves would
* have placed, in case of a successful execution.
* However, this would not allow exercise their control flows.
*
* Without this injection technique, it is also not easy to use `chopsticks` to test calls requiring `Root` or other
* origins.
*
* So, a compromise is to manually inject the `schedule` calls themselves.
*/
/**
* Note on relaychain vs parachain scheduler agenda keying.
*
* On parachains using the scheduler pallet and non-local block providers, the scheduler agenda can be keyed by
* these providers. Example: on Asset Hubs (post AHM), the scheduler agenda is keyed by the relay chain block number.
*
* Some things to keep in mind:
* 1. on a relay chain at block `r`, to schedule a task for execution next block, use `r + 1`
* 2. on a parachain at block `p` and with last known relay block number `r`, to schedule a task for execution next
* block, use `r` - **not** `p + 1` or `r + 1`
* - on parachains with async backing, use `r` to schedule a task for execution the block after the next,
* **not** `r + 2`
*/
/// -------
/// Helpers
/// -------
/**
* Helper used in tests to origin checks on `Root`-gated scheduler extrinsics.
*
* @param scheduleTx The extrinsinc to be deliberately executed with a signed origin.
* @param snapshotDescription The string used to identify the snapshot.
*/
export async function badOriginHelper<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(
client: Client<TCustom, TInitStorages>,
scheduleTx: SubmittableExtrinsic<'promise', ISubmittableResult>,
snapshotDescription: string,
) {
const alice = testAccounts.alice
await sendTransaction(scheduleTx.signAsync(alice))
await client.dev.newBlock()
await checkSystemEvents(client, { section: 'system', method: 'ExtrinsicFailed' }).toMatchSnapshot(snapshotDescription)
// Check events
const events = await client.api.query.system.events()
const [ev] = events.filter((record) => {
const { event } = record
return event.section === 'system' && event.method === 'ExtrinsicFailed'
})
assert(client.api.events.system.ExtrinsicFailed.is(ev.event))
const dispatchError = ev.event.data.dispatchError
expect(dispatchError.isBadOrigin).toBe(true)
}
/**
* The period of the periodic task.
*
* Used in test to scheduling of periodic tasks.
*/
const PERIOD = 2
/**
* The number of repetitions that a given periodic task should run for.
*
* Used in test to scheduling of periodic tasks.
*/
const REPETITIONS = 3
/// -------
/// -------
/// -------
/**
* Test the process of scheduling a call with a signed (bad) origin, and check that it fails.
*
* 1. Sign scheduling extrinsic, and submit to chain
* 2. Check that the extrinsic fails
*/
export async function scheduleBadOriginTest<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const targetBlockNumber = await nextSchedulableBlockNum(client.api, testConfig.blockProvider)
const call = client.api.tx.system.remark('test').method.toHex()
const scheduleTx = client.api.tx.scheduler.schedule(targetBlockNumber, null, 0, call)
await badOriginHelper(client, scheduleTx, 'events when scheduling task with insufficient origin')
}
/**
* Test the process of scheduling a named call with a signed (bad) origin, and check that it fails.
*
* 1. Sign scheduling extrinsic, and submit to chain
* 2. Check that the extrinsic fails
*/
export async function scheduleNamedBadOriginTest<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const targetBlockNumber = await nextSchedulableBlockNum(client.api, testConfig.blockProvider)
const call = client.api.tx.system.remark('test').method.toHex()
const taskId = sha256AsU8a('task_id')
const scheduleTx = client.api.tx.scheduler.scheduleNamed(taskId, targetBlockNumber, null, 0, call)
await badOriginHelper(client, scheduleTx, 'events when scheduling named task with insufficient origin')
}
/**
* Test the process of
*
* 1. scheduling a call with an origin fulfilling `ScheduleOrigin`
* 2. cancelling the call with a bad origin
* 3. checking that the cancellation call was not executed
*/
export async function cancelScheduledTaskBadOriginTest<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const call = client.api.tx.system.remark('test').method.toHex()
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + offset
})
.exhaustive()
const scheduleTx = client.api.tx.scheduler.schedule(targetBlockNumber!, null, 0, call)
await scheduleInlineCallWithOrigin(client, scheduleTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
// Add a bogus task to the agenda to test robustness
const currentAgenda = await client.api.query.scheduler.agenda(targetBlockNumber!)
const bogusCall = client.api.tx.system.remarkWithEvent('bogus task').method.toHex()
const modifiedAgenda = [...currentAgenda]
modifiedAgenda.push(
client.api.createType('Option<PalletSchedulerScheduled>', {
call: { Inline: bogusCall },
maybeId: null,
priority: 1,
maybePeriodic: null,
origin: { system: 'Root' },
}),
)
await client.dev.setStorage({
Scheduler: {
agenda: [[[targetBlockNumber!], modifiedAgenda]],
},
})
const scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBeGreaterThan(0)
// Find our scheduled task (unnamed, priority 0, with our specific call)
const ourTask = scheduled.find((item) => {
if (!item.isSome) return false
const task = item.unwrap()
return (
task.maybeId.isNone && task.priority.toNumber() === 0 && task.call.isInline && task.call.asInline.toHex() === call
)
})
expect(ourTask).toBeDefined()
expect(ourTask!.isSome).toBeTruthy()
await check(ourTask!.unwrap()).toMatchObject({
maybeId: null,
priority: 0,
call: { inline: call },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
const cancelTx = client.api.tx.scheduler.cancel(targetBlockNumber!, 0)
await badOriginHelper(client, cancelTx, 'events when cancelling task with insufficient origin')
}
/**
* Test the process of
*
* 1. scheduling a named call with an origin fulfilling `ScheduleOrigin`
* 2. cancelling the call with a bad origin
*/
export async function cancelNamedScheduledTaskBadOriginTest<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const call = client.api.tx.system.remark('test').method.toHex()
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + offset
})
.exhaustive()
const taskId = sha256AsU8a('task_id')
const scheduleTx = client.api.tx.scheduler.scheduleNamed(taskId, targetBlockNumber!, null, 0, call)
await scheduleInlineCallWithOrigin(client, scheduleTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
const scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
expect(scheduled[0].isSome).toBeTruthy()
await check(scheduled[0].unwrap())
.redact({ redactKeys: /maybeId/ })
.toMatchObject({
priority: 0,
call: { inline: call },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
expect(scheduled[0].unwrap().maybeId.unwrap().toU8a()).toEqual(taskId)
const cancelTx = client.api.tx.scheduler.cancelNamed(taskId)
await badOriginHelper(client, cancelTx, 'events when cancelling named task with insufficient origin')
}
/**
* Test the process of
*
* 1. scheduling a call requiring a `Root` origin: an update to total issuance
* 2. advancing to the scheduled block of execution
* 3. checking that the call was executed (verify total issuance, and events)
*/
export async function scheduledCallExecutes<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + offset
})
.exhaustive()
const scheduleTx = client.api.tx.scheduler.schedule(targetBlockNumber!, null, 0, adjustIssuanceTx)
await scheduleInlineCallWithOrigin(client, scheduleTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
const oldTotalIssuance = await client.api.query.balances.totalIssuance()
await client.dev.newBlock()
let scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
expect(scheduled[0].isSome).toBeTruthy()
await check(scheduled[0].unwrap()).toMatchObject({
maybeId: null,
priority: 0,
call: { inline: adjustIssuanceTx.method.toHex() },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
await client.dev.newBlock()
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /new|old|when|task/,
})
.toMatchSnapshot('events for scheduled task execution')
const newTotalIssuance = await client.api.query.balances.totalIssuance()
expect(newTotalIssuance.toBigInt()).toBe(BigInt(oldTotalIssuance.addn(1).toString()))
// Check that the call was removed from the agenda
scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(0)
}
/**
* Test the process of
*
* 1. scheduling a named call requiring a `Root` origin: an update to total issuance
* 2. advancing to the scheduled block of execution
* 3. checking that the call was executed (verify total issuance, and events)
*/
export async function scheduledNamedCallExecutes<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
const taskId = sha256AsU8a('task_id')
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + offset
})
.exhaustive()
const scheduleNamedTx = client.api.tx.scheduler.scheduleNamed(taskId, targetBlockNumber!, null, 0, adjustIssuanceTx)
await scheduleInlineCallWithOrigin(
client,
scheduleNamedTx.method.toHex(),
{ system: 'Root' },
testConfig.blockProvider,
)
const oldTotalIssuance = await client.api.query.balances.totalIssuance()
await client.dev.newBlock()
let scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
expect(scheduled[0].isSome).toBeTruthy()
await check(scheduled[0].unwrap()).toMatchObject({
maybeId: `0x${Buffer.from(taskId).toString('hex')}`,
priority: 0,
call: { inline: adjustIssuanceTx.method.toHex() },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
await client.dev.newBlock()
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /new|old|when|task/,
})
.toMatchSnapshot('events for scheduled task execution')
const newTotalIssuance = await client.api.query.balances.totalIssuance()
expect(newTotalIssuance.toBigInt()).toBe(BigInt(oldTotalIssuance.addn(1).toString()))
// Check that the call was removed from the agenda
scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(0)
}
/**
* Test cancellation of scheduled task
*
* 1. schedule a `Root`-origin call for execution sometime in the future
* 2. cancel the call by scheduling `scheduler.cancel` to execute before the scheduled call
* 3. verify that the original call is not executed
* 4. verify that its data is removed from the agenda
*/
export async function cancelScheduledTask<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 3 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.exhaustive()
const scheduleTx = client.api.tx.scheduler.schedule(targetBlockNumber!, null, 0, adjustIssuanceTx)
await scheduleInlineCallWithOrigin(client, scheduleTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
let scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
expect(scheduled[0].isSome).toBeTruthy()
const cancelTx = client.api.tx.scheduler.cancel(targetBlockNumber!, 0)
await scheduleInlineCallWithOrigin(client, cancelTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
// This should capture 2 system events, and no `TotalIssuanceForced`.
// 1. One system event will be for the test-originated dispatch injected via the helper `scheduleInlineCallWithOrigin`
// 2. The other will be a `scheduler.Cancelled` event of the scheduled task
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /new|old|when|task/,
})
.toMatchSnapshot('events for scheduled task cancellation')
scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(0)
await client.dev.newBlock()
}
/**
* Test cancellation of a (named) scheduled task
*
* 1. schedule a `Root`-origin call for execution sometime in the future
* 2. cancel the call by scheduling `scheduler.cancel` to execute before the scheduled call
* 3. verify that the original call is not executed
* 4. verify that its data is removed from the agenda
*/
export async function cancelScheduledNamedTask<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
const taskId = sha256AsU8a('task_id')
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 3 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.exhaustive()
const scheduleNamedTx = client.api.tx.scheduler.scheduleNamed(taskId, targetBlockNumber!, null, 0, adjustIssuanceTx)
await scheduleInlineCallWithOrigin(
client,
scheduleNamedTx.method.toHex(),
{ system: 'Root' },
testConfig.blockProvider,
)
await client.dev.newBlock()
let scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
expect(scheduled[0].isSome).toBeTruthy()
const cancelTx = client.api.tx.scheduler.cancelNamed(taskId)
await scheduleInlineCallWithOrigin(client, cancelTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /when|task/,
})
.toMatchSnapshot('events for scheduled task cancellation')
scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(0)
await client.dev.newBlock()
const events = await client.api.query.system.events()
const filteredEvents = events.filter((ev) => {
const { event } = ev
return (
(event.section === 'scheduler' && event.method === 'Cancelled') ||
(event.section === 'balances' && event.method === 'TotalIssuanceForced')
)
})
expect(filteredEvents.length).toBe(0)
}
/**
* Test scheduling a task after a delay.
*
* 1. schedule a delayed `Root`-origin call e.g. a fixed number of blocks after the block in which it was scheduled
* 2. verify that the call is scheduled in the agenda at the correct block
* 3. advance blocks to reach the execution time
* 4. verify that the call was executed (check total issuance and events)
* 5. verify that the call was removed from the agenda after execution
*/
export async function scheduleTaskAfterDelay<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
const offset = blockProviderOffset(testConfig)
// In case of non-local block providers, spans of blocks must be specified in terms of the nonlocal
// provider.
// This multiplication is because on parachains with AB, each para block spans 2 relay blocks.
// In all other cases, the offset will just be 1, and this is idempotent.
const delay = 3 * offset
const scheduleTx = client.api.tx.scheduler.scheduleAfter(delay, null, 0, adjustIssuanceTx)
let currBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
await scheduleInlineCallWithOrigin(client, scheduleTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
currBlockNumber += offset
await checkSystemEvents(client, 'scheduler')
.redact({
redactKeys: /when|task/,
})
.toMatchSnapshot('events when scheduling task with delay')
let targetBlock: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlock = currBlockNumber + delay + 1
})
.with('NonLocal', () => {
// Recall that parachains use `parachainSystem.lastRelayChainBlockNumber` to key the agenda for the next block,
// not the agenda for the current block - a step back is needed.
// Also, the scheduler considers the block in which call to schedule the delayed task to not count, so the
// `+ 1` is to start counting from the next, as yet uncreated block.
targetBlock = currBlockNumber + delay + 1 - offset
})
.exhaustive()
let scheduled = await client.api.query.scheduler.agenda(targetBlock!)
expect(scheduled.length).toBe(1)
expect(scheduled[0].isSome).toBeTruthy()
await check(scheduled[0].unwrap()).toMatchObject({
maybeId: null,
priority: 0,
call: { inline: adjustIssuanceTx.method.toHex() },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
const oldTotalIssuance = await client.api.query.balances.totalIssuance()
await client.dev.newBlock({ count: delay / offset + 1 })
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /new|old|when|task/,
})
.toMatchSnapshot('events for scheduled task execution')
// Check that the call was removed from the agenda
scheduled = await client.api.query.scheduler.agenda(targetBlock!)
expect(scheduled.length).toBe(0)
// Verify total issuance was increased
const newTotalIssuance = await client.api.query.balances.totalIssuance()
expect(newTotalIssuance.toBigInt()).toBe(BigInt(oldTotalIssuance.addn(1).toString()))
}
/**
* Test scheduling a named task after a delay.
*
* 1. schedule a delayed named `Root`-origin call e.g. a fixed number of blocks after the block in which it was
* scheduled
* 2. verify that the call is scheduled in the agenda at the correct block
* 3. advance blocks to reach the execution time
* 4. verify that the call was executed (check total issuance and events)
* 5. verify that the call was removed from the agenda after execution
*/
export async function scheduleNamedTaskAfterDelay<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
const taskId = sha256AsU8a('task_id')
let currBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
// See above note in `scheduleTaskAfterDelay`
const delay = 5 * offset
const scheduleNamedTx = client.api.tx.scheduler.scheduleNamedAfter(taskId, delay, null, 0, adjustIssuanceTx)
await scheduleInlineCallWithOrigin(
client,
scheduleNamedTx.method.toHex(),
{ system: 'Root' },
testConfig.blockProvider,
)
await client.dev.newBlock()
currBlockNumber += offset
await checkSystemEvents(client, 'scheduler')
.redact({
redactKeys: /when|task/,
})
.toMatchSnapshot('events when scheduling task with delay')
let targetBlock: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlock = currBlockNumber + delay + 1
})
.with('NonLocal', () => {
// Recall that parachains use `parachainSystem.lastRelayChainBlockNumber` to key the agenda for the next block,
// not the agenda for the current block - a step back is needed.
targetBlock = currBlockNumber + delay + 1 - offset
})
.exhaustive()
let scheduled = await client.api.query.scheduler.agenda(targetBlock!)
expect(scheduled.length).toBe(1)
scheduled = await client.api.query.scheduler.agenda(targetBlock!)
expect(scheduled[0].isSome).toBeTruthy()
await check(scheduled[0].unwrap()).toMatchObject({
maybeId: `0x${Buffer.from(taskId).toString('hex')}`,
priority: 0,
call: { inline: adjustIssuanceTx.method.toHex() },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
const oldTotalIssuance = await client.api.query.balances.totalIssuance()
await client.dev.newBlock({ count: delay / offset + 1 })
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /new|old|when|task/,
})
.toMatchSnapshot('events for scheduled task execution')
// Check that the call was removed from the agenda
scheduled = await client.api.query.scheduler.agenda(currBlockNumber + delay + 1)
expect(scheduled.length).toBe(0)
// Verify total issuance was increased
const newTotalIssuance = await client.api.query.balances.totalIssuance()
expect(newTotalIssuance.toBigInt()).toBe(BigInt(oldTotalIssuance.addn(1).toString()))
}
/**
* Test overweight call scheduling.
*
* 1. create a call requiring a `Root` origin: an update to total issuance
* 2. artificially manipulate that call's weight to the per-block weight limit allotted to scheduled calls
* 3. schedule the call
* 4. check that the call was not executed
* 5. check that it remains in the agenda for the original block it was scheduled in
* @param chain
*
*/
export async function scheduledOverweightCallFails<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
// Call whose weight will be artifically inflated
const adjustIssuanceTx = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1)
// Network's maximum allowed weight for a block's entirety of scheduled calls.
const maxWeight = client.api.consts.scheduler.maximumWeight
const withWeightTx = client.api.tx.utility.withWeight(adjustIssuanceTx, maxWeight)
const offset = blockProviderOffset(testConfig)
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
// Target block is two blocks in the future - see the notes about parachain scheduling differences.
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + offset
})
.exhaustive()
const scheduleTx = client.api.tx.scheduler.schedule(targetBlockNumber!, null, 0, withWeightTx)
await scheduleInlineCallWithOrigin(client, scheduleTx.method.toHex(), { system: 'Root' }, testConfig.blockProvider)
await client.dev.newBlock()
let scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
const scheduledTask: PalletSchedulerScheduled = scheduled[0].unwrap()
const task = {
maybeId: null,
priority: 0,
call: { inline: withWeightTx.method.toHex() },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
}
await check(scheduledTask).toMatchObject(task)
// Get current total issuance
const totalIssuance = await client.api.query.balances.totalIssuance()
await client.dev.newBlock()
// Check that the call was not executed
const newTotalIssuance = await client.api.query.balances.totalIssuance()
expect(newTotalIssuance.toBigInt()).toBe(totalIssuance.toBigInt())
// Check that an event was emitted certifying the scheduled call as overweight
await checkSystemEvents(client, 'scheduler')
.redact({
redactKeys: /task|when/,
})
.toMatchSnapshot('events when scheduling overweight task')
let events = await client.api.query.system.events()
let overweightEvent = events.find((record) => {
const { event } = record
return event.section === 'scheduler' && event.method === 'PermanentlyOverweight'
})
// This flag is set to `true` if an overweight event is found immediately after execution.
// An overweight event is emitted only if the task is the first to be executed in a given block, and fails
// execution due to being overweight.
// If this path is taken, the test is likely running on a pre-AHM runtime, or the collectives network.
let overweightEventFound = false
if (overweightEvent) {
overweightEventFound = true
assert(client.api.events.scheduler.PermanentlyOverweight.is(overweightEvent.event))
expect(overweightEvent.event.data.task.toJSON()).toMatchObject([targetBlockNumber!, 0])
expect(overweightEvent.event.data.id.toJSON()).toBeNull()
const incompleteSince = await client.api.query.scheduler.incompleteSince()
assert(incompleteSince.isSome)
expect(incompleteSince.unwrap().toNumber()).toBe(targetBlockNumber! + 1)
}
// Check that the call remains in the agenda for the original block it was scheduled in
scheduled = await client.api.query.scheduler.agenda(targetBlockNumber!)
expect(scheduled.length).toBe(1)
await check(scheduled[0].unwrap()).toMatchObject(task)
// If the overweight event is not found, even though the task was overweight, it's likely that other scheduled events
// interfered with the agenda's scheduled tasks - even though the test clears the agenda for this block.
// Possible cause: `voterList.ScoreUpdated` from the `on_idle` hook. Use `client.pause()` to verify.
// IF this path is taken, the test is likely running on a post-migration asset hub runtime.
if (!overweightEventFound) {
let incompleteSince = await client.api.query.scheduler.incompleteSince()
assert(incompleteSince.isSome)
expect(incompleteSince.unwrap().toNumber()).toBe(targetBlockNumber!)
await client.dev.newBlock()
events = await client.api.query.system.events()
overweightEvent = events.find((record) => {
const { event } = record
return event.section === 'scheduler' && event.method === 'PermanentlyOverweight'
})
expect(overweightEvent).toBeDefined()
assert(client.api.events.scheduler.PermanentlyOverweight.is(overweightEvent!.event))
expect(overweightEvent!.event.data.task.toJSON()).toMatchObject([targetBlockNumber!, 0])
expect(overweightEvent!.event.data.id.toJSON()).toBeNull()
incompleteSince = await client.api.query.scheduler.incompleteSince()
assert(incompleteSince.isSome)
expect(incompleteSince.unwrap().toNumber()).toBe(targetBlockNumber! + offset + 1)
}
}
/**
* Test scheduling of preimage lookup call.
*
* 1. Create a call requiring a `Root` origin: an update to total issuance
* 2. Note the call in storage for the `preimage` pallet
* 3. Schedule the call
* 4. Move to the execution block
* 5. Check that the call is executed
*
* Circa Mar. 2025, this failed on the Collectives chain.
* The issue has been fixed, and when it is upstreamed, this test can then be updated.
* @param client
*/
async function scheduleLookupCall<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const encodedProposal = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1).method
const preimageTx = client.api.tx.preimage.notePreimage(encodedProposal.toHex())
const preImageEvents = await sendTransaction(preimageTx.signAsync(testAccounts.alice))
await client.dev.newBlock()
await checkEvents(preImageEvents, 'preimage').toMatchSnapshot('note preimage events')
const preimageHash = encodedProposal.hash
await scheduleLookupCallWithOrigin(
client,
{ hash: preimageHash, len: encodedProposal.encodedLength },
{ system: 'Root' },
testConfig.blockProvider,
)
const targetBlock = await nextSchedulableBlockNum(client.api, testConfig.blockProvider)
let agenda = await client.api.query.scheduler.agenda(targetBlock)
expect(agenda.length).toBe(1)
assert(agenda[0].isSome)
const scheduledTask = agenda[0].unwrap()
await check(scheduledTask).toMatchObject({
maybeId: null,
priority: 0,
call: { lookup: { hash: preimageHash.toHex(), len: encodedProposal.encodedLength } },
maybePeriodic: null,
origin: {
system: {
root: null,
},
},
})
const oldTotalIssuance = await client.api.query.balances.totalIssuance()
await client.dev.newBlock()
const newTotalIssuance = await client.api.query.balances.totalIssuance()
expect(newTotalIssuance.toBigInt()).toBe(BigInt(oldTotalIssuance.addn(1).toString()))
await checkSystemEvents(client, 'scheduler', { section: 'balances', method: 'TotalIssuanceForced' })
.redact({
redactKeys: /new|old|task/,
})
.toMatchSnapshot('events for scheduled lookup-task execution')
agenda = await client.api.query.scheduler.agenda(targetBlock)
expect(agenda.length).toBe(0)
}
/**
* Test scheduling a call using a preimage that gets removed:
*
* 1. Note a preimage for a call that adjusts total issuance
* 2. Schedule the preimaged call
* 3. Remove the preimage
* 4. Move to execution block
* 5. Check that the call is *not* executed
*/
export async function schedulePreimagedCall<
TCustom extends Record<string, unknown> | undefined,
TInitStorages extends Record<string, Record<string, any>> | undefined,
>(chain: Chain<TCustom, TInitStorages>, testConfig: TestConfig) {
const [client] = await setupNetworks(chain)
const encodedProposal = client.api.tx.balances.forceAdjustTotalIssuance('Increase', 1).method
// Note the preimage
const noteTx = client.api.tx.preimage.notePreimage(encodedProposal.toHex())
const noteEvents = await sendTransaction(noteTx.signAsync(testAccounts.alice))
await client.dev.newBlock()
await checkEvents(noteEvents, 'preimage').toMatchSnapshot('note preimage events')
// Schedule using the preimage hash
const initialBlockNumber = await getBlockNumber(client.api, testConfig.blockProvider)
const offset = blockProviderOffset(testConfig)
// Target block number is two blocks in the future: if `n` is the most recent block, the task should be executed
// at `n + 2`.
let targetBlockNumber: number
match(testConfig.blockProvider)
.with('Local', () => {
targetBlockNumber = initialBlockNumber + 2 * offset
})
.with('NonLocal', () => {
targetBlockNumber = initialBlockNumber + offset
})
.exhaustive()
await client.dev.setStorage({
Scheduler: {
agenda: [
[
[targetBlockNumber!],
[
{
call: {
lookup: {
hash: encodedProposal.hash.toHex(),
len: encodedProposal.encodedLength,
},
},
origin: {
system: 'Root',