Skip to content

chore: remove @metamask/sdk-analytics and migrate SDKv1 events to MetaMetrics - #28322

Merged
wenfix merged 23 commits into
mainfrom
wapi-1375
Apr 16, 2026
Merged

chore: remove @metamask/sdk-analytics and migrate SDKv1 events to MetaMetrics#28322
wenfix merged 23 commits into
mainfrom
wapi-1375

Conversation

@wenfix

@wenfix wenfix commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

Description

SDKv1 (socket relay) was tracking wallet-side analytics through two channels:

  1. @metamask/sdk-analytics — external package with its own telemetry backend; enabled in SDKConnect.init() via analytics.enable().
  2. SendAnalytics from @metamask/sdk-communication-layer — posted events directly to socketServerUrl/evt

Both bypassed the MetaMetrics opt-in/opt-out pipeline entirely.

This PR removes both and replaces all call sites with analytics.trackEvent() through AnalyticsController.

Four events are added to MetaMetrics.events.ts:

  • Remote Connection Request Received — fired in connectToChannel when a connection request arrives (pre-permission, measures dapp→wallet drop-off)
  • Remote Connection RPC Request Received — fired in handleConnectionMessage when an RPC message arrives
  • Remote Connection RPC Request Approved / Remote Connection RPC Request Rejected — fired in handleSendMessage on RPC outcome

wallet_connection_user_approved and wallet_connection_user_rejected are intentionally omitted — the permission UI already fires CONNECT_REQUEST_COMPLETED / CONNECT_REQUEST_CANCELLED which cover the same signal.

A new ANALYTICS_TRACKED_RPC_METHODS constant in SDKConnectConstants.ts replaces both the isAnalyticsTrackedRpcMethod helper from sdk-communication-layer and a local duplicate array.

All events include transport_type: 'socket_relay' to identify the SDKv1 source, rpc_method for RPC events, sdk_version from originatorInfo.apiVersion, and remote_session_id (a dapp-generated UUID for cross-side session correlation, kept in regular properties so the MetaMetrics privacy plugin does not split it into a separate anonymous event).

Changelog

CHANGELOG entry: null

Related issues

Fixes: WAPI-1375

Manual testing steps

Feature: SDK wallet analytics via MetaMetrics

  Scenario: dapp initiates an SDK connection (opted in)
    Given the user has MetaMetrics opted in
    And a dapp initiates an SDK connection via socket relay

    When the connection request arrives
    Then a Remote Connection Request Received event is sent to Segment
     And it includes transport_type: 'socket_relay' and remote_session_id

  Scenario: dapp sends an RPC request (opted in)
    Given an SDK connection is established
    And the dapp sends an RPC request for a tracked method

    When the user approves the request
    Then a Remote Connection RPC Request Approved event is sent to Segment

    When the user rejects the request
    Then a Remote Connection RPC Request Rejected event is sent to Segment

  Scenario: user has MetaMetrics opted out
    Given the user has MetaMetrics opted out
    And a dapp initiates an SDK connection

    When any SDK interaction occurs
    Then no analytics events are sent to Segment

Screenshots/Recordings

Before

N/A — analytics-only change, no UI changes.

After

N/A

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

Medium Risk
Moderate risk because it changes instrumentation inside SDKConnect connection/RPC handling and removes the legacy SendAnalytics path; mistakes could silently drop or mislabel telemetry, but it should not affect core transaction or auth flows.

Overview
Routes SDKv1 (socket relay) wallet-side analytics through the app’s MetaMetrics pipeline by replacing @metamask/sdk-analytics/SendAnalytics usage with analytics.trackEvent() + AnalyticsEventBuilder.

Adds four new MetaMetrics events (REMOTE_CONNECTION_REQUEST_RECEIVED, SDK_LEGACY_RPC_REQUEST_RECEIVED, ..._APPROVED, ..._REJECTED) and a centralized ANALYTICS_TRACKED_RPC_METHODS allowlist, and updates unit tests accordingly; also removes @metamask/sdk-analytics from dependencies and stops enabling it during SDKConnect.init().

Reviewed by Cursor Bugbot for commit fef4453. Bugbot is set up for automated code reviews on this repo. Configure here.

@github-actions

github-actions Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

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.

@metamaskbot metamaskbot added the team-wallet-integrations Wallet Integrations team label Apr 2, 2026
@github-actions github-actions Bot added the size-M label Apr 2, 2026
Comment on lines +57 to +58
// Comparison is intentionally case-sensitive: RPC method names are standardised
// and the SDK is expected to send them in canonical casing.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
// Comparison is intentionally case-sensitive: RPC method names are standardised
// and the SDK is expected to send them in canonical casing.

Comment thread app/core/SDKConnect/SDKConnectConstants.ts
Align event names with segment-schema PR #512 review feedback:

- wallet_connection_request_received → MMConnect Request Received
- wallet_action_received → SDK RPC Request Received
- wallet_action_user_approved → SDK RPC Request Approved
- wallet_action_user_rejected → SDK RPC Request Rejected

Uses Title Case "Object + Past-tense Verb" naming per repo conventions.
Enum keys updated accordingly (MMCONNECT_REQUEST_RECEIVED,
SDK_RPC_REQUEST_RECEIVED, etc.).
The event fires for all remote connection paths (SDK v1 socket relay,
MetaMask Connect / MWP, and eventually WalletConnect), not just
MMConnect. "Remote" correctly scopes it to connections that have a
pre-permission lifecycle step distinct from the transport-agnostic
Connect Request Started/Completed/Cancelled family.
Rename events to reflect cross-transport scope:
- SDK RPC Request Received → Remote Connection RPC Request Received
- SDK RPC Request Approved → Remote Connection RPC Request Approved
- SDK RPC Request Rejected → Remote Connection RPC Request Rejected

These events track post-connection RPC method calls from remotely
connected dapps. Renaming from "SDK" to "Remote Connection" aligns
with the segment-schema PR (Consensys/segment-schema#520) and sets
up the schema for future MWP and WalletConnect instrumentation.
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 82.12%. Comparing base (bd7e6fd) to head (9548357).
⚠️ Report is 116 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #28322      +/-   ##
==========================================
- Coverage   82.66%   82.12%   -0.54%     
==========================================
  Files        4866     4911      +45     
  Lines      126134   129040    +2906     
  Branches    28268    28757     +489     
==========================================
+ Hits       104273   105979    +1706     
- Misses      14660    15790    +1130     
- Partials     7201     7271      +70     

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

if (anonId) {
DevLogger.log(
`[MM SDK Analytics] event=wallet_connection_request_received anonId=${anonId}`,
`[MM SDK Analytics] event=Remote Connect Request Received anonId=${anonId}`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
`[MM SDK Analytics] event=Remote Connect Request Received anonId=${anonId}`,
`[MM SDK Analytics] event=${MetaMetricsEvents.REMOTE_CONNECT_REQUEST_RECEIVED} anonId=${anonId}`,

is this a valid suggestion ? I'm assuming the value of MetaMetricsEvents.REMOTE_CONNECT_REQUEST_RECEIVED is what we want here

@@ -180,9 +188,17 @@ async function connectToChannel({
DevLogger.log(
`[MM SDK Analytics] event=wallet_connection_user_approved anonId=${anonId}`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
`[MM SDK Analytics] event=wallet_connection_user_approved anonId=${anonId}`,
`[MM SDK Analytics] event=${MetaMetricsEvents.WALLET_CONNECTION_USER_APPROVED} anonId=${anonId}`,

same here if valid, even though you did not touch this piece of code, might as well do some cleaning (IF MetaMetricsEvents.WALLET_CONNECTION_USER_APPROVED is wallet_connection_user_approved which I'm not 100% sure of)

@@ -193,20 +209,21 @@ async function connectToChannel({
DevLogger.log(
`[MM SDK Analytics] event=wallet_connection_user_rejected anonId=${anonId}`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

same here

if (anonId && ANALYTICS_TRACKED_RPC_METHODS.includes(message.method)) {
DevLogger.log(
`[MM SDK Analytics] event=wallet_action_received anonId=${anonId}`,
`[MM SDK Analytics] event=Remote Connection RPC Request Received anonId=${anonId}`,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

same here

…1 events (#28390)

## Summary

Same rationale as the V2 cleanup (#28358): V1 connections flow through
the connection approval UI, which already fires
`CONNECT_REQUEST_COMPLETED` / `CONNECT_REQUEST_CANCELLED`. Adding
`wallet_connection_user_approved` / `wallet_connection_user_rejected` in
the relay layer re-implements the same signal.

**Removed:**

* `wallet_connection_user_approved` tracking from `connectToChannel.ts`
* `wallet_connection_user_rejected` tracking from `connectToChannel.ts`
* Both event definitions from `MetaMetrics.events.ts`
* Both test cases from `connectToChannel.test.ts`

**Kept** (no existing MetaMetrics event covers these):

* `Remote Connect Request Received` — fires before the permission check,
needed to measure dapp-to-wallet drop-off
* `Remote Connection RPC Request *` events — track per-RPC-method
confirmation lifecycle, separate concern from connection approval

**Renames in latest commit:**

The `SDK RPC Request *` events have been renamed to `Remote Connection
RPC Request *` to reflect their intended cross-transport scope.
Currently only SDKv1 is instrumented but the schema supports
`socket_relay`, `mwp`, and `walletconnect` transports.

**Context:** The `useOriginSource` fix (WAPI-1380, #28290) ensures the
`source` property is correct for both V1 and V2 connections on all
permission events, so the existing events already carry the right
attribution.

## Related schema PRs

-
[Consensys/segment-schema#519](Consensys/segment-schema#519)
— `Remote Connect Request Received/Failed` schemas
-
[Consensys/segment-schema#520](Consensys/segment-schema#520)
— `Remote Connection RPC Request Received/Approved/Rejected` schemas

## Test plan

* `connectToChannel.test.ts` — all remaining tests pass
* `handleConnectionMessage.test.ts` — updated for new event names
* `handleSendMessage.test.ts` — updated for new event names

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Low Risk**
> Low risk: removes redundant MetaMetrics tracking and associated tests,
with no changes to connection/permission behavior beyond analytics
emission.
> 
> **Overview**
> Removes the SDK v1 relay-layer MetaMetrics events
`wallet_connection_user_approved` and `wallet_connection_user_rejected`,
including their definitions in `MetaMetrics.events.ts`.
> 
> `connectToChannel.ts` no longer emits these events on
`checkPermissions` success/failure, relying instead on the permission
UI’s existing `CONNECT_REQUEST_COMPLETED` / `CONNECT_REQUEST_CANCELLED`
tracking. The corresponding unit tests asserting those emissions are
deleted and replaced with a clarifying comment.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1dc8ab6. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
adonesky1 and others added 4 commits April 9, 2026 16:04
- Rename `Remote Connect Request Received` → `Remote Connection Request Received`
  to match the finalized naming convention in segment-schema PR #519
- Rename `anon_id` property → `remote_session_id` across all remote
  connection/RPC analytics events for clarity
- Update corresponding test assertions
…rties

Aligns with the decision in PR #28470 — remote_session_id is a
dapp-generated UUID for cross-side analytics correlation, not sensitive
data. Keeping it in sensitiveProperties triggered the anonymous event
split which prevented linking dapp sessions to wallet user activity.
@adonesky1
adonesky1 marked this pull request as ready for review April 13, 2026 15:46
@adonesky1
adonesky1 requested a review from a team as a code owner April 13, 2026 15:46
@github-actions github-actions Bot added risk-medium Moderate testing recommended · Possible bug introduction risk and removed risk-medium Moderate testing recommended · Possible bug introduction risk labels Apr 14, 2026
@github-actions github-actions Bot added risk-medium Moderate testing recommended · Possible bug introduction risk and removed risk-medium Moderate testing recommended · Possible bug introduction risk labels Apr 15, 2026

@cursor cursor Bot left a comment

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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 72d6d97. Configure here.

Comment thread app/core/SDKConnect/handlers/handleSendMessage.ts
Aligns event names with the merged schema change in
Consensys/segment-schema#526 which renamed
"Remote Connection RPC Request *" → "SDK Legacy RPC Request *"
to reflect that these events are SDKv1-only.

Also removes unplanned wallet_version property (not in schema).
@adonesky1

adonesky1 commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

Pushed 2d4b465 — renamed event names from Remote Connection RPC Request *SDK Legacy RPC Request * to match the schema change in https://github.com/Consensys/segment-schema/pull/526 (merged). We renamed these in the schema to make it explicit that these events are SDKv1-only (socket relay + deeplink protocol) and won't be extended to MWP or WC. Also dropped the wallet_version property since it's not in the schema.

@github-actions github-actions Bot added risk-medium Moderate testing recommended · Possible bug introduction risk and removed risk-medium Moderate testing recommended · Possible bug introduction risk labels Apr 15, 2026
The comment was explaining why wallet_connection_user_approved/rejected
were removed, which is useful in PR review but not in the codebase.
@github-actions github-actions Bot added risk-low Low testing needed · Low bug introduction risk and removed risk-medium Moderate testing recommended · Possible bug introduction risk labels Apr 15, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔍 Smart E2E Test Selection

  • Selected E2E tags: SmokeWalletPlatform
  • Selected Performance tags: None (no tests recommended)
  • Risk Level: low
  • AI Confidence: 82%
click to see 🤖 AI reasoning details

E2E Test Selection:
The PR is a focused analytics refactoring in the SDKConnect layer:

  1. Package removal: @metamask/sdk-analytics (v0.0.5) is removed from package.json — no remaining references found in the codebase.

  2. Analytics migration: connectToChannel.ts, handleConnectionMessage.ts, and handleSendMessage.ts migrate from the external analytics.track() API to the internal MetaMetrics analytics.trackEvent() + AnalyticsEventBuilder pattern. New events (REMOTE_CONNECTION_REQUEST_RECEIVED, SDK_LEGACY_RPC_REQUEST_RECEIVED/APPROVED/REJECTED) are added to MetaMetrics.events.ts.

  3. No functional changes: The actual SDK connection logic, permission checks, RPC method routing, and user-facing flows are completely unchanged. Only the analytics instrumentation is updated.

  4. SDKConnect initialization: Removes analytics.setGlobalProperty('platform', 'mobile') and analytics.enable() calls that were specific to the old library.

  5. Test files: Unit tests updated to mock the new analytics API — these are unit tests, not E2E.

Why SmokeWalletPlatform: This tag covers EVM provider event handling and dApp communication flows, which exercise the SDKConnect layer. Running these tests validates that the analytics refactoring didn't accidentally break the connection flow or message handling. The changes touch core SDK connection infrastructure, so a smoke test of dApp-related functionality is prudent.

Why not more tags: The changes are purely analytics instrumentation — no UI, no navigation, no transaction flows, no account management, no network switching. The risk of regression is low and confined to the SDK connection layer.

Performance Test Selection:
These changes are analytics-only refactoring — migrating from an external analytics library to the internal MetaMetrics system. No UI rendering, no data loading, no state management changes, no component modifications. There is no performance impact expected from changing analytics event tracking calls.

View GitHub Actions results

@sonarqubecloud

Copy link
Copy Markdown

@github-actions

Copy link
Copy Markdown
Contributor

E2E Fixture Validation — Schema is up to date
11 value mismatches detected (expected — fixture represents an existing user).
View details

@adonesky1

Copy link
Copy Markdown
Contributor
Screen.Recording.2026-04-15.at.12.46.31.PM.mov

Having trouble validating the segment events (even just in console. let alone segment) Seeing if someone can gut check me here

@adonesky1

adonesky1 commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

Ok after a lot of fiddling, I'm seeing the events

Screenshot 2026-04-15 at 4 16 21 PM

And in Segment 🙌
Screenshot 2026-04-15 at 4 19 40 PM

@adonesky1 adonesky1 left a comment

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.

LGMT

@adonesky1
adonesky1 added this pull request to the merge queue Apr 16, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Apr 16, 2026
@wenfix
wenfix added this pull request to the merge queue Apr 16, 2026
Merged via the queue into main with commit 5e9026a Apr 16, 2026
97 checks passed
@wenfix
wenfix deleted the wapi-1375 branch April 16, 2026 15:22
@github-actions github-actions Bot locked and limited conversation to collaborators Apr 16, 2026
@metamaskbotv2 metamaskbotv2 Bot added the release-7.74.0 Issue or pull request that will be included in release 7.74.0 label Apr 16, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.74.0 Issue or pull request that will be included in release 7.74.0 risk-low Low testing needed · Low bug introduction risk size-M team-wallet-integrations Wallet Integrations team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants