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

View File

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