Skip to content

Handle token balance retrieval failures #7600

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 3 commits into
base: main
Choose a base branch
from

Conversation

gregfromstl
Copy link
Member

@gregfromstl gregfromstl commented Jul 11, 2025

<!--

## [SDK] Feature: Add fallback for `getOwnedTokens` failures in `usePaymentMethods`

## Notes for the reviewer

- Implemented a `try-catch` block around `getOwnedTokens` calls in `usePaymentMethods.ts`.
- If a `getOwnedTokens` batch fails, it now falls back to fetching native token balances for the chains in that batch using `getWalletBalance`.
- Uses `Promise.allSettled` for robust handling of native balance fetches.
- Ensures fallback data is formatted consistently with `getOwnedTokens` results and filters out zero balances.

## How to test

- To test the fallback, simulate a failure of the `getOwnedTokens` call within `usePaymentMethods` (e.g., by mocking the function to throw an error).
- Verify that native token balances are displayed correctly when the `getOwnedTokens` call fails.

-->

Slack Thread


PR-Codex overview

This PR introduces a fallback mechanism in the usePaymentMethods hook to handle failures when fetching owned tokens. It ensures users can still access their native token balances during API issues by using getWalletBalance.

Detailed summary

  • Added fallback for getOwnedTokens failures in usePaymentMethods.
  • Logs warnings on getOwnedTokens errors.
  • Fetches native balances using getWalletBalance for each chain.
  • Transforms native balance results to match the expected format.
  • Maintains normal processing flow seamlessly.

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

Summary by CodeRabbit

  • Bug Fixes

    • Improved reliability of token retrieval by adding a fallback to native wallet balances if the primary method fails.
  • Style

    • Enhanced readability of string formatting in token key construction.

@gregfromstl gregfromstl requested review from a team as code owners July 11, 2025 22:25
Copy link

changeset-bot bot commented Jul 11, 2025

🦋 Changeset detected

Latest commit: c512d2c

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

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

Copy link
Contributor

coderabbitai bot commented Jul 11, 2025

"""

Walkthrough

The code in the usePaymentMethods hook was updated to wrap the getOwnedTokens call in a try-catch block. If an error occurs, it now falls back to retrieving wallet balances for each relevant chain, ensuring continued functionality. Minor formatting adjustments to string templates were also made for readability.

Changes

File(s) Change Summary
packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts Wrapped getOwnedTokens in try-catch; added fallback to getWalletBalance per chain; improved string template formatting.

Sequence Diagram(s)

sequenceDiagram
    participant UI
    participant usePaymentMethods
    participant getOwnedTokens
    participant getWalletBalance

    UI->>usePaymentMethods: Invoke hook
    usePaymentMethods->>getOwnedTokens: Fetch tokens (batch)
    alt getOwnedTokens succeeds
        getOwnedTokens-->>usePaymentMethods: Return tokens
    else getOwnedTokens fails
        usePaymentMethods->>getWalletBalance: For each chain, fetch native balance
        getWalletBalance-->>usePaymentMethods: Return balances
        usePaymentMethods-->>usePaymentMethods: Filter and transform balances
    end
    usePaymentMethods-->>UI: Return payment methods
Loading

"""


📜 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 5dfc01e and c512d2c.

📒 Files selected for processing (1)
  • packages/thirdweb/src/react/core/hooks/usePaymentMethods.ts (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • 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, vite)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Lint Packages
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: Build Packages
  • 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.

Copy link
Contributor

graphite-app bot commented Jul 11, 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

github-actions bot commented Jul 11, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 63.25 KB (0%) 1.3 s (0%) 361 ms (+67.49% 🔺) 1.7 s
thirdweb (cjs) 353.31 KB (0%) 7.1 s (0%) 1.6 s (-0.61% 🔽) 8.7 s
thirdweb (minimal + tree-shaking) 5.7 KB (0%) 114 ms (0%) 95 ms (+406.99% 🔺) 209 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 45 ms (+778.15% 🔺) 55 ms
thirdweb/react (minimal + tree-shaking) 19.59 KB (0%) 392 ms (0%) 68 ms (+156.57% 🔺) 460 ms

Copy link

codecov bot commented Jul 11, 2025

Codecov Report

Attention: Patch coverage is 2.38095% with 41 lines in your changes missing coverage. Please review.

Project coverage is 56.43%. Comparing base (592bf6f) to head (c512d2c).

Files with missing lines Patch % Lines
...thirdweb/src/react/core/hooks/usePaymentMethods.ts 2.38% 41 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #7600      +/-   ##
==========================================
- Coverage   56.45%   56.43%   -0.03%     
==========================================
  Files         906      906              
  Lines       58115    58144      +29     
  Branches     4226     4227       +1     
==========================================
+ Hits        32810    32811       +1     
- Misses      25195    25223      +28     
  Partials      110      110              
Flag Coverage Δ
packages 56.43% <2.38%> (-0.03%) ⬇️
Files with missing lines Coverage Δ
...thirdweb/src/react/core/hooks/usePaymentMethods.ts 4.56% <2.38%> (-0.20%) ⬇️
🚀 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.

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)
.changeset/fallback-native-balance.md (1)

5-13: Use consistent, imperative mood in changeset description

Changeset summaries usually follow the “Imperative present tense” convention (“Add → Adds”), and end with a period. Consider tweaking the summary and bullets for consistency:

-Add fallback mechanism to usePaymentMethods hook for getOwnedTokens failures
+Adds a fallback mechanism to the `usePaymentMethods` hook for `getOwnedTokens` failures.

Likewise, switch the bullet list verbs to the same tense (“Catches → Catch”, “Falls → Fall”, etc.) for stylistic consistency.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b2b8426 and 65972fe.

📒 Files selected for processing (1)
  • .changeset/fallback-native-balance.md (1 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: MananTank
PR: thirdweb-dev/js#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-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support EIP-1193, EIP-5792, EIP-7702 standards in wallet architecture
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support for in-app wallets (social/email login) in wallet architecture
Learnt from: MananTank
PR: thirdweb-dev/js#7152
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/nfts/components/table.tsx:304-313
Timestamp: 2025-05-26T16:27:26.443Z
Learning: The `useChainSlug` hook returns `string | number`, not `string | undefined` as previously assumed. It does not return undefined values.
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: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Unified `Wallet` and `Account` interfaces in wallet architecture
Learnt from: MananTank
PR: thirdweb-dev/js#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: joaquim-verges
PR: thirdweb-dev/js#7268
File: packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts:210-216
Timestamp: 2025-06-03T23:44:40.243Z
Learning: EIP7702 wallets do not need special handling for switching chains, unlike EIP4337 wallets which require reconnection when switching chains. In the switchChain method condition, EIP7702 should be intentionally excluded from the reconnection logic.
.changeset/fallback-native-balance.md (7)
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support EIP-1193, EIP-5792, EIP-7702 standards in wallet architecture
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Unified `Wallet` and `Account` interfaces in wallet architecture
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Support for in-app wallets (social/email login) in wallet architecture
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-06-30T10:25:29.489Z
Learning: Applies to src/wallets/**/*.{ts,tsx} : Smart wallets with account abstraction in wallet architecture
Learnt from: MananTank
PR: thirdweb-dev/js#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: 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: joaquim-verges
PR: thirdweb-dev/js#7268
File: packages/thirdweb/src/wallets/in-app/core/wallet/in-app-core.ts:210-216
Timestamp: 2025-06-03T23:44:40.243Z
Learning: EIP7702 wallets do not need special handling for switching chains, unlike EIP4337 wallets which require reconnection when switching chains. In the switchChain method condition, EIP7702 should be intentionally excluded from the reconnection logic.
⏰ 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). (5)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Unit Tests
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Analyze (javascript)

@gregfromstl gregfromstl force-pushed the cursor/handle-token-balance-retrieval-failures-d090 branch from 5dfc01e to c512d2c Compare July 11, 2025 23:47
Copy link
Member Author

Merge activity

  • Jul 11, 11:57 PM UTC: The merge label 'merge-queue' was detected. This PR will be added to the Graphite merge queue once it meets the requirements.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
merge-queue Adds the pull request to Graphite's merge queue. packages SDK Involves changes to the thirdweb SDK
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants