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

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,7 +39,6 @@ __export(index_exports, {
39
39
  SignerEth: () => SignerEth,
40
40
  SignerManager: () => SignerManager,
41
41
  SignerSol: () => SignerSol,
42
- SignerZcash: () => SignerZcash,
43
42
  debugLog: () => debugLog,
44
43
  deviceActionToPromise: () => deviceActionToPromise,
45
44
  isDeviceLockedError: () => isDeviceLockedError,
@@ -58,14 +57,17 @@ var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
58
57
 
59
58
  // src/errors.ts
60
59
  var import_hwk_adapter_core = require("@onekeyfe/hwk-adapter-core");
61
- function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
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) {
62
67
  const payload = { error, code };
63
68
  if (appName !== void 0) payload.appName = appName;
64
69
  if (tag !== void 0) payload._tag = tag;
65
70
  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);
69
71
  return { success: false, payload };
70
72
  }
71
73
  var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
@@ -206,10 +208,7 @@ var ERROR_TAG = {
206
208
  UnknownDevice: "UnknownDeviceError",
207
209
  DeviceSessionRefresher: "DeviceSessionRefresherError",
208
210
  DeviceNotInitialized: "DeviceNotInitializedError",
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",
211
+ OpeningConnection: "OpeningConnectionError",
213
212
  DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
214
213
  DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
215
214
  Disconnect: "DisconnectError",
@@ -222,16 +221,7 @@ var ERROR_TAG = {
222
221
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
223
222
  WebSocketConnection: "WebSocketConnectionError",
224
223
  HttpFetch: "FetchError",
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"
224
+ InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError"
235
225
  };
236
226
  function isDeviceLockedError(err) {
237
227
  if (!err || typeof err !== "object") return false;
@@ -261,6 +251,7 @@ function isBlePairingFailureError(err) {
261
251
  return false;
262
252
  }
263
253
  var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
254
+ ERROR_TAG.DeviceLocked,
264
255
  ERROR_TAG.DeviceNotAdvertising,
265
256
  ERROR_TAG.BlePairingTimeout,
266
257
  ERROR_TAG.BleGattBondingFailed,
@@ -272,7 +263,6 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
272
263
  ERROR_TAG.DeviceSessionRefresher,
273
264
  ERROR_TAG.DeviceNotInitialized,
274
265
  ERROR_TAG.OpeningConnection,
275
- ERROR_TAG.OpeningConnectionLegacy,
276
266
  ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
277
267
  ERROR_TAG.DeviceDisconnectedWhileSending,
278
268
  ERROR_TAG.Disconnect,
@@ -287,10 +277,7 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
287
277
  // Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
288
278
  ERROR_TAG.DeviceNotInDiscoveryCache
289
279
  ]);
290
- var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
291
- ERROR_TAG.OpeningConnection,
292
- ERROR_TAG.OpeningConnectionLegacy
293
- ]);
280
+ var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OpeningConnection]);
294
281
  var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
295
282
  ERROR_TAG.DeviceNotRecognized,
296
283
  ERROR_TAG.DeviceSessionNotFound,
@@ -302,18 +289,17 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
302
289
  ERROR_TAG.WebHIDDisconnect
303
290
  ]);
304
291
  function isConnectionLevelError(err) {
305
- return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
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;
306
299
  }
307
300
  function isKnownConnectionTag(tag) {
308
301
  return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
309
302
  }
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
- }
317
303
  function hasStatusCode(err, codeSet) {
318
304
  if (!err || typeof err !== "object") return false;
319
305
  const e = err;
@@ -349,28 +335,28 @@ function hasInvalidArgumentCode(err) {
349
335
  if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
350
336
  return false;
351
337
  }
352
- function hasErrorTag(err, tags) {
338
+ function isDeviceNotFoundError(err) {
353
339
  if (!err || typeof err !== "object") return false;
340
+ const tag = err._tag;
341
+ if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
354
342
  const e = err;
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;
343
+ if (e.originalError != null && isDeviceNotFoundError(e.originalError)) return true;
344
+ if (e.error != null && e._tag && isDeviceNotFoundError(e.error)) return true;
358
345
  return false;
359
346
  }
360
- function isDeviceNotFoundError(err) {
361
- return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
362
- }
363
347
  function isDeviceBusyError(err) {
364
- return hasErrorTag(err, DEVICE_BUSY_TAGS);
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;
365
355
  }
366
- var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
367
- ERROR_TAG.UserRefusedOnDevice,
368
- ERROR_TAG.RefusedByUserDA
369
- ]);
370
356
  function isUserRejectedError(err) {
371
357
  if (!err || typeof err !== "object") return false;
372
358
  const e = err;
373
- if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
359
+ if (e._tag === ERROR_TAG.UserRefusedOnDevice) return true;
374
360
  if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
375
361
  if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
376
362
  return false;
@@ -401,33 +387,15 @@ function isAppNotInstalledError(err) {
401
387
  if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
402
388
  return false;
403
389
  }
404
- var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
405
390
  function isOutOfMemoryError(err) {
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);
391
+ if (!err || typeof err !== "object") return false;
392
+ const e = err;
393
+ return e._tag === "OutOfMemoryDAError";
426
394
  }
427
395
  var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
428
396
  ERROR_TAG.WebSocketConnection,
429
397
  ERROR_TAG.HttpFetch,
430
- ERROR_TAG.NetworkDA
398
+ ERROR_TAG.InvalidFirmwareMetadataResponse
431
399
  ]);
432
400
  function isNetworkError(err) {
433
401
  if (!err || typeof err !== "object") return false;
@@ -477,34 +445,23 @@ function isTransportStuck(err) {
477
445
  function isStuckAppStateError(err) {
478
446
  return isAppStuckByApdu(err) || isTransportStuck(err);
479
447
  }
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
- }
489
448
  function mapLedgerError(err, opts) {
490
449
  let originalMessage = "Unknown Ledger error";
491
450
  if (err instanceof Error) {
492
451
  originalMessage = err.message;
493
452
  } else if (err && typeof err === "object") {
494
453
  const e = err;
495
- originalMessage = String(
496
- e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
497
- );
454
+ originalMessage = String(e.message ?? e._tag ?? e.type ?? JSON.stringify(err));
498
455
  }
499
456
  let code;
500
457
  if (isDeviceLockedError(err)) {
501
458
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceLocked;
502
459
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
503
460
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotFound;
504
- } else if (isBlePairingFailureError(err)) {
505
- code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
506
461
  } else if (isDeviceBusyError(err)) {
507
462
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
463
+ } else if (isBlePairingFailureError(err)) {
464
+ code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
508
465
  } else if (isUserAbortedError(err)) {
509
466
  code = import_hwk_adapter_core.HardwareErrorCode.UserAborted;
510
467
  } else if (isUserRejectedError(err)) {
@@ -513,18 +470,10 @@ function mapLedgerError(err, opts) {
513
470
  code = import_hwk_adapter_core.HardwareErrorCode.WrongApp;
514
471
  } else if (isAppNotInstalledError(err)) {
515
472
  code = import_hwk_adapter_core.HardwareErrorCode.AppNotInstalled;
516
- } else if (isAppAlreadyInstalledError(err)) {
517
- code = import_hwk_adapter_core.HardwareErrorCode.AppAlreadyInstalled;
518
473
  } else if (isOutOfMemoryError(err)) {
519
474
  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;
524
475
  } else if (isNetworkError(err)) {
525
476
  code = import_hwk_adapter_core.HardwareErrorCode.NetworkError;
526
- } else if (isSecureChannelError(err)) {
527
- code = import_hwk_adapter_core.HardwareErrorCode.LedgerSecureChannelError;
528
477
  } else if (isDeviceDisconnectedError(err)) {
529
478
  code = import_hwk_adapter_core.HardwareErrorCode.DeviceDisconnected;
530
479
  } else if (isTimeoutError(err)) {
@@ -537,21 +486,7 @@ function mapLedgerError(err, opts) {
537
486
  }
538
487
  const errAppName = err && typeof err === "object" ? err.appName : void 0;
539
488
  const appName = errAppName ?? opts?.defaultAppName;
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;
489
+ return { code, message: (0, import_hwk_adapter_core.enrichErrorMessage)(code, originalMessage), appName };
555
490
  }
556
491
 
557
492
  // src/adapter/methods/allNetworkGetAddress.ts
@@ -612,105 +547,57 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
612
547
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
613
548
  function createAllNetworkGetAddress({
614
549
  callChain,
615
- getChainFingerprint,
616
- retainOperation,
617
- errorToFailure,
618
- createCancelScope,
619
- releaseBundle
550
+ getChainFingerprint
620
551
  }) {
621
552
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
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
- };
553
+ debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
554
+ const installContext = {};
642
555
  const commonParams = {
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
556
+ autoInstallApp: params.autoInstallApp
649
557
  };
650
558
  const chainFingerprints = /* @__PURE__ */ new Map();
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,
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,
678
572
  item,
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);
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
+ );
702
593
  }
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
- }
594
+ });
595
+ debugLog("[LedgerAdapter][RES]", {
596
+ method: "allNetworkGetAddress",
597
+ success: result.success,
598
+ payload: result
599
+ });
600
+ return result;
714
601
  };
715
602
  }
716
603
  function isTopLevelAllNetworkFailure(response) {
@@ -718,7 +605,7 @@ function isTopLevelAllNetworkFailure(response) {
718
605
  return false;
719
606
  }
720
607
  const code = response.payload?.code;
721
- return (0, import_hwk_adapter_core2.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core2.isUserRefusal)(code) || (0, import_hwk_adapter_core2.isConnectionLost)(code);
608
+ return code === import_hwk_adapter_core2.HardwareErrorCode.DeviceMismatch || code === import_hwk_adapter_core2.HardwareErrorCode.UserAborted || code === import_hwk_adapter_core2.HardwareErrorCode.UserRejected;
722
609
  }
723
610
  function getItemDeviceId(item) {
724
611
  const { deviceId } = item;
@@ -748,18 +635,8 @@ function normalizeLedgerAllNetworkItem(method, item) {
748
635
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
749
636
  return coin ? { ...item, coin } : item;
750
637
  }
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
- );
638
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
639
+ const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
763
640
  if (!fingerprint) {
764
641
  return buildFingerprintBootstrapFailure(item, chain);
765
642
  }
@@ -780,8 +657,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
780
657
  }
781
658
  };
782
659
  }
783
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
784
- const response = await getChainFingerprint(connectId, chain, context);
660
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
661
+ const response = await getChainFingerprint(connectId, chain);
785
662
  return response.success ? response.payload : "";
786
663
  }
787
664
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -874,20 +751,6 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
874
751
  function formatDeviceMismatchError(expected, actual) {
875
752
  return `Wrong device: expected ${expected}, got ${actual}`;
876
753
  }
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
- }
891
754
  var BTC_HIGH_INDEX_THRESHOLD = 100;
892
755
  function btcAccountIndexFromPath(path) {
893
756
  const segments = path.replace(/^m\//, "").split("/");
@@ -899,35 +762,9 @@ function btcAccountIndexFromPath(path) {
899
762
  var _LedgerAdapter = class _LedgerAdapter {
900
763
  constructor(connector, options) {
901
764
  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";
905
765
  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
- });
920
766
  this._discoveredDevices = /* @__PURE__ */ new Map();
921
767
  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();
931
768
  this._uiRegistry = new import_hwk_adapter_core3.UiRequestRegistry();
932
769
  // BTC App rejects account index >= 100 unless display=true. Cached per
933
770
  // adapter instance: first 100+ path asks the user once via UI request,
@@ -941,36 +778,21 @@ var _LedgerAdapter = class _LedgerAdapter {
941
778
  this._deviceAuthenticityQueueTail = Promise.resolve();
942
779
  // Shared across concurrent callers — only `cancel()` aborts.
943
780
  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();
952
781
  this._installProgressLastEmittedValue = -Infinity;
953
782
  this.allNetworkGetAddress = createAllNetworkGetAddress({
954
783
  callChain: this.callChain.bind(this),
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)
784
+ getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
970
785
  });
971
786
  // ---------------------------------------------------------------------------
972
787
  // Private helpers
973
788
  // ---------------------------------------------------------------------------
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
+ */
974
796
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
975
797
  this._connectingPromise = null;
976
798
  // ---------------------------------------------------------------------------
@@ -986,12 +808,6 @@ var _LedgerAdapter = class _LedgerAdapter {
986
808
  });
987
809
  };
988
810
  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
- }
995
811
  this._discoveredDevices.delete(data.connectId);
996
812
  this._sessions.delete(data.connectId);
997
813
  this.emitter.emit(import_hwk_adapter_core3.DEVICE.DISCONNECT, {
@@ -1000,8 +816,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1000
816
  });
1001
817
  };
1002
818
  // Forward connector `ui-event` to the public hw.emitter so consumers only
1003
- // need to subscribe in one place. The AppInstallProgress variant re-keys
1004
- // sessionId to connectId via `_sessions`, and drops if no mapping exists.
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.
1005
823
  this.uiEventForwarder = (event) => {
1006
824
  if (event.type === import_hwk_adapter_core3.EConnectorInteraction.AppInstallProgress) {
1007
825
  let connectId;
@@ -1046,30 +864,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1046
864
  this._jobQueue = new import_hwk_adapter_core3.DeviceJobQueue();
1047
865
  this.registerEventListeners();
1048
866
  }
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
- }
1063
867
  // Transport
1064
868
  get activeTransport() {
1065
- return this._isBleConnection() ? "ble" : "hid";
869
+ return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1066
870
  }
1067
871
  getAvailableTransports() {
1068
- if (this.connector.availableTransports) {
1069
- return this.connector.availableTransports.map(
1070
- (transport) => transport === "ble" ? "ble" : "hid"
1071
- );
1072
- }
1073
872
  return this.activeTransport ? [this.activeTransport] : [];
1074
873
  }
1075
874
  // Connector is bound at construction; switching requires a new adapter.
@@ -1086,42 +885,21 @@ var _LedgerAdapter = class _LedgerAdapter {
1086
885
  * The next operation will re-discover and re-connect automatically.
1087
886
  */
1088
887
  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();
1098
888
  this._discoveredDevices.clear();
1099
889
  this._sessions.clear();
1100
- this._sessionTransports.clear();
1101
- this._pendingOperationBindings.clear();
1102
- this._pendingPickBindings.clear();
1103
- this._selectedBleReconnectTargets.clear();
1104
890
  this._connectingPromise = null;
1105
- this._doConnectAbortController = null;
1106
891
  this._uiRegistry.reset();
1107
892
  this._jobQueue.clear();
1108
893
  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
- });
1120
894
  }
1121
895
  async dispose() {
1122
- await this._resetStateAndDisconnectSessions();
896
+ this._uiRegistry.reset();
897
+ this._jobQueue.clear();
1123
898
  this.unregisterEventListeners();
1124
899
  this.connector.reset();
900
+ this._discoveredDevices.clear();
901
+ this._sessions.clear();
902
+ this._btcHighIndexConfirmedThisSession = false;
1125
903
  this.emitter.removeAllListeners();
1126
904
  }
1127
905
  uiResponse(response) {
@@ -1131,32 +909,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1131
909
  // Device management
1132
910
  // ---------------------------------------------------------------------------
1133
911
  async searchDevices(options) {
1134
- return this._searchDevices(options);
1135
- }
1136
- async _searchDevices(options, signal) {
1137
912
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
1138
913
  try {
1139
914
  if (options?.resetSession) {
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
- });
915
+ this._doConnectAbortController?.abort();
916
+ this._sessions.clear();
917
+ this._connectingPromise = null;
918
+ this._doConnectAbortController = null;
919
+ this._btcHighIndexConfirmedThisSession = false;
1159
920
  }
921
+ await this._ensureDevicePermission();
922
+ const devices = await this.connector.searchDevices();
1160
923
  this._discoveredDevices.clear();
1161
924
  for (const d of devices) {
1162
925
  if (d.connectId) {
@@ -1164,7 +927,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1164
927
  }
1165
928
  }
1166
929
  if (this._discoveredDevices.size === 0) {
1167
- await this._ensureDevicePermission(void 0, void 0, signal);
930
+ await this._ensureDevicePermission();
1168
931
  }
1169
932
  const result = Array.from(this._discoveredDevices.values());
1170
933
  debugLog("[LedgerAdapter][RES]", {
@@ -1183,263 +946,41 @@ var _LedgerAdapter = class _LedgerAdapter {
1183
946
  throw err;
1184
947
  }
1185
948
  }
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
- }
1190
949
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
1191
- async _evictAllSessions(preserveOperationId) {
1192
- this._operations.endAll("explicit", preserveOperationId);
950
+ async _evictAllSessions() {
1193
951
  if (this._sessions.size === 0) return;
1194
952
  const stale = [...this._sessions.values()];
1195
953
  this._sessions.clear();
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
- }
954
+ for (const sid of stale) {
955
+ try {
956
+ await this.connector.disconnect(sid);
957
+ } catch {
1203
958
  }
1204
- });
959
+ }
1205
960
  }
1206
961
  static _createDeviceBusyError(method) {
1207
962
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
1208
963
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusy
1209
964
  });
1210
965
  }
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) {
966
+ async connectDevice(connectId) {
1391
967
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
1392
968
  try {
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) {
969
+ if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1399
970
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1400
971
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
1401
972
  });
1402
973
  }
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();
974
+ if (!isLedgerBleConnectionType(this.connector.connectionType)) {
975
+ await this._evictAllSessions();
1435
976
  }
1436
- const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1437
- this._sessions.set(resolvedConnectId, session.sessionId);
1438
- this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
977
+ await this._ensureDevicePermission(connectId);
978
+ const session = await this.connector.connect(connectId);
979
+ this._sessions.set(connectId, session.sessionId);
1439
980
  if (session.deviceInfo) {
1440
- this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
981
+ this._discoveredDevices.set(connectId, session.deviceInfo);
1441
982
  }
1442
- const result = (0, import_hwk_adapter_core3.success)(resolvedConnectId);
983
+ const result = (0, import_hwk_adapter_core3.success)(connectId);
1443
984
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
1444
985
  return result;
1445
986
  } catch (err) {
@@ -1452,73 +993,30 @@ var _LedgerAdapter = class _LedgerAdapter {
1452
993
  return failureResult;
1453
994
  }
1454
995
  }
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;
996
+ async disconnectDevice(connectId) {
1461
997
  debugLog("[LedgerAdapter][REQ]", {
1462
- method: "releaseOperation",
998
+ method: "disconnectDevice",
1463
999
  connectId,
1464
1000
  params: { connectId }
1465
1001
  });
1466
1002
  try {
1467
- await this._releaseOperationConnection(endedOperation);
1468
- debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
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 });
1469
1009
  } catch (err) {
1470
1010
  const e = err;
1471
1011
  debugLog("[LedgerAdapter][RES]", {
1472
- method: "releaseOperation",
1012
+ method: "disconnectDevice",
1473
1013
  success: false,
1474
1014
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1475
1015
  });
1476
1016
  throw err;
1477
1017
  }
1478
1018
  }
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
- }
1019
+ async getDeviceInfo(connectId, deviceId) {
1522
1020
  debugLog("[LedgerAdapter][REQ]", {
1523
1021
  method: "getDeviceInfo",
1524
1022
  connectId,
@@ -1553,19 +1051,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1553
1051
  success: false,
1554
1052
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1555
1053
  });
1556
- return this.errorToFailure(err);
1054
+ throw err;
1557
1055
  }
1558
1056
  }
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
- }
1057
+ getSupportedChains() {
1058
+ return ["evm", "btc", "sol", "tron"];
1569
1059
  }
1570
1060
  // ---------------------------------------------------------------------------
1571
1061
  // Chain call helper
@@ -1601,25 +1091,13 @@ var _LedgerAdapter = class _LedgerAdapter {
1601
1091
  if (params && typeof params === "object") {
1602
1092
  const {
1603
1093
  autoInstallApp,
1604
- operationId,
1605
1094
  passphraseState: _passphraseState,
1606
1095
  useEmptyPassphrase: _useEmptyPassphrase,
1607
- knownConnections,
1608
- extra,
1609
- allowDeviceSelection,
1610
- supportedTransports,
1611
1096
  ...rest
1612
1097
  } = params;
1613
1098
  return {
1614
1099
  commonParams: {
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
- })
1100
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1623
1101
  },
1624
1102
  rest
1625
1103
  };
@@ -1795,28 +1273,9 @@ var _LedgerAdapter = class _LedgerAdapter {
1795
1273
  );
1796
1274
  }
1797
1275
  // ---------------------------------------------------------------------------
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.
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.
1820
1279
  // ---------------------------------------------------------------------------
1821
1280
  async installApp(connectId, appName) {
1822
1281
  try {
@@ -1902,7 +1361,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1902
1361
  );
1903
1362
  }
1904
1363
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1905
- await this._resetStateAndDisconnectSessions();
1364
+ this.resetState();
1906
1365
  }
1907
1366
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1908
1367
  if (!result.isGenuine) {
@@ -1928,10 +1387,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1928
1387
  if (relayUrl) {
1929
1388
  try {
1930
1389
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1931
- await this._resetStateAndDisconnectSessions();
1390
+ this.resetState();
1932
1391
  } catch {
1933
1392
  this.connector.reset();
1934
- await this._resetStateAndDisconnectSessions();
1393
+ this.resetState();
1935
1394
  }
1936
1395
  }
1937
1396
  }
@@ -1943,20 +1402,6 @@ var _LedgerAdapter = class _LedgerAdapter {
1943
1402
  this.emitter.off(event, listener);
1944
1403
  }
1945
1404
  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
- }
1960
1405
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1961
1406
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
1962
1407
  _tag: ERROR_TAG.UserAborted
@@ -1967,48 +1412,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1967
1412
  this._lastCancelReason = void 0;
1968
1413
  }
1969
1414
  }, 2e3);
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
- });
1415
+ this._uiRegistry.cancel();
1416
+ if (connectId) {
1417
+ this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
2007
1418
  } else {
2008
1419
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
2009
1420
  }
2010
- if (resolvedConnectId) {
2011
- const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1421
+ if (connectId) {
1422
+ const sessionId = this._sessions.get(connectId) ?? connectId;
2012
1423
  void this.connector.cancel(sessionId);
2013
1424
  } else {
2014
1425
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
@@ -2016,86 +1427,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2016
1427
  if (this._connectingPromise) {
2017
1428
  this._doConnectAbortController?.abort(userAbortReason);
2018
1429
  }
2019
- const connectingConnectId = this._connectingConnectId;
2020
- if (connectingConnectId) void this.connector.cancel(connectingConnectId);
2021
1430
  }
2022
1431
  // ---------------------------------------------------------------------------
2023
1432
  // Chain fingerprint
2024
1433
  // ---------------------------------------------------------------------------
2025
- /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
2026
1434
  async getChainFingerprint(connectId, deviceId, chain) {
2027
1435
  try {
2028
1436
  const fingerprint = await this._computeChainFingerprint(
2029
1437
  chain,
2030
1438
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
2031
1439
  );
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
- }
2040
1440
  return (0, import_hwk_adapter_core3.success)(fingerprint);
2041
1441
  } catch (err) {
2042
1442
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
2043
1443
  return this.errorToFailure(err);
2044
1444
  }
2045
1445
  }
2046
- /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2047
- async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
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 };
2048
1452
  try {
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
1453
+ const fingerprint = await this._computeChainFingerprint(
1454
+ chain,
1455
+ (method, params) => this._callConnector(sessionId, method, params)
2060
1456
  );
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
- });
1457
+ if (fingerprint === deviceId) {
1458
+ return { success: true };
2067
1459
  }
2068
- } catch (error) {
2069
- await this._dropSession(connectId, signal);
2070
- throw error;
2071
- } finally {
2072
- if (this._bindingSelectionRequestId === selectionRequestId) {
2073
- this._bindingSelectionRequestId = void 0;
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 };
2074
1465
  }
1466
+ throw err;
2075
1467
  }
2076
1468
  }
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
1469
  /**
2100
1470
  * Compute the chain fingerprint via a caller-supplied call strategy.
2101
1471
  *
@@ -2123,20 +1493,11 @@ var _LedgerAdapter = class _LedgerAdapter {
2123
1493
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
2124
1494
  } else if (chain === "tron") {
2125
1495
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2126
- } else if (chain === "zcash") {
2127
- address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
2128
1496
  } else {
2129
1497
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
2130
1498
  }
2131
1499
  return (0, import_hwk_adapter_core3.deriveDeviceFingerprint)(address);
2132
1500
  }
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
- }
2140
1501
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
2141
1502
  // The user must press Confirm after unlocking, which triggers a search retry.
2142
1503
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -2146,18 +1507,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2146
1507
  if (signal?.aborted) {
2147
1508
  _LedgerAdapter._throwIfAborted(signal);
2148
1509
  }
2149
- const operationId = this._activeOperationId();
2150
1510
  const waitPromise = this._uiRegistry.wait(
2151
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT,
2152
- { operationId }
1511
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT
2153
1512
  );
2154
1513
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
2155
1514
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT,
2156
1515
  payload: {
2157
1516
  vendor: "ledger",
2158
1517
  reason: "device-not-found",
2159
- message: "Please connect and unlock your Ledger device",
2160
- operationId
1518
+ message: "Please connect and unlock your Ledger device"
2161
1519
  }
2162
1520
  });
2163
1521
  let payload;
@@ -2203,7 +1561,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2203
1561
  * Returns the params to pass through (with `showOnDevice` possibly
2204
1562
  * promoted), or `null` if the user declined.
2205
1563
  */
2206
- async _gateBtcHighIndex(params, signal) {
1564
+ async _gateBtcHighIndex(params) {
2207
1565
  const accountIndex = btcAccountIndexFromPath(params.path);
2208
1566
  if (params.showOnDevice) return params;
2209
1567
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -2212,32 +1570,25 @@ var _LedgerAdapter = class _LedgerAdapter {
2212
1570
  if (this._btcHighIndexConfirmedThisSession) {
2213
1571
  return { ...params, showOnDevice: true };
2214
1572
  }
2215
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1573
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2216
1574
  if (!confirmed) return null;
2217
1575
  this._btcHighIndexConfirmedThisSession = true;
2218
1576
  return { ...params, showOnDevice: true };
2219
1577
  }
2220
- async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2221
- const operationId = this._activeOperationId();
1578
+ async _waitForBtcHighIndexConfirm(path, accountIndex) {
2222
1579
  const waitPromise = this._uiRegistry.wait(
2223
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2224
- { operationId }
1580
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2225
1581
  );
2226
1582
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
2227
1583
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2228
1584
  payload: {
2229
1585
  vendor: "ledger",
2230
1586
  path,
2231
- accountIndex,
2232
- operationId
1587
+ accountIndex
2233
1588
  }
2234
1589
  });
2235
1590
  try {
2236
- const payload = await this._awaitUiAnswer(
2237
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2238
- waitPromise,
2239
- signal
2240
- );
1591
+ const payload = await waitPromise;
2241
1592
  return !!payload?.confirmed;
2242
1593
  } catch (err) {
2243
1594
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -2247,35 +1598,18 @@ var _LedgerAdapter = class _LedgerAdapter {
2247
1598
  return false;
2248
1599
  }
2249
1600
  }
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
- }
2261
1601
  // Ask the user whether to install a missing app (autoInstallApp flow).
2262
1602
  // Same register-then-emit ordering as the BTC high-index gate.
2263
- async _waitForInstallAppConfirm(appName, signal) {
2264
- const operationId = this._activeOperationId();
1603
+ async _waitForInstallAppConfirm(appName) {
2265
1604
  const waitPromise = this._uiRegistry.wait(
2266
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
2267
- { operationId }
1605
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP
2268
1606
  );
2269
1607
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP, {
2270
1608
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
2271
- payload: { vendor: "ledger", appName, operationId }
1609
+ payload: { vendor: "ledger", appName }
2272
1610
  });
2273
1611
  try {
2274
- const payload = await this._awaitUiAnswer(
2275
- import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
2276
- waitPromise,
2277
- signal
2278
- );
1612
+ const payload = await waitPromise;
2279
1613
  return !!payload?.confirmed;
2280
1614
  } catch (err) {
2281
1615
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -2288,17 +1622,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2288
1622
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
2289
1623
  // `_doConnect` runs under its own internal controller so caller A's cancel
2290
1624
  // doesn't kill caller B's await.
2291
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1625
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2292
1626
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
2293
- this._assertConnectorReady("connectDevice");
2294
- if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1627
+ if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2295
1628
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2296
1629
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2297
1630
  });
2298
1631
  }
2299
1632
  if (connectId && this._sessions.has(connectId)) return connectId;
2300
1633
  if (!connectId && this._sessions.size > 0) {
2301
- if (!this._isBleConnection() && this._sessions.size > 1) {
1634
+ if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2302
1635
  throw Object.assign(
2303
1636
  new Error(
2304
1637
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -2308,24 +1641,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2308
1641
  }
2309
1642
  return this._sessions.keys().next().value;
2310
1643
  }
2311
- if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2312
- const controller = new AbortController();
2313
- this._doConnectAbortController = controller;
2314
- const innerSignal = controller.signal;
1644
+ if (!this._connectingPromise) {
1645
+ this._doConnectAbortController = new AbortController();
1646
+ const innerSignal = this._doConnectAbortController.signal;
2315
1647
  this._connectingPromise = (async () => {
2316
1648
  try {
2317
- return await this._doConnect(
2318
- innerSignal,
2319
- connectId,
2320
- allowUsbEphemeralFallback,
2321
- preserveOperationId,
2322
- context
2323
- );
1649
+ return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2324
1650
  } finally {
2325
- if (this._doConnectAbortController === controller) {
2326
- this._connectingPromise = null;
2327
- this._doConnectAbortController = null;
2328
- }
1651
+ this._connectingPromise = null;
1652
+ this._doConnectAbortController = null;
2329
1653
  }
2330
1654
  })();
2331
1655
  }
@@ -2334,57 +1658,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2334
1658
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
2335
1659
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
2336
1660
  // throw DeviceNotFound so the user is kicked out of the loop.
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);
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
- });
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
+ }
2375
1676
  }
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);
2388
1677
  }
2389
1678
  let confirms = 0;
2390
1679
  while (!internalSignal.aborted) {
@@ -2392,28 +1681,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2392
1681
  type: import_hwk_adapter_core3.EConnectorInteraction.Searching,
2393
1682
  payload: { sessionId: "" }
2394
1683
  });
2395
- let devices = await this._searchDevices(void 0, internalSignal);
2396
- _LedgerAdapter._throwIfAborted(internalSignal);
1684
+ let devices = await this.searchDevices();
2397
1685
  if (devices.length === 0) {
2398
1686
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
2399
1687
  await new Promise((resolve) => {
2400
1688
  setTimeout(resolve, import_hwk_adapter_core3.DEVICE_CONNECT_RETRY_DELAY_MS);
2401
1689
  });
2402
- _LedgerAdapter._throwIfAborted(internalSignal);
2403
- devices = await this._searchDevices(void 0, internalSignal);
2404
- _LedgerAdapter._throwIfAborted(internalSignal);
1690
+ devices = await this.searchDevices();
2405
1691
  if (devices.length > 0) break;
2406
1692
  }
2407
1693
  }
2408
- if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1694
+ if (devices.length > 0) {
2409
1695
  try {
2410
1696
  return await this._connectFirstOrSelect(
2411
1697
  devices,
2412
1698
  targetConnectId,
2413
- allowUsbEphemeralFallback,
2414
- preserveOperationId,
2415
- context,
2416
- internalSignal
1699
+ allowUsbEphemeralFallback
2417
1700
  );
2418
1701
  } catch (err) {
2419
1702
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -2442,147 +1725,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2442
1725
  _LedgerAdapter._throwIfAborted(internalSignal);
2443
1726
  throw new Error("_doConnect aborted");
2444
1727
  }
2445
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2446
- _LedgerAdapter._throwIfAborted(signal);
1728
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2447
1729
  if (targetConnectId) {
2448
1730
  const target = devices.find(
2449
1731
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
2450
1732
  );
2451
1733
  if (target) {
2452
- return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1734
+ return this._connectDeviceOrThrow(target.connectId);
2453
1735
  }
2454
- if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1736
+ if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2455
1737
  debugLog(
2456
1738
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
2457
1739
  );
2458
- return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1740
+ return this._connectDeviceOrThrow(devices[0].connectId);
2459
1741
  }
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;
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;
2468
1747
  }
1748
+ throw err;
2469
1749
  }
2470
- const requiresBleSelection = this._isBleConnection();
2471
- if (requiresBleSelection && !allowUsbEphemeralFallback) {
1750
+ if (isLedgerBleConnectionType(this.connector.connectionType)) {
2472
1751
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2473
1752
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2474
1753
  });
2475
1754
  }
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);
1755
+ if (devices.length > 1) {
1756
+ throw createMultipleUsbLedgerDevicesError();
2576
1757
  }
2577
1758
  if (devices.length !== 1) {
2578
1759
  throw Object.assign(new Error("Ledger device not found."), {
2579
1760
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2580
1761
  });
2581
1762
  }
2582
- return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1763
+ return this._connectDeviceOrThrow(devices[0].connectId);
2583
1764
  }
