-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.js
52 lines (45 loc) · 1.42 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
import fetch from 'node-fetch';
export class SimpleRpcClient {
constructor(rpcUrl, rpcUser = '', rpcPassword = '') {
this.rpcUrl = rpcUrl;
if (rpcUser && rpcPassword) {
this.authHeader = 'Basic ' + Buffer.from(`${rpcUser}:${rpcPassword}`).toString('base64');
}
this.id = 1;
}
async request(method, params = []) {
const rpcRequest = {
jsonrpc: '2.0',
id: this.id++,
method: method,
params: params
};
let headers = {
'Content-Type': 'application/json',
};
if (this.authHeader) {
headers['Authorization'] = this.authHeader;
}
try {
const response = await fetch(this.rpcUrl, {
method: 'POST',
headers,
body: JSON.stringify(rpcRequest)
});
const responseText = await response.text();
let data;
try {
data = JSON.parse(responseText);
} catch (parseError) {
console.error('Error parsing JSON:', parseError);
throw new Error(`Failed to parse response: ${responseText}`);
}
if (data.error) {
throw new Error(`RPC error: ${JSON.stringify(data.error)}`);
}
return data.result;
} catch (error) {
throw error;
}
}
}