-
Notifications
You must be signed in to change notification settings - Fork 13
/
utils.js
58 lines (52 loc) · 1.63 KB
/
utils.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
// Returns the time of the last mined block in seconds
function latestTime() {
return web3.eth.getBlock('latest').timestamp;
}
// Increases testrpc time by the passed duration in seconds
function increaseTime(duration) {
const id = Date.now()
return new Promise((resolve, reject) => {
web3.currentProvider.sendAsync({
jsonrpc: '2.0',
method: 'evm_increaseTime',
params: [duration],
id: id,
}, err1 => {
if (err1) return reject(err1)
web3.currentProvider.sendAsync({
jsonrpc: '2.0',
method: 'evm_mine',
id: id+1,
}, (err2, res) => {
return err2 ? reject(err2) : resolve(res)
})
})
})
}
/**
* Beware that due to the need of calling two separate testrpc methods and rpc calls overhead
* it's hard to increase time precisely to a target point so design your test to tolerate
* small fluctuations from time to time.
*
* @param target time in seconds
*/
function increaseTimeTo(target) {
let now = latestTime();
if (target < now) throw Error(`Cannot increase current time(${now}) to a moment in the past(${target})`);
let diff = target - now;
return increaseTime(diff);
}
const duration = {
seconds: function(val) { return val},
minutes: function(val) { return val * this.seconds(60) },
hours: function(val) { return val * this.minutes(60) },
days: function(val) { return val * this.hours(24) },
weeks: function(val) { return val * this.days(7) },
years: function(val) { return val * this.days(365)}
}
module.exports = {
latestTime: latestTime,
increaseTime: increaseTime,
increaseTimeTo: increaseTimeTo,
duration: duration
}