|
| 1 | +/** |
| 2 | + * This file is intended to be renamed to metametrics.js once the conversion is complete. |
| 3 | + * MetaMetrics is our own brand, and should remain aptly named regardless of the underlying |
| 4 | + * metrics system. This file implements Segment analytics tracking. |
| 5 | + */ |
| 6 | +import React, { useRef, Component, createContext, useEffect, useCallback } from 'react' |
| 7 | +import { useSelector } from 'react-redux' |
| 8 | +import PropTypes from 'prop-types' |
| 9 | +import { useLocation, matchPath, useRouteMatch } from 'react-router-dom' |
| 10 | +import { captureException, captureMessage } from '@sentry/browser' |
| 11 | + |
| 12 | +import { omit } from 'lodash' |
| 13 | +import { |
| 14 | + getCurrentNetworkId, |
| 15 | +} from '../selectors/selectors' |
| 16 | + |
| 17 | +import { getEnvironmentType } from '../../../app/scripts/lib/util' |
| 18 | +import { |
| 19 | + sendCountIsTrackable, |
| 20 | + segment, |
| 21 | + METAMETRICS_ANONYMOUS_ID, |
| 22 | +} from '../helpers/utils/metametrics.util' |
| 23 | +import { PATH_NAME_MAP } from '../helpers/constants/routes' |
| 24 | +import { getCurrentLocale } from '../ducks/metamask/metamask' |
| 25 | +import { txDataSelector } from '../selectors' |
| 26 | + |
| 27 | +export const MetaMetricsContext = createContext(() => { |
| 28 | + captureException( |
| 29 | + Error(`MetaMetrics context function was called from a react node that is not a descendant of a MetaMetrics context provider`), |
| 30 | + ) |
| 31 | +}) |
| 32 | + |
| 33 | +const PATHS_TO_CHECK = Object.keys(PATH_NAME_MAP) |
| 34 | + |
| 35 | +function useSegmentContext () { |
| 36 | + const match = useRouteMatch({ path: PATHS_TO_CHECK, exact: true, strict: true }) |
| 37 | + const locale = useSelector(getCurrentLocale) |
| 38 | + const txData = useSelector(txDataSelector) || {} |
| 39 | + const confirmTransactionOrigin = txData.origin |
| 40 | + |
| 41 | + const referrer = confirmTransactionOrigin ? { |
| 42 | + url: confirmTransactionOrigin, |
| 43 | + } : undefined |
| 44 | + |
| 45 | + let version = global.platform.getVersion() |
| 46 | + if (process.env.METAMASK_ENVIRONMENT !== 'production') { |
| 47 | + version = `${version}-${process.env.METAMASK_ENVIRONMENT}` |
| 48 | + } |
| 49 | + |
| 50 | + const page = match ? { |
| 51 | + path: match.path, |
| 52 | + title: PATH_NAME_MAP[match.path], |
| 53 | + url: match.path, |
| 54 | + } : undefined |
| 55 | + |
| 56 | + return { |
| 57 | + app: { |
| 58 | + version, |
| 59 | + name: 'MetaMask Extension', |
| 60 | + }, |
| 61 | + locale: locale.replace('_', '-'), |
| 62 | + page, |
| 63 | + referrer, |
| 64 | + userAgent: window.navigator.userAgent, |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +export function MetaMetricsProvider ({ children }) { |
| 69 | + const network = useSelector(getCurrentNetworkId) |
| 70 | + const metaMetricsId = useSelector((state) => state.metamask.metaMetricsId) |
| 71 | + const participateInMetaMetrics = useSelector((state) => state.metamask.participateInMetaMetrics) |
| 72 | + const metaMetricsSendCount = useSelector((state) => state.metamask.metaMetricsSendCount) |
| 73 | + const location = useLocation() |
| 74 | + const context = useSegmentContext() |
| 75 | + |
| 76 | + // Used to prevent double tracking page calls |
| 77 | + const previousMatch = useRef() |
| 78 | + |
| 79 | + /** |
| 80 | + * Anytime the location changes, track a page change with segment. |
| 81 | + * Previously we would manually track changes to history and keep a |
| 82 | + * reference to the previous url, but with page tracking we can see |
| 83 | + * which page the user is on and their navigation path. |
| 84 | + */ |
| 85 | + useEffect(() => { |
| 86 | + const environmentType = getEnvironmentType() |
| 87 | + if ( |
| 88 | + (participateInMetaMetrics === null && location.pathname.startsWith('/initialize')) || |
| 89 | + participateInMetaMetrics |
| 90 | + ) { |
| 91 | + // Events that happen during initialization before the user opts into MetaMetrics will be anonymous |
| 92 | + const idTrait = metaMetricsId ? 'userId' : 'anonymousId' |
| 93 | + const idValue = metaMetricsId ?? METAMETRICS_ANONYMOUS_ID |
| 94 | + const match = matchPath(location.pathname, { path: PATHS_TO_CHECK, exact: true, strict: true }) |
| 95 | + if ( |
| 96 | + match && |
| 97 | + previousMatch.current !== match.path && |
| 98 | + // If we're in a popup or notification we don't want the initial home route to track |
| 99 | + !( |
| 100 | + (environmentType === 'popup' || environmentType === 'notification') && |
| 101 | + match.path === '/' && |
| 102 | + previousMatch.current === undefined |
| 103 | + ) |
| 104 | + ) { |
| 105 | + const { path, params } = match |
| 106 | + const name = PATH_NAME_MAP[path] |
| 107 | + segment.page({ |
| 108 | + [idTrait]: idValue, |
| 109 | + name, |
| 110 | + properties: { |
| 111 | + // We do not want to send addresses or accounts in any events |
| 112 | + // Some routes include these as params. |
| 113 | + params: omit(params, ['account', 'address']), |
| 114 | + network, |
| 115 | + environment_type: environmentType, |
| 116 | + }, |
| 117 | + context, |
| 118 | + }) |
| 119 | + } else if (location.pathname !== '/confirm-transaction') { |
| 120 | + // We have more specific pages for each type of transaction confirmation |
| 121 | + // The user lands on /confirm-transaction first, then is redirected based on |
| 122 | + // the contents of state. |
| 123 | + captureMessage(`${location.pathname} would have issued a page track event to segment, but no route match was found`) |
| 124 | + } |
| 125 | + previousMatch.current = match?.path |
| 126 | + } |
| 127 | + }, [location, context, network, metaMetricsId, participateInMetaMetrics]) |
| 128 | + |
| 129 | + /** |
| 130 | + * track a metametrics event using segment |
| 131 | + * e.g metricsEvent({ event: 'Unlocked MetaMask', category: 'Navigation' }) |
| 132 | + * |
| 133 | + * @param {object} config - configuration object for the event to track |
| 134 | + * @param {string} config.event - event name to track |
| 135 | + * @param {string} config.category - category to associate event to |
| 136 | + * @param {boolean} [config.isOptIn] - happened during opt in/out workflow |
| 137 | + * @param {object} [config.properties] - object of custom values to track, snake_case |
| 138 | + * @param {number} [config.revenue] - amount of currency that event creates in revenue for MetaMask |
| 139 | + * @param {string} [config.currency] - ISO 4127 format currency for events with revenue, defaults to US dollars |
| 140 | + * @param {number} [config.value] - Abstract "value" that this event has for MetaMask. |
| 141 | + * @return {undefined} |
| 142 | + */ |
| 143 | + const trackEvent = useCallback( |
| 144 | + (config = {}) => { |
| 145 | + const { event, category, isOptIn = false, properties = {}, revenue, value, currency } = config |
| 146 | + if (!event) { |
| 147 | + // Event name is required for tracking an event |
| 148 | + throw new Error('MetaMetrics trackEvent function must be provided a payload with an "event" key') |
| 149 | + } |
| 150 | + if (!category) { |
| 151 | + // Category must be supplied for every tracking event |
| 152 | + throw new Error('MetaMetrics events must be provided a category') |
| 153 | + } |
| 154 | + const environmentType = getEnvironmentType() |
| 155 | + |
| 156 | + let excludeMetaMetricsId = config.excludeMetaMetricsId ?? false |
| 157 | + |
| 158 | + // This is carried over from the old implementation, and will likely need |
| 159 | + // to be updated to work with the new tracking plan. I think we should use |
| 160 | + // a config setting for this instead of trying to match the event name |
| 161 | + const isSendFlow = Boolean(event.match(/^send|^confirm/u)) |
| 162 | + if (isSendFlow && !sendCountIsTrackable(metaMetricsSendCount + 1)) { |
| 163 | + excludeMetaMetricsId = true |
| 164 | + } |
| 165 | + const idTrait = excludeMetaMetricsId ? 'anonymousId' : 'userId' |
| 166 | + const idValue = excludeMetaMetricsId ? METAMETRICS_ANONYMOUS_ID : metaMetricsId |
| 167 | + |
| 168 | + if (participateInMetaMetrics || isOptIn) { |
| 169 | + segment.track({ |
| 170 | + [idTrait]: idValue, |
| 171 | + event, |
| 172 | + properties: { |
| 173 | + ...omit(properties, ['revenue', 'currency', 'value']), |
| 174 | + revenue, |
| 175 | + value, |
| 176 | + currency, |
| 177 | + category, |
| 178 | + network, |
| 179 | + environment_type: environmentType, |
| 180 | + }, |
| 181 | + context, |
| 182 | + }) |
| 183 | + } |
| 184 | + |
| 185 | + return undefined |
| 186 | + }, [ |
| 187 | + context, |
| 188 | + network, |
| 189 | + metaMetricsId, |
| 190 | + metaMetricsSendCount, |
| 191 | + participateInMetaMetrics, |
| 192 | + ], |
| 193 | + ) |
| 194 | + |
| 195 | + return ( |
| 196 | + <MetaMetricsContext.Provider value={trackEvent}> |
| 197 | + {children} |
| 198 | + </MetaMetricsContext.Provider> |
| 199 | + ) |
| 200 | +} |
| 201 | + |
| 202 | +MetaMetricsProvider.propTypes = { children: PropTypes.node } |
| 203 | + |
| 204 | +export class LegacyMetaMetricsProvider extends Component { |
| 205 | + static propTypes = { |
| 206 | + children: PropTypes.node, |
| 207 | + } |
| 208 | + |
| 209 | + static defaultProps = { |
| 210 | + children: undefined, |
| 211 | + } |
| 212 | + |
| 213 | + static contextType = MetaMetricsContext |
| 214 | + |
| 215 | + static childContextTypes = { |
| 216 | + // This has to be different than the type name for the old metametrics file |
| 217 | + // using the same name would result in whichever was lower in the tree to be |
| 218 | + // used. |
| 219 | + trackEvent: PropTypes.func, |
| 220 | + } |
| 221 | + |
| 222 | + getChildContext () { |
| 223 | + return { |
| 224 | + trackEvent: this.context, |
| 225 | + } |
| 226 | + } |
| 227 | + |
| 228 | + render () { |
| 229 | + return this.props.children |
| 230 | + } |
| 231 | +} |
0 commit comments