@metamask-previews/eth-trezor-keyring 4.0.0-d5a036e → 6.0.0-22cd5fe

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.
Files changed (39) hide show
  1. package/CHANGELOG.md +17 -1
  2. package/dist/{index.js → index.cjs} +3 -3
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +4 -0
  5. package/dist/index.d.cts.map +1 -0
  6. package/dist/index.d.mts +4 -0
  7. package/dist/index.d.mts.map +1 -0
  8. package/dist/index.mjs +3 -0
  9. package/dist/index.mjs.map +1 -0
  10. package/dist/{trezor-bridge.js → trezor-bridge.cjs} +1 -1
  11. package/dist/trezor-bridge.cjs.map +1 -0
  12. package/dist/{trezor-bridge.d.ts → trezor-bridge.d.cts} +2 -1
  13. package/dist/trezor-bridge.d.cts.map +1 -0
  14. package/dist/trezor-bridge.d.mts +19 -0
  15. package/dist/trezor-bridge.d.mts.map +1 -0
  16. package/dist/trezor-bridge.mjs +2 -0
  17. package/dist/trezor-bridge.mjs.map +1 -0
  18. package/dist/{trezor-connect-bridge.js → trezor-connect-bridge.cjs} +1 -1
  19. package/dist/trezor-connect-bridge.cjs.map +1 -0
  20. package/dist/{trezor-connect-bridge.d.ts → trezor-connect-bridge.d.cts} +4 -3
  21. package/dist/trezor-connect-bridge.d.cts.map +1 -0
  22. package/dist/trezor-connect-bridge.d.mts +19 -0
  23. package/dist/trezor-connect-bridge.d.mts.map +1 -0
  24. package/dist/trezor-connect-bridge.mjs +48 -0
  25. package/dist/trezor-connect-bridge.mjs.map +1 -0
  26. package/dist/{trezor-keyring.js → trezor-keyring.cjs} +2 -1
  27. package/dist/trezor-keyring.cjs.map +1 -0
  28. package/dist/{trezor-keyring.d.ts → trezor-keyring.d.cts} +7 -7
  29. package/dist/trezor-keyring.d.cts.map +1 -0
  30. package/dist/trezor-keyring.d.mts +103 -0
  31. package/dist/trezor-keyring.d.mts.map +1 -0
  32. package/dist/trezor-keyring.mjs +450 -0
  33. package/dist/trezor-keyring.mjs.map +1 -0
  34. package/package.json +20 -10
  35. package/dist/index.d.ts +0 -3
  36. package/dist/index.js.map +0 -1
  37. package/dist/trezor-bridge.js.map +0 -1
  38. package/dist/trezor-connect-bridge.js.map +0 -1
  39. package/dist/trezor-keyring.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [6.0.0]
11
+
12
+ ### Added
13
+
14
+ - **BREAKING:** Add ESM build ([#40](https://github.com/MetaMask/accounts/pull/40))
15
+ - It's no longer possible to import files from `./dist` directly.
16
+
17
+ ## [5.0.0]
18
+
19
+ ### Changed
20
+
21
+ - **BREAKING**: Bump `@metamask/eth-sig-util` dependency from `^7.0.3` to `^8.0.0` ([#79](https://github.com/MetaMask/accounts/pull/79))
22
+ - `signTypedData` no longer support `number` for addresses, see [here](https://github.com/MetaMask/eth-sig-util/blob/main/CHANGELOG.md#800).
23
+
10
24
  ## [4.0.0]
11
25
 
12
26
  ### Changed
@@ -127,7 +141,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
127
141
 
128
142
  - Support new versions of ethereumjs/tx ([#88](https://github.com/metamask/eth-trezor-keyring/pull/88))
129
143
 
130
- [Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@4.0.0...HEAD
144
+ [Unreleased]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@6.0.0...HEAD
145
+ [6.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@5.0.0...@metamask/eth-trezor-keyring@6.0.0
146
+ [5.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@4.0.0...@metamask/eth-trezor-keyring@5.0.0
131
147
  [4.0.0]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@3.1.3...@metamask/eth-trezor-keyring@4.0.0
132
148
  [3.1.3]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@3.1.2...@metamask/eth-trezor-keyring@3.1.3
133
149
  [3.1.2]: https://github.com/MetaMask/accounts/compare/@metamask/eth-trezor-keyring@3.1.1...@metamask/eth-trezor-keyring@3.1.2
@@ -14,6 +14,6 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
14
  for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
- __exportStar(require("./trezor-keyring"), exports);
18
- __exportStar(require("./trezor-connect-bridge"), exports);
19
- //# sourceMappingURL=index.js.map
17
+ __exportStar(require("./trezor-keyring.cjs"), exports);
18
+ __exportStar(require("./trezor-connect-bridge.cjs"), exports);
19
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,uDAAiC;AAEjC,8DAAwC","sourcesContent":["export * from './trezor-keyring';\nexport type * from './trezor-bridge';\nexport * from './trezor-connect-bridge';\n"]}
@@ -0,0 +1,4 @@
1
+ export * from "./trezor-keyring.cjs";
2
+ export type * from "./trezor-bridge.cjs";
3
+ export * from "./trezor-connect-bridge.cjs";
4
+ //# sourceMappingURL=index.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.cts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAiC;AACjC,yCAAqC;AACrC,4CAAwC"}
@@ -0,0 +1,4 @@
1
+ export * from "./trezor-keyring.mjs";
2
+ export type * from "./trezor-bridge.mjs";
3
+ export * from "./trezor-connect-bridge.mjs";
4
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAiC;AACjC,yCAAqC;AACrC,4CAAwC"}
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./trezor-keyring.mjs";
2
+ export * from "./trezor-connect-bridge.mjs";
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,qCAAiC;AAEjC,4CAAwC","sourcesContent":["export * from './trezor-keyring';\nexport type * from './trezor-bridge';\nexport * from './trezor-connect-bridge';\n"]}
@@ -1,3 +1,3 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- //# sourceMappingURL=trezor-bridge.js.map
3
+ //# sourceMappingURL=trezor-bridge.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge.cjs","sourceRoot":"","sources":["../src/trezor-bridge.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ConnectSettings,\n EthereumSignedTx,\n Manifest,\n PROTO,\n Response,\n Params,\n EthereumSignMessage,\n EthereumSignTransaction,\n EthereumSignTypedDataTypes,\n EthereumSignTypedHash,\n} from '@trezor/connect-web';\n\nexport interface TrezorBridge {\n model?: string;\n\n init(\n settings: {\n manifest: Manifest;\n } & Partial<ConnectSettings>,\n ): Promise<void>;\n\n dispose(): Promise<void>;\n\n // TrezorConnect.getPublicKey has two overloads\n // It is not possible to extract them from the library using utility types\n getPublicKey(params: {\n path: string;\n coin: string;\n }): Response<{ publicKey: string; chainCode: string }>;\n\n ethereumSignTransaction(\n params: Params<EthereumSignTransaction>,\n ): Response<EthereumSignedTx>;\n\n ethereumSignMessage(\n params: Params<EthereumSignMessage>,\n ): Response<PROTO.MessageSignature>;\n\n ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(\n params: Params<EthereumSignTypedHash<T>>,\n ): Response<PROTO.EthereumTypedDataSignature>;\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { ConnectSettings, EthereumSignedTx, Manifest, PROTO, Response, Params, EthereumSignMessage, EthereumSignTransaction, EthereumSignTypedDataTypes, EthereumSignTypedHash } from '@trezor/connect-web';
1
+ import type { ConnectSettings, EthereumSignedTx, Manifest, PROTO, Response, Params, EthereumSignMessage, EthereumSignTransaction, EthereumSignTypedDataTypes, EthereumSignTypedHash } from "@trezor/connect-web";
2
2
  export interface TrezorBridge {
3
3
  model?: string;
4
4
  init(settings: {
@@ -16,3 +16,4 @@ export interface TrezorBridge {
16
16
  ethereumSignMessage(params: Params<EthereumSignMessage>): Response<PROTO.MessageSignature>;
17
17
  ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(params: Params<EthereumSignTypedHash<T>>): Response<PROTO.EthereumTypedDataSignature>;
18
18
  }
19
+ //# sourceMappingURL=trezor-bridge.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge.d.cts","sourceRoot":"","sources":["../src/trezor-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,QAAQ,EACR,KAAK,EACL,QAAQ,EACR,MAAM,EACN,mBAAmB,EACnB,uBAAuB,EACvB,0BAA0B,EAC1B,qBAAqB,EACtB,4BAA4B;AAE7B,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,IAAI,CACF,QAAQ,EAAE;QACR,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,eAAe,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAIzB,YAAY,CAAC,MAAM,EAAE;QACnB,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,GAAG,QAAQ,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAEvD,uBAAuB,CACrB,MAAM,EAAE,MAAM,CAAC,uBAAuB,CAAC,GACtC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAE9B,mBAAmB,CACjB,MAAM,EAAE,MAAM,CAAC,mBAAmB,CAAC,GAClC,QAAQ,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEpC,qBAAqB,CAAC,CAAC,SAAS,0BAA0B,EACxD,MAAM,EAAE,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GACvC,QAAQ,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;CAC/C"}
@@ -0,0 +1,19 @@
1
+ import type { ConnectSettings, EthereumSignedTx, Manifest, PROTO, Response, Params, EthereumSignMessage, EthereumSignTransaction, EthereumSignTypedDataTypes, EthereumSignTypedHash } from "@trezor/connect-web";
2
+ export interface TrezorBridge {
3
+ model?: string;
4
+ init(settings: {
5
+ manifest: Manifest;
6
+ } & Partial<ConnectSettings>): Promise<void>;
7
+ dispose(): Promise<void>;
8
+ getPublicKey(params: {
9
+ path: string;
10
+ coin: string;
11
+ }): Response<{
12
+ publicKey: string;
13
+ chainCode: string;
14
+ }>;
15
+ ethereumSignTransaction(params: Params<EthereumSignTransaction>): Response<EthereumSignedTx>;
16
+ ethereumSignMessage(params: Params<EthereumSignMessage>): Response<PROTO.MessageSignature>;
17
+ ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(params: Params<EthereumSignTypedHash<T>>): Response<PROTO.EthereumTypedDataSignature>;
18
+ }
19
+ //# sourceMappingURL=trezor-bridge.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge.d.mts","sourceRoot":"","sources":["../src/trezor-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,gBAAgB,EAChB,QAAQ,EACR,KAAK,EACL,QAAQ,EACR,MAAM,EACN,mBAAmB,EACnB,uBAAuB,EACvB,0BAA0B,EAC1B,qBAAqB,EACtB,4BAA4B;AAE7B,MAAM,WAAW,YAAY;IAC3B,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,IAAI,CACF,QAAQ,EAAE;QACR,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,eAAe,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAIzB,YAAY,CAAC,MAAM,EAAE;QACnB,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,GAAG,QAAQ,CAAC;QAAE,SAAS,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAEvD,uBAAuB,CACrB,MAAM,EAAE,MAAM,CAAC,uBAAuB,CAAC,GACtC,QAAQ,CAAC,gBAAgB,CAAC,CAAC;IAE9B,mBAAmB,CACjB,MAAM,EAAE,MAAM,CAAC,mBAAmB,CAAC,GAClC,QAAQ,CAAC,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAEpC,qBAAqB,CAAC,CAAC,SAAS,0BAA0B,EACxD,MAAM,EAAE,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GACvC,QAAQ,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC;CAC/C"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=trezor-bridge.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-bridge.mjs","sourceRoot":"","sources":["../src/trezor-bridge.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ConnectSettings,\n EthereumSignedTx,\n Manifest,\n PROTO,\n Response,\n Params,\n EthereumSignMessage,\n EthereumSignTransaction,\n EthereumSignTypedDataTypes,\n EthereumSignTypedHash,\n} from '@trezor/connect-web';\n\nexport interface TrezorBridge {\n model?: string;\n\n init(\n settings: {\n manifest: Manifest;\n } & Partial<ConnectSettings>,\n ): Promise<void>;\n\n dispose(): Promise<void>;\n\n // TrezorConnect.getPublicKey has two overloads\n // It is not possible to extract them from the library using utility types\n getPublicKey(params: {\n path: string;\n coin: string;\n }): Response<{ publicKey: string; chainCode: string }>;\n\n ethereumSignTransaction(\n params: Params<EthereumSignTransaction>,\n ): Response<EthereumSignedTx>;\n\n ethereumSignMessage(\n params: Params<EthereumSignMessage>,\n ): Response<PROTO.MessageSignature>;\n\n ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(\n params: Params<EthereumSignTypedHash<T>>,\n ): Response<PROTO.EthereumTypedDataSignature>;\n}\n"]}
@@ -64,4 +64,4 @@ class TrezorConnectBridge {
64
64
  }
65
65
  }
66
66
  exports.TrezorConnectBridge = TrezorConnectBridge;
67
- //# sourceMappingURL=trezor-connect-bridge.js.map
67
+ //# sourceMappingURL=trezor-connect-bridge.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-connect-bridge.cjs","sourceRoot":"","sources":["../src/trezor-connect-bridge.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,mEAA0E;AAgB1E,MAAa,mBAAmB;IAAhC;QAGE,2BAAsB,GAAG,KAAK,CAAC;IAsDjC,CAAC;IApDC,KAAK,CAAC,IAAI,CACR,QAE4B;QAE5B,qBAAa,CAAC,EAAE,CAAC,0BAAY,EAAE,CAAC,KAAK,EAAE,EAAE;;YACvC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAM,CAAC,OAAO,EAAE,CAAC;gBAClC,OAAO;YACT,CAAC;YACD,IAAI,CAAC,KAAK,GAAG,MAAA,KAAK,CAAC,OAAO,CAAC,QAAQ,0CAAE,KAAK,CAAC;QAC7C,CAAC,CAAC,CAAC;QAEH,IAAI,IAAI,CAAC,sBAAsB,EAAE,CAAC;YAChC,OAAO;QACT,CAAC;QAED,MAAM,qBAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,OAAO;QACX,sDAAsD;QACtD,wEAAwE;QACxE,sHAAsH;QACtH,qBAAa,CAAC,OAAO,EAAE,CAAC;QACxB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,YAAY,CAAC,MAGZ;QACC,OAAO,qBAAa,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;IAED,uBAAuB,CACrB,MAAuC;QAEvC,OAAO,qBAAa,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;IACvD,CAAC;IAED,mBAAmB,CACjB,MAAmC;QAEnC,OAAO,qBAAa,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACnD,CAAC;IAED,qBAAqB,CACnB,MAAwC;QAExC,OAAO,qBAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACrD,CAAC;CACF;AAzDD,kDAyDC","sourcesContent":["import type { HDNodeResponse } from '@trezor/connect/lib/types/api/getPublicKey';\nimport TrezorConnect, { DEVICE_EVENT, DEVICE } from '@trezor/connect-web';\nimport type {\n EthereumSignedTx,\n PROTO,\n Response,\n Manifest,\n ConnectSettings,\n EthereumSignTransaction,\n Params,\n EthereumSignMessage,\n EthereumSignTypedDataTypes,\n EthereumSignTypedHash,\n} from '@trezor/connect-web';\n\nimport type { TrezorBridge } from './trezor-bridge';\n\nexport class TrezorConnectBridge implements TrezorBridge {\n model?: string;\n\n trezorConnectInitiated = false;\n\n async init(\n settings: {\n manifest: Manifest;\n } & Partial<ConnectSettings>,\n ): Promise<void> {\n TrezorConnect.on(DEVICE_EVENT, (event) => {\n if (event.type !== DEVICE.CONNECT) {\n return;\n }\n this.model = event.payload.features?.model;\n });\n\n if (this.trezorConnectInitiated) {\n return;\n }\n\n await TrezorConnect.init(settings);\n this.trezorConnectInitiated = true;\n }\n\n async dispose(): Promise<void> {\n // This removes the Trezor Connect iframe from the DOM\n // This method is not well documented, but the code it calls can be seen\n // here: https://github.com/trezor/connect/blob/dec4a56af8a65a6059fb5f63fa3c6690d2c37e00/src/js/iframe/builder.js#L181\n TrezorConnect.dispose();\n return Promise.resolve();\n }\n\n getPublicKey(params: {\n path: string;\n coin: string;\n }): Response<HDNodeResponse> {\n return TrezorConnect.getPublicKey(params);\n }\n\n ethereumSignTransaction(\n params: Params<EthereumSignTransaction>,\n ): Response<EthereumSignedTx> {\n return TrezorConnect.ethereumSignTransaction(params);\n }\n\n ethereumSignMessage(\n params: Params<EthereumSignMessage>,\n ): Response<PROTO.MessageSignature> {\n return TrezorConnect.ethereumSignMessage(params);\n }\n\n ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(\n params: Params<EthereumSignTypedHash<T>>,\n ): Response<PROTO.EthereumTypedDataSignature> {\n return TrezorConnect.ethereumSignTypedData(params);\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- import type { HDNodeResponse } from '@trezor/connect/lib/types/api/getPublicKey';
2
- import type { EthereumSignedTx, PROTO, Response, Manifest, ConnectSettings, EthereumSignTransaction, Params, EthereumSignMessage, EthereumSignTypedDataTypes, EthereumSignTypedHash } from '@trezor/connect-web';
3
- import type { TrezorBridge } from './trezor-bridge';
1
+ import type { HDNodeResponse } from "@trezor/connect/lib/types/api/getPublicKey.js";
2
+ import type { EthereumSignedTx, PROTO, Response, Manifest, ConnectSettings, EthereumSignTransaction, Params, EthereumSignMessage, EthereumSignTypedDataTypes, EthereumSignTypedHash } from "@trezor/connect-web";
3
+ import type { TrezorBridge } from "./trezor-bridge.cjs";
4
4
  export declare class TrezorConnectBridge implements TrezorBridge {
5
5
  model?: string;
6
6
  trezorConnectInitiated: boolean;
@@ -16,3 +16,4 @@ export declare class TrezorConnectBridge implements TrezorBridge {
16
16
  ethereumSignMessage(params: Params<EthereumSignMessage>): Response<PROTO.MessageSignature>;
17
17
  ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(params: Params<EthereumSignTypedHash<T>>): Response<PROTO.EthereumTypedDataSignature>;
18
18
  }
19
+ //# sourceMappingURL=trezor-connect-bridge.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-connect-bridge.d.cts","sourceRoot":"","sources":["../src/trezor-connect-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,sDAAmD;AAEjF,OAAO,KAAK,EACV,gBAAgB,EAChB,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,eAAe,EACf,uBAAuB,EACvB,MAAM,EACN,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,EACtB,4BAA4B;AAE7B,OAAO,KAAK,EAAE,YAAY,EAAE,4BAAwB;AAEpD,qBAAa,mBAAoB,YAAW,YAAY;IACtD,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,sBAAsB,UAAS;IAEzB,IAAI,CACR,QAAQ,EAAE;QACR,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,eAAe,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC;IAgBV,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ9B,YAAY,CAAC,MAAM,EAAE;QACnB,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,GAAG,QAAQ,CAAC,cAAc,CAAC;IAI5B,uBAAuB,CACrB,MAAM,EAAE,MAAM,CAAC,uBAAuB,CAAC,GACtC,QAAQ,CAAC,gBAAgB,CAAC;IAI7B,mBAAmB,CACjB,MAAM,EAAE,MAAM,CAAC,mBAAmB,CAAC,GAClC,QAAQ,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAInC,qBAAqB,CAAC,CAAC,SAAS,0BAA0B,EACxD,MAAM,EAAE,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GACvC,QAAQ,CAAC,KAAK,CAAC,0BAA0B,CAAC;CAG9C"}
@@ -0,0 +1,19 @@
1
+ import type { HDNodeResponse } from "@trezor/connect/lib/types/api/getPublicKey.js";
2
+ import type { EthereumSignedTx, PROTO, Response, Manifest, ConnectSettings, EthereumSignTransaction, Params, EthereumSignMessage, EthereumSignTypedDataTypes, EthereumSignTypedHash } from "@trezor/connect-web";
3
+ import type { TrezorBridge } from "./trezor-bridge.mjs";
4
+ export declare class TrezorConnectBridge implements TrezorBridge {
5
+ model?: string;
6
+ trezorConnectInitiated: boolean;
7
+ init(settings: {
8
+ manifest: Manifest;
9
+ } & Partial<ConnectSettings>): Promise<void>;
10
+ dispose(): Promise<void>;
11
+ getPublicKey(params: {
12
+ path: string;
13
+ coin: string;
14
+ }): Response<HDNodeResponse>;
15
+ ethereumSignTransaction(params: Params<EthereumSignTransaction>): Response<EthereumSignedTx>;
16
+ ethereumSignMessage(params: Params<EthereumSignMessage>): Response<PROTO.MessageSignature>;
17
+ ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(params: Params<EthereumSignTypedHash<T>>): Response<PROTO.EthereumTypedDataSignature>;
18
+ }
19
+ //# sourceMappingURL=trezor-connect-bridge.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-connect-bridge.d.mts","sourceRoot":"","sources":["../src/trezor-connect-bridge.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,sDAAmD;AAEjF,OAAO,KAAK,EACV,gBAAgB,EAChB,KAAK,EACL,QAAQ,EACR,QAAQ,EACR,eAAe,EACf,uBAAuB,EACvB,MAAM,EACN,mBAAmB,EACnB,0BAA0B,EAC1B,qBAAqB,EACtB,4BAA4B;AAE7B,OAAO,KAAK,EAAE,YAAY,EAAE,4BAAwB;AAEpD,qBAAa,mBAAoB,YAAW,YAAY;IACtD,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,sBAAsB,UAAS;IAEzB,IAAI,CACR,QAAQ,EAAE;QACR,QAAQ,EAAE,QAAQ,CAAC;KACpB,GAAG,OAAO,CAAC,eAAe,CAAC,GAC3B,OAAO,CAAC,IAAI,CAAC;IAgBV,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAQ9B,YAAY,CAAC,MAAM,EAAE;QACnB,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;KACd,GAAG,QAAQ,CAAC,cAAc,CAAC;IAI5B,uBAAuB,CACrB,MAAM,EAAE,MAAM,CAAC,uBAAuB,CAAC,GACtC,QAAQ,CAAC,gBAAgB,CAAC;IAI7B,mBAAmB,CACjB,MAAM,EAAE,MAAM,CAAC,mBAAmB,CAAC,GAClC,QAAQ,CAAC,KAAK,CAAC,gBAAgB,CAAC;IAInC,qBAAqB,CAAC,CAAC,SAAS,0BAA0B,EACxD,MAAM,EAAE,MAAM,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAAC,GACvC,QAAQ,CAAC,KAAK,CAAC,0BAA0B,CAAC;CAG9C"}
@@ -0,0 +1,48 @@
1
+ function $importDefault(module) {
2
+ if (module === null || module === void 0 ? void 0 : module.__esModule) {
3
+ return module.default;
4
+ }
5
+ return module;
6
+ }
7
+ import $TrezorConnect from "@trezor/connect-web";
8
+ const { DEVICE_EVENT, DEVICE } = $TrezorConnect;
9
+ const TrezorConnect = $importDefault($TrezorConnect);
10
+ export class TrezorConnectBridge {
11
+ constructor() {
12
+ this.trezorConnectInitiated = false;
13
+ }
14
+ async init(settings) {
15
+ TrezorConnect.on(DEVICE_EVENT, (event) => {
16
+ var _a;
17
+ if (event.type !== DEVICE.CONNECT) {
18
+ return;
19
+ }
20
+ this.model = (_a = event.payload.features) === null || _a === void 0 ? void 0 : _a.model;
21
+ });
22
+ if (this.trezorConnectInitiated) {
23
+ return;
24
+ }
25
+ await TrezorConnect.init(settings);
26
+ this.trezorConnectInitiated = true;
27
+ }
28
+ async dispose() {
29
+ // This removes the Trezor Connect iframe from the DOM
30
+ // This method is not well documented, but the code it calls can be seen
31
+ // here: https://github.com/trezor/connect/blob/dec4a56af8a65a6059fb5f63fa3c6690d2c37e00/src/js/iframe/builder.js#L181
32
+ TrezorConnect.dispose();
33
+ return Promise.resolve();
34
+ }
35
+ getPublicKey(params) {
36
+ return TrezorConnect.getPublicKey(params);
37
+ }
38
+ ethereumSignTransaction(params) {
39
+ return TrezorConnect.ethereumSignTransaction(params);
40
+ }
41
+ ethereumSignMessage(params) {
42
+ return TrezorConnect.ethereumSignMessage(params);
43
+ }
44
+ ethereumSignTypedData(params) {
45
+ return TrezorConnect.ethereumSignTypedData(params);
46
+ }
47
+ }
48
+ //# sourceMappingURL=trezor-connect-bridge.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-connect-bridge.mjs","sourceRoot":"","sources":["../src/trezor-connect-bridge.ts"],"names":[],"mappings":";;;;;;;;;AAiBA,MAAM,OAAO,mBAAmB;IAAhC;QAGE,2BAAsB,GAAG,KAAK,CAAC;IAsDjC,CAAC;IApDC,KAAK,CAAC,IAAI,CACR,QAE4B;QAE5B,aAAa,CAAC,EAAE,CAAC,YAAY,EAAE,CAAC,KAAK,EAAE,EAAE;;YACvC,IAAI,KAAK,CAAC,IAAI,KAAK,MAAM,CAAC,OAAO,EAAE,CAAC;gBAClC,OAAO;YACT,CAAC;YACD,IAAI,CAAC,KAAK,GAAG,MAAA,KAAK,CAAC,OAAO,CAAC,QAAQ,0CAAE,KAAK,CAAC;QAC7C,CAAC,CAAC,CAAC;QAEH,IAAI,IAAI,CAAC,sBAAsB,EAAE,CAAC;YAChC,OAAO;QACT,CAAC;QAED,MAAM,aAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,OAAO;QACX,sDAAsD;QACtD,wEAAwE;QACxE,sHAAsH;QACtH,aAAa,CAAC,OAAO,EAAE,CAAC;QACxB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,YAAY,CAAC,MAGZ;QACC,OAAO,aAAa,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;IAED,uBAAuB,CACrB,MAAuC;QAEvC,OAAO,aAAa,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;IACvD,CAAC;IAED,mBAAmB,CACjB,MAAmC;QAEnC,OAAO,aAAa,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACnD,CAAC;IAED,qBAAqB,CACnB,MAAwC;QAExC,OAAO,aAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACrD,CAAC;CACF","sourcesContent":["import type { HDNodeResponse } from '@trezor/connect/lib/types/api/getPublicKey';\nimport TrezorConnect, { DEVICE_EVENT, DEVICE } from '@trezor/connect-web';\nimport type {\n EthereumSignedTx,\n PROTO,\n Response,\n Manifest,\n ConnectSettings,\n EthereumSignTransaction,\n Params,\n EthereumSignMessage,\n EthereumSignTypedDataTypes,\n EthereumSignTypedHash,\n} from '@trezor/connect-web';\n\nimport type { TrezorBridge } from './trezor-bridge';\n\nexport class TrezorConnectBridge implements TrezorBridge {\n model?: string;\n\n trezorConnectInitiated = false;\n\n async init(\n settings: {\n manifest: Manifest;\n } & Partial<ConnectSettings>,\n ): Promise<void> {\n TrezorConnect.on(DEVICE_EVENT, (event) => {\n if (event.type !== DEVICE.CONNECT) {\n return;\n }\n this.model = event.payload.features?.model;\n });\n\n if (this.trezorConnectInitiated) {\n return;\n }\n\n await TrezorConnect.init(settings);\n this.trezorConnectInitiated = true;\n }\n\n async dispose(): Promise<void> {\n // This removes the Trezor Connect iframe from the DOM\n // This method is not well documented, but the code it calls can be seen\n // here: https://github.com/trezor/connect/blob/dec4a56af8a65a6059fb5f63fa3c6690d2c37e00/src/js/iframe/builder.js#L181\n TrezorConnect.dispose();\n return Promise.resolve();\n }\n\n getPublicKey(params: {\n path: string;\n coin: string;\n }): Response<HDNodeResponse> {\n return TrezorConnect.getPublicKey(params);\n }\n\n ethereumSignTransaction(\n params: Params<EthereumSignTransaction>,\n ): Response<EthereumSignedTx> {\n return TrezorConnect.ethereumSignTransaction(params);\n }\n\n ethereumSignMessage(\n params: Params<EthereumSignMessage>,\n ): Response<PROTO.MessageSignature> {\n return TrezorConnect.ethereumSignMessage(params);\n }\n\n ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(\n params: Params<EthereumSignTypedHash<T>>,\n ): Response<PROTO.EthereumTypedDataSignature> {\n return TrezorConnect.ethereumSignTypedData(params);\n }\n}\n"]}
@@ -39,6 +39,7 @@ const eth_sig_util_1 = require("@metamask/eth-sig-util");
39
39
  const connect_plugin_ethereum_1 = require("@trezor/connect-plugin-ethereum");
40
40
  const events_1 = require("events");
41
41
  const hdkey_1 = __importDefault(require("hdkey"));
42
+ const trezor_bridge_1 = require("./trezor-bridge.cjs");
42
43
  const hdPathString = `m/44'/60'/0'/0`;
43
44
  const SLIP0044TestnetPath = `m/44'/1'/0'/0`;
44
45
  const legacyMewPath = `m/44'/60'/0'`;
@@ -468,4 +469,4 @@ async function _TrezorKeyring_signTransaction(address, chainId, tx, handleSignin
468
469
  return `${this.hdPath}/${index}`;
469
470
  };
470
471
  TrezorKeyring.type = keyringType;
471
- //# sourceMappingURL=trezor-keyring.js.map
472
+ //# sourceMappingURL=trezor-keyring.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-keyring.cjs","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAoD;AAEpD,0DAA4C;AAC5C,yDAIgC;AAChC,6EAAqE;AAOrE,mCAAsC;AACtC,kDAA0B;AAE1B,uDAA+C;AAE/C,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAC5C,MAAM,aAAa,GAAG,cAAc,CAAC;AAErC,MAAM,gBAAgB,GAAG;IACvB,CAAC,YAAY,CAAC,EAAE,IAAI;IACpB,CAAC,aAAa,CAAC,EAAE,IAAI;IACrB,CAAC,mBAAmB,CAAC,EAAE,IAAI;CACnB,CAAC;AAEX,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,QAAQ,GAAG,GAA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kB,KAAK,uBAAA,IAAI,iEAAkB,MAAtB,IAAI,EAAmB,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC;gBAC/D,KAAK,GAAG,CAAC,CAAC;gBACV,MAAM;YACR,CAAC;QACH,CAAC;IACH,CAAC;IAED,IAAI,OAAO,KAAK,KAAK,WAAW,EAAE,CAAC;QACjC,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IACrC,CAAC;IACD,OAAO,GAAG,IAAI,CAAC,MAAM,IAAI,KAAK,EAAE,CAAC;AACnC,CAAC;AA3eM,kBAAI,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedTransaction, TxData } from '@ethereumjs/tx';\nimport * as ethUtil from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\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 { EventEmitter } from 'events';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\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 email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport interface TrezorControllerOptions {\n hdPath?: string;\n accounts?: string[];\n page?: number;\n perPage?: number;\n}\n\nexport interface TrezorControllerState {\n hdPath: string;\n accounts: readonly string[];\n page: number;\n paths: Record<string, 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\nexport class TrezorKeyring extends EventEmitter {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly string[] = [];\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 super();\n\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,\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 return new Promise((resolve, reject) => {\n this.bridge\n .getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n })\n .then((response) => {\n if (response.success) {\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n resolve('just unlocked');\n } else {\n reject(new Error(response.payload?.error || 'Unknown error'));\n }\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n });\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(n = 1): Promise<readonly string[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + n;\n const newAccounts = [];\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[ethUtil.toChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<string[]> {\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: string,\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: TxData = 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 = ethUtil.addHexPrefix(payload.v);\n txData.r = ethUtil.addHexPrefix(payload.r);\n txData.s = ethUtil.addHexPrefix(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: string,\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(ethUtil.toBuffer(tx.to)),\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 = ethUtil.toChecksumAddress(\n ethUtil.addHexPrefix(\n newOrMutatedTx.getSenderAddress().toString('hex'),\n ),\n );\n const correctAddress = ethUtil.toChecksumAddress(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 (e) {\n throw new Error(e?.toString() ?? 'Unknown error');\n }\n }\n\n async signMessage(withAccount: string, 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: string,\n message: string,\n ): Promise<string> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((status) => {\n setTimeout(\n () => {\n this.bridge\n .ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: ethUtil.stripHexPrefix(message),\n hex: true,\n })\n .then((response) => {\n if (response.success) {\n if (\n response.payload.address !==\n ethUtil.toChecksumAddress(withAccount)\n ) {\n reject(\n new Error('signature doesnt match the right address'),\n );\n }\n const signature = `0x${response.payload.signature}`;\n resolve(signature);\n } else {\n reject(\n new Error(response.payload?.error || 'Unknown error'),\n );\n }\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n },\n status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0,\n );\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n });\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<T extends MessageTypes>(\n address: string,\n data: TypedMessage<T>,\n { version }: { version: SignTypedDataVersion },\n ): Promise<string> {\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\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, // eslint-disable-line camelcase\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 if (ethUtil.toChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n }\n\n throw new Error(response.payload?.error || 'Unknown error');\n }\n\n async exportAccount(): Promise<never> {\n return Promise.reject(new Error('Not supported on this device'));\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 ethUtil.bufferToHex(buf).toString();\n }\n\n #addressFromIndex(basePath: string, i: number): string {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = ethUtil\n .publicToAddress(dkey.publicKey, true)\n .toString('hex');\n return ethUtil.toChecksumAddress(`0x${address}`);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = ethUtil.toChecksumAddress(address);\n let index = this.paths[checksummedAddress];\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 return `${this.hdPath}/${index}`;\n }\n}\n"]}
@@ -1,10 +1,9 @@
1
- /// <reference types="node" />
2
- import type { TypedTransaction } from '@ethereumjs/tx';
3
- import { TypedMessage, SignTypedDataVersion, MessageTypes } from '@metamask/eth-sig-util';
4
- import type OldEthJsTransaction from 'ethereumjs-tx';
5
- import { EventEmitter } from 'events';
6
- import HDKey from 'hdkey';
7
- import { TrezorBridge } from './trezor-bridge';
1
+ import type { TypedTransaction } from "@ethereumjs/tx";
2
+ import { TypedMessage, SignTypedDataVersion, MessageTypes } from "@metamask/eth-sig-util";
3
+ import type OldEthJsTransaction from "ethereumjs-tx";
4
+ import { EventEmitter } from "events";
5
+ import HDKey from "hdkey";
6
+ import { TrezorBridge } from "./trezor-bridge.cjs";
8
7
  declare const ALLOWED_HD_PATHS: {
9
8
  readonly "m/44'/60'/0'/0": true;
10
9
  readonly "m/44'/60'/0'": true;
@@ -101,3 +100,4 @@ export declare class TrezorKeyring extends EventEmitter {
101
100
  setHdPath(hdPath: keyof typeof ALLOWED_HD_PATHS): void;
102
101
  }
103
102
  export {};
103
+ //# sourceMappingURL=trezor-keyring.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-keyring.d.cts","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAU,uBAAuB;AAE/D,OAAO,EACL,YAAY,EACZ,oBAAoB,EACpB,YAAY,EACb,+BAA+B;AAOhC,OAAO,KAAK,mBAAmB,sBAAsB;AAC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,OAAO,CAAC,MAAM,CAAC;IA+CZ,aAAa,IAAI,OAAO,CAAC,KAAK,CAAC;IAIrC,YAAY,IAAI,IAAI;IAQpB;;;;;;;;;OASG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,OAAO,gBAAgB,GAAG,IAAI;CAgDvD"}
@@ -0,0 +1,103 @@
1
+ import type { TypedTransaction } from "@ethereumjs/tx";
2
+ import { TypedMessage, SignTypedDataVersion, MessageTypes } from "@metamask/eth-sig-util";
3
+ import type OldEthJsTransaction from "ethereumjs-tx";
4
+ import { EventEmitter } from "events";
5
+ import HDKey from "hdkey";
6
+ import { TrezorBridge } from "./trezor-bridge.mjs";
7
+ declare const ALLOWED_HD_PATHS: {
8
+ readonly "m/44'/60'/0'/0": true;
9
+ readonly "m/44'/60'/0'": true;
10
+ readonly "m/44'/1'/0'/0": true;
11
+ };
12
+ export declare const TREZOR_CONNECT_MANIFEST: {
13
+ email: string;
14
+ appUrl: string;
15
+ };
16
+ export type AccountPageEntry = {
17
+ address: string;
18
+ balance: number | null;
19
+ index: number;
20
+ };
21
+ export type AccountPage = AccountPageEntry[];
22
+ export interface TrezorControllerOptions {
23
+ hdPath?: string;
24
+ accounts?: string[];
25
+ page?: number;
26
+ perPage?: number;
27
+ }
28
+ export interface TrezorControllerState {
29
+ hdPath: string;
30
+ accounts: readonly string[];
31
+ page: number;
32
+ paths: Record<string, number>;
33
+ perPage: number;
34
+ unlockedAccount: number;
35
+ }
36
+ export declare class TrezorKeyring extends EventEmitter {
37
+ #private;
38
+ static type: string;
39
+ readonly type: string;
40
+ accounts: readonly string[];
41
+ hdk: HDKey;
42
+ hdPath: string;
43
+ page: number;
44
+ perPage: number;
45
+ unlockedAccount: number;
46
+ paths: Record<string, number>;
47
+ bridge: TrezorBridge;
48
+ constructor({ bridge }: {
49
+ bridge: TrezorBridge;
50
+ });
51
+ /**
52
+ * Gets the model, if known.
53
+ * This may be `undefined` if the model hasn't been loaded yet.
54
+ *
55
+ * @returns
56
+ */
57
+ getModel(): string | undefined;
58
+ init(): Promise<void>;
59
+ destroy(): Promise<void>;
60
+ serialize(): Promise<TrezorControllerState>;
61
+ deserialize(opts?: TrezorControllerOptions): Promise<void>;
62
+ isUnlocked(): boolean;
63
+ unlock(): Promise<string>;
64
+ setAccountToUnlock(index: number | string): void;
65
+ addAccounts(n?: number): Promise<readonly string[]>;
66
+ getFirstPage(): Promise<AccountPage>;
67
+ getNextPage(): Promise<AccountPage>;
68
+ getPreviousPage(): Promise<AccountPage>;
69
+ getAccounts(): Promise<string[]>;
70
+ removeAccount(address: string): void;
71
+ /**
72
+ * Signs a transaction using Trezor.
73
+ *
74
+ * Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns
75
+ * the same type.
76
+ *
77
+ * @param address - Hex string address.
78
+ * @param tx - Instance of either new-style or old-style ethereumjs transaction.
79
+ * @returns The signed transaction, an instance of either new-style or old-style
80
+ * ethereumjs transaction.
81
+ */
82
+ signTransaction(address: string, tx: TypedTransaction | OldEthJsTransaction): Promise<TypedTransaction | OldEthJsTransaction>;
83
+ signMessage(withAccount: string, data: string): Promise<string>;
84
+ signPersonalMessage(withAccount: string, message: string): Promise<string>;
85
+ signTypedData<T extends MessageTypes>(address: string, data: TypedMessage<T>, { version }: {
86
+ version: SignTypedDataVersion;
87
+ }): Promise<string>;
88
+ exportAccount(): Promise<never>;
89
+ forgetDevice(): void;
90
+ /**
91
+ * Set the HD path to be used by the keyring. Only known supported HD paths are allowed.
92
+ *
93
+ * If the given HD path is already the current HD path, nothing happens. Otherwise the new HD
94
+ * path is set, and the wallet state is completely reset.
95
+ *
96
+ * @throws {Error] Throws if the HD path is not supported.
97
+ *
98
+ * @param hdPath - The HD path to set.
99
+ */
100
+ setHdPath(hdPath: keyof typeof ALLOWED_HD_PATHS): void;
101
+ }
102
+ export {};
103
+ //# sourceMappingURL=trezor-keyring.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-keyring.d.mts","sourceRoot":"","sources":["../src/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8CZ,aAAa,CAAC,CAAC,SAAS,YAAY,EACxC,OAAO,EAAE,MAAM,EACf,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,EACrB,EAAE,OAAO,EAAE,EAAE;QAAE,OAAO,EAAE,oBAAoB,CAAA;KAAE,GAC7C,OAAO,CAAC,MAAM,CAAC;IA+CZ,aAAa,IAAI,OAAO,CAAC,KAAK,CAAC;IAIrC,YAAY,IAAI,IAAI;IAQpB;;;;;;;;;OASG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,OAAO,gBAAgB,GAAG,IAAI;CAgDvD"}
@@ -0,0 +1,450 @@
1
+ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
2
+ if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
3
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
+ };
6
+ var _TrezorKeyring_instances, _TrezorKeyring_getPage, _TrezorKeyring_signTransaction, _TrezorKeyring_normalize, _TrezorKeyring_addressFromIndex, _TrezorKeyring_pathFromAddress;
7
+ function $importDefault(module) {
8
+ if (module === null || module === void 0 ? void 0 : module.__esModule) {
9
+ return module.default;
10
+ }
11
+ return module;
12
+ }
13
+ import { TransactionFactory } from "@ethereumjs/tx";
14
+ import * as ethUtil from "@ethereumjs/util";
15
+ import $metamaskethsigutil from "@metamask/eth-sig-util";
16
+ const { TypedMessage, SignTypedDataVersion, MessageTypes } = $metamaskethsigutil;
17
+ import { transformTypedData } from "@trezor/connect-plugin-ethereum";
18
+ import { EventEmitter } from "events";
19
+ import $HDKey from "hdkey";
20
+ const HDKey = $importDefault($HDKey);
21
+ import { TrezorBridge } from "./trezor-bridge.mjs";
22
+ const hdPathString = `m/44'/60'/0'/0`;
23
+ const SLIP0044TestnetPath = `m/44'/1'/0'/0`;
24
+ const legacyMewPath = `m/44'/60'/0'`;
25
+ const ALLOWED_HD_PATHS = {
26
+ [hdPathString]: true,
27
+ [legacyMewPath]: true,
28
+ [SLIP0044TestnetPath]: true,
29
+ };
30
+ const keyringType = 'Trezor Hardware';
31
+ const pathBase = 'm';
32
+ const MAX_INDEX = 1000;
33
+ const DELAY_BETWEEN_POPUPS = 1000;
34
+ export const TREZOR_CONNECT_MANIFEST = {
35
+ email: 'support@metamask.io',
36
+ appUrl: 'https://metamask.io',
37
+ };
38
+ async function wait(ms) {
39
+ return new Promise((resolve) => setTimeout(resolve, ms));
40
+ }
41
+ /**
42
+ * Check if the given transaction is made with ethereumjs-tx or @ethereumjs/tx
43
+ *
44
+ * Transactions built with older versions of ethereumjs-tx have a
45
+ * getChainId method that newer versions do not.
46
+ * Older versions are mutable
47
+ * while newer versions default to being immutable.
48
+ * Expected shape and type
49
+ * of data for v, r and s differ (Buffer (old) vs BN (new)).
50
+ *
51
+ * @param tx
52
+ * @returns Returns `true` if tx is an old-style ethereumjs-tx transaction.
53
+ */
54
+ function isOldStyleEthereumjsTx(tx) {
55
+ return typeof tx.getChainId === 'function';
56
+ }
57
+ export class TrezorKeyring extends EventEmitter {
58
+ constructor({ bridge }) {
59
+ super();
60
+ _TrezorKeyring_instances.add(this);
61
+ this.type = keyringType;
62
+ this.accounts = [];
63
+ this.hdk = new HDKey();
64
+ this.hdPath = hdPathString;
65
+ this.page = 0;
66
+ this.perPage = 5;
67
+ this.unlockedAccount = 0;
68
+ this.paths = {};
69
+ if (!bridge) {
70
+ throw new Error('Bridge is a required dependency for the keyring');
71
+ }
72
+ this.bridge = bridge;
73
+ }
74
+ /**
75
+ * Gets the model, if known.
76
+ * This may be `undefined` if the model hasn't been loaded yet.
77
+ *
78
+ * @returns
79
+ */
80
+ getModel() {
81
+ return this.bridge.model;
82
+ }
83
+ async init() {
84
+ return this.bridge.init({
85
+ manifest: TREZOR_CONNECT_MANIFEST,
86
+ lazyLoad: true,
87
+ });
88
+ }
89
+ async destroy() {
90
+ return this.bridge.dispose();
91
+ }
92
+ async serialize() {
93
+ return Promise.resolve({
94
+ hdPath: this.hdPath,
95
+ accounts: this.accounts,
96
+ page: this.page,
97
+ paths: this.paths,
98
+ perPage: this.perPage,
99
+ unlockedAccount: this.unlockedAccount,
100
+ });
101
+ }
102
+ async deserialize(opts = {}) {
103
+ var _a, _b, _c, _d;
104
+ this.hdPath = (_a = opts.hdPath) !== null && _a !== void 0 ? _a : hdPathString;
105
+ this.accounts = (_b = opts.accounts) !== null && _b !== void 0 ? _b : [];
106
+ this.page = (_c = opts.page) !== null && _c !== void 0 ? _c : 0;
107
+ this.perPage = (_d = opts.perPage) !== null && _d !== void 0 ? _d : 5;
108
+ return Promise.resolve();
109
+ }
110
+ isUnlocked() {
111
+ var _a;
112
+ return Boolean((_a = this.hdk) === null || _a === void 0 ? void 0 : _a.publicKey);
113
+ }
114
+ async unlock() {
115
+ if (this.isUnlocked()) {
116
+ return Promise.resolve('already unlocked');
117
+ }
118
+ return new Promise((resolve, reject) => {
119
+ this.bridge
120
+ .getPublicKey({
121
+ path: this.hdPath,
122
+ coin: 'ETH',
123
+ })
124
+ .then((response) => {
125
+ var _a;
126
+ if (response.success) {
127
+ this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');
128
+ this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');
129
+ resolve('just unlocked');
130
+ }
131
+ else {
132
+ reject(new Error(((_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) || 'Unknown error'));
133
+ }
134
+ })
135
+ .catch((e) => {
136
+ reject(new Error((e === null || e === void 0 ? void 0 : e.toString()) || 'Unknown error'));
137
+ });
138
+ });
139
+ }
140
+ setAccountToUnlock(index) {
141
+ this.unlockedAccount = parseInt(String(index), 10);
142
+ }
143
+ async addAccounts(n = 1) {
144
+ return new Promise((resolve, reject) => {
145
+ this.unlock()
146
+ .then((_) => {
147
+ const from = this.unlockedAccount;
148
+ const to = from + n;
149
+ const newAccounts = [];
150
+ for (let i = from; i < to; i++) {
151
+ const address = __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_addressFromIndex).call(this, pathBase, i);
152
+ if (!this.accounts.includes(address)) {
153
+ this.accounts = [...this.accounts, address];
154
+ newAccounts.push(address);
155
+ }
156
+ this.page = 0;
157
+ }
158
+ resolve(newAccounts);
159
+ })
160
+ .catch((e) => {
161
+ reject(e);
162
+ });
163
+ });
164
+ }
165
+ async getFirstPage() {
166
+ this.page = 0;
167
+ return __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_getPage).call(this, 1);
168
+ }
169
+ async getNextPage() {
170
+ return __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_getPage).call(this, 1);
171
+ }
172
+ async getPreviousPage() {
173
+ return __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_getPage).call(this, -1);
174
+ }
175
+ async getAccounts() {
176
+ return Promise.resolve(this.accounts.slice());
177
+ }
178
+ removeAccount(address) {
179
+ if (!this.accounts.map((a) => a.toLowerCase()).includes(address.toLowerCase())) {
180
+ throw new Error(`Address ${address} not found in this keyring`);
181
+ }
182
+ this.accounts = this.accounts.filter((a) => a.toLowerCase() !== address.toLowerCase());
183
+ }
184
+ /**
185
+ * Signs a transaction using Trezor.
186
+ *
187
+ * Accepts either an ethereumjs-tx or @ethereumjs/tx transaction, and returns
188
+ * the same type.
189
+ *
190
+ * @param address - Hex string address.
191
+ * @param tx - Instance of either new-style or old-style ethereumjs transaction.
192
+ * @returns The signed transaction, an instance of either new-style or old-style
193
+ * ethereumjs transaction.
194
+ */
195
+ async signTransaction(address, tx) {
196
+ if (isOldStyleEthereumjsTx(tx)) {
197
+ // In this version of ethereumjs-tx we must add the chainId in hex format
198
+ // to the initial v value. The chainId must be included in the serialized
199
+ // transaction which is only communicated to ethereumjs-tx in this
200
+ // value. In newer versions the chainId is communicated via the 'Common'
201
+ // object.
202
+ return __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_signTransaction).call(this, address,
203
+ // @types/ethereumjs-tx and old ethereumjs-tx versions document
204
+ // this function return value as Buffer, but the actual
205
+ // Transaction._chainId will always be a number.
206
+ // See https://github.com/ethereumjs/ethereumjs-tx/blob/v1.3.7/index.js#L126
207
+ tx.getChainId(), tx, (payload) => {
208
+ tx.v = Buffer.from(payload.v, 'hex');
209
+ tx.r = Buffer.from(payload.r, 'hex');
210
+ tx.s = Buffer.from(payload.s, 'hex');
211
+ return tx;
212
+ });
213
+ }
214
+ return __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_signTransaction).call(this, address, Number(tx.common.chainId()), tx, (payload) => {
215
+ // Because tx will be immutable, first get a plain javascript object that
216
+ // represents the transaction. Using txData here as it aligns with the
217
+ // nomenclature of ethereumjs/tx.
218
+ const txData = tx.toJSON();
219
+ // The fromTxData utility expects a type to support transactions with a type other than 0
220
+ txData.type = tx.type;
221
+ // The fromTxData utility expects v,r and s to be hex prefixed
222
+ txData.v = ethUtil.addHexPrefix(payload.v);
223
+ txData.r = ethUtil.addHexPrefix(payload.r);
224
+ txData.s = ethUtil.addHexPrefix(payload.s);
225
+ // Adopt the 'common' option from the original transaction and set the
226
+ // returned object to be frozen if the original is frozen.
227
+ return TransactionFactory.fromTxData(txData, {
228
+ common: tx.common,
229
+ freeze: Object.isFrozen(tx),
230
+ });
231
+ });
232
+ }
233
+ async signMessage(withAccount, data) {
234
+ return this.signPersonalMessage(withAccount, data);
235
+ }
236
+ // For personal_sign, we need to prefix the message:
237
+ async signPersonalMessage(withAccount, message) {
238
+ return new Promise((resolve, reject) => {
239
+ this.unlock()
240
+ .then((status) => {
241
+ setTimeout(() => {
242
+ this.bridge
243
+ .ethereumSignMessage({
244
+ path: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_pathFromAddress).call(this, withAccount),
245
+ message: ethUtil.stripHexPrefix(message),
246
+ hex: true,
247
+ })
248
+ .then((response) => {
249
+ var _a;
250
+ if (response.success) {
251
+ if (response.payload.address !==
252
+ ethUtil.toChecksumAddress(withAccount)) {
253
+ reject(new Error('signature doesnt match the right address'));
254
+ }
255
+ const signature = `0x${response.payload.signature}`;
256
+ resolve(signature);
257
+ }
258
+ else {
259
+ reject(new Error(((_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) || 'Unknown error'));
260
+ }
261
+ })
262
+ .catch((e) => {
263
+ reject(new Error((e === null || e === void 0 ? void 0 : e.toString()) || 'Unknown error'));
264
+ });
265
+ // This is necessary to avoid popup collision
266
+ // between the unlock & sign trezor popups
267
+ }, status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);
268
+ })
269
+ .catch((e) => {
270
+ reject(new Error((e === null || e === void 0 ? void 0 : e.toString()) || 'Unknown error'));
271
+ });
272
+ });
273
+ }
274
+ // EIP-712 Sign Typed Data
275
+ async signTypedData(address, data, { version }) {
276
+ var _a, _b;
277
+ const dataWithHashes = transformTypedData(data, version === SignTypedDataVersion.V4);
278
+ // set default values for signTypedData
279
+ // Trezor is stricter than @metamask/eth-sig-util in what it accepts
280
+ const { types, message = {}, domain = {}, primaryType,
281
+ // snake_case since Trezor uses Protobuf naming conventions here
282
+ domain_separator_hash, // eslint-disable-line camelcase
283
+ message_hash, // eslint-disable-line camelcase
284
+ } = dataWithHashes;
285
+ // This is necessary to avoid popup collision
286
+ // between the unlock & sign trezor popups
287
+ const status = await this.unlock();
288
+ await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);
289
+ const response = await this.bridge.ethereumSignTypedData({
290
+ path: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_pathFromAddress).call(this, address),
291
+ data: {
292
+ types: Object.assign(Object.assign({}, types), { EIP712Domain: (_a = types.EIP712Domain) !== null && _a !== void 0 ? _a : [] }),
293
+ message,
294
+ domain,
295
+ primaryType,
296
+ },
297
+ metamask_v4_compat: true, // eslint-disable-line camelcase
298
+ // Trezor 1 only supports blindly signing hashes
299
+ domain_separator_hash, // eslint-disable-line camelcase
300
+ message_hash: message_hash !== null && message_hash !== void 0 ? message_hash : '', // eslint-disable-line camelcase
301
+ });
302
+ if (response.success) {
303
+ if (ethUtil.toChecksumAddress(address) !== response.payload.address) {
304
+ throw new Error('signature doesnt match the right address');
305
+ }
306
+ return response.payload.signature;
307
+ }
308
+ throw new Error(((_b = response.payload) === null || _b === void 0 ? void 0 : _b.error) || 'Unknown error');
309
+ }
310
+ async exportAccount() {
311
+ return Promise.reject(new Error('Not supported on this device'));
312
+ }
313
+ forgetDevice() {
314
+ this.accounts = [];
315
+ this.hdk = new HDKey();
316
+ this.page = 0;
317
+ this.unlockedAccount = 0;
318
+ this.paths = {};
319
+ }
320
+ /**
321
+ * Set the HD path to be used by the keyring. Only known supported HD paths are allowed.
322
+ *
323
+ * If the given HD path is already the current HD path, nothing happens. Otherwise the new HD
324
+ * path is set, and the wallet state is completely reset.
325
+ *
326
+ * @throws {Error] Throws if the HD path is not supported.
327
+ *
328
+ * @param hdPath - The HD path to set.
329
+ */
330
+ setHdPath(hdPath) {
331
+ if (!ALLOWED_HD_PATHS[hdPath]) {
332
+ throw new Error(`The setHdPath method does not support setting HD Path to ${hdPath}`);
333
+ }
334
+ // Reset HDKey if the path changes
335
+ if (this.hdPath !== hdPath) {
336
+ this.hdk = new HDKey();
337
+ this.accounts = [];
338
+ this.page = 0;
339
+ this.perPage = 5;
340
+ this.unlockedAccount = 0;
341
+ this.paths = {};
342
+ }
343
+ this.hdPath = hdPath;
344
+ }
345
+ }
346
+ _TrezorKeyring_instances = new WeakSet(), _TrezorKeyring_getPage = async function _TrezorKeyring_getPage(increment) {
347
+ this.page += increment;
348
+ if (this.page <= 0) {
349
+ this.page = 1;
350
+ }
351
+ return new Promise((resolve, reject) => {
352
+ this.unlock()
353
+ .then((_) => {
354
+ const from = (this.page - 1) * this.perPage;
355
+ const to = from + this.perPage;
356
+ const accounts = [];
357
+ for (let i = from; i < to; i++) {
358
+ const address = __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_addressFromIndex).call(this, pathBase, i);
359
+ accounts.push({
360
+ address,
361
+ balance: null,
362
+ index: i,
363
+ });
364
+ this.paths[ethUtil.toChecksumAddress(address)] = i;
365
+ }
366
+ resolve(accounts);
367
+ })
368
+ .catch((e) => {
369
+ reject(e);
370
+ });
371
+ });
372
+ }, _TrezorKeyring_signTransaction =
373
+ /**
374
+ *
375
+ * @param address - Hex string address.
376
+ * @param chainId - Chain ID
377
+ * @param tx - Instance of either new-style or old-style ethereumjs transaction.
378
+ * @param handleSigning - Converts signed transaction
379
+ * to the same new-style or old-style ethereumjs-tx.
380
+ * @returns The signed transaction, an instance of either new-style or old-style
381
+ * ethereumjs transaction.
382
+ */
383
+ async function _TrezorKeyring_signTransaction(address, chainId, tx, handleSigning) {
384
+ var _a, _b;
385
+ let transaction;
386
+ if (isOldStyleEthereumjsTx(tx)) {
387
+ // legacy transaction from ethereumjs-tx package has no .toJSON() function,
388
+ // so we need to convert to hex-strings manually manually
389
+ transaction = {
390
+ to: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, tx.to),
391
+ value: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, tx.value),
392
+ data: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, tx.data),
393
+ chainId,
394
+ nonce: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, tx.nonce),
395
+ gasLimit: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, tx.gasLimit),
396
+ gasPrice: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, tx.gasPrice),
397
+ };
398
+ }
399
+ else {
400
+ // new-style transaction from @ethereumjs/tx package
401
+ // we can just copy tx.toJSON() for everything except chainId, which must be a number
402
+ transaction = Object.assign(Object.assign({}, tx.toJSON()), { chainId, to: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_normalize).call(this, ethUtil.toBuffer(tx.to)) });
403
+ }
404
+ try {
405
+ const status = await this.unlock();
406
+ await wait(status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0);
407
+ const response = await this.bridge.ethereumSignTransaction({
408
+ path: __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_pathFromAddress).call(this, address),
409
+ transaction,
410
+ });
411
+ if (response.success) {
412
+ const newOrMutatedTx = handleSigning(response.payload);
413
+ const addressSignedWith = ethUtil.toChecksumAddress(ethUtil.addHexPrefix(newOrMutatedTx.getSenderAddress().toString('hex')));
414
+ const correctAddress = ethUtil.toChecksumAddress(address);
415
+ if (addressSignedWith !== correctAddress) {
416
+ throw new Error("signature doesn't match the right address");
417
+ }
418
+ return newOrMutatedTx;
419
+ }
420
+ throw new Error(((_a = response.payload) === null || _a === void 0 ? void 0 : _a.error) || 'Unknown error');
421
+ }
422
+ catch (e) {
423
+ throw new Error((_b = e === null || e === void 0 ? void 0 : e.toString()) !== null && _b !== void 0 ? _b : 'Unknown error');
424
+ }
425
+ }, _TrezorKeyring_normalize = function _TrezorKeyring_normalize(buf) {
426
+ return ethUtil.bufferToHex(buf).toString();
427
+ }, _TrezorKeyring_addressFromIndex = function _TrezorKeyring_addressFromIndex(basePath, i) {
428
+ const dkey = this.hdk.derive(`${basePath}/${i}`);
429
+ const address = ethUtil
430
+ .publicToAddress(dkey.publicKey, true)
431
+ .toString('hex');
432
+ return ethUtil.toChecksumAddress(`0x${address}`);
433
+ }, _TrezorKeyring_pathFromAddress = function _TrezorKeyring_pathFromAddress(address) {
434
+ const checksummedAddress = ethUtil.toChecksumAddress(address);
435
+ let index = this.paths[checksummedAddress];
436
+ if (typeof index === 'undefined') {
437
+ for (let i = 0; i < MAX_INDEX; i++) {
438
+ if (checksummedAddress === __classPrivateFieldGet(this, _TrezorKeyring_instances, "m", _TrezorKeyring_addressFromIndex).call(this, pathBase, i)) {
439
+ index = i;
440
+ break;
441
+ }
442
+ }
443
+ }
444
+ if (typeof index === 'undefined') {
445
+ throw new Error('Unknown address');
446
+ }
447
+ return `${this.hdPath}/${index}`;
448
+ };
449
+ TrezorKeyring.type = keyringType;
450
+ //# sourceMappingURL=trezor-keyring.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"trezor-keyring.mjs","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,kBAAkB,EAAE,uBAAuB;AAEpD,OAAO,KAAK,OAAO,yBAAyB;;;AAM5C,OAAO,EAAE,kBAAkB,EAAE,wCAAwC;AAOrE,OAAO,EAAE,YAAY,EAAE,eAAe;AACtC,OAAO,MAAK,cAAc;;AAE1B,OAAO,EAAE,YAAY,EAAE,4BAAwB;AAE/C,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAC5C,MAAM,aAAa,GAAG,cAAc,CAAC;AAErC,MAAM,gBAAgB,GAAG;IACvB,CAAC,YAAY,CAAC,EAAE,IAAI;IACpB,CAAC,aAAa,CAAC,EAAE,IAAI;IACrB,CAAC,mBAAmB,CAAC,EAAE,IAAI;CACnB,CAAC;AAEX,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB,MAAM,oBAAoB,GAAG,IAAI,CAAC;AAClC,MAAM,CAAC,MAAM,uBAAuB,GAAG;IACrC,KAAK,EAAE,qBAAqB;IAC5B,MAAM,EAAE,qBAAqB;CAC9B,CAAC;AA0BF,KAAK,UAAU,IAAI,CAAC,EAAU;IAC5B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;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I,GAAW,WAAW,AAAtB,CAAuB","sourcesContent":["import { TransactionFactory } from '@ethereumjs/tx';\nimport type { TypedTransaction, TxData } from '@ethereumjs/tx';\nimport * as ethUtil from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\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 { EventEmitter } from 'events';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\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 email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport interface TrezorControllerOptions {\n hdPath?: string;\n accounts?: string[];\n page?: number;\n perPage?: number;\n}\n\nexport interface TrezorControllerState {\n hdPath: string;\n accounts: readonly string[];\n page: number;\n paths: Record<string, 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\nexport class TrezorKeyring extends EventEmitter {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly string[] = [];\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 super();\n\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,\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 return new Promise((resolve, reject) => {\n this.bridge\n .getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n })\n .then((response) => {\n if (response.success) {\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n resolve('just unlocked');\n } else {\n reject(new Error(response.payload?.error || 'Unknown error'));\n }\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n });\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(n = 1): Promise<readonly string[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + n;\n const newAccounts = [];\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[ethUtil.toChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<string[]> {\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: string,\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: TxData = 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 = ethUtil.addHexPrefix(payload.v);\n txData.r = ethUtil.addHexPrefix(payload.r);\n txData.s = ethUtil.addHexPrefix(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: string,\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(ethUtil.toBuffer(tx.to)),\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 = ethUtil.toChecksumAddress(\n ethUtil.addHexPrefix(\n newOrMutatedTx.getSenderAddress().toString('hex'),\n ),\n );\n const correctAddress = ethUtil.toChecksumAddress(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 (e) {\n throw new Error(e?.toString() ?? 'Unknown error');\n }\n }\n\n async signMessage(withAccount: string, 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: string,\n message: string,\n ): Promise<string> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((status) => {\n setTimeout(\n () => {\n this.bridge\n .ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: ethUtil.stripHexPrefix(message),\n hex: true,\n })\n .then((response) => {\n if (response.success) {\n if (\n response.payload.address !==\n ethUtil.toChecksumAddress(withAccount)\n ) {\n reject(\n new Error('signature doesnt match the right address'),\n );\n }\n const signature = `0x${response.payload.signature}`;\n resolve(signature);\n } else {\n reject(\n new Error(response.payload?.error || 'Unknown error'),\n );\n }\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n },\n status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0,\n );\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n });\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<T extends MessageTypes>(\n address: string,\n data: TypedMessage<T>,\n { version }: { version: SignTypedDataVersion },\n ): Promise<string> {\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\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, // eslint-disable-line camelcase\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 if (ethUtil.toChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n }\n\n throw new Error(response.payload?.error || 'Unknown error');\n }\n\n async exportAccount(): Promise<never> {\n return Promise.reject(new Error('Not supported on this device'));\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 ethUtil.bufferToHex(buf).toString();\n }\n\n #addressFromIndex(basePath: string, i: number): string {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = ethUtil\n .publicToAddress(dkey.publicKey, true)\n .toString('hex');\n return ethUtil.toChecksumAddress(`0x${address}`);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = ethUtil.toChecksumAddress(address);\n let index = this.paths[checksummedAddress];\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 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": "4.0.0-d5a036e",
3
+ "version": "6.0.0-22cd5fe",
4
4
  "description": "A MetaMask compatible keyring, for trezor hardware wallets",
5
5
  "keywords": [
6
6
  "ethereum",
@@ -18,28 +18,38 @@
18
18
  },
19
19
  "license": "ISC",
20
20
  "author": "Bruno Barbieri",
21
- "main": "dist/index.js",
22
- "types": "dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "import": {
24
+ "types": "./dist/index.d.mts",
25
+ "default": "./dist/index.mjs"
26
+ },
27
+ "require": {
28
+ "types": "./dist/index.d.cts",
29
+ "default": "./dist/index.cjs"
30
+ }
31
+ }
32
+ },
33
+ "main": "./dist/index.cjs",
34
+ "types": "./dist/index.d.cts",
23
35
  "files": [
24
36
  "dist/"
25
37
  ],
26
38
  "scripts": {
27
- "build": "tsc --build tsconfig.build.json",
28
- "build:clean": "rimraf dist && yarn build",
39
+ "build": "ts-bridge --project tsconfig.build.json --no-references",
40
+ "build:clean": "yarn build --clean",
29
41
  "build:docs": "typedoc",
30
- "build:force": "tsc --build tsconfig.build.json --force",
31
42
  "changelog:update": "../../scripts/update-changelog.sh @metamask/eth-trezor-keyring",
32
43
  "changelog:validate": "../../scripts/validate-changelog.sh @metamask/eth-trezor-keyring",
33
44
  "publish:preview": "yarn npm publish --tag preview",
34
45
  "test": "jest && jest-it-up",
35
46
  "test:clean": "jest --clearCache",
36
- "test:verbose": "jest --verbose",
37
47
  "test:watch": "jest --watch"
38
48
  },
39
49
  "dependencies": {
40
50
  "@ethereumjs/tx": "^4.2.0",
41
51
  "@ethereumjs/util": "^8.1.0",
42
- "@metamask/eth-sig-util": "^7.0.3",
52
+ "@metamask/eth-sig-util": "^8.0.0",
43
53
  "@trezor/connect-plugin-ethereum": "^9.0.3",
44
54
  "@trezor/connect-web": "^9.1.11",
45
55
  "hdkey": "^2.1.0",
@@ -50,6 +60,7 @@
50
60
  "@lavamoat/allow-scripts": "^3.2.1",
51
61
  "@lavamoat/preinstall-always-fail": "^2.1.0",
52
62
  "@metamask/auto-changelog": "^3.4.4",
63
+ "@ts-bridge/cli": "^0.6.0",
53
64
  "@types/ethereumjs-tx": "^1.0.1",
54
65
  "@types/hdkey": "^2.0.1",
55
66
  "@types/jest": "^29.5.12",
@@ -62,12 +73,11 @@
62
73
  "jest": "^29.5.0",
63
74
  "jest-environment-jsdom": "^29.7.0",
64
75
  "jest-it-up": "^3.1.0",
65
- "rimraf": "^5.0.10",
66
76
  "sinon": "^19.0.2",
67
77
  "ts-jest": "^29.0.5",
68
78
  "ts-node": "^10.9.2",
69
79
  "typedoc": "^0.25.13",
70
- "typescript": "~5.4.5"
80
+ "typescript": "~5.6.3"
71
81
  },
72
82
  "engines": {
73
83
  "node": "^18.18 || >=20"
package/dist/index.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export * from './trezor-keyring';
2
- export type * from './trezor-bridge';
3
- export * from './trezor-connect-bridge';
package/dist/index.js.map DELETED
@@ -1 +0,0 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,mDAAiC;AAEjC,0DAAwC","sourcesContent":["export * from './trezor-keyring';\nexport type * from './trezor-bridge';\nexport * from './trezor-connect-bridge';\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"trezor-bridge.js","sourceRoot":"","sources":["../src/trezor-bridge.ts"],"names":[],"mappings":"","sourcesContent":["import type {\n ConnectSettings,\n EthereumSignedTx,\n Manifest,\n PROTO,\n Response,\n Params,\n EthereumSignMessage,\n EthereumSignTransaction,\n EthereumSignTypedDataTypes,\n EthereumSignTypedHash,\n} from '@trezor/connect-web';\n\nexport interface TrezorBridge {\n model?: string;\n\n init(\n settings: {\n manifest: Manifest;\n } & Partial<ConnectSettings>,\n ): Promise<void>;\n\n dispose(): Promise<void>;\n\n // TrezorConnect.getPublicKey has two overloads\n // It is not possible to extract them from the library using utility types\n getPublicKey(params: {\n path: string;\n coin: string;\n }): Response<{ publicKey: string; chainCode: string }>;\n\n ethereumSignTransaction(\n params: Params<EthereumSignTransaction>,\n ): Response<EthereumSignedTx>;\n\n ethereumSignMessage(\n params: Params<EthereumSignMessage>,\n ): Response<PROTO.MessageSignature>;\n\n ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(\n params: Params<EthereumSignTypedHash<T>>,\n ): Response<PROTO.EthereumTypedDataSignature>;\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"trezor-connect-bridge.js","sourceRoot":"","sources":["../src/trezor-connect-bridge.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AACA,mEAA0E;AAgB1E,MAAa,mBAAmB;IAAhC;QAGE,2BAAsB,GAAG,KAAK,CAAC;IAsDjC,CAAC;IApDC,KAAK,CAAC,IAAI,CACR,QAE4B;QAE5B,qBAAa,CAAC,EAAE,CAAC,0BAAY,EAAE,CAAC,KAAK,EAAE,EAAE;;YACvC,IAAI,KAAK,CAAC,IAAI,KAAK,oBAAM,CAAC,OAAO,EAAE,CAAC;gBAClC,OAAO;YACT,CAAC;YACD,IAAI,CAAC,KAAK,GAAG,MAAA,KAAK,CAAC,OAAO,CAAC,QAAQ,0CAAE,KAAK,CAAC;QAC7C,CAAC,CAAC,CAAC;QAEH,IAAI,IAAI,CAAC,sBAAsB,EAAE,CAAC;YAChC,OAAO;QACT,CAAC;QAED,MAAM,qBAAa,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACnC,IAAI,CAAC,sBAAsB,GAAG,IAAI,CAAC;IACrC,CAAC;IAED,KAAK,CAAC,OAAO;QACX,sDAAsD;QACtD,wEAAwE;QACxE,sHAAsH;QACtH,qBAAa,CAAC,OAAO,EAAE,CAAC;QACxB,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC;IAC3B,CAAC;IAED,YAAY,CAAC,MAGZ;QACC,OAAO,qBAAa,CAAC,YAAY,CAAC,MAAM,CAAC,CAAC;IAC5C,CAAC;IAED,uBAAuB,CACrB,MAAuC;QAEvC,OAAO,qBAAa,CAAC,uBAAuB,CAAC,MAAM,CAAC,CAAC;IACvD,CAAC;IAED,mBAAmB,CACjB,MAAmC;QAEnC,OAAO,qBAAa,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACnD,CAAC;IAED,qBAAqB,CACnB,MAAwC;QAExC,OAAO,qBAAa,CAAC,qBAAqB,CAAC,MAAM,CAAC,CAAC;IACrD,CAAC;CACF;AAzDD,kDAyDC","sourcesContent":["import type { HDNodeResponse } from '@trezor/connect/lib/types/api/getPublicKey';\nimport TrezorConnect, { DEVICE_EVENT, DEVICE } from '@trezor/connect-web';\nimport type {\n EthereumSignedTx,\n PROTO,\n Response,\n Manifest,\n ConnectSettings,\n EthereumSignTransaction,\n Params,\n EthereumSignMessage,\n EthereumSignTypedDataTypes,\n EthereumSignTypedHash,\n} from '@trezor/connect-web';\n\nimport type { TrezorBridge } from './trezor-bridge';\n\nexport class TrezorConnectBridge implements TrezorBridge {\n model?: string;\n\n trezorConnectInitiated = false;\n\n async init(\n settings: {\n manifest: Manifest;\n } & Partial<ConnectSettings>,\n ): Promise<void> {\n TrezorConnect.on(DEVICE_EVENT, (event) => {\n if (event.type !== DEVICE.CONNECT) {\n return;\n }\n this.model = event.payload.features?.model;\n });\n\n if (this.trezorConnectInitiated) {\n return;\n }\n\n await TrezorConnect.init(settings);\n this.trezorConnectInitiated = true;\n }\n\n async dispose(): Promise<void> {\n // This removes the Trezor Connect iframe from the DOM\n // This method is not well documented, but the code it calls can be seen\n // here: https://github.com/trezor/connect/blob/dec4a56af8a65a6059fb5f63fa3c6690d2c37e00/src/js/iframe/builder.js#L181\n TrezorConnect.dispose();\n return Promise.resolve();\n }\n\n getPublicKey(params: {\n path: string;\n coin: string;\n }): Response<HDNodeResponse> {\n return TrezorConnect.getPublicKey(params);\n }\n\n ethereumSignTransaction(\n params: Params<EthereumSignTransaction>,\n ): Response<EthereumSignedTx> {\n return TrezorConnect.ethereumSignTransaction(params);\n }\n\n ethereumSignMessage(\n params: Params<EthereumSignMessage>,\n ): Response<PROTO.MessageSignature> {\n return TrezorConnect.ethereumSignMessage(params);\n }\n\n ethereumSignTypedData<T extends EthereumSignTypedDataTypes>(\n params: Params<EthereumSignTypedHash<T>>,\n ): Response<PROTO.EthereumTypedDataSignature> {\n return TrezorConnect.ethereumSignTypedData(params);\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"file":"trezor-keyring.js","sourceRoot":"","sources":["../src/trezor-keyring.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,uCAAoD;AAEpD,0DAA4C;AAC5C,yDAIgC;AAChC,6EAAqE;AAOrE,mCAAsC;AACtC,kDAA0B;AAI1B,MAAM,YAAY,GAAG,gBAAgB,CAAC;AACtC,MAAM,mBAAmB,GAAG,eAAe,CAAC;AAC5C,MAAM,aAAa,GAAG,cAAc,CAAC;AAErC,MAAM,gBAAgB,GAAG;IACvB,CAAC,YAAY,CAAC,EAAE,IAAI;IACpB,CAAC,aAAa,CAAC,EAAE,IAAI;IACrB,CAAC,mBAAmB,CAAC,EAAE,IAAI;CACnB,CAAC;AAEX,MAAM,WAAW,GAAG,iBAAiB,CAAC;AACtC,MAAM,QAAQ,GAAG,GAAG,CAAC;AACrB,MAAM,SAAS,GAAG,IAAI,CAAC;AACvB,MAAM,oBAAoB,GAAG,IAAI,CAAC;AACrB,QAAA,uBAAuB,GAAG;IACrC,KAAK,EAAE,qBAAqB;IAC5B,MAAM,EAAE,qBAAqB;CAC9B,CAAC;AA0BF,KAAK,UAAU,IAAI,CAAC,EAAU;IAC5B,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC;AAED;;;;;;;;;;;;GAYG;AACH,SAAS,sBAAsB,CAC7B,EAA0C;IAE1C,OAAO,OAAQ,EAA0B,CA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\nimport type { TypedTransaction, TxData } from '@ethereumjs/tx';\nimport * as ethUtil from '@ethereumjs/util';\nimport {\n TypedMessage,\n SignTypedDataVersion,\n MessageTypes,\n} from '@metamask/eth-sig-util';\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 { EventEmitter } from 'events';\nimport HDKey from 'hdkey';\n\nimport { TrezorBridge } from './trezor-bridge';\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 email: 'support@metamask.io',\n appUrl: 'https://metamask.io',\n};\n\nexport type AccountPageEntry = {\n address: string;\n balance: number | null;\n index: number;\n};\n\nexport type AccountPage = AccountPageEntry[];\n\nexport interface TrezorControllerOptions {\n hdPath?: string;\n accounts?: string[];\n page?: number;\n perPage?: number;\n}\n\nexport interface TrezorControllerState {\n hdPath: string;\n accounts: readonly string[];\n page: number;\n paths: Record<string, 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\nexport class TrezorKeyring extends EventEmitter {\n static type: string = keyringType;\n\n readonly type: string = keyringType;\n\n accounts: readonly string[] = [];\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 super();\n\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,\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 return new Promise((resolve, reject) => {\n this.bridge\n .getPublicKey({\n path: this.hdPath,\n coin: 'ETH',\n })\n .then((response) => {\n if (response.success) {\n this.hdk.publicKey = Buffer.from(response.payload.publicKey, 'hex');\n this.hdk.chainCode = Buffer.from(response.payload.chainCode, 'hex');\n resolve('just unlocked');\n } else {\n reject(new Error(response.payload?.error || 'Unknown error'));\n }\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n });\n }\n\n setAccountToUnlock(index: number | string): void {\n this.unlockedAccount = parseInt(String(index), 10);\n }\n\n async addAccounts(n = 1): Promise<readonly string[]> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((_) => {\n const from = this.unlockedAccount;\n const to = from + n;\n const newAccounts = [];\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[ethUtil.toChecksumAddress(address)] = i;\n }\n resolve(accounts);\n })\n .catch((e: Error) => {\n reject(e);\n });\n });\n }\n\n async getAccounts(): Promise<string[]> {\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: string,\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: TxData = 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 = ethUtil.addHexPrefix(payload.v);\n txData.r = ethUtil.addHexPrefix(payload.r);\n txData.s = ethUtil.addHexPrefix(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: string,\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(ethUtil.toBuffer(tx.to)),\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 = ethUtil.toChecksumAddress(\n ethUtil.addHexPrefix(\n newOrMutatedTx.getSenderAddress().toString('hex'),\n ),\n );\n const correctAddress = ethUtil.toChecksumAddress(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 (e) {\n throw new Error(e?.toString() ?? 'Unknown error');\n }\n }\n\n async signMessage(withAccount: string, 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: string,\n message: string,\n ): Promise<string> {\n return new Promise((resolve, reject) => {\n this.unlock()\n .then((status) => {\n setTimeout(\n () => {\n this.bridge\n .ethereumSignMessage({\n path: this.#pathFromAddress(withAccount),\n message: ethUtil.stripHexPrefix(message),\n hex: true,\n })\n .then((response) => {\n if (response.success) {\n if (\n response.payload.address !==\n ethUtil.toChecksumAddress(withAccount)\n ) {\n reject(\n new Error('signature doesnt match the right address'),\n );\n }\n const signature = `0x${response.payload.signature}`;\n resolve(signature);\n } else {\n reject(\n new Error(response.payload?.error || 'Unknown error'),\n );\n }\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n // This is necessary to avoid popup collision\n // between the unlock & sign trezor popups\n },\n status === 'just unlocked' ? DELAY_BETWEEN_POPUPS : 0,\n );\n })\n .catch((e) => {\n reject(new Error(e?.toString() || 'Unknown error'));\n });\n });\n }\n\n // EIP-712 Sign Typed Data\n async signTypedData<T extends MessageTypes>(\n address: string,\n data: TypedMessage<T>,\n { version }: { version: SignTypedDataVersion },\n ): Promise<string> {\n const dataWithHashes = transformTypedData(\n data,\n version === SignTypedDataVersion.V4,\n );\n\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, // eslint-disable-line camelcase\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 if (ethUtil.toChecksumAddress(address) !== response.payload.address) {\n throw new Error('signature doesnt match the right address');\n }\n return response.payload.signature;\n }\n\n throw new Error(response.payload?.error || 'Unknown error');\n }\n\n async exportAccount(): Promise<never> {\n return Promise.reject(new Error('Not supported on this device'));\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 ethUtil.bufferToHex(buf).toString();\n }\n\n #addressFromIndex(basePath: string, i: number): string {\n const dkey = this.hdk.derive(`${basePath}/${i}`);\n const address = ethUtil\n .publicToAddress(dkey.publicKey, true)\n .toString('hex');\n return ethUtil.toChecksumAddress(`0x${address}`);\n }\n\n #pathFromAddress(address: string): string {\n const checksummedAddress = ethUtil.toChecksumAddress(address);\n let index = this.paths[checksummedAddress];\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 return `${this.hdPath}/${index}`;\n }\n}\n"]}