Smart Contract
Clock
A.30cf5dcf6ea8d379.Clock
1
2/*
3A contract to mock time.
4
5If you want to mock time create an function in your admin that enables the Clock
6The clock will then start at block 0
7use the tick method to tick the time.
8
9```
10 //this is used to mock the clock, NB! Should consider removing this before deploying to mainnet?
11 pub fun tickClock(_ time: UFix64) {
12 pre {
13 self.capability != nil: "Cannot use AdminProxy, ste capability first"
14 }
15 Clock.enable()
16 Clock.tick(time)
17 }
18```
19
20You can then call this from a transaction like this:
21
22```
23import YourThing from "../contracts/YouThing.cdc"
24
25transaction(clock: UFix64) {
26 prepare(account: AuthAccount) {
27
28 let adminClient=account.borrow<&YourThing.AdminProxy>(from: YourThing.AdminProxyStoragePath)!
29 adminClient.tickClock(clock)
30
31 }
32}
33```
34
35In order to read the mocked time you use the following code in cadence
36
37```
38Clock.time()
39```
40
41Limitations:
42 - all contracts must live in the same account to (ab)use this trick
43
44*/
45pub contract Clock{
46 //want to mock time on emulator.
47 access(contract) var fakeClock:UFix64
48 access(contract) var enabled:Bool
49
50
51 access(account) fun tick(_ duration: UFix64) {
52 self.fakeClock = self.fakeClock + duration
53 }
54
55
56 access(account) fun enable() {
57 self.enabled=true
58 }
59
60 //mocking the time! Should probably remove self.fakeClock in mainnet?
61 pub fun time() : UFix64 {
62 if self.enabled {
63 return self.fakeClock
64 }
65 return getCurrentBlock().timestamp
66 }
67
68 init() {
69 self.fakeClock=0.0
70 self.enabled=false
71 }
72
73}
74