From 42b05e7bb57f5c85b25c4ca954013a8c15438da4 Mon Sep 17 00:00:00 2001 From: tate Date: Thu, 24 Aug 2023 11:49:11 +1000 Subject: [PATCH] fix: graceful balance query error --- src/index.ts | 40 ++++++++++++++++++++++++++++++++++++---- 1 file changed, 36 insertions(+), 4 deletions(-) diff --git a/src/index.ts b/src/index.ts index 1ca525c..142bbba 100644 --- a/src/index.ts +++ b/src/index.ts @@ -7,19 +7,38 @@ export interface Env { RELAYER_AUTH: string; } -type JsonRPC = { +type JsonRpc = { jsonrpc: string; id: string | number | null; method: string; params: any; }; -type BaseJsonRPCResponse = { +type RpcError = { + code: number; + message: string; +}; + +type BaseJsonRpcResponse = { jsonrpc: string; id: string | number | null; + result?: string; + error?: RpcError; +}; + +type SuccessJsonRpcResponse = { result: string; + error?: never; }; +type ErrorJsonRpcResponse = { + result?: never; + error: RpcError; +}; + +type JsonRpcResponse = BaseJsonRpcResponse & + (SuccessJsonRpcResponse | ErrorJsonRpcResponse); + const SUPPORTED_METHODS = [ "faucet_status", "faucet_getAddress", @@ -55,7 +74,7 @@ const query = ({ "Content-Type": "application/json", }, body: JSON.stringify({ jsonrpc: "2.0", method, params, id: 1 }), - }).then((res) => res.json()); + }).then((res) => res.json()); type DomainArray = { id: string }[]; @@ -132,7 +151,7 @@ export default { return makeResponse(`Unsupported method: ${request.method}`, 405); } - const body = await request.json().catch(() => null); + const body = await request.json().catch(() => null); if (!body || !body.jsonrpc || !body.method || !body.params) { return makeRpcResponse( @@ -184,6 +203,19 @@ export default { method: "eth_getBalance", params: [item.address, "latest"], }); + if ("error" in balanceResponse && balanceResponse.error) { + const { code, message } = balanceResponse.error; + return makeRpcResponse( + { + error: { + code: -32000, + message: `Error fetching balance (${code}): ${message}`, + }, + }, + body.id, + 400 + ); + } const balance = BigInt(balanceResponse.result); if (claimAmount > balance) {