[clock] Add Clock interface that abstracts away ethereum details

This commit is contained in:
Mark Spanbroek 2022-05-17 11:50:52 +02:00 committed by markspanbroek
parent fa84861d86
commit ea72d99798
3 changed files with 17 additions and 11 deletions

6
dagger/clock.nim Normal file
View File

@ -0,0 +1,6 @@
type
Clock* = ref object of RootObj
SecondsSince1970* = int64
method now*(clock: Clock): SecondsSince1970 {.base.} =
raiseAssert "not implemented"

View File

@ -2,19 +2,19 @@ import std/times
import pkg/ethers
import pkg/chronos
import pkg/stint
import ../clock
type
Clock* = ref object
OnChainClock* = ref object of Clock
provider: Provider
subscription: Subscription
offset: int64
started: bool
SecondsSince1970* = int64
proc new*(_: type Clock, provider: Provider): Clock =
Clock(provider: provider)
proc new*(_: type OnChainClock, provider: Provider): OnChainClock =
OnChainClock(provider: provider)
proc start*(clock: Clock) {.async.} =
proc start*(clock: OnChainClock) {.async.} =
if clock.started:
return
clock.started = true
@ -28,13 +28,13 @@ proc start*(clock: Clock) {.async.} =
clock.subscription = await clock.provider.subscribe(onBlock)
proc stop*(clock: Clock) {.async.} =
proc stop*(clock: OnChainClock) {.async.} =
if not clock.started:
return
clock.started = false
await clock.subscription.unsubscribe()
proc now*(clock: Clock): SecondsSince1970 =
method now*(clock: OnChainClock): SecondsSince1970 =
doAssert clock.started, "clock should be started before calling now()"
getTime().toUnix + clock.offset

View File

@ -3,12 +3,12 @@ import pkg/chronos
import dagger/contracts/clock
import ../ethertest
ethersuite "Clock":
ethersuite "On-Chain Clock":
var clock: Clock
var clock: OnChainClock
setup:
clock = Clock.new(provider)
clock = OnChainClock.new(provider)
await clock.start()
teardown:
@ -32,7 +32,7 @@ ethersuite "Clock":
test "raises when not started":
expect AssertionError:
discard Clock.new(provider).now()
discard OnChainClock.new(provider).now()
test "raises when stopped":
await clock.stop()