Skip to content
Open
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
fd40efd
feat: add new hardware entropy type option
montelaidev Mar 5, 2026
cd75414
feat: ledger dmk bridge and middleware fix
montelaidev Mar 12, 2026
986bddb
fix: use ble for bridge
montelaidev Mar 12, 2026
e434b83
fix: rename bridge and transport to be mobile specific
montelaidev Mar 12, 2026
c27079a
fix: remove patch
montelaidev Mar 12, 2026
b3e201b
Merge remote-tracking branch 'origin/main' into feat/ledger-dmk-mobile
montelaidev May 27, 2026
424c816
chore: add .worktrees/ to .gitignore
montelaidev May 28, 2026
e80fc5b
feat(speculos): add @metamask/speculos and @metamask/speculos-up pack…
montelaidev May 28, 2026
5b74d06
fix(speculos): resolve all ESLint errors across both packages
montelaidev May 28, 2026
e7361c9
feat: update to hw-emulator
montelaidev May 28, 2026
aea9751
fix: remove not used
montelaidev May 28, 2026
5320a49
fix: retry
montelaidev May 28, 2026
a73de59
revert: ledger code
montelaidev May 28, 2026
50391d0
fix: readme and licence
montelaidev May 28, 2026
abde647
fix: remove the download ability
montelaidev May 28, 2026
8c2a839
fix: update lock
montelaidev May 28, 2026
e3611c6
chore: add changelog
montelaidev May 28, 2026
4bf3baf
fix: lint, add jsdoc and pass env to docker
montelaidev May 28, 2026
0c3023d
feat: add speculos up
montelaidev May 29, 2026
c769de1
fix: address comments
montelaidev May 29, 2026
c019355
fix: yarn lock
montelaidev May 29, 2026
e843f55
fix: display env
montelaidev May 29, 2026
85a9ca9
fix: changelog and readme
montelaidev May 29, 2026
22cfc1a
fix: seed
montelaidev May 30, 2026
45eb689
feat: create default binary and scripts to generate binary
montelaidev May 30, 2026
8f2d47b
feat: create default binary and scripts to generate binary
montelaidev May 30, 2026
9ae4604
fix: test and lint
montelaidev May 31, 2026
c77d9ee
fix: package name and lint
montelaidev May 31, 2026
08e9687
fix: change runner type
montelaidev May 31, 2026
0ab7c8c
fix: lint
montelaidev May 31, 2026
de887b2
fix: lint and have ci only build linux
montelaidev May 31, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -77,4 +77,7 @@ node_modules/
!.yarn/versions

# Cursor rules
.cursorrules
.cursorrules

# Git worktrees
.worktrees/
2 changes: 1 addition & 1 deletion eslint-suppressions.json
Original file line number Diff line number Diff line change
Expand Up @@ -254,4 +254,4 @@
"count": 2
}
}
}
}
21 changes: 21 additions & 0 deletions packages/hw-emulator/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 MetaMask

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
137 changes: 137 additions & 0 deletions packages/hw-emulator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
# `@metamask/hw-emulator`

Hardware wallet emulator lifecycle, transport, and device interaction for E2E testing.

Provides a programmatic interface for launching and controlling hardware wallet emulators (Ledger via [Speculos](https://github.com/LedgerHQ/speculos)), sending APDU commands, and automating device screen interactions (button presses, touch gestures) — all without physical hardware.

## Installation

`yarn add @metamask/hw-emulator`

or

`npm install @metamask/hw-emulator`

## Supported Devices

| Device | Model ID | Interaction Type |
| --------- | -------- | ---------------- |
| Nano S+ | `nanosp` | Button |
| Nano X | `nanox` | Button |
| Stax | `stax` | Touch |
| Flex | `flex` | Touch |

## Quick Start

### Docker Mode (recommended for macOS / CI)

```typescript
import { createEmulator, EmulatorType } from '@metamask/hw-emulator';

const emulator = createEmulator(EmulatorType.Ledger, {
device: 'flex',
mode: 'docker',
});

await emulator.start();
await emulator.approveTransaction();
await emulator.stop();
```

### Native Mode (Linux only)

Requires the Speculos binary to be installed and available on `PATH`, or passed via the `binary` option.

```typescript
import { createEmulator, EmulatorType } from '@metamask/hw-emulator';

const emulator = createEmulator(EmulatorType.Ledger, {
device: 'nanosp',
mode: 'native',
binary: '/usr/local/bin/speculos',
});

await emulator.start();
await emulator.approveSigning();
await emulator.stop();
```

## API

### `createEmulator(type, options?)`

Factory function that creates a `HardwareWalletEmulator` instance.

- **`type`** — `'ledger'` (via `EmulatorType.Ledger`). Trezor support is not yet implemented.
- **`options`** — See [`SpeculosOptions`](#speculosoptions).

### `HardwareWalletEmulator`

| Method | Description |
| ------------------------ | ---------------------------------------- |
| `start()` | Start the emulator (Docker or native). |
| `stop()` | Stop the emulator and clean up resources.|
| `isRunning()` | Returns whether the emulator is active. |
| `approveTransaction()` | Approve the current transaction on screen.|
| `approveSigning()` | Approve the current signing request. |
| `rejectTransaction()` | Reject the current transaction on screen.|
| `navigateToMainMenu()` | Navigate back to the device main menu. |
| `getInteraction()` | Get the low-level device interaction API. |

### `SpeculosOptions`

| Option | Type | Default | Description |
| --------------- | -------- | ----------- | ----------------------------------------------- |
| `device` | `string` | `'flex'` | Device model ID (`nanosp`, `nanox`, `stax`, `flex`). |
| `seed` | `string` | Built-in | Mnemonic seed for deterministic accounts. |
| `apduPort` | `number` | `9998` | APDU communication port. |
| `apiPort` | `number` | `5001` | Speculos REST API port. |
| `wsBridgePort` | `number` | `9876` | WebSocket bridge port for WebHID mock. |
| `mode` | `string` | Auto | Run mode: `'docker'` or `'native'`. Auto-detected. |
| `binary` | `string` | — | Path to Speculos binary (native mode only). |
| `display` | `string` | `'headless'`| Display mode. |
| `loadNvram` | `boolean`| `true` | Load persisted NVRAM state. |
| `startTimeout` | `number` | `60000` | Startup timeout in ms. |

### Low-Level APIs

The package also exports granular components for advanced use cases:

- **`SpeculosClient`** — HTTP client for the Speculos REST API (APDU exchange, screen events).
- **`ApduBridge`** — WebSocket-to-APDU bridge for browser-based WebHID mocking.
- **`DockerManager`** — Direct Docker Compose lifecycle management.
- **`createProcessManager()`** — Native Speculos process spawning and monitoring.
- **`createDeviceInteraction()`** — Screen automation (button presses, touch coordinates).
- **`withRetry()` / `ExponentialBackoff`** — Resilience utilities for flaky device communication.
- **`createLedgerHidFramingSession()`** — Low-level Ledger HID frame encoding/decoding.
- **`getWebHidMockScript()`** — Generates a browser script to mock WebHID for E2E tests.

## Docker Setup

The package includes a `docker-compose.yml` for running Speculos via Docker:

```bash
# Start with default device (Flex)
docker compose up -d

# Start with a specific device
SPECULOS_DEVICE=nanosp docker compose up -d
```

The ELF app binaries for all supported devices are bundled in the `apps/` directory.

## Deterministic Accounts

The default seed produces these pre-funded Ethereum accounts:

| Index | Address |
| ----- | ------------------------------------------------ |
| 0 | `0x24fC293546A31F5Ce73bAfecE37969A95CCd1aBf` |
| 1 | `0x730A5c73bC3ACcf56daba2D5D897bEb10F852865` |
| 2 | `0x805c2797CCBa57887F5fA0DD95C017145d67604a` |
| 3 | `0x2Bf9972F600D8C3B3f0AEe8f1e17Fc4631242fF4` |
| 4 | `0xDc660e6D52F6f774d0879f99929711155Bc03902` |

## Contributing

This package is part of a monorepo. Instructions for contributing can be found in the [monorepo README](https://github.com/MetaMask/accounts#readme).
Binary file added packages/hw-emulator/apps/ethereum-apex_p.elf
Binary file not shown.
Binary file added packages/hw-emulator/apps/ethereum-flex.elf
Binary file not shown.
Binary file added packages/hw-emulator/apps/ethereum-nanosp.elf
Binary file not shown.
Binary file added packages/hw-emulator/apps/ethereum-nanox.elf
Binary file not shown.
Binary file added packages/hw-emulator/apps/ethereum-stax.elf
Binary file not shown.
36 changes: 36 additions & 0 deletions packages/hw-emulator/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
version: '3.8'
services:
speculos:
image: ghcr.io/ledgerhq/speculos:latest
container_name: metamask-speculos
ports:
- '9998:9999'
- '5001:5000'
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated
volumes:
- ./apps:/speculos/apps
- ./nvram/main_nvram.bin:/speculos/main_nvram.bin
environment:
- DISPLAY=:99
command: >
--model ${SPECULOS_DEVICE:-nanosp}
/speculos/apps/${SPECULOS_ELF_FILENAME:-ethereum-nanosp.elf}
--seed "urban secret spare tunnel rubber rally ladder spatial feature elite success"
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated
--display headless
Comment thread
cursor[bot] marked this conversation as resolved.
Outdated
--apdu-port 9999
--api-port 5000
--load-nvram
healthcheck:
test:
- CMD-SHELL
- python3 -c "import urllib.request; urllib.request.urlopen('http://localhost:5000/')"
interval: 2s
timeout: 3s
retries: 10

---
# Note:
# - APDU port mapped from host 9998 to container 9999 (9999 is used by PhishingWarningPageServer)
# - REST API mapped from host 5001 to container 5000 (5000 used by macOS Control Center)
# - SPECULOS_DEVICE selects the device model (nanosp, nanox, stax, flex)
# - SPECULOS_ELF_FILENAME is the ELF filename inside /speculos/apps/ (NOT the host path)
# - Defaults to Nano S+ (nanosp) for local development without SPECULOS_DEVICE set
8 changes: 8 additions & 0 deletions packages/hw-emulator/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const merge = require('deepmerge');
const path = require('path');
const baseConfig = require('../../jest.config.packages');

module.exports = merge(baseConfig, {
displayName: path.basename(__dirname),
coverageThreshold: { global: { branches: 10, functions: 20, lines: 20, statements: 20 } },
});
Binary file added packages/hw-emulator/nvram/main_nvram.bin
Binary file not shown.
95 changes: 95 additions & 0 deletions packages/hw-emulator/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
{
"name": "@metamask/hw-emulator",
"version": "0.1.0",
"description": "Hardware wallet emulator lifecycle, transport, and device interaction for E2E testing",
"keywords": [
"hardware-wallet",
"emulator",
"ledger",
"trezor",
"e2e",
"testing",
"metamask"
],
"homepage": "https://github.com/MetaMask/accounts/tree/main/packages/hw-emulator#readme",
"bugs": {
"url": "https://github.com/MetaMask/accounts/issues"
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/MetaMask/accounts.git"
},
"files": [
"dist/",
"apps/",
"nvram/",
"docker-compose.yml"
],
"sideEffects": false,
"main": "./dist/index.cjs",
"types": "./dist/index.d.cts",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./package.json": "./package.json"
},
"publishConfig": {
"access": "public",
"registry": "https://registry.npmjs.org/"
},
"scripts": {
"build": "ts-bridge --project tsconfig.build.json --verbose --clean --no-references",
"build:all": "ts-bridge --project tsconfig.build.json --verbose --clean",
"build:clean": "yarn build --clean",
"build:docs": "typedoc",
"changelog:update": "../../scripts/update-changelog.sh @metamask/hw-emulator",
"changelog:validate": "../../scripts/validate-changelog.sh @metamask/hw-emulator",
"publish:preview": "yarn npm publish --tag preview",
"since-latest-release": "../../scripts/since-latest-release.sh",
"test": "yarn test:source && yarn test:types",
"test:clean": "NODE_OPTIONS=--experimental-vm-modules jest --clearCache",
"test:source": "NODE_OPTIONS=--experimental-vm-modules jest --reporters=jest-silent-reporter",
"test:types": "../../scripts/tsd-test.sh ./src",
"test:verbose": "NODE_OPTIONS=--experimental-vm-modules jest --verbose",
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
},
"dependencies": {
"@ledgerhq/devices": "^7.0.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@lavamoat/allow-scripts": "^3.2.1",
"@lavamoat/preinstall-always-fail": "^2.1.0",
"@metamask/auto-changelog": "^6.1.0",
"@ts-bridge/cli": "^0.6.3",
"@types/jest": "^29.5.12",
"@types/node": "^20.12.12",
"@types/ws": "^8.18.1",
"depcheck": "^1.4.7",
"jest": "^29.5.0",
"jest-it-up": "^3.1.0",
"rimraf": "^5.0.7",
"ts-jest": "^29.0.5",
"ts-node": "^10.9.2",
"tsd": "^0.31.0",
"typedoc": "^0.25.13",
"typescript": "~5.3.3"
},
"engines": {
"node": "^18.18 || >=20"
},
"lavamoat": {
"allowScripts": {
"@lavamoat/preinstall-always-fail": false
}
}
}
50 changes: 50 additions & 0 deletions packages/hw-emulator/src/factory.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { createEmulator } from './factory';
import { EmulatorType } from './types';
import type { EmulatorType as EmulatorTypeValue } from './types';

describe('createEmulator', () => {
it('creates a Ledger emulator', () => {
const emu = createEmulator(EmulatorType.Ledger);
expect(emu).toBeDefined();
expect(emu.isRunning()).toBe(false);
});

it('creates a Ledger emulator with options', () => {
const emu = createEmulator(EmulatorType.Ledger, { device: 'nanosp' });
expect(emu).toBeDefined();
expect(emu.isRunning()).toBe(false);
});

it('creates a Ledger emulator from an EmulatorType value', () => {
const type: EmulatorTypeValue = EmulatorType.Ledger;

const emu = createEmulator(type);

expect(emu).toBeDefined();
expect(emu.isRunning()).toBe(false);
});

it('throws for trezor (not yet implemented)', () => {
expect(() => createEmulator(EmulatorType.Trezor)).toThrow(
'Trezor emulator is not yet implemented',
);
});

it('throws for unknown emulator type', () => {
expect(() =>
createEmulator('unknown' as typeof EmulatorType.Ledger),
).toThrow('Unknown emulator type');
});

it('returns an emulator with the HardwareWalletEmulator interface', () => {
const emu = createEmulator(EmulatorType.Ledger);
expect(typeof emu.start).toBe('function');
expect(typeof emu.stop).toBe('function');
expect(typeof emu.isRunning).toBe('function');
expect(typeof emu.getInteraction).toBe('function');
expect(typeof emu.approveTransaction).toBe('function');
expect(typeof emu.approveSigning).toBe('function');
expect(typeof emu.rejectTransaction).toBe('function');
expect(typeof emu.navigateToMainMenu).toBe('function');
});
});
Loading
Loading