-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
63 lines (50 loc) · 1.44 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
module.exports = function (perSecond, minSeconds = 0, offset = 0) {
if (perSecond === undefined) throw new Error('rate must be specified')
const payments = []
function add (payment) {
if (payment.amount === undefined || payment.time === undefined) {
throw new Error('payment must be of format { amount: x, time: y }')
}
payments.push(payment)
}
function active () {
if (!perSecond) return true
return remainingFunds() > 0
}
function remainingTime () {
const funds = remainingFunds()
return Math.floor(Math.max(0, funds / perSecond * 1000))
}
function remainingFunds () {
let now = Date.now() + minSeconds * 1000
now -= offset // compensate delay for the seller to receive block
let funds = 0
for (let i = 0; i < payments.length; i++) {
const { amount, time } = payments[i]
const nextTime = i + 1 < payments.length ? payments[i + 1].time : now
// add current payment
funds += amount
// subtract amount spent since previous payment
const consumed = Math.max(0, perSecond * (nextTime - time) / 1000)
funds -= consumed
// if funds are out, clear all earlier payments
if (funds < 0) {
payments.splice(0, i + 1)
i = -1
funds = 0
}
}
return funds
}
function gc () {
remainingFunds()
return payments.length
}
return {
add,
active,
remainingTime,
remainingFunds,
gc
}
}