(rpcUrl, rpcMethod, rpcParams = [])
| 12 | * or throws an error in case of failure. |
| 13 | */ |
| 14 | export 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 | |
| 60 | export default jsonRpcRequest; |
no test coverage detected