@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.11 → 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.js CHANGED
@@ -39,6 +39,7 @@ __export(index_exports, {
39
39
  SignerEth: () => SignerEth,
40
40
  SignerManager: () => SignerManager,
41
41
  SignerSol: () => SignerSol,
42
+ SignerZcash: () => SignerZcash,
42
43
  debugLog: () => debugLog,
43
44
  deviceActionToPromise: () => deviceActionToPromise,
44
45
  isDeviceLockedError: () => isDeviceLockedError,
@@ -57,17 +58,14 @@ var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
57
58
 
58
59
  // src/errors.ts
59
60
  var import_hwk_adapter_core = require("@onekeyfe/hwk-adapter-core");
60
- var MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE = "Multiple Ledger USB devices are connected. Please connect only one Ledger device and try again.";
61
- function createMultipleUsbLedgerDevicesError() {
62
- return Object.assign(new Error(MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE), {
63
- code: import_hwk_adapter_core.HardwareErrorCode.DeviceOneDeviceOnly
64
- });
65
- }
66
- function ledgerFailure(code, error, appName, tag, params) {
61
+ function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
67
62
  const payload = { error, code };
68
63
  if (appName !== void 0) payload.appName = appName;
69
64
  if (tag !== void 0) payload._tag = tag;
70
65
  if (params !== void 0) payload.params = params;
66
+ const resolvedOrigin = origin ?? (0, import_hwk_adapter_core.defaultOriginForCode)(code);
67
+ if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
68
+ payload.recovery = recovery ?? (0, import_hwk_adapter_core.defaultRecoveryForCode)(code);
71
69
  return { success: false, payload };
72
70
  }
73
71
  var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
@@ -208,7 +206,10 @@ var ERROR_TAG = {
208
206
  UnknownDevice: "UnknownDeviceError",
209
207
  DeviceSessionRefresher: "DeviceSessionRefresherError",
210
208
  DeviceNotInitialized: "DeviceNotInitializedError",
211
- OpeningConnection: "OpeningConnectionError",
209
+ // DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
210
+ // spellings are kept so a DMK release that aligns them still classifies.
211
+ OpeningConnection: "ConnectionOpeningError",
212
+ OpeningConnectionLegacy: "OpeningConnectionError",
212
213
  DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
213
214
  DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
214
215
  Disconnect: "DisconnectError",
@@ -221,7 +222,16 @@ var ERROR_TAG = {
221
222
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
222
223
  WebSocketConnection: "WebSocketConnectionError",
223
224
  HttpFetch: "FetchError",
224
- InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError"
225
+ NetworkDA: "NetworkDAError",
226
+ InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
227
+ ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
228
+ // DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
229
+ // after splitting out device answers, i.e. the relay itself broke.
230
+ SecureChannel: "SecureChannelError",
231
+ RefusedByUserDA: "RefusedByUserDAError",
232
+ AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
233
+ OutOfMemoryDA: "OutOfMemoryDAError",
234
+ DeviceNotOnboarded: "DeviceNotOnboardedError"
225
235
  };
226
236
  function isDeviceLockedError(err) {
227
237
  if (!err || typeof err !== "object") return false;
@@ -251,7 +261,6 @@ function isBlePairingFailureError(err) {
251
261
  return false;
252
262
  }
253
263
  var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
254
- ERROR_TAG.DeviceLocked,
255
264
  ERROR_TAG.DeviceNotAdvertising,
256
265
  ERROR_TAG.BlePairingTimeout,
257
266
  ERROR_TAG.BleGattBondingFailed,
@@ -263,6 +272,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
263
272
  ERROR_TAG.DeviceSessionRefresher,
264
273
  ERROR_TAG.DeviceNotInitialized,
265
274
  ERROR_TAG.OpeningConnection,
275
+ ERROR_TAG.OpeningConnectionLegacy,
266
276
  ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
267
277
  ERROR_TAG.DeviceDisconnectedWhileSending,
268
278
  ERROR_TAG.Disconnect,
@@ -277,7 +287,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
277
287
  // Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
278
288
  ERROR_TAG.DeviceNotInDiscoveryCache
279
289
  ]);
280
- var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OpeningConnection]);
290
+ var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
291
+ ERROR_TAG.OpeningConnection,
292
+ ERROR_TAG.OpeningConnectionLegacy
293
+ ]);
281
294
  var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
282
295
  ERROR_TAG.DeviceNotRecognized,
283
296
  ERROR_TAG.DeviceSessionNotFound,
@@ -289,17 +302,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
289
302
  ERROR_TAG.WebHIDDisconnect
290
303
  ]);
291
304
  function isConnectionLevelError(err) {
292
- if (!err || typeof err !== "object") return false;
293
- const tag = err._tag;
294
- if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
295
- const e = err;
296
- if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
297
- if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
298
- return false;
305
+ return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
299
306
  }
300
307
  function isKnownConnectionTag(tag) {
301
308
  return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
302
309
  }
310
+ var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
311
+ ERROR_TAG.OpeningConnection,
312
+ ERROR_TAG.OpeningConnectionLegacy
313
+ ]);
314
+ function isConnectionOpeningTag(tag) {
315
+ return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
316
+ }
303
317
  function hasStatusCode(err, codeSet) {
304
318
  if (!err || typeof err !== "object") return false;
305
319
  const e = err;
@@ -335,28 +349,28 @@ function hasInvalidArgumentCode(err) {
335
349
  if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
336
350
  return false;
337
351
  }
338
- function isDeviceNotFoundError(err) {
352
+ function hasErrorTag(err, tags) {
339
353
  if (!err || typeof err !== "object") return false;
340
- const tag = err._tag;
341
- if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
342
354
  const e = err;
343
- if (e.originalError != null && isDeviceNotFoundError(e.originalError)) return true;
344
- if (e.error != null && e._tag && isDeviceNotFoundError(e.error)) return true;
355
+ if (typeof e._tag === "string" && tags.has(e._tag)) return true;
356
+ if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
357
+ if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
345
358
  return false;
346
359
  }
360
+ function isDeviceNotFoundError(err) {
361
+ return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
362
+ }
347
363
  function isDeviceBusyError(err) {
348
- if (!err || typeof err !== "object") return false;
349
- const tag = err._tag;
350
- if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
351
- const e = err;
352
- if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
353
- if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
354
- return false;
364
+ return hasErrorTag(err, DEVICE_BUSY_TAGS);
355
365
  }
366
+ var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
367
+ ERROR_TAG.UserRefusedOnDevice,
368
+ ERROR_TAG.RefusedByUserDA
369
+ ]);
356
370
  function isUserRejectedError(err) {
357
371
  if (!err || typeof err !== "object") return false;
358
372
  const e = err;
359
- if (e._tag === ERROR_TAG.UserRefusedOnDevice) return true;
373
+ if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
360
374
  if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
361
375
  if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
362
376
  return false;
@@ -387,15 +401,33 @@ function isAppNotInstalledError(err) {
387
401
  if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
388
402
  return false;
389
403
  }
404
+ var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
390
405
  function isOutOfMemoryError(err) {
391
- if (!err || typeof err !== "object") return false;
392
- const e = err;
393
- return e._tag === "OutOfMemoryDAError";
406
+ return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
407
+ }
408
+ var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
409
+ function isAppAlreadyInstalledError(err) {
410
+ return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
411
+ }
412
+ var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
413
+ function isDeviceNotOnboardedError(err) {
414
+ return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
415
+ }
416
+ var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
417
+ ERROR_TAG.InvalidFirmwareMetadataResponse,
418
+ ERROR_TAG.ApplicationsMetadataTask
419
+ ]);
420
+ function isFirmwareMetadataError(err) {
421
+ return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
422
+ }
423
+ var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
424
+ function isSecureChannelError(err) {
425
+ return hasErrorTag(err, SECURE_CHANNEL_TAGS);
394
426
  }
395
427
  var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
396
428
  ERROR_TAG.WebSocketConnection,
397
429
  ERROR_TAG.HttpFetch,
398
- ERROR_TAG.InvalidFirmwareMetadataResponse
430
+ ERROR_TAG.NetworkDA
399
431
  ]);
400
432
  function isNetworkError(err) {
401
433
  if (!err || typeof err !== "object") return false;
@@ -445,23 +477,34 @@ function isTransportStuck(err) {
445
477
  function isStuckAppStateError(err) {
446
478
  return isAppStuckByApdu(err) || isTransportStuck(err);
447
479
  }
480
+ var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
481
+ function nestedErrorMessage(nested) {
482
+ if (!nested || typeof nested !== "object") return void 0;
483
+ const { message } = nested;
484
+ if (typeof message !== "string") return void 0;
485
+ const trimmed = message.trim();
486
+ if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
487
+ return message;
488
+ }
448
489
  function mapLedgerError(err, opts) {
449
490
  let originalMessage = "Unknown Ledger error";
450
491
  if (err instanceof Error) {
451
492
  originalMessage = err.message;
452
493
  } else if (err && typeof err === "object") {
453
494
  const e = err;
454
- originalMessage = String(e.message ?? e._tag ?? e.type ?? JSON.stringify(err));
495
+ originalMessage = String(
496
+ e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
497
+ );
455
498
  }
456
499
  let code;
457
500
  if (isDeviceLockedError(err)) {
458
501
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceLocked;
459
502
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
460
503
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotFound;
461
- } else if (isDeviceBusyError(err)) {
462
- code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
463
504
  } else if (isBlePairingFailureError(err)) {
464
505
  code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
506
+ } else if (isDeviceBusyError(err)) {
507
+ code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
465
508
  } else if (isUserAbortedError(err)) {
466
509
  code = import_hwk_adapter_core.HardwareErrorCode.UserAborted;
467
510
  } else if (isUserRejectedError(err)) {
@@ -470,10 +513,18 @@ function mapLedgerError(err, opts) {
470
513
  code = import_hwk_adapter_core.HardwareErrorCode.WrongApp;
471
514
  } else if (isAppNotInstalledError(err)) {
472
515
  code = import_hwk_adapter_core.HardwareErrorCode.AppNotInstalled;
516
+ } else if (isAppAlreadyInstalledError(err)) {
517
+ code = import_hwk_adapter_core.HardwareErrorCode.AppAlreadyInstalled;
473
518
  } else if (isOutOfMemoryError(err)) {
474
519
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceOutOfMemory;
520
+ } else if (isDeviceNotOnboardedError(err)) {
521
+ code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotInitialized;
522
+ } else if (isFirmwareMetadataError(err)) {
523
+ code = import_hwk_adapter_core.HardwareErrorCode.LedgerFirmwareMetadataError;
475
524
  } else if (isNetworkError(err)) {
476
525
  code = import_hwk_adapter_core.HardwareErrorCode.NetworkError;
526
+ } else if (isSecureChannelError(err)) {
527
+ code = import_hwk_adapter_core.HardwareErrorCode.LedgerSecureChannelError;
477
528
  } else if (isDeviceDisconnectedError(err)) {
478
529
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceDisconnected;
479
530
  } else if (isTimeoutError(err)) {
@@ -486,7 +537,21 @@ function mapLedgerError(err, opts) {
486
537
  }
487
538
  const errAppName = err && typeof err === "object" ? err.appName : void 0;
488
539
  const appName = errAppName ?? opts?.defaultAppName;
489
- return { code, message: (0, import_hwk_adapter_core.enrichErrorMessage)(code, originalMessage), appName };
540
+ return {
541
+ code,
542
+ message: (0, import_hwk_adapter_core.enrichErrorMessage)(code, originalMessage),
543
+ origin: (0, import_hwk_adapter_core.defaultOriginForCode)(code),
544
+ appName
545
+ };
546
+ }
547
+
548
+ // src/utils/queueKey.ts
549
+ var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
550
+ function ledgerQueueKey({
551
+ operationId,
552
+ connectId
553
+ }) {
554
+ return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
490
555
  }
491
556
 
492
557
  // src/adapter/methods/allNetworkGetAddress.ts
@@ -547,57 +612,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
547
612
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
548
613
  function createAllNetworkGetAddress({
549
614
  callChain,
550
- getChainFingerprint
615
+ getChainFingerprint,
616
+ retainOperation,
617
+ errorToFailure,
618
+ createCancelScope,
619
+ releaseBundle
551
620
  }) {
552
621
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
553
- debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
554
- const installContext = {};
622
+ debugLog("[LedgerAdapter][REQ]", {
623
+ method: "allNetworkGetAddress",
624
+ connectId,
625
+ itemCount: params.bundle.length
626
+ });
627
+ const target = (0, import_hwk_adapter_core2.resolveHardwareOperationTarget)(connectId, params.operationId, "ledger");
628
+ if (!target.success) return target;
629
+ const effectiveTargetId = target.payload.targetId ?? "";
630
+ let releaseOperationRetention;
631
+ try {
632
+ releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
633
+ } catch (error) {
634
+ return errorToFailure(error);
635
+ }
636
+ const cancelScope = createCancelScope(
637
+ ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
638
+ );
639
+ const installContext = {
640
+ walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
641
+ };
555
642
  const commonParams = {
556
- autoInstallApp: params.autoInstallApp
643
+ autoInstallApp: params.autoInstallApp,
644
+ operationId: target.payload.operationId,
645
+ knownConnections: params.knownConnections,
646
+ extra: params.extra,
647
+ allowDeviceSelection: params.allowDeviceSelection,
648
+ supportedTransports: params.supportedTransports
557
649
  };
558
650
  const chainFingerprints = /* @__PURE__ */ new Map();
559
- const result = await (0, import_hwk_adapter_core2.runAllNetworkGetAddress)({
560
- connectId,
561
- deviceId: _deviceId,
562
- params,
563
- normalizeItem: normalizeLedgerAllNetworkItem,
564
- buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
565
- callItem: async ({ method, chain, item }) => {
566
- const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
567
- return callAllNetworkMethod(
568
- callChain,
569
- connectId,
570
- itemDeviceId,
571
- method,
651
+ const order = params.bundle.map((_item, index) => index).sort(
652
+ (a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
653
+ );
654
+ try {
655
+ const ordered = await (0, import_hwk_adapter_core2.runAllNetworkGetAddress)({
656
+ connectId: effectiveTargetId,
657
+ deviceId: _deviceId,
658
+ params: { ...params, bundle: order.map((index) => params.bundle[index]) },
659
+ normalizeItem: normalizeLedgerAllNetworkItem,
660
+ buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
661
+ callItem: async ({ method, chain, item }) => {
662
+ if (cancelScope.signal.aborted)
663
+ return (0, import_hwk_adapter_core2.buildAllNetworkCancelledFailure)(cancelScope.signal);
664
+ const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
665
+ return callAllNetworkMethod(
666
+ callChain,
667
+ effectiveTargetId,
668
+ itemDeviceId,
669
+ method,
670
+ item,
671
+ commonParams,
672
+ installContext
673
+ );
674
+ },
675
+ attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
676
+ getChainFingerprint,
677
+ effectiveTargetId,
572
678
  item,
573
- commonParams,
574
- installContext
575
- );
576
- },
577
- attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
578
- getChainFingerprint,
579
- connectId,
580
- item,
581
- chain,
582
- payload,
583
- chainFingerprints
584
- ),
585
- shouldAbortBundle: isTopLevelAllNetworkFailure,
586
- buildTopLevelFailure: (response) => {
587
- const code = response.payload?.code ?? import_hwk_adapter_core2.HardwareErrorCode.DeviceMismatch;
588
- return (0, import_hwk_adapter_core2.failure)(
589
- code,
590
- response.payload?.error ?? "All-network get-address aborted",
591
- response.payload?.params
592
- );
679
+ chain,
680
+ payload,
681
+ chainFingerprints,
682
+ installContext,
683
+ cancelScope.signal
684
+ ),
685
+ shouldAbortBundle: isTopLevelAllNetworkFailure,
686
+ buildTopLevelFailure: (response) => {
687
+ const code = response.payload?.code ?? import_hwk_adapter_core2.HardwareErrorCode.DeviceMismatch;
688
+ return (0, import_hwk_adapter_core2.failure)(
689
+ code,
690
+ response.payload?.error ?? "All-network get-address aborted",
691
+ response.payload?.params
692
+ );
693
+ }
694
+ });
695
+ let result = ordered;
696
+ if (ordered.success) {
697
+ const responses = [];
698
+ ordered.payload.forEach((response, position) => {
699
+ responses[order[position]] = response;
700
+ });
701
+ result = (0, import_hwk_adapter_core2.success)(responses);
593
702
  }
594
- });
595
- debugLog("[LedgerAdapter][RES]", {
596
- method: "allNetworkGetAddress",
597
- success: result.success,
598
- payload: result
599
- });
600
- return result;
703
+ debugLog("[LedgerAdapter][RES]", {
704
+ method: "allNetworkGetAddress",
705
+ success: result.success,
706
+ payload: result
707
+ });
708
+ return result;
709
+ } finally {
710
+ await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
711
+ cancelScope.release();
712
+ releaseOperationRetention?.();
713
+ }
601
714
  };
602
715
  }
603
716
  function isTopLevelAllNetworkFailure(response) {
@@ -605,7 +718,7 @@ function isTopLevelAllNetworkFailure(response) {
605
718
  return false;
606
719
  }
607
720
  const code = response.payload?.code;
608
- return code === import_hwk_adapter_core2.HardwareErrorCode.DeviceMismatch || code === import_hwk_adapter_core2.HardwareErrorCode.UserAborted || code === import_hwk_adapter_core2.HardwareErrorCode.UserRejected;
721
+ return (0, import_hwk_adapter_core2.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core2.isUserRefusal)(code) || (0, import_hwk_adapter_core2.isConnectionLost)(code);
609
722
  }
610
723
  function getItemDeviceId(item) {
611
724
  const { deviceId } = item;
@@ -635,8 +748,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
635
748
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
636
749
  return coin ? { ...item, coin } : item;
637
750
  }
638
- async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
639
- const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
751
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
752
+ const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
753
+ if (!knownFingerprint && cancelSignal.aborted) {
754
+ const cancelled = (0, import_hwk_adapter_core2.buildAllNetworkCancelledFailure)(cancelSignal);
755
+ return { ...item, success: false, payload: cancelled.payload };
756
+ }
757
+ const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
758
+ getChainFingerprint,
759
+ context.connection?.connectId ?? connectId,
760
+ chain,
761
+ context
762
+ );
640
763
  if (!fingerprint) {
641
764
  return buildFingerprintBootstrapFailure(item, chain);
642
765
  }
@@ -657,8 +780,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
657
780
  }
658
781
  };
