Skip to content

[SDK] Fix native token fallback when insight query fails #7666

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

joaquim-verges
Copy link
Member

@joaquim-verges joaquim-verges commented Jul 21, 2025


PR-Codex overview

This PR focuses on fixing the fallback mechanism for native tokens when an insight query fails in the thirdweb package.

Detailed summary

  • Updated the logic in usePaymentMethods.ts to handle cases where the query fails.
  • Introduced a mapping of results to extract token balances and details.
  • Created a tokensWithBalance array to store formatted token information.
  • Ensured that only tokens with a balance greater than zero are processed.

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

Summary by CodeRabbit

  • Bug Fixes

    • Improved handling of native token balances when insight queries fail, ensuring these balances are properly formatted and included in the list of owned tokens.
  • Chores

    • Added documentation for a patch update related to the native token fallback mechanism.

Copy link

vercel bot commented Jul 21, 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 Jul 21, 2025 8:30pm
nebula ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 21, 2025 8:30pm
thirdweb_playground ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 21, 2025 8:30pm
thirdweb-www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 21, 2025 8:30pm
wallet-ui ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 21, 2025 8:30pm

Copy link

changeset-bot bot commented Jul 21, 2025

🦋 Changeset detected

Latest commit: 8b4cfef

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
thirdweb Patch
@thirdweb-dev/nebula Patch
@thirdweb-dev/wagmi-adapter Patch

Not sure what this means? Click here to learn what changesets are.

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

Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

Walkthrough

A changeset file was added to document a patch update for the "thirdweb" package, specifically noting a fix to the native token fallback mechanism during insight query failures. Additionally, the internal logic of the usePaymentMethods hook was updated to convert native balances into the internal token format and append them to the owned tokens list when the fallback is triggered.

Changes

File(s) Change Summary
.changeset/eighty-rings-think.md Added a changeset file documenting a patch update for the "thirdweb" package regarding fallback logic.
packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts Updated fallback logic to convert native balances into token format and append them to owned tokens.

Estimated code review effort

2 (~15 minutes)

Warning

Review ran into problems

🔥 Problems

Errors were encountered while retrieving linked issues.

Errors (1)
  • TEAM-0000: Entity not found: Issue - Could not find referenced Issue.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7cf351 and 8b4cfef.

📒 Files selected for processing (2)
  • .changeset/eighty-rings-think.md (1 hunks)
  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • .changeset/eighty-rings-think.md
  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.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). (8)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Build Packages
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Lint Packages
  • GitHub Check: Unit Tests
  • GitHub Check: Analyze (javascript)
✨ 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 Jul 21, 2025
@joaquim-verges joaquim-verges changed the title [React] Fix native token fallback when insight query fails [SDK] Fix native token fallback when insight query fails Jul 21, 2025
@joaquim-verges joaquim-verges marked this pull request as ready for review July 21, 2025 19:52
@joaquim-verges joaquim-verges requested review from a team as code owners July 21, 2025 19:52
Copy link
Member Author


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.

This stack of pull requests is managed by Graphite. Learn more about stacking.

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

🔭 Outside diff range comments (1)
packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (1)

99-142: Consider extracting token conversion logic.

The token conversion logic (lines 124-139) is duplicated at lines 150-165. Consider extracting this into a helper function to follow DRY principles.

Extract the conversion logic into a reusable function:

function convertBalancesToTokens(balances: GetWalletBalanceResult[]): Array<{
  balance: bigint;
  originToken: Token;
}> {
  return balances
    .filter((b) => b.value > 0n)
    .map((b) => ({
      balance: b.value,
      originToken: {
        address: b.tokenAddress,
        chainId: b.chainId,
        decimals: b.decimals,
        iconUri: "",
        name: b.name,
        prices: {
          USD: 0,
        },
        symbol: b.symbol,
      } as Token,
    }));
}

Then use it in both places:

-          // Convert to our format and filter out zero balances
-          const tokensWithBalance = batch
-            .filter((b) => b.value > 0n)
-            .map((b) => ({
-              balance: b.value,
-              originToken: {
-                address: b.tokenAddress,
-                chainId: b.chainId,
-                decimals: b.decimals,
-                iconUri: "",
-                name: b.name,
-                prices: {
-                  USD: 0,
-                },
-                symbol: b.symbol,
-              } as Token,
-            }));
+          const tokensWithBalance = convertBalancesToTokens(batch);
🧹 Nitpick comments (2)
packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (2)

124-125: Remove redundant filtering.