2584
- async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2585
- const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1765
+ async _connectDeviceOrThrow(chosenConnectId) {
1766
+ const result = await this.connectDevice(chosenConnectId);
2586
1767
  if (!result.success) {
2587
1768
  const payload = result.payload;
2588
1769
  const rethrow = Object.assign(new Error(payload.error), {
@@ -2593,8 +1774,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2593
1774
  }
2594
1775
  throw rethrow;
2595
1776
  }
2596
- return result.payload;
1777
+ return chosenConnectId;
2597
1778
  }
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
+ */
2598
1787
  /**
2599
1788
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
2600
1789
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -2615,145 +1804,33 @@ var _LedgerAdapter = class _LedgerAdapter {
2615
1804
  * lives in one place.
2616
1805
  */
2617
1806
  async _callConnector(sessionId, method, params, signal) {
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
- }
1807
+ const promise = this.connector.call(sessionId, method, params);
2628
1808
  const result = signal ? await this._abortable(signal, promise) : await promise;
2629
1809
  return this._unwrapConnectorResult(result);
2630
1810
  }
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
- }
2683
1811
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
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 });
1812
+ debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1813
+ const queueKey = connectId || "__ledger_default__";
2705
1814
  try {
2706
1815
  const result = await this._jobQueue.enqueue(
2707
1816
  queueKey,
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
- },
1817
+ async (signal) => this._runConnectorCall(
1818
+ connectId,
1819
+ method,
1820
+ params,
1821
+ signal,
1822
+ fingerprint,
1823
+ permissionDeviceId,
1824
+ commonParams,
1825
+ installContext
1826
+ ),
2746
1827
  {
2747
1828
  label: method,
2748
1829
  rejectIfBusy: true,
2749
1830
  busyError: _LedgerAdapter._createDeviceBusyError(method)
2750
1831
  }
2751
1832
  );
2752
- debugLog("[LedgerAdapter][RES]", {
2753
- method,
2754
- success: true,
2755
- payload: redactResultForLog(result, method)
2756
- });
1833
+ debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2757
1834
  return result;
2758
1835
  } catch (err) {
2759
1836
  const e = err;
@@ -2767,22 +1844,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2767
1844
  }
2768
1845
  });
2769
1846
  throw err;
2770
- } finally {
2771
- releaseOperationRetention?.();
2772
1847
  }
2773
1848
  }
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
- }
2778
1849
  /**
2779
1850
  * Race a promise against an abort signal. On abort, rejects with
2780
1851
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
2781
1852
  */
2782
1853
  _abortable(signal, promise) {
2783
- const getAbortReason = () => this._abortReason(signal);
1854
+ const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2784
1855
  if (signal.aborted) {
2785
- void promise.catch(() => void 0);
2786
1856
  return Promise.reject(getAbortReason());
2787
1857
  }
2788
1858
  return new Promise((resolve, reject) => {
@@ -2809,19 +1879,17 @@ var _LedgerAdapter = class _LedgerAdapter {
2809
1879
  }
2810
1880
  }
2811
1881
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
2812
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1882
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2813
1883
  _LedgerAdapter._throwIfAborted(signal);
2814
- if (!operationId) {
2815
- await this._ensureDevicePermission(
2816
- connectId,
2817
- permissionDeviceId ?? fingerprint?.deviceId,
2818
- signal
2819
- );
2820
- }
1884
+ await this._ensureDevicePermission(
1885
+ connectId,
1886
+ permissionDeviceId ?? fingerprint?.deviceId,
1887
+ signal
1888
+ );
2821
1889
  _LedgerAdapter._throwIfAborted(signal);
2822
1890
  let effectiveParams = params;
2823
1891
  if (method === "btcGetPublicKey") {
2824
- const gatedParams = await this._gateBtcHighIndex(params, signal);
1892
+ const gatedParams = await this._gateBtcHighIndex(params);
2825
1893
  if (gatedParams === null) {
2826
1894
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
2827
1895
  _tag: ERROR_TAG.UserAborted,
@@ -2831,67 +1899,19 @@ var _LedgerAdapter = class _LedgerAdapter {
2831
1899
  effectiveParams = gatedParams;
2832
1900
  }
2833
1901
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
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,
1902
+ const resolvedConnectId = await this.ensureConnected(
1903
+ connectId,
2858
1904
  signal,
2859
- allowUsbEphemeralFallback,
2860
- void 0,
2861
- connectionAttempt
1905
+ allowUsbEphemeralFallback
2862
1906
  );
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
- }
2870
1907
  const sessionId = this._sessions.get(resolvedConnectId);
2871
- if (sessionId && installContext && !installContext.connection) {
2872
- installContext.connection = { connectId: resolvedConnectId, sessionId };
2873
- }
2874
1908
  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
- }
2883
1909
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
2884
1910
  _tag: ERROR_TAG.DeviceSessionNotFound
2885
1911
  });
2886
1912
  }
2887
1913
  try {
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) {
1914
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2895
1915
  const fp = await this._abortable(
2896
1916
  signal,
2897
1917
  this._verifyDeviceFingerprintWithSession(
@@ -2901,68 +1921,14 @@ var _LedgerAdapter = class _LedgerAdapter {
2901
1921
  )
2902
1922
  );
2903
1923
  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
- }
2913
1924
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2914
1925
  code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2915
1926
  });
2916
1927
  }
2917
- if (walletCheck) walletCheck.verified = true;
2918
1928
  }
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;
1929
+ return await this._callConnector(sessionId, method, effectiveParams, signal);
2948
1930
  } catch (err) {
2949
1931
  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
- }
2966
1932
  const errObj = err;
2967
1933
  debugLog("[LedgerAdapter] connectorCall error:", method, {
2968
1934
  message: errObj?.message,
@@ -2974,64 +1940,6 @@ var _LedgerAdapter = class _LedgerAdapter {
2974
1940
  isNotAdvertising: isDeviceNotAdvertisingError(err),
2975
1941
  isStuckApp: isStuckAppStateError(err)
2976
1942
  });
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
- }
3035
1943
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
3036
1944
  const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core3.HardwareErrorCode.AppNotInstalled;
3037
1945
  if (autoInstallApp && isAppMissing) {
@@ -3048,7 +1956,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3048
1956
  appName
3049
1957
  });
3050
1958
  }
3051
- const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1959
+ const confirmed = await this._waitForInstallAppConfirm(appName);
3052
1960
  if (!confirmed) {
3053
1961
  throw (0, import_hwk_adapter_core3.createHwkError)({
3054
1962
  code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
@@ -3087,14 +1995,157 @@ var _LedgerAdapter = class _LedgerAdapter {
3087
1995
  fingerprint,
3088
1996
  permissionDeviceId,
3089
1997
  commonParams,
3090
- installContext,
3091
- operationId
1998
+ installContext
3092
1999
  );
3093
2000
  }
3094
2001
  }
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
+ }
3095
2112
  throw err;
3096
2113
  }
3097
2114
  }
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
+ }
3098
2149
  _sleepAbortable(ms, signal) {
3099
2150
  return new Promise((resolve, reject) => {
3100
2151
  if (signal.aborted) {
@@ -3113,22 +2164,111 @@ var _LedgerAdapter = class _LedgerAdapter {
3113
2164
  });
3114
2165
  }
3115
2166
  /**
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.
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
3118
2259
  */
3119
2260
  async _ensureDevicePermission(connectId, deviceId, signal) {
3120
2261
  if (signal?.aborted) {
3121
2262
  _LedgerAdapter._throwIfAborted(signal);
3122
2263
  }
3123
2264
  const transportType = this.activeTransport ?? "hid";
3124
- const operationId = this._activeOperationId();
3125
2265
  const waitPromise = this._uiRegistry.wait(
3126
2266
  import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
3127
- { timeoutMs: 6e4, operationId }
2267
+ { timeoutMs: 6e4 }
3128
2268
  );
3129
2269
  this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
3130
2270
  type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
3131
- payload: { transportType, connectId, deviceId, operationId }
2271
+ payload: { transportType, connectId, deviceId }
3132
2272
  });
3133
2273
  let response;
3134
2274
  const onAbort = () => {
@@ -3174,15 +2314,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3174
2314
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
3175
2315
  const e = err;
3176
2316
  const params = e.code === import_hwk_adapter_core3.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.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
- );
2317
+ return ledgerFailure(e.code, e.message ?? "Unknown error", e.appName, tag, params);
3186
2318
  }
3187
2319
  const mapped = mapLedgerError(err);
3188
2320
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -3209,7 +2341,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3209
2341
  deviceId: device.deviceId,
3210
2342
  connectId: device.connectId,
3211
2343
  label: device.name,
3212
- connectionType: device.connectionType ?? this.connector.connectionType,
2344
+ connectionType: this.connector.connectionType,
3213
2345
  rssi: device.rssi,
3214
2346
  isConnectable: device.isConnectable,
3215
2347
  serialNumber: device.serialNumber,
@@ -3234,7 +2366,7 @@ _LedgerAdapter.APP_INSTALL_PROGRESS_MIN_DELTA = 0.05;
3234
2366
  var LedgerAdapter = _LedgerAdapter;
3235
2367
 
3236
2368
  // src/connector/LedgerConnectorBase.ts
3237
- var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
2369
+ var import_hwk_adapter_core13 = require("@onekeyfe/hwk-adapter-core");
3238
2370
 
3239
2371
  // src/device/LedgerDeviceManager.ts
3240
2372
  var LedgerDeviceManager = class {
@@ -3512,7 +2644,6 @@ var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
3512
2644
  // src/signer/deviceActionToPromise.ts
3513
2645
  var import_device_management_kit = require("@ledgerhq/device-management-kit");
3514
2646
  var IDLE_WATCHDOG_MS = 65e3;
3515
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3516
2647
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
3517
2648
  return new Promise((resolve, reject) => {
3518
2649
  let settled = false;
@@ -3700,6 +2831,7 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
3700
2831
  }
3701
2832
 
3702
2833
  // src/signer/SignerEth.ts
2834
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3703
2835
  var SignerEth = class {
3704
2836
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3705
2837
  constructor(_sdk) {
@@ -3770,7 +2902,7 @@ var SignerManager = class _SignerManager {
3770
2902
  return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
3771
2903
  }
3772
2904
  static _createContextModule() {
3773
- const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2905
+ const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
3774
2906
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
3775
2907
  }
3776
2908
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -3800,33 +2932,12 @@ function collapseSignerInteraction(interaction) {
3800
2932
  switch (interaction) {
3801
2933
  case "confirm-open-app":
3802
2934
  return import_hwk_adapter_core5.EConnectorInteraction.ConfirmOpenApp;
3803
- case "unlock-device":
3804
- return import_hwk_adapter_core5.EConnectorInteraction.UnlockDevice;
3805
- case "interaction-complete":
3806
- return import_hwk_adapter_core5.EConnectorInteraction.InteractionComplete;
3807
- default:
3808
- return import_hwk_adapter_core5.EConnectorInteraction.ConfirmOnDevice;
3809
- }
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);
2935
+ case "unlock-device":
2936
+ return import_hwk_adapter_core5.EConnectorInteraction.UnlockDevice;
2937
+ case "interaction-complete":
2938
+ return import_hwk_adapter_core5.EConnectorInteraction.InteractionComplete;
2939
+ default:
2940
+ return import_hwk_adapter_core5.EConnectorInteraction.ConfirmOnDevice;
3830
2941
  }
3831
2942
  }
3832
2943
 
@@ -3936,6 +3047,7 @@ var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
3936
3047
  function hexToUtf8(hex) {
3937
3048
  return new TextDecoder().decode((0, import_hwk_adapter_core7.hexToBytes)(hex));
3938
3049
  }
3050
+ var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3939
3051
  var SignerBtc = class {
3940
3052
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3941
3053
  constructor(_sdk) {
@@ -3949,7 +3061,7 @@ var SignerBtc = class {
3949
3061
  return deviceActionToPromise(
3950
3062
  action,
3951
3063
  this.onInteraction,
3952
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3064
+ void 0,
3953
3065
  this.onRegisterCanceller
3954
3066
  );
3955
3067
  }
@@ -3967,7 +3079,7 @@ var SignerBtc = class {
3967
3079
  const result = await deviceActionToPromise(
3968
3080
  action,
3969
3081
  this.onInteraction,
3970
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3082
+ void 0,
3971
3083
  this.onRegisterCanceller
3972
3084
  );
3973
3085
  debugLog(
@@ -4003,7 +3115,7 @@ var SignerBtc = class {
4003
3115
  return deviceActionToPromise(
4004
3116
  action,
4005
3117
  this.onInteraction,
4006
- INTERACTIVE_TIMEOUT_MS,
3118
+ INTERACTIVE_TIMEOUT_MS2,
4007
3119
  this.onRegisterCanceller
4008
3120
  );
4009
3121
  }
@@ -4016,7 +3128,7 @@ var SignerBtc = class {
4016
3128
  return deviceActionToPromise(
4017
3129
  action,
4018
3130
  this.onInteraction,
4019
- INTERACTIVE_TIMEOUT_MS,
3131
+ INTERACTIVE_TIMEOUT_MS2,
4020
3132
  this.onRegisterCanceller
4021
3133
  );
4022
3134
  }
@@ -4029,7 +3141,7 @@ var SignerBtc = class {
4029
3141
  return deviceActionToPromise(
4030
3142
  action,
4031
3143
  this.onInteraction,
4032
- INTERACTIVE_TIMEOUT_MS,
3144
+ INTERACTIVE_TIMEOUT_MS2,
4033
3145
  this.onRegisterCanceller
4034
3146
  );
4035
3147
  }
@@ -4052,21 +3164,7 @@ function _purposeToTemplate(purpose, DDT) {
4052
3164
  });
4053
3165
  }
4054
3166
  }
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
- }
4062
3167
  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
- }
4070
3168
  const btcSigner = await _createBtcSigner(ctx, sessionId);
4071
3169
  const path = normalizePath(params.path);
4072
3170
  try {
@@ -4097,7 +3195,6 @@ async function btcGetAddress(ctx, sessionId, params) {
4097
3195
  }
4098
3196
  }
4099
3197
  async function btcGetPublicKey(ctx, sessionId, params) {
4100
- assertBitcoinMainnet(params.coin);
4101
3198
  const btcSigner = await _createBtcSigner(ctx, sessionId);
4102
3199
  const path = normalizePath(params.path);
4103
3200
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -4276,7 +3373,6 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
4276
3373
 
4277
3374
  // src/connector/chains/sol.ts
4278
3375
  var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
4279
- var import_bs58 = __toESM(require("bs58"));
4280
3376
 
4281
3377
  // src/signer/SignerSol.ts
4282
3378
  var SignerSol = class {
@@ -4294,7 +3390,7 @@ var SignerSol = class {
4294
3390
  return deviceActionToPromise(
4295
3391
  action,
4296
3392
  this.onInteraction,
4297
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3393
+ void 0,
4298
3394
  this.onRegisterCanceller
4299
3395
  );
4300
3396
  }
@@ -4306,7 +3402,7 @@ var SignerSol = class {
4306
3402
  return deviceActionToPromise(
4307
3403
  action,
4308
3404
  this.onInteraction,
4309
- INTERACTIVE_TIMEOUT_MS,
3405
+ void 0,
4310
3406
  this.onRegisterCanceller
4311
3407
  );
4312
3408
  }
@@ -4319,7 +3415,7 @@ var SignerSol = class {
4319
3415
  return deviceActionToPromise(
4320
3416
  action,
4321
3417
  this.onInteraction,
4322
- INTERACTIVE_TIMEOUT_MS,
3418
+ void 0,
4323
3419
  this.onRegisterCanceller
4324
3420
  );
4325
3421
  }
@@ -4360,21 +3456,8 @@ async function solSignMessage(ctx, sessionId, params) {
4360
3456
  const path = normalizePath(params.path);
4361
3457
  const messageBytes = (0, import_hwk_adapter_core9.hexToBytes)(params.message);
4362
3458
  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
- }
4376
3459
  const result = await solSigner.signMessage(path, messageBytes);
4377
- return { signature: decodeBase58EnvelopeSignature(result.signature) };
3460
+ return { signature: result.signature };
4378
3461
  } catch (err) {
4379
3462
  ctx.invalidateSession(sessionId);
4380
3463
  throw ctx.wrapError(err);
@@ -4382,27 +3465,11 @@ async function solSignMessage(ctx, sessionId, params) {
4382
3465
  ctx.clearCanceller(sessionId);
4383
3466
  }
4384
3467
  }
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
- }
4399
3468
  async function _createSolSigner(ctx, sessionId) {
4400
3469
  const dmk = await ctx.getOrCreateDmk();
4401
- const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4402
- "@ledgerhq/context-module"
4403
- );
3470
+ const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4404
3471
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
4405
- const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3472
+ const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4406
3473
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
4407
3474
  const signer = new SignerSol(sdkSigner);
4408
3475
  signer.onInteraction = (interaction) => {
@@ -4418,151 +3485,360 @@ async function _createSolSigner(ctx, sessionId) {
4418
3485
  return signer;
4419
3486
  }
4420
3487
 
4421
- // src/connector/chains/zcash.ts
4422
- var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
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"));
4423
3491
 
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;
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");
3497
+ 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;
4429
3514
  }
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
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);
3556
+ }
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
+ }
4438
3593
  );
4439
3594
  }
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
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})`
4448
3657
  );
4449
3658
  }
3659
+ _isDashboard(appName) {
3660
+ return appName === DASHBOARD_APP_NAME;
3661
+ }
3662
+ _wait() {
3663
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3664
+ }
4450
3665
  };
4451
3666
 
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
- });
3667
+ // src/connector/chains/legacyChainCall.ts
3668
+ function isLegacyWrongAppError(err, _appName) {
3669
+ return isWrongAppError(err);
4464
3670
  }
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
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 }
4471
3679
  });
4472
- return { address: result.address, path: params.path };
4473
- });
4474
- }
4475
- async function _createZcashSigner(ctx, sessionId) {
4476
- const dmk = await ctx.getOrCreateDmk();
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));
4480
- }
4481
-
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;
4490
- }
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
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
4499
3697
  );
4500
- return { address: result.address, publicKey: result.publicKey };
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;
4501
3746
  }
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
- );
3747
+ }
3748
+ async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
3749
+ const dmk = await ctx.getOrCreateDmk();
3750
+ const appManager = new AppManager(dmk);
3751
+ await appManager.ensureAppOpen(sessionId, appName, onPrompt);
3752
+ }
3753
+
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;
4511
3761
  }
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
- );
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;
3774
+ }
3775
+ async close() {
4521
3776
  }
4522
3777
  };
4523
3778
 
4524
3779
  // src/connector/chains/tron.ts
4525
3780
  async function tronGetAddress(ctx, sessionId, params) {
4526
- const tronSigner = await _createTronSigner(ctx, sessionId);
4527
3781
  const path = normalizePath(params.path);
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
- });
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
+ );
4534
3798
  }
4535
3799
  async function tronSignTransaction(ctx, sessionId, params) {
4536
3800
  if (!params.rawTxHex) {
4537
3801
  throw Object.assign(
4538
3802
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
4539
- { code: import_hwk_adapter_core11.HardwareErrorCode.InvalidParams }
3803
+ { code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
4540
3804
  );
4541
3805
  }
4542
- const tronSigner = await _createTronSigner(ctx, sessionId);
4543
3806
  const path = normalizePath(params.path);
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
- });
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
+ );
4548
3821
  }
4549
3822
  async function tronSignMessage(ctx, sessionId, params) {
4550
- const tronSigner = await _createTronSigner(ctx, sessionId);
4551
3823
  const path = normalizePath(params.path);
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
- });
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
+ );
4556
3834
  }
4557
- async function _createTronSigner(ctx, sessionId) {
3835
+ async function _createTrx(ctx, sessionId) {
4558
3836
  const dmk = await ctx.getOrCreateDmk();
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));
3837
+ return new import_hw_app_trx.default(new DmkTransport(dmk, sessionId));
4562
3838
  }
4563
3839
 
4564
3840
  // src/device-apps/customActions.ts
4565
- var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
3841
+ var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
4566
3842
  var import_rxjs = require("rxjs");
4567
3843
  var GetOsVersionDeviceAction = class {
4568
3844
  // eslint-disable-next-line no-useless-constructor, no-empty-function
@@ -4576,7 +3852,7 @@ var GetOsVersionDeviceAction = class {
4576
3852
  (async () => {
4577
3853
  try {
4578
3854
  subject.next({
4579
- status: import_device_management_kit2.DeviceActionStatus.Pending,
3855
+ status: import_device_management_kit3.DeviceActionStatus.Pending,
4580
3856
  intermediateValue: { requiredUserInteraction: "none" }
4581
3857
  });
4582
3858
  const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
@@ -4585,11 +3861,11 @@ var GetOsVersionDeviceAction = class {
4585
3861
  const errObj = result?.error;
4586
3862
  throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
4587
3863
  }
4588
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
3864
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Completed, output: result.data });
4589
3865
  subject.complete();
4590
3866
  } catch (err) {
4591
3867
  if (cancelled) return;
4592
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
3868
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Error, error: err });
4593
3869
  subject.complete();
4594
3870
  }
4595
3871
  })();
@@ -4597,7 +3873,7 @@ var GetOsVersionDeviceAction = class {
4597
3873
  observable: subject.asObservable(),
4598
3874
  cancel: () => {
4599
3875
  cancelled = true;
4600
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
3876
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Stopped });
4601
3877
  subject.complete();
4602
3878
  }
4603
3879
  };
@@ -4615,7 +3891,7 @@ var ListAvailableAppsDeviceAction = class {
4615
3891
  (async () => {
4616
3892
  try {
4617
3893
  subject.next({
4618
- status: import_device_management_kit2.DeviceActionStatus.Pending,
3894
+ status: import_device_management_kit3.DeviceActionStatus.Pending,
4619
3895
  intermediateValue: { requiredUserInteraction: "none" }
4620
3896
  });
4621
3897
  const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
@@ -4632,11 +3908,11 @@ var ListAvailableAppsDeviceAction = class {
4632
3908
  throw new Error(httpErr?.message ?? "Manager API getAppList failed");
4633
3909
  }
4634
3910
  const apps = either.extract();
4635
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
3911
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Completed, output: apps });
4636
3912
  subject.complete();
4637
3913
  } catch (err) {
4638
3914
  if (cancelled) return;
4639
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
3915
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Error, error: err });
4640
3916
  subject.complete();
4641
3917
  }
4642
3918
  })();
@@ -4644,7 +3920,7 @@ var ListAvailableAppsDeviceAction = class {
4644
3920
  observable: subject.asObservable(),
4645
3921
  cancel: () => {
4646
3922
  cancelled = true;
4647
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
3923
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Stopped });
4648
3924
  subject.complete();
4649
3925
  }
4650
3926
  };
@@ -4737,7 +4013,7 @@ var DeviceApps = class {
4737
4013
  seTargetId: v.seTargetId,
4738
4014
  mcuTargetId: v.mcuTargetId,
4739
4015
  seVersion: v.seVersion,
4740
- seFlagsHex: bytesToHex4(v.seFlags),
4016
+ seFlagsHex: bytesToHex2(v.seFlags),
4741
4017
  mcuSephVersion: v.mcuSephVersion,
4742
4018
  mcuBootloaderVersion: v.mcuBootloaderVersion,
4743
4019
  hwVersion: v.hwVersion
@@ -4811,7 +4087,7 @@ var DeviceApps = class {
4811
4087
  }
4812
4088
  }
4813
4089
  };
4814
- function bytesToHex4(bytes) {
4090
+ function bytesToHex2(bytes) {
4815
4091
  if (!bytes) return "";
4816
4092
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4817
4093
  }
@@ -4854,11 +4130,10 @@ var METHOD_PREFIX_TO_APP_NAME = {
4854
4130
  evm: "Ethereum",
4855
4131
  btc: "Bitcoin",
4856
4132
  sol: "Solana",
4857
- tron: "Tron",
4858
- zcash: "Zcash"
4133
+ tron: "Tron"
4859
4134
  };
4860
4135
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4861
- Object.values(import_hwk_adapter_core12.HardwareErrorCode).filter((value) => typeof value === "number")
4136
+ Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
4862
4137
  );
4863
4138
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4864
4139
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4895,10 +4170,6 @@ async function defaultLedgerKitImporter(pkg) {
4895
4170
  return import("@ledgerhq/device-signer-kit-bitcoin");
4896
4171
  case "@ledgerhq/device-signer-kit-solana":
4897
4172
  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");
4902
4173
  case "@ledgerhq/context-module":
4903
4174
  return import("@ledgerhq/context-module");
4904
4175
  default:
@@ -4958,7 +4229,6 @@ var LedgerConnectorBase = class {
4958
4229
  this._ctx = {
4959
4230
  emit: (event, data) => this._emit(event, data),
4960
4231
  invalidateSession: (sid) => this._invalidateSession(sid),
4961
- teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4962
4232
  wrapError: (err, opts) => this._wrapError(err, opts),
4963
4233
  getOrCreateDmk: () => this._getOrCreateDmk(),
4964
4234
  getDeviceManager: () => this._getDeviceManager(),
@@ -5010,7 +4280,7 @@ var LedgerConnectorBase = class {
5010
4280
  async searchDevices() {
5011
4281
  const dm = await this._getDeviceManager();
5012
4282
  const descriptors = await this._discoverDescriptors(dm);
5013
- const resolvedDescriptors = descriptors.filter((d) => !(0, import_hwk_adapter_core12.isKnownNonTargetHardwareVendor)(d, "ledger")).map((d) => ({
4283
+ const resolvedDescriptors = descriptors.filter((d) => !(0, import_hwk_adapter_core13.isKnownNonTargetHardwareVendor)(d, "ledger")).map((d) => ({
5014
4284
  descriptor: d,
5015
4285
  connectId: this._resolveConnectId(d)
5016
4286
  }));
@@ -5058,7 +4328,7 @@ var LedgerConnectorBase = class {
5058
4328
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
5059
4329
  );
5060
4330
  err._tag = ERROR_TAG.BlePairingTimeout;
5061
- err.code = import_hwk_adapter_core12.HardwareErrorCode.BlePairingTimeout;
4331
+ err.code = import_hwk_adapter_core13.HardwareErrorCode.BlePairingTimeout;
5062
4332
  reject(err);
5063
4333
  }, HANG_CEILING_MS);
5064
4334
  });
@@ -5091,7 +4361,7 @@ var LedgerConnectorBase = class {
5091
4361
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
5092
4362
  );
5093
4363
  err._tag = ERROR_TAG.DeviceNotAdvertising;
5094
- err.code = import_hwk_adapter_core12.HardwareErrorCode.DeviceNotFound;
4364
+ err.code = import_hwk_adapter_core13.HardwareErrorCode.DeviceNotFound;
5095
4365
  throw err;
5096
4366
  };
5097
4367
  const doConnect = async (path) => {
@@ -5148,14 +4418,14 @@ var LedgerConnectorBase = class {
5148
4418
  this._resetSignersAndSessions();
5149
4419
  if (isLedgerBleConnectionType(this.connectionType)) {
5150
4420
  const tag = err?._tag;
5151
- if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4421
+ if (isKnownConnectionTag(tag)) {
5152
4422
  throw err;
5153
4423
  }
5154
4424
  const wrapped = new Error(
5155
4425
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
5156
4426
  );
5157
4427
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
5158
- wrapped.code = import_hwk_adapter_core12.HardwareErrorCode.BlePairingTimeout;
4428
+ wrapped.code = import_hwk_adapter_core13.HardwareErrorCode.BlePairingTimeout;
5159
4429
  wrapped.originalError = err;
5160
4430
  throw wrapped;
5161
4431
  }
@@ -5233,7 +4503,7 @@ var LedgerConnectorBase = class {
5233
4503
  this._unwatchSessionState(sessionId);
5234
4504
  this._signerManager?.invalidate(sessionId);
5235
4505
  this._cancellers.get(sessionId)?.({
5236
- code: import_hwk_adapter_core12.HardwareErrorCode.DeviceDisconnected,
4506
+ code: import_hwk_adapter_core13.HardwareErrorCode.DeviceDisconnected,
5237
4507
  tag: "DeviceDisconnected",
5238
4508
  message: "Device disconnected"
5239
4509
  });
@@ -5257,9 +4527,9 @@ var LedgerConnectorBase = class {
5257
4527
  if (isAppStuckByApdu(err)) {
5258
4528
  return {
5259
4529
  success: false,
5260
- error: (0, import_hwk_adapter_core12.serializeConnectorError)(
4530
+ error: (0, import_hwk_adapter_core13.serializeConnectorError)(
5261
4531
  Object.assign(new Error("Ledger app is unresponsive"), {
5262
- code: import_hwk_adapter_core12.HardwareErrorCode.DeviceAppStuck,
4532
+ code: import_hwk_adapter_core13.HardwareErrorCode.DeviceAppStuck,
5263
4533
  _tag: ERROR_TAG.DeviceAppStuck,
5264
4534
  originalError: err
5265
4535
  })
@@ -5269,16 +4539,16 @@ var LedgerConnectorBase = class {
5269
4539
  if (isTransportStuck(err)) {
5270
4540
  return {
5271
4541
  success: false,
5272
- error: (0, import_hwk_adapter_core12.serializeConnectorError)(
4542
+ error: (0, import_hwk_adapter_core13.serializeConnectorError)(
5273
4543
  Object.assign(new Error("Device communication interrupted, please retry"), {
5274
- code: import_hwk_adapter_core12.HardwareErrorCode.TransportError,
4544
+ code: import_hwk_adapter_core13.HardwareErrorCode.TransportError,
5275
4545
  _tag: ERROR_TAG.DeviceTransportStuck,
5276
4546
  originalError: err
5277
4547
  })
5278
4548
  )
5279
4549
  };
5280
4550
  }
5281
- return { success: false, error: (0, import_hwk_adapter_core12.serializeConnectorError)(err) };
4551
+ return { success: false, error: (0, import_hwk_adapter_core13.serializeConnectorError)(err) };
5282
4552
  }
5283
4553
  }
5284
4554
  async _dispatch(sessionId, method, params) {
@@ -5317,11 +4587,6 @@ var LedgerConnectorBase = class {
5317
4587
  return solSignTransaction(ctx, sessionId, params);
5318
4588
  case "solSignMessage":
5319
4589
  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);
5325
4590
  // TRON
5326
4591
  case "tronGetAddress":
5327
4592
  return tronGetAddress(ctx, sessionId, params);
@@ -5346,7 +4611,7 @@ var LedgerConnectorBase = class {
5346
4611
  try {
5347
4612
  return await apps.install(p.appName, ({ progress }) => {
5348
4613
  ctx.emit("ui-event", {
5349
- type: import_hwk_adapter_core12.EConnectorInteraction.AppInstallProgress,
4614
+ type: import_hwk_adapter_core13.EConnectorInteraction.AppInstallProgress,
5350
4615
  payload: {
5351
4616
  sessionId,
5352
4617
  appName: p.appName,
@@ -5355,7 +4620,7 @@ var LedgerConnectorBase = class {
5355
4620
  });
5356
4621
  });
5357
4622
  } catch (err) {
5358
- ctx.teardownSecureChannelSession(sessionId);
4623
+ ctx.invalidateSession(sessionId);
5359
4624
  throw ctx.wrapError(err);
5360
4625
  } finally {
5361
4626
  ctx.clearCanceller(sessionId);
@@ -5445,7 +4710,7 @@ var LedgerConnectorBase = class {
5445
4710
  );
5446
4711
  return { isGenuine: output.isGenuine, deviceId };
5447
4712
  } catch (err) {
5448
- ctx.teardownSecureChannelSession(sessionId);
4713
+ ctx.invalidateSession(sessionId);
5449
4714
  throw ctx.wrapError(err);
5450
4715
  } finally {
5451
4716
  ctx.clearCanceller(sessionId);
@@ -5567,17 +4832,6 @@ var LedgerConnectorBase = class {
5567
4832
  _invalidateSession(sessionId) {
5568
4833
  this._signerManager?.invalidate(sessionId);
5569
4834
  }
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
- }
5581
4835
  /**
5582
4836
  * Replace an old session with a new one after app switch.
5583
4837
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -5662,7 +4916,7 @@ var LedgerConnectorBase = class {
5662
4916
  * at every catch site. Falls through unchanged for unknown methods.
5663
4917
  */
5664
4918
  _ctxForMethod(method) {
5665
- const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4919
+ const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5666
4920
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
5667
4921
  if (!defaultAppName) return this._ctx;
5668
4922
  return {
@@ -5696,204 +4950,6 @@ var LedgerConnectorBase = class {
5696
4950
  return error;
5697
4951
  }
5698
4952
  };
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
- };
5897
4953
  // Annotate the CommonJS export names for ESM import in node:
5898
4954
  0 && (module.exports = {
5899
4955
  AppManager,
@@ -5905,7 +4961,6 @@ var AppManager = class {
5905
4961
  SignerEth,
5906
4962
  SignerManager,
5907
4963
  SignerSol,
5908
- SignerZcash,
5909
4964
  debugLog,
5910
4965
  deviceActionToPromise,
5911
4966
  isDeviceLockedError,