Skip to content

Convert bigNumber to bigint #908

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

joaquim-verges
Copy link
Member

@joaquim-verges joaquim-verges commented Aug 1, 2025

Fixes BLD-37

Summary by CodeRabbit

  • New Features

    • Improved handling of large numeric values in wallet signing requests to ensure compatibility and accuracy when processing complex data structures.
  • Bug Fixes

    • Enhanced support for signing typed data containing large numbers, reducing the risk of errors with certain payloads.

Copy link

coderabbitai bot commented Aug 1, 2025

Walkthrough

A new utility module for transforming BigNumber objects within data structures has been added. The backend wallet route now uses this utility to convert any BigNumber instances in incoming request payloads to stringified bigints before signing typed data. No changes were made to exported entity signatures or error handling.

Changes

Cohort / File(s) Change Summary
Backend Wallet Route Update
src/server/routes/backend-wallet/sign-typed-data.ts
Imports and applies transformBigNumbers to request payloads, ensuring BigNumber instances are stringified before signing.
BigNumber Transformation Utility
src/shared/utils/bignumber.ts
Introduces utility functions and types to identify, convert, and recursively transform BigNumber objects into stringified bigints.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant BackendRoute
    participant Utils

    Client->>BackendRoute: POST /sign-typed-data { value }
    BackendRoute->>Utils: transformBigNumbers(value)
    Utils-->>BackendRoute: transformedValue
    BackendRoute->>BackendRoute: signTypedData(message=transformedValue)
    BackendRoute-->>Client: Response (signed data)
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/convert-bignumber-to-bigint-string-in-payload-cfba

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

linear bot commented Aug 1, 2025

@joaquim-verges joaquim-verges changed the title Convert%20bigNumber%20to%20bigint%20string%20in%20payload Convert bigNumber to bigint Aug 1, 2025
Copy link

@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.

Actionable comments posted: 2

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 067d5da and c59c6c4.

📒 Files selected for processing (2)
  • src/server/routes/backend-wallet/sign-typed-data.ts (3 hunks)
  • src/shared/utils/bignumber.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: the `getchecksumaddress` function in this codebase safely handles undefined/null values by accepting...
Learnt from: d4mr
PR: thirdweb-dev/engine#897
File: src/server/routes/backend-wallet/transfer.ts:15-0
Timestamp: 2025-06-09T23:37:07.373Z
Learning: The `getChecksumAddress` function in this codebase safely handles undefined/null values by accepting `val?: string | Address | null` and returning `Address | undefined`. It returns `undefined` when passed falsy values, so calling it on potentially undefined values like `accountFactoryAddress` does not cause runtime errors.

Applied to files:

  • src/server/routes/backend-wallet/sign-typed-data.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build
  • GitHub Check: lint
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (5)
src/shared/utils/bignumber.ts (2)

8-11: LGTM! Interface correctly models BigNumber objects.

The interface accurately represents the BigNumber object structure as described in the PR objectives.


16-25: LGTM! Robust type guard implementation.

The type guard properly validates all required properties and types, including null safety checks.

src/server/routes/backend-wallet/sign-typed-data.ts (3)

9-9: LGTM! Import statement is correct.

The import properly references the new utility function.


51-52: LGTM! Proper placement of BigNumber transformation.

The transformation is correctly applied to the value before signing typed data.


86-86: LGTM! Correct usage of transformed value.

The transformed value is properly passed as the message parameter to the signing function.

Comment on lines +30 to +33
function bigNumberToStringifiedBigInt(bigNumberObj: BigNumberObject): string {
// Convert hex string to bigint, then to string
return BigInt(bigNumberObj.hex).toString();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling for invalid hex strings.

The BigInt() constructor will throw a SyntaxError if the hex string is malformed. This could cause runtime errors when processing user input.

 function bigNumberToStringifiedBigInt(bigNumberObj: BigNumberObject): string {
-  // Convert hex string to bigint, then to string
-  return BigInt(bigNumberObj.hex).toString();
+  try {
+    // Convert hex string to bigint, then to string
+    return BigInt(bigNumberObj.hex).toString();
+  } catch (error) {
+    throw new Error(`Invalid hex string in BigNumber object: ${bigNumberObj.hex}`);
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function bigNumberToStringifiedBigInt(bigNumberObj: BigNumberObject): string {
// Convert hex string to bigint, then to string
return BigInt(bigNumberObj.hex).toString();
}
function bigNumberToStringifiedBigInt(bigNumberObj: BigNumberObject): string {
try {
// Convert hex string to bigint, then to string
return BigInt(bigNumberObj.hex).toString();
} catch (error) {
throw new Error(`Invalid hex string in BigNumber object: ${bigNumberObj.hex}`);
}
}
🤖 Prompt for AI Agents
In src/shared/utils/bignumber.ts around lines 30 to 33, the function
bigNumberToStringifiedBigInt directly converts a hex string to BigInt without
handling potential errors. To fix this, wrap the BigInt conversion in a
try-catch block to catch SyntaxError exceptions caused by malformed hex strings,
and handle the error gracefully, such as returning a default value or throwing a
custom error with a clear message.

Comment on lines +39 to +66
export function transformBigNumbers(obj: unknown): unknown {
// Handle null/undefined
if (obj === null || obj === undefined) {
return obj;
}

// Handle BigNumber objects
if (isBigNumberObject(obj)) {
return bigNumberToStringifiedBigInt(obj);
}

// Handle arrays
if (Array.isArray(obj)) {
return obj.map(transformBigNumbers);
}

// Handle objects
if (typeof obj === "object") {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = transformBigNumbers(value);
}
return result;
}

// Handle primitives (string, number, boolean, etc.)
return obj;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add protection against circular references.

The recursive function could cause stack overflow with circular references. Consider adding a WeakSet to track visited objects.

-export function transformBigNumbers(obj: unknown): unknown {
+export function transformBigNumbers(obj: unknown, visited = new WeakSet()): unknown {
   // Handle null/undefined
   if (obj === null || obj === undefined) {
     return obj;
   }

+  // Handle circular references
+  if (typeof obj === "object" && visited.has(obj as object)) {
+    return obj;
+  }
+
   // Handle BigNumber objects
   if (isBigNumberObject(obj)) {
     return bigNumberToStringifiedBigInt(obj);
   }

   // Handle arrays
   if (Array.isArray(obj)) {
+    visited.add(obj);
-    return obj.map(transformBigNumbers);
+    return obj.map(item => transformBigNumbers(item, visited));
   }

   // Handle objects
   if (typeof obj === "object") {
+    visited.add(obj);
     const result: Record<string, unknown> = {};
     for (const [key, value] of Object.entries(obj)) {
-      result[key] = transformBigNumbers(value);
+      result[key] = transformBigNumbers(value, visited);
     }
     return result;
   }

   // Handle primitives (string, number, boolean, etc.)
   return obj;
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export function transformBigNumbers(obj: unknown): unknown {
// Handle null/undefined
if (obj === null || obj === undefined) {
return obj;
}
// Handle BigNumber objects
if (isBigNumberObject(obj)) {
return bigNumberToStringifiedBigInt(obj);
}
// Handle arrays
if (Array.isArray(obj)) {
return obj.map(transformBigNumbers);
}
// Handle objects
if (typeof obj === "object") {
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = transformBigNumbers(value);
}
return result;
}
// Handle primitives (string, number, boolean, etc.)
return obj;
}
export function transformBigNumbers(
obj: unknown,
visited = new WeakSet<object>()
): unknown {
// Handle null/undefined
if (obj === null || obj === undefined) {
return obj;
}
// Handle circular references
if (typeof obj === "object" && visited.has(obj as object)) {
return obj;
}
// Handle BigNumber objects
if (isBigNumberObject(obj)) {
return bigNumberToStringifiedBigInt(obj);
}
// Handle arrays
if (Array.isArray(obj)) {
visited.add(obj);
return obj.map(item => transformBigNumbers(item, visited));
}
// Handle objects
if (typeof obj === "object") {
visited.add(obj);
const result: Record<string, unknown> = {};
for (const [key, value] of Object.entries(obj)) {
result[key] = transformBigNumbers(value, visited);
}
return result;
}
// Handle primitives (string, number, boolean, etc.)
return obj;
}
🤖 Prompt for AI Agents
In src/shared/utils/bignumber.ts between lines 39 and 66, the
transformBigNumbers function lacks protection against circular references, which
can cause infinite recursion and stack overflow. Fix this by adding a WeakSet
parameter to track visited objects during recursion. Before processing an object
or array, check if it has already been visited; if so, return it directly to
avoid reprocessing. Pass this WeakSet through recursive calls to maintain state
across the traversal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants