Skip to content

Conversation

@IAmKio
Copy link
Contributor

@IAmKio IAmKio commented Jul 17, 2025

Description

Types of changes

What types of changes does your code introduce?

  • Bugfix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation Update
  • Code style update (formatting, renaming)
  • Refactoring (no functional changes, no api changes)
  • Build related changes
  • Other (please describe):

Further comments (optional)

Summary by CodeRabbit

  • New Features

    • Added support for disabling and rotating session keys, with updated method signatures and simplified logic.
    • Introduced batch encoding for multiple calls in wallet operations.
  • Bug Fixes

    • Improved input validation and error handling across session key, wallet API, and provider functionalities.
    • Added checks to prevent duplicate subscriptions in service management.
  • Refactor

    • Standardized error handling using a custom error handler throughout the SDK.
    • Enhanced type safety and documentation for utility and core SDK functions.
    • Enforced batch size and array consistency validation for user operation estimation.
  • Documentation

    • Added and improved JSDoc comments for better clarity across classes and methods.

@coderabbitai
Copy link

coderabbitai bot commented Jul 17, 2025

Walkthrough

This update introduces consistent and structured error handling across the SDK by replacing generic errors with a custom ErrorHandler class. It adds and refines session key management methods, enforces stricter input validation, enhances batch processing logic, and improves type safety and documentation throughout the codebase. Several APIs now include explicit checks and better error messaging.

Changes

File(s) Change Summary
src/sdk/SessionKeyValidator/SessionKeyValidator.ts Refactored to use ErrorHandler for all errors, added disableSessionKey, updated rotateSessionKey signature and logic, improved enableSessionKey error handling, and updated private error handling.
src/sdk/base/BaseAccountAPI.ts Improved error handling in getCounterFactualAddress using ErrorHandler.
src/sdk/base/EtherspotWalletAPI.ts Enhanced error handling and input validation, refined encodeExecute, added encodeBatch, improved getNonce, updated documentation.
src/sdk/base/HttpRpcClient.ts Standardized error handling with ErrorHandler, expanded error parsing in parseViemRPCRequestError.
src/sdk/common/OperationUtils.ts Improved type safety and documentation in toJSON, updated return type.
src/sdk/common/getInitData.ts Added ErrorHandler-based error handling, JSDoc comments, and improved decoding robustness.
src/sdk/common/rxjs/error.subject.ts Made ErrorSubject strictly type-safe for Error, wrapped non-Error emissions, updated method signatures and documentation.
src/sdk/common/service.ts Added detailed JSDoc comments, prevented duplicate subscriptions in addSubscriptions.
src/sdk/common/utils/deep-compare.ts Improved type safety, explicit error handling, expanded type checks, enhanced documentation.
src/sdk/common/utils/hashing-utils.ts Tightened input type checks, improved error handling, clarified logic for hashing and hex conversion.
src/sdk/sdk.ts Added MAX_BATCH_SIZE, enforced batch size and array length validation in estimate.
src/sdk/wallet/providers/key.wallet-provider.ts Replaced generic errors with ErrorHandler, validated private key, added accountAddress, improved documentation.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant SessionKeyValidator
    participant ErrorHandler
    participant API/KeyStore

    User->>SessionKeyValidator: enableSessionKey/rotateSessionKey/disableSessionKey(...)
    SessionKeyValidator->>SessionKeyValidator: Validate inputs
    alt Invalid input
        SessionKeyValidator->>ErrorHandler: throw ErrorHandler(code=1, message)
        ErrorHandler-->>User: Error thrown
    else Valid input
        SessionKeyValidator->>API/KeyStore: Fetch context or generate session key data
        API/KeyStore-->>SessionKeyValidator: Response / Data
        alt API/KeyStore error
            SessionKeyValidator->>ErrorHandler: throw ErrorHandler(code=1, message)
            ErrorHandler-->>User: Error thrown
        else Success
            SessionKeyValidator-->>User: Return session key data
        end
    end
Loading

Suggested reviewers

  • nikhilkumar1612
  • cryptonoyaiba
  • kanthgithub

Poem

In fields of code, the rabbits hop,
Wrapping errors, never stop.
Session keys now safe and sound,
Batch sizes checked, bugs unwound.
With docs and types, the gardens bloom—
A happy warren, more robust room!
🐇✨

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

src/sdk/common/getInitData.ts

Oops! Something went wrong! :(

ESLint: 8.28.0

ReferenceError: Cannot read config file: /.eslintrc.js
Error: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///.eslintrc.js:1:1
at ModuleJobSync.runSync (node:internal/modules/esm/module_job:498:37)
at ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:437:47)
at loadESMFromCJS (node:internal/modules/cjs/loader:1523:24)
at Module._compile (node:internal/modules/cjs/loader:1674:5)
at Object..js (node:internal/modules/cjs/loader:1824:10)
at Module.load (node:internal/modules/cjs/loader:1427:32)
at Module._load (node:internal/modules/cjs/loader:1250:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)

src/sdk/SessionKeyValidator/SessionKeyValidator.ts

Oops! Something went wrong! :(

ESLint: 8.28.0

ReferenceError: Cannot read config file: /.eslintrc.js
Error: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///.eslintrc.js:1:1
at ModuleJobSync.runSync (node:internal/modules/esm/module_job:498:37)
at ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:437:47)
at loadESMFromCJS (node:internal/modules/cjs/loader:1523:24)
at Module._compile (node:internal/modules/cjs/loader:1674:5)
at Object..js (node:internal/modules/cjs/loader:1824:10)
at Module.load (node:internal/modules/cjs/loader:1427:32)
at Module._load (node:internal/modules/cjs/loader:1250:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)

src/sdk/base/BaseAccountAPI.ts

Oops! Something went wrong! :(

ESLint: 8.28.0

ReferenceError: Cannot read config file: /.eslintrc.js
Error: module is not defined in ES module scope
This file is being treated as an ES module because it has a '.js' file extension and '/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
at file:///.eslintrc.js:1:1
at ModuleJobSync.runSync (node:internal/modules/esm/module_job:498:37)
at ModuleLoader.importSyncForRequire (node:internal/modules/esm/loader:437:47)
at loadESMFromCJS (node:internal/modules/cjs/loader:1523:24)
at Module._compile (node:internal/modules/cjs/loader:1674:5)
at Object..js (node:internal/modules/cjs/loader:1824:10)
at Module.load (node:internal/modules/cjs/loader:1427:32)
at Module._load (node:internal/modules/cjs/loader:1250:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:235:24)

  • 9 others
✨ Finishing Touches
  • 📝 Generate Docstrings

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

@github-actions
Copy link

Yooo! You forgot to bump the version in package.json!

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: 1

🔭 Outside diff range comments (1)
src/sdk/SessionKeyValidator/SessionKeyValidator.ts (1)

186-263: Breaking change: Parameter order modified

The rotateSessionKey method has been simplified and the parameter order changed with oldSessionKey moved to the first position. This is a breaking change that will require updates to any existing code using this method.

The simplification (removing user operation handling) improves separation of concerns.

🧹 Nitpick comments (4)
src/sdk/common/service.ts (1)

68-78: Consider using a Set for better performance with many subscriptions.

While the duplicate prevention logic is correct, using includes() has O(n) complexity for each subscription check. For services with many subscriptions, this could impact performance.

Consider using a Set to track subscriptions for O(1) lookup:

-  private subscriptions: Subscription[] = [];
+  private subscriptions = new Set<Subscription>();

   protected addSubscriptions(...subscriptions: Subscription[]): void {
     for (const sub of subscriptions) {
-      if (sub && !this.subscriptions.includes(sub)) {
-        this.subscriptions.push(sub);
+      if (sub && !this.subscriptions.has(sub)) {
+        this.subscriptions.add(sub);
       }
     }
   }

   protected removeSubscriptions(): void {
-    for (const subscription of this.subscriptions) {
+    for (const subscription of this.subscriptions) {
       subscription.unsubscribe();
     }
-    this.subscriptions = [];
+    this.subscriptions.clear();
   }
src/sdk/common/utils/deep-compare.ts (1)

58-60: Consider providing more context in the error message.

The error handling is good, but the message could be more descriptive for debugging.

           } else {
-            throw new Error('deepCompare: Mismatched array/object types');
+            throw new Error(`deepCompare: Type mismatch - comparing ${aIsArray ? 'array' : 'object'} with ${bIsArray ? 'array' : 'object'}`);
           }
src/sdk/common/getInitData.ts (1)

49-54: Consider adding runtime type validation for the decoded arguments.

While the error handling is comprehensive, the type assertions could potentially hide runtime type errors.

Consider validating the types before assertion:

     return {
-      validators: initCallDataArgs[0] as Module[],
-      executors: initCallDataArgs[1] as Module[],
-      hooks: [initCallDataArgs[2]] as Module[],
-      fallbacks: initCallDataArgs[3] as Module[],
+      validators: Array.isArray(initCallDataArgs[0]) ? initCallDataArgs[0] as Module[] : throw new ErrorHandler('Invalid validators format', 1),
+      executors: Array.isArray(initCallDataArgs[1]) ? initCallDataArgs[1] as Module[] : throw new ErrorHandler('Invalid executors format', 1),
+      hooks: [initCallDataArgs[2]] as Module[],
+      fallbacks: Array.isArray(initCallDataArgs[3]) ? initCallDataArgs[3] as Module[] : throw new ErrorHandler('Invalid fallbacks format', 1),
     }

Alternatively, create a validation helper function to keep the code clean.

src/sdk/base/HttpRpcClient.ts (1)

73-73: Apply optional chaining for safer property access

The static analysis tool correctly identifies that optional chaining should be used here for safer property access.

Apply this fix:

-    if (body && body?.details && body?.code) {
+    if (body?.details && body?.code) {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 05dd049 and 603a701.

📒 Files selected for processing (12)
  • src/sdk/SessionKeyValidator/SessionKeyValidator.ts (12 hunks)
  • src/sdk/base/BaseAccountAPI.ts (3 hunks)
  • src/sdk/base/EtherspotWalletAPI.ts (4 hunks)
  • src/sdk/base/HttpRpcClient.ts (1 hunks)
  • src/sdk/common/OperationUtils.ts (2 hunks)
  • src/sdk/common/getInitData.ts (1 hunks)
  • src/sdk/common/rxjs/error.subject.ts (1 hunks)
  • src/sdk/common/service.ts (3 hunks)
  • src/sdk/common/utils/deep-compare.ts (3 hunks)
  • src/sdk/common/utils/hashing-utils.ts (1 hunks)
  • src/sdk/sdk.ts (4 hunks)
  • src/sdk/wallet/providers/key.wallet-provider.ts (4 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (9)
src/sdk/common/OperationUtils.ts (1)
src/sdk/types/user-operation-types.ts (1)
  • BaseAccountUserOperationStruct (6-16)
src/sdk/base/BaseAccountAPI.ts (1)
src/sdk/errorHandler/errorHandler.service.ts (1)
  • ErrorHandler (3-17)
src/sdk/common/getInitData.ts (1)
src/sdk/errorHandler/errorHandler.service.ts (1)
  • ErrorHandler (3-17)
src/sdk/sdk.ts (3)
src/sdk/index.ts (1)
  • ModularSdk (11-11)
src/sdk/errorHandler/errorHandler.service.ts (1)
  • ErrorHandler (3-17)
src/sdk/common/exceptions/validation.exception.ts (1)
  • ValidationException (4-17)
src/sdk/common/service.ts (1)
src/sdk/context.ts (1)
  • Context (5-33)
src/sdk/common/utils/deep-compare.ts (1)
src/sdk/types/bignumber.ts (1)
  • BigNumber (49-303)
src/sdk/base/HttpRpcClient.ts (1)
src/sdk/errorHandler/errorHandler.service.ts (1)
  • ErrorHandler (3-17)
src/sdk/common/utils/hashing-utils.ts (1)
src/sdk/common/utils/viem-utils.ts (1)
  • isAddress (140-158)
src/sdk/SessionKeyValidator/SessionKeyValidator.ts (4)
src/sdk/errorHandler/errorHandler.service.ts (1)
  • ErrorHandler (3-17)
src/sdk/SessionKeyValidator/interfaces.ts (1)
  • SessionKeyResponse (19-22)
src/sdk/network/network.service.ts (1)
  • chainId (47-49)
src/sdk/SessionKeyValidator/constants.ts (1)
  • PERMISSIONS_URL (1-1)
🪛 Biome (1.9.4)
src/sdk/common/OperationUtils.ts

[error] 26-26: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

src/sdk/base/HttpRpcClient.ts

[error] 73-73: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (31)
src/sdk/common/service.ts (1)

4-17: Documentation improvements look good!

The JSDoc comments clearly describe the Service class purpose and the idempotent behavior of lifecycle methods.

src/sdk/common/OperationUtils.ts (1)

6-12: Type safety improvements are excellent!

The JSDoc documentation and specific return type Promise<Record<string, string>> provide better clarity and type safety.

src/sdk/base/BaseAccountAPI.ts (1)

252-276: Ensure robust extraction of sender from simulateContract errors

We only found this single instance of simulateContract error handling in src/sdk/base/BaseAccountAPI.ts, and no other patterns or examples in the codebase. To guard against differences in error shapes across RPC providers or viem versions, add defensive fallbacks when extracting sender:

• File to update:

  • src/sdk/base/BaseAccountAPI.ts (method getCounterFactualAddress, lines 252–276)

• Suggested diff:

   } catch (e: any) {
-    if (e?.errorArgs?.sender) {
-      return e.errorArgs.sender;
+    // Handle different error payloads from simulateContract reverts
+    const sender =
+      e?.errorArgs?.sender ??
+      e?.data?.args?.sender ??
+      e?.error?.data?.args?.sender;
+    if (sender) {
+      return sender;
+    }
     throw new ErrorHandler(
       `Failed to get counterfactual address: ${e instanceof Error ? e.message : String(e)}`,
       1
     );
   }

Please verify against your target RPC providers and viem version that these fallback paths correctly capture the reverted sender field.

src/sdk/common/utils/deep-compare.ts (1)

5-11: Excellent type safety improvements!

The change from any to unknown parameters and comprehensive JSDoc documentation enhance type safety and API clarity.

src/sdk/sdk.ts (4)

24-24: LGTM: Proper import for enhanced validation

The import of ValidationException supports the new batch validation logic in the estimate method.


44-47: LGTM: Well-defined batch size limit

The MAX_BATCH_SIZE constant provides a clear limit for user operation batches. The value of 50 seems reasonable for preventing resource exhaustion while allowing sufficient batch operations.


176-180: LGTM: Improved documentation

The enhanced JSDoc clearly describes the method's behavior and failure conditions, improving developer experience.


193-198: LGTM: Comprehensive batch validation logic

The validation improvements are excellent:

  • Prevents processing batches exceeding MAX_BATCH_SIZE
  • Ensures array length consistency between to, data, and value arrays
  • Uses appropriate error types (ErrorHandler for size limits, ValidationException for structural issues)

The validation logic is robust and follows the SDK's error handling patterns.

src/sdk/wallet/providers/key.wallet-provider.ts (5)

5-5: LGTM: Proper import for standardized error handling

The ErrorHandler import supports the consistent error handling pattern being implemented across the SDK.


7-9: LGTM: Enhanced documentation

The improved JSDoc comments provide clear information about the class purpose and constructor parameters.

Also applies to: 17-22


24-26: LGTM: Important security validation

The private key validation prevents initialization with invalid keys, improving security and error handling. The check for both existence and string type is appropriate.


34-36: LGTM: Consistent error handling and useful property

The account validation uses ErrorHandler consistently, and the accountAddress property provides a convenient reference to the wallet address.

Also applies to: 41-41


45-45: LGTM: Comprehensive error handling standardization

All methods now use ErrorHandler with appropriate error codes (1) instead of generic Error objects. The error messages are clear and consistent across all validation points:

  • Account validation
  • Required parameter validation (validatorAddress, factoryAddress, initCode)

This provides better error tracking and user experience.

Also applies to: 50-52, 68-68, 76-78, 101-101, 109-109, 119-119

src/sdk/common/rxjs/error.subject.ts (4)

6-6: LGTM: Improved type safety

Changing from Subject<any> to Subject<Error> enforces type safety and ensures only Error instances are emitted.


18-25: LGTM: Robust error wrapping in next method

The enhanced next method ensures type safety by:

  • Only emitting actual Error instances
  • Wrapping non-Error values in Error objects
  • Maintaining backward compatibility

This prevents type-related issues in error handling.


31-31: LGTM: Enhanced error handling in wrap method

The improvements include:

  • Updated return type to T | null for clarity
  • Consistent error wrapping for both synchronous and asynchronous errors
  • Type checks before wrapping to preserve Error instances

The logic correctly handles Promise rejections and synchronous exceptions.

Also applies to: 36-39, 42-42


64-64: LGTM: Consistent error wrapping in catch method

The catch method now applies the same error wrapping logic as other methods, ensuring all emitted errors are proper Error instances.

Also applies to: 73-73

src/sdk/common/utils/hashing-utils.ts (4)

6-11: LGTM: Comprehensive documentation

The enhanced JSDoc clearly describes the supported input types and return value, improving developer experience.


20-20: LGTM: Improved type safety and error handling

The enhancements include:

  • Using isAHex from viem for better hex validation
  • Restricting object inputs to Uint8Array and Buffer only
  • Clear error messages for unsupported types
  • Warning before throwing for better debugging

The stricter validation prevents potential runtime errors and provides better feedback.

Also applies to: 27-41


47-55: LGTM: Simplified and more reliable hex validation

The updated isHex function leverages the imported isAHex helper, which is more reliable than custom validation logic.


63-92: LGTM: Enhanced robustness in toHexFromBytesLike

The improvements include:

  • Address-specific handling using isAddress
  • Better string-to-bytes conversion with stringToBytes
  • Stricter object type validation
  • More descriptive error messages

The logic correctly handles different input types while maintaining type safety.

src/sdk/base/HttpRpcClient.ts (2)

67-78: LGTM: Standardized error handling

The method now uses ErrorHandler consistently with the SDK's error handling pattern. The fallback to error code 1 provides a reasonable default.


80-117: LGTM: Comprehensive error parsing improvements

The enhanced error parsing logic is excellent:

  • Handles viem-specific error types (BaseError, ContractFunctionExecutionError)
  • Provides structured error objects with code, details, and data
  • Includes fallback handling for unknown error types
  • Maintains backward compatibility

This significantly improves error handling robustness across the RPC client.

src/sdk/base/EtherspotWalletAPI.ts (4)

10-10: LGTM!

The import is correctly added as part of the SDK-wide error handling standardization.


302-348: Good error handling improvements!

The enhanced error handling with specific error messages and the addition of try-catch for contract calls improves robustness. The JSDoc documentation is also helpful.


351-403: Excellent input validation and type handling!

The added parameter validation and comprehensive BigNumberish type handling significantly improve the method's robustness. The explicit handling of all possible types with a fallback ensures proper value conversion.


414-480: Well-implemented batch encoding method!

The new encodeBatch method includes comprehensive validation:

  • Proper null/undefined checks
  • Array length equality validation
  • Non-empty array validation
  • Per-element type validation

The implementation correctly handles batch operations and aligns with the SDK's batch processing enhancements.

src/sdk/SessionKeyValidator/SessionKeyValidator.ts (4)

8-8: LGTM!

ErrorHandler import aligns with SDK-wide error handling standardization.


38-131: Good error handling standardization!

The method now uses ErrorHandler consistently with proper error messages and includes a well-structured error re-throw pattern that preserves ErrorHandler instances.


133-183: Verify the session key disabling logic

The new disableSessionKey method follows good patterns for validation and error handling. However, it calls generateSessionKeyData with empty values for token, functionSelector, and zero values for timestamps.

Please verify that passing empty/zero values to the backend API actually disables the session key as intended.


364-556: Consistent error handling improvements

All private methods now use ErrorHandler consistently with error code 1, completing the error handling standardization across the SessionKeyValidator class.

Comment on lines 24 to 30
.reduce(
(set, [k, v]) => ({
...set,
[k]: v,
}),
{},
{} as Record<string, string>,
),
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix O(n²) complexity issue with spread syntax in reduce.

The spread syntax in the reduce accumulator creates a new object on each iteration, resulting in O(n²) time complexity.

Use Object.fromEntries for better performance:

 export async function toJSON(op: Partial<BaseAccountUserOperationStruct>): Promise<Record<string, string>> {
   return resolveProperties(op).then((userOp) =>
-    Object.keys(userOp)
-      .map((key) => {
-        let val = (userOp as any)[key];
-        if (typeof val === 'object' && BigNumber.isBigNumber(val)) {
-          val = val.toHexString()
-        }
-        else if (typeof val !== 'string' || !val.startsWith('0x')) {
-          val = toHex(val);
-        }
-        return [key, val as string];
-      })
-      .reduce(
-        (set, [k, v]) => ({
-          ...set,
-          [k]: v,
-        }),
-        {} as Record<string, string>,
-      ),
+    Object.fromEntries(
+      Object.keys(userOp).map((key) => {
+        let val = (userOp as any)[key];
+        if (typeof val === 'object' && BigNumber.isBigNumber(val)) {
+          val = val.toHexString()
+        }
+        else if (typeof val !== 'string' || !val.startsWith('0x')) {
+          val = toHex(val);
+        }
+        return [key, val as string];
+      })
+    ),
   );
 }
📝 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
.reduce(
(set, [k, v]) => ({
...set,
[k]: v,
}),
{},
{} as Record<string, string>,
),
export async function toJSON(op: Partial<BaseAccountUserOperationStruct>): Promise<Record<string, string>> {
return resolveProperties(op).then((userOp) =>
Object.fromEntries(
Object.keys(userOp).map((key) => {
let val = (userOp as any)[key];
if (typeof val === 'object' && BigNumber.isBigNumber(val)) {
val = val.toHexString();
} else if (typeof val !== 'string' || !val.startsWith('0x')) {
val = toHex(val);
}
return [key, val as string];
})
),
);
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 26-26: Avoid the use of spread (...) syntax on accumulators.

Spread syntax should be avoided on accumulators (like those in .reduce) because it causes a time complexity of O(n^2).
Consider methods such as .splice or .push instead.

(lint/performance/noAccumulatingSpread)

🤖 Prompt for AI Agents
In src/sdk/common/OperationUtils.ts around lines 24 to 30, the use of spread
syntax inside the reduce function causes O(n²) complexity by creating a new
object on each iteration. Replace the entire reduce call with a single call to
Object.fromEntries on the original array to convert it directly into a
Record<string, string>, which improves performance to O(n).

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

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants