Skip to content

Conversation

@gregfromstl
Copy link
Contributor

@gregfromstl gregfromstl commented Sep 6, 2025

Summary

  • Updated all insight API queries to use block_timestamp instead of time for the group_by parameter
  • This change affects analytics data fetching in the contract dashboard

Changes

  • Updated group_by=time to group_by=block_timestamp in:
    • contract-event-breakdown.ts
    • contract-events.ts
    • contract-function-breakdown.ts
    • contract-transactions.ts
    • contract-wallet-analytics.ts

Test plan

  • Verify analytics charts still load correctly on contract dashboard
  • Check that time-based grouping works as expected
  • Confirm no errors in browser console

🤖 Generated with Claude Code


PR-Codex overview

This PR focuses on updating the query parameters in three utility files related to contract events in the dashboard application. The changes primarily involve renaming the chain parameter to chain_id and modifying the grouping criteria for data aggregation.

Detailed summary

  • In total-contract-events.ts, changed chain=${params.chainId} to chain_id=${params.chainId}.
  • In contract-events.ts, updated chain=${params.chainId} to chain_id=${params.chainId} and changed grouping from group_by=time to group_by=block_timestamp.
  • In contract-event-breakdown.ts, modified chain=${params.chainId} to chain_id=${params.chainId} and changed grouping from group_by=time to group_by=block_timestamp.

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

Summary by CodeRabbit

  • Bug Fixes
    • Improved accuracy of contract event analytics and breakdowns by aligning backend grouping to block timestamps, ensuring consistent daily totals across views.
  • Chores
    • Standardized API query shape for event analytics to reduce inconsistencies and improve reliability without changing public interfaces.

@gregfromstl gregfromstl requested review from a team as code owners September 6, 2025 22:13
@changeset-bot
Copy link

changeset-bot bot commented Sep 6, 2025

⚠️ No Changeset found

Latest commit: 75bd824

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 Sep 6, 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 Sep 6, 2025 10:44pm
4 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
docs-v2 Skipped Skipped Sep 6, 2025 10:44pm
nebula Skipped Skipped Sep 6, 2025 10:44pm
thirdweb_playground Skipped Skipped Sep 6, 2025 10:44pm
wallet-ui Skipped Skipped Sep 6, 2025 10:44pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 6, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Updated analytics utilities to rename the query parameter chainchain_id and to use group_by=block_timestamp instead of group_by=time while keeping daily aggregation via toStartOfDay(toDate(block_timestamp)) as time. No exported signatures, error handling, or post-processing changed.

Changes

Cohort / File(s) Summary of Changes
Analytics grouping & chain param updates
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts, apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
Query now uses chain_id=${params.chainId} and group_by=block_timestamp (was group_by=time); keeps aggregate=toStartOfDay(toDate(block_timestamp)) as time, other params, error handling, and post-processing unchanged.
Total contract events chain param rename
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/total-contract-events.ts
Renamed query parameter from chain to chain_id in the constructed request; remaining logic (endpoint, headers, error handling, JSON parsing, count extraction) unchanged.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant UI as Dashboard UI
  participant Util as Analytics Utils
  participant API as Analytics Backend

  UI->>Util: getContractEventBreakdown / getContractEventAnalytics(params)
  Note over Util: Build query with<br/>chain_id=${params.chainId}<br/>aggregate=toStartOfDay(toDate(block_timestamp)) as time<br/>group_by=block_timestamp
  Util->>API: HTTP GET /events?chain_id=...&group_by=block_timestamp&aggregate=...
  API-->>Util: Rows grouped by block_timestamp with aggregated fields
  Note over Util: Post-process rows into daily series using "time" alias
  Util-->>UI: Return per-day metrics
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/insight-group-by

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

@graphite-app
Copy link
Contributor

graphite-app bot commented Sep 6, 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.

@github-actions github-actions bot added the Dashboard Involves changes to the Dashboard. label Sep 6, 2025
@codecov
Copy link

codecov bot commented Sep 6, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 56.64%. Comparing base (f789e76) to head (75bd824).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #8000   +/-   ##
=======================================
  Coverage   56.64%   56.64%           
=======================================
  Files         904      904           
  Lines       58677    58677           
  Branches     4164     4164           
