[BLD-143] Dashboard: Fix distribute funds in split contract#7907
Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
WalkthroughDetect native token by address and call the appropriate split contract method (distribute vs distributeByToken) per currency, await each distribution promise before resolving. Simplify the distribute button by removing toast error handling, renaming the mutation, and adding a native-token-specific transaction-count branch. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
participant U as User
participant B as DistributeButton
participant H as useSplit hook
participant SDK as thirdweb SDK
participant N as Network
U->>B: Click "Distribute"
B->>H: call distributeFundsMutation.mutateAsync()
activate H
loop per selected currency
alt currency.tokenAddress == NATIVE_TOKEN_ADDRESS
H->>SDK: distribute({ contract })
else
H->>SDK: distributeByToken({ contract, tokenAddress })
end
SDK->>N: submit tx
N-->>SDK: tx receipt
SDK-->>H: resolve
end
H-->>B: all distributions resolved
deactivate H
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Assessment against linked issues: Out-of-scope changes
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (1)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 💡 Knowledge Base configuration:
You can enable these sources in your CodeRabbit configuration. 📒 Files selected for processing (2)
🚧 Files skipped from review as they are similar to previous changes (2)
⏰ 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)
✨ Finishing Touches
🧪 Generate unit tests
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
How to use the Graphite Merge QueueAdd either label to this PR to merge it via the merge queue:
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. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #7907 +/- ##
=======================================
Coverage 56.53% 56.53%
=======================================
Files 904 904
Lines 58592 58592
Branches 4143 4143
=======================================
Hits 33126 33126
Misses 25360 25360
Partials 106 106
🚀 New features to boost your workflow:
|
size-limit report 📦
|
Merge activity
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
apps/dashboard/src/@/hooks/useSplit.ts (3)
98-127: Parallel map still runs all transactions concurrently; consider serializing to avoid wallet prompt contentionAdding
awaitinside themapcallback doesn’t serialize the operations; they still start concurrently and then all await. If you want one approval/signature at a time (smoother UX and fewer wallet-edge-case failures), iterate sequentially.Apply this diff to serialize transactions:
- const distributions = balances - .filter((token) => token.value !== 0n) - .map(async (currency) => { - const transaction = - getAddress(currency.tokenAddress) === - getAddress(NATIVE_TOKEN_ADDRESS) - ? distribute({ contract }) - : distributeByToken({ - contract, - tokenAddress: currency.tokenAddress, - }); - const promise = sendAndConfirmTransaction({ - account, - transaction, - }); - - toast.promise(promise, { - error: (err) => ({ - message: `Error distributing ${currency.name}`, - description: parseError(err), - }), - loading: `Distributing ${currency.name}`, - success: `Successfully distributed ${currency.name}`, - }); - - await promise; - }); - - return await Promise.all(distributions); + for (const currency of balances.filter((t) => t.value !== 0n)) { + const transaction = + getAddress(currency.tokenAddress) === getAddress(NATIVE_TOKEN_ADDRESS) + ? distribute({ contract }) + : distributeByToken({ contract, tokenAddress: currency.tokenAddress }); + + const txPromise = sendAndConfirmTransaction({ account, transaction }); + + toast.promise(txPromise, { + error: (err) => ({ + message: `Error distributing ${currency.name}`, + description: parseError(err), + }), + loading: `Distributing ${currency.name}`, + success: `Successfully distributed ${currency.name}`, + }); + + await txPromise; // ensure prompts execute one-by-one + }
128-131: Use React Query v5 invalidate signaturePassing the full query options object to
invalidateQueriesis non-idiomatic and can confuse types. Use{ queryKey }to avoid accidental breakage and to align with v5 API.Apply this diff:
- onSettled: () => { - queryClient.invalidateQueries(getTokenBalancesQuery(params)); - }, + onSettled: () => { + queryClient.invalidateQueries({ + queryKey: getTokenBalancesQuery(params).queryKey, + }); + },
93-97: Prefer ensureQueryData for typed cache + fetchYou can avoid the manual cache-or-fetch branching and get better typing by using
ensureQueryData.Apply this diff:
- const balances = - // get the cached data if it exists, otherwise fetch it - queryClient.getQueryData(getTokenBalancesQuery(params).queryKey) || - (await queryClient.fetchQuery(getTokenBalancesQuery(params))); + const balances = await queryClient.ensureQueryData( + getTokenBalancesQuery(params), + );apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (2)
28-33: Avoid name-based native detection; use address normalization to match hook logicRelying on
name === "Native Token"is brittle (localization/providers may differ). Align with the hook by comparing addresses.Apply this diff:
+import { getAddress, NATIVE_TOKEN_ADDRESS } from "thirdweb"; ... const numTransactions = useMemo(() => { if ( validBalances.length === 1 && - validBalances[0]?.name === "Native Token" + getAddress(validBalances[0]!.tokenAddress) === + getAddress(NATIVE_TOKEN_ADDRESS) ) { return 1; }Nit: since both native and ERC20 paths currently perform a single tx for a single balance, you could simplify to
return validBalances.length;unless you plan to show multi-step counts in the future.
42-44: Avoid unhandled rejections: use mutate() or await mutateAsync with try/catchCalling
mutateAsync()withoutawait/.catch()can surface unhandled promise rejections in dev tools. Prefermutate()for event handlers, or make the handlerasyncand handle errors.Apply one of these diffs (Option A recommended):
Option A – use mutate():
- const distributeFunds = () => { - distributeFundsMutation.mutateAsync(); - }; + const distributeFunds = () => { + distributeFundsMutation.mutate(); + };Option B – await with try/catch:
- const distributeFunds = () => { - distributeFundsMutation.mutateAsync(); - }; + const distributeFunds = async () => { + try { + await distributeFundsMutation.mutateAsync(); + } catch { + // handled by hook toasts / React Query error state + } + };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
💡 Knowledge Base configuration:
- MCP integration is disabled by default for public repositories
- Jira integration is disabled by default for public repositories
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (2)
apps/dashboard/src/@/hooks/useSplit.ts(4 hunks)apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx(3 hunks)
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{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@/typesor localtypes.tsbarrels
Prefer type aliases over interface except for nominal shapes
Avoidanyandunknownunless 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:
apps/dashboard/src/@/hooks/useSplit.tsapps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (CLAUDE.md)
Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)
Files:
apps/dashboard/src/@/hooks/useSplit.tsapps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
apps/{dashboard,playground-web}/**/*.{ts,tsx}
📄 CodeRabbit inference engine (CLAUDE.md)
apps/{dashboard,playground-web}/**/*.{ts,tsx}: Import UI primitives from@/components/ui/*(Button, Input, Select, Tabs, Card, Sidebar, Badge, Separator) in dashboard and playground apps
UseNavLinkfor internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Usecn()from@/lib/utilsfor conditional class logic
Use design system tokens (e.g.,bg-card,border-border,text-muted-foreground)
Server Components (Node edge): Start files withimport "server-only";
Client Components (browser): Begin files with'use client';
Always callgetAuthToken()to retrieve JWT from cookies on server side
UseAuthorization: Bearerheader – never embed tokens in URLs
Return typed results (e.g.,Project[],User[]) – avoidany
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stablequeryKeysfor React Query cache hits
ConfigurestaleTime/cacheTimein React Query based on freshness (default ≥ 60s)
Keep tokens secret via internal API routes or server actions
Never importposthog-jsin server components
Files:
apps/dashboard/src/@/hooks/useSplit.tsapps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
🧬 Code graph analysis (2)
apps/dashboard/src/@/hooks/useSplit.ts (1)
packages/thirdweb/src/exports/thirdweb.ts (1)
NATIVE_TOKEN_ADDRESS(31-31)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (1)
apps/dashboard/src/@/hooks/useSplit.ts (1)
useSplitDistributeFunds(79-132)
⏰ 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, vite)
- GitHub Check: E2E Tests (pnpm, webpack)
- GitHub Check: Lint Packages
- GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
apps/dashboard/src/@/hooks/useSplit.ts (2)
102-109: Good fix: address-normalized native token detectionSwitching from name checks to
getAddress(currency.tokenAddress) === getAddress(NATIVE_TOKEN_ADDRESS)is the right move and should prevent false negatives for POL/native across chains and providers.
1-11: Client-only usage confirmed – no changes neededI’ve verified that
useSplit.tsis only imported by modules that start with the"use client";directive:• apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
• apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/account/components/account-balance.tsx
• apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsxSince all consumers are already client components, the hook will never be imported by a server component. No changes are required.
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (2)
51-52: LGTM: pending state is correctly wired to the mutationUsing
distributeFundsMutation.isPendingfor the error state button is consistent with the main button below.
78-79: LGTM: consistent pending state on main actionThe
TransactionButtonreflects the mutation pending state appropriately.
<!--
## title your PR with this format: "[SDK/Dashboard/Portal] Feature/Fix: Concise title for the changes"
If you did not copy the branch name from Linear, paste the issue tag here (format is TEAM-0000):
## Notes for the reviewer
Anything important to call out? Be sure to also clarify these in your comments.
## How to test
Unit tests, playground, etc.
-->
<!-- start pr-codex -->
---
## PR-Codex overview
This PR focuses on improving the `useSplitDistributeFunds` hook and the `DistributeButton` component by refining the distribution logic and enhancing error handling.
### Detailed summary
- Replaced direct comparison of `currency.name` with a check using `getAddress(currency.tokenAddress)` against `getAddress(NATIVE_TOKEN_ADDRESS)`.
- Added `await` for the promise in the `useSplitDistributeFunds` function.
- Renamed the mutation variable in `DistributeButton` from `mutation` to `distributeFundsMutation`.
- Updated the `distributeFunds` function to use `distributeFundsMutation.mutateAsync()`.
- Adjusted the `isPending` prop in `TransactionButton` to reference `distributeFundsMutation.isPending`.
> ✨ Ask PR-Codex anything about this PR by commenting with `/codex {your question}`
<!-- end pr-codex -->
<!-- This is an auto-generated comment: release notes by coderabbit.ai -->
## Summary by CodeRabbit
- Bug Fixes
- Correctly detects and handles the native token during fund distribution, ensuring accurate routing and transaction counts.
- Ensures each distribution transaction completes before the next begins, reducing partial or overlapping operations.
- Refactor
- Streamlined distribution flow and loading state handling for a more consistent experience.
- Removed toast-based error pop-ups during distribution; status is reflected via the ongoing operation state.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
e69fa41 to
27f50a8
Compare

PR-Codex overview
This PR focuses on enhancing the
useSplitDistributeFundshook and its usage in theDistributeButtoncomponent. Key improvements include better address comparison and updated mutation handling for distributing funds.Detailed summary
useSplitDistributeFundsto usegetAddress(currency.tokenAddress).mutationtodistributeFundsMutationinDistributeButton.distributeFundsfunction to calldistributeFundsMutation.mutateAsync().isPendingprop inTransactionButtonto usedistributeFundsMutation.isPending.Summary by CodeRabbit
Bug Fixes
Refactor