-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpcUtil.js
More file actions
48 lines (43 loc) · 1.38 KB
/
rpcUtil.js
File metadata and controls
48 lines (43 loc) · 1.38 KB
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
import { proxyFetch } from './fetchUtil.js';
/**
* Perform a JSON-RPC call with timeout and error handling.
* @param {string} url - RPC endpoint URL
* @param {string} method - JSON-RPC method name
* @param {Object} options - Optional configuration
* @param {Array} options.params - JSON-RPC params (default: [])
* @param {number} options.timeoutMs - Timeout in milliseconds (default: 10000)
* @returns {Promise<*>} The result field from the JSON-RPC response
*/
export async function jsonRpcCall(url, method, { params = [], timeoutMs = 10000 } = {}) {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
try {
const response = await proxyFetch(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method,
params,
}),
signal: controller.signal,
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const body = await response.json();
if (body.error) {
const message = body.error.message || JSON.stringify(body.error);
throw new Error(message);
}
return body.result;
} catch (error) {
if (error.name === 'AbortError') {
throw new Error('RPC request timed out');
}
throw error;
} finally {
clearTimeout(timeoutId);
}
}