=======================================
  Hits        33236    33236           
  Misses      25335    25335           
  Partials      106      106           
Flag Coverage Δ
packages 56.64% <ø> (ø)
🚀 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

github-actions bot commented Sep 6, 2025

size-limit report 📦

Path Size Loading time (3g) Running time (snapdragon) Total time
thirdweb (esm) 64.01 KB (0%) 1.3 s (0%) 253 ms (+51.77% 🔺) 1.6 s
thirdweb (cjs) 357.32 KB (0%) 7.2 s (0%) 1.3 s (+1.96% 🔺) 8.5 s
thirdweb (minimal + tree-shaking) 5.73 KB (0%) 115 ms (0%) 83 ms (+736.3% 🔺) 198 ms
thirdweb/chains (tree-shaking) 526 B (0%) 11 ms (0%) 49 ms (+1443.17% 🔺) 59 ms
thirdweb/react (minimal + tree-shaking) 19.15 KB (0%) 383 ms (0%) 69 ms (+177.63% 🔺) 452 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: 2

🧹 Nitpick comments (2)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (1)

31-34: Prefer grouping by the day bucket to avoid cardinality blow-up

You aggregate to daily time but group by block_timestamp + event_signature, then re-aggregate on the client. Let the backend do the daily grouping to cut response size and CPU.

Apply:

-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",
     "group_by=topic_0 as event_signature",
     "aggregate=toStartOfDay(toDate(block_timestamp)) as time",

If expressions aren’t allowed in group_by, we can keep current params but remove the client-side summing by switching the first group_by back to the day bucket once supported.

apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-function-breakdown.ts (1)

31-34: Do daily grouping server-side for efficiency

Same pattern: grouping by block_timestamp + function_selector leads to unnecessary cardinality; group by the daily bucket instead.

Apply:

-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",
     "group_by=function_selector",
     "aggregate=toStartOfDay(toDate(block_timestamp)) as time",
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • 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 f789e76 and 56258ca.

📒 Files selected for processing (5)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-function-breakdown.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-transactions.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{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

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-transactions.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-function-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
**/*.{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]/analytics/utils/contract-transactions.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-function-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
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]/analytics/utils/contract-transactions.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-function-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
apps/{dashboard,playground}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/_ (e.g., Button, Input, Tabs, Card)
Use NavLink for internal navigation to get active state handling
Use Tailwind CSS for styling; no inline styles
Merge class names with cn() from @/lib/utils for conditional classes
Stick to design tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components must start with import "server-only"; use next/headers, server‑only env, heavy data fetching, and redirect() where appropriate
Client Components must start with 'use client'; handle interactivity with hooks and browser APIs
Server-side data fetching: call getAuthToken() from cookies, send Authorization: Bearer <token> header, and return typed results (avoid any)
Client-side data fetching: wrap calls in React Query with descriptive, stable queryKeys and set sensible staleTime/cacheTime (≥ 60s default); keep tokens secret via internal routes or server actions
Do not import posthog-js in server components (client-side only)

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-transactions.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-function-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
🧠 Learnings (1)
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/@/analytics/report.ts : Review `src/@/analytics/report.ts` before adding analytics events to check for duplicates

Applied to files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.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). (6)
  • GitHub Check: E2E Tests (pnpm, webpack)
  • GitHub Check: Size
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts (1)

35-35: I’ve initiated verification to confirm the existing grouping and inspect surrounding context. Once results are in, I’ll update the comment accordingly.

const queryParams = [
`chain=${params.chainId}`,
"group_by=time",
"group_by=block_timestamp",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Bug: per-block buckets returned instead of per-day totals

Same issue here—grouping on block_timestamp explodes cardinality and breaks the intended day series.

Apply:

-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",

🏁 Script executed:

#!/usr/bin/env bash
set -e

# Locate the contract-transactions utility file
file=$(fd --hidden --relative-path --glob 'contract-transactions.ts')
[ -n "$file" ] || { echo "File not found"; exit 1; }

# Print the first 200 lines to inspect the group_by usage
sed -n '1,200p' "$file"

Length of output: 2558


Group by day instead of block timestamp
Change in apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-transactions.ts line 35:

-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp))",
📝 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
"group_by=block_timestamp",
// …
"group_by=toStartOfDay(toDate(block_timestamp))",
// …
🤖 Prompt for AI Agents
In
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-transactions.ts
around line 35, the query currently uses "group_by=block_timestamp" but should
group by day; replace the parameter with "group_by=day" (and adjust any related
date-bucket parsing/formatting code if it assumes a block timestamp bucket) so
the analytics aggregate is performed per day instead of per block timestamp.

const queryParams = [
`chain=${params.chainId}`,
"group_by=time",
"group_by=block_timestamp",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Bug: unique wallets no longer aggregated by day

Grouping by block_timestamp returns distinct-counts per block, not per day, changing chart semantics and increasing payload size.

Apply:

-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",

🏁 Script executed:

#!/bin/bash
# Locate the analytics utility file
fd contract-wallet-analytics.ts

Length of output: 156


🏁 Script executed:

#!/bin/bash
sed -n '1,100p' 'apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts'

Length of output: 2235


Aggregate by day instead of per-block timestamps
Replace in apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts (line 35):

-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",

This ensures unique wallet counts are batched per day rather than per block (clickhouse.com).

📝 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
"group_by=block_timestamp",
"group_by=toStartOfDay(toDate(block_timestamp)) as time",
🤖 Prompt for AI Agents
In
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-wallet-analytics.ts
around line 35, change the grouping from per-block timestamps to daily buckets
by replacing "group_by=block_timestamp" with an expression that rounds
timestamps to the day (e.g. "group_by=toStartOfDay(block_timestamp)" or
"group_by=toDate(block_timestamp)" depending on downstream usage); ensure any
SELECT and GROUP BY use the same day-rounded expression so unique wallet counts
are aggregated per day rather than per block.

@vercel vercel bot temporarily deployed to Preview – docs-v2 September 6, 2025 22:26 Inactive
@vercel vercel bot temporarily deployed to Preview – thirdweb_playground September 6, 2025 22:26 Inactive
@vercel vercel bot temporarily deployed to Preview – nebula September 6, 2025 22:26 Inactive
@vercel vercel bot temporarily deployed to Preview – wallet-ui September 6, 2025 22:26 Inactive
Comment on lines +35 to 36
"group_by=block_timestamp",
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
Copy link
Contributor

Choose a reason for hiding this comment

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

The change from group_by=time to group_by=block_timestamp introduces a potential field naming inconsistency. While the grouping parameter now uses block_timestamp, the aggregation still creates a time alias with toStartOfDay(toDate(block_timestamp)) as time.

This mismatch between the grouping field and aggregation alias might cause issues if the backend expects consistent naming between these clauses. Consider either:

  1. Updating the aggregation to use a matching alias:

    "aggregate=toStartOfDay(toDate(block_timestamp)) as block_timestamp"
    
  2. Or documenting why this apparent inconsistency is intentional and safe in this context

This would ensure the query parameters maintain logical consistency and reduce the risk of unexpected behavior.

Suggested change
"group_by=block_timestamp",
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
"group_by=block_timestamp",
"aggregate=toStartOfDay(toDate(block_timestamp)) as block_timestamp",

Spotted by Diamond

Fix in Graphite


Is this helpful? React 👍 or 👎 to let us know.

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 (5)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (5)

29-35: Confirm cardinality impact of grouping by raw block_timestamp; prefer server-side day bucketing if supported

Grouping by block_timestamp can explode rows and shift daily bucketing to the client. If Insight supports grouping by the day boundary directly, switch to server-side daily grouping to reduce payload and CPU in the browser.

Apply if supported:

   const queryParams = [
     `chain=${params.chainId}`,
-    "group_by=block_timestamp",
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",
     "group_by=topic_0 as event_signature",
-    "aggregate=toStartOfDay(toDate(block_timestamp)) as time",
     "aggregate=count(*) as count",

If the API does not support grouping by computed expressions, keep your current approach and see the next comment to remove timezone ambiguity.


33-33: If grouping must remain on block_timestamp, return epoch for time to avoid timezone parsing issues

The current time comes back as a string; new Date(string) can be locale-dependent. Returning epoch seconds is safer.

-    "aggregate=toStartOfDay(toDate(block_timestamp)) as time",
+    "aggregate=toUnixTimestamp(toStartOfDay(toDate(block_timestamp))) as time",

100-103: Parse epoch seconds when present; falls back to ISO parsing

Pairs with the previous suggestion; keeps behavior correct either way.

-    values.push({
-      time: new Date(day),
-      ...value,
-    } as EventBreakdownEntry);
+    const ts = Number(day);
+    values.push({
+      time: Number.isFinite(ts) ? new Date(ts * 1000) : new Date(day),
+      ...value,
+    });

58-60: Guard against empty/missing aggregations to avoid runtime errors

Insight occasionally returns empty aggregations; this will throw on [0].

-  const json = (await res.json()) as InsightResponse;
-  const aggregations = Object.values(json.aggregations[0]);
+  const json = (await res.json()) as InsightResponse;
+  const aggObj = json?.aggregations?.[0] ?? {};
+  const aggregations = Object.values(aggObj);
+  if (Object.keys(aggObj).length === 0) {
+    return [];
+  }

107-109: Minor: avoid redundant Date construction

time is already a Date.

-  return values.sort((a, b) => {
-    return new Date(a.time).getTime() - new Date(b.time).getTime();
-  });
+  return values.sort((a, b) => a.time.getTime() - b.time.getTime());
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • 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 56258ca and 2512e5f.

📒 Files selected for processing (2)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{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

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
**/*.{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]/analytics/utils/contract-event-breakdown.ts
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]/analytics/utils/contract-event-breakdown.ts
apps/{dashboard,playground}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/_ (e.g., Button, Input, Tabs, Card)
Use NavLink for internal navigation to get active state handling
Use Tailwind CSS for styling; no inline styles
Merge class names with cn() from @/lib/utils for conditional classes
Stick to design tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components must start with import "server-only"; use next/headers, server‑only env, heavy data fetching, and redirect() where appropriate
Client Components must start with 'use client'; handle interactivity with hooks and browser APIs
Server-side data fetching: call getAuthToken() from cookies, send Authorization: Bearer <token> header, and return typed results (avoid any)
Client-side data fetching: wrap calls in React Query with descriptive, stable queryKeys and set sensible staleTime/cacheTime (≥ 60s default); keep tokens secret via internal routes or server actions
Do not import posthog-js in server components (client-side only)

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.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). (6)
  • GitHub Check: E2E Tests (pnpm, esbuild)
  • GitHub Check: E2E Tests (pnpm, vite)
  • GitHub Check: Size
  • GitHub Check: Unit Tests
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)

…ecated chain param

Updated all insight /v1/events endpoint calls to use chain_id parameter as chain is deprecated.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <[email protected]>
@vercel vercel bot temporarily deployed to Preview – thirdweb_playground September 6, 2025 22:35 Inactive
@vercel vercel bot temporarily deployed to Preview – nebula September 6, 2025 22:35 Inactive
@vercel vercel bot temporarily deployed to Preview – docs-v2 September 6, 2025 22:35 Inactive
@vercel vercel bot temporarily deployed to Preview – wallet-ui September 6, 2025 22:35 Inactive
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: 2

Caution

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

⚠️ Outside diff range comments (1)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (1)

36-40: Convert timestamp filters to milliseconds
getUnixTime() returns seconds, but the Insight events API expects milliseconds since the Unix epoch (UTC). Multiply by 1000 for both filter_block_timestamp_gte and filter_block_timestamp_lte.

? `filter_block_timestamp_gte=${getUnixTime(params.startDate) * 1000}`
: "",
params.endDate
? `filter_block_timestamp_lte=${getUnixTime(params.endDate) * 1000}`
: "",
♻️ Duplicate comments (1)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts (1)

35-37: Field/alias mismatch noted already; align group_by with returned alias.

Prior feedback flagged the inconsistency between group_by=block_timestamp and as time. The fix above resolves both the naming mismatch and the grouping granularity.

🧹 Nitpick comments (3)
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/total-contract-events.ts (1)

23-25: LGTM on chain_id switch; consider normalizing count expression.

