Skip to content

Conversation

@0xFirekeeper
Copy link
Member

@0xFirekeeper 0xFirekeeper commented Dec 16, 2025

Refactored fetchAllPortfolios to use up to 50 concurrent workers instead of batching, improving throughput. Updated fetchWithRetry to return null on failure instead of throwing, and adjusted downstream logic to handle null responses gracefully. Errors for individual addresses are now logged and do not interrupt processing of others.


PR-Codex overview

This PR improves the fetchWithRetry function to return null on failure instead of throwing an error, enhancing error handling. It also refines the fetchAllPortfolios function to process up to 50 addresses concurrently, improving performance and error management during portfolio fetching.

Detailed summary

  • Updated fetchWithRetry to return null on failure instead of throwing an error.
  • Modified the response check in fetchTokensForChain to handle null responses.
  • Increased concurrency from processing batches of 10 addresses to 50 concurrently in fetchAllPortfolios.
  • Implemented a worker function to process addresses individually while maintaining concurrency.
  • Improved error handling by logging failures without interrupting the entire process.

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

Summary by CodeRabbit

  • Bug Fixes

    • Improved error resilience with automatic retry logic for rate limiting and server errors
    • Prevented cascade failures when individual address lookups fail during portfolio loading
  • Performance

    • Increased concurrency for portfolio fetching, enabling faster data loading
    • Enhanced progress tracking with more frequent updates during portfolio sync

✏️ Tip: You can customize this high-level summary in your review settings.

Refactored fetchAllPortfolios to use up to 50 concurrent workers instead of batching, improving throughput. Updated fetchWithRetry to return null on failure instead of throwing, and adjusted downstream logic to handle null responses gracefully. Errors for individual addresses are now logged and do not interrupt processing of others.
@0xFirekeeper 0xFirekeeper requested review from a team as code owners December 16, 2025 23:00
@changeset-bot
Copy link

changeset-bot bot commented Dec 16, 2025

⚠️ No Changeset found

Latest commit: 20d9e43

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

@vercel
Copy link

vercel bot commented Dec 16, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
thirdweb-www Building Building Preview, Comment Dec 16, 2025 11:00pm
4 Skipped Deployments
Project Deployment Review Updated (UTC)
docs-v2 Skipped Skipped Dec 16, 2025 11:00pm
nebula Skipped Skipped Dec 16, 2025 11:00pm
thirdweb_playground Skipped Skipped Dec 16, 2025 11:00pm
wallet-ui Skipped Skipped Dec 16, 2025 11:00pm

@github-actions github-actions bot added the Dashboard Involves changes to the Dashboard. label Dec 16, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 16, 2025

Walkthrough

Modified useWalletPortfolio.ts to add exponential backoff retry logic that returns null on failure, change token fetch to return empty lists on errors, and reorganize portfolio fetching from batched Promise aggregation to a concurrent worker model (up to 50 workers) with per-address error handling and progress updates.

Changes

Cohort / File(s) Summary
Retry and error handling
apps/dashboard/src/@/hooks/useWalletPortfolio.ts
Added fetchWithRetry function with exponential backoff that retries on 429 (rate limit) and 5xx errors, returning null instead of throwing on persistent failure.
Token fetch resilience
apps/dashboard/src/@/hooks/useWalletPortfolio.ts
Modified fetchTokensForChain to treat non-ok or missing responses as empty token lists, removing error propagation.
Concurrency model refactoring
apps/dashboard/src/@/hooks/useWalletPortfolio.ts
Replaced batch-based Promise.allSettled processing in fetchAllPortfolios with high-concurrency worker loop (up to 50 concurrent workers), processing addresses one-by-one with per-address error isolation and progress updates after each completion.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Retry mechanism with exponential backoff: Verify timing calculations, boundary conditions, and that null-on-failure aligns with calling code expectations.
  • Concurrency worker implementation: Inspect worker loop logic, queue management, race conditions, and proper state updates across concurrent operations.
  • Error isolation per address: Ensure one address failure truly does not abort other addresses or corrupt the results Map.
  • Progress tracking accuracy: Confirm progress updates reflect actual completion state and don't race with worker operations.
  • Impact on performance and rate limiting: High concurrency (50) may need load testing to confirm it doesn't overwhelm APIs or create unexpected bottlenecks.

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Improve portfolio fetch concurrency and error handling' accurately summarizes the main changes: enhanced concurrency in portfolio fetching and improved error handling mechanisms.
Description check ✅ Passed The PR description covers the main changes (concurrency improvement, null return handling, error logging) but lacks the recommended format with issue tag and 'Notes for the reviewer' section from the template.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch firekeeper/bal-perf

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov
Copy link

codecov bot commented Dec 16, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 54.47%. Comparing base (5f0e25b) to head (20d9e43).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #8572   +/-   ##
=======================================
  Coverage   54.47%   54.47%           
=======================================
  Files         922      922           
  Lines       61361    61361           
  Branches     4149     4149           
=======================================
  Hits        33425    33425           
  Misses      27835    27835           
  Partials      101      101           
Flag Coverage Δ
packages 54.47% <ø> (ø)
🚀 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)
apps/dashboard/src/@/hooks/useWalletPortfolio.ts (1)

160-196: Consider reducing concurrency or documenting the rationale.

With 50 concurrent workers, and each address fetching all chains in parallel (via Promise.all in fetchWalletPortfolio), peak concurrent requests could be 50 × chainIds.length. For 10+ chains, this means 500+ simultaneous requests, which may trigger API rate limiting despite the retry logic.

Consider either:

  1. Reducing concurrency to a more conservative value (e.g., 10-20)
  2. Adding per-chain concurrency limits within fetchWalletPortfolio
  3. Making concurrency configurable via a parameter

Also, per coding guidelines, add an explicit return type annotation to the worker function:

-  async function worker() {
+  async function worker(): Promise<void> {
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Disabled knowledge base sources:

  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5f0e25b and 20d9e43.

📒 Files selected for processing (1)
  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

**/*.{ts,tsx}: Write idiomatic TypeScript with explicit function declarations and return types
Limit each TypeScript 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 in TypeScript
Avoid any and unknown in TypeScript unless unavoidable; narrow generics when possible
Choose composition over inheritance; leverage utility types (Partial, Pick, etc.) in TypeScript

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

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
apps/{dashboard,playground-web}/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

apps/{dashboard,playground-web}/src/**/*.{ts,tsx}: Import UI component primitives from @/components/ui/* (Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground
Use Tailwind CSS only – no inline styles or CSS modules in dashboard and playground
Use cn() from @/lib/utils for conditional Tailwind class merging
Use design system tokens for styling (backgrounds: bg-card, borders: border-border, muted text: text-muted-foreground)
Expose className prop on root element for component overrides

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
apps/dashboard/src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

apps/dashboard/src/**/*.{ts,tsx}: Use NavLink for internal navigation with automatic active states in dashboard
Start server component files with import "server-only"; in Next.js
Read cookies/headers with next/headers in server components
Access server-only environment variables in server components
Perform heavy data fetching in server components
Implement redirect logic with redirect() from next/navigation in server components
Begin client component files with 'use client'; directive in Next.js
Handle interactive UI with React hooks (useState, useEffect, React Query, wallet hooks) in client components
Access browser APIs (localStorage, window, IntersectionObserver) in client components
Support fast transitions with prefetched data in client components
Always call getAuthToken() to retrieve JWT from cookies on server side
Use Authorization: Bearer header for API calls – never embed tokens in URLs
Return typed results (Project[], User[]) from server-side data fetches – avoid any
Wrap client-side API calls in React Query (@tanstack/react-query)
Use descriptive, stable queryKeys in React Query for cache hits
Configure staleTime/cacheTime in React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never import posthog-js in server components – only use analytics client-side

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
apps/dashboard/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)

apps/dashboard/**/*.{ts,tsx}: Always import from the central UI library under @/components/ui/* for reusable core UI components like Button, Input, Select, Tabs, Card, Sidebar, Separator, Badge
Use NavLink from @/components/ui/NavLink for internal navigation to ensure active states are handled automatically
For notices and skeletons, rely on AnnouncementBanner, GenericLoadingPage, and EmptyStateCard components
Import icons from lucide-react or the project-specific …/icons exports; never embed raw SVG
Keep components pure; fetch data outside using server components or hooks and pass it down via props
Use Tailwind CSS as the styling system; avoid inline styles or CSS modules
Merge class names with cn from @/lib/utils to keep conditional logic readable
Stick to design tokens: use bg-card, border-border, text-muted-foreground and other Tailwind variables instead of hard-coded colors
Use spacing utilities (px-*, py-*, gap-*) instead of custom margins
Follow mobile-first responsive design with Tailwind helpers (max-sm, md, lg, xl)
Never hard-code colors; always use Tailwind variables
Combine class names via cn, and expose className prop if useful in components
Use React Query (@tanstack/react-query) for all client-side data fetching with typed hooks

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
apps/dashboard/**/*use*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/dashboard.mdc)

apps/dashboard/**/*use*.{ts,tsx}: Keep queryKey stable and descriptive in React Query hooks for reliable cache hits
Configure staleTime and cacheTime in React Query according to data freshness requirements

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
**/*.{js,jsx,ts,tsx,json}

📄 CodeRabbit inference engine (AGENTS.md)

Biome governs formatting and linting; its rules live in biome.json. Run pnpm fix & pnpm lint before committing, ensure there are no linting errors

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
apps/{dashboard,playground}/**/*.{tsx,ts}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{tsx,ts}: Import UI primitives from @/components/ui/_ (Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in Dashboard and Playground apps
Use NavLink for internal navigation so active states are handled automatically
Use Tailwind CSS for styling – no inline styles or CSS modules
Merge class names with cn() from @/lib/utils to keep conditional logic readable
Stick to design tokens for styling: backgrounds (bg-card), borders (border-border), muted text (text-muted-foreground), etc.
Server Components: Read cookies/headers with next/headers, access server-only environment variables or secrets, perform heavy data fetching, implement redirect logic with redirect() from next/navigation, and start files with import 'server-only'; to prevent client bundling
Client Components: Begin files with 'use client'; before imports, handle interactive UI relying on React hooks (useState, useEffect, React Query, wallet hooks), access browser APIs (localStorage, window, IntersectionObserver, etc.), and support fast transitions with client-side data prefetching
For client-side data fetching: Wrap calls in React Query (@tanstack/react-query), use descriptive and stable queryKeys for cache hits, configure staleTime / cacheTime based on freshness requirements (default ≥ 60 s), and keep tokens secret by calling internal API routes or server actions

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
apps/{dashboard,playground}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{ts,tsx}: For server-side data fetching: Always call getAuthToken() to retrieve the JWT from cookies and inject the token as an Authorization: Bearer header – never embed it in the URL. Return typed results (Project[], User[], …) – avoid any
Never import posthog-js in server components; analytics reporting is client-side only

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Lazy-import optional features; avoid top-level side-effects

Files:

  • apps/dashboard/src/@/hooks/useWalletPortfolio.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, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Build Packages
  • GitHub Check: Lint Packages
  • GitHub Check: Unit Tests
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
apps/dashboard/src/@/hooks/useWalletPortfolio.ts (3)

15-42: LGTM - Clean retry implementation with graceful degradation.

The exponential backoff logic is correct (1s → 2s → 4s, capped at 10s), and returning null on failure instead of throwing enables the caller to handle failures gracefully without interrupting batch operations.


75-78: LGTM - Graceful handling of failed chain fetches.

Returning an empty array for failed fetches is appropriate since it allows aggregation to continue without affecting totals for other successful chains.


201-231: LGTM - Hook correctly wraps the portfolio fetching logic.

The useMutation pattern is appropriate for this use case since it's a user-triggered action with progress tracking rather than a cached query.

@0xFirekeeper 0xFirekeeper merged commit 7ebc32a into main Dec 16, 2025
24 of 25 checks passed
@0xFirekeeper 0xFirekeeper deleted the firekeeper/bal-perf branch December 16, 2025 23:06
@github-actions
Copy link
Contributor

github-actions bot commented Dec 16, 2025

size-limit report 📦

Path Size
@thirdweb-dev/nexus (esm) 105.66 KB (0%)
@thirdweb-dev/nexus (cjs) 319.47 KB (0%)

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

Labels

Dashboard Involves changes to the Dashboard.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants