-
Notifications
You must be signed in to change notification settings - Fork 196
chore: add mixpanel tracking for quickbuy #10407
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: develop
Are you sure you want to change the base?
Conversation
📝 WalkthroughWalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Assessment against linked issues
Suggested reviewers
Poem
✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
CodeRabbit Configuration File (
|
76c8610
to
2eae853
Compare
2eae853
to
672b476
Compare
There was a problem hiding this 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 inuseQuickBuy
, move the Preview event intostartPurchase
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 emitQuickBuyPreview
insidestartPurchase
.)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) returnsrc/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 defaultuseMixpanel()
here so Success/Failed aren’t emitted without event payloads. Keeptrue
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.
📒 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 useuseMemo
for expensive computations, object/array creations, and filtered data
ALWAYS useuseMemo
for derived values and computed properties
ALWAYS useuseMemo
for conditional values and simple transformations
ALWAYS useuseCallback
for event handlers and functions passed as props
ALWAYS useuseCallback
for any function that could be passed as a prop or dependency
ALWAYS include all dependencies inuseEffect
,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 withmemo
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.
UsinguseMixpanel(true)
is reasonable for Preview/Confirm, where event data may be missing before a trade is initialized.
74-78
: Track before action — good sequencing.
EmittingQuickBuyConfirm
beforeconfirmPurchase()
avoids losing event context on rapid state changes.
if (!mixpanel) return | ||
|
||
const eventData = getMixpanelEventData() | ||
// Allow tracking without eventData if flag is set |
There was a problem hiding this comment.
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?

@@ -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) |
There was a problem hiding this comment.
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).

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?
There was a problem hiding this 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




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
Testing
Engineering
Operations
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