The param rename looks correct. For consistency with other files (one uses count(*), another count(block_timestamp)), consider count() to avoid null-sensitivity and keep queries uniform.

-  "aggregate=count(block_number) as total",
+  "aggregate=count() as total",
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts (1)

66-79: Tighten runtime type narrowing with a type guard to satisfy TS and avoid casts.

Current "in" checks still leave value typed as object, so property access may trip strict TS configs. Add a type predicate and use it.

+function isTimeCountEntry(v: unknown): v is { time: string; count: number } {
+  return (
+    typeof v === "object" &&
+    v !== null &&
+    typeof (v as any).time === "string" &&
+    typeof (v as any).count === "number"
+  );
+}
   for (const value of aggregations) {
-    if (
-      typeof value === "object" &&
-      value !== null &&
-      "time" in value &&
-      "count" in value &&
-      typeof value.time === "string" &&
-      typeof value.count === "number"
-    ) {
+    if (isTimeCountEntry(value)) {
       values.push({
-        count: value.count,
-        time: new Date(value.time),
+        count: value.count,
+        time: new Date(value.time),
       });
     }
   }
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (1)

61-79: Strengthen type narrowing with a predicate for aggregation rows.

Avoid accessing properties on a generic object. This keeps strict TS happy and documents the wire shape.

+function isAggregationEntry(v: unknown): v is InsightAggregationEntry {
+  return (
+    typeof v === "object" &&
+    v !== null &&
+    typeof (v as any).event_signature === "string" &&
+    typeof (v as any).time === "string" &&
+    typeof (v as any).count === "number"
+  );
+}
   const collectedAggregations: InsightAggregationEntry[] = [];
   for (const value of aggregations) {
-    if (
-      typeof value === "object" &&
-      value !== null &&
-      "time" in value &&
-      "count" in value &&
-      "event_signature" in value &&
-      typeof value.event_signature === "string" &&
-      typeof value.time === "string" &&
-      typeof value.count === "number"
-    ) {
-      collectedAggregations.push({
-        count: value.count,
-        event_signature: value.event_signature,
-        time: value.time,
-      });
-    }
+    if (isAggregationEntry(value)) {
+      collectedAggregations.push({
+        count: value.count,
+        event_signature: value.event_signature,
+        time: value.time,
+      });
+    }
   }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • 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 2512e5f and 75bd824.

📒 Files selected for processing (3)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts (1 hunks)
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/total-contract-events.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{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

**/*.{ts,tsx}: Use explicit function declarations and explicit return types in TypeScript
Limit each file to one stateless, single‑responsibility function
Re‑use shared types from @/types where applicable
Prefer type aliases over interface except for nominal shapes
Avoid any and unknown unless unavoidable; narrow generics when possible
Prefer composition over inheritance; use utility types (Partial, Pick, etc.)
Lazy‑import optional features and avoid top‑level side‑effects to reduce bundle size

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/total-contract-events.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
**/*.{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]/analytics/utils/total-contract-events.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
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]/analytics/utils/total-contract-events.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
apps/{dashboard,playground}/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

apps/{dashboard,playground}/**/*.{ts,tsx}: Import UI primitives from @/components/ui/_ (e.g., Button, Input, Tabs, Card)
Use NavLink for internal navigation to get active state handling
Use Tailwind CSS for styling; no inline styles
Merge class names with cn() from @/lib/utils for conditional classes
Stick to design tokens (e.g., bg-card, border-border, text-muted-foreground)
Server Components must start with import "server-only"; use next/headers, server‑only env, heavy data fetching, and redirect() where appropriate
Client Components must start with 'use client'; handle interactivity with hooks and browser APIs
Server-side data fetching: call getAuthToken() from cookies, send Authorization: Bearer <token> header, and return typed results (avoid any)
Client-side data fetching: wrap calls in React Query with descriptive, stable queryKeys and set sensible staleTime/cacheTime (≥ 60s default); keep tokens secret via internal routes or server actions
Do not import posthog-js in server components (client-side only)

Files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/total-contract-events.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
🧠 Learnings (1)
📚 Learning: 2025-07-18T19:19:55.613Z
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/@/analytics/report.ts : Review `src/@/analytics/report.ts` before adding analytics events to check for duplicates

Applied to files:

  • apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.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). (3)
  • GitHub Check: Size
  • GitHub Check: Lint Packages
  • GitHub Check: Analyze (javascript)

Comment on lines +30 to 34
`chain_id=${params.chainId}`,
"group_by=block_timestamp",
"group_by=topic_0 as event_signature",
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
"aggregate=count(*) as count",
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Same grouping issue: per-day breakdown should group by the day expression, not raw block_timestamp.

Group by the day bucket (aliased time) alongside event_signature, and remove the separate aggregate for time.

-    `chain_id=${params.chainId}`,
-    "group_by=block_timestamp",
-    "group_by=topic_0 as event_signature",
-    "aggregate=toStartOfDay(toDate(block_timestamp)) as time",
+    `chain_id=${params.chainId}`,
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",
+    "group_by=topic_0 as event_signature",

Optionally normalize count:

-    "aggregate=count(*) as count",
+    "aggregate=count() as count",
📝 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
`chain_id=${params.chainId}`,
"group_by=block_timestamp",
"group_by=topic_0 as event_signature",
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
"aggregate=count(*) as count",
`chain_id=${params.chainId}`,
"group_by=toStartOfDay(toDate(block_timestamp)) as time",
"group_by=topic_0 as event_signature",
"aggregate=count() as count",
🤖 Prompt for AI Agents
In
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-event-breakdown.ts
around lines 30 to 34, the query groups by raw block_timestamp instead of the
day bucket; change grouping to use the day expression
(toStartOfDay(toDate(block_timestamp)) as time) and group_by that alias plus
topic_0 as event_signature, remove the separate aggregate entry that defines
time, and keep aggregate=count(*) as count (or optionally normalize count
afterwards).

Comment on lines +34 to 36
`chain_id=${params.chainId}`,
"group_by=block_timestamp",
"aggregate=toStartOfDay(toDate(block_timestamp)) as time",
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Daily buckets will fragment: grouping by raw block_timestamp yields per-block groups.

If the intent is daily aggregation, group_by=block_timestamp creates one group per block, not per day. Group by the day expression (aliased as time) and drop the redundant aggregate for time.

-    `chain_id=${params.chainId}`,
-    "group_by=block_timestamp",
-    "aggregate=toStartOfDay(toDate(block_timestamp)) as time",
+    `chain_id=${params.chainId}`,
+    "group_by=toStartOfDay(toDate(block_timestamp)) as time",

Optionally normalize count:

-    "aggregate=count(block_timestamp) as count",
+    "aggregate=count() as count",

🌐 Web query:

Does the Insight API support grouping by an aliased expression in the `group_by` param (e.g., `group_by=toStartOfDay(toDate(block_timestamp)) as time`), and should time filters use epoch seconds?

💡 Result:

Short answer: No — the group_by parameter must reference an existing field/alias (or the API's documented filter_alias), not an arbitrary SQL expression with an inline alias. And time filters depend on the provider: some Insight APIs (e.g. Dune) expect date/time strings (use timestamp/date strings in filters), while others (e.g. AWS X‑Ray Insights) require Unix epoch seconds — check the specific API docs. [1][2]

Sources:

  • Dune API — filtering / result parameters (dates used as strings; group/filter operate on columns). [1]
  • AWS X‑Ray GetInsightImpactGraph — start/end times in Unix time seconds. [2]

Group by existing alias, not inline SQL
Insight API only accepts columns or documented aliases in group_by. To bucket by day, keep aggregate=toStartOfDay(toDate(block_timestamp)) as time and change "group_by=block_timestamp" to "group_by=time" (or use the provider’s filter_alias for daily grouping). Optionally normalize counts: use aggregate=count() as count.
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts:34-36

🤖 Prompt for AI Agents
In
apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/analytics/utils/contract-events.ts
around lines 34-36, the query uses an inline expression in group_by which the
Insight API rejects; keep the aggregate alias
aggregate=toStartOfDay(toDate(block_timestamp)) as time and replace
"group_by=block_timestamp" with "group_by=time" (or the provider’s daily
filter_alias), and optionally change/augment aggregates to include a normalized
count like aggregate=count() as count if you need per-day counts.

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.

3 participants