Smart Contract
VolumeControl
A.08dd120226ec2213.VolumeControl
1access(all) contract VolumeControl {
2
3 access(all) let AdminPath: StoragePath
4 // ========== events ==========
5 access(all) event EpochLengthUpdated(length: UInt64)
6
7 access(all) var epochLength: UInt64 // seconds, how soon the volume in last window will be clear
8 access(account) var epochVolumes: {String: UFix64} // the sum volume in last time window
9 access(account) var lastOpTimestamps: {String: UInt64} // unix seconds, the last time window record the volume
10
11 // ========== admin resource ==========
12 access(all) resource Admin {
13 access(all) fun setEpochLength(newLength: UInt64) {
14 VolumeControl.epochLength = newLength
15 emit EpochLengthUpdated(
16 length: newLength
17 )
18 }
19
20 // createNewAdmin creates a new Admin resource
21 access(all) fun createNewAdmin(): @Admin {
22 return <-create Admin()
23 }
24 }
25
26 // ========== functions ==========
27 init() {
28 self.epochLength = 0
29 self.epochVolumes = {}
30 self.lastOpTimestamps = {}
31 self.AdminPath = /storage/VolumeControlAdmin
32 self.account.storage.save<@Admin>(<- create Admin(), to: self.AdminPath)
33 }
34
35 access(account) fun updateVolume(token: String, amt: UFix64, cap: UFix64) {
36 if self.epochLength == 0 {
37 return
38 }
39 if cap == 0.0 {
40 return
41 }
42 var volume = self.epochVolumes[token] ?? 0.0
43 let timestamp = UInt64(getCurrentBlock().timestamp)
44 let epochStartTime = (timestamp / self.epochLength) * self.epochLength;
45 let lastOpTimestamp = self.lastOpTimestamps[token] ?? 0
46 if (lastOpTimestamp < epochStartTime) {
47 volume = amt
48 } else {
49 volume = volume + amt;
50 }
51 assert(volume <= cap, message: "volume exceeds cap")
52 self.epochVolumes[token] = volume;
53 self.lastOpTimestamps[token] = timestamp;
54 }
55
56 access(all) view fun getEpochVolume(token: String): UFix64 {
57 return self.epochVolumes[token] ?? 0.0
58 }
59
60 access(all) view fun getLastOpTimestamp(token: String): UInt64 {
61 return self.lastOpTimestamps[token] ?? 0
62 }
63}