Skip to content

Commit 803491c

Browse files
authored
fix(rewards): guard pending referral acceptance (#47668)
## **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: #47622, #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 #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 -->
1 parent 95528ad commit 803491c

5 files changed

Lines changed: 261 additions & 35 deletions

File tree

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

Lines changed: 70 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { configureStore } from '@reduxjs/toolkit';
44
import { Provider } from 'react-redux';
55
import { act, fireEvent, render } from '@testing-library/react';
66
import { userEvent } from '@testing-library/user-event';
7+
import { withResolvers } from '#shared/lib/promise-with-resolvers';
78
import type { ReferralMeDto } from '../../../../../shared/types/rewards-money';
89
import { enLocale as messages } from '../../../../../test/lib/i18n-helpers';
910
import { AcceptInviteSheet } from './AcceptInviteSheet';
@@ -68,7 +69,7 @@ const mockReferralState: {
6869
const mockT = (key: string) =>
6970
(
7071
({
71-
close: 'Close',
72+
close: messages.close.message,
7273
rewardsMoneyReferralCodeError: 'Invalid referral code',
7374
rewardsMoneyReferralCodeUnknownError:
7475
'Referral code couldn’t be validated.',
@@ -407,6 +408,71 @@ describe('AcceptInviteSheet', () => {
407408
}
408409
});
409410

411+
it.each(['validation', 'registration'] as const)(
412+
'waits for pending %s before allowing dismissal',
413+
async (phase) => {
414+
const validation = withResolvers<string>();
415+
const registration = withResolvers<void>();
416+
if (phase === 'validation') {
417+
mockValidation.validateCode.mockReturnValue(validation.promise);
418+
} else {
419+
mockRegister.mockReturnValue(registration.promise);
420+
}
421+
const view = renderSheet();
422+
423+
await act(async () => {
424+
fireEvent.click(view.getByTestId('money-referral-accept'));
425+
});
426+
expect(view.getByTestId('money-referral-accept')).toBeDisabled();
427+
expect(view.getByTestId('money-referral-decline')).toBeDisabled();
428+
expect(view.getByTestId('money-referral-code-input')).toBeDisabled();
429+
expect(
430+
view.getByRole('button', { name: messages.close.message }),
431+
).toBeDisabled();
432+
fireEvent.keyDown(document, { key: 'Escape' });
433+
fireEvent.click(view.getByTestId('money-referral-decline'));
434+
expect(view.onClose).not.toHaveBeenCalled();
435+
expect(trackedTypes()).toEqual(['viewed']);
436+
437+
await act(async () => {
438+
if (phase === 'validation') {
439+
validation.resolve('');
440+
} else {
441+
registration.resolve();
442+
}
443+
});
444+
445+
expect(view.getByTestId('money-referral-activated')).toBeInTheDocument();
446+
expect(trackedTypes()).toEqual(['viewed', 'accepted']);
447+
},
448+
);
449+
450+
it.each(['registration', 'read-back'] as const)(
451+
'does not track acceptance when %s finishes after unmount',
452+
async (phase) => {
453+
const pending = withResolvers<void>();
454+
if (phase === 'registration') {
455+
mockRegister.mockReturnValue(pending.promise);
456+
} else {
457+
mockReferralState.fetch.mockReturnValue(pending.promise);
458+
}
459+
const view = renderSheet();
460+
await act(async () => {
461+
fireEvent.click(view.getByTestId('money-referral-accept'));
462+
});
463+
expect(mockReferralState.fetch).toHaveBeenCalledTimes(
464+
phase === 'read-back' ? 1 : 0,
465+
);
466+
view.unmount();
467+
468+
await act(async () => {
469+
pending.resolve();
470+
});
471+
472+
expect(trackedTypes()).toEqual(['viewed']);
473+
},
474+
);
475+
410476
it('records a refused accept without locking a later answer', async () => {
411477
const user = userEvent.setup();
412478
mockRegister.mockRejectedValueOnce({
@@ -420,6 +486,9 @@ describe('AcceptInviteSheet', () => {
420486
});
421487

422488
expect(trackedTypes()).toEqual(['viewed', 'refused']);
489+
expect(
490+
view.getByRole('button', { name: messages.close.message }),
491+
).toBeEnabled();
423492
expect(mockTrackEvent).toHaveBeenCalledWith(
424493
expect.objectContaining({
425494
properties: expect.objectContaining({

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

Lines changed: 22 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,14 @@ const AcceptInviteSheetContent = ({
125125
const [acceptStarted, setAcceptStarted] = useState(false);
126126
const hasTrackedViewRef = useRef(false);
127127
const hasRespondedRef = useRef(false);
128+
const mountedRef = useRef(true);
129+
130+
useEffect(() => {
131+
mountedRef.current = true;
132+
return () => {
133+
mountedRef.current = false;
134+
};
135+
}, []);
128136

129137
const acceptAllowedForGeo = useSelector(selectMoneyReferralAllowedForGeo);
130138
const geoLoading = useSelector(selectOptinAllowedForGeoLoading);
@@ -274,20 +282,29 @@ const AcceptInviteSheetContent = ({
274282
}, [onClose, shouldDismissForGeo, trackResponded]);
275283

276284
const handleDecline = useCallback(() => {
285+
if (isAccepting) {
286+
return;
287+
}
277288
trackResponded('declined');
278289
onClose();
279-
}, [onClose, trackResponded]);
290+
}, [isAccepting, onClose, trackResponded]);
280291

281292
const handleDismiss = useCallback(() => {
293+
if (isAccepting) {
294+
return;
295+
}
282296
trackResponded('dismissed');
283297
onClose();
284-
}, [onClose, trackResponded]);
298+
}, [isAccepting, onClose, trackResponded]);
285299

286300
const handleAccept = useCallback(() => {
287301
setAcceptStarted(true);
288302
setHasSeenEligibleInvite(true);
289303
accept(code)
290304
.then((result) => {
305+
if (!mountedRef.current) {
306+
return;
307+
}
291308
if (result.accepted) {
292309
trackResponded('accepted');
293310
return;
@@ -321,7 +338,7 @@ const AcceptInviteSheetContent = ({
321338
<ModalContent className="items-center" size={ModalContentSize.Md}>
322339
<ModalHeader
323340
onClose={handleDismiss}
324-
closeButtonProps={{ ariaLabel: t('close') }}
341+
closeButtonProps={{ ariaLabel: t('close'), isDisabled: isAccepting }}
325342
>
326343
{copy.title}
327344
</ModalHeader>
@@ -347,6 +364,7 @@ const AcceptInviteSheetContent = ({
347364
value={code}
348365
size={TextFieldSize.Lg}
349366
isError={Boolean(fieldError)}
367+
isDisabled={isAccepting}
350368
className="h-14 w-full"
351369
onChange={(event) => {
352370
setCode(normalizeMoneyReferralCode(event.target.value));
@@ -390,6 +408,7 @@ const AcceptInviteSheetContent = ({
390408
size={ButtonSize.Lg}
391409
isFullWidth
392410
onClick={handleDecline}
411+
isDisabled={isAccepting}
393412
className="text-default"
394413
data-testid="money-referral-decline"
395414
>

‎ui/hooks/rewards/useAcceptMoneyReferralCode.test.tsx‎

Lines changed: 118 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,10 @@ import { it } from '@jest/globals';
22
import React from 'react';
33
import { configureStore } from '@reduxjs/toolkit';
44
import { Provider } from 'react-redux';
5-
import { act, render } from '@testing-library/react';
5+
import { act, render, renderHook } from '@testing-library/react';
6+
import { withResolvers } from '#shared/lib/promise-with-resolvers';
67
import { useAcceptMoneyReferralCode } from './useAcceptMoneyReferralCode';
8+
import { refreshReferralMeWithRetries } from './useReferralMe';
79

810
const mockRegister = jest.fn();
911
const acceptMessenger = {
@@ -94,6 +96,121 @@ describe('useAcceptMoneyReferralCode', () => {
9496
mockRegister.mockReset();
9597
});
9698

99+
it('does not register when validation completes after unmount', async () => {
100+
const validation = withResolvers<string>();
101+
const onAccepted = jest.fn();
102+
const { result, unmount } = renderHook(() =>
103+
useAcceptMoneyReferralCode({
104+
validateCode: () => validation.promise,
105+
fetchReferralMe: async () => ({ status: 'settled' }),
106+
onAccepted,
107+
}),
108+
);
109+
let accepting!: ReturnType<typeof result.current.accept>;
110+
act(() => {
111+
accepting = result.current.accept('CODE');
112+
});
113+
unmount();
114+
115+
await act(async () => {
116+
validation.resolve('');
117+
await accepting;
118+
});
119+
120+
expect(mockRegister).not.toHaveBeenCalled();
121+
expect(onAccepted).not.toHaveBeenCalled();
122+
});
123+
124+
it.each(['resolve', 'reject'] as const)(
125+
'ignores a registration that finishes after unmount: %s',
126+
async (outcome) => {
127+
const registration = withResolvers<void>();
128+
mockRegister.mockReturnValue(registration.promise);
129+
const onAccepted = jest.fn();
130+
const { result, unmount } = renderHook(() =>
131+
useAcceptMoneyReferralCode({
132+
validateCode: async () => '',
133+
fetchReferralMe: async () => ({ status: 'settled' }),
134+
onAccepted,
135+
}),
136+
);
137+
let accepting!: ReturnType<typeof result.current.accept>;
138+
await act(async () => {
139+
accepting = result.current.accept('CODE');
140+
});
141+
expect(mockRegister).toHaveBeenCalledTimes(1);
142+
unmount();
143+
144+
await act(async () => {
145+
if (outcome === 'resolve') {
146+
registration.resolve();
147+
} else {
148+
registration.reject({ data: { status: 429, retryAfterSeconds: 2 } });
149+
}
150+
await accepting;
151+
});
152+
153+
expect(onAccepted).not.toHaveBeenCalled();
154+
expect(await accepting).not.toHaveProperty('refusalReason');
155+
},
156+
);
157+
158+
it('ignores another Accept while validation is pending', async () => {
159+
const validation = withResolvers<string>();
160+
const validateCode = jest.fn(() => validation.promise);
161+
const onAccepted = jest.fn();
162+
const { result } = renderHook(() =>
163+
useAcceptMoneyReferralCode({
164+
validateCode,
165+
fetchReferralMe: async () => ({ status: 'settled' }),
166+
onAccepted,
167+
}),
168+
);
169+
170+
await act(async () => {
171+
const first = result.current.accept('CODE');
172+
const second = result.current.accept('OTHER');
173+
validation.resolve('');
174+
await Promise.all([first, second]);
175+
});
176+
177+
expect(validateCode).toHaveBeenCalledTimes(1);
178+
expect(mockRegister).toHaveBeenCalledTimes(1);
179+
expect(mockRegister).toHaveBeenCalledWith({ code: 'CODE' });
180+
expect(onAccepted).toHaveBeenCalledTimes(1);
181+
});
182+
183+
it('blocks another Accept during read-back and ignores completion after unmount', async () => {
184+
const readBack = withResolvers<void>();
185+
jest
186+
.mocked(refreshReferralMeWithRetries)
187+
.mockReturnValueOnce(readBack.promise);
188+
const onAccepted = jest.fn();
189+
const { result, unmount } = renderHook(() =>
190+
useAcceptMoneyReferralCode({
191+
validateCode: async () => '',
192+
fetchReferralMe: async () => ({ status: 'settled' }),
193+
onAccepted,
194+
}),
195+
);
196+
let accepting!: ReturnType<typeof result.current.accept>;
197+
await act(async () => {
198+
accepting = result.current.accept('CODE');
199+
});
200+
expect(result.current.isAccepting).toBe(true);
201+
expect(onAccepted).not.toHaveBeenCalled();
202+
expect(await result.current.accept('OTHER')).toEqual({ accepted: false });
203+
expect(mockRegister).toHaveBeenCalledTimes(1);
204+
unmount();
205+
206+
await act(async () => {
207+
readBack.resolve();
208+
await accepting;
209+
});
210+
211+
expect(onAccepted).not.toHaveBeenCalled();
212+
});
213+
97214
it.each([
98215
[422, '', 'rewardsMoneyReferralCodeError'],
99216
[409, '', 'rewardsMoneyReferralAlreadyReferred'],

0 commit comments

Comments
 (0)