Skip to content

[SDK] Feature: Track insufficient funds error across SDK #7256

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

Merged

Conversation

gregfromstl
Copy link
Member

@gregfromstl gregfromstl commented Jun 2, 2025

This PR implements comprehensive tracking for insufficient funds errors throughout the thirdweb SDK. Includes helper functions for error detection, tracking during transaction execution and preparation phases, and comprehensive test coverage with 34 passing tests. Tracks errors from smart wallets, injected wallets, gas estimation, and transaction simulation. Uses existing analytics infrastructure with fail-safe implementation.


PR-Codex overview

This PR focuses on enhancing error tracking for insufficient funds in transaction processes. It introduces a new utility function to identify insufficient funds errors and integrates tracking for these errors across various transaction-related functions.

Detailed summary

  • Added isInsufficientFundsError function to identify insufficient funds errors.
  • Integrated insufficient funds error tracking in estimateGas, simulate, and other transaction functions.
  • Enhanced error handling in useSendTransactionCore and _sendUserOp.
  • Updated tests to verify insufficient funds error tracking functionality.

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

Summary by CodeRabbit

  • New Features
    • Introduced automatic tracking and logging of insufficient funds errors during transaction processes, providing enhanced error visibility and diagnostics for users.
  • Bug Fixes
    • Improved error detection and reporting for insufficient funds scenarios across various wallet and transaction flows.
  • Tests
    • Added comprehensive tests to ensure robust detection and extraction of error details related to insufficient funds.
  • Chores
    • Enhanced internal error extraction and tracking mechanisms to include additional transaction context for better analytics.

…with helper functions, transaction execution/preparation tracking, and comprehensive test coverage
@gregfromstl gregfromstl requested review from a team as code owners June 2, 2025 21:51
Copy link

linear bot commented Jun 2, 2025

Copy link

changeset-bot bot commented Jun 2, 2025

⚠️ No Changeset found

Latest commit: 33ff5a2

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

Copy link

vercel bot commented Jun 2, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
docs-v2 ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2025 10:01pm
login ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2025 10:01pm
thirdweb_playground ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2025 10:01pm
thirdweb-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2025 10:01pm
wallet-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jun 2, 2025 10:01pm

Copy link
Contributor

graphite-app bot commented Jun 2, 2025

How to use the Graphite Merge Queue

Add either label to this PR to merge it via the merge queue:

  • merge-queue - adds this PR to the back of the merge queue
  • hotfix - for urgent hot fixes, skip the queue and merge this PR next

You must have a Graphite account in order to use the merge queue. Sign up using this link.

An organization admin has enabled the Graphite Merge Queue in this repository.

Please do not merge from GitHub as this will restart CI on PRs being processed by the merge queue.

Copy link
Contributor

coderabbitai bot commented Jun 2, 2025

Walkthrough

The changes introduce robust detection and tracking of insufficient funds errors throughout transaction-related modules. New helper functions for error identification and detail extraction are added, with corresponding unit tests. Transaction flows in wallets and transaction utilities are updated to track insufficient funds errors with contextual information whenever such errors occur.

Changes

Files/Groups Change Summary
.../analytics/track/helpers.ts, .../analytics/track/helpers.test.ts Added helper functions for detecting insufficient funds errors and extracting error details, with comprehensive unit tests.
.../analytics/track/transaction.ts, .../analytics/track/transaction.test.ts Added and tested trackInsufficientFundsError function for tracking insufficient funds errors during transactions.
.../react/core/hooks/transaction/useSendTransaction.ts Integrated insufficient funds error detection and tracking into transaction sending logic.
.../transaction/actions/estimate-gas.ts, .../transaction/actions/simulate.ts Passed fromAddress to error extraction for enhanced context in gas estimation and simulation error handling.
.../transaction/extract-error.ts Updated extractError to accept fromAddress and track insufficient funds errors when detected.
.../wallets/injected/index.ts, .../wallets/smart/index.ts Wrapped transaction sending logic in try-catch, detecting and tracking insufficient funds errors with contextual details.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Wallet
    participant TransactionModule
    participant Helpers
    participant Analytics

    User->>Wallet: Initiate transaction
    Wallet->>TransactionModule: Send transaction
    TransactionModule->>Helpers: Try transaction, catch error
    Helpers->>Helpers: isInsufficientFundsError(error)
    alt Insufficient funds error detected
        Helpers->>Analytics: trackInsufficientFundsError(context)
    end
    Helpers->>TransactionModule: Propagate error
    TransactionModule->>Wallet: Propagate error
    Wallet->>User: Error response
Loading

Suggested labels

packages, SDK

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 github-actions bot added packages SDK Involves changes to the thirdweb SDK labels Jun 2, 2025
@gregfromstl gregfromstl changed the title feat: Add comprehensive insufficient funds error tracking across SDK [SDK] Feature: Add comprehensive insufficient funds error tracking across SDK Jun 2, 2025
Copy link
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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/thirdweb/src/wallets/smart/index.ts (1)

564-577: Well-implemented error tracking with proper error flow preservation.

The implementation correctly:

  • Wraps existing logic without changing the success path
  • Uses resolvePromisedValue to handle potentially promised values
  • Re-throws the original error to maintain existing error handling

However, consider adding error handling around the resolvePromisedValue calls to prevent secondary errors from masking the original transaction error.

Consider wrapping the resolvePromisedValue calls in try-catch blocks:

  } catch (error) {
    // Track insufficient funds errors
    if (isInsufficientFundsError(error)) {
+     try {
        trackInsufficientFundsError({
          client: options.client,
          error,
          walletAddress: options.accountContract.address,
          chainId: options.chain.id,
-         contractAddress: await resolvePromisedValue(executeTx.to ?? undefined),
-         transactionValue: await resolvePromisedValue(executeTx.value),
+         contractAddress: await resolvePromisedValue(executeTx.to ?? undefined).catch(() => undefined),
+         transactionValue: await resolvePromisedValue(executeTx.value).catch(() => undefined),
        });
+     } catch {
+       // Ignore tracking errors to preserve original error
+     }
    }

    throw error;
  }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2114e5f and 33ff5a2.

📒 Files selected for processing (10)
  • packages/thirdweb/src/analytics/track/helpers.test.ts (1 hunks)
  • packages/thirdweb/src/analytics/track/helpers.ts (1 hunks)
  • packages/thirdweb/src/analytics/track/transaction.test.ts (2 hunks)
  • packages/thirdweb/src/analytics/track/transaction.ts (2 hunks)
  • packages/thirdweb/src/react/core/hooks/transaction/useSendTransaction.ts (2 hunks)
  • packages/thirdweb/src/transaction/actions/estimate-gas.ts (2 hunks)
  • packages/thirdweb/src/transaction/actions/simulate.ts (1 hunks)
  • packages/thirdweb/src/transaction/extract-error.ts (2 hunks)
  • packages/thirdweb/src/wallets/injected/index.ts (2 hunks)
  • packages/thirdweb/src/wallets/smart/index.ts (2 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
packages/thirdweb/src/transaction/extract-error.ts (2)
packages/thirdweb/src/analytics/track/helpers.ts (1)
  • isInsufficientFundsError (4-26)
packages/thirdweb/src/analytics/track/transaction.ts (1)
  • trackInsufficientFundsError (63-94)
packages/thirdweb/src/analytics/track/transaction.test.ts (2)
packages/thirdweb/src/exports/thirdweb.ts (1)
  • ThirdwebClient (26-26)
packages/thirdweb/src/analytics/track/transaction.ts (1)
  • trackInsufficientFundsError (63-94)
packages/thirdweb/src/analytics/track/helpers.test.ts (1)
packages/thirdweb/src/analytics/track/helpers.ts (2)
  • isInsufficientFundsError (4-26)
  • getErrorDetails (31-49)
packages/thirdweb/src/analytics/track/transaction.ts (2)
packages/thirdweb/src/wallets/in-app/core/wallet/types.ts (1)
  • Ecosystem (20-23)
packages/thirdweb/src/analytics/track/helpers.ts (1)
  • getErrorDetails (31-49)
packages/thirdweb/src/wallets/injected/index.ts (3)
packages/thirdweb/src/exports/thirdweb.ts (2)
  • Hex (261-261)
  • getAddress (307-307)
packages/thirdweb/src/analytics/track/transaction.ts (2)
  • trackTransaction (27-32)
  • trackInsufficientFundsError (63-94)
packages/thirdweb/src/analytics/track/helpers.ts (1)
  • isInsufficientFundsError (4-26)
packages/thirdweb/src/wallets/smart/index.ts (2)
packages/thirdweb/src/analytics/track/helpers.ts (1)
  • isInsufficientFundsError (4-26)
packages/thirdweb/src/analytics/track/transaction.ts (1)
  • trackInsufficientFundsError (63-94)
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Build Packages
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Lint Packages
  • GitHub Check: Unit Tests
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (22)
packages/thirdweb/src/analytics/track/helpers.ts (2)

4-26: Strong error detection logic with comprehensive pattern matching.

The function correctly handles various error formats and uses case-insensitive matching for reliable detection. The logic covers multiple error structures and common insufficient funds error patterns.


31-49: Well-structured error details extraction.

The function provides a consistent interface for extracting error information from various error formats. The fallback logic ensures a valid response even for malformed errors.

packages/thirdweb/src/transaction/actions/simulate.ts (1)

92-92: Good addition of sender context for error tracking.

Adding fromAddress to the error extraction provides valuable context for insufficient funds error tracking without affecting the existing functionality.

packages/thirdweb/src/transaction/actions/estimate-gas.ts (1)

97-97: Consistent addition of sender context across gas estimation error paths.

Both error handling paths now include fromAddress for better error tracking context. This enhances the insufficient funds error detection capabilities during gas estimation.

Also applies to: 154-154

packages/thirdweb/src/react/core/hooks/transaction/useSendTransaction.ts (2)

2-4: Clean imports for error detection and tracking functionality.

The new imports are properly organized and provide the necessary functionality for insufficient funds error detection and tracking.


179-189: Excellent implementation of insufficient funds error tracking.

The error tracking logic is well-implemented with:

  • Proper conditional detection using isInsufficientFundsError
  • Comprehensive context including wallet, chain, contract, and transaction details
  • Correct use of resolvePromisedValue for async properties
  • Non-intrusive placement that doesn't affect the error flow

This enhances analytics capabilities while maintaining the existing error handling behavior.

packages/thirdweb/src/transaction/extract-error.ts (3)

3-4: Clean imports for the new tracking functionality.

The imports are properly structured and follow the existing import patterns in the file.


16-16: Good addition of optional fromAddress parameter.

This provides necessary context for tracking while maintaining backward compatibility with existing calls.


20-29: Excellent fail-safe implementation of error tracking.

The implementation correctly:

  • Uses conditional checks to ensure tracking only occurs when appropriate
  • Doesn't interfere with the existing error extraction flow
  • Provides comprehensive context for analytics

The tracking call is not awaited, which is correct since it shouldn't block the error extraction process.

packages/thirdweb/src/wallets/smart/index.ts (1)

2-4: Clean import organization.

The imports are well-organized and follow the existing patterns in the file.

packages/thirdweb/src/analytics/track/transaction.test.ts (4)

5-8: Proper import update for the new tracking function.

The import statement correctly includes the new trackInsufficientFundsError function alongside the existing import.


134-172: Comprehensive test coverage for insufficient funds error tracking.

The test correctly verifies:

  • Proper payload structure with the correct action type
  • String conversion of bigint values (transactionValue)
  • Handling of undefined optional fields
  • Extraction of error message from the error object

This provides good coverage for the core tracking functionality.


174-199: Excellent test for error resilience.

This test ensures that tracking failures don't interfere with the main application flow, which is crucial for a tracking/analytics feature. The timeout is appropriate for ensuring the async operation completes.


201-238: Good test coverage for transaction preparation scenario.

This test verifies tracking behavior when optional fields like transactionValue are not provided, ensuring the function handles partial data gracefully.

packages/thirdweb/src/wallets/injected/index.ts (2)

8-10: Consistent import pattern with other wallet implementations.

The imports follow the same pattern established in the smart wallet implementation, maintaining consistency across the codebase.


205-239: Excellent implementation consistent with smart wallet error tracking.

The implementation correctly:

  • Preserves the existing success path unchanged
  • Tracks insufficient funds errors with comprehensive context
  • Maintains the original error flow by re-throwing
  • Uses the same tracking pattern as the smart wallet implementation

The error tracking provides valuable analytics data including transaction value, contract address, and wallet context.

packages/thirdweb/src/analytics/track/helpers.test.ts (3)

1-3: LGTM: Well-structured test setup.

The imports are clean and appropriate. Using vitest for testing framework and importing the helper functions to be tested.


4-68: Excellent comprehensive test coverage for isInsufficientFundsError.

The test suite thoroughly covers all the error detection patterns implemented in the helper function:

Positive cases well covered:

  • Basic insufficient funds messages
  • Gas-related insufficient funds
  • Balance-related errors
  • Error codes and reason fields
  • Nested data structures
  • String errors
  • Case insensitivity

Edge cases properly handled:

  • Null/undefined inputs
  • Non-insufficient funds errors

The tests align perfectly with the implementation patterns in the helper function and provide robust validation.


70-109: Comprehensive test coverage for getErrorDetails function.

The test suite effectively validates all error extraction scenarios:

Error shapes covered:

  • Standard Error objects
  • Objects with message and code properties
  • Nested data structures
  • String errors
  • Null/undefined inputs

Property extraction verified:

  • Message extraction from various sources
  • Code extraction from both code and reason fields
  • Proper fallback handling

The tests ensure the function can handle the diverse error formats that might be encountered in the SDK.

packages/thirdweb/src/analytics/track/transaction.ts (3)

5-5: LGTM: Appropriate import addition.

The import of getErrorDetails from the helpers module is correctly placed and necessary for the new tracking function.


60-74: Well-designed function signature for comprehensive error tracking.

The function signature captures all the essential context needed for insufficient funds error analytics:

Required parameters: Client and error object
Optional context: Ecosystem, wallet address, chain ID, contract details
Financial context: Transaction value, required amount, user balance

The parameter structure enables rich analytics while maintaining flexibility for different calling contexts.


75-94: Robust implementation with proper error detail extraction.

The function implementation is well-structured:

Error processing: Uses getErrorDetails helper for consistent error parsing
Data consistency: Converts bigint values to strings for serialization
Analytics structure: Follows established pattern with action and comprehensive data payload
Optional handling: Properly handles optional fields (e.g., errorCode only included if present)

The tracked data provides comprehensive context for analyzing insufficient funds scenarios across the SDK.

Copy link
Contributor

github-actions bot commented Jun 2, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 62.57 KB (+0.57% 🔺) 1.3 s (+0.57% 🔺) 314 ms (+33.17% 🔺) 1.6 s
thirdweb (cjs) 345.62 KB (+0.15% 🔺) 7 s (+0.15% 🔺) 1.9 s (-2.88% 🔽) 8.8 s
thirdweb (minimal + tree-shaking) 5.7 KB (0%) 114 ms (0%) 87 ms (+504.33% 🔺) 201 ms
thirdweb/chains (tree-shaking) 531 B (0%) 11 ms (0%) 7 ms (-17.19% 🔽) 18 ms
thirdweb/react (minimal + tree-shaking) 19.56 KB (+0.1% 🔺) 392 ms (+0.1% 🔺) 80 ms (+140.15% 🔺) 472 ms

Copy link

codecov bot commented Jun 2, 2025

Codecov Report

Attention: Patch coverage is 45.23810% with 69 lines in your changes missing coverage. Please review.

Project coverage is 55.57%. Comparing base (ca08417) to head (33ff5a2).
Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
packages/thirdweb/src/wallets/injected/index.ts 6.25% 30 Missing ⚠️
...react/core/hooks/transaction/useSendTransaction.ts 16.66% 10 Missing ⚠️
packages/thirdweb/src/wallets/smart/index.ts 28.57% 10 Missing ⚠️
packages/thirdweb/src/transaction/extract-error.ts 25.00% 9 Missing ⚠️
packages/thirdweb/src/analytics/track/helpers.ts 83.87% 4 Missing and 1 partial ⚠️
...ckages/thirdweb/src/analytics/track/transaction.ts 86.36% 3 Missing ⚠️
...s/thirdweb/src/transaction/actions/estimate-gas.ts 50.00% 1 Missing ⚠️
...kages/thirdweb/src/transaction/actions/simulate.ts 0.00% 1 Missing ⚠️

❌ Your patch status has failed because the patch coverage (45.23%) is below the target coverage (80.00%). You can increase the patch coverage or adjust the target coverage.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7256      +/-   ##
==========================================
+ Coverage   55.55%   55.57%   +0.01%     
==========================================
  Files         908      909       +1     
  Lines       58571    58680     +109     
  Branches     4131     4157      +26     
==========================================
+ Hits        32540    32610      +70     
- Misses      25927    25963      +36     
- Partials      104      107       +3     
Flag Coverage Δ
packages 55.57% <45.23%> (+0.01%) ⬆️
Files with missing lines Coverage Δ
...s/thirdweb/src/transaction/actions/estimate-gas.ts 78.70% <50.00%> (-0.55%) ⬇️
...kages/thirdweb/src/transaction/actions/simulate.ts 81.39% <0.00%> (-1.94%) ⬇️
...ckages/thirdweb/src/analytics/track/transaction.ts 94.00% <86.36%> (-6.00%) ⬇️
packages/thirdweb/src/analytics/track/helpers.ts 83.87% <83.87%> (ø)
packages/thirdweb/src/transaction/extract-error.ts 76.92% <25.00%> (-11.97%) ⬇️
...react/core/hooks/transaction/useSendTransaction.ts 11.04% <16.66%> (+0.44%) ⬆️
packages/thirdweb/src/wallets/smart/index.ts 59.58% <28.57%> (-1.14%) ⬇️
packages/thirdweb/src/wallets/injected/index.ts 35.27% <6.25%> (-1.25%) ⬇️

... and 3 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@gregfromstl gregfromstl changed the title [SDK] Feature: Add comprehensive insufficient funds error tracking across SDK [SDK] Feature: Track insufficient funds error across SDK Jun 2, 2025
@gregfromstl gregfromstl merged commit de297e4 into main Jun 2, 2025
24 of 25 checks passed
@gregfromstl gregfromstl deleted the greg/tool-4657-track-insufficient-funds-erros-in-sdk branch June 2, 2025 22:16
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