The code filters for b.value > 0n twice - once at line 121 and again at line 125. This is redundant since batch already contains only non-zero balances.

-          const tokensWithBalance = batch
-            .filter((b) => b.value > 0n)
-            .map((b) => ({
+          const tokensWithBalance = batch.map((b) => ({

128-138: Enhance token data with proper defaults.

The token construction uses hardcoded defaults that might not be optimal. Consider using more descriptive defaults or constants.

              originToken: {
                address: b.tokenAddress,
                chainId: b.chainId,
                decimals: b.decimals,
-               iconUri: "",
+               iconUri: "", // TODO: Add native token icon URL
                name: b.name,
                prices: {
-                 USD: 0,
+                 USD: 0, // Price will be fetched later via routes
                },
                symbol: b.symbol,
              } as Token,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22bf68a and 0509f94.

📒 Files selected for processing (2)
  • .changeset/eighty-rings-think.md (1 hunks)
  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each file to one stateless, single-responsibility function for clarity
Re-use shared types from @/types or local types.ts barrels
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.)
Comment only ambiguous logic; avoid restating TypeScript in prose

Files:

  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules
Learnt from: MananTank
PR: thirdweb-dev/js#7177
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/erc20/_hooks/useTokenPriceData.ts:49-49
Timestamp: 2025-05-27T19:55:25.056Z
Learning: In the ERC20 public pages token price data hook (`useTokenPriceData.ts`), direct array access on `json.data[0]` without optional chaining is intentionally correct and should not be changed to use safety checks.
Learnt from: MananTank
PR: thirdweb-dev/js#7081
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/assets/create/create-token-page-impl.tsx:110-118
Timestamp: 2025-05-20T18:54:15.781Z
Learning: In the thirdweb dashboard's token asset creation flow, the `transferBatch` function from `thirdweb/extensions/erc20` accepts the raw quantity values from the form without requiring explicit conversion to wei using `toUnits()`. The function appears to handle this conversion internally or is designed to work with the values in the format they're already provided.
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Support for in-app wallets (social/email login)
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Smart wallets with account abstraction
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Unified `Wallet` and `Account` interfaces in wallet architecture
Learnt from: gregfromstl
PR: thirdweb-dev/js#7450
File: packages/thirdweb/src/bridge/Webhook.ts:57-81
Timestamp: 2025-06-26T19:46:04.024Z
Learning: In the onramp webhook schema (`packages/thirdweb/src/bridge/Webhook.ts`), the `currencyAmount` field is intentionally typed as `z.number()` while other amount fields use `z.string()` because `currencyAmount` represents fiat currency amounts in decimals (like $10.50), whereas other amount fields represent token amounts in wei (very large integers that benefit from bigint representation). The different naming convention (`currencyAmount` vs `amount`) reflects this intentional distinction.
.changeset/eighty-rings-think.md (4)

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Surface breaking changes prominently in PR descriptions

Learnt from: MananTank
PR: #7081
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/assets/create/create-token-page-impl.tsx:110-118
Timestamp: 2025-05-20T18:54:15.781Z
Learning: In the thirdweb dashboard's token asset creation flow, the transferBatch function from thirdweb/extensions/erc20 accepts the raw quantity values from the form without requiring explicit conversion to wei using toUnits(). The function appears to handle this conversion internally or is designed to work with the values in the format they're already provided.

Learnt from: MananTank
PR: #7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nft-drop-claim.tsx:82-90
Timestamp: 2025-06-13T13:03:41.732Z
Learning: The thirdweb contract object is serializable and can safely be used in contexts (e.g., React-Query keys) that require serializable values.

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (10)

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules

Learnt from: MananTank
PR: #7177
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/erc20/_hooks/useTokenPriceData.ts:49-49
Timestamp: 2025-05-27T19:55:25.056Z
Learning: In the ERC20 public pages token price data hook (useTokenPriceData.ts), direct array access on json.data[0] without optional chaining is intentionally correct and should not be changed to use safety checks.

Learnt from: MananTank
PR: #7081
File: apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/assets/create/create-token-page-impl.tsx:110-118
Timestamp: 2025-05-20T18:54:15.781Z
Learning: In the thirdweb dashboard's token asset creation flow, the transferBatch function from thirdweb/extensions/erc20 accepts the raw quantity values from the form without requiring explicit conversion to wei using toUnits(). The function appears to handle this conversion internally or is designed to work with the values in the format they're already provided.

Learnt from: gregfromstl
PR: #7450
File: packages/thirdweb/src/bridge/Webhook.ts:57-81
Timestamp: 2025-06-26T19:46:04.024Z
Learning: In the onramp webhook schema (packages/thirdweb/src/bridge/Webhook.ts), the currencyAmount field is intentionally typed as z.number() while other amount fields use z.string() because currencyAmount represents fiat currency amounts in decimals (like $10.50), whereas other amount fields represent token amounts in wei (very large integers that benefit from bigint representation). The different naming convention (currencyAmount vs amount) reflects this intentional distinction.

Learnt from: CR
PR: thirdweb-dev/js#0
File: .cursor/rules/dashboard.mdc:0-0
Timestamp: 2025-07-18T19:20:32.530Z
Learning: Applies to dashboard/**/*client.tsx : Interactive UI that relies on hooks (useState, useEffect, React Query, wallet hooks).

Learnt from: MananTank
PR: #7307
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:324-346
Timestamp: 2025-06-09T15:15:02.350Z
Learning: In the move-funds functionality, MananTank prefers having both individual toast.promise notifications for each token transfer AND batch summary toasts, even though this creates multiple notifications. This dual notification approach is acceptable for the move-funds user experience.

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to test/src/test-wallets.ts : Predefined test accounts are in test/src/test-wallets.ts

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : Unified Wallet and Account interfaces in wallet architecture

Learnt from: MananTank
PR: #7177
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/erc20/erc20.tsx:15-17
Timestamp: 2025-05-27T19:54:55.885Z
Learning: The fetchDashboardContractMetadata function from "@3rdweb-sdk/react/hooks/useDashboardContractMetadata" has internal error handlers for all promises and cannot throw errors, so external error handling is not needed when calling this function.

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/exports/react.native.ts : React Native specific exports are in src/exports/react.native.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). (8)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Build Packages
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (2)
.changeset/eighty-rings-think.md (1)

1-6: LGTM! Changeset properly documents the patch fix.

The changeset correctly follows the standard format and accurately describes the native token fallback fix with appropriate patch versioning.

packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (1)

122-142: No action needed: Native token address is always set to NATIVE_TOKEN_ADDRESS

The fallback paths in usePaymentMethods call getWalletBalance without a tokenAddress, and in getWalletBalance.ts you can see:

  • tokenAddress: tokenAddress ?? NATIVE_TOKEN_ADDRESS

Since tokenAddress is injected when fetching native balances, b.tokenAddress will never be undefined or the zero address—it will always be the NATIVE_TOKEN_ADDRESS constant (0xeeee…eeee).

Copy link
Contributor

github-actions bot commented Jul 21, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 63.23 KB (0%) 1.3 s (0%) 392 ms (+94.95% 🔺) 1.7 s
thirdweb (cjs) 353.45 KB (0%) 7.1 s (0%) 1.7 s (+8.18% 🔺) 8.8 s
thirdweb (minimal + tree-shaking) 5.7 KB (0%) 114 ms (0%) 196 ms (+1289.58% 🔺) 310 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 97 ms (+2463.56% 🔺) 107 ms
thirdweb/react (minimal + tree-shaking) 19.59 KB (0%) 392 ms (0%) 125 ms (+348.23% 🔺) 517 ms

Copy link

codecov bot commented Jul 21, 2025

Codecov Report

Attention: Patch coverage is 0% with 16 lines in your changes missing coverage. Please review.

Project coverage is 56.36%. Comparing base (22bf68a) to head (8b4cfef).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
...thirdweb/src/react/core/hooks/usePaymentMethods.ts 0.00% 16 Missing ⚠️

❌ Your patch status has failed because the patch coverage (0.00%) 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    #7666      +/-   ##
==========================================
- Coverage   56.40%   56.36%   -0.05%     
==========================================
  Files         908      908              
  Lines       58228    58244      +16     
  Branches     4226     4226              
==========================================
- Hits        32844    32829      -15     
- Misses      25274    25307      +33     
+ Partials      110      108       -2     
Flag Coverage Δ
packages 56.36% <0.00%> (-0.05%) ⬇️
Files with missing lines Coverage Δ
...thirdweb/src/react/core/hooks/usePaymentMethods.ts 4.22% <0.00%> (-0.35%) ⬇️

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

@joaquim-verges joaquim-verges force-pushed the _React_Fix_native_token_fallback_when_insight_query_fails branch from 0509f94 to 2dbc389 Compare July 21, 2025 20:03
@joaquim-verges joaquim-verges force-pushed the _React_Fix_native_token_fallback_when_insight_query_fails branch from f7cf351 to 8b4cfef Compare July 21, 2025 20:13
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.

2 participants