Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
});
});
28 changes: 21 additions & 7 deletions packages/thirdweb/src/wallets/utils/normalizeChainId.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Loading