Skip to content

Commit 606fd94

Browse files
test(mosaic): cover recovery across wallet providers
1 parent de92d06 commit 606fd94

3 files changed

Lines changed: 296 additions & 30 deletions

File tree

‎packages/mosaic/AGENTS.md‎

Lines changed: 30 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -32,37 +32,37 @@ A flow lives in `src/features/<feature>/`. The **model** (`*.model.ts(x)`) is th
3232

3333
Most problems a feature hits already have a shared answer. Find the row for your problem and use it. Do not write a local version, even a small one.
3434

35-
| Problem | Use |
36-
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
35+
| Problem | Use |
36+
| --------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
3737
| An async action from a button or row: pending, an error, one lock, unmount signal | `usePendingAction` (`src/hooks/`) |
38-
| A form: values, validation, submit, field errors, success UI | `useForm` (`src/components/form/`), with `validateAsync` for server checks and `onSuccess` for mounted success UI |
39-
| A `<form>` element, without the browser's validation popup | `Form` (`src/primitives/form/`) |
40-
| A model save whose Clerk errors should land on form fields | `save` (`src/utils/errors.ts`) in the model, or reject with `FormSubmitError` |
41-
| A confirm step before an action | `useConfirmController` (`src/blocks/confirm/`) with `Confirmation` (`src/blocks/confirmation/`) |
42-
| A delete that needs the user to type a phrase | `useConfirmController` (`src/blocks/confirm/`) with `Destructive` (`src/blocks/destructive/`) |
43-
| An action that may need step-up verification | `useReverificationFlow` (`src/features/reverification/`) in the model, passed to `useConfirmController` |
44-
| A direct action that needs step-up verification | `useReverificationFlow` in the model, with `ReverificationDialog` (`src/blocks/reverification/`) in the view |
45-
| Showing any error to the user | One of the owners above. They call `toLocalizableError` and resolve copy with `useErrorText` |
46-
| Moving focus after a list row is removed | `useListRemovalFocus` (`src/hooks/`) |
47-
| A debounced, abortable async check as the user types | `useDebouncedAsync` (`src/hooks/`) |
48-
| A spinner that should not flash or flicker | `useSpinDelay` (`src/hooks/`) |
49-
| A placeholder for content that is still loading | `Skeleton` (`src/components/skeleton/`), see [Skeletons](docs/skeletons.md) |
50-
| A date shown to the user | `formatDate` (`src/utils/format-date.ts`) |
51-
| A value turned into kebab case, e.g. for a `data-*` attribute | `kebabCase` (`src/utils/kebab-case.ts`) |
52-
| Current time for display labels | `useNow` (`src/hooks/`) |
53-
| Whether enterprise SSO permits adding another identification | `allowsIdentificationCreation` (`src/utils/allows-identification-creation.ts`) |
54-
| An inline message row; height is undefined until measured | `useHeldMessage`, `useMessageHeight`, `FeedbackBody` (`src/utils/feedback.tsx`) + `src/styles/feedback.styles.ts` |
55-
| Data read from a Clerk resource that should be cached across mounts | A query hook in `src/queries/`, called from the model (`src/queries/use-user-sessions-query.ts`) |
56-
| An item changed in place in an infinite list, kept until the next reload | `replaceInPages` (`src/utils/infinite-pages.ts`), passed to the list's `setData` |
57-
| An organization permission checked with `checkAuthorization` | `ORGANIZATION_PERMISSIONS` (`src/utils/permissions.ts`) |
58-
| A verification code's length or resend cooldown | `CODE_LENGTH`, `CODE_RESEND_SECONDS` (`src/utils/verification.ts`) |
59-
| An avatar or logo file picker and its rejection errors | `AVATAR_UPLOAD`, `AVATAR_REJECTION_ERRORS` (`src/utils/avatar-upload.ts`) |
60-
| Siblings that slide when an item is added or removed | `useLayoutAnimation` (`src/primitives/hooks/`) |
61-
| An input that reformats as the user types without moving the caret | `useFormattedInput` (`src/primitives/hooks/`) |
62-
| A panel that animates open and closed to its measured size | `usePanelSize` (`src/primitives/hooks/`) |
63-
| One screen replacing another on the same card or dialog | `Flow` (`src/components/flow/`), see [Views](docs/views.md) |
64-
| An interaction with an async lifecycle or two values that move together | A machine in the controller file, via `setup()` (`src/machine/`) |
65-
| Styles several components share | `src/styles/*.styles.ts` |
38+
| A form: values, validation, submit, field errors, success UI | `useForm` (`src/components/form/`), with `validateAsync` for server checks and `onSuccess` for mounted success UI |
39+
| A `<form>` element, without the browser's validation popup | `Form` (`src/primitives/form/`) |
40+
| A model save whose Clerk errors should land on form fields | `save` (`src/utils/errors.ts`) in the model, or reject with `FormSubmitError` |
41+
| A confirm step before an action | `useConfirmController` (`src/blocks/confirm/`) with `Confirmation` (`src/blocks/confirmation/`) |
42+
| A delete that needs the user to type a phrase | `useConfirmController` (`src/blocks/confirm/`) with `Destructive` (`src/blocks/destructive/`) |
43+
| An action that may need step-up verification | `useReverificationFlow` (`src/features/reverification/`) in the model, passed to `useConfirmController` |
44+
| A direct action that needs step-up verification | `useReverificationFlow` in the model, with `ReverificationDialog` (`src/blocks/reverification/`) in the view |
45+
| Showing any error to the user | One of the owners above. They call `toLocalizableError` and resolve copy with `useErrorText` |
46+
| Moving focus after a list row is removed | `useListRemovalFocus` (`src/hooks/`) |
47+
| A debounced, abortable async check as the user types | `useDebouncedAsync` (`src/hooks/`) |
48+
| A spinner that should not flash or flicker | `useSpinDelay` (`src/hooks/`) |
49+
| A placeholder for content that is still loading | `Skeleton` (`src/components/skeleton/`), see [Skeletons](docs/skeletons.md) |
50+
| A date shown to the user | `formatDate` (`src/utils/format-date.ts`) |
51+
| A value turned into kebab case, e.g. for a `data-*` attribute | `kebabCase` (`src/utils/kebab-case.ts`) |
52+
| Current time for display labels | `useNow` (`src/hooks/`) |
53+
| Whether enterprise SSO permits adding another identification | `allowsIdentificationCreation` (`src/utils/allows-identification-creation.ts`) |
54+
| An inline message row; height is undefined until measured | `useHeldMessage`, `useMessageHeight`, `FeedbackBody` (`src/utils/feedback.tsx`) + `src/styles/feedback.styles.ts` |
55+
| Data read from a Clerk resource that should be cached across mounts | A query hook in `src/queries/`, called from the model (`src/queries/use-user-sessions-query.ts`) |
56+
| An item changed in place in an infinite list, kept until the next reload | `replaceInPages` (`src/utils/infinite-pages.ts`), passed to the list's `setData` |
57+
| An organization permission checked with `checkAuthorization` | `ORGANIZATION_PERMISSIONS` (`src/utils/permissions.ts`) |
58+
| A verification code's length or resend cooldown | `CODE_LENGTH`, `CODE_RESEND_SECONDS` (`src/utils/verification.ts`) |
59+
| An avatar or logo file picker and its rejection errors | `AVATAR_UPLOAD`, `AVATAR_REJECTION_ERRORS` (`src/utils/avatar-upload.ts`) |
60+
| Siblings that slide when an item is added or removed | `useLayoutAnimation` (`src/primitives/hooks/`) |
61+
| An input that reformats as the user types without moving the caret | `useFormattedInput` (`src/primitives/hooks/`) |
62+
| A panel that animates open and closed to its measured size | `usePanelSize` (`src/primitives/hooks/`) |
63+
| One screen replacing another on the same card or dialog | `Flow` (`src/components/flow/`), see [Views](docs/views.md) |
64+
| An interaction with an async lifecycle or two values that move together | A machine in the controller file, via `setup()` (`src/machine/`) |
65+
| Styles several components share | `src/styles/*.styles.ts` |
6666

6767
## Signs you are about to invent a pattern
6868

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,142 @@
1+
import { act, screen, waitFor } from '@testing-library/react';
2+
import userEvent from '@testing-library/user-event';
3+
import { afterEach, describe, expect, it, vi } from 'vitest';
4+
5+
import { deferred } from '../../../../__tests__/async';
6+
import { serveFapi } from '../../../../__tests__/feature/fake-fapi';
7+
import { openMenu } from '../../../../__tests__/feature/menu';
8+
import { renderWithClerk } from '../../../../__tests__/feature/render';
9+
import { UserProfileWeb3WalletsSection } from '../user-profile-web3-wallets-section';
10+
import { signedInWallets } from './user-profile-web3-wallets.fixtures';
11+
12+
const request = vi.fn<(params: { method: string }) => Promise<string | string[]>>();
13+
const provider = { request };
14+
const announceOKX = () =>
15+
window.dispatchEvent(
16+
new CustomEvent('eip6963:announceProvider', {
17+
detail: { info: { name: 'OKX Wallet', uuid: 'recovery-okx', icon: '', rdns: 'com.okx.wallet' }, provider },
18+
}),
19+
);
20+
21+
afterEach(() => window.removeEventListener('eip6963:requestProvider', announceOKX));
22+
23+
describe.each([
24+
['Base', 'web3_base_signature', '@base-org/account'],
25+
['Coinbase Wallet', 'web3_coinbase_wallet_signature', '@coinbase/wallet-sdk'],
26+
['OKX Wallet', 'web3_okx_wallet_signature', null],
27+
] as const)('%s recovery', (name, strategy, moduleName) => {
28+
async function setup() {
29+
vi.stubGlobal('ethereum', {
30+
request: () => {
31+
throw new Error('The selected wallet must not use the fallback Ethereum provider.');
32+
},
33+
});
34+
const fapi = serveFapi(signedInWallets([strategy]));
35+
const view = await renderWithClerk(<UserProfileWeb3WalletsSection />);
36+
Object.defineProperty(view.clerk, '__internal_moduleManager', {
37+
value: {
38+
import: (module: string) => {
39+
expect(module).toBe(moduleName);
40+
return Promise.resolve({
41+
createBaseAccountSDK: () => ({ getProvider: () => provider }),
42+
createCoinbaseWalletSDK: () => ({ getProvider: () => provider }),
43+
});
44+
},
45+
},
46+
});
47+
if (moduleName === null) {
48+
window.addEventListener('eip6963:requestProvider', announceOKX);
49+
announceOKX();
50+
}
51+
return { fapi, view, user: userEvent.setup() };
52+
}
53+
54+
it.each(['eth_requestAccounts', 'personal_sign'] as const)(
55+
'recovers from cancellation during %s and verifies on retry',
56+
async method => {
57+
request.mockImplementation(({ method: requested }) => {
58+
if (requested === method) {
59+
return Promise.reject(Object.assign(new Error('User rejected the request.'), { code: 4001 }));
60+
}
61+
return Promise.resolve(['0x1234567890abcdef']);
62+
});
63+
const { fapi, user } = await setup();
64+
await user.click(await screen.findByRole('button', { name: `Connect ${name}` }));
65+
await waitFor(() =>
66+
expect(screen.getByRole('alert')).toHaveTextContent('Wallet connection was cancelled. Please try again.'),
67+
);
68+
request.mockImplementation(({ method: requested }) =>
69+
Promise.resolve(requested === 'personal_sign' ? 'signature' : ['0x1234567890abcdef']),
70+
);
71+
if (method === 'personal_sign') {
72+
await openMenu(user, screen.getByRole('button', { name: `Manage ${name}` }));
73+
await user.click(screen.getByRole('menuitem', { name: 'Verify' }));
74+
} else {
75+
expect(fapi.client.sessions[0]?.user.web3_wallets).toHaveLength(0);
76+
await user.click(screen.getByRole('button', { name: `Connect ${name}` }));
77+
}
78+
await waitFor(() => expect(fapi.client.sessions[0]?.user.web3_wallets[0]?.verification?.status).toBe('verified'));
79+
expect(fapi.client.sessions[0]?.user.web3_wallets).toHaveLength(1);
80+
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
81+
},
82+
);
83+
84+
it('explains a pending provider request and releases its busy state', async () => {
85+
request.mockRejectedValue({ code: -32002 });
86+
const { user } = await setup();
87+
await user.click(await screen.findByRole('button', { name: `Connect ${name}` }));
88+
await waitFor(() =>
89+
expect(screen.getByRole('alert')).toHaveTextContent(
90+
'A request is already pending in your wallet. Open your wallet to complete or reject it, then try again.',
91+
),
92+
);
93+
expect(screen.getByRole('button', { name: `Connect ${name}` })).toBeEnabled();
94+
});
95+
96+
it.each([
97+
['eth_requestAccounts', 'resolve'],
98+
['eth_requestAccounts', 'reject'],
99+
['personal_sign', 'resolve'],
100+
['personal_sign', 'reject'],
101+
] as const)('ignores abandoned %s %s after reopening and completes the new attempt', async (method, outcome) => {
102+
const old = deferred<string | string[]>();
103+
const next = deferred<string | string[]>();
104+
request.mockImplementation(async ({ method: requested }) =>
105+
requested === method ? old.promise : ['0x1234567890abcdef'],
106+
);
107+
const { fapi, view, user } = await setup();
108+
await user.click(await screen.findByRole('button', { name: `Connect ${name}` }));
109+
await waitFor(() => expect(request).toHaveBeenCalledWith(expect.objectContaining({ method })));
110+
view.rerender(<div />);
111+
view.rerender(<UserProfileWeb3WalletsSection />);
112+
request.mockImplementation(async ({ method: requested }) => {
113+
if (requested === method) {
114+
return next.promise;
115+
}
116+
return requested === 'personal_sign' ? 'signature' : ['0x1234567890abcdef'];
117+
});
118+
if (method === 'personal_sign') {
119+
await openMenu(user, await screen.findByRole('button', { name: `Manage ${name}` }));
120+
await user.click(screen.getByRole('menuitem', { name: 'Verify' }));
121+
} else {
122+
await user.click(await screen.findByRole('button', { name: `Connect ${name}` }));
123+
}
124+
await waitFor(() => expect(request.mock.calls.filter(([params]) => params.method === method)).toHaveLength(2));
125+
await act(() => {
126+
if (outcome === 'resolve') {
127+
old.resolve(method === 'personal_sign' ? 'old-signature' : ['0xold']);
128+
} else {
129+
old.reject({ code: 4001 });
130+
}
131+
});
132+
expect(screen.queryByRole('alert')).not.toBeInTheDocument();
133+
expect(fapi.client.sessions[0]?.user.web3_wallets).toHaveLength(method === 'personal_sign' ? 1 : 0);
134+
expect(fapi.client.sessions[0]?.user.web3_wallets[0]?.verification?.status).not.toBe('verified');
135+
expect(
136+
screen.getByRole('button', { name: `${method === 'personal_sign' ? 'Manage' : 'Connect'} ${name}` }),
137+
).toHaveAttribute('aria-disabled', 'true');
138+
await act(() => next.resolve(method === 'personal_sign' ? 'signature' : ['0x1234567890abcdef']));
139+
await waitFor(() => expect(fapi.client.sessions[0]?.user.web3_wallets[0]?.verification?.status).toBe('verified'));
140+
expect(fapi.client.sessions[0]?.user.web3_wallets).toHaveLength(1);
141+
});
142+
});

0 commit comments

Comments
 (0)