Skip to content

Dashboard: Add fallback to native token balance on contract/split page when insight is not supported #7847

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

Conversation

MananTank
Copy link
Member

@MananTank MananTank commented Aug 12, 2025


PR-Codex overview

This PR focuses on improving the DistributeButton component and enhancing the ContractSplitPage by refining the handling of transaction counts and token balances, as well as updating the UI for better clarity and usability.

Detailed summary

  • In distribute-button.tsx, updated transactionCount logic to handle undefined values.
  • In useSplit.ts, added fallback logic for fetching wallet balance when token balance retrieval fails.
  • In ContractSplitPage.tsx, improved variable naming and UI structure for better readability.
  • Enhanced loading states with skeletons for token and recipient tables.
  • Updated error handling and empty state messages for balance queries.

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

Summary by CodeRabbit

  • Bug Fixes
    • Improved reliability of token balances by falling back to native wallet balance if token data fails to load.
  • Style
    • Refreshed Split page layout: simplified headers, refined spacing, and updated table containers.
    • Adjusted column widths for Tokens and Addresses for better readability.
    • Enhanced loading skeletons and preserved clear empty/error states.
  • Refactor
    • Unified recipients and balances to read from a single query object.
  • Chores
    • Button tweaks: small size on error; hide transaction count when only one transaction.

@vercel vercel bot temporarily deployed to Preview – docs-v2 August 12, 2025 22:46 Inactive
@vercel vercel bot temporarily deployed to Preview – thirdweb_playground August 12, 2025 22:46 Inactive
@vercel vercel bot temporarily deployed to Preview – nebula August 12, 2025 22:46 Inactive
Copy link

vercel bot commented Aug 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Project Deployment Preview Comments Updated (UTC)
thirdweb-www Ready Preview Comment Aug 12, 2025 11:48pm
4 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
docs-v2 ⬜️ Skipped Aug 12, 2025 11:48pm
nebula ⬜️ Skipped Aug 12, 2025 11:48pm
thirdweb_playground ⬜️ Skipped Aug 12, 2025 11:48pm
wallet-ui ⬜️ Skipped Aug 12, 2025 11:48pm

@vercel vercel bot temporarily deployed to Preview – wallet-ui August 12, 2025 22:46 Inactive
Copy link

changeset-bot bot commented Aug 12, 2025

⚠️ No Changeset found

Latest commit: 24e4802

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

Copy link
Contributor

coderabbitai bot commented Aug 12, 2025

Walkthrough

Adds a try/catch fallback in the split token-balance hook to return native balance on error; updates ContractSplitPage to consume full recipients query object and refactors balances/recipients UI/markup; adjusts DistributeButton sizing and transaction count behavior.

Changes

Cohort / File(s) Summary of Changes
Balance fetching fallback
apps/dashboard/src/@/hooks/useSplit.ts
Wraps getOwnedTokens call in tryCatch; on error fetches native balance via getWalletBalance and returns a single GetBalanceResult with NATIVE_TOKEN_ADDRESS and derived chainId. Adds imports and intermediate promise/result handling. No public API changes.
Split page UI and data access
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
Replaces destructured useReadContract data with the full query object (allRecipientsPercentagesQuery) and reads .data. Refactors Balances and Recipients sections: simplified headers, updated container/card styling, adjusted table column widths, skeletons, empty/error placement, spacing, and token/address cell classes. Active recipient/percentages now sourced from allRecipientsPercentagesQuery.data.
Distribute button behavior
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
Adds size="sm" to the error-state TransactionButton. Changes transactionCount prop to pass undefined when numTransactions === 1 so the count is hidden for a single transaction.

Sequence Diagram(s)

sequenceDiagram
  participant UI as ContractSplitPage
  participant Hook as useSplit / getTokenBalancesQuery
  participant TokenSvc as getOwnedTokens
  participant Wallet as getWalletBalance

  UI->>Hook: request token balances
  Hook->>TokenSvc: getOwnedTokens()
  alt token fetch succeeds
    TokenSvc-->>Hook: tokens[]
    Hook-->>UI: tokens[]
  else token fetch fails
    TokenSvc-->>Hook: error
    Hook->>Wallet: getWalletBalance()
    Wallet-->>Hook: nativeBalance
    Hook-->>UI: [GetBalanceResult(native token)]
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~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 24e4802 and 74d4074.

📒 Files selected for processing (3)
  • apps/dashboard/src/@/hooks/useSplit.ts (2 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx (2 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
  • apps/dashboard/src/@/hooks/useSplit.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
⏰ 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). (7)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch 08-13-dashboard_add_fallback_to_native_token_balance_on_contract_split_page_when_insight_is_not_supported

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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 the Dashboard Involves changes to the Dashboard. label Aug 12, 2025
@MananTank MananTank marked this pull request as ready for review August 12, 2025 22:46
@MananTank MananTank requested review from a team as code owners August 12, 2025 22:46
Copy link
Member Author

MananTank commented Aug 12, 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.

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

Copy link

codecov bot commented Aug 12, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.34%. Comparing base (a36c850) to head (74d4074).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7847   +/-   ##
=======================================
  Coverage   56.34%   56.34%           
=======================================
  Files         905      905           
  Lines       58834    58834           
  Branches     4150     4150           
=======================================
  Hits        33151    33151           
  Misses      25577    25577           
  Partials      106      106           
Flag Coverage Δ
packages 56.34% <ø> (ø)
🚀 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

github-actions bot commented Aug 12, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.06 KB (0%) 1.3 s (0%) 193 ms (+128.43% 🔺) 1.5 s
thirdweb (cjs) 357.05 KB (0%) 7.2 s (0%) 695 ms (+10.51% 🔺) 7.9 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 52 ms (+984.85% 🔺) 166 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 51 ms (+1617.5% 🔺) 61 ms
thirdweb/react (minimal + tree-shaking) 19.15 KB (0%) 383 ms (0%) 68 ms (+623.16% 🔺) 451 ms

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: 1

🔭 Outside diff range comments (3)
apps/dashboard/src/@/hooks/useSplit.ts (3)

101-106: Use tokenAddress to detect native token (name is unreliable)

The fallback uses walletBalance.name (e.g., “Ether”), so name === "Native Token" will misclassify the native balance path and call distributeByToken incorrectly. Compare tokenAddress to NATIVE_TOKEN_ADDRESS instead.

Apply this diff:

-          const transaction =
-            currency.name === "Native Token"
-              ? distribute({ contract })
-              : distributeByToken({
-                  contract,
-                  tokenAddress: currency.tokenAddress,
-                });
+          const transaction =
+            currency.tokenAddress === NATIVE_TOKEN_ADDRESS
+              ? distribute({ contract })
+              : distributeByToken({
+                  contract,
+                  tokenAddress: currency.tokenAddress,
+                });

97-121: Mutation resolves early; return the transaction promises

The map callback doesn’t return the promise, so Promise.all resolves immediately, marking the mutation done before transactions finish. Return the promise to ensure correct lifecycle and toasts timing.

Apply this diff:

-      const distributions = balances
-        .filter((token) => token.value !== 0n)
-        .map(async (currency) => {
+      const distributions = balances
+        .filter((token) => token.value !== 0n)
+        .map((currency) => {
           const transaction =
-            currency.name === "Native Token"
+            currency.tokenAddress === 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}`,
           });
+          return promise;
         });

124-125: Fix invalidateQueries usage with queryKey

invalidateQueries expects a queryKey/filter, not a full queryOptions object.

Apply this diff:

-      queryClient.invalidateQueries(getTokenBalancesQuery(params));
+      queryClient.invalidateQueries({
+        queryKey: getTokenBalancesQuery(params).queryKey,
+      });
🧹 Nitpick comments (6)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (3)

28-39: Simplify numTransactions logic (remove redundancy)

The early “Native Token” check and second zero-filter are redundant given validBalances is already filtered.

Apply this diff to simplify:

-  const numTransactions = useMemo(() => {
-    if (
-      validBalances.length === 1 &&
-      validBalances[0]?.name === "Native Token"
-    ) {
-      return 1;
-    }
-    if (!validBalances || balancesIsPending) {
-      return 0;
-    }
-    return validBalances?.filter((b) => b.value !== 0n).length;
-  }, [validBalances, balancesIsPending]);
+  const numTransactions = useMemo(() => {
+    if (balancesIsPending) {
+      return 0;
+    }
+    return validBalances.length;
+  }, [validBalances, balancesIsPending]);

14-26: Add explicit return type to component per guidelines

Declare a JSX return type for the component.

Apply this diff:

-export const DistributeButton = ({
+export const DistributeButton = ({
   contract,
   balances,
   balancesIsPending,
   balancesIsError,
   isLoggedIn,
 }: {
   contract: ThirdwebContract;
   balances: GetBalanceResult[];
   balancesIsPending: boolean;
   balancesIsError: boolean;
   isLoggedIn: boolean;
-}) => {
+}): JSX.Element => {

43-55: Type the helper function return

Annotate distributeFunds to return void for clarity.

Apply this diff:

-  const distributeFunds = () => {
+  const distributeFunds = (): void => {
apps/dashboard/src/@/hooks/useSplit.ts (2)

29-68: Set a sensible staleTime for balances to reduce refetch churn

Per guidelines, configure staleTime/cacheTime. Recommend staleTime ≥ 60s for balances.

Apply this diff:

   return queryOptions({
     queryFn: async () => {
       const ownedTokenBalancePromise = getOwnedTokens({
         client: params.client,
         chains: [params.chain],
         ownerAddress: params.ownerAddress,
         queryOptions: {
           include_native: "true",
         },
       });
       const result = await tryCatch(ownedTokenBalancePromise);
       // fallback to fetch native token balance with rpc
       if (result.error) {
         const walletBalance = await getWalletBalance({
           address: params.ownerAddress,
           client: params.client,
           chain: params.chain,
         });
         const nativeTokenBalance: GetBalanceResult = {
           name: walletBalance.name,
           value: walletBalance.value,
           decimals: walletBalance.decimals,
           displayValue: walletBalance.displayValue,
           symbol: walletBalance.symbol,
           chainId: params.chain.id,
           tokenAddress: NATIVE_TOKEN_ADDRESS,
         };
         return [nativeTokenBalance];
       }
       return result.data;
     },
     queryKey: ["getOwnedTokens", params.chain.id, params.ownerAddress],
     retry: false,
+    staleTime: 60_000,
   });

29-31: Optional: Add explicit generics to queryOptions for clearer typing

This clarifies the intended data shape.

Apply this diff:

-  return queryOptions({
+  return queryOptions<GetBalanceResult[]>({
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx (1)

23-29: Add explicit return type to component per guidelines

Declare the JSX return type on the page component.

Apply this diff:

-export function ContractSplitPage({
+export function ContractSplitPage({
   contract,
   isLoggedIn,
 }: {
   contract: ThirdwebContract;
   isLoggedIn: boolean;
-}) {
+}): JSX.Element {
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 59a8dad and 24e4802.

📒 Files selected for processing (3)
  • apps/dashboard/src/@/hooks/useSplit.ts (2 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx (2 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (2 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 @/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:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
  • apps/dashboard/src/@/hooks/useSplit.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.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/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
  • apps/dashboard/src/@/hooks/useSplit.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.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
Use NavLink for internal navigation with automatic active states in dashboard and playground apps
Use Tailwind CSS only – no inline styles or CSS modules
Use cn() from @/lib/utils for conditional class logic
Use design system tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components (Node edge): Start files with import "server-only";
Client Components (browser): Begin files with 'use client';
Always call getAuthToken() to retrieve JWT from cookies on server side
Use Authorization: Bearer header – never embed tokens in URLs
Return typed results (e.g., Project[], User[]) – avoid any
Wrap client-side data fetching calls in React Query (@tanstack/react-query)
Use descriptive, stable queryKeys for React Query 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

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
  • apps/dashboard/src/@/hooks/useSplit.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
🧠 Learnings (3)
📚 Learning: 2025-05-29T00:46:09.063Z
Learnt from: jnsdls
PR: thirdweb-dev/js#7188
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/accounts/components/accounts-count.tsx:15-15
Timestamp: 2025-05-29T00:46:09.063Z
Learning: In the accounts component at apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/accounts/components/accounts-count.tsx, the 3-column grid layout (md:grid-cols-3) is intentionally maintained even when rendering only one StatCard, as part of the design structure for this component.

Applied to files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
📚 Learning: 2025-07-18T19:20:32.530Z
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).

Applied to files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
📚 Learning: 2025-07-18T19:20:32.530Z
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/**/*.{tsx,jsx} : Prefer composable primitives over custom markup: `Button`, `Input`, `Select`, `Tabs`, `Card`, `Sidebar`, `Separator`, `Badge`.

Applied to files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx
⏰ 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). (7)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: Size
  • GitHub Check: Lint Packages
  • GitHub Check: Unit Tests
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (8)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/components/distribute-button.tsx (3)

64-64: Button sizing in error state aligns with UI updates

Adding size="sm" keeps the error-state TransactionButton visually consistent with the rest of the page.


91-91: Hide transactionCount when it equals 1

This improves UX by avoiding redundant “1 tx” labels while still showing the badge for multi-tx cases.


57-72: Potentially unreachable error branch due to parent gating

Parent only renders DistributeButton when balanceQuery.data?.length > 0, so this balancesIsError branch likely won’t render when the query errors (unless stale data exists). Confirm intended behavior.

If you want to always allow “Distribute” even when the balance query errors, consider moving the error-state button rendering into the parent alongside the error UI.

apps/dashboard/src/@/hooks/useSplit.ts (1)

31-64: Solid fallback to native balance when insights are unsupported

Wrapping getOwnedTokens with tryCatch and falling back to getWalletBalance provides resilience and keeps the UI usable on chains without Insight support.

apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx (4)

32-35: Good consolidation of recipients into a single query object

Using allRecipientsPercentagesQuery directly reduces state duplication and clarifies loading/error states.


42-44: Recipient detection is robust

Lowercasing both sides avoids checksum/format issues. LGTM.


137-147: Consider rendering DistributeButton even when balances query errors (if intended)

Currently, the button is only shown when data.length > 0, so the DistributeButton’s internal balancesIsError handling won’t surface. If you want to allow distribution attempts despite balance insight failures (given your new native fallback), loosen this gating.

If desired, I can propose a small layout tweak to always render the footer row and mount DistributeButton with error/pending states reflected by the query.


56-66: Table container and headers look consistent with design tokens

Use of bg-card, border, and responsive widths reads well and matches dashboard UI guidance.

Comment on lines +124 to +127
{balanceQuery.isError && (
<div className="text-red-500 px-4 flex justify-center items-center py-20 text-muted-foreground">
{balanceQuery.error.message}
</div>
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Conflicting text colors override error state

"text-red-500" is overridden by "text-muted-foreground" in the same className. Remove the muted class to ensure the error appears red.

Apply this diff:

-            <div className="text-red-500 px-4 flex justify-center items-center py-20 text-muted-foreground">
+            <div className="text-red-500 px-4 flex justify-center items-center py-20">
               {balanceQuery.error.message}
             </div>
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{balanceQuery.isError && (
<div className="text-red-500 px-4 flex justify-center items-center py-20 text-muted-foreground">
{balanceQuery.error.message}
</div>
{balanceQuery.isError && (
<div className="text-red-500 px-4 flex justify-center items-center py-20">
{balanceQuery.error.message}
</div>
🤖 Prompt for AI Agents
In
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/split/ContractSplitPage.tsx
around lines 124 to 127, the error div mixes "text-red-500" and
"text-muted-foreground" which conflicts and prevents the error text from
appearing red; remove "text-muted-foreground" from the className so the error
uses the red styling (leave the other layout classes intact).

Copy link
Contributor

graphite-app bot commented Aug 12, 2025

Merge activity

…e when insight is not supported (#7847)

<!--

## 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 handling of token balances and recipient percentages in the `ContractSplitPage` and related components, enhancing user experience and error handling.

### Detailed summary
- Updated `transactionCount` logic in `DistributeButton` to handle undefined cases.
- Added error handling for fetching token balances using `tryCatch`.
- Improved UI structure and styling in `ContractSplitPage`.
- Changed variable naming for clarity in `useReadContract`.
- Enhanced loading states for recipient percentages and balances.

> ✨ 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**
  * Improved reliability of token balances by falling back to native balance if token data fails to load.
* **Style**
  * Refreshed Split page layout: simplified headers, refined spacing, and updated table containers.
  * Adjusted column widths for Tokens and Addresses for better readability.
  * Enhanced loading skeletons and maintained clear empty/error states.
* **Refactor**
  * Streamlined data flow for recipients and balances to use a unified query object.
* **Chores**
  * Button tweaks: small size on error; hide transaction count when only one transaction.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
@graphite-app graphite-app bot force-pushed the 08-13-dashboard_add_fallback_to_native_token_balance_on_contract_split_page_when_insight_is_not_supported branch from 24e4802 to 74d4074 Compare August 12, 2025 23:41
@vercel vercel bot temporarily deployed to Preview – wallet-ui August 12, 2025 23:41 Inactive
@vercel vercel bot temporarily deployed to Preview – thirdweb_playground August 12, 2025 23:41 Inactive
@vercel vercel bot temporarily deployed to Preview – docs-v2 August 12, 2025 23:41 Inactive
@vercel vercel bot temporarily deployed to Preview – nebula August 12, 2025 23:41 Inactive
@graphite-app graphite-app bot merged commit 74d4074 into main Aug 12, 2025
24 checks passed
@graphite-app graphite-app bot deleted the 08-13-dashboard_add_fallback_to_native_token_balance_on_contract_split_page_when_insight_is_not_supported branch August 12, 2025 23:49
@vercel vercel bot temporarily deployed to Production – docs-v2 August 12, 2025 23:49 Inactive
@vercel vercel bot temporarily deployed to Production – thirdweb_playground August 12, 2025 23:49 Inactive
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