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
use std::{fmt::Display, str::FromStr};
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{
Addr, Binary, CosmosMsg, Empty, Env, Timestamp, TransactionInfo, Uint64, WasmQuery,
};
use cron_schedule::Schedule;
use croncat_mod_generic::types::PathToValue;
pub use croncat_sdk_core::types::AmountForOneTask;
use cw20::Cw20Coin;
use hex::ToHex;
use sha2::{Digest, Sha256};
#[cw_serde]
pub struct Config {
/// Address of the contract owner
pub owner_addr: Addr,
/// A multisig admin whose sole responsibility is to pause the contract in event of emergency.
/// Must be a different contract address than DAO, cannot be a regular keypair
/// Does not have the ability to unpause, must rely on the DAO to assess the situation and act accordingly
pub pause_admin: Addr,
/// Address of the factory contract
pub croncat_factory_addr: Addr,
/// Chain name to add prefix to the task_hash
pub chain_name: String,
/// Assigned by Factory, denotes the version of this contract (CW2 spec) & used as the task verion as well.
pub version: String,
/// Name of the key for raw querying Manager address from the factory
pub croncat_manager_key: (String, [u8; 2]),
/// Name of the key for raw querying Agents address from the factory
pub croncat_agents_key: (String, [u8; 2]),
/// Time in nanos for each bucket of tasks
pub slot_granularity_time: u64,
/// Gas needed to cover proxy call without any action
pub gas_base_fee: u64,
/// Gas needed to cover single non-wasm task's Action
pub gas_action_fee: u64,
/// Gas needed to cover single query
pub gas_query_fee: u64,
/// Gas limit, to make sure task won't lock contract
pub gas_limit: u64,
}
/// Request to create a task
#[cw_serde]
pub struct TaskRequest {
pub interval: Interval,
pub boundary: Option<Boundary>,
pub stop_on_fail: bool,
pub actions: Vec<Action>,
pub queries: Option<Vec<CosmosQuery>>,
pub transforms: Option<Vec<Transform>>,
/// How much of cw20 coin is attached to this task
/// This will be taken from the manager's contract temporary "Users balance"
/// and attached directly to the task's balance.
///
/// Note: Unlike other coins ( which get refunded to the task creator in the same transaction as task removal)
/// cw20's will get moved back to the temporary "Users balance".
/// This is done primarily to save up gas from executing another contract during `proxy_call`
pub cw20: Option<Cw20Coin>,
}
/// Defines the spacing of execution
/// NOTES:
/// - Block Height Based: Once, Immediate, Block
/// - Timestamp Based: Once, Cron
/// - No Epoch support directly, advised to use block heights instead
#[cw_serde]
pub enum Interval {
/// For when this is a non-recurring future scheduled TXN
Once,
/// The ugly batch schedule type, in case you need to exceed single TXN gas limits, within fewest block(s)
Immediate,
/// Allows timing based on block intervals rather than timestamps
Block(u64),
/// Crontab Spec String
Cron(String),
}
impl Interval {
pub fn next(
&self,
env: &Env,
boundary: &Boundary,
slot_granularity_time: u64,
) -> (u64, SlotType) {
match (self, boundary) {
// If Once, return the first block within a specific range that can be triggered 1 time.
// If Immediate, return the first block within a specific range that can be triggered immediately, potentially multiple times.
(Interval::Once, Boundary::Height(boundary_height))
| (Interval::Immediate, Boundary::Height(boundary_height)) => (
get_next_block_limited(env, boundary_height),
SlotType::Block,
),
// If Once, return the first time within a specific range that can be triggered 1 time.
// If Immediate, return the first time within a specific range that can be triggered immediately, potentially multiple times.
(Interval::Once, Boundary::Time(boundary_time))
| (Interval::Immediate, Boundary::Time(boundary_time)) => {
(get_next_time_in_window(env, boundary_time), SlotType::Cron)
}
// return the first block within a specific range that can be triggered 1 or more times based on timestamps.
// Uses crontab spec
(Interval::Cron(crontab), Boundary::Time(boundary_time)) => (
get_next_cron_time(env, boundary_time, crontab, slot_granularity_time),
SlotType::Cron,
),
// return the block within a specific range that can be triggered 1 or more times based on block heights.
// Uses block offset (Example: Block(100) will trigger every 100 blocks)
// So either:
// - Boundary specifies a start/end that block offsets can be computed from
// - Block offset will truncate to specific modulo offsets
(Interval::Block(block), Boundary::Height(boundary_height)) => (
get_next_block_by_offset(env.block.height, boundary_height, *block),
SlotType::Block,
),
// If interval is cron it means boundary is [`BoundaryTime`], and rest of the items is height
_ => unreachable!(),
}
}
pub fn is_valid(&self) -> bool {
match self {
Interval::Once | Interval::Immediate | Interval::Block(_) => true,
Interval::Cron(crontab) => {
let s = Schedule::from_str(crontab);
s.is_ok()
}
}
}
}
/// Start and end block or timestamp when task should be executed for the last time
#[cw_serde]
pub enum Boundary {
Height(BoundaryHeight),
Time(BoundaryTime),
}
impl Boundary {
pub fn is_block(&self) -> bool {
matches!(self, Boundary::Height(_))
}
}
#[cw_serde]
pub struct BoundaryHeight {
pub start: Option<Uint64>,
pub end: Option<Uint64>,
}
#[cw_serde]
pub struct BoundaryTime {
pub start: Option<Timestamp>,
pub end: Option<Timestamp>,
}
#[cw_serde]
pub struct Action<T = Empty> {
/// Supported CosmosMsgs only!
pub msg: CosmosMsg<T>,
/// The gas needed to safely process the execute msg
pub gas_limit: Option<u64>,
}
/// Transforms of the tasks actions
#[cw_serde]
pub struct Transform {
/// Action index to update
/// first action would be "0"
pub action_idx: u64,
/// Query index of the new data for this action
/// first query would be "0"
pub query_idx: u64,
/// Action key path to the value that should get replaced
/// for example:
/// X: {Y: {Z: value}}
/// \[X,Y,Z\] to reach that value
pub action_path: PathToValue,
/// Query response key's path to the value that needs to be taken to replace value from the above
/// for example query gave that response:
/// A: {B: {C: value}}
/// In order to reach a value \[A,B,C\] should be used as input
pub query_response_path: PathToValue,
}
#[cw_serde]
pub struct Task {
/// Entity responsible for this task, can change task details
pub owner_addr: Addr,
/// Scheduling definitions
pub interval: Interval,
pub boundary: Boundary,
/// Defines if this task can continue until balance runs out
pub stop_on_fail: bool,
/// The cosmos message to call, if time or rules are met
pub actions: Vec<Action>,
/// A prioritized list of messages that can be chained decision matrix
/// required to complete before task action
/// Rules MUST return the ResolverResponse type
pub queries: Vec<CosmosQuery>,
pub transforms: Vec<Transform>,
// allows future backward compat
pub version: String,
// computed amounts / fees
pub amount_for_one_task: AmountForOneTask,
// pub
}
impl Task {
/// Get the hash of a task based on parameters
pub fn to_hash(&self, prefix: &str) -> String {
let message = format!(
"{:?}{:?}{:?}{:?}{:?}{:?}",
self.owner_addr,
self.interval,
self.boundary,
self.actions,
self.queries,
self.transforms
);
let hash = Sha256::digest(message.as_bytes());
let encoded: String = hash.encode_hex();
// Return prefixed hash, since multi-chain tasks require simpler identification
// Using the specified native_denom, if none, no prefix
// Example:
// No prefix: fca49b82eb84818215768293c9e57e7d4194a7c862538e1dedb4516bf2dff0ca (No longer used/stored)
// with prefix: stars:82eb84818215768293c9e57e7d4194a7c862538e1dedb4516bf2dff0ca
// with prefix: longnetwork:818215768293c9e57e7d4194a7c862538e1dedb4516bf2dff0ca
let (_, l) = encoded.split_at(prefix.len() + 1);
format!("{}:{}", prefix, l)
}
/// Get the hash of a task based on parameters
pub fn to_hash_vec(&self, prefix: &str) -> Vec<u8> {
self.to_hash(prefix).into_bytes()
}
pub fn recurring(&self) -> bool {
!matches!(self.interval, Interval::Once)
}
pub fn is_evented(&self) -> bool {
!self.queries.is_empty()
&& (self.interval == Interval::Once || self.interval == Interval::Immediate)
}
pub fn into_response(self, prefix: &str) -> TaskResponse {
let task_hash = self.to_hash(prefix);
let queries = if !self.queries.is_empty() {
Some(self.queries)
} else {
None
};
TaskResponse {
task: Some(TaskInfo {
task_hash,
owner_addr: self.owner_addr,
interval: self.interval,
boundary: self.boundary,
stop_on_fail: self.stop_on_fail,
amount_for_one_task: self.amount_for_one_task,
actions: self.actions,
queries,
transforms: self.transforms,
version: self.version,
}),
}
}
}
/// Query given module contract with a message
#[cw_serde]
pub struct CroncatQuery {
/// This is address of the queried module contract.
/// For the addr can use one of our croncat-mod-* contracts, or custom contracts
pub contract_addr: String,
pub msg: Binary,
/// For queries with `check_result`: query return value should be formatted as a:
/// [`QueryResponse`](mod_sdk::types::QueryResponse)
pub check_result: bool,
}
/// Query given module contract with a message
#[cw_serde]
pub enum CosmosQuery<T = WasmQuery> {
// For optionally checking results, esp for modules
Croncat(CroncatQuery),
// For covering native wasm query cases (Smart, Raw)
Wasm(T),
}
#[cw_serde]
pub struct SlotTasksTotalResponse {
pub block_tasks: u64,
pub cron_tasks: u64,
pub evented_tasks: u64,
}
#[cw_serde]
pub struct CurrentTaskInfoResponse {
pub total: Uint64,
pub last_created_task: Timestamp,
}
#[cw_serde]
pub struct TaskInfo {
pub task_hash: String,
pub owner_addr: Addr,
pub interval: Interval,
pub boundary: Boundary,
pub stop_on_fail: bool,
pub amount_for_one_task: AmountForOneTask,
pub actions: Vec<Action>,
pub queries: Option<Vec<CosmosQuery>>,
pub transforms: Vec<Transform>,
pub version: String,
}
#[cw_serde]
pub struct TaskResponse {
pub task: Option<TaskInfo>,
}
/// This struct is used in two important places.
/// On the tasks contract, when [`create_task`](crate::msg::TasksExecuteMsg::CreateTask) is called, this struct
/// is returned in the binary data field of the response.
/// It's also saved on the manager contract before [`proxy_call`](https://docs.rs/croncat-sdk-manager/latest/croncat_sdk_manager/msg/enum.ManagerExecuteMsg.html#variant.ProxyCall), allowing for validation
/// on the receiving contract, by doing a raw query to the manager's state key [LAST_TASK_EXECUTION_INFO_KEY](https://docs.rs/croncat-sdk-manager/latest/croncat_sdk_manager/types/constant.LAST_TASK_EXECUTION_INFO_KEY.html).
#[cw_serde]
pub struct TaskExecutionInfo {
pub block_height: u64,
pub tx_info: Option<TransactionInfo>,
pub task_hash: String,
pub owner_addr: Addr,
pub amount_for_one_task: AmountForOneTask,
pub version: String,
}
impl Default for TaskExecutionInfo {
fn default() -> Self {
Self {
block_height: u64::default(),
tx_info: None,
task_hash: String::default(),
owner_addr: Addr::unchecked(""),
amount_for_one_task: AmountForOneTask::default(),
version: String::default(),
}
}
}
#[cw_serde]
pub struct SlotHashesResponse {
pub block_id: u64,
pub block_task_hash: Vec<String>,
pub time_id: u64,
pub time_task_hash: Vec<String>,
}
#[cw_serde]
pub struct SlotIdsResponse {
pub time_ids: Vec<u64>,
pub block_ids: Vec<u64>,
}
#[cw_serde]
pub enum SlotType {
Block,
Cron,
}
impl Display for SlotType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
SlotType::Block => write!(f, "block"),
SlotType::Cron => write!(f, "cron"),
}
}
}
/// Get the next block within the boundary
fn get_next_block_limited(env: &Env, boundary_height: &BoundaryHeight) -> u64 {
let current_block_height = env.block.height;
let next_block_height = match boundary_height.start {
// shorthand - remove 1 since it adds 1 later
Some(id) if current_block_height < id.u64() => id.u64() - 1,
_ => current_block_height,
};
match boundary_height.end {
// stop if passed end height
Some(end) if current_block_height > end.u64() => 0,
// we ONLY want to catch if we're passed the end block height
Some(end) if next_block_height > end.u64() => end.u64(),
// immediate needs to return this block + 1
_ => next_block_height + 1,
}
}
/// Get the next time within the boundary
/// Does not shift the timestamp, to allow better windowed event boundary
fn get_next_time_in_window(env: &Env, boundary: &BoundaryTime) -> u64 {
let current_block_time = env.block.time.nanos();
let next_block_time = match boundary.start {
Some(id) if current_block_time < id.nanos() => id.nanos(),
_ => current_block_time,
};
match boundary.end {
// stop if passed end time
Some(end) if current_block_time > end.nanos() => 0,
// we ONLY want to catch if we're passed the end block time
Some(end) if next_block_time > end.nanos() => end.nanos(),
// immediate needs to return this time
_ => next_block_time,
}
}
/// Either:
/// - Boundary specifies a start/end that block offsets can be computed from
/// - Block offset will truncate to specific modulo offsets
pub(crate) fn get_next_block_by_offset(
block_height: u64,
boundary_height: &BoundaryHeight,
block: u64,
) -> u64 {
let current_block_height = block_height;
let modulo_block = if block > 0 {
current_block_height.saturating_sub(current_block_height % block) + block
} else {
return 0;
};
let next_block_height = match boundary_height.start {
Some(id) if current_block_height < id.u64() => {
let rem = id.u64() % block;
if rem > 0 {
id.u64().saturating_sub(rem) + block
} else {
id.u64()
}
}
_ => modulo_block,
};
match boundary_height.end {
// stop if passed end height
Some(end) if current_block_height > end.u64() => 0,
// we ONLY want to catch if we're passed the end block height
Some(end) => {
let end_height = if let Some(rem) = end.u64().checked_rem(block) {
end.u64().saturating_sub(rem)
} else {
end.u64()
};
// we ONLY want to catch if we're passed the end block height
if next_block_height > end_height {
0
} else {
next_block_height
}
}
None => next_block_height,
}
}
/// Get the slot number (in nanos) of the next task according to boundaries
/// Unless current slot is the end slot, don't put in the current slot
fn get_next_cron_time(
env: &Env,
boundary: &BoundaryTime,
crontab: &str,
slot_granularity_time: u64,
) -> u64 {
let current_block_ts = env.block.time.nanos();
let current_block_slot =
current_block_ts.saturating_sub(current_block_ts % slot_granularity_time);
// get earliest possible time
let current_ts = match boundary.start {
Some(ts) if current_block_ts < ts.nanos() => ts.nanos(),
_ => current_block_ts,
};
// receive time from schedule, calculate slot for this time
let schedule = Schedule::from_str(crontab).unwrap();
let next_ts = schedule.next_after(¤t_ts).unwrap();
let next_ts_slot = next_ts.saturating_sub(next_ts % slot_granularity_time);
// put task in the next slot if next_ts_slot in the current slot
let next_slot = if next_ts_slot == current_block_slot {
next_ts_slot + slot_granularity_time
} else {
next_ts_slot
};
match boundary.end {
Some(end) if current_block_ts > end.nanos() => 0,
Some(end) => {
let end_slot = end
.nanos()
.saturating_sub(end.nanos() % slot_granularity_time);
u64::min(end_slot, next_slot)
}
_ => next_slot,
}
}
#[cfg(test)]
mod test {
use cosmwasm_std::{testing::mock_env, Addr, CosmosMsg, Timestamp, Uint64, WasmMsg};
use croncat_sdk_core::types::{AmountForOneTask, GasPrice};
use hex::ToHex;
use sha2::{Digest, Sha256};
use crate::types::{Action, BoundaryHeight, CosmosQuery, CroncatQuery, Transform};
use super::{Boundary, BoundaryTime, Interval, SlotType, Task};
const TWO_MINUTES: u64 = 120_000_000_000;
#[test]
fn is_valid_test() {
let once = Interval::Once;
assert!(once.is_valid());
let immediate = Interval::Immediate;
assert!(immediate.is_valid());
let block = Interval::Block(100);
assert!(block.is_valid());
let cron_correct = Interval::Cron("1 * * * * *".to_string());
assert!(cron_correct.is_valid());
let cron_wrong = Interval::Cron("1 * * * * * *".to_string());
assert!(cron_wrong.is_valid());
}
#[test]
fn hashing() {
let task = Task {
owner_addr: Addr::unchecked("bob"),
interval: Interval::Block(5),
boundary: Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(4)),
end: None,
}),
stop_on_fail: false,
amount_for_one_task: AmountForOneTask {
cw20: None,
coin: [None, None],
gas: 100,
agent_fee: u16::default(),
treasury_fee: u16::default(),
gas_price: GasPrice::default(),
},
actions: vec![Action {
msg: CosmosMsg::Wasm(WasmMsg::ClearAdmin {
contract_addr: "alice".to_string(),
}),
gas_limit: Some(5),
}],
queries: vec![CosmosQuery::Croncat(CroncatQuery {
msg: Default::default(),
contract_addr: "addr".to_owned(),
check_result: true,
})],
transforms: vec![Transform {
action_idx: 0,
query_idx: 0,
action_path: vec![].into(),
query_response_path: vec![].into(),
}],
version: String::from(""),
};
let message = format!(
"{:?}{:?}{:?}{:?}{:?}{:?}",
task.owner_addr,
task.interval,
task.boundary,
task.actions,
task.queries,
task.transforms
);
let hash = Sha256::digest(message.as_bytes());
let encode: String = hash.encode_hex();
let prefix = "atom";
let (_, l) = encode.split_at(prefix.len() + 1);
let encoded = format!("{}:{}", prefix, l);
let bytes = encoded.clone().into_bytes();
// Tests
assert_eq!(encoded, task.to_hash(prefix));
assert_eq!(bytes, task.to_hash_vec(prefix));
}
#[test]
fn interval_get_next_block_limited() {
// (input, input, outcome, outcome)
let cases: Vec<(Interval, Boundary, u64, SlotType)> = vec![
// Once cases
(
Interval::Once,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
12346,
SlotType::Block,
),
(
Interval::Once,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12348)),
end: None,
}),
12348,
SlotType::Block,
),
(
Interval::Once,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12346)),
}),
12346,
SlotType::Block,
),
(
Interval::Once,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12340)),
}),
0,
SlotType::Block,
),
// Immediate cases
(
Interval::Immediate,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
12346,
SlotType::Block,
),
(
Interval::Immediate,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12348)),
end: None,
}),
12348,
SlotType::Block,
),
(
Interval::Immediate,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12346)),
}),
12346,
SlotType::Block,
),
(
Interval::Immediate,
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12340)),
}),
0,
SlotType::Block,
),
];
// Check all these cases
for (interval, boundary, outcome_block, outcome_slot_kind) in cases.iter() {
let env = mock_env();
let (next_id, slot_kind) = interval.next(&env, boundary, 1);
assert_eq!(outcome_block, &next_id);
assert_eq!(outcome_slot_kind, &slot_kind);
}
}
#[test]
fn interval_get_next_block_by_offset() {
// (input, input, outcome, outcome)
let cases: Vec<(Interval, Boundary, u64, SlotType)> = vec![
// strictly modulo cases
(
Interval::Block(1),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
12346,
SlotType::Block,
),
(
Interval::Block(10),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
12350,
SlotType::Block,
),
(
Interval::Block(100),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
12400,
SlotType::Block,
),
(
Interval::Block(1000),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
13000,
SlotType::Block,
),
(
Interval::Block(10000),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
20000,
SlotType::Block,
),
(
Interval::Block(100000),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: None,
}),
100000,
SlotType::Block,
),
// with another start
(
Interval::Block(1),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12348)),
end: None,
}),
12348,
SlotType::Block,
),
(
Interval::Block(10),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12360)),
end: None,
}),
12360,
SlotType::Block,
),
(
Interval::Block(10),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12364)),
end: None,
}),
12370,
SlotType::Block,
),
(
Interval::Block(100),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12364)),
end: None,
}),
12400,
SlotType::Block,
),
// modulo + boundary end
(
Interval::Block(1),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12345)),
}),
0,
SlotType::Block,
),
(
Interval::Block(10),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12355)),
}),
12350,
SlotType::Block,
),
(
Interval::Block(100),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12355)),
}),
0,
SlotType::Block,
),
(
Interval::Block(100),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12300)),
}),
0,
SlotType::Block,
),
(
Interval::Block(100),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12545)),
}),
12400,
SlotType::Block,
),
(
Interval::Block(100),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(11345)),
end: Some(Uint64::new(11545)),
}),
0,
SlotType::Block,
),
(
Interval::Block(100_000),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(120355)),
}),
100_000,
SlotType::Block,
),
// wrong block interval
(
Interval::Block(100_000),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12355)),
}),
0,
SlotType::Block,
),
(
Interval::Block(0),
Boundary::Height(BoundaryHeight {
start: Some(Uint64::new(12345)),
end: Some(Uint64::new(12355)),
}),
0,
SlotType::Block,
),
];
// Check all these cases
let env = mock_env();
for (interval, boundary, outcome_block, outcome_slot_kind) in cases.iter() {
let (next_id, slot_kind) = interval.next(&env, boundary, 1);
assert_eq!(outcome_block, &next_id);
assert_eq!(outcome_slot_kind, &slot_kind);
}
}
#[test]
fn interval_get_next_cron_time() {
// (input, input, outcome, outcome)
// test the case when slot_granularity_time == 1
let cases: Vec<(Interval, Boundary, u64, SlotType)> = vec![
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_797_420_000_000_000, // current time in nanos is 1_571_797_419_879_305_533
SlotType::Cron,
),
(
Interval::Cron("1 * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_797_441_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("* 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_799_600_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_799_615_000_000_000,
SlotType::Cron,
),
// with another start
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_471_799_600_000_000_000)),
end: None,
}),
1_571_799_615_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_799_600_000_000_000)),
end: None,
}),
1_571_799_615_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_799_700_000_000_000)),
end: None,
}),
1_571_803_215_000_000_000,
SlotType::Cron,
),
// cases when a boundary has end
// current slot is the end slot
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
}),
1_571_797_419_879_305_533,
SlotType::Cron,
),
// the next slot is after the end, return end slot
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_419_879_305_535)),
}),
1_571_797_419_879_305_535,
SlotType::Cron,
),
// next slot in boundaries
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_420_000_000_000)),
}),
1_571_797_420_000_000_000,
SlotType::Cron,
),
// the task has ended
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_419_879_305_532)),
}),
0,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_471_799_600_000_000_000)),
end: Some(Timestamp::from_nanos(1_471_799_600_000_000_000)),
}),
0,
SlotType::Cron,
),
(
Interval::Cron("1 * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_471_797_441_000_000_000)),
end: Some(Timestamp::from_nanos(1_671_797_441_000_000_000)),
}),
1_571_797_441_000_000_000,
SlotType::Cron,
),
];
// Check all these cases
for (interval, boundary, outcome_time, outcome_slot_kind) in cases.iter() {
let env = mock_env();
let (next_id, slot_kind) = interval.next(&env, boundary, 1);
assert_eq!(outcome_time, &next_id);
assert_eq!(outcome_slot_kind, &slot_kind);
}
// slot_granularity_time == 120_000_000_000 ~ 2 minutes
let cases: Vec<(Interval, Boundary, u64, SlotType)> = vec![
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
// the timestamp is in the current slot, so we take the next slot
1_571_797_420_000_000_000_u64
.saturating_sub(1_571_797_420_000_000_000 % TWO_MINUTES)
+ TWO_MINUTES, // current time in nanos is 1_571_797_419_879_305_533
SlotType::Cron,
),
(
Interval::Cron("1 * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_797_440_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("* 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_799_600_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: None,
}),
1_571_799_600_000_000_000,
SlotType::Cron,
),
// with another start
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_471_799_600_000_000_000)),
end: None,
}),
1_571_799_600_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_799_600_000_000_000)),
end: None,
}),
1_571_799_600_000_000_000,
SlotType::Cron,
),
(
Interval::Cron("15 0 * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_799_700_000_000_000)),
end: None,
}),
1_571_803_200_000_000_000,
SlotType::Cron,
),
// cases when a boundary has end
// boundary end in the current slot
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_419_879_305_535)),
}),
1_571_797_320_000_000_000,
SlotType::Cron,
),
// next slot in boundaries
(
Interval::Cron("1 * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_560_000_000_000)),
}),
1_571_797_440_000_000_000,
SlotType::Cron,
),
// next slot after the end, return end slot
(
Interval::Cron("1 * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_420_000_000_000)),
}),
1_571_797_320_000_000_000,
SlotType::Cron,
),
// the task has ended
(
Interval::Cron("* * * * * *".to_string()),
Boundary::Time(BoundaryTime {
start: Some(Timestamp::from_nanos(1_571_797_419_879_305_533)),
end: Some(Timestamp::from_nanos(1_571_797_419_879_305_532)),
}),
0,
SlotType::Cron,
),
];
// Check all these cases
for (interval, boundary, outcome_time, outcome_slot_kind) in cases.iter() {
let env = mock_env();
let (next_id, slot_kind) = interval.next(&env, boundary, TWO_MINUTES);
assert_eq!(outcome_time, &next_id);
assert_eq!(outcome_slot_kind, &slot_kind);
}
}
}