Repository navigation
feat(rewards): open referral invites from deep links - #47665
Conversation
|
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. |
✨ Files requiring CODEOWNER review ✨🕵️ @MetaMask/extension-privacy-reviewers (1 files, +1 -0)
🧪 @MetaMask/qa (1 files, +1 -0)
🔐 @MetaMask/web3auth (2 files, +16 -4)
|
Builds ready [013e6a0]
⚡ Performance Benchmarks (Total: 🟢 8 pass · 🟡 3 warn · 🔴 2 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
Builds ready [adaad9c]
⚡ Performance Benchmarks (Total: 🟢 5 pass · 🟡 5 warn · 🔴 3 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
Builds ready [8dfc210]
⚡ Performance Benchmarks (Total: 🟢 4 pass · 🟡 6 warn · 🔴 3 fail)
Bundle Size Diffs [🚨 Warning! Bundle size has increased!]
|
## **Description** Closing a referral invite while Accept is pending can submit registration after the sheet unmounts or record dismissal before a successful acceptance. Repeated Accept calls can also start duplicate registrations. Keep one Accept attempt active through validation, registration, and the read-back. Disable editing and decline while it runs, ignore dismissal, and prevent late work from submitting after validation or updating the UI and analytics after unmount. Validation: 51 tests passed across five related suites; changed-file lint and circular dependency checks passed. The full project typecheck reports errors in unchanged MCP, Discover, and perps files; none were reported for the four changed files. Manual testing is pending. ## **Changelog** CHANGELOG entry: Fixed referral invitations allowing dismissal or duplicate submission while acceptance was pending. ## **Related issues** Related: MetaMask#47622, MetaMask#47665. This fix is independent of referral deep-link routing. ## **Manual testing steps** 1. Use a development build containing this fix and the referral entry flow from MetaMask#47665. Enable Basic Functionality and Money rewards, then open an invite with an eligible profile and a valid test code. 2. Throttle validation and registration requests. Press Accept, then try editing the code, accepting again, declining, and closing the sheet. Verify the sheet stays open, editing/Accept/Decline are disabled, and only one registration is submitted. 3. Let registration finish. Verify the activation screen opens and the offer records acceptance without an intervening dismissal. Repeat with an API refusal and verify retry and dismissal become available afterward. 4. Lock the wallet while validation or registration is pending. Let the request settle and unlock. Verify validation does not start registration after the invite unmounts and late callbacks do not reopen the activation screen or emit offer interactions from the old sheet. ## **Screenshots/Recordings** Not captured locally. <!-- ### **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** > Touches referral registration and MetaMetrics interaction timing; behavior is constrained by new guards and tests but still affects rewards onboarding UX. > > **Overview** > Fixes a race where users could dismiss the money referral invite or tap **Accept** again while validation, registration, or referral-me read-back was still running—leading to duplicate registrations, dismissal recorded before success, or analytics/UI updates after the sheet unmounted. > > `useAcceptMoneyReferralCode` now treats **`isAccepting` as true for the whole flow** (not just registration), blocks overlapping `accept` calls via `acceptingRef`, and **bails out of register, read-back, `onAccepted`, and state updates** when the hook unmounts mid-flight. `AcceptInviteSheet` **disables close, decline, code input, and dismiss handlers** while accepting and **skips acceptance tracking** if the component unmounted before the promise settles. > > Hook and sheet tests add coverage for pending validation/registration, post-unmount completion, and duplicate Accept. **`useTokenInsightsData.test.ts`** only adjusts Redux selector mocking/assertion ordering (no product change). > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit ce0a9b9. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
|
## **Description** Opening an internal deep link before wallet onboarding is complete loses the intended destination and finishes on Home. Retain the internal route in the existing UI state before redirecting to onboarding, then resume and clear it when setup finishes. The latest saved direct destination in the current UI session takes precedence over the install-time deferred destination. Preserve its query and fragment, and keep it in that UI when the side panel is enabled. No cross-tab synchronization is added. The social-import unlock path also retains its saved direct destination. Keep install attribution and the deferred `DeepLinkUsed` event, including attribution and campaign parameters, even when a later direct link supplies the action. Without a saved direct destination, deferred navigation and its required interstitial remain the fallback. A saved direct destination also supersedes a pending deferred interstitial; the requester identified themselves as the Extension Security team and approved this behavior in the implementation conversation. Validly signed direct links also skip the interstitial while local onboarding state is explicitly incomplete, matching the existing behavior for signed deferred links. Unsigned or invalidly signed links and links received after onboarding retain the existing policy. The requester identified themselves as a member of Extension Security and explicitly approved this pre-onboarding exception in the implementation conversation, clarifying that it applies only to valid signatures in both flows. Validation: 94 tests passed across five onboarding, routing, and unlock suites; full TypeScript checking, changed-file lint, and circular dependency checks passed. Both social-import completion-failure regression cases failed before the retry fix and passed afterward; automatic completion retry is also covered. Earlier signed-link onboarding regressions remain covered. Manual testing is pending. ## **Changelog** CHANGELOG entry: Fixed direct deep-link destinations being lost during onboarding and removed the extra pre-onboarding warning for validly signed links. ## **Related issues** Fixes MetaMask#47667 Jira: [MWPE-805](https://consensyssoftware.atlassian.net/browse/MWPE-805) Related: MetaMask#47665. This fix does not depend on referral functionality. ## **Manual testing steps** 1. In a fresh extension profile, leave onboarding incomplete and open `https://link.metamask.io/privacy`. Continue through the existing security warning, then finish wallet setup. Verify Privacy & Security opens at the MetaMetrics section instead of Home. 2. Start with an install-time deferred link containing attribution and campaign parameters. Before finishing onboarding, open a different direct destination in the same UI. Complete setup and verify the later destination opens. With metrics enabled, verify install attribution and the deferred `DeepLinkUsed` event retain the original link's attribution and campaign parameters. 3. Repeat with a deferred link that would require an interstitial. Verify the later direct destination supersedes that deferred action, and the direct link's own security warning still appears when required. 4. Repeat with the side-panel experience enabled. Verify the later destination opens in the UI that received it. Ordinary onboarding without a direct destination keeps its usual side-panel behavior. 5. Repeat through social import, including unlock/rehydration, and verify the saved direct destination is retained. For a supported link with product parameters, verify its query and scroll fragment survive setup. 6. Open another direct destination in the same UI before completion and verify the last one is used. Completing onboarding in a separate UI does not inherit that destination. If completion fails, retry and verify the destination remains available. 7. Repeat the install-attribution deferred-link flow without a later direct destination. Verify its destination and any required security warning remain the fallback. 8. With the interstitial opt-out disabled, open a validly signed direct link before onboarding is complete. Verify setup opens without a security warning and resumes the destination afterward. Repeat after onboarding and verify the normal warning appears. Repeat with unsigned and invalidly signed links before onboarding and verify the existing warning behavior remains. ## **Screenshots/Recordings** Not captured locally. <!-- ### **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. [MWPE-805]: https://consensyssoftware.atlassian.net/browse/MWPE-805?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Changes onboarding navigation, deep-link interstitial policy, and security-boundary logic for signed links before onboarding completes; mistakes could mis-route users or weaken warnings. > > **Overview** > Fixes **direct deep links being dropped** when the wallet is still onboarding by introducing session-scoped **`onboardingRedirect`** UI state. `RequireAuthenticated` saves the full internal path (query/hash) before sending users to onboarding; completion paths in **`useOnboardingCompletion`**, **`onboarding-flow`**, and unlock/social-import flows **resume that route** and clear it, with the saved direct destination **beating** install-time deferred deep links while still emitting deferred **DeepLinkUsed** attribution. > > The deep-link **security policy** now consults **`completedOnboarding`**: **valid signed** intercepted links skip the interstitial only while onboarding is explicitly incomplete; unsigned/invalid links and post-onboarding behavior stay unchanged. The router lazily reads controller state once per intercept for this check. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit c153a3b. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
Replaced by a newer auto-merge request
Auto-merge was disabled for another pull request in the stack
| * @returns The normalized code, or null when absent or invalid. | ||
| */ | ||
| export function getReferralCode(params: URLSearchParams): string | null { | ||
| const values = params.getAll('ref'); |
There was a problem hiding this comment.
Looks like a referral code appended to a link MetaMask signed with a sig_params list that leaves out ref would still verify, and the invite would open prefilled with that code. If I'm reading the policy right, there'd be no interstitial when the user skips it or hasn't finished onboarding, and otherwise it reads "Redirecting to MetaMask".
Would it make sense to have getReferralCode skip ref when the link's sig_params doesn't list it? Something like:
| const values = params.getAll('ref'); | |
| const signedParams = params.get('sig_params'); | |
| const values = | |
| signedParams === null || signedParams.split(',').includes('ref') | |
| ? params.getAll('ref') | |
| : []; |



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_codeas a regular property on Deep Link Used.Validation after updating main:
pendingReferralCode.Changelog
CHANGELOG entry: Added referral invitations to deep links, including links restored after onboarding.
Related issues
Related: #47622
Manual testing steps
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-levelrefdisappears from the URL.referral_codeproperty.refvalues do not open it.Screenshots/Recordings
Captured using
yarn mmand an isolated test wallet. This PR's captures use013e6a0; the explicitly labeled after-comparison uses7fe9521from #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.05-sheet-priority-before-47665.webm
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.06-sheet-priority-after-47682.webm
Referral flows in this PR
Money-page referral flow (returning user). Follow
/money?ref=DEMO2026through the security interstitial, review the prefilled invite over Money, accept it, and close the confirmation to remain on the Money page.04-money-page-referral.webm
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.
01-accept-referral.webm
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.
02-validation-and-rate-limit.webm
Dismiss an invite. Close the invite without accepting it; the destination remains available.
03-dismiss-referral.webm
Screenshots
Open and accept an invite
Security interstitial. The unsigned referral link still shows the third-party warning before Continue.
Prefilled invite. The referral code is carried to the home destination and prefilled in the invite sheet.
Acceptance confirmation. A successful mocked registration opens the cashback-activated confirmation with sample offer dates.
Destination after acceptance. Closing the confirmation leaves the home screen usable without the invite.
Code validation and rate limiting
Rejected referral code. An invalid-code response shows inline feedback and disables Accept invite.
Corrected referral code. Replacing the rejected code with a valid one clears the error and enables Accept invite again.
Rate-limited acceptance. A mocked HTTP 429 response shows retry feedback and temporarily disables acceptance.
Decline or dismiss without blocking the destination
Decline with Not now. Declining closes the invite and returns to the existing destination.
Before dismissal. The invite remains dismissible through its close button.
After dismissal. Closing the invite leaves the home screen unobstructed and usable.
Conditions that skip the invite
Already joined. A mocked profile with the REFEREE role skips the invite and keeps the destination visible.
Restricted region. A mocked excluded-country state skips the invite rather than blocking the destination.
Malformed referral parameter. A link containing
ref=bad!reaches the destination without opening an invite.Pre-merge author checklist
Pre-merge reviewer checklist
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
refquery param.Deep links normalize and attach
refwithwithReferralCodeon direct extension destinations (router and interstitial Continue links) while keeping existing interstitial/security behavior. Deep Link Used analytics gainreferral_code; malformed or duplicaterefvalues are dropped.UI startup reads the temporary document
?ref=, stores it aspendingReferralCodein Redux (consumeReferralCodeon boot), andReferralInvitein 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 sharedmoney-referral-codehelpers.Reviewed by Cursor Bugbot for commit 9c5f618. Bugbot is set up for automated code reviews on this repo. Configure here.