@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.50 → 1.2.8-alpha.51

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,
@@ -54,18 +53,21 @@ __export(index_exports, {
54
53
  module.exports = __toCommonJS(index_exports);
55
54
 
56
55
  // src/adapter/LedgerAdapter.ts
57
- var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
56
+ 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,25 +486,11 @@ 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
558
- var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
493
+ var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
559
494
 
560
495
  // src/utils/sdkEventBus.ts
561
496
  var listeners = /* @__PURE__ */ new Set();
@@ -602,32 +537,6 @@ function debugError(...args) {
602
537
  emitLog("error", ...args);
603
538
  }
604
539
 
605
- // src/utils/logSummary.ts
606
- var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
607
- var import_bitcoinjs_lib = require("bitcoinjs-lib");
608
- var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
609
- var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
610
- function parsePsbt(input) {
611
- if (typeof input !== "string") return import_bitcoinjs_lib.Psbt.fromBuffer(input);
612
- if (HEX_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromHex(input.replace(/^0x/i, ""));
613
- if (BASE64_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromBase64(input);
614
- return void 0;
615
- }
616
- var describePsbtForLog = (key, value) => {
617
- if (key !== "psbt") return void 0;
618
- try {
619
- const psbt = parsePsbt(value);
620
- if (!psbt) return void 0;
621
- const unsignedTx = import_bitcoinjs_lib.Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
622
- return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
623
- } catch {
624
- return void 0;
625
- }
626
- };
627
- function summarizeForLog(value, options = {}) {
628
- return (0, import_hwk_adapter_core2.summarizeForLog)(value, { ...options, describePayload: describePsbtForLog });
629
- }
630
-
631
540
  // src/adapter/methods/allNetworkGetAddress.ts
632
541
  var LEDGER_BTC_NETWORK_COIN_MAP = {
633
542
  tbtc: "Testnet",
@@ -638,105 +547,57 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
638
547
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
639
548
  function createAllNetworkGetAddress({
640
549
  callChain,
641
- getChainFingerprint,
642
- retainOperation,
643
- errorToFailure,
644
- createCancelScope,
645
- releaseBundle
550
+ getChainFingerprint
646
551
  }) {
647
552
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
648
- debugLog("[LedgerAdapter][REQ]", {
649
- method: "allNetworkGetAddress",
650
- connectId,
651
- itemCount: params.bundle.length
652
- });
653
- const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(connectId, params.operationId, "ledger");
654
- if (!target.success) return target;
655
- const effectiveTargetId = target.payload.targetId ?? "";
656
- let releaseOperationRetention;
657
- try {
658
- releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
659
- } catch (error) {
660
- return errorToFailure(error);
661
- }
662
- const cancelScope = createCancelScope(
663
- ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
664
- );
665
- const installContext = {
666
- walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
667
- };
553
+ debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
554
+ const installContext = {};
668
555
  const commonParams = {
669
- autoInstallApp: params.autoInstallApp,
670
- operationId: target.payload.operationId,
671
- knownConnections: params.knownConnections,
672
- extra: params.extra,
673
- allowDeviceSelection: params.allowDeviceSelection,
674
- supportedTransports: params.supportedTransports
556
+ autoInstallApp: params.autoInstallApp
675
557
  };
676
558
  const chainFingerprints = /* @__PURE__ */ new Map();
677
- const order = params.bundle.map((_item, index) => index).sort(
678
- (a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
679
- );
680
- try {
681
- const ordered = await (0, import_hwk_adapter_core3.runAllNetworkGetAddress)({
682
- connectId: effectiveTargetId,
683
- deviceId: _deviceId,
684
- params: { ...params, bundle: order.map((index) => params.bundle[index]) },
685
- normalizeItem: normalizeLedgerAllNetworkItem,
686
- buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
687
- callItem: async ({ method, chain, item }) => {
688
- if (cancelScope.signal.aborted)
689
- return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelScope.signal);
690
- const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
691
- return callAllNetworkMethod(
692
- callChain,
693
- effectiveTargetId,
694
- itemDeviceId,
695
- method,
696
- item,
697
- commonParams,
698
- installContext
699
- );
700
- },
701
- attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
702
- getChainFingerprint,
703
- 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,
704
572
  item,
705
- chain,
706
- payload,
707
- chainFingerprints,
708
- installContext,
709
- cancelScope.signal
710
- ),
711
- shouldAbortBundle: isTopLevelAllNetworkFailure,
712
- buildTopLevelFailure: (response) => {
713
- const code = response.payload?.code ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch;
714
- return (0, import_hwk_adapter_core3.failure)(
715
- code,
716
- response.payload?.error ?? "All-network get-address aborted",
717
- response.payload?.params
718
- );
719
- }
720
- });
721
- let result = ordered;
722
- if (ordered.success) {
723
- const responses = [];
724
- ordered.payload.forEach((response, position) => {
725
- responses[order[position]] = response;
726
- });
727
- result = (0, import_hwk_adapter_core3.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
+ );
728
593
  }
729
- debugLog("[LedgerAdapter][RES]", {
730
- method: "allNetworkGetAddress",
731
- success: result.success,
732
- payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
733
- });
734
- return result;
735
- } finally {
736
- await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
737
- cancelScope.release();
738
- releaseOperationRetention?.();
739
- }
594
+ });
595
+ debugLog("[LedgerAdapter][RES]", {
596
+ method: "allNetworkGetAddress",
597
+ success: result.success,
598
+ payload: result
599
+ });
600
+ return result;
740
601
  };
741
602
  }
742
603
  function isTopLevelAllNetworkFailure(response) {
@@ -744,7 +605,7 @@ function isTopLevelAllNetworkFailure(response) {
744
605
  return false;
745
606
  }
746
607
  const code = response.payload?.code;
747
- return (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.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;
748
609
  }
749
610
  function getItemDeviceId(item) {
750
611
  const { deviceId } = item;
@@ -758,7 +619,7 @@ function buildUnsupportedNetworkResponse(item) {
758
619
  ...item,
759
620
  success: false,
760
621
  payload: {
761
- code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
622
+ code: import_hwk_adapter_core2.HardwareErrorCode.ChainNotSupported,
762
623
  error: `Ledger allNetwork does not support ${item.network.toLowerCase() === "doge" ? "Dogecoin" : item.network}`
763
624
  }
764
625
  };
@@ -774,18 +635,8 @@ function normalizeLedgerAllNetworkItem(method, item) {
774
635
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
775
636
  return coin ? { ...item, coin } : item;
776
637
  }
777
- async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
778
- const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
779
- if (!knownFingerprint && cancelSignal.aborted) {
780
- const cancelled = (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelSignal);
781
- return { ...item, success: false, payload: cancelled.payload };
782
- }
783
- const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
784
- getChainFingerprint,
785
- context.connection?.connectId ?? connectId,
786
- chain,
787
- context
788
- );
638
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
639
+ const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
789
640
  if (!fingerprint) {
790
641
  return buildFingerprintBootstrapFailure(item, chain);
791
642
  }
@@ -806,8 +657,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
806
657
  }
807
658
  };
808
659
  }
809
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
810
- const response = await getChainFingerprint(connectId, chain, context);
660
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
661
+ const response = await getChainFingerprint(connectId, chain);
811
662
  return response.success ? response.payload : "";
812
663
  }
813
664
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -815,7 +666,7 @@ function buildFingerprintBootstrapFailure(item, chain) {
815
666
  ...item,
816
667
  success: false,
817
668
  payload: {
818
- code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
669
+ code: import_hwk_adapter_core2.HardwareErrorCode.DeviceMismatch,
819
670
  error: `Could not establish chain fingerprint for ${chain} after device call; refusing to return unverifiable result. Please retry.`
820
671
  }
821
672
  };
@@ -879,7 +730,7 @@ async function callAllNetworkMethod(callChain, connectId, deviceId, method, item
879
730
  );
880
731
  default:
881
732
  throw Object.assign(new Error(`Unsupported allNetwork method: ${method}`), {
882
- code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams
733
+ code: import_hwk_adapter_core2.HardwareErrorCode.InvalidParams
883
734
  });
884
735
  }
885
736
  }
@@ -900,9 +751,6 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
900
751
  function formatDeviceMismatchError(expected, actual) {
901
752
  return `Wrong device: expected ${expected}, got ${actual}`;
902
753
  }
903
- function isLostConnectionError(err) {
904
- return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
905
- }
906
754
  var BTC_HIGH_INDEX_THRESHOLD = 100;
907
755
  function btcAccountIndexFromPath(path) {
908
756
  const segments = path.replace(/^m\//, "").split("/");
@@ -914,36 +762,10 @@ function btcAccountIndexFromPath(path) {
914
762
  var _LedgerAdapter = class _LedgerAdapter {
915
763
  constructor(connector, options) {
916
764
  this.vendor = "ledger";
917
- // Cancel frees the DMK action and its intent-queue slot, but cannot retract a
918
- // confirmation screen the device is already showing.
919
- this.cancelCapability = "stops-waiting";
920
- this.emitter = new import_hwk_adapter_core4.TypedEventEmitter();
921
- this._operations = new import_hwk_adapter_core4.OperationRegistry({
922
- vendor: "ledger",
923
- onEnded: (operation, reason) => {
924
- this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
925
- this._pendingOperationBindings.delete(operation.operationId);
926
- this.emitter.emit(import_hwk_adapter_core4.SDK.OPERATION_ENDED, {
927
- type: import_hwk_adapter_core4.SDK.OPERATION_ENDED,
928
- payload: { operationId: operation.operationId, reason }
929
- });
930
- if (reason === "timeout") {
931
- void this._releaseOperationConnection(operation);
932
- }
933
- }
934
- });
765
+ this.emitter = new import_hwk_adapter_core3.TypedEventEmitter();
935
766
  this._discoveredDevices = /* @__PURE__ */ new Map();
936
767
  this._sessions = /* @__PURE__ */ new Map();
937
- // An operation's BLE pick is saved by its first call that gets past the wallet check.
938
- this._pendingOperationBindings = /* @__PURE__ */ new Map();
939
- // A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
940
- // through an unlock retry; any other failure drops it with its session.
941
- this._pendingPickBindings = /* @__PURE__ */ new Map();
942
- // Transport each session was opened on, by sessionId. The adapter-wide
943
- // `_activeConnectionType` moves with every discovery and can go stale.
944
- this._sessionTransports = /* @__PURE__ */ new Map();
945
- this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
946
- this._uiRegistry = new import_hwk_adapter_core4.UiRequestRegistry();
768
+ this._uiRegistry = new import_hwk_adapter_core3.UiRequestRegistry();
947
769
  // BTC App rejects account index >= 100 unless display=true. Cached per
948
770
  // adapter instance: first 100+ path asks the user once via UI request,
949
771
  // subsequent 100+ paths in the same session auto-promote silently.
@@ -956,36 +778,21 @@ var _LedgerAdapter = class _LedgerAdapter {
956
778
  this._deviceAuthenticityQueueTail = Promise.resolve();
957
779
  // Shared across concurrent callers — only `cancel()` aborts.
958
780
  this._doConnectAbortController = null;
959
- this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
960
- this._connectorIdleWaiters = /* @__PURE__ */ new Set();
961
- this._resetPromise = null;
962
- this._stateGeneration = 0;
963
- this._connectorTeardownTail = Promise.resolve();
964
- this._pendingConnectorTeardowns = 0;
965
- this._activeOperationJobs = /* @__PURE__ */ new Set();
966
- this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
967
781
  this._installProgressLastEmittedValue = -Infinity;
968
782
  this.allNetworkGetAddress = createAllNetworkGetAddress({
969
783
  callChain: this.callChain.bind(this),
970
- getChainFingerprint: async (connectId, chain, context) => {
971
- try {
972
- const fingerprint = await this._computeChainFingerprint(
973
- chain,
974
- (method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
975
- );
976
- return (0, import_hwk_adapter_core4.success)(fingerprint);
977
- } catch (error) {
978
- return this.errorToFailure(error);
979
- }
980
- },
981
- retainOperation: (operationId) => this._operations.retain(operationId),
982
- errorToFailure: (error) => this.errorToFailure(error),
983
- createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
984
- releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
784
+ getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
985
785
  });
986
786
  // ---------------------------------------------------------------------------
987
787
  // Private helpers
988
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
+ */
989
796
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
990
797
  this._connectingPromise = null;
991
798
  // ---------------------------------------------------------------------------
@@ -995,30 +802,26 @@ var _LedgerAdapter = class _LedgerAdapter {
995
802
  const deviceInfo = this.connectorDeviceToDeviceInfo(data.device);
996
803
  this._discoveredDevices.set(deviceInfo.connectId, deviceInfo);
997
804
  this._sessions.delete(deviceInfo.connectId);
998
- this.emitter.emit(import_hwk_adapter_core4.DEVICE.CONNECT, {
999
- type: import_hwk_adapter_core4.DEVICE.CONNECT,
805
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.CONNECT, {
806
+ type: import_hwk_adapter_core3.DEVICE.CONNECT,
1000
807
  payload: deviceInfo
1001
808
  });
1002
809
  };
1003
810
  this.deviceDisconnectHandler = (data) => {
1004
- const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
1005
- if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
1006
- this._pendingOperationDisconnects.add(activeOperation.operationId);
1007
- } else {
1008
- this._operations.endByConnectionKey(data.connectId, "disconnect");
1009
- }
1010
811
  this._discoveredDevices.delete(data.connectId);
1011
812
  this._sessions.delete(data.connectId);
1012
- this.emitter.emit(import_hwk_adapter_core4.DEVICE.DISCONNECT, {
1013
- type: import_hwk_adapter_core4.DEVICE.DISCONNECT,
813
+ this.emitter.emit(import_hwk_adapter_core3.DEVICE.DISCONNECT, {
814
+ type: import_hwk_adapter_core3.DEVICE.DISCONNECT,
1014
815
  payload: { connectId: data.connectId }
1015
816
  });
1016
817
  };
1017
818
  // Forward connector `ui-event` to the public hw.emitter so consumers only
1018
- // need to subscribe in one place. The AppInstallProgress variant re-keys
1019
- // 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.
1020
823
  this.uiEventForwarder = (event) => {
1021
- if (event.type === import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress) {
824
+ if (event.type === import_hwk_adapter_core3.EConnectorInteraction.AppInstallProgress) {
1022
825
  let connectId;
1023
826
  for (const [cid, sid] of this._sessions) {
1024
827
  if (sid === event.payload.sessionId) {
@@ -1045,7 +848,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1045
848
  }
1046
849
  this._installProgressLastEmittedValue = progress;
1047
850
  this.emitter.emit("ui-event", {
1048
- type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
851
+ type: import_hwk_adapter_core3.EConnectorInteraction.AppInstallProgress,
1049
852
  payload: {
1050
853
  connectId,
1051
854
  appName,
@@ -1058,33 +861,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1058
861
  };
1059
862
  this.connector = connector;
1060
863
  this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
1061
- this._jobQueue = new import_hwk_adapter_core4.DeviceJobQueue();
864
+ this._jobQueue = new import_hwk_adapter_core3.DeviceJobQueue();
1062
865
  this.registerEventListeners();
1063
866
  }
1064
- _discardPendingBinding(owner, status = "cancelled") {
1065
- const pending = owner?.pendingBinding;
1066
- if (!owner || !pending) return;
1067
- owner.pendingBinding = void 0;
1068
- if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1069
- }
1070
- _finishBleBinding(status) {
1071
- const selectionRequestId = this._bindingSelectionRequestId;
1072
- this._bindingSelectionRequestId = void 0;
1073
- if (selectionRequestId) (0, import_hwk_adapter_core4.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
1074
- }
1075
- _isBleConnection() {
1076
- return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1077
- }
1078
867
  // Transport
1079
868
  get activeTransport() {
1080
- return this._isBleConnection() ? "ble" : "hid";
869
+ return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1081
870
  }
1082
871
  getAvailableTransports() {
1083
- if (this.connector.availableTransports) {
1084
- return this.connector.availableTransports.map(
1085
- (transport) => transport === "ble" ? "ble" : "hid"
1086
- );
1087
- }
1088
872
  return this.activeTransport ? [this.activeTransport] : [];
1089
873
  }
1090
874
  // Connector is bound at construction; switching requires a new adapter.
@@ -1101,42 +885,21 @@ var _LedgerAdapter = class _LedgerAdapter {
1101
885
  * The next operation will re-discover and re-connect automatically.
1102
886
  */
1103
887
  resetState() {
1104
- void this._resetStateAndDisconnectSessions();
1105
- }
1106
- _resetStateAndDisconnectSessions() {
1107
- if (this._resetPromise) return this._resetPromise;
1108
- const sessionIds = new Set(this._sessions.values());
1109
- this._stateGeneration += 1;
1110
- this._finishBleBinding("cancelled");
1111
- this._operations.endAll("runtime-reset");
1112
- this._doConnectAbortController?.abort();
1113
888
  this._discoveredDevices.clear();
1114
889
  this._sessions.clear();
1115
- this._sessionTransports.clear();
1116
- this._pendingOperationBindings.clear();
1117
- this._pendingPickBindings.clear();
1118
- this._selectedBleReconnectTargets.clear();
1119
890
  this._connectingPromise = null;
1120
- this._doConnectAbortController = null;
1121
891
  this._uiRegistry.reset();
1122
892
  this._jobQueue.clear();
1123
893
  this._btcHighIndexConfirmedThisSession = false;
1124
- const resetPromise = this._runConnectorTeardown(async () => {
1125
- for (const sessionId of sessionIds) {
1126
- await this.connector.disconnect(sessionId).catch(() => void 0);
1127
- }
1128
- });
1129
- this._resetPromise = resetPromise;
1130
- return resetPromise.finally(() => {
1131
- if (this._resetPromise === resetPromise) {
1132
- this._resetPromise = null;
1133
- }
1134
- });
1135
894
  }
1136
895
  async dispose() {
1137
- await this._resetStateAndDisconnectSessions();
896
+ this._uiRegistry.reset();
897
+ this._jobQueue.clear();
1138
898
  this.unregisterEventListeners();
1139
899
  this.connector.reset();
900
+ this._discoveredDevices.clear();
901
+ this._sessions.clear();
902
+ this._btcHighIndexConfirmedThisSession = false;
1140
903
  this.emitter.removeAllListeners();
1141
904
  }
1142
905
  uiResponse(response) {
@@ -1146,32 +909,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1146
909
  // Device management
1147
910
  // ---------------------------------------------------------------------------
1148
911
  async searchDevices(options) {
1149
- return this._searchDevices(options);
1150
- }
1151
- async _searchDevices(options, signal) {
1152
912
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
1153
913
  try {
1154
914
  if (options?.resetSession) {
1155
- await this._resetStateAndDisconnectSessions();
1156
- } else {
1157
- await this._connectorTeardownTail;
1158
- }
1159
- await this._ensureDevicePermission(void 0, void 0, signal);
1160
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1161
- const stateGeneration = this._stateGeneration;
1162
- const devices = await this.connector.searchDevices(
1163
- options?.transportType ? {
1164
- transportType: options.transportType,
1165
- waitForAll: options.waitForAllTransports
1166
- } : void 0
1167
- );
1168
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1169
- if (stateGeneration !== this._stateGeneration) {
1170
- throw (0, import_hwk_adapter_core4.createHwkError)({
1171
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
1172
- message: "Ledger discovery was reset"
1173
- });
915
+ this._doConnectAbortController?.abort();
916
+ this._sessions.clear();
917
+ this._connectingPromise = null;
918
+ this._doConnectAbortController = null;
919
+ this._btcHighIndexConfirmedThisSession = false;
1174
920
  }
921
+ await this._ensureDevicePermission();
922
+ const devices = await this.connector.searchDevices();
1175
923
  this._discoveredDevices.clear();
1176
924
  for (const d of devices) {
1177
925
  if (d.connectId) {
@@ -1179,7 +927,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1179
927
  }
1180
928
  }
1181
929
  if (this._discoveredDevices.size === 0) {
1182
- await this._ensureDevicePermission(void 0, void 0, signal);
930
+ await this._ensureDevicePermission();
1183
931
  }
1184
932
  const result = Array.from(this._discoveredDevices.values());
1185
933
  debugLog("[LedgerAdapter][RES]", {
@@ -1198,263 +946,41 @@ var _LedgerAdapter = class _LedgerAdapter {
1198
946
  throw err;
1199
947
  }
1200
948
  }
1201
- async searchDeviceTargets(options) {
1202
- const devices = await this.searchDevices(options);
1203
- return devices.map((device) => (0, import_hwk_adapter_core4.toPhysicalDeviceSearchTarget)("ledger", device));
1204
- }
1205
949
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
1206
- async _evictAllSessions(preserveOperationId) {
1207
- this._operations.endAll("explicit", preserveOperationId);
950
+ async _evictAllSessions() {
1208
951
  if (this._sessions.size === 0) return;
1209
952
  const stale = [...this._sessions.values()];
1210
953
  this._sessions.clear();
1211
- for (const sid of stale) this._sessionTransports.delete(sid);
1212
- await this._runConnectorTeardown(async () => {
1213
- for (const sid of stale) {
1214
- try {
1215
- await this.connector.disconnect(sid);
1216
- } catch {
1217
- }
954
+ for (const sid of stale) {
955
+ try {
956
+ await this.connector.disconnect(sid);
957
+ } catch {
1218
958
  }
1219
- });
959
+ }
1220
960
  }
1221
961
  static _createDeviceBusyError(method) {
1222
962
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
1223
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceBusy
1224
- });
1225
- }
1226
- async connectDevice(searchTargetId) {
1227
- try {
1228
- return await this._jobQueue.enqueue(
1229
- searchTargetId || "__ledger_connect__",
1230
- async (signal) => {
1231
- const connected = await this._connectTarget(searchTargetId, void 0, signal);
1232
- if (!connected.success) return connected;
1233
- return this._createOperation(searchTargetId, connected.payload);
1234
- },
1235
- {
1236
- label: "connectDevice",
1237
- rejectIfBusy: true,
1238
- busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1239
- }
1240
- );
1241
- } catch (error) {
1242
- return this.errorToFailure(error);
1243
- }
1244
- }
1245
- /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1246
- async bindBleDevice(params) {
1247
- const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1248
- try {
1249
- return await this._jobQueue.enqueue(
1250
- "__ledger_bind_ble__",
1251
- async (signal) => {
1252
- if (!this.getAvailableTransports().includes("ble")) {
1253
- throw (0, import_hwk_adapter_core4.createHwkError)({
1254
- code: import_hwk_adapter_core4.HardwareErrorCode.TransportNotAvailable,
1255
- message: "Ledger Bluetooth transport is not available"
1256
- });
1257
- }
1258
- this._activeConnectionType = "ble";
1259
- await this._ensureDevicePermission(void 0, void 0, signal);
1260
- const attempt = {
1261
- extra: params.extra,
1262
- bindingReason: "manual-rebind",
1263
- deferBindingSave: Boolean(identity)
1264
- };
1265
- try {
1266
- const connectId = await this._connectFirstOrSelect(
1267
- [],
1268
- void 0,
1269
- true,
1270
- void 0,
1271
- attempt,
1272
- signal
1273
- );
1274
- const pending = attempt.pendingBinding;
1275
- if (identity && pending) {
1276
- attempt.pendingBinding = void 0;
1277
- const sessionId = this._sessions.get(connectId);
1278
- if (!sessionId) {
1279
- throw (0, import_hwk_adapter_core4.createHwkError)({
1280
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
1281
- message: "Selected Ledger connection ended"
1282
- });
1283
- }
1284
- const fingerprint = await this._computeChainFingerprint(
1285
- identity.chain,
1286
- (method, callParams) => this._runConnectorCall(
1287
- connectId,
1288
- method,
1289
- callParams,
1290
- signal,
1291
- void 0,
1292
- void 0,
1293
- { autoInstallApp: true },
1294
- { connection: { connectId, sessionId } }
1295
- )
1296
- );
1297
- if (fingerprint !== identity.value) {
1298
- await this._dropSession(connectId, signal);
1299
- throw (0, import_hwk_adapter_core4.createHwkError)({
1300
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
1301
- message: formatDeviceMismatchError(identity.value, fingerprint)
1302
- });
1303
- }
1304
- await this._saveSelectedBleBinding(
1305
- connectId,
1306
- pending.requestId,
1307
- attempt,
1308
- void 0,
1309
- signal,
1310
- identity
1311
- );
1312
- }
1313
- if (!attempt.bindingSaved) {
1314
- await this._dropSession(connectId, signal);
1315
- throw (0, import_hwk_adapter_core4.createHwkError)({
1316
- code: import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
1317
- message: "Bluetooth binding could not be saved",
1318
- origin: "host"
1319
- });
1320
- }
1321
- return (0, import_hwk_adapter_core4.success)(connectId);
1322
- } catch (error) {
1323
- this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1324
- throw error;
1325
- }
1326
- },
1327
- {
1328
- label: "bindBleDevice",
1329
- rejectIfBusy: true,
1330
- busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1331
- }
1332
- );
1333
- } catch (error) {
1334
- return this.errorToFailure(error);
1335
- }
1336
- }
1337
- async acquireOperation(connectId, context) {
1338
- try {
1339
- return await this._jobQueue.enqueue(
1340
- connectId || "__ledger_acquire__",
1341
- async (signal) => {
1342
- const transport = this._isBleConnection() ? "ble" : "usb";
1343
- const hint = context.knownConnections?.find(
1344
- (connection) => connection.transport === transport
1345
- );
1346
- const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1347
- await this._ensureDevicePermission(target, void 0, signal);
1348
- const attempt = {
1349
- ...context,
1350
- extra: context.extra ? { ...context.extra } : void 0,
1351
- // The operation's calls decide whether the pick is the right wallet.
1352
- deferBindingSave: true
1353
- };
1354
- try {
1355
- const resolvedConnectId = await this.ensureConnected(
1356
- target,
1357
- signal,
1358
- true,
1359
- void 0,
1360
- attempt
1361
- );
1362
- _LedgerAdapter._throwIfAborted(signal);
1363
- const result = this._createOperation(connectId, resolvedConnectId);
1364
- if (result.success && attempt.pendingBinding) {
1365
- this._pendingOperationBindings.set(result.payload, attempt);
1366
- }
1367
- return result;
1368
- } catch (error) {
1369
- this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1370
- throw error;
1371
- }
1372
- },
1373
- {
1374
- label: "acquireOperation",
1375
- rejectIfBusy: true,
1376
- busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1377
- }
1378
- );
1379
- } catch (error) {
1380
- return this.errorToFailure(error);
1381
- }
1382
- }
1383
- _createOperation(searchTargetId, resolvedConnectId) {
1384
- this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1385
- const sessionId = this._sessions.get(resolvedConnectId);
1386
- if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1387
- const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1388
- const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1389
- vendor: "ledger",
1390
- model: "unknown",
1391
- firmwareVersion: "",
1392
- deviceId: "",
1393
- connectId: resolvedConnectId,
1394
- connectionType
1395
- };
1396
- const operation = this._operations.create({
1397
- searchTargetId,
1398
- connectId: resolvedConnectId,
1399
- device,
1400
- connectionType,
1401
- connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
963
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceBusy
1402
964
  });
1403
- return (0, import_hwk_adapter_core4.success)(operation.operationId);
1404
965
  }
1405
- async _connectTarget(connectId, preserveOperationId, signal) {
966
+ async connectDevice(connectId) {
1406
967
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
1407
968
  try {
1408
- this._assertConnectorReady("connectDevice");
1409
- const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1410
- if (discoveredType === "usb" || discoveredType === "ble") {
1411
- this._activeConnectionType = discoveredType;
1412
- }
1413
- if (this._isBleConnection() && !connectId) {
969
+ if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1414
970
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1415
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
971
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
1416
972
  });
1417
973
  }
1418
- await this._ensureDevicePermission(connectId, void 0, signal);
1419
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1420
- const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1421
- if (!isMultiTransport && this._isBleConnection()) {
1422
- const previousSessionId = this._sessions.get(connectId);
1423
- this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1424
- if (previousSessionId) {
1425
- this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1426
- this._sessions.delete(connectId);
1427
- await this.connector.disconnect(previousSessionId).catch(() => void 0);
1428
- }
1429
- } else {
1430
- await this._evictAllSessions(preserveOperationId);
1431
- }
1432
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1433
- const stateGeneration = this._stateGeneration;
1434
- const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1435
- let session;
1436
- this._connectingConnectId = connectId;
1437
- try {
1438
- session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1439
- transportType: this._activeConnectionType ?? "usb"
1440
- }) : await this.connector.connect(connectId);
1441
- if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1442
- await this.connector.disconnect(session.sessionId).catch(() => void 0);
1443
- throw Object.assign(new Error("Ledger connection aborted"), {
1444
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
1445
- });
1446
- }
1447
- } finally {
1448
- if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1449
- releaseOperation();
974
+ if (!isLedgerBleConnectionType(this.connector.connectionType)) {
975
+ await this._evictAllSessions();
1450
976
  }
1451
- const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1452
- this._sessions.set(resolvedConnectId, session.sessionId);
1453
- 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);
1454
980
  if (session.deviceInfo) {
1455
- this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
981
+ this._discoveredDevices.set(connectId, session.deviceInfo);
1456
982
  }
1457
- const result = (0, import_hwk_adapter_core4.success)(resolvedConnectId);
983
+ const result = (0, import_hwk_adapter_core3.success)(connectId);
1458
984
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
1459
985
  return result;
1460
986
  } catch (err) {
@@ -1467,75 +993,30 @@ var _LedgerAdapter = class _LedgerAdapter {
1467
993
  return failureResult;
1468
994
  }
1469
995
  }
1470
- async releaseOperation(operationId) {
1471
- const operation = this._operations.findActive(operationId);
1472
- if (operation) this._cancelOperationWork(operation);
1473
- const endedOperation = this._operations.release(operationId);
1474
- if (!endedOperation) return;
1475
- const { connectId } = endedOperation;
996
+ async disconnectDevice(connectId) {
1476
997
  debugLog("[LedgerAdapter][REQ]", {
1477
- method: "releaseOperation",
998
+ method: "disconnectDevice",
1478
999
  connectId,
1479
1000
  params: { connectId }
1480
1001
  });
1481
1002
  try {
1482
- await this._releaseOperationConnection(endedOperation);
1483
- 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 });
1484
1009
  } catch (err) {
1485
1010
  const e = err;
1486
1011
  debugLog("[LedgerAdapter][RES]", {
1487
- method: "releaseOperation",
1012
+ method: "disconnectDevice",
1488
1013
  success: false,
1489
1014
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1490
1015
  });
1491
1016
  throw err;
1492
1017
  }
1493
1018
  }
1494
- /**
1495
- * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1496
- * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1497
- */
1498
- _cancelOperationWork(operation) {
1499
- const { operationId } = operation;
1500
- const reason = (0, import_hwk_adapter_core4.createHwkError)({
1501
- code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
1502
- message: "Ledger operation was released",
1503
- params: { operationId, reason: "explicit" }
1504
- });
1505
- const queueKey = ledgerQueueKey({ operationId });
1506
- const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1507
- this._jobQueue.cancelActiveAndPending(queueKey, reason);
1508
- if (!ownsRunningCall) return;
1509
- this._uiRegistry.cancel(void 0, void 0, operationId);
1510
- void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
1511
- }
1512
- async _releaseOperationConnection(operation) {
1513
- const sessionIds = /* @__PURE__ */ new Set();
1514
- for (const [connectId, sessionId] of this._sessions) {
1515
- if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1516
- this._sessions.delete(connectId);
1517
- sessionIds.add(sessionId);
1518
- }
1519
- }
1520
- for (const sessionId of sessionIds) {
1521
- await this._runConnectorTeardown(
1522
- () => this.connector.disconnect(sessionId).catch(() => void 0)
1523
- );
1524
- }
1525
- }
1526
- async _releaseLostOperationConnection(operationId) {
1527
- const endedOperation = this._operations.end(operationId, "disconnect");
1528
- if (!endedOperation) return;
1529
- this._discoveredDevices.delete(endedOperation.connectId);
1530
- await this._releaseOperationConnection(endedOperation);
1531
- }
1532
- async getDeviceInfo(connectIdOrOperationId, deviceId) {
1533
- let connectId;
1534
- try {
1535
- connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1536
- } catch (error) {
1537
- return this.errorToFailure(error);
1538
- }
1019
+ async getDeviceInfo(connectId, deviceId) {
1539
1020
  debugLog("[LedgerAdapter][REQ]", {
1540
1021
  method: "getDeviceInfo",
1541
1022
  connectId,
@@ -1545,7 +1026,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1545
1026
  await this._ensureDevicePermission(connectId, deviceId);
1546
1027
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
1547
1028
  if (cached) {
1548
- const result = (0, import_hwk_adapter_core4.success)(cached);
1029
+ const result = (0, import_hwk_adapter_core3.success)(cached);
1549
1030
  debugLog("[LedgerAdapter][RES]", {
1550
1031
  method: "getDeviceInfo",
1551
1032
  success: true,
@@ -1553,8 +1034,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1553
1034
  });
1554
1035
  return result;
1555
1036
  }
1556
- const notFound = (0, import_hwk_adapter_core4.failure)(
1557
- import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
1037
+ const notFound = (0, import_hwk_adapter_core3.failure)(
1038
+ import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound,
1558
1039
  "Device not found in cache. Call searchDevices() or wait for a device-connected event first."
1559
1040
  );
1560
1041
  debugLog("[LedgerAdapter][RES]", {
@@ -1570,19 +1051,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1570
1051
  success: false,
1571
1052
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1572
1053
  });
1573
- return this.errorToFailure(err);
1054
+ throw err;
1574
1055
  }
1575
1056
  }
1576
- /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1577
- async _dropUncheckedBundlePick(context, signal) {
1578
- const { connection } = context;
1579
- const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1580
- if (!connection || !owner) return;
1581
- this._pendingPickBindings.delete(connection.connectId);
1582
- this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1583
- if (this._sessions.get(connection.connectId) === connection.sessionId) {
1584
- await this._dropSession(connection.connectId, signal);
1585
- }
1057
+ getSupportedChains() {
1058
+ return ["evm", "btc", "sol", "tron"];
1586
1059
  }
1587
1060
  // ---------------------------------------------------------------------------
1588
1061
  // Chain call helper
@@ -1602,7 +1075,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1602
1075
  commonParams,
1603
1076
  installContext
1604
1077
  );
1605
- return (0, import_hwk_adapter_core4.success)(result);
1078
+ return (0, import_hwk_adapter_core3.success)(result);
1606
1079
  } catch (err) {
1607
1080
  return this.errorToFailure(err);
1608
1081
  }
@@ -1618,25 +1091,13 @@ var _LedgerAdapter = class _LedgerAdapter {
1618
1091
  if (params && typeof params === "object") {
1619
1092
  const {
1620
1093
  autoInstallApp,
1621
- operationId,
1622
1094
  passphraseState: _passphraseState,
1623
1095
  useEmptyPassphrase: _useEmptyPassphrase,
1624
- knownConnections,
1625
- extra,
1626
- allowDeviceSelection,
1627
- supportedTransports,
1628
1096
  ...rest
1629
1097
  } = params;
1630
1098
  return {
1631
1099
  commonParams: {
1632
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1633
- operationId: typeof operationId === "string" ? operationId : void 0,
1634
- ...(0, import_hwk_adapter_core4.pickConnectionContext)({
1635
- knownConnections,
1636
- extra,
1637
- allowDeviceSelection,
1638
- supportedTransports
1639
- })
1100
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1640
1101
  },
1641
1102
  rest
1642
1103
  };
@@ -1812,33 +1273,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1812
1273
  );
1813
1274
  }
1814
1275
  // ---------------------------------------------------------------------------
1815
- // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1816
- // ---------------------------------------------------------------------------
1817
- zcashGetFullViewingKey(connectId, deviceId, params) {
1818
- return this.callChainWithMergedParams(
1819
- connectId,
1820
- deviceId,
1821
- "zcash",
1822
- "zcashGetFullViewingKey",
1823
- params
1824
- );
1825
- }
1826
- zcashGetShieldedAddress(connectId, deviceId, params) {
1827
- return this.callChainWithMergedParams(
1828
- connectId,
1829
- deviceId,
1830
- "zcash",
1831
- "zcashGetShieldedAddress",
1832
- params
1833
- );
1834
- }
1835
- // ---------------------------------------------------------------------------
1836
- // 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.
1837
1279
  // ---------------------------------------------------------------------------
1838
1280
  async installApp(connectId, appName) {
1839
1281
  try {
1840
1282
  await this.connectorCall(connectId, "installApp", { appName });
1841
- return (0, import_hwk_adapter_core4.success)(void 0);
1283
+ return (0, import_hwk_adapter_core3.success)(void 0);
1842
1284
  } catch (err) {
1843
1285
  return this.errorToFailure(err);
1844
1286
  }
@@ -1846,7 +1288,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1846
1288
  async listInstalledApps(connectId) {
1847
1289
  try {
1848
1290
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1849
- return (0, import_hwk_adapter_core4.success)(result);
1291
+ return (0, import_hwk_adapter_core3.success)(result);
1850
1292
  } catch (err) {
1851
1293
  return this.errorToFailure(err);
1852
1294
  }
@@ -1855,7 +1297,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1855
1297
  async listInstalledNames(connectId) {
1856
1298
  try {
1857
1299
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1858
- return (0, import_hwk_adapter_core4.success)(result);
1300
+ return (0, import_hwk_adapter_core3.success)(result);
1859
1301
  } catch (err) {
1860
1302
  return this.errorToFailure(err);
1861
1303
  }
@@ -1863,7 +1305,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1863
1305
  async listAvailableApps(connectId) {
1864
1306
  try {
1865
1307
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1866
- return (0, import_hwk_adapter_core4.success)(result);
1308
+ return (0, import_hwk_adapter_core3.success)(result);
1867
1309
  } catch (err) {
1868
1310
  return this.errorToFailure(err);
1869
1311
  }
@@ -1871,7 +1313,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1871
1313
  async getLedgerFirmwareVersion(connectId) {
1872
1314
  try {
1873
1315
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1874
- return (0, import_hwk_adapter_core4.success)(result);
1316
+ return (0, import_hwk_adapter_core3.success)(result);
1875
1317
  } catch (err) {
1876
1318
  return this.errorToFailure(err);
1877
1319
  }
@@ -1879,7 +1321,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1879
1321
  async getLedgerDeviceInfo(connectId) {
1880
1322
  try {
1881
1323
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1882
- return (0, import_hwk_adapter_core4.success)(result);
1324
+ return (0, import_hwk_adapter_core3.success)(result);
1883
1325
  } catch (err) {
1884
1326
  return this.errorToFailure(err);
1885
1327
  }
@@ -1913,28 +1355,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1913
1355
  try {
1914
1356
  if (relayUrl) {
1915
1357
  if (!this.connector.configure) {
1916
- return (0, import_hwk_adapter_core4.failure)(
1917
- import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
1358
+ return (0, import_hwk_adapter_core3.failure)(
1359
+ import_hwk_adapter_core3.HardwareErrorCode.MethodNotSupported,
1918
1360
  "This Ledger connector does not support genuine-check relay configuration"
1919
1361
  );
1920
1362
  }
1921
1363
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1922
- await this._resetStateAndDisconnectSessions();
1364
+ this.resetState();
1923
1365
  }
1924
1366
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1925
1367
  if (!result.isGenuine) {
1926
- return (0, import_hwk_adapter_core4.success)({
1368
+ return (0, import_hwk_adapter_core3.success)({
1927
1369
  vendor: "ledger",
1928
1370
  verified: false
1929
1371
  });
1930
1372
  }
1931
1373
  if (!result.deviceId) {
1932
- return (0, import_hwk_adapter_core4.failure)(
1933
- import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
1374
+ return (0, import_hwk_adapter_core3.failure)(
1375
+ import_hwk_adapter_core3.HardwareErrorCode.UnknownError,
1934
1376
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1935
1377
  );
1936
1378
  }
1937
- return (0, import_hwk_adapter_core4.success)({
1379
+ return (0, import_hwk_adapter_core3.success)({
1938
1380
  vendor: "ledger",
1939
1381
  verified: result.isGenuine,
1940
1382
  deviceId: result.deviceId
@@ -1945,10 +1387,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1945
1387
  if (relayUrl) {
1946
1388
  try {
1947
1389
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1948
- await this._resetStateAndDisconnectSessions();
1390
+ this.resetState();
1949
1391
  } catch {
1950
1392
  this.connector.reset();
1951
- await this._resetStateAndDisconnectSessions();
1393
+ this.resetState();
1952
1394
  }
1953
1395
  }
1954
1396
  }
@@ -1960,22 +1402,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1960
1402
  this.emitter.off(event, listener);
1961
1403
  }
1962
1404
  cancel(connectId) {
1963
- const namedOperationIsLive = (id) => {
1964
- try {
1965
- this._operations.resolve(id);
1966
- return true;
1967
- } catch {
1968
- return false;
1969
- }
1970
- };
1971
- if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
1972
- debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
1973
- connectId
1974
- });
1975
- return;
1976
- }
1977
1405
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1978
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
1406
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
1979
1407
  _tag: ERROR_TAG.UserAborted
1980
1408
  });
1981
1409
  this._lastCancelReason = userAbortReason;
@@ -1984,48 +1412,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1984
1412
  this._lastCancelReason = void 0;
1985
1413
  }
1986
1414
  }, 2e3);
1987
- const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
1988
- let operationId;
1989
- if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
1990
- operationId = connectId;
1991
- } else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
1992
- operationId = activeJobId;
1993
- }
1994
- let resolvedConnectId = connectId;
1995
- if (operationId) {
1996
- try {
1997
- resolvedConnectId = this._operations.resolve(operationId).connectId;
1998
- } catch {
1999
- resolvedConnectId = void 0;
2000
- }
2001
- }
2002
- const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
2003
- const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
2004
- if (!connectId) {
2005
- this._uiRegistry.cancel();
2006
- } else if (pendingOperationId) {
2007
- this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
2008
- }
2009
- this._finishBleBinding("cancelled");
2010
- if (!connectId) this._pendingOperationBindings.clear();
2011
- else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
2012
- const queueKeys = /* @__PURE__ */ new Set();
2013
- if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
2014
- if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
2015
- if (queueKeys.size) {
2016
- let cancelledAnyJob = false;
2017
- for (const key of queueKeys) {
2018
- cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
2019
- }
2020
- debugLog("[LedgerAdapter] cancel routed to queue keys", {
2021
- queueKeys: [...queueKeys],
2022
- cancelledAnyJob
2023
- });
1415
+ this._uiRegistry.cancel();
1416
+ if (connectId) {
1417
+ this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
2024
1418
  } else {
2025
1419
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
2026
1420
  }
2027
- if (resolvedConnectId) {
2028
- const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1421
+ if (connectId) {
1422
+ const sessionId = this._sessions.get(connectId) ?? connectId;
2029
1423
  void this.connector.cancel(sessionId);
2030
1424
  } else {
2031
1425
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
@@ -2033,86 +1427,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2033
1427
  if (this._connectingPromise) {
2034
1428
  this._doConnectAbortController?.abort(userAbortReason);
2035
1429
  }
2036
- const connectingConnectId = this._connectingConnectId;
2037
- if (connectingConnectId) void this.connector.cancel(connectingConnectId);
2038
1430
  }
2039
1431
  // ---------------------------------------------------------------------------
2040
1432
  // Chain fingerprint
2041
1433
  // ---------------------------------------------------------------------------
2042
- /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
2043
1434
  async getChainFingerprint(connectId, deviceId, chain) {
2044
1435
  try {
2045
1436
  const fingerprint = await this._computeChainFingerprint(
2046
1437
  chain,
2047
1438
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
2048
1439
  );
2049
- if (deviceId) {
2050
- if (fingerprint !== deviceId) {
2051
- return (0, import_hwk_adapter_core4.failure)(
2052
- import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
2053
- formatDeviceMismatchError(deviceId, fingerprint)
2054
- );
2055
- }
2056
- }
2057
- return (0, import_hwk_adapter_core4.success)(fingerprint);
1440
+ return (0, import_hwk_adapter_core3.success)(fingerprint);
2058
1441
  } catch (err) {
2059
1442
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
2060
1443
  return this.errorToFailure(err);
2061
1444
  }
2062
1445
  }
2063
- /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2064
- 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 };
2065
1452
  try {
2066
- const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
2067
- this.emitter,
2068
- this._uiRegistry,
2069
- {
2070
- selectionRequestId,
2071
- connection: { transport: "ble", connectId },
2072
- ...identity ? { identity } : {},
2073
- extra: context?.extra,
2074
- operationId
2075
- },
2076
- signal
1453
+ const fingerprint = await this._computeChainFingerprint(
1454
+ chain,
1455
+ (method, params) => this._callConnector(sessionId, method, params)
2077
1456
  );
2078
- if (context) context.bindingSaved = outcome.saved;
2079
- if (!outcome.saved) {
2080
- debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2081
- connectId,
2082
- reason: outcome.reason
2083
- });
1457
+ if (fingerprint === deviceId) {
1458
+ return { success: true };
2084
1459
  }
2085
- } catch (error) {
2086
- await this._dropSession(connectId, signal);
2087
- throw error;
2088
- } finally {
2089
- if (this._bindingSelectionRequestId === selectionRequestId) {
2090
- 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 };
2091
1465
  }
1466
+ throw err;
2092
1467
  }
2093
1468
  }
2094
- async _dropSession(connectId, signal) {
2095
- const sessionId = this._sessions.get(connectId);
2096
- this._sessions.delete(connectId);
2097
- if (!sessionId) return;
2098
- this._sessionTransports.delete(sessionId);
2099
- const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2100
- () => void 0
2101
- );
2102
- if (!signal.aborted) await teardown;
2103
- }
2104
- /** Verify on the acquired session without re-entering the job queue. */
2105
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2106
- if (!deviceId) return { success: true };
2107
- const fingerprint = await this._computeChainFingerprint(
2108
- chain,
2109
- (method, params) => this._callConnector(sessionId, method, params)
2110
- );
2111
- if (fingerprint === deviceId) {
2112
- return { success: true };
2113
- }
2114
- return { success: false, expected: deviceId, actual: fingerprint };
2115
- }
2116
1469
  /**
2117
1470
  * Compute the chain fingerprint via a caller-supplied call strategy.
2118
1471
  *
@@ -2132,7 +1485,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2132
1485
  const result = await callMethod("btcGetMasterFingerprint", {});
2133
1486
  return result.masterFingerprint;
2134
1487
  }
2135
- const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
1488
+ const path = import_hwk_adapter_core3.CHAIN_FINGERPRINT_PATHS[chain];
2136
1489
  let address;
2137
1490
  if (chain === "evm") {
2138
1491
  address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
@@ -2140,19 +1493,10 @@ var _LedgerAdapter = class _LedgerAdapter {
2140
1493
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
2141
1494
  } else if (chain === "tron") {
2142
1495
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2143
- } else if (chain === "zcash") {
2144
- address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
2145
1496
  } else {
2146
1497
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
2147
1498
  }
2148
- return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
2149
- }
2150
- /**
2151
- * Operation owning the running job, so a mid-call UI request can name it.
2152
- * Undefined at cold start when no operation owns the job.
2153
- */
2154
- _activeOperationId() {
2155
- return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
1499
+ return (0, import_hwk_adapter_core3.deriveDeviceFingerprint)(address);
2156
1500
  }
2157
1501
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
2158
1502
  // The user must press Confirm after unlocking, which triggers a search retry.
@@ -2163,25 +1507,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2163
1507
  if (signal?.aborted) {
2164
1508
  _LedgerAdapter._throwIfAborted(signal);
2165
1509
  }
2166
- const operationId = this._activeOperationId();
2167
1510
  const waitPromise = this._uiRegistry.wait(
2168
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
2169
- { operationId }
1511
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT
2170
1512
  );
2171
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
2172
- type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
1513
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1514
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT,
2173
1515
  payload: {
2174
1516
  vendor: "ledger",
2175
1517
  reason: "device-not-found",
2176
- message: "Please connect and unlock your Ledger device",
2177
- operationId
1518
+ message: "Please connect and unlock your Ledger device"
2178
1519
  }
2179
1520
  });
2180
1521
  let payload;
2181
1522
  try {
2182
1523
  if (signal) {
2183
1524
  const onAbort = () => {
2184
- this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
1525
+ this._uiRegistry.cancel(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_CONNECT);
2185
1526
  };
2186
1527
  signal.addEventListener("abort", onAbort, { once: true });
2187
1528
  try {
@@ -2193,20 +1534,20 @@ var _LedgerAdapter = class _LedgerAdapter {
2193
1534
  payload = await waitPromise;
2194
1535
  }
2195
1536
  } catch (err) {
2196
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
2197
- type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
1537
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
1538
+ type: import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW,
2198
1539
  payload: {}
2199
1540
  });
2200
1541
  throw Object.assign(new Error("User cancelled Ledger connection"), {
2201
1542
  _tag: ERROR_TAG.UserAborted,
2202
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
1543
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
2203
1544
  cause: err
2204
1545
  });
2205
1546
  }
2206
1547
  if (!payload?.confirmed) {
2207
1548
  throw Object.assign(new Error("User cancelled Ledger connection"), {
2208
1549
  _tag: ERROR_TAG.UserAborted,
2209
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
1550
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted
2210
1551
  });
2211
1552
  }
2212
1553
  await new Promise((resolve) => {
@@ -2220,7 +1561,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2220
1561
  * Returns the params to pass through (with `showOnDevice` possibly
2221
1562
  * promoted), or `null` if the user declined.
2222
1563
  */
2223
- async _gateBtcHighIndex(params, signal) {
1564
+ async _gateBtcHighIndex(params) {
2224
1565
  const accountIndex = btcAccountIndexFromPath(params.path);
2225
1566
  if (params.showOnDevice) return params;
2226
1567
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -2229,74 +1570,50 @@ var _LedgerAdapter = class _LedgerAdapter {
2229
1570
  if (this._btcHighIndexConfirmedThisSession) {
2230
1571
  return { ...params, showOnDevice: true };
2231
1572
  }
2232
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1573
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2233
1574
  if (!confirmed) return null;
2234
1575
  this._btcHighIndexConfirmedThisSession = true;
2235
1576
  return { ...params, showOnDevice: true };
2236
1577
  }
2237
- async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2238
- const operationId = this._activeOperationId();
1578
+ async _waitForBtcHighIndexConfirm(path, accountIndex) {
2239
1579
  const waitPromise = this._uiRegistry.wait(
2240
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2241
- { operationId }
1580
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2242
1581
  );
2243
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
2244
- type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1582
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1583
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2245
1584
  payload: {
2246
1585
  vendor: "ledger",
2247
1586
  path,
2248
- accountIndex,
2249
- operationId
1587
+ accountIndex
2250
1588
  }
2251
1589
  });
2252
1590
  try {
2253
- const payload = await this._awaitUiAnswer(
2254
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2255
- waitPromise,
2256
- signal
2257
- );
1591
+ const payload = await waitPromise;
2258
1592
  return !!payload?.confirmed;
2259
1593
  } catch (err) {
2260
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
2261
- type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
1594
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
1595
+ type: import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW,
2262
1596
  payload: {}
2263
1597
  });
2264
1598
  return false;
2265
1599
  }
2266
1600
  }
2267
- /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2268
- async _awaitUiAnswer(requestType, waitPromise, signal) {
2269
- const onAbort = () => this._uiRegistry.cancel(requestType);
2270
- if (signal.aborted) onAbort();
2271
- signal.addEventListener("abort", onAbort, { once: true });
2272
- try {
2273
- return await waitPromise;
2274
- } finally {
2275
- signal.removeEventListener("abort", onAbort);
2276
- }
2277
- }
2278
1601
  // Ask the user whether to install a missing app (autoInstallApp flow).
2279
1602
  // Same register-then-emit ordering as the BTC high-index gate.
2280
- async _waitForInstallAppConfirm(appName, signal) {
2281
- const operationId = this._activeOperationId();
1603
+ async _waitForInstallAppConfirm(appName) {
2282
1604
  const waitPromise = this._uiRegistry.wait(
2283
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
2284
- { operationId }
1605
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP
2285
1606
  );
2286
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
2287
- type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
2288
- payload: { vendor: "ledger", appName, operationId }
1607
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP, {
1608
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_INSTALL_APP,
1609
+ payload: { vendor: "ledger", appName }
2289
1610
  });
2290
1611
  try {
2291
- const payload = await this._awaitUiAnswer(
2292
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
2293
- waitPromise,
2294
- signal
2295
- );
1612
+ const payload = await waitPromise;
2296
1613
  return !!payload?.confirmed;
2297
1614
  } catch (err) {
2298
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
2299
- type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
1615
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
1616
+ type: import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW,
2300
1617
  payload: {}
2301
1618
  });
2302
1619
  return false;
@@ -2305,44 +1622,34 @@ var _LedgerAdapter = class _LedgerAdapter {
2305
1622
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
2306
1623
  // `_doConnect` runs under its own internal controller so caller A's cancel
2307
1624
  // doesn't kill caller B's await.
2308
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1625
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2309
1626
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
2310
- this._assertConnectorReady("connectDevice");
2311
- if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1627
+ if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2312
1628
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2313
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
1629
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2314
1630
  });
2315
1631
  }
2316
1632
  if (connectId && this._sessions.has(connectId)) return connectId;
2317
1633
  if (!connectId && this._sessions.size > 0) {
2318
- if (!this._isBleConnection() && this._sessions.size > 1) {
1634
+ if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2319
1635
  throw Object.assign(
2320
1636
  new Error(
2321
1637
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
2322
1638
  ),
2323
- { code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
1639
+ { code: import_hwk_adapter_core3.HardwareErrorCode.DeviceOneDeviceOnly }
2324
1640
  );
2325
1641
  }
2326
1642
  return this._sessions.keys().next().value;
2327
1643
  }
2328
- if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2329
- const controller = new AbortController();
2330
- this._doConnectAbortController = controller;
2331
- const innerSignal = controller.signal;
1644
+ if (!this._connectingPromise) {
1645
+ this._doConnectAbortController = new AbortController();
1646
+ const innerSignal = this._doConnectAbortController.signal;
2332
1647
  this._connectingPromise = (async () => {
2333
1648
  try {
2334
- return await this._doConnect(
2335
- innerSignal,
2336
- connectId,
2337
- allowUsbEphemeralFallback,
2338
- preserveOperationId,
2339
- context
2340
- );
1649
+ return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2341
1650
  } finally {
2342
- if (this._doConnectAbortController === controller) {
2343
- this._connectingPromise = null;
2344
- this._doConnectAbortController = null;
2345
- }
1651
+ this._connectingPromise = null;
1652
+ this._doConnectAbortController = null;
2346
1653
  }
2347
1654
  })();
2348
1655
  }
@@ -2351,86 +1658,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2351
1658
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
2352
1659
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
2353
1660
  // throw DeviceNotFound so the user is kicked out of the loop.
2354
- async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2355
- _LedgerAdapter._throwIfAborted(internalSignal);
2356
- if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2357
- this._activeConnectionType = "usb";
2358
- const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2359
- _LedgerAdapter._throwIfAborted(internalSignal);
2360
- const knownUsb = context?.knownConnections?.find(
2361
- (connection) => connection.transport === "usb"
2362
- );
2363
- const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2364
- if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2365
- return this._connectFirstOrSelect(
2366
- usbDevices,
2367
- usbTarget,
2368
- allowUsbEphemeralFallback,
2369
- preserveOperationId,
2370
- context,
2371
- internalSignal
2372
- );
2373
- }
2374
- if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2375
- throw (0, import_hwk_adapter_core4.createHwkError)({
2376
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
2377
- message: "This Ledger model has no Bluetooth transport; connect it over USB"
2378
- });
2379
- }
2380
- this._activeConnectionType = "ble";
2381
- const knownBle = context?.knownConnections?.find(
2382
- (connection) => connection.transport === "ble"
2383
- );
2384
- if (knownBle?.transport === "ble") {
2385
- return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2386
- }
2387
- if (targetConnectId && context?.knownConnections === void 0) {
2388
- throw (0, import_hwk_adapter_core4.createHwkError)({
2389
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
2390
- message: "Ledger connection metadata is required before starting Bluetooth binding"
2391
- });
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
+ }
2392
1676
  }
2393
- const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2394
- return this._connectFirstOrSelect(
2395
- bleDevices,
2396
- void 0,
2397
- allowUsbEphemeralFallback,
2398
- preserveOperationId,
2399
- context,
2400
- internalSignal
2401
- );
2402
- }
2403
- if (this._isBleConnection() && targetConnectId) {
2404
- return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
2405
1677
  }
2406
1678
  let confirms = 0;
2407
1679
  while (!internalSignal.aborted) {
2408
1680
  this.emitter.emit("ui-event", {
2409
- type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
1681
+ type: import_hwk_adapter_core3.EConnectorInteraction.Searching,
2410
1682
  payload: { sessionId: "" }
2411
1683
  });
2412
- let devices = await this._searchDevices(void 0, internalSignal);
2413
- _LedgerAdapter._throwIfAborted(internalSignal);
1684
+ let devices = await this.searchDevices();
2414
1685
  if (devices.length === 0) {
2415
1686
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
2416
1687
  await new Promise((resolve) => {
2417
- setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
1688
+ setTimeout(resolve, import_hwk_adapter_core3.DEVICE_CONNECT_RETRY_DELAY_MS);
2418
1689
  });
2419
- _LedgerAdapter._throwIfAborted(internalSignal);
2420
- devices = await this._searchDevices(void 0, internalSignal);
2421
- _LedgerAdapter._throwIfAborted(internalSignal);
1690
+ devices = await this.searchDevices();
2422
1691
  if (devices.length > 0) break;
2423
1692
  }
2424
1693
  }
2425
- if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1694
+ if (devices.length > 0) {
2426
1695
  try {
2427
1696
  return await this._connectFirstOrSelect(
2428
1697
  devices,
2429
1698
  targetConnectId,
2430
- allowUsbEphemeralFallback,
2431
- preserveOperationId,
2432
- context,
2433
- internalSignal
1699
+ allowUsbEphemeralFallback
2434
1700
  );
2435
1701
  } catch (err) {
2436
1702
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -2450,7 +1716,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2450
1716
  new Error(
2451
1717
  "Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
2452
1718
  ),
2453
- { code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
1719
+ { code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound }
2454
1720
  );
2455
1721
  }
2456
1722
  await this._waitForDeviceConnect(internalSignal);
@@ -2459,147 +1725,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2459
1725
  _LedgerAdapter._throwIfAborted(internalSignal);
2460
1726
  throw new Error("_doConnect aborted");
2461
1727
  }
2462
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2463
- _LedgerAdapter._throwIfAborted(signal);
1728
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2464
1729
  if (targetConnectId) {
2465
1730
  const target = devices.find(
2466
1731
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
2467
1732
  );
2468
1733
  if (target) {
2469
- return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1734
+ return this._connectDeviceOrThrow(target.connectId);
2470
1735
  }
2471
- if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1736
+ if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2472
1737
  debugLog(
2473
1738
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
2474
1739
  );
2475
- return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1740
+ return this._connectDeviceOrThrow(devices[0].connectId);
2476
1741
  }
2477
- if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2478
- const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2479
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
2480
- });
2481
- if (this._isBleConnection()) {
2482
- err._tag = ERROR_TAG.DeviceNotAdvertising;
2483
- }
2484
- 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;
2485
1747
  }
1748
+ throw err;
2486
1749
  }
2487
- const requiresBleSelection = this._isBleConnection();
2488
- if (requiresBleSelection && !allowUsbEphemeralFallback) {
1750
+ if (isLedgerBleConnectionType(this.connector.connectionType)) {
2489
1751
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2490
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
1752
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2491
1753
  });
2492
1754
  }
2493
- if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2494
- const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2495
- if (context) context.bindingSessionId = bindingSessionId;
2496
- const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2497
- const knownUsb = context?.knownConnections?.find(
2498
- (connection) => connection.transport === "usb"
2499
- );
2500
- const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2501
- const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
2502
- emitter: this.emitter,
2503
- registry: this._uiRegistry,
2504
- signal,
2505
- allowUsbFallback,
2506
- scan: async () => {
2507
- if (allowUsbFallback) {
2508
- const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2509
- const candidate = usbDevices.find(
2510
- (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2511
- ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2512
- if (candidate) return [candidate];
2513
- }
2514
- return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2515
- },
2516
- request: {
2517
- devices,
2518
- bindingSessionId,
2519
- context: {
2520
- kind: "bind-connection",
2521
- transport: "ble",
2522
- reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2523
- },
2524
- extra: context?.extra,
2525
- operationId: preserveOperationId
2526
- }
2527
- });
2528
- if (device.connectionType === "usb") {
2529
- this._activeConnectionType = "usb";
2530
- if (context) context.selectedConnection = void 0;
2531
- this._bindingSelectionRequestId = requestId;
2532
- this._finishBleBinding("cancelled");
2533
- return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2534
- }
2535
- this._bindingSelectionRequestId = requestId;
2536
- const connected = await this._connectDeviceOrThrow(
2537
- device.connectId,
2538
- preserveOperationId,
2539
- signal
2540
- );
2541
- if (context) context.selectedConnection = { connectId: connected, requestId };
2542
- if (context?.deferBindingSave) {
2543
- context.pendingBinding = { connectId: connected, requestId };
2544
- } else {
2545
- await this._saveSelectedBleBinding(
2546
- connected,
2547
- requestId,
2548
- context,
2549
- preserveOperationId,
2550
- signal
2551
- );
2552
- }
2553
- return connected;
2554
- }
2555
- if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2556
- if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2557
- throw (0, import_hwk_adapter_core4.createHwkError)({
2558
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
2559
- message: "Select a Ledger device before continuing"
2560
- });
2561
- }
2562
- const requestId = this._uiRegistry.createRequestId();
2563
- const operationId = this._activeOperationId();
2564
- const waitPromise = this._uiRegistry.wait(
2565
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
2566
- { requestId, operationId }
2567
- );
2568
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
2569
- type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
2570
- payload: {
2571
- devices,
2572
- requestId,
2573
- operationId,
2574
- context: requiresBleSelection ? {
2575
- kind: "bind-connection",
2576
- transport: "ble",
2577
- reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2578
- } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2579
- extra: context?.extra
2580
- }
2581
- });
2582
- const { sdkConnectId } = await this._abortable(signal, waitPromise);
2583
- _LedgerAdapter._throwIfAborted(signal);
2584
- const selected = devices.find((device) => device.connectId === sdkConnectId);
2585
- if (!selected) {
2586
- throw Object.assign(new Error("Selected Ledger is no longer available"), {
2587
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
2588
- });
2589
- }
2590
- if (context && requiresBleSelection)
2591
- context.selectedConnection = { connectId: selected.connectId, requestId };
2592
- return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1755
+ if (devices.length > 1) {
1756
+ throw createMultipleUsbLedgerDevicesError();
2593
1757
  }
2594
1758
  if (devices.length !== 1) {
2595
1759
  throw Object.assign(new Error("Ledger device not found."), {
2596
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
1760
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceNotFound
2597
1761
  });
2598
1762
  }
2599
- return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1763
+ return this._connectDeviceOrThrow(devices[0].connectId);
2600
1764
  }
2601
- async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2602
- const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1765
+ async _connectDeviceOrThrow(chosenConnectId) {
1766
+ const result = await this.connectDevice(chosenConnectId);
2603
1767
  if (!result.success) {
2604
1768
  const payload = result.payload;
2605
1769
  const rethrow = Object.assign(new Error(payload.error), {
@@ -2610,8 +1774,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2610
1774
  }
2611
1775
  throw rethrow;
2612
1776
  }
2613
- return result.payload;
1777
+ return chosenConnectId;
2614
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
+ */
2615
1787
  /**
2616
1788
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
2617
1789
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -2623,7 +1795,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2623
1795
  */
2624
1796
  _unwrapConnectorResult(result) {
2625
1797
  if (result.success) return result.payload;
2626
- throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
1798
+ throw (0, import_hwk_adapter_core3.rehydrateConnectorError)(result.error);
2627
1799
  }
2628
1800
  /**
2629
1801
  * `connector.call` + result unwrap, optionally raced against an abort
@@ -2632,145 +1804,33 @@ var _LedgerAdapter = class _LedgerAdapter {
2632
1804
  * lives in one place.
2633
1805
  */
2634
1806
  async _callConnector(sessionId, method, params, signal) {
2635
- this._assertConnectorReady(method);
2636
- if (signal?.aborted) throw this._abortReason(signal);
2637
- const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2638
- let promise;
2639
- try {
2640
- promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2641
- } catch (error) {
2642
- releaseOperation();
2643
- throw error;
2644
- }
1807
+ const promise = this.connector.call(sessionId, method, params);
2645
1808
  const result = signal ? await this._abortable(signal, promise) : await promise;
2646
1809
  return this._unwrapConnectorResult(result);
2647
1810
  }
2648
- _assertConnectorReady(method) {
2649
- if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2650
- throw _LedgerAdapter._createDeviceBusyError(method);
2651
- }
2652
- }
2653
- _runConnectorTeardown(task) {
2654
- const previous = this._connectorTeardownTail;
2655
- let releaseTail = () => void 0;
2656
- this._connectorTeardownTail = new Promise((resolve) => {
2657
- releaseTail = resolve;
2658
- });
2659
- this._pendingConnectorTeardowns += 1;
2660
- return (async () => {
2661
- try {
2662
- await previous;
2663
- await this._waitForConnectorOperationsToDrain();
2664
- await task();
2665
- } finally {
2666
- this._pendingConnectorTeardowns -= 1;
2667
- releaseTail();
2668
- }
2669
- })();
2670
- }
2671
- _waitForConnectorOperationsToDrain() {
2672
- if (this._unsettledConnectorOperations.size === 0) {
2673
- return Promise.resolve();
2674
- }
2675
- return new Promise((resolve) => {
2676
- this._connectorIdleWaiters.add(resolve);
2677
- });
2678
- }
2679
- _retainConnectorOperation(key) {
2680
- this._unsettledConnectorOperations.set(
2681
- key,
2682
- (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2683
- );
2684
- let released = false;
2685
- return () => {
2686
- if (released) return;
2687
- released = true;
2688
- const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2689
- if (remaining > 0) {
2690
- this._unsettledConnectorOperations.set(key, remaining);
2691
- } else {
2692
- this._unsettledConnectorOperations.delete(key);
2693
- }
2694
- if (this._unsettledConnectorOperations.size === 0) {
2695
- for (const resolve of this._connectorIdleWaiters) resolve();
2696
- this._connectorIdleWaiters.clear();
2697
- }
2698
- };
2699
- }
2700
1811
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
2701
- const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
2702
- if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2703
- throw (0, import_hwk_adapter_core4.createHwkError)({
2704
- code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
2705
- message: "Conflicting Ledger operation ids",
2706
- params: {
2707
- positionalOperationId,
2708
- commonOperationId: commonParams.operationId
2709
- }
2710
- });
2711
- }
2712
- const operationId = commonParams?.operationId ?? positionalOperationId;
2713
- const operation = operationId ? this._operations.resolve(operationId) : void 0;
2714
- const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2715
- const effectiveConnectId = operation?.connectId ?? connectId;
2716
- debugLog("[LedgerAdapter][REQ]", {
2717
- method,
2718
- connectId: effectiveConnectId || "(empty)",
2719
- params: summarizeForLog(params, { method })
2720
- });
2721
- const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1812
+ debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1813
+ const queueKey = connectId || "__ledger_default__";
2722
1814
  try {
2723
1815
  const result = await this._jobQueue.enqueue(
2724
1816
  queueKey,
2725
- async (signal) => {
2726
- if (operationId) this._activeOperationJobs.add(operationId);
2727
- try {
2728
- return await this._runConnectorCall(
2729
- effectiveConnectId,
2730
- method,
2731
- params,
2732
- signal,
2733
- fingerprint,
2734
- permissionDeviceId,
2735
- commonParams,
2736
- installContext ?? {},
2737
- operationId
2738
- );
2739
- } catch (error) {
2740
- const status = signal.aborted ? "cancelled" : "failed";
2741
- const bundleConnectId = installContext?.connection?.connectId;
2742
- let keptBundlePick = false;
2743
- for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2744
- if (pickedConnectId === bundleConnectId) {
2745
- keptBundlePick = true;
2746
- } else {
2747
- this._pendingPickBindings.delete(pickedConnectId);
2748
- this._discardPendingBinding(owner, status);
2749
- await this._dropSession(pickedConnectId, signal);
2750
- }
2751
- }
2752
- if (!keptBundlePick) this._finishBleBinding(status);
2753
- throw error;
2754
- } finally {
2755
- if (operationId) {
2756
- this._activeOperationJobs.delete(operationId);
2757
- if (this._pendingOperationDisconnects.delete(operationId)) {
2758
- await this._releaseLostOperationConnection(operationId);
2759
- }
2760
- }
2761
- }
2762
- },
1817
+ async (signal) => this._runConnectorCall(
1818
+ connectId,
1819
+ method,
1820
+ params,
1821
+ signal,
1822
+ fingerprint,
1823
+ permissionDeviceId,
1824
+ commonParams,
1825
+ installContext
1826
+ ),
2763
1827
  {
2764
1828
  label: method,
2765
1829
  rejectIfBusy: true,
2766
1830
  busyError: _LedgerAdapter._createDeviceBusyError(method)
2767
1831
  }
2768
1832
  );
2769
- debugLog("[LedgerAdapter][RES]", {
2770
- method,
2771
- success: true,
2772
- payload: summarizeForLog(result, { method, role: "result" })
2773
- });
1833
+ debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2774
1834
  return result;
2775
1835
  } catch (err) {
2776
1836
  const e = err;
@@ -2784,22 +1844,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2784
1844
  }
2785
1845
  });
2786
1846
  throw err;
2787
- } finally {
2788
- releaseOperationRetention?.();
2789
1847
  }
2790
1848
  }
2791
- /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2792
- _abortReason(signal) {
2793
- return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2794
- }
2795
1849
  /**
2796
1850
  * Race a promise against an abort signal. On abort, rejects with
2797
1851
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
2798
1852
  */
2799
1853
  _abortable(signal, promise) {
2800
- const getAbortReason = () => this._abortReason(signal);
1854
+ const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2801
1855
  if (signal.aborted) {
2802
- void promise.catch(() => void 0);
2803
1856
  return Promise.reject(getAbortReason());
2804
1857
  }
2805
1858
  return new Promise((resolve, reject) => {
@@ -2826,89 +1879,39 @@ var _LedgerAdapter = class _LedgerAdapter {
2826
1879
  }
2827
1880
  }
2828
1881
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
2829
- 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) {
2830
1883
  _LedgerAdapter._throwIfAborted(signal);
2831
- if (!operationId) {
2832
- await this._ensureDevicePermission(
2833
- connectId,
2834
- permissionDeviceId ?? fingerprint?.deviceId,
2835
- signal
2836
- );
2837
- }
1884
+ await this._ensureDevicePermission(
1885
+ connectId,
1886
+ permissionDeviceId ?? fingerprint?.deviceId,
1887
+ signal
1888
+ );
2838
1889
  _LedgerAdapter._throwIfAborted(signal);
2839
1890
  let effectiveParams = params;
2840
1891
  if (method === "btcGetPublicKey") {
2841
- const gatedParams = await this._gateBtcHighIndex(params, signal);
1892
+ const gatedParams = await this._gateBtcHighIndex(params);
2842
1893
  if (gatedParams === null) {
2843
1894
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
2844
1895
  _tag: ERROR_TAG.UserAborted,
2845
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
1896
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted
2846
1897
  });
2847
1898
  }
2848
1899
  effectiveParams = gatedParams;
2849
1900
  }
2850
1901
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
2851
- let businessCallStarted = false;
2852
- const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2853
- const knownTransport = this._isBleConnection() ? "ble" : "usb";
2854
- const hintedConnectId = commonParams?.knownConnections?.find(
2855
- (connection) => connection.transport === knownTransport
2856
- );
2857
- const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2858
- const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2859
- const checksWallet = Boolean(
2860
- fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2861
- );
2862
- const connectionAttempt = {
2863
- ...commonParams,
2864
- deferBindingSave: checksWallet
2865
- };
2866
- const bundleConnection = installContext?.connection;
2867
- if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2868
- throw (0, import_hwk_adapter_core4.createHwkError)({
2869
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
2870
- message: "Ledger all-network connection ended"
2871
- });
2872
- }
2873
- const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2874
- preferredConnectId,
1902
+ const resolvedConnectId = await this.ensureConnected(
1903
+ connectId,
2875
1904
  signal,
2876
- allowUsbEphemeralFallback,
2877
- void 0,
2878
- connectionAttempt
1905
+ allowUsbEphemeralFallback
2879
1906
  );
2880
- const walletCheck = installContext?.walletCheck;
2881
- if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2882
- throw (0, import_hwk_adapter_core4.createHwkError)({
2883
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
2884
- message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2885
- });
2886
- }
2887
1907
  const sessionId = this._sessions.get(resolvedConnectId);
2888
- if (sessionId && installContext && !installContext.connection) {
2889
- installContext.connection = { connectId: resolvedConnectId, sessionId };
2890
- }
2891
1908
  if (!sessionId) {
2892
- if (operationId) {
2893
- this._operations.end(operationId, "disconnect");
2894
- throw (0, import_hwk_adapter_core4.createHwkError)({
2895
- code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
2896
- message: "Ledger operation connection is no longer active",
2897
- params: { operationId, reason: "disconnect" }
2898
- });
2899
- }
2900
1909
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
2901
1910
  _tag: ERROR_TAG.DeviceSessionNotFound
2902
1911
  });
2903
1912
  }
2904
1913
  try {
2905
- const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2906
- if (!operationId && connectionAttempt.pendingBinding) {
2907
- this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2908
- }
2909
- const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2910
- const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2911
- if (fingerprint && checksWallet) {
1914
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2912
1915
  const fp = await this._abortable(
2913
1916
  signal,
2914
1917
  this._verifyDeviceFingerprintWithSession(
@@ -2918,68 +1921,14 @@ var _LedgerAdapter = class _LedgerAdapter {
2918
1921
  )
2919
1922
  );
2920
1923
  if (!fp.success) {
2921
- if (pendingBinding) {
2922
- this._discardPendingBinding(bindingOwner, "failed");
2923
- this._pendingPickBindings.delete(resolvedConnectId);
2924
- }
2925
- if (operationId) {
2926
- this._pendingOperationBindings.delete(operationId);
2927
- this._operations.end(operationId, "explicit");
2928
- await this._dropSession(resolvedConnectId, signal);
2929
- }
2930
1924
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2931
- code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
1925
+ code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
2932
1926
  });
2933
1927
  }
2934
- if (walletCheck) walletCheck.verified = true;
2935
- }
2936
- if (pendingBinding && bindingOwner) {
2937
- bindingOwner.pendingBinding = void 0;
2938
- if (operationId) this._pendingOperationBindings.delete(operationId);
2939
- else this._pendingPickBindings.delete(resolvedConnectId);
2940
- await this._saveSelectedBleBinding(
2941
- pendingBinding.connectId,
2942
- pendingBinding.requestId,
2943
- bindingOwner,
2944
- operationId,
2945
- signal,
2946
- fingerprint && checksWallet ? {
2947
- vendor: "ledger",
2948
- type: "chainFingerprint",
2949
- chain: fingerprint.chain,
2950
- value: fingerprint.deviceId
2951
- } : void 0
2952
- );
2953
1928
  }
