Skip to content

Conversation

premiumjibles
Copy link
Collaborator

@premiumjibles premiumjibles commented Sep 1, 2025

Description

Adds mixpanel tracking to quick buy, mimicking the same patterns we use for the swapper tracking.

Note: Since quick buy is utilising the regular swap mechanisms under the hood. We do also get regular swap events for quick buys on top of these new events. I think that's probably fine as quick buys will be included in trade analysis. We just need to take note not to try and add quick buy events to regular swap events as we'd be doubling up.

To make this other tracking not happen, i'd need to add some state in redux to track whether we're doing a quick buy. Which is a bit hacky but possilble if we think it's necessary.

Issue (if applicable)

closes #10378

Risk

Low risk, just adds mixpanel tracking

High Risk PRs Require 2 approvals

What protocols, transaction types, wallets or contract interactions might be affected by this PR?

Testing

  • If you have access to mixpanel, perform a quick buy and check for quick buy events. Events are Quick Buy Preview, Quick Buy Confirm, Quick Buy Success and Quick Buy Failed

Engineering

Operations

  • 🏁 My feature is behind a flag and doesn't require operations testing (yet)

Screenshots (if applicable)

https://jam.dev/c/1981d426-c3fb-4097-bd4d-5ed082e85175 - This is with a console log right before mixpanel.track

Summary by CodeRabbit

  • Chores
    • Added comprehensive analytics tracking for the Quick Buy flow (preview, confirm, success, failure) to improve telemetry and diagnostics.
    • Captures contextual details like assets, networks, and amounts (including user currency) for more accurate insights and timing.
    • No changes to the interface, behavior, or permissions; the Quick Buy experience remains unchanged for users.
    • Prepares the app for future improvements based on aggregated usage data.

@premiumjibles premiumjibles requested a review from a team as a code owner September 1, 2025 22:29
Copy link
Contributor

coderabbitai bot commented Sep 1, 2025

📝 Walkthrough

Walkthrough

Adds Mixpanel instrumentation for the Quick Buy flow. Introduces new MixPanelEvent enum members and integrates event tracking in QuickBuy component actions and useQuickBuy hook states. Updates useMixpanel hook signature to support optional event data, and adjusts callers to pass a flag.

Changes

Cohort / File(s) Summary
Quick Buy UI integration
src/components/AssetHeader/QuickBuy.tsx
Tracks Mixpanel events on quick-buy preview and confirm; wires useMixpanel(true); updates handlers’ dependency arrays.
Quick Buy state hooks
src/components/AssetHeader/hooks/useQuickBuy.ts
Emits Mixpanel events on purchase success and failure; updates setState callbacks to include tracker in deps.
Analytics event types
src/lib/mixpanel/types.ts
Adds MixPanelEvent members: QuickBuyPreview, QuickBuyConfirm, QuickBuySuccess, QuickBuyFailed.
Mixpanel hook behavior
src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
Changes signature to useMixpanel(allowUndefinedEventData = false); computes event data at call time; supports optional eventData and early returns if unavailable.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant QB as QuickBuy (UI)
  participant UQB as useQuickBuy (hook)
  participant MP as Mixpanel
  participant PS as Purchase Service

  U->>QB: Tap amount
  QB->>MP: Track QuickBuyPreview
  QB->>UQB: startPurchase(amount)

  U->>QB: Confirm purchase
  QB->>MP: Track QuickBuyConfirm
  QB->>UQB: confirmPurchase()

  UQB->>PS: Execute purchase
  alt Success
    UQB->>MP: Track QuickBuySuccess
    UQB-->>QB: success state
  else Failure
    UQB->>MP: Track QuickBuyFailed
    UQB-->>QB: error state
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Add Mixpanel event tracking for Quick Buy [#10378]

Suggested reviewers

  • gomesalexandre
  • NeOMakinG

Poem

I tapped my paw for “Quick Buy” delight,
Beep went the stats in Mixpanel’s light.
Preview, Confirm—carrots in queue,
Success? I thump! If fail, I rue.
Data trails hop, left and right—
A rabbit’s trade, tracked just right. 🥕✨

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

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.
    • 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 or @coderabbit 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.

@premiumjibles premiumjibles marked this pull request as draft September 1, 2025 22:30
@premiumjibles premiumjibles force-pushed the 10378_mixpanel_quickbuy branch 3 times, most recently from 76c8610 to 2eae853 Compare September 1, 2025 22:42
@premiumjibles premiumjibles force-pushed the 10378_mixpanel_quickbuy branch from 2eae853 to 672b476 Compare September 1, 2025 22:50
@premiumjibles premiumjibles marked this pull request as ready for review September 1, 2025 22:51
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 (8)
src/components/AssetHeader/QuickBuy.tsx (2)

117-121: Replace inline onClick with a memoized handler; drop the eslint-disable.
Keeps to our hooks guidelines and avoids suppressing lint.

Apply:

@@
-                    // eslint-disable-next-line react-memo/require-usememo
-                    onClick={() => {
-                      trackMixpanelEvent(MixPanelEvent.QuickBuyPreview)
-                      startPurchase(amount)
-                    }}
+                    onClick={makeHandleQuickBuyAmountClick(amount)}

And add a memoized factory near the other handlers (after Line 72):

@@
   const trackMixpanelEvent = useMixpanel(true)
 
+  const makeHandleQuickBuyAmountClick = useCallback(
+    (selectedAmount: number): (() => void) => () => {
+      trackMixpanelEvent(MixPanelEvent.QuickBuyPreview)
+      startPurchase(selectedAmount)
+    },
+    [trackMixpanelEvent, startPurchase],
+  )

118-121: Alternative: centralize Preview tracking in the hook.
If you prefer keeping all Quick Buy analytics in useQuickBuy, move the Preview event into startPurchase and remove it here. This reduces the chance of missing instrumentation from other call sites.

Proposed changes in this file:

-                    onClick={() => {
-                      trackMixpanelEvent(MixPanelEvent.QuickBuyPreview)
-                      startPurchase(amount)
-                    }}
+                    onClick={() => startPurchase(amount)}

(See paired suggestion in useQuickBuy.ts to emit QuickBuyPreview inside startPurchase.)

src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx (1)

7-21: Add an explicit return type to the hook.
Matches our TS guidelines and clarifies the API surface.

-export const useMixpanel = (allowUndefinedEventData = false) => {
+export const useMixpanel = (allowUndefinedEventData = false): ((event: MixPanelEvent) => void) => {
   const mixpanel = useMemo(() => getMixPanel(), [])
   const trackMixpanelEvent = useCallback(
     (event: MixPanelEvent) => {
       // mixpanel is undefined when the feature is disabled
       if (!mixpanel) return
src/components/AssetHeader/hooks/useQuickBuy.ts (5)

8-11: Shared analytics dependency usage is fine; consider relocating hook to a shared path.
useMixpanel lives under MultiHopTrade but is now used by Quick Buy; moving it to a shared analytics folder would better reflect reuse.


149-149: Require event data for Success/Failed; keep “allow undefined” only where necessary.
For reliability, use the default useMixpanel() here so Success/Failed aren’t emitted without event payloads. Keep true in UI where Preview/Confirm may lack data.

-  const trackMixpanelEvent = useMixpanel(true)
+  const trackMixpanelEvent = useMixpanel()

151-158: Add explicit return type.
Aligns with our TS rule to annotate function returns.

-  const setErrorState = useCallback(
-    (messageKey: string, amount: number) => {
+  const setErrorState = useCallback(
+    (messageKey: string, amount: number): void => {
       trackMixpanelEvent(MixPanelEvent.QuickBuyFailed)
       setQuickBuyState({ status: 'error', amount, messageKey })
       resetTrade()
     },
     [resetTrade, trackMixpanelEvent],
   )

160-174: Add explicit return type.
Same reasoning as above.

-  const setSuccessState = useCallback(
-    (amount: number) => {
+  const setSuccessState = useCallback(
+    (amount: number): void => {
       trackMixpanelEvent(MixPanelEvent.QuickBuySuccess)
       setQuickBuyState({ status: 'success', amount })
       resetTrade()
 
       clearSuccessTimer()
       successTimerRef.current = setTimeout(() => {
         setQuickBuyState(currentState =>
           currentState.status === 'success' ? DEFAULT_STATE : currentState,
         )
       }, SUCCESS_TIMEOUT_MS)
     },
     [resetTrade, clearSuccessTimer, trackMixpanelEvent],
   )

176-193: (If centralizing) Emit Preview inside startPurchase.
Keeps all Quick Buy analytics in one place. Pair with removal from the component as suggested there.

   const startPurchase = useCallback(
     (amount: number) => {
       if (!asset || !feeAsset || !feeAssetMarketData) return
+      trackMixpanelEvent(MixPanelEvent.QuickBuyPreview)
 
       const estimatedSellAmountCryptoPrecision = bn(amount)
         .dividedBy(bn(feeAssetMarketData.price))
         .toString()
📜 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 aa5ef16 and 672b476.

📒 Files selected for processing (4)
  • src/components/AssetHeader/QuickBuy.tsx (3 hunks)
  • src/components/AssetHeader/hooks/useQuickBuy.ts (3 hunks)
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx (1 hunks)
  • src/lib/mixpanel/types.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/lib/mixpanel/types.ts
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{ts,tsx}: ALWAYS use Result<T, E> pattern for error handling in swappers and APIs
ALWAYS use Ok() and Err() from @sniptt/monads for monadic error handling
ALWAYS use custom error classes from @shapeshiftoss/errors
ALWAYS provide meaningful error codes for internationalization
ALWAYS include relevant details in error objects
ALWAYS wrap async operations in try-catch blocks
ALWAYS use AsyncResultOf utility for converting promises to Results
ALWAYS provide fallback error handling
ALWAYS use timeoutMonadic for API calls
ALWAYS provide appropriate timeout values for API calls
ALWAYS handle timeout errors gracefully
ALWAYS validate inputs before processing
ALWAYS provide clear validation error messages
ALWAYS use early returns for validation failures
ALWAYS log errors for debugging
ALWAYS use structured logging for errors
ALWAYS include relevant context in error logs
Throwing errors instead of using monadic patterns is an anti-pattern
Missing try-catch blocks for async operations is an anti-pattern
Generic error messages without context are an anti-pattern
Not handling specific error types is an anti-pattern
Missing timeout handling is an anti-pattern
No input validation is an anti-pattern
Poor error logging is an anti-pattern
Using any for error types is an anti-pattern
Missing error codes for internationalization is an anti-pattern
No fallback error handling is an anti-pattern
Console.error without structured logging is an anti-pattern

**/*.{ts,tsx}: ALWAYS use camelCase for variables, functions, and methods
ALWAYS use descriptive names that explain the purpose for variables and functions
ALWAYS use verb prefixes for functions that perform actions
ALWAYS use PascalCase for types, interfaces, and enums
ALWAYS use descriptive names that indicate the structure for types, interfaces, and enums
ALWAYS use suffixes like Props, State, Config, Type when appropriate for types and interfaces
ALWAYS use UPPER_SNAKE_CASE for constants and configuration values
ALWAYS use d...

Files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
  • src/components/AssetHeader/hooks/useQuickBuy.ts
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.tsx: ALWAYS wrap components in error boundaries
ALWAYS provide user-friendly fallback components in error boundaries
ALWAYS log errors for debugging in error boundaries
ALWAYS use useErrorToast hook for displaying errors
ALWAYS provide translated error messages in error toasts
ALWAYS handle different error types appropriately in error toasts
Missing error boundaries in React components is an anti-pattern

**/*.tsx: ALWAYS use PascalCase for React component names
ALWAYS use descriptive names that indicate the component's purpose
ALWAYS match the component name to the file name
Flag components without PascalCase
Flag default exports for components

Files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
**/*

📄 CodeRabbit inference engine (.cursor/rules/naming-conventions.mdc)

**/*: ALWAYS use appropriate file extensions
Flag files without kebab-case

Files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
  • src/components/AssetHeader/hooks/useQuickBuy.ts
**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/react-best-practices.mdc)

**/*.{tsx,jsx}: ALWAYS use useMemo for expensive computations, object/array creations, and filtered data
ALWAYS use useMemo for derived values and computed properties
ALWAYS use useMemo for conditional values and simple transformations
ALWAYS use useCallback for event handlers and functions passed as props
ALWAYS use useCallback for any function that could be passed as a prop or dependency
ALWAYS include all dependencies in useEffect, useMemo, useCallback dependency arrays
NEVER use // eslint-disable-next-line react-hooks/exhaustive-deps unless absolutely necessary
ALWAYS explain why dependencies are excluded if using eslint disable
ALWAYS use named exports for components
NEVER use default exports for components
KEEP component files under 200 lines when possible
BREAK DOWN large components into smaller, reusable pieces
EXTRACT complex logic into custom hooks
USE local state for component-level state
LIFT state up when needed across multiple components
USE Context for avoiding prop drilling
ALWAYS wrap components in error boundaries for production
ALWAYS handle async errors properly
ALWAYS provide user-friendly error messages
ALWAYS use virtualization for lists with 100+ items
ALWAYS implement proper key props for list items
ALWAYS lazy load heavy components
ALWAYS use React.lazy for code splitting
Components receiving props are wrapped with memo

Files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/react-best-practices.mdc)

USE Redux only for global state shared across multiple places

Files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
  • src/components/AssetHeader/hooks/useQuickBuy.ts
**/use*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/naming-conventions.mdc)

**/use*.{ts,tsx}: ALWAYS use use prefix for custom hooks
ALWAYS use descriptive names that indicate the hook's purpose
ALWAYS use camelCase after the use prefix for custom hooks

Files:

  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
  • src/components/AssetHeader/hooks/useQuickBuy.ts
🧠 Learnings (3)
📚 Learning: 2025-07-29T15:04:28.083Z
Learnt from: NeOMakinG
PR: shapeshift/web#10139
File: src/components/MultiHopTrade/components/TradeConfirm/components/ExpandableStepperSteps.tsx:109-115
Timestamp: 2025-07-29T15:04:28.083Z
Learning: In src/components/MultiHopTrade/components/TradeConfirm/components/ExpandableStepperSteps.tsx, the component is used under an umbrella that 100% of the time contains the quote, making the type assertion `activeTradeQuote?.steps[currentHopIndex] as TradeQuoteStep` safe. Adding conditional returns before hooks would violate React's Rules of Hooks.

Applied to files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/AssetHeader/hooks/useQuickBuy.ts
📚 Learning: 2025-08-08T11:40:55.734Z
Learnt from: NeOMakinG
PR: shapeshift/web#10234
File: src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx:41-41
Timestamp: 2025-08-08T11:40:55.734Z
Learning: In MultiHopTrade confirm flow (src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx and related hooks), there is only one active trade per flow. Because of this, persistent (module/Redux) dedupe for QuotesReceived in useTrackTradeQuotes is not necessary; the existing ref-based dedupe is acceptable.

Applied to files:

  • src/components/AssetHeader/QuickBuy.tsx
  • src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx
  • src/components/AssetHeader/hooks/useQuickBuy.ts
📚 Learning: 2025-08-08T11:41:36.971Z
Learnt from: NeOMakinG
PR: shapeshift/web#10234
File: src/components/MultiHopTrade/hooks/useGetTradeQuotes/hooks/useTrackTradeQuotes.ts:88-109
Timestamp: 2025-08-08T11:41:36.971Z
Learning: In MultiHopTrade Confirm flow (src/components/MultiHopTrade/components/TradeConfirm/TradeConfirm.tsx), the Confirm route does not remount; navigating away goes to the swapper input page. Therefore, persistent deduplication across remounts for quote tracking is unnecessary; a ref-based single-mount dedupe is sufficient.

Applied to files:

  • src/components/AssetHeader/hooks/useQuickBuy.ts
🧬 Code graph analysis (3)
src/components/AssetHeader/QuickBuy.tsx (1)
src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx (1)
  • useMixpanel (7-24)
src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx (2)
src/lib/mixpanel/mixPanelSingleton.ts (1)
  • getMixPanel (9-41)
src/components/MultiHopTrade/helpers.ts (1)
  • getMixpanelEventData (24-74)
src/components/AssetHeader/hooks/useQuickBuy.ts (1)
src/components/MultiHopTrade/components/TradeConfirm/hooks/useMixpanel.tsx (1)
  • useMixpanel (7-24)
⏰ 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). (1)
  • GitHub Check: Call / Static
🔇 Additional comments (3)
src/components/AssetHeader/QuickBuy.tsx (3)

22-22: LGTM – consistent analytics imports.
Reuses the shared hook and enum; naming and paths look consistent.

Also applies to: 29-29


72-72: OK to allow events without data here.
Using useMixpanel(true) is reasonable for Preview/Confirm, where event data may be missing before a trade is initialized.


74-78: Track before action — good sequencing.
Emitting QuickBuyConfirm before confirmPurchase() avoids losing event context on rapid state changes.

@gomesalexandre gomesalexandre self-requested a review September 2, 2025 07:18
if (!mixpanel) return

const eventData = getMixpanelEventData()
// Allow tracking without eventData if flag is set
Copy link
Contributor

@gomesalexandre gomesalexandre Sep 2, 2025

Choose a reason for hiding this comment

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

Edit: Instead of supporting undefined, we could probably do even better and actually pass event data for previews, see https://github.com/shapeshift/web/pull/10407/files#r2315208720

q: is there any benefit in supporting an optional allowUndefinedEventData?

Feels like since this is a wrapper over mixpanel.track(), we could simply remove the eventData to comply with the signature of the track() method, WDYT?

image

@@ -110,7 +115,10 @@ export const QuickBuy: React.FC<QuickBuyProps> = ({ assetId, onEditAmounts }) =>
rounded='full'
background={isSuccess ? 'green.500' : undefined}
// eslint-disable-next-line react-memo/require-usememo
onClick={() => startPurchase(amount)}
onClick={() => {
trackMixpanelEvent(MixPanelEvent.QuickBuyPreview)
Copy link
Contributor

Choose a reason for hiding this comment

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

Since this is leveraging swapper slice, there won't be any event data here (which I assume is the reason why we've added support for undefined event data).

image

Wondering if instead of supporting undefined, we couldn't instead have trackMixpanelEvent support eventData from args (i.e Dic | undefined), and pass some event data here in the same shape as ReturnType<typeof getMixpanelEventData> , which would allow us to get proper tracking for quick buy previews?

Copy link
Contributor

@gomesalexandre gomesalexandre left a comment

Choose a reason for hiding this comment

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

Tested locally, does the do minus previews missing event data - happy with this as-is, though would be noice to tackle either here or as a follow-up! 🙏🏽

Added some comments re: undefined event data for event previews, feels like we should be able to pass some minimal data for MixPanelEvent.QuickBuyPreview (composite sell and buy assets, composite fee asset, sell amount USD, sell and buy asset chains).

https://jam.dev/c/843f285d-3f93-45ad-8703-d9b7b71d6822

image image image image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Add mixpanel event for quick buy
2 participants