-
Notifications
You must be signed in to change notification settings - Fork 5.5k
feat: add QR adapter #41488
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: add QR adapter #41488
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
51fcdfa
Add QR adapter
david0xd 69ff639
Update camera check logic
david0xd d6ae46a
Refactor to use navigator instead of window
david0xd 2d502fa
Refactor unit tests
david0xd e3dea6f
Add small improvements to unit tests
david0xd 19b9d1f
Add some small refactoring
david0xd 46822f7
Remove redundant test for camera permission
david0xd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
135 changes: 135 additions & 0 deletions
135
ui/contexts/hardware-wallets/adapters/QrAdapter.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| import { ErrorCode, HardwareWalletError } from '@metamask/hw-wallet-sdk'; | ||
| import { CameraPermissionState } from '../constants'; | ||
| import { DeviceEvent, type HardwareWalletAdapterOptions } from '../types'; | ||
| import * as webConnectionUtils from '../webConnectionUtils'; | ||
| import { QrAdapter } from './QrAdapter'; | ||
|
|
||
| jest.mock('../webConnectionUtils', () => ({ | ||
| ...jest.requireActual('../webConnectionUtils'), | ||
| checkCameraPermission: jest.fn(), | ||
| })); | ||
|
|
||
| const mockCheckCameraPermission = | ||
| webConnectionUtils.checkCameraPermission as jest.MockedFunction< | ||
| typeof webConnectionUtils.checkCameraPermission | ||
| >; | ||
|
|
||
| describe('QrAdapter', () => { | ||
| let adapter: QrAdapter; | ||
| let mockOptions: HardwareWalletAdapterOptions; | ||
|
|
||
| const createMockOptions = (): HardwareWalletAdapterOptions => ({ | ||
| onDisconnect: jest.fn(), | ||
| onAwaitingConfirmation: jest.fn(), | ||
| onDeviceLocked: jest.fn(), | ||
| onAppNotOpen: jest.fn(), | ||
| onDeviceEvent: jest.fn(), | ||
| }); | ||
|
|
||
| beforeEach(() => { | ||
| jest.clearAllMocks(); | ||
| mockOptions = createMockOptions(); | ||
| adapter = new QrAdapter(mockOptions); | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| jest.resetAllMocks(); | ||
| adapter.destroy(); | ||
| }); | ||
|
|
||
| it('connect marks adapter as connected', async () => { | ||
| await adapter.connect(); | ||
| expect(adapter.isConnected()).toBe(true); | ||
| }); | ||
|
|
||
| it('disconnect emits disconnected event', async () => { | ||
| await adapter.connect(); | ||
| await adapter.disconnect(); | ||
|
|
||
| expect(adapter.isConnected()).toBe(false); | ||
| expect(mockOptions.onDeviceEvent).toHaveBeenCalledWith({ | ||
| event: DeviceEvent.Disconnected, | ||
| }); | ||
| }); | ||
|
|
||
| it('disconnect calls onDisconnect when onDeviceEvent throws', async () => { | ||
| await adapter.connect(); | ||
| const handlerError = new Error('onDeviceEvent failed'); | ||
| jest.mocked(mockOptions.onDeviceEvent).mockImplementation(() => { | ||
| throw handlerError; | ||
| }); | ||
|
|
||
| await adapter.disconnect(); | ||
|
|
||
| expect(mockOptions.onDisconnect).toHaveBeenCalledWith(handlerError); | ||
| }); | ||
|
|
||
| it('ensureDeviceReady returns true when camera permission is granted', async () => { | ||
| mockCheckCameraPermission.mockResolvedValue(CameraPermissionState.Granted); | ||
| await expect(adapter.ensureDeviceReady()).resolves.toBe(true); | ||
| }); | ||
|
|
||
| it('ensureDeviceReady does not call connect again when already connected', async () => { | ||
| mockCheckCameraPermission.mockResolvedValue(CameraPermissionState.Granted); | ||
| await adapter.connect(); | ||
| const connectSpy = jest.spyOn(adapter, 'connect'); | ||
|
|
||
| await expect(adapter.ensureDeviceReady()).resolves.toBe(true); | ||
|
|
||
| expect(connectSpy).not.toHaveBeenCalled(); | ||
| connectSpy.mockRestore(); | ||
| }); | ||
|
|
||
| it('ensureDeviceReady throws PermissionCameraDenied when camera permission is denied', async () => { | ||
| mockCheckCameraPermission.mockResolvedValue(CameraPermissionState.Denied); | ||
|
|
||
| await expect(adapter.ensureDeviceReady()).rejects.toThrow( | ||
| HardwareWalletError, | ||
| ); | ||
|
|
||
| expect(mockOptions.onDeviceEvent).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| event: DeviceEvent.ConnectionFailed, | ||
| error: expect.objectContaining({ | ||
| code: ErrorCode.PermissionCameraDenied, | ||
| }), | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('ensureDeviceReady throws PermissionCameraPromptDismissed when camera permission is prompt', async () => { | ||
| mockCheckCameraPermission.mockResolvedValue(CameraPermissionState.Prompt); | ||
|
|
||
| await expect(adapter.ensureDeviceReady()).rejects.toThrow( | ||
| HardwareWalletError, | ||
| ); | ||
|
|
||
| expect(mockOptions.onDeviceEvent).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| event: DeviceEvent.ConnectionFailed, | ||
| error: expect.objectContaining({ | ||
| code: ErrorCode.PermissionCameraPromptDismissed, | ||
| }), | ||
| }), | ||
| ); | ||
| }); | ||
|
|
||
| it('maps unexpected errors to hardware wallet errors and emits device event', async () => { | ||
| mockCheckCameraPermission.mockRejectedValue( | ||
| new Error('Unable to read camera permission'), | ||
| ); | ||
|
|
||
| await expect(adapter.ensureDeviceReady()).rejects.toThrow( | ||
| HardwareWalletError, | ||
| ); | ||
|
|
||
| expect(mockOptions.onDeviceEvent).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| event: DeviceEvent.ConnectionFailed, | ||
| error: expect.objectContaining({ | ||
| code: ErrorCode.Unknown, | ||
| }), | ||
| }), | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| import { ErrorCode, type HardwareWalletError } from '@metamask/hw-wallet-sdk'; | ||
| import { createHardwareWalletError, getDeviceEventForError } from '../errors'; | ||
| import { toHardwareWalletError } from '../rpcErrorUtils'; | ||
| import { | ||
| DeviceEvent, | ||
| HardwareWalletType, | ||
| type EnsureDeviceReadyOptions, | ||
| type HardwareWalletAdapter, | ||
| type HardwareWalletAdapterOptions, | ||
| } from '../types'; | ||
| import { CameraPermissionState } from '../constants'; | ||
| import { checkCameraPermission } from '../webConnectionUtils'; | ||
|
|
||
| /** | ||
| * QR hardware wallet adapter. | ||
| * | ||
| * Readiness depends on camera availability and permission state for QR scanning. | ||
| */ | ||
| export class QrAdapter implements HardwareWalletAdapter { | ||
| private readonly options: HardwareWalletAdapterOptions; | ||
|
|
||
| private connected = false; | ||
|
|
||
| constructor(options: HardwareWalletAdapterOptions) { | ||
| this.options = options; | ||
| } | ||
|
|
||
| /** | ||
| * Marks the adapter as connected. | ||
| */ | ||
| async connect(): Promise<void> { | ||
| this.connected = true; | ||
| } | ||
|
|
||
| /** | ||
| * Clears connection state and notifies listeners that the QR flow is no longer active. | ||
| */ | ||
| async disconnect(): Promise<void> { | ||
| try { | ||
| this.connected = false; | ||
| this.options.onDeviceEvent({ | ||
| event: DeviceEvent.Disconnected, | ||
| }); | ||
| } catch (error) { | ||
| this.options.onDisconnect(error); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Whether the adapter considers the QR account flow active (after connection). | ||
| */ | ||
| isConnected(): boolean { | ||
| return this.connected; | ||
| } | ||
|
|
||
| /** | ||
| * Resets local connection state. | ||
| */ | ||
| destroy(): void { | ||
| this.connected = false; | ||
| } | ||
|
|
||
| /** | ||
| * Emits a device event for the given error and returns a rejected promise with that error. | ||
| * | ||
| * @param hwError - Structured hardware wallet error to surface to the UI layer. | ||
| * @returns A promise that rejects with `hwError`. | ||
| */ | ||
| private failEnsureDeviceReady(hwError: HardwareWalletError): Promise<never> { | ||
| this.options.onDeviceEvent({ | ||
| event: getDeviceEventForError(hwError.code), | ||
| error: hwError, | ||
| }); | ||
| return Promise.reject(hwError); | ||
| } | ||
|
|
||
| /** | ||
| * Ensures camera permission state allows QR scanning (via Permissions API probe). | ||
| * Rejects with `HardwareWalletError` when permission is denied, still prompt, or the probe fails. | ||
| * | ||
| * @param _options - Reserved for parity with other hardware adapters; ignored for QR. | ||
| * @returns True when camera permission is granted. | ||
| */ | ||
| async ensureDeviceReady( | ||
| _options?: EnsureDeviceReadyOptions, | ||
| ): Promise<boolean> { | ||
| if (!this.isConnected()) { | ||
| await this.connect(); | ||
| } | ||
|
|
||
| let permissionState: PermissionState; | ||
| try { | ||
| permissionState = await checkCameraPermission(); | ||
| } catch (error) { | ||
| return this.failEnsureDeviceReady( | ||
| toHardwareWalletError(error, HardwareWalletType.Qr), | ||
| ); | ||
| } | ||
|
|
||
| if (permissionState === CameraPermissionState.Granted) { | ||
| return true; | ||
| } | ||
|
|
||
| if (permissionState === CameraPermissionState.Denied) { | ||
| return this.failEnsureDeviceReady( | ||
| createHardwareWalletError( | ||
| ErrorCode.PermissionCameraDenied, | ||
| HardwareWalletType.Qr, | ||
| ), | ||
| ); | ||
| } | ||
|
|
||
| return this.failEnsureDeviceReady( | ||
| createHardwareWalletError( | ||
| ErrorCode.PermissionCameraPromptDismissed, | ||
| HardwareWalletType.Qr, | ||
| ), | ||
| ); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nit: But I wonder if
destroyshould also calldisconnectimplicitly in-case the device is still connected (I know we're not doing that for theLedgerAdapter, but that might be something we should discuss internally cc @montelaidev)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
(not something we need to handle on this PR btw)