659
782
  }
660
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
661
- const response = await getChainFingerprint(connectId, chain);
783
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
784
+ const response = await getChainFingerprint(connectId, chain, context);
662
785
  return response.success ? response.payload : "";
663
786
  }
664
787
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -751,6 +874,20 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
751
874
  function formatDeviceMismatchError(expected, actual) {
752
875
  return `Wrong device: expected ${expected}, got ${actual}`;
753
876
  }
877
+ var LOG_REDACTED_RESULT_KEYS = ["ufvk", "orchardFvk"];
878
+ function isSigningMethod(method) {
879
+ return /sign/i.test(method);
880
+ }
881
+ function redactResultForLog(result, method) {
882
+ if (isSigningMethod(method)) return "[redacted]";
883
+ if (!result || typeof result !== "object") return result;
884
+ const keys = LOG_REDACTED_RESULT_KEYS.filter((key) => key in result);
885
+ if (!keys.length) return result;
886
+ return { ...result, ...Object.fromEntries(keys.map((key) => [key, "[redacted]"])) };
887
+ }
888
+ function isLostConnectionError(err) {
889
+ return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
890
+ }
754
891
  var BTC_HIGH_INDEX_THRESHOLD = 100;
755
892
  function btcAccountIndexFromPath(path) {
756
893
  const segments = path.replace(/^m\//, "").split("/");
@@ -762,9 +899,35 @@ function btcAccountIndexFromPath(path) {
762
899
  var _LedgerAdapter = class _LedgerAdapter {
763
900
  constructor(connector, options) {
764
901
  this.vendor = "ledger";
902
+ // Cancel frees the DMK action and its intent-queue slot, but cannot retract a
903
+ // confirmation screen the device is already showing.
904
+ this.cancelCapability = "stops-waiting";
765
905
  this.emitter = new import_hwk_adapter_core3.TypedEventEmitter();
906
+ this._operations = new import_hwk_adapter_core3.OperationRegistry({
907
+ vendor: "ledger",
908
+ onEnded: (operation, reason) => {
909
+ this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
910
+ this._pendingOperationBindings.delete(operation.operationId);
911
+ this.emitter.emit(import_hwk_adapter_core3.SDK.OPERATION_ENDED, {
912
+ type: import_hwk_adapter_core3.SDK.OPERATION_ENDED,
913
+ payload: { operationId: operation.operationId, reason }
914
+ });
915
+ if (reason === "timeout") {
916
+ void this._releaseOperationConnection(operation);
917
+ }
918
+ }
919
+ });
766
920
  this._discoveredDevices = /* @__PURE__ */ new Map();
767
921
  this._sessions = /* @__PURE__ */ new Map();
922
+ // An operation's BLE pick is saved by its first call that gets past the wallet check.
923
+ this._pendingOperationBindings = /* @__PURE__ */ new Map();
924
+ // A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
925
+ // through an unlock retry; any other failure drops it with its session.
926
+ this._pendingPickBindings = /* @__PURE__ */ new Map();
927
+ // Transport each session was opened on, by sessionId. The adapter-wide
928
+ // `_activeConnectionType` moves with every discovery and can go stale.
929
+ this._sessionTransports = /* @__PURE__ */ new Map();
930
+ this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
768
931
  this._uiRegistry = new import_hwk_adapter_core3.UiRequestRegistry();
769
932
  // BTC App rejects account index >= 100 unless display=true. Cached per
770
933
  // adapter instance: first 100+ path asks the user once via UI request,
@@ -778,21 +941,36 @@ var _LedgerAdapter = class _LedgerAdapter {
778
941
  this._deviceAuthenticityQueueTail = Promise.resolve();
779
942
  // Shared across concurrent callers — only `cancel()` aborts.
780
943
  this._doConnectAbortController = null;
944
+ this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
945
+ this._connectorIdleWaiters = /* @__PURE__ */ new Set();
946
+ this._resetPromise = null;
947
+ this._stateGeneration = 0;
948
+ this._connectorTeardownTail = Promise.resolve();
949
+ this._pendingConnectorTeardowns = 0;
950
+ this._activeOperationJobs = /* @__PURE__ */ new Set();
951
+ this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
781
952
  this._installProgressLastEmittedValue = -Infinity;
782
953
  this.allNetworkGetAddress = createAllNetworkGetAddress({
783
954
  callChain: this.callChain.bind(this),
784
- getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
955
+ getChainFingerprint: async (connectId, chain, context) => {
956
+ try {
957
+ const fingerprint = await this._computeChainFingerprint(
958
+ chain,
959
+ (method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
960
+ );
961
+ return (0, import_hwk_adapter_core3.success)(fingerprint);
962
+ } catch (error) {
963
+ return this.errorToFailure(error);
964
+ }
965
+ },
966
+ retainOperation: (operationId) => this._operations.retain(operationId),
967
+ errorToFailure: (error) => this.errorToFailure(error),
968
+ createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
969
+ releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
785
970
  });
786
971
  // ---------------------------------------------------------------------------
787
972
  // Private helpers
788
973
  // ---------------------------------------------------------------------------
789
- /**
790
- * Ensure at least one device is connected and return a valid connectId.
791
- *
792
- * - If a session already exists for the given connectId, reuse it.
793
- * - If ANY session exists (Ledger IDs are ephemeral), reuse it.
794
- * - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
795
- */
796
974
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
797
975
  this._connectingPromise = null;
798
976
  // ---------------------------------------------------------------------------
@@ -808,6 +986,12 @@ var _LedgerAdapter = class _LedgerAdapter {
808
986
  });
809
987
  };
810
988
  this.deviceDisconnectHandler = (data) => {
989
+ const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
990
+ if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
991
+ this._pendingOperationDisconnects.add(activeOperation.operationId);
992
+ } else {
993
+ this._operations.endByConnectionKey(data.connectId, "disconnect");
994
+ }
811
995
  this._discoveredDevices.delete(data.connectId);
812
996
  this._sessions.delete(data.connectId);
813
997
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.DISCONNECT, {
@@ -816,10 +1000,8 @@ var _LedgerAdapter = class _LedgerAdapter {
816
1000
  });
817
1001
  };
818
1002
  // Forward connector `ui-event` to the public hw.emitter so consumers only
819
- // need to subscribe in one place. For the AppInstallProgress variant we
820
- // re-key sessionId → connectId via the live _sessions map; if no mapping
821
- // exists (race during teardown) we drop. All other variants pass through
822
- // unchanged.
1003
+ // need to subscribe in one place. The AppInstallProgress variant re-keys
1004
+ // sessionId to connectId via `_sessions`, and drops if no mapping exists.
823
1005
  this.uiEventForwarder = (event) => {
824
1006
  if (event.type === import_hwk_adapter_core3.EConnectorInteraction.AppInstallProgress) {
825
1007
  let connectId;
@@ -864,11 +1046,30 @@ var _LedgerAdapter = class _LedgerAdapter {
864
1046
  this._jobQueue = new import_hwk_adapter_core3.DeviceJobQueue();
865
1047
  this.registerEventListeners();
866
1048
  }
1049
+ _discardPendingBinding(owner, status = "cancelled") {
1050
+ const pending = owner?.pendingBinding;
1051
+ if (!owner || !pending) return;
1052
+ owner.pendingBinding = void 0;
1053
+ if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1054
+ }
1055
+ _finishBleBinding(status) {
1056
+ const selectionRequestId = this._bindingSelectionRequestId;
1057
+ this._bindingSelectionRequestId = void 0;
1058
+ if (selectionRequestId) (0, import_hwk_adapter_core3.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
1059
+ }
1060
+ _isBleConnection() {
1061
+ return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1062
+ }
867
1063
  // Transport
868
1064
  get activeTransport() {
869
- return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1065
+ return this._isBleConnection() ? "ble" : "hid";
870
1066
  }
871
1067
  getAvailableTransports() {
1068
+ if (this.connector.availableTransports) {
1069
+ return this.connector.availableTransports.map(
1070
+ (transport) => transport === "ble" ? "ble" : "hid"
1071
+ );
1072
+ }
872
1073
  return this.activeTransport ? [this.activeTransport] : [];
873
1074
  }
874
1075
  // Connector is bound at construction; switching requires a new adapter.
@@ -885,21 +1086,42 @@ var _LedgerAdapter = class _LedgerAdapter {
885
1086
  * The next operation will re-discover and re-connect automatically.
886
1087
  */
887
1088
  resetState() {
1089
+ void this._resetStateAndDisconnectSessions();
1090
+ }
1091
+ _resetStateAndDisconnectSessions() {
1092
+ if (this._resetPromise) return this._resetPromise;
1093
+ const sessionIds = new Set(this._sessions.values());
1094
+ this._stateGeneration += 1;
1095
+ this._finishBleBinding("cancelled");
1096
+ this._operations.endAll("runtime-reset");
1097
+ this._doConnectAbortController?.abort();
888
1098
  this._discoveredDevices.clear();
889
1099
  this._sessions.clear();
1100
+ this._sessionTransports.clear();
1101
+ this._pendingOperationBindings.clear();
1102
+ this._pendingPickBindings.clear();
1103
+ this._selectedBleReconnectTargets.clear();
890
1104
  this._connectingPromise = null;
1105
+ this._doConnectAbortController = null;
891
1106
  this._uiRegistry.reset();
892
1107
  this._jobQueue.clear();
893
1108
  this._btcHighIndexConfirmedThisSession = false;
1109
+ const resetPromise = this._runConnectorTeardown(async () => {
1110
+ for (const sessionId of sessionIds) {
1111
+ await this.connector.disconnect(sessionId).catch(() => void 0);
1112
+ }
1113
+ });
1114
+ this._resetPromise = resetPromise;
1115
+ return resetPromise.finally(() => {
1116
+ if (this._resetPromise === resetPromise) {
1117
+ this._resetPromise = null;
1118
+ }
1119
+ });
894
1120
  }
895
1121
  async dispose() {
896
- this._uiRegistry.reset();
897
- this._jobQueue.clear();
1122
+ await this._resetStateAndDisconnectSessions();
898
1123
  this.unregisterEventListeners();
899
1124
  this.connector.reset();
900
- this._discoveredDevices.clear();
901
- this._sessions.clear();
902
- this._btcHighIndexConfirmedThisSession = false;
903
1125
  this.emitter.removeAllListeners();
904
1126
  }
905
1127
  uiResponse(response) {
@@ -909,17 +1131,32 @@ var _LedgerAdapter = class _LedgerAdapter {
909
1131
  // Device management
910
1132
  // ---------------------------------------------------------------------------
911
1133
  async searchDevices(options) {
1134
+ return this._searchDevices(options);
1135
+ }
1136
+ async _searchDevices(options, signal) {
912
1137
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
913
1138
  try {
914
1139
  if (options?.resetSession) {
915
- this._doConnectAbortController?.abort();
916
- this._sessions.clear();
917
- this._connectingPromise = null;
918
- this._doConnectAbortController = null;
919
- this._btcHighIndexConfirmedThisSession = false;
1140
+ await this._resetStateAndDisconnectSessions();
1141
+ } else {
1142
+ await this._connectorTeardownTail;
1143
+ }
1144
+ await this._ensureDevicePermission(void 0, void 0, signal);
1145
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1146
+ const stateGeneration = this._stateGeneration;
1147
+ const devices = await this.connector.searchDevices(
1148
+ options?.transportType ? {
1149
+ transportType: options.transportType,
1150
+ waitForAll: options.waitForAllTransports
1151
+ } : void 0
1152
+ );
1153
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1154
+ if (stateGeneration !== this._stateGeneration) {
1155
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1156
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
1157
+ message: "Ledger discovery was reset"
1158
+ });
920
1159
  }
921
- await this._ensureDevicePermission();
922
- const devices = await this.connector.searchDevices();
923
1160
  this._discoveredDevices.clear();
924
1161
  for (const d of devices) {
925
1162
  if (d.connectId) {
@@ -927,7 +1164,7 @@ var _LedgerAdapter = class _LedgerAdapter {
927
1164
  }
928
1165
  }
929
1166
  if (this._discoveredDevices.size === 0) {
930
- await this._ensureDevicePermission();
1167
+ await this._ensureDevicePermission(void 0, void 0, signal);
931
1168
  }
932
1169
  const result = Array.from(this._discoveredDevices.values());
933
1170
  debugLog("[LedgerAdapter][RES]", {
@@ -946,41 +1183,263 @@ var _LedgerAdapter = class _LedgerAdapter {
946
1183
  throw err;
947
1184
  }
948
1185
  }
1186
+ async searchDeviceTargets(options) {
1187
+ const devices = await this.searchDevices(options);
1188
+ return devices.map((device) => (0, import_hwk_adapter_core3.toPhysicalDeviceSearchTarget)("ledger", device));
1189
+ }
949
1190
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
950
- async _evictAllSessions() {
1191
+ async _evictAllSessions(preserveOperationId) {
1192
+ this._operations.endAll("explicit", preserveOperationId);
951
1193
  if (this._sessions.size === 0) return;
952
1194
  const stale = [...this._sessions.values()];
953
1195
  this._sessions.clear();
954
- for (const sid of stale) {
955
- try {
956
- await this.connector.disconnect(sid);
957
- } catch {
1196
+ for (const sid of stale) this._sessionTransports.delete(sid);
1197
+ await this._runConnectorTeardown(async () => {
1198
+ for (const sid of stale) {
1199
+ try {
1200
+ await this.connector.disconnect(sid);
1201
+ } catch {
1202
+ }
958
1203
  }
959
- }
1204
+ });
960
1205
  }
961
1206
  static _createDeviceBusyError(method) {
962
1207
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
963
1208
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusy
964
1209
  });
965
1210
  }
966
- async connectDevice(connectId) {
1211
+ async connectDevice(searchTargetId) {
1212
+ try {
1213
+ return await this._jobQueue.enqueue(
1214
+ searchTargetId || "__ledger_connect__",
1215
+ async (signal) => {
1216
+ const connected = await this._connectTarget(searchTargetId, void 0, signal);
1217
+ if (!connected.success) return connected;
1218
+ return this._createOperation(searchTargetId, connected.payload);
1219
+ },
1220
+ {
1221
+ label: "connectDevice",
1222
+ rejectIfBusy: true,
1223
+ busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1224
+ }
1225
+ );
1226
+ } catch (error) {
1227
+ return this.errorToFailure(error);
1228
+ }
1229
+ }
1230
+ /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1231
+ async bindBleDevice(params) {
1232
+ const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1233
+ try {
1234
+ return await this._jobQueue.enqueue(
1235
+ "__ledger_bind_ble__",
1236
+ async (signal) => {
1237
+ if (!this.getAvailableTransports().includes("ble")) {
1238
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1239
+ code: import_hwk_adapter_core3.HardwareErrorCode.TransportNotAvailable,
1240
+ message: "Ledger Bluetooth transport is not available"
1241
+ });
1242
+ }
1243
+ this._activeConnectionType = "ble";
1244
+ await this._ensureDevicePermission(void 0, void 0, signal);
1245
+ const attempt = {
1246
+ extra: params.extra,
1247
+ bindingReason: "manual-rebind",
1248
+ deferBindingSave: Boolean(identity)
1249
+ };
1250
+ try {
1251
+ const connectId = await this._connectFirstOrSelect(
1252
+ [],
1253
+ void 0,
1254
+ true,
1255
+ void 0,
1256
+ attempt,
1257
+ signal
1258
+ );
1259
+ const pending = attempt.pendingBinding;
1260
+ if (identity && pending) {
1261
+ attempt.pendingBinding = void 0;
1262
+ const sessionId = this._sessions.get(connectId);
1263
+ if (!sessionId) {
1264
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1265
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected,
1266
+ message: "Selected Ledger connection ended"
1267
+ });
1268
+ }
1269
+ const fingerprint = await this._computeChainFingerprint(
1270
+ identity.chain,
1271
+ (method, callParams) => this._runConnectorCall(
1272
+ connectId,
1273
+ method,
1274
+ callParams,
1275
+ signal,
1276
+ void 0,
1277
+ void 0,
1278
+ { autoInstallApp: true },
1279
+ { connection: { connectId, sessionId } }
1280
+ )
1281
+ );
1282
+ if (fingerprint !== identity.value) {
1283
+ await this._dropSession(connectId, signal);
1284
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1285
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
1286
+ message: formatDeviceMismatchError(identity.value, fingerprint)
1287
+ });
1288
+ }
1289
+ await this._saveSelectedBleBinding(
1290
+ connectId,
1291
+ pending.requestId,
1292
+ attempt,
1293
+ void 0,
1294
+ signal,
1295
+ identity
1296
+ );
1297
+ }
1298
+ if (!attempt.bindingSaved) {
1299
+ await this._dropSession(connectId, signal);
1300
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1301
+ code: import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
1302
+ message: "Bluetooth binding could not be saved",
1303
+ origin: "host"
1304
+ });
1305
+ }
1306
+ return (0, import_hwk_adapter_core3.success)(connectId);
1307
+ } catch (error) {
1308
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1309
+ throw error;
1310
+ }
1311
+ },
1312
+ {
1313
+ label: "bindBleDevice",
1314
+ rejectIfBusy: true,
1315
+ busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1316
+ }
1317
+ );
1318
+ } catch (error) {
1319
+ return this.errorToFailure(error);
1320
+ }
1321
+ }
1322
+ async acquireOperation(connectId, context) {
1323
+ try {
1324
+ return await this._jobQueue.enqueue(
1325
+ connectId || "__ledger_acquire__",
1326
+ async (signal) => {
1327
+ const transport = this._isBleConnection() ? "ble" : "usb";
1328
+ const hint = context.knownConnections?.find(
1329
+ (connection) => connection.transport === transport
1330
+ );
1331
+ const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1332
+ await this._ensureDevicePermission(target, void 0, signal);
1333
+ const attempt = {
1334
+ ...context,
1335
+ extra: context.extra ? { ...context.extra } : void 0,
1336
+ // The operation's calls decide whether the pick is the right wallet.
1337
+ deferBindingSave: true
1338
+ };
1339
+ try {
1340
+ const resolvedConnectId = await this.ensureConnected(
1341
+ target,
1342
+ signal,
1343
+ true,
1344
+ void 0,
1345
+ attempt
1346
+ );
1347
+ _LedgerAdapter._throwIfAborted(signal);
1348
+ const result = this._createOperation(connectId, resolvedConnectId);
1349
+ if (result.success && attempt.pendingBinding) {
1350
+ this._pendingOperationBindings.set(result.payload, attempt);
1351
+ }
1352
+ return result;
1353
+ } catch (error) {
1354
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1355
+ throw error;
1356
+ }
1357
+ },
1358
+ {
1359
+ label: "acquireOperation",
1360
+ rejectIfBusy: true,
1361
+ busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1362
+ }
1363
+ );
1364
+ } catch (error) {
1365
+ return this.errorToFailure(error);
1366
+ }
1367
+ }
1368
+ _createOperation(searchTargetId, resolvedConnectId) {
1369
+ this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1370
+ const sessionId = this._sessions.get(resolvedConnectId);
1371
+ if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1372
+ const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1373
+ const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1374
+ vendor: "ledger",
1375
+ model: "unknown",
1376
+ firmwareVersion: "",
1377
+ deviceId: "",
1378
+ connectId: resolvedConnectId,
1379
+ connectionType
1380
+ };
1381
+ const operation = this._operations.create({
1382
+ searchTargetId,
1383
+ connectId: resolvedConnectId,
1384
+ device,
1385
+ connectionType,
1386
+ connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
1387
+ });
1388
+ return (0, import_hwk_adapter_core3.success)(operation.operationId);
1389
+ }
1390
+ async _connectTarget(connectId, preserveOperationId, signal) {
967
1391
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
968
1392
  try {
969
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1393
+ this._assertConnectorReady("connectDevice");
1394
+ const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1395
+ if (discoveredType === "usb" || discoveredType === "ble") {
1396
+ this._activeConnectionType = discoveredType;
1397
+ }
1398
+ if (this._isBleConnection() && !connectId) {
970
1399
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
971
1400
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
972
1401
  });
973
1402
  }
974
- if (!isLedgerBleConnectionType(this.connector.connectionType)) {
975
- await this._evictAllSessions();
1403
+ await this._ensureDevicePermission(connectId, void 0, signal);
1404
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1405
+ const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1406
+ if (!isMultiTransport && this._isBleConnection()) {
1407
+ const previousSessionId = this._sessions.get(connectId);
1408
+ this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1409
+ if (previousSessionId) {
1410
+ this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1411
+ this._sessions.delete(connectId);
1412
+ await this.connector.disconnect(previousSessionId).catch(() => void 0);
1413
+ }
1414
+ } else {
1415
+ await this._evictAllSessions(preserveOperationId);
1416
+ }
1417
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1418
+ const stateGeneration = this._stateGeneration;
1419
+ const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1420
+ let session;
1421
+ this._connectingConnectId = connectId;
1422
+ try {
1423
+ session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1424
+ transportType: this._activeConnectionType ?? "usb"
1425
+ }) : await this.connector.connect(connectId);
1426
+ if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1427
+ await this.connector.disconnect(session.sessionId).catch(() => void 0);
1428
+ throw Object.assign(new Error("Ledger connection aborted"), {
1429
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted
1430
+ });
1431
+ }
1432
+ } finally {
1433
+ if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1434
+ releaseOperation();
976
1435
  }
977
- await this._ensureDevicePermission(connectId);
978
- const session = await this.connector.connect(connectId);
979
- this._sessions.set(connectId, session.sessionId);
1436
+ const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1437
+ this._sessions.set(resolvedConnectId, session.sessionId);
1438
+ this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
980
1439
  if (session.deviceInfo) {
981
- this._discoveredDevices.set(connectId, session.deviceInfo);
1440
+ this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
982
1441
  }
983
- const result = (0, import_hwk_adapter_core3.success)(connectId);
1442
+ const result = (0, import_hwk_adapter_core3.success)(resolvedConnectId);
984
1443
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
985
1444
  return result;
986
1445
  } catch (err) {
@@ -993,30 +1452,73 @@ var _LedgerAdapter = class _LedgerAdapter {
993
1452
  return failureResult;
994
1453
  }
995
1454
  }
996
- async disconnectDevice(connectId) {
1455
+ async releaseOperation(operationId) {
1456
+ const operation = this._operations.findActive(operationId);
1457
+ if (operation) this._cancelOperationWork(operation);
1458
+ const endedOperation = this._operations.release(operationId);
1459
+ if (!endedOperation) return;
1460
+ const { connectId } = endedOperation;
997
1461
  debugLog("[LedgerAdapter][REQ]", {
998
- method: "disconnectDevice",
1462
+ method: "releaseOperation",
999
1463
  connectId,
1000
1464
  params: { connectId }
1001
1465
  });
1002
1466
  try {
1003
- const sessionId = this._sessions.get(connectId);
1004
- if (sessionId) {
1005
- await this.connector.disconnect(sessionId);
1006
- this._sessions.delete(connectId);
1007
- }
1008
- debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
1467
+ await this._releaseOperationConnection(endedOperation);
1468
+ debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
1009
1469
  } catch (err) {
1010
1470
  const e = err;
1011
1471
  debugLog("[LedgerAdapter][RES]", {
1012
- method: "disconnectDevice",
1472
+ method: "releaseOperation",
1013
1473
  success: false,
1014
1474
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1015
1475
  });
1016
1476
  throw err;
1017
1477
  }
1018
1478
  }
1019
- async getDeviceInfo(connectId, deviceId) {
1479
+ /**
1480
+ * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1481
+ * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1482
+ */
1483
+ _cancelOperationWork(operation) {
1484
+ const { operationId } = operation;
1485
+ const reason = (0, import_hwk_adapter_core3.createHwkError)({
1486
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
1487
+ message: "Ledger operation was released",
1488
+ params: { operationId, reason: "explicit" }
1489
+ });
1490
+ const queueKey = ledgerQueueKey({ operationId });
1491
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1492
+ this._jobQueue.cancelActiveAndPending(queueKey, reason);
1493
+ if (ownsRunningCall) this._uiRegistry.cancel(void 0, void 0, operationId);
1494
+ }
1495
+ async _releaseOperationConnection(operation) {
1496
+ const sessionIds = /* @__PURE__ */ new Set();
1497
+ for (const [connectId, sessionId] of this._sessions) {
1498
+ if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1499
+ this._sessions.delete(connectId);
1500
+ sessionIds.add(sessionId);
1501
+ }
1502
+ }
1503
+ for (const sessionId of sessionIds) {
1504
+ await this._runConnectorTeardown(
1505
+ () => this.connector.disconnect(sessionId).catch(() => void 0)
1506
+ );
1507
+ }
1508
+ }
1509
+ async _releaseLostOperationConnection(operationId) {
1510
+ const endedOperation = this._operations.end(operationId, "disconnect");
1511
+ if (!endedOperation) return;
1512
+ this._discoveredDevices.delete(endedOperation.connectId);
1513
+ await this._releaseOperationConnection(endedOperation);
1514
+ }
1515
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1516
+ let connectId;
1517
+ try {
1518
+ connectId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1519
+ } catch (error) {
1520
+ return this.errorToFailure(error);
1521
+ }
1020
1522
  debugLog("[LedgerAdapter][REQ]", {
1021
1523
  method: "getDeviceInfo",
1022
1524
  connectId,
@@ -1051,11 +1553,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1051
1553
  success: false,
1052
1554
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1053
1555
  });
1054
- throw err;
1556
+ return this.errorToFailure(err);
1055
1557
  }
1056
1558
  }
1057
- getSupportedChains() {
1058
- return ["evm", "btc", "sol", "tron"];
1559
+ /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1560
+ async _dropUncheckedBundlePick(context, signal) {
1561
+ const { connection } = context;
1562
+ const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1563
+ if (!connection || !owner) return;
1564
+ this._pendingPickBindings.delete(connection.connectId);
1565
+ this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1566
+ if (this._sessions.get(connection.connectId) === connection.sessionId) {
1567
+ await this._dropSession(connection.connectId, signal);
1568
+ }
1059
1569
  }
1060
1570
  // ---------------------------------------------------------------------------
1061
1571
  // Chain call helper
@@ -1091,13 +1601,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1091
1601
  if (params && typeof params === "object") {
1092
1602
  const {
1093
1603
  autoInstallApp,
1604
+ operationId,
1094
1605
  passphraseState: _passphraseState,
1095
1606
  useEmptyPassphrase: _useEmptyPassphrase,
1607
+ knownConnections,
1608
+ extra,
1609
+ allowDeviceSelection,
1610
+ supportedTransports,
1096
1611
  ...rest
1097
1612
  } = params;
1098
1613
  return {
1099
1614
  commonParams: {
1100
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1615
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1616
+ operationId: typeof operationId === "string" ? operationId : void 0,
1617
+ ...(0, import_hwk_adapter_core3.pickConnectionContext)({
1618
+ knownConnections,
1619
+ extra,
1620
+ allowDeviceSelection,
1621
+ supportedTransports
1622
+ })
1101
1623
  },
1102
1624
  rest
1103
1625
  };
@@ -1273,9 +1795,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1273
1795
  );
1274
1796
  }
1275
1797
  // ---------------------------------------------------------------------------
1276
- // App management — OS-level Ledger app install / list. Bypasses fingerprint
1277
- // and chain-handler dispatch; installApp progress is forwarded to the adapter
1278
- // emitter via 'ui-event' AppInstallProgress events.
1798
+ // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1799
+ // ---------------------------------------------------------------------------
1800
+ zcashGetFullViewingKey(connectId, deviceId, params) {
1801
+ return this.callChainWithMergedParams(
1802
+ connectId,
1803
+ deviceId,
1804
+ "zcash",
1805
+ "zcashGetFullViewingKey",
1806
+ params
1807
+ );
1808
+ }
1809
+ zcashGetShieldedAddress(connectId, deviceId, params) {
1810
+ return this.callChainWithMergedParams(
1811
+ connectId,
1812
+ deviceId,
1813
+ "zcash",
1814
+ "zcashGetShieldedAddress",
1815
+ params
1816
+ );
1817
+ }
1818
+ // ---------------------------------------------------------------------------
1819
+ // App management: OS-level app install/list, no fingerprint or chain dispatch.
1279
1820
  // ---------------------------------------------------------------------------
1280
1821
  async installApp(connectId, appName) {
1281
1822
  try {
@@ -1361,7 +1902,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1361
1902
  );
1362
1903
  }
1363
1904
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1364
- this.resetState();
1905
+ await this._resetStateAndDisconnectSessions();
1365
1906
  }
1366
1907
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1367
1908
  if (!result.isGenuine) {
@@ -1387,10 +1928,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1387
1928
  if (relayUrl) {
1388
1929
  try {
1389
1930
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1390
- this.resetState();
1931
+ await this._resetStateAndDisconnectSessions();
1391
1932
  } catch {
1392
1933
  this.connector.reset();
1393
- this.resetState();
1934
+ await this._resetStateAndDisconnectSessions();
1394
1935
  }
1395
1936
  }
1396
1937
  }
@@ -1402,6 +1943,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1402
1943
  this.emitter.off(event, listener);
1403
1944
  }
1404
1945
  cancel(connectId) {
1946
+ const namedOperationIsLive = (id) => {
1947
+ try {
1948
+ this._operations.resolve(id);
1949
+ return true;
1950
+ } catch {
1951
+ return false;
1952
+ }
1953
+ };
1954
+ if ((0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
1955
+ debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
1956
+ connectId
1957
+ });
1958
+ return;
1959
+ }
1405
1960
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1406
1961
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
1407
1962
  _tag: ERROR_TAG.UserAborted
@@ -1412,14 +1967,48 @@ var _LedgerAdapter = class _LedgerAdapter {
1412
1967
  this._lastCancelReason = void 0;
1413
1968
  }
1414
1969
  }, 2e3);
1415
- this._uiRegistry.cancel();
1416
- if (connectId) {
1417
- this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1970
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
1971
+ let operationId;
1972
+ if ((0, import_hwk_adapter_core3.isHardwareOperationId)(connectId)) {
1973
+ operationId = connectId;
1974
+ } else if (!connectId && (0, import_hwk_adapter_core3.isHardwareOperationId)(activeJobId)) {
1975
+ operationId = activeJobId;
1976
+ }
1977
+ let resolvedConnectId = connectId;
1978
+ if (operationId) {
1979
+ try {
1980
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
1981
+ } catch {
1982
+ resolvedConnectId = void 0;
1983
+ }
1984
+ }
1985
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1986
+ const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
1987
+ if (!connectId) {
1988
+ this._uiRegistry.cancel();
1989
+ } else if (pendingOperationId) {
1990
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
1991
+ }
1992
+ this._finishBleBinding("cancelled");
1993
+ if (!connectId) this._pendingOperationBindings.clear();
1994
+ else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
1995
+ const queueKeys = /* @__PURE__ */ new Set();
1996
+ if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
1997
+ if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
1998
+ if (queueKeys.size) {
1999
+ let cancelledAnyJob = false;
2000
+ for (const key of queueKeys) {
2001
+ cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
2002
+ }
2003
+ debugLog("[LedgerAdapter] cancel routed to queue keys", {
2004
+ queueKeys: [...queueKeys],
2005
+ cancelledAnyJob
2006
+ });
1418
2007
  } else {
1419
2008
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1420
2009
  }
1421
- if (connectId) {
1422
- const sessionId = this._sessions.get(connectId) ?? connectId;
2010
+ if (resolvedConnectId) {
2011
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1423
2012
  void this.connector.cancel(sessionId);
1424
2013
  } else {
1425
2014
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
@@ -1427,49 +2016,90 @@ var _LedgerAdapter = class _LedgerAdapter {
1427
2016
  if (this._connectingPromise) {
1428
2017
  this._doConnectAbortController?.abort(userAbortReason);
1429
2018
  }
2019
+ const connectingConnectId = this._connectingConnectId;
2020
+ if (connectingConnectId) void this.connector.cancel(connectingConnectId);
1430
2021
  }
1431
2022
  // ---------------------------------------------------------------------------
1432
2023
  // Chain fingerprint
1433
2024
  // ---------------------------------------------------------------------------
2025
+ /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
1434
2026
  async getChainFingerprint(connectId, deviceId, chain) {
1435
2027
  try {
1436
2028
  const fingerprint = await this._computeChainFingerprint(
1437
2029
  chain,
1438
2030
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
1439
2031
  );
2032
+ if (deviceId) {
2033
+ if (fingerprint !== deviceId) {
2034
+ return (0, import_hwk_adapter_core3.failure)(
2035
+ import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2036
+ formatDeviceMismatchError(deviceId, fingerprint)
2037
+ );
2038
+ }
2039
+ }
1440
2040
  return (0, import_hwk_adapter_core3.success)(fingerprint);
1441
2041
  } catch (err) {
1442
2042
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
1443
2043
  return this.errorToFailure(err);
1444
2044
  }
1445
2045
  }
1446
- /**
1447
- * Verify fingerprint using an existing sessionId directly.
1448
- * Safe to call inside connectorCall without causing queue deadlock.
1449
- */
1450
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
1451
- if (!deviceId) return { success: true };
2046
+ /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2047
+ async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
1452
2048
  try {
1453
- const fingerprint = await this._computeChainFingerprint(
1454
- chain,
1455
- (method, params) => this._callConnector(sessionId, method, params)
2049
+ const outcome = await (0, import_hwk_adapter_core3.requestSaveDeviceBinding)(
2050
+ this.emitter,
2051
+ this._uiRegistry,
2052
+ {
2053
+ selectionRequestId,
2054
+ connection: { transport: "ble", connectId },
2055
+ ...identity ? { identity } : {},
2056
+ extra: context?.extra,
2057
+ operationId
2058
+ },
2059
+ signal
1456
2060
  );
1457
- if (fingerprint === deviceId) {
1458
- return { success: true };
2061
+ if (context) context.bindingSaved = outcome.saved;
2062
+ if (!outcome.saved) {
2063
+ debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2064
+ connectId,
2065
+ reason: outcome.reason
2066
+ });
1459
2067
  }
1460
- return { success: false, expected: deviceId, actual: fingerprint };
1461
- } catch (err) {
1462
- const mapped = mapLedgerError(err);
1463
- if (mapped.code === import_hwk_adapter_core3.HardwareErrorCode.WrongApp || mapped.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceLocked) {
1464
- return { success: true };
2068
+ } catch (error) {
2069
+ await this._dropSession(connectId, signal);
2070
+ throw error;
2071
+ } finally {
2072
+ if (this._bindingSelectionRequestId === selectionRequestId) {
2073
+ this._bindingSelectionRequestId = void 0;
1465
2074
  }
1466
- throw err;
1467
2075
  }
1468
2076
  }
1469
- /**
1470
- * Compute the chain fingerprint via a caller-supplied call strategy.
1471
- *
1472
- * Chains with a native device-side identity primitive (BTC → BIP32 master
2077
+ async _dropSession(connectId, signal) {
2078
+ const sessionId = this._sessions.get(connectId);
2079
+ this._sessions.delete(connectId);
2080
+ if (!sessionId) return;
2081
+ this._sessionTransports.delete(sessionId);
2082
+ const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2083
+ () => void 0
2084
+ );
2085
+ if (!signal.aborted) await teardown;
2086
+ }
2087
+ /** Verify on the acquired session without re-entering the job queue. */
2088
+ async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2089
+ if (!deviceId) return { success: true };
2090
+ const fingerprint = await this._computeChainFingerprint(
2091
+ chain,
2092
+ (method, params) => this._callConnector(sessionId, method, params)
2093
+ );
2094
+ if (fingerprint === deviceId) {
2095
+ return { success: true };
2096
+ }
2097
+ return { success: false, expected: deviceId, actual: fingerprint };
2098
+ }
2099
+ /**
2100
+ * Compute the chain fingerprint via a caller-supplied call strategy.
2101
+ *
2102
+ * Chains with a native device-side identity primitive (BTC → BIP32 master
1473
2103
  * fingerprint) short-circuit at the top and return it verbatim, so the value
1474
2104
  * stays reusable for higher-level use (BIP380 descriptors, PSBT signing).
1475
2105
  *
@@ -1493,11 +2123,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1493
2123
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
1494
2124
  } else if (chain === "tron") {
1495
2125
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2126
+ } else if (chain === "zcash") {
2127
+ address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
1496
2128
  } else {
1497
2129
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
1498
2130
  }
1499
2131
  return (0, import_hwk_adapter_core3.deriveDeviceFingerprint)(address);
1500
2132
  }
2133
+ /**
2134
+ * Operation owning the running job, so a mid-call UI request can name it.
2135
+ * Undefined at cold start when no operation owns the job.
2136
+ */
2137
+ _activeOperationId() {
2138
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2139
+ }
1501
2140
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
1502
2141
  // The user must press Confirm after unlocking, which triggers a search retry.
1503
2142
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -1507,15 +2146,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1507
2146
  if (signal?.aborted) {
1508
2147
  _LedgerAdapter._throwIfAborted(signal);
1509
2148
  }
2149
+ const operationId = this._activeOperationId();
1510
2150
  const waitPromise = this._uiRegistry.wait(
1511
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT
2151
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT,
2152
+ { operationId }
1512
2153
  );
1513
2154
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1514
2155
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT,
1515
2156
  payload: {
1516
2157
  vendor: "ledger",
1517
2158
  reason: "device-not-found",
1518
- message: "Please connect and unlock your Ledger device"
2159
+ message: "Please connect and unlock your Ledger device",
2160
+ operationId
1519
2161
  }
1520
2162
  });
1521
2163
  let payload;
@@ -1561,7 +2203,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1561
2203
  * Returns the params to pass through (with `showOnDevice` possibly
1562
2204
  * promoted), or `null` if the user declined.
1563
2205
  */
1564
- async _gateBtcHighIndex(params) {
2206
+ async _gateBtcHighIndex(params, signal) {
1565
2207
  const accountIndex = btcAccountIndexFromPath(params.path);
1566
2208
  if (params.showOnDevice) return params;
1567
2209
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -1570,25 +2212,32 @@ var _LedgerAdapter = class _LedgerAdapter {
1570
2212
  if (this._btcHighIndexConfirmedThisSession) {
1571
2213
  return { ...params, showOnDevice: true };
1572
2214
  }
1573
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2215
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1574
2216
  if (!confirmed) return null;
1575
2217
  this._btcHighIndexConfirmedThisSession = true;
1576
2218
  return { ...params, showOnDevice: true };
1577
2219
  }
1578
- async _waitForBtcHighIndexConfirm(path, accountIndex) {
2220
+ async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2221
+ const operationId = this._activeOperationId();
1579
2222
  const waitPromise = this._uiRegistry.wait(
1580
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2223
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2224
+ { operationId }
1581
2225
  );
1582
2226
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1583
2227
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1584
2228
  payload: {
1585
2229
  vendor: "ledger",
1586
2230
  path,
1587
- accountIndex
2231
+ accountIndex,
2232
+ operationId
1588
2233
  }
1589
2234
  });
1590
2235
  try {
1591
- const payload = await waitPromise;
2236
+ const payload = await this._awaitUiAnswer(
2237
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2238
+ waitPromise,
2239
+ signal
2240
+ );
1592
2241
  return !!payload?.confirmed;
1593
2242
  } catch (err) {
1594
2243
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1598,18 +2247,35 @@ var _LedgerAdapter = class _LedgerAdapter {
1598
2247
  return false;
1599
2248
  }
1600
2249
  }
2250
+ /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2251
+ async _awaitUiAnswer(requestType, waitPromise, signal) {
2252
+ const onAbort = () => this._uiRegistry.cancel(requestType);
2253
+ if (signal.aborted) onAbort();
2254
+ signal.addEventListener("abort", onAbort, { once: true });
2255
+ try {
2256
+ return await waitPromise;
2257
+ } finally {
2258
+ signal.removeEventListener("abort", onAbort);
2259
+ }
2260
+ }
1601
2261
  // Ask the user whether to install a missing app (autoInstallApp flow).
1602
2262
  // Same register-then-emit ordering as the BTC high-index gate.
1603
- async _waitForInstallAppConfirm(appName) {
2263
+ async _waitForInstallAppConfirm(appName, signal) {
2264
+ const operationId = this._activeOperationId();
1604
2265
  const waitPromise = this._uiRegistry.wait(
1605
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP
2266
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
2267
+ { operationId }
1606
2268
  );
1607
2269
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP, {
1608
2270
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
1609
- payload: { vendor: "ledger", appName }
2271
+ payload: { vendor: "ledger", appName, operationId }
1610
2272
  });
1611
2273
  try {
1612
- const payload = await waitPromise;
2274
+ const payload = await this._awaitUiAnswer(
2275
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
2276
+ waitPromise,
2277
+ signal
2278
+ );
1613
2279
  return !!payload?.confirmed;
1614
2280
  } catch (err) {
1615
2281
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1622,16 +2288,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1622
2288
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
1623
2289
  // `_doConnect` runs under its own internal controller so caller A's cancel
1624
2290
  // doesn't kill caller B's await.
1625
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2291
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1626
2292
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
1627
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2293
+ this._assertConnectorReady("connectDevice");
2294
+ if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1628
2295
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1629
2296
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
1630
2297
  });
1631
2298
  }
1632
2299
  if (connectId && this._sessions.has(connectId)) return connectId;
1633
2300
  if (!connectId && this._sessions.size > 0) {
1634
- if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2301
+ if (!this._isBleConnection() && this._sessions.size > 1) {
1635
2302
  throw Object.assign(
1636
2303
  new Error(
1637
2304
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -1641,15 +2308,24 @@ var _LedgerAdapter = class _LedgerAdapter {
1641
2308
  }
1642
2309
  return this._sessions.keys().next().value;
1643
2310
  }
1644
- if (!this._connectingPromise) {
1645
- this._doConnectAbortController = new AbortController();
1646
- const innerSignal = this._doConnectAbortController.signal;
2311
+ if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2312
+ const controller = new AbortController();
2313
+ this._doConnectAbortController = controller;
2314
+ const innerSignal = controller.signal;
1647
2315
  this._connectingPromise = (async () => {
1648
2316
  try {
1649
- return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2317
+ return await this._doConnect(
2318
+ innerSignal,
2319
+ connectId,
2320
+ allowUsbEphemeralFallback,
2321
+ preserveOperationId,
2322
+ context
2323
+ );
1650
2324
  } finally {
1651
- this._connectingPromise = null;
1652
- this._doConnectAbortController = null;
2325
+ if (this._doConnectAbortController === controller) {
2326
+ this._connectingPromise = null;
2327
+ this._doConnectAbortController = null;
2328
+ }
1653
2329
  }
1654
2330
  })();
1655
2331
  }
@@ -1658,22 +2334,57 @@ var _LedgerAdapter = class _LedgerAdapter {
1658
2334
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
1659
2335
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
1660
2336
  // throw DeviceNotFound so the user is kicked out of the loop.
1661
- async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
1662
- if (isLedgerBleConnectionType(this.connector.connectionType) && targetConnectId) {
1663
- try {
1664
- return await this._connectDeviceOrThrow(targetConnectId);
1665
- } catch (err) {
1666
- if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
1667
- throw err;
1668
- }
1669
- this._discoveredDevices.delete(targetConnectId);
1670
- if (isDeviceDisconnectedError(err)) {
1671
- try {
1672
- this.connector.reset?.();
1673
- } catch {
1674
- }
1675
- }
2337
+ async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2338
+ _LedgerAdapter._throwIfAborted(internalSignal);
2339
+ if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2340
+ this._activeConnectionType = "usb";
2341
+ const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2342
+ _LedgerAdapter._throwIfAborted(internalSignal);
2343
+ const knownUsb = context?.knownConnections?.find(
2344
+ (connection) => connection.transport === "usb"
2345
+ );
2346
+ const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2347
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2348
+ return this._connectFirstOrSelect(
2349
+ usbDevices,
2350
+ usbTarget,
2351
+ allowUsbEphemeralFallback,
2352
+ preserveOperationId,
2353
+ context,
2354
+ internalSignal
2355
+ );
2356
+ }
2357
+ if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2358
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2359
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
2360
+ message: "This Ledger model has no Bluetooth transport; connect it over USB"
2361
+ });
2362
+ }
2363
+ this._activeConnectionType = "ble";
2364
+ const knownBle = context?.knownConnections?.find(
2365
+ (connection) => connection.transport === "ble"
2366
+ );
2367
+ if (knownBle?.transport === "ble") {
2368
+ return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
1676
2369
  }
2370
+ if (targetConnectId && context?.knownConnections === void 0) {
2371
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2372
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
2373
+ message: "Ledger connection metadata is required before starting Bluetooth binding"
2374
+ });
2375
+ }
2376
+ const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2377
+ return this._connectFirstOrSelect(
2378
+ bleDevices,
2379
+ void 0,
2380
+ allowUsbEphemeralFallback,
2381
+ preserveOperationId,
2382
+ context,
2383
+ internalSignal
2384
+ );
2385
+ }
2386
+ if (this._isBleConnection() && targetConnectId) {
2387
+ return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
1677
2388
  }
1678
2389
  let confirms = 0;
1679
2390
  while (!internalSignal.aborted) {
@@ -1681,22 +2392,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1681
2392
  type: import_hwk_adapter_core3.EConnectorInteraction.Searching,
1682
2393
  payload: { sessionId: "" }
1683
2394
  });
1684
- let devices = await this.searchDevices();
2395
+ let devices = await this._searchDevices(void 0, internalSignal);
2396
+ _LedgerAdapter._throwIfAborted(internalSignal);
1685
2397
  if (devices.length === 0) {
1686
2398
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
1687
2399
  await new Promise((resolve) => {
1688
2400
  setTimeout(resolve, import_hwk_adapter_core3.DEVICE_CONNECT_RETRY_DELAY_MS);
1689
2401
  });
1690
- devices = await this.searchDevices();
2402
+ _LedgerAdapter._throwIfAborted(internalSignal);
2403
+ devices = await this._searchDevices(void 0, internalSignal);
2404
+ _LedgerAdapter._throwIfAborted(internalSignal);
1691
2405
  if (devices.length > 0) break;
1692
2406
  }
1693
2407
  }
1694
- if (devices.length > 0) {
2408
+ if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1695
2409
  try {
1696
2410
  return await this._connectFirstOrSelect(
1697
2411
  devices,
1698
2412
  targetConnectId,
1699
- allowUsbEphemeralFallback
2413
+ allowUsbEphemeralFallback,
2414
+ preserveOperationId,
2415
+ context,
2416
+ internalSignal
1700
2417
  );
1701
2418
  } catch (err) {
1702
2419
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -1725,45 +2442,147 @@ var _LedgerAdapter = class _LedgerAdapter {
1725
2442
  _LedgerAdapter._throwIfAborted(internalSignal);
1726
2443
  throw new Error("_doConnect aborted");
1727
2444
  }
1728
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2445
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2446
+ _LedgerAdapter._throwIfAborted(signal);
1729
2447
  if (targetConnectId) {
1730
2448
  const target = devices.find(
1731
2449
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
1732
2450
  );
1733
2451
  if (target) {
1734
- return this._connectDeviceOrThrow(target.connectId);
2452
+ return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1735
2453
  }
1736
- if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2454
+ if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1737
2455
  debugLog(
1738
2456
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
1739
2457
  );
1740
- return this._connectDeviceOrThrow(devices[0].connectId);
2458
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1741
2459
  }
1742
- const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
1743
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
1744
- });
1745
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
1746
- err._tag = ERROR_TAG.DeviceNotAdvertising;
2460
+ if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2461
+ const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2462
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2463
+ });
2464
+ if (this._isBleConnection()) {
2465
+ err._tag = ERROR_TAG.DeviceNotAdvertising;
2466
+ }
2467
+ throw err;
1747
2468
  }
1748
- throw err;
1749
2469
  }
1750
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
2470
+ const requiresBleSelection = this._isBleConnection();
2471
+ if (requiresBleSelection && !allowUsbEphemeralFallback) {
1751
2472
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1752
2473
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
1753
2474
  });
1754
2475
  }
1755
- if (devices.length > 1) {
1756
- throw createMultipleUsbLedgerDevicesError();
2476
+ if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2477
+ const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2478
+ if (context) context.bindingSessionId = bindingSessionId;
2479
+ const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2480
+ const knownUsb = context?.knownConnections?.find(
2481
+ (connection) => connection.transport === "usb"
2482
+ );
2483
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2484
+ const { device, requestId } = await (0, import_hwk_adapter_core3.requestBleDeviceSelection)({
2485
+ emitter: this.emitter,
2486
+ registry: this._uiRegistry,
2487
+ signal,
2488
+ allowUsbFallback,
2489
+ scan: async () => {
2490
+ if (allowUsbFallback) {
2491
+ const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2492
+ const candidate = usbDevices.find(
2493
+ (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2494
+ ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2495
+ if (candidate) return [candidate];
2496
+ }
2497
+ return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2498
+ },
2499
+ request: {
2500
+ devices,
2501
+ bindingSessionId,
2502
+ context: {
2503
+ kind: "bind-connection",
2504
+ transport: "ble",
2505
+ reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2506
+ },
2507
+ extra: context?.extra,
2508
+ operationId: preserveOperationId
2509
+ }
2510
+ });
2511
+ if (device.connectionType === "usb") {
2512
+ this._activeConnectionType = "usb";
2513
+ if (context) context.selectedConnection = void 0;
2514
+ this._bindingSelectionRequestId = requestId;
2515
+ this._finishBleBinding("cancelled");
2516
+ return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2517
+ }
2518
+ this._bindingSelectionRequestId = requestId;
2519
+ const connected = await this._connectDeviceOrThrow(
2520
+ device.connectId,
2521
+ preserveOperationId,
2522
+ signal
2523
+ );
2524
+ if (context) context.selectedConnection = { connectId: connected, requestId };
2525
+ if (context?.deferBindingSave) {
2526
+ context.pendingBinding = { connectId: connected, requestId };
2527
+ } else {
2528
+ await this._saveSelectedBleBinding(
2529
+ connected,
2530
+ requestId,
2531
+ context,
2532
+ preserveOperationId,
2533
+ signal
2534
+ );
2535
+ }
2536
+ return connected;
2537
+ }
2538
+ if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2539
+ if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core3.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2540
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2541
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
2542
+ message: "Select a Ledger device before continuing"
2543
+ });
2544
+ }
2545
+ const requestId = this._uiRegistry.createRequestId();
2546
+ const operationId = this._activeOperationId();
2547
+ const waitPromise = this._uiRegistry.wait(
2548
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_SELECT_DEVICE,
2549
+ { requestId, operationId }
2550
+ );
2551
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_SELECT_DEVICE, {
2552
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_SELECT_DEVICE,
2553
+ payload: {
2554
+ devices,
2555
+ requestId,
2556
+ operationId,
2557
+ context: requiresBleSelection ? {
2558
+ kind: "bind-connection",
2559
+ transport: "ble",
2560
+ reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2561
+ } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2562
+ extra: context?.extra
2563
+ }
2564
+ });
2565
+ const { sdkConnectId } = await this._abortable(signal, waitPromise);
2566
+ _LedgerAdapter._throwIfAborted(signal);
2567
+ const selected = devices.find((device) => device.connectId === sdkConnectId);
2568
+ if (!selected) {
2569
+ throw Object.assign(new Error("Selected Ledger is no longer available"), {
2570
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2571
+ });
2572
+ }
2573
+ if (context && requiresBleSelection)
2574
+ context.selectedConnection = { connectId: selected.connectId, requestId };
2575
+ return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1757
2576
  }
1758
2577
  if (devices.length !== 1) {
1759
2578
  throw Object.assign(new Error("Ledger device not found."), {
1760
2579
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
1761
2580
  });
1762
2581
  }
1763
- return this._connectDeviceOrThrow(devices[0].connectId);
2582
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1764
2583
  }
1765
- async _connectDeviceOrThrow(chosenConnectId) {
1766
- const result = await this.connectDevice(chosenConnectId);
2584
+ async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2585
+ const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1767
2586
  if (!result.success) {
1768
2587
  const payload = result.payload;
1769
2588
  const rethrow = Object.assign(new Error(payload.error), {
@@ -1774,16 +2593,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1774
2593
  }
1775
2594
  throw rethrow;
1776
2595
  }
1777
- return chosenConnectId;
2596
+ return result.payload;
1778
2597
  }
1779
- /**
1780
- * Call the connector with automatic session resolution and disconnect retry.
1781
- *
1782
- * 1. Resolves a valid connectId via ensureConnected()
1783
- * 2. Looks up sessionId from _sessions
1784
- * 3. Calls connector.call()
1785
- * 4. On disconnect error: clears stale session, re-connects, retries once
1786
- */
1787
2598
  /**
1788
2599
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
1789
2600
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -1804,33 +2615,145 @@ var _LedgerAdapter = class _LedgerAdapter {
1804
2615
  * lives in one place.
1805
2616
  */
1806
2617
  async _callConnector(sessionId, method, params, signal) {
1807
- const promise = this.connector.call(sessionId, method, params);
2618
+ this._assertConnectorReady(method);
2619
+ if (signal?.aborted) throw this._abortReason(signal);
2620
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2621
+ let promise;
2622
+ try {
2623
+ promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2624
+ } catch (error) {
2625
+ releaseOperation();
2626
+ throw error;
2627
+ }
1808
2628
  const result = signal ? await this._abortable(signal, promise) : await promise;
1809
2629
  return this._unwrapConnectorResult(result);
1810
2630
  }
2631
+ _assertConnectorReady(method) {
2632
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2633
+ throw _LedgerAdapter._createDeviceBusyError(method);
2634
+ }
2635
+ }
2636
+ _runConnectorTeardown(task) {
2637
+ const previous = this._connectorTeardownTail;
2638
+ let releaseTail = () => void 0;
2639
+ this._connectorTeardownTail = new Promise((resolve) => {
2640
+ releaseTail = resolve;
2641
+ });
2642
+ this._pendingConnectorTeardowns += 1;
2643
+ return (async () => {
2644
+ try {
2645
+ await previous;
2646
+ await this._waitForConnectorOperationsToDrain();
2647
+ await task();
2648
+ } finally {
2649
+ this._pendingConnectorTeardowns -= 1;
2650
+ releaseTail();
2651
+ }
2652
+ })();
2653
+ }
2654
+ _waitForConnectorOperationsToDrain() {
2655
+ if (this._unsettledConnectorOperations.size === 0) {
2656
+ return Promise.resolve();
2657
+ }
2658
+ return new Promise((resolve) => {
2659
+ this._connectorIdleWaiters.add(resolve);
2660
+ });
2661
+ }
2662
+ _retainConnectorOperation(key) {
2663
+ this._unsettledConnectorOperations.set(
2664
+ key,
2665
+ (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2666
+ );
2667
+ let released = false;
2668
+ return () => {
2669
+ if (released) return;
2670
+ released = true;
2671
+ const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2672
+ if (remaining > 0) {
2673
+ this._unsettledConnectorOperations.set(key, remaining);
2674
+ } else {
2675
+ this._unsettledConnectorOperations.delete(key);
2676
+ }
2677
+ if (this._unsettledConnectorOperations.size === 0) {
2678
+ for (const resolve of this._connectorIdleWaiters) resolve();
2679
+ this._connectorIdleWaiters.clear();
2680
+ }
2681
+ };
2682
+ }
1811
2683
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1812
- debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1813
- const queueKey = connectId || "__ledger_default__";
2684
+ const positionalOperationId = (0, import_hwk_adapter_core3.isHardwareOperationId)(connectId) ? connectId : void 0;
2685
+ if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2686
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2687
+ code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams,
2688
+ message: "Conflicting Ledger operation ids",
2689
+ params: {
2690
+ positionalOperationId,
2691
+ commonOperationId: commonParams.operationId
2692
+ }
2693
+ });
2694
+ }
2695
+ const operationId = commonParams?.operationId ?? positionalOperationId;
2696
+ const operation = operationId ? this._operations.resolve(operationId) : void 0;
2697
+ const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2698
+ const effectiveConnectId = operation?.connectId ?? connectId;
2699
+ debugLog("[LedgerAdapter][REQ]", {
2700
+ method,
2701
+ connectId: effectiveConnectId || "(empty)",
2702
+ params: isSigningMethod(method) ? "[redacted]" : params
2703
+ });
2704
+ const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1814
2705
  try {
1815
2706
  const result = await this._jobQueue.enqueue(
1816
2707
  queueKey,
1817
- async (signal) => this._runConnectorCall(
1818
- connectId,
1819
- method,
1820
- params,
1821
- signal,
1822
- fingerprint,
1823
- permissionDeviceId,
1824
- commonParams,
1825
- installContext
1826
- ),
2708
+ async (signal) => {
2709
+ if (operationId) this._activeOperationJobs.add(operationId);
2710
+ try {
2711
+ return await this._runConnectorCall(
2712
+ effectiveConnectId,
2713
+ method,
2714
+ params,
2715
+ signal,
2716
+ fingerprint,
2717
+ permissionDeviceId,
2718
+ commonParams,
2719
+ installContext ?? {},
2720
+ operationId
2721
+ );
2722
+ } catch (error) {
2723
+ const status = signal.aborted ? "cancelled" : "failed";
2724
+ const bundleConnectId = installContext?.connection?.connectId;
2725
+ let keptBundlePick = false;
2726
+ for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2727
+ if (pickedConnectId === bundleConnectId) {
2728
+ keptBundlePick = true;
2729
+ } else {
2730
+ this._pendingPickBindings.delete(pickedConnectId);
2731
+ this._discardPendingBinding(owner, status);
2732
+ await this._dropSession(pickedConnectId, signal);
2733
+ }
2734
+ }
2735
+ if (!keptBundlePick) this._finishBleBinding(status);
2736
+ throw error;
2737
+ } finally {
2738
+ if (operationId) {
2739
+ this._activeOperationJobs.delete(operationId);
2740
+ if (this._pendingOperationDisconnects.delete(operationId)) {
2741
+ await this._releaseLostOperationConnection(operationId);
2742
+ }
2743
+ }
2744
+ }
2745
+ },
1827
2746
  {
1828
2747
  label: method,
1829
2748
  rejectIfBusy: true,
1830
2749
  busyError: _LedgerAdapter._createDeviceBusyError(method)
1831
2750
  }
1832
2751
  );
1833
- debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2752
+ debugLog("[LedgerAdapter][RES]", {
2753
+ method,
2754
+ success: true,
2755
+ payload: redactResultForLog(result, method)
2756
+ });
1834
2757
  return result;
1835
2758
  } catch (err) {
1836
2759
  const e = err;
@@ -1844,15 +2767,22 @@ var _LedgerAdapter = class _LedgerAdapter {
1844
2767
  }
1845
2768
  });
1846
2769
  throw err;
2770
+ } finally {
2771
+ releaseOperationRetention?.();
1847
2772
  }
1848
2773
  }
2774
+ /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2775
+ _abortReason(signal) {
2776
+ return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2777
+ }
1849
2778
  /**
1850
2779
  * Race a promise against an abort signal. On abort, rejects with
1851
2780
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
1852
2781
  */
1853
2782
  _abortable(signal, promise) {
1854
- const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2783
+ const getAbortReason = () => this._abortReason(signal);
1855
2784
  if (signal.aborted) {
2785
+ void promise.catch(() => void 0);
1856
2786
  return Promise.reject(getAbortReason());
1857
2787
  }
1858
2788
  return new Promise((resolve, reject) => {
@@ -1879,17 +2809,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1879
2809
  }
1880
2810
  }
1881
2811
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
1882
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2812
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1883
2813
  _LedgerAdapter._throwIfAborted(signal);
1884
- await this._ensureDevicePermission(
1885
- connectId,
1886
- permissionDeviceId ?? fingerprint?.deviceId,
1887
- signal
1888
- );
2814
+ if (!operationId) {
2815
+ await this._ensureDevicePermission(
2816
+ connectId,
2817
+ permissionDeviceId ?? fingerprint?.deviceId,
2818
+ signal
2819
+ );
2820
+ }
1889
2821
  _LedgerAdapter._throwIfAborted(signal);
1890
2822
  let effectiveParams = params;
1891
2823
  if (method === "btcGetPublicKey") {
1892
- const gatedParams = await this._gateBtcHighIndex(params);
2824
+ const gatedParams = await this._gateBtcHighIndex(params, signal);
1893
2825
  if (gatedParams === null) {
1894
2826
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
1895
2827
  _tag: ERROR_TAG.UserAborted,
@@ -1899,19 +2831,67 @@ var _LedgerAdapter = class _LedgerAdapter {
1899
2831
  effectiveParams = gatedParams;
1900
2832
  }
1901
2833
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
1902
- const resolvedConnectId = await this.ensureConnected(
1903
- connectId,
2834
+ let businessCallStarted = false;
2835
+ const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2836
+ const knownTransport = this._isBleConnection() ? "ble" : "usb";
2837
+ const hintedConnectId = commonParams?.knownConnections?.find(
2838
+ (connection) => connection.transport === knownTransport
2839
+ );
2840
+ const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2841
+ const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2842
+ const checksWallet = Boolean(
2843
+ fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2844
+ );
2845
+ const connectionAttempt = {
2846
+ ...commonParams,
2847
+ deferBindingSave: checksWallet
2848
+ };
2849
+ const bundleConnection = installContext?.connection;
2850
+ if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2851
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2852
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected,
2853
+ message: "Ledger all-network connection ended"
2854
+ });
2855
+ }
2856
+ const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2857
+ preferredConnectId,
1904
2858
  signal,
1905
- allowUsbEphemeralFallback
2859
+ allowUsbEphemeralFallback,
2860
+ void 0,
2861
+ connectionAttempt
1906
2862
  );
2863
+ const walletCheck = installContext?.walletCheck;
2864
+ if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2865
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2866
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
2867
+ message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2868
+ });
2869
+ }
1907
2870
  const sessionId = this._sessions.get(resolvedConnectId);
2871
+ if (sessionId && installContext && !installContext.connection) {
2872
+ installContext.connection = { connectId: resolvedConnectId, sessionId };
2873
+ }
1908
2874
  if (!sessionId) {
2875
+ if (operationId) {
2876
+ this._operations.end(operationId, "disconnect");
2877
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2878
+ code: import_hwk_adapter_core3.HardwareErrorCode.OperationEnded,
2879
+ message: "Ledger operation connection is no longer active",
2880
+ params: { operationId, reason: "disconnect" }
2881
+ });
2882
+ }
1909
2883
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
1910
2884
  _tag: ERROR_TAG.DeviceSessionNotFound
1911
2885
  });
1912
2886
  }
1913
2887
  try {
1914
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2888
+ const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2889
+ if (!operationId && connectionAttempt.pendingBinding) {
2890
+ this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2891
+ }
2892
+ const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2893
+ const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2894
+ if (fingerprint && checksWallet) {
1915
2895
  const fp = await this._abortable(
1916
2896
  signal,
1917
2897
  this._verifyDeviceFingerprintWithSession(
@@ -1921,14 +2901,68 @@ var _LedgerAdapter = class _LedgerAdapter {
1921
2901
  )
1922
2902
  );
1923
2903
  if (!fp.success) {
2904
+ if (pendingBinding) {
2905
+ this._discardPendingBinding(bindingOwner, "failed");
2906
+ this._pendingPickBindings.delete(resolvedConnectId);
2907
+ }
2908
+ if (operationId) {
2909
+ this._pendingOperationBindings.delete(operationId);
2910
+ this._operations.end(operationId, "explicit");
2911
+ await this._dropSession(resolvedConnectId, signal);
2912
+ }
1924
2913
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
1925
2914
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
1926
2915
  });
1927
2916
  }
2917
+ if (walletCheck) walletCheck.verified = true;
1928
2918
  }
1929
- return await this._callConnector(sessionId, method, effectiveParams, signal);
2919
+ if (pendingBinding && bindingOwner) {
2920
+ bindingOwner.pendingBinding = void 0;
2921
+ if (operationId) this._pendingOperationBindings.delete(operationId);
2922
+ else this._pendingPickBindings.delete(resolvedConnectId);
2923
+ await this._saveSelectedBleBinding(
2924
+ pendingBinding.connectId,
2925
+ pendingBinding.requestId,
2926
+ bindingOwner,
2927
+ operationId,
2928
+ signal,
2929
+ fingerprint && checksWallet ? {
2930
+ vendor: "ledger",
2931
+ type: "chainFingerprint",
2932
+ chain: fingerprint.chain,
2933
+ value: fingerprint.deviceId
2934
+ } : void 0
2935
+ );
2936
+ }
2937
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
2938
+ this._selectedBleReconnectTargets.set(connectId, {
2939
+ connectId: resolvedConnectId,
2940
+ chain: fingerprint.chain,
2941
+ fingerprint: fingerprint.deviceId
2942
+ });
2943
+ }
2944
+ businessCallStarted = true;
2945
+ const result = await this._callConnector(sessionId, method, effectiveParams, signal);
2946
+ if (walletCheck) walletCheck.derived = true;
2947
+ return result;
1930
2948
  } catch (err) {
1931
2949
  if (signal.aborted) throw err;
2950
+ if (isLostConnectionError(err)) {
2951
+ this._discoveredDevices.delete(resolvedConnectId);
2952
+ if (operationId) await this._releaseLostOperationConnection(operationId);
2953
+ else {
2954
+ this._sessions.delete(resolvedConnectId);
2955
+ await this.connector.disconnect(sessionId).catch(() => void 0);
2956
+ }
2957
+ const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core3.canReplayHardwareMethodAfterTransportFailure)(method);
2958
+ const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
2959
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2960
+ code: operationId ? import_hwk_adapter_core3.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
2961
+ message: "Ledger operation connection was lost; start a new operation",
2962
+ params: ambiguous ? (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
2963
+ recovery: ambiguous ? { scope: "unknown" } : void 0
2964
+ });
2965
+ }
1932
2966
  const errObj = err;
1933
2967
  debugLog("[LedgerAdapter] connectorCall error:", method, {
1934
2968
  message: errObj?.message,
@@ -1940,6 +2974,64 @@ var _LedgerAdapter = class _LedgerAdapter {
1940
2974
  isNotAdvertising: isDeviceNotAdvertisingError(err),
1941
2975
  isStuckApp: isStuckAppStateError(err)
1942
2976
  });
2977
+ const assertSessionCurrent = (message) => {
2978
+ if (this._sessions.get(resolvedConnectId) === sessionId) return;
2979
+ throw (0, import_hwk_adapter_core3.createHwkError)({
2980
+ code: operationId ? import_hwk_adapter_core3.HardwareErrorCode.OperationEnded : import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected,
2981
+ message
2982
+ });
2983
+ };
2984
+ if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
2985
+ await this._waitForDeviceConnect(signal);
2986
+ assertSessionCurrent("Ledger connection ended while waiting for unlock");
2987
+ if (walletCheck?.derived) walletCheck.verified = false;
2988
+ return this._runConnectorCall(
2989
+ resolvedConnectId,
2990
+ method,
2991
+ effectiveParams,
2992
+ signal,
2993
+ fingerprint,
2994
+ permissionDeviceId,
2995
+ commonParams,
2996
+ installContext,
2997
+ operationId,
2998
+ lockedRetryBudget - 1
2999
+ );
3000
+ }
3001
+ if (businessCallStarted && isStuckAppStateError(err)) {
3002
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
3003
+ assertSessionCurrent("Ledger connection ended during the app transition");
3004
+ try {
3005
+ const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
3006
+ if (walletCheck) walletCheck.derived = true;
3007
+ return retried;
3008
+ } catch (retryErr) {
3009
+ if (isStuckAppStateError(retryErr)) throw err;
3010
+ if (isLostConnectionError(retryErr)) {
3011
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3012
+ else {
3013
+ this._sessions.delete(resolvedConnectId);
3014
+ this._discoveredDevices.delete(resolvedConnectId);
3015
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3016
+ }
3017
+ const ambiguous = !(0, import_hwk_adapter_core3.canReplayHardwareMethodAfterTransportFailure)(method);
3018
+ throw (0, import_hwk_adapter_core3.createHwkError)({
3019
+ code: operationId ? import_hwk_adapter_core3.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
3020
+ message: `Ledger ${method} may have completed before the connection was lost`,
3021
+ params: ambiguous ? (0, import_hwk_adapter_core3.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3022
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3023
+ });
3024
+ }
3025
+ throw retryErr;
3026
+ }
3027
+ }
3028
+ if (!operationId && errObj?.code === import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch) {
3029
+ this._sessions.delete(resolvedConnectId);
3030
+ this._sessionTransports.delete(sessionId);
3031
+ this._discoveredDevices.delete(resolvedConnectId);
3032
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3033
+ throw err;
3034
+ }
1943
3035
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
1944
3036
  const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core3.HardwareErrorCode.AppNotInstalled;
1945
3037
  if (autoInstallApp && isAppMissing) {
@@ -1956,7 +3048,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1956
3048
  appName
1957
3049
  });
1958
3050
  }
1959
- const confirmed = await this._waitForInstallAppConfirm(appName);
3051
+ const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1960
3052
  if (!confirmed) {
1961
3053
  throw (0, import_hwk_adapter_core3.createHwkError)({
1962
3054
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
@@ -1995,157 +3087,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1995
3087
  fingerprint,
1996
3088
  permissionDeviceId,
1997
3089
  commonParams,
1998
- installContext
3090
+ installContext,
3091
+ operationId
1999
3092
  );
2000
3093
  }
2001
3094
  }
2002
- if (isStuckAppStateError(err)) {
2003
- try {
2004
- this._sessions.delete(resolvedConnectId);
2005
- this._discoveredDevices.delete(resolvedConnectId);
2006
- this.connector.reset?.();
2007
- } catch {
2008
- }
2009
- debugLog(
2010
- "[LedgerAdapter] stuck-app retry: method=",
2011
- method,
2012
- "delayMs=",
2013
- _LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
2014
- "_tag=",
2015
- err?._tag
2016
- );
2017
- try {
2018
- const retryResult = await this._retryAfterStuckApp(
2019
- resolvedConnectId,
2020
- method,
2021
- effectiveParams,
2022
- signal,
2023
- err,
2024
- fingerprint
2025
- );
2026
- debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
2027
- return retryResult;
2028
- } catch (retryErr) {
2029
- if (signal.aborted) throw retryErr;
2030
- if (isStuckAppStateError(retryErr)) {
2031
- debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
2032
- throw err;
2033
- }
2034
- debugLog(
2035
- "[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
2036
- method,
2037
- "retryErrTag=",
2038
- retryErr?._tag
2039
- );
2040
- throw retryErr;
2041
- }
2042
- }
2043
- if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
2044
- let lastErr = err;
2045
- for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
2046
- if (signal.aborted) throw lastErr;
2047
- try {
2048
- this._sessions.delete(resolvedConnectId);
2049
- this._discoveredDevices.delete(resolvedConnectId);
2050
- if (isDeviceDisconnectedError(lastErr)) {
2051
- try {
2052
- this.connector.reset?.();
2053
- } catch {
2054
- }
2055
- }
2056
- const reConnectId = await this.ensureConnected(
2057
- resolvedConnectId,
2058
- signal,
2059
- allowUsbEphemeralFallback
2060
- );
2061
- const reSessionId = this._sessions.get(reConnectId);
2062
- if (!reSessionId) throw lastErr;
2063
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2064
- const fp = await this._abortable(
2065
- signal,
2066
- this._verifyDeviceFingerprintWithSession(
2067
- reSessionId,
2068
- fingerprint.deviceId,
2069
- fingerprint.chain
2070
- )
2071
- );
2072
- if (!fp.success) {
2073
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2074
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2075
- });
2076
- }
2077
- }
2078
- return await this._callConnector(reSessionId, method, effectiveParams, signal);
2079
- } catch (retryErr) {
2080
- if (signal.aborted) throw retryErr;
2081
- lastErr = retryErr;
2082
- const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
2083
- if (!canRetry) {
2084
- throw retryErr;
2085
- }
2086
- }
2087
- }
2088
- throw lastErr;
2089
- }
2090
- if (isTimeoutError(err)) {
2091
- debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
2092
- this._discoveredDevices.delete(resolvedConnectId);
2093
- return this._retryWithFreshConnection(
2094
- resolvedConnectId,
2095
- method,
2096
- effectiveParams,
2097
- signal,
2098
- err,
2099
- fingerprint
2100
- );
2101
- }
2102
- if (isConnectionLevelError(err)) {
2103
- debugLog("[LedgerAdapter] connection-level fail-closed reset");
2104
- this._sessions.delete(resolvedConnectId);
2105
- this._discoveredDevices.delete(resolvedConnectId);
2106
- this.connector.reset();
2107
- const codeNum = err?.code;
2108
- throw Object.assign(err, {
2109
- code: codeNum ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected
2110
- });
2111
- }
2112
3095
  throw err;
2113
3096
  }
2114
3097
  }
2115
- /**
2116
- * Stuck-app recovery: pause for the device's UI transition, then retry once.
2117
- *
2118
- * Caller has already cleared the session + reset connector. We wait so Stax
2119
- * finishes its post-CloseApp animation, then go through ensureConnected +
2120
- * fingerprint check + call exactly once. Caller decides what to do on a
2121
- * second stuck-app hit.
2122
- */
2123
- async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
2124
- await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
2125
- const retryConnectId = await this.ensureConnected(
2126
- resolvedConnectId,
2127
- signal,
2128
- !!fingerprint?.deviceId && !fingerprint.skipFingerprint
2129
- );
2130
- const retrySessionId = this._sessions.get(retryConnectId);
2131
- if (!retrySessionId) throw originalErr;
2132
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2133
- const fp = await this._abortable(
2134
- signal,
2135
- this._verifyDeviceFingerprintWithSession(
2136
- retrySessionId,
2137
- fingerprint.deviceId,
2138
- fingerprint.chain
2139
- )
2140
- );
2141
- if (!fp.success) {
2142
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2143
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2144
- });
2145
- }
2146
- }
2147
- return this._callConnector(retrySessionId, method, params, signal);
2148
- }
2149
3098
  _sleepAbortable(ms, signal) {
2150
3099
  return new Promise((resolve, reject) => {
2151
3100
  if (signal.aborted) {
@@ -2164,111 +3113,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2164
3113
  });
2165
3114
  }
2166
3115
  /**
2167
- * Clear stale session, reconnect, and retry the call.
2168
- *
2169
- * Timeout recovery starts with a full connector reset. After an APDU
2170
- * timeout, DMK/transport state may still emit malformed responses; retrying
2171
- * on the same DMK can poison the next chain switch.
2172
- */
2173
- async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
2174
- this.connector.reset();
2175
- this._sessions.clear();
2176
- this._discoveredDevices.clear();
2177
- this._connectingPromise = null;
2178
- const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
2179
- const retryConnectId = await this.ensureConnected(
2180
- targetConnectId,
2181
- signal,
2182
- allowUsbEphemeralFallback
2183
- );
2184
- const retrySessionId = this._sessions.get(retryConnectId);
2185
- if (!retrySessionId) {
2186
- throw originalErr;
2187
- }
2188
- try {
2189
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2190
- const fp = await this._abortable(
2191
- signal,
2192
- this._verifyDeviceFingerprintWithSession(
2193
- retrySessionId,
2194
- fingerprint.deviceId,
2195
- fingerprint.chain
2196
- )
2197
- );
2198
- if (!fp.success) {
2199
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2200
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2201
- });
2202
- }
2203
- }
2204
- return await this._callConnector(retrySessionId, method, params, signal);
2205
- } catch (retryErr) {
2206
- if (signal.aborted) throw retryErr;
2207
- this.connector.reset();
2208
- this._sessions.clear();
2209
- this._discoveredDevices.clear();
2210
- this._connectingPromise = null;
2211
- if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
2212
- throw retryErr;
2213
- }
2214
- debugLog(
2215
- "[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
2216
- );
2217
- this.connector.reset();
2218
- this._sessions.clear();
2219
- this._discoveredDevices.clear();
2220
- this._connectingPromise = null;
2221
- const finalConnectId = await this.ensureConnected(
2222
- targetConnectId,
2223
- signal,
2224
- allowUsbEphemeralFallback
2225
- );
2226
- const finalSessionId = this._sessions.get(finalConnectId);
2227
- if (!finalSessionId) {
2228
- throw originalErr;
2229
- }
2230
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2231
- const fp = await this._abortable(
2232
- signal,
2233
- this._verifyDeviceFingerprintWithSession(
2234
- finalSessionId,
2235
- fingerprint.deviceId,
2236
- fingerprint.chain
2237
- )
2238
- );
2239
- if (!fp.success) {
2240
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2241
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2242
- });
2243
- }
2244
- }
2245
- return this._callConnector(finalSessionId, method, params, signal);
2246
- }
2247
- }
2248
- /**
2249
- * Ensure OS-level device permission (Bluetooth / USB) before proceeding.
2250
- *
2251
- * Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
2252
- * `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
2253
- * prompt → user tap" plus a generous margin). If the consumer never wires
2254
- * a handler or never replies, the wait times out and the operation fails
2255
- * fast so scanners/callers don't hang silently.
2256
- *
2257
- * - No connectId (searchDevices): environment-level permission
2258
- * - With connectId (business methods): device-level permission
3116
+ * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3117
+ * replies. Without connectId the request is environment-level, else device-level.
2259
3118
  */
2260
3119
  async _ensureDevicePermission(connectId, deviceId, signal) {
2261
3120
  if (signal?.aborted) {
2262
3121
  _LedgerAdapter._throwIfAborted(signal);
2263
3122
  }
2264
3123
  const transportType = this.activeTransport ?? "hid";
3124
+ const operationId = this._activeOperationId();
2265
3125
  const waitPromise = this._uiRegistry.wait(
2266
3126
  import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2267
- { timeoutMs: 6e4 }
3127
+ { timeoutMs: 6e4, operationId }
2268
3128
  );
2269
3129
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2270
3130
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2271
- payload: { transportType, connectId, deviceId }
3131
+ payload: { transportType, connectId, deviceId, operationId }
2272
3132
  });
2273
3133
  let response;
2274
3134
  const onAbort = () => {
@@ -2314,7 +3174,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2314
3174
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
2315
3175
  const e = err;
2316
3176
  const params = e.code === import_hwk_adapter_core3.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
2317
- return ledgerFailure(e.code, e.message ?? "Unknown error", e.appName, tag, params);
3177
+ return ledgerFailure(
3178
+ e.code,
3179
+ e.message ?? "Unknown error",
3180
+ e.appName,
3181
+ tag,
3182
+ params,
3183
+ void 0,
3184
+ (0, import_hwk_adapter_core3.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
3185
+ );
2318
3186
  }
2319
3187
  const mapped = mapLedgerError(err);
2320
3188
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -2341,7 +3209,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2341
3209
  deviceId: device.deviceId,
2342
3210
  connectId: device.connectId,
2343
3211
  label: device.name,
2344
- connectionType: this.connector.connectionType,
3212
+ connectionType: device.connectionType ?? this.connector.connectionType,
2345
3213
  rssi: device.rssi,
2346
3214
  isConnectable: device.isConnectable,
2347
3215
  serialNumber: device.serialNumber,
@@ -2366,7 +3234,7 @@ _LedgerAdapter.APP_INSTALL_PROGRESS_MIN_DELTA = 0.05;
2366
3234
  var LedgerAdapter = _LedgerAdapter;
2367
3235
 
2368
3236
  // src/connector/LedgerConnectorBase.ts
2369
- var import_hwk_adapter_core13 = require("@onekeyfe/hwk-adapter-core");
3237
+ var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
2370
3238
 
2371
3239
  // src/device/LedgerDeviceManager.ts
2372
3240
  var LedgerDeviceManager = class {
@@ -2644,6 +3512,7 @@ var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
2644
3512
  // src/signer/deviceActionToPromise.ts
2645
3513
  var import_device_management_kit = require("@ledgerhq/device-management-kit");
2646
3514
  var IDLE_WATCHDOG_MS = 65e3;
3515
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2647
3516
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
2648
3517
  return new Promise((resolve, reject) => {
2649
3518
  let settled = false;
@@ -2831,7 +3700,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
2831
3700
  }
2832
3701
 
2833
3702
  // src/signer/SignerEth.ts
2834
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2835
3703
  var SignerEth = class {
2836
3704
  // eslint-disable-next-line no-useless-constructor, no-empty-function
2837
3705
  constructor(_sdk) {
@@ -2902,7 +3770,7 @@ var SignerManager = class _SignerManager {
2902
3770
  return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
2903
3771
  }
2904
3772
  static _createContextModule() {
2905
- const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
3773
+ const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2906
3774
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
2907
3775
  }
2908
3776
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -2940,6 +3808,27 @@ function collapseSignerInteraction(interaction) {
2940
3808
  return import_hwk_adapter_core5.EConnectorInteraction.ConfirmOnDevice;
2941
3809
  }
2942
3810
  }
3811
+ function wireSignerToSession(ctx, sessionId, chain, signer) {
3812
+ signer.onInteraction = (interaction) => {
3813
+ debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3814
+ ctx.emit("ui-event", {
3815
+ type: collapseSignerInteraction(interaction),
3816
+ payload: { sessionId }
3817
+ });
3818
+ };
3819
+ signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3820
+ return signer;
3821
+ }
3822
+ async function runSignerCall(ctx, sessionId, call) {
3823
+ try {
3824
+ return await call();
3825
+ } catch (err) {
3826
+ ctx.invalidateSession(sessionId);
3827
+ throw ctx.wrapError(err);
3828
+ } finally {
3829
+ ctx.clearCanceller(sessionId);
3830
+ }
3831
+ }
2943
3832
 
2944
3833
  // src/connector/chains/evm.ts
2945
3834
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3047,7 +3936,6 @@ var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
3047
3936
  function hexToUtf8(hex) {
3048
3937
  return new TextDecoder().decode((0, import_hwk_adapter_core7.hexToBytes)(hex));
3049
3938
  }
3050
- var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3051
3939
  var SignerBtc = class {
3052
3940
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3053
3941
  constructor(_sdk) {
@@ -3061,7 +3949,7 @@ var SignerBtc = class {
3061
3949
  return deviceActionToPromise(
3062
3950
  action,
3063
3951
  this.onInteraction,
3064
- void 0,
3952
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3065
3953
  this.onRegisterCanceller
3066
3954
  );
3067
3955
  }
@@ -3079,7 +3967,7 @@ var SignerBtc = class {
3079
3967
  const result = await deviceActionToPromise(
3080
3968
  action,
3081
3969
  this.onInteraction,
3082
- void 0,
3970
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3083
3971
  this.onRegisterCanceller
3084
3972
  );
3085
3973
  debugLog(
@@ -3115,7 +4003,7 @@ var SignerBtc = class {
3115
4003
  return deviceActionToPromise(
3116
4004
  action,
3117
4005
  this.onInteraction,
3118
- INTERACTIVE_TIMEOUT_MS2,
4006
+ INTERACTIVE_TIMEOUT_MS,
3119
4007
  this.onRegisterCanceller
3120
4008
  );
3121
4009
  }
@@ -3128,7 +4016,7 @@ var SignerBtc = class {
3128
4016
  return deviceActionToPromise(
3129
4017
  action,
3130
4018
  this.onInteraction,
3131
- INTERACTIVE_TIMEOUT_MS2,
4019
+ INTERACTIVE_TIMEOUT_MS,
3132
4020
  this.onRegisterCanceller
3133
4021
  );
3134
4022
  }
@@ -3141,7 +4029,7 @@ var SignerBtc = class {
3141
4029
  return deviceActionToPromise(
3142
4030
  action,
3143
4031
  this.onInteraction,
3144
- INTERACTIVE_TIMEOUT_MS2,
4032
+ INTERACTIVE_TIMEOUT_MS,
3145
4033
  this.onRegisterCanceller
3146
4034
  );
3147
4035
  }
@@ -3164,7 +4052,21 @@ function _purposeToTemplate(purpose, DDT) {
3164
4052
  });
3165
4053
  }
3166
4054
  }
4055
+ function assertBitcoinMainnet(coin) {
4056
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4057
+ throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4058
+ code: import_hwk_adapter_core8.HardwareErrorCode.ChainNotSupported
4059
+ });
4060
+ }
4061
+ }
3167
4062
  async function btcGetAddress(ctx, sessionId, params) {
4063
+ assertBitcoinMainnet(params.coin);
4064
+ if (normalizePath(params.path).split("/").length !== 3) {
4065
+ throw Object.assign(
4066
+ new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4067
+ { code: import_hwk_adapter_core8.HardwareErrorCode.InvalidParams }
4068
+ );
4069
+ }
3168
4070
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3169
4071
  const path = normalizePath(params.path);
3170
4072
  try {
@@ -3195,6 +4097,7 @@ async function btcGetAddress(ctx, sessionId, params) {
3195
4097
  }
3196
4098
  }
3197
4099
  async function btcGetPublicKey(ctx, sessionId, params) {
4100
+ assertBitcoinMainnet(params.coin);
3198
4101
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3199
4102
  const path = normalizePath(params.path);
3200
4103
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -3373,6 +4276,7 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
3373
4276
 
3374
4277
  // src/connector/chains/sol.ts
3375
4278
  var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
4279
+ var import_bs58 = __toESM(require("bs58"));
3376
4280
 
3377
4281
  // src/signer/SignerSol.ts
3378
4282
  var SignerSol = class {
@@ -3390,7 +4294,7 @@ var SignerSol = class {
3390
4294
  return deviceActionToPromise(
3391
4295
  action,
3392
4296
  this.onInteraction,
3393
- void 0,
4297
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3394
4298
  this.onRegisterCanceller
3395
4299
  );
3396
4300
  }
@@ -3402,7 +4306,7 @@ var SignerSol = class {
3402
4306
  return deviceActionToPromise(
3403
4307
  action,
3404
4308
  this.onInteraction,
3405
- void 0,
4309
+ INTERACTIVE_TIMEOUT_MS,
3406
4310
  this.onRegisterCanceller
3407
4311
  );
3408
4312
  }
@@ -3415,7 +4319,7 @@ var SignerSol = class {
3415
4319
  return deviceActionToPromise(
3416
4320
  action,
3417
4321
  this.onInteraction,
3418
- void 0,
4322
+ INTERACTIVE_TIMEOUT_MS,
3419
4323
  this.onRegisterCanceller
3420
4324
  );
3421
4325
  }
@@ -3456,8 +4360,21 @@ async function solSignMessage(ctx, sessionId, params) {
3456
4360
  const path = normalizePath(params.path);
3457
4361
  const messageBytes = (0, import_hwk_adapter_core9.hexToBytes)(params.message);
3458
4362
  try {
4363
+ if (params.messageVersion === 1) {
4364
+ const preparedMessage = (0, import_hwk_adapter_core9.prepareSolanaOffchainMessageV1)({
4365
+ message: messageBytes,
4366
+ requiredSigners: params.requiredSigners
4367
+ });
4368
+ const { SignMessageVersion } = await ctx.importLedgerKit(
4369
+ "@ledgerhq/device-signer-kit-solana"
4370
+ );
4371
+ const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4372
+ version: SignMessageVersion.Raw
4373
+ });
4374
+ return { signature: decodeBase58Signature(result2.signature) };
4375
+ }
3459
4376
  const result = await solSigner.signMessage(path, messageBytes);
3460
- return { signature: result.signature };
4377
+ return { signature: decodeBase58EnvelopeSignature(result.signature) };
3461
4378
  } catch (err) {
3462
4379
  ctx.invalidateSession(sessionId);
3463
4380
  throw ctx.wrapError(err);
@@ -3465,11 +4382,27 @@ async function solSignMessage(ctx, sessionId, params) {
3465
4382
  ctx.clearCanceller(sessionId);
3466
4383
  }
3467
4384
  }
4385
+ function decodeBase58Signature(signature) {
4386
+ const bytes = import_bs58.default.decode(signature);
4387
+ if (bytes.length !== 64) {
4388
+ throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4389
+ }
4390
+ return (0, import_hwk_adapter_core9.bytesToHex)(bytes);
4391
+ }
4392
+ function decodeBase58EnvelopeSignature(envelope) {
4393
+ const bytes = import_bs58.default.decode(envelope);
4394
+ if (bytes.length < 65 || bytes[0] !== 1) {
4395
+ throw new Error("Ledger Solana signature envelope is invalid");
4396
+ }
4397
+ return (0, import_hwk_adapter_core9.bytesToHex)(bytes.subarray(1, 65));
4398
+ }
3468
4399
  async function _createSolSigner(ctx, sessionId) {
3469
4400
  const dmk = await ctx.getOrCreateDmk();
3470
- const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4401
+ const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4402
+ "@ledgerhq/context-module"
4403
+ );
3471
4404
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
3472
- const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4405
+ const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3473
4406
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
3474
4407
  const signer = new SignerSol(sdkSigner);
3475
4408
  signer.onInteraction = (interaction) => {
@@ -3485,360 +4418,151 @@ async function _createSolSigner(ctx, sessionId) {
3485
4418
  return signer;
3486
4419
  }
3487
4420
 
3488
- // src/connector/chains/tron.ts
3489
- var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
3490
- var import_hw_app_trx = __toESM(require("@ledgerhq/hw-app-trx"));
3491
-
3492
- // src/connector/chains/legacyChainCall.ts
3493
- var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
3494
-
3495
- // src/app/AppManager.ts
3496
- var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
4421
+ // src/connector/chains/zcash.ts
3497
4422
  var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
3498
- var APP_NAME_MAP = {
3499
- ETH: "Ethereum",
3500
- BTC: "Bitcoin",
3501
- SOL: "Solana",
3502
- TRX: "Tron",
3503
- XRP: "XRP",
3504
- ADA: "Cardano",
3505
- DOT: "Polkadot",
3506
- ATOM: "Cosmos"
3507
- };
3508
- var DASHBOARD_APP_NAME = "BOLOS";
3509
- var AppManager = class {
3510
- constructor(dmk, options) {
3511
- this._dmk = dmk;
3512
- this._waitMs = options?.waitMs ?? 1e3;
3513
- this._maxRetries = options?.maxRetries ?? 10;
3514
- }
3515
- /**
3516
- * Return the Ledger app name for a given chain ticker,
3517
- * or undefined if the chain is not supported.
3518
- */
3519
- static getAppName(chain) {
3520
- return APP_NAME_MAP[chain];
3521
- }
3522
- /**
3523
- * Ensure the target app is open on the device identified by `sessionId`.
3524
- *
3525
- * Flow:
3526
- * 1. Check the currently running app.
3527
- * 2. If it is already the target, return immediately.
3528
- * 3. If a different app is running (not dashboard), close it first.
3529
- * 4. Open the target app.
3530
- * 5. Poll until the device confirms the target app is running.
3531
- */
3532
- /**
3533
- * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
3534
- * device is about to display "Open <app>" on screen and wait for the
3535
- * user's button press. UI consumers should show their "open app" prompt
3536
- * in response. NOT called when the target app is already open (no user
3537
- * interaction needed in that case).
3538
- *
3539
- * Important: OpenAppCommand is blocking. It does not resolve until the user
3540
- * has physically confirmed on the device, so anything that runs AFTER
3541
- * `await this._openApp(...)` lands AFTER the prompt is already gone.
3542
- * Hence the callback must fire BEFORE that await.
3543
- */
3544
- async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
3545
- const currentApp = await this._getCurrentApp(sessionId);
3546
- if (currentApp === targetAppName) {
3547
- return;
3548
- }
3549
- if (!this._isDashboard(currentApp)) {
3550
- await this._closeCurrentApp(sessionId);
3551
- await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
3552
- }
3553
- onConfirmOnDevice?.();
3554
- await this._openApp(sessionId, targetAppName);
3555
- await this._waitForApp(sessionId, targetAppName);
4423
+
4424
+ // src/signer/SignerZcash.ts
4425
+ var SignerZcash = class {
4426
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4427
+ constructor(_sdk) {
4428
+ this._sdk = _sdk;
3556
4429
  }
3557
- // ---------------------------------------------------------------------------
3558
- // Private helpers
3559
- // ---------------------------------------------------------------------------
3560
- async _getCurrentApp(sessionId) {
3561
- const result = await this._dmk.sendCommand({
3562
- sessionId,
3563
- command: new import_device_management_kit2.GetAppAndVersionCommand()
3564
- });
3565
- if ((0, import_device_management_kit2.isSuccessCommandResult)(result)) {
3566
- debugLog("[AppManager] currentApp:", result.data.name);
3567
- return result.data.name;
3568
- }
3569
- const errResult = result;
3570
- const dmkErr = errResult.error ?? {};
3571
- const original = dmkErr.originalError;
3572
- debugLog(
3573
- "[AppManager] _getCurrentApp failed sessionId=",
3574
- sessionId,
3575
- "tag=",
3576
- dmkErr._tag,
3577
- "errorCode=",
3578
- dmkErr.errorCode,
3579
- "message=",
3580
- dmkErr.message,
3581
- "originalErrorMessage=",
3582
- original?.message ?? String(original ?? "")
3583
- );
3584
- throw Object.assign(
3585
- new Error(
3586
- dmkErr.message ?? "Failed to get current app from device"
3587
- ),
3588
- {
3589
- _tag: dmkErr._tag,
3590
- errorCode: dmkErr.errorCode,
3591
- originalError: original
3592
- }
4430
+ /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4431
+ async getFullViewingKey(derivationPath, options) {
4432
+ const action = this._sdk.getFullViewingKey(derivationPath, options);
4433
+ return deviceActionToPromise(
4434
+ action,
4435
+ this.onInteraction,
4436
+ void 0,
4437
+ this.onRegisterCanceller
3593
4438
  );
3594
4439
  }
3595
- async _openApp(sessionId, appName) {
3596
- const result = await this._dmk.sendCommand({
3597
- sessionId,
3598
- command: new import_device_management_kit2.OpenAppCommand({ appName })
3599
- });
3600
- if (!(0, import_device_management_kit2.isSuccessCommandResult)(result)) {
3601
- const dmkErr = result.error;
3602
- const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
3603
- const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
3604
- debugLog(
3605
- "[AppManager] openApp failed:",
3606
- appName,
3607
- "errorCode:",
3608
- errorCode,
3609
- "tag:",
3610
- dmkErr._tag
3611
- );
3612
- let code;
3613
- if (errorCode === "6807" || /unknown application/i.test(message)) {
3614
- code = import_hwk_adapter_core10.HardwareErrorCode.AppNotInstalled;
3615
- } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
3616
- code = import_hwk_adapter_core10.HardwareErrorCode.UserRejected;
3617
- }
3618
- throw Object.assign(new Error(`Failed to open "${appName}"`), {
3619
- _tag: ERROR_TAG.OpenAppCommand,
3620
- code,
3621
- errorCode,
3622
- statusCode: errorCode,
3623
- appName,
3624
- originalError: dmkErr
3625
- });
3626
- }
3627
- }
3628
- async _closeCurrentApp(sessionId) {
3629
- debugLog("[AppManager] closeCurrentApp");
3630
- await this._dmk.sendCommand({
3631
- sessionId,
3632
- command: new import_device_management_kit2.CloseAppCommand()
3633
- });
3634
- }
3635
- /**
3636
- * Poll the device until the expected app is reported as running,
3637
- * or throw after `_maxRetries` attempts.
3638
- */
3639
- async _waitForApp(sessionId, expectedAppName) {
3640
- let lastSeen = "";
3641
- for (let i = 0; i < this._maxRetries; i++) {
3642
- await this._wait();
3643
- const current = await this._getCurrentApp(sessionId);
3644
- lastSeen = current;
3645
- if (current === expectedAppName) {
3646
- return;
3647
- }
3648
- }
3649
- debugLog(
3650
- "[AppManager] waitForApp exhausted: expected=",
3651
- expectedAppName,
3652
- "lastSeen=",
3653
- lastSeen
3654
- );
3655
- throw new Error(
3656
- `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
4440
+ /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4441
+ async getShieldedAddress(derivationPath, options) {
4442
+ const action = this._sdk.getShieldedAddress(derivationPath, options);
4443
+ return deviceActionToPromise(
4444
+ action,
4445
+ this.onInteraction,
4446
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4447
+ this.onRegisterCanceller
3657
4448
  );
3658
4449
  }
3659
- _isDashboard(appName) {
3660
- return appName === DASHBOARD_APP_NAME;
3661
- }
3662
- _wait() {
3663
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3664
- }
3665
4450
  };
3666
4451
 
3667
- // src/connector/chains/legacyChainCall.ts
3668
- function isLegacyWrongAppError(err, _appName) {
3669
- return isWrongAppError(err);
4452
+ // src/connector/chains/zcash.ts
4453
+ async function zcashGetFullViewingKey(ctx, sessionId, params) {
4454
+ const signer = await _createZcashSigner(ctx, sessionId);
4455
+ const path = normalizePath(params.path);
4456
+ const mode = params.mode ?? "ufvk";
4457
+ return runSignerCall(ctx, sessionId, async () => {
4458
+ const result = await signer.getFullViewingKey(path, { mode });
4459
+ if (result.mode === "ufvk") {
4460
+ return { path: params.path, mode, ufvk: result.fullViewingKey };
4461
+ }
4462
+ return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core10.bytesToHex)(result.fullViewingKey) };
4463
+ });
3670
4464
  }
3671
- async function withLegacyChainCall(ctx, sessionId, options, action) {
3672
- const { appName, needsConfirmation } = options;
3673
- let openAppPromptShown = false;
3674
- const onAppOpenPrompt = () => {
3675
- openAppPromptShown = true;
3676
- ctx.emit("ui-event", {
3677
- type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
3678
- payload: { sessionId }
4465
+ async function zcashGetShieldedAddress(ctx, sessionId, params) {
4466
+ const signer = await _createZcashSigner(ctx, sessionId);
4467
+ const path = normalizePath(params.path);
4468
+ return runSignerCall(ctx, sessionId, async () => {
4469
+ const result = await signer.getShieldedAddress(path, {
4470
+ checkOnDevice: params.showOnDevice ?? false
3679
4471
  });
3680
- };
3681
- const closeOpenAppUiIfShown = () => {
3682
- if (openAppPromptShown) {
3683
- ctx.emit("ui-event", {
3684
- type: import_hwk_adapter_core11.EConnectorInteraction.InteractionComplete,
3685
- payload: { sessionId }
3686
- });
3687
- openAppPromptShown = false;
3688
- }
3689
- };
3690
- try {
3691
- await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
3692
- } catch (err) {
3693
- debugLog(
3694
- "[LegacyChainCall] pre-flight ensureAppOpen failed:",
3695
- appName,
3696
- err?.message
3697
- );
3698
- closeOpenAppUiIfShown();
3699
- throw ctx.wrapError(err, { defaultAppName: appName });
3700
- }
3701
- const runOnce = async () => {
3702
- let confirmEmitted = false;
3703
- if (needsConfirmation) {
3704
- ctx.emit("ui-event", {
3705
- type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOnDevice,
3706
- payload: { sessionId }
3707
- });
3708
- confirmEmitted = true;
3709
- }
3710
- try {
3711
- return await action(sessionId);
3712
- } finally {
3713
- if (confirmEmitted || openAppPromptShown) {
3714
- ctx.emit("ui-event", {
3715
- type: import_hwk_adapter_core11.EConnectorInteraction.InteractionComplete,
3716
- payload: { sessionId }
3717
- });
3718
- openAppPromptShown = false;
3719
- }
3720
- }
3721
- };
3722
- try {
3723
- return await runOnce();
3724
- } catch (err) {
3725
- if (!isLegacyWrongAppError(err, appName)) {
3726
- debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
3727
- ctx.invalidateSession(sessionId);
3728
- throw ctx.wrapError(err, { defaultAppName: appName });
3729
- }
3730
- debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
3731
- try {
3732
- await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
3733
- } catch (switchErr) {
3734
- debugLog(
3735
- "[LegacyChainCall] retry ensureAppOpen failed:",
3736
- appName,
3737
- switchErr?.message
3738
- );
3739
- closeOpenAppUiIfShown();
3740
- throw ctx.wrapError(switchErr, { defaultAppName: appName });
3741
- }
3742
- ctx.clearAllSigners();
3743
- const result = await runOnce();
3744
- debugLog("[LegacyChainCall] retry succeeded:", appName);
3745
- return result;
3746
- }
4472
+ return { address: result.address, path: params.path };
4473
+ });
3747
4474
  }
3748
- async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4475
+ async function _createZcashSigner(ctx, sessionId) {
3749
4476
  const dmk = await ctx.getOrCreateDmk();
3750
- const appManager = new AppManager(dmk);
3751
- await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4477
+ const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4478
+ const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4479
+ return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3752
4480
  }
3753
4481
 
3754
- // src/transport/DmkTransport.ts
3755
- var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
3756
- var DmkTransport = class extends import_hw_transport.default {
3757
- constructor(dmk, sessionId) {
3758
- super();
3759
- this._dmk = dmk;
3760
- this._sessionId = sessionId;
4482
+ // src/connector/chains/tron.ts
4483
+ var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
4484
+
4485
+ // src/signer/SignerTron.ts
4486
+ var SignerTron = class {
4487
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4488
+ constructor(_sdk) {
4489
+ this._sdk = _sdk;
3761
4490
  }
3762
- async exchange(apdu) {
3763
- const response = await this._dmk.sendApdu({
3764
- sessionId: this._sessionId,
3765
- apdu: new Uint8Array(apdu)
3766
- });
3767
- const { data, statusCode } = response;
3768
- const result = Buffer.alloc(data.length + 2);
3769
- if (data.length > 0) {
3770
- result.set(data, 0);
3771
- }
3772
- result.set(statusCode, data.length);
3773
- return result;
4491
+ /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4492
+ async getAddress(derivationPath, options) {
4493
+ const action = this._sdk.getAddress(derivationPath, options);
4494
+ const result = await deviceActionToPromise(
4495
+ action,
4496
+ this.onInteraction,
4497
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4498
+ this.onRegisterCanceller
4499
+ );
4500
+ return { address: result.address, publicKey: result.publicKey };
3774
4501
  }
3775
- async close() {
4502
+ /** Sign a protobuf-encoded raw transaction. */
4503
+ async signTransaction(derivationPath, transaction, options) {
4504
+ const action = this._sdk.signTransaction(derivationPath, transaction, options);
4505
+ return deviceActionToPromise(
4506
+ action,
4507
+ this.onInteraction,
4508
+ INTERACTIVE_TIMEOUT_MS,
4509
+ this.onRegisterCanceller
4510
+ );
4511
+ }
4512
+ /** Sign a personal message (TIP-191). */
4513
+ async signPersonalMessage(derivationPath, message, options) {
4514
+ const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4515
+ return deviceActionToPromise(
4516
+ action,
4517
+ this.onInteraction,
4518
+ INTERACTIVE_TIMEOUT_MS,
4519
+ this.onRegisterCanceller
4520
+ );
3776
4521
  }
3777
4522
  };
3778
4523
 
3779
4524
  // src/connector/chains/tron.ts
3780
4525
  async function tronGetAddress(ctx, sessionId, params) {
4526
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3781
4527
  const path = normalizePath(params.path);
3782
- const showOnDevice = params.showOnDevice ?? false;
3783
- return withLegacyChainCall(
3784
- ctx,
3785
- sessionId,
3786
- {
3787
- appName: "Tron",
3788
- // Only show "confirm on device" UI when the device is actually going
3789
- // to display the address for the user to verify.
3790
- needsConfirmation: showOnDevice
3791
- },
3792
- async (sid) => {
3793
- const trx = await _createTrx(ctx, sid);
3794
- const result = await trx.getAddress(path, showOnDevice);
3795
- return { address: result.address, publicKey: result.publicKey, path: params.path };
3796
- }
3797
- );
4528
+ return runSignerCall(ctx, sessionId, async () => {
4529
+ const result = await tronSigner.getAddress(path, {
4530
+ checkOnDevice: params.showOnDevice ?? false
4531
+ });
4532
+ return { address: result.address, publicKey: result.publicKey, path: params.path };
4533
+ });
3798
4534
  }
3799
4535
  async function tronSignTransaction(ctx, sessionId, params) {
3800
4536
  if (!params.rawTxHex) {
3801
4537
  throw Object.assign(
3802
4538
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
3803
- { code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
4539
+ { code: import_hwk_adapter_core11.HardwareErrorCode.InvalidParams }
3804
4540
  );
3805
4541
  }
4542
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3806
4543
  const path = normalizePath(params.path);
3807
- return withLegacyChainCall(
3808
- ctx,
3809
- sessionId,
3810
- { appName: "Tron", needsConfirmation: true },
3811
- async (sid) => {
3812
- const trx = await _createTrx(ctx, sid);
3813
- const signature = await trx.signTransaction(
3814
- path,
3815
- params.rawTxHex,
3816
- params.tokenSignatures ?? []
3817
- );
3818
- return { signature };
3819
- }
3820
- );
4544
+ return runSignerCall(ctx, sessionId, async () => {
4545
+ const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core11.hexToBytes)(params.rawTxHex));
4546
+ return { signature: (0, import_hwk_adapter_core11.bytesToHex)(signature) };
4547
+ });
3821
4548
  }
3822
4549
  async function tronSignMessage(ctx, sessionId, params) {
4550
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3823
4551
  const path = normalizePath(params.path);
3824
- return withLegacyChainCall(
3825
- ctx,
3826
- sessionId,
3827
- { appName: "Tron", needsConfirmation: true },
3828
- async (sid) => {
3829
- const trx = await _createTrx(ctx, sid);
3830
- const signature = await trx.signPersonalMessage(path, params.messageHex);
3831
- return { signature };
3832
- }
3833
- );
4552
+ return runSignerCall(ctx, sessionId, async () => {
4553
+ const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core11.hexToBytes)(params.messageHex));
4554
+ return { signature: (0, import_hwk_adapter_core11.bytesToHex)(signature) };
4555
+ });
3834
4556
  }
3835
- async function _createTrx(ctx, sessionId) {
4557
+ async function _createTronSigner(ctx, sessionId) {
3836
4558
  const dmk = await ctx.getOrCreateDmk();
3837
- return new import_hw_app_trx.default(new DmkTransport(dmk, sessionId));
4559
+ const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4560
+ const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4561
+ return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3838
4562
  }
3839
4563
 
3840
4564
  // src/device-apps/customActions.ts
3841
- var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
4565
+ var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
3842
4566
  var import_rxjs = require("rxjs");
3843
4567
  var GetOsVersionDeviceAction = class {
3844
4568
  // eslint-disable-next-line no-useless-constructor, no-empty-function
@@ -3852,7 +4576,7 @@ var GetOsVersionDeviceAction = class {
3852
4576
  (async () => {
3853
4577
  try {
3854
4578
  subject.next({
3855
- status: import_device_management_kit3.DeviceActionStatus.Pending,
4579
+ status: import_device_management_kit2.DeviceActionStatus.Pending,
3856
4580
  intermediateValue: { requiredUserInteraction: "none" }
3857
4581
  });
3858
4582
  const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
@@ -3861,11 +4585,11 @@ var GetOsVersionDeviceAction = class {
3861
4585
  const errObj = result?.error;
3862
4586
  throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
3863
4587
  }
3864
- subject.next({ status: import_device_management_kit3.DeviceActionStatus.Completed, output: result.data });
4588
+ subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
3865
4589
  subject.complete();
3866
4590
  } catch (err) {
3867
4591
  if (cancelled) return;
3868
- subject.next({ status: import_device_management_kit3.DeviceActionStatus.Error, error: err });
4592
+ subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
3869
4593
  subject.complete();
3870
4594
  }
3871
4595
  })();
@@ -3873,7 +4597,7 @@ var GetOsVersionDeviceAction = class {
3873
4597
  observable: subject.asObservable(),
3874
4598
  cancel: () => {
3875
4599
  cancelled = true;
3876
- subject.next({ status: import_device_management_kit3.DeviceActionStatus.Stopped });
4600
+ subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
3877
4601
  subject.complete();
3878
4602
  }
3879
4603
  };
@@ -3891,7 +4615,7 @@ var ListAvailableAppsDeviceAction = class {
3891
4615
  (async () => {
3892
4616
  try {
3893
4617
  subject.next({
3894
- status: import_device_management_kit3.DeviceActionStatus.Pending,
4618
+ status: import_device_management_kit2.DeviceActionStatus.Pending,
3895
4619
  intermediateValue: { requiredUserInteraction: "none" }
3896
4620
  });
3897
4621
  const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
@@ -3908,11 +4632,11 @@ var ListAvailableAppsDeviceAction = class {
3908
4632
  throw new Error(httpErr?.message ?? "Manager API getAppList failed");
3909
4633
  }
3910
4634
  const apps = either.extract();
3911
- subject.next({ status: import_device_management_kit3.DeviceActionStatus.Completed, output: apps });
4635
+ subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
3912
4636
  subject.complete();
3913
4637
  } catch (err) {
3914
4638
  if (cancelled) return;
3915
- subject.next({ status: import_device_management_kit3.DeviceActionStatus.Error, error: err });
4639
+ subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
3916
4640
  subject.complete();
3917
4641
  }
3918
4642
  })();
@@ -3920,7 +4644,7 @@ var ListAvailableAppsDeviceAction = class {
3920
4644
  observable: subject.asObservable(),
3921
4645
  cancel: () => {
3922
4646
  cancelled = true;
3923
- subject.next({ status: import_device_management_kit3.DeviceActionStatus.Stopped });
4647
+ subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
3924
4648
  subject.complete();
3925
4649
  }
3926
4650
  };
@@ -4013,7 +4737,7 @@ var DeviceApps = class {
4013
4737
  seTargetId: v.seTargetId,
4014
4738
  mcuTargetId: v.mcuTargetId,
4015
4739
  seVersion: v.seVersion,
4016
- seFlagsHex: bytesToHex2(v.seFlags),
4740
+ seFlagsHex: bytesToHex4(v.seFlags),
4017
4741
  mcuSephVersion: v.mcuSephVersion,
4018
4742
  mcuBootloaderVersion: v.mcuBootloaderVersion,
4019
4743
  hwVersion: v.hwVersion
@@ -4087,7 +4811,7 @@ var DeviceApps = class {
4087
4811
  }
4088
4812
  }
4089
4813
  };
4090
- function bytesToHex2(bytes) {
4814
+ function bytesToHex4(bytes) {
4091
4815
  if (!bytes) return "";
4092
4816
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4093
4817
  }
@@ -4130,10 +4854,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
4130
4854
  evm: "Ethereum",
4131
4855
  btc: "Bitcoin",
4132
4856
  sol: "Solana",
4133
- tron: "Tron"
4857
+ tron: "Tron",
4858
+ zcash: "Zcash"
4134
4859
  };
4135
4860
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4136
- Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
4861
+ Object.values(import_hwk_adapter_core12.HardwareErrorCode).filter((value) => typeof value === "number")
4137
4862
  );
4138
4863
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4139
4864
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4170,6 +4895,10 @@ async function defaultLedgerKitImporter(pkg) {
4170
4895
  return import("@ledgerhq/device-signer-kit-bitcoin");
4171
4896
  case "@ledgerhq/device-signer-kit-solana":
4172
4897
  return import("@ledgerhq/device-signer-kit-solana");
4898
+ case "@ledgerhq/device-signer-kit-tron":
4899
+ return import("@ledgerhq/device-signer-kit-tron");
4900
+ case "@ledgerhq/device-signer-kit-zcash":
4901
+ return import("@ledgerhq/device-signer-kit-zcash");
4173
4902
  case "@ledgerhq/context-module":
4174
4903
  return import("@ledgerhq/context-module");
4175
4904
  default:
@@ -4229,6 +4958,7 @@ var LedgerConnectorBase = class {
4229
4958
  this._ctx = {
4230
4959
  emit: (event, data) => this._emit(event, data),
4231
4960
  invalidateSession: (sid) => this._invalidateSession(sid),
4961
+ teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4232
4962
  wrapError: (err, opts) => this._wrapError(err, opts),
4233
4963
  getOrCreateDmk: () => this._getOrCreateDmk(),
4234
4964
  getDeviceManager: () => this._getDeviceManager(),
@@ -4280,7 +5010,7 @@ var LedgerConnectorBase = class {
4280
5010
  async searchDevices() {
4281
5011
  const dm = await this._getDeviceManager();
4282
5012
  const descriptors = await this._discoverDescriptors(dm);
4283
- const resolvedDescriptors = descriptors.filter((d) => !(0, import_hwk_adapter_core13.isKnownNonTargetHardwareVendor)(d, "ledger")).map((d) => ({
5013
+ const resolvedDescriptors = descriptors.filter((d) => !(0, import_hwk_adapter_core12.isKnownNonTargetHardwareVendor)(d, "ledger")).map((d) => ({
4284
5014
  descriptor: d,
4285
5015
  connectId: this._resolveConnectId(d)
4286
5016
  }));
@@ -4328,7 +5058,7 @@ var LedgerConnectorBase = class {
4328
5058
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
4329
5059
  );
4330
5060
  err._tag = ERROR_TAG.BlePairingTimeout;
4331
- err.code = import_hwk_adapter_core13.HardwareErrorCode.BlePairingTimeout;
5061
+ err.code = import_hwk_adapter_core12.HardwareErrorCode.BlePairingTimeout;
4332
5062
  reject(err);
4333
5063
  }, HANG_CEILING_MS);
4334
5064
  });
@@ -4361,7 +5091,7 @@ var LedgerConnectorBase = class {
4361
5091
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
4362
5092
  );
4363
5093
  err._tag = ERROR_TAG.DeviceNotAdvertising;
4364
- err.code = import_hwk_adapter_core13.HardwareErrorCode.DeviceNotFound;
5094
+ err.code = import_hwk_adapter_core12.HardwareErrorCode.DeviceNotFound;
4365
5095
  throw err;
4366
5096
  };
4367
5097
  const doConnect = async (path) => {
@@ -4418,14 +5148,14 @@ var LedgerConnectorBase = class {
4418
5148
  this._resetSignersAndSessions();
4419
5149
  if (isLedgerBleConnectionType(this.connectionType)) {
4420
5150
  const tag = err?._tag;
4421
- if (isKnownConnectionTag(tag)) {
5151
+ if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4422
5152
  throw err;
4423
5153
  }
4424
5154
  const wrapped = new Error(
4425
5155
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
4426
5156
  );
4427
5157
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
4428
- wrapped.code = import_hwk_adapter_core13.HardwareErrorCode.BlePairingTimeout;
5158
+ wrapped.code = import_hwk_adapter_core12.HardwareErrorCode.BlePairingTimeout;
4429
5159
  wrapped.originalError = err;
4430
5160
  throw wrapped;
4431
5161
  }
@@ -4503,7 +5233,7 @@ var LedgerConnectorBase = class {
4503
5233
  this._unwatchSessionState(sessionId);
4504
5234
  this._signerManager?.invalidate(sessionId);
4505
5235
  this._cancellers.get(sessionId)?.({
4506
- code: import_hwk_adapter_core13.HardwareErrorCode.DeviceDisconnected,
5236
+ code: import_hwk_adapter_core12.HardwareErrorCode.DeviceDisconnected,
4507
5237
  tag: "DeviceDisconnected",
4508
5238
  message: "Device disconnected"
4509
5239
  });
@@ -4527,9 +5257,9 @@ var LedgerConnectorBase = class {
4527
5257
  if (isAppStuckByApdu(err)) {
4528
5258
  return {
4529
5259
  success: false,
4530
- error: (0, import_hwk_adapter_core13.serializeConnectorError)(
5260
+ error: (0, import_hwk_adapter_core12.serializeConnectorError)(
4531
5261
  Object.assign(new Error("Ledger app is unresponsive"), {
4532
- code: import_hwk_adapter_core13.HardwareErrorCode.DeviceAppStuck,
5262
+ code: import_hwk_adapter_core12.HardwareErrorCode.DeviceAppStuck,
4533
5263
  _tag: ERROR_TAG.DeviceAppStuck,
4534
5264
  originalError: err
4535
5265
  })
@@ -4539,16 +5269,16 @@ var LedgerConnectorBase = class {
4539
5269
  if (isTransportStuck(err)) {
4540
5270
  return {
4541
5271
  success: false,
4542
- error: (0, import_hwk_adapter_core13.serializeConnectorError)(
5272
+ error: (0, import_hwk_adapter_core12.serializeConnectorError)(
4543
5273
  Object.assign(new Error("Device communication interrupted, please retry"), {
4544
- code: import_hwk_adapter_core13.HardwareErrorCode.TransportError,
5274
+ code: import_hwk_adapter_core12.HardwareErrorCode.TransportError,
4545
5275
  _tag: ERROR_TAG.DeviceTransportStuck,
4546
5276
  originalError: err
4547
5277
  })
4548
5278
  )
4549
5279
  };
4550
5280
  }
4551
- return { success: false, error: (0, import_hwk_adapter_core13.serializeConnectorError)(err) };
5281
+ return { success: false, error: (0, import_hwk_adapter_core12.serializeConnectorError)(err) };
4552
5282
  }
4553
5283
  }
4554
5284
  async _dispatch(sessionId, method, params) {
@@ -4587,6 +5317,11 @@ var LedgerConnectorBase = class {
4587
5317
  return solSignTransaction(ctx, sessionId, params);
4588
5318
  case "solSignMessage":
4589
5319
  return solSignMessage(ctx, sessionId, params);
5320
+ // ZCASH
5321
+ case "zcashGetFullViewingKey":
5322
+ return zcashGetFullViewingKey(ctx, sessionId, params);
5323
+ case "zcashGetShieldedAddress":
5324
+ return zcashGetShieldedAddress(ctx, sessionId, params);
4590
5325
  // TRON
4591
5326
  case "tronGetAddress":
4592
5327
  return tronGetAddress(ctx, sessionId, params);
@@ -4611,7 +5346,7 @@ var LedgerConnectorBase = class {
4611
5346
  try {
4612
5347
  return await apps.install(p.appName, ({ progress }) => {
4613
5348
  ctx.emit("ui-event", {
4614
- type: import_hwk_adapter_core13.EConnectorInteraction.AppInstallProgress,
5349
+ type: import_hwk_adapter_core12.EConnectorInteraction.AppInstallProgress,
4615
5350
  payload: {
4616
5351
  sessionId,
4617
5352
  appName: p.appName,
@@ -4620,7 +5355,7 @@ var LedgerConnectorBase = class {
4620
5355
  });
4621
5356
  });
4622
5357
  } catch (err) {
4623
- ctx.invalidateSession(sessionId);
5358
+ ctx.teardownSecureChannelSession(sessionId);
4624
5359
  throw ctx.wrapError(err);
4625
5360
  } finally {
4626
5361
  ctx.clearCanceller(sessionId);
@@ -4710,7 +5445,7 @@ var LedgerConnectorBase = class {
4710
5445
  );
4711
5446
  return { isGenuine: output.isGenuine, deviceId };
4712
5447
  } catch (err) {
4713
- ctx.invalidateSession(sessionId);
5448
+ ctx.teardownSecureChannelSession(sessionId);
4714
5449
  throw ctx.wrapError(err);
4715
5450
  } finally {
4716
5451
  ctx.clearCanceller(sessionId);
@@ -4832,6 +5567,17 @@ var LedgerConnectorBase = class {
4832
5567
  _invalidateSession(sessionId) {
4833
5568
  this._signerManager?.invalidate(sessionId);
4834
5569
  }
5570
+ _teardownSecureChannelSession(sessionId) {
5571
+ const cancel = this._cancellers.get(sessionId);
5572
+ this._cancellers.delete(sessionId);
5573
+ if (cancel) {
5574
+ try {
5575
+ cancel();
5576
+ } catch {
5577
+ }
5578
+ }
5579
+ this._invalidateSession(sessionId);
5580
+ }
4835
5581
  /**
4836
5582
  * Replace an old session with a new one after app switch.
4837
5583
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -4916,7 +5662,7 @@ var LedgerConnectorBase = class {
4916
5662
  * at every catch site. Falls through unchanged for unknown methods.
4917
5663
  */
4918
5664
  _ctxForMethod(method) {
4919
- const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5665
+ const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4920
5666
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
4921
5667
  if (!defaultAppName) return this._ctx;
4922
5668
  return {
@@ -4950,6 +5696,204 @@ var LedgerConnectorBase = class {
4950
5696
  return error;
4951
5697
  }
4952
5698
  };
5699
+
5700
+ // src/transport/DmkTransport.ts
5701
+ var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
5702
+ var DmkTransport = class extends import_hw_transport.default {
5703
+ constructor(dmk, sessionId) {
5704
+ super();
5705
+ this._dmk = dmk;
5706
+ this._sessionId = sessionId;
5707
+ }
5708
+ async exchange(apdu) {
5709
+ const response = await this._dmk.sendApdu({
5710
+ sessionId: this._sessionId,
5711
+ apdu: new Uint8Array(apdu)
5712
+ });
5713
+ const { data, statusCode } = response;
5714
+ const result = Buffer.alloc(data.length + 2);
5715
+ if (data.length > 0) {
5716
+ result.set(data, 0);
5717
+ }
5718
+ result.set(statusCode, data.length);
5719
+ return result;
5720
+ }
5721
+ async close() {
5722
+ }
5723
+ };
5724
+
5725
+ // src/app/AppManager.ts
5726
+ var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
5727
+ var import_hwk_adapter_core13 = require("@onekeyfe/hwk-adapter-core");
5728
+ var APP_NAME_MAP = {
5729
+ ETH: "Ethereum",
5730
+ BTC: "Bitcoin",
5731
+ SOL: "Solana",
5732
+ TRX: "Tron",
5733
+ ZEC: "Zcash",
5734
+ XRP: "XRP",
5735
+ ADA: "Cardano",
5736
+ DOT: "Polkadot",
5737
+ ATOM: "Cosmos"
5738
+ };
5739
+ var DASHBOARD_APP_NAME = "BOLOS";
5740
+ var AppManager = class {
5741
+ constructor(dmk, options) {
5742
+ this._dmk = dmk;
5743
+ this._waitMs = options?.waitMs ?? 1e3;
5744
+ this._maxRetries = options?.maxRetries ?? 10;
5745
+ }
5746
+ /**
5747
+ * Return the Ledger app name for a given chain ticker,
5748
+ * or undefined if the chain is not supported.
5749
+ */
5750
+ static getAppName(chain) {
5751
+ return APP_NAME_MAP[chain];
5752
+ }
5753
+ /**
5754
+ * Ensure the target app is open on the device identified by `sessionId`.
5755
+ *
5756
+ * Flow:
5757
+ * 1. Check the currently running app.
5758
+ * 2. If it is already the target, return immediately.
5759
+ * 3. If a different app is running (not dashboard), close it first.
5760
+ * 4. Open the target app.
5761
+ * 5. Poll until the device confirms the target app is running.
5762
+ */
5763
+ /**
5764
+ * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5765
+ * device is about to display "Open <app>" on screen and wait for the
5766
+ * user's button press. UI consumers should show their "open app" prompt
5767
+ * in response. NOT called when the target app is already open (no user
5768
+ * interaction needed in that case).
5769
+ *
5770
+ * Important: OpenAppCommand is blocking. It does not resolve until the user
5771
+ * has physically confirmed on the device, so anything that runs AFTER
5772
+ * `await this._openApp(...)` lands AFTER the prompt is already gone.
5773
+ * Hence the callback must fire BEFORE that await.
5774
+ */
5775
+ async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5776
+ const currentApp = await this._getCurrentApp(sessionId);
5777
+ if (currentApp === targetAppName) {
5778
+ return;
5779
+ }
5780
+ if (!this._isDashboard(currentApp)) {
5781
+ await this._closeCurrentApp(sessionId);
5782
+ await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5783
+ }
5784
+ onConfirmOnDevice?.();
5785
+ await this._openApp(sessionId, targetAppName);
5786
+ await this._waitForApp(sessionId, targetAppName);
5787
+ }
5788
+ // ---------------------------------------------------------------------------
5789
+ // Private helpers
5790
+ // ---------------------------------------------------------------------------
5791
+ async _getCurrentApp(sessionId) {
5792
+ const result = await this._dmk.sendCommand({
5793
+ sessionId,
5794
+ command: new import_device_management_kit3.GetAppAndVersionCommand()
5795
+ });
5796
+ if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
5797
+ debugLog("[AppManager] currentApp:", result.data.name);
5798
+ return result.data.name;
5799
+ }
5800
+ const errResult = result;
5801
+ const dmkErr = errResult.error ?? {};
5802
+ const original = dmkErr.originalError;
5803
+ debugLog(
5804
+ "[AppManager] _getCurrentApp failed sessionId=",
5805
+ sessionId,
5806
+ "tag=",
5807
+ dmkErr._tag,
5808
+ "errorCode=",
5809
+ dmkErr.errorCode,
5810
+ "message=",
5811
+ dmkErr.message,
5812
+ "originalErrorMessage=",
5813
+ original?.message ?? String(original ?? "")
5814
+ );
5815
+ throw Object.assign(
5816
+ new Error(
5817
+ dmkErr.message ?? "Failed to get current app from device"
5818
+ ),
5819
+ {
5820
+ _tag: dmkErr._tag,
5821
+ errorCode: dmkErr.errorCode,
5822
+ originalError: original
5823
+ }
5824
+ );
5825
+ }
5826
+ async _openApp(sessionId, appName) {
5827
+ const result = await this._dmk.sendCommand({
5828
+ sessionId,
5829
+ command: new import_device_management_kit3.OpenAppCommand({ appName })
5830
+ });
5831
+ if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
5832
+ const dmkErr = result.error;
5833
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5834
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5835
+ debugLog(
5836
+ "[AppManager] openApp failed:",
5837
+ appName,
5838
+ "errorCode:",
5839
+ errorCode,
5840
+ "tag:",
5841
+ dmkErr._tag
5842
+ );
5843
+ let code;
5844
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
5845
+ code = import_hwk_adapter_core13.HardwareErrorCode.AppNotInstalled;
5846
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5847
+ code = import_hwk_adapter_core13.HardwareErrorCode.UserRejected;
5848
+ }
5849
+ throw Object.assign(new Error(`Failed to open "${appName}"`), {
5850
+ _tag: ERROR_TAG.OpenAppCommand,
5851
+ code,
5852
+ errorCode,
5853
+ statusCode: errorCode,
5854
+ appName,
5855
+ originalError: dmkErr
5856
+ });
5857
+ }
5858
+ }
5859
+ async _closeCurrentApp(sessionId) {
5860
+ debugLog("[AppManager] closeCurrentApp");
5861
+ await this._dmk.sendCommand({
5862
+ sessionId,
5863
+ command: new import_device_management_kit3.CloseAppCommand()
5864
+ });
5865
+ }
5866
+ /**
5867
+ * Poll the device until the expected app is reported as running,
5868
+ * or throw after `_maxRetries` attempts.
5869
+ */
5870
+ async _waitForApp(sessionId, expectedAppName) {
5871
+ let lastSeen = "";
5872
+ for (let i = 0; i < this._maxRetries; i++) {
5873
+ await this._wait();
5874
+ const current = await this._getCurrentApp(sessionId);
5875
+ lastSeen = current;
5876
+ if (current === expectedAppName) {
5877
+ return;
5878
+ }
5879
+ }
5880
+ debugLog(
5881
+ "[AppManager] waitForApp exhausted: expected=",
5882
+ expectedAppName,
5883
+ "lastSeen=",
5884
+ lastSeen
5885
+ );
5886
+ throw new Error(
5887
+ `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
5888
+ );
5889
+ }
5890
+ _isDashboard(appName) {
5891
+ return appName === DASHBOARD_APP_NAME;
5892
+ }
5893
+ _wait() {
5894
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
5895
+ }
5896
+ };
4953
5897
  // Annotate the CommonJS export names for ESM import in node:
4954
5898
  0 && (module.exports = {
4955
5899
  AppManager,
@@ -4961,6 +5905,7 @@ var LedgerConnectorBase = class {
4961
5905
  SignerEth,
4962
5906
  SignerManager,
4963
5907
  SignerSol,
5908
+ SignerZcash,
4964
5909
  debugLog,
4965
5910
  deviceActionToPromise,
4966
5911
  isDeviceLockedError,