Skip to content

Commit 721934e

Browse files
authored
feat(card): add Money Account card linkage hook and inline background linking from Money home (#30057)
<!-- Please submit this PR as a draft initially. Do not mark it as "Ready for review" until this PR meets the canonical Definition of Ready For Review in `docs/readme/ready-for-review.md`. In short: the template must be materially complete (not just section titles present), all status checks must be currently passing, and the only expected follow-up commits must be reviewer-driven. --> ## **Description** <!-- Write a short description of the changes included in this pull request, also include relevant motivation and context. Have in mind the following questions: 1. What is the reason for the change? 2. What is the improvement/solution? --> This is the **B2 hook + inline-trigger** branch of the Money Account ↔ Card linkage stack, stacked on top of [#30000 (B1 foundation)](#30000). B1 delivered the `CardController.linkMoneyAccountCard` orchestration; B2 adds the thin UI layer that drives it from the Money home screen. ### Why After B1, the wallet has a fully-orchestrated, race-safe Money Account → Card linkage flow in the controller, but it is only invoked from one wallet path (`useCardDelegation` for the Spending Limit screen). The Money home "Link card" CTA still navigated the user out to `CARD.HOME`, which forced an extra screen + tap even when the user already had everything needed to link in-place (cardholder + authenticated card session + a primary Money Account on a supported chain). This PR introduces a dedicated UI hook so any screen can: - ask the question "is this user ready to link a Card to their Money Account right now?" (`canLink`), and - trigger that linkage as a background operation that owns its own toast UX (`linkInBackground`). This unblocks B3 (`SpendingLimit` fixed-MA option + `linkInteractive`) without requiring `SpendingLimit` to know anything about toast plumbing or selector composition. ### What | Layer | Change | | --- | --- | | **`useMoneyAccountCardLinkage` hook** (new) | UI-only hook wrapping `Engine.context.CardController.linkMoneyAccountCard`. Exposes `linkInBackground()`, `status`, `isLinking`, `error`, `reset`, plus the derived prerequisites (`hasMoneyAccountRequirements`, `isCardAuthenticated`, `primaryMoneyAccount`, `moneyAccountCardToken`, `canLink`). Composes the five Money/Card selectors and the `resolveMoneyAccountCardToken` + `hasMoneyAccountCardRequirements` utils delivered in B1. **No on-chain logic** — all transaction work stays in the controller. | | **Predict-style toasts** | Hook owns three toasts: pending (bold title + body + `<Spinner color={PrimaryDefault}>` `startAccessory`, `hasNoTimeout: true`), success (bold title + non-bold description, `Confirmation` icon, `success.default` color), error (`Danger` icon, `error.muted` background, `error.default` color). `UserCancelledError` is silent — no error toast on user-rejected signatures. | | **`MoneyHomeView.handleLinkCardPress`** | Now async. When `isCardholder && isCardAuthenticated && hasMoneyAccountRequirements`, it calls `linkInBackground()` and returns early — no navigation. Otherwise the existing `navigation.navigate(Routes.CARD.ROOT, { screen: Routes.CARD.HOME })` behaviour is preserved. The 4-branch routing helper (welcome / authentication / fully-ready) is intentionally deferred to B3. | | **Locale strings** | Adds `money.metamask_card.link_pending_title`, `link_pending_description`, `link_success_title`, `link_success_description`, `link_error`. | ### Out of scope (lands in B3+) - `linkInteractive({ amount })` on the hook + `useSpendingLimit.submit` MA dispatch. - `getNextRouteAfterCardReady` route helper + WELCOME / AUTHENTICATION navigation branches in `handleLinkCardPress`. - Removing the 3s `setTimeout` in the wallet submit flow. - Surfacing `isLinking` on `MoneyMetaMaskCard mode="link"` for disable / loading affordance. ### Test coverage - New `useMoneyAccountCardLinkage.test.tsx` — 12 tests covering the derived-state matrix, happy-path transitions (`idle → pending → success`), pending toast (Spinner `startAccessory`, `hasNoTimeout: true`, bold title + non-bold description), success toast, generic error reject, `UserCancelledError` silent path, fail-closed (`!canLink`), and `reset`. - `MoneyHomeView.test.tsx` — adds 4 assertions: regression (no MA readiness → still navigates to `CARD.HOME`) and fully-ready inline-linking, for both `MoneyOnboardingCard` CTA and `MoneyMetaMaskCard` link-button press paths. - Full `app/components/UI/Card` + `app/components/UI/Money` jest scope: **2983 tests / 156 suites passing.** ## **Changelog** <!-- If this PR is not End-User-Facing and should not show up in the CHANGELOG, you can choose to either: 1. Write `CHANGELOG entry: null` 2. Label with `no-changelog` If this PR is End-User-Facing, please write a short User-Facing description in the past tense like: `CHANGELOG entry: Added a new tab for users to see their NFTs` `CHANGELOG entry: Fixed a bug that was causing some NFTs to flicker` (This helps the Release Engineer do their job more quickly and accurately) --> CHANGELOG entry: null ## **Related issues** Refs: [#30000](#30000) (B1 foundation) No issue: internal hook + inline trigger for the Money Account ↔ Card linkage stack (B2 of a multi-branch stack). ## **Manual testing steps** ```gherkin Feature: Inline Money Account → Card linkage from Money home Background: Given the user is a cardholder And the user has an authenticated Card session And the user has a primary Money Account on a supported chain And the Money Account feature flag is enabled And the user is on the Money home screen with the "Link card" CTA visible Scenario: Successful inline linking from Money home When the user taps "Link card" (either onboarding-card CTA or MetaMaskCard link button) Then the screen does NOT navigate to Card home And a pending toast appears with title "Linking card", description "Approving spending limit…", and a spinner icon And the pending toast persists until the on-chain approval is confirmed When the approval transaction is confirmed Then the pending toast is replaced by a success toast with title "Card linked successfully" and description "You can now spend while you earn" Scenario: User rejects the signature When the user taps "Link card" And the user rejects the SIWE signature prompt Then no error toast is shown And the user stays on Money home Scenario: Transaction failure When the user taps "Link card" And the on-chain approval fails or times out Then an error toast appears with title "Couldn't link card" Scenario: Falls back to navigation when prerequisites are not met Given the user is a cardholder But the user is NOT authenticated for Card OR has no Money Account on a supported chain When the user taps "Link card" Then the app navigates to Card home (existing behaviour preserved) ``` ## **Screenshots/Recordings** <!-- If applicable, add screenshots and/or recordings to visualize the before and after of your change. --> ### **Before** N/A — no inline linking on Money home; "Link card" always navigated to `CARD.HOME`. ### **After** https://github.com/user-attachments/assets/07691435-05a5-4b5d-b80a-f199ccb47c1b <!-- Pending and error toasts follow the Predict toast style; pending uses an animated Spinner startAccessory. --> ## **Pre-merge author checklist** <!-- Every checklist item must be consciously assessed before marking this PR as "Ready for review". A checked box means you deliberately considered that responsibility, not that you literally performed every action listed. Unchecked boxes are ambiguous: they are not an implicit "N/A" and they are not a silent "skip". See `docs/readme/ready-for-review.md` for the full checklist semantics. --> - [x] I've followed [MetaMask Contributor Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile Coding Standards](https://github.com/MetaMask/metamask-mobile/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-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)). Not required for external contributors. #### Performance checks (if applicable) - [ ] I've tested on Android - Ideally on a mid-range device; emulator is acceptable - [ ] I've tested with a power user scenario - Use these [power-user SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93) to import wallets with many accounts and tokens - [ ] I've instrumented key operations with Sentry traces for production performance metrics - See [`trace()`](/app/util/trace.ts) for usage and [`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274) for an example For performance guidelines and tooling, see the [Performance Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers). ## **Pre-merge reviewer checklist** <!-- Reviewer checklist items follow the same semantics as the author checklist: an unchecked box is ambiguous, a checked box means the reviewer consciously assessed that responsibility. See `docs/readme/ready-for-review.md`. --> - [ ] 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. <!-- Generated with the help of the pr-description AI skill --> <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Medium risk because it changes Money home CTA behavior to trigger background card-linking (on-chain flow) and introduces new toast-driven orchestration around `CardController.linkMoneyAccountCard`, which could affect user navigation and error handling. > > **Overview** > Adds a new UI hook, `useMoneyAccountCardLinkage`, that derives whether a user can link a Money Account to a MetaMask Card and, when triggered, runs `CardController.linkMoneyAccountCard` in the background while managing pending/success/error toast UX (including a silent user-cancel path). > > Updates `MoneyHomeView` so the “Link card” actions *inline-link* (no navigation) when `isCardholder && canLink`, otherwise preserving the existing navigation to `CARD.HOME`. Adds/updates Jest coverage for the hook and Money home linking behavior, and introduces new locale strings for the new toasts. > > <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 91d05cd. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 7876524 commit 721934e

5 files changed

Lines changed: 669 additions & 5 deletions

File tree

Lines changed: 336 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,336 @@
1+
import React from 'react';
2+
import { renderHook, act } from '@testing-library/react-hooks';
3+
import { useSelector } from 'react-redux';
4+
import { ToastContext } from '../../../../component-library/components/Toast';
5+
import Logger from '../../../../util/Logger';
6+
import { selectPrimaryMoneyAccount } from '../../../../selectors/moneyAccountController';
7+
import { selectMoneyAccountVaultConfig } from '../../../../selectors/featureFlagController/moneyAccount';
8+
import {
9+
selectCardDelegationSettings,
10+
selectIsCardAuthenticated,
11+
} from '../../../../selectors/cardController';
12+
import { selectMoneyEnableMoneyAccountFlag } from '../../Money/selectors/featureFlags';
13+
import { resolveMoneyAccountCardToken } from '../../../../core/Engine/controllers/card-controller/utils/moneyAccountCardToken';
14+
import { BAANX_MAX_LIMIT } from '../constants';
15+
import { FundingStatus } from '../types';
16+
import { useMoneyAccountCardLinkage } from './useMoneyAccountCardLinkage';
17+
18+
jest.mock('react-redux', () => ({
19+
useSelector: jest.fn(),
20+
}));
21+
22+
const mockLinkMoneyAccountCard = jest.fn();
23+
jest.mock('../../../../core/Engine', () => ({
24+
__esModule: true,
25+
default: {
26+
context: {
27+
CardController: {
28+
linkMoneyAccountCard: (...args: unknown[]) =>
29+
mockLinkMoneyAccountCard(...args),
30+
},
31+
},
32+
},
33+
}));
34+
35+
jest.mock('./useCardDelegation', () => {
36+
class MockUserCancelledError extends Error {
37+
constructor(message = 'User cancelled') {
38+
super(message);
39+
this.name = 'UserCancelledError';
40+
}
41+
}
42+
return { UserCancelledError: MockUserCancelledError };
43+
});
44+
45+
jest.mock(
46+
'../../../../core/Engine/controllers/card-controller/utils/moneyAccountCardToken',
47+
() => ({
48+
resolveMoneyAccountCardToken: jest.fn(),
49+
hasMoneyAccountCardRequirements: ({
50+
isMoneyAccountEnabled,
51+
vaultConfig,
52+
moneyAccountAddress,
53+
}: {
54+
isMoneyAccountEnabled: boolean;
55+
vaultConfig: unknown;
56+
moneyAccountAddress?: string | null;
57+
}) => Boolean(isMoneyAccountEnabled && vaultConfig && moneyAccountAddress),
58+
}),
59+
);
60+
61+
jest.mock('../../../../util/Logger', () => ({
62+
log: jest.fn(),
63+
error: jest.fn(),
64+
}));
65+
66+
jest.mock('../../../../util/theme', () => {
67+
const actual = jest.requireActual('../../../../util/theme');
68+
return {
69+
...actual,
70+
useTheme: jest.fn(() => actual.mockTheme),
71+
};
72+
});
73+
74+
const mockUseSelector = useSelector as unknown as jest.Mock;
75+
const mockResolveMoneyAccountCardToken =
76+
resolveMoneyAccountCardToken as jest.Mock;
77+
78+
const MONEY_ACCOUNT_ADDRESS = '0x1234567890123456789012345678901234567890';
79+
80+
const MOCK_TOKEN = {
81+
address: '0xtoken',
82+
symbol: 'USDC',
83+
name: 'USDC',
84+
decimals: 6,
85+
caipChainId: 'eip155:11297108099' as `${string}:${string}`,
86+
fundingStatus: FundingStatus.NotEnabled,
87+
spendableBalance: '0',
88+
delegationContract: '0xdelegation',
89+
};
90+
91+
const buildSelectors = (
92+
overrides: {
93+
primaryMoneyAccount?: { address: string } | undefined;
94+
vaultConfig?: unknown;
95+
isMoneyAccountEnabled?: boolean;
96+
isCardAuthenticated?: boolean;
97+
delegationSettings?: unknown;
98+
} = {},
99+
) => ({
100+
primaryMoneyAccount: { address: MONEY_ACCOUNT_ADDRESS },
101+
vaultConfig: { id: 'vault-1' },
102+
isMoneyAccountEnabled: true,
103+
isCardAuthenticated: true,
104+
delegationSettings: { ok: true },
105+
...overrides,
106+
});
107+
108+
const applySelectorMocks = (state: ReturnType<typeof buildSelectors>) => {
109+
mockUseSelector.mockImplementation((selector: (s: unknown) => unknown) => {
110+
if (selector === selectPrimaryMoneyAccount)
111+
return state.primaryMoneyAccount;
112+
if (selector === selectMoneyAccountVaultConfig) return state.vaultConfig;
113+
if (selector === selectMoneyEnableMoneyAccountFlag)
114+
return state.isMoneyAccountEnabled;
115+
if (selector === selectIsCardAuthenticated)
116+
return state.isCardAuthenticated;
117+
if (selector === selectCardDelegationSettings)
118+
return state.delegationSettings;
119+
return undefined;
120+
});
121+
};
122+
123+
describe('useMoneyAccountCardLinkage', () => {
124+
let mockShowToast: jest.Mock;
125+
let mockToastRef: { current: { showToast: jest.Mock } };
126+
127+
const renderLinkageHook = () =>
128+
renderHook(() => useMoneyAccountCardLinkage(), {
129+
wrapper: ({ children }: { children: React.ReactNode }) => (
130+
<ToastContext.Provider value={{ toastRef: mockToastRef } as never}>
131+
{children}
132+
</ToastContext.Provider>
133+
),
134+
});
135+
136+
beforeEach(() => {
137+
jest.clearAllMocks();
138+
mockShowToast = jest.fn();
139+
mockToastRef = { current: { showToast: mockShowToast } };
140+
141+
mockResolveMoneyAccountCardToken.mockReturnValue(MOCK_TOKEN);
142+
applySelectorMocks(buildSelectors());
143+
});
144+
145+
describe('derived state', () => {
146+
it('reports canLink=true when all requirements are met', () => {
147+
const { result } = renderLinkageHook();
148+
149+
expect(result.current.canLink).toBe(true);
150+
expect(result.current.hasMoneyAccountRequirements).toBe(true);
151+
expect(result.current.isCardAuthenticated).toBe(true);
152+
expect(result.current.moneyAccountCardToken).toBe(MOCK_TOKEN);
153+
expect(result.current.status).toBe('idle');
154+
expect(result.current.isLinking).toBe(false);
155+
expect(result.current.error).toBeNull();
156+
});
157+
158+
it('reports canLink=false when the card is not authenticated', () => {
159+
applySelectorMocks(buildSelectors({ isCardAuthenticated: false }));
160+
const { result } = renderLinkageHook();
161+
expect(result.current.canLink).toBe(false);
162+
});
163+
164+
it('reports canLink=false when there is no Money account', () => {
165+
applySelectorMocks(buildSelectors({ primaryMoneyAccount: undefined }));
166+
const { result } = renderLinkageHook();
167+
expect(result.current.canLink).toBe(false);
168+
});
169+
170+
it('reports canLink=false when the feature flag is off', () => {
171+
applySelectorMocks(buildSelectors({ isMoneyAccountEnabled: false }));
172+
const { result } = renderLinkageHook();
173+
expect(result.current.canLink).toBe(false);
174+
});
175+
176+
it('reports canLink=false when vault config is missing', () => {
177+
applySelectorMocks(buildSelectors({ vaultConfig: undefined }));
178+
const { result } = renderLinkageHook();
179+
expect(result.current.canLink).toBe(false);
180+
});
181+
182+
it('reports canLink=false when the Monad USDC token cannot be resolved', () => {
183+
mockResolveMoneyAccountCardToken.mockReturnValueOnce(null);
184+
const { result } = renderLinkageHook();
185+
expect(result.current.canLink).toBe(false);
186+
});
187+
});
188+
189+
describe('linkInBackground - happy path', () => {
190+
it('transitions idle -> pending -> success and calls the controller once with BAANX_MAX_LIMIT and the MA address', async () => {
191+
mockLinkMoneyAccountCard.mockResolvedValueOnce(undefined);
192+
193+
const { result } = renderLinkageHook();
194+
195+
let returned: boolean | undefined;
196+
await act(async () => {
197+
returned = await result.current.linkInBackground();
198+
});
199+
200+
expect(returned).toBe(true);
201+
expect(result.current.status).toBe('success');
202+
expect(result.current.error).toBeNull();
203+
expect(mockLinkMoneyAccountCard).toHaveBeenCalledTimes(1);
204+
expect(mockLinkMoneyAccountCard).toHaveBeenCalledWith({
205+
moneyAccountAddress: MONEY_ACCOUNT_ADDRESS,
206+
delegationAmountHuman: BAANX_MAX_LIMIT,
207+
});
208+
});
209+
210+
it('shows the Predict-style pending toast with a Spinner startAccessory before the success toast', async () => {
211+
let resolveLink: () => void = () => undefined;
212+
mockLinkMoneyAccountCard.mockReturnValueOnce(
213+
new Promise<void>((resolve) => {
214+
resolveLink = resolve;
215+
}),
216+
);
217+
218+
const { result } = renderLinkageHook();
219+
220+
let linkPromise: Promise<boolean> | undefined;
221+
act(() => {
222+
linkPromise = result.current.linkInBackground();
223+
});
224+
225+
const pendingCall = mockShowToast.mock.calls[0]?.[0];
226+
expect(pendingCall).toMatchObject({
227+
hasNoTimeout: true,
228+
labelOptions: [
229+
{ label: 'Linking card', isBold: true },
230+
{ label: '\n', isBold: false },
231+
{ label: 'Approving spending limit…', isBold: false },
232+
],
233+
});
234+
expect(pendingCall?.startAccessory).toBeDefined();
235+
236+
await act(async () => {
237+
resolveLink();
238+
await linkPromise;
239+
});
240+
241+
const successCall = mockShowToast.mock.calls[1]?.[0];
242+
expect(successCall).toMatchObject({
243+
labelOptions: [
244+
{ label: 'Card linked successfully', isBold: true },
245+
{ label: '\n', isBold: false },
246+
{ label: 'You can now spend while you earn', isBold: false },
247+
],
248+
hasNoTimeout: false,
249+
});
250+
});
251+
});
252+
253+
describe('linkInBackground - failure paths', () => {
254+
it('sets status=error and shows error toast on generic reject', async () => {
255+
mockLinkMoneyAccountCard.mockRejectedValueOnce(new Error('boom'));
256+
257+
const { result } = renderLinkageHook();
258+
259+
let returned: boolean | undefined;
260+
await act(async () => {
261+
returned = await result.current.linkInBackground();
262+
});
263+
264+
expect(returned).toBe(false);
265+
expect(result.current.status).toBe('error');
266+
expect(result.current.error?.message).toBe('boom');
267+
expect(Logger.error).toHaveBeenCalled();
268+
269+
const errorCall = mockShowToast.mock.calls.at(-1)?.[0];
270+
expect(errorCall).toMatchObject({
271+
labelOptions: [{ label: "Couldn't link card", isBold: true }],
272+
hasNoTimeout: false,
273+
});
274+
});
275+
276+
it('sets status=cancelled and shows NO error toast on UserCancelledError', async () => {
277+
const { UserCancelledError } = jest.requireMock('./useCardDelegation');
278+
mockLinkMoneyAccountCard.mockRejectedValueOnce(
279+
new UserCancelledError('User denied'),
280+
);
281+
282+
const { result } = renderLinkageHook();
283+
284+
let returned: boolean | undefined;
285+
await act(async () => {
286+
returned = await result.current.linkInBackground();
287+
});
288+
289+
expect(returned).toBe(false);
290+
expect(result.current.status).toBe('cancelled');
291+
292+
// Only the pending toast should have fired — no error toast.
293+
const lastCall = mockShowToast.mock.calls.at(-1)?.[0];
294+
expect(lastCall).toMatchObject({ hasNoTimeout: true });
295+
expect(Logger.error).not.toHaveBeenCalled();
296+
});
297+
298+
it('fails closed when canLink is false: no controller call, error toast, returns false', async () => {
299+
applySelectorMocks(buildSelectors({ isCardAuthenticated: false }));
300+
const { result } = renderLinkageHook();
301+
302+
let returned: boolean | undefined;
303+
await act(async () => {
304+
returned = await result.current.linkInBackground();
305+
});
306+
307+
expect(returned).toBe(false);
308+
expect(mockLinkMoneyAccountCard).not.toHaveBeenCalled();
309+
expect(mockShowToast).toHaveBeenCalledTimes(1);
310+
expect(mockShowToast.mock.calls[0][0]).toMatchObject({
311+
labelOptions: [{ label: "Couldn't link card", isBold: true }],
312+
});
313+
});
314+
});
315+
316+
describe('reset', () => {
317+
it('clears status and error back to idle / null', async () => {
318+
mockLinkMoneyAccountCard.mockRejectedValueOnce(new Error('boom'));
319+
320+
const { result } = renderLinkageHook();
321+
322+
await act(async () => {
323+
await result.current.linkInBackground();
324+
});
325+
expect(result.current.status).toBe('error');
326+
expect(result.current.error).not.toBeNull();
327+
328+
act(() => {
329+
result.current.reset();
330+
});
331+
332+
expect(result.current.status).toBe('idle');
333+
expect(result.current.error).toBeNull();
334+
});
335+
});
336+
});

0 commit comments

Comments
 (0)