-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRpcClient.js
95 lines (84 loc) · 3.02 KB
/
RpcClient.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
95
const http = require('http');
const { BufferUtils } = require('@nimiq/core');
class RpcClient {
constructor(host, port) {
this._host = host;
this._port = port;
}
async isConnected() {
try {
return !!await this.getBlockHeight();
} catch (e) {
return false;
}
}
async getBlockHeight() {
return this._jsonRpcFetch('blockNumber');
}
async getBalance(address) {
return this._jsonRpcFetch('getBalance', address.toUserFriendlyAddress());
}
async getMempoolTransactions(includeTransactions = false) {
return this._jsonRpcFetch('mempoolContent', includeTransactions);
}
async getTransactionReceipt(txHash) {
return this._jsonRpcFetch('getTransactionReceipt', txHash);
}
async getTransactionsByAddress(address) {
return this._jsonRpcFetch('getTransactionsByAddress', address.toUserFriendlyAddress());
}
async sendTransaction(transaction) {
return this._jsonRpcFetch('sendRawTransaction', BufferUtils.toHex(transaction.serialize()));
}
// from JsonRpcServer in core
async _jsonRpcFetch(method, ...params) {
return new Promise((resolve, fail) => {
while (params.length > 0 && typeof params[params.length - 1] === 'undefined') params.pop();
const jsonrpc = JSON.stringify({
jsonrpc: '2.0',
id: 42,
method: method,
params: params
});
const headers = {'Content-Length': jsonrpc.length};
const req = http.request({
hostname: this._host,
port: this._port,
method: 'POST',
headers: headers
}, (res) => {
if (res.statusCode === 401) {
fail(new Error(`Request Failed: Authentication Required. Status Code: ${res.statusCode}`));
res.resume();
return;
}
if (res.statusCode !== 200) {
fail(new Error(`Request Failed. ${res.statusMessage? `${res.statusMessage} - `
: ''}Status Code: ${res.statusCode}`));
res.resume();
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('error', fail);
res.on('data', (chunk) => { rawData += chunk; });
res.on('end', () => {
try {
const parse = JSON.parse(rawData);
if (parse.error) {
fail(parse.error.message);
} else {
resolve(parse.result);
}
} catch (e) {
fail(e);
}
});
});
req.on('error', fail);
req.write(jsonrpc);
req.end();
});
}
}
module.exports = RpcClient;