Skip to content

chore: add metrics for trending#23674

Merged
sahar-fehri merged 14 commits intomainfrom
chore/add-metrics-for-trending
Dec 11, 2025
Merged

chore: add metrics for trending#23674
sahar-fehri merged 14 commits intomainfrom
chore/add-metrics-for-trending

Conversation

@sahar-fehri
Copy link
Copy Markdown
Contributor

@sahar-fehri sahar-fehri commented Dec 4, 2025

Description

PR adds metrics for trending.

Metric Event Name Key Property
Trending Feed visitsl TRENDING_FEED_VIEWED session_id, is_session_end
Time spent on page TRENDING_FEED_VIEWED session_time
Swap volume from Trending SWAP_BUTTON_CLICKED from_trending: true
Perps volume from Trending PERPS_TRADE_TRANSACTION source: 'trending'
Predict volume from Trending PREDICT_TRADE_TRANSACTION entry_point: 'trending'

To test this i added logs where it should emit the events:

1️⃣ & 2️⃣ Trending Feed Session (Visits + Time Spent)
File: app/components/UI/Trending/services/TrendingFeedSessionManager.ts

private trackEvent(isSessionEnd: boolean = false): void {
  if (!this.sessionId) return;

  const analyticsProperties = {
    session_id: this.sessionId,
    session_time: this.getElapsedTime(),
    is_session_end: isSessionEnd,
    entry_point: this.entryPoint,
  };

  // eslint-disable-next-line no-console
  console.log('=== TRENDING_FEED_VIEWED ===', analyticsProperties);

  MetaMetrics.getInstance().trackEvent(
    // ... existing code
  );
}

3️⃣ Swap Volume from Trending
File: app/components/UI/Bridge/hooks/useSwapBridgeNavigation/index.ts

      const swapEventProperties = {
        location,
        chain_id_source: getDecimalChainId(sourceToken.chainId),
        token_symbol_source: sourceToken?.symbol,
        token_address_source: sourceToken?.address,
        from_trending: fromTrending ?? false,
      };
      // eslint-disable-next-line no-console
      console.log('=== SWAP_BUTTON_CLICKED ===', swapEventProperties);
      trackEvent(
        createEventBuilder(MetaMetricsEvents.SWAP_BUTTON_CLICKED)
          .addProperties(swapEventProperties)
          .build(),
      );

4️⃣ Perps Volume from Trending
File: app/components/UI/Perps/controllers/services/TradingService.ts

     .......
    } else {
      // Add failure-specific properties
      eventBuilder.addProperties({
        [PerpsEventProperties.ERROR_MESSAGE]:
          error?.message || result?.error || 'Unknown error',
      });
    }

    // eslint-disable-next-line no-console
    console.log('=== PERPS_TRADE_TRANSACTION ===', {
      asset: params.coin,
      source: params.trackingData?.source || 'none',
      status,
    });

5️⃣ Predict Volume from Trending
File: app/components/UI/Predict/controllers/PredictController.ts

console.log('=== PREDICT_TRADE_TRANSACTION ===', {
  marketId: analyticsProperties?.marketId,
  entryPoint: analyticsProperties?.entryPoint,
  transactionType: analyticsProperties?.transactionType,
  status,
});

MetaMetrics.getInstance().trackEvent(
  // ... existing code
);

🧪 Test Scenarios

Test 1: Trending Feed Session
Navigate to Trending tab
Check: Log shows TRENDING_FEED_VIEWED with is_session_end: false
Wait 30 seconds
Navigate away OR background the app
Check: Log shows TRENDING_FEED_VIEWED with is_session_end: true, session_time: ~30

Test 2: Swap from Trending
Go to Trending → Click on a token card
On Token Details, click Swap
Check: Log shows from_trending: true
Test 3: Swap NOT from Trending
Go to Wallet → Click on any token
Click Swap
Check: Log shows from_trending: false

Test 4: Perps from Trending (Carousel)
Go to Trending → Click on a Perps market card in carousel
Click Long/Short → Place order
Check: Log shows source: "trending"

Test 5: Perps from Trending (QuickAction)
Go to Trending → Click Perps QuickAction button
Click on a market from the list
Click Long/Short → Place order
Check: Log shows source: "trending"

Test 6: Perps NOT from Trending
Go to Perps tab from home (not from Trending)
Click on start trading → Choose any crypto → Place order
Check: Log shows source: "none" or different source

Test 7: Predict from Trending
Go to Trending → Click on a Predict market card in carousel
Click Yes/No → Complete trade
Check: Log shows entryPoint: "trending"

Test 8: Predict NOT from Trending
Go to Predict tab directly
Click on a market → Complete trade
Check: Log shows entryPoint: "predict_feed"

Changelog

CHANGELOG entry: Adds metrics for trending feature

Related issues

Fixes:

Manual testing steps

Feature: my feature name

  Scenario: user [verb for user action]
    Given [describe expected initial app state]

    When user [verb for user action]
    Then [describe expected outcome]

Screenshots/Recordings

Before

After

Pre-merge author checklist

Pre-merge reviewer checklist

  • I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed).
  • I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.

Note

Adds Trending Feed session analytics and propagates “from trending”/entry point to Swaps, Perps, and Predict events.

  • Analytics:
    • Trending session: Introduces TrendingFeedSessionManager to track sessions (start/end, app state) and emits TRENDING_FEED_VIEWED with session_id, session_time, is_session_end, entry_point.
    • Events: Registers TRENDING_FEED_VIEWED in MetaMetrics.events.
  • Trending View:
    • Initializes/destroys trending sessions in Views/TrendingView.tsx (enable AppState listener, start/end session).
  • Swaps:
    • In useSwapBridgeNavigation, augments SWAP_BUTTON_CLICKED with from_trending based on active trending session.
  • Perps:
    • Auto-sets tracking source: 'trending' in PerpsOrderView when session active; TradingService includes source in PERPS_TRADE_TRANSACTION.
    • Extends TrackingData with optional source.
  • Predict:
    • Auto-resolves entryPoint to ENTRY_POINT.TRENDING in PredictMarketSingle/PredictMarketMultiple and propagates via navigation (including market details); adds ENTRY_POINT.TRENDING to constants and types.
  • Tests:
    • Adds comprehensive tests for TrendingFeedSessionManager.
    • Updates Predict component tests to mock session manager and validate navigation params.

Written by Cursor Bugbot for commit ca00a11. This will update automatically on new commits. Configure here.

@github-actions
Copy link
Copy Markdown
Contributor

github-actions bot commented Dec 4, 2025

CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes.

chain_id_source: getDecimalChainId(sourceToken.chainId),
token_symbol_source: sourceToken?.symbol,
token_address_source: sourceToken?.address,
from_trending: fromTrending ?? false,
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The event for swaps already exists; i am adding a property "from_trending" to recognize if the user came from trending page

{
screen: Routes.PERPS.MARKET_DETAILS,
params: { market: item as PerpsMarketData },
params: { market: item as PerpsMarketData, source: 'trending' },
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Adding source "trending" for when user clicks on rowItem from the trendingFeed, or from ViewAllAction

navigateToOrder({
direction,
asset: market.symbol,
source,
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

passing down the source to PerpsOrderView

@sahar-fehri sahar-fehri marked this pull request as ready for review December 4, 2025 15:23
@sahar-fehri sahar-fehri requested review from a team as code owners December 4, 2025 15:23
@github-actions github-actions bot added size-L and removed size-M labels Dec 4, 2025
@sahar-fehri sahar-fehri added the skip-sonar-cloud Only used for bypassing sonar cloud when failures are not relevant to the changes. label Dec 4, 2025
@codecov-commenter
Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.47826% with 6 lines in your changes missing coverage. Please review.
✅ Project coverage is 78.74%. Comparing base (27e7f2e) to head (4cdfa2d).
⚠️ Report is 9 commits behind head on main.

Files with missing lines Patch % Lines
...UI/Trending/services/TrendingFeedSessionManager.ts 93.75% 1 Missing and 4 partials ⚠️
...ts/UI/Perps/controllers/services/TradingService.ts 0.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #23674      +/-   ##
==========================================
+ Coverage   78.73%   78.74%   +0.01%     
==========================================
  Files        4042     4043       +1     
  Lines      105606   105723     +117     
  Branches    21267    21292      +25     
==========================================
+ Hits        83144    83248     +104     
- Misses      16637    16641       +4     
- Partials     5825     5834       +9     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

interface PredictMarketProps {
market: PredictMarketType;
testID?: string;
entryPoint?: PredictEntryPoint;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

If poss, can we revert this file change (we can reduce the number of CO files to review)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

gambinish
gambinish previously approved these changes Dec 8, 2025
GeorgeGkas
GeorgeGkas previously approved these changes Dec 9, 2025
matallui
matallui previously approved these changes Dec 11, 2025
@github-actions
Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

  • Selected E2E tags: SmokePredictions, SmokePerps, SmokeTrade, SmokeAnalytics
  • Risk Level: medium
  • AI Confidence: 85%
click to see 🤖 AI reasoning details

The changes in this PR introduce a new TrendingFeedSessionManager service for tracking user sessions in the Trending Feed, along with analytics event tracking improvements across multiple features:

  1. Analytics Events (CRITICAL FILE): MetaMetrics.events.ts adds a new TRENDING_FEED_VIEWED event. This is a critical file but the change is purely additive - adding a new analytics event name.

  2. TrendingFeedSessionManager: New singleton service that tracks:

    • Session lifecycle (start/end with AppState handling)
    • Time spent in feed
    • Entry point tracking
    • isFromTrending flag for cross-feature analytics attribution
  3. Perps Integration:

    • PerpsOrderView.tsx - Uses TrendingFeedSessionManager to detect if user came from trending feed and adds source to tracking data
    • TradingService.ts - Adds source property to analytics events
    • types/index.ts - Adds source field to TrackingData interface
  4. Predict Integration:

    • PredictMarketSingle.tsx and PredictMarketMultiple.tsx - Auto-detect entry point based on trending session state
    • PredictMarketDetails.tsx - Passes entryPoint prop through to child components
    • eventNames.ts - Adds new TRENDING entry point value
    • navigation.ts - Adds TRENDING to PredictEntryPoint type
  5. Bridge/Swap Integration:

    • useSwapBridgeNavigation - Adds from_trending property to swap button analytics
  6. TrendingView Integration:

    • Initializes TrendingFeedSessionManager when mounted, handles session lifecycle

All changes are primarily analytics-related, adding tracking capabilities for when users navigate from the Trending Feed to other features (Perps, Predictions, Swaps/Bridge). The unit tests added cover the new TrendingFeedSessionManager service and update mocks in Predict component tests.

Selected tags rationale:

  • SmokePredictions: Direct changes to Predict components and analytics event tracking
  • SmokePerps: Direct changes to Perps order view and trading service analytics
  • SmokeTrade: Changes to swap/bridge navigation hook with analytics tracking, plus some predict tests use SmokeTrade
  • SmokeAnalytics: Changes to core analytics events file and cross-feature analytics attribution

View GitHub Actions results

@GeorgeGkas GeorgeGkas self-requested a review December 11, 2025 12:53
@sonarqubecloud
Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
30.2% Duplication on New Code (required ≤ 10%)

See analysis details on SonarQube Cloud

@sahar-fehri sahar-fehri added this pull request to the merge queue Dec 11, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Dec 11, 2025
@sahar-fehri sahar-fehri added this pull request to the merge queue Dec 11, 2025
@github-merge-queue github-merge-queue bot removed this pull request from the merge queue due to failed status checks Dec 11, 2025
@sahar-fehri sahar-fehri added this pull request to the merge queue Dec 11, 2025
Merged via the queue into main with commit 3bde41e Dec 11, 2025
161 of 165 checks passed
@sahar-fehri sahar-fehri deleted the chore/add-metrics-for-trending branch December 11, 2025 19:11
@github-actions github-actions bot locked and limited conversation to collaborators Dec 11, 2025
@metamaskbot metamaskbot added the release-7.62.0 Issue or pull request that will be included in release 7.62.0 label Dec 11, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.62.0 Issue or pull request that will be included in release 7.62.0 size-L skip-sonar-cloud Only used for bypassing sonar cloud when failures are not relevant to the changes. team-assets

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants