2022-05-16 13:38:52 +00:00
|
|
|
import std/times
|
|
|
|
import pkg/chronos
|
2022-05-19 19:56:03 +00:00
|
|
|
import codex/contracts/clock
|
2023-12-07 01:16:36 +00:00
|
|
|
import codex/utils/json
|
2022-05-16 13:38:52 +00:00
|
|
|
import ../ethertest
|
|
|
|
|
2022-05-17 09:50:52 +00:00
|
|
|
ethersuite "On-Chain Clock":
|
|
|
|
var clock: OnChainClock
|
2022-05-16 13:38:52 +00:00
|
|
|
|
|
|
|
setup:
|
2022-05-17 09:50:52 +00:00
|
|
|
clock = OnChainClock.new(provider)
|
2022-05-16 13:38:52 +00:00
|
|
|
await clock.start()
|
|
|
|
|
|
|
|
teardown:
|
|
|
|
await clock.stop()
|
|
|
|
|
|
|
|
test "returns the current time of the EVM":
|
|
|
|
let latestBlock = (!await provider.getBlock(BlockTag.latest))
|
|
|
|
let timestamp = latestBlock.timestamp.truncate(int64)
|
|
|
|
check clock.now() == timestamp
|
|
|
|
|
|
|
|
test "updates time with timestamp of new blocks":
|
|
|
|
let future = (getTime() + 42.years).toUnix
|
|
|
|
discard await provider.send("evm_setNextBlockTimestamp", @[%future])
|
|
|
|
discard await provider.send("evm_mine")
|
|
|
|
check clock.now() == future
|
|
|
|
|
|
|
|
test "updates time using wall-clock in-between blocks":
|
|
|
|
let past = clock.now()
|
|
|
|
await sleepAsync(chronos.seconds(1))
|
2022-05-18 12:47:24 +00:00
|
|
|
check clock.now() > past
|
2022-05-16 13:38:52 +00:00
|
|
|
|
2023-07-13 09:19:45 +00:00
|
|
|
test "can wait until a certain time is reached by the chain":
|
|
|
|
let future = clock.now() + 42 # seconds
|
|
|
|
let waiting = clock.waitUntil(future)
|
|
|
|
discard await provider.send("evm_setNextBlockTimestamp", @[%future])
|
|
|
|
discard await provider.send("evm_mine")
|
|
|
|
check await waiting.withTimeout(chronos.milliseconds(100))
|
|
|
|
|
|
|
|
test "can wait until a certain time is reached by the wall-clock":
|
|
|
|
let future = clock.now() + 1 # seconds
|
|
|
|
let waiting = clock.waitUntil(future)
|
|
|
|
check await waiting.withTimeout(chronos.seconds(2))
|
|
|
|
|
2022-05-16 13:38:52 +00:00
|
|
|
test "raises when not started":
|
2023-03-09 11:23:45 +00:00
|
|
|
expect AssertionDefect:
|
2022-05-17 09:50:52 +00:00
|
|
|
discard OnChainClock.new(provider).now()
|
2022-05-16 13:38:52 +00:00
|
|
|
|
|
|
|
test "raises when stopped":
|
|
|
|
await clock.stop()
|
2023-03-09 11:23:45 +00:00
|
|
|
expect AssertionDefect:
|
2022-05-16 13:38:52 +00:00
|
|
|
discard clock.now()
|
|
|
|
|
|
|
|
test "handles starting multiple times":
|
|
|
|
await clock.start()
|
|
|
|
await clock.start()
|
|
|
|
|
|
|
|
test "handles stopping multiple times":
|
|
|
|
await clock.stop()
|
|
|
|
await clock.stop()
|