MCPcopy Create free account
hub / github.com/ICBNetwork/web3-Wallet / jsonRpcRequest

Function jsonRpcRequest

app/util/jsonRpcRequest.js:14–58  ·  view source on GitHub ↗
(rpcUrl, rpcMethod, rpcParams = [])

Source from the content-addressed store, hash-verified

12 * or throws an error in case of failure.
13 */
14export async function jsonRpcRequest(rpcUrl, rpcMethod, rpcParams = []) {
15 let fetchUrl = rpcUrl;
16 const headers = {
17 'Content-Type': 'application/json',
18 };
19
20 // Convert basic auth URL component to Authorization header
21 const { origin, pathname, username, password, search } = new URL(rpcUrl);
22 // URLs containing username and password needs special processing
23 if (username && password) {
24 const encodedAuth = Buffer.from(`${username}:${password}`).toString(
25 'base64',
26 );
27 headers.Authorization = `Basic ${encodedAuth}`;
28 fetchUrl = `${origin}${pathname}${search}`;
29 }
30
31 const jsonRpcResponse = await fetch(fetchUrl, {
32 method: 'POST',
33 body: JSON.stringify({
34 id: Date.now().toString(),
35 jsonrpc: '2.0',
36 method: rpcMethod,
37 params: rpcParams,
38 }),
39 headers,
40 cache: 'default',
41 });
42
43 const jsonRpcResponseJson = await jsonRpcResponse.json();
44
45 if (
46 !jsonRpcResponseJson ||
47 Array.isArray(jsonRpcResponseJson) ||
48 typeof jsonRpcResponseJson !== 'object'
49 ) {
50 throw new Error(`RPC endpoint ${rpcUrl} returned non-object response.`);
51 }
52 const { error, result } = jsonRpcResponseJson;
53
54 if (error) {
55 throw new Error(error?.message || error);
56 }
57 return result;
58}
59
60export default jsonRpcRequest;

Callers 2

index.jsFile · 0.90
wallet_addEthereumChainFunction · 0.90

Calls 1

toStringMethod · 0.80

Tested by

no test coverage detected