Skip to content

Conversation

@joaquim-verges
Copy link
Member

@joaquim-verges joaquim-verges commented Aug 20, 2025


PR-Codex overview

This PR focuses on modifying date handling and analytics calculations in the wallets and highlights-card components to improve data accuracy and adjust the date range for analytics.

Detailed summary

  • Changed the default date range from "last-120" to "last-30" in index.tsx.
  • Updated todayDate to set it to the start of the next day in date-range-selector.tsx.
  • Enhanced date filtering logic in highlights-card.tsx to ensure consistency by using slice(0, 10) for date comparisons.

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

Summary by CodeRabbit

  • Bug Fixes
    • Corrected date range handling to make the end date inclusive by using the start of the next day.
    • Standardized date-only comparisons across analytics to align user and volume metrics, ensuring accurate daily counts and totals.
  • Improvements
    • Unified time-series date axis across datasets for clearer, consistent charts.
    • Default analytics window for In-App Wallets now shows the last 30 days (was 120), offering a more focused view by default.
    • Metrics now consistently reflect only completed transactions for volume and fees.

@vercel vercel bot temporarily deployed to Preview – nebula August 20, 2025 00:44 Inactive
@vercel vercel bot temporarily deployed to Preview – docs-v2 August 20, 2025 00:44 Inactive
@vercel
Copy link

vercel bot commented Aug 20, 2025

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

Project Deployment Preview Comments Updated (UTC)
thirdweb-www Ready Ready Preview Comment Aug 20, 2025 0:52am
4 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
docs-v2 Skipped Skipped Aug 20, 2025 0:52am
nebula Skipped Skipped Aug 20, 2025 0:52am
thirdweb_playground Skipped Skipped Aug 20, 2025 0:52am
wallet-ui Skipped Skipped Aug 20, 2025 0:52am

@vercel vercel bot temporarily deployed to Preview – wallet-ui August 20, 2025 00:44 Inactive
@vercel vercel bot temporarily deployed to Preview – thirdweb_playground August 20, 2025 00:44 Inactive
@changeset-bot
Copy link

changeset-bot bot commented Aug 20, 2025

⚠️ No Changeset found

Latest commit: 4223068

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

@github-actions github-actions bot added the Dashboard Involves changes to the Dashboard. label Aug 20, 2025
Copy link
Member Author


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.

@joaquim-verges joaquim-verges marked this pull request as ready for review August 20, 2025 00:45
@joaquim-verges joaquim-verges requested review from a team as code owners August 20, 2025 00:45
@codecov
Copy link

codecov bot commented Aug 20, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.54%. Comparing base (3126d87) to head (4223068).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #7885   +/-   ##
=======================================
  Coverage   56.54%   56.54%           
=======================================
  Files         904      904           
  Lines       58592    58592           
  Branches     4143     4143           
=======================================
  Hits        33131    33131           
  Misses      25355    25355           
  Partials      106      106           
Flag Coverage Δ
packages 56.54% <ø> (ø)
🚀 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.

@github-actions
Copy link
Contributor

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.06 KB (0%) 1.3 s (0%) 72 ms (+86.46% 🔺) 1.4 s
thirdweb (cjs) 357.05 KB (0%) 7.2 s (0%) 303 ms (+1.58% 🔺) 7.5 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 29 ms (+934.73% 🔺) 143 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 13 ms (+1594.42% 🔺) 23 ms
thirdweb/react (minimal + tree-shaking) 19.15 KB (0%) 383 ms (0%) 27 ms (+343.86% 🔺) 410 ms

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 20, 2025

Walkthrough

Adjusted date range end boundary to start of next day in date-range selector. Updated highlights card to aggregate time series by date-only keys across datasets and compute metrics per day with status filtering. Changed default analytics range for wallets chart from last-120 to last-30 days.

Changes

Cohort / File(s) Summary
Date Range Boundary Update
apps/dashboard/src/@/components/analytics/date-range-selector.tsx
End boundary now set to next day at 00:00; start computed relative to this end via subDays. No signature changes.
Time Series Date Union & Aggregation
apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.tsx
Unified date axis via YYYY-MM-DD keys from userStats and volumeStats; comparisons use date-only strings; added TimeSeriesMetrics; processTimeSeriesData aggregates activeUsers, newUsers, totalVolume, feesCollected per date with completed status for volume/fees.
Wallets Analytics Default Range
apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx
Default fallback range changed to last-30 (from last-120) when props.range is undefined; callpaths and rendering unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as Dashboard UI
  participant DRS as DateRangeSelector
  participant HC as Highlights Card
  participant WA as Wallets Analytics Chart

  User->>UI: Open analytics views
  UI->>DRS: Request default range
  DRS-->>UI: { from, to } (to = next day 00:00)
  UI->>HC: Fetch/process userStats, volumeStats with {from,to}
  HC->>HC: processTimeSeriesData()
  note right of HC: Build union of YYYY-MM-DD dates<br/>Aggregate metrics per date<br/>Filter volume by status=completed
  HC-->>UI: Time series metrics
  UI->>WA: Initialize chart range
  alt No explicit props.range
    WA->>WA: Use fallback "last-30"
  else Explicit range
    WA->>WA: Use provided range
  end
  WA-->>UI: Stats for rendering
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

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.
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch _Dashboard_Fix_date_handling_in_analytics_components

🪧 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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (4)
apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx (4)

31-38: Type mismatch prevents the new fallback from ever triggering; make range optional here

props.range is treated as optional (?? getLastNDaysRange("last-30")) but the type declares it as required via InAppWalletAnalyticsProps. This will cause TS errors upstream or render the fallback unreachable in strict code. Make range optional specifically on the async props type.

Apply this diff:

-type AsyncInAppWalletAnalyticsProps = Omit<
-  InAppWalletAnalyticsProps,
-  "stats" | "isPending"
-> & {
+type AsyncInAppWalletAnalyticsProps = Omit<
+  InAppWalletAnalyticsProps,
+  "stats" | "isPending" | "range"
+> & {
   teamId: string;
   projectId: string;
   authToken: string;
-};
+  range?: Range;
+};

17-29: Do not over-type UI props; avoid leaking unrelated async props into the UI component

InAppWalletAnalyticsUI doesn’t use interval or range, yet its props type requires them, and it’s invoked with {...props}, which includes unknown keys (teamId, projectId, authToken). This causes JSX prop type errors. Narrow the UI component’s props to what it actually consumes.

Apply this diff:

-type InAppWalletAnalyticsProps = {
-  interval: "day" | "week";
-  range: Range;
-  stats: InAppWalletStats[];
-  isPending: boolean;
-};
+type InAppWalletAnalyticsProps = {
+  interval: "day" | "week";
+  range: Range;
+  stats: InAppWalletStats[];
+  isPending: boolean;
+};
 
-function InAppWalletAnalyticsUI({
-  stats,
-  isPending,
-}: InAppWalletAnalyticsProps) {
+function InAppWalletAnalyticsUI({
+  stats,
+  isPending,
+}: {
+  stats: InAppWalletStats[];
+  isPending: boolean;
+}) {

Then, update the call sites (see next comments) to pass only stats and isPending.


59-66: Pass only the props the UI needs; remove spread of async props

Avoid spreading AsyncInAppWalletAnalyticsProps into the UI (props leakage and type errors). Pass only stats and isPending.

Apply this diff:

   return (
     <InAppWalletAnalyticsUI
-      {...props}
-      isPending={false}
-      range={range}
-      stats={stats}
+      isPending={false}
+      stats={stats}
     />
   );

73-75: Fix fallback props to match the narrowed UI prop type

The fallback should only pass stats and isPending now.

Apply this diff:

       fallback={
-        <InAppWalletAnalyticsUI {...props} isPending={true} stats={[]} />
+        <InAppWalletAnalyticsUI isPending={true} stats={[]} />
       }
🧹 Nitpick comments (6)
apps/dashboard/src/@/components/analytics/date-range-selector.tsx (2)

89-91: Compute “to” as start of next day using date-fns to avoid DST/locale pitfalls

Manually mutating Date with setDate/setHours can misbehave across DST transitions. Use date-fns helpers for clarity and correctness.

Apply this diff:

-  const todayDate = new Date();
-  todayDate.setDate(todayDate.getDate() + 1); // Move to next day
-  todayDate.setHours(0, 0, 0, 0); // Set to start of next day (00:00)
+  const todayDate = startOfDay(addDays(new Date(), 1)); // start of next day (local)

Outside the selected lines, update the import to include addDays and startOfDay:

import { differenceInCalendarDays, format, subDays, addDays, startOfDay } from "date-fns";

22-25: Preset detection should compare against start of next day (new “to” semantics)

Since getLastNDaysRange now sets to to next day 00:00, the preset matching logic should compare to that same reference instead of “today at 00:00”. Otherwise, custom ranges equivalent to a preset won’t be recognized as such.

Apply this diff:

-  const matchingRange =
-    normalizeTime(range.to).getTime() === normalizeTime(new Date()).getTime()
-      ? durationPresets.find((preset) => preset.days === daysDiff)
-      : undefined;
+  const matchingRange =
+    normalizeTime(range.to).getTime() === normalizeTime(addDays(new Date(), 1)).getTime()
+      ? durationPresets.find((preset) => preset.days === daysDiff)
+      : undefined;

Note: Ensure addDays is imported from date-fns (see previous comment). Please verify in the UI that selecting “Last 30 Days” (or similar) correctly highlights the preset rather than falling back to “custom”.

apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.tsx (4)

108-114: Stabilize ordering and avoid repeated date parsing by introducing a date key helper

  • The union of dates is currently unsorted; downstream logic like trendFn implicitly relies on chronological order.
  • You also parse and slice ISO strings repeatedly; introduce a small helper and reuse it.

Apply this diff:

-  const dates = [
-    ...new Set([
-      ...userStats.map((a) => new Date(a.date).toISOString().slice(0, 10)),
-      ...volumeStats.map((a) => new Date(a.date).toISOString().slice(0, 10)),
-    ]),
-  ];
+  const toDateKey = (d: string | Date) => new Date(d).toISOString().slice(0, 10);
+  const dates = Array.from(
+    new Set([
+      ...userStats.map((a) => toDateKey(a.date)),
+      ...volumeStats.map((a) => toDateKey(a.date)),
+    ]),
+  ).sort();

117-117: Deduplicate date normalization using the helper

Use the toDateKey helper for consistency and fewer object creations.

Apply this diff:

-    const activeUsers = userStats
-      .filter((u) => new Date(u.date).toISOString().slice(0, 10) === date)
+    const activeUsers = userStats
+      .filter((u) => toDateKey(u.date) === date)
       .reduce((acc, curr) => acc + curr.uniqueWalletsConnected, 0);

-    const newUsers = userStats
-      .filter((u) => new Date(u.date).toISOString().slice(0, 10) === date)
+    const newUsers = userStats
+      .filter((u) => toDateKey(u.date) === date)
       .reduce((acc, curr) => acc + curr.newUsers, 0);

-    const volume = volumeStats
-      .filter(
-        (v) =>
-          new Date(v.date).toISOString().slice(0, 10) === date &&
+    const volume = volumeStats
+      .filter(
+        (v) =>
+          toDateKey(v.date) === date &&
           v.status === "completed",
       )
       .reduce((acc, curr) => acc + curr.amountUsdCents / 100, 0);

-    const fees = volumeStats
-      .filter(
-        (v) =>
-          new Date(v.date).toISOString().slice(0, 10) === date &&
+    const fees = volumeStats
+      .filter(
+        (v) =>
+          toDateKey(v.date) === date &&
           v.status === "completed",
       )
       .reduce((acc, curr) => acc + curr.developerFeeUsdCents / 100, 0);

Also applies to: 121-121, 127-129, 135-137


85-91: Guard against divide-by-zero in trend calculation

If the first data point is 0, ((data[data.length - 2] / data[0]) - 1) yields Infinity. Return undefined (or 0) to avoid misleading UI.

Apply this diff:

-      trendFn={(data, key) =>
-        data.filter((d) => (d[key] as number) > 0).length >= 2
-          ? ((data[data.length - 2]?.[key] as number) ?? 0) /
-              ((data[0]?.[key] as number) ?? 0) -
-            1
-          : undefined
-      }
+      trendFn={(data, key) => {
+        const hasEnough = data.filter((d) => (d[key] as number) > 0).length >= 2;
+        if (!hasEnough) return undefined;
+        const numerator = (data[data.length - 2]?.[key] as number) ?? 0;
+        const denominator = (data[0]?.[key] as number) ?? 0;
+        if (denominator === 0) return undefined;
+        return numerator / denominator - 1;
+      }}

124-139: Optional: pre-index by date to drop repeated scans (O(n) instead of O(n·d))

You filter and reduce over userStats/volumeStats four times per date. Consider pre-grouping both arrays by dateKey once, then reading sums in O(1) per date. This will materially help when datasets grow.

If you want, I can provide a concise refactor using Maps to aggregate active/new users and volume/fees in one pass.

📜 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.

📥 Commits

Reviewing files that changed from the base of the PR and between 3126d87 and 4223068.

📒 Files selected for processing (3)
  • apps/dashboard/src/@/components/analytics/date-range-selector.tsx (1 hunks)
  • apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.tsx (1 hunks)
  • apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx (1 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)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx
  • apps/dashboard/src/@/components/analytics/date-range-selector.tsx
  • apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.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)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx
  • apps/dashboard/src/@/components/analytics/date-range-selector.tsx
  • apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.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)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx
  • apps/dashboard/src/@/components/analytics/date-range-selector.tsx
  • apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.tsx
🔇 Additional comments (3)
apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/wallets/analytics/chart/index.tsx (2)

43-43: LGTM: Narrowed default range to last-30

Defaulting to a shorter range improves load and relevance for most views.


45-57: Confirm exclusive upper-bound semantics for to

  • We normalize to via normalizedParamsnormalizeTime, then pass it straight through buildSearchParams into the v2/wallet/connects query.
  • getLastNDaysRange("last-30") (and any custom range.to) is set to the start of the next day.
  • If the backend treats to as inclusive, the final day’s data will be duplicated.

Please verify in the API contract whether to is meant as an exclusive upper bound and, if not, adjust either the client or server logic to prevent double-counting.

apps/dashboard/src/app/(app)/team/[team_slug]/[project_slug]/(sidebar)/overview/highlights-card.tsx (1)

108-114: Timezone confirmation

You normalize to UTC day keys via toISOString().slice(0, 10). This aligns with API timestamps if they are UTC-based. If product expectations are to show metrics in the viewer’s local timezone, this will shift counts on day boundaries.

Would you like a follow-up patch to toggle between UTC vs local-day grouping via a single strategy function?

@joaquim-verges joaquim-verges merged commit fd7e10d into main Aug 20, 2025
27 checks passed
@joaquim-verges joaquim-verges deleted the _Dashboard_Fix_date_handling_in_analytics_components branch August 20, 2025 00:59
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