Skip to content

Fix wallet chain id normalization#8784

Open
samsamtrum wants to merge 1 commit into
thirdweb-dev:mainfrom
samsamtrum:fix-normalize-chain-id-validation
Open

Fix wallet chain id normalization#8784
samsamtrum wants to merge 1 commit into
thirdweb-dev:mainfrom
samsamtrum:fix-normalize-chain-id-validation

Conversation

@samsamtrum
Copy link
Copy Markdown

@samsamtrum samsamtrum commented Jun 1, 2026

Fixes wallet chain id normalization so malformed decimal strings are rejected instead of being partially parsed. It also rejects NaN, negative, and unsafe numeric values, with regression coverage for invalid chain IDs.


PR-Codex overview

This PR enhances the normalizeChainId function to handle various invalid input scenarios by throwing errors. It also improves the logic for processing different types of chainId, ensuring that only valid chain IDs are accepted.

Detailed summary

  • Added a new test case in normalizeChainId.test.ts to check for invalid chainId inputs.
  • Updated normalizeChainId function in normalizeChainId.ts to:
    • Introduce a normalizedChainId variable for cleaner logic.
    • Validate bigint inputs to ensure they are within safe limits.
    • Trim and validate string inputs against a regex for digits.
    • Throw errors for invalid inputs, ensuring robust error handling.

✨ Ask PR-Codex anything about this PR by commenting with /codex {your question}

Summary by CodeRabbit

  • Tests

    • Added test case to verify chain ID validation rejects malformed inputs, invalid formats, and values exceeding safe integer limits.
  • Bug Fixes

    • Improved chain ID normalization with stricter validation. Now rejects invalid strings, out-of-bounds values, and negative numbers, ensuring only safe integers are accepted.

@samsamtrum samsamtrum requested review from a team as code owners June 1, 2026 12:10
@vercel
Copy link
Copy Markdown

vercel Bot commented Jun 1, 2026

@samsamtrum is attempting to deploy a commit to the thirdweb Team on Vercel.

A member of the Team first needs to authorize it.

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Jun 1, 2026

⚠️ No Changeset found

Latest commit: e363d51

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@github-actions github-actions Bot added packages SDK Involves changes to the thirdweb SDK labels Jun 1, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 1, 2026

Review Change Stack

Walkthrough

normalizeChainId adds stricter validation for chain ID inputs. The function now rejects out-of-range bigints, enforces a digits-only string format, and validates that all normalized values are non-negative safe integers. New test cases verify rejection of invalid inputs.

Changes

Chain ID Normalization Validation

Layer / File(s) Summary
Stricter chain ID validation
packages/thirdweb/src/wallets/utils/normalizeChainId.ts
Replaces early-return logic with centralized normalization via normalizedChainId variable. Bigint inputs now enforce bounds (0n to BigInt(Number.MAX_SAFE_INTEGER)), string inputs are trimmed and validated against a digits-only regex, and a final validation ensures all normalized values are non-negative safe integers.
Validation test coverage
packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts
Added test block asserting normalizeChainId throws "Invalid chain ID" for malformed numeric strings, Number.NaN, and out-of-safe-range BigInt values.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The PR description is well-detailed and covers the key changes, but does not follow the repository's template format with required sections like title prefix and testing instructions. Consider restructuring the description to follow the template format: add the [SDK] prefix, include a dedicated 'How to test' section, and organize notes for reviewers clearly.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Fix wallet chain id normalization' directly describes the main change in the PR—enhancing chain ID validation in the wallet utilities.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts (1)

21-29: ⚡ Quick win

Good coverage of invalid inputs.

The test cases effectively verify rejection of malformed strings, NaN, and out-of-range bigints. Consider adding a few more edge cases for completeness:

  • Negative number input: normalizeChainId(-1)
  • Empty or whitespace-only strings: normalizeChainId(""), normalizeChainId(" ")
  • Whitespace handling (positive test): normalizeChainId(" 1 ") should equal 1
🧪 Optional additional test cases
  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");
+    expect(() => normalizeChainId(-1)).toThrow("Invalid chain ID");
+    expect(() => normalizeChainId("")).toThrow("Invalid chain ID");
+    expect(() => normalizeChainId("   ")).toThrow("Invalid chain ID");
  });
+
+  it("should handle whitespace in string inputs", () => {
+    expect(normalizeChainId(" 1 ")).toBe(1);
+    expect(normalizeChainId("  42  ")).toBe(42);
+  });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts` around lines 21
- 29, Add tests to cover negative numbers and empty/whitespace-only strings and
to assert trimming behavior: in the normalizeChainId test suite add expects that
normalizeChainId(-1) throws "Invalid chain ID", that normalizeChainId("") and
normalizeChainId("   ") throw "Invalid chain ID", and that normalizeChainId(" 1
") returns 1 (or does not throw and equals 1). Reference the normalizeChainId
test block so these new cases are grouped with the existing "should reject
invalid chain ids" tests.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts`:
- Around line 21-29: Add tests to cover negative numbers and
empty/whitespace-only strings and to assert trimming behavior: in the
normalizeChainId test suite add expects that normalizeChainId(-1) throws
"Invalid chain ID", that normalizeChainId("") and normalizeChainId("   ") throw
"Invalid chain ID", and that normalizeChainId(" 1 ") returns 1 (or does not
throw and equals 1). Reference the normalizeChainId test block so these new
cases are grouped with the existing "should reject invalid chain ids" tests.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dc3524e8-e56f-43b6-80ff-41447afd5e6f

📥 Commits

Reviewing files that changed from the base of the PR and between a82e633 and e363d51.

📒 Files selected for processing (2)
  • packages/thirdweb/src/wallets/utils/normalizeChainId.test.ts
  • packages/thirdweb/src/wallets/utils/normalizeChainId.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

packages SDK Involves changes to the thirdweb SDK

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant