@onekeyfe/hd-core 1.2.0-alpha.35 → 1.2.0-alpha.37

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 (100) hide show
  1. package/__tests__/AllNetworkGetAddressBase.tracing.test.ts +78 -0
  2. package/__tests__/DeviceEventRegistration.test.ts +6 -0
  3. package/__tests__/deviceUploadNft.test.ts +187 -0
  4. package/__tests__/get-device-state.test.ts +104 -12
  5. package/__tests__/homescreen.test.ts +41 -1
  6. package/__tests__/logBlockEvent.test.ts +1 -1
  7. package/__tests__/open-wallet-session.test.ts +259 -18
  8. package/__tests__/pro2Nft.test.ts +108 -0
  9. package/__tests__/protocol-v2-ui-lifecycle.test.ts +56 -0
  10. package/__tests__/protocol-v2-unlock-policy.test.ts +86 -35
  11. package/__tests__/protocol-v2.test.ts +377 -402
  12. package/__tests__/public-pro2-api-boundary.test.ts +1 -0
  13. package/dist/api/BaseMethod.d.ts +3 -1
  14. package/dist/api/BaseMethod.d.ts.map +1 -1
  15. package/dist/api/FirmwareUpdateV4.d.ts.map +1 -1
  16. package/dist/api/GetPassphraseState.d.ts.map +1 -1
  17. package/dist/api/OpenWalletSession.d.ts.map +1 -1
  18. package/dist/api/allnetwork/AllNetworkGetAddressBase.d.ts.map +1 -1
  19. package/dist/api/helpers/protocolV2FileWrite.d.ts +2 -0
  20. package/dist/api/helpers/protocolV2FileWrite.d.ts.map +1 -1
  21. package/dist/api/index.d.ts +1 -0
  22. package/dist/api/index.d.ts.map +1 -1
  23. package/dist/api/protocol-v2/DeviceUploadNft.d.ts +30 -0
  24. package/dist/api/protocol-v2/DeviceUploadNft.d.ts.map +1 -0
  25. package/dist/api/protocol-v2/ProtocolInfoRequest.d.ts.map +1 -1
  26. package/dist/core/deviceEventRegistration.d.ts +2 -0
  27. package/dist/core/deviceEventRegistration.d.ts.map +1 -1
  28. package/dist/core/index.d.ts.map +1 -1
  29. package/dist/device/Device.d.ts +22 -4
  30. package/dist/device/Device.d.ts.map +1 -1
  31. package/dist/events/device.d.ts +4 -0
  32. package/dist/events/device.d.ts.map +1 -1
  33. package/dist/events/logBlockEvent.d.ts.map +1 -1
  34. package/dist/events/ui-request.d.ts +27 -2
  35. package/dist/events/ui-request.d.ts.map +1 -1
  36. package/dist/index.d.ts +88 -7
  37. package/dist/index.js +937 -604
  38. package/dist/inject.d.ts.map +1 -1
  39. package/dist/protocols/protocol-v2/features.d.ts.map +1 -1
  40. package/dist/protocols/protocol-v2/uiInteraction.d.ts +3 -3
  41. package/dist/protocols/protocol-v2/uiInteraction.d.ts.map +1 -1
  42. package/dist/protocols/protocol-v2/unlockPolicy.d.ts +1 -3
  43. package/dist/protocols/protocol-v2/unlockPolicy.d.ts.map +1 -1
  44. package/dist/protocols/protocol-v2/unlockPolicyRunner.d.ts +22 -0
  45. package/dist/protocols/protocol-v2/unlockPolicyRunner.d.ts.map +1 -0
  46. package/dist/protocols/protocol-v2/walletSession.d.ts +4 -1
  47. package/dist/protocols/protocol-v2/walletSession.d.ts.map +1 -1
  48. package/dist/types/api/index.d.ts +2 -1
  49. package/dist/types/api/index.d.ts.map +1 -1
  50. package/dist/types/api/protocolV2.d.ts +3 -0
  51. package/dist/types/api/protocolV2.d.ts.map +1 -1
  52. package/dist/utils/deviceFeaturesUtils.d.ts +2 -0
  53. package/dist/utils/deviceFeaturesUtils.d.ts.map +1 -1
  54. package/dist/utils/homescreen.d.ts +4 -0
  55. package/dist/utils/homescreen.d.ts.map +1 -1
  56. package/dist/utils/index.d.ts +1 -1
  57. package/dist/utils/index.d.ts.map +1 -1
  58. package/dist/utils/patch.d.ts +1 -1
  59. package/dist/utils/patch.d.ts.map +1 -1
  60. package/dist/utils/pro2Nft.d.ts +29 -0
  61. package/dist/utils/pro2Nft.d.ts.map +1 -0
  62. package/dist/utils/pro2Wallpaper.d.ts +10 -0
  63. package/dist/utils/pro2Wallpaper.d.ts.map +1 -1
  64. package/package.json +4 -4
  65. package/src/api/BaseMethod.ts +8 -10
  66. package/src/api/FirmwareUpdateV4.ts +13 -6
  67. package/src/api/GetPassphraseState.ts +7 -1
  68. package/src/api/OpenWalletSession.ts +54 -17
  69. package/src/api/allnetwork/AllNetworkGetAddressBase.ts +32 -11
  70. package/src/api/device/DeviceUnlock.ts +1 -1
  71. package/src/api/helpers/protocolV2FileWrite.ts +11 -4
  72. package/src/api/index.ts +1 -0
  73. package/src/api/protocol-v2/DeviceUploadNft.ts +166 -0
  74. package/src/api/protocol-v2/ProtocolInfoRequest.ts +3 -1
  75. package/src/core/deviceEventRegistration.ts +4 -0
  76. package/src/core/index.ts +111 -74
  77. package/src/data/messages/messages-protocol-v2.json +10 -0
  78. package/src/device/Device.ts +221 -24
  79. package/src/events/device.ts +4 -0
  80. package/src/events/logBlockEvent.ts +1 -0
  81. package/src/events/ui-request.ts +32 -2
  82. package/src/inject.ts +1 -0
  83. package/src/protocols/protocol-v2/features.ts +9 -2
  84. package/src/protocols/protocol-v2/uiInteraction.ts +31 -5
  85. package/src/protocols/protocol-v2/unlockPolicy.ts +1 -105
  86. package/src/protocols/protocol-v2/unlockPolicyRunner.ts +117 -0
  87. package/src/protocols/protocol-v2/walletSession.ts +93 -18
  88. package/src/types/api/index.ts +2 -0
  89. package/src/types/api/protocolV2.ts +13 -0
  90. package/src/utils/deviceFeaturesUtils.ts +4 -0
  91. package/src/utils/homescreen.ts +32 -6
  92. package/src/utils/index.ts +6 -1
  93. package/src/utils/pro2Nft.ts +91 -0
  94. package/src/utils/pro2Wallpaper.ts +35 -8
  95. package/dist/protocols/protocol-v2/lockedError.d.ts +0 -2
  96. package/dist/protocols/protocol-v2/lockedError.d.ts.map +0 -1
  97. package/dist/protocols/protocol-v2/unlockRetry.d.ts +0 -10
  98. package/dist/protocols/protocol-v2/unlockRetry.d.ts.map +0 -1
  99. package/src/protocols/protocol-v2/lockedError.ts +0 -10
  100. package/src/protocols/protocol-v2/unlockRetry.ts +0 -109
@@ -106,6 +106,7 @@ export const getPassphraseStateWithRefreshDeviceInfo = async (
106
106
  expectPassphraseState?: string;
107
107
  onlyMainPin?: boolean;
108
108
  initSession?: boolean;
109
+ deriveCardano?: boolean;
109
110
  }
110
111
  ) => {
111
112
  if (device.isProtocolV2()) {
@@ -121,6 +122,7 @@ export const getPassphraseStateWithRefreshDeviceInfo = async (
121
122
  initSession: options?.initSession,
122
123
  expectedPassphraseState: options?.expectPassphraseState,
123
124
  onlyMainPin: options?.onlyMainPin,
125
+ deriveCardano: options?.deriveCardano,
124
126
  });
125
127
  }
126
128
 
@@ -185,6 +187,7 @@ export const getPassphraseState = async (
185
187
  expectPassphraseState?: string;
186
188
  onlyMainPin?: boolean;
187
189
  initSession?: boolean;
190
+ deriveCardano?: boolean;
188
191
  }
189
192
  ): Promise<{
190
193
  passphraseState: string | undefined;
@@ -205,6 +208,7 @@ export const getPassphraseState = async (
205
208
  initSession: options?.initSession,
206
209
  expectedPassphraseState: options?.expectPassphraseState,
207
210
  onlyMainPin: options?.onlyMainPin,
211
+ deriveCardano: options?.deriveCardano,
208
212
  });
209
213
  }
210
214
 
@@ -4,6 +4,12 @@ import { EDeviceType } from '@onekeyfe/hd-shared';
4
4
  import { getDeviceType } from './deviceInfoUtils';
5
5
  import { getDeviceFirmwareVersion } from './deviceVersionUtils';
6
6
  import { PRO2_WALLPAPER_HEIGHT, PRO2_WALLPAPER_WIDTH } from './pro2Wallpaper';
7
+ import {
8
+ PRO2_NFT_IMAGE_HEIGHT,
9
+ PRO2_NFT_IMAGE_WIDTH,
10
+ PRO2_NFT_THUMBNAIL_HEIGHT,
11
+ PRO2_NFT_THUMBNAIL_WIDTH,
12
+ } from './pro2Nft';
7
13
 
8
14
  import type { Features, IDeviceType } from '../types';
9
15
 
@@ -302,6 +308,31 @@ type SizeConfig = {
302
308
  radius?: number;
303
309
  };
304
310
 
311
+ export const getNftSize = ({
312
+ deviceType,
313
+ thumbnail,
314
+ }: {
315
+ deviceType: IDeviceType;
316
+ thumbnail?: boolean;
317
+ }): SizeConfig | undefined => {
318
+ const sizes: Partial<Record<IDeviceType, { full: SizeConfig; thumbnail: SizeConfig }>> = {
319
+ touch: {
320
+ full: { width: 480, height: 800 },
321
+ thumbnail: { width: 238, height: 238 },
322
+ },
323
+ pro: {
324
+ full: { width: 480, height: 800 },
325
+ thumbnail: { width: 226, height: 226, radius: 40 },
326
+ },
327
+ pro2: {
328
+ full: { width: PRO2_NFT_IMAGE_WIDTH, height: PRO2_NFT_IMAGE_HEIGHT },
329
+ thumbnail: { width: PRO2_NFT_THUMBNAIL_WIDTH, height: PRO2_NFT_THUMBNAIL_HEIGHT },
330
+ },
331
+ };
332
+
333
+ return sizes[deviceType]?.[thumbnail ? 'thumbnail' : 'full'];
334
+ };
335
+
305
336
  export const getHomeScreenSize = ({
306
337
  deviceType,
307
338
  homeScreenType,
@@ -312,12 +343,7 @@ export const getHomeScreenSize = ({
312
343
  thumbnail?: boolean;
313
344
  }) => {
314
345
  if (deviceType === EDeviceType.Pro2) {
315
- return thumbnail
316
- ? undefined
317
- : {
318
- width: PRO2_WALLPAPER_WIDTH,
319
- height: PRO2_WALLPAPER_HEIGHT,
320
- };
346
+ return thumbnail ? undefined : { width: PRO2_WALLPAPER_WIDTH, height: PRO2_WALLPAPER_HEIGHT };
321
347
  }
322
348
 
323
349
  const sizes: Partial<
@@ -54,7 +54,12 @@ export { getHDPath, getScriptType, getOutputScriptType } from '../api/helpers/pa
54
54
 
55
55
  export const isBleConnect = (env: string) => env === 'react-native' || env === 'lowlevel';
56
56
 
57
- export { getHomeScreenHex, getHomeScreenDefaultList, getHomeScreenSize } from './homescreen';
57
+ export {
58
+ getHomeScreenHex,
59
+ getHomeScreenDefaultList,
60
+ getHomeScreenSize,
61
+ getNftSize,
62
+ } from './homescreen';
58
63
  export { encodePro2Wallpaper, PRO2_WALLPAPER_HEIGHT, PRO2_WALLPAPER_WIDTH } from './pro2Wallpaper';
59
64
  export type { Pro2WallpaperColorFormat } from './pro2Wallpaper';
60
65
 
@@ -0,0 +1,91 @@
1
+ import { blake2s } from '@noble/hashes/blake2s';
2
+ import { bytesToHex } from '@noble/hashes/utils';
3
+
4
+ import { invalidParameter } from '../api/helpers/filesystemValidation';
5
+ import { encodePro2Image } from './pro2Wallpaper';
6
+
7
+ export const PRO2_NFT_IMAGE_WIDTH = 540;
8
+ export const PRO2_NFT_IMAGE_HEIGHT = 540;
9
+ export const PRO2_NFT_THUMBNAIL_WIDTH = 263;
10
+ export const PRO2_NFT_THUMBNAIL_HEIGHT = 263;
11
+ export const PRO2_NFT_DIRECTORY = 'vol1:/nft';
12
+ export const PRO2_NFT_DEFAULT_CHUNK_SIZE = 512;
13
+ export const PRO2_NFT_DEFAULT_PACE_MS = 20;
14
+ export const PRO2_NFT_DEFAULT_TIMEOUT_MS = 15_000;
15
+ export const PRO2_NFT_MIN_CHUNK_SIZE = 64;
16
+ export const PRO2_NFT_MAX_CHUNK_SIZE = 2048;
17
+
18
+ export type Pro2NftImage = {
19
+ width: number;
20
+ height: number;
21
+ rgba: Uint8Array | ArrayBuffer;
22
+ };
23
+
24
+ export type Pro2NftBundle = {
25
+ basename: string;
26
+ image: Uint8Array;
27
+ thumbnail: Uint8Array;
28
+ metadata: Uint8Array;
29
+ };
30
+
31
+ function utf8Length(value: string): number {
32
+ return new TextEncoder().encode(value).byteLength;
33
+ }
34
+
35
+ function assertImage(
36
+ name: string,
37
+ image: Pro2NftImage,
38
+ expectedWidth: number,
39
+ expectedHeight: number
40
+ ) {
41
+ if (image.width !== expectedWidth || image.height !== expectedHeight) {
42
+ throw invalidParameter(
43
+ `Pro2 NFT ${name} dimensions must be ${expectedWidth}x${expectedHeight}.`
44
+ );
45
+ }
46
+ if (!(image.rgba instanceof ArrayBuffer) && !ArrayBuffer.isView(image.rgba)) {
47
+ throw invalidParameter(`Parameter [${name}.rgba] must be an ArrayBuffer or Uint8Array.`);
48
+ }
49
+ }
50
+
51
+ export function buildPro2NftBundle(options: {
52
+ image: Pro2NftImage;
53
+ thumbnail: Pro2NftImage;
54
+ title: string;
55
+ subtitle: string;
56
+ timestampMs: number;
57
+ }): Pro2NftBundle {
58
+ const { image, thumbnail, title, subtitle, timestampMs } = options;
59
+ assertImage('image', image, PRO2_NFT_IMAGE_WIDTH, PRO2_NFT_IMAGE_HEIGHT);
60
+ assertImage('thumbnail', thumbnail, PRO2_NFT_THUMBNAIL_WIDTH, PRO2_NFT_THUMBNAIL_HEIGHT);
61
+ const titleLength = typeof title === 'string' ? utf8Length(title) : 0;
62
+ const subtitleLength =
63
+ typeof subtitle === 'string' ? utf8Length(subtitle) : Number.POSITIVE_INFINITY;
64
+ if (titleLength < 1 || titleLength > 63) {
65
+ throw invalidParameter('Pro2 NFT title must contain 1 to 63 UTF-8 bytes.');
66
+ }
67
+ if (subtitleLength > 95) {
68
+ throw invalidParameter('Pro2 NFT subtitle must contain at most 95 UTF-8 bytes.');
69
+ }
70
+ if (!Number.isSafeInteger(timestampMs) || timestampMs <= 0) {
71
+ throw invalidParameter('Parameter [timestampMs] must be a positive safe integer.');
72
+ }
73
+
74
+ const encodedImage = encodePro2Image({ ...image, alphaMode: 'black-background' }).data;
75
+ const encodedThumbnail = encodePro2Image({
76
+ ...thumbnail,
77
+ alphaMode: 'black-background',
78
+ }).data;
79
+ const metadata = new TextEncoder().encode(JSON.stringify({ title, subtitle }));
80
+ if (metadata.byteLength === 0 || metadata.byteLength > 512) {
81
+ throw invalidParameter('Pro2 NFT metadata must contain 1 to 512 UTF-8 bytes.');
82
+ }
83
+
84
+ const hash8 = bytesToHex(blake2s(encodedImage)).slice(0, 8);
85
+ return {
86
+ basename: `nft-${hash8}-${timestampMs}`,
87
+ image: encodedImage,
88
+ thumbnail: encodedThumbnail,
89
+ metadata,
90
+ };
91
+ }
@@ -8,6 +8,8 @@ export const PRO2_WALLPAPER_HEIGHT = 1024;
8
8
 
9
9
  export type Pro2WallpaperColorFormat = 'RGB565' | 'RGB565A8';
10
10
 
11
+ export type Pro2ImageAlphaMode = 'preserve' | 'black-background';
12
+
11
13
  const COLOR_FORMAT_RGB565 = 0x12;
12
14
  const COLOR_FORMAT_RGB565A8 = 0x14;
13
15
 
@@ -36,10 +38,11 @@ function align(value: number, boundary: number): number {
36
38
  return Math.ceil(value / boundary) * boundary;
37
39
  }
38
40
 
39
- export function encodePro2Wallpaper(options: {
41
+ export function encodePro2Image(options: {
40
42
  width: number;
41
43
  height: number;
42
44
  rgba: Uint8Array | ArrayBuffer;
45
+ alphaMode?: Pro2ImageAlphaMode;
43
46
  }): { data: Uint8Array; colorFormat: Pro2WallpaperColorFormat } {
44
47
  const { width, height } = options;
45
48
  if (!Number.isInteger(width) || width <= 0 || width > 0xffff) {
@@ -57,11 +60,14 @@ export function encodePro2Wallpaper(options: {
57
60
  );
58
61
  }
59
62
 
63
+ const alphaMode = options.alphaMode ?? 'preserve';
60
64
  let hasTransparency = false;
61
- for (let index = 3; index < rgba.length; index += 4) {
62
- if (rgba[index] !== 0xff) {
63
- hasTransparency = true;
64
- break;
65
+ if (alphaMode === 'preserve') {
66
+ for (let index = 3; index < rgba.length; index += 4) {
67
+ if (rgba[index] !== 0xff) {
68
+ hasTransparency = true;
69
+ break;
70
+ }
65
71
  }
66
72
  }
67
73
 
@@ -85,9 +91,22 @@ export function encodePro2Wallpaper(options: {
85
91
  for (let x = 0; x < width; x += 1) {
86
92
  const sourceOffset = (y * width + x) * 4;
87
93
  const thresholdIndex = ((y & 7) << 3) + (x & 7);
88
- const red = Math.min(rgba[sourceOffset] + RED_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
89
- const green = Math.min(rgba[sourceOffset + 1] + GREEN_THRESHOLD[thresholdIndex], 0xff) & 0xfc;
90
- const blue = Math.min(rgba[sourceOffset + 2] + BLUE_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
94
+ const alpha = rgba[sourceOffset + 3];
95
+ const redChannel =
96
+ alphaMode === 'black-background'
97
+ ? Math.round((rgba[sourceOffset] * alpha) / 0xff)
98
+ : rgba[sourceOffset];
99
+ const greenChannel =
100
+ alphaMode === 'black-background'
101
+ ? Math.round((rgba[sourceOffset + 1] * alpha) / 0xff)
102
+ : rgba[sourceOffset + 1];
103
+ const blueChannel =
104
+ alphaMode === 'black-background'
105
+ ? Math.round((rgba[sourceOffset + 2] * alpha) / 0xff)
106
+ : rgba[sourceOffset + 2];
107
+ const red = Math.min(redChannel + RED_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
108
+ const green = Math.min(greenChannel + GREEN_THRESHOLD[thresholdIndex], 0xff) & 0xfc;
109
+ const blue = Math.min(blueChannel + BLUE_THRESHOLD[thresholdIndex], 0xff) & 0xf8;
91
110
  const rgb565 = ((red >> 3) << 11) | ((green >> 2) << 5) | (blue >> 3);
92
111
  const rgbOffset = 12 + y * stride + x * 2;
93
112
  data[rgbOffset] = rgb565 & 0xff;
@@ -101,3 +120,11 @@ export function encodePro2Wallpaper(options: {
101
120
 
102
121
  return { data, colorFormat };
103
122
  }
123
+
124
+ export function encodePro2Wallpaper(options: {
125
+ width: number;
126
+ height: number;
127
+ rgba: Uint8Array | ArrayBuffer;
128
+ }): { data: Uint8Array; colorFormat: Pro2WallpaperColorFormat } {
129
+ return encodePro2Image(options);
130
+ }
@@ -1,2 +0,0 @@
1
- export declare function isDeviceLockedError(error: unknown): boolean;
2
- //# sourceMappingURL=lockedError.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"lockedError.d.ts","sourceRoot":"","sources":["../../../src/protocols/protocol-v2/lockedError.ts"],"names":[],"mappings":"AAEA,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,OAAO,GAAG,OAAO,CAO3D"}
@@ -1,10 +0,0 @@
1
- import type { BaseMethod } from '../../api/BaseMethod';
2
- import type { Device } from '../../device/Device';
3
- import type { ProtocolV2UiInteractionCoordinator } from './uiInteraction';
4
- type RunnableMethod = Pick<BaseMethod, 'run' | 'unlockPolicy' | 'protocolV2UiInteraction' | 'protocolV2UiMode' | 'params' | 'payload' | 'useDevicePassphraseState'> & {
5
- name?: string;
6
- };
7
- type UiInteractionCoordinator = Pick<ProtocolV2UiInteractionCoordinator, 'enterMethodInteraction' | 'enterUnlockInteraction' | 'resumeMethodInteraction'>;
8
- export declare function runMethodWithUnlockRetry(method: RunnableMethod, device: Device, uiCoordinator?: UiInteractionCoordinator): Promise<any>;
9
- export {};
10
- //# sourceMappingURL=unlockRetry.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"unlockRetry.d.ts","sourceRoot":"","sources":["../../../src/protocols/protocol-v2/unlockRetry.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,iBAAiB,CAAC;AAI1E,KAAK,cAAc,GAAG,IAAI,CACxB,UAAU,EACR,KAAK,GACL,cAAc,GACd,yBAAyB,GACzB,kBAAkB,GAClB,QAAQ,GACR,SAAS,GACT,0BAA0B,CAC7B,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AACtB,KAAK,wBAAwB,GAAG,IAAI,CAClC,kCAAkC,EAClC,wBAAwB,GAAG,wBAAwB,GAAG,yBAAyB,CAChF,CAAC;AAkBF,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,MAAM,EACd,aAAa,CAAC,EAAE,wBAAwB,gBA+DzC"}
@@ -1,10 +0,0 @@
1
- import { HardwareErrorCode } from '@onekeyfe/hd-shared';
2
-
3
- export function isDeviceLockedError(error: unknown): boolean {
4
- return (
5
- typeof error === 'object' &&
6
- error !== null &&
7
- 'errorCode' in error &&
8
- error.errorCode === HardwareErrorCode.DeviceLocked
9
- );
10
- }
@@ -1,109 +0,0 @@
1
- import { LoggerNames, getLogger } from '../../utils';
2
- import { isDeviceLockedError } from './lockedError';
3
- import { isProtocolV2UiEnabled, resolveProtocolV2UiInteraction } from './uiInteraction';
4
- import { refreshProtocolV2DeviceStatus, restoreProtocolV2WalletSession } from './walletSession';
5
-
6
- import type { BaseMethod } from '../../api/BaseMethod';
7
- import type { Device } from '../../device/Device';
8
- import type { ProtocolV2UiInteractionCoordinator } from './uiInteraction';
9
-
10
- const Log = getLogger(LoggerNames.Core);
11
-
12
- type RunnableMethod = Pick<
13
- BaseMethod,
14
- | 'run'
15
- | 'unlockPolicy'
16
- | 'protocolV2UiInteraction'
17
- | 'protocolV2UiMode'
18
- | 'params'
19
- | 'payload'
20
- | 'useDevicePassphraseState'
21
- > & { name?: string };
22
- type UiInteractionCoordinator = Pick<
23
- ProtocolV2UiInteractionCoordinator,
24
- 'enterMethodInteraction' | 'enterUnlockInteraction' | 'resumeMethodInteraction'
25
- >;
26
-
27
- const restoreExpectedWalletSessionAfterUnlock = async (method: RunnableMethod, device: Device) => {
28
- const expectedPassphraseState = method.payload?.useEmptyPassphrase
29
- ? undefined
30
- : method.payload?.passphraseState ?? device.passphraseState;
31
- if (
32
- !method.useDevicePassphraseState ||
33
- typeof expectedPassphraseState !== 'string' ||
34
- expectedPassphraseState.length === 0
35
- ) {
36
- return;
37
- }
38
-
39
- await restoreProtocolV2WalletSession(device, expectedPassphraseState);
40
- Log.debug('Protocol V2 wallet session restored after unlock', { method: method.name });
41
- };
42
-
43
- export async function runMethodWithUnlockRetry(
44
- method: RunnableMethod,
45
- device: Device,
46
- uiCoordinator?: UiInteractionCoordinator
47
- ) {
48
- const shouldEmitUi = isProtocolV2UiEnabled(method);
49
- const isProtocolV2 = device.isProtocolV2();
50
- const requiresFreshStatus =
51
- isProtocolV2 &&
52
- method.unlockPolicy === 'unlock-before-run' &&
53
- !device.isBootloader?.() &&
54
- !device.isRomloader?.();
55
-
56
- if (requiresFreshStatus) {
57
- await refreshProtocolV2DeviceStatus(device);
58
- }
59
-
60
- const shouldUnlockBeforeRun =
61
- isProtocolV2 &&
62
- method.unlockPolicy !== 'none' &&
63
- !device.isBootloader?.() &&
64
- !device.isRomloader?.() &&
65
- device.features?.unlocked === false;
66
-
67
- if (shouldUnlockBeforeRun) {
68
- if (shouldEmitUi) {
69
- uiCoordinator?.enterUnlockInteraction(method.name);
70
- }
71
- await device.unlockDevice();
72
- Log.debug('Protocol V2 pre-unlock completed', { method: method.name });
73
- await restoreExpectedWalletSessionAfterUnlock(method, device);
74
- if (shouldEmitUi) {
75
- uiCoordinator?.enterMethodInteraction(resolveProtocolV2UiInteraction(method));
76
- }
77
- return method.run();
78
- }
79
-
80
- if (shouldEmitUi) {
81
- uiCoordinator?.enterMethodInteraction(resolveProtocolV2UiInteraction(method));
82
- }
83
- try {
84
- return await method.run();
85
- } catch (error) {
86
- if (!isProtocolV2 || method.unlockPolicy !== 'retry-on-locked' || !isDeviceLockedError(error)) {
87
- throw error;
88
- }
89
-
90
- Log.debug('Protocol V2 unlock retry triggered', { method: method.name });
91
- if (shouldEmitUi) {
92
- uiCoordinator?.enterUnlockInteraction(method.name);
93
- }
94
- await device.unlockDevice();
95
- Log.debug('Protocol V2 unlock completed', { method: method.name });
96
- await restoreExpectedWalletSessionAfterUnlock(method, device);
97
- if (shouldEmitUi) {
98
- uiCoordinator?.resumeMethodInteraction();
99
- }
100
- try {
101
- const response = await method.run();
102
- Log.debug('Protocol V2 method retry completed', { method: method.name, success: true });
103
- return response;
104
- } catch (retryError) {
105
- Log.debug('Protocol V2 method retry completed', { method: method.name, success: false });
106
- throw retryError;
107
- }
108
- }
109
- }