From 91f3551a70c83a8ff837c8e3d8805117ac9fc167 Mon Sep 17 00:00:00 2001 From: Prithvish Baidya Date: Sat, 2 Nov 2024 04:26:42 +0530 Subject: [PATCH] 400 for user errors --- src/server/routes/contract/read/read.ts | 22 ++++++++++++++++++++-- test/e2e/tests/read.test.ts | 25 +++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 4 deletions(-) diff --git a/src/server/routes/contract/read/read.ts b/src/server/routes/contract/read/read.ts index 46dc8fffd..65a335622 100644 --- a/src/server/routes/contract/read/read.ts +++ b/src/server/routes/contract/read/read.ts @@ -2,6 +2,7 @@ import { Type } from "@sinclair/typebox"; import type { FastifyInstance } from "fastify"; import { StatusCodes } from "http-status-codes"; import { getContract } from "../../../../utils/cache/getContract"; +import { createCustomError } from "../../../middleware/error"; import { readRequestQuerySchema, type readSchema, @@ -62,11 +63,28 @@ export async function readContract(fastify: FastifyInstance) { return arg; }); - let returnData = await contract.call(functionName, parsedArgs ?? []); + let returnData: unknown; + + try { + returnData = await contract.call(functionName, parsedArgs ?? []); + } catch (e) { + if ( + e instanceof Error && + (e.message.includes("is not a function") || + e.message.includes("arguments, but")) + ) { + throw createCustomError( + e.message, + StatusCodes.BAD_REQUEST, + "BAD_REQUEST", + ); + } + } returnData = bigNumberReplacer(returnData); reply.status(StatusCodes.OK).send({ - result: returnData, + // biome-ignore lint/suspicious/noExplicitAny: data from chain + result: returnData as any, }); }, }); diff --git a/test/e2e/tests/read.test.ts b/test/e2e/tests/read.test.ts index b1612b55d..7be048956 100644 --- a/test/e2e/tests/read.test.ts +++ b/test/e2e/tests/read.test.ts @@ -1,6 +1,6 @@ -import { beforeAll, describe, test } from "bun:test"; +import { beforeAll, describe, expect, test } from "bun:test"; import { sepolia } from "thirdweb/chains"; -import { expect } from "vitest"; +import type { ApiError } from "../../../sdk/dist/thirdweb-dev-engine.cjs"; import type { setupEngine } from "../utils/engine"; import { setup } from "./setup"; @@ -35,4 +35,25 @@ describe("Read Tests", () => { expect(result[2]).toEqual("1"); expect(result[3]).toEqual("2"); }); + + test("Incorrectly read a contract should 400 (incorrect arity)", async () => { + const structValues = { + name: "test", + value: 123, + }; + + const structString = JSON.stringify(structValues); + + try { + await engine.contract.read( + "readStructAndInts", + chainIdString, + structContractAddress, + [structString, 1].join(","), + ); + throw new Error("Expected method to throw"); + } catch (error) { + expect((error as ApiError).status).toBe(400); + } + }); });