-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathrpc.ts
79 lines (64 loc) · 2.12 KB
/
rpc.ts
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
import {ethers} from "ethers"
export default class RPC {
constructor(public provider: ethers.providers.JsonRpcProvider) {}
sendAsync(method: string, arg: any[]) {
try {
return this.provider.send(method, arg)
} catch (error: any) {
throw error
}
}
// Change block time using TestRPC call evm_setTimestamp
// https://github.com/numerai/contract/blob/master/test/numeraire.js
increaseTime(time: number) {
return this.sendAsync("evm_increaseTime", [time])
}
mine() {
return this.sendAsync("evm_mine", [])
}
async snapshot() {
const id = await this.sendAsync("evm_snapshot", [])
return id
}
revert(snapshotId: number) {
return this.sendAsync("evm_revert", [snapshotId])
}
async wait(blocks = 1, seconds = 20) {
const currentBlock = await this.provider.getBlockNumber()
const targetBlock = currentBlock + blocks
await this.waitUntilBlock(targetBlock, seconds)
}
async getBlockNumberAsync() {
return this.provider.getBlockNumber()
}
async waitUntilBlock(targetBlock: number, seconds = 20) {
let currentBlock = await this.provider.getBlockNumber()
while (currentBlock < targetBlock) {
await this.increaseTime(seconds)
await this.mine()
currentBlock++
}
}
async waitUntilNextBlockMultiple(
blockMultiple: number,
multiples = 1,
seconds = 20
) {
const currentBlock = await this.provider.getBlockNumber()
const additionalBlocks = (multiples - 1) * blockMultiple
await this.waitUntilBlock(
this.nextBlockMultiple(currentBlock, blockMultiple) +
additionalBlocks
)
}
nextBlockMultiple(currentBlockNum: number, blockMultiple: number) {
if (blockMultiple === 0) {
return currentBlockNum
}
const remainder = currentBlockNum % blockMultiple
if (remainder === 0) {
return currentBlockNum
}
return currentBlockNum + blockMultiple - remainder
}
}