2022-05-16 13:38:52 +00:00
|
|
|
import std/times
|
|
|
|
import pkg/ethers
|
|
|
|
import pkg/chronos
|
|
|
|
import pkg/stint
|
2022-05-17 09:50:52 +00:00
|
|
|
import ../clock
|
2022-05-16 13:38:52 +00:00
|
|
|
|
|
|
|
type
|
2022-05-17 09:50:52 +00:00
|
|
|
OnChainClock* = ref object of Clock
|
2022-05-16 13:38:52 +00:00
|
|
|
provider: Provider
|
|
|
|
subscription: Subscription
|
|
|
|
offset: int64
|
|
|
|
started: bool
|
|
|
|
|
2022-05-17 09:50:52 +00:00
|
|
|
proc new*(_: type OnChainClock, provider: Provider): OnChainClock =
|
|
|
|
OnChainClock(provider: provider)
|
2022-05-16 13:38:52 +00:00
|
|
|
|
2022-05-17 09:50:52 +00:00
|
|
|
proc start*(clock: OnChainClock) {.async.} =
|
2022-05-16 13:38:52 +00:00
|
|
|
if clock.started:
|
|
|
|
return
|
|
|
|
clock.started = true
|
|
|
|
|
|
|
|
proc onBlock(blck: Block) {.gcsafe, upraises:[].} =
|
|
|
|
let blockTime = blck.timestamp.truncate(int64)
|
|
|
|
let computerTime = getTime().toUnix
|
|
|
|
clock.offset = blockTime - computerTime
|
|
|
|
|
|
|
|
onBlock(!await clock.provider.getBlock(BlockTag.latest))
|
|
|
|
|
|
|
|
clock.subscription = await clock.provider.subscribe(onBlock)
|
|
|
|
|
2022-05-17 09:50:52 +00:00
|
|
|
proc stop*(clock: OnChainClock) {.async.} =
|
2022-05-16 13:38:52 +00:00
|
|
|
if not clock.started:
|
|
|
|
return
|
|
|
|
clock.started = false
|
|
|
|
|
|
|
|
await clock.subscription.unsubscribe()
|
|
|
|
|
2022-05-17 09:50:52 +00:00
|
|
|
method now*(clock: OnChainClock): SecondsSince1970 =
|
2022-05-16 13:38:52 +00:00
|
|
|
doAssert clock.started, "clock should be started before calling now()"
|
|
|
|
getTime().toUnix + clock.offset
|