@metamask-previews/eth-trezor-keyring 10.1.0-c42f34c → 10.1.0-e51c895

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -9,8 +9,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
- - Bump `@metamask/keyring-api` from `^23.1.0` to `^23.2.0` ([#562](https://github.com/MetaMask/accounts/pull/562))
12
+ - Bump `@metamask/keyring-api` from `^23.1.0` to `^23.3.0` ([#562](https://github.com/MetaMask/accounts/pull/562), [#569](https://github.com/MetaMask/accounts/pull/569))
13
13
  - Bump `@metamask/keyring-sdk` from `^2.1.1` to `^2.2.0` ([#562](https://github.com/MetaMask/accounts/pull/562))
14
+ - Bump `@metamask/hw-wallet-sdk` from `^0.8.0` to `^0.9.0` ([#576](https://github.com/MetaMask/accounts/pull/576))
15
+
16
+ ### Fixed
17
+
18
+ - Surface Trezor user cancellation and rejection errors as `UserCancelled`/`UserRejected` instead of `ErrorCode.Unknown`, fixing uninformative "Unknown error" messages when users reject signing ([#576](https://github.com/MetaMask/accounts/pull/576))
19
+ - Complements [MetaMask/core#8490](https://github.com/MetaMask/core/pull/8490) and fixes [metamask-extension#41184](https://github.com/MetaMask/metamask-extension/issues/41184).
14
20
 
15
21
  ## [10.1.0]
16
22
 
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createErrorFromTrezorResponse = void 0;
4
+ /**
5
+ * Creates an Error from a Trezor Connect unsuccessful response payload.
6
+ * Preserves machine-readable Trezor error codes when present.
7
+ *
8
+ * @param payload - The error payload from a Trezor Connect response.
9
+ * @returns An Error with optional `.code` for downstream mapping.
10
+ */
11
+ function createErrorFromTrezorResponse(payload) {
12
+ var _a;
13
+ const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : 'Unknown error';
14
+ const error = new Error(message);
15
+ if ((payload === null || payload === void 0 ? void 0 : payload.code) !== undefined) {
16
+ Object.assign(error, { code: payload.code });
17
+ }
18
+ return error;
19
+ }
20
+ exports.createErrorFromTrezorResponse = createErrorFromTrezorResponse;
21
+ //# sourceMappingURL=trezor-bridge-error.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge-error.cjs","sourceRoot":"","sources":["../src/trezor-bridge-error.ts"],"names":[],"mappings":";;;AAKA;;;;;;GAMG;AACH,SAAgB,6BAA6B,CAC3C,OAAuC;;IAEvC,MAAM,OAAO,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK,mCAAI,eAAe,CAAC;IAClD,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAEjC,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,MAAK,SAAS,EAAE,CAAC;QAChC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAXD,sEAWC","sourcesContent":["type TrezorErrorPayload = {\n error?: string;\n code?: string;\n};\n\n/**\n * Creates an Error from a Trezor Connect unsuccessful response payload.\n * Preserves machine-readable Trezor error codes when present.\n *\n * @param payload - The error payload from a Trezor Connect response.\n * @returns An Error with optional `.code` for downstream mapping.\n */\nexport function createErrorFromTrezorResponse(\n payload: TrezorErrorPayload | undefined,\n): Error {\n const message = payload?.error ?? 'Unknown error';\n const error = new Error(message);\n\n if (payload?.code !== undefined) {\n Object.assign(error, { code: payload.code });\n }\n\n return error;\n}\n"]}
@@ -0,0 +1,14 @@
1
+ type TrezorErrorPayload = {
2
+ error?: string;
3
+ code?: string;
4
+ };
5
+ /**
6
+ * Creates an Error from a Trezor Connect unsuccessful response payload.
7
+ * Preserves machine-readable Trezor error codes when present.
8
+ *
9
+ * @param payload - The error payload from a Trezor Connect response.
10
+ * @returns An Error with optional `.code` for downstream mapping.
11
+ */
12
+ export declare function createErrorFromTrezorResponse(payload: TrezorErrorPayload | undefined): Error;
13
+ export {};
14
+ //# sourceMappingURL=trezor-bridge-error.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge-error.d.cts","sourceRoot":"","sources":["../src/trezor-bridge-error.ts"],"names":[],"mappings":"AAAA,KAAK,kBAAkB,GAAG;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,kBAAkB,GAAG,SAAS,GACtC,KAAK,CASP"}
@@ -0,0 +1,14 @@
1
+ type TrezorErrorPayload = {
2
+ error?: string;
3
+ code?: string;
4
+ };
5
+ /**
6
+ * Creates an Error from a Trezor Connect unsuccessful response payload.
7
+ * Preserves machine-readable Trezor error codes when present.
8
+ *
9
+ * @param payload - The error payload from a Trezor Connect response.
10
+ * @returns An Error with optional `.code` for downstream mapping.
11
+ */
12
+ export declare function createErrorFromTrezorResponse(payload: TrezorErrorPayload | undefined): Error;
13
+ export {};
14
+ //# sourceMappingURL=trezor-bridge-error.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge-error.d.mts","sourceRoot":"","sources":["../src/trezor-bridge-error.ts"],"names":[],"mappings":"AAAA,KAAK,kBAAkB,GAAG;IACxB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,IAAI,CAAC,EAAE,MAAM,CAAC;CACf,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,kBAAkB,GAAG,SAAS,GACtC,KAAK,CASP"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Creates an Error from a Trezor Connect unsuccessful response payload.
3
+ * Preserves machine-readable Trezor error codes when present.
4
+ *
5
+ * @param payload - The error payload from a Trezor Connect response.
6
+ * @returns An Error with optional `.code` for downstream mapping.
7
+ */
8
+ export function createErrorFromTrezorResponse(payload) {
9
+ var _a;
10
+ const message = (_a = payload === null || payload === void 0 ? void 0 : payload.error) !== null && _a !== void 0 ? _a : 'Unknown error';
11
+ const error = new Error(message);
12
+ if ((payload === null || payload === void 0 ? void 0 : payload.code) !== undefined) {
13
+ Object.assign(error, { code: payload.code });
14
+ }
15
+ return error;
16
+ }
17
+ //# sourceMappingURL=trezor-bridge-error.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge-error.mjs","sourceRoot":"","sources":["../src/trezor-bridge-error.ts"],"names":[],"mappings":"AAKA;;;;;;GAMG;AACH,MAAM,UAAU,6BAA6B,CAC3C,OAAuC;;IAEvC,MAAM,OAAO,GAAG,MAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,KAAK,mCAAI,eAAe,CAAC;IAClD,MAAM,KAAK,GAAG,IAAI,KAAK,CAAC,OAAO,CAAC,CAAC;IAEjC,IAAI,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,IAAI,MAAK,SAAS,EAAE,CAAC;QAChC,MAAM,CAAC,MAAM,CAAC,KAAK,EAAE,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC;IAC/C,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["type TrezorErrorPayload = {\n error?: string;\n code?: string;\n};\n\n/**\n * Creates an Error from a Trezor Connect unsuccessful response payload.\n * Preserves machine-readable Trezor error codes when present.\n *\n * @param payload - The error payload from a Trezor Connect response.\n * @returns An Error with optional `.code` for downstream mapping.\n */\nexport function createErrorFromTrezorResponse(\n payload: TrezorErrorPayload | undefined,\n): Error {\n const message = payload?.error ?? 'Unknown error';\n const error = new Error(message);\n\n if (payload?.code !== undefined) {\n Object.assign(error, { code: payload.code });\n }\n\n return error;\n}\n"]}
@@ -3,6 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.handleTrezorTransportError = void 0;
4
4
  const hw_wallet_sdk_1 = require("@metamask/hw-wallet-sdk");
5
5
  const trezor_errors_1 = require("./trezor-errors.cjs");
6
+ const USER_REJECTION_TREZOR_IDENTIFIERS = {
7
+ [hw_wallet_sdk_1.ErrorCode.UserCancelled]: 'Failure_ActionCancelled',
8
+ [hw_wallet_sdk_1.ErrorCode.UserRejected]: 'Method_PermissionsNotGranted',
9
+ };
6
10
  function getErrorDetails(error) {
7
11
  const details = {
8
12
  message: error.message,
@@ -13,6 +17,9 @@ function getErrorDetails(error) {
13
17
  if (typeof code === 'string') {
14
18
  details.code = code;
15
19
  }
20
+ else if (typeof code === 'number') {
21
+ details.code = String(code);
22
+ }
16
23
  }
17
24
  return details;
18
25
  }
@@ -34,6 +41,10 @@ function handleTrezorTransportError(error, fallbackMessage) {
34
41
  if (identifier) {
35
42
  throw (0, trezor_errors_1.createTrezorError)(identifier, details.message);
36
43
  }
44
+ const userRejectionCode = (0, hw_wallet_sdk_1.resolveUserRejectionErrorCode)(error);
45
+ if (userRejectionCode !== undefined) {
46
+ throw (0, trezor_errors_1.createTrezorError)(USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode], details.message);
47
+ }
37
48
  throw new hw_wallet_sdk_1.HardwareWalletError((_a = details.message) !== null && _a !== void 0 ? _a : fallbackMessage, {
38
49
  code: hw_wallet_sdk_1.ErrorCode.Unknown,
39
50
  severity: hw_wallet_sdk_1.Severity.Err,
@@ -42,6 +53,10 @@ function handleTrezorTransportError(error, fallbackMessage) {
42
53
  cause: error,
43
54
  });
44
55
  }
56
+ const userRejectionCode = (0, hw_wallet_sdk_1.resolveUserRejectionErrorCode)(error);
57
+ if (userRejectionCode !== undefined) {
58
+ throw (0, trezor_errors_1.createTrezorError)(USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode]);
59
+ }
45
60
  throw new hw_wallet_sdk_1.HardwareWalletError(fallbackMessage, {
46
61
  code: hw_wallet_sdk_1.ErrorCode.Unknown,
47
62
  severity: hw_wallet_sdk_1.Severity.Err,
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-error-handler.cjs","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":";;;AAAA,2DAKiC;AAEjC,uDAAwE;AAQxE,SAAS,eAAe,CAAC,KAAY;IACnC,MAAM,OAAO,GAAiB;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC;IAEF,IAAI,MAAM,IAAI,KAAK,EAAE,CAAC;QACpB,MAAM,EAAE,IAAI,EAAE,GAAG,KAAmC,CAAC;QACrD,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;QACtB,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,0BAA0B,CACxC,KAAc,EACd,eAAuB;;IAEvB,IAAI,KAAK,YAAY,mCAAmB,EAAE,CAAC;QACzC,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,MAAM,UAAU,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC,IAAI,CACnE,CAAC,KAAK,EAAmB,EAAE,CACzB,KAAK,KAAK,SAAS,IAAI,IAAA,kCAAkB,EAAC,KAAK,CAAC,CACnD,CAAC;QAEF,IAAI,UAAU,EAAE,CAAC;YACf,MAAM,IAAA,iCAAiB,EAAC,UAAU,EAAE,OAAO,CAAC,OAAO,CAAC,CAAC;QACvD,CAAC;QAED,MAAM,IAAI,mCAAmB,CAAC,MAAA,OAAO,CAAC,OAAO,mCAAI,eAAe,EAAE;YAChE,IAAI,EAAE,yBAAS,CAAC,OAAO;YACvB,QAAQ,EAAE,wBAAQ,CAAC,GAAG;YACtB,QAAQ,EAAE,wBAAQ,CAAC,OAAO;YAC1B,WAAW,EAAE,MAAA,OAAO,CAAC,OAAO,mCAAI,eAAe;YAC/C,KAAK,EAAE,KAAK;SACb,CAAC,CAAC;IACL,CAAC;IAED,MAAM,IAAI,mCAAmB,CAAC,eAAe,EAAE;QAC7C,IAAI,EAAE,yBAAS,CAAC,OAAO;QACvB,QAAQ,EAAE,wBAAQ,CAAC,GAAG;QACtB,QAAQ,EAAE,wBAAQ,CAAC,OAAO;QAC1B,WAAW,EAAE,eAAe;KAC7B,CAAC,CAAC;AACL,CAAC;AAlCD,gEAkCC","sourcesContent":["import {\n ErrorCode,\n Severity,\n Category,\n HardwareWalletError,\n} from '@metamask/hw-wallet-sdk';\n\nimport { createTrezorError, isKnownTrezorError } from './trezor-errors';\n\ntype ErrorDetails = {\n message?: string;\n code?: string;\n name?: string;\n};\n\nfunction getErrorDetails(error: Error): ErrorDetails {\n const details: ErrorDetails = {\n message: error.message,\n name: error.name,\n };\n\n if ('code' in error) {\n const { code } = error as Error & { code?: unknown };\n if (typeof code === 'string') {\n details.code = code;\n }\n }\n\n return details;\n}\n\n/**\n * Converts unknown Trezor errors into typed HardwareWalletError instances.\n *\n * @param error - Error thrown from Trezor bridge or keyring flow.\n * @param fallbackMessage - Default message for unknown non-Error inputs.\n * @throws HardwareWalletError Always throws typed errors.\n */\nexport function handleTrezorTransportError(\n error: unknown,\n fallbackMessage: string,\n): never {\n if (error instanceof HardwareWalletError) {\n throw error;\n }\n\n if (error instanceof Error) {\n const details = getErrorDetails(error);\n const identifier = [details.code, details.name, details.message].find(\n (value): value is string =>\n value !== undefined && isKnownTrezorError(value),\n );\n\n if (identifier) {\n throw createTrezorError(identifier, details.message);\n }\n\n throw new HardwareWalletError(details.message ?? fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: details.message ?? fallbackMessage,\n cause: error,\n });\n }\n\n throw new HardwareWalletError(fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: fallbackMessage,\n });\n}\n"]}
1
+ {"version":3,"file":"trezor-error-handler.cjs","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":";;;AAAA,2DAMiC;AAEjC,uDAAwE;AAQxE,MAAM,iCAAiC,GAGnC;IACF,CAAC,yBAAS,CAAC,aAAa,CAAC,EAAE,yBAAyB;IACpD,CAAC,yBAAS,CAAC,YAAY,CAAC,EAAE,8BAA8B;CACzD,CAAC;AAEF,SAAS,eAAe,CAAC,KAAY;IACnC,MAAM,OAAO,GAAiB;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC;IAEF,IAAI,MAAM,IAAI,KAAK,EAAE,CAAC;QACpB,MAAM,EAAE,IAAI,EAAE,GAAG,KAAmC,CAAC;QACrD,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;QACtB,CAAC;aAAM,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YACpC,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;IAED,OAAO,OAAO,CAAC;AACjB,CAAC;AAED;;;;;;GAMG;AACH,SAAgB,0BAA0B,CACxC,KAAc,EACd,eAAuB;;IAEvB,IAAI,KAAK,YAAY,mCAAmB,EAAE,CAAC;QACzC,MAAM,KAAK,CAAC;IACd,CAAC;IAED,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,MAAM,OAAO,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;QACvC,MAAM,UAAU,GAAG,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,OA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\n Category,\n HardwareWalletError,\n resolveUserRejectionErrorCode,\n} from '@metamask/hw-wallet-sdk';\n\nimport { createTrezorError, isKnownTrezorError } from './trezor-errors';\n\ntype ErrorDetails = {\n message?: string;\n code?: string;\n name?: string;\n};\n\nconst USER_REJECTION_TREZOR_IDENTIFIERS: Record<\n ErrorCode.UserCancelled | ErrorCode.UserRejected,\n string\n> = {\n [ErrorCode.UserCancelled]: 'Failure_ActionCancelled',\n [ErrorCode.UserRejected]: 'Method_PermissionsNotGranted',\n};\n\nfunction getErrorDetails(error: Error): ErrorDetails {\n const details: ErrorDetails = {\n message: error.message,\n name: error.name,\n };\n\n if ('code' in error) {\n const { code } = error as Error & { code?: unknown };\n if (typeof code === 'string') {\n details.code = code;\n } else if (typeof code === 'number') {\n details.code = String(code);\n }\n }\n\n return details;\n}\n\n/**\n * Converts unknown Trezor errors into typed HardwareWalletError instances.\n *\n * @param error - Error thrown from Trezor bridge or keyring flow.\n * @param fallbackMessage - Default message for unknown non-Error inputs.\n * @throws HardwareWalletError Always throws typed errors.\n */\nexport function handleTrezorTransportError(\n error: unknown,\n fallbackMessage: string,\n): never {\n if (error instanceof HardwareWalletError) {\n throw error;\n }\n\n if (error instanceof Error) {\n const details = getErrorDetails(error);\n const identifier = [details.code, details.name, details.message].find(\n (value): value is string =>\n value !== undefined && isKnownTrezorError(value),\n );\n\n if (identifier) {\n throw createTrezorError(identifier, details.message);\n }\n\n const userRejectionCode = resolveUserRejectionErrorCode(error);\n if (userRejectionCode !== undefined) {\n throw createTrezorError(\n USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode],\n details.message,\n );\n }\n\n throw new HardwareWalletError(details.message ?? fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: details.message ?? fallbackMessage,\n cause: error,\n });\n }\n\n const userRejectionCode = resolveUserRejectionErrorCode(error);\n if (userRejectionCode !== undefined) {\n throw createTrezorError(\n USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode],\n );\n }\n\n throw new HardwareWalletError(fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: fallbackMessage,\n });\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-error-handler.d.cts","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":"AA+BA;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,OAAO,EACd,eAAe,EAAE,MAAM,GACtB,KAAK,CA+BP"}
1
+ {"version":3,"file":"trezor-error-handler.d.cts","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":"AA0CA;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,OAAO,EACd,eAAe,EAAE,MAAM,GACtB,KAAK,CA8CP"}
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-error-handler.d.mts","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":"AA+BA;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,OAAO,EACd,eAAe,EAAE,MAAM,GACtB,KAAK,CA+BP"}
1
+ {"version":3,"file":"trezor-error-handler.d.mts","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":"AA0CA;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CACxC,KAAK,EAAE,OAAO,EACd,eAAe,EAAE,MAAM,GACtB,KAAK,CA8CP"}
@@ -1,5 +1,9 @@
1
- import { ErrorCode, Severity, Category, HardwareWalletError } from "@metamask/hw-wallet-sdk";
1
+ import { ErrorCode, Severity, Category, HardwareWalletError, resolveUserRejectionErrorCode } from "@metamask/hw-wallet-sdk";
2
2
  import { createTrezorError, isKnownTrezorError } from "./trezor-errors.mjs";
3
+ const USER_REJECTION_TREZOR_IDENTIFIERS = {
4
+ [ErrorCode.UserCancelled]: 'Failure_ActionCancelled',
5
+ [ErrorCode.UserRejected]: 'Method_PermissionsNotGranted',
6
+ };
3
7
  function getErrorDetails(error) {
4
8
  const details = {
5
9
  message: error.message,
@@ -10,6 +14,9 @@ function getErrorDetails(error) {
10
14
  if (typeof code === 'string') {
11
15
  details.code = code;
12
16
  }
17
+ else if (typeof code === 'number') {
18
+ details.code = String(code);
19
+ }
13
20
  }
14
21
  return details;
15
22
  }
@@ -31,6 +38,10 @@ export function handleTrezorTransportError(error, fallbackMessage) {
31
38
  if (identifier) {
32
39
  throw createTrezorError(identifier, details.message);
33
40
  }
41
+ const userRejectionCode = resolveUserRejectionErrorCode(error);
42
+ if (userRejectionCode !== undefined) {
43
+ throw createTrezorError(USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode], details.message);
44
+ }
34
45
  throw new HardwareWalletError((_a = details.message) !== null && _a !== void 0 ? _a : fallbackMessage, {
35
46
  code: ErrorCode.Unknown,
36
47
  severity: Severity.Err,
@@ -39,6 +50,10 @@ export function handleTrezorTransportError(error, fallbackMessage) {
39
50
  cause: error,
40
51
  });
41
52
  }
53
+ const userRejectionCode = resolveUserRejectionErrorCode(error);
54
+ if (userRejectionCode !== undefined) {
55
+ throw createTrezorError(USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode]);
56
+ }
42
57
  throw new HardwareWalletError(fallbackMessage, {
43
58
  code: ErrorCode.Unknown,
44
59
  severity: Severity.Err,
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-error-handler.mjs","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACpB,gCAAgC;AAEjC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,4BAAwB;AAQxE,SAAS,eAAe,CAAC,KAAY;IACnC,MAAM,OAAO,GAAiB;QAC5B,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,IAAI,EAAE,KAAK,CAAC,IAAI;KACjB,CAAC;IAEF,IAAI,MAAM,IAAI,K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,OAAO;QAC1B,WAAW,EAAE,eAAe;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n ErrorCode,\n Severity,\n Category,\n HardwareWalletError,\n} from '@metamask/hw-wallet-sdk';\n\nimport { createTrezorError, isKnownTrezorError } from './trezor-errors';\n\ntype ErrorDetails = {\n message?: string;\n code?: string;\n name?: string;\n};\n\nfunction getErrorDetails(error: Error): ErrorDetails {\n const details: ErrorDetails = {\n message: error.message,\n name: error.name,\n };\n\n if ('code' in error) {\n const { code } = error as Error & { code?: unknown };\n if (typeof code === 'string') {\n details.code = code;\n }\n }\n\n return details;\n}\n\n/**\n * Converts unknown Trezor errors into typed HardwareWalletError instances.\n *\n * @param error - Error thrown from Trezor bridge or keyring flow.\n * @param fallbackMessage - Default message for unknown non-Error inputs.\n * @throws HardwareWalletError Always throws typed errors.\n */\nexport function handleTrezorTransportError(\n error: unknown,\n fallbackMessage: string,\n): never {\n if (error instanceof HardwareWalletError) {\n throw error;\n }\n\n if (error instanceof Error) {\n const details = getErrorDetails(error);\n const identifier = [details.code, details.name, details.message].find(\n (value): value is string =>\n value !== undefined && isKnownTrezorError(value),\n );\n\n if (identifier) {\n throw createTrezorError(identifier, details.message);\n }\n\n throw new HardwareWalletError(details.message ?? fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: details.message ?? fallbackMessage,\n cause: error,\n });\n }\n\n throw new HardwareWalletError(fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: fallbackMessage,\n });\n}\n"]}
1
+ {"version":3,"file":"trezor-error-handler.mjs","sourceRoot":"","sources":["../src/trezor-error-handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,SAAS,EACT,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,6BAA6B,EAC9B,gCAAgC;AAEjC,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,4BAAwB;AAQxE,MAAM,iC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CAAC,KAAK,CAAC,CAAC;QAC/D,IAAI,iBAAiB,KAAK,SAAS,EAAE,CAAC;YACpC,MAAM,iBAAiB,CACrB,iCAAiC,CAAC,iBAAiB,CAAC,EACpD,OAAO,CAAC,OAAO,CAChB,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,mBAAmB,CAAC,MAAA,OAAO,CAAC,OAAO,mCAAI,eAAe,EAAE;YAChE,IAAI,EAAE,SAAS,CAAC,OAAO;YACvB,QAAQ,EAAE,QAAQ,CAAC,GAAG;YACtB,QAAQ,EAAE,QAAQ,CAAC,OAAO;YAC1B,WAAW,EAAE,MAAA,OAAO,CAAC,OAAO,mCAAI,eAAe;YAC/C,KAAK,EAAE,KAAK;SACb,CAAC,CAAC;IACL,CAAC;IAED,MAAM,iBAAiB,GAAG,6BAA6B,CAAC,KAAK,CAAC,CAAC;IAC/D,IAAI,iBAAiB,KAAK,SAAS,EAAE,CAAC;QACpC,MAAM,iBAAiB,CACrB,iCAAiC,CAAC,iBAAiB,CAAC,CACrD,CAAC;IACJ,CAAC;IAED,MAAM,IAAI,mBAAmB,CAAC,eAAe,EAAE;QAC7C,IAAI,EAAE,SAAS,CAAC,OAAO;QACvB,QAAQ,EAAE,QAAQ,CAAC,GAAG;QACtB,QAAQ,EAAE,QAAQ,CAAC,OAAO;QAC1B,WAAW,EAAE,eAAe;KAC7B,CAAC,CAAC;AACL,CAAC","sourcesContent":["import {\n ErrorCode,\n Severity,\n Category,\n HardwareWalletError,\n resolveUserRejectionErrorCode,\n} from '@metamask/hw-wallet-sdk';\n\nimport { createTrezorError, isKnownTrezorError } from './trezor-errors';\n\ntype ErrorDetails = {\n message?: string;\n code?: string;\n name?: string;\n};\n\nconst USER_REJECTION_TREZOR_IDENTIFIERS: Record<\n ErrorCode.UserCancelled | ErrorCode.UserRejected,\n string\n> = {\n [ErrorCode.UserCancelled]: 'Failure_ActionCancelled',\n [ErrorCode.UserRejected]: 'Method_PermissionsNotGranted',\n};\n\nfunction getErrorDetails(error: Error): ErrorDetails {\n const details: ErrorDetails = {\n message: error.message,\n name: error.name,\n };\n\n if ('code' in error) {\n const { code } = error as Error & { code?: unknown };\n if (typeof code === 'string') {\n details.code = code;\n } else if (typeof code === 'number') {\n details.code = String(code);\n }\n }\n\n return details;\n}\n\n/**\n * Converts unknown Trezor errors into typed HardwareWalletError instances.\n *\n * @param error - Error thrown from Trezor bridge or keyring flow.\n * @param fallbackMessage - Default message for unknown non-Error inputs.\n * @throws HardwareWalletError Always throws typed errors.\n */\nexport function handleTrezorTransportError(\n error: unknown,\n fallbackMessage: string,\n): never {\n if (error instanceof HardwareWalletError) {\n throw error;\n }\n\n if (error instanceof Error) {\n const details = getErrorDetails(error);\n const identifier = [details.code, details.name, details.message].find(\n (value): value is string =>\n value !== undefined && isKnownTrezorError(value),\n );\n\n if (identifier) {\n throw createTrezorError(identifier, details.message);\n }\n\n const userRejectionCode = resolveUserRejectionErrorCode(error);\n if (userRejectionCode !== undefined) {\n throw createTrezorError(\n USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode],\n details.message,\n );\n }\n\n throw new HardwareWalletError(details.message ?? fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: details.message ?? fallbackMessage,\n cause: error,\n });\n }\n\n const userRejectionCode = resolveUserRejectionErrorCode(error);\n if (userRejectionCode !== undefined) {\n throw createTrezorError(\n USER_REJECTION_TREZOR_IDENTIFIERS[userRejectionCode],\n );\n }\n\n throw new HardwareWalletError(fallbackMessage, {\n code: ErrorCode.Unknown,\n severity: Severity.Err,\n category: Category.Unknown,\n userMessage: fallbackMessage,\n });\n}\n"]}
@@ -16,6 +16,7 @@ const eth_sig_util_1 = require("@metamask/eth-sig-util");
16
16
  const utils_1 = require("@metamask/utils");
17
17
  const connect_plugin_ethereum_1 = require("@trezor/connect-plugin-ethereum");
18
18
  const hdkey_1 = __importDefault(require("hdkey"));
19
+ const trezor_bridge_error_1 = require("./trezor-bridge-error.cjs");
19
20
  const trezor_error_handler_1 = require("./trezor-error-handler.cjs");
20
21
  const hdPathString = `m/44'/60'/0'/0`;
21
22
  const SLIP0044TestnetPath = `m/44'/1'/0'/0`;
@@ -117,7 +118,6 @@ class TrezorKeyring {
117
118
  return Boolean((_a = this.hdk) === null || _a === void 0 ? void 0 : _a.publicKey);
118
119
  }
119
120
  async unlock() {
120
- var _a, _b;
121
121
  if (this.isUnlocked()) {
122
122
  return Promise.resolve('already unlocked');
123
123
  }
@@ -127,7 +127,7 @@ class TrezorKeyring {
127
127
  coin: 'ETH',
128
128
  });
129
129
  if (!response.success) {
130
- throw new Error((_b = (_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : 'Unknown error');
130
+ throw (0, trezor_bridge_error_1.createErrorFromTrezorResponse)(response.payload);
131
131
  }
132
132
  this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');
133
133
  this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');
@@ -235,7 +235,6 @@ class TrezorKeyring {
235
235
  }
236
236
  // For personal_sign, we need to prefix the message:
237
237
  async signPersonalMessage(withAccount, message) {
238
- var _a, _b;
239
238
  try {
240
239
  const status = await this.unlock();
241
240
  // This is necessary to avoid popup collision
@@ -247,7 +246,7 @@ class TrezorKeyring {
247
246
  hex: true,
248
247
  });
249
248
  if (!response.success) {
250
- throw new Error((_b = (_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : 'Unknown error');
249
+ throw (0, trezor_bridge_error_1.createErrorFromTrezorResponse)(response.payload);
251
250
  }
252
251
  if (response.payload.address !== (0, utils_1.getChecksumAddress)(withAccount)) {
253
252
  throw new Error('signature doesnt match the right address');
@@ -264,7 +263,7 @@ class TrezorKeyring {
264
263
  }
265
264
  // EIP-712 Sign Typed Data
266
265
  async signTypedData(address, data, options) {
267
- var _a, _b, _c;
266
+ var _a;
268
267
  const { version } = options !== null && options !== void 0 ? options : { version: eth_sig_util_1.SignTypedDataVersion.V4 };
269
268
  const dataWithHashes = (0, connect_plugin_ethereum_1.transformTypedData)(data, version === eth_sig_util_1.SignTypedDataVersion.V4);
270
269
  try {
@@ -293,7 +292,7 @@ class TrezorKeyring {
293
292
  message_hash: message_hash !== null && message_hash !== void 0 ? message_hash : '', // eslint-disable-line camelcase
294
293
  });
295
294
  if (!response.success) {
296
- throw new Error((_c = (_b = response.payload) === null || _b === void 0 ? void 0 : _b.error) !== null && _c !== void 0 ? _c : 'Unknown error');
295
+ throw (0, trezor_bridge_error_1.createErrorFromTrezorResponse)(response.payload);
297
296
  }
298
297
  if ((0, utils_1.getChecksumAddress)(address) !== response.payload.address) {
299
298
  throw new Error('signature doesnt match the right address');
@@ -406,7 +405,7 @@ _TrezorKeyring_instances = new WeakSet(), _TrezorKeyring_getPage = async functio
406
405
  * ethereumjs transaction.
407
406
  */
408
407
  async function _TrezorKeyring_signTransaction(address, chainId, tx, handleSigning) {
409
- var _a, _b, _c, _d;
408
+ var _a, _b;
410
409
  let transaction;
411
410
  if (isOldStyleEthereumjsTx(tx)) {
412
411
  // legacy transaction from ethereumjs-tx package has no .toJSON() function,
@@ -442,7 +441,7 @@ async function _TrezorKeyring_signTransaction(address, chainId, tx, handleSignin
442
441
  }
443
442
  return newOrMutatedTx;
444
443
  }
445
- throw new Error((_d = (_c = response.payload) === null || _c === void 0 ? void 0 : _c.error) !== null && _d !== void 0 ? _d : 'Unknown error');
444
+ throw (0, trezor_bridge_error_1.createErrorFromTrezorResponse)(response.payload);
446
445
  }
447
446
  catch (error) {
448
447
  // Re-throw address validation errors as plain Errors, not hardware errors
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-keyring.cjs","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,uCAAoD;AAEpD,2CAAsE;AACtE,yDAIgC;AAEhC,2CAMyB;AACzB,6EAAqE;AAOrE,kDAA0B;AAG1B,qEAAoE;AAEpE,MAAM,YAAY,GA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D,CAAC;IACJ,CAAC;AACH,CAAC,+DAqJU,GAAW;IACpB,OAAO,IAAA,kBAAU,EAAC,GAAG,CAAC,CAAC;AACzB,CAAC,6EASiB,QAAgB,EAAE,CAAS;IAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,IAAI,CAAC,EAAE,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,IAAA,sBAAe,EAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAClE,OAAO,IAAA,wBAAiB,EAAC,OAAO,CAAC,CAAC;AACpC,CAAC,2EAgCgB,OAAY;IAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAC/C,OAAO,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnC,CAAC;AArgBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { publicToAddress, toChecksumAddress } from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { transformTypedData } from '@trezor/connect-plugin-ethereum';\nimport type {\n EthereumTransactionEIP1559,\n EthereumSignedTx,\n EthereumTransaction,\n} from '@trezor/connect-web';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\nimport { handleTrezorTransportError } from './trezor-error-handler';\n\nconst hdPathString = `m/44'/60'/0'/0`;\nconst SLIP0044TestnetPath = `m/44'/1'/0'/0`;\nconst legacyMewPath = `m/44'/60'/0'`;\n\nconst ALLOWED_HD_PATHS = {\n [hdPathString]: true,\n [legacyMewPath]: true,\n [SLIP0044TestnetPath]: true,\n} as const;\n\nconst keyringType = 'Trezor Hardware';\nconst pathBase = 'm';\nconst MAX_INDEX = 1000;\nconst DELAY_BETWEEN_POPUPS = 1000;\nexport const TREZOR_CONNECT_MANIFEST = {\n appName: 'MetaMask',\n email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: Hex;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type TrezorControllerOptions = {\n hdPath?: string;\n accounts?: Hex[];\n page?: number;\n perPage?: number;\n};\n\nexport type TrezorControllerState = {\n hdPath: string;\n accounts: Hex[];\n page: number;\n paths: Record<Hex, number>;\n perPage: number;\n unlockedAccount: number;\n};\n\nasync function wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return typeof (tx as OldEthJsTransaction).getChainId === 'function';\n}\n\nfunction isAddressValidationError(error: unknown): error is Error {\n return (\n error instanceof Error &&\n [\n \"signature doesn't match the right address\",\n 'signature doesnt match the right address',\n ].includes(error.message)\n );\n}\n\nexport class TrezorKeyring implements Keyring {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly Hex[] = [];\n\n hdk: HDKey = new HDKey();\n\n hdPath: string = hdPathString;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n paths: Record<string, number> = {};\n\n bridge: TrezorBridge;\n\n constructor({ bridge }: { bridge: TrezorBridge }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n /**\n * Gets the model, if known.\n * This may be `undefined` if the model hasn't been loaded yet.\n *\n * @returns\n */\n getModel(): string | undefined {\n return this.bridge.model;\n }\n\n async init(): Promise<void> {\n return this.bridge.init({\n manifest: TREZOR_CONNECT_MANIFEST,\n lazyLoad: true,\n });\n }\n\n async destroy(): Promise<void> {\n return this.bridge.dispose();\n }\n\n async serialize(): Promise<TrezorControllerState> {\n return Promise.resolve({\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n page: this.page,\n paths: this.paths,\n perPage: this.perPage,\n unlockedAccount: this.unlockedAccount,\n });\n }\n\n async deserialize(opts: TrezorControllerOptions): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.page = opts.page ?? 0;\n this.perPage = opts.perPage ?? 5;\n return Promise.resolve();\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk?.publicKey);\n }\n\n async unlock(): Promise<string> {\n if (this.isUnlocked()) {\n return Promise.resolve('already unlocked');\n }\n\n try {\n const response = await this.bridge.getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n });\n if (!response.success) {\n throw new Error(response.payload?.error ?? 'Unknown error');\n }\n\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n return 'just unlocked';\n } catch (error) {\n return handleTrezorTransportError(\n error,\n 'Failed to unlock Trezor device',\n );\n }\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(numberOfAccounts: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + numberOfAccounts;\n const newAccounts: Hex[] = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n const accounts = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[getChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n if (\n !this.accounts.map((a) => a.toLowerCase()).includes(address.toLowerCase())\n ) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n }\n\n /**\n * Signs a transaction using Trezor.\n *\n * Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns\n * the same type.\n *\n * @param address - Hex string address.\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n return this.#signTransaction(\n address,\n // @types/ethereumjs-tx and old ethereumjs-tx versions document\n // this function return value as Buffer, but the actual\n // Transaction._chainId will always be a number.\n // See https://github.com/ethereumjs/ethereumjs-tx/blob/v1.3.7/index.js#L126\n tx.getChainId() as unknown as number,\n tx,\n (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n },\n );\n }\n return this.#signTransaction(\n address,\n Number(tx.common.chainId()),\n tx,\n (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n },\n );\n }\n\n /**\n *\n * @param address - Hex string address.\n * @param chainId - Chain ID\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @param handleSigning - Converts signed transaction\n * to the same new-style or old-style ethereumjs-tx.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async #signTransaction<T extends TypedTransaction | OldEthJsTransaction>(\n address: Hex,\n chainId: number,\n tx: T,\n handleSigning: (tx: EthereumSignedTx) => T,\n ): Promise<T> {\n let transaction: EthereumTransaction | EthereumTransactionEIP1559;\n if (isOldStyleEthereumjsTx(tx)) {\n // legacy transaction from ethereumjs-tx package has no .toJSON() function,\n // so we need to convert to hex-strings manually manually\n transaction = {\n to: this.#normalize(tx.to),\n value: this.#normalize(tx.value),\n data: this.#normalize(tx.data),\n chainId,\n nonce: this.#normalize(tx.nonce),\n gasLimit: this.#normalize(tx.gasLimit),\n gasPrice: this.#normalize(tx.gasPrice),\n };\n } else {\n // new-style transaction from @ethereumjs/tx package\n // we can just copy tx.toJSON() for everything except chainId, which must be a number\n transaction = {\n ...tx.toJSON(),\n chainId,\n to: this.#normalize(Buffer.from(tx.to?.bytes ?? [])),\n } as EthereumTransaction | EthereumTransactionEIP1559;\n }\n\n try {\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignTransaction({\n path: this.#pathFromAddress(address),\n transaction,\n });\n if (response.success) {\n const newOrMutatedTx = handleSigning(response.payload);\n\n const addressSignedWith = getChecksumAddress(\n add0x(newOrMutatedTx.getSenderAddress().toString('hex')),\n );\n const correctAddress = getChecksumAddress(address);\n if (addressSignedWith !== correctAddress) {\n throw new Error(\"signature doesn't match the right address\");\n }\n\n return newOrMutatedTx;\n }\n throw new Error(response.payload?.error ?? 'Unknown error');\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign transaction with Trezor device',\n );\n }\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n try {\n const status = await this.unlock();\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: remove0x(message),\n hex: true,\n });\n\n if (!response.success) {\n throw new Error(response.payload?.error ?? 'Unknown error');\n }\n\n if (response.payload.address !== getChecksumAddress(withAccount)) {\n throw new Error('signature doesnt match the right address');\n }\n\n return `0x${response.payload.signature}`;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign personal message with Trezor device',\n );\n }\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<\n Version extends SignTypedDataVersion.V3 | SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? { version: SignTypedDataVersion.V4 };\n\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\n try {\n // set default values for signTypedData\n // Trezor is stricter than @metamask/eth-sig-util in what it accepts\n const {\n types,\n message = {},\n domain = {},\n primaryType,\n // snake_case since Trezor uses Protobuf naming conventions here\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash, // eslint-disable-line camelcase\n } = dataWithHashes;\n\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n\n const response = await this.bridge.ethereumSignTypedData({\n path: this.#pathFromAddress(address),\n data: {\n types: { ...types, EIP712Domain: types.EIP712Domain ?? [] },\n message,\n domain,\n primaryType,\n },\n metamask_v4_compat: true,\n // Trezor 1 only supports blindly signing hashes\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash: message_hash ?? '', // eslint-disable-line camelcase\n });\n\n if (!response.success) {\n throw new Error(response.payload?.error ?? 'Unknown error');\n }\n\n if (getChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign typed data with Trezor device',\n );\n }\n }\n\n forgetDevice(): void {\n this.accounts = [];\n this.hdk = new HDKey();\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n\n /**\n * Set the HD path to be used by the keyring. Only known supported HD paths are allowed.\n *\n * If the given HD path is already the current HD path, nothing happens. Otherwise the new HD\n * path is set, and the wallet state is completely reset.\n *\n * @throws {Error] Throws if the HD path is not supported.\n *\n * @param hdPath - The HD path to set.\n */\n setHdPath(hdPath: keyof typeof ALLOWED_HD_PATHS): void {\n if (!ALLOWED_HD_PATHS[hdPath]) {\n throw new Error(\n `The setHdPath method does not support setting HD Path to ${hdPath}`,\n );\n }\n\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n this.accounts = [];\n this.page = 0;\n this.perPage = 5;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n this.hdPath = hdPath;\n }\n\n #normalize(buf: Buffer): string {\n return bytesToHex(buf);\n }\n\n /**\n * Derive an address at a specific index using the HDKey.\n *\n * @param basePath - The base derivation path (e.g., 'm').\n * @param i - The derivation index.\n * @returns The checksummed address.\n */\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return toChecksumAddress(address);\n }\n\n /**\n * Get the account index for a given address.\n *\n * This method first checks the `paths` map, and if not found, derives\n * addresses up to MAX_INDEX to find the matching index.\n *\n * @param address - The account address.\n * @returns The account index.\n * @throws If the address is not found.\n */\n getIndexForAddress(address: Hex): number {\n const checksummedAddress = getChecksumAddress(address);\n let index = this.paths[checksummedAddress];\n\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n\n return index;\n }\n\n #pathFromAddress(address: Hex): string {\n const index = this.getIndexForAddress(address);\n return `${this.hdPath}/${index}`;\n }\n}\n"]}
1
+ {"version":3,"file":"trezor-keyring.cjs","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;A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J,CAAC;AACH,CAAC,+DAqJU,GAAW;IACpB,OAAO,IAAA,kBAAU,EAAC,GAAG,CAAC,CAAC;AACzB,CAAC,6EASiB,QAAgB,EAAE,CAAS;IAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,IAAI,CAAC,EAAE,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,IAAA,kBAAU,EAAC,IAAA,sBAAe,EAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAClE,OAAO,IAAA,wBAAiB,EAAC,OAAO,CAAC,CAAC;AACpC,CAAC,2EAgCgB,OAAY;IAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAC/C,OAAO,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnC,CAAC;AArgBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { publicToAddress, toChecksumAddress } from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { transformTypedData } from '@trezor/connect-plugin-ethereum';\nimport type {\n EthereumTransactionEIP1559,\n EthereumSignedTx,\n EthereumTransaction,\n} from '@trezor/connect-web';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\nimport { createErrorFromTrezorResponse } from './trezor-bridge-error';\nimport { handleTrezorTransportError } from './trezor-error-handler';\n\nconst hdPathString = `m/44'/60'/0'/0`;\nconst SLIP0044TestnetPath = `m/44'/1'/0'/0`;\nconst legacyMewPath = `m/44'/60'/0'`;\n\nconst ALLOWED_HD_PATHS = {\n [hdPathString]: true,\n [legacyMewPath]: true,\n [SLIP0044TestnetPath]: true,\n} as const;\n\nconst keyringType = 'Trezor Hardware';\nconst pathBase = 'm';\nconst MAX_INDEX = 1000;\nconst DELAY_BETWEEN_POPUPS = 1000;\nexport const TREZOR_CONNECT_MANIFEST = {\n appName: 'MetaMask',\n email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: Hex;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type TrezorControllerOptions = {\n hdPath?: string;\n accounts?: Hex[];\n page?: number;\n perPage?: number;\n};\n\nexport type TrezorControllerState = {\n hdPath: string;\n accounts: Hex[];\n page: number;\n paths: Record<Hex, number>;\n perPage: number;\n unlockedAccount: number;\n};\n\nasync function wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return typeof (tx as OldEthJsTransaction).getChainId === 'function';\n}\n\nfunction isAddressValidationError(error: unknown): error is Error {\n return (\n error instanceof Error &&\n [\n \"signature doesn't match the right address\",\n 'signature doesnt match the right address',\n ].includes(error.message)\n );\n}\n\nexport class TrezorKeyring implements Keyring {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly Hex[] = [];\n\n hdk: HDKey = new HDKey();\n\n hdPath: string = hdPathString;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n paths: Record<string, number> = {};\n\n bridge: TrezorBridge;\n\n constructor({ bridge }: { bridge: TrezorBridge }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n /**\n * Gets the model, if known.\n * This may be `undefined` if the model hasn't been loaded yet.\n *\n * @returns\n */\n getModel(): string | undefined {\n return this.bridge.model;\n }\n\n async init(): Promise<void> {\n return this.bridge.init({\n manifest: TREZOR_CONNECT_MANIFEST,\n lazyLoad: true,\n });\n }\n\n async destroy(): Promise<void> {\n return this.bridge.dispose();\n }\n\n async serialize(): Promise<TrezorControllerState> {\n return Promise.resolve({\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n page: this.page,\n paths: this.paths,\n perPage: this.perPage,\n unlockedAccount: this.unlockedAccount,\n });\n }\n\n async deserialize(opts: TrezorControllerOptions): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.page = opts.page ?? 0;\n this.perPage = opts.perPage ?? 5;\n return Promise.resolve();\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk?.publicKey);\n }\n\n async unlock(): Promise<string> {\n if (this.isUnlocked()) {\n return Promise.resolve('already unlocked');\n }\n\n try {\n const response = await this.bridge.getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n });\n if (!response.success) {\n throw createErrorFromTrezorResponse(response.payload);\n }\n\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n return 'just unlocked';\n } catch (error) {\n return handleTrezorTransportError(\n error,\n 'Failed to unlock Trezor device',\n );\n }\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(numberOfAccounts: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + numberOfAccounts;\n const newAccounts: Hex[] = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n const accounts = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[getChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n if (\n !this.accounts.map((a) => a.toLowerCase()).includes(address.toLowerCase())\n ) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n }\n\n /**\n * Signs a transaction using Trezor.\n *\n * Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns\n * the same type.\n *\n * @param address - Hex string address.\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n return this.#signTransaction(\n address,\n // @types/ethereumjs-tx and old ethereumjs-tx versions document\n // this function return value as Buffer, but the actual\n // Transaction._chainId will always be a number.\n // See https://github.com/ethereumjs/ethereumjs-tx/blob/v1.3.7/index.js#L126\n tx.getChainId() as unknown as number,\n tx,\n (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n },\n );\n }\n return this.#signTransaction(\n address,\n Number(tx.common.chainId()),\n tx,\n (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n },\n );\n }\n\n /**\n *\n * @param address - Hex string address.\n * @param chainId - Chain ID\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @param handleSigning - Converts signed transaction\n * to the same new-style or old-style ethereumjs-tx.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async #signTransaction<T extends TypedTransaction | OldEthJsTransaction>(\n address: Hex,\n chainId: number,\n tx: T,\n handleSigning: (tx: EthereumSignedTx) => T,\n ): Promise<T> {\n let transaction: EthereumTransaction | EthereumTransactionEIP1559;\n if (isOldStyleEthereumjsTx(tx)) {\n // legacy transaction from ethereumjs-tx package has no .toJSON() function,\n // so we need to convert to hex-strings manually manually\n transaction = {\n to: this.#normalize(tx.to),\n value: this.#normalize(tx.value),\n data: this.#normalize(tx.data),\n chainId,\n nonce: this.#normalize(tx.nonce),\n gasLimit: this.#normalize(tx.gasLimit),\n gasPrice: this.#normalize(tx.gasPrice),\n };\n } else {\n // new-style transaction from @ethereumjs/tx package\n // we can just copy tx.toJSON() for everything except chainId, which must be a number\n transaction = {\n ...tx.toJSON(),\n chainId,\n to: this.#normalize(Buffer.from(tx.to?.bytes ?? [])),\n } as EthereumTransaction | EthereumTransactionEIP1559;\n }\n\n try {\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignTransaction({\n path: this.#pathFromAddress(address),\n transaction,\n });\n if (response.success) {\n const newOrMutatedTx = handleSigning(response.payload);\n\n const addressSignedWith = getChecksumAddress(\n add0x(newOrMutatedTx.getSenderAddress().toString('hex')),\n );\n const correctAddress = getChecksumAddress(address);\n if (addressSignedWith !== correctAddress) {\n throw new Error(\"signature doesn't match the right address\");\n }\n\n return newOrMutatedTx;\n }\n throw createErrorFromTrezorResponse(response.payload);\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign transaction with Trezor device',\n );\n }\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n try {\n const status = await this.unlock();\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: remove0x(message),\n hex: true,\n });\n\n if (!response.success) {\n throw createErrorFromTrezorResponse(response.payload);\n }\n\n if (response.payload.address !== getChecksumAddress(withAccount)) {\n throw new Error('signature doesnt match the right address');\n }\n\n return `0x${response.payload.signature}`;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign personal message with Trezor device',\n );\n }\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<\n Version extends SignTypedDataVersion.V3 | SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? { version: SignTypedDataVersion.V4 };\n\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\n try {\n // set default values for signTypedData\n // Trezor is stricter than @metamask/eth-sig-util in what it accepts\n const {\n types,\n message = {},\n domain = {},\n primaryType,\n // snake_case since Trezor uses Protobuf naming conventions here\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash, // eslint-disable-line camelcase\n } = dataWithHashes;\n\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n\n const response = await this.bridge.ethereumSignTypedData({\n path: this.#pathFromAddress(address),\n data: {\n types: { ...types, EIP712Domain: types.EIP712Domain ?? [] },\n message,\n domain,\n primaryType,\n },\n metamask_v4_compat: true,\n // Trezor 1 only supports blindly signing hashes\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash: message_hash ?? '', // eslint-disable-line camelcase\n });\n\n if (!response.success) {\n throw createErrorFromTrezorResponse(response.payload);\n }\n\n if (getChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign typed data with Trezor device',\n );\n }\n }\n\n forgetDevice(): void {\n this.accounts = [];\n this.hdk = new HDKey();\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n\n /**\n * Set the HD path to be used by the keyring. Only known supported HD paths are allowed.\n *\n * If the given HD path is already the current HD path, nothing happens. Otherwise the new HD\n * path is set, and the wallet state is completely reset.\n *\n * @throws {Error] Throws if the HD path is not supported.\n *\n * @param hdPath - The HD path to set.\n */\n setHdPath(hdPath: keyof typeof ALLOWED_HD_PATHS): void {\n if (!ALLOWED_HD_PATHS[hdPath]) {\n throw new Error(\n `The setHdPath method does not support setting HD Path to ${hdPath}`,\n );\n }\n\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n this.accounts = [];\n this.page = 0;\n this.perPage = 5;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n this.hdPath = hdPath;\n }\n\n #normalize(buf: Buffer): string {\n return bytesToHex(buf);\n }\n\n /**\n * Derive an address at a specific index using the HDKey.\n *\n * @param basePath - The base derivation path (e.g., 'm').\n * @param i - The derivation index.\n * @returns The checksummed address.\n */\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return toChecksumAddress(address);\n }\n\n /**\n * Get the account index for a given address.\n *\n * This method first checks the `paths` map, and if not found, derives\n * addresses up to MAX_INDEX to find the matching index.\n *\n * @param address - The account address.\n * @returns The account index.\n * @throws If the address is not found.\n */\n getIndexForAddress(address: Hex): number {\n const checksummedAddress = getChecksumAddress(address);\n let index = this.paths[checksummedAddress];\n\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n\n return index;\n }\n\n #pathFromAddress(address: Hex): string {\n const index = this.getIndexForAddress(address);\n return `${this.hdPath}/${index}`;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-keyring.d.cts","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"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I;IAI1C,WAAW,CAAC,gBAAgB,EAAE,MAAM,GAAG,OAAO,CAAC,GAAG,EAAE,CAAC;IAwBrD,YAAY,IAAI,OAAO,CAAC,WAAW,CAAC;IAKpC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC;IAInC,eAAe,IAAI,OAAO,CAAC,WAAW,CAAC;IAoCvC,WAAW,IAAI,OAAO,CAAC,GAAG,EAAE,CAAC;IAInC,aAAa,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI;IAYpC;;;;;;;;;;OAUG;IACG,eAAe,CACnB,OAAO,EAAE,GAAG,EACZ,EAAE,EAAE,gBAAgB,GAAG,mBAAmB,GACzC,OAAO,CAAC,gBAAgB,GAAG,mBAAmB,CAAC;IAwH5C,WAAW,CAAC,WAAW,EAAE,GAAG,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAK5D,mBAAmB,CACvB,WAAW,EAAE,GAAG,EAChB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,MAAM,CAAC;IAkCZ,aAAa,CACjB,OAAO,SAAS,oBAAoB,CAAC,EAAE,GAAG,oBAAoB,CAAC,EAAE,EACjE,KAAK,SAAS,YAAY,EAC1B,OAAO,SAAS;QAAE,OAAO,CAAC,EAAE,OAAO,CAAA;KAAE,EAErC,OAAO,EAAE,GAAG,EACZ,IAAI,EAAE,YAAY,CAAC,KAAK,CAAC,EACzB,OAAO,CAAC,EAAE,OAAO,GAChB,OAAO,CAAC,MAAM,CAAC;IA4DlB,YAAY,IAAI,IAAI;IAQpB;;;;;;;;;OASG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,OAAO,gBAAgB,GAAG,IAAI;IAoCtD;;;;;;;;;OASG;IACH,kBAAkB,CAAC,OAAO,EAAE,GAAG,GAAG,MAAM;CAwBzC"}
@@ -17,6 +17,7 @@ import { add0x, bytesToHex, getChecksumAddress, remove0x } from "@metamask/utils
17
17
  import { transformTypedData } from "@trezor/connect-plugin-ethereum";
18
18
  import $HDKey from "hdkey";
19
19
  const HDKey = $importDefault($HDKey);
20
+ import { createErrorFromTrezorResponse } from "./trezor-bridge-error.mjs";
20
21
  import { handleTrezorTransportError } from "./trezor-error-handler.mjs";
21
22
  const hdPathString = `m/44'/60'/0'/0`;
22
23
  const SLIP0044TestnetPath = `m/44'/1'/0'/0`;
@@ -118,7 +119,6 @@ export class TrezorKeyring {
118
119
  return Boolean((_a = this.hdk) === null || _a === void 0 ? void 0 : _a.publicKey);
119
120
  }
120
121
  async unlock() {
121
- var _a, _b;
122
122
  if (this.isUnlocked()) {
123
123
  return Promise.resolve('already unlocked');
124
124
  }
@@ -128,7 +128,7 @@ export class TrezorKeyring {
128
128
  coin: 'ETH',
129
129
  });
130
130
  if (!response.success) {
131
- throw new Error((_b = (_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : 'Unknown error');
131
+ throw createErrorFromTrezorResponse(response.payload);
132
132
  }
133
133
  this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');
134
134
  this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');
@@ -236,7 +236,6 @@ export class TrezorKeyring {
236
236
  }
237
237
  // For personal_sign, we need to prefix the message:
238
238
  async signPersonalMessage(withAccount, message) {
239
- var _a, _b;
240
239
  try {
241
240
  const status = await this.unlock();
242
241
  // This is necessary to avoid popup collision
@@ -248,7 +247,7 @@ export class TrezorKeyring {
248
247
  hex: true,
249
248
  });
250
249
  if (!response.success) {
251
- throw new Error((_b = (_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) !== null && _b !== void 0 ? _b : 'Unknown error');
250
+ throw createErrorFromTrezorResponse(response.payload);
252
251
  }
253
252
  if (response.payload.address !== getChecksumAddress(withAccount)) {
254
253
  throw new Error('signature doesnt match the right address');
@@ -265,7 +264,7 @@ export class TrezorKeyring {
265
264
  }
266
265
  // EIP-712 Sign Typed Data
267
266
  async signTypedData(address, data, options) {
268
- var _a, _b, _c;
267
+ var _a;
269
268
  const { version } = options !== null && options !== void 0 ? options : { version: SignTypedDataVersion.V4 };
270
269
  const dataWithHashes = transformTypedData(data, version === SignTypedDataVersion.V4);
271
270
  try {
@@ -294,7 +293,7 @@ export class TrezorKeyring {
294
293
  message_hash: message_hash !== null && message_hash !== void 0 ? message_hash : '', // eslint-disable-line camelcase
295
294
  });
296
295
  if (!response.success) {
297
- throw new Error((_c = (_b = response.payload) === null || _b === void 0 ? void 0 : _b.error) !== null && _c !== void 0 ? _c : 'Unknown error');
296
+ throw createErrorFromTrezorResponse(response.payload);
298
297
  }
299
298
  if (getChecksumAddress(address) !== response.payload.address) {
300
299
  throw new Error('signature doesnt match the right address');
@@ -406,7 +405,7 @@ _TrezorKeyring_instances = new WeakSet(), _TrezorKeyring_getPage = async functio
406
405
  * ethereumjs transaction.
407
406
  */
408
407
  async function _TrezorKeyring_signTransaction(address, chainId, tx, handleSigning) {
409
- var _a, _b, _c, _d;
408
+ var _a, _b;
410
409
  let transaction;
411
410
  if (isOldStyleEthereumjsTx(tx)) {
412
411
  // legacy transaction from ethereumjs-tx package has no .toJSON() function,
@@ -442,7 +441,7 @@ async function _TrezorKeyring_signTransaction(address, chainId, tx, handleSignin
442
441
  }
443
442
  return newOrMutatedTx;
444
443
  }
445
- throw new Error((_d = (_c = response.payload) === null || _c === void 0 ? void 0 : _c.error) !== null && _d !== void 0 ? _d : 'Unknown error');
444
+ throw createErrorFromTrezorResponse(response.payload);
446
445
  }
447
446
  catch (error) {
448
447
  // Re-throw address validation errors as plain Errors, not hardware errors
@@ -1 +1 @@
1
- {"version":3,"file":"trezor-keyring.mjs","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,uBAAuB;AAEpD,OAAO,EAAE,eAAe,EAAE,iBAAiB,EAAE,yBAAyB;AACtE,OAAO,EAEL,oBAAoB,EAErB,+BAA+B;AAEhC,OAAO,EACL,KAAK,EACL,UAAU,EACV,k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K,CAAC;QACd,CAAC;QACD,OAAO,0BAA0B,CAC/B,KAAK,EACL,+CAA+C,CAChD,CAAC;IACJ,CAAC;AACH,CAAC,+DAqJU,GAAW;IACpB,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC;AACzB,CAAC,6EASiB,QAAgB,EAAE,CAAS;IAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,IAAI,CAAC,EAAE,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAClE,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC,2EAgCgB,OAAY;IAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAC/C,OAAO,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnC,CAAC;AArgBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { publicToAddress, toChecksumAddress } from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { transformTypedData } from '@trezor/connect-plugin-ethereum';\nimport type {\n EthereumTransactionEIP1559,\n EthereumSignedTx,\n EthereumTransaction,\n} from '@trezor/connect-web';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\nimport { handleTrezorTransportError } from './trezor-error-handler';\n\nconst hdPathString = `m/44'/60'/0'/0`;\nconst SLIP0044TestnetPath = `m/44'/1'/0'/0`;\nconst legacyMewPath = `m/44'/60'/0'`;\n\nconst ALLOWED_HD_PATHS = {\n [hdPathString]: true,\n [legacyMewPath]: true,\n [SLIP0044TestnetPath]: true,\n} as const;\n\nconst keyringType = 'Trezor Hardware';\nconst pathBase = 'm';\nconst MAX_INDEX = 1000;\nconst DELAY_BETWEEN_POPUPS = 1000;\nexport const TREZOR_CONNECT_MANIFEST = {\n appName: 'MetaMask',\n email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: Hex;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type TrezorControllerOptions = {\n hdPath?: string;\n accounts?: Hex[];\n page?: number;\n perPage?: number;\n};\n\nexport type TrezorControllerState = {\n hdPath: string;\n accounts: Hex[];\n page: number;\n paths: Record<Hex, number>;\n perPage: number;\n unlockedAccount: number;\n};\n\nasync function wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return typeof (tx as OldEthJsTransaction).getChainId === 'function';\n}\n\nfunction isAddressValidationError(error: unknown): error is Error {\n return (\n error instanceof Error &&\n [\n \"signature doesn't match the right address\",\n 'signature doesnt match the right address',\n ].includes(error.message)\n );\n}\n\nexport class TrezorKeyring implements Keyring {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly Hex[] = [];\n\n hdk: HDKey = new HDKey();\n\n hdPath: string = hdPathString;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n paths: Record<string, number> = {};\n\n bridge: TrezorBridge;\n\n constructor({ bridge }: { bridge: TrezorBridge }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n /**\n * Gets the model, if known.\n * This may be `undefined` if the model hasn't been loaded yet.\n *\n * @returns\n */\n getModel(): string | undefined {\n return this.bridge.model;\n }\n\n async init(): Promise<void> {\n return this.bridge.init({\n manifest: TREZOR_CONNECT_MANIFEST,\n lazyLoad: true,\n });\n }\n\n async destroy(): Promise<void> {\n return this.bridge.dispose();\n }\n\n async serialize(): Promise<TrezorControllerState> {\n return Promise.resolve({\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n page: this.page,\n paths: this.paths,\n perPage: this.perPage,\n unlockedAccount: this.unlockedAccount,\n });\n }\n\n async deserialize(opts: TrezorControllerOptions): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.page = opts.page ?? 0;\n this.perPage = opts.perPage ?? 5;\n return Promise.resolve();\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk?.publicKey);\n }\n\n async unlock(): Promise<string> {\n if (this.isUnlocked()) {\n return Promise.resolve('already unlocked');\n }\n\n try {\n const response = await this.bridge.getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n });\n if (!response.success) {\n throw new Error(response.payload?.error ?? 'Unknown error');\n }\n\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n return 'just unlocked';\n } catch (error) {\n return handleTrezorTransportError(\n error,\n 'Failed to unlock Trezor device',\n );\n }\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(numberOfAccounts: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + numberOfAccounts;\n const newAccounts: Hex[] = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n const accounts = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[getChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n if (\n !this.accounts.map((a) => a.toLowerCase()).includes(address.toLowerCase())\n ) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n }\n\n /**\n * Signs a transaction using Trezor.\n *\n * Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns\n * the same type.\n *\n * @param address - Hex string address.\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n return this.#signTransaction(\n address,\n // @types/ethereumjs-tx and old ethereumjs-tx versions document\n // this function return value as Buffer, but the actual\n // Transaction._chainId will always be a number.\n // See https://github.com/ethereumjs/ethereumjs-tx/blob/v1.3.7/index.js#L126\n tx.getChainId() as unknown as number,\n tx,\n (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n },\n );\n }\n return this.#signTransaction(\n address,\n Number(tx.common.chainId()),\n tx,\n (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n },\n );\n }\n\n /**\n *\n * @param address - Hex string address.\n * @param chainId - Chain ID\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @param handleSigning - Converts signed transaction\n * to the same new-style or old-style ethereumjs-tx.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async #signTransaction<T extends TypedTransaction | OldEthJsTransaction>(\n address: Hex,\n chainId: number,\n tx: T,\n handleSigning: (tx: EthereumSignedTx) => T,\n ): Promise<T> {\n let transaction: EthereumTransaction | EthereumTransactionEIP1559;\n if (isOldStyleEthereumjsTx(tx)) {\n // legacy transaction from ethereumjs-tx package has no .toJSON() function,\n // so we need to convert to hex-strings manually manually\n transaction = {\n to: this.#normalize(tx.to),\n value: this.#normalize(tx.value),\n data: this.#normalize(tx.data),\n chainId,\n nonce: this.#normalize(tx.nonce),\n gasLimit: this.#normalize(tx.gasLimit),\n gasPrice: this.#normalize(tx.gasPrice),\n };\n } else {\n // new-style transaction from @ethereumjs/tx package\n // we can just copy tx.toJSON() for everything except chainId, which must be a number\n transaction = {\n ...tx.toJSON(),\n chainId,\n to: this.#normalize(Buffer.from(tx.to?.bytes ?? [])),\n } as EthereumTransaction | EthereumTransactionEIP1559;\n }\n\n try {\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignTransaction({\n path: this.#pathFromAddress(address),\n transaction,\n });\n if (response.success) {\n const newOrMutatedTx = handleSigning(response.payload);\n\n const addressSignedWith = getChecksumAddress(\n add0x(newOrMutatedTx.getSenderAddress().toString('hex')),\n );\n const correctAddress = getChecksumAddress(address);\n if (addressSignedWith !== correctAddress) {\n throw new Error(\"signature doesn't match the right address\");\n }\n\n return newOrMutatedTx;\n }\n throw new Error(response.payload?.error ?? 'Unknown error');\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign transaction with Trezor device',\n );\n }\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n try {\n const status = await this.unlock();\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: remove0x(message),\n hex: true,\n });\n\n if (!response.success) {\n throw new Error(response.payload?.error ?? 'Unknown error');\n }\n\n if (response.payload.address !== getChecksumAddress(withAccount)) {\n throw new Error('signature doesnt match the right address');\n }\n\n return `0x${response.payload.signature}`;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign personal message with Trezor device',\n );\n }\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<\n Version extends SignTypedDataVersion.V3 | SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? { version: SignTypedDataVersion.V4 };\n\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\n try {\n // set default values for signTypedData\n // Trezor is stricter than @metamask/eth-sig-util in what it accepts\n const {\n types,\n message = {},\n domain = {},\n primaryType,\n // snake_case since Trezor uses Protobuf naming conventions here\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash, // eslint-disable-line camelcase\n } = dataWithHashes;\n\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n\n const response = await this.bridge.ethereumSignTypedData({\n path: this.#pathFromAddress(address),\n data: {\n types: { ...types, EIP712Domain: types.EIP712Domain ?? [] },\n message,\n domain,\n primaryType,\n },\n metamask_v4_compat: true,\n // Trezor 1 only supports blindly signing hashes\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash: message_hash ?? '', // eslint-disable-line camelcase\n });\n\n if (!response.success) {\n throw new Error(response.payload?.error ?? 'Unknown error');\n }\n\n if (getChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign typed data with Trezor device',\n );\n }\n }\n\n forgetDevice(): void {\n this.accounts = [];\n this.hdk = new HDKey();\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n\n /**\n * Set the HD path to be used by the keyring. Only known supported HD paths are allowed.\n *\n * If the given HD path is already the current HD path, nothing happens. Otherwise the new HD\n * path is set, and the wallet state is completely reset.\n *\n * @throws {Error] Throws if the HD path is not supported.\n *\n * @param hdPath - The HD path to set.\n */\n setHdPath(hdPath: keyof typeof ALLOWED_HD_PATHS): void {\n if (!ALLOWED_HD_PATHS[hdPath]) {\n throw new Error(\n `The setHdPath method does not support setting HD Path to ${hdPath}`,\n );\n }\n\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n this.accounts = [];\n this.page = 0;\n this.perPage = 5;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n this.hdPath = hdPath;\n }\n\n #normalize(buf: Buffer): string {\n return bytesToHex(buf);\n }\n\n /**\n * Derive an address at a specific index using the HDKey.\n *\n * @param basePath - The base derivation path (e.g., 'm').\n * @param i - The derivation index.\n * @returns The checksummed address.\n */\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return toChecksumAddress(address);\n }\n\n /**\n * Get the account index for a given address.\n *\n * This method first checks the `paths` map, and if not found, derives\n * addresses up to MAX_INDEX to find the matching index.\n *\n * @param address - The account address.\n * @returns The account index.\n * @throws If the address is not found.\n */\n getIndexForAddress(address: Hex): number {\n const checksummedAddress = getChecksumAddress(address);\n let index = this.paths[checksummedAddress];\n\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n\n return index;\n }\n\n #pathFromAddress(address: Hex): string {\n const index = this.getIndexForAddress(address);\n return `${this.hdPath}/${index}`;\n }\n}\n"]}
1
+ {"version":3,"file":"trezor-keyring.mjs","sourceRoot":"","sources":["../src/tr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;QACf,0EAA0E;QAC1E,IAAI,wBAAwB,CAAC,KAAK,CAAC,EAAE,CAAC;YACpC,MAAM,KAAK,CAAC;QACd,CAAC;QACD,OAAO,0BAA0B,CAC/B,KAAK,EACL,+CAA+C,CAChD,CAAC;IACJ,CAAC;AACH,CAAC,+DAqJU,GAAW;IACpB,OAAO,UAAU,CAAC,GAAG,CAAC,CAAC;AACzB,CAAC,6EASiB,QAAgB,EAAE,CAAS;IAC3C,MAAM,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,QAAQ,IAAI,CAAC,EAAE,CAAC,CAAC;IACjD,MAAM,OAAO,GAAG,UAAU,CAAC,eAAe,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,CAAC,CAAC,CAAC;IAClE,OAAO,iBAAiB,CAAC,OAAO,CAAC,CAAC;AACpC,CAAC,2EAgCgB,OAAY;IAC3B,MAAM,KAAK,GAAG,IAAI,CAAC,kBAAkB,CAAC,OAAO,CAAC,CAAC;IAC/C,OAAO,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnC,CAAC;AArgBM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedTransaction, TypedTxData } from '@ethereumjs/tx';\nimport { publicToAddress, toChecksumAddress } from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\nimport type { Keyring } from '@metamask/keyring-utils';\nimport {\n add0x,\n bytesToHex,\n getChecksumAddress,\n Hex,\n remove0x,\n} from '@metamask/utils';\nimport { transformTypedData } from '@trezor/connect-plugin-ethereum';\nimport type {\n EthereumTransactionEIP1559,\n EthereumSignedTx,\n EthereumTransaction,\n} from '@trezor/connect-web';\nimport type OldEthJsTransaction from 'ethereumjs-tx';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\nimport { createErrorFromTrezorResponse } from './trezor-bridge-error';\nimport { handleTrezorTransportError } from './trezor-error-handler';\n\nconst hdPathString = `m/44'/60'/0'/0`;\nconst SLIP0044TestnetPath = `m/44'/1'/0'/0`;\nconst legacyMewPath = `m/44'/60'/0'`;\n\nconst ALLOWED_HD_PATHS = {\n [hdPathString]: true,\n [legacyMewPath]: true,\n [SLIP0044TestnetPath]: true,\n} as const;\n\nconst keyringType = 'Trezor Hardware';\nconst pathBase = 'm';\nconst MAX_INDEX = 1000;\nconst DELAY_BETWEEN_POPUPS = 1000;\nexport const TREZOR_CONNECT_MANIFEST = {\n appName: 'MetaMask',\n email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: Hex;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport type TrezorControllerOptions = {\n hdPath?: string;\n accounts?: Hex[];\n page?: number;\n perPage?: number;\n};\n\nexport type TrezorControllerState = {\n hdPath: string;\n accounts: Hex[];\n page: number;\n paths: Record<Hex, number>;\n perPage: number;\n unlockedAccount: number;\n};\n\nasync function wait(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx\n *\n * Transactions built with older versions of ethereumjs-tx have a\n * getChainId method that newer versions do not.\n * Older versions are mutable\n * while newer versions default to being immutable.\n * Expected shape and type\n * of data for v, r and s differ (Buffer (old) vs BN (new)).\n *\n * @param tx\n * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.\n */\nfunction isOldStyleEthereumjsTx(\n tx: TypedTransaction | OldEthJsTransaction,\n): tx is OldEthJsTransaction {\n return typeof (tx as OldEthJsTransaction).getChainId === 'function';\n}\n\nfunction isAddressValidationError(error: unknown): error is Error {\n return (\n error instanceof Error &&\n [\n \"signature doesn't match the right address\",\n 'signature doesnt match the right address',\n ].includes(error.message)\n );\n}\n\nexport class TrezorKeyring implements Keyring {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly Hex[] = [];\n\n hdk: HDKey = new HDKey();\n\n hdPath: string = hdPathString;\n\n page = 0;\n\n perPage = 5;\n\n unlockedAccount = 0;\n\n paths: Record<string, number> = {};\n\n bridge: TrezorBridge;\n\n constructor({ bridge }: { bridge: TrezorBridge }) {\n if (!bridge) {\n throw new Error('Bridge is a required dependency for the keyring');\n }\n\n this.bridge = bridge;\n }\n\n /**\n * Gets the model, if known.\n * This may be `undefined` if the model hasn't been loaded yet.\n *\n * @returns\n */\n getModel(): string | undefined {\n return this.bridge.model;\n }\n\n async init(): Promise<void> {\n return this.bridge.init({\n manifest: TREZOR_CONNECT_MANIFEST,\n lazyLoad: true,\n });\n }\n\n async destroy(): Promise<void> {\n return this.bridge.dispose();\n }\n\n async serialize(): Promise<TrezorControllerState> {\n return Promise.resolve({\n hdPath: this.hdPath,\n accounts: this.accounts.slice(),\n page: this.page,\n paths: this.paths,\n perPage: this.perPage,\n unlockedAccount: this.unlockedAccount,\n });\n }\n\n async deserialize(opts: TrezorControllerOptions): Promise<void> {\n this.hdPath = opts.hdPath ?? hdPathString;\n this.accounts = opts.accounts ?? [];\n this.page = opts.page ?? 0;\n this.perPage = opts.perPage ?? 5;\n return Promise.resolve();\n }\n\n isUnlocked(): boolean {\n return Boolean(this.hdk?.publicKey);\n }\n\n async unlock(): Promise<string> {\n if (this.isUnlocked()) {\n return Promise.resolve('already unlocked');\n }\n\n try {\n const response = await this.bridge.getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n });\n if (!response.success) {\n throw createErrorFromTrezorResponse(response.payload);\n }\n\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n return 'just unlocked';\n } catch (error) {\n return handleTrezorTransportError(\n error,\n 'Failed to unlock Trezor device',\n );\n }\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(numberOfAccounts: number): Promise<Hex[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + numberOfAccounts;\n const newAccounts: Hex[] = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n if (!this.accounts.includes(address)) {\n this.accounts = [...this.accounts, address];\n newAccounts.push(address);\n }\n this.page = 0;\n }\n resolve(newAccounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getFirstPage(): Promise<AccountPage> {\n this.page = 0;\n return this.#getPage(1);\n }\n\n async getNextPage(): Promise<AccountPage> {\n return this.#getPage(1);\n }\n\n async getPreviousPage(): Promise<AccountPage> {\n return this.#getPage(-1);\n }\n\n async #getPage(increment: number): Promise<AccountPage> {\n this.page += increment;\n\n if (this.page <= 0) {\n this.page = 1;\n }\n\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = (this.page - 1) * this.perPage;\n const to = from + this.perPage;\n\n const accounts = [];\n\n for (let i = from; i < to; i++) {\n const address = this.#addressFromIndex(pathBase, i);\n accounts.push({\n address,\n balance: null,\n index: i,\n });\n this.paths[getChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<Hex[]> {\n return Promise.resolve(this.accounts.slice());\n }\n\n removeAccount(address: string): void {\n if (\n !this.accounts.map((a) => a.toLowerCase()).includes(address.toLowerCase())\n ) {\n throw new Error(`Address ${address} not found in this keyring`);\n }\n\n this.accounts = this.accounts.filter(\n (a) => a.toLowerCase() !== address.toLowerCase(),\n );\n }\n\n /**\n * Signs a transaction using Trezor.\n *\n * Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns\n * the same type.\n *\n * @param address - Hex string address.\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async signTransaction(\n address: Hex,\n tx: TypedTransaction | OldEthJsTransaction,\n ): Promise<TypedTransaction | OldEthJsTransaction> {\n if (isOldStyleEthereumjsTx(tx)) {\n // In this version of ethereumjs-tx we must add the chainId in hex format\n // to the initial v value. The chainId must be included in the serialized\n // transaction which is only communicated to ethereumjs-tx in this\n // value. In newer versions the chainId is communicated via the 'Common'\n // object.\n return this.#signTransaction(\n address,\n // @types/ethereumjs-tx and old ethereumjs-tx versions document\n // this function return value as Buffer, but the actual\n // Transaction._chainId will always be a number.\n // See https://github.com/ethereumjs/ethereumjs-tx/blob/v1.3.7/index.js#L126\n tx.getChainId() as unknown as number,\n tx,\n (payload) => {\n tx.v = Buffer.from(payload.v, 'hex');\n tx.r = Buffer.from(payload.r, 'hex');\n tx.s = Buffer.from(payload.s, 'hex');\n return tx;\n },\n );\n }\n return this.#signTransaction(\n address,\n Number(tx.common.chainId()),\n tx,\n (payload) => {\n // Because tx will be immutable, first get a plain javascript object that\n // represents the transaction. Using txData here as it aligns with the\n // nomenclature of ethereumjs/tx.\n const txData: TypedTxData = tx.toJSON();\n // The fromTxData utility expects a type to support transactions with a type other than 0\n txData.type = tx.type;\n // The fromTxData utility expects v,r and s to be hex prefixed\n txData.v = add0x(payload.v);\n txData.r = add0x(payload.r);\n txData.s = add0x(payload.s);\n // Adopt the 'common' option from the original transaction and set the\n // returned object to be frozen if the original is frozen.\n return TransactionFactory.fromTxData(txData, {\n common: tx.common,\n freeze: Object.isFrozen(tx),\n });\n },\n );\n }\n\n /**\n *\n * @param address - Hex string address.\n * @param chainId - Chain ID\n * @param tx - Instance of either new-style or old-style ethereumjs transaction.\n * @param handleSigning - Converts signed transaction\n * to the same new-style or old-style ethereumjs-tx.\n * @returns The signed transaction, an instance of either new-style or old-style\n * ethereumjs transaction.\n */\n async #signTransaction<T extends TypedTransaction | OldEthJsTransaction>(\n address: Hex,\n chainId: number,\n tx: T,\n handleSigning: (tx: EthereumSignedTx) => T,\n ): Promise<T> {\n let transaction: EthereumTransaction | EthereumTransactionEIP1559;\n if (isOldStyleEthereumjsTx(tx)) {\n // legacy transaction from ethereumjs-tx package has no .toJSON() function,\n // so we need to convert to hex-strings manually manually\n transaction = {\n to: this.#normalize(tx.to),\n value: this.#normalize(tx.value),\n data: this.#normalize(tx.data),\n chainId,\n nonce: this.#normalize(tx.nonce),\n gasLimit: this.#normalize(tx.gasLimit),\n gasPrice: this.#normalize(tx.gasPrice),\n };\n } else {\n // new-style transaction from @ethereumjs/tx package\n // we can just copy tx.toJSON() for everything except chainId, which must be a number\n transaction = {\n ...tx.toJSON(),\n chainId,\n to: this.#normalize(Buffer.from(tx.to?.bytes ?? [])),\n } as EthereumTransaction | EthereumTransactionEIP1559;\n }\n\n try {\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignTransaction({\n path: this.#pathFromAddress(address),\n transaction,\n });\n if (response.success) {\n const newOrMutatedTx = handleSigning(response.payload);\n\n const addressSignedWith = getChecksumAddress(\n add0x(newOrMutatedTx.getSenderAddress().toString('hex')),\n );\n const correctAddress = getChecksumAddress(address);\n if (addressSignedWith !== correctAddress) {\n throw new Error(\"signature doesn't match the right address\");\n }\n\n return newOrMutatedTx;\n }\n throw createErrorFromTrezorResponse(response.payload);\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign transaction with Trezor device',\n );\n }\n }\n\n async signMessage(withAccount: Hex, data: string): Promise<string> {\n return this.signPersonalMessage(withAccount, data);\n }\n\n // For personal_sign, we need to prefix the message:\n async signPersonalMessage(\n withAccount: Hex,\n message: string,\n ): Promise<string> {\n try {\n const status = await this.unlock();\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n const response = await this.bridge.ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: remove0x(message),\n hex: true,\n });\n\n if (!response.success) {\n throw createErrorFromTrezorResponse(response.payload);\n }\n\n if (response.payload.address !== getChecksumAddress(withAccount)) {\n throw new Error('signature doesnt match the right address');\n }\n\n return `0x${response.payload.signature}`;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign personal message with Trezor device',\n );\n }\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<\n Version extends SignTypedDataVersion.V3 | SignTypedDataVersion.V4,\n Types extends MessageTypes,\n Options extends { version?: Version },\n >(\n address: Hex,\n data: TypedMessage<Types>,\n options?: Options,\n ): Promise<string> {\n const { version } = options ?? { version: SignTypedDataVersion.V4 };\n\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\n try {\n // set default values for signTypedData\n // Trezor is stricter than @metamask/eth-sig-util in what it accepts\n const {\n types,\n message = {},\n domain = {},\n primaryType,\n // snake_case since Trezor uses Protobuf naming conventions here\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash, // eslint-disable-line camelcase\n } = dataWithHashes;\n\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n const status = await this.unlock();\n await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);\n\n const response = await this.bridge.ethereumSignTypedData({\n path: this.#pathFromAddress(address),\n data: {\n types: { ...types, EIP712Domain: types.EIP712Domain ?? [] },\n message,\n domain,\n primaryType,\n },\n metamask_v4_compat: true,\n // Trezor 1 only supports blindly signing hashes\n domain_separator_hash, // eslint-disable-line camelcase\n message_hash: message_hash ?? '', // eslint-disable-line camelcase\n });\n\n if (!response.success) {\n throw createErrorFromTrezorResponse(response.payload);\n }\n\n if (getChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n } catch (error) {\n // Re-throw address validation errors as plain Errors, not hardware errors\n if (isAddressValidationError(error)) {\n throw error;\n }\n return handleTrezorTransportError(\n error,\n 'Failed to sign typed data with Trezor device',\n );\n }\n }\n\n forgetDevice(): void {\n this.accounts = [];\n this.hdk = new HDKey();\n this.page = 0;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n\n /**\n * Set the HD path to be used by the keyring. Only known supported HD paths are allowed.\n *\n * If the given HD path is already the current HD path, nothing happens. Otherwise the new HD\n * path is set, and the wallet state is completely reset.\n *\n * @throws {Error] Throws if the HD path is not supported.\n *\n * @param hdPath - The HD path to set.\n */\n setHdPath(hdPath: keyof typeof ALLOWED_HD_PATHS): void {\n if (!ALLOWED_HD_PATHS[hdPath]) {\n throw new Error(\n `The setHdPath method does not support setting HD Path to ${hdPath}`,\n );\n }\n\n // Reset HDKey if the path changes\n if (this.hdPath !== hdPath) {\n this.hdk = new HDKey();\n this.accounts = [];\n this.page = 0;\n this.perPage = 5;\n this.unlockedAccount = 0;\n this.paths = {};\n }\n this.hdPath = hdPath;\n }\n\n #normalize(buf: Buffer): string {\n return bytesToHex(buf);\n }\n\n /**\n * Derive an address at a specific index using the HDKey.\n *\n * @param basePath - The base derivation path (e.g., 'm').\n * @param i - The derivation index.\n * @returns The checksummed address.\n */\n #addressFromIndex(basePath: string, i: number): Hex {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = bytesToHex(publicToAddress(dkey.publicKey, true));\n return toChecksumAddress(address);\n }\n\n /**\n * Get the account index for a given address.\n *\n * This method first checks the `paths` map, and if not found, derives\n * addresses up to MAX_INDEX to find the matching index.\n *\n * @param address - The account address.\n * @returns The account index.\n * @throws If the address is not found.\n */\n getIndexForAddress(address: Hex): number {\n const checksummedAddress = getChecksumAddress(address);\n let index = this.paths[checksummedAddress];\n\n if (typeof index === 'undefined') {\n for (let i = 0; i < MAX_INDEX; i++) {\n if (checksummedAddress === this.#addressFromIndex(pathBase, i)) {\n index = i;\n break;\n }\n }\n }\n\n if (typeof index === 'undefined') {\n throw new Error('Unknown address');\n }\n\n return index;\n }\n\n #pathFromAddress(address: Hex): string {\n const index = this.getIndexForAddress(address);\n return `${this.hdPath}/${index}`;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/eth-trezor-keyring",
3
- "version": "10.1.0-c42f34c",
3
+ "version": "10.1.0-e51c895",
4
4
  "description": "A MetaMask compatible keyring, for trezor hardware wallets",
5
5
  "keywords": [
6
6
  "ethereum",
@@ -71,8 +71,8 @@
71
71
  "@ethereumjs/tx": "^5.4.0",
72
72
  "@ethereumjs/util": "^9.1.0",
73
73
  "@metamask/eth-sig-util": "^8.2.0",
74
- "@metamask/hw-wallet-sdk": "0.8.0",
75
- "@metamask/keyring-api": "23.2.0",
74
+ "@metamask/hw-wallet-sdk": "0.9.0",
75
+ "@metamask/keyring-api": "23.3.0",
76
76
  "@metamask/keyring-sdk": "2.2.0",
77
77
  "@metamask/keyring-utils": "3.3.1",
78
78
  "@metamask/utils": "^11.11.0",