Skip to content

Commit e363d51

Browse files
committed
fix wallet chain id normalization
1 parent a82e633 commit e363d51

2 files changed

Lines changed: 31 additions & 7 deletions

File tree

packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,14 @@ describe("normalizeChainId", () => {
1717
it("should try to convert a string to a decimal (base 10) integer", () => {
1818
expect(normalizeChainId("1")).toBe(1);
1919
});
20+
21+
it("should reject invalid chain ids", () => {
22+
expect(() => normalizeChainId("1abc")).toThrow("Invalid chain ID");
23+
expect(() => normalizeChainId("abc")).toThrow("Invalid chain ID");
24+
expect(() => normalizeChainId("0x")).toThrow("Invalid chain ID");
25+
expect(() => normalizeChainId(Number.NaN)).toThrow("Invalid chain ID");
26+
expect(() =>
27+
normalizeChainId(BigInt(Number.MAX_SAFE_INTEGER) + 1n),
28+
).toThrow("Invalid chain ID");
29+
});
2030
});

packages/thirdweb/src/wallets/utils/normalizeChainId.ts

Lines changed: 21 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,28 @@ import { hexToNumber, isHex } from "../../utils/encoding/hex.js";
44
* @internal
55
*/
66
export function normalizeChainId(chainId: string | number | bigint): number {
7+
let normalizedChainId: number;
8+
79
if (typeof chainId === "number") {
8-
return chainId;
9-
}
10-
if (isHex(chainId)) {
11-
return hexToNumber(chainId);
10+
normalizedChainId = chainId;
11+
} else if (isHex(chainId)) {
12+
normalizedChainId = hexToNumber(chainId);
13+
} else if (typeof chainId === "bigint") {
14+
if (chainId < 0n || chainId > BigInt(Number.MAX_SAFE_INTEGER)) {
15+
throw new Error(`Invalid chain ID: ${chainId.toString()}`);
16+
}
17+
normalizedChainId = Number(chainId);
18+
} else {
19+
const trimmed = chainId.trim();
20+
if (!/^\d+$/u.test(trimmed)) {
21+
throw new Error(`Invalid chain ID: ${chainId}`);
22+
}
23+
normalizedChainId = Number.parseInt(trimmed, 10);
1224
}
13-
if (typeof chainId === "bigint") {
14-
return Number(chainId);
25+
26+
if (!Number.isSafeInteger(normalizedChainId) || normalizedChainId < 0) {
27+
throw new Error(`Invalid chain ID: ${chainId.toString()}`);
1528
}
16-
return Number.parseInt(chainId, 10);
29+
30+
return normalizedChainId;
1731
}

0 commit comments

Comments
 (0)