-
Notifications
You must be signed in to change notification settings - Fork 45
/
Copy pathrpc.js
94 lines (78 loc) · 2.62 KB
/
rpc.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
export default class RPC {
constructor(web3) {
this.web3 = web3
}
sendAsync(method, arg) {
const req = {
jsonrpc: "2.0",
method: method,
id: new Date().getTime()
}
if (arg) req.params = arg
return new Promise((resolve, reject) => {
return this.web3.currentProvider.send(req, (err, result) => {
if (err) {
reject(err)
} else if (result && result.error) {
reject(new Error("RPC Error: " + (result.error.message || result.error)))
} else {
resolve(result)
}
})
})
}
// Change block time using TestRPC call evm_setTimestamp
// https://github.com/numerai/contract/blob/master/test/numeraire.js
increaseTime(time) {
return this.sendAsync("evm_increaseTime", [time])
}
mine() {
return this.sendAsync("evm_mine")
}
snapshot() {
return this.sendAsync("evm_snapshot")
.then(res => res.result)
}
revert(snapshotId) {
return this.sendAsync("evm_revert", [snapshotId])
}
async wait(blocks = 1, seconds = 20) {
const currentBlock = await this.getBlockNumberAsync()
const targetBlock = currentBlock + blocks
await this.waitUntilBlock(targetBlock, seconds)
}
async waitUntilBlock(targetBlock, seconds = 20) {
let currentBlock = await this.getBlockNumberAsync()
while (currentBlock < targetBlock) {
await this.increaseTime(seconds)
await this.mine()
currentBlock++
}
}
async waitUntilNextBlockMultiple(blockMultiple, multiples = 1, seconds = 20) {
const currentBlock = await this.getBlockNumberAsync()
const additionalBlocks = (multiples - 1) * blockMultiple
await this.waitUntilBlock(this.nextBlockMultiple(currentBlock, blockMultiple) + additionalBlocks)
}
getBlockNumberAsync() {
return new Promise((resolve, reject) => {
return this.web3.eth.getBlockNumber((err, blockNum) => {
if (err) {
reject(err)
} else {
resolve(blockNum)
}
})
})
}
nextBlockMultiple(currentBlockNum, blockMultiple) {
if (blockMultiple === 0) {
return currentBlockNum
}
const remainder = currentBlockNum % blockMultiple
if (remainder === 0) {
return currentBlockNum
}
return currentBlockNum + blockMultiple - remainder
}
}