Skip to content

Commit

Permalink
400 for user errors (#751)
Browse files Browse the repository at this point in the history
  • Loading branch information
d4mr authored Nov 1, 2024
1 parent 8539938 commit 07b29de
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
22 changes: 20 additions & 2 deletions src/server/routes/contract/read/read.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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,
});
},
});
Expand Down
25 changes: 23 additions & 2 deletions test/e2e/tests/read.test.ts
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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);
}
});
});

0 comments on commit 07b29de

Please sign in to comment.