Skip to content
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

chore: move metrics identify to state listener #13203

Merged
merged 6 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 1 addition & 11 deletions app/components/Nav/App/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,6 @@ import SDKSessionModal from '../../Views/SDK/SDKSessionModal/SDKSessionModal';
import ExperienceEnhancerModal from '../../../../app/components/Views/ExperienceEnhancerModal';
import { MetaMetrics } from '../../../core/Analytics';
import trackErrorAsAnalytics from '../../../util/metrics/TrackError/trackErrorAsAnalytics';
import generateDeviceAnalyticsMetaData from '../../../util/metrics/DeviceAnalyticsMetaData/generateDeviceAnalyticsMetaData';
import generateUserSettingsAnalyticsMetaData from '../../../util/metrics/UserSettingsAnalyticsMetaData/generateUserProfileAnalyticsMetaData';
import LedgerSelectAccount from '../../Views/LedgerSelectAccount';
import OnboardingSuccess from '../../Views/OnboardingSuccess';
import DefaultSettings from '../../Views/OnboardingSuccess/DefaultSettings';
Expand Down Expand Up @@ -745,15 +743,7 @@ const App = (props) => {

useEffect(() => {
const initMetrics = async () => {
const metrics = MetaMetrics.getInstance();
await metrics.configure();
// identify user with the latest traits
// run only after the MetaMetrics is configured
const consolidatedTraits = {
...generateDeviceAnalyticsMetaData(),
...generateUserSettingsAnalyticsMetaData(),
};
await metrics.addTraitsToUser(consolidatedTraits);
await MetaMetrics.getInstance().configure();
};

initMetrics().catch((err) => {
Expand Down
4 changes: 0 additions & 4 deletions app/components/Nav/App/index.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,6 @@ describe('App', () => {
);
await waitFor(() => {
expect(mockMetrics.configure).toHaveBeenCalledTimes(1);
expect(mockMetrics.addTraitsToUser).toHaveBeenNthCalledWith(1, {
deviceProp: 'Device value',
userProp: 'User value',
});
});
});
});
45 changes: 44 additions & 1 deletion app/core/AppStateEventListener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ jest.mock('./processAttribution', () => ({
jest.mock('./Analytics/MetaMetrics');

const mockMetrics = {
trackEvent: jest.fn().mockImplementation(() => Promise.resolve()),
trackEvent: jest.fn(),
enable: jest.fn(() => Promise.resolve()),
addTraitsToUser: jest.fn(() => Promise.resolve()),
isEnabled: jest.fn(() => true),
Expand Down Expand Up @@ -105,6 +105,49 @@ describe('AppStateEventListener', () => {
);
});

it('identifies user when app becomes active', () => {
jest
.spyOn(ReduxService, 'store', 'get')
.mockReturnValue({} as unknown as ReduxStore);

mockAppStateListener('active');
jest.advanceTimersByTime(2000);

expect(mockMetrics.addTraitsToUser).toHaveBeenCalledTimes(1);
expect(mockMetrics.addTraitsToUser).toHaveBeenCalledWith({
'Batch account balance requests': 'OFF',
'Enable OpenSea API': 'OFF',
'NFT Autodetection': 'OFF',
'Theme': undefined,
'applicationVersion': expect.any(Promise),
'currentBuildNumber': expect.any(Promise),
'deviceBrand': 'Apple',
'operatingSystemVersion': 'ios',
'platform': 'ios',
'security_providers': '',
'token_detection_enable': 'OFF',
});
});

it('logs error when identifying user fails', () => {
jest
.spyOn(ReduxService, 'store', 'get')
.mockReturnValue({} as unknown as ReduxStore);
const testError = new Error('Test error');
mockMetrics.addTraitsToUser.mockImplementation(() => {
throw testError;
});

mockAppStateListener('active');
jest.advanceTimersByTime(2000);

expect(Logger.error).toHaveBeenCalledWith(
testError,
'AppStateManager: Error processing app state change'
);
expect(mockMetrics.trackEvent).not.toHaveBeenCalled();
});

it('handles errors gracefully', () => {
jest
.spyOn(ReduxService, 'store', 'get')
Expand Down
17 changes: 16 additions & 1 deletion app/core/AppStateEventListener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { MetricsEventBuilder } from './Analytics/MetricsEventBuilder';
import { processAttribution } from './processAttribution';
import DevLogger from './SDKConnect/utils/DevLogger';
import ReduxService from './redux';
import generateDeviceAnalyticsMetaData from '../util/metrics';
import generateUserSettingsAnalyticsMetaData
from '../util/metrics/UserSettingsAnalyticsMetaData/generateUserProfileAnalyticsMetaData';

export class AppStateEventListener {
private appStateSubscription:
Expand Down Expand Up @@ -48,6 +51,18 @@ export class AppStateEventListener {
currentDeeplink: this.currentDeeplink,
store: ReduxService.store,
});
const metrics = MetaMetrics.getInstance();
Cal-L marked this conversation as resolved.
Show resolved Hide resolved
// identify user with the latest traits
const consolidatedTraits = {
...generateDeviceAnalyticsMetaData(),
...generateUserSettingsAnalyticsMetaData(),
};
metrics.addTraitsToUser(consolidatedTraits).catch((error) => {
Logger.error(
error as Error,
'AppStateManager: Error adding traits to user',
);
});
const appOpenedEventBuilder = MetricsEventBuilder.createEventBuilder(MetaMetricsEvents.APP_OPENED);
if (attribution) {
const { attributionId, utm, ...utmParams } = attribution;
Expand All @@ -57,7 +72,7 @@ export class AppStateEventListener {
);
appOpenedEventBuilder.addProperties({ attributionId, ...utmParams });
}
MetaMetrics.getInstance().trackEvent(appOpenedEventBuilder.build());
metrics.trackEvent(appOpenedEventBuilder.build());
} catch (error) {
Logger.error(
error as Error,
Expand Down
Loading