Skip to content

fix: refetch token balances after dust success#2845

Merged
mmioana merged 1 commit into
developfrom
fix/refetch-token-balances-after-dust-success
May 8, 2026
Merged

fix: refetch token balances after dust success#2845
mmioana merged 1 commit into
developfrom
fix/refetch-token-balances-after-dust-success

Conversation

@mmioana
Copy link
Copy Markdown
Contributor

@mmioana mmioana commented May 6, 2026

Which Jira task belongs to this PR?

Closes https://linear.app/lifi-linear/issue/JUM-911/check-frequency-of-token-balance-refresh

Testing steps

  1. Go to /portfolio
  2. Try converting dust on a chain where we get a quote for
  3. Once the tx is successful and we either close the modal/status bottom sheet, a balance refresh should be triggered for the exchanged tokens
  4. Thus, these tokens should no longer be available for conversion
  5. Also the portfolio tokens should have the balances updated (both on the portfolio page and in the wallet menu)

Why did I implement it this way?

Checklist before requesting a review

  • I have performed a self-review of my code
  • This pull request is as small as possible and only tackles one problem
  • I have added tests that cover the functionality / test the bug
  • If this changed the API, I have updated the documentation
  • I have provided QA instructions for the feature / fix implemented in this PR (if applicable)
  • I have provided instructions for any environment / deployment changes that this PR needs when merged

Summary by CodeRabbit

  • Refactor
    • Optimized token balance refresh handling after conversions for improved efficiency and decoupled state management. Internal portfolio refresh logic restructured to use targeted token-specific refresh operations rather than full portfolio updates.

@mmioana mmioana self-assigned this May 6, 2026
@vercel
Copy link
Copy Markdown

vercel Bot commented May 6, 2026

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

Project Deployment Actions Updated (UTC)
jumper-exchange Ready Ready Preview, Comment May 6, 2026 4:18pm
jumper-exchange-storybook Ready Ready Preview, Comment May 6, 2026 4:18pm

Request Review

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 6, 2026

✅ All snapshot tests passed

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

Walkthrough

The PR decouples token refresh from portfolio refresh by introducing a new refreshForTokens flow through the portfolio provider stack. It adds token-specific balance fetching and refresh mechanisms at each layer, enabling targeted updates of specific token balances while maintaining the existing portfolio refresh path.

Changes

Token-Specific Balance Refresh Flow

Layer / File(s) Summary
Type Definitions
src/providers/PortfolioProvider/types.ts
Added refreshForTokens(address: string, tokens: LifiToken[]) => Promise<void> to OrchestrationState interface with LifiToken import from '@lifi/sdk'.
Core Balance Fetching
src/providers/PortfolioProvider/lib/fetchBalancesForAddresses.ts
Exported createTokenBalancesFromPlainArray and added new fetchTokenBalancesForAddress function that batches token balance requests per chainId using lodash groupBy.
Hook Implementations
src/providers/PortfolioProvider/hooks/useBalancesData.ts
Added refetchForTokens(address, tokens) method to UseTokensDataResult that fetches fresh token balances, filters existing balances, and merges results into the cache.
Orchestration Wiring
src/providers/PortfolioProvider/hooks/useOrchestrationState.ts
Added refreshForTokens callback wrapping balances.refetchForTokens with proper typing and included in hook return and dependency array.
Context Exposure
src/providers/PortfolioProvider/PortfolioContext.ts
Added refreshForTokens to defaultOrchestrationState object alongside existing refresh and refreshByAddress handlers.
DustFlow Integration
src/components/composite/DustFlow/hooks/useDustModalFlow.tsx
Replaced portfolio refresh calls with refreshForTokens from usePortfolioState(). Added completedDustSummaryRef to cache completed dust summaries and new refreshCompletedDustTokens helper. Updated transaction form and status sheet onSuccess handlers to trigger token refresh after dust conversion completes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • laurentsenta
  • oktapodia
  • callMeTheQA

Poem

🐰 A dusty conversion now flows so clean,
Token by token, a refresh machine,
No whole portfolio need spin around,
Just the changed tokens we've found!
The dust settles light, the balances bright. ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: refetch token balances after dust success' directly and clearly describes the main purpose of the PR - refreshing token balances after a successful dust conversion.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/refetch-token-balances-after-dust-success

Warning

Review ran into problems

🔥 Problems

Git: Failed to clone repository. Please run the @coderabbitai full review command to re-trigger a full review. If the issue persists, set path_filters to include or exclude specific files.


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

Copy link
Copy Markdown
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.

🧹 Nitpick comments (1)
src/providers/PortfolioProvider/hooks/useBalancesData.ts (1)

148-175: 💤 Low value

Consider persisting refreshed balances to cache.

The refetchForTokens function updates the React Query cache but does not persist to setBalancesInCache, unlike the main queryFn which persists on completion. This means refreshed token balances will be lost on next app load until a full refetch occurs.

If this is intentional (e.g., relying on next full refresh to persist), the current approach is fine. Otherwise, consider adding persistence:

♻️ Optional: Persist refreshed balances
   const refetchForTokens = useCallback(
     async (address: string, tokens: LifiToken[]) => {
       const freshBalances = await fetchTokenBalancesForAddress(address, tokens);

       queryClient.setQueryData<TokenQueryData>(
         ['portfolio-tokens', address],
         (prev) => {
           if (!prev) {
             return prev;
           }

           const kept = differenceWith(
             prev.balances,
             tokens,
             (b, t) =>
               b.token.chainId === t.chainId &&
               b.token.address.toLowerCase() === t.address.toLowerCase(),
           );

-          return {
+          const newBalances = [...kept, ...freshBalances];
+          
+          // Persist to cache for next app load
+          if (newBalances.length) {
+            setBalancesInCache(address, newBalances);
+          }
+
+          return {
             ...prev,
-            balances: [...kept, ...freshBalances],
+            balances: newBalances,
           };
         },
       );
     },
-    [queryClient],
+    [queryClient, setBalancesInCache],
   );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/providers/PortfolioProvider/hooks/useBalancesData.ts` around lines 148 -
175, refetchForTokens updates the React Query cache but doesn't persist the
refreshed balances to storage; modify refetchForTokens (the function defined as
refetchForTokens) to call setBalancesInCache after computing the new
TokenQueryData/balances (the same shape produced in the queryFn) so the updated
balances are saved persistently; ensure you pass the address and the updated
balances/TokenQueryData into setBalancesInCache and keep the existing
queryClient.setQueryData update logic intact.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/providers/PortfolioProvider/hooks/useBalancesData.ts`:
- Around line 148-175: refetchForTokens updates the React Query cache but
doesn't persist the refreshed balances to storage; modify refetchForTokens (the
function defined as refetchForTokens) to call setBalancesInCache after computing
the new TokenQueryData/balances (the same shape produced in the queryFn) so the
updated balances are saved persistently; ensure you pass the address and the
updated balances/TokenQueryData into setBalancesInCache and keep the existing
queryClient.setQueryData update logic intact.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 62448d6a-4635-4d0a-82c9-1208ccefb271

📥 Commits

Reviewing files that changed from the base of the PR and between e173ebb and 89f03ae.

📒 Files selected for processing (6)
  • src/components/composite/DustFlow/hooks/useDustModalFlow.tsx
  • src/providers/PortfolioProvider/PortfolioContext.ts
  • src/providers/PortfolioProvider/hooks/useBalancesData.ts
  • src/providers/PortfolioProvider/hooks/useOrchestrationState.ts
  • src/providers/PortfolioProvider/lib/fetchBalancesForAddresses.ts
  • src/providers/PortfolioProvider/types.ts

@github-actions
Copy link
Copy Markdown

github-actions Bot commented May 6, 2026

Playwright test results

failed  2 failed
passed  53 passed
flaky  1 flaky
skipped  1 skipped

Details

stats  57 tests across 11 suites
duration  12 minutes, 36 seconds
commit  89f03ae

Failed tests

chromium › earnPage.spec.ts › Analytics filters on Earn page › Should be able to verify analytics buttons are visible (Qase ID: 47)
chromium › landingPage.spec.ts › Landing page and navigation › Should navigate to the homepage and change tabs (Qase ID: 2)

Flaky tests

chromium › mainMenu.spec.ts › Main Menu flows › Should be able to navigate to X (Qase ID: 16)

Skipped tests

chromium › themeManipulation.spec.ts › Switch between dark and light theme and check the background color › Partner theme should appear in theme menu and apply background color (Qase ID: 49)

📋 View Detailed Qase Report

@mmioana mmioana merged commit d354050 into develop May 8, 2026
17 of 18 checks passed
@mmioana mmioana deleted the fix/refetch-token-balances-after-dust-success branch May 8, 2026 07:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants