Skip to content

Commit 6870129

Browse files
feat(rewards): open referral invites from deep links (#47665)
## **Description** Open the existing referral invite sheet over the intended destination when an internal deep link includes a single valid `ref`. This also handles deferred links after onboarding, while preserving the sheet's existing eligibility checks and interaction events. Carry the code in a temporary document query parameter, then move it into UI state before any routed screen mounts. Continue links remain ordinary anchors, so opening a new tab and copying the URL still work. Signed route parameters and security interstitial decisions keep their existing behavior. Share referral-code validation with the invite input and include `referral_code` as a regular property on **Deep Link Used**. Validation after updating main: - 161 tests passed across 11 focused suites. - CI follow-up: both RootLayout tests and all four dedicated ReferralInvite tests pass after isolating the invite in the layout fixture. The two layout failures were reproduced before the fix. - Changed-file lint, full TypeScript checking, JSON fixture formatting, and circular dependency checks passed. - Resolved the root-layout merge conflict and updated the state-log fixture for `pendingReferralCode`. - Existing visual captures are below. Live-service and install/onboarding verification remain pending. ## **Changelog** CHANGELOG entry: Added referral invitations to deep links, including links restored after onboarding. ## **Related issues** Related: #47622 ## **Manual testing steps** 1. Enable Basic Functionality and the Money rewards feature flag. Using an eligible test wallet and a valid test referral code, open `https://link.metamask.io/money?ref=CODE`. Complete any interstitial or unlock step. Verify the intended screen appears with the invite prefilled and the temporary document-level `ref` disappears from the URL. 2. From an interstitial, open Continue in a new tab and copy/paste its URL into another tab. Verify both preserve the invite code and destination. 3. Decline or dismiss the invite and verify the destination remains usable. Repeat and accept a valid offer. Check **Rewards Money Referral Offer Interacted** events across both screens and **Deep Link Used** with a regular `referral_code` property. 4. Repeat with an already-joined or ineligible wallet and verify the existing eligibility checks skip the invite. Verify malformed or duplicate `ref` values do not open it. 5. Follow a referral deep link through install and onboarding. Verify the invite appears over the intended destination after onboarding, unlock, and any interstitial. Verify it does not appear on those prerequisite screens. ## **Screenshots/Recordings** Captured using `yarn mm` and an isolated test wallet. This PR's captures use `013e6a0`; the explicitly labeled after-comparison uses `7fe9521` from #47682. Referral responses, eligibility/region state, and offer copy are mocked; cashback rates and dates are illustrative. These captures demonstrate the home and Money destination UI flows, not live backend registration or install/onboarding. The standalone Money-page referral recording uses a returning-user state with the Money introduction already dismissed. The comparison below instead shows a first Money visit with both dialogs opening together. ### Recordings #### First-visit sheet-priority comparison **Known limitation in this PR.** When the Money introduction and referral invite open together, their ordering can depend on mount timing and dismissal events can reach both dialogs. The fix is separate in the stacked #47682; the after-recording is comparison evidence, not behavior included in this PR. **Before: this PR, #47665 (`013e6a0`).** On a first Money visit, both dialogs mount. In this recording, the Money introduction covers the referral invite, and pressing Escape dismisses both dialogs instead of just the top one. https://github.com/user-attachments/assets/33e5b755-b699-4c26-a4ee-2fa91d4d14c6 **After: companion #47682 (`7fe9521`).** In the same first-visit scenario, the referral stays above the Money introduction and keeps code-input focus. Escape closes only the referral; the Money introduction remains open until separately dismissed. https://github.com/user-attachments/assets/7e7eabbb-ce32-4be9-9842-ad9c89616865 #### Referral flows in this PR **Money-page referral flow (returning user).** Follow `/money?ref=DEMO2026` through the security interstitial, review the prefilled invite over Money, accept it, and close the confirmation to remain on the Money page. https://github.com/user-attachments/assets/ed28c748-b36f-4596-a525-39ca30056027 **Accept an invite.** Continue past the security interstitial, review the prefilled referral code, accept the invite, and close the cashback confirmation to return to the destination. https://github.com/user-attachments/assets/c5b1b691-d30f-4f6b-a394-7c83b500c6b6 **Validation and rate-limit feedback.** Enter a rejected code, correct it, encounter a mocked rate-limit response, and choose Not now to return to the destination. https://github.com/user-attachments/assets/c84fe409-49e1-4342-be0c-2157ea74b4d5 **Dismiss an invite.** Close the invite without accepting it; the destination remains available. https://github.com/user-attachments/assets/8a1634d1-9b82-4353-a506-75a42b1fe32b ### Screenshots <details open> <summary>Open and accept an invite</summary> **Security interstitial.** The unsigned referral link still shows the third-party warning before Continue. <img width="1280" height="800" alt="Security interstitial with the third-party warning and Continue link" src="https://github.com/user-attachments/assets/bd42524b-b655-4674-930b-1e9da0e72f37" /> **Prefilled invite.** The referral code is carried to the home destination and prefilled in the invite sheet. <img width="1280" height="800" alt="Referral invite sheet over the home destination with DEMO2026 prefilled" src="https://github.com/user-attachments/assets/83483188-75ff-4fca-af3d-a4e3fe5f445b" /> **Acceptance confirmation.** A successful mocked registration opens the cashback-activated confirmation with sample offer dates. <img width="1280" height="800" alt="Cashback activation confirmation after accepting the test referral invite" src="https://github.com/user-attachments/assets/354abd03-0fc4-43a3-ae4e-e18a9508b3aa" /> **Destination after acceptance.** Closing the confirmation leaves the home screen usable without the invite. <img width="1280" height="800" alt="Home destination after closing the referral acceptance confirmation" src="https://github.com/user-attachments/assets/2fbe1f40-eb45-4e99-8e6f-e48f14435e69" /> </details> <details> <summary>Code validation and rate limiting</summary> **Rejected referral code.** An invalid-code response shows inline feedback and disables Accept invite. <img width="1280" height="800" alt="Referral invite with invalid-code feedback and Accept invite disabled" src="https://github.com/user-attachments/assets/43b60531-493b-4c03-b449-1b41ec40b9b0" /> **Corrected referral code.** Replacing the rejected code with a valid one clears the error and enables Accept invite again. <img width="1280" height="800" alt="Corrected referral code with the error cleared and Accept invite enabled" src="https://github.com/user-attachments/assets/fdd1c042-86fe-424a-acd0-cf38ce71fdd0" /> **Rate-limited acceptance.** A mocked HTTP 429 response shows retry feedback and temporarily disables acceptance. <img width="1280" height="800" alt="Referral invite showing rate-limit feedback with acceptance temporarily disabled" src="https://github.com/user-attachments/assets/c20dbafc-479b-4ad7-9e07-7695b8bc918f" /> </details> <details> <summary>Decline or dismiss without blocking the destination</summary> **Decline with Not now.** Declining closes the invite and returns to the existing destination. <img width="1280" height="800" alt="Home destination after declining the referral invite with Not now" src="https://github.com/user-attachments/assets/c17e63ea-f212-42bb-a9d8-b6d144550fed" /> **Before dismissal.** The invite remains dismissible through its close button. <img width="1280" height="800" alt="Open referral invite before dismissal with its close button available" src="https://github.com/user-attachments/assets/43160f02-dc0a-4053-bef1-a3407c39a592" /> **After dismissal.** Closing the invite leaves the home screen unobstructed and usable. <img width="1280" height="800" alt="Unobstructed home destination after dismissing the referral invite" src="https://github.com/user-attachments/assets/6db4c740-2131-4418-8fb6-74d7c3a76c34" /> </details> <details> <summary>Conditions that skip the invite</summary> **Already joined.** A mocked profile with the REFEREE role skips the invite and keeps the destination visible. <img width="1280" height="800" alt="Home destination without an invite for an already-joined test profile" src="https://github.com/user-attachments/assets/6564c670-b85e-4201-9b77-af30205fd541" /> **Restricted region.** A mocked excluded-country state skips the invite rather than blocking the destination. <img width="1280" height="800" alt="Home destination without an invite for a restricted-region test profile" src="https://github.com/user-attachments/assets/67f5a1af-72f4-4ef3-9e0d-18397b09b6d3" /> **Malformed referral parameter.** A link containing `ref=bad!` reaches the destination without opening an invite. <img width="1280" height="800" alt="Home destination without an invite after a link containing a malformed referral code" src="https://github.com/user-attachments/assets/10737fa0-d403-4618-a56d-91e4ba0e7ee3" /> </details> <!-- ### **Before** ### **After** --> ## **Pre-merge author checklist** - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Extension Coding Standards](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/CODING_GUIDELINES.md). - [x] I've completed the PR template to the best of my ability - [x] I’ve included tests if applicable - [x] I’ve documented my code using [JSDoc](https://jsdoc.app/) format if applicable - [x] I’ve applied the right labels on the PR (see [labeling guidelines](https://github.com/MetaMask/metamask-extension/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. ## **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. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes deep-link routing, startup URL handling, and onboarding completion navigation; security interstitial rules are preserved but referral metadata now flows through those paths. > > **Overview** > Adds end-to-end support for **Money referral codes** on internal deep links via a validated `ref` query param. > > **Deep links** normalize and attach `ref` with `withReferralCode` on direct extension destinations (router and interstitial Continue links) while keeping existing interstitial/security behavior. **Deep Link Used** analytics gain `referral_code`; malformed or duplicate `ref` values are dropped. > > **UI startup** reads the temporary document `?ref=`, stores it as `pendingReferralCode` in Redux (`consumeReferralCode` on boot), and **`ReferralInvite`** in root layout opens the existing **AcceptInviteSheet** over the destination when rewards are enabled. Deferred links after onboarding set the same pending code. Referral input normalization moves to shared `money-referral-code` helpers. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9c5f618. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY --> --------- Co-authored-by: Baptiste Marchand <75846779+baptiste-marchand@users.noreply.github.com>
1 parent b469544 commit 6870129

24 files changed

Lines changed: 445 additions & 39 deletions

‎app/scripts/lib/deep-links/deep-link-router.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import EventEmitter from 'events';
22
import browser from 'webextension-polyfill';
33
import log from 'loglevel';
4+
import { withReferralCode } from '#shared/lib/deep-links/referral';
45
import { isManifestV3 } from '../../../../shared/lib/mv3.utils';
56
import {
67
type ParsedDeepLink,
@@ -211,6 +212,7 @@ export class DeepLinkRouter extends EventEmitter<{
211212
parsed.destination.path,
212213
parsed.destination.query.toString(),
213214
);
215+
link = withReferralCode(link, url.searchParams);
214216
}
215217
} else {
216218
// unable to parse, show error page

‎app/scripts/lib/deep-links/deep-link.router.test.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,40 @@ describe('DeepLinkRouter', () => {
122122
router.install();
123123
});
124124

125+
it.each([
126+
{
127+
initiator: 'https://metamask.io',
128+
expectedUrl:
129+
'chrome-extension://extension-id/home.html?ref=ABC123#/money?asset=ETH',
130+
},
131+
{
132+
initiator: undefined,
133+
expectedUrl:
134+
'chrome-extension://extension-id/home.html#link?u=%2Fmoney%3Fref%3Dabc123%26unsigned%3Dignored',
135+
},
136+
])(
137+
'uses the existing security policy for referral links from $initiator',
138+
async ({ initiator, expectedUrl }) => {
139+
parseMock.mockResolvedValue({
140+
signature: 'missing',
141+
destination: {
142+
path: '/money',
143+
query: new URLSearchParams('asset=ETH'),
144+
},
145+
} as ParsedDeepLink);
146+
147+
await onBeforeRequest?.({
148+
tabId: 1,
149+
url: 'https://link.metamask.io/money?ref=abc123&unsigned=ignored',
150+
initiator,
151+
} as browser.WebRequest.OnBeforeRequestDetailsType);
152+
153+
expect(browser.tabs.update).toHaveBeenCalledWith(1, {
154+
url: expectedUrl,
155+
});
156+
},
157+
);
158+
125159
it.each([false, true, undefined])(
126160
'handles a signed direct destination when onboarding completion is %s',
127161
async (completedOnboarding) => {

‎shared/lib/deep-links/metrics.test.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,15 @@ describe('shouldTrackDeepLinkNavigation', () => {
2929
});
3030

3131
describe('createEvent', () => {
32+
it('omits malformed referrals from analytics', () => {
33+
const result = createEvent({
34+
signature: MISSING,
35+
url: new URL('https://link.metamask.io/money?ref=ABC&ref=DEF'),
36+
});
37+
38+
expect(result.properties).not.toHaveProperty('referral_code');
39+
expect(result.sensitiveProperties).not.toHaveProperty('ref');
40+
});
3241
describe('basic functionality', () => {
3342
it('should create event with minimal required properties', () => {
3443
const url = new URL('https://example.com/test-route');
@@ -127,15 +136,16 @@ describe('createEvent', () => {
127136
expect(result.properties.utm_term).toBe('crypto-wallet');
128137
});
129138

130-
it('should handle referral as a standard attribution property', () => {
139+
it('handles referral codes as standard attribution properties', () => {
131140
const url = new URL(
132-
'https://example.com/test?referral=ABC123&customParam=secret-value',
141+
'https://example.com/test?referral=ABC123&ref=%20def456%20&customParam=secret-value',
133142
);
134143
const signature = MISSING;
135144

136145
const result = createEvent({ signature, url });
137146

138147
expect(result.properties.referral).toBe('ABC123');
148+
expect(result.properties.referral_code).toBe('DEF456');
139149
expect(result.sensitiveProperties).toStrictEqual({
140150
customParam: 'secret-value',
141151
});

‎shared/lib/deep-links/metrics.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { getReferralCode } from '#shared/lib/deep-links/referral';
12
import { createEventBuilder } from '../analytics/create-event-builder';
23
import type { AnalyticsEvent } from '../analytics/create-event-builder';
34
import {
@@ -15,6 +16,8 @@ export type Properties = {
1516
// eslint-disable-next-line @typescript-eslint/naming-convention
1617
attribution_id?: string;
1718
referral?: string;
19+
// eslint-disable-next-line @typescript-eslint/naming-convention -- analytics property
20+
referral_code?: string;
1821
} & { [key in UTMParameter]?: string };
1922

2023
export type EventDetails = {
@@ -41,8 +44,7 @@ export function shouldTrackDeepLinkNavigation({
4144
/**
4245
* Creates a trackable analytics event representing deep link usage.
4346
*
44-
* If the route has query params, and the query params have duplicate keys,
45-
* only the last value will be used in the properties.
47+
* Repeated parameters use the last value, except `ref`, which must be unique.
4648
*
4749
* @param route - The parameters for the tracking event.
4850
* @param route.url - The original full URL of the deep link.
@@ -53,13 +55,14 @@ export function createEvent({ signature, url }: EventDetails): AnalyticsEvent {
5355
const properties: Properties = {
5456
route: url.pathname,
5557
signature,
58+
// eslint-disable-next-line @typescript-eslint/naming-convention -- analytics property
59+
referral_code: getReferralCode(url.searchParams) ?? undefined,
5660
};
5761
const sensitiveProperties: Record<string, string> = {};
5862

5963
for (const [key, value] of url.searchParams.entries()) {
60-
if (key === 'sig') {
61-
// don't need to include the signature itself in the properties, utm
62-
// params are much more useful, so `sig` would be redundant.
64+
if (key === 'sig' || key === 'ref') {
65+
// Signatures are redundant; referral metadata is handled above.
6366
continue;
6467
}
6568

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { it as jestIt } from '@jest/globals';
2+
import {
3+
getReferralCode,
4+
withReferralCode,
5+
} from '#shared/lib/deep-links/referral';
6+
7+
describe('getReferralCode', () => {
8+
jestIt.each([
9+
[' a1b ', 'A1B'],
10+
['a'.repeat(24), 'A'.repeat(24)],
11+
])('normalizes a valid code: %s', (input, expected) => {
12+
expect(getReferralCode(new URLSearchParams({ ref: input }))).toBe(expected);
13+
});
14+
15+
jestIt.each([
16+
'',
17+
'ref=ab',
18+
'ref=ABC-123',
19+
'ref=ABC&ref=DEF',
20+
`ref=${'A'.repeat(25)}`,
21+
])('ignores malformed or ambiguous input: %s', (query) => {
22+
expect(getReferralCode(new URLSearchParams(query))).toBeNull();
23+
});
24+
});
25+
26+
describe('withReferralCode', () => {
27+
it('carries the code outside the product route without changing its parameters', () => {
28+
const params = new URLSearchParams('ref=abc123&unsigned=ignored');
29+
const result = withReferralCode('scheme://id/home.html?a=v#/r?t=E', params);
30+
expect(result).toBe('scheme://id/home.html?a=v&ref=ABC123#/r?t=E');
31+
});
32+
33+
it('preserves the destination when there is no valid referral', () => {
34+
const destination = 'scheme://id/home.html#/m';
35+
const route = withReferralCode(destination, new URLSearchParams('ref=???'));
36+
expect(route).toBe(destination);
37+
});
38+
});

‎shared/lib/deep-links/referral.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import {
2+
MONEY_REFERRAL_CODE_MIN_LENGTH,
3+
normalizeMoneyReferralCode,
4+
} from '#shared/lib/money-referral-code';
5+
6+
/**
7+
* Reads a referral without turning malformed or ambiguous input into a code.
8+
*
9+
* @param params - Parameters from the original deep link.
10+
* @returns The normalized code, or null when absent or invalid.
11+
*/
12+
export function getReferralCode(params: URLSearchParams): string | null {
13+
const values = params.getAll('ref');
14+
const code = values.length === 1 ? values[0].trim().toUpperCase() : '';
15+
return code.length >= MONEY_REFERRAL_CODE_MIN_LENGTH &&
16+
normalizeMoneyReferralCode(code) === code
17+
? code
18+
: null;
19+
}
20+
21+
/**
22+
* Carries a referral outside the extension's hash route for startup to consume.
23+
*
24+
* @param extensionUrl - The internal destination URL, after deep-link parsing.
25+
* @param params - Parameters from the original deep link, before canonicalization.
26+
* @returns The destination with temporary document-level referral metadata.
27+
*/
28+
export function withReferralCode(
29+
extensionUrl: string,
30+
params: URLSearchParams,
31+
): string {
32+
const code = getReferralCode(params);
33+
if (!code) {
34+
return extensionUrl;
35+
}
36+
const url = new URL(extensionUrl);
37+
url.searchParams.set('ref', code);
38+
return url.toString();
39+
}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
import { normalizeMoneyReferralCode } from '#shared/lib/money-referral-code';
2+
3+
describe('normalizeMoneyReferralCode', () => {
4+
it('cleans partial text-field input', () => {
5+
expect(normalizeMoneyReferralCode('a-b!')).toBe('AB');
6+
});
7+
8+
it('caps editable input at 24 characters', () => {
9+
expect(normalizeMoneyReferralCode('a'.repeat(25))).toBe('A'.repeat(24));
10+
});
11+
});

‎shared/lib/money-referral-code.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
export const MONEY_REFERRAL_CODE_MIN_LENGTH = 3;
2+
3+
/**
4+
* Cleans editable input, allowing partial codes while the user types.
5+
*
6+
* @param value - Raw text-field input.
7+
* @returns Uppercase letters and digits, capped at the supported length.
8+
*/
9+
export function normalizeMoneyReferralCode(value: string): string {
10+
return value
11+
.toUpperCase()
12+
.replace(/[^A-Z0-9]/gu, '')
13+
.slice(0, 24);
14+
}

‎test/e2e/tests/settings/state-logs.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1374,6 +1374,7 @@
13741374
}
13751375
},
13761376
"rewardsMoney": {
1377+
"pendingReferralCode": "null",
13771378
"referralMe": "null",
13781379
"referralMeSettled": "boolean"
13791380
},

‎ui/components/app/rewards/money-referral/AcceptInviteSheet.tsx‎

Lines changed: 1 addition & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import {
2222
TextFieldSize,
2323
TextVariant,
2424
} from '@metamask/design-system-react';
25+
import { normalizeMoneyReferralCode } from '#shared/lib/money-referral-code';
2526
import {
2627
MetaMetricsEventCategory,
2728
MetaMetricsEventName,
@@ -49,8 +50,6 @@ import { REWARDS_MONEY_INVITE_ALLOWED_CAPABILITIES } from '../../../../hooks/rew
4950
import { RouteMessengerProvider } from '../../../../contexts/route-messenger';
5051
import { ReferralActivatedModal } from './ReferralActivatedModal';
5152

52-
const MONEY_REFERRAL_CODE_MAX_LENGTH = 24;
53-
5453
const MONEY_REFERRAL_CODE_ERROR_ID = 'money-referral-code-error';
5554

5655
type Translate = (key: string) => string;
@@ -88,19 +87,6 @@ const referralCodeInputProps = {
8887
'data-testid': 'money-referral-code-input',
8988
};
9089

91-
/**
92-
* Keeps letters and digits, uppercases them, and caps the length at 24.
93-
*
94-
* @param value - Raw code from the route or the text field.
95-
* @returns The normalized code.
96-
*/
97-
function normalizeMoneyReferralCode(value: string): string {
98-
return value
99-
.toUpperCase()
100-
.replace(/[^A-Z0-9]/gu, '')
101-
.slice(0, MONEY_REFERRAL_CODE_MAX_LENGTH);
102-
}
103-
10490
type AcceptInviteSheetProps = {
10591
initialCode: string;
10692
onClose: () => void;

0 commit comments

Comments
 (0)