diff --git a/packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts b/packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts index 5c5af8acf57..b63fc4eaf46 100644 --- a/packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts +++ b/packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts @@ -17,4 +17,14 @@ describe("normalizeChainId", () => { it("should try to convert a string to a decimal (base 10) integer", () => { expect(normalizeChainId("1")).toBe(1); }); + + it("should reject invalid chain ids", () => { + expect(() => normalizeChainId("1abc")).toThrow("Invalid chain ID"); + expect(() => normalizeChainId("abc")).toThrow("Invalid chain ID"); + expect(() => normalizeChainId("0x")).toThrow("Invalid chain ID"); + expect(() => normalizeChainId(Number.NaN)).toThrow("Invalid chain ID"); + expect(() => + normalizeChainId(BigInt(Number.MAX_SAFE_INTEGER) + 1n), + ).toThrow("Invalid chain ID"); + }); }); diff --git a/packages/thirdweb/src/wallets/utils/normalizeChainId.ts b/packages/thirdweb/src/wallets/utils/normalizeChainId.ts index 6214d870fd3..9c3c2c224a6 100644 --- a/packages/thirdweb/src/wallets/utils/normalizeChainId.ts +++ b/packages/thirdweb/src/wallets/utils/normalizeChainId.ts @@ -4,14 +4,28 @@ import { hexToNumber, isHex } from "../../utils/encoding/hex.js"; * @internal */ export function normalizeChainId(chainId: string | number | bigint): number { + let normalizedChainId: number; + if (typeof chainId === "number") { - return chainId; - } - if (isHex(chainId)) { - return hexToNumber(chainId); + normalizedChainId = chainId; + } else if (isHex(chainId)) { + normalizedChainId = hexToNumber(chainId); + } else if (typeof chainId === "bigint") { + if (chainId < 0n || chainId > BigInt(Number.MAX_SAFE_INTEGER)) { + throw new Error(`Invalid chain ID: ${chainId.toString()}`); + } + normalizedChainId = Number(chainId); + } else { + const trimmed = chainId.trim(); + if (!/^\d+$/u.test(trimmed)) { + throw new Error(`Invalid chain ID: ${chainId}`); + } + normalizedChainId = Number.parseInt(trimmed, 10); } - if (typeof chainId === "bigint") { - return Number(chainId); + + if (!Number.isSafeInteger(normalizedChainId) || normalizedChainId < 0) { + throw new Error(`Invalid chain ID: ${chainId.toString()}`); } - return Number.parseInt(chainId, 10); + + return normalizedChainId; }