@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.12 → 1.2.8-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -6,30 +6,43 @@ import {
6
6
  DeviceJobQueue,
7
7
  EConnectorInteraction,
8
8
  HardwareErrorCode as HardwareErrorCode3,
9
+ OperationRegistry,
10
+ SDK,
9
11
  TypedEventEmitter,
10
12
  UI_REQUEST,
11
13
  UI_REQUEST_PREEMPTED_TAG,
12
14
  UiRequestRegistry,
15
+ canReplayHardwareMethodAfterTransportFailure,
13
16
  createHwkError,
14
17
  deriveDeviceFingerprint,
18
+ emitDeviceBindingStatus,
15
19
  failure as failure2,
20
+ isHardwareOperationId,
21
+ isHwkRecoveryHint,
22
+ operationMayHaveCompletedParams,
23
+ pickConnectionContext,
16
24
  rehydrateConnectorError,
17
- success
25
+ requestBleDeviceSelection,
26
+ requestSaveDeviceBinding,
27
+ success as success2,
28
+ toPhysicalDeviceSearchTarget
18
29
  } from "@onekeyfe/hwk-adapter-core";
19
30
 
20
31
  // src/errors.ts
21
- import { HardwareErrorCode, enrichErrorMessage } from "@onekeyfe/hwk-adapter-core";
22
- var MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE = "Multiple Ledger USB devices are connected. Please connect only one Ledger device and try again.";
23
- function createMultipleUsbLedgerDevicesError() {
24
- return Object.assign(new Error(MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE), {
25
- code: HardwareErrorCode.DeviceOneDeviceOnly
26
- });
27
- }
28
- function ledgerFailure(code, error, appName, tag, params) {
32
+ import {
33
+ HardwareErrorCode,
34
+ defaultOriginForCode,
35
+ defaultRecoveryForCode,
36
+ enrichErrorMessage
37
+ } from "@onekeyfe/hwk-adapter-core";
38
+ function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
29
39
  const payload = { error, code };
30
40
  if (appName !== void 0) payload.appName = appName;
31
41
  if (tag !== void 0) payload._tag = tag;
32
42
  if (params !== void 0) payload.params = params;
43
+ const resolvedOrigin = origin ?? defaultOriginForCode(code);
44
+ if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
45
+ payload.recovery = recovery ?? defaultRecoveryForCode(code);
33
46
  return { success: false, payload };
34
47
  }
35
48
  var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
@@ -170,7 +183,10 @@ var ERROR_TAG = {
170
183
  UnknownDevice: "UnknownDeviceError",
171
184
  DeviceSessionRefresher: "DeviceSessionRefresherError",
172
185
  DeviceNotInitialized: "DeviceNotInitializedError",
173
- OpeningConnection: "OpeningConnectionError",
186
+ // DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
187
+ // spellings are kept so a DMK release that aligns them still classifies.
188
+ OpeningConnection: "ConnectionOpeningError",
189
+ OpeningConnectionLegacy: "OpeningConnectionError",
174
190
  DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
175
191
  DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
176
192
  Disconnect: "DisconnectError",
@@ -183,7 +199,16 @@ var ERROR_TAG = {
183
199
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
184
200
  WebSocketConnection: "WebSocketConnectionError",
185
201
  HttpFetch: "FetchError",
186
- InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError"
202
+ NetworkDA: "NetworkDAError",
203
+ InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
204
+ ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
205
+ // DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
206
+ // after splitting out device answers, i.e. the relay itself broke.
207
+ SecureChannel: "SecureChannelError",
208
+ RefusedByUserDA: "RefusedByUserDAError",
209
+ AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
210
+ OutOfMemoryDA: "OutOfMemoryDAError",
211
+ DeviceNotOnboarded: "DeviceNotOnboardedError"
187
212
  };
188
213
  function isDeviceLockedError(err) {
189
214
  if (!err || typeof err !== "object") return false;
@@ -213,7 +238,6 @@ function isBlePairingFailureError(err) {
213
238
  return false;
214
239
  }
215
240
  var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
216
- ERROR_TAG.DeviceLocked,
217
241
  ERROR_TAG.DeviceNotAdvertising,
218
242
  ERROR_TAG.BlePairingTimeout,
219
243
  ERROR_TAG.BleGattBondingFailed,
@@ -225,6 +249,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
225
249
  ERROR_TAG.DeviceSessionRefresher,
226
250
  ERROR_TAG.DeviceNotInitialized,
227
251
  ERROR_TAG.OpeningConnection,
252
+ ERROR_TAG.OpeningConnectionLegacy,
228
253
  ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
229
254
  ERROR_TAG.DeviceDisconnectedWhileSending,
230
255
  ERROR_TAG.Disconnect,
@@ -239,7 +264,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
239
264
  // Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
240
265
  ERROR_TAG.DeviceNotInDiscoveryCache
241
266
  ]);
242
- var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OpeningConnection]);
267
+ var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
268
+ ERROR_TAG.OpeningConnection,
269
+ ERROR_TAG.OpeningConnectionLegacy
270
+ ]);
243
271
  var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
244
272
  ERROR_TAG.DeviceNotRecognized,
245
273
  ERROR_TAG.DeviceSessionNotFound,
@@ -251,17 +279,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
251
279
  ERROR_TAG.WebHIDDisconnect
252
280
  ]);
253
281
  function isConnectionLevelError(err) {
254
- if (!err || typeof err !== "object") return false;
255
- const tag = err._tag;
256
- if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
257
- const e = err;
258
- if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
259
- if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
260
- return false;
282
+ return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
261
283
  }
262
284
  function isKnownConnectionTag(tag) {
263
285
  return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
264
286
  }
287
+ var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
288
+ ERROR_TAG.OpeningConnection,
289
+ ERROR_TAG.OpeningConnectionLegacy
290
+ ]);
291
+ function isConnectionOpeningTag(tag) {
292
+ return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
293
+ }
265
294
  function hasStatusCode(err, codeSet) {
266
295
  if (!err || typeof err !== "object") return false;
267
296
  const e = err;
@@ -297,28 +326,28 @@ function hasInvalidArgumentCode(err) {
297
326
  if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
298
327
  return false;
299
328
  }
300
- function isDeviceNotFoundError(err) {
329
+ function hasErrorTag(err, tags) {
301
330
  if (!err || typeof err !== "object") return false;
302
- const tag = err._tag;
303
- if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
304
331
  const e = err;
305
- if (e.originalError != null && isDeviceNotFoundError(e.originalError)) return true;
306
- if (e.error != null && e._tag && isDeviceNotFoundError(e.error)) return true;
332
+ if (typeof e._tag === "string" && tags.has(e._tag)) return true;
333
+ if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
334
+ if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
307
335
  return false;
308
336
  }
337
+ function isDeviceNotFoundError(err) {
338
+ return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
339
+ }
309
340
  function isDeviceBusyError(err) {
310
- if (!err || typeof err !== "object") return false;
311
- const tag = err._tag;
312
- if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
313
- const e = err;
314
- if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
315
- if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
316
- return false;
341
+ return hasErrorTag(err, DEVICE_BUSY_TAGS);
317
342
  }
343
+ var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
344
+ ERROR_TAG.UserRefusedOnDevice,
345
+ ERROR_TAG.RefusedByUserDA
346
+ ]);
318
347
  function isUserRejectedError(err) {
319
348
  if (!err || typeof err !== "object") return false;
320
349
  const e = err;
321
- if (e._tag === ERROR_TAG.UserRefusedOnDevice) return true;
350
+ if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
322
351
  if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
323
352
  if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
324
353
  return false;
@@ -349,15 +378,33 @@ function isAppNotInstalledError(err) {
349
378
  if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
350
379
  return false;
351
380
  }
381
+ var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
352
382
  function isOutOfMemoryError(err) {
353
- if (!err || typeof err !== "object") return false;
354
- const e = err;
355
- return e._tag === "OutOfMemoryDAError";
383
+ return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
384
+ }
385
+ var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
386
+ function isAppAlreadyInstalledError(err) {
387
+ return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
388
+ }
389
+ var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
390
+ function isDeviceNotOnboardedError(err) {
391
+ return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
392
+ }
393
+ var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
394
+ ERROR_TAG.InvalidFirmwareMetadataResponse,
395
+ ERROR_TAG.ApplicationsMetadataTask
396
+ ]);
397
+ function isFirmwareMetadataError(err) {
398
+ return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
399
+ }
400
+ var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
401
+ function isSecureChannelError(err) {
402
+ return hasErrorTag(err, SECURE_CHANNEL_TAGS);
356
403
  }
357
404
  var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
358
405
  ERROR_TAG.WebSocketConnection,
359
406
  ERROR_TAG.HttpFetch,
360
- ERROR_TAG.InvalidFirmwareMetadataResponse
407
+ ERROR_TAG.NetworkDA
361
408
  ]);
362
409
  function isNetworkError(err) {
363
410
  if (!err || typeof err !== "object") return false;
@@ -407,23 +454,34 @@ function isTransportStuck(err) {
407
454
  function isStuckAppStateError(err) {
408
455
  return isAppStuckByApdu(err) || isTransportStuck(err);
409
456
  }
457
+ var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
458
+ function nestedErrorMessage(nested) {
459
+ if (!nested || typeof nested !== "object") return void 0;
460
+ const { message } = nested;
461
+ if (typeof message !== "string") return void 0;
462
+ const trimmed = message.trim();
463
+ if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
464
+ return message;
465
+ }
410
466
  function mapLedgerError(err, opts) {
411
467
  let originalMessage = "Unknown Ledger error";
412
468
  if (err instanceof Error) {
413
469
  originalMessage = err.message;
414
470
  } else if (err && typeof err === "object") {
415
471
  const e = err;
416
- originalMessage = String(e.message ?? e._tag ?? e.type ?? JSON.stringify(err));
472
+ originalMessage = String(
473
+ e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
474
+ );
417
475
  }
418
476
  let code;
419
477
  if (isDeviceLockedError(err)) {
420
478
  code = HardwareErrorCode.DeviceLocked;
421
479
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
422
480
  code = HardwareErrorCode.DeviceNotFound;
423
- } else if (isDeviceBusyError(err)) {
424
- code = HardwareErrorCode.DeviceBusy;
425
481
  } else if (isBlePairingFailureError(err)) {
426
482
  code = HardwareErrorCode.BlePairingTimeout;
483
+ } else if (isDeviceBusyError(err)) {
484
+ code = HardwareErrorCode.DeviceBusy;
427
485
  } else if (isUserAbortedError(err)) {
428
486
  code = HardwareErrorCode.UserAborted;
429
487
  } else if (isUserRejectedError(err)) {
@@ -432,10 +490,18 @@ function mapLedgerError(err, opts) {
432
490
  code = HardwareErrorCode.WrongApp;
433
491
  } else if (isAppNotInstalledError(err)) {
434
492
  code = HardwareErrorCode.AppNotInstalled;
493
+ } else if (isAppAlreadyInstalledError(err)) {
494
+ code = HardwareErrorCode.AppAlreadyInstalled;
435
495
  } else if (isOutOfMemoryError(err)) {
436
496
  code = HardwareErrorCode.DeviceOutOfMemory;
497
+ } else if (isDeviceNotOnboardedError(err)) {
498
+ code = HardwareErrorCode.DeviceNotInitialized;
499
+ } else if (isFirmwareMetadataError(err)) {
500
+ code = HardwareErrorCode.LedgerFirmwareMetadataError;
437
501
  } else if (isNetworkError(err)) {
438
502
  code = HardwareErrorCode.NetworkError;
503
+ } else if (isSecureChannelError(err)) {
504
+ code = HardwareErrorCode.LedgerSecureChannelError;
439
505
  } else if (isDeviceDisconnectedError(err)) {
440
506
  code = HardwareErrorCode.DeviceDisconnected;
441
507
  } else if (isTimeoutError(err)) {
@@ -448,11 +514,35 @@ function mapLedgerError(err, opts) {
448
514
  }
449
515
  const errAppName = err && typeof err === "object" ? err.appName : void 0;
450
516
  const appName = errAppName ?? opts?.defaultAppName;
451
- return { code, message: enrichErrorMessage(code, originalMessage), appName };
517
+ return {
518
+ code,
519
+ message: enrichErrorMessage(code, originalMessage),
520
+ origin: defaultOriginForCode(code),
521
+ appName
522
+ };
523
+ }
524
+
525
+ // src/utils/queueKey.ts
526
+ var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
527
+ function ledgerQueueKey({
528
+ operationId,
529
+ connectId
530
+ }) {
531
+ return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
452
532
  }
453
533
 
454
534
  // src/adapter/methods/allNetworkGetAddress.ts
455
- import { HardwareErrorCode as HardwareErrorCode2, failure, runAllNetworkGetAddress } from "@onekeyfe/hwk-adapter-core";
535
+ import {
536
+ HardwareErrorCode as HardwareErrorCode2,
537
+ buildAllNetworkCancelledFailure,
538
+ failure,
539
+ isConnectionLost,
540
+ isUserRefusal,
541
+ isWalletSafetyFailure,
542
+ resolveHardwareOperationTarget,
543
+ runAllNetworkGetAddress,
544
+ success
545
+ } from "@onekeyfe/hwk-adapter-core";
456
546
 
457
547
  // src/utils/sdkEventBus.ts
458
548
  var listeners = /* @__PURE__ */ new Set();
@@ -509,57 +599,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
509
599
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
510
600
  function createAllNetworkGetAddress({
511
601
  callChain,
512
- getChainFingerprint
602
+ getChainFingerprint,
603
+ retainOperation,
604
+ errorToFailure,
605
+ createCancelScope,
606
+ releaseBundle
513
607
  }) {
514
608
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
515
- debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
516
- const installContext = {};
609
+ debugLog("[LedgerAdapter][REQ]", {
610
+ method: "allNetworkGetAddress",
611
+ connectId,
612
+ itemCount: params.bundle.length
613
+ });
614
+ const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
615
+ if (!target.success) return target;
616
+ const effectiveTargetId = target.payload.targetId ?? "";
617
+ let releaseOperationRetention;
618
+ try {
619
+ releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
620
+ } catch (error) {
621
+ return errorToFailure(error);
622
+ }
623
+ const cancelScope = createCancelScope(
624
+ ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
625
+ );
626
+ const installContext = {
627
+ walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
628
+ };
517
629
  const commonParams = {
518
- autoInstallApp: params.autoInstallApp
630
+ autoInstallApp: params.autoInstallApp,
631
+ operationId: target.payload.operationId,
632
+ knownConnections: params.knownConnections,
633
+ extra: params.extra,
634
+ allowDeviceSelection: params.allowDeviceSelection,
635
+ supportedTransports: params.supportedTransports
519
636
  };
520
637
  const chainFingerprints = /* @__PURE__ */ new Map();
521
- const result = await runAllNetworkGetAddress({
522
- connectId,
523
- deviceId: _deviceId,
524
- params,
525
- normalizeItem: normalizeLedgerAllNetworkItem,
526
- buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
527
- callItem: async ({ method, chain, item }) => {
528
- const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
529
- return callAllNetworkMethod(
530
- callChain,
531
- connectId,
532
- itemDeviceId,
533
- method,
638
+ const order = params.bundle.map((_item, index) => index).sort(
639
+ (a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
640
+ );
641
+ try {
642
+ const ordered = await runAllNetworkGetAddress({
643
+ connectId: effectiveTargetId,
644
+ deviceId: _deviceId,
645
+ params: { ...params, bundle: order.map((index) => params.bundle[index]) },
646
+ normalizeItem: normalizeLedgerAllNetworkItem,
647
+ buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
648
+ callItem: async ({ method, chain, item }) => {
649
+ if (cancelScope.signal.aborted)
650
+ return buildAllNetworkCancelledFailure(cancelScope.signal);
651
+ const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
652
+ return callAllNetworkMethod(
653
+ callChain,
654
+ effectiveTargetId,
655
+ itemDeviceId,
656
+ method,
657
+ item,
658
+ commonParams,
659
+ installContext
660
+ );
661
+ },
662
+ attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
663
+ getChainFingerprint,
664
+ effectiveTargetId,
534
665
  item,
535
- commonParams,
536
- installContext
537
- );
538
- },
539
- attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
540
- getChainFingerprint,
541
- connectId,
542
- item,
543
- chain,
544
- payload,
545
- chainFingerprints
546
- ),
547
- shouldAbortBundle: isTopLevelAllNetworkFailure,
548
- buildTopLevelFailure: (response) => {
549
- const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
550
- return failure(
551
- code,
552
- response.payload?.error ?? "All-network get-address aborted",
553
- response.payload?.params
554
- );
666
+ chain,
667
+ payload,
668
+ chainFingerprints,
669
+ installContext,
670
+ cancelScope.signal
671
+ ),
672
+ shouldAbortBundle: isTopLevelAllNetworkFailure,
673
+ buildTopLevelFailure: (response) => {
674
+ const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
675
+ return failure(
676
+ code,
677
+ response.payload?.error ?? "All-network get-address aborted",
678
+ response.payload?.params
679
+ );
680
+ }
681
+ });
682
+ let result = ordered;
683
+ if (ordered.success) {
684
+ const responses = [];
685
+ ordered.payload.forEach((response, position) => {
686
+ responses[order[position]] = response;
687
+ });
688
+ result = success(responses);
555
689
  }
556
- });
557
- debugLog("[LedgerAdapter][RES]", {
558
- method: "allNetworkGetAddress",
559
- success: result.success,
560
- payload: result
561
- });
562
- return result;
690
+ debugLog("[LedgerAdapter][RES]", {
691
+ method: "allNetworkGetAddress",
692
+ success: result.success,
693
+ payload: result
694
+ });
695
+ return result;
696
+ } finally {
697
+ await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
698
+ cancelScope.release();
699
+ releaseOperationRetention?.();
700
+ }
563
701
  };
564
702
  }
565
703
  function isTopLevelAllNetworkFailure(response) {
@@ -567,7 +705,7 @@ function isTopLevelAllNetworkFailure(response) {
567
705
  return false;
568
706
  }
569
707
  const code = response.payload?.code;
570
- return code === HardwareErrorCode2.DeviceMismatch || code === HardwareErrorCode2.UserAborted || code === HardwareErrorCode2.UserRejected;
708
+ return isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
571
709
  }
572
710
  function getItemDeviceId(item) {
573
711
  const { deviceId } = item;
@@ -597,8 +735,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
597
735
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
598
736
  return coin ? { ...item, coin } : item;
599
737
  }
600
- async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
601
- const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
738
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
739
+ const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
740
+ if (!knownFingerprint && cancelSignal.aborted) {
741
+ const cancelled = buildAllNetworkCancelledFailure(cancelSignal);
742
+ return { ...item, success: false, payload: cancelled.payload };
743
+ }
744
+ const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
745
+ getChainFingerprint,
746
+ context.connection?.connectId ?? connectId,
747
+ chain,
748
+ context
749
+ );
602
750
  if (!fingerprint) {
603
751
  return buildFingerprintBootstrapFailure(item, chain);
604
752
  }
@@ -619,8 +767,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
619
767
  }
620
768
  };
621
769
  }
622
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
623
- const response = await getChainFingerprint(connectId, chain);
770
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
771
+ const response = await getChainFingerprint(connectId, chain, context);
624
772
  return response.success ? response.payload : "";
625
773
  }
626
774
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -713,6 +861,20 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
713
861
  function formatDeviceMismatchError(expected, actual) {
714
862
  return `Wrong device: expected ${expected}, got ${actual}`;
715
863
  }
864
+ var LOG_REDACTED_RESULT_KEYS = ["ufvk", "orchardFvk"];
865
+ function isSigningMethod(method) {
866
+ return /sign/i.test(method);
867
+ }
868
+ function redactResultForLog(result, method) {
869
+ if (isSigningMethod(method)) return "[redacted]";
870
+ if (!result || typeof result !== "object") return result;
871
+ const keys = LOG_REDACTED_RESULT_KEYS.filter((key) => key in result);
872
+ if (!keys.length) return result;
873
+ return { ...result, ...Object.fromEntries(keys.map((key) => [key, "[redacted]"])) };
874
+ }
875
+ function isLostConnectionError(err) {
876
+ return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
877
+ }
716
878
  var BTC_HIGH_INDEX_THRESHOLD = 100;
717
879
  function btcAccountIndexFromPath(path) {
718
880
  const segments = path.replace(/^m\//, "").split("/");
@@ -724,9 +886,35 @@ function btcAccountIndexFromPath(path) {
724
886
  var _LedgerAdapter = class _LedgerAdapter {
725
887
  constructor(connector, options) {
726
888
  this.vendor = "ledger";
889
+ // Cancel frees the DMK action and its intent-queue slot, but cannot retract a
890
+ // confirmation screen the device is already showing.
891
+ this.cancelCapability = "stops-waiting";
727
892
  this.emitter = new TypedEventEmitter();
893
+ this._operations = new OperationRegistry({
894
+ vendor: "ledger",
895
+ onEnded: (operation, reason) => {
896
+ this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
897
+ this._pendingOperationBindings.delete(operation.operationId);
898
+ this.emitter.emit(SDK.OPERATION_ENDED, {
899
+ type: SDK.OPERATION_ENDED,
900
+ payload: { operationId: operation.operationId, reason }
901
+ });
902
+ if (reason === "timeout") {
903
+ void this._releaseOperationConnection(operation);
904
+ }
905
+ }
906
+ });
728
907
  this._discoveredDevices = /* @__PURE__ */ new Map();
729
908
  this._sessions = /* @__PURE__ */ new Map();
909
+ // An operation's BLE pick is saved by its first call that gets past the wallet check.
910
+ this._pendingOperationBindings = /* @__PURE__ */ new Map();
911
+ // A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
912
+ // through an unlock retry; any other failure drops it with its session.
913
+ this._pendingPickBindings = /* @__PURE__ */ new Map();
914
+ // Transport each session was opened on, by sessionId. The adapter-wide
915
+ // `_activeConnectionType` moves with every discovery and can go stale.
916
+ this._sessionTransports = /* @__PURE__ */ new Map();
917
+ this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
730
918
  this._uiRegistry = new UiRequestRegistry();
731
919
  // BTC App rejects account index >= 100 unless display=true. Cached per
732
920
  // adapter instance: first 100+ path asks the user once via UI request,
@@ -740,21 +928,36 @@ var _LedgerAdapter = class _LedgerAdapter {
740
928
  this._deviceAuthenticityQueueTail = Promise.resolve();
741
929
  // Shared across concurrent callers — only `cancel()` aborts.
742
930
  this._doConnectAbortController = null;
931
+ this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
932
+ this._connectorIdleWaiters = /* @__PURE__ */ new Set();
933
+ this._resetPromise = null;
934
+ this._stateGeneration = 0;
935
+ this._connectorTeardownTail = Promise.resolve();
936
+ this._pendingConnectorTeardowns = 0;
937
+ this._activeOperationJobs = /* @__PURE__ */ new Set();
938
+ this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
743
939
  this._installProgressLastEmittedValue = -Infinity;
744
940
  this.allNetworkGetAddress = createAllNetworkGetAddress({
745
941
  callChain: this.callChain.bind(this),
746
- getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
942
+ getChainFingerprint: async (connectId, chain, context) => {
943
+ try {
944
+ const fingerprint = await this._computeChainFingerprint(
945
+ chain,
946
+ (method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
947
+ );
948
+ return success2(fingerprint);
949
+ } catch (error) {
950
+ return this.errorToFailure(error);
951
+ }
952
+ },
953
+ retainOperation: (operationId) => this._operations.retain(operationId),
954
+ errorToFailure: (error) => this.errorToFailure(error),
955
+ createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
956
+ releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
747
957
  });
748
958
  // ---------------------------------------------------------------------------
749
959
  // Private helpers
750
960
  // ---------------------------------------------------------------------------
751
- /**
752
- * Ensure at least one device is connected and return a valid connectId.
753
- *
754
- * - If a session already exists for the given connectId, reuse it.
755
- * - If ANY session exists (Ledger IDs are ephemeral), reuse it.
756
- * - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
757
- */
758
961
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
759
962
  this._connectingPromise = null;
760
963
  // ---------------------------------------------------------------------------
@@ -770,6 +973,12 @@ var _LedgerAdapter = class _LedgerAdapter {
770
973
  });
771
974
  };
772
975
  this.deviceDisconnectHandler = (data) => {
976
+ const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
977
+ if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
978
+ this._pendingOperationDisconnects.add(activeOperation.operationId);
979
+ } else {
980
+ this._operations.endByConnectionKey(data.connectId, "disconnect");
981
+ }
773
982
  this._discoveredDevices.delete(data.connectId);
774
983
  this._sessions.delete(data.connectId);
775
984
  this.emitter.emit(DEVICE.DISCONNECT, {
@@ -778,10 +987,8 @@ var _LedgerAdapter = class _LedgerAdapter {
778
987
  });
779
988
  };
780
989
  // Forward connector `ui-event` to the public hw.emitter so consumers only
781
- // need to subscribe in one place. For the AppInstallProgress variant we
782
- // re-key sessionId → connectId via the live _sessions map; if no mapping
783
- // exists (race during teardown) we drop. All other variants pass through
784
- // unchanged.
990
+ // need to subscribe in one place. The AppInstallProgress variant re-keys
991
+ // sessionId to connectId via `_sessions`, and drops if no mapping exists.
785
992
  this.uiEventForwarder = (event) => {
786
993
  if (event.type === EConnectorInteraction.AppInstallProgress) {
787
994
  let connectId;
@@ -826,11 +1033,30 @@ var _LedgerAdapter = class _LedgerAdapter {
826
1033
  this._jobQueue = new DeviceJobQueue();
827
1034
  this.registerEventListeners();
828
1035
  }
1036
+ _discardPendingBinding(owner, status = "cancelled") {
1037
+ const pending = owner?.pendingBinding;
1038
+ if (!owner || !pending) return;
1039
+ owner.pendingBinding = void 0;
1040
+ if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1041
+ }
1042
+ _finishBleBinding(status) {
1043
+ const selectionRequestId = this._bindingSelectionRequestId;
1044
+ this._bindingSelectionRequestId = void 0;
1045
+ if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
1046
+ }
1047
+ _isBleConnection() {
1048
+ return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1049
+ }
829
1050
  // Transport
830
1051
  get activeTransport() {
831
- return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1052
+ return this._isBleConnection() ? "ble" : "hid";
832
1053
  }
833
1054
  getAvailableTransports() {
1055
+ if (this.connector.availableTransports) {
1056
+ return this.connector.availableTransports.map(
1057
+ (transport) => transport === "ble" ? "ble" : "hid"
1058
+ );
1059
+ }
834
1060
  return this.activeTransport ? [this.activeTransport] : [];
835
1061
  }
836
1062
  // Connector is bound at construction; switching requires a new adapter.
@@ -847,21 +1073,42 @@ var _LedgerAdapter = class _LedgerAdapter {
847
1073
  * The next operation will re-discover and re-connect automatically.
848
1074
  */
849
1075
  resetState() {
1076
+ void this._resetStateAndDisconnectSessions();
1077
+ }
1078
+ _resetStateAndDisconnectSessions() {
1079
+ if (this._resetPromise) return this._resetPromise;
1080
+ const sessionIds = new Set(this._sessions.values());
1081
+ this._stateGeneration += 1;
1082
+ this._finishBleBinding("cancelled");
1083
+ this._operations.endAll("runtime-reset");
1084
+ this._doConnectAbortController?.abort();
850
1085
  this._discoveredDevices.clear();
851
1086
  this._sessions.clear();
1087
+ this._sessionTransports.clear();
1088
+ this._pendingOperationBindings.clear();
1089
+ this._pendingPickBindings.clear();
1090
+ this._selectedBleReconnectTargets.clear();
852
1091
  this._connectingPromise = null;
1092
+ this._doConnectAbortController = null;
853
1093
  this._uiRegistry.reset();
854
1094
  this._jobQueue.clear();
855
1095
  this._btcHighIndexConfirmedThisSession = false;
1096
+ const resetPromise = this._runConnectorTeardown(async () => {
1097
+ for (const sessionId of sessionIds) {
1098
+ await this.connector.disconnect(sessionId).catch(() => void 0);
1099
+ }
1100
+ });
1101
+ this._resetPromise = resetPromise;
1102
+ return resetPromise.finally(() => {
1103
+ if (this._resetPromise === resetPromise) {
1104
+ this._resetPromise = null;
1105
+ }
1106
+ });
856
1107
  }
857
1108
  async dispose() {
858
- this._uiRegistry.reset();
859
- this._jobQueue.clear();
1109
+ await this._resetStateAndDisconnectSessions();
860
1110
  this.unregisterEventListeners();
861
1111
  this.connector.reset();
862
- this._discoveredDevices.clear();
863
- this._sessions.clear();
864
- this._btcHighIndexConfirmedThisSession = false;
865
1112
  this.emitter.removeAllListeners();
866
1113
  }
867
1114
  uiResponse(response) {
@@ -871,17 +1118,32 @@ var _LedgerAdapter = class _LedgerAdapter {
871
1118
  // Device management
872
1119
  // ---------------------------------------------------------------------------
873
1120
  async searchDevices(options) {
1121
+ return this._searchDevices(options);
1122
+ }
1123
+ async _searchDevices(options, signal) {
874
1124
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
875
1125
  try {
876
1126
  if (options?.resetSession) {
877
- this._doConnectAbortController?.abort();
878
- this._sessions.clear();
879
- this._connectingPromise = null;
880
- this._doConnectAbortController = null;
881
- this._btcHighIndexConfirmedThisSession = false;
1127
+ await this._resetStateAndDisconnectSessions();
1128
+ } else {
1129
+ await this._connectorTeardownTail;
1130
+ }
1131
+ await this._ensureDevicePermission(void 0, void 0, signal);
1132
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1133
+ const stateGeneration = this._stateGeneration;
1134
+ const devices = await this.connector.searchDevices(
1135
+ options?.transportType ? {
1136
+ transportType: options.transportType,
1137
+ waitForAll: options.waitForAllTransports
1138
+ } : void 0
1139
+ );
1140
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1141
+ if (stateGeneration !== this._stateGeneration) {
1142
+ throw createHwkError({
1143
+ code: HardwareErrorCode3.UserAborted,
1144
+ message: "Ledger discovery was reset"
1145
+ });
882
1146
  }
883
- await this._ensureDevicePermission();
884
- const devices = await this.connector.searchDevices();
885
1147
  this._discoveredDevices.clear();
886
1148
  for (const d of devices) {
887
1149
  if (d.connectId) {
@@ -889,7 +1151,7 @@ var _LedgerAdapter = class _LedgerAdapter {
889
1151
  }
890
1152
  }
891
1153
  if (this._discoveredDevices.size === 0) {
892
- await this._ensureDevicePermission();
1154
+ await this._ensureDevicePermission(void 0, void 0, signal);
893
1155
  }
894
1156
  const result = Array.from(this._discoveredDevices.values());
895
1157
  debugLog("[LedgerAdapter][RES]", {
@@ -908,41 +1170,263 @@ var _LedgerAdapter = class _LedgerAdapter {
908
1170
  throw err;
909
1171
  }
910
1172
  }
1173
+ async searchDeviceTargets(options) {
1174
+ const devices = await this.searchDevices(options);
1175
+ return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
1176
+ }
911
1177
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
912
- async _evictAllSessions() {
1178
+ async _evictAllSessions(preserveOperationId) {
1179
+ this._operations.endAll("explicit", preserveOperationId);
913
1180
  if (this._sessions.size === 0) return;
914
1181
  const stale = [...this._sessions.values()];
915
1182
  this._sessions.clear();
916
- for (const sid of stale) {
917
- try {
918
- await this.connector.disconnect(sid);
919
- } catch {
1183
+ for (const sid of stale) this._sessionTransports.delete(sid);
1184
+ await this._runConnectorTeardown(async () => {
1185
+ for (const sid of stale) {
1186
+ try {
1187
+ await this.connector.disconnect(sid);
1188
+ } catch {
1189
+ }
920
1190
  }
921
- }
1191
+ });
922
1192
  }
923
1193
  static _createDeviceBusyError(method) {
924
1194
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
925
1195
  code: HardwareErrorCode3.DeviceBusy
926
1196
  });
927
1197
  }
928
- async connectDevice(connectId) {
1198
+ async connectDevice(searchTargetId) {
1199
+ try {
1200
+ return await this._jobQueue.enqueue(
1201
+ searchTargetId || "__ledger_connect__",
1202
+ async (signal) => {
1203
+ const connected = await this._connectTarget(searchTargetId, void 0, signal);
1204
+ if (!connected.success) return connected;
1205
+ return this._createOperation(searchTargetId, connected.payload);
1206
+ },
1207
+ {
1208
+ label: "connectDevice",
1209
+ rejectIfBusy: true,
1210
+ busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1211
+ }
1212
+ );
1213
+ } catch (error) {
1214
+ return this.errorToFailure(error);
1215
+ }
1216
+ }
1217
+ /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1218
+ async bindBleDevice(params) {
1219
+ const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1220
+ try {
1221
+ return await this._jobQueue.enqueue(
1222
+ "__ledger_bind_ble__",
1223
+ async (signal) => {
1224
+ if (!this.getAvailableTransports().includes("ble")) {
1225
+ throw createHwkError({
1226
+ code: HardwareErrorCode3.TransportNotAvailable,
1227
+ message: "Ledger Bluetooth transport is not available"
1228
+ });
1229
+ }
1230
+ this._activeConnectionType = "ble";
1231
+ await this._ensureDevicePermission(void 0, void 0, signal);
1232
+ const attempt = {
1233
+ extra: params.extra,
1234
+ bindingReason: "manual-rebind",
1235
+ deferBindingSave: Boolean(identity)
1236
+ };
1237
+ try {
1238
+ const connectId = await this._connectFirstOrSelect(
1239
+ [],
1240
+ void 0,
1241
+ true,
1242
+ void 0,
1243
+ attempt,
1244
+ signal
1245
+ );
1246
+ const pending = attempt.pendingBinding;
1247
+ if (identity && pending) {
1248
+ attempt.pendingBinding = void 0;
1249
+ const sessionId = this._sessions.get(connectId);
1250
+ if (!sessionId) {
1251
+ throw createHwkError({
1252
+ code: HardwareErrorCode3.DeviceDisconnected,
1253
+ message: "Selected Ledger connection ended"
1254
+ });
1255
+ }
1256
+ const fingerprint = await this._computeChainFingerprint(
1257
+ identity.chain,
1258
+ (method, callParams) => this._runConnectorCall(
1259
+ connectId,
1260
+ method,
1261
+ callParams,
1262
+ signal,
1263
+ void 0,
1264
+ void 0,
1265
+ { autoInstallApp: true },
1266
+ { connection: { connectId, sessionId } }
1267
+ )
1268
+ );
1269
+ if (fingerprint !== identity.value) {
1270
+ await this._dropSession(connectId, signal);
1271
+ throw createHwkError({
1272
+ code: HardwareErrorCode3.DeviceMismatch,
1273
+ message: formatDeviceMismatchError(identity.value, fingerprint)
1274
+ });
1275
+ }
1276
+ await this._saveSelectedBleBinding(
1277
+ connectId,
1278
+ pending.requestId,
1279
+ attempt,
1280
+ void 0,
1281
+ signal,
1282
+ identity
1283
+ );
1284
+ }
1285
+ if (!attempt.bindingSaved) {
1286
+ await this._dropSession(connectId, signal);
1287
+ throw createHwkError({
1288
+ code: HardwareErrorCode3.UnknownError,
1289
+ message: "Bluetooth binding could not be saved",
1290
+ origin: "host"
1291
+ });
1292
+ }
1293
+ return success2(connectId);
1294
+ } catch (error) {
1295
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1296
+ throw error;
1297
+ }
1298
+ },
1299
+ {
1300
+ label: "bindBleDevice",
1301
+ rejectIfBusy: true,
1302
+ busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1303
+ }
1304
+ );
1305
+ } catch (error) {
1306
+ return this.errorToFailure(error);
1307
+ }
1308
+ }
1309
+ async acquireOperation(connectId, context) {
1310
+ try {
1311
+ return await this._jobQueue.enqueue(
1312
+ connectId || "__ledger_acquire__",
1313
+ async (signal) => {
1314
+ const transport = this._isBleConnection() ? "ble" : "usb";
1315
+ const hint = context.knownConnections?.find(
1316
+ (connection) => connection.transport === transport
1317
+ );
1318
+ const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1319
+ await this._ensureDevicePermission(target, void 0, signal);
1320
+ const attempt = {
1321
+ ...context,
1322
+ extra: context.extra ? { ...context.extra } : void 0,
1323
+ // The operation's calls decide whether the pick is the right wallet.
1324
+ deferBindingSave: true
1325
+ };
1326
+ try {
1327
+ const resolvedConnectId = await this.ensureConnected(
1328
+ target,
1329
+ signal,
1330
+ true,
1331
+ void 0,
1332
+ attempt
1333
+ );
1334
+ _LedgerAdapter._throwIfAborted(signal);
1335
+ const result = this._createOperation(connectId, resolvedConnectId);
1336
+ if (result.success && attempt.pendingBinding) {
1337
+ this._pendingOperationBindings.set(result.payload, attempt);
1338
+ }
1339
+ return result;
1340
+ } catch (error) {
1341
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1342
+ throw error;
1343
+ }
1344
+ },
1345
+ {
1346
+ label: "acquireOperation",
1347
+ rejectIfBusy: true,
1348
+ busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1349
+ }
1350
+ );
1351
+ } catch (error) {
1352
+ return this.errorToFailure(error);
1353
+ }
1354
+ }
1355
+ _createOperation(searchTargetId, resolvedConnectId) {
1356
+ this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1357
+ const sessionId = this._sessions.get(resolvedConnectId);
1358
+ if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1359
+ const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1360
+ const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1361
+ vendor: "ledger",
1362
+ model: "unknown",
1363
+ firmwareVersion: "",
1364
+ deviceId: "",
1365
+ connectId: resolvedConnectId,
1366
+ connectionType
1367
+ };
1368
+ const operation = this._operations.create({
1369
+ searchTargetId,
1370
+ connectId: resolvedConnectId,
1371
+ device,
1372
+ connectionType,
1373
+ connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
1374
+ });
1375
+ return success2(operation.operationId);
1376
+ }
1377
+ async _connectTarget(connectId, preserveOperationId, signal) {
929
1378
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
930
1379
  try {
931
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1380
+ this._assertConnectorReady("connectDevice");
1381
+ const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1382
+ if (discoveredType === "usb" || discoveredType === "ble") {
1383
+ this._activeConnectionType = discoveredType;
1384
+ }
1385
+ if (this._isBleConnection() && !connectId) {
932
1386
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
933
1387
  code: HardwareErrorCode3.DeviceNotFound
934
1388
  });
935
1389
  }
936
- if (!isLedgerBleConnectionType(this.connector.connectionType)) {
937
- await this._evictAllSessions();
1390
+ await this._ensureDevicePermission(connectId, void 0, signal);
1391
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1392
+ const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1393
+ if (!isMultiTransport && this._isBleConnection()) {
1394
+ const previousSessionId = this._sessions.get(connectId);
1395
+ this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1396
+ if (previousSessionId) {
1397
+ this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1398
+ this._sessions.delete(connectId);
1399
+ await this.connector.disconnect(previousSessionId).catch(() => void 0);
1400
+ }
1401
+ } else {
1402
+ await this._evictAllSessions(preserveOperationId);
1403
+ }
1404
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1405
+ const stateGeneration = this._stateGeneration;
1406
+ const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1407
+ let session;
1408
+ this._connectingConnectId = connectId;
1409
+ try {
1410
+ session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1411
+ transportType: this._activeConnectionType ?? "usb"
1412
+ }) : await this.connector.connect(connectId);
1413
+ if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1414
+ await this.connector.disconnect(session.sessionId).catch(() => void 0);
1415
+ throw Object.assign(new Error("Ledger connection aborted"), {
1416
+ code: HardwareErrorCode3.UserAborted
1417
+ });
1418
+ }
1419
+ } finally {
1420
+ if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1421
+ releaseOperation();
938
1422
  }
939
- await this._ensureDevicePermission(connectId);
940
- const session = await this.connector.connect(connectId);
941
- this._sessions.set(connectId, session.sessionId);
1423
+ const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1424
+ this._sessions.set(resolvedConnectId, session.sessionId);
1425
+ this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
942
1426
  if (session.deviceInfo) {
943
- this._discoveredDevices.set(connectId, session.deviceInfo);
1427
+ this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
944
1428
  }
945
- const result = success(connectId);
1429
+ const result = success2(resolvedConnectId);
946
1430
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
947
1431
  return result;
948
1432
  } catch (err) {
@@ -955,30 +1439,73 @@ var _LedgerAdapter = class _LedgerAdapter {
955
1439
  return failureResult;
956
1440
  }
957
1441
  }
958
- async disconnectDevice(connectId) {
1442
+ async releaseOperation(operationId) {
1443
+ const operation = this._operations.findActive(operationId);
1444
+ if (operation) this._cancelOperationWork(operation);
1445
+ const endedOperation = this._operations.release(operationId);
1446
+ if (!endedOperation) return;
1447
+ const { connectId } = endedOperation;
959
1448
  debugLog("[LedgerAdapter][REQ]", {
960
- method: "disconnectDevice",
1449
+ method: "releaseOperation",
961
1450
  connectId,
962
1451
  params: { connectId }
963
1452
  });
964
1453
  try {
965
- const sessionId = this._sessions.get(connectId);
966
- if (sessionId) {
967
- await this.connector.disconnect(sessionId);
968
- this._sessions.delete(connectId);
969
- }
970
- debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
1454
+ await this._releaseOperationConnection(endedOperation);
1455
+ debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
971
1456
  } catch (err) {
972
1457
  const e = err;
973
1458
  debugLog("[LedgerAdapter][RES]", {
974
- method: "disconnectDevice",
1459
+ method: "releaseOperation",
975
1460
  success: false,
976
1461
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
977
1462
  });
978
1463
  throw err;
979
1464
  }
980
1465
  }
981
- async getDeviceInfo(connectId, deviceId) {
1466
+ /**
1467
+ * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1468
+ * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1469
+ */
1470
+ _cancelOperationWork(operation) {
1471
+ const { operationId } = operation;
1472
+ const reason = createHwkError({
1473
+ code: HardwareErrorCode3.OperationEnded,
1474
+ message: "Ledger operation was released",
1475
+ params: { operationId, reason: "explicit" }
1476
+ });
1477
+ const queueKey = ledgerQueueKey({ operationId });
1478
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1479
+ this._jobQueue.cancelActiveAndPending(queueKey, reason);
1480
+ if (ownsRunningCall) this._uiRegistry.cancel(void 0, void 0, operationId);
1481
+ }
1482
+ async _releaseOperationConnection(operation) {
1483
+ const sessionIds = /* @__PURE__ */ new Set();
1484
+ for (const [connectId, sessionId] of this._sessions) {
1485
+ if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1486
+ this._sessions.delete(connectId);
1487
+ sessionIds.add(sessionId);
1488
+ }
1489
+ }
1490
+ for (const sessionId of sessionIds) {
1491
+ await this._runConnectorTeardown(
1492
+ () => this.connector.disconnect(sessionId).catch(() => void 0)
1493
+ );
1494
+ }
1495
+ }
1496
+ async _releaseLostOperationConnection(operationId) {
1497
+ const endedOperation = this._operations.end(operationId, "disconnect");
1498
+ if (!endedOperation) return;
1499
+ this._discoveredDevices.delete(endedOperation.connectId);
1500
+ await this._releaseOperationConnection(endedOperation);
1501
+ }
1502
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1503
+ let connectId;
1504
+ try {
1505
+ connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1506
+ } catch (error) {
1507
+ return this.errorToFailure(error);
1508
+ }
982
1509
  debugLog("[LedgerAdapter][REQ]", {
983
1510
  method: "getDeviceInfo",
984
1511
  connectId,
@@ -988,7 +1515,7 @@ var _LedgerAdapter = class _LedgerAdapter {
988
1515
  await this._ensureDevicePermission(connectId, deviceId);
989
1516
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
990
1517
  if (cached) {
991
- const result = success(cached);
1518
+ const result = success2(cached);
992
1519
  debugLog("[LedgerAdapter][RES]", {
993
1520
  method: "getDeviceInfo",
994
1521
  success: true,
@@ -1013,11 +1540,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1013
1540
  success: false,
1014
1541
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1015
1542
  });
1016
- throw err;
1543
+ return this.errorToFailure(err);
1017
1544
  }
1018
1545
  }
1019
- getSupportedChains() {
1020
- return ["evm", "btc", "sol", "tron"];
1546
+ /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1547
+ async _dropUncheckedBundlePick(context, signal) {
1548
+ const { connection } = context;
1549
+ const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1550
+ if (!connection || !owner) return;
1551
+ this._pendingPickBindings.delete(connection.connectId);
1552
+ this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1553
+ if (this._sessions.get(connection.connectId) === connection.sessionId) {
1554
+ await this._dropSession(connection.connectId, signal);
1555
+ }
1021
1556
  }
1022
1557
  // ---------------------------------------------------------------------------
1023
1558
  // Chain call helper
@@ -1037,7 +1572,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1037
1572
  commonParams,
1038
1573
  installContext
1039
1574
  );
1040
- return success(result);
1575
+ return success2(result);
1041
1576
  } catch (err) {
1042
1577
  return this.errorToFailure(err);
1043
1578
  }
@@ -1053,13 +1588,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1053
1588
  if (params && typeof params === "object") {
1054
1589
  const {
1055
1590
  autoInstallApp,
1591
+ operationId,
1056
1592
  passphraseState: _passphraseState,
1057
1593
  useEmptyPassphrase: _useEmptyPassphrase,
1594
+ knownConnections,
1595
+ extra,
1596
+ allowDeviceSelection,
1597
+ supportedTransports,
1058
1598
  ...rest
1059
1599
  } = params;
1060
1600
  return {
1061
1601
  commonParams: {
1062
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1602
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1603
+ operationId: typeof operationId === "string" ? operationId : void 0,
1604
+ ...pickConnectionContext({
1605
+ knownConnections,
1606
+ extra,
1607
+ allowDeviceSelection,
1608
+ supportedTransports
1609
+ })
1063
1610
  },
1064
1611
  rest
1065
1612
  };
@@ -1235,14 +1782,33 @@ var _LedgerAdapter = class _LedgerAdapter {
1235
1782
  );
1236
1783
  }
1237
1784
  // ---------------------------------------------------------------------------
1238
- // App management — OS-level Ledger app install / list. Bypasses fingerprint
1239
- // and chain-handler dispatch; installApp progress is forwarded to the adapter
1240
- // emitter via 'ui-event' AppInstallProgress events.
1785
+ // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1786
+ // ---------------------------------------------------------------------------
1787
+ zcashGetFullViewingKey(connectId, deviceId, params) {
1788
+ return this.callChainWithMergedParams(
1789
+ connectId,
1790
+ deviceId,
1791
+ "zcash",
1792
+ "zcashGetFullViewingKey",
1793
+ params
1794
+ );
1795
+ }
1796
+ zcashGetShieldedAddress(connectId, deviceId, params) {
1797
+ return this.callChainWithMergedParams(
1798
+ connectId,
1799
+ deviceId,
1800
+ "zcash",
1801
+ "zcashGetShieldedAddress",
1802
+ params
1803
+ );
1804
+ }
1805
+ // ---------------------------------------------------------------------------
1806
+ // App management: OS-level app install/list, no fingerprint or chain dispatch.
1241
1807
  // ---------------------------------------------------------------------------
1242
1808
  async installApp(connectId, appName) {
1243
1809
  try {
1244
1810
  await this.connectorCall(connectId, "installApp", { appName });
1245
- return success(void 0);
1811
+ return success2(void 0);
1246
1812
  } catch (err) {
1247
1813
  return this.errorToFailure(err);
1248
1814
  }
@@ -1250,7 +1816,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1250
1816
  async listInstalledApps(connectId) {
1251
1817
  try {
1252
1818
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1253
- return success(result);
1819
+ return success2(result);
1254
1820
  } catch (err) {
1255
1821
  return this.errorToFailure(err);
1256
1822
  }
@@ -1259,7 +1825,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1259
1825
  async listInstalledNames(connectId) {
1260
1826
  try {
1261
1827
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1262
- return success(result);
1828
+ return success2(result);
1263
1829
  } catch (err) {
1264
1830
  return this.errorToFailure(err);
1265
1831
  }
@@ -1267,7 +1833,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1267
1833
  async listAvailableApps(connectId) {
1268
1834
  try {
1269
1835
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1270
- return success(result);
1836
+ return success2(result);
1271
1837
  } catch (err) {
1272
1838
  return this.errorToFailure(err);
1273
1839
  }
@@ -1275,7 +1841,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1275
1841
  async getLedgerFirmwareVersion(connectId) {
1276
1842
  try {
1277
1843
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1278
- return success(result);
1844
+ return success2(result);
1279
1845
  } catch (err) {
1280
1846
  return this.errorToFailure(err);
1281
1847
  }
@@ -1283,7 +1849,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1283
1849
  async getLedgerDeviceInfo(connectId) {
1284
1850
  try {
1285
1851
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1286
- return success(result);
1852
+ return success2(result);
1287
1853
  } catch (err) {
1288
1854
  return this.errorToFailure(err);
1289
1855
  }
@@ -1323,11 +1889,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1323
1889
  );
1324
1890
  }
1325
1891
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1326
- this.resetState();
1892
+ await this._resetStateAndDisconnectSessions();
1327
1893
  }
1328
1894
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1329
1895
  if (!result.isGenuine) {
1330
- return success({
1896
+ return success2({
1331
1897
  vendor: "ledger",
1332
1898
  verified: false
1333
1899
  });
@@ -1338,7 +1904,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1338
1904
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1339
1905
  );
1340
1906
  }
1341
- return success({
1907
+ return success2({
1342
1908
  vendor: "ledger",
1343
1909
  verified: result.isGenuine,
1344
1910
  deviceId: result.deviceId
@@ -1349,10 +1915,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1349
1915
  if (relayUrl) {
1350
1916
  try {
1351
1917
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1352
- this.resetState();
1918
+ await this._resetStateAndDisconnectSessions();
1353
1919
  } catch {
1354
1920
  this.connector.reset();
1355
- this.resetState();
1921
+ await this._resetStateAndDisconnectSessions();
1356
1922
  }
1357
1923
  }
1358
1924
  }
@@ -1364,6 +1930,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1364
1930
  this.emitter.off(event, listener);
1365
1931
  }
1366
1932
  cancel(connectId) {
1933
+ const namedOperationIsLive = (id) => {
1934
+ try {
1935
+ this._operations.resolve(id);
1936
+ return true;
1937
+ } catch {
1938
+ return false;
1939
+ }
1940
+ };
1941
+ if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
1942
+ debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
1943
+ connectId
1944
+ });
1945
+ return;
1946
+ }
1367
1947
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1368
1948
  code: HardwareErrorCode3.UserAborted,
1369
1949
  _tag: ERROR_TAG.UserAborted
@@ -1374,14 +1954,48 @@ var _LedgerAdapter = class _LedgerAdapter {
1374
1954
  this._lastCancelReason = void 0;
1375
1955
  }
1376
1956
  }, 2e3);
1377
- this._uiRegistry.cancel();
1378
- if (connectId) {
1379
- this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1957
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
1958
+ let operationId;
1959
+ if (isHardwareOperationId(connectId)) {
1960
+ operationId = connectId;
1961
+ } else if (!connectId && isHardwareOperationId(activeJobId)) {
1962
+ operationId = activeJobId;
1963
+ }
1964
+ let resolvedConnectId = connectId;
1965
+ if (operationId) {
1966
+ try {
1967
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
1968
+ } catch {
1969
+ resolvedConnectId = void 0;
1970
+ }
1971
+ }
1972
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1973
+ const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
1974
+ if (!connectId) {
1975
+ this._uiRegistry.cancel();
1976
+ } else if (pendingOperationId) {
1977
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
1978
+ }
1979
+ this._finishBleBinding("cancelled");
1980
+ if (!connectId) this._pendingOperationBindings.clear();
1981
+ else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
1982
+ const queueKeys = /* @__PURE__ */ new Set();
1983
+ if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
1984
+ if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
1985
+ if (queueKeys.size) {
1986
+ let cancelledAnyJob = false;
1987
+ for (const key of queueKeys) {
1988
+ cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
1989
+ }
1990
+ debugLog("[LedgerAdapter] cancel routed to queue keys", {
1991
+ queueKeys: [...queueKeys],
1992
+ cancelledAnyJob
1993
+ });
1380
1994
  } else {
1381
1995
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1382
1996
  }
1383
- if (connectId) {
1384
- const sessionId = this._sessions.get(connectId) ?? connectId;
1997
+ if (resolvedConnectId) {
1998
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1385
1999
  void this.connector.cancel(sessionId);
1386
2000
  } else {
1387
2001
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
@@ -1389,45 +2003,86 @@ var _LedgerAdapter = class _LedgerAdapter {
1389
2003
  if (this._connectingPromise) {
1390
2004
  this._doConnectAbortController?.abort(userAbortReason);
1391
2005
  }
2006
+ const connectingConnectId = this._connectingConnectId;
2007
+ if (connectingConnectId) void this.connector.cancel(connectingConnectId);
1392
2008
  }
1393
2009
  // ---------------------------------------------------------------------------
1394
2010
  // Chain fingerprint
1395
2011
  // ---------------------------------------------------------------------------
2012
+ /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
1396
2013
  async getChainFingerprint(connectId, deviceId, chain) {
1397
2014
  try {
1398
2015
  const fingerprint = await this._computeChainFingerprint(
1399
2016
  chain,
1400
2017
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
1401
2018
  );
1402
- return success(fingerprint);
2019
+ if (deviceId) {
2020
+ if (fingerprint !== deviceId) {
2021
+ return failure2(
2022
+ HardwareErrorCode3.DeviceMismatch,
2023
+ formatDeviceMismatchError(deviceId, fingerprint)
2024
+ );
2025
+ }
2026
+ }
2027
+ return success2(fingerprint);
1403
2028
  } catch (err) {
1404
2029
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
1405
2030
  return this.errorToFailure(err);
1406
2031
  }
1407
2032
  }
1408
- /**
1409
- * Verify fingerprint using an existing sessionId directly.
1410
- * Safe to call inside connectorCall without causing queue deadlock.
1411
- */
1412
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
1413
- if (!deviceId) return { success: true };
2033
+ /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2034
+ async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
1414
2035
  try {
1415
- const fingerprint = await this._computeChainFingerprint(
1416
- chain,
1417
- (method, params) => this._callConnector(sessionId, method, params)
2036
+ const outcome = await requestSaveDeviceBinding(
2037
+ this.emitter,
2038
+ this._uiRegistry,
2039
+ {
2040
+ selectionRequestId,
2041
+ connection: { transport: "ble", connectId },
2042
+ ...identity ? { identity } : {},
2043
+ extra: context?.extra,
2044
+ operationId
2045
+ },
2046
+ signal
1418
2047
  );
1419
- if (fingerprint === deviceId) {
1420
- return { success: true };
2048
+ if (context) context.bindingSaved = outcome.saved;
2049
+ if (!outcome.saved) {
2050
+ debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2051
+ connectId,
2052
+ reason: outcome.reason
2053
+ });
1421
2054
  }
1422
- return { success: false, expected: deviceId, actual: fingerprint };
1423
- } catch (err) {
1424
- const mapped = mapLedgerError(err);
1425
- if (mapped.code === HardwareErrorCode3.WrongApp || mapped.code === HardwareErrorCode3.DeviceLocked) {
1426
- return { success: true };
2055
+ } catch (error) {
2056
+ await this._dropSession(connectId, signal);
2057
+ throw error;
2058
+ } finally {
2059
+ if (this._bindingSelectionRequestId === selectionRequestId) {
2060
+ this._bindingSelectionRequestId = void 0;
1427
2061
  }
1428
- throw err;
1429
2062
  }
1430
2063
  }
2064
+ async _dropSession(connectId, signal) {
2065
+ const sessionId = this._sessions.get(connectId);
2066
+ this._sessions.delete(connectId);
2067
+ if (!sessionId) return;
2068
+ this._sessionTransports.delete(sessionId);
2069
+ const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2070
+ () => void 0
2071
+ );
2072
+ if (!signal.aborted) await teardown;
2073
+ }
2074
+ /** Verify on the acquired session without re-entering the job queue. */
2075
+ async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2076
+ if (!deviceId) return { success: true };
2077
+ const fingerprint = await this._computeChainFingerprint(
2078
+ chain,
2079
+ (method, params) => this._callConnector(sessionId, method, params)
2080
+ );
2081
+ if (fingerprint === deviceId) {
2082
+ return { success: true };
2083
+ }
2084
+ return { success: false, expected: deviceId, actual: fingerprint };
2085
+ }
1431
2086
  /**
1432
2087
  * Compute the chain fingerprint via a caller-supplied call strategy.
1433
2088
  *
@@ -1455,11 +2110,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1455
2110
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
1456
2111
  } else if (chain === "tron") {
1457
2112
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2113
+ } else if (chain === "zcash") {
2114
+ address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
1458
2115
  } else {
1459
2116
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
1460
2117
  }
1461
2118
  return deriveDeviceFingerprint(address);
1462
2119
  }
2120
+ /**
2121
+ * Operation owning the running job, so a mid-call UI request can name it.
2122
+ * Undefined at cold start when no operation owns the job.
2123
+ */
2124
+ _activeOperationId() {
2125
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2126
+ }
1463
2127
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
1464
2128
  // The user must press Confirm after unlocking, which triggers a search retry.
1465
2129
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -1469,15 +2133,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1469
2133
  if (signal?.aborted) {
1470
2134
  _LedgerAdapter._throwIfAborted(signal);
1471
2135
  }
2136
+ const operationId = this._activeOperationId();
1472
2137
  const waitPromise = this._uiRegistry.wait(
1473
- UI_REQUEST.REQUEST_DEVICE_CONNECT
2138
+ UI_REQUEST.REQUEST_DEVICE_CONNECT,
2139
+ { operationId }
1474
2140
  );
1475
2141
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1476
2142
  type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
1477
2143
  payload: {
1478
2144
  vendor: "ledger",
1479
2145
  reason: "device-not-found",
1480
- message: "Please connect and unlock your Ledger device"
2146
+ message: "Please connect and unlock your Ledger device",
2147
+ operationId
1481
2148
  }
1482
2149
  });
1483
2150
  let payload;
@@ -1523,7 +2190,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1523
2190
  * Returns the params to pass through (with `showOnDevice` possibly
1524
2191
  * promoted), or `null` if the user declined.
1525
2192
  */
1526
- async _gateBtcHighIndex(params) {
2193
+ async _gateBtcHighIndex(params, signal) {
1527
2194
  const accountIndex = btcAccountIndexFromPath(params.path);
1528
2195
  if (params.showOnDevice) return params;
1529
2196
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -1532,25 +2199,32 @@ var _LedgerAdapter = class _LedgerAdapter {
1532
2199
  if (this._btcHighIndexConfirmedThisSession) {
1533
2200
  return { ...params, showOnDevice: true };
1534
2201
  }
1535
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2202
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1536
2203
  if (!confirmed) return null;
1537
2204
  this._btcHighIndexConfirmedThisSession = true;
1538
2205
  return { ...params, showOnDevice: true };
1539
2206
  }
1540
- async _waitForBtcHighIndexConfirm(path, accountIndex) {
2207
+ async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2208
+ const operationId = this._activeOperationId();
1541
2209
  const waitPromise = this._uiRegistry.wait(
1542
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2210
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2211
+ { operationId }
1543
2212
  );
1544
2213
  this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1545
2214
  type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1546
2215
  payload: {
1547
2216
  vendor: "ledger",
1548
2217
  path,
1549
- accountIndex
2218
+ accountIndex,
2219
+ operationId
1550
2220
  }
1551
2221
  });
1552
2222
  try {
1553
- const payload = await waitPromise;
2223
+ const payload = await this._awaitUiAnswer(
2224
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2225
+ waitPromise,
2226
+ signal
2227
+ );
1554
2228
  return !!payload?.confirmed;
1555
2229
  } catch (err) {
1556
2230
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1560,18 +2234,35 @@ var _LedgerAdapter = class _LedgerAdapter {
1560
2234
  return false;
1561
2235
  }
1562
2236
  }
2237
+ /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2238
+ async _awaitUiAnswer(requestType, waitPromise, signal) {
2239
+ const onAbort = () => this._uiRegistry.cancel(requestType);
2240
+ if (signal.aborted) onAbort();
2241
+ signal.addEventListener("abort", onAbort, { once: true });
2242
+ try {
2243
+ return await waitPromise;
2244
+ } finally {
2245
+ signal.removeEventListener("abort", onAbort);
2246
+ }
2247
+ }
1563
2248
  // Ask the user whether to install a missing app (autoInstallApp flow).
1564
2249
  // Same register-then-emit ordering as the BTC high-index gate.
1565
- async _waitForInstallAppConfirm(appName) {
2250
+ async _waitForInstallAppConfirm(appName, signal) {
2251
+ const operationId = this._activeOperationId();
1566
2252
  const waitPromise = this._uiRegistry.wait(
1567
- UI_REQUEST.REQUEST_INSTALL_APP
2253
+ UI_REQUEST.REQUEST_INSTALL_APP,
2254
+ { operationId }
1568
2255
  );
1569
2256
  this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
1570
2257
  type: UI_REQUEST.REQUEST_INSTALL_APP,
1571
- payload: { vendor: "ledger", appName }
2258
+ payload: { vendor: "ledger", appName, operationId }
1572
2259
  });
1573
2260
  try {
1574
- const payload = await waitPromise;
2261
+ const payload = await this._awaitUiAnswer(
2262
+ UI_REQUEST.REQUEST_INSTALL_APP,
2263
+ waitPromise,
2264
+ signal
2265
+ );
1575
2266
  return !!payload?.confirmed;
1576
2267
  } catch (err) {
1577
2268
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1584,16 +2275,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1584
2275
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
1585
2276
  // `_doConnect` runs under its own internal controller so caller A's cancel
1586
2277
  // doesn't kill caller B's await.
1587
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2278
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1588
2279
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
1589
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2280
+ this._assertConnectorReady("connectDevice");
2281
+ if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1590
2282
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1591
2283
  code: HardwareErrorCode3.DeviceNotFound
1592
2284
  });
1593
2285
  }
1594
2286
  if (connectId && this._sessions.has(connectId)) return connectId;
1595
2287
  if (!connectId && this._sessions.size > 0) {
1596
- if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2288
+ if (!this._isBleConnection() && this._sessions.size > 1) {
1597
2289
  throw Object.assign(
1598
2290
  new Error(
1599
2291
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -1603,15 +2295,24 @@ var _LedgerAdapter = class _LedgerAdapter {
1603
2295
  }
1604
2296
  return this._sessions.keys().next().value;
1605
2297
  }
1606
- if (!this._connectingPromise) {
1607
- this._doConnectAbortController = new AbortController();
1608
- const innerSignal = this._doConnectAbortController.signal;
2298
+ if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2299
+ const controller = new AbortController();
2300
+ this._doConnectAbortController = controller;
2301
+ const innerSignal = controller.signal;
1609
2302
  this._connectingPromise = (async () => {
1610
2303
  try {
1611
- return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2304
+ return await this._doConnect(
2305
+ innerSignal,
2306
+ connectId,
2307
+ allowUsbEphemeralFallback,
2308
+ preserveOperationId,
2309
+ context
2310
+ );
1612
2311
  } finally {
1613
- this._connectingPromise = null;
1614
- this._doConnectAbortController = null;
2312
+ if (this._doConnectAbortController === controller) {
2313
+ this._connectingPromise = null;
2314
+ this._doConnectAbortController = null;
2315
+ }
1615
2316
  }
1616
2317
  })();
1617
2318
  }
@@ -1620,22 +2321,57 @@ var _LedgerAdapter = class _LedgerAdapter {
1620
2321
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
1621
2322
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
1622
2323
  // throw DeviceNotFound so the user is kicked out of the loop.
1623
- async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
1624
- if (isLedgerBleConnectionType(this.connector.connectionType) && targetConnectId) {
1625
- try {
1626
- return await this._connectDeviceOrThrow(targetConnectId);
1627
- } catch (err) {
1628
- if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
1629
- throw err;
1630
- }
1631
- this._discoveredDevices.delete(targetConnectId);
1632
- if (isDeviceDisconnectedError(err)) {
1633
- try {
1634
- this.connector.reset?.();
1635
- } catch {
1636
- }
1637
- }
2324
+ async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2325
+ _LedgerAdapter._throwIfAborted(internalSignal);
2326
+ if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2327
+ this._activeConnectionType = "usb";
2328
+ const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2329
+ _LedgerAdapter._throwIfAborted(internalSignal);
2330
+ const knownUsb = context?.knownConnections?.find(
2331
+ (connection) => connection.transport === "usb"
2332
+ );
2333
+ const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2334
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2335
+ return this._connectFirstOrSelect(
2336
+ usbDevices,
2337
+ usbTarget,
2338
+ allowUsbEphemeralFallback,
2339
+ preserveOperationId,
2340
+ context,
2341
+ internalSignal
2342
+ );
1638
2343
  }
2344
+ if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2345
+ throw createHwkError({
2346
+ code: HardwareErrorCode3.DeviceNotFound,
2347
+ message: "This Ledger model has no Bluetooth transport; connect it over USB"
2348
+ });
2349
+ }
2350
+ this._activeConnectionType = "ble";
2351
+ const knownBle = context?.knownConnections?.find(
2352
+ (connection) => connection.transport === "ble"
2353
+ );
2354
+ if (knownBle?.transport === "ble") {
2355
+ return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2356
+ }
2357
+ if (targetConnectId && context?.knownConnections === void 0) {
2358
+ throw createHwkError({
2359
+ code: HardwareErrorCode3.DeviceNotFound,
2360
+ message: "Ledger connection metadata is required before starting Bluetooth binding"
2361
+ });
2362
+ }
2363
+ const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2364
+ return this._connectFirstOrSelect(
2365
+ bleDevices,
2366
+ void 0,
2367
+ allowUsbEphemeralFallback,
2368
+ preserveOperationId,
2369
+ context,
2370
+ internalSignal
2371
+ );
2372
+ }
2373
+ if (this._isBleConnection() && targetConnectId) {
2374
+ return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
1639
2375
  }
1640
2376
  let confirms = 0;
1641
2377
  while (!internalSignal.aborted) {
@@ -1643,22 +2379,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1643
2379
  type: EConnectorInteraction.Searching,
1644
2380
  payload: { sessionId: "" }
1645
2381
  });
1646
- let devices = await this.searchDevices();
2382
+ let devices = await this._searchDevices(void 0, internalSignal);
2383
+ _LedgerAdapter._throwIfAborted(internalSignal);
1647
2384
  if (devices.length === 0) {
1648
2385
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
1649
2386
  await new Promise((resolve) => {
1650
2387
  setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
1651
2388
  });
1652
- devices = await this.searchDevices();
2389
+ _LedgerAdapter._throwIfAborted(internalSignal);
2390
+ devices = await this._searchDevices(void 0, internalSignal);
2391
+ _LedgerAdapter._throwIfAborted(internalSignal);
1653
2392
  if (devices.length > 0) break;
1654
2393
  }
1655
2394
  }
1656
- if (devices.length > 0) {
2395
+ if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1657
2396
  try {
1658
2397
  return await this._connectFirstOrSelect(
1659
2398
  devices,
1660
2399
  targetConnectId,
1661
- allowUsbEphemeralFallback
2400
+ allowUsbEphemeralFallback,
2401
+ preserveOperationId,
2402
+ context,
2403
+ internalSignal
1662
2404
  );
1663
2405
  } catch (err) {
1664
2406
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -1687,45 +2429,147 @@ var _LedgerAdapter = class _LedgerAdapter {
1687
2429
  _LedgerAdapter._throwIfAborted(internalSignal);
1688
2430
  throw new Error("_doConnect aborted");
1689
2431
  }
1690
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2432
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2433
+ _LedgerAdapter._throwIfAborted(signal);
1691
2434
  if (targetConnectId) {
1692
2435
  const target = devices.find(
1693
2436
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
1694
2437
  );
1695
2438
  if (target) {
1696
- return this._connectDeviceOrThrow(target.connectId);
2439
+ return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1697
2440
  }
1698
- if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2441
+ if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1699
2442
  debugLog(
1700
2443
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
1701
2444
  );
1702
- return this._connectDeviceOrThrow(devices[0].connectId);
2445
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1703
2446
  }
1704
- const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
1705
- code: HardwareErrorCode3.DeviceNotFound
1706
- });
1707
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
1708
- err._tag = ERROR_TAG.DeviceNotAdvertising;
2447
+ if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2448
+ const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2449
+ code: HardwareErrorCode3.DeviceNotFound
2450
+ });
2451
+ if (this._isBleConnection()) {
2452
+ err._tag = ERROR_TAG.DeviceNotAdvertising;
2453
+ }
2454
+ throw err;
1709
2455
  }
1710
- throw err;
1711
2456
  }
1712
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
2457
+ const requiresBleSelection = this._isBleConnection();
2458
+ if (requiresBleSelection && !allowUsbEphemeralFallback) {
1713
2459
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1714
2460
  code: HardwareErrorCode3.DeviceNotFound
1715
2461
  });
1716
2462
  }
1717
- if (devices.length > 1) {
1718
- throw createMultipleUsbLedgerDevicesError();
2463
+ if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2464
+ const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2465
+ if (context) context.bindingSessionId = bindingSessionId;
2466
+ const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2467
+ const knownUsb = context?.knownConnections?.find(
2468
+ (connection) => connection.transport === "usb"
2469
+ );
2470
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2471
+ const { device, requestId } = await requestBleDeviceSelection({
2472
+ emitter: this.emitter,
2473
+ registry: this._uiRegistry,
2474
+ signal,
2475
+ allowUsbFallback,
2476
+ scan: async () => {
2477
+ if (allowUsbFallback) {
2478
+ const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2479
+ const candidate = usbDevices.find(
2480
+ (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2481
+ ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2482
+ if (candidate) return [candidate];
2483
+ }
2484
+ return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2485
+ },
2486
+ request: {
2487
+ devices,
2488
+ bindingSessionId,
2489
+ context: {
2490
+ kind: "bind-connection",
2491
+ transport: "ble",
2492
+ reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2493
+ },
2494
+ extra: context?.extra,
2495
+ operationId: preserveOperationId
2496
+ }
2497
+ });
2498
+ if (device.connectionType === "usb") {
2499
+ this._activeConnectionType = "usb";
2500
+ if (context) context.selectedConnection = void 0;
2501
+ this._bindingSelectionRequestId = requestId;
2502
+ this._finishBleBinding("cancelled");
2503
+ return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2504
+ }
2505
+ this._bindingSelectionRequestId = requestId;
2506
+ const connected = await this._connectDeviceOrThrow(
2507
+ device.connectId,
2508
+ preserveOperationId,
2509
+ signal
2510
+ );
2511
+ if (context) context.selectedConnection = { connectId: connected, requestId };
2512
+ if (context?.deferBindingSave) {
2513
+ context.pendingBinding = { connectId: connected, requestId };
2514
+ } else {
2515
+ await this._saveSelectedBleBinding(
2516
+ connected,
2517
+ requestId,
2518
+ context,
2519
+ preserveOperationId,
2520
+ signal
2521
+ );
2522
+ }
2523
+ return connected;
2524
+ }
2525
+ if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2526
+ if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2527
+ throw createHwkError({
2528
+ code: HardwareErrorCode3.DeviceNotFound,
2529
+ message: "Select a Ledger device before continuing"
2530
+ });
2531
+ }
2532
+ const requestId = this._uiRegistry.createRequestId();
2533
+ const operationId = this._activeOperationId();
2534
+ const waitPromise = this._uiRegistry.wait(
2535
+ UI_REQUEST.REQUEST_SELECT_DEVICE,
2536
+ { requestId, operationId }
2537
+ );
2538
+ this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
2539
+ type: UI_REQUEST.REQUEST_SELECT_DEVICE,
2540
+ payload: {
2541
+ devices,
2542
+ requestId,
2543
+ operationId,
2544
+ context: requiresBleSelection ? {
2545
+ kind: "bind-connection",
2546
+ transport: "ble",
2547
+ reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2548
+ } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2549
+ extra: context?.extra
2550
+ }
2551
+ });
2552
+ const { sdkConnectId } = await this._abortable(signal, waitPromise);
2553
+ _LedgerAdapter._throwIfAborted(signal);
2554
+ const selected = devices.find((device) => device.connectId === sdkConnectId);
2555
+ if (!selected) {
2556
+ throw Object.assign(new Error("Selected Ledger is no longer available"), {
2557
+ code: HardwareErrorCode3.DeviceNotFound
2558
+ });
2559
+ }
2560
+ if (context && requiresBleSelection)
2561
+ context.selectedConnection = { connectId: selected.connectId, requestId };
2562
+ return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1719
2563
  }
1720
2564
  if (devices.length !== 1) {
1721
2565
  throw Object.assign(new Error("Ledger device not found."), {
1722
2566
  code: HardwareErrorCode3.DeviceNotFound
1723
2567
  });
1724
2568
  }
1725
- return this._connectDeviceOrThrow(devices[0].connectId);
2569
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1726
2570
  }
1727
- async _connectDeviceOrThrow(chosenConnectId) {
1728
- const result = await this.connectDevice(chosenConnectId);
2571
+ async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2572
+ const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1729
2573
  if (!result.success) {
1730
2574
  const payload = result.payload;
1731
2575
  const rethrow = Object.assign(new Error(payload.error), {
@@ -1736,16 +2580,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1736
2580
  }
1737
2581
  throw rethrow;
1738
2582
  }
1739
- return chosenConnectId;
2583
+ return result.payload;
1740
2584
  }
1741
- /**
1742
- * Call the connector with automatic session resolution and disconnect retry.
1743
- *
1744
- * 1. Resolves a valid connectId via ensureConnected()
1745
- * 2. Looks up sessionId from _sessions
1746
- * 3. Calls connector.call()
1747
- * 4. On disconnect error: clears stale session, re-connects, retries once
1748
- */
1749
2585
  /**
1750
2586
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
1751
2587
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -1766,33 +2602,145 @@ var _LedgerAdapter = class _LedgerAdapter {
1766
2602
  * lives in one place.
1767
2603
  */
1768
2604
  async _callConnector(sessionId, method, params, signal) {
1769
- const promise = this.connector.call(sessionId, method, params);
2605
+ this._assertConnectorReady(method);
2606
+ if (signal?.aborted) throw this._abortReason(signal);
2607
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2608
+ let promise;
2609
+ try {
2610
+ promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2611
+ } catch (error) {
2612
+ releaseOperation();
2613
+ throw error;
2614
+ }
1770
2615
  const result = signal ? await this._abortable(signal, promise) : await promise;
1771
2616
  return this._unwrapConnectorResult(result);
1772
2617
  }
2618
+ _assertConnectorReady(method) {
2619
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2620
+ throw _LedgerAdapter._createDeviceBusyError(method);
2621
+ }
2622
+ }
2623
+ _runConnectorTeardown(task) {
2624
+ const previous = this._connectorTeardownTail;
2625
+ let releaseTail = () => void 0;
2626
+ this._connectorTeardownTail = new Promise((resolve) => {
2627
+ releaseTail = resolve;
2628
+ });
2629
+ this._pendingConnectorTeardowns += 1;
2630
+ return (async () => {
2631
+ try {
2632
+ await previous;
2633
+ await this._waitForConnectorOperationsToDrain();
2634
+ await task();
2635
+ } finally {
2636
+ this._pendingConnectorTeardowns -= 1;
2637
+ releaseTail();
2638
+ }
2639
+ })();
2640
+ }
2641
+ _waitForConnectorOperationsToDrain() {
2642
+ if (this._unsettledConnectorOperations.size === 0) {
2643
+ return Promise.resolve();
2644
+ }
2645
+ return new Promise((resolve) => {
2646
+ this._connectorIdleWaiters.add(resolve);
2647
+ });
2648
+ }
2649
+ _retainConnectorOperation(key) {
2650
+ this._unsettledConnectorOperations.set(
2651
+ key,
2652
+ (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2653
+ );
2654
+ let released = false;
2655
+ return () => {
2656
+ if (released) return;
2657
+ released = true;
2658
+ const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2659
+ if (remaining > 0) {
2660
+ this._unsettledConnectorOperations.set(key, remaining);
2661
+ } else {
2662
+ this._unsettledConnectorOperations.delete(key);
2663
+ }
2664
+ if (this._unsettledConnectorOperations.size === 0) {
2665
+ for (const resolve of this._connectorIdleWaiters) resolve();
2666
+ this._connectorIdleWaiters.clear();
2667
+ }
2668
+ };
2669
+ }
1773
2670
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1774
- debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1775
- const queueKey = connectId || "__ledger_default__";
2671
+ const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
2672
+ if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2673
+ throw createHwkError({
2674
+ code: HardwareErrorCode3.InvalidParams,
2675
+ message: "Conflicting Ledger operation ids",
2676
+ params: {
2677
+ positionalOperationId,
2678
+ commonOperationId: commonParams.operationId
2679
+ }
2680
+ });
2681
+ }
2682
+ const operationId = commonParams?.operationId ?? positionalOperationId;
2683
+ const operation = operationId ? this._operations.resolve(operationId) : void 0;
2684
+ const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2685
+ const effectiveConnectId = operation?.connectId ?? connectId;
2686
+ debugLog("[LedgerAdapter][REQ]", {
2687
+ method,
2688
+ connectId: effectiveConnectId || "(empty)",
2689
+ params: isSigningMethod(method) ? "[redacted]" : params
2690
+ });
2691
+ const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1776
2692
  try {
1777
2693
  const result = await this._jobQueue.enqueue(
1778
2694
  queueKey,
1779
- async (signal) => this._runConnectorCall(
1780
- connectId,
1781
- method,
1782
- params,
1783
- signal,
1784
- fingerprint,
1785
- permissionDeviceId,
1786
- commonParams,
1787
- installContext
1788
- ),
2695
+ async (signal) => {
2696
+ if (operationId) this._activeOperationJobs.add(operationId);
2697
+ try {
2698
+ return await this._runConnectorCall(
2699
+ effectiveConnectId,
2700
+ method,
2701
+ params,
2702
+ signal,
2703
+ fingerprint,
2704
+ permissionDeviceId,
2705
+ commonParams,
2706
+ installContext ?? {},
2707
+ operationId
2708
+ );
2709
+ } catch (error) {
2710
+ const status = signal.aborted ? "cancelled" : "failed";
2711
+ const bundleConnectId = installContext?.connection?.connectId;
2712
+ let keptBundlePick = false;
2713
+ for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2714
+ if (pickedConnectId === bundleConnectId) {
2715
+ keptBundlePick = true;
2716
+ } else {
2717
+ this._pendingPickBindings.delete(pickedConnectId);
2718
+ this._discardPendingBinding(owner, status);
2719
+ await this._dropSession(pickedConnectId, signal);
2720
+ }
2721
+ }
2722
+ if (!keptBundlePick) this._finishBleBinding(status);
2723
+ throw error;
2724
+ } finally {
2725
+ if (operationId) {
2726
+ this._activeOperationJobs.delete(operationId);
2727
+ if (this._pendingOperationDisconnects.delete(operationId)) {
2728
+ await this._releaseLostOperationConnection(operationId);
2729
+ }
2730
+ }
2731
+ }
2732
+ },
1789
2733
  {
1790
2734
  label: method,
1791
2735
  rejectIfBusy: true,
1792
2736
  busyError: _LedgerAdapter._createDeviceBusyError(method)
1793
2737
  }
1794
2738
  );
1795
- debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2739
+ debugLog("[LedgerAdapter][RES]", {
2740
+ method,
2741
+ success: true,
2742
+ payload: redactResultForLog(result, method)
2743
+ });
1796
2744
  return result;
1797
2745
  } catch (err) {
1798
2746
  const e = err;
@@ -1806,15 +2754,22 @@ var _LedgerAdapter = class _LedgerAdapter {
1806
2754
  }
1807
2755
  });
1808
2756
  throw err;
2757
+ } finally {
2758
+ releaseOperationRetention?.();
1809
2759
  }
1810
2760
  }
2761
+ /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2762
+ _abortReason(signal) {
2763
+ return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2764
+ }
1811
2765
  /**
1812
2766
  * Race a promise against an abort signal. On abort, rejects with
1813
2767
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
1814
2768
  */
1815
2769
  _abortable(signal, promise) {
1816
- const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2770
+ const getAbortReason = () => this._abortReason(signal);
1817
2771
  if (signal.aborted) {
2772
+ void promise.catch(() => void 0);
1818
2773
  return Promise.reject(getAbortReason());
1819
2774
  }
1820
2775
  return new Promise((resolve, reject) => {
@@ -1841,17 +2796,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1841
2796
  }
1842
2797
  }
1843
2798
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
1844
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2799
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1845
2800
  _LedgerAdapter._throwIfAborted(signal);
1846
- await this._ensureDevicePermission(
1847
- connectId,
1848
- permissionDeviceId ?? fingerprint?.deviceId,
1849
- signal
1850
- );
2801
+ if (!operationId) {
2802
+ await this._ensureDevicePermission(
2803
+ connectId,
2804
+ permissionDeviceId ?? fingerprint?.deviceId,
2805
+ signal
2806
+ );
2807
+ }
1851
2808
  _LedgerAdapter._throwIfAborted(signal);
1852
2809
  let effectiveParams = params;
1853
2810
  if (method === "btcGetPublicKey") {
1854
- const gatedParams = await this._gateBtcHighIndex(params);
2811
+ const gatedParams = await this._gateBtcHighIndex(params, signal);
1855
2812
  if (gatedParams === null) {
1856
2813
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
1857
2814
  _tag: ERROR_TAG.UserAborted,
@@ -1861,19 +2818,67 @@ var _LedgerAdapter = class _LedgerAdapter {
1861
2818
  effectiveParams = gatedParams;
1862
2819
  }
1863
2820
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
1864
- const resolvedConnectId = await this.ensureConnected(
1865
- connectId,
2821
+ let businessCallStarted = false;
2822
+ const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2823
+ const knownTransport = this._isBleConnection() ? "ble" : "usb";
2824
+ const hintedConnectId = commonParams?.knownConnections?.find(
2825
+ (connection) => connection.transport === knownTransport
2826
+ );
2827
+ const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2828
+ const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2829
+ const checksWallet = Boolean(
2830
+ fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2831
+ );
2832
+ const connectionAttempt = {
2833
+ ...commonParams,
2834
+ deferBindingSave: checksWallet
2835
+ };
2836
+ const bundleConnection = installContext?.connection;
2837
+ if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2838
+ throw createHwkError({
2839
+ code: HardwareErrorCode3.DeviceDisconnected,
2840
+ message: "Ledger all-network connection ended"
2841
+ });
2842
+ }
2843
+ const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2844
+ preferredConnectId,
1866
2845
  signal,
1867
- allowUsbEphemeralFallback
2846
+ allowUsbEphemeralFallback,
2847
+ void 0,
2848
+ connectionAttempt
1868
2849
  );
2850
+ const walletCheck = installContext?.walletCheck;
2851
+ if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2852
+ throw createHwkError({
2853
+ code: HardwareErrorCode3.DeviceMismatch,
2854
+ message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2855
+ });
2856
+ }
1869
2857
  const sessionId = this._sessions.get(resolvedConnectId);
2858
+ if (sessionId && installContext && !installContext.connection) {
2859
+ installContext.connection = { connectId: resolvedConnectId, sessionId };
2860
+ }
1870
2861
  if (!sessionId) {
2862
+ if (operationId) {
2863
+ this._operations.end(operationId, "disconnect");
2864
+ throw createHwkError({
2865
+ code: HardwareErrorCode3.OperationEnded,
2866
+ message: "Ledger operation connection is no longer active",
2867
+ params: { operationId, reason: "disconnect" }
2868
+ });
2869
+ }
1871
2870
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
1872
2871
  _tag: ERROR_TAG.DeviceSessionNotFound
1873
2872
  });
1874
2873
  }
1875
2874
  try {
1876
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2875
+ const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2876
+ if (!operationId && connectionAttempt.pendingBinding) {
2877
+ this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2878
+ }
2879
+ const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2880
+ const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2881
+ if (fingerprint && checksWallet) {
1877
2882
  const fp = await this._abortable(
1878
2883
  signal,
1879
2884
  this._verifyDeviceFingerprintWithSession(
@@ -1883,14 +2888,68 @@ var _LedgerAdapter = class _LedgerAdapter {
1883
2888
  )
1884
2889
  );
1885
2890
  if (!fp.success) {
2891
+ if (pendingBinding) {
2892
+ this._discardPendingBinding(bindingOwner, "failed");
2893
+ this._pendingPickBindings.delete(resolvedConnectId);
2894
+ }
2895
+ if (operationId) {
2896
+ this._pendingOperationBindings.delete(operationId);
2897
+ this._operations.end(operationId, "explicit");
2898
+ await this._dropSession(resolvedConnectId, signal);
2899
+ }
1886
2900
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
1887
2901
  code: HardwareErrorCode3.DeviceMismatch
1888
2902
  });
1889
2903
  }
2904
+ if (walletCheck) walletCheck.verified = true;
2905
+ }
2906
+ if (pendingBinding && bindingOwner) {
2907
+ bindingOwner.pendingBinding = void 0;
2908
+ if (operationId) this._pendingOperationBindings.delete(operationId);
2909
+ else this._pendingPickBindings.delete(resolvedConnectId);
2910
+ await this._saveSelectedBleBinding(
2911
+ pendingBinding.connectId,
2912
+ pendingBinding.requestId,
2913
+ bindingOwner,
2914
+ operationId,
2915
+ signal,
2916
+ fingerprint && checksWallet ? {
2917
+ vendor: "ledger",
2918
+ type: "chainFingerprint",
2919
+ chain: fingerprint.chain,
2920
+ value: fingerprint.deviceId
2921
+ } : void 0
2922
+ );
1890
2923
  }
1891
- return await this._callConnector(sessionId, method, effectiveParams, signal);
2924
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
2925
+ this._selectedBleReconnectTargets.set(connectId, {
2926
+ connectId: resolvedConnectId,
2927
+ chain: fingerprint.chain,
2928
+ fingerprint: fingerprint.deviceId
2929
+ });
2930
+ }
2931
+ businessCallStarted = true;
2932
+ const result = await this._callConnector(sessionId, method, effectiveParams, signal);
2933
+ if (walletCheck) walletCheck.derived = true;
2934
+ return result;
1892
2935
  } catch (err) {
1893
2936
  if (signal.aborted) throw err;
2937
+ if (isLostConnectionError(err)) {
2938
+ this._discoveredDevices.delete(resolvedConnectId);
2939
+ if (operationId) await this._releaseLostOperationConnection(operationId);
2940
+ else {
2941
+ this._sessions.delete(resolvedConnectId);
2942
+ await this.connector.disconnect(sessionId).catch(() => void 0);
2943
+ }
2944
+ const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
2945
+ const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
2946
+ throw createHwkError({
2947
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
2948
+ message: "Ledger operation connection was lost; start a new operation",
2949
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
2950
+ recovery: ambiguous ? { scope: "unknown" } : void 0
2951
+ });
2952
+ }
1894
2953
  const errObj = err;
1895
2954
  debugLog("[LedgerAdapter] connectorCall error:", method, {
1896
2955
  message: errObj?.message,
@@ -1902,6 +2961,64 @@ var _LedgerAdapter = class _LedgerAdapter {
1902
2961
  isNotAdvertising: isDeviceNotAdvertisingError(err),
1903
2962
  isStuckApp: isStuckAppStateError(err)
1904
2963
  });
2964
+ const assertSessionCurrent = (message) => {
2965
+ if (this._sessions.get(resolvedConnectId) === sessionId) return;
2966
+ throw createHwkError({
2967
+ code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
2968
+ message
2969
+ });
2970
+ };
2971
+ if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
2972
+ await this._waitForDeviceConnect(signal);
2973
+ assertSessionCurrent("Ledger connection ended while waiting for unlock");
2974
+ if (walletCheck?.derived) walletCheck.verified = false;
2975
+ return this._runConnectorCall(
2976
+ resolvedConnectId,
2977
+ method,
2978
+ effectiveParams,
2979
+ signal,
2980
+ fingerprint,
2981
+ permissionDeviceId,
2982
+ commonParams,
2983
+ installContext,
2984
+ operationId,
2985
+ lockedRetryBudget - 1
2986
+ );
2987
+ }
2988
+ if (businessCallStarted && isStuckAppStateError(err)) {
2989
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
2990
+ assertSessionCurrent("Ledger connection ended during the app transition");
2991
+ try {
2992
+ const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
2993
+ if (walletCheck) walletCheck.derived = true;
2994
+ return retried;
2995
+ } catch (retryErr) {
2996
+ if (isStuckAppStateError(retryErr)) throw err;
2997
+ if (isLostConnectionError(retryErr)) {
2998
+ if (operationId) await this._releaseLostOperationConnection(operationId);
2999
+ else {
3000
+ this._sessions.delete(resolvedConnectId);
3001
+ this._discoveredDevices.delete(resolvedConnectId);
3002
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3003
+ }
3004
+ const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
3005
+ throw createHwkError({
3006
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
3007
+ message: `Ledger ${method} may have completed before the connection was lost`,
3008
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3009
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3010
+ });
3011
+ }
3012
+ throw retryErr;
3013
+ }
3014
+ }
3015
+ if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
3016
+ this._sessions.delete(resolvedConnectId);
3017
+ this._sessionTransports.delete(sessionId);
3018
+ this._discoveredDevices.delete(resolvedConnectId);
3019
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3020
+ throw err;
3021
+ }
1905
3022
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
1906
3023
  const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
1907
3024
  if (autoInstallApp && isAppMissing) {
@@ -1918,7 +3035,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1918
3035
  appName
1919
3036
  });
1920
3037
  }
1921
- const confirmed = await this._waitForInstallAppConfirm(appName);
3038
+ const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1922
3039
  if (!confirmed) {
1923
3040
  throw createHwkError({
1924
3041
  code: HardwareErrorCode3.UserAborted,
@@ -1957,157 +3074,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1957
3074
  fingerprint,
1958
3075
  permissionDeviceId,
1959
3076
  commonParams,
1960
- installContext
3077
+ installContext,
3078
+ operationId
1961
3079
  );
1962
3080
  }
1963
3081
  }
1964
- if (isStuckAppStateError(err)) {
1965
- try {
1966
- this._sessions.delete(resolvedConnectId);
1967
- this._discoveredDevices.delete(resolvedConnectId);
1968
- this.connector.reset?.();
1969
- } catch {
1970
- }
1971
- debugLog(
1972
- "[LedgerAdapter] stuck-app retry: method=",
1973
- method,
1974
- "delayMs=",
1975
- _LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
1976
- "_tag=",
1977
- err?._tag
1978
- );
1979
- try {
1980
- const retryResult = await this._retryAfterStuckApp(
1981
- resolvedConnectId,
1982
- method,
1983
- effectiveParams,
1984
- signal,
1985
- err,
1986
- fingerprint
1987
- );
1988
- debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
1989
- return retryResult;
1990
- } catch (retryErr) {
1991
- if (signal.aborted) throw retryErr;
1992
- if (isStuckAppStateError(retryErr)) {
1993
- debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
1994
- throw err;
1995
- }
1996
- debugLog(
1997
- "[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
1998
- method,
1999
- "retryErrTag=",
2000
- retryErr?._tag
2001
- );
2002
- throw retryErr;
2003
- }
2004
- }
2005
- if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
2006
- let lastErr = err;
2007
- for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
2008
- if (signal.aborted) throw lastErr;
2009
- try {
2010
- this._sessions.delete(resolvedConnectId);
2011
- this._discoveredDevices.delete(resolvedConnectId);
2012
- if (isDeviceDisconnectedError(lastErr)) {
2013
- try {
2014
- this.connector.reset?.();
2015
- } catch {
2016
- }
2017
- }
2018
- const reConnectId = await this.ensureConnected(
2019
- resolvedConnectId,
2020
- signal,
2021
- allowUsbEphemeralFallback
2022
- );
2023
- const reSessionId = this._sessions.get(reConnectId);
2024
- if (!reSessionId) throw lastErr;
2025
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2026
- const fp = await this._abortable(
2027
- signal,
2028
- this._verifyDeviceFingerprintWithSession(
2029
- reSessionId,
2030
- fingerprint.deviceId,
2031
- fingerprint.chain
2032
- )
2033
- );
2034
- if (!fp.success) {
2035
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2036
- code: HardwareErrorCode3.DeviceMismatch
2037
- });
2038
- }
2039
- }
2040
- return await this._callConnector(reSessionId, method, effectiveParams, signal);
2041
- } catch (retryErr) {
2042
- if (signal.aborted) throw retryErr;
2043
- lastErr = retryErr;
2044
- const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
2045
- if (!canRetry) {
2046
- throw retryErr;
2047
- }
2048
- }
2049
- }
2050
- throw lastErr;
2051
- }
2052
- if (isTimeoutError(err)) {
2053
- debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
2054
- this._discoveredDevices.delete(resolvedConnectId);
2055
- return this._retryWithFreshConnection(
2056
- resolvedConnectId,
2057
- method,
2058
- effectiveParams,
2059
- signal,
2060
- err,
2061
- fingerprint
2062
- );
2063
- }
2064
- if (isConnectionLevelError(err)) {
2065
- debugLog("[LedgerAdapter] connection-level fail-closed reset");
2066
- this._sessions.delete(resolvedConnectId);
2067
- this._discoveredDevices.delete(resolvedConnectId);
2068
- this.connector.reset();
2069
- const codeNum = err?.code;
2070
- throw Object.assign(err, {
2071
- code: codeNum ?? HardwareErrorCode3.DeviceDisconnected
2072
- });
2073
- }
2074
3082
  throw err;
2075
3083
  }
2076
3084
  }
2077
- /**
2078
- * Stuck-app recovery: pause for the device's UI transition, then retry once.
2079
- *
2080
- * Caller has already cleared the session + reset connector. We wait so Stax
2081
- * finishes its post-CloseApp animation, then go through ensureConnected +
2082
- * fingerprint check + call exactly once. Caller decides what to do on a
2083
- * second stuck-app hit.
2084
- */
2085
- async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
2086
- await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
2087
- const retryConnectId = await this.ensureConnected(
2088
- resolvedConnectId,
2089
- signal,
2090
- !!fingerprint?.deviceId && !fingerprint.skipFingerprint
2091
- );
2092
- const retrySessionId = this._sessions.get(retryConnectId);
2093
- if (!retrySessionId) throw originalErr;
2094
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2095
- const fp = await this._abortable(
2096
- signal,
2097
- this._verifyDeviceFingerprintWithSession(
2098
- retrySessionId,
2099
- fingerprint.deviceId,
2100
- fingerprint.chain
2101
- )
2102
- );
2103
- if (!fp.success) {
2104
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2105
- code: HardwareErrorCode3.DeviceMismatch
2106
- });
2107
- }
2108
- }
2109
- return this._callConnector(retrySessionId, method, params, signal);
2110
- }
2111
3085
  _sleepAbortable(ms, signal) {
2112
3086
  return new Promise((resolve, reject) => {
2113
3087
  if (signal.aborted) {
@@ -2126,111 +3100,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2126
3100
  });
2127
3101
  }
2128
3102
  /**
2129
- * Clear stale session, reconnect, and retry the call.
2130
- *
2131
- * Timeout recovery starts with a full connector reset. After an APDU
2132
- * timeout, DMK/transport state may still emit malformed responses; retrying
2133
- * on the same DMK can poison the next chain switch.
2134
- */
2135
- async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
2136
- this.connector.reset();
2137
- this._sessions.clear();
2138
- this._discoveredDevices.clear();
2139
- this._connectingPromise = null;
2140
- const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
2141
- const retryConnectId = await this.ensureConnected(
2142
- targetConnectId,
2143
- signal,
2144
- allowUsbEphemeralFallback
2145
- );
2146
- const retrySessionId = this._sessions.get(retryConnectId);
2147
- if (!retrySessionId) {
2148
- throw originalErr;
2149
- }
2150
- try {
2151
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2152
- const fp = await this._abortable(
2153
- signal,
2154
- this._verifyDeviceFingerprintWithSession(
2155
- retrySessionId,
2156
- fingerprint.deviceId,
2157
- fingerprint.chain
2158
- )
2159
- );
2160
- if (!fp.success) {
2161
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2162
- code: HardwareErrorCode3.DeviceMismatch
2163
- });
2164
- }
2165
- }
2166
- return await this._callConnector(retrySessionId, method, params, signal);
2167
- } catch (retryErr) {
2168
- if (signal.aborted) throw retryErr;
2169
- this.connector.reset();
2170
- this._sessions.clear();
2171
- this._discoveredDevices.clear();
2172
- this._connectingPromise = null;
2173
- if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
2174
- throw retryErr;
2175
- }
2176
- debugLog(
2177
- "[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
2178
- );
2179
- this.connector.reset();
2180
- this._sessions.clear();
2181
- this._discoveredDevices.clear();
2182
- this._connectingPromise = null;
2183
- const finalConnectId = await this.ensureConnected(
2184
- targetConnectId,
2185
- signal,
2186
- allowUsbEphemeralFallback
2187
- );
2188
- const finalSessionId = this._sessions.get(finalConnectId);
2189
- if (!finalSessionId) {
2190
- throw originalErr;
2191
- }
2192
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2193
- const fp = await this._abortable(
2194
- signal,
2195
- this._verifyDeviceFingerprintWithSession(
2196
- finalSessionId,
2197
- fingerprint.deviceId,
2198
- fingerprint.chain
2199
- )
2200
- );
2201
- if (!fp.success) {
2202
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2203
- code: HardwareErrorCode3.DeviceMismatch
2204
- });
2205
- }
2206
- }
2207
- return this._callConnector(finalSessionId, method, params, signal);
2208
- }
2209
- }
2210
- /**
2211
- * Ensure OS-level device permission (Bluetooth / USB) before proceeding.
2212
- *
2213
- * Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
2214
- * `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
2215
- * prompt → user tap" plus a generous margin). If the consumer never wires
2216
- * a handler or never replies, the wait times out and the operation fails
2217
- * fast so scanners/callers don't hang silently.
2218
- *
2219
- * - No connectId (searchDevices): environment-level permission
2220
- * - With connectId (business methods): device-level permission
3103
+ * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3104
+ * replies. Without connectId the request is environment-level, else device-level.
2221
3105
  */
2222
3106
  async _ensureDevicePermission(connectId, deviceId, signal) {
2223
3107
  if (signal?.aborted) {
2224
3108
  _LedgerAdapter._throwIfAborted(signal);
2225
3109
  }
2226
3110
  const transportType = this.activeTransport ?? "hid";
3111
+ const operationId = this._activeOperationId();
2227
3112
  const waitPromise = this._uiRegistry.wait(
2228
3113
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2229
- { timeoutMs: 6e4 }
3114
+ { timeoutMs: 6e4, operationId }
2230
3115
  );
2231
3116
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2232
3117
  type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2233
- payload: { transportType, connectId, deviceId }
3118
+ payload: { transportType, connectId, deviceId, operationId }
2234
3119
  });
2235
3120
  let response;
2236
3121
  const onAbort = () => {
@@ -2276,7 +3161,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2276
3161
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
2277
3162
  const e = err;
2278
3163
  const params = e.code === HardwareErrorCode3.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
2279
- return ledgerFailure(e.code, e.message ?? "Unknown error", e.appName, tag, params);
3164
+ return ledgerFailure(
3165
+ e.code,
3166
+ e.message ?? "Unknown error",
3167
+ e.appName,
3168
+ tag,
3169
+ params,
3170
+ void 0,
3171
+ isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
3172
+ );
2280
3173
  }
2281
3174
  const mapped = mapLedgerError(err);
2282
3175
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -2303,7 +3196,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2303
3196
  deviceId: device.deviceId,
2304
3197
  connectId: device.connectId,
2305
3198
  label: device.name,
2306
- connectionType: this.connector.connectionType,
3199
+ connectionType: device.connectionType ?? this.connector.connectionType,
2307
3200
  rssi: device.rssi,
2308
3201
  isConnectable: device.isConnectable,
2309
3202
  serialNumber: device.serialNumber,
@@ -2329,8 +3222,8 @@ var LedgerAdapter = _LedgerAdapter;
2329
3222
 
2330
3223
  // src/connector/LedgerConnectorBase.ts
2331
3224
  import {
2332
- EConnectorInteraction as EConnectorInteraction4,
2333
- HardwareErrorCode as HardwareErrorCode8,
3225
+ EConnectorInteraction as EConnectorInteraction3,
3226
+ HardwareErrorCode as HardwareErrorCode7,
2334
3227
  isKnownNonTargetHardwareVendor,
2335
3228
  serializeConnectorError
2336
3229
  } from "@onekeyfe/hwk-adapter-core";
@@ -2603,7 +3496,7 @@ var LedgerDeviceManager = class {
2603
3496
 
2604
3497
  // src/signer/SignerManager.ts
2605
3498
  import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
2606
- import { ContextModuleBuilder } from "@ledgerhq/context-module";
3499
+ import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
2607
3500
 
2608
3501
  // src/signer/SignerEth.ts
2609
3502
  import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
@@ -2611,6 +3504,7 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
2611
3504
  // src/signer/deviceActionToPromise.ts
2612
3505
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
2613
3506
  var IDLE_WATCHDOG_MS = 65e3;
3507
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2614
3508
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
2615
3509
  return new Promise((resolve, reject) => {
2616
3510
  let settled = false;
@@ -2798,7 +3692,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
2798
3692
  }
2799
3693
 
2800
3694
  // src/signer/SignerEth.ts
2801
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2802
3695
  var SignerEth = class {
2803
3696
  // eslint-disable-next-line no-useless-constructor, no-empty-function
2804
3697
  constructor(_sdk) {
@@ -2869,7 +3762,7 @@ var SignerManager = class _SignerManager {
2869
3762
  return (args) => new SignerEthBuilder(args);
2870
3763
  }
2871
3764
  static _createContextModule() {
2872
- const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
3765
+ const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2873
3766
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
2874
3767
  }
2875
3768
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -2907,6 +3800,27 @@ function collapseSignerInteraction(interaction) {
2907
3800
  return EConnectorInteraction2.ConfirmOnDevice;
2908
3801
  }
2909
3802
  }
3803
+ function wireSignerToSession(ctx, sessionId, chain, signer) {
3804
+ signer.onInteraction = (interaction) => {
3805
+ debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3806
+ ctx.emit("ui-event", {
3807
+ type: collapseSignerInteraction(interaction),
3808
+ payload: { sessionId }
3809
+ });
3810
+ };
3811
+ signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3812
+ return signer;
3813
+ }
3814
+ async function runSignerCall(ctx, sessionId, call) {
3815
+ try {
3816
+ return await call();
3817
+ } catch (err) {
3818
+ ctx.invalidateSession(sessionId);
3819
+ throw ctx.wrapError(err);
3820
+ } finally {
3821
+ ctx.clearCanceller(sessionId);
3822
+ }
3823
+ }
2910
3824
 
2911
3825
  // src/connector/chains/evm.ts
2912
3826
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3014,7 +3928,6 @@ import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
3014
3928
  function hexToUtf8(hex) {
3015
3929
  return new TextDecoder().decode(hexToBytes2(hex));
3016
3930
  }
3017
- var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3018
3931
  var SignerBtc = class {
3019
3932
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3020
3933
  constructor(_sdk) {
@@ -3028,7 +3941,7 @@ var SignerBtc = class {
3028
3941
  return deviceActionToPromise(
3029
3942
  action,
3030
3943
  this.onInteraction,
3031
- void 0,
3944
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3032
3945
  this.onRegisterCanceller
3033
3946
  );
3034
3947
  }
@@ -3046,7 +3959,7 @@ var SignerBtc = class {
3046
3959
  const result = await deviceActionToPromise(
3047
3960
  action,
3048
3961
  this.onInteraction,
3049
- void 0,
3962
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3050
3963
  this.onRegisterCanceller
3051
3964
  );
3052
3965
  debugLog(
@@ -3082,7 +3995,7 @@ var SignerBtc = class {
3082
3995
  return deviceActionToPromise(
3083
3996
  action,
3084
3997
  this.onInteraction,
3085
- INTERACTIVE_TIMEOUT_MS2,
3998
+ INTERACTIVE_TIMEOUT_MS,
3086
3999
  this.onRegisterCanceller
3087
4000
  );
3088
4001
  }
@@ -3095,7 +4008,7 @@ var SignerBtc = class {
3095
4008
  return deviceActionToPromise(
3096
4009
  action,
3097
4010
  this.onInteraction,
3098
- INTERACTIVE_TIMEOUT_MS2,
4011
+ INTERACTIVE_TIMEOUT_MS,
3099
4012
  this.onRegisterCanceller
3100
4013
  );
3101
4014
  }
@@ -3108,7 +4021,7 @@ var SignerBtc = class {
3108
4021
  return deviceActionToPromise(
3109
4022
  action,
3110
4023
  this.onInteraction,
3111
- INTERACTIVE_TIMEOUT_MS2,
4024
+ INTERACTIVE_TIMEOUT_MS,
3112
4025
  this.onRegisterCanceller
3113
4026
  );
3114
4027
  }
@@ -3131,7 +4044,21 @@ function _purposeToTemplate(purpose, DDT) {
3131
4044
  });
3132
4045
  }
3133
4046
  }
4047
+ function assertBitcoinMainnet(coin) {
4048
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4049
+ throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4050
+ code: HardwareErrorCode5.ChainNotSupported
4051
+ });
4052
+ }
4053
+ }
3134
4054
  async function btcGetAddress(ctx, sessionId, params) {
4055
+ assertBitcoinMainnet(params.coin);
4056
+ if (normalizePath(params.path).split("/").length !== 3) {
4057
+ throw Object.assign(
4058
+ new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4059
+ { code: HardwareErrorCode5.InvalidParams }
4060
+ );
4061
+ }
3135
4062
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3136
4063
  const path = normalizePath(params.path);
3137
4064
  try {
@@ -3162,6 +4089,7 @@ async function btcGetAddress(ctx, sessionId, params) {
3162
4089
  }
3163
4090
  }
3164
4091
  async function btcGetPublicKey(ctx, sessionId, params) {
4092
+ assertBitcoinMainnet(params.coin);
3165
4093
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3166
4094
  const path = normalizePath(params.path);
3167
4095
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -3339,7 +4267,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
3339
4267
  }
3340
4268
 
3341
4269
  // src/connector/chains/sol.ts
3342
- import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
4270
+ import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
4271
+ import bs58 from "bs58";
3343
4272
 
3344
4273
  // src/signer/SignerSol.ts
3345
4274
  var SignerSol = class {
@@ -3357,7 +4286,7 @@ var SignerSol = class {
3357
4286
  return deviceActionToPromise(
3358
4287
  action,
3359
4288
  this.onInteraction,
3360
- void 0,
4289
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3361
4290
  this.onRegisterCanceller
3362
4291
  );
3363
4292
  }
@@ -3369,7 +4298,7 @@ var SignerSol = class {
3369
4298
  return deviceActionToPromise(
3370
4299
  action,
3371
4300
  this.onInteraction,
3372
- void 0,
4301
+ INTERACTIVE_TIMEOUT_MS,
3373
4302
  this.onRegisterCanceller
3374
4303
  );
3375
4304
  }
@@ -3382,7 +4311,7 @@ var SignerSol = class {
3382
4311
  return deviceActionToPromise(
3383
4312
  action,
3384
4313
  this.onInteraction,
3385
- void 0,
4314
+ INTERACTIVE_TIMEOUT_MS,
3386
4315
  this.onRegisterCanceller
3387
4316
  );
3388
4317
  }
@@ -3423,8 +4352,21 @@ async function solSignMessage(ctx, sessionId, params) {
3423
4352
  const path = normalizePath(params.path);
3424
4353
  const messageBytes = hexToBytes3(params.message);
3425
4354
  try {
4355
+ if (params.messageVersion === 1) {
4356
+ const preparedMessage = prepareSolanaOffchainMessageV1({
4357
+ message: messageBytes,
4358
+ requiredSigners: params.requiredSigners
4359
+ });
4360
+ const { SignMessageVersion } = await ctx.importLedgerKit(
4361
+ "@ledgerhq/device-signer-kit-solana"
4362
+ );
4363
+ const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4364
+ version: SignMessageVersion.Raw
4365
+ });
4366
+ return { signature: decodeBase58Signature(result2.signature) };
4367
+ }
3426
4368
  const result = await solSigner.signMessage(path, messageBytes);
3427
- return { signature: result.signature };
4369
+ return { signature: decodeBase58EnvelopeSignature(result.signature) };
3428
4370
  } catch (err) {
3429
4371
  ctx.invalidateSession(sessionId);
3430
4372
  throw ctx.wrapError(err);
@@ -3432,11 +4374,27 @@ async function solSignMessage(ctx, sessionId, params) {
3432
4374
  ctx.clearCanceller(sessionId);
3433
4375
  }
3434
4376
  }
4377
+ function decodeBase58Signature(signature) {
4378
+ const bytes = bs58.decode(signature);
4379
+ if (bytes.length !== 64) {
4380
+ throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4381
+ }
4382
+ return bytesToHex(bytes);
4383
+ }
4384
+ function decodeBase58EnvelopeSignature(envelope) {
4385
+ const bytes = bs58.decode(envelope);
4386
+ if (bytes.length < 65 || bytes[0] !== 1) {
4387
+ throw new Error("Ledger Solana signature envelope is invalid");
4388
+ }
4389
+ return bytesToHex(bytes.subarray(1, 65));
4390
+ }
3435
4391
  async function _createSolSigner(ctx, sessionId) {
3436
4392
  const dmk = await ctx.getOrCreateDmk();
3437
- const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4393
+ const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4394
+ "@ledgerhq/context-module"
4395
+ );
3438
4396
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
3439
- const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4397
+ const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3440
4398
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
3441
4399
  const signer = new SignerSol(sdkSigner);
3442
4400
  signer.onInteraction = (interaction) => {
@@ -3452,361 +4410,147 @@ async function _createSolSigner(ctx, sessionId) {
3452
4410
  return signer;
3453
4411
  }
3454
4412
 
3455
- // src/connector/chains/tron.ts
3456
- import { HardwareErrorCode as HardwareErrorCode7 } from "@onekeyfe/hwk-adapter-core";
3457
- import Trx from "@ledgerhq/hw-app-trx";
3458
-
3459
- // src/connector/chains/legacyChainCall.ts
3460
- import { EConnectorInteraction as EConnectorInteraction3 } from "@onekeyfe/hwk-adapter-core";
4413
+ // src/connector/chains/zcash.ts
4414
+ import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
3461
4415
 
3462
- // src/app/AppManager.ts
3463
- import {
3464
- CloseAppCommand,
3465
- GetAppAndVersionCommand,
3466
- OpenAppCommand,
3467
- isSuccessCommandResult
3468
- } from "@ledgerhq/device-management-kit";
3469
- import { HardwareErrorCode as HardwareErrorCode6 } from "@onekeyfe/hwk-adapter-core";
3470
- var APP_NAME_MAP = {
3471
- ETH: "Ethereum",
3472
- BTC: "Bitcoin",
3473
- SOL: "Solana",
3474
- TRX: "Tron",
3475
- XRP: "XRP",
3476
- ADA: "Cardano",
3477
- DOT: "Polkadot",
3478
- ATOM: "Cosmos"
3479
- };
3480
- var DASHBOARD_APP_NAME = "BOLOS";
3481
- var AppManager = class {
3482
- constructor(dmk, options) {
3483
- this._dmk = dmk;
3484
- this._waitMs = options?.waitMs ?? 1e3;
3485
- this._maxRetries = options?.maxRetries ?? 10;
3486
- }
3487
- /**
3488
- * Return the Ledger app name for a given chain ticker,
3489
- * or undefined if the chain is not supported.
3490
- */
3491
- static getAppName(chain) {
3492
- return APP_NAME_MAP[chain];
3493
- }
3494
- /**
3495
- * Ensure the target app is open on the device identified by `sessionId`.
3496
- *
3497
- * Flow:
3498
- * 1. Check the currently running app.
3499
- * 2. If it is already the target, return immediately.
3500
- * 3. If a different app is running (not dashboard), close it first.
3501
- * 4. Open the target app.
3502
- * 5. Poll until the device confirms the target app is running.
3503
- */
3504
- /**
3505
- * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
3506
- * device is about to display "Open <app>" on screen and wait for the
3507
- * user's button press. UI consumers should show their "open app" prompt
3508
- * in response. NOT called when the target app is already open (no user
3509
- * interaction needed in that case).
3510
- *
3511
- * Important: OpenAppCommand is blocking. It does not resolve until the user
3512
- * has physically confirmed on the device, so anything that runs AFTER
3513
- * `await this._openApp(...)` lands AFTER the prompt is already gone.
3514
- * Hence the callback must fire BEFORE that await.
3515
- */
3516
- async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
3517
- const currentApp = await this._getCurrentApp(sessionId);
3518
- if (currentApp === targetAppName) {
3519
- return;
3520
- }
3521
- if (!this._isDashboard(currentApp)) {
3522
- await this._closeCurrentApp(sessionId);
3523
- await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
3524
- }
3525
- onConfirmOnDevice?.();
3526
- await this._openApp(sessionId, targetAppName);
3527
- await this._waitForApp(sessionId, targetAppName);
4416
+ // src/signer/SignerZcash.ts
4417
+ var SignerZcash = class {
4418
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4419
+ constructor(_sdk) {
4420
+ this._sdk = _sdk;
3528
4421
  }
3529
- // ---------------------------------------------------------------------------
3530
- // Private helpers
3531
- // ---------------------------------------------------------------------------
3532
- async _getCurrentApp(sessionId) {
3533
- const result = await this._dmk.sendCommand({
3534
- sessionId,
3535
- command: new GetAppAndVersionCommand()
3536
- });
3537
- if (isSuccessCommandResult(result)) {
3538
- debugLog("[AppManager] currentApp:", result.data.name);
3539
- return result.data.name;
3540
- }
3541
- const errResult = result;
3542
- const dmkErr = errResult.error ?? {};
3543
- const original = dmkErr.originalError;
3544
- debugLog(
3545
- "[AppManager] _getCurrentApp failed sessionId=",
3546
- sessionId,
3547
- "tag=",
3548
- dmkErr._tag,
3549
- "errorCode=",
3550
- dmkErr.errorCode,
3551
- "message=",
3552
- dmkErr.message,
3553
- "originalErrorMessage=",
3554
- original?.message ?? String(original ?? "")
3555
- );
3556
- throw Object.assign(
3557
- new Error(
3558
- dmkErr.message ?? "Failed to get current app from device"
3559
- ),
3560
- {
3561
- _tag: dmkErr._tag,
3562
- errorCode: dmkErr.errorCode,
3563
- originalError: original
3564
- }
4422
+ /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4423
+ async getFullViewingKey(derivationPath, options) {
4424
+ const action = this._sdk.getFullViewingKey(derivationPath, options);
4425
+ return deviceActionToPromise(
4426
+ action,
4427
+ this.onInteraction,
4428
+ void 0,
4429
+ this.onRegisterCanceller
3565
4430
  );
3566
4431
  }
3567
- async _openApp(sessionId, appName) {
3568
- const result = await this._dmk.sendCommand({
3569
- sessionId,
3570
- command: new OpenAppCommand({ appName })
3571
- });
3572
- if (!isSuccessCommandResult(result)) {
3573
- const dmkErr = result.error;
3574
- const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
3575
- const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
3576
- debugLog(
3577
- "[AppManager] openApp failed:",
3578
- appName,
3579
- "errorCode:",
3580
- errorCode,
3581
- "tag:",
3582
- dmkErr._tag
3583
- );
3584
- let code;
3585
- if (errorCode === "6807" || /unknown application/i.test(message)) {
3586
- code = HardwareErrorCode6.AppNotInstalled;
3587
- } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
3588
- code = HardwareErrorCode6.UserRejected;
3589
- }
3590
- throw Object.assign(new Error(`Failed to open "${appName}"`), {
3591
- _tag: ERROR_TAG.OpenAppCommand,
3592
- code,
3593
- errorCode,
3594
- statusCode: errorCode,
3595
- appName,
3596
- originalError: dmkErr
3597
- });
3598
- }
3599
- }
3600
- async _closeCurrentApp(sessionId) {
3601
- debugLog("[AppManager] closeCurrentApp");
3602
- await this._dmk.sendCommand({
3603
- sessionId,
3604
- command: new CloseAppCommand()
3605
- });
3606
- }
3607
- /**
3608
- * Poll the device until the expected app is reported as running,
3609
- * or throw after `_maxRetries` attempts.
3610
- */
3611
- async _waitForApp(sessionId, expectedAppName) {
3612
- let lastSeen = "";
3613
- for (let i = 0; i < this._maxRetries; i++) {
3614
- await this._wait();
3615
- const current = await this._getCurrentApp(sessionId);
3616
- lastSeen = current;
3617
- if (current === expectedAppName) {
3618
- return;
3619
- }
3620
- }
3621
- debugLog(
3622
- "[AppManager] waitForApp exhausted: expected=",
3623
- expectedAppName,
3624
- "lastSeen=",
3625
- lastSeen
3626
- );
3627
- throw new Error(
3628
- `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
4432
+ /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4433
+ async getShieldedAddress(derivationPath, options) {
4434
+ const action = this._sdk.getShieldedAddress(derivationPath, options);
4435
+ return deviceActionToPromise(
4436
+ action,
4437
+ this.onInteraction,
4438
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4439
+ this.onRegisterCanceller
3629
4440
  );
3630
4441
  }
3631
- _isDashboard(appName) {
3632
- return appName === DASHBOARD_APP_NAME;
3633
- }
3634
- _wait() {
3635
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3636
- }
3637
4442
  };
3638
4443
 
3639
- // src/connector/chains/legacyChainCall.ts
3640
- function isLegacyWrongAppError(err, _appName) {
3641
- return isWrongAppError(err);
4444
+ // src/connector/chains/zcash.ts
4445
+ async function zcashGetFullViewingKey(ctx, sessionId, params) {
4446
+ const signer = await _createZcashSigner(ctx, sessionId);
4447
+ const path = normalizePath(params.path);
4448
+ const mode = params.mode ?? "ufvk";
4449
+ return runSignerCall(ctx, sessionId, async () => {
4450
+ const result = await signer.getFullViewingKey(path, { mode });
4451
+ if (result.mode === "ufvk") {
4452
+ return { path: params.path, mode, ufvk: result.fullViewingKey };
4453
+ }
4454
+ return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
4455
+ });
3642
4456
  }
3643
- async function withLegacyChainCall(ctx, sessionId, options, action) {
3644
- const { appName, needsConfirmation } = options;
3645
- let openAppPromptShown = false;
3646
- const onAppOpenPrompt = () => {
3647
- openAppPromptShown = true;
3648
- ctx.emit("ui-event", {
3649
- type: EConnectorInteraction3.ConfirmOpenApp,
3650
- payload: { sessionId }
4457
+ async function zcashGetShieldedAddress(ctx, sessionId, params) {
4458
+ const signer = await _createZcashSigner(ctx, sessionId);
4459
+ const path = normalizePath(params.path);
4460
+ return runSignerCall(ctx, sessionId, async () => {
4461
+ const result = await signer.getShieldedAddress(path, {
4462
+ checkOnDevice: params.showOnDevice ?? false
3651
4463
  });
3652
- };
3653
- const closeOpenAppUiIfShown = () => {
3654
- if (openAppPromptShown) {
3655
- ctx.emit("ui-event", {
3656
- type: EConnectorInteraction3.InteractionComplete,
3657
- payload: { sessionId }
3658
- });
3659
- openAppPromptShown = false;
3660
- }
3661
- };
3662
- try {
3663
- await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
3664
- } catch (err) {
3665
- debugLog(
3666
- "[LegacyChainCall] pre-flight ensureAppOpen failed:",
3667
- appName,
3668
- err?.message
3669
- );
3670
- closeOpenAppUiIfShown();
3671
- throw ctx.wrapError(err, { defaultAppName: appName });
3672
- }
3673
- const runOnce = async () => {
3674
- let confirmEmitted = false;
3675
- if (needsConfirmation) {
3676
- ctx.emit("ui-event", {
3677
- type: EConnectorInteraction3.ConfirmOnDevice,
3678
- payload: { sessionId }
3679
- });
3680
- confirmEmitted = true;
3681
- }
3682
- try {
3683
- return await action(sessionId);
3684
- } finally {
3685
- if (confirmEmitted || openAppPromptShown) {
3686
- ctx.emit("ui-event", {
3687
- type: EConnectorInteraction3.InteractionComplete,
3688
- payload: { sessionId }
3689
- });
3690
- openAppPromptShown = false;
3691
- }
3692
- }
3693
- };
3694
- try {
3695
- return await runOnce();
3696
- } catch (err) {
3697
- if (!isLegacyWrongAppError(err, appName)) {
3698
- debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
3699
- ctx.invalidateSession(sessionId);
3700
- throw ctx.wrapError(err, { defaultAppName: appName });
3701
- }
3702
- debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
3703
- try {
3704
- await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
3705
- } catch (switchErr) {
3706
- debugLog(
3707
- "[LegacyChainCall] retry ensureAppOpen failed:",
3708
- appName,
3709
- switchErr?.message
3710
- );
3711
- closeOpenAppUiIfShown();
3712
- throw ctx.wrapError(switchErr, { defaultAppName: appName });
3713
- }
3714
- ctx.clearAllSigners();
3715
- const result = await runOnce();
3716
- debugLog("[LegacyChainCall] retry succeeded:", appName);
3717
- return result;
3718
- }
4464
+ return { address: result.address, path: params.path };
4465
+ });
3719
4466
  }
3720
- async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4467
+ async function _createZcashSigner(ctx, sessionId) {
3721
4468
  const dmk = await ctx.getOrCreateDmk();
3722
- const appManager = new AppManager(dmk);
3723
- await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4469
+ const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4470
+ const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4471
+ return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3724
4472
  }
3725
4473
 
3726
- // src/transport/DmkTransport.ts
3727
- import Transport from "@ledgerhq/hw-transport";
3728
- var DmkTransport = class extends Transport {
3729
- constructor(dmk, sessionId) {
3730
- super();
3731
- this._dmk = dmk;
3732
- this._sessionId = sessionId;
4474
+ // src/connector/chains/tron.ts
4475
+ import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
4476
+
4477
+ // src/signer/SignerTron.ts
4478
+ var SignerTron = class {
4479
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4480
+ constructor(_sdk) {
4481
+ this._sdk = _sdk;
4482
+ }
4483
+ /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4484
+ async getAddress(derivationPath, options) {
4485
+ const action = this._sdk.getAddress(derivationPath, options);
4486
+ const result = await deviceActionToPromise(
4487
+ action,
4488
+ this.onInteraction,
4489
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4490
+ this.onRegisterCanceller
4491
+ );
4492
+ return { address: result.address, publicKey: result.publicKey };
3733
4493
  }
3734
- async exchange(apdu) {
3735
- const response = await this._dmk.sendApdu({
3736
- sessionId: this._sessionId,
3737
- apdu: new Uint8Array(apdu)
3738
- });
3739
- const { data, statusCode } = response;
3740
- const result = Buffer.alloc(data.length + 2);
3741
- if (data.length > 0) {
3742
- result.set(data, 0);
3743
- }
3744
- result.set(statusCode, data.length);
3745
- return result;
4494
+ /** Sign a protobuf-encoded raw transaction. */
4495
+ async signTransaction(derivationPath, transaction, options) {
4496
+ const action = this._sdk.signTransaction(derivationPath, transaction, options);
4497
+ return deviceActionToPromise(
4498
+ action,
4499
+ this.onInteraction,
4500
+ INTERACTIVE_TIMEOUT_MS,
4501
+ this.onRegisterCanceller
4502
+ );
3746
4503
  }
3747
- async close() {
4504
+ /** Sign a personal message (TIP-191). */
4505
+ async signPersonalMessage(derivationPath, message, options) {
4506
+ const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4507
+ return deviceActionToPromise(
4508
+ action,
4509
+ this.onInteraction,
4510
+ INTERACTIVE_TIMEOUT_MS,
4511
+ this.onRegisterCanceller
4512
+ );
3748
4513
  }
3749
4514
  };
3750
4515
 
3751
4516
  // src/connector/chains/tron.ts
3752
4517
  async function tronGetAddress(ctx, sessionId, params) {
4518
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3753
4519
  const path = normalizePath(params.path);
3754
- const showOnDevice = params.showOnDevice ?? false;
3755
- return withLegacyChainCall(
3756
- ctx,
3757
- sessionId,
3758
- {
3759
- appName: "Tron",
3760
- // Only show "confirm on device" UI when the device is actually going
3761
- // to display the address for the user to verify.
3762
- needsConfirmation: showOnDevice
3763
- },
3764
- async (sid) => {
3765
- const trx = await _createTrx(ctx, sid);
3766
- const result = await trx.getAddress(path, showOnDevice);
3767
- return { address: result.address, publicKey: result.publicKey, path: params.path };
3768
- }
3769
- );
4520
+ return runSignerCall(ctx, sessionId, async () => {
4521
+ const result = await tronSigner.getAddress(path, {
4522
+ checkOnDevice: params.showOnDevice ?? false
4523
+ });
4524
+ return { address: result.address, publicKey: result.publicKey, path: params.path };
4525
+ });
3770
4526
  }
3771
4527
  async function tronSignTransaction(ctx, sessionId, params) {
3772
4528
  if (!params.rawTxHex) {
3773
4529
  throw Object.assign(
3774
4530
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
3775
- { code: HardwareErrorCode7.InvalidParams }
4531
+ { code: HardwareErrorCode6.InvalidParams }
3776
4532
  );
3777
4533
  }
4534
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3778
4535
  const path = normalizePath(params.path);
3779
- return withLegacyChainCall(
3780
- ctx,
3781
- sessionId,
3782
- { appName: "Tron", needsConfirmation: true },
3783
- async (sid) => {
3784
- const trx = await _createTrx(ctx, sid);
3785
- const signature = await trx.signTransaction(
3786
- path,
3787
- params.rawTxHex,
3788
- params.tokenSignatures ?? []
3789
- );
3790
- return { signature };
3791
- }
3792
- );
4536
+ return runSignerCall(ctx, sessionId, async () => {
4537
+ const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
4538
+ return { signature: bytesToHex3(signature) };
4539
+ });
3793
4540
  }
3794
4541
  async function tronSignMessage(ctx, sessionId, params) {
4542
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3795
4543
  const path = normalizePath(params.path);
3796
- return withLegacyChainCall(
3797
- ctx,
3798
- sessionId,
3799
- { appName: "Tron", needsConfirmation: true },
3800
- async (sid) => {
3801
- const trx = await _createTrx(ctx, sid);
3802
- const signature = await trx.signPersonalMessage(path, params.messageHex);
3803
- return { signature };
3804
- }
3805
- );
4544
+ return runSignerCall(ctx, sessionId, async () => {
4545
+ const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
4546
+ return { signature: bytesToHex3(signature) };
4547
+ });
3806
4548
  }
3807
- async function _createTrx(ctx, sessionId) {
4549
+ async function _createTronSigner(ctx, sessionId) {
3808
4550
  const dmk = await ctx.getOrCreateDmk();
3809
- return new Trx(new DmkTransport(dmk, sessionId));
4551
+ const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4552
+ const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4553
+ return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3810
4554
  }
3811
4555
 
3812
4556
  // src/device-apps/customActions.ts
@@ -3985,7 +4729,7 @@ var DeviceApps = class {
3985
4729
  seTargetId: v.seTargetId,
3986
4730
  mcuTargetId: v.mcuTargetId,
3987
4731
  seVersion: v.seVersion,
3988
- seFlagsHex: bytesToHex2(v.seFlags),
4732
+ seFlagsHex: bytesToHex4(v.seFlags),
3989
4733
  mcuSephVersion: v.mcuSephVersion,
3990
4734
  mcuBootloaderVersion: v.mcuBootloaderVersion,
3991
4735
  hwVersion: v.hwVersion
@@ -4059,7 +4803,7 @@ var DeviceApps = class {
4059
4803
  }
4060
4804
  }
4061
4805
  };
4062
- function bytesToHex2(bytes) {
4806
+ function bytesToHex4(bytes) {
4063
4807
  if (!bytes) return "";
4064
4808
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4065
4809
  }
@@ -4102,10 +4846,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
4102
4846
  evm: "Ethereum",
4103
4847
  btc: "Bitcoin",
4104
4848
  sol: "Solana",
4105
- tron: "Tron"
4849
+ tron: "Tron",
4850
+ zcash: "Zcash"
4106
4851
  };
4107
4852
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4108
- Object.values(HardwareErrorCode8).filter((value) => typeof value === "number")
4853
+ Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4109
4854
  );
4110
4855
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4111
4856
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4142,6 +4887,10 @@ async function defaultLedgerKitImporter(pkg) {
4142
4887
  return import("@ledgerhq/device-signer-kit-bitcoin");
4143
4888
  case "@ledgerhq/device-signer-kit-solana":
4144
4889
  return import("@ledgerhq/device-signer-kit-solana");
4890
+ case "@ledgerhq/device-signer-kit-tron":
4891
+ return import("@ledgerhq/device-signer-kit-tron");
4892
+ case "@ledgerhq/device-signer-kit-zcash":
4893
+ return import("@ledgerhq/device-signer-kit-zcash");
4145
4894
  case "@ledgerhq/context-module":
4146
4895
  return import("@ledgerhq/context-module");
4147
4896
  default:
@@ -4201,6 +4950,7 @@ var LedgerConnectorBase = class {
4201
4950
  this._ctx = {
4202
4951
  emit: (event, data) => this._emit(event, data),
4203
4952
  invalidateSession: (sid) => this._invalidateSession(sid),
4953
+ teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4204
4954
  wrapError: (err, opts) => this._wrapError(err, opts),
4205
4955
  getOrCreateDmk: () => this._getOrCreateDmk(),
4206
4956
  getDeviceManager: () => this._getDeviceManager(),
@@ -4300,7 +5050,7 @@ var LedgerConnectorBase = class {
4300
5050
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
4301
5051
  );
4302
5052
  err._tag = ERROR_TAG.BlePairingTimeout;
4303
- err.code = HardwareErrorCode8.BlePairingTimeout;
5053
+ err.code = HardwareErrorCode7.BlePairingTimeout;
4304
5054
  reject(err);
4305
5055
  }, HANG_CEILING_MS);
4306
5056
  });
@@ -4333,7 +5083,7 @@ var LedgerConnectorBase = class {
4333
5083
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
4334
5084
  );
4335
5085
  err._tag = ERROR_TAG.DeviceNotAdvertising;
4336
- err.code = HardwareErrorCode8.DeviceNotFound;
5086
+ err.code = HardwareErrorCode7.DeviceNotFound;
4337
5087
  throw err;
4338
5088
  };
4339
5089
  const doConnect = async (path) => {
@@ -4390,14 +5140,14 @@ var LedgerConnectorBase = class {
4390
5140
  this._resetSignersAndSessions();
4391
5141
  if (isLedgerBleConnectionType(this.connectionType)) {
4392
5142
  const tag = err?._tag;
4393
- if (isKnownConnectionTag(tag)) {
5143
+ if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4394
5144
  throw err;
4395
5145
  }
4396
5146
  const wrapped = new Error(
4397
5147
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
4398
5148
  );
4399
5149
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
4400
- wrapped.code = HardwareErrorCode8.BlePairingTimeout;
5150
+ wrapped.code = HardwareErrorCode7.BlePairingTimeout;
4401
5151
  wrapped.originalError = err;
4402
5152
  throw wrapped;
4403
5153
  }
@@ -4475,7 +5225,7 @@ var LedgerConnectorBase = class {
4475
5225
  this._unwatchSessionState(sessionId);
4476
5226
  this._signerManager?.invalidate(sessionId);
4477
5227
  this._cancellers.get(sessionId)?.({
4478
- code: HardwareErrorCode8.DeviceDisconnected,
5228
+ code: HardwareErrorCode7.DeviceDisconnected,
4479
5229
  tag: "DeviceDisconnected",
4480
5230
  message: "Device disconnected"
4481
5231
  });
@@ -4501,7 +5251,7 @@ var LedgerConnectorBase = class {
4501
5251
  success: false,
4502
5252
  error: serializeConnectorError(
4503
5253
  Object.assign(new Error("Ledger app is unresponsive"), {
4504
- code: HardwareErrorCode8.DeviceAppStuck,
5254
+ code: HardwareErrorCode7.DeviceAppStuck,
4505
5255
  _tag: ERROR_TAG.DeviceAppStuck,
4506
5256
  originalError: err
4507
5257
  })
@@ -4513,7 +5263,7 @@ var LedgerConnectorBase = class {
4513
5263
  success: false,
4514
5264
  error: serializeConnectorError(
4515
5265
  Object.assign(new Error("Device communication interrupted, please retry"), {
4516
- code: HardwareErrorCode8.TransportError,
5266
+ code: HardwareErrorCode7.TransportError,
4517
5267
  _tag: ERROR_TAG.DeviceTransportStuck,
4518
5268
  originalError: err
4519
5269
  })
@@ -4559,6 +5309,11 @@ var LedgerConnectorBase = class {
4559
5309
  return solSignTransaction(ctx, sessionId, params);
4560
5310
  case "solSignMessage":
4561
5311
  return solSignMessage(ctx, sessionId, params);
5312
+ // ZCASH
5313
+ case "zcashGetFullViewingKey":
5314
+ return zcashGetFullViewingKey(ctx, sessionId, params);
5315
+ case "zcashGetShieldedAddress":
5316
+ return zcashGetShieldedAddress(ctx, sessionId, params);
4562
5317
  // TRON
4563
5318
  case "tronGetAddress":
4564
5319
  return tronGetAddress(ctx, sessionId, params);
@@ -4583,7 +5338,7 @@ var LedgerConnectorBase = class {
4583
5338
  try {
4584
5339
  return await apps.install(p.appName, ({ progress }) => {
4585
5340
  ctx.emit("ui-event", {
4586
- type: EConnectorInteraction4.AppInstallProgress,
5341
+ type: EConnectorInteraction3.AppInstallProgress,
4587
5342
  payload: {
4588
5343
  sessionId,
4589
5344
  appName: p.appName,
@@ -4592,7 +5347,7 @@ var LedgerConnectorBase = class {
4592
5347
  });
4593
5348
  });
4594
5349
  } catch (err) {
4595
- ctx.invalidateSession(sessionId);
5350
+ ctx.teardownSecureChannelSession(sessionId);
4596
5351
  throw ctx.wrapError(err);
4597
5352
  } finally {
4598
5353
  ctx.clearCanceller(sessionId);
@@ -4682,7 +5437,7 @@ var LedgerConnectorBase = class {
4682
5437
  );
4683
5438
  return { isGenuine: output.isGenuine, deviceId };
4684
5439
  } catch (err) {
4685
- ctx.invalidateSession(sessionId);
5440
+ ctx.teardownSecureChannelSession(sessionId);
4686
5441
  throw ctx.wrapError(err);
4687
5442
  } finally {
4688
5443
  ctx.clearCanceller(sessionId);
@@ -4804,6 +5559,17 @@ var LedgerConnectorBase = class {
4804
5559
  _invalidateSession(sessionId) {
4805
5560
  this._signerManager?.invalidate(sessionId);
4806
5561
  }
5562
+ _teardownSecureChannelSession(sessionId) {
5563
+ const cancel = this._cancellers.get(sessionId);
5564
+ this._cancellers.delete(sessionId);
5565
+ if (cancel) {
5566
+ try {
5567
+ cancel();
5568
+ } catch {
5569
+ }
5570
+ }
5571
+ this._invalidateSession(sessionId);
5572
+ }
4807
5573
  /**
4808
5574
  * Replace an old session with a new one after app switch.
4809
5575
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -4888,7 +5654,7 @@ var LedgerConnectorBase = class {
4888
5654
  * at every catch site. Falls through unchanged for unknown methods.
4889
5655
  */
4890
5656
  _ctxForMethod(method) {
4891
- const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5657
+ const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4892
5658
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
4893
5659
  if (!defaultAppName) return this._ctx;
4894
5660
  return {
@@ -4922,6 +5688,209 @@ var LedgerConnectorBase = class {
4922
5688
  return error;
4923
5689
  }
4924
5690
  };
5691
+
5692
+ // src/transport/DmkTransport.ts
5693
+ import Transport from "@ledgerhq/hw-transport";
5694
+ var DmkTransport = class extends Transport {
5695
+ constructor(dmk, sessionId) {
5696
+ super();
5697
+ this._dmk = dmk;
5698
+ this._sessionId = sessionId;
5699
+ }
5700
+ async exchange(apdu) {
5701
+ const response = await this._dmk.sendApdu({
5702
+ sessionId: this._sessionId,
5703
+ apdu: new Uint8Array(apdu)
5704
+ });
5705
+ const { data, statusCode } = response;
5706
+ const result = Buffer.alloc(data.length + 2);
5707
+ if (data.length > 0) {
5708
+ result.set(data, 0);
5709
+ }
5710
+ result.set(statusCode, data.length);
5711
+ return result;
5712
+ }
5713
+ async close() {
5714
+ }
5715
+ };
5716
+
5717
+ // src/app/AppManager.ts
5718
+ import {
5719
+ CloseAppCommand,
5720
+ GetAppAndVersionCommand,
5721
+ OpenAppCommand,
5722
+ isSuccessCommandResult
5723
+ } from "@ledgerhq/device-management-kit";
5724
+ import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
5725
+ var APP_NAME_MAP = {
5726
+ ETH: "Ethereum",
5727
+ BTC: "Bitcoin",
5728
+ SOL: "Solana",
5729
+ TRX: "Tron",
5730
+ ZEC: "Zcash",
5731
+ XRP: "XRP",
5732
+ ADA: "Cardano",
5733
+ DOT: "Polkadot",
5734
+ ATOM: "Cosmos"
5735
+ };
5736
+ var DASHBOARD_APP_NAME = "BOLOS";
5737
+ var AppManager = class {
5738
+ constructor(dmk, options) {
5739
+ this._dmk = dmk;
5740
+ this._waitMs = options?.waitMs ?? 1e3;
5741
+ this._maxRetries = options?.maxRetries ?? 10;
5742
+ }
5743
+ /**
5744
+ * Return the Ledger app name for a given chain ticker,
5745
+ * or undefined if the chain is not supported.
5746
+ */
5747
+ static getAppName(chain) {
5748
+ return APP_NAME_MAP[chain];
5749
+ }
5750
+ /**
5751
+ * Ensure the target app is open on the device identified by `sessionId`.
5752
+ *
5753
+ * Flow:
5754
+ * 1. Check the currently running app.
5755
+ * 2. If it is already the target, return immediately.
5756
+ * 3. If a different app is running (not dashboard), close it first.
5757
+ * 4. Open the target app.
5758
+ * 5. Poll until the device confirms the target app is running.
5759
+ */
5760
+ /**
5761
+ * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5762
+ * device is about to display "Open <app>" on screen and wait for the
5763
+ * user's button press. UI consumers should show their "open app" prompt
5764
+ * in response. NOT called when the target app is already open (no user
5765
+ * interaction needed in that case).
5766
+ *
5767
+ * Important: OpenAppCommand is blocking. It does not resolve until the user
5768
+ * has physically confirmed on the device, so anything that runs AFTER
5769
+ * `await this._openApp(...)` lands AFTER the prompt is already gone.
5770
+ * Hence the callback must fire BEFORE that await.
5771
+ */
5772
+ async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5773
+ const currentApp = await this._getCurrentApp(sessionId);
5774
+ if (currentApp === targetAppName) {
5775
+ return;
5776
+ }
5777
+ if (!this._isDashboard(currentApp)) {
5778
+ await this._closeCurrentApp(sessionId);
5779
+ await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5780
+ }
5781
+ onConfirmOnDevice?.();
5782
+ await this._openApp(sessionId, targetAppName);
5783
+ await this._waitForApp(sessionId, targetAppName);
5784
+ }
5785
+ // ---------------------------------------------------------------------------
5786
+ // Private helpers
5787
+ // ---------------------------------------------------------------------------
5788
+ async _getCurrentApp(sessionId) {
5789
+ const result = await this._dmk.sendCommand({
5790
+ sessionId,
5791
+ command: new GetAppAndVersionCommand()
5792
+ });
5793
+ if (isSuccessCommandResult(result)) {
5794
+ debugLog("[AppManager] currentApp:", result.data.name);
5795
+ return result.data.name;
5796
+ }
5797
+ const errResult = result;
5798
+ const dmkErr = errResult.error ?? {};
5799
+ const original = dmkErr.originalError;
5800
+ debugLog(
5801
+ "[AppManager] _getCurrentApp failed sessionId=",
5802
+ sessionId,
5803
+ "tag=",
5804
+ dmkErr._tag,
5805
+ "errorCode=",
5806
+ dmkErr.errorCode,
5807
+ "message=",
5808
+ dmkErr.message,
5809
+ "originalErrorMessage=",
5810
+ original?.message ?? String(original ?? "")
5811
+ );
5812
+ throw Object.assign(
5813
+ new Error(
5814
+ dmkErr.message ?? "Failed to get current app from device"
5815
+ ),
5816
+ {
5817
+ _tag: dmkErr._tag,
5818
+ errorCode: dmkErr.errorCode,
5819
+ originalError: original
5820
+ }
5821
+ );
5822
+ }
5823
+ async _openApp(sessionId, appName) {
5824
+ const result = await this._dmk.sendCommand({
5825
+ sessionId,
5826
+ command: new OpenAppCommand({ appName })
5827
+ });
5828
+ if (!isSuccessCommandResult(result)) {
5829
+ const dmkErr = result.error;
5830
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5831
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5832
+ debugLog(
5833
+ "[AppManager] openApp failed:",
5834
+ appName,
5835
+ "errorCode:",
5836
+ errorCode,
5837
+ "tag:",
5838
+ dmkErr._tag
5839
+ );
5840
+ let code;
5841
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
5842
+ code = HardwareErrorCode8.AppNotInstalled;
5843
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5844
+ code = HardwareErrorCode8.UserRejected;
5845
+ }
5846
+ throw Object.assign(new Error(`Failed to open "${appName}"`), {
5847
+ _tag: ERROR_TAG.OpenAppCommand,
5848
+ code,
5849
+ errorCode,
5850
+ statusCode: errorCode,
5851
+ appName,
5852
+ originalError: dmkErr
5853
+ });
5854
+ }
5855
+ }
5856
+ async _closeCurrentApp(sessionId) {
5857
+ debugLog("[AppManager] closeCurrentApp");
5858
+ await this._dmk.sendCommand({
5859
+ sessionId,
5860
+ command: new CloseAppCommand()
5861
+ });
5862
+ }
5863
+ /**
5864
+ * Poll the device until the expected app is reported as running,
5865
+ * or throw after `_maxRetries` attempts.
5866
+ */
5867
+ async _waitForApp(sessionId, expectedAppName) {
5868
+ let lastSeen = "";
5869
+ for (let i = 0; i < this._maxRetries; i++) {
5870
+ await this._wait();
5871
+ const current = await this._getCurrentApp(sessionId);
5872
+ lastSeen = current;
5873
+ if (current === expectedAppName) {
5874
+ return;
5875
+ }
5876
+ }
5877
+ debugLog(
5878
+ "[AppManager] waitForApp exhausted: expected=",
5879
+ expectedAppName,
5880
+ "lastSeen=",
5881
+ lastSeen
5882
+ );
5883
+ throw new Error(
5884
+ `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
5885
+ );
5886
+ }
5887
+ _isDashboard(appName) {
5888
+ return appName === DASHBOARD_APP_NAME;
5889
+ }
5890
+ _wait() {
5891
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
5892
+ }
5893
+ };
4925
5894
  export {
4926
5895
  AppManager,
4927
5896
  DmkTransport,
@@ -4932,6 +5901,7 @@ export {
4932
5901
  SignerEth,
4933
5902
  SignerManager,
4934
5903
  SignerSol,
5904
+ SignerZcash,
4935
5905
  debugLog,
4936
5906
  deviceActionToPromise,
4937
5907
  isDeviceLockedError,