import getNextRequestId from "./getNextRequestId";

/**
 * Sends an RPC request to a Solana RPC node.
 *
 * @param rpcNodeURL
 * @param method
 * @param params
 * @returns {Promise<any>}
 */

interface RPCCallParams {
  abortSignal: AbortSignal;
  method: string;
  params?: any[];
  rpcNodeURL: string;
}

export async function makeRPCCall({ abortSignal, method, params, rpcNodeURL }: RPCCallParams) {
  try {
    const response = await fetch(rpcNodeURL, {
      body: JSON.stringify({
        jsonrpc: "2.0",
        id: getNextRequestId().toString(),
        method,
        params,
      }),
      headers: {
        "Content-Type": "application/json",
      },
      method: "POST",
      signal: abortSignal,
    });
    return await response.json();
  } catch (e) {
    throw e;
  }
}
