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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
// This file is part of Substrate.

// Copyright (C) 2017-2020 Parity Technologies (UK) Ltd.
// 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.

//! # Scheduler
//! A module for scheduling dispatches.
//!
//! - [`scheduler::Trait`](./trait.Trait.html)
//! - [`Call`](./enum.Call.html)
//! - [`Module`](./struct.Module.html)
//!
//! ## Overview
//!
//! This module exposes capabilities for scheduling dispatches to occur at a
//! specified block number or at a specified period. These scheduled dispatches
//! may be named or anonymous and may be canceled.
//!
//! **NOTE:** The scheduled calls will be dispatched with the default filter
//! for the origin: namely `frame_system::Trait::BaseCallFilter` for all origin
//! except root which will get no filter. And not the filter contained in origin
//! use to call `fn schedule`.
//!
//! If a call is scheduled using proxy or whatever mecanism which adds filter,
//! then those filter will not be used when dispatching the schedule call.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! * `schedule` - schedule a dispatch, which may be periodic, to occur at a
//!   specified block and with a specified priority.
//! * `cancel` - cancel a scheduled dispatch, specified by block number and
//!   index.
//! * `schedule_named` - augments the `schedule` interface with an additional
//!   `Vec<u8>` parameter that can be used for identification.
//! * `cancel_named` - the named complement to the cancel function.

// Ensure we're `no_std` when compiling for Wasm.
#![cfg_attr(not(feature = "std"), no_std)]

mod benchmarking;
mod default_weights;

use sp_std::{prelude::*, marker::PhantomData, borrow::Borrow};
use codec::{Encode, Decode, Codec};
use sp_runtime::{RuntimeDebug, traits::{Zero, One, BadOrigin, Saturating}};
use frame_support::{
	decl_module, decl_storage, decl_event, decl_error, IterableStorageMap,
	dispatch::{Dispatchable, DispatchError, DispatchResult, Parameter},
	traits::{Get, schedule::{self, DispatchTime}, OriginTrait, EnsureOrigin, IsType},
	weights::{GetDispatchInfo, Weight},
};
use frame_system::{self as system};

pub trait WeightInfo {
	fn schedule(s: u32, ) -> Weight;
	fn cancel(s: u32, ) -> Weight;
	fn schedule_named(s: u32, ) -> Weight;
	fn cancel_named(s: u32, ) -> Weight;
}

/// Our pallet's configuration trait. All our types and constants go in here. If the
/// pallet is dependent on specific other pallets, then their configuration traits
/// should be added to our implied traits list.
///
/// `system::Trait` should always be included in our implied traits.
pub trait Trait: system::Trait {
	/// The overarching event type.
	type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;

	/// The aggregated origin which the dispatch will take.
	type Origin: OriginTrait<PalletsOrigin =
		Self::PalletsOrigin> + From<Self::PalletsOrigin> + IsType<<Self as system::Trait>::Origin>;

	/// The caller origin, overarching type of all pallets origins.
	type PalletsOrigin: From<system::RawOrigin<Self::AccountId>> + Codec + Clone + Eq;

	/// The aggregated call type.
	type Call: Parameter + Dispatchable<Origin=<Self as Trait>::Origin> + GetDispatchInfo + From<system::Call<Self>>;

	/// The maximum weight that may be scheduled per block for any dispatchables of less priority
	/// than `schedule::HARD_DEADLINE`.
	type MaximumWeight: Get<Weight>;

	/// Required origin to schedule or cancel calls.
	type ScheduleOrigin: EnsureOrigin<<Self as system::Trait>::Origin>;

	/// The maximum number of scheduled calls in the queue for a single block.
	/// Not strictly enforced, but used for weight estimation.
	type MaxScheduledPerBlock: Get<u32>;

	/// Weight information for extrinsics in this pallet.
	type WeightInfo: WeightInfo;
}

/// Just a simple index for naming period tasks.
pub type PeriodicIndex = u32;
/// The location of a scheduled task that can be used to remove it.
pub type TaskAddress<BlockNumber> = (BlockNumber, u32);

#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
#[derive(Clone, RuntimeDebug, Encode, Decode)]
struct ScheduledV1<Call, BlockNumber> {
	maybe_id: Option<Vec<u8>>,
	priority: schedule::Priority,
	call: Call,
	maybe_periodic: Option<schedule::Period<BlockNumber>>,
}

/// Information regarding an item to be executed in the future.
#[cfg_attr(any(feature = "std", test), derive(PartialEq, Eq))]
#[derive(Clone, RuntimeDebug, Encode, Decode)]
pub struct ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId> {
	/// The unique identity for this task, if there is one.
	maybe_id: Option<Vec<u8>>,
	/// This task's priority.
	priority: schedule::Priority,
	/// The call to be dispatched.
	call: Call,
	/// If the call is periodic, then this points to the information concerning that.
	maybe_periodic: Option<schedule::Period<BlockNumber>>,
	/// The origin to dispatch the call.
	origin: PalletsOrigin,
	_phantom: PhantomData<AccountId>,
}

/// The current version of Scheduled struct.
pub type Scheduled<Call, BlockNumber, PalletsOrigin, AccountId> = ScheduledV2<Call, BlockNumber, PalletsOrigin, AccountId>;

// A value placed in storage that represents the current version of the Scheduler storage.
// This value is used by the `on_runtime_upgrade` logic to determine whether we run
// storage migration logic.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, RuntimeDebug)]
enum Releases {
	V1,
	V2,
}

impl Default for Releases {
	fn default() -> Self {
		Releases::V1
	}
}

decl_storage! {
	trait Store for Module<T: Trait> as Scheduler {
		/// Items to be executed, indexed by the block number that they should be executed on.
		pub Agenda: map hasher(twox_64_concat) T::BlockNumber
			=> Vec<Option<Scheduled<<T as Trait>::Call, T::BlockNumber, T::PalletsOrigin, T::AccountId>>>;

		/// Lookup from identity to the block number and index of the task.
		Lookup: map hasher(twox_64_concat) Vec<u8> => Option<TaskAddress<T::BlockNumber>>;

		/// Storage version of the pallet.
		///
		/// New networks start with last version.
		StorageVersion build(|_| Releases::V2): Releases;
	}
}

decl_event!(
	pub enum Event<T> where <T as system::Trait>::BlockNumber {
		/// Scheduled some task. \[when, index\]
		Scheduled(BlockNumber, u32),
		/// Canceled some task. \[when, index\]
		Canceled(BlockNumber, u32),
		/// Dispatched some task. \[task, id, result\]
		Dispatched(TaskAddress<BlockNumber>, Option<Vec<u8>>, DispatchResult),
	}
);

decl_error! {
	pub enum Error for Module<T: Trait> {
		/// Failed to schedule a call
		FailedToSchedule,
		/// Failed to cancel a scheduled call
		FailedToCancel,
		/// Given target block number is in the past.
		TargetBlockNumberInPast,
	}
}

decl_module! {
	/// Scheduler module declaration.
	pub struct Module<T: Trait> for enum Call where origin: <T as system::Trait>::Origin {
		type Error = Error<T>;
		fn deposit_event() = default;

		/// Anonymously schedule a task.
		///
		/// # <weight>
		/// - S = Number of already scheduled calls
		/// - Base Weight: 22.29 + .126 * S µs
		/// - DB Weight:
		///     - Read: Agenda
		///     - Write: Agenda
		/// - Will use base weight of 25 which should be good for up to 30 scheduled calls
		/// # </weight>
		#[weight = T::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
		fn schedule(origin,
			when: T::BlockNumber,
			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
			priority: schedule::Priority,
			call: Box<<T as Trait>::Call>,
		) {
			T::ScheduleOrigin::ensure_origin(origin.clone())?;
			let origin = <T as Trait>::Origin::from(origin);
			Self::do_schedule(DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call)?;
		}

		/// Cancel an anonymously scheduled task.
		///
		/// # <weight>
		/// - S = Number of already scheduled calls
		/// - Base Weight: 22.15 + 2.869 * S µs
		/// - DB Weight:
		///     - Read: Agenda
		///     - Write: Agenda, Lookup
		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls
		/// # </weight>
		#[weight = T::WeightInfo::cancel(T::MaxScheduledPerBlock::get())]
		fn cancel(origin, when: T::BlockNumber, index: u32) {
			T::ScheduleOrigin::ensure_origin(origin.clone())?;
			let origin = <T as Trait>::Origin::from(origin);
			Self::do_cancel(Some(origin.caller().clone()), (when, index))?;
		}

		/// Schedule a named task.
		///
		/// # <weight>
		/// - S = Number of already scheduled calls
		/// - Base Weight: 29.6 + .159 * S µs
		/// - DB Weight:
		///     - Read: Agenda, Lookup
		///     - Write: Agenda, Lookup
		/// - Will use base weight of 35 which should be good for more than 30 scheduled calls
		/// # </weight>
		#[weight = T::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]
		fn schedule_named(origin,
			id: Vec<u8>,
			when: T::BlockNumber,
			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
			priority: schedule::Priority,
			call: Box<<T as Trait>::Call>,
		) {
			T::ScheduleOrigin::ensure_origin(origin.clone())?;
			let origin = <T as Trait>::Origin::from(origin);
			Self::do_schedule_named(
				id, DispatchTime::At(when), maybe_periodic, priority, origin.caller().clone(), *call
			)?;
		}

		/// Cancel a named scheduled task.
		///
		/// # <weight>
		/// - S = Number of already scheduled calls
		/// - Base Weight: 24.91 + 2.907 * S µs
		/// - DB Weight:
		///     - Read: Agenda, Lookup
		///     - Write: Agenda, Lookup
		/// - Will use base weight of 100 which should be good for up to 30 scheduled calls
		/// # </weight>
		#[weight = T::WeightInfo::cancel_named(T::MaxScheduledPerBlock::get())]
		fn cancel_named(origin, id: Vec<u8>) {
			T::ScheduleOrigin::ensure_origin(origin.clone())?;
			let origin = <T as Trait>::Origin::from(origin);
			Self::do_cancel_named(Some(origin.caller().clone()), id)?;
		}

		/// Anonymously schedule a task after a delay.
		///
		/// # <weight>
		/// Same as [`schedule`].
		/// # </weight>
		#[weight = T::WeightInfo::schedule(T::MaxScheduledPerBlock::get())]
		fn schedule_after(origin,
			after: T::BlockNumber,
			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
			priority: schedule::Priority,
			call: Box<<T as Trait>::Call>,
		) {
			T::ScheduleOrigin::ensure_origin(origin.clone())?;
			let origin = <T as Trait>::Origin::from(origin);
			Self::do_schedule(
				DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call
			)?;
		}

		/// Schedule a named task after a delay.
		///
		/// # <weight>
		/// Same as [`schedule_named`].
		/// # </weight>
		#[weight = T::WeightInfo::schedule_named(T::MaxScheduledPerBlock::get())]
		fn schedule_named_after(origin,
			id: Vec<u8>,
			after: T::BlockNumber,
			maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
			priority: schedule::Priority,
			call: Box<<T as Trait>::Call>,
		) {
			T::ScheduleOrigin::ensure_origin(origin.clone())?;
			let origin = <T as Trait>::Origin::from(origin);
			Self::do_schedule_named(
				id, DispatchTime::After(after), maybe_periodic, priority, origin.caller().clone(), *call
			)?;
		}

		/// Execute the scheduled calls
		///
		/// # <weight>
		/// - S = Number of already scheduled calls
		/// - N = Named scheduled calls
		/// - P = Periodic Calls
		/// - Base Weight: 9.243 + 23.45 * S µs
		/// - DB Weight:
		///     - Read: Agenda + Lookup * N + Agenda(Future) * P
		///     - Write: Agenda + Lookup * N  + Agenda(future) * P
		/// # </weight>
		fn on_initialize(now: T::BlockNumber) -> Weight {
			let limit = T::MaximumWeight::get();
			let mut queued = Agenda::<T>::take(now).into_iter()
				.enumerate()
				.filter_map(|(index, s)| s.map(|inner| (index as u32, inner)))
				.collect::<Vec<_>>();
			if queued.len() as u32 > T::MaxScheduledPerBlock::get() {
				frame_support::debug::warn!(
					"Warning: This block has more items queued in Scheduler than \
					expected from the runtime configuration. An update might be needed."
				);
			}
			queued.sort_by_key(|(_, s)| s.priority);
			let base_weight: Weight = T::DbWeight::get().reads_writes(1, 2); // Agenda + Agenda(next)
			let mut total_weight: Weight = 0;
			queued.into_iter()
				.enumerate()
				.scan(base_weight, |cumulative_weight, (order, (index, s))| {
					*cumulative_weight = cumulative_weight
						.saturating_add(s.call.get_dispatch_info().weight);

					if s.maybe_id.is_some() {
						// Remove/Modify Lookup
						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().writes(1));
					}
					if s.maybe_periodic.is_some() {
						// Read/Write Agenda for future block
						*cumulative_weight = cumulative_weight.saturating_add(T::DbWeight::get().reads_writes(1, 1));
					}

					Some((order, index, *cumulative_weight, s))
				})
				.filter_map(|(order, index, cumulative_weight, mut s)| {
					// We allow a scheduled call if any is true:
					// - It's priority is `HARD_DEADLINE`
					// - It does not push the weight past the limit.
					// - It is the first item in the schedule
					if s.priority <= schedule::HARD_DEADLINE || cumulative_weight <= limit || order == 0 {
						let r = s.call.clone().dispatch(s.origin.clone().into());
						let maybe_id = s.maybe_id.clone();
						if let &Some((period, count)) = &s.maybe_periodic {
							if count > 1 {
								s.maybe_periodic = Some((period, count - 1));
							} else {
								s.maybe_periodic = None;
							}
							let next = now + period;
							// If scheduled is named, place it's information in `Lookup`
							if let Some(ref id) = s.maybe_id {
								let next_index = Agenda::<T>::decode_len(now + period).unwrap_or(0);
								Lookup::<T>::insert(id, (next, next_index as u32));
							}
							Agenda::<T>::append(next, Some(s));
						} else {
							if let Some(ref id) = s.maybe_id {
								Lookup::<T>::remove(id);
							}
						}
						Self::deposit_event(RawEvent::Dispatched(
							(now, index),
							maybe_id,
							r.map(|_| ()).map_err(|e| e.error)
						));
						total_weight = cumulative_weight;
						None
					} else {
						Some(Some(s))
					}
				})
				.for_each(|unused| {
					let next = now + One::one();
					Agenda::<T>::append(next, unused);
				});

			total_weight
		}
	}
}

impl<T: Trait> Module<T> {
	/// Migrate storage format from V1 to V2.
	/// Return true if migration is performed.
	pub fn migrate_v1_to_t2() -> bool {
		if StorageVersion::get() == Releases::V1 {
			StorageVersion::put(Releases::V2);

			Agenda::<T>::translate::<
				Vec<Option<ScheduledV1<<T as Trait>::Call, T::BlockNumber>>>, _
			>(|_, agenda| Some(
				agenda
					.into_iter()
					.map(|schedule| schedule.map(|schedule| ScheduledV2 {
						maybe_id: schedule.maybe_id,
						priority: schedule.priority,
						call: schedule.call,
						maybe_periodic: schedule.maybe_periodic,
						origin: system::RawOrigin::Root.into(),
						_phantom: Default::default(),
					}))
					.collect::<Vec<_>>()
			));

			true
		} else {
			false
		}
	}

	/// Helper to migrate scheduler when the pallet origin type has changed.
	pub fn migrate_origin<OldOrigin: Into<T::PalletsOrigin> + codec::Decode>() {
		Agenda::<T>::translate::<
			Vec<Option<Scheduled<<T as Trait>::Call, T::BlockNumber, OldOrigin, T::AccountId>>>, _
		>(|_, agenda| Some(
			agenda
				.into_iter()
				.map(|schedule| schedule.map(|schedule| Scheduled {
					maybe_id: schedule.maybe_id,
					priority: schedule.priority,
					call: schedule.call,
					maybe_periodic: schedule.maybe_periodic,
					origin: schedule.origin.into(),
					_phantom: Default::default(),
				}))
				.collect::<Vec<_>>()
		));
	}

	fn do_schedule(
		when: DispatchTime<T::BlockNumber>,
		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
		priority: schedule::Priority,
		origin: T::PalletsOrigin,
		call: <T as Trait>::Call
	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
		let now = frame_system::Module::<T>::block_number();

		let when = match when {
			DispatchTime::At(x) => x,
			DispatchTime::After(x) => now.saturating_add(x)
		};

		if when <= now {
			return Err(Error::<T>::TargetBlockNumberInPast.into())
		}

		// sanitize maybe_periodic
		let maybe_periodic = maybe_periodic
			.filter(|p| p.1 > 1 && !p.0.is_zero())
			// Remove one from the number of repetitions since we will schedule one now.
			.map(|(p, c)| (p, c - 1));
		let s = Some(Scheduled {
			maybe_id: None, priority, call, maybe_periodic, origin, _phantom: PhantomData::<T::AccountId>::default(),
		});
		Agenda::<T>::append(when, s);
		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
		if index > T::MaxScheduledPerBlock::get() {
			frame_support::debug::warn!(
				"Warning: There are more items queued in the Scheduler than \
				expected from the runtime configuration. An update might be needed."
			);
		}
		Self::deposit_event(RawEvent::Scheduled(when, index));

		Ok((when, index))
	}

	fn do_cancel(
		origin: Option<T::PalletsOrigin>,
		(when, index): TaskAddress<T::BlockNumber>
	) -> Result<(), DispatchError> {
		let scheduled = Agenda::<T>::try_mutate(
			when,
			|agenda| {
				agenda.get_mut(index as usize)
					.map_or(Ok(None), |s| -> Result<Option<Scheduled<_, _, _, _>>, DispatchError> {
						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
							if *o != s.origin {
								return Err(BadOrigin.into());
							}
						};
						Ok(s.take())
					})
			},
		)?;
		if let Some(s) = scheduled {
			if let Some(id) = s.maybe_id {
				Lookup::<T>::remove(id);
			}
			Self::deposit_event(RawEvent::Canceled(when, index));
			Ok(())
		} else {
			Err(Error::<T>::FailedToCancel)?
		}
	}

	fn do_schedule_named(
		id: Vec<u8>,
		when: DispatchTime<T::BlockNumber>,
		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
		priority: schedule::Priority,
		origin: T::PalletsOrigin,
		call: <T as Trait>::Call,
	) -> Result<TaskAddress<T::BlockNumber>, DispatchError> {
		// ensure id it is unique
		if Lookup::<T>::contains_key(&id) {
			return Err(Error::<T>::FailedToSchedule)?
		}

		let now = frame_system::Module::<T>::block_number();

		let when = match when {
			DispatchTime::At(x) => x,
			DispatchTime::After(x) => now.saturating_add(x)
		};

		if when <= now {
			return Err(Error::<T>::TargetBlockNumberInPast.into())
		}

		// sanitize maybe_periodic
		let maybe_periodic = maybe_periodic
			.filter(|p| p.1 > 1 && !p.0.is_zero())
			// Remove one from the number of repetitions since we will schedule one now.
			.map(|(p, c)| (p, c - 1));

		let s = Scheduled {
			maybe_id: Some(id.clone()), priority, call, maybe_periodic, origin, _phantom: Default::default()
		};
		Agenda::<T>::append(when, Some(s));
		let index = Agenda::<T>::decode_len(when).unwrap_or(1) as u32 - 1;
		if index > T::MaxScheduledPerBlock::get() {
			frame_support::debug::warn!(
				"Warning: There are more items queued in the Scheduler than \
				expected from the runtime configuration. An update might be needed."
			);
		}
		let address = (when, index);
		Lookup::<T>::insert(&id, &address);
		Self::deposit_event(RawEvent::Scheduled(when, index));

		Ok(address)
	}

	fn do_cancel_named(origin: Option<T::PalletsOrigin>, id: Vec<u8>) -> DispatchResult {
		Lookup::<T>::try_mutate_exists(id, |lookup| -> DispatchResult {
			if let Some((when, index)) = lookup.take() {
				let i = index as usize;
				Agenda::<T>::try_mutate(when, |agenda| -> DispatchResult {
					if let Some(s) = agenda.get_mut(i) {
						if let (Some(ref o), Some(ref s)) = (origin, s.borrow()) {
							if *o != s.origin {
								return Err(BadOrigin.into());
							}
						}
						*s = None;
					}
					Ok(())
				})?;
				Self::deposit_event(RawEvent::Canceled(when, index));
				Ok(())
			} else {
				Err(Error::<T>::FailedToCancel)?
			}
		})
	}
}

impl<T: Trait> schedule::Anon<T::BlockNumber, <T as Trait>::Call, T::PalletsOrigin> for Module<T> {
	type Address = TaskAddress<T::BlockNumber>;

	fn schedule(
		when: DispatchTime<T::BlockNumber>,
		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
		priority: schedule::Priority,
		origin: T::PalletsOrigin,
		call: <T as Trait>::Call
	) -> Result<Self::Address, DispatchError> {
		Self::do_schedule(when, maybe_periodic, priority, origin, call)
	}

	fn cancel((when, index): Self::Address) -> Result<(), ()> {
		Self::do_cancel(None, (when, index)).map_err(|_| ())
	}
}

impl<T: Trait> schedule::Named<T::BlockNumber, <T as Trait>::Call, T::PalletsOrigin> for Module<T> {
	type Address = TaskAddress<T::BlockNumber>;

	fn schedule_named(
		id: Vec<u8>,
		when: DispatchTime<T::BlockNumber>,
		maybe_periodic: Option<schedule::Period<T::BlockNumber>>,
		priority: schedule::Priority,
		origin: T::PalletsOrigin,
		call: <T as Trait>::Call,
	) -> Result<Self::Address, ()> {
		Self::do_schedule_named(id, when, maybe_periodic, priority, origin, call).map_err(|_| ())
	}

	fn cancel_named(id: Vec<u8>) -> Result<(), ()> {
		Self::do_cancel_named(None, id).map_err(|_| ())
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	use frame_support::{
		impl_outer_event, impl_outer_origin, impl_outer_dispatch, parameter_types, assert_ok, ord_parameter_types,
		assert_noop, assert_err, Hashable,
		traits::{OnInitialize, OnFinalize, Filter},
		weights::constants::RocksDbWeight,
	};
	use sp_core::H256;
	use sp_runtime::{
		Perbill,
		testing::Header,
		traits::{BlakeTwo256, IdentityLookup},
	};
	use frame_system::{EnsureOneOf, EnsureRoot, EnsureSignedBy};
	use substrate_test_utils::assert_eq_uvec;
	use crate as scheduler;

	mod logger {
		use super::*;
		use std::cell::RefCell;

		thread_local! {
			static LOG: RefCell<Vec<(OriginCaller, u32)>> = RefCell::new(Vec::new());
		}
		pub fn log() -> Vec<(OriginCaller, u32)> {
			LOG.with(|log| log.borrow().clone())
		}
		pub trait Trait: system::Trait {
			type Event: From<Event> + Into<<Self as system::Trait>::Event>;
		}
		decl_event! {
			pub enum Event {
				Logged(u32, Weight),
			}
		}
		decl_module! {
			pub struct Module<T: Trait> for enum Call
			where
				origin: <T as system::Trait>::Origin,
				<T as system::Trait>::Origin: OriginTrait<PalletsOrigin = OriginCaller>
			{
				fn deposit_event() = default;

				#[weight = *weight]
				fn log(origin, i: u32, weight: Weight) {
					Self::deposit_event(Event::Logged(i, weight));
					LOG.with(|log| {
						log.borrow_mut().push((origin.caller().clone(), i));
					})
				}

				#[weight = *weight]
				fn log_without_filter(origin, i: u32, weight: Weight) {
					Self::deposit_event(Event::Logged(i, weight));
					LOG.with(|log| {
						log.borrow_mut().push((origin.caller().clone(), i));
					})
				}
			}
		}
	}

	impl_outer_origin! {
		pub enum Origin for Test where system = frame_system {}
	}

	impl_outer_dispatch! {
		pub enum Call for Test where origin: Origin {
			system::System,
			logger::Logger,
		}
	}

	impl_outer_event! {
		pub enum Event for Test {
			system<T>,
			logger,
			scheduler<T>,
		}
	}

	// Scheduler must dispatch with root and no filter, this tests base filter is indeed not used.
	pub struct BaseFilter;
	impl Filter<Call> for BaseFilter {
		fn filter(call: &Call) -> bool {
			!matches!(call, Call::Logger(logger::Call::log(_, _)))
		}
	}

	#[derive(Clone, Eq, PartialEq)]
	pub struct Test;
	parameter_types! {
		pub const BlockHashCount: u64 = 250;
		pub const MaximumBlockWeight: Weight = 2_000_000_000_000;
		pub const MaximumBlockLength: u32 = 2 * 1024;
		pub const AvailableBlockRatio: Perbill = Perbill::one();
	}
	impl system::Trait for Test {
		type BaseCallFilter = BaseFilter;
		type Origin = Origin;
		type Call = Call;
		type Index = u64;
		type BlockNumber = u64;
		type Hash = H256;
		type Hashing = BlakeTwo256;
		type AccountId = u64;
		type Lookup = IdentityLookup<Self::AccountId>;
		type Header = Header;
		type Event = ();
		type BlockHashCount = BlockHashCount;
		type MaximumBlockWeight = MaximumBlockWeight;
		type DbWeight = RocksDbWeight;
		type BlockExecutionWeight = ();
		type ExtrinsicBaseWeight = ();
		type MaximumExtrinsicWeight = MaximumBlockWeight;
		type MaximumBlockLength = MaximumBlockLength;
		type AvailableBlockRatio = AvailableBlockRatio;
		type Version = ();
		type PalletInfo = ();
		type AccountData = ();
		type OnNewAccount = ();
		type OnKilledAccount = ();
		type SystemWeightInfo = ();
	}
	impl logger::Trait for Test {
		type Event = ();
	}
	parameter_types! {
		pub MaximumSchedulerWeight: Weight = Perbill::from_percent(80) * MaximumBlockWeight::get();
		pub const MaxScheduledPerBlock: u32 = 10;
	}
	ord_parameter_types! {
		pub const One: u64 = 1;
	}

	impl Trait for Test {
		type Event = ();
		type Origin = Origin;
		type PalletsOrigin = OriginCaller;
		type Call = Call;
		type MaximumWeight = MaximumSchedulerWeight;
		type ScheduleOrigin = EnsureOneOf<u64, EnsureRoot<u64>, EnsureSignedBy<One, u64>>;
		type MaxScheduledPerBlock = MaxScheduledPerBlock;
		type WeightInfo = ();
	}
	type System = system::Module<Test>;
	type Logger = logger::Module<Test>;
	type Scheduler = Module<Test>;

	pub fn new_test_ext() -> sp_io::TestExternalities {
		let t = system::GenesisConfig::default().build_storage::<Test>().unwrap();
		t.into()
	}

	fn run_to_block(n: u64) {
		while System::block_number() < n {
			Scheduler::on_finalize(System::block_number());
			System::set_block_number(System::block_number() + 1);
			Scheduler::on_initialize(System::block_number());
		}
	}

	fn root() -> OriginCaller {
		system::RawOrigin::Root.into()
	}

	#[test]
	fn basic_scheduling_works() {
		new_test_ext().execute_with(|| {
			let call = Call::Logger(logger::Call::log(42, 1000));
			assert!(!<Test as frame_system::Trait>::BaseCallFilter::filter(&call));
			let _ = Scheduler::do_schedule(DispatchTime::At(4), None, 127, root(), call);
			run_to_block(3);
			assert!(logger::log().is_empty());
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
			run_to_block(100);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
		});
	}

	#[test]
	fn schedule_after_works() {
		new_test_ext().execute_with(|| {
			run_to_block(2);
			let call = Call::Logger(logger::Call::log(42, 1000));
			assert!(!<Test as frame_system::Trait>::BaseCallFilter::filter(&call));
			let _ = Scheduler::do_schedule(DispatchTime::After(3), None, 127, root(), call);
			run_to_block(4);
			assert!(logger::log().is_empty());
			run_to_block(5);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
			run_to_block(100);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
		});
	}

	#[test]
	fn periodic_scheduling_works() {
		new_test_ext().execute_with(|| {
			// at #4, every 3 blocks, 3 times.
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4), Some((3, 3)), 127, root(), Call::Logger(logger::Call::log(42, 1000))
			);
			run_to_block(3);
			assert!(logger::log().is_empty());
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
			run_to_block(6);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
			run_to_block(7);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
			run_to_block(9);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32)]);
			run_to_block(10);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);
			run_to_block(100);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 42u32), (root(), 42u32)]);
		});
	}

	#[test]
	fn cancel_named_scheduling_works_with_normal_cancel() {
		new_test_ext().execute_with(|| {
			// at #4.
			Scheduler::do_schedule_named(
				1u32.encode(), DispatchTime::At(4), None, 127, root(), Call::Logger(logger::Call::log(69, 1000))
			).unwrap();
			let i = Scheduler::do_schedule(
				DispatchTime::At(4), None, 127, root(), Call::Logger(logger::Call::log(42, 1000))
			).unwrap();
			run_to_block(3);
			assert!(logger::log().is_empty());
			assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
			assert_ok!(Scheduler::do_cancel(None, i));
			run_to_block(100);
			assert!(logger::log().is_empty());
		});
	}

	#[test]
	fn cancel_named_periodic_scheduling_works() {
		new_test_ext().execute_with(|| {
			// at #4, every 3 blocks, 3 times.
			Scheduler::do_schedule_named(
				1u32.encode(),
				DispatchTime::At(4),
				Some((3, 3)),
				127,
				root(),
				Call::Logger(logger::Call::log(42, 1000))
			).unwrap();
			// same id results in error.
			assert!(Scheduler::do_schedule_named(
				1u32.encode(),
				DispatchTime::At(4),
				None,
				127,
				root(),
				Call::Logger(logger::Call::log(69, 1000))
			).is_err());
			// different id is ok.
			Scheduler::do_schedule_named(
				2u32.encode(), DispatchTime::At(8), None, 127, root(), Call::Logger(logger::Call::log(69, 1000))
			).unwrap();
			run_to_block(3);
			assert!(logger::log().is_empty());
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
			run_to_block(6);
			assert_ok!(Scheduler::do_cancel_named(None, 1u32.encode()));
			run_to_block(100);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
		});
	}

	#[test]
	fn scheduler_respects_weight_limits() {
		new_test_ext().execute_with(|| {
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				127,
				root(),
				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
			);
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				127,
				root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
			);
			// 69 and 42 do not fit together
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 42u32)]);
			run_to_block(5);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
		});
	}

	#[test]
	fn scheduler_respects_hard_deadlines_more() {
		new_test_ext().execute_with(|| {
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				0,
				root(),
				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
			);
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				0,
				root(),
				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
			);
			// With base weights, 69 and 42 should not fit together, but do because of hard deadlines
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 42u32), (root(), 69u32)]);
		});
	}

	#[test]
	fn scheduler_respects_priority_ordering() {
		new_test_ext().execute_with(|| {
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				1,
				root(),
				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 2))
			);
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				0,
				root(),
				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
			);
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 69u32), (root(), 42u32)]);
		});
	}

	#[test]
	fn scheduler_respects_priority_ordering_with_soft_deadlines() {
		new_test_ext().execute_with(|| {
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				255,
				root(), Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
			);
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				127,
				root(), Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
			);
			let _ = Scheduler::do_schedule(
				DispatchTime::At(4),
				None,
				126,
				root(), Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2))
			);

			// 2600 does not fit with 69 or 42, but has higher priority, so will go through
			run_to_block(4);
			assert_eq!(logger::log(), vec![(root(), 2600u32)]);
			// 69 and 42 fit together
			run_to_block(5);
			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);
		});
	}

	#[test]
	fn on_initialize_weight_is_correct() {
		new_test_ext().execute_with(|| {
			let base_weight: Weight = <Test as frame_system::Trait>::DbWeight::get().reads_writes(1, 2);
			let base_multiplier = 0;
			let named_multiplier = <Test as frame_system::Trait>::DbWeight::get().writes(1);
			let periodic_multiplier = <Test as frame_system::Trait>::DbWeight::get().reads_writes(1, 1);

			// Named
			assert_ok!(
				Scheduler::do_schedule_named(
					1u32.encode(), DispatchTime::At(1), None, 255, root(),
					Call::Logger(logger::Call::log(3, MaximumSchedulerWeight::get() / 3))
				)
			);
			// Anon Periodic
			let _ = Scheduler::do_schedule(
				DispatchTime::At(1),
				Some((1000, 3)),
				128,
				root(),
				Call::Logger(logger::Call::log(42, MaximumSchedulerWeight::get() / 3))
			);
			// Anon
			let _ = Scheduler::do_schedule(
				DispatchTime::At(1),
				None,
				127,
				root(),
				Call::Logger(logger::Call::log(69, MaximumSchedulerWeight::get() / 2))
			);
			// Named Periodic
			assert_ok!(Scheduler::do_schedule_named(
				2u32.encode(), DispatchTime::At(1), Some((1000, 3)), 126, root(),
				Call::Logger(logger::Call::log(2600, MaximumSchedulerWeight::get() / 2)))
			);

			// Will include the named periodic only
			let actual_weight = Scheduler::on_initialize(1);
			let call_weight = MaximumSchedulerWeight::get() / 2;
			assert_eq!(
				actual_weight, call_weight + base_weight + base_multiplier + named_multiplier + periodic_multiplier
			);
			assert_eq!(logger::log(), vec![(root(), 2600u32)]);

			// Will include anon and anon periodic
			let actual_weight = Scheduler::on_initialize(2);
			let call_weight = MaximumSchedulerWeight::get() / 2 + MaximumSchedulerWeight::get() / 3;
			assert_eq!(actual_weight, call_weight + base_weight + base_multiplier * 2 + periodic_multiplier);
			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32)]);

			// Will include named only
			let actual_weight = Scheduler::on_initialize(3);
			let call_weight = MaximumSchedulerWeight::get() / 3;
			assert_eq!(actual_weight, call_weight + base_weight + base_multiplier + named_multiplier);
			assert_eq!(logger::log(), vec![(root(), 2600u32), (root(), 69u32), (root(), 42u32), (root(), 3u32)]);

			// Will contain none
			let actual_weight = Scheduler::on_initialize(4);
			assert_eq!(actual_weight, 0);
		});
	}

	#[test]
	fn root_calls_works() {
		new_test_ext().execute_with(|| {
			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
			assert_ok!(Scheduler::schedule_named(Origin::root(), 1u32.encode(), 4, None, 127, call));
			assert_ok!(Scheduler::schedule(Origin::root(), 4, None, 127, call2));
			run_to_block(3);
			// Scheduled calls are in the agenda.
			assert_eq!(Agenda::<Test>::get(4).len(), 2);
			assert!(logger::log().is_empty());
			assert_ok!(Scheduler::cancel_named(Origin::root(), 1u32.encode()));
			assert_ok!(Scheduler::cancel(Origin::root(), 4, 1));
			// Scheduled calls are made NONE, so should not effect state
			run_to_block(100);
			assert!(logger::log().is_empty());
		});
	}

	#[test]
	fn fails_to_schedule_task_in_the_past() {
		new_test_ext().execute_with(|| {
			run_to_block(3);

			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));

			assert_err!(
				Scheduler::schedule_named(Origin::root(), 1u32.encode(), 2, None, 127, call),
				Error::<Test>::TargetBlockNumberInPast,
			);

			assert_err!(
				Scheduler::schedule(Origin::root(), 2, None, 127, call2.clone()),
				Error::<Test>::TargetBlockNumberInPast,
			);

			assert_err!(
				Scheduler::schedule(Origin::root(), 3, None, 127, call2),
				Error::<Test>::TargetBlockNumberInPast,
			);
		});
	}

	#[test]
	fn should_use_orign() {
		new_test_ext().execute_with(|| {
			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
			assert_ok!(
				Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)
			);
			assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));
			run_to_block(3);
			// Scheduled calls are in the agenda.
			assert_eq!(Agenda::<Test>::get(4).len(), 2);
			assert!(logger::log().is_empty());
			assert_ok!(Scheduler::cancel_named(system::RawOrigin::Signed(1).into(), 1u32.encode()));
			assert_ok!(Scheduler::cancel(system::RawOrigin::Signed(1).into(), 4, 1));
			// Scheduled calls are made NONE, so should not effect state
			run_to_block(100);
			assert!(logger::log().is_empty());
		});
	}

	#[test]
	fn should_check_orign() {
		new_test_ext().execute_with(|| {
			let call = Box::new(Call::Logger(logger::Call::log(69, 1000)));
			let call2 = Box::new(Call::Logger(logger::Call::log(42, 1000)));
			assert_noop!(
				Scheduler::schedule_named(system::RawOrigin::Signed(2).into(), 1u32.encode(), 4, None, 127, call),
				BadOrigin
			);
			assert_noop!(Scheduler::schedule(system::RawOrigin::Signed(2).into(), 4, None, 127, call2), BadOrigin);
		});
	}

	#[test]
	fn should_check_orign_for_cancel() {
		new_test_ext().execute_with(|| {
			let call = Box::new(Call::Logger(logger::Call::log_without_filter(69, 1000)));
			let call2 = Box::new(Call::Logger(logger::Call::log_without_filter(42, 1000)));
			assert_ok!(
				Scheduler::schedule_named(system::RawOrigin::Signed(1).into(), 1u32.encode(), 4, None, 127, call)
			);
			assert_ok!(Scheduler::schedule(system::RawOrigin::Signed(1).into(), 4, None, 127, call2));
			run_to_block(3);
			// Scheduled calls are in the agenda.
			assert_eq!(Agenda::<Test>::get(4).len(), 2);
			assert!(logger::log().is_empty());
			assert_noop!(Scheduler::cancel_named(system::RawOrigin::Signed(2).into(), 1u32.encode()), BadOrigin);
			assert_noop!(Scheduler::cancel(system::RawOrigin::Signed(2).into(), 4, 1), BadOrigin);
			assert_noop!(Scheduler::cancel_named(system::RawOrigin::Root.into(), 1u32.encode()), BadOrigin);
			assert_noop!(Scheduler::cancel(system::RawOrigin::Root.into(), 4, 1), BadOrigin);
			run_to_block(5);
			assert_eq!(
				logger::log(),
				vec![(system::RawOrigin::Signed(1).into(), 69u32), (system::RawOrigin::Signed(1).into(), 42u32)]
			);
		});
	}

	#[test]
	fn migration_to_v2_works() {
		new_test_ext().execute_with(|| {
			for i in 0..3u64 {
				let k = i.twox_64_concat();
				let old = vec![
					Some(ScheduledV1 {
						maybe_id: None,
						priority: i as u8 + 10,
						call: Call::Logger(logger::Call::log(96, 100)),
						maybe_periodic: None,
					}),
					None,
					Some(ScheduledV1 {
						maybe_id: Some(b"test".to_vec()),
						priority: 123,
						call: Call::Logger(logger::Call::log(69, 1000)),
						maybe_periodic: Some((456u64, 10)),
					}),
				];
				frame_support::migration::put_storage_value(
					b"Scheduler",
					b"Agenda",
					&k,
					old,
				);
			}

			assert_eq!(StorageVersion::get(), Releases::V1);

			assert!(Scheduler::migrate_v1_to_t2());

			assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![
				(
					0,
					vec![
					Some(ScheduledV2 {
						maybe_id: None,
						priority: 10,
						call: Call::Logger(logger::Call::log(96, 100)),
						maybe_periodic: None,
						origin: root(),
						_phantom: PhantomData::<u64>::default(),
					}),
					None,
					Some(ScheduledV2 {
						maybe_id: Some(b"test".to_vec()),
						priority: 123,
						call: Call::Logger(logger::Call::log(69, 1000)),
						maybe_periodic: Some((456u64, 10)),
						origin: root(),
						_phantom: PhantomData::<u64>::default(),
					}),
				]),
				(
					1,
					vec![
						Some(ScheduledV2 {
							maybe_id: None,
							priority: 11,
							call: Call::Logger(logger::Call::log(96, 100)),
							maybe_periodic: None,
							origin: root(),
							_phantom: PhantomData::<u64>::default(),
						}),
						None,
						Some(ScheduledV2 {
							maybe_id: Some(b"test".to_vec()),
							priority: 123,
							call: Call::Logger(logger::Call::log(69, 1000)),
							maybe_periodic: Some((456u64, 10)),
							origin: root(),
							_phantom: PhantomData::<u64>::default(),
						}),
					]
				),
				(
					2,
					vec![
						Some(ScheduledV2 {
							maybe_id: None,
							priority: 12,
							call: Call::Logger(logger::Call::log(96, 100)),
							maybe_periodic: None,
							origin: root(),
							_phantom: PhantomData::<u64>::default(),
						}),
						None,
						Some(ScheduledV2 {
							maybe_id: Some(b"test".to_vec()),
							priority: 123,
							call: Call::Logger(logger::Call::log(69, 1000)),
							maybe_periodic: Some((456u64, 10)),
							origin: root(),
							_phantom: PhantomData::<u64>::default(),
						}),
					]
				)
			]);

			assert_eq!(StorageVersion::get(), Releases::V2);
		});
	}

	#[test]
	fn test_migrate_origin() {
		new_test_ext().execute_with(|| {
			for i in 0..3u64 {
				let k = i.twox_64_concat();
				let old: Vec<Option<Scheduled<_, _, u32, u64>>> = vec![
					Some(Scheduled {
						maybe_id: None,
						priority: i as u8 + 10,
						call: Call::Logger(logger::Call::log(96, 100)),
						origin: 3u32,
						maybe_periodic: None,
						_phantom: Default::default(),
					}),
					None,
					Some(Scheduled {
						maybe_id: Some(b"test".to_vec()),
						priority: 123,
						origin: 2u32,
						call: Call::Logger(logger::Call::log(69, 1000)),
						maybe_periodic: Some((456u64, 10)),
						_phantom: Default::default(),
					}),
				];
				frame_support::migration::put_storage_value(
					b"Scheduler",
					b"Agenda",
					&k,
					old,
				);
			}

			impl Into<OriginCaller> for u32 {
				fn into(self) -> OriginCaller {
					match self {
						3u32 => system::RawOrigin::Root.into(),
						2u32 => system::RawOrigin::None.into(),
						_ => unreachable!("test make no use of it"),
					}
				}
			}

			Scheduler::migrate_origin::<u32>();

			assert_eq_uvec!(Agenda::<Test>::iter().collect::<Vec<_>>(), vec![
				(
					0,
					vec![
					Some(ScheduledV2::<_, _, OriginCaller, u64> {
						maybe_id: None,
						priority: 10,
						call: Call::Logger(logger::Call::log(96, 100)),
						maybe_periodic: None,
						origin: system::RawOrigin::Root.into(),
						_phantom: PhantomData::<u64>::default(),
					}),
					None,
					Some(ScheduledV2 {
						maybe_id: Some(b"test".to_vec()),
						priority: 123,
						call: Call::Logger(logger::Call::log(69, 1000)),
						maybe_periodic: Some((456u64, 10)),
						origin: system::RawOrigin::None.into(),
						_phantom: PhantomData::<u64>::default(),
					}),
				]),
				(
					1,
					vec![
						Some(ScheduledV2 {
							maybe_id: None,
							priority: 11,
							call: Call::Logger(logger::Call::log(96, 100)),
							maybe_periodic: None,
							origin: system::RawOrigin::Root.into(),
							_phantom: PhantomData::<u64>::default(),
						}),
						None,
						Some(ScheduledV2 {
							maybe_id: Some(b"test".to_vec()),
							priority: 123,
							call: Call::Logger(logger::Call::log(69, 1000)),
							maybe_periodic: Some((456u64, 10)),
							origin: system::RawOrigin::None.into(),
							_phantom: PhantomData::<u64>::default(),
						}),
					]
				),
				(
					2,
					vec![
						Some(ScheduledV2 {
							maybe_id: None,
							priority: 12,
							call: Call::Logger(logger::Call::log(96, 100)),
							maybe_periodic: None,
							origin: system::RawOrigin::Root.into(),
							_phantom: PhantomData::<u64>::default(),
						}),
						None,
						Some(ScheduledV2 {
							maybe_id: Some(b"test".to_vec()),
							priority: 123,
							call: Call::Logger(logger::Call::log(69, 1000)),
							maybe_periodic: Some((456u64, 10)),
							origin: system::RawOrigin::None.into(),
							_phantom: PhantomData::<u64>::default(),
						}),
					]
				)
			]);
		});
	}
}