From ea72d9979828c17fa95e89cc8be3a85b532f265f Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Tue, 17 May 2022 11:50:52 +0200 Subject: [PATCH] [clock] Add Clock interface that abstracts away ethereum details --- dagger/clock.nim | 6 ++++++ dagger/contracts/clock.nim | 14 +++++++------- tests/contracts/testClock.nim | 8 ++++---- 3 files changed, 17 insertions(+), 11 deletions(-) create mode 100644 dagger/clock.nim diff --git a/dagger/clock.nim b/dagger/clock.nim new file mode 100644 index 00000000..00728888 --- /dev/null +++ b/dagger/clock.nim @@ -0,0 +1,6 @@ +type + Clock* = ref object of RootObj + SecondsSince1970* = int64 + +method now*(clock: Clock): SecondsSince1970 {.base.} = + raiseAssert "not implemented" diff --git a/dagger/contracts/clock.nim b/dagger/contracts/clock.nim index 334d2dff..584c16c4 100644 --- a/dagger/contracts/clock.nim +++ b/dagger/contracts/clock.nim @@ -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 diff --git a/tests/contracts/testClock.nim b/tests/contracts/testClock.nim index 95266f82..37d5cada 100644 --- a/tests/contracts/testClock.nim +++ b/tests/contracts/testClock.nim @@ -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()