From 8501074b25967c141e28c4a3d499a7a3741280b2 Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Mon, 27 Mar 2023 08:04:12 -0400 Subject: [PATCH] *refactor handling of requests and responses *Ensure consensus query args are handled correctly --- src/index.ts | 49 +++++++++++++++++++++++++++++++++++++------------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/src/index.ts b/src/index.ts index 844a5e8..03e49f2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,22 +1,29 @@ import type { Plugin, PluginAPI } from "@lumeweb/interface-relay"; import fetch, { Request, RequestInit } from "node-fetch"; +import { URL } from "url"; + const EXECUTION_RPC_URL = "https://g.w.lavanet.xyz:443/gateway/eth/rpc-http/f195d68175eb091ec1f71d00f8952b85"; const CONSENSUS_RPC_URL = "https://www.lightclientdata.org"; async function doFetch(url: string, request: RequestInit) { - sanitizeRequestArgs(request); + sanitizeRequestArgs(url, request); - let req = new Request(url, request); + let req = new Request(url, { + ...request, + headers: { + "Content-Type": "application/json", + }, + }); const resp = await fetch(req); return (await resp.json()) as any; } -function sanitizeRequestArgs(request: RequestInit) { +function sanitizeRequestArgs(url: string, request: RequestInit) { if (!request || typeof request !== "object") { throw Error("invalid request"); } @@ -40,20 +47,38 @@ function sanitizeRequestArgs(request: RequestInit) { }); } +interface ConsensusRequest extends RequestInit { + path: string; +} +interface ExecutionRequest { + method: string; + params: string; +} + const plugin: Plugin = { name: "eth", async plugin(api: PluginAPI): Promise { - api.registerMethod("execution_request", { - cacheable: false, - async handler(request: RequestInit): Promise { - return doFetch(EXECUTION_RPC_URL, request); - }, - }); - api.registerMethod("consensus_request", { cacheable: false, - async handler(request: RequestInit): Promise { - return doFetch(CONSENSUS_RPC_URL, request); + async handler(request: ConsensusRequest): Promise { + const consensusUrl = new URL(CONSENSUS_RPC_URL); + + let dummyUrl = new URL( + `http://dummy/${request.path.replace(/^\/+/, "")}` + ); + consensusUrl.pathname = dummyUrl.pathname; + consensusUrl.search = dummyUrl.search; + + return doFetch(consensusUrl.toString(), request); + }, + }); + api.registerMethod("execution_request", { + cacheable: false, + async handler(request: ExecutionRequest): Promise { + return doFetch(EXECUTION_RPC_URL, { + method: "POST", + body: JSON.stringify(request), + }); }, }); },