Skip to content

Conversation

@alecananian
Copy link
Contributor

@alecananian alecananian commented Jul 31, 2025

Closes #7737

Test code used:

  const [from, setFrom] = useState(
    "0x83359747324E83eAAa596C7414D80365Bd75438A",
  );

  const { data: events = [] } = useContractEvents({
    contract: getContract({
      client: THIRDWEB_CLIENT,
      chain: baseSepolia,
      address: "0x036CbD53842c5426634e7929541eC2318f3dCF7e",
    }),
    events: [
      prepareEvent({
        signature:
          "event Transfer(address indexed from, address indexed to, uint256 value)",
        filters: {
          from,
        },
      }),
    ],
  });

  <button onClick={() => setFrom(ZERO_ADDRESS)}>Toggle From</button>

PR-Codex overview

This PR focuses on fixing the useContractEvents hook to ensure it correctly handles changes in filters by updating how event identifiers are generated.

Detailed summary

  • Updated the logic in useContractEvents to generate unique identifiers for events.
  • Changed the return statement to concatenate curr.hash with curr.topics.join(""), improving how identifiers are formed when filters change.

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

Summary by CodeRabbit

  • Bug Fixes
    • Resolved an issue where event data could persist from previous filters in contract event queries. Event data now accurately reflects the current filter criteria without mixing in stale results.

@alecananian alecananian requested review from a team as code owners July 31, 2025 03:24
@changeset-bot
Copy link

changeset-bot bot commented Jul 31, 2025

🦋 Changeset detected

Latest commit: 59fc826

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
thirdweb Patch
@thirdweb-dev/nebula Patch
@thirdweb-dev/wagmi-adapter Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@vercel
Copy link

vercel bot commented Jul 31, 2025

@alecananian is attempting to deploy a commit to the thirdweb Team on Vercel.

A member of the Team first needs to authorize it.

@graphite-app
Copy link
Contributor

graphite-app bot commented Jul 31, 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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 31, 2025

Walkthrough

A patch was applied to the useContractEvents hook in the "thirdweb" package. The modification updates the cache key generation logic to include both event hashes and their associated filter topics, ensuring that event data is correctly scoped to the current filter and does not persist stale data from previous filters.

Changes

Cohort / File(s) Change Summary
Contract Events Hook Logic
packages/thirdweb/src/react/core/hooks/contract/useContractEvents.ts
Updated the eventsKey memoization logic to concatenate each event's hash with its topics, ensuring cache keys are unique to the filter criteria.
Changelog
.changeset/witty-ducks-lie.md
Added a changeset entry describing the patch and its impact on the useContractEvents hook.

Sequence Diagram(s)

sequenceDiagram
  participant Component
  participant useContractEvents
  participant Cache

  Component->>useContractEvents: Provide event filters (hashes + topics)
  useContractEvents->>Cache: Generate cache key (hash + topics)
  Cache-->>useContractEvents: Return cached event data (if key matches)
  useContractEvents-->>Component: Return event data scoped to current filters
Loading

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Assessment against linked issues

Objective Addressed Explanation
Ensure useContractEvents cache key includes event filters (topics) to prevent persistence of old event data (#7737)

Assessment against linked issues: Out-of-scope changes

No out-of-scope changes found.

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 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 ed65f4c and 59fc826.

📒 Files selected for processing (2)
  • .changeset/witty-ducks-lie.md (1 hunks)
  • packages/thirdweb/src/react/core/hooks/contract/useContractEvents.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{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:

  • packages/thirdweb/src/react/core/hooks/contract/useContractEvents.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit Inference Engine (CLAUDE.md)

Load heavy dependencies inside async paths to keep initial bundle lean (lazy loading)

Files:

  • packages/thirdweb/src/react/core/hooks/contract/useContractEvents.ts
🧠 Learnings (3)
📓 Common learnings
Learnt from: MananTank
PR: thirdweb-dev/js#7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nft-drop-claim.tsx:82-90
Timestamp: 2025-06-13T13:03:41.732Z
Learning: The thirdweb `contract` object is serializable and can safely be used in contexts (e.g., React-Query keys) that require serializable values.
Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to packages/thirdweb/src/wallets/** : EIP-1193, EIP-5792, EIP-7702 standard support in wallet modules
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 : Anything that consumes hooks from `@tanstack/react-query` or thirdweb SDKs.
Learnt from: MananTank
PR: thirdweb-dev/js#7356
File: apps/nebula/src/app/not-found.tsx:1-1
Timestamp: 2025-06-17T18:30:52.976Z
Learning: In the thirdweb/js project, the React namespace is available for type annotations (like React.FC) without needing to explicitly import React. This is project-specific configuration that differs from typical TypeScript/React setups.
Learnt from: MananTank
PR: thirdweb-dev/js#7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:424-424
Timestamp: 2025-06-06T23:46:08.795Z
Learning: The thirdweb project has an ESLint rule that restricts direct usage of `defineChain`. When it's necessary to use `defineChain` directly, it's acceptable to disable the rule with `// eslint-disable-next-line no-restricted-syntax`.
.changeset/witty-ducks-lie.md (3)

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Surface breaking changes prominently in PR descriptions

Learnt from: MananTank
PR: #7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nft-drop-claim.tsx:82-90
Timestamp: 2025-06-13T13:03:41.732Z
Learning: The thirdweb contract object is serializable and can safely be used in contexts (e.g., React-Query keys) that require serializable values.

Learnt from: MananTank
PR: #7298
File: apps/dashboard/src/app/nebula-app/move-funds/move-funds.tsx:424-424
Timestamp: 2025-06-06T23:46:08.795Z
Learning: The thirdweb project has an ESLint rule that restricts direct usage of defineChain. When it's necessary to use defineChain directly, it's acceptable to disable the rule with // eslint-disable-next-line no-restricted-syntax.

packages/thirdweb/src/react/core/hooks/contract/useContractEvents.ts (8)

Learnt from: MananTank
PR: #7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nft-drop-claim.tsx:82-90
Timestamp: 2025-06-13T13:03:41.732Z
Learning: The thirdweb contract object is serializable and can safely be used in contexts (e.g., React-Query keys) that require serializable values.

Learnt from: MananTank
PR: #7332
File: apps/dashboard/src/app/(app)/(dashboard)/(chain)/[chain_id]/[contractAddress]/public-pages/nft/overview/nft-drop-claim.tsx:170-178
Timestamp: 2025-06-13T13:50:08.622Z
Learning: In event-tracking (useTrack) calls across the dashboard, the team intentionally keeps contractType generic as "NFTCollection" even for ERC-721 drops; contract differentiation is handled via the ercType field instead.

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to apps/{dashboard,playground-web}/**/*.{ts,tsx} : Use descriptive, stable queryKeys for React Query cache hits

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 : Keep queryKey stable and descriptive for cache hits.

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

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 : Analytics event name: human-readable <subject> <verb> (e.g., "contract deployed"); function: report<Subject><Verb> (PascalCase)

Learnt from: CR
PR: thirdweb-dev/js#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-18T19:19:55.613Z
Learning: Applies to src/extensions/** : Auto-generated contracts from ABI definitions in extensions

Learnt from: CR
PR: thirdweb-dev/js#0
File: .cursor/rules/dashboard.mdc:0-0
Timestamp: 2025-07-18T19:20:32.530Z
Learning: Event name: human-readable <subject> <verb> phrase (e.g. "contract deployed").

🔇 Additional comments (2)
packages/thirdweb/src/react/core/hooks/contract/useContractEvents.ts (1)

91-98: Excellent fix for the filter persistence issue!

The enhancement to include curr.topics.join("") in the eventsKey generation effectively resolves the core problem. By incorporating the encoded filter topics alongside the event hash, the cache key now becomes unique to both the event signature and its applied filters. This ensures that when filters change, a new query key is generated, preventing stale event data from persisting across different filter states.

The implementation is solid - the string concatenation approach provides stable cache key generation while maintaining backward compatibility with the existing hash-based structure.

.changeset/witty-ducks-lie.md (1)

1-6: Well-documented changeset entry.

The changeset accurately describes the bug fix and uses the appropriate patch version type for this non-breaking change. The description clearly communicates the issue that was resolved.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 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.
    • Explain this complex logic.
    • 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. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • 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 src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

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

Documentation and Community

  • 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 packages SDK Involves changes to the thirdweb SDK labels Jul 31, 2025
@codecov
Copy link

codecov bot commented Jul 31, 2025

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 36.34%. Comparing base (ed65f4c) to head (59fc826).
⚠️ Report is 5 commits behind head on main.

❗ There is a different number of reports uploaded between BASE (ed65f4c) and HEAD (59fc826). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (ed65f4c) HEAD (59fc826)
packages 2 1
Additional details and impacted files
@@             Coverage Diff             @@
##             main    #7766       +/-   ##
===========================================
- Coverage   56.42%   36.34%   -20.09%     
===========================================
  Files         904      897        -7     
  Lines       58674    58177      -497     
  Branches     4139     2312     -1827     
===========================================
- Hits        33108    21142    -11966     
- Misses      25461    36963    +11502     
+ Partials      105       72       -33     
Flag Coverage Δ
packages 36.34% <ø> (-20.09%) ⬇️
see 301 files with indirect coverage changes
🚀 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.

@joaquim-verges joaquim-verges merged commit 58787a2 into thirdweb-dev:main Jul 31, 2025
18 of 24 checks passed
@joaquim-verges joaquim-verges mentioned this pull request Jul 31, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

packages SDK Involves changes to the thirdweb SDK

Projects

None yet

Development

Successfully merging this pull request may close these issues.

useContractEvents hook persists old event data when event filter changes

2 participants