2954
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
2955
- this._selectedBleReconnectTargets.set(connectId, {
2956
- connectId: resolvedConnectId,
2957
- chain: fingerprint.chain,
2958
- fingerprint: fingerprint.deviceId
2959
- });
2960
- }
2961
- businessCallStarted = true;
2962
- const result = await this._callConnector(sessionId, method, effectiveParams, signal);
2963
- if (walletCheck) walletCheck.derived = true;
2964
- return result;
1929
+ return await this._callConnector(sessionId, method, effectiveParams, signal);
2965
1930
  } catch (err) {
2966
1931
  if (signal.aborted) throw err;
2967
- if (isLostConnectionError(err)) {
2968
- this._discoveredDevices.delete(resolvedConnectId);
2969
- if (operationId) await this._releaseLostOperationConnection(operationId);
2970
- else {
2971
- this._sessions.delete(resolvedConnectId);
2972
- await this.connector.disconnect(sessionId).catch(() => void 0);
2973
- }
2974
- const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
2975
- const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
2976
- throw (0, import_hwk_adapter_core4.createHwkError)({
2977
- code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
2978
- message: "Ledger operation connection was lost; start a new operation",
2979
- params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
2980
- recovery: ambiguous ? { scope: "unknown" } : void 0
2981
- });
2982
- }
2983
1932
  const errObj = err;
2984
1933
  debugLog("[LedgerAdapter] connectorCall error:", method, {
2985
1934
  message: errObj?.message,
@@ -2991,66 +1940,8 @@ var _LedgerAdapter = class _LedgerAdapter {
2991
1940
  isNotAdvertising: isDeviceNotAdvertisingError(err),
2992
1941
  isStuckApp: isStuckAppStateError(err)
2993
1942
  });
2994
- const assertSessionCurrent = (message) => {
2995
- if (this._sessions.get(resolvedConnectId) === sessionId) return;
2996
- throw (0, import_hwk_adapter_core4.createHwkError)({
2997
- code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
2998
- message
2999
- });
3000
- };
3001
- if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
3002
- await this._waitForDeviceConnect(signal);
3003
- assertSessionCurrent("Ledger connection ended while waiting for unlock");
3004
- if (walletCheck?.derived) walletCheck.verified = false;
3005
- return this._runConnectorCall(
3006
- resolvedConnectId,
3007
- method,
3008
- effectiveParams,
3009
- signal,
3010
- fingerprint,
3011
- permissionDeviceId,
3012
- commonParams,
3013
- installContext,
3014
- operationId,
3015
- lockedRetryBudget - 1
3016
- );
3017
- }
3018
- if (businessCallStarted && isStuckAppStateError(err)) {
3019
- await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
3020
- assertSessionCurrent("Ledger connection ended during the app transition");
3021
- try {
3022
- const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
3023
- if (walletCheck) walletCheck.derived = true;
3024
- return retried;
3025
- } catch (retryErr) {
3026
- if (isStuckAppStateError(retryErr)) throw err;
3027
- if (isLostConnectionError(retryErr)) {
3028
- if (operationId) await this._releaseLostOperationConnection(operationId);
3029
- else {
3030
- this._sessions.delete(resolvedConnectId);
3031
- this._discoveredDevices.delete(resolvedConnectId);
3032
- await this.connector.disconnect(sessionId).catch(() => void 0);
3033
- }
3034
- const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
3035
- throw (0, import_hwk_adapter_core4.createHwkError)({
3036
- code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
3037
- message: `Ledger ${method} may have completed before the connection was lost`,
3038
- params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3039
- recovery: ambiguous ? { scope: "unknown" } : void 0
3040
- });
3041
- }
3042
- throw retryErr;
3043
- }
3044
- }
3045
- if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
3046
- this._sessions.delete(resolvedConnectId);
3047
- this._sessionTransports.delete(sessionId);
3048
- this._discoveredDevices.delete(resolvedConnectId);
3049
- await this.connector.disconnect(sessionId).catch(() => void 0);
3050
- throw err;
3051
- }
3052
1943
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
3053
- const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
1944
+ const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core3.HardwareErrorCode.AppNotInstalled;
3054
1945
  if (autoInstallApp && isAppMissing) {
3055
1946
  if (installContext?.deviceOutOfMemoryError) {
3056
1947
  throw installContext.deviceOutOfMemoryError;
@@ -3058,30 +1949,30 @@ var _LedgerAdapter = class _LedgerAdapter {
3058
1949
  const appName = err?.appName ?? mapLedgerError(err).appName;
3059
1950
  if (appName) {
3060
1951
  if (installContext?.installAttemptedAppNames?.has(appName)) {
3061
- throw (0, import_hwk_adapter_core4.createHwkError)({
3062
- code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
1952
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1953
+ code: import_hwk_adapter_core3.HardwareErrorCode.AppNotInstalled,
3063
1954
  message: `${appName} install reported success but the app is still missing on device`,
3064
1955
  _tag: ERROR_TAG.AppInstallVerifyFailed,
3065
1956
  appName
3066
1957
  });
3067
1958
  }
3068
- const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1959
+ const confirmed = await this._waitForInstallAppConfirm(appName);
3069
1960
  if (!confirmed) {
3070
- throw (0, import_hwk_adapter_core4.createHwkError)({
3071
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
1961
+ throw (0, import_hwk_adapter_core3.createHwkError)({
1962
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
3072
1963
  message: `User declined to install ${appName}`,
3073
1964
  _tag: ERROR_TAG.UserAborted,
3074
1965
  appName
3075
1966
  });
3076
1967
  }
3077
1968
  this.emitter.emit("ui-event", {
3078
- type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
1969
+ type: import_hwk_adapter_core3.EConnectorInteraction.AppInstallProgress,
3079
1970
  payload: { connectId: resolvedConnectId, appName, progress: 0 }
3080
1971
  });
3081
1972
  try {
3082
1973
  await this._callConnector(sessionId, "installApp", { appName }, signal);
3083
1974
  } catch (installErr) {
3084
- if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
1975
+ if (mapLedgerError(installErr).code === import_hwk_adapter_core3.HardwareErrorCode.DeviceOutOfMemory) {
3085
1976
  if (installContext) {
3086
1977
  installContext.deviceOutOfMemoryError = installErr;
3087
1978
  }
@@ -3092,8 +1983,8 @@ var _LedgerAdapter = class _LedgerAdapter {
3092
1983
  installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
3093
1984
  installContext.installAttemptedAppNames.add(appName);
3094
1985
  }
3095
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
3096
- type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
1986
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
1987
+ type: import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW,
3097
1988
  payload: {}
3098
1989
  });
3099
1990
  return await this._runConnectorCall(
@@ -3104,14 +1995,157 @@ var _LedgerAdapter = class _LedgerAdapter {
3104
1995
  fingerprint,
3105
1996
  permissionDeviceId,
3106
1997
  commonParams,
3107
- installContext,
3108
- operationId
1998
+ installContext
3109
1999
  );
3110
2000
  }
3111
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
+ }
3112
2112
  throw err;
3113
2113
  }
3114
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
+ }
3115
2149
  _sleepAbortable(ms, signal) {
3116
2150
  return new Promise((resolve, reject) => {
3117
2151
  if (signal.aborted) {
@@ -3130,26 +2164,115 @@ var _LedgerAdapter = class _LedgerAdapter {
3130
2164
  });
3131
2165
  }
3132
2166
  /**
3133
- * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3134
- * 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
3135
2259
  */
3136
2260
  async _ensureDevicePermission(connectId, deviceId, signal) {
3137
2261
  if (signal?.aborted) {
3138
2262
  _LedgerAdapter._throwIfAborted(signal);
3139
2263
  }
3140
2264
  const transportType = this.activeTransport ?? "hid";
3141
- const operationId = this._activeOperationId();
3142
2265
  const waitPromise = this._uiRegistry.wait(
3143
- import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
3144
- { timeoutMs: 6e4, operationId }
2266
+ import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2267
+ { timeoutMs: 6e4 }
3145
2268
  );
3146
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
3147
- type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
3148
- payload: { transportType, connectId, deviceId, operationId }
2269
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2270
+ type: import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2271
+ payload: { transportType, connectId, deviceId }
3149
2272
  });
3150
2273
  let response;
3151
2274
  const onAbort = () => {
3152
- this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
2275
+ this._uiRegistry.cancel(import_hwk_adapter_core3.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
3153
2276
  };
3154
2277
  try {
3155
2278
  signal?.addEventListener("abort", onAbort, { once: true });
@@ -3158,14 +2281,14 @@ var _LedgerAdapter = class _LedgerAdapter {
3158
2281
  if (signal?.aborted) {
3159
2282
  _LedgerAdapter._throwIfAborted(signal);
3160
2283
  }
3161
- if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
3162
- this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
3163
- type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
2284
+ if (err?._tag === import_hwk_adapter_core3.UI_REQUEST_PREEMPTED_TAG) {
2285
+ this.emitter.emit(import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW, {
2286
+ type: import_hwk_adapter_core3.UI_REQUEST.CLOSE_UI_WINDOW,
3164
2287
  payload: {}
3165
2288
  });
3166
2289
  throw Object.assign(new Error("Device permission request superseded"), {
3167
2290
  _tag: ERROR_TAG.UserAborted,
3168
- code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
2291
+ code: import_hwk_adapter_core3.HardwareErrorCode.UserAborted,
3169
2292
  cause: err
3170
2293
  });
3171
2294
  }
@@ -3176,7 +2299,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3176
2299
  const { granted, reason, message } = response;
3177
2300
  if (!granted) {
3178
2301
  throw Object.assign(new Error(message ?? "Device permission denied"), {
3179
- code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
2302
+ code: import_hwk_adapter_core3.HardwareErrorCode.DevicePermissionDenied,
3180
2303
  reason
3181
2304
  });
3182
2305
  }
@@ -3190,16 +2313,8 @@ var _LedgerAdapter = class _LedgerAdapter {
3190
2313
  const tag = err && typeof err === "object" ? err._tag : void 0;
3191
2314
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
3192
2315
  const e = err;
3193
- const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
3194
- return ledgerFailure(
3195
- e.code,
3196
- e.message ?? "Unknown error",
3197
- e.appName,
3198
- tag,
3199
- params,
3200
- void 0,
3201
- (0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
3202
- );
2316
+ const params = e.code === import_hwk_adapter_core3.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
2317
+ return ledgerFailure(e.code, e.message ?? "Unknown error", e.appName, tag, params);
3203
2318
  }
3204
2319
  const mapped = mapLedgerError(err);
3205
2320
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -3226,7 +2341,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3226
2341
  deviceId: device.deviceId,
3227
2342
  connectId: device.connectId,
3228
2343
  label: device.name,
3229
- connectionType: device.connectionType ?? this.connector.connectionType,
2344
+ connectionType: this.connector.connectionType,
3230
2345
  rssi: device.rssi,
3231
2346
  isConnectable: device.isConnectable,
3232
2347
  serialNumber: device.serialNumber,
@@ -3524,12 +2639,11 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
3524
2639
  var import_context_module = require("@ledgerhq/context-module");
3525
2640
 
3526
2641
  // src/signer/SignerEth.ts
3527
- var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
2642
+ var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
3528
2643
 
3529
2644
  // src/signer/deviceActionToPromise.ts
3530
2645
  var import_device_management_kit = require("@ledgerhq/device-management-kit");
3531
2646
  var IDLE_WATCHDOG_MS = 65e3;
3532
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3533
2647
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
3534
2648
  return new Promise((resolve, reject) => {
3535
2649
  let settled = false;
@@ -3717,6 +2831,7 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
3717
2831
  }
3718
2832
 
3719
2833
  // src/signer/SignerEth.ts
2834
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3720
2835
  var SignerEth = class {
3721
2836
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3722
2837
  constructor(_sdk) {
@@ -3737,7 +2852,7 @@ var SignerEth = class {
3737
2852
  );
3738
2853
  }
3739
2854
  async signTransaction(derivationPath, serializedTxHex) {
3740
- const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
2855
+ const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core4.hexToBytes)(serializedTxHex));
3741
2856
  return deviceActionToPromise(
3742
2857
  action,
3743
2858
  this.onInteraction,
@@ -3746,7 +2861,7 @@ var SignerEth = class {
3746
2861
  );
3747
2862
  }
3748
2863
  async signMessage(derivationPath, message) {
3749
- const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
2864
+ const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core4.hexToBytes)(message));
3750
2865
  return deviceActionToPromise(
3751
2866
  action,
3752
2867
  this.onInteraction,
@@ -3787,7 +2902,7 @@ var SignerManager = class _SignerManager {
3787
2902
  return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
3788
2903
  }
3789
2904
  static _createContextModule() {
3790
- 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();
3791
2906
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
3792
2907
  }
3793
2908
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -3806,44 +2921,23 @@ var SignerManager = class _SignerManager {
3806
2921
  };
3807
2922
 
3808
2923
  // src/connector/chains/evm.ts
3809
- var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
2924
+ var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
3810
2925
 
3811
2926
  // src/connector/chains/utils.ts
3812
- var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
2927
+ var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
3813
2928
  function normalizePath(path) {
3814
2929
  return path.startsWith("m/") ? path.slice(2) : path;
3815
2930
  }
3816
2931
  function collapseSignerInteraction(interaction) {
3817
2932
  switch (interaction) {
3818
2933
  case "confirm-open-app":
3819
- return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
3820
- case "unlock-device":
3821
- return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
3822
- case "interaction-complete":
3823
- return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
3824
- default:
3825
- return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
3826
- }
3827
- }
3828
- function wireSignerToSession(ctx, sessionId, chain, signer) {
3829
- signer.onInteraction = (interaction) => {
3830
- debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3831
- ctx.emit("ui-event", {
3832
- type: collapseSignerInteraction(interaction),
3833
- payload: { sessionId }
3834
- });
3835
- };
3836
- signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3837
- return signer;
3838
- }
3839
- async function runSignerCall(ctx, sessionId, call) {
3840
- try {
3841
- return await call();
3842
- } catch (err) {
3843
- ctx.invalidateSession(sessionId);
3844
- throw ctx.wrapError(err);
3845
- } finally {
3846
- ctx.clearCanceller(sessionId);
2934
+ return import_hwk_adapter_core5.EConnectorInteraction.ConfirmOpenApp;
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;
3847
2941
  }
3848
2942
  }
3849
2943
 
@@ -3869,7 +2963,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
3869
2963
  new Error(
3870
2964
  "Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
3871
2965
  ),
3872
- { code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
2966
+ { code: import_hwk_adapter_core6.HardwareErrorCode.InvalidParams }
3873
2967
  );
3874
2968
  }
3875
2969
  const signer = await _getEthSigner(ctx, sessionId);
@@ -3878,8 +2972,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
3878
2972
  const result = await signer.signTransaction(path, params.serializedTx);
3879
2973
  return {
3880
2974
  v: `0x${result.v.toString(16)}`,
3881
- r: (0, import_hwk_adapter_core7.padHex64)(result.r),
3882
- s: (0, import_hwk_adapter_core7.padHex64)(result.s)
2975
+ r: (0, import_hwk_adapter_core6.padHex64)(result.r),
2976
+ s: (0, import_hwk_adapter_core6.padHex64)(result.s)
3883
2977
  };
3884
2978
  } catch (err) {
3885
2979
  ctx.invalidateSession(sessionId);
@@ -3893,8 +2987,8 @@ async function evmSignMessage(ctx, sessionId, params) {
3893
2987
  const path = normalizePath(params.path);
3894
2988
  try {
3895
2989
  const result = await signer.signMessage(path, params.message);
3896
- const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
3897
- const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
2990
+ const rHex = (0, import_hwk_adapter_core6.stripHex)(result.r).padStart(64, "0");
2991
+ const sHex = (0, import_hwk_adapter_core6.stripHex)(result.s).padStart(64, "0");
3898
2992
  const vHex = result.v.toString(16).padStart(2, "0");
3899
2993
  return { signature: `0x${rHex}${sHex}${vHex}` };
3900
2994
  } catch (err) {
@@ -3910,15 +3004,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
3910
3004
  new Error(
3911
3005
  'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
3912
3006
  ),
3913
- { code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
3007
+ { code: import_hwk_adapter_core6.HardwareErrorCode.MethodNotSupported }
3914
3008
  );
3915
3009
  }
3916
3010
  const signer = await _getEthSigner(ctx, sessionId);
3917
3011
  const path = normalizePath(params.path);
3918
3012
  try {
3919
3013
  const result = await signer.signTypedData(path, params.data);
3920
- const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
3921
- const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
3014
+ const rHex = (0, import_hwk_adapter_core6.stripHex)(result.r).padStart(64, "0");
3015
+ const sHex = (0, import_hwk_adapter_core6.stripHex)(result.s).padStart(64, "0");
3922
3016
  const vHex = result.v.toString(16).padStart(2, "0");
3923
3017
  return { signature: `0x${rHex}${sHex}${vHex}` };
3924
3018
  } catch (err) {
@@ -3945,14 +3039,15 @@ async function _getEthSigner(ctx, sessionId) {
3945
3039
  }
3946
3040
 
3947
3041
  // src/connector/chains/btc.ts
3948
- var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
3949
- var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
3042
+ var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
3043
+ var import_bitcoinjs_lib = require("bitcoinjs-lib");
3950
3044
 
3951
3045
  // src/signer/SignerBtc.ts
3952
- var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
3046
+ var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
3953
3047
  function hexToUtf8(hex) {
3954
- return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
3048
+ return new TextDecoder().decode((0, import_hwk_adapter_core7.hexToBytes)(hex));
3955
3049
  }
3050
+ var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3956
3051
  var SignerBtc = class {
3957
3052
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3958
3053
  constructor(_sdk) {
@@ -3966,7 +3061,7 @@ var SignerBtc = class {
3966
3061
  return deviceActionToPromise(
3967
3062
  action,
3968
3063
  this.onInteraction,
3969
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3064
+ void 0,
3970
3065
  this.onRegisterCanceller
3971
3066
  );
3972
3067
  }
@@ -3984,14 +3079,14 @@ var SignerBtc = class {
3984
3079
  const result = await deviceActionToPromise(
3985
3080
  action,
3986
3081
  this.onInteraction,
3987
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3082
+ void 0,
3988
3083
  this.onRegisterCanceller
3989
3084
  );
3990
3085
  debugLog(
3991
3086
  "[SignerBtc] getExtendedPublicKey result type:",
3992
3087
  typeof result,
3993
3088
  "value:",
3994
- summarizeForLog(result)
3089
+ typeof result === "string" ? `${result.substring(0, 20)}...` : JSON.stringify(result).substring(0, 50)
3995
3090
  );
3996
3091
  if (typeof result === "string") return result;
3997
3092
  return result.extendedPublicKey;
@@ -4020,7 +3115,7 @@ var SignerBtc = class {
4020
3115
  return deviceActionToPromise(
4021
3116
  action,
4022
3117
  this.onInteraction,
4023
- INTERACTIVE_TIMEOUT_MS,
3118
+ INTERACTIVE_TIMEOUT_MS2,
4024
3119
  this.onRegisterCanceller
4025
3120
  );
4026
3121
  }
@@ -4033,7 +3128,7 @@ var SignerBtc = class {
4033
3128
  return deviceActionToPromise(
4034
3129
  action,
4035
3130
  this.onInteraction,
4036
- INTERACTIVE_TIMEOUT_MS,
3131
+ INTERACTIVE_TIMEOUT_MS2,
4037
3132
  this.onRegisterCanceller
4038
3133
  );
4039
3134
  }
@@ -4046,7 +3141,7 @@ var SignerBtc = class {
4046
3141
  return deviceActionToPromise(
4047
3142
  action,
4048
3143
  this.onInteraction,
4049
- INTERACTIVE_TIMEOUT_MS,
3144
+ INTERACTIVE_TIMEOUT_MS2,
4050
3145
  this.onRegisterCanceller
4051
3146
  );
4052
3147
  }
@@ -4065,25 +3160,11 @@ function _purposeToTemplate(purpose, DDT) {
4065
3160
  return DDT.TAPROOT;
4066
3161
  default:
4067
3162
  throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
4068
- code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
3163
+ code: import_hwk_adapter_core8.HardwareErrorCode.InvalidParams
4069
3164
  });
4070
3165
  }
4071
3166
  }
4072
- function assertBitcoinMainnet(coin) {
4073
- if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4074
- throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4075
- code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
4076
- });
4077
- }
4078
- }
4079
3167
  async function btcGetAddress(ctx, sessionId, params) {
4080
- assertBitcoinMainnet(params.coin);
4081
- if (normalizePath(params.path).split("/").length !== 3) {
4082
- throw Object.assign(
4083
- new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4084
- { code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
4085
- );
4086
- }
4087
3168
  const btcSigner = await _createBtcSigner(ctx, sessionId);
4088
3169
  const path = normalizePath(params.path);
4089
3170
  try {
@@ -4114,7 +3195,6 @@ async function btcGetAddress(ctx, sessionId, params) {
4114
3195
  }
4115
3196
  }
4116
3197
  async function btcGetPublicKey(ctx, sessionId, params) {
4117
- assertBitcoinMainnet(params.coin);
4118
3198
  const btcSigner = await _createBtcSigner(ctx, sessionId);
4119
3199
  const path = normalizePath(params.path);
4120
3200
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -4122,7 +3202,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
4122
3202
  const xpub = await btcSigner.getExtendedPublicKey(path, {
4123
3203
  checkOnDevice: params.showOnDevice ?? false
4124
3204
  });
4125
- debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
3205
+ debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", `${xpub?.substring(0, 20)}...`);
4126
3206
  return { xpub, path: params.path };
4127
3207
  } catch (err) {
4128
3208
  debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
@@ -4136,7 +3216,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
4136
3216
  if (!params.psbt) {
4137
3217
  throw Object.assign(
4138
3218
  new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
4139
- { code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
3219
+ { code: import_hwk_adapter_core8.HardwareErrorCode.InvalidParams }
4140
3220
  );
4141
3221
  }
4142
3222
  const btcSigner = await _createBtcSigner(ctx, sessionId);
@@ -4150,7 +3230,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
4150
3230
  debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
4151
3231
  const wallet = new DefaultWallet(path, template);
4152
3232
  const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
4153
- return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
3233
+ return { serializedTx: (0, import_hwk_adapter_core8.stripHex)(signedTxHex) };
4154
3234
  } catch (err) {
4155
3235
  ctx.invalidateSession(sessionId);
4156
3236
  throw ctx.wrapError(err);
@@ -4161,7 +3241,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
4161
3241
  async function btcSignPsbt(ctx, sessionId, params) {
4162
3242
  if (!params.psbt) {
4163
3243
  throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
4164
- code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
3244
+ code: import_hwk_adapter_core8.HardwareErrorCode.InvalidParams
4165
3245
  });
4166
3246
  }
4167
3247
  const btcSigner = await _createBtcSigner(ctx, sessionId);
@@ -4191,8 +3271,8 @@ async function btcSignMessage(ctx, sessionId, params) {
4191
3271
  try {
4192
3272
  const result = await btcSigner.signMessage(path, params.message);
4193
3273
  const vHex = result.v.toString(16).padStart(2, "0");
4194
- const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
4195
- const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
3274
+ const rHex = (0, import_hwk_adapter_core8.stripHex)(result.r).padStart(64, "0");
3275
+ const sHex = (0, import_hwk_adapter_core8.stripHex)(result.s).padStart(64, "0");
4196
3276
  return { signature: `${vHex}${rHex}${sHex}` };
4197
3277
  } catch (err) {
4198
3278
  ctx.invalidateSession(sessionId);
@@ -4243,7 +3323,7 @@ function _isScriptPathInput(input) {
4243
3323
  return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
4244
3324
  }
4245
3325
  function _applySignaturesToPsbt(psbtHex, signatures) {
4246
- const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
3326
+ const psbt = import_bitcoinjs_lib.Psbt.fromHex(psbtHex);
4247
3327
  for (const sig of signatures) {
4248
3328
  const input = psbt.data.inputs[sig.inputIndex];
4249
3329
  if (!input) {
@@ -4292,8 +3372,7 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
4292
3372
  }
4293
3373
 
4294
3374
  // src/connector/chains/sol.ts
4295
- var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
4296
- var import_bs58 = __toESM(require("bs58"));
3375
+ var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
4297
3376
 
4298
3377
  // src/signer/SignerSol.ts
4299
3378
  var SignerSol = class {
@@ -4311,7 +3390,7 @@ var SignerSol = class {
4311
3390
  return deviceActionToPromise(
4312
3391
  action,
4313
3392
  this.onInteraction,
4314
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3393
+ void 0,
4315
3394
  this.onRegisterCanceller
4316
3395
  );
4317
3396
  }
@@ -4323,7 +3402,7 @@ var SignerSol = class {
4323
3402
  return deviceActionToPromise(
4324
3403
  action,
4325
3404
  this.onInteraction,
4326
- INTERACTIVE_TIMEOUT_MS,
3405
+ void 0,
4327
3406
  this.onRegisterCanceller
4328
3407
  );
4329
3408
  }
@@ -4336,7 +3415,7 @@ var SignerSol = class {
4336
3415
  return deviceActionToPromise(
4337
3416
  action,
4338
3417
  this.onInteraction,
4339
- INTERACTIVE_TIMEOUT_MS,
3418
+ void 0,
4340
3419
  this.onRegisterCanceller
4341
3420
  );
4342
3421
  }
@@ -4361,10 +3440,10 @@ async function solGetAddress(ctx, sessionId, params) {
4361
3440
  async function solSignTransaction(ctx, sessionId, params) {
4362
3441
  const solSigner = await _createSolSigner(ctx, sessionId);
4363
3442
  const path = normalizePath(params.path);
4364
- const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
3443
+ const txBytes = (0, import_hwk_adapter_core9.hexToBytes)(params.serializedTx);
4365
3444
  try {
4366
3445
  const result = await solSigner.signTransaction(path, txBytes);
4367
- return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
3446
+ return { signature: (0, import_hwk_adapter_core9.bytesToHex)(result) };
4368
3447
  } catch (err) {
4369
3448
  ctx.invalidateSession(sessionId);
4370
3449
  throw ctx.wrapError(err);
@@ -4375,23 +3454,10 @@ async function solSignTransaction(ctx, sessionId, params) {
4375
3454
  async function solSignMessage(ctx, sessionId, params) {
4376
3455
  const solSigner = await _createSolSigner(ctx, sessionId);
4377
3456
  const path = normalizePath(params.path);
4378
- const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
3457
+ const messageBytes = (0, import_hwk_adapter_core9.hexToBytes)(params.message);
4379
3458
  try {
4380
- if (params.messageVersion === 1) {
4381
- const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
4382
- message: messageBytes,
4383
- requiredSigners: params.requiredSigners
4384
- });
4385
- const { SignMessageVersion } = await ctx.importLedgerKit(
4386
- "@ledgerhq/device-signer-kit-solana"
4387
- );
4388
- const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4389
- version: SignMessageVersion.Raw
4390
- });
4391
- return { signature: decodeBase58Signature(result2.signature) };
4392
- }
4393
3459
  const result = await solSigner.signMessage(path, messageBytes);
4394
- return { signature: decodeBase58EnvelopeSignature(result.signature) };
3460
+ return { signature: result.signature };
4395
3461
  } catch (err) {
4396
3462
  ctx.invalidateSession(sessionId);
4397
3463
  throw ctx.wrapError(err);
@@ -4399,27 +3465,11 @@ async function solSignMessage(ctx, sessionId, params) {
4399
3465
  ctx.clearCanceller(sessionId);
4400
3466
  }
4401
3467
  }
4402
- function decodeBase58Signature(signature) {
4403
- const bytes = import_bs58.default.decode(signature);
4404
- if (bytes.length !== 64) {
4405
- throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4406
- }
4407
- return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
4408
- }
4409
- function decodeBase58EnvelopeSignature(envelope) {
4410
- const bytes = import_bs58.default.decode(envelope);
4411
- if (bytes.length < 65 || bytes[0] !== 1) {
4412
- throw new Error("Ledger Solana signature envelope is invalid");
4413
- }
4414
- return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
4415
- }
4416
3468
  async function _createSolSigner(ctx, sessionId) {
4417
3469
  const dmk = await ctx.getOrCreateDmk();
4418
- const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4419
- "@ledgerhq/context-module"
4420
- );
3470
+ const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4421
3471
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
4422
- const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3472
+ const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4423
3473
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
4424
3474
  const signer = new SignerSol(sdkSigner);
4425
3475
  signer.onInteraction = (interaction) => {
@@ -4435,119 +3485,316 @@ async function _createSolSigner(ctx, sessionId) {
4435
3485
  return signer;
4436
3486
  }
4437
3487
 
4438
- // src/connector/chains/zcash.ts
3488
+ // src/connector/chains/tron.ts
3489
+ var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
3490
+ var import_hw_app_trx = __toESM(require("@ledgerhq/hw-app-trx"));
3491
+
3492
+ // src/connector/chains/legacyChainCall.ts
4439
3493
  var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
4440
3494
 
4441
- // src/signer/SignerZcash.ts
4442
- var SignerZcash = class {
4443
- // eslint-disable-next-line no-useless-constructor, no-empty-function
4444
- constructor(_sdk) {
4445
- this._sdk = _sdk;
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;
4446
3514
  }
4447
- /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4448
- async getFullViewingKey(derivationPath, options) {
4449
- const action = this._sdk.getFullViewingKey(derivationPath, options);
4450
- return deviceActionToPromise(
4451
- action,
4452
- this.onInteraction,
4453
- void 0,
4454
- 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
+ }
4455
3593
  );
4456
3594
  }
4457
- /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4458
- async getShieldedAddress(derivationPath, options) {
4459
- const action = this._sdk.getShieldedAddress(derivationPath, options);
4460
- return deviceActionToPromise(
4461
- action,
4462
- this.onInteraction,
4463
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4464
- 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})`
4465
3657
  );
4466
3658
  }
3659
+ _isDashboard(appName) {
3660
+ return appName === DASHBOARD_APP_NAME;
3661
+ }
3662
+ _wait() {
3663
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3664
+ }
4467
3665
  };
4468
3666
 
4469
- // src/connector/chains/zcash.ts
4470
- async function zcashGetFullViewingKey(ctx, sessionId, params) {
4471
- const signer = await _createZcashSigner(ctx, sessionId);
4472
- const path = normalizePath(params.path);
4473
- const mode = params.mode ?? "ufvk";
4474
- return runSignerCall(ctx, sessionId, async () => {
4475
- const result = await signer.getFullViewingKey(path, { mode });
4476
- if (result.mode === "ufvk") {
4477
- return { path: params.path, mode, ufvk: result.fullViewingKey };
4478
- }
4479
- return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
4480
- });
3667
+ // src/connector/chains/legacyChainCall.ts
3668
+ function isLegacyWrongAppError(err, _appName) {
3669
+ return isWrongAppError(err);
4481
3670
  }
4482
- async function zcashGetShieldedAddress(ctx, sessionId, params) {
4483
- const signer = await _createZcashSigner(ctx, sessionId);
4484
- const path = normalizePath(params.path);
4485
- return runSignerCall(ctx, sessionId, async () => {
4486
- const result = await signer.getShieldedAddress(path, {
4487
- 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 }
4488
3679
  });
4489
- return { address: result.address, path: params.path };
4490
- });
4491
- }
4492
- async function _createZcashSigner(ctx, sessionId) {
4493
- const dmk = await ctx.getOrCreateDmk();
4494
- const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4495
- const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4496
- return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
4497
- }
4498
-
4499
- // src/connector/chains/tron.ts
4500
- var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
4501
-
4502
- // src/signer/SignerTron.ts
4503
- var SignerTron = class {
4504
- // eslint-disable-next-line no-useless-constructor, no-empty-function
4505
- constructor(_sdk) {
4506
- this._sdk = _sdk;
4507
- }
4508
- /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4509
- async getAddress(derivationPath, options) {
4510
- const action = this._sdk.getAddress(derivationPath, options);
4511
- const result = await deviceActionToPromise(
4512
- action,
4513
- this.onInteraction,
4514
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4515
- 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
4516
3697
  );
4517
- 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;
4518
3746
  }
4519
- /** Sign a protobuf-encoded raw transaction. */
4520
- async signTransaction(derivationPath, transaction, options) {
4521
- const action = this._sdk.signTransaction(derivationPath, transaction, options);
4522
- return deviceActionToPromise(
4523
- action,
4524
- this.onInteraction,
4525
- INTERACTIVE_TIMEOUT_MS,
4526
- this.onRegisterCanceller
4527
- );
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;
4528
3761
  }
4529
- /** Sign a personal message (TIP-191). */
4530
- async signPersonalMessage(derivationPath, message, options) {
4531
- const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4532
- return deviceActionToPromise(
4533
- action,
4534
- this.onInteraction,
4535
- INTERACTIVE_TIMEOUT_MS,
4536
- this.onRegisterCanceller
4537
- );
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() {
4538
3776
  }
4539
3777
  };
4540
3778
 
4541
3779
  // src/connector/chains/tron.ts
4542
3780
  async function tronGetAddress(ctx, sessionId, params) {
4543
- const tronSigner = await _createTronSigner(ctx, sessionId);
4544
3781
  const path = normalizePath(params.path);
4545
- return runSignerCall(ctx, sessionId, async () => {
4546
- const result = await tronSigner.getAddress(path, {
4547
- checkOnDevice: params.showOnDevice ?? false
4548
- });
4549
- return { address: result.address, publicKey: result.publicKey, path: params.path };
4550
- });
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
+ );
4551
3798
  }
4552
3799
  async function tronSignTransaction(ctx, sessionId, params) {
4553
3800
  if (!params.rawTxHex) {
@@ -4556,30 +3803,42 @@ async function tronSignTransaction(ctx, sessionId, params) {
4556
3803
  { code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
4557
3804
  );
4558
3805
  }
4559
- const tronSigner = await _createTronSigner(ctx, sessionId);
4560
3806
  const path = normalizePath(params.path);
4561
- return runSignerCall(ctx, sessionId, async () => {
4562
- const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
4563
- return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
4564
- });
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
+ );
4565
3821
  }
4566
3822
  async function tronSignMessage(ctx, sessionId, params) {
4567
- const tronSigner = await _createTronSigner(ctx, sessionId);
4568
3823
  const path = normalizePath(params.path);
4569
- return runSignerCall(ctx, sessionId, async () => {
4570
- const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
4571
- return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
4572
- });
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
+ );
4573
3834
  }
4574
- async function _createTronSigner(ctx, sessionId) {
3835
+ async function _createTrx(ctx, sessionId) {
4575
3836
  const dmk = await ctx.getOrCreateDmk();
4576
- const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4577
- const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4578
- return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3837
+ return new import_hw_app_trx.default(new DmkTransport(dmk, sessionId));
4579
3838
  }
4580
3839
 
4581
3840
  // src/device-apps/customActions.ts
4582
- var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
3841
+ var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
4583
3842
  var import_rxjs = require("rxjs");
4584
3843
  var GetOsVersionDeviceAction = class {
4585
3844
  // eslint-disable-next-line no-useless-constructor, no-empty-function
@@ -4593,7 +3852,7 @@ var GetOsVersionDeviceAction = class {
4593
3852
  (async () => {
4594
3853
  try {
4595
3854
  subject.next({
4596
- status: import_device_management_kit2.DeviceActionStatus.Pending,
3855
+ status: import_device_management_kit3.DeviceActionStatus.Pending,
4597
3856
  intermediateValue: { requiredUserInteraction: "none" }
4598
3857
  });
4599
3858
  const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
@@ -4602,11 +3861,11 @@ var GetOsVersionDeviceAction = class {
4602
3861
  const errObj = result?.error;
4603
3862
  throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
4604
3863
  }
4605
- 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 });
4606
3865
  subject.complete();
4607
3866
  } catch (err) {
4608
3867
  if (cancelled) return;
4609
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
3868
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Error, error: err });
4610
3869
  subject.complete();
4611
3870
  }
4612
3871
  })();
@@ -4614,7 +3873,7 @@ var GetOsVersionDeviceAction = class {
4614
3873
  observable: subject.asObservable(),
4615
3874
  cancel: () => {
4616
3875
  cancelled = true;
4617
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
3876
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Stopped });
4618
3877
  subject.complete();
4619
3878
  }
4620
3879
  };
@@ -4632,7 +3891,7 @@ var ListAvailableAppsDeviceAction = class {
4632
3891
  (async () => {
4633
3892
  try {
4634
3893
  subject.next({
4635
- status: import_device_management_kit2.DeviceActionStatus.Pending,
3894
+ status: import_device_management_kit3.DeviceActionStatus.Pending,
4636
3895
  intermediateValue: { requiredUserInteraction: "none" }
4637
3896
  });
4638
3897
  const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
@@ -4649,11 +3908,11 @@ var ListAvailableAppsDeviceAction = class {
4649
3908
  throw new Error(httpErr?.message ?? "Manager API getAppList failed");
4650
3909
  }
4651
3910
  const apps = either.extract();
4652
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
3911
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Completed, output: apps });
4653
3912
  subject.complete();
4654
3913
  } catch (err) {
4655
3914
  if (cancelled) return;
4656
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
3915
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Error, error: err });
4657
3916
  subject.complete();
4658
3917
  }
4659
3918
  })();
@@ -4661,7 +3920,7 @@ var ListAvailableAppsDeviceAction = class {
4661
3920
  observable: subject.asObservable(),
4662
3921
  cancel: () => {
4663
3922
  cancelled = true;
4664
- subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
3923
+ subject.next({ status: import_device_management_kit3.DeviceActionStatus.Stopped });
4665
3924
  subject.complete();
4666
3925
  }
4667
3926
  };
@@ -4754,7 +4013,7 @@ var DeviceApps = class {
4754
4013
  seTargetId: v.seTargetId,
4755
4014
  mcuTargetId: v.mcuTargetId,
4756
4015
  seVersion: v.seVersion,
4757
- seFlagsHex: bytesToHex4(v.seFlags),
4016
+ seFlagsHex: bytesToHex2(v.seFlags),
4758
4017
  mcuSephVersion: v.mcuSephVersion,
4759
4018
  mcuBootloaderVersion: v.mcuBootloaderVersion,
4760
4019
  hwVersion: v.hwVersion
@@ -4828,7 +4087,7 @@ var DeviceApps = class {
4828
4087
  }
4829
4088
  }
4830
4089
  };
4831
- function bytesToHex4(bytes) {
4090
+ function bytesToHex2(bytes) {
4832
4091
  if (!bytes) return "";
4833
4092
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4834
4093
  }
@@ -4871,8 +4130,7 @@ var METHOD_PREFIX_TO_APP_NAME = {
4871
4130
  evm: "Ethereum",
4872
4131
  btc: "Bitcoin",
4873
4132
  sol: "Solana",
4874
- tron: "Tron",
4875
- zcash: "Zcash"
4133
+ tron: "Tron"
4876
4134
  };
4877
4135
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4878
4136
  Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
@@ -4912,10 +4170,6 @@ async function defaultLedgerKitImporter(pkg) {
4912
4170
  return import("@ledgerhq/device-signer-kit-bitcoin");
4913
4171
  case "@ledgerhq/device-signer-kit-solana":
4914
4172
  return import("@ledgerhq/device-signer-kit-solana");
4915
- case "@ledgerhq/device-signer-kit-tron":
4916
- return import("@ledgerhq/device-signer-kit-tron");
4917
- case "@ledgerhq/device-signer-kit-zcash":
4918
- return import("@ledgerhq/device-signer-kit-zcash");
4919
4173
  case "@ledgerhq/context-module":
4920
4174
  return import("@ledgerhq/context-module");
4921
4175
  default:
@@ -4975,7 +4229,6 @@ var LedgerConnectorBase = class {
4975
4229
  this._ctx = {
4976
4230
  emit: (event, data) => this._emit(event, data),
4977
4231
  invalidateSession: (sid) => this._invalidateSession(sid),
4978
- teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4979
4232
  wrapError: (err, opts) => this._wrapError(err, opts),
4980
4233
  getOrCreateDmk: () => this._getOrCreateDmk(),
4981
4234
  getDeviceManager: () => this._getDeviceManager(),
@@ -5165,7 +4418,7 @@ var LedgerConnectorBase = class {
5165
4418
  this._resetSignersAndSessions();
5166
4419
  if (isLedgerBleConnectionType(this.connectionType)) {
5167
4420
  const tag = err?._tag;
5168
- if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4421
+ if (isKnownConnectionTag(tag)) {
5169
4422
  throw err;
5170
4423
  }
5171
4424
  const wrapped = new Error(
@@ -5266,7 +4519,7 @@ var LedgerConnectorBase = class {
5266
4519
  // whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
5267
4520
  // locally (see LedgerAdapter._unwrapConnectorResult).
5268
4521
  async call(sessionId, method, params) {
5269
- debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
4522
+ debugLog("[DMK] call:", method, JSON.stringify(params));
5270
4523
  try {
5271
4524
  const payload = await this._dispatch(sessionId, method, params);
5272
4525
  return { success: true, payload };
@@ -5334,11 +4587,6 @@ var LedgerConnectorBase = class {
5334
4587
  return solSignTransaction(ctx, sessionId, params);
5335
4588
  case "solSignMessage":
5336
4589
  return solSignMessage(ctx, sessionId, params);
5337
- // ZCASH
5338
- case "zcashGetFullViewingKey":
5339
- return zcashGetFullViewingKey(ctx, sessionId, params);
5340
- case "zcashGetShieldedAddress":
5341
- return zcashGetShieldedAddress(ctx, sessionId, params);
5342
4590
  // TRON
5343
4591
  case "tronGetAddress":
5344
4592
  return tronGetAddress(ctx, sessionId, params);
@@ -5372,7 +4620,7 @@ var LedgerConnectorBase = class {
5372
4620
  });
5373
4621
  });
5374
4622
  } catch (err) {
5375
- ctx.teardownSecureChannelSession(sessionId);
4623
+ ctx.invalidateSession(sessionId);
5376
4624
  throw ctx.wrapError(err);
5377
4625
  } finally {
5378
4626
  ctx.clearCanceller(sessionId);
@@ -5462,7 +4710,7 @@ var LedgerConnectorBase = class {
5462
4710
  );
5463
4711
  return { isGenuine: output.isGenuine, deviceId };
5464
4712
  } catch (err) {
5465
- ctx.teardownSecureChannelSession(sessionId);
4713
+ ctx.invalidateSession(sessionId);
5466
4714
  throw ctx.wrapError(err);
5467
4715
  } finally {
5468
4716
  ctx.clearCanceller(sessionId);
@@ -5584,17 +4832,6 @@ var LedgerConnectorBase = class {
5584
4832
  _invalidateSession(sessionId) {
5585
4833
  this._signerManager?.invalidate(sessionId);
5586
4834
  }
5587
- _teardownSecureChannelSession(sessionId) {
5588
- const cancel = this._cancellers.get(sessionId);
5589
- this._cancellers.delete(sessionId);
5590
- if (cancel) {
5591
- try {
5592
- cancel();
5593
- } catch {
5594
- }
5595
- }
5596
- this._invalidateSession(sessionId);
5597
- }
5598
4835
  /**
5599
4836
  * Replace an old session with a new one after app switch.
5600
4837
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -5679,7 +4916,7 @@ var LedgerConnectorBase = class {
5679
4916
  * at every catch site. Falls through unchanged for unknown methods.
5680
4917
  */
5681
4918
  _ctxForMethod(method) {
5682
- const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4919
+ const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5683
4920
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
5684
4921
  if (!defaultAppName) return this._ctx;
5685
4922
  return {
@@ -5713,204 +4950,6 @@ var LedgerConnectorBase = class {
5713
4950
  return error;
5714
4951
  }
5715
4952
  };
5716
-
5717
- // src/transport/DmkTransport.ts
5718
- var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
5719
- var DmkTransport = class extends import_hw_transport.default {
5720
- constructor(dmk, sessionId) {
5721
- super();
5722
- this._dmk = dmk;
5723
- this._sessionId = sessionId;
5724
- }
5725
- async exchange(apdu) {
5726
- const response = await this._dmk.sendApdu({
5727
- sessionId: this._sessionId,
5728
- apdu: new Uint8Array(apdu)
5729
- });
5730
- const { data, statusCode } = response;
5731
- const result = Buffer.alloc(data.length + 2);
5732
- if (data.length > 0) {
5733
- result.set(data, 0);
5734
- }
5735
- result.set(statusCode, data.length);
5736
- return result;
5737
- }
5738
- async close() {
5739
- }
5740
- };
5741
-
5742
- // src/app/AppManager.ts
5743
- var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
5744
- var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
5745
- var APP_NAME_MAP = {
5746
- ETH: "Ethereum",
5747
- BTC: "Bitcoin",
5748
- SOL: "Solana",
5749
- TRX: "Tron",
5750
- ZEC: "Zcash",
5751
- XRP: "XRP",
5752
- ADA: "Cardano",
5753
- DOT: "Polkadot",
5754
- ATOM: "Cosmos"
5755
- };
5756
- var DASHBOARD_APP_NAME = "BOLOS";
5757
- var AppManager = class {
5758
- constructor(dmk, options) {
5759
- this._dmk = dmk;
5760
- this._waitMs = options?.waitMs ?? 1e3;
5761
- this._maxRetries = options?.maxRetries ?? 10;
5762
- }
5763
- /**
5764
- * Return the Ledger app name for a given chain ticker,
5765
- * or undefined if the chain is not supported.
5766
- */
5767
- static getAppName(chain) {
5768
- return APP_NAME_MAP[chain];
5769
- }
5770
- /**
5771
- * Ensure the target app is open on the device identified by `sessionId`.
5772
- *
5773
- * Flow:
5774
- * 1. Check the currently running app.
5775
- * 2. If it is already the target, return immediately.
5776
- * 3. If a different app is running (not dashboard), close it first.
5777
- * 4. Open the target app.
5778
- * 5. Poll until the device confirms the target app is running.
5779
- */
5780
- /**
5781
- * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5782
- * device is about to display "Open <app>" on screen and wait for the
5783
- * user's button press. UI consumers should show their "open app" prompt
5784
- * in response. NOT called when the target app is already open (no user
5785
- * interaction needed in that case).
5786
- *
5787
- * Important: OpenAppCommand is blocking. It does not resolve until the user
5788
- * has physically confirmed on the device, so anything that runs AFTER
5789
- * `await this._openApp(...)` lands AFTER the prompt is already gone.
5790
- * Hence the callback must fire BEFORE that await.
5791
- */
5792
- async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5793
- const currentApp = await this._getCurrentApp(sessionId);
5794
- if (currentApp === targetAppName) {
5795
- return;
5796
- }
5797
- if (!this._isDashboard(currentApp)) {
5798
- await this._closeCurrentApp(sessionId);
5799
- await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5800
- }
5801
- onConfirmOnDevice?.();
5802
- await this._openApp(sessionId, targetAppName);
5803
- await this._waitForApp(sessionId, targetAppName);
5804
- }
5805
- // ---------------------------------------------------------------------------
5806
- // Private helpers
5807
- // ---------------------------------------------------------------------------
5808
- async _getCurrentApp(sessionId) {
5809
- const result = await this._dmk.sendCommand({
5810
- sessionId,
5811
- command: new import_device_management_kit3.GetAppAndVersionCommand()
5812
- });
5813
- if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
5814
- debugLog("[AppManager] currentApp:", result.data.name);
5815
- return result.data.name;
5816
- }
5817
- const errResult = result;
5818
- const dmkErr = errResult.error ?? {};
5819
- const original = dmkErr.originalError;
5820
- debugLog(
5821
- "[AppManager] _getCurrentApp failed sessionId=",
5822
- sessionId,
5823
- "tag=",
5824
- dmkErr._tag,
5825
- "errorCode=",
5826
- dmkErr.errorCode,
5827
- "message=",
5828
- dmkErr.message,
5829
- "originalErrorMessage=",
5830
- original?.message ?? String(original ?? "")
5831
- );
5832
- throw Object.assign(
5833
- new Error(
5834
- dmkErr.message ?? "Failed to get current app from device"
5835
- ),
5836
- {
5837
- _tag: dmkErr._tag,
5838
- errorCode: dmkErr.errorCode,
5839
- originalError: original
5840
- }
5841
- );
5842
- }
5843
- async _openApp(sessionId, appName) {
5844
- const result = await this._dmk.sendCommand({
5845
- sessionId,
5846
- command: new import_device_management_kit3.OpenAppCommand({ appName })
5847
- });
5848
- if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
5849
- const dmkErr = result.error;
5850
- const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5851
- const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5852
- debugLog(
5853
- "[AppManager] openApp failed:",
5854
- appName,
5855
- "errorCode:",
5856
- errorCode,
5857
- "tag:",
5858
- dmkErr._tag
5859
- );
5860
- let code;
5861
- if (errorCode === "6807" || /unknown application/i.test(message)) {
5862
- code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
5863
- } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5864
- code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
5865
- }
5866
- throw Object.assign(new Error(`Failed to open "${appName}"`), {
5867
- _tag: ERROR_TAG.OpenAppCommand,
5868
- code,
5869
- errorCode,
5870
- statusCode: errorCode,
5871
- appName,
5872
- originalError: dmkErr
5873
- });
5874
- }
5875
- }
5876
- async _closeCurrentApp(sessionId) {
5877
- debugLog("[AppManager] closeCurrentApp");
5878
- await this._dmk.sendCommand({
5879
- sessionId,
5880
- command: new import_device_management_kit3.CloseAppCommand()
5881
- });
5882
- }
5883
- /**
5884
- * Poll the device until the expected app is reported as running,
5885
- * or throw after `_maxRetries` attempts.
5886
- */
5887
- async _waitForApp(sessionId, expectedAppName) {
5888
- let lastSeen = "";
5889
- for (let i = 0; i < this._maxRetries; i++) {
5890
- await this._wait();
5891
- const current = await this._getCurrentApp(sessionId);
5892
- lastSeen = current;
5893
- if (current === expectedAppName) {
5894
- return;
5895
- }
5896
- }
5897
- debugLog(
5898
- "[AppManager] waitForApp exhausted: expected=",
5899
- expectedAppName,
5900
- "lastSeen=",
5901
- lastSeen
5902
- );
5903
- throw new Error(
5904
- `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
5905
- );
5906
- }
5907
- _isDashboard(appName) {
5908
- return appName === DASHBOARD_APP_NAME;
5909
- }
5910
- _wait() {
5911
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
5912
- }
5913
- };
5914
4953
  // Annotate the CommonJS export names for ESM import in node:
5915
4954
  0 && (module.exports = {
5916
4955
  AppManager,
@@ -5922,7 +4961,6 @@ var AppManager = class {
5922
4961
  SignerEth,
5923
4962
  SignerManager,
5924
4963
  SignerSol,
5925
- SignerZcash,
5926
4964
  debugLog,
5927
4965
  deviceActionToPromise,
5928
4966
  isDeviceLockedError,