@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.11 → 1.2.8-alpha.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -6,30 +6,43 @@ import {
6
6
  DeviceJobQueue,
7
7
  EConnectorInteraction,
8
8
  HardwareErrorCode as HardwareErrorCode3,
9
+ OperationRegistry,
10
+ SDK,
9
11
  TypedEventEmitter,
10
12
  UI_REQUEST,
11
13
  UI_REQUEST_PREEMPTED_TAG,
12
14
  UiRequestRegistry,
15
+ canReplayHardwareMethodAfterTransportFailure,
13
16
  createHwkError,
14
17
  deriveDeviceFingerprint,
18
+ emitDeviceBindingStatus,
15
19
  failure as failure2,
20
+ isHardwareOperationId,
21
+ isHwkRecoveryHint,
22
+ operationMayHaveCompletedParams,
23
+ pickConnectionContext,
16
24
  rehydrateConnectorError,
17
- success
25
+ requestBleDeviceSelection,
26
+ requestSaveDeviceBinding,
27
+ success as success2,
28
+ toPhysicalDeviceSearchTarget
18
29
  } from "@onekeyfe/hwk-adapter-core";
19
30
 
20
31
  // src/errors.ts
21
- import { HardwareErrorCode, enrichErrorMessage } from "@onekeyfe/hwk-adapter-core";
22
- var MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE = "Multiple Ledger USB devices are connected. Please connect only one Ledger device and try again.";
23
- function createMultipleUsbLedgerDevicesError() {
24
- return Object.assign(new Error(MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE), {
25
- code: HardwareErrorCode.DeviceOneDeviceOnly
26
- });
27
- }
28
- function ledgerFailure(code, error, appName, tag, params) {
32
+ import {
33
+ HardwareErrorCode,
34
+ defaultOriginForCode,
35
+ defaultRecoveryForCode,
36
+ enrichErrorMessage
37
+ } from "@onekeyfe/hwk-adapter-core";
38
+ function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
29
39
  const payload = { error, code };
30
40
  if (appName !== void 0) payload.appName = appName;
31
41
  if (tag !== void 0) payload._tag = tag;
32
42
  if (params !== void 0) payload.params = params;
43
+ const resolvedOrigin = origin ?? defaultOriginForCode(code);
44
+ if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
45
+ payload.recovery = recovery ?? defaultRecoveryForCode(code);
33
46
  return { success: false, payload };
34
47
  }
35
48
  var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
@@ -170,7 +183,10 @@ var ERROR_TAG = {
170
183
  UnknownDevice: "UnknownDeviceError",
171
184
  DeviceSessionRefresher: "DeviceSessionRefresherError",
172
185
  DeviceNotInitialized: "DeviceNotInitializedError",
173
- OpeningConnection: "OpeningConnectionError",
186
+ // DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
187
+ // spellings are kept so a DMK release that aligns them still classifies.
188
+ OpeningConnection: "ConnectionOpeningError",
189
+ OpeningConnectionLegacy: "OpeningConnectionError",
174
190
  DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
175
191
  DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
176
192
  Disconnect: "DisconnectError",
@@ -180,10 +196,20 @@ var ERROR_TAG = {
180
196
  // outcome when the user doesn't confirm pairing on the device, or the
181
197
  // existing bond is invalid. Observed in production after ~30s.
182
198
  PairingRefused: "PairingRefusedError",
199
+ PeerRemovedPairing: "PeerRemovedPairingError",
183
200
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
184
201
  WebSocketConnection: "WebSocketConnectionError",
185
202
  HttpFetch: "FetchError",
186
- InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError"
203
+ NetworkDA: "NetworkDAError",
204
+ InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
205
+ ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
206
+ // DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
207
+ // after splitting out device answers, i.e. the relay itself broke.
208
+ SecureChannel: "SecureChannelError",
209
+ RefusedByUserDA: "RefusedByUserDAError",
210
+ AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
211
+ OutOfMemoryDA: "OutOfMemoryDAError",
212
+ DeviceNotOnboarded: "DeviceNotOnboardedError"
187
213
  };
188
214
  function isDeviceLockedError(err) {
189
215
  if (!err || typeof err !== "object") return false;
@@ -199,6 +225,27 @@ function isDeviceNotAdvertisingError(err) {
199
225
  if (!err || typeof err !== "object") return false;
200
226
  return err._tag === ERROR_TAG.DeviceNotAdvertising;
201
227
  }
228
+ function isBleBondInvalidError(err) {
229
+ const pending = [err];
230
+ const seen = /* @__PURE__ */ new Set();
231
+ while (pending.length > 0) {
232
+ const candidate = pending.pop();
233
+ if (candidate && typeof candidate === "object" && !seen.has(candidate)) {
234
+ seen.add(candidate);
235
+ const e = candidate;
236
+ if (e._tag === ERROR_TAG.PeerRemovedPairing || e.iosErrorCode === 14 || e.attErrorCode === 5 || e.nativeErrorDomain === "CBErrorDomain" && e.nativeErrorCode === 14) {
237
+ return true;
238
+ }
239
+ const reason = typeof e.reason === "string" ? e.reason : "";
240
+ const message = typeof e.message === "string" ? e.message : "";
241
+ if (/\bCBErrorDomain:14(?:\s|$)/.test(message) || reason.includes("Peer removed pairing information") || reason.includes("GATT_INSUF_AUTHENTICATION")) {
242
+ return true;
243
+ }
244
+ pending.push(e.originalError, e.err);
245
+ }
246
+ }
247
+ return false;
248
+ }
202
249
  var PAIRING_FAILURE_TAGS = /* @__PURE__ */ new Set([
203
250
  ERROR_TAG.BlePairingTimeout,
204
251
  ERROR_TAG.BleGattBondingFailed,
@@ -213,11 +260,11 @@ function isBlePairingFailureError(err) {
213
260
  return false;
214
261
  }
215
262
  var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
216
- ERROR_TAG.DeviceLocked,
217
263
  ERROR_TAG.DeviceNotAdvertising,
218
264
  ERROR_TAG.BlePairingTimeout,
219
265
  ERROR_TAG.BleGattBondingFailed,
220
266
  ERROR_TAG.PairingRefused,
267
+ ERROR_TAG.PeerRemovedPairing,
221
268
  ERROR_TAG.DeviceNotRecognized,
222
269
  ERROR_TAG.NoAccessibleDevice,
223
270
  ERROR_TAG.UnknownDevice,
@@ -225,6 +272,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
225
272
  ERROR_TAG.DeviceSessionRefresher,
226
273
  ERROR_TAG.DeviceNotInitialized,
227
274
  ERROR_TAG.OpeningConnection,
275
+ ERROR_TAG.OpeningConnectionLegacy,
228
276
  ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
229
277
  ERROR_TAG.DeviceDisconnectedWhileSending,
230
278
  ERROR_TAG.Disconnect,
@@ -239,7 +287,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
239
287
  // Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
240
288
  ERROR_TAG.DeviceNotInDiscoveryCache
241
289
  ]);
242
- var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OpeningConnection]);
290
+ var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
291
+ ERROR_TAG.OpeningConnection,
292
+ ERROR_TAG.OpeningConnectionLegacy
293
+ ]);
243
294
  var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
244
295
  ERROR_TAG.DeviceNotRecognized,
245
296
  ERROR_TAG.DeviceSessionNotFound,
@@ -251,17 +302,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
251
302
  ERROR_TAG.WebHIDDisconnect
252
303
  ]);
253
304
  function isConnectionLevelError(err) {
254
- if (!err || typeof err !== "object") return false;
255
- const tag = err._tag;
256
- if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
257
- const e = err;
258
- if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
259
- if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
260
- return false;
305
+ return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
261
306
  }
262
307
  function isKnownConnectionTag(tag) {
263
308
  return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
264
309
  }
310
+ var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
311
+ ERROR_TAG.OpeningConnection,
312
+ ERROR_TAG.OpeningConnectionLegacy
313
+ ]);
314
+ function isConnectionOpeningTag(tag) {
315
+ return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
316
+ }
265
317
  function hasStatusCode(err, codeSet) {
266
318
  if (!err || typeof err !== "object") return false;
267
319
  const e = err;
@@ -297,28 +349,28 @@ function hasInvalidArgumentCode(err) {
297
349
  if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
298
350
  return false;
299
351
  }
300
- function isDeviceNotFoundError(err) {
352
+ function hasErrorTag(err, tags) {
301
353
  if (!err || typeof err !== "object") return false;
302
- const tag = err._tag;
303
- if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
304
354
  const e = err;
305
- if (e.originalError != null && isDeviceNotFoundError(e.originalError)) return true;
306
- if (e.error != null && e._tag && isDeviceNotFoundError(e.error)) return true;
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;
307
358
  return false;
308
359
  }
360
+ function isDeviceNotFoundError(err) {
361
+ return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
362
+ }
309
363
  function isDeviceBusyError(err) {
310
- if (!err || typeof err !== "object") return false;
311
- const tag = err._tag;
312
- if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
313
- const e = err;
314
- if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
315
- if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
316
- return false;
364
+ return hasErrorTag(err, DEVICE_BUSY_TAGS);
317
365
  }
366
+ var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
367
+ ERROR_TAG.UserRefusedOnDevice,
368
+ ERROR_TAG.RefusedByUserDA
369
+ ]);
318
370
  function isUserRejectedError(err) {
319
371
  if (!err || typeof err !== "object") return false;
320
372
  const e = err;
321
- if (e._tag === ERROR_TAG.UserRefusedOnDevice) return true;
373
+ if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
322
374
  if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
323
375
  if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
324
376
  return false;
@@ -349,15 +401,33 @@ function isAppNotInstalledError(err) {
349
401
  if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
350
402
  return false;
351
403
  }
404
+ var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
352
405
  function isOutOfMemoryError(err) {
353
- if (!err || typeof err !== "object") return false;
354
- const e = err;
355
- return e._tag === "OutOfMemoryDAError";
406
+ return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
407
+ }
408
+ var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
409
+ function isAppAlreadyInstalledError(err) {
410
+ return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
411
+ }
412
+ var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
413
+ function isDeviceNotOnboardedError(err) {
414
+ return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
415
+ }
416
+ var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
417
+ ERROR_TAG.InvalidFirmwareMetadataResponse,
418
+ ERROR_TAG.ApplicationsMetadataTask
419
+ ]);
420
+ function isFirmwareMetadataError(err) {
421
+ return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
422
+ }
423
+ var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
424
+ function isSecureChannelError(err) {
425
+ return hasErrorTag(err, SECURE_CHANNEL_TAGS);
356
426
  }
357
427
  var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
358
428
  ERROR_TAG.WebSocketConnection,
359
429
  ERROR_TAG.HttpFetch,
360
- ERROR_TAG.InvalidFirmwareMetadataResponse
430
+ ERROR_TAG.NetworkDA
361
431
  ]);
362
432
  function isNetworkError(err) {
363
433
  if (!err || typeof err !== "object") return false;
@@ -407,23 +477,36 @@ function isTransportStuck(err) {
407
477
  function isStuckAppStateError(err) {
408
478
  return isAppStuckByApdu(err) || isTransportStuck(err);
409
479
  }
480
+ var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
481
+ function nestedErrorMessage(nested) {
482
+ if (!nested || typeof nested !== "object") return void 0;
483
+ const { message } = nested;
484
+ if (typeof message !== "string") return void 0;
485
+ const trimmed = message.trim();
486
+ if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
487
+ return message;
488
+ }
410
489
  function mapLedgerError(err, opts) {
411
490
  let originalMessage = "Unknown Ledger error";
412
491
  if (err instanceof Error) {
413
492
  originalMessage = err.message;
414
493
  } else if (err && typeof err === "object") {
415
494
  const e = err;
416
- originalMessage = String(e.message ?? e._tag ?? e.type ?? JSON.stringify(err));
495
+ originalMessage = String(
496
+ e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
497
+ );
417
498
  }
418
499
  let code;
419
500
  if (isDeviceLockedError(err)) {
420
501
  code = HardwareErrorCode.DeviceLocked;
421
502
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
422
503
  code = HardwareErrorCode.DeviceNotFound;
423
- } else if (isDeviceBusyError(err)) {
424
- code = HardwareErrorCode.DeviceBusy;
504
+ } else if (isBleBondInvalidError(err)) {
505
+ code = HardwareErrorCode.BleBondInvalid;
425
506
  } else if (isBlePairingFailureError(err)) {
426
507
  code = HardwareErrorCode.BlePairingTimeout;
508
+ } else if (isDeviceBusyError(err)) {
509
+ code = HardwareErrorCode.DeviceBusy;
427
510
  } else if (isUserAbortedError(err)) {
428
511
  code = HardwareErrorCode.UserAborted;
429
512
  } else if (isUserRejectedError(err)) {
@@ -432,10 +515,18 @@ function mapLedgerError(err, opts) {
432
515
  code = HardwareErrorCode.WrongApp;
433
516
  } else if (isAppNotInstalledError(err)) {
434
517
  code = HardwareErrorCode.AppNotInstalled;
518
+ } else if (isAppAlreadyInstalledError(err)) {
519
+ code = HardwareErrorCode.AppAlreadyInstalled;
435
520
  } else if (isOutOfMemoryError(err)) {
436
521
  code = HardwareErrorCode.DeviceOutOfMemory;
522
+ } else if (isDeviceNotOnboardedError(err)) {
523
+ code = HardwareErrorCode.DeviceNotInitialized;
524
+ } else if (isFirmwareMetadataError(err)) {
525
+ code = HardwareErrorCode.LedgerFirmwareMetadataError;
437
526
  } else if (isNetworkError(err)) {
438
527
  code = HardwareErrorCode.NetworkError;
528
+ } else if (isSecureChannelError(err)) {
529
+ code = HardwareErrorCode.LedgerSecureChannelError;
439
530
  } else if (isDeviceDisconnectedError(err)) {
440
531
  code = HardwareErrorCode.DeviceDisconnected;
441
532
  } else if (isTimeoutError(err)) {
@@ -448,11 +539,35 @@ function mapLedgerError(err, opts) {
448
539
  }
449
540
  const errAppName = err && typeof err === "object" ? err.appName : void 0;
450
541
  const appName = errAppName ?? opts?.defaultAppName;
451
- return { code, message: enrichErrorMessage(code, originalMessage), appName };
542
+ return {
543
+ code,
544
+ message: enrichErrorMessage(code, originalMessage),
545
+ origin: defaultOriginForCode(code),
546
+ appName
547
+ };
548
+ }
549
+
550
+ // src/utils/queueKey.ts
551
+ var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
552
+ function ledgerQueueKey({
553
+ operationId,
554
+ connectId
555
+ }) {
556
+ return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
452
557
  }
453
558
 
454
559
  // src/adapter/methods/allNetworkGetAddress.ts
455
- import { HardwareErrorCode as HardwareErrorCode2, failure, runAllNetworkGetAddress } from "@onekeyfe/hwk-adapter-core";
560
+ import {
561
+ HardwareErrorCode as HardwareErrorCode2,
562
+ buildAllNetworkCancelledFailure,
563
+ failure,
564
+ isConnectionLost,
565
+ isUserRefusal,
566
+ isWalletSafetyFailure,
567
+ resolveHardwareOperationTarget,
568
+ runAllNetworkGetAddress,
569
+ success
570
+ } from "@onekeyfe/hwk-adapter-core";
456
571
 
457
572
  // src/utils/sdkEventBus.ts
458
573
  var listeners = /* @__PURE__ */ new Set();
@@ -499,6 +614,32 @@ function debugError(...args) {
499
614
  emitLog("error", ...args);
500
615
  }
501
616
 
617
+ // src/utils/logSummary.ts
618
+ import { summarizeForLog as summarizeForLogCore } from "@onekeyfe/hwk-adapter-core";
619
+ import { Psbt, Transaction } from "bitcoinjs-lib";
620
+ var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
621
+ var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
622
+ function parsePsbt(input) {
623
+ if (typeof input !== "string") return Psbt.fromBuffer(input);
624
+ if (HEX_RE.test(input)) return Psbt.fromHex(input.replace(/^0x/i, ""));
625
+ if (BASE64_RE.test(input)) return Psbt.fromBase64(input);
626
+ return void 0;
627
+ }
628
+ var describePsbtForLog = (key, value) => {
629
+ if (key !== "psbt") return void 0;
630
+ try {
631
+ const psbt = parsePsbt(value);
632
+ if (!psbt) return void 0;
633
+ const unsignedTx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
634
+ return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
635
+ } catch {
636
+ return void 0;
637
+ }
638
+ };
639
+ function summarizeForLog(value, options = {}) {
640
+ return summarizeForLogCore(value, { ...options, describePayload: describePsbtForLog });
641
+ }
642
+
502
643
  // src/adapter/methods/allNetworkGetAddress.ts
503
644
  var LEDGER_BTC_NETWORK_COIN_MAP = {
504
645
  tbtc: "Testnet",
@@ -509,57 +650,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
509
650
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
510
651
  function createAllNetworkGetAddress({
511
652
  callChain,
512
- getChainFingerprint
653
+ getChainFingerprint,
654
+ retainOperation,
655
+ errorToFailure,
656
+ createCancelScope,
657
+ releaseBundle
513
658
  }) {
514
659
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
515
- debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
516
- const installContext = {};
660
+ debugLog("[LedgerAdapter][REQ]", {
661
+ method: "allNetworkGetAddress",
662
+ connectId,
663
+ itemCount: params.bundle.length
664
+ });
665
+ const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
666
+ if (!target.success) return target;
667
+ const effectiveTargetId = target.payload.targetId ?? "";
668
+ let releaseOperationRetention;
669
+ try {
670
+ releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
671
+ } catch (error) {
672
+ return errorToFailure(error);
673
+ }
674
+ const cancelScope = createCancelScope(
675
+ ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
676
+ );
677
+ const installContext = {
678
+ walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
679
+ };
517
680
  const commonParams = {
518
- autoInstallApp: params.autoInstallApp
681
+ autoInstallApp: params.autoInstallApp,
682
+ operationId: target.payload.operationId,
683
+ knownConnections: params.knownConnections,
684
+ extra: params.extra,
685
+ allowDeviceSelection: params.allowDeviceSelection,
686
+ supportedTransports: params.supportedTransports
519
687
  };
520
688
  const chainFingerprints = /* @__PURE__ */ new Map();
521
- const result = await runAllNetworkGetAddress({
522
- connectId,
523
- deviceId: _deviceId,
524
- params,
525
- normalizeItem: normalizeLedgerAllNetworkItem,
526
- buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
527
- callItem: async ({ method, chain, item }) => {
528
- const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
529
- return callAllNetworkMethod(
530
- callChain,
531
- connectId,
532
- itemDeviceId,
533
- method,
689
+ const order = params.bundle.map((_item, index) => index).sort(
690
+ (a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
691
+ );
692
+ try {
693
+ const ordered = await runAllNetworkGetAddress({
694
+ connectId: effectiveTargetId,
695
+ deviceId: _deviceId,
696
+ params: { ...params, bundle: order.map((index) => params.bundle[index]) },
697
+ normalizeItem: normalizeLedgerAllNetworkItem,
698
+ buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
699
+ callItem: async ({ method, chain, item }) => {
700
+ if (cancelScope.signal.aborted)
701
+ return buildAllNetworkCancelledFailure(cancelScope.signal);
702
+ const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
703
+ return callAllNetworkMethod(
704
+ callChain,
705
+ effectiveTargetId,
706
+ itemDeviceId,
707
+ method,
708
+ item,
709
+ commonParams,
710
+ installContext
711
+ );
712
+ },
713
+ attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
714
+ getChainFingerprint,
715
+ effectiveTargetId,
534
716
  item,
535
- commonParams,
536
- installContext
537
- );
538
- },
539
- attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
540
- getChainFingerprint,
541
- connectId,
542
- item,
543
- chain,
544
- payload,
545
- chainFingerprints
546
- ),
547
- shouldAbortBundle: isTopLevelAllNetworkFailure,
548
- buildTopLevelFailure: (response) => {
549
- const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
550
- return failure(
551
- code,
552
- response.payload?.error ?? "All-network get-address aborted",
553
- response.payload?.params
554
- );
717
+ chain,
718
+ payload,
719
+ chainFingerprints,
720
+ installContext,
721
+ cancelScope.signal
722
+ ),
723
+ shouldAbortBundle: isTopLevelAllNetworkFailure,
724
+ buildTopLevelFailure: (response) => {
725
+ const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
726
+ return failure(
727
+ code,
728
+ response.payload?.error ?? "All-network get-address aborted",
729
+ response.payload?.params
730
+ );
731
+ }
732
+ });
733
+ let result = ordered;
734
+ if (ordered.success) {
735
+ const responses = [];
736
+ ordered.payload.forEach((response, position) => {
737
+ responses[order[position]] = response;
738
+ });
739
+ result = success(responses);
555
740
  }
556
- });
557
- debugLog("[LedgerAdapter][RES]", {
558
- method: "allNetworkGetAddress",
559
- success: result.success,
560
- payload: result
561
- });
562
- return result;
741
+ debugLog("[LedgerAdapter][RES]", {
742
+ method: "allNetworkGetAddress",
743
+ success: result.success,
744
+ payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
745
+ });
746
+ return result;
747
+ } finally {
748
+ await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
749
+ cancelScope.release();
750
+ releaseOperationRetention?.();
751
+ }
563
752
  };
564
753
  }
565
754
  function isTopLevelAllNetworkFailure(response) {
@@ -567,7 +756,7 @@ function isTopLevelAllNetworkFailure(response) {
567
756
  return false;
568
757
  }
569
758
  const code = response.payload?.code;
570
- return code === HardwareErrorCode2.DeviceMismatch || code === HardwareErrorCode2.UserAborted || code === HardwareErrorCode2.UserRejected;
759
+ return isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
571
760
  }
572
761
  function getItemDeviceId(item) {
573
762
  const { deviceId } = item;
@@ -597,8 +786,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
597
786
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
598
787
  return coin ? { ...item, coin } : item;
599
788
  }
600
- async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
601
- const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
789
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
790
+ const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
791
+ if (!knownFingerprint && cancelSignal.aborted) {
792
+ const cancelled = buildAllNetworkCancelledFailure(cancelSignal);
793
+ return { ...item, success: false, payload: cancelled.payload };
794
+ }
795
+ const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
796
+ getChainFingerprint,
797
+ context.connection?.connectId ?? connectId,
798
+ chain,
799
+ context
800
+ );
602
801
  if (!fingerprint) {
603
802
  return buildFingerprintBootstrapFailure(item, chain);
604
803
  }
@@ -619,8 +818,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
619
818
  }
620
819
  };
621
820
  }
622
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
623
- const response = await getChainFingerprint(connectId, chain);
821
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
822
+ const response = await getChainFingerprint(connectId, chain, context);
624
823
  return response.success ? response.payload : "";
625
824
  }
626
825
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -713,6 +912,9 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
713
912
  function formatDeviceMismatchError(expected, actual) {
714
913
  return `Wrong device: expected ${expected}, got ${actual}`;
715
914
  }
915
+ function isLostConnectionError(err) {
916
+ return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
917
+ }
716
918
  var BTC_HIGH_INDEX_THRESHOLD = 100;
717
919
  function btcAccountIndexFromPath(path) {
718
920
  const segments = path.replace(/^m\//, "").split("/");
@@ -724,9 +926,35 @@ function btcAccountIndexFromPath(path) {
724
926
  var _LedgerAdapter = class _LedgerAdapter {
725
927
  constructor(connector, options) {
726
928
  this.vendor = "ledger";
929
+ // Cancel frees the DMK action and its intent-queue slot, but cannot retract a
930
+ // confirmation screen the device is already showing.
931
+ this.cancelCapability = "stops-waiting";
727
932
  this.emitter = new TypedEventEmitter();
933
+ this._operations = new OperationRegistry({
934
+ vendor: "ledger",
935
+ onEnded: (operation, reason) => {
936
+ this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
937
+ this._pendingOperationBindings.delete(operation.operationId);
938
+ this.emitter.emit(SDK.OPERATION_ENDED, {
939
+ type: SDK.OPERATION_ENDED,
940
+ payload: { operationId: operation.operationId, reason }
941
+ });
942
+ if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
943
+ void this._releaseOperationConnection(operation);
944
+ }
945
+ }
946
+ });
728
947
  this._discoveredDevices = /* @__PURE__ */ new Map();
729
948
  this._sessions = /* @__PURE__ */ new Map();
949
+ // An operation's BLE pick is saved by its first call that gets past the wallet check.
950
+ this._pendingOperationBindings = /* @__PURE__ */ new Map();
951
+ // A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
952
+ // through an unlock retry; any other failure drops it with its session.
953
+ this._pendingPickBindings = /* @__PURE__ */ new Map();
954
+ // Transport each session was opened on, by sessionId. The adapter-wide
955
+ // `_activeConnectionType` moves with every discovery and can go stale.
956
+ this._sessionTransports = /* @__PURE__ */ new Map();
957
+ this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
730
958
  this._uiRegistry = new UiRequestRegistry();
731
959
  // BTC App rejects account index >= 100 unless display=true. Cached per
732
960
  // adapter instance: first 100+ path asks the user once via UI request,
@@ -740,21 +968,36 @@ var _LedgerAdapter = class _LedgerAdapter {
740
968
  this._deviceAuthenticityQueueTail = Promise.resolve();
741
969
  // Shared across concurrent callers — only `cancel()` aborts.
742
970
  this._doConnectAbortController = null;
971
+ this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
972
+ this._connectorIdleWaiters = /* @__PURE__ */ new Set();
973
+ this._resetPromise = null;
974
+ this._stateGeneration = 0;
975
+ this._connectorTeardownTail = Promise.resolve();
976
+ this._pendingConnectorTeardowns = 0;
977
+ this._activeOperationJobs = /* @__PURE__ */ new Set();
978
+ this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
743
979
  this._installProgressLastEmittedValue = -Infinity;
744
980
  this.allNetworkGetAddress = createAllNetworkGetAddress({
745
981
  callChain: this.callChain.bind(this),
746
- getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
982
+ getChainFingerprint: async (connectId, chain, context) => {
983
+ try {
984
+ const fingerprint = await this._computeChainFingerprint(
985
+ chain,
986
+ (method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
987
+ );
988
+ return success2(fingerprint);
989
+ } catch (error) {
990
+ return this.errorToFailure(error);
991
+ }
992
+ },
993
+ retainOperation: (operationId) => this._operations.retain(operationId),
994
+ errorToFailure: (error) => this.errorToFailure(error),
995
+ createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
996
+ releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
747
997
  });
748
998
  // ---------------------------------------------------------------------------
749
999
  // Private helpers
750
1000
  // ---------------------------------------------------------------------------
751
- /**
752
- * Ensure at least one device is connected and return a valid connectId.
753
- *
754
- * - If a session already exists for the given connectId, reuse it.
755
- * - If ANY session exists (Ledger IDs are ephemeral), reuse it.
756
- * - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
757
- */
758
1001
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
759
1002
  this._connectingPromise = null;
760
1003
  // ---------------------------------------------------------------------------
@@ -770,6 +1013,12 @@ var _LedgerAdapter = class _LedgerAdapter {
770
1013
  });
771
1014
  };
772
1015
  this.deviceDisconnectHandler = (data) => {
1016
+ const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
1017
+ if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
1018
+ this._pendingOperationDisconnects.add(activeOperation.operationId);
1019
+ } else {
1020
+ this._operations.endByConnectionKey(data.connectId, "disconnect");
1021
+ }
773
1022
  this._discoveredDevices.delete(data.connectId);
774
1023
  this._sessions.delete(data.connectId);
775
1024
  this.emitter.emit(DEVICE.DISCONNECT, {
@@ -778,10 +1027,8 @@ var _LedgerAdapter = class _LedgerAdapter {
778
1027
  });
779
1028
  };
780
1029
  // Forward connector `ui-event` to the public hw.emitter so consumers only
781
- // need to subscribe in one place. For the AppInstallProgress variant we
782
- // re-key sessionId → connectId via the live _sessions map; if no mapping
783
- // exists (race during teardown) we drop. All other variants pass through
784
- // unchanged.
1030
+ // need to subscribe in one place. The AppInstallProgress variant re-keys
1031
+ // sessionId to connectId via `_sessions`, and drops if no mapping exists.
785
1032
  this.uiEventForwarder = (event) => {
786
1033
  if (event.type === EConnectorInteraction.AppInstallProgress) {
787
1034
  let connectId;
@@ -826,11 +1073,30 @@ var _LedgerAdapter = class _LedgerAdapter {
826
1073
  this._jobQueue = new DeviceJobQueue();
827
1074
  this.registerEventListeners();
828
1075
  }
1076
+ _discardPendingBinding(owner, status = "cancelled") {
1077
+ const pending = owner?.pendingBinding;
1078
+ if (!owner || !pending) return;
1079
+ owner.pendingBinding = void 0;
1080
+ if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1081
+ }
1082
+ _finishBleBinding(status) {
1083
+ const selectionRequestId = this._bindingSelectionRequestId;
1084
+ this._bindingSelectionRequestId = void 0;
1085
+ if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
1086
+ }
1087
+ _isBleConnection() {
1088
+ return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1089
+ }
829
1090
  // Transport
830
1091
  get activeTransport() {
831
- return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1092
+ return this._isBleConnection() ? "ble" : "hid";
832
1093
  }
833
1094
  getAvailableTransports() {
1095
+ if (this.connector.availableTransports) {
1096
+ return this.connector.availableTransports.map(
1097
+ (transport) => transport === "ble" ? "ble" : "hid"
1098
+ );
1099
+ }
834
1100
  return this.activeTransport ? [this.activeTransport] : [];
835
1101
  }
836
1102
  // Connector is bound at construction; switching requires a new adapter.
@@ -847,21 +1113,43 @@ var _LedgerAdapter = class _LedgerAdapter {
847
1113
  * The next operation will re-discover and re-connect automatically.
848
1114
  */
849
1115
  resetState() {
1116
+ void this._resetStateAndDisconnectSessions();
1117
+ }
1118
+ _resetStateAndDisconnectSessions() {
1119
+ if (this._resetPromise) return this._resetPromise;
1120
+ const sessionIds = new Set(this._sessions.values());
1121
+ this._stateGeneration += 1;
1122
+ this._finishBleBinding("cancelled");
1123
+ this._operations.endAll("runtime-reset");
1124
+ this._doConnectAbortController?.abort();
850
1125
  this._discoveredDevices.clear();
851
1126
  this._sessions.clear();
1127
+ this._sessionTransports.clear();
1128
+ this._activeConnectionType = void 0;
1129
+ this._pendingOperationBindings.clear();
1130
+ this._pendingPickBindings.clear();
1131
+ this._selectedBleReconnectTargets.clear();
852
1132
  this._connectingPromise = null;
1133
+ this._doConnectAbortController = null;
853
1134
  this._uiRegistry.reset();
854
1135
  this._jobQueue.clear();
855
1136
  this._btcHighIndexConfirmedThisSession = false;
1137
+ const resetPromise = this._runConnectorTeardown(async () => {
1138
+ for (const sessionId of sessionIds) {
1139
+ await this.connector.disconnect(sessionId).catch(() => void 0);
1140
+ }
1141
+ });
1142
+ this._resetPromise = resetPromise;
1143
+ return resetPromise.finally(() => {
1144
+ if (this._resetPromise === resetPromise) {
1145
+ this._resetPromise = null;
1146
+ }
1147
+ });
856
1148
  }
857
1149
  async dispose() {
858
- this._uiRegistry.reset();
859
- this._jobQueue.clear();
1150
+ await this._resetStateAndDisconnectSessions();
860
1151
  this.unregisterEventListeners();
861
1152
  this.connector.reset();
862
- this._discoveredDevices.clear();
863
- this._sessions.clear();
864
- this._btcHighIndexConfirmedThisSession = false;
865
1153
  this.emitter.removeAllListeners();
866
1154
  }
867
1155
  uiResponse(response) {
@@ -871,17 +1159,32 @@ var _LedgerAdapter = class _LedgerAdapter {
871
1159
  // Device management
872
1160
  // ---------------------------------------------------------------------------
873
1161
  async searchDevices(options) {
1162
+ return this._searchDevices(options);
1163
+ }
1164
+ async _searchDevices(options, signal) {
874
1165
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
875
1166
  try {
876
1167
  if (options?.resetSession) {
877
- this._doConnectAbortController?.abort();
878
- this._sessions.clear();
879
- this._connectingPromise = null;
880
- this._doConnectAbortController = null;
881
- this._btcHighIndexConfirmedThisSession = false;
1168
+ await this._resetStateAndDisconnectSessions();
1169
+ } else {
1170
+ await this._connectorTeardownTail;
1171
+ }
1172
+ await this._ensureDevicePermission(void 0, void 0, signal);
1173
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1174
+ const stateGeneration = this._stateGeneration;
1175
+ const devices = await this.connector.searchDevices(
1176
+ options?.transportType ? {
1177
+ transportType: options.transportType,
1178
+ waitForAll: options.waitForAllTransports
1179
+ } : void 0
1180
+ );
1181
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1182
+ if (stateGeneration !== this._stateGeneration) {
1183
+ throw createHwkError({
1184
+ code: HardwareErrorCode3.UserAborted,
1185
+ message: "Ledger discovery was reset"
1186
+ });
882
1187
  }
883
- await this._ensureDevicePermission();
884
- const devices = await this.connector.searchDevices();
885
1188
  this._discoveredDevices.clear();
886
1189
  for (const d of devices) {
887
1190
  if (d.connectId) {
@@ -889,7 +1192,7 @@ var _LedgerAdapter = class _LedgerAdapter {
889
1192
  }
890
1193
  }
891
1194
  if (this._discoveredDevices.size === 0) {
892
- await this._ensureDevicePermission();
1195
+ await this._ensureDevicePermission(void 0, void 0, signal);
893
1196
  }
894
1197
  const result = Array.from(this._discoveredDevices.values());
895
1198
  debugLog("[LedgerAdapter][RES]", {
@@ -908,41 +1211,267 @@ var _LedgerAdapter = class _LedgerAdapter {
908
1211
  throw err;
909
1212
  }
910
1213
  }
1214
+ async searchDeviceTargets(options) {
1215
+ const devices = await this.searchDevices(options);
1216
+ return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
1217
+ }
911
1218
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
912
- async _evictAllSessions() {
1219
+ async _evictAllSessions(preserveOperationId) {
1220
+ this._operations.endAll("explicit", preserveOperationId);
913
1221
  if (this._sessions.size === 0) return;
914
1222
  const stale = [...this._sessions.values()];
915
1223
  this._sessions.clear();
916
- for (const sid of stale) {
917
- try {
918
- await this.connector.disconnect(sid);
919
- } catch {
1224
+ for (const sid of stale) this._sessionTransports.delete(sid);
1225
+ await this._runConnectorTeardown(async () => {
1226
+ for (const sid of stale) {
1227
+ try {
1228
+ await this.connector.disconnect(sid);
1229
+ } catch {
1230
+ }
920
1231
  }
921
- }
1232
+ });
922
1233
  }
923
1234
  static _createDeviceBusyError(method) {
924
1235
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
925
1236
  code: HardwareErrorCode3.DeviceBusy
926
1237
  });
927
1238
  }
928
- async connectDevice(connectId) {
1239
+ async connectDevice(searchTargetId) {
1240
+ try {
1241
+ return await this._jobQueue.enqueue(
1242
+ searchTargetId || "__ledger_connect__",
1243
+ async (signal) => {
1244
+ const connected = await this._connectTarget(searchTargetId, void 0, signal);
1245
+ if (!connected.success) return connected;
1246
+ return this._createOperation(searchTargetId, connected.payload);
1247
+ },
1248
+ {
1249
+ label: "connectDevice",
1250
+ rejectIfBusy: true,
1251
+ busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1252
+ }
1253
+ );
1254
+ } catch (error) {
1255
+ return this.errorToFailure(error);
1256
+ }
1257
+ }
1258
+ /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1259
+ async bindBleDevice(params) {
1260
+ const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1261
+ const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
1262
+ try {
1263
+ return await this._jobQueue.enqueue(
1264
+ "__ledger_bind_ble__",
1265
+ async (signal) => {
1266
+ if (!this.getAvailableTransports().includes("ble")) {
1267
+ throw createHwkError({
1268
+ code: HardwareErrorCode3.TransportNotAvailable,
1269
+ message: "Ledger Bluetooth transport is not available"
1270
+ });
1271
+ }
1272
+ this._activeConnectionType = "ble";
1273
+ await this._ensureDevicePermission(void 0, void 0, signal);
1274
+ const attempt = {
1275
+ extra: params.extra,
1276
+ bindingReason: "manual-rebind",
1277
+ deferBindingSave: Boolean(identity)
1278
+ };
1279
+ try {
1280
+ const connectId = await this._connectFirstOrSelect(
1281
+ [],
1282
+ void 0,
1283
+ true,
1284
+ void 0,
1285
+ attempt,
1286
+ signal
1287
+ );
1288
+ const pending = attempt.pendingBinding;
1289
+ if (identity && pending) {
1290
+ attempt.pendingBinding = void 0;
1291
+ const sessionId = this._sessions.get(connectId);
1292
+ if (!sessionId) {
1293
+ throw createHwkError({
1294
+ code: HardwareErrorCode3.DeviceDisconnected,
1295
+ message: "Selected Ledger connection ended"
1296
+ });
1297
+ }
1298
+ const checked = await this._fingerprintFirstOpenableChain(
1299
+ identities,
1300
+ (chain, autoInstallApp) => this._computeChainFingerprint(
1301
+ chain,
1302
+ (method, callParams) => this._runConnectorCall(
1303
+ connectId,
1304
+ method,
1305
+ callParams,
1306
+ signal,
1307
+ void 0,
1308
+ void 0,
1309
+ { autoInstallApp },
1310
+ { connection: { connectId, sessionId } }
1311
+ )
1312
+ )
1313
+ );
1314
+ if (checked.fingerprint !== checked.identity.value) {
1315
+ await this._dropSession(connectId, signal);
1316
+ throw createHwkError({
1317
+ code: HardwareErrorCode3.DeviceMismatch,
1318
+ message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
1319
+ });
1320
+ }
1321
+ await this._saveSelectedBleBinding(
1322
+ connectId,
1323
+ pending.requestId,
1324
+ attempt,
1325
+ void 0,
1326
+ signal,
1327
+ checked.identity
1328
+ );
1329
+ }
1330
+ if (!attempt.bindingSaved) {
1331
+ await this._dropSession(connectId, signal);
1332
+ throw createHwkError({
1333
+ code: HardwareErrorCode3.UnknownError,
1334
+ message: "Bluetooth binding could not be saved",
1335
+ origin: "host"
1336
+ });
1337
+ }
1338
+ return success2(connectId);
1339
+ } catch (error) {
1340
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1341
+ throw error;
1342
+ }
1343
+ },
1344
+ {
1345
+ label: "bindBleDevice",
1346
+ rejectIfBusy: true,
1347
+ busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1348
+ }
1349
+ );
1350
+ } catch (error) {
1351
+ return this.errorToFailure(error);
1352
+ }
1353
+ }
1354
+ async acquireOperation(connectId, context) {
1355
+ try {
1356
+ return await this._jobQueue.enqueue(
1357
+ connectId || "__ledger_acquire__",
1358
+ async (signal) => {
1359
+ const transport = this._isBleConnection() ? "ble" : "usb";
1360
+ const hint = context.knownConnections?.find(
1361
+ (connection) => connection.transport === transport
1362
+ );
1363
+ const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1364
+ await this._ensureDevicePermission(target, void 0, signal);
1365
+ const attempt = {
1366
+ ...context,
1367
+ extra: context.extra ? { ...context.extra } : void 0,
1368
+ // The operation's calls decide whether the pick is the right wallet.
1369
+ deferBindingSave: true
1370
+ };
1371
+ try {
1372
+ const resolvedConnectId = await this.ensureConnected(
1373
+ target,
1374
+ signal,
1375
+ true,
1376
+ void 0,
1377
+ attempt
1378
+ );
1379
+ _LedgerAdapter._throwIfAborted(signal);
1380
+ const result = this._createOperation(connectId, resolvedConnectId);
1381
+ if (result.success && attempt.pendingBinding) {
1382
+ this._pendingOperationBindings.set(result.payload, attempt);
1383
+ }
1384
+ return result;
1385
+ } catch (error) {
1386
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1387
+ throw error;
1388
+ }
1389
+ },
1390
+ {
1391
+ label: "acquireOperation",
1392
+ rejectIfBusy: true,
1393
+ busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1394
+ }
1395
+ );
1396
+ } catch (error) {
1397
+ return this.errorToFailure(error);
1398
+ }
1399
+ }
1400
+ _createOperation(searchTargetId, resolvedConnectId) {
1401
+ this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1402
+ const sessionId = this._sessions.get(resolvedConnectId);
1403
+ if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1404
+ const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1405
+ const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1406
+ vendor: "ledger",
1407
+ model: "unknown",
1408
+ firmwareVersion: "",
1409
+ deviceId: "",
1410
+ connectId: resolvedConnectId,
1411
+ connectionType
1412
+ };
1413
+ const operation = this._operations.create({
1414
+ searchTargetId,
1415
+ connectId: resolvedConnectId,
1416
+ device,
1417
+ connectionType,
1418
+ connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
1419
+ });
1420
+ return success2(operation.operationId);
1421
+ }
1422
+ async _connectTarget(connectId, preserveOperationId, signal) {
929
1423
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
930
1424
  try {
931
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1425
+ this._assertConnectorReady("connectDevice");
1426
+ const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1427
+ if (discoveredType === "usb" || discoveredType === "ble") {
1428
+ this._activeConnectionType = discoveredType;
1429
+ }
1430
+ if (this._isBleConnection() && !connectId) {
932
1431
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
933
1432
  code: HardwareErrorCode3.DeviceNotFound
934
1433
  });
935
1434
  }
936
- if (!isLedgerBleConnectionType(this.connector.connectionType)) {
937
- await this._evictAllSessions();
1435
+ await this._ensureDevicePermission(connectId, void 0, signal);
1436
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1437
+ const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1438
+ if (!isMultiTransport && this._isBleConnection()) {
1439
+ const previousSessionId = this._sessions.get(connectId);
1440
+ this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1441
+ if (previousSessionId) {
1442
+ this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1443
+ this._sessions.delete(connectId);
1444
+ await this.connector.disconnect(previousSessionId).catch(() => void 0);
1445
+ }
1446
+ } else {
1447
+ await this._evictAllSessions(preserveOperationId);
1448
+ }
1449
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1450
+ const stateGeneration = this._stateGeneration;
1451
+ const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1452
+ let session;
1453
+ this._connectingConnectId = connectId;
1454
+ try {
1455
+ session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1456
+ transportType: this._activeConnectionType ?? "usb"
1457
+ }) : await this.connector.connect(connectId);
1458
+ if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1459
+ await this.connector.disconnect(session.sessionId).catch(() => void 0);
1460
+ throw Object.assign(new Error("Ledger connection aborted"), {
1461
+ code: HardwareErrorCode3.UserAborted
1462
+ });
1463
+ }
1464
+ } finally {
1465
+ if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1466
+ releaseOperation();
938
1467
  }
939
- await this._ensureDevicePermission(connectId);
940
- const session = await this.connector.connect(connectId);
941
- this._sessions.set(connectId, session.sessionId);
1468
+ const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1469
+ this._sessions.set(resolvedConnectId, session.sessionId);
1470
+ this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
942
1471
  if (session.deviceInfo) {
943
- this._discoveredDevices.set(connectId, session.deviceInfo);
1472
+ this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
944
1473
  }
945
- const result = success(connectId);
1474
+ const result = success2(resolvedConnectId);
946
1475
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
947
1476
  return result;
948
1477
  } catch (err) {
@@ -955,30 +1484,84 @@ var _LedgerAdapter = class _LedgerAdapter {
955
1484
  return failureResult;
956
1485
  }
957
1486
  }
958
- async disconnectDevice(connectId) {
1487
+ async releaseOperation(operationId) {
1488
+ const operation = this._operations.findActive(operationId);
1489
+ if (operation) this._cancelOperationWork(operation);
1490
+ const endedOperation = this._operations.release(operationId);
1491
+ if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
1492
+ const { connectId } = endedOperation;
959
1493
  debugLog("[LedgerAdapter][REQ]", {
960
- method: "disconnectDevice",
1494
+ method: "releaseOperation",
961
1495
  connectId,
962
1496
  params: { connectId }
963
1497
  });
964
1498
  try {
965
- const sessionId = this._sessions.get(connectId);
966
- if (sessionId) {
967
- await this.connector.disconnect(sessionId);
968
- this._sessions.delete(connectId);
969
- }
970
- debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
1499
+ await this._releaseOperationConnection(endedOperation);
1500
+ debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
971
1501
  } catch (err) {
972
1502
  const e = err;
973
1503
  debugLog("[LedgerAdapter][RES]", {
974
- method: "disconnectDevice",
1504
+ method: "releaseOperation",
975
1505
  success: false,
976
1506
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
977
1507
  });
978
1508
  throw err;
979
1509
  }
980
1510
  }
981
- async getDeviceInfo(connectId, deviceId) {
1511
+ /**
1512
+ * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1513
+ * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1514
+ */
1515
+ _cancelOperationWork(operation) {
1516
+ const { operationId } = operation;
1517
+ const reason = createHwkError({
1518
+ code: HardwareErrorCode3.OperationEnded,
1519
+ message: "Ledger operation was released",
1520
+ params: { operationId, reason: "explicit" }
1521
+ });
1522
+ const queueKey = ledgerQueueKey({ operationId });
1523
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1524
+ this._jobQueue.cancelActiveAndPending(queueKey, reason);
1525
+ if (!ownsRunningCall) return;
1526
+ this._uiRegistry.cancel(void 0, void 0, operationId);
1527
+ void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
1528
+ }
1529
+ /**
1530
+ * A running call by bare connectId (or still resolving its device by identity) may be on this
1531
+ * connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
1532
+ * caller like any bare call's session. A lost connection is torn down regardless.
1533
+ */
1534
+ _bareCallMayUseConnection(operation) {
1535
+ const activeKey = this._jobQueue.getActiveJob()?.deviceId;
1536
+ return activeKey !== void 0 && !isHardwareOperationId(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
1537
+ }
1538
+ async _releaseOperationConnection(operation) {
1539
+ const sessionIds = /* @__PURE__ */ new Set();
1540
+ for (const [connectId, sessionId] of this._sessions) {
1541
+ if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1542
+ this._sessions.delete(connectId);
1543
+ sessionIds.add(sessionId);
1544
+ }
1545
+ }
1546
+ for (const sessionId of sessionIds) {
1547
+ await this._runConnectorTeardown(
1548
+ () => this.connector.disconnect(sessionId).catch(() => void 0)
1549
+ );
1550
+ }
1551
+ }
1552
+ async _releaseLostOperationConnection(operationId) {
1553
+ const endedOperation = this._operations.end(operationId, "disconnect");
1554
+ if (!endedOperation) return;
1555
+ this._discoveredDevices.delete(endedOperation.connectId);
1556
+ await this._releaseOperationConnection(endedOperation);
1557
+ }
1558
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1559
+ let connectId;
1560
+ try {
1561
+ connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1562
+ } catch (error) {
1563
+ return this.errorToFailure(error);
1564
+ }
982
1565
  debugLog("[LedgerAdapter][REQ]", {
983
1566
  method: "getDeviceInfo",
984
1567
  connectId,
@@ -988,7 +1571,7 @@ var _LedgerAdapter = class _LedgerAdapter {
988
1571
  await this._ensureDevicePermission(connectId, deviceId);
989
1572
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
990
1573
  if (cached) {
991
- const result = success(cached);
1574
+ const result = success2(cached);
992
1575
  debugLog("[LedgerAdapter][RES]", {
993
1576
  method: "getDeviceInfo",
994
1577
  success: true,
@@ -1013,11 +1596,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1013
1596
  success: false,
1014
1597
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1015
1598
  });
1016
- throw err;
1599
+ return this.errorToFailure(err);
1017
1600
  }
1018
1601
  }
1019
- getSupportedChains() {
1020
- return ["evm", "btc", "sol", "tron"];
1602
+ /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1603
+ async _dropUncheckedBundlePick(context, signal) {
1604
+ const { connection } = context;
1605
+ const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1606
+ if (!connection || !owner) return;
1607
+ this._pendingPickBindings.delete(connection.connectId);
1608
+ this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1609
+ if (this._sessions.get(connection.connectId) === connection.sessionId) {
1610
+ await this._dropSession(connection.connectId, signal);
1611
+ }
1021
1612
  }
1022
1613
  // ---------------------------------------------------------------------------
1023
1614
  // Chain call helper
@@ -1037,7 +1628,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1037
1628
  commonParams,
1038
1629
  installContext
1039
1630
  );
1040
- return success(result);
1631
+ return success2(result);
1041
1632
  } catch (err) {
1042
1633
  return this.errorToFailure(err);
1043
1634
  }
@@ -1053,13 +1644,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1053
1644
  if (params && typeof params === "object") {
1054
1645
  const {
1055
1646
  autoInstallApp,
1647
+ operationId,
1056
1648
  passphraseState: _passphraseState,
1057
1649
  useEmptyPassphrase: _useEmptyPassphrase,
1650
+ knownConnections,
1651
+ extra,
1652
+ allowDeviceSelection,
1653
+ supportedTransports,
1058
1654
  ...rest
1059
1655
  } = params;
1060
1656
  return {
1061
1657
  commonParams: {
1062
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1658
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1659
+ operationId: typeof operationId === "string" ? operationId : void 0,
1660
+ ...pickConnectionContext({
1661
+ knownConnections,
1662
+ extra,
1663
+ allowDeviceSelection,
1664
+ supportedTransports
1665
+ })
1063
1666
  },
1064
1667
  rest
1065
1668
  };
@@ -1225,7 +1828,13 @@ var _LedgerAdapter = class _LedgerAdapter {
1225
1828
  params
1226
1829
  );
1227
1830
  }
1228
- tronSignMessage(connectId, deviceId, params) {
1831
+ async tronSignMessage(connectId, deviceId, params) {
1832
+ if (params?.messageType !== "V2") {
1833
+ return failure2(
1834
+ HardwareErrorCode3.MethodNotSupported,
1835
+ 'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1836
+ );
1837
+ }
1229
1838
  return this.callChainWithMergedParams(
1230
1839
  connectId,
1231
1840
  deviceId,
@@ -1235,14 +1844,33 @@ var _LedgerAdapter = class _LedgerAdapter {
1235
1844
  );
1236
1845
  }
1237
1846
  // ---------------------------------------------------------------------------
1238
- // App management — OS-level Ledger app install / list. Bypasses fingerprint
1239
- // and chain-handler dispatch; installApp progress is forwarded to the adapter
1240
- // emitter via 'ui-event' AppInstallProgress events.
1847
+ // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1848
+ // ---------------------------------------------------------------------------
1849
+ zcashGetFullViewingKey(connectId, deviceId, params) {
1850
+ return this.callChainWithMergedParams(
1851
+ connectId,
1852
+ deviceId,
1853
+ "zcash",
1854
+ "zcashGetFullViewingKey",
1855
+ params
1856
+ );
1857
+ }
1858
+ zcashGetShieldedAddress(connectId, deviceId, params) {
1859
+ return this.callChainWithMergedParams(
1860
+ connectId,
1861
+ deviceId,
1862
+ "zcash",
1863
+ "zcashGetShieldedAddress",
1864
+ params
1865
+ );
1866
+ }
1867
+ // ---------------------------------------------------------------------------
1868
+ // App management: OS-level app install/list, no fingerprint or chain dispatch.
1241
1869
  // ---------------------------------------------------------------------------
1242
1870
  async installApp(connectId, appName) {
1243
1871
  try {
1244
1872
  await this.connectorCall(connectId, "installApp", { appName });
1245
- return success(void 0);
1873
+ return success2(void 0);
1246
1874
  } catch (err) {
1247
1875
  return this.errorToFailure(err);
1248
1876
  }
@@ -1250,7 +1878,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1250
1878
  async listInstalledApps(connectId) {
1251
1879
  try {
1252
1880
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1253
- return success(result);
1881
+ return success2(result);
1254
1882
  } catch (err) {
1255
1883
  return this.errorToFailure(err);
1256
1884
  }
@@ -1259,7 +1887,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1259
1887
  async listInstalledNames(connectId) {
1260
1888
  try {
1261
1889
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1262
- return success(result);
1890
+ return success2(result);
1263
1891
  } catch (err) {
1264
1892
  return this.errorToFailure(err);
1265
1893
  }
@@ -1267,7 +1895,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1267
1895
  async listAvailableApps(connectId) {
1268
1896
  try {
1269
1897
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1270
- return success(result);
1898
+ return success2(result);
1271
1899
  } catch (err) {
1272
1900
  return this.errorToFailure(err);
1273
1901
  }
@@ -1275,7 +1903,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1275
1903
  async getLedgerFirmwareVersion(connectId) {
1276
1904
  try {
1277
1905
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1278
- return success(result);
1906
+ return success2(result);
1279
1907
  } catch (err) {
1280
1908
  return this.errorToFailure(err);
1281
1909
  }
@@ -1283,7 +1911,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1283
1911
  async getLedgerDeviceInfo(connectId) {
1284
1912
  try {
1285
1913
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1286
- return success(result);
1914
+ return success2(result);
1287
1915
  } catch (err) {
1288
1916
  return this.errorToFailure(err);
1289
1917
  }
@@ -1323,11 +1951,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1323
1951
  );
1324
1952
  }
1325
1953
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1326
- this.resetState();
1954
+ await this._resetStateAndDisconnectSessions();
1327
1955
  }
1328
1956
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1329
1957
  if (!result.isGenuine) {
1330
- return success({
1958
+ return success2({
1331
1959
  vendor: "ledger",
1332
1960
  verified: false
1333
1961
  });
@@ -1338,7 +1966,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1338
1966
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1339
1967
  );
1340
1968
  }
1341
- return success({
1969
+ return success2({
1342
1970
  vendor: "ledger",
1343
1971
  verified: result.isGenuine,
1344
1972
  deviceId: result.deviceId
@@ -1349,10 +1977,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1349
1977
  if (relayUrl) {
1350
1978
  try {
1351
1979
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1352
- this.resetState();
1980
+ await this._resetStateAndDisconnectSessions();
1353
1981
  } catch {
1354
1982
  this.connector.reset();
1355
- this.resetState();
1983
+ await this._resetStateAndDisconnectSessions();
1356
1984
  }
1357
1985
  }
1358
1986
  }
@@ -1364,6 +1992,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1364
1992
  this.emitter.off(event, listener);
1365
1993
  }
1366
1994
  cancel(connectId) {
1995
+ const namedOperationIsLive = (id) => {
1996
+ try {
1997
+ this._operations.resolve(id);
1998
+ return true;
1999
+ } catch {
2000
+ return false;
2001
+ }
2002
+ };
2003
+ if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
2004
+ debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
2005
+ connectId
2006
+ });
2007
+ return;
2008
+ }
1367
2009
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1368
2010
  code: HardwareErrorCode3.UserAborted,
1369
2011
  _tag: ERROR_TAG.UserAborted
@@ -1374,60 +2016,161 @@ var _LedgerAdapter = class _LedgerAdapter {
1374
2016
  this._lastCancelReason = void 0;
1375
2017
  }
1376
2018
  }, 2e3);
1377
- this._uiRegistry.cancel();
1378
- if (connectId) {
1379
- this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1380
- } else {
1381
- this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1382
- }
1383
- if (connectId) {
1384
- const sessionId = this._sessions.get(connectId) ?? connectId;
1385
- void this.connector.cancel(sessionId);
1386
- } else {
1387
- for (const sid of this._sessions.values()) void this.connector.cancel(sid);
2019
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2020
+ let operationId;
2021
+ if (isHardwareOperationId(connectId)) {
2022
+ operationId = connectId;
2023
+ } else if (!connectId && isHardwareOperationId(activeJobId)) {
2024
+ operationId = activeJobId;
1388
2025
  }
1389
- if (this._connectingPromise) {
2026
+ let resolvedConnectId = connectId;
2027
+ if (operationId) {
2028
+ try {
2029
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
2030
+ } catch {
2031
+ resolvedConnectId = void 0;
2032
+ }
2033
+ }
2034
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
2035
+ const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
2036
+ if (!connectId) {
2037
+ this._uiRegistry.cancel();
2038
+ } else if (pendingOperationId) {
2039
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
2040
+ }
2041
+ this._finishBleBinding("cancelled");
2042
+ if (!connectId) this._pendingOperationBindings.clear();
2043
+ else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
2044
+ const queueKeys = /* @__PURE__ */ new Set();
2045
+ if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
2046
+ if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
2047
+ if (queueKeys.size) {
2048
+ let cancelledAnyJob = false;
2049
+ for (const key of queueKeys) {
2050
+ cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
2051
+ }
2052
+ debugLog("[LedgerAdapter] cancel routed to queue keys", {
2053
+ queueKeys: [...queueKeys],
2054
+ cancelledAnyJob
2055
+ });
2056
+ } else {
2057
+ this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
2058
+ }
2059
+ if (resolvedConnectId) {
2060
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
2061
+ void this.connector.cancel(sessionId);
2062
+ } else {
2063
+ for (const sid of this._sessions.values()) void this.connector.cancel(sid);
2064
+ }
2065
+ const connectingConnectId = this._connectingConnectId;
2066
+ const targetKeys = new Set(
2067
+ [
2068
+ connectId,
2069
+ resolvedConnectId,
2070
+ ...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
2071
+ ].filter(Boolean)
2072
+ );
2073
+ const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
2074
+ if (this._connectingPromise && ownsPendingConnect) {
1390
2075
  this._doConnectAbortController?.abort(userAbortReason);
1391
2076
  }
2077
+ if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
1392
2078
  }
1393
2079
  // ---------------------------------------------------------------------------
1394
2080
  // Chain fingerprint
1395
2081
  // ---------------------------------------------------------------------------
2082
+ /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
1396
2083
  async getChainFingerprint(connectId, deviceId, chain) {
1397
2084
  try {
1398
2085
  const fingerprint = await this._computeChainFingerprint(
1399
2086
  chain,
1400
2087
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
1401
2088
  );
1402
- return success(fingerprint);
2089
+ if (deviceId) {
2090
+ if (fingerprint !== deviceId) {
2091
+ return failure2(
2092
+ HardwareErrorCode3.DeviceMismatch,
2093
+ formatDeviceMismatchError(deviceId, fingerprint)
2094
+ );
2095
+ }
2096
+ }
2097
+ return success2(fingerprint);
1403
2098
  } catch (err) {
1404
2099
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
1405
2100
  return this.errorToFailure(err);
1406
2101
  }
1407
2102
  }
1408
2103
  /**
1409
- * Verify fingerprint using an existing sessionId directly.
1410
- * Safe to call inside connectorCall without causing queue deadlock.
2104
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
2105
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
1411
2106
  */
1412
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
1413
- if (!deviceId) return { success: true };
2107
+ async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
2108
+ const [first] = identities;
2109
+ if (identities.length > 1) {
2110
+ for (const identity of identities) {
2111
+ try {
2112
+ return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
2113
+ } catch (error) {
2114
+ const isAppMissing = isAppNotInstalledError(error) || error?.code === HardwareErrorCode3.AppNotInstalled;
2115
+ if (!isAppMissing) throw error;
2116
+ }
2117
+ }
2118
+ }
2119
+ return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
2120
+ }
2121
+ /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2122
+ async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
1414
2123
  try {
1415
- const fingerprint = await this._computeChainFingerprint(
1416
- chain,
1417
- (method, params) => this._callConnector(sessionId, method, params)
2124
+ const outcome = await requestSaveDeviceBinding(
2125
+ this.emitter,
2126
+ this._uiRegistry,
2127
+ {
2128
+ selectionRequestId,
2129
+ connection: { transport: "ble", connectId },
2130
+ ...identity ? { identity } : {},
2131
+ extra: context?.extra,
2132
+ operationId
2133
+ },
2134
+ signal
1418
2135
  );
1419
- if (fingerprint === deviceId) {
1420
- return { success: true };
2136
+ if (context) context.bindingSaved = outcome.saved;
2137
+ if (!outcome.saved) {
2138
+ debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2139
+ connectId,
2140
+ reason: outcome.reason
2141
+ });
1421
2142
  }
1422
- return { success: false, expected: deviceId, actual: fingerprint };
1423
- } catch (err) {
1424
- const mapped = mapLedgerError(err);
1425
- if (mapped.code === HardwareErrorCode3.WrongApp || mapped.code === HardwareErrorCode3.DeviceLocked) {
1426
- return { success: true };
2143
+ } catch (error) {
2144
+ await this._dropSession(connectId, signal);
2145
+ throw error;
2146
+ } finally {
2147
+ if (this._bindingSelectionRequestId === selectionRequestId) {
2148
+ this._bindingSelectionRequestId = void 0;
1427
2149
  }
1428
- throw err;
1429
2150
  }
1430
2151
  }
2152
+ async _dropSession(connectId, signal) {
2153
+ const sessionId = this._sessions.get(connectId);
2154
+ this._sessions.delete(connectId);
2155
+ if (!sessionId) return;
2156
+ this._sessionTransports.delete(sessionId);
2157
+ const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2158
+ () => void 0
2159
+ );
2160
+ if (!signal.aborted) await teardown;
2161
+ }
2162
+ /** Verify on the acquired session without re-entering the job queue. */
2163
+ async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2164
+ if (!deviceId) return { success: true };
2165
+ const fingerprint = await this._computeChainFingerprint(
2166
+ chain,
2167
+ (method, params) => this._callConnector(sessionId, method, params)
2168
+ );
2169
+ if (fingerprint === deviceId) {
2170
+ return { success: true };
2171
+ }
2172
+ return { success: false, expected: deviceId, actual: fingerprint };
2173
+ }
1431
2174
  /**
1432
2175
  * Compute the chain fingerprint via a caller-supplied call strategy.
1433
2176
  *
@@ -1455,11 +2198,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1455
2198
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
1456
2199
  } else if (chain === "tron") {
1457
2200
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2201
+ } else if (chain === "zcash") {
2202
+ address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
1458
2203
  } else {
1459
2204
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
1460
2205
  }
1461
2206
  return deriveDeviceFingerprint(address);
1462
2207
  }
2208
+ /**
2209
+ * Operation owning the running job, so a mid-call UI request can name it.
2210
+ * Undefined at cold start when no operation owns the job.
2211
+ */
2212
+ _activeOperationId() {
2213
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2214
+ }
1463
2215
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
1464
2216
  // The user must press Confirm after unlocking, which triggers a search retry.
1465
2217
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -1469,15 +2221,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1469
2221
  if (signal?.aborted) {
1470
2222
  _LedgerAdapter._throwIfAborted(signal);
1471
2223
  }
2224
+ const operationId = this._activeOperationId();
1472
2225
  const waitPromise = this._uiRegistry.wait(
1473
- UI_REQUEST.REQUEST_DEVICE_CONNECT
2226
+ UI_REQUEST.REQUEST_DEVICE_CONNECT,
2227
+ { operationId }
1474
2228
  );
1475
2229
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1476
2230
  type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
1477
2231
  payload: {
1478
2232
  vendor: "ledger",
1479
2233
  reason: "device-not-found",
1480
- message: "Please connect and unlock your Ledger device"
2234
+ message: "Please connect and unlock your Ledger device",
2235
+ operationId
1481
2236
  }
1482
2237
  });
1483
2238
  let payload;
@@ -1523,7 +2278,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1523
2278
  * Returns the params to pass through (with `showOnDevice` possibly
1524
2279
  * promoted), or `null` if the user declined.
1525
2280
  */
1526
- async _gateBtcHighIndex(params) {
2281
+ async _gateBtcHighIndex(params, signal) {
1527
2282
  const accountIndex = btcAccountIndexFromPath(params.path);
1528
2283
  if (params.showOnDevice) return params;
1529
2284
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -1532,25 +2287,32 @@ var _LedgerAdapter = class _LedgerAdapter {
1532
2287
  if (this._btcHighIndexConfirmedThisSession) {
1533
2288
  return { ...params, showOnDevice: true };
1534
2289
  }
1535
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2290
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1536
2291
  if (!confirmed) return null;
1537
2292
  this._btcHighIndexConfirmedThisSession = true;
1538
2293
  return { ...params, showOnDevice: true };
1539
2294
  }
1540
- async _waitForBtcHighIndexConfirm(path, accountIndex) {
2295
+ async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2296
+ const operationId = this._activeOperationId();
1541
2297
  const waitPromise = this._uiRegistry.wait(
1542
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2298
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2299
+ { operationId }
1543
2300
  );
1544
2301
  this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1545
2302
  type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1546
2303
  payload: {
1547
2304
  vendor: "ledger",
1548
2305
  path,
1549
- accountIndex
2306
+ accountIndex,
2307
+ operationId
1550
2308
  }
1551
2309
  });
1552
2310
  try {
1553
- const payload = await waitPromise;
2311
+ const payload = await this._awaitUiAnswer(
2312
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2313
+ waitPromise,
2314
+ signal
2315
+ );
1554
2316
  return !!payload?.confirmed;
1555
2317
  } catch (err) {
1556
2318
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1560,18 +2322,35 @@ var _LedgerAdapter = class _LedgerAdapter {
1560
2322
  return false;
1561
2323
  }
1562
2324
  }
2325
+ /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2326
+ async _awaitUiAnswer(requestType, waitPromise, signal) {
2327
+ const onAbort = () => this._uiRegistry.cancel(requestType);
2328
+ if (signal.aborted) onAbort();
2329
+ signal.addEventListener("abort", onAbort, { once: true });
2330
+ try {
2331
+ return await waitPromise;
2332
+ } finally {
2333
+ signal.removeEventListener("abort", onAbort);
2334
+ }
2335
+ }
1563
2336
  // Ask the user whether to install a missing app (autoInstallApp flow).
1564
2337
  // Same register-then-emit ordering as the BTC high-index gate.
1565
- async _waitForInstallAppConfirm(appName) {
2338
+ async _waitForInstallAppConfirm(appName, signal) {
2339
+ const operationId = this._activeOperationId();
1566
2340
  const waitPromise = this._uiRegistry.wait(
1567
- UI_REQUEST.REQUEST_INSTALL_APP
2341
+ UI_REQUEST.REQUEST_INSTALL_APP,
2342
+ { operationId }
1568
2343
  );
1569
2344
  this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
1570
2345
  type: UI_REQUEST.REQUEST_INSTALL_APP,
1571
- payload: { vendor: "ledger", appName }
2346
+ payload: { vendor: "ledger", appName, operationId }
1572
2347
  });
1573
2348
  try {
1574
- const payload = await waitPromise;
2349
+ const payload = await this._awaitUiAnswer(
2350
+ UI_REQUEST.REQUEST_INSTALL_APP,
2351
+ waitPromise,
2352
+ signal
2353
+ );
1575
2354
  return !!payload?.confirmed;
1576
2355
  } catch (err) {
1577
2356
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1584,16 +2363,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1584
2363
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
1585
2364
  // `_doConnect` runs under its own internal controller so caller A's cancel
1586
2365
  // doesn't kill caller B's await.
1587
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2366
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1588
2367
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
1589
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2368
+ this._assertConnectorReady("connectDevice");
2369
+ if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1590
2370
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1591
2371
  code: HardwareErrorCode3.DeviceNotFound
1592
2372
  });
1593
2373
  }
1594
2374
  if (connectId && this._sessions.has(connectId)) return connectId;
1595
2375
  if (!connectId && this._sessions.size > 0) {
1596
- if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2376
+ if (!this._isBleConnection() && this._sessions.size > 1) {
1597
2377
  throw Object.assign(
1598
2378
  new Error(
1599
2379
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -1603,15 +2383,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1603
2383
  }
1604
2384
  return this._sessions.keys().next().value;
1605
2385
  }
1606
- if (!this._connectingPromise) {
1607
- this._doConnectAbortController = new AbortController();
1608
- const innerSignal = this._doConnectAbortController.signal;
2386
+ if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2387
+ const controller = new AbortController();
2388
+ this._doConnectAbortController = controller;
2389
+ const innerSignal = controller.signal;
1609
2390
  this._connectingPromise = (async () => {
1610
2391
  try {
1611
- return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2392
+ return await this._doConnect(
2393
+ innerSignal,
2394
+ connectId,
2395
+ allowUsbEphemeralFallback,
2396
+ preserveOperationId,
2397
+ context
2398
+ );
1612
2399
  } finally {
1613
- this._connectingPromise = null;
1614
- this._doConnectAbortController = null;
2400
+ if (this._doConnectAbortController === controller) {
2401
+ this._connectingPromise = null;
2402
+ this._doConnectAbortController = null;
2403
+ if (this._sessions.size === 0) this._activeConnectionType = void 0;
2404
+ }
1615
2405
  }
1616
2406
  })();
1617
2407
  }
@@ -1620,22 +2410,54 @@ var _LedgerAdapter = class _LedgerAdapter {
1620
2410
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
1621
2411
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
1622
2412
  // throw DeviceNotFound so the user is kicked out of the loop.
1623
- async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
1624
- if (isLedgerBleConnectionType(this.connector.connectionType) && targetConnectId) {
1625
- try {
1626
- return await this._connectDeviceOrThrow(targetConnectId);
1627
- } catch (err) {
1628
- if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
1629
- throw err;
1630
- }
1631
- this._discoveredDevices.delete(targetConnectId);
1632
- if (isDeviceDisconnectedError(err)) {
1633
- try {
1634
- this.connector.reset?.();
1635
- } catch {
1636
- }
1637
- }
2413
+ async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2414
+ _LedgerAdapter._throwIfAborted(internalSignal);
2415
+ if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2416
+ this._activeConnectionType = "usb";
2417
+ const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2418
+ _LedgerAdapter._throwIfAborted(internalSignal);
2419
+ const knownUsb = context?.knownConnections?.find(
2420
+ (connection) => connection.transport === "usb"
2421
+ );
2422
+ const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2423
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2424
+ return this._connectFirstOrSelect(
2425
+ usbDevices,
2426
+ usbTarget,
2427
+ allowUsbEphemeralFallback,
2428
+ preserveOperationId,
2429
+ context,
2430
+ internalSignal
2431
+ );
2432
+ }
2433
+ if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2434
+ throw createHwkError({
2435
+ code: HardwareErrorCode3.DeviceNotFound,
2436
+ message: "This Ledger model has no Bluetooth transport; connect it over USB"
2437
+ });
1638
2438
  }
2439
+ this._activeConnectionType = "ble";
2440
+ const knownBle = context?.knownConnections?.find(
2441
+ (connection) => connection.transport === "ble"
2442
+ );
2443
+ if (knownBle?.transport === "ble") {
2444
+ return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2445
+ }
2446
+ const bleContext = context ?? {};
2447
+ bleContext.allowBleSelection = true;
2448
+ bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
2449
+ const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2450
+ return this._connectFirstOrSelect(
2451
+ bleDevices,
2452
+ void 0,
2453
+ allowUsbEphemeralFallback,
2454
+ preserveOperationId,
2455
+ bleContext,
2456
+ internalSignal
2457
+ );
2458
+ }
2459
+ if (this._isBleConnection() && targetConnectId) {
2460
+ return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
1639
2461
  }
1640
2462
  let confirms = 0;
1641
2463
  while (!internalSignal.aborted) {
@@ -1643,22 +2465,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1643
2465
  type: EConnectorInteraction.Searching,
1644
2466
  payload: { sessionId: "" }
1645
2467
  });
1646
- let devices = await this.searchDevices();
2468
+ let devices = await this._searchDevices(void 0, internalSignal);
2469
+ _LedgerAdapter._throwIfAborted(internalSignal);
1647
2470
  if (devices.length === 0) {
1648
2471
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
1649
2472
  await new Promise((resolve) => {
1650
2473
  setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
1651
2474
  });
1652
- devices = await this.searchDevices();
2475
+ _LedgerAdapter._throwIfAborted(internalSignal);
2476
+ devices = await this._searchDevices(void 0, internalSignal);
2477
+ _LedgerAdapter._throwIfAborted(internalSignal);
1653
2478
  if (devices.length > 0) break;
1654
2479
  }
1655
2480
  }
1656
- if (devices.length > 0) {
2481
+ if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1657
2482
  try {
1658
2483
  return await this._connectFirstOrSelect(
1659
2484
  devices,
1660
2485
  targetConnectId,
1661
- allowUsbEphemeralFallback
2486
+ allowUsbEphemeralFallback,
2487
+ preserveOperationId,
2488
+ context,
2489
+ internalSignal
1662
2490
  );
1663
2491
  } catch (err) {
1664
2492
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -1687,45 +2515,148 @@ var _LedgerAdapter = class _LedgerAdapter {
1687
2515
  _LedgerAdapter._throwIfAborted(internalSignal);
1688
2516
  throw new Error("_doConnect aborted");
1689
2517
  }
1690
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2518
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2519
+ _LedgerAdapter._throwIfAborted(signal);
1691
2520
  if (targetConnectId) {
1692
2521
  const target = devices.find(
1693
2522
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
1694
2523
  );
1695
2524
  if (target) {
1696
- return this._connectDeviceOrThrow(target.connectId);
2525
+ return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1697
2526
  }
1698
- if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2527
+ if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1699
2528
  debugLog(
1700
2529
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
1701
2530
  );
1702
- return this._connectDeviceOrThrow(devices[0].connectId);
2531
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1703
2532
  }
1704
- const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
1705
- code: HardwareErrorCode3.DeviceNotFound
1706
- });
1707
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
1708
- err._tag = ERROR_TAG.DeviceNotAdvertising;
2533
+ if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2534
+ const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2535
+ code: HardwareErrorCode3.DeviceNotFound
2536
+ });
2537
+ if (this._isBleConnection()) {
2538
+ err._tag = ERROR_TAG.DeviceNotAdvertising;
2539
+ }
2540
+ throw err;
1709
2541
  }
1710
- throw err;
1711
2542
  }
1712
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
2543
+ const requiresBleSelection = this._isBleConnection();
2544
+ if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
1713
2545
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1714
2546
  code: HardwareErrorCode3.DeviceNotFound
1715
2547
  });
1716
2548
  }
1717
- if (devices.length > 1) {
1718
- throw createMultipleUsbLedgerDevicesError();
2549
+ if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2550
+ const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2551
+ if (context) context.bindingSessionId = bindingSessionId;
2552
+ const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2553
+ const knownUsb = context?.knownConnections?.find(
2554
+ (connection) => connection.transport === "usb"
2555
+ );
2556
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
2557
+ const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
2558
+ const { device, requestId } = await requestBleDeviceSelection({
2559
+ emitter: this.emitter,
2560
+ registry: this._uiRegistry,
2561
+ signal,
2562
+ allowUsbFallback,
2563
+ scan: async () => {
2564
+ if (allowUsbFallback) {
2565
+ const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2566
+ const candidate = usbDevices.find(
2567
+ (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2568
+ ) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2569
+ if (candidate) return [candidate];
2570
+ }
2571
+ return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2572
+ },
2573
+ request: {
2574
+ devices,
2575
+ bindingSessionId,
2576
+ context: {
2577
+ kind: "bind-connection",
2578
+ transport: "ble",
2579
+ reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2580
+ },
2581
+ extra: context?.extra,
2582
+ operationId: preserveOperationId
2583
+ }
2584
+ });
2585
+ if (device.connectionType === "usb") {
2586
+ this._activeConnectionType = "usb";
2587
+ if (context) context.selectedConnection = void 0;
2588
+ this._bindingSelectionRequestId = requestId;
2589
+ this._finishBleBinding("cancelled");
2590
+ return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2591
+ }
2592
+ this._bindingSelectionRequestId = requestId;
2593
+ const connected = await this._connectDeviceOrThrow(
2594
+ device.connectId,
2595
+ preserveOperationId,
2596
+ signal
2597
+ );
2598
+ if (context) context.selectedConnection = { connectId: connected, requestId };
2599
+ if (context?.deferBindingSave) {
2600
+ context.pendingBinding = { connectId: connected, requestId };
2601
+ } else {
2602
+ await this._saveSelectedBleBinding(
2603
+ connected,
2604
+ requestId,
2605
+ context,
2606
+ preserveOperationId,
2607
+ signal
2608
+ );
2609
+ }
2610
+ return connected;
2611
+ }
2612
+ if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2613
+ if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2614
+ throw createHwkError({
2615
+ code: HardwareErrorCode3.DeviceNotFound,
2616
+ message: "Select a Ledger device before continuing"
2617
+ });
2618
+ }
2619
+ const requestId = this._uiRegistry.createRequestId();
2620
+ const operationId = this._activeOperationId();
2621
+ const waitPromise = this._uiRegistry.wait(
2622
+ UI_REQUEST.REQUEST_SELECT_DEVICE,
2623
+ { requestId, operationId }
2624
+ );
2625
+ this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
2626
+ type: UI_REQUEST.REQUEST_SELECT_DEVICE,
2627
+ payload: {
2628
+ devices,
2629
+ requestId,
2630
+ operationId,
2631
+ context: requiresBleSelection ? {
2632
+ kind: "bind-connection",
2633
+ transport: "ble",
2634
+ reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2635
+ } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2636
+ extra: context?.extra
2637
+ }
2638
+ });
2639
+ const { sdkConnectId } = await this._abortable(signal, waitPromise);
2640
+ _LedgerAdapter._throwIfAborted(signal);
2641
+ const selected = devices.find((device) => device.connectId === sdkConnectId);
2642
+ if (!selected) {
2643
+ throw Object.assign(new Error("Selected Ledger is no longer available"), {
2644
+ code: HardwareErrorCode3.DeviceNotFound
2645
+ });
2646
+ }
2647
+ if (context && requiresBleSelection)
2648
+ context.selectedConnection = { connectId: selected.connectId, requestId };
2649
+ return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1719
2650
  }
1720
2651
  if (devices.length !== 1) {
1721
2652
  throw Object.assign(new Error("Ledger device not found."), {
1722
2653
  code: HardwareErrorCode3.DeviceNotFound
1723
2654
  });
1724
2655
  }
1725
- return this._connectDeviceOrThrow(devices[0].connectId);
2656
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1726
2657
  }
1727
- async _connectDeviceOrThrow(chosenConnectId) {
1728
- const result = await this.connectDevice(chosenConnectId);
2658
+ async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2659
+ const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1729
2660
  if (!result.success) {
1730
2661
  const payload = result.payload;
1731
2662
  const rethrow = Object.assign(new Error(payload.error), {
@@ -1736,16 +2667,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1736
2667
  }
1737
2668
  throw rethrow;
1738
2669
  }
1739
- return chosenConnectId;
2670
+ return result.payload;
1740
2671
  }
1741
- /**
1742
- * Call the connector with automatic session resolution and disconnect retry.
1743
- *
1744
- * 1. Resolves a valid connectId via ensureConnected()
1745
- * 2. Looks up sessionId from _sessions
1746
- * 3. Calls connector.call()
1747
- * 4. On disconnect error: clears stale session, re-connects, retries once
1748
- */
1749
2672
  /**
1750
2673
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
1751
2674
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -1766,33 +2689,145 @@ var _LedgerAdapter = class _LedgerAdapter {
1766
2689
  * lives in one place.
1767
2690
  */
1768
2691
  async _callConnector(sessionId, method, params, signal) {
1769
- const promise = this.connector.call(sessionId, method, params);
2692
+ this._assertConnectorReady(method);
2693
+ if (signal?.aborted) throw this._abortReason(signal);
2694
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2695
+ let promise;
2696
+ try {
2697
+ promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2698
+ } catch (error) {
2699
+ releaseOperation();
2700
+ throw error;
2701
+ }
1770
2702
  const result = signal ? await this._abortable(signal, promise) : await promise;
1771
2703
  return this._unwrapConnectorResult(result);
1772
2704
  }
2705
+ _assertConnectorReady(method) {
2706
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2707
+ throw _LedgerAdapter._createDeviceBusyError(method);
2708
+ }
2709
+ }
2710
+ _runConnectorTeardown(task) {
2711
+ const previous = this._connectorTeardownTail;
2712
+ let releaseTail = () => void 0;
2713
+ this._connectorTeardownTail = new Promise((resolve) => {
2714
+ releaseTail = resolve;
2715
+ });
2716
+ this._pendingConnectorTeardowns += 1;
2717
+ return (async () => {
2718
+ try {
2719
+ await previous;
2720
+ await this._waitForConnectorOperationsToDrain();
2721
+ await task();
2722
+ } finally {
2723
+ this._pendingConnectorTeardowns -= 1;
2724
+ releaseTail();
2725
+ }
2726
+ })();
2727
+ }
2728
+ _waitForConnectorOperationsToDrain() {
2729
+ if (this._unsettledConnectorOperations.size === 0) {
2730
+ return Promise.resolve();
2731
+ }
2732
+ return new Promise((resolve) => {
2733
+ this._connectorIdleWaiters.add(resolve);
2734
+ });
2735
+ }
2736
+ _retainConnectorOperation(key) {
2737
+ this._unsettledConnectorOperations.set(
2738
+ key,
2739
+ (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2740
+ );
2741
+ let released = false;
2742
+ return () => {
2743
+ if (released) return;
2744
+ released = true;
2745
+ const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2746
+ if (remaining > 0) {
2747
+ this._unsettledConnectorOperations.set(key, remaining);
2748
+ } else {
2749
+ this._unsettledConnectorOperations.delete(key);
2750
+ }
2751
+ if (this._unsettledConnectorOperations.size === 0) {
2752
+ for (const resolve of this._connectorIdleWaiters) resolve();
2753
+ this._connectorIdleWaiters.clear();
2754
+ }
2755
+ };
2756
+ }
1773
2757
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1774
- debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1775
- const queueKey = connectId || "__ledger_default__";
2758
+ const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
2759
+ if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2760
+ throw createHwkError({
2761
+ code: HardwareErrorCode3.InvalidParams,
2762
+ message: "Conflicting Ledger operation ids",
2763
+ params: {
2764
+ positionalOperationId,
2765
+ commonOperationId: commonParams.operationId
2766
+ }
2767
+ });
2768
+ }
2769
+ const operationId = commonParams?.operationId ?? positionalOperationId;
2770
+ const operation = operationId ? this._operations.resolve(operationId) : void 0;
2771
+ const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2772
+ const effectiveConnectId = operation?.connectId ?? connectId;
2773
+ debugLog("[LedgerAdapter][REQ]", {
2774
+ method,
2775
+ connectId: effectiveConnectId || "(empty)",
2776
+ params: summarizeForLog(params, { method })
2777
+ });
2778
+ const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1776
2779
  try {
1777
2780
  const result = await this._jobQueue.enqueue(
1778
2781
  queueKey,
1779
- async (signal) => this._runConnectorCall(
1780
- connectId,
1781
- method,
1782
- params,
1783
- signal,
1784
- fingerprint,
1785
- permissionDeviceId,
1786
- commonParams,
1787
- installContext
1788
- ),
2782
+ async (signal) => {
2783
+ if (operationId) this._activeOperationJobs.add(operationId);
2784
+ try {
2785
+ return await this._runConnectorCall(
2786
+ effectiveConnectId,
2787
+ method,
2788
+ params,
2789
+ signal,
2790
+ fingerprint,
2791
+ permissionDeviceId,
2792
+ commonParams,
2793
+ installContext ?? {},
2794
+ operationId
2795
+ );
2796
+ } catch (error) {
2797
+ const status = signal.aborted ? "cancelled" : "failed";
2798
+ const bundleConnectId = installContext?.connection?.connectId;
2799
+ let keptBundlePick = false;
2800
+ for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2801
+ if (pickedConnectId === bundleConnectId) {
2802
+ keptBundlePick = true;
2803
+ } else {
2804
+ this._pendingPickBindings.delete(pickedConnectId);
2805
+ this._discardPendingBinding(owner, status);
2806
+ await this._dropSession(pickedConnectId, signal);
2807
+ }
2808
+ }
2809
+ if (!keptBundlePick) this._finishBleBinding(status);
2810
+ throw error;
2811
+ } finally {
2812
+ if (operationId) {
2813
+ this._activeOperationJobs.delete(operationId);
2814
+ if (this._pendingOperationDisconnects.delete(operationId)) {
2815
+ await this._releaseLostOperationConnection(operationId);
2816
+ }
2817
+ }
2818
+ }
2819
+ },
1789
2820
  {
1790
2821
  label: method,
1791
2822
  rejectIfBusy: true,
1792
2823
  busyError: _LedgerAdapter._createDeviceBusyError(method)
1793
2824
  }
1794
2825
  );
1795
- debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2826
+ debugLog("[LedgerAdapter][RES]", {
2827
+ method,
2828
+ success: true,
2829
+ payload: summarizeForLog(result, { method, role: "result" })
2830
+ });
1796
2831
  return result;
1797
2832
  } catch (err) {
1798
2833
  const e = err;
@@ -1806,15 +2841,22 @@ var _LedgerAdapter = class _LedgerAdapter {
1806
2841
  }
1807
2842
  });
1808
2843
  throw err;
2844
+ } finally {
2845
+ releaseOperationRetention?.();
1809
2846
  }
1810
2847
  }
2848
+ /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2849
+ _abortReason(signal) {
2850
+ return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2851
+ }
1811
2852
  /**
1812
2853
  * Race a promise against an abort signal. On abort, rejects with
1813
2854
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
1814
2855
  */
1815
2856
  _abortable(signal, promise) {
1816
- const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2857
+ const getAbortReason = () => this._abortReason(signal);
1817
2858
  if (signal.aborted) {
2859
+ void promise.catch(() => void 0);
1818
2860
  return Promise.reject(getAbortReason());
1819
2861
  }
1820
2862
  return new Promise((resolve, reject) => {
@@ -1841,17 +2883,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1841
2883
  }
1842
2884
  }
1843
2885
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
1844
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2886
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1845
2887
  _LedgerAdapter._throwIfAborted(signal);
1846
- await this._ensureDevicePermission(
1847
- connectId,
1848
- permissionDeviceId ?? fingerprint?.deviceId,
1849
- signal
1850
- );
2888
+ if (!operationId) {
2889
+ await this._ensureDevicePermission(
2890
+ connectId,
2891
+ permissionDeviceId ?? fingerprint?.deviceId,
2892
+ signal
2893
+ );
2894
+ }
1851
2895
  _LedgerAdapter._throwIfAborted(signal);
1852
2896
  let effectiveParams = params;
1853
2897
  if (method === "btcGetPublicKey") {
1854
- const gatedParams = await this._gateBtcHighIndex(params);
2898
+ const gatedParams = await this._gateBtcHighIndex(params, signal);
1855
2899
  if (gatedParams === null) {
1856
2900
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
1857
2901
  _tag: ERROR_TAG.UserAborted,
@@ -1861,19 +2905,67 @@ var _LedgerAdapter = class _LedgerAdapter {
1861
2905
  effectiveParams = gatedParams;
1862
2906
  }
1863
2907
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
1864
- const resolvedConnectId = await this.ensureConnected(
1865
- connectId,
2908
+ let businessCallStarted = false;
2909
+ const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2910
+ const knownTransport = this._isBleConnection() ? "ble" : "usb";
2911
+ const hintedConnectId = commonParams?.knownConnections?.find(
2912
+ (connection) => connection.transport === knownTransport
2913
+ );
2914
+ const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2915
+ const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2916
+ const checksWallet = Boolean(
2917
+ fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2918
+ );
2919
+ const connectionAttempt = {
2920
+ ...commonParams,
2921
+ deferBindingSave: checksWallet
2922
+ };
2923
+ const bundleConnection = installContext?.connection;
2924
+ if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2925
+ throw createHwkError({
2926
+ code: HardwareErrorCode3.DeviceDisconnected,
2927
+ message: "Ledger all-network connection ended"
2928
+ });
2929
+ }
2930
+ const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2931
+ preferredConnectId,
1866
2932
  signal,
1867
- allowUsbEphemeralFallback
2933
+ allowUsbEphemeralFallback,
2934
+ void 0,
2935
+ connectionAttempt
1868
2936
  );
2937
+ const walletCheck = installContext?.walletCheck;
2938
+ if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2939
+ throw createHwkError({
2940
+ code: HardwareErrorCode3.DeviceMismatch,
2941
+ message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2942
+ });
2943
+ }
1869
2944
  const sessionId = this._sessions.get(resolvedConnectId);
2945
+ if (sessionId && installContext && !installContext.connection) {
2946
+ installContext.connection = { connectId: resolvedConnectId, sessionId };
2947
+ }
1870
2948
  if (!sessionId) {
2949
+ if (operationId) {
2950
+ this._operations.end(operationId, "disconnect");
2951
+ throw createHwkError({
2952
+ code: HardwareErrorCode3.OperationEnded,
2953
+ message: "Ledger operation connection is no longer active",
2954
+ params: { operationId, reason: "disconnect" }
2955
+ });
2956
+ }
1871
2957
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
1872
2958
  _tag: ERROR_TAG.DeviceSessionNotFound
1873
2959
  });
1874
2960
  }
1875
2961
  try {
1876
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2962
+ const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2963
+ if (!operationId && connectionAttempt.pendingBinding) {
2964
+ this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2965
+ }
2966
+ const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2967
+ const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2968
+ if (fingerprint && checksWallet) {
1877
2969
  const fp = await this._abortable(
1878
2970
  signal,
1879
2971
  this._verifyDeviceFingerprintWithSession(
@@ -1883,14 +2975,68 @@ var _LedgerAdapter = class _LedgerAdapter {
1883
2975
  )
1884
2976
  );
1885
2977
  if (!fp.success) {
2978
+ if (pendingBinding) {
2979
+ this._discardPendingBinding(bindingOwner, "failed");
2980
+ this._pendingPickBindings.delete(resolvedConnectId);
2981
+ }
2982
+ if (operationId) {
2983
+ this._pendingOperationBindings.delete(operationId);
2984
+ this._operations.end(operationId, "explicit");
2985
+ await this._dropSession(resolvedConnectId, signal);
2986
+ }
1886
2987
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
1887
2988
  code: HardwareErrorCode3.DeviceMismatch
1888
2989
  });
1889
2990
  }
2991
+ if (walletCheck) walletCheck.verified = true;
2992
+ }
2993
+ if (pendingBinding && bindingOwner) {
2994
+ bindingOwner.pendingBinding = void 0;
2995
+ if (operationId) this._pendingOperationBindings.delete(operationId);
2996
+ else this._pendingPickBindings.delete(resolvedConnectId);
2997
+ await this._saveSelectedBleBinding(
2998
+ pendingBinding.connectId,
2999
+ pendingBinding.requestId,
3000
+ bindingOwner,
3001
+ operationId,
3002
+ signal,
3003
+ fingerprint && checksWallet ? {
3004
+ vendor: "ledger",
3005
+ type: "chainFingerprint",
3006
+ chain: fingerprint.chain,
3007
+ value: fingerprint.deviceId
3008
+ } : void 0
3009
+ );
3010
+ }
3011
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
3012
+ this._selectedBleReconnectTargets.set(connectId, {
3013
+ connectId: resolvedConnectId,
3014
+ chain: fingerprint.chain,
3015
+ fingerprint: fingerprint.deviceId
3016
+ });
1890
3017
  }
1891
- return await this._callConnector(sessionId, method, effectiveParams, signal);
3018
+ businessCallStarted = true;
3019
+ const result = await this._callConnector(sessionId, method, effectiveParams, signal);
3020
+ if (walletCheck) walletCheck.derived = true;
3021
+ return result;
1892
3022
  } catch (err) {
1893
3023
  if (signal.aborted) throw err;
3024
+ if (isLostConnectionError(err)) {
3025
+ this._discoveredDevices.delete(resolvedConnectId);
3026
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3027
+ else {
3028
+ this._sessions.delete(resolvedConnectId);
3029
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3030
+ }
3031
+ const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
3032
+ const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
3033
+ throw createHwkError({
3034
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
3035
+ message: "Ledger operation connection was lost; start a new operation",
3036
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
3037
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3038
+ });
3039
+ }
1894
3040
  const errObj = err;
1895
3041
  debugLog("[LedgerAdapter] connectorCall error:", method, {
1896
3042
  message: errObj?.message,
@@ -1902,6 +3048,64 @@ var _LedgerAdapter = class _LedgerAdapter {
1902
3048
  isNotAdvertising: isDeviceNotAdvertisingError(err),
1903
3049
  isStuckApp: isStuckAppStateError(err)
1904
3050
  });
3051
+ const assertSessionCurrent = (message) => {
3052
+ if (this._sessions.get(resolvedConnectId) === sessionId) return;
3053
+ throw createHwkError({
3054
+ code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
3055
+ message
3056
+ });
3057
+ };
3058
+ if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
3059
+ await this._waitForDeviceConnect(signal);
3060
+ assertSessionCurrent("Ledger connection ended while waiting for unlock");
3061
+ if (walletCheck?.derived) walletCheck.verified = false;
3062
+ return this._runConnectorCall(
3063
+ resolvedConnectId,
3064
+ method,
3065
+ effectiveParams,
3066
+ signal,
3067
+ fingerprint,
3068
+ permissionDeviceId,
3069
+ commonParams,
3070
+ installContext,
3071
+ operationId,
3072
+ lockedRetryBudget - 1
3073
+ );
3074
+ }
3075
+ if (businessCallStarted && isStuckAppStateError(err)) {
3076
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
3077
+ assertSessionCurrent("Ledger connection ended during the app transition");
3078
+ try {
3079
+ const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
3080
+ if (walletCheck) walletCheck.derived = true;
3081
+ return retried;
3082
+ } catch (retryErr) {
3083
+ if (isStuckAppStateError(retryErr)) throw err;
3084
+ if (isLostConnectionError(retryErr)) {
3085
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3086
+ else {
3087
+ this._sessions.delete(resolvedConnectId);
3088
+ this._discoveredDevices.delete(resolvedConnectId);
3089
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3090
+ }
3091
+ const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
3092
+ throw createHwkError({
3093
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
3094
+ message: `Ledger ${method} may have completed before the connection was lost`,
3095
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3096
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3097
+ });
3098
+ }
3099
+ throw retryErr;
3100
+ }
3101
+ }
3102
+ if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
3103
+ this._sessions.delete(resolvedConnectId);
3104
+ this._sessionTransports.delete(sessionId);
3105
+ this._discoveredDevices.delete(resolvedConnectId);
3106
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3107
+ throw err;
3108
+ }
1905
3109
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
1906
3110
  const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
1907
3111
  if (autoInstallApp && isAppMissing) {
@@ -1918,7 +3122,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1918
3122
  appName
1919
3123
  });
1920
3124
  }
1921
- const confirmed = await this._waitForInstallAppConfirm(appName);
3125
+ const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1922
3126
  if (!confirmed) {
1923
3127
  throw createHwkError({
1924
3128
  code: HardwareErrorCode3.UserAborted,
@@ -1957,162 +3161,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1957
3161
  fingerprint,
1958
3162
  permissionDeviceId,
1959
3163
  commonParams,
1960
- installContext
1961
- );
1962
- }
1963
- }
1964
- if (isStuckAppStateError(err)) {
1965
- try {
1966
- this._sessions.delete(resolvedConnectId);
1967
- this._discoveredDevices.delete(resolvedConnectId);
1968
- this.connector.reset?.();
1969
- } catch {
1970
- }
1971
- debugLog(
1972
- "[LedgerAdapter] stuck-app retry: method=",
1973
- method,
1974
- "delayMs=",
1975
- _LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
1976
- "_tag=",
1977
- err?._tag
1978
- );
1979
- try {
1980
- const retryResult = await this._retryAfterStuckApp(
1981
- resolvedConnectId,
1982
- method,
1983
- effectiveParams,
1984
- signal,
1985
- err,
1986
- fingerprint
1987
- );
1988
- debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
1989
- return retryResult;
1990
- } catch (retryErr) {
1991
- if (signal.aborted) throw retryErr;
1992
- if (isStuckAppStateError(retryErr)) {
1993
- debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
1994
- throw err;
1995
- }
1996
- debugLog(
1997
- "[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
1998
- method,
1999
- "retryErrTag=",
2000
- retryErr?._tag
3164
+ installContext,
3165
+ operationId
2001
3166
  );
2002
- throw retryErr;
2003
3167
  }
2004
3168
  }
2005
- if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
2006
- let lastErr = err;
2007
- for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
2008
- if (signal.aborted) throw lastErr;
2009
- try {
2010
- this._sessions.delete(resolvedConnectId);
2011
- this._discoveredDevices.delete(resolvedConnectId);
2012
- if (isDeviceDisconnectedError(lastErr)) {
2013
- try {
2014
- this.connector.reset?.();
2015
- } catch {
2016
- }
2017
- }
2018
- const reConnectId = await this.ensureConnected(
2019
- resolvedConnectId,
2020
- signal,
2021
- allowUsbEphemeralFallback
2022
- );
2023
- const reSessionId = this._sessions.get(reConnectId);
2024
- if (!reSessionId) throw lastErr;
2025
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2026
- const fp = await this._abortable(
2027
- signal,
2028
- this._verifyDeviceFingerprintWithSession(
2029
- reSessionId,
2030
- fingerprint.deviceId,
2031
- fingerprint.chain
2032
- )
2033
- );
2034
- if (!fp.success) {
2035
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2036
- code: HardwareErrorCode3.DeviceMismatch
2037
- });
2038
- }
2039
- }
2040
- return await this._callConnector(reSessionId, method, effectiveParams, signal);
2041
- } catch (retryErr) {
2042
- if (signal.aborted) throw retryErr;
2043
- lastErr = retryErr;
2044
- const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
2045
- if (!canRetry) {
2046
- throw retryErr;
2047
- }
2048
- }
2049
- }
2050
- throw lastErr;
2051
- }
2052
- if (isTimeoutError(err)) {
2053
- debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
2054
- this._discoveredDevices.delete(resolvedConnectId);
2055
- return this._retryWithFreshConnection(
2056
- resolvedConnectId,
2057
- method,
2058
- effectiveParams,
2059
- signal,
2060
- err,
2061
- fingerprint
2062
- );
2063
- }
2064
- if (isConnectionLevelError(err)) {
2065
- debugLog("[LedgerAdapter] connection-level fail-closed reset");
2066
- this._sessions.delete(resolvedConnectId);
2067
- this._discoveredDevices.delete(resolvedConnectId);
2068
- this.connector.reset();
2069
- const codeNum = err?.code;
2070
- throw Object.assign(err, {
2071
- code: codeNum ?? HardwareErrorCode3.DeviceDisconnected
2072
- });
2073
- }
2074
- throw err;
2075
- }
2076
- }
2077
- /**
2078
- * Stuck-app recovery: pause for the device's UI transition, then retry once.
2079
- *
2080
- * Caller has already cleared the session + reset connector. We wait so Stax
2081
- * finishes its post-CloseApp animation, then go through ensureConnected +
2082
- * fingerprint check + call exactly once. Caller decides what to do on a
2083
- * second stuck-app hit.
2084
- */
2085
- async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
2086
- await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
2087
- const retryConnectId = await this.ensureConnected(
2088
- resolvedConnectId,
2089
- signal,
2090
- !!fingerprint?.deviceId && !fingerprint.skipFingerprint
2091
- );
2092
- const retrySessionId = this._sessions.get(retryConnectId);
2093
- if (!retrySessionId) throw originalErr;
2094
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2095
- const fp = await this._abortable(
2096
- signal,
2097
- this._verifyDeviceFingerprintWithSession(
2098
- retrySessionId,
2099
- fingerprint.deviceId,
2100
- fingerprint.chain
2101
- )
2102
- );
2103
- if (!fp.success) {
2104
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2105
- code: HardwareErrorCode3.DeviceMismatch
2106
- });
2107
- }
2108
- }
2109
- return this._callConnector(retrySessionId, method, params, signal);
2110
- }
2111
- _sleepAbortable(ms, signal) {
2112
- return new Promise((resolve, reject) => {
2113
- if (signal.aborted) {
2114
- reject(signal.reason ?? new Error("Aborted"));
2115
- return;
3169
+ throw err;
3170
+ }
3171
+ }
3172
+ _sleepAbortable(ms, signal) {
3173
+ return new Promise((resolve, reject) => {
3174
+ if (signal.aborted) {
3175
+ reject(signal.reason ?? new Error("Aborted"));
3176
+ return;
2116
3177
  }
2117
3178
  const timer = setTimeout(() => {
2118
3179
  signal.removeEventListener("abort", onAbort);
@@ -2126,111 +3187,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2126
3187
  });
2127
3188
  }
2128
3189
  /**
2129
- * Clear stale session, reconnect, and retry the call.
2130
- *
2131
- * Timeout recovery starts with a full connector reset. After an APDU
2132
- * timeout, DMK/transport state may still emit malformed responses; retrying
2133
- * on the same DMK can poison the next chain switch.
2134
- */
2135
- async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
2136
- this.connector.reset();
2137
- this._sessions.clear();
2138
- this._discoveredDevices.clear();
2139
- this._connectingPromise = null;
2140
- const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
2141
- const retryConnectId = await this.ensureConnected(
2142
- targetConnectId,
2143
- signal,
2144
- allowUsbEphemeralFallback
2145
- );
2146
- const retrySessionId = this._sessions.get(retryConnectId);
2147
- if (!retrySessionId) {
2148
- throw originalErr;
2149
- }
2150
- try {
2151
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2152
- const fp = await this._abortable(
2153
- signal,
2154
- this._verifyDeviceFingerprintWithSession(
2155
- retrySessionId,
2156
- fingerprint.deviceId,
2157
- fingerprint.chain
2158
- )
2159
- );
2160
- if (!fp.success) {
2161
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2162
- code: HardwareErrorCode3.DeviceMismatch
2163
- });
2164
- }
2165
- }
2166
- return await this._callConnector(retrySessionId, method, params, signal);
2167
- } catch (retryErr) {
2168
- if (signal.aborted) throw retryErr;
2169
- this.connector.reset();
2170
- this._sessions.clear();
2171
- this._discoveredDevices.clear();
2172
- this._connectingPromise = null;
2173
- if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
2174
- throw retryErr;
2175
- }
2176
- debugLog(
2177
- "[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
2178
- );
2179
- this.connector.reset();
2180
- this._sessions.clear();
2181
- this._discoveredDevices.clear();
2182
- this._connectingPromise = null;
2183
- const finalConnectId = await this.ensureConnected(
2184
- targetConnectId,
2185
- signal,
2186
- allowUsbEphemeralFallback
2187
- );
2188
- const finalSessionId = this._sessions.get(finalConnectId);
2189
- if (!finalSessionId) {
2190
- throw originalErr;
2191
- }
2192
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2193
- const fp = await this._abortable(
2194
- signal,
2195
- this._verifyDeviceFingerprintWithSession(
2196
- finalSessionId,
2197
- fingerprint.deviceId,
2198
- fingerprint.chain
2199
- )
2200
- );
2201
- if (!fp.success) {
2202
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2203
- code: HardwareErrorCode3.DeviceMismatch
2204
- });
2205
- }
2206
- }
2207
- return this._callConnector(finalSessionId, method, params, signal);
2208
- }
2209
- }
2210
- /**
2211
- * Ensure OS-level device permission (Bluetooth / USB) before proceeding.
2212
- *
2213
- * Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
2214
- * `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
2215
- * prompt → user tap" plus a generous margin). If the consumer never wires
2216
- * a handler or never replies, the wait times out and the operation fails
2217
- * fast so scanners/callers don't hang silently.
2218
- *
2219
- * - No connectId (searchDevices): environment-level permission
2220
- * - With connectId (business methods): device-level permission
3190
+ * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3191
+ * replies. Without connectId the request is environment-level, else device-level.
2221
3192
  */
2222
3193
  async _ensureDevicePermission(connectId, deviceId, signal) {
2223
3194
  if (signal?.aborted) {
2224
3195
  _LedgerAdapter._throwIfAborted(signal);
2225
3196
  }
2226
3197
  const transportType = this.activeTransport ?? "hid";
3198
+ const operationId = this._activeOperationId();
2227
3199
  const waitPromise = this._uiRegistry.wait(
2228
3200
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2229
- { timeoutMs: 6e4 }
3201
+ { timeoutMs: 6e4, operationId }
2230
3202
  );
2231
3203
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2232
3204
  type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2233
- payload: { transportType, connectId, deviceId }
3205
+ payload: { transportType, connectId, deviceId, operationId }
2234
3206
  });
2235
3207
  let response;
2236
3208
  const onAbort = () => {
@@ -2276,7 +3248,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2276
3248
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
2277
3249
  const e = err;
2278
3250
  const params = e.code === HardwareErrorCode3.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
2279
- return ledgerFailure(e.code, e.message ?? "Unknown error", e.appName, tag, params);
3251
+ return ledgerFailure(
3252
+ e.code,
3253
+ e.message ?? "Unknown error",
3254
+ e.appName,
3255
+ tag,
3256
+ params,
3257
+ void 0,
3258
+ isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
3259
+ );
2280
3260
  }
2281
3261
  const mapped = mapLedgerError(err);
2282
3262
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -2303,7 +3283,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2303
3283
  deviceId: device.deviceId,
2304
3284
  connectId: device.connectId,
2305
3285
  label: device.name,
2306
- connectionType: this.connector.connectionType,
3286
+ connectionType: device.connectionType ?? this.connector.connectionType,
2307
3287
  rssi: device.rssi,
2308
3288
  isConnectable: device.isConnectable,
2309
3289
  serialNumber: device.serialNumber,
@@ -2329,8 +3309,9 @@ var LedgerAdapter = _LedgerAdapter;
2329
3309
 
2330
3310
  // src/connector/LedgerConnectorBase.ts
2331
3311
  import {
2332
- EConnectorInteraction as EConnectorInteraction4,
2333
- HardwareErrorCode as HardwareErrorCode8,
3312
+ EConnectorInteraction as EConnectorInteraction3,
3313
+ HardwareErrorCode as HardwareErrorCode7,
3314
+ createHwkError as createHwkError2,
2334
3315
  isKnownNonTargetHardwareVendor,
2335
3316
  serializeConnectorError
2336
3317
  } from "@onekeyfe/hwk-adapter-core";
@@ -2603,7 +3584,7 @@ var LedgerDeviceManager = class {
2603
3584
 
2604
3585
  // src/signer/SignerManager.ts
2605
3586
  import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
2606
- import { ContextModuleBuilder } from "@ledgerhq/context-module";
3587
+ import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
2607
3588
 
2608
3589
  // src/signer/SignerEth.ts
2609
3590
  import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
@@ -2611,11 +3592,15 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
2611
3592
  // src/signer/deviceActionToPromise.ts
2612
3593
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
2613
3594
  var IDLE_WATCHDOG_MS = 65e3;
3595
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3596
+ var INTERACTION_PROMPT_DELAY_MS = 500;
2614
3597
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
2615
3598
  return new Promise((resolve, reject) => {
2616
3599
  let settled = false;
2617
3600
  let lastStep;
2618
3601
  let activeInteraction;
3602
+ let pendingInteraction;
3603
+ let pendingInteractionTimer = null;
2619
3604
  const observedSteps = [];
2620
3605
  let sub;
2621
3606
  let timer = null;
@@ -2643,31 +3628,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
2643
3628
  }
2644
3629
  return false;
2645
3630
  };
3631
+ const cancelPendingInteraction = () => {
3632
+ if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
3633
+ pendingInteractionTimer = null;
3634
+ pendingInteraction = void 0;
3635
+ };
3636
+ const showInteraction = (interactionName) => {
3637
+ activeInteraction = interactionName;
3638
+ debugLog(
3639
+ "[DeviceAction] requiredUserInteraction",
3640
+ `interaction=${interactionName}`,
3641
+ `step=${lastStep ?? "unknown"}`
3642
+ );
3643
+ if (interactionName === "unlock-device" && timer) {
3644
+ clearTimeout(timer);
3645
+ timer = null;
3646
+ }
3647
+ onInteraction?.(interactionName);
3648
+ };
2646
3649
  const emitInteraction = (interaction) => {
2647
3650
  if (!onInteraction) {
2648
3651
  return;
2649
3652
  }
2650
3653
  if (!interaction || interaction === "none") {
3654
+ cancelPendingInteraction();
2651
3655
  clearActiveInteraction();
2652
3656
  return;
2653
3657
  }
2654
3658
  const interactionName = String(interaction);
2655
- if (interactionName === activeInteraction) {
3659
+ if (interactionName === activeInteraction || interactionName === pendingInteraction) {
2656
3660
  return;
2657
3661
  }
2658
- activeInteraction = interactionName;
2659
- debugLog(
2660
- "[DeviceAction] requiredUserInteraction",
2661
- `interaction=${interactionName}`,
2662
- `step=${lastStep ?? "unknown"}`
2663
- );
2664
- if (interaction === "unlock-device" && timer) {
2665
- clearTimeout(timer);
2666
- timer = null;
3662
+ cancelPendingInteraction();
3663
+ clearActiveInteraction();
3664
+ if (interactionName === "unlock-device") {
3665
+ showInteraction(interactionName);
3666
+ return;
2667
3667
  }
2668
- onInteraction(interactionName);
3668
+ pendingInteraction = interactionName;
3669
+ pendingInteractionTimer = setTimeout(() => {
3670
+ pendingInteractionTimer = null;
3671
+ pendingInteraction = void 0;
3672
+ if (!settled) showInteraction(interactionName);
3673
+ }, INTERACTION_PROMPT_DELAY_MS);
2669
3674
  };
2670
3675
  const completeInteraction = () => {
3676
+ cancelPendingInteraction();
2671
3677
  if (!clearActiveInteraction()) {
2672
3678
  onInteraction?.("interaction-complete");
2673
3679
  }
@@ -2798,7 +3804,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
2798
3804
  }
2799
3805
 
2800
3806
  // src/signer/SignerEth.ts
2801
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2802
3807
  var SignerEth = class {
2803
3808
  // eslint-disable-next-line no-useless-constructor, no-empty-function
2804
3809
  constructor(_sdk) {
@@ -2869,7 +3874,7 @@ var SignerManager = class _SignerManager {
2869
3874
  return (args) => new SignerEthBuilder(args);
2870
3875
  }
2871
3876
  static _createContextModule() {
2872
- const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
3877
+ const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2873
3878
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
2874
3879
  }
2875
3880
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -2907,6 +3912,27 @@ function collapseSignerInteraction(interaction) {
2907
3912
  return EConnectorInteraction2.ConfirmOnDevice;
2908
3913
  }
2909
3914
  }
3915
+ function wireSignerToSession(ctx, sessionId, chain, signer) {
3916
+ signer.onInteraction = (interaction) => {
3917
+ debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3918
+ ctx.emit("ui-event", {
3919
+ type: collapseSignerInteraction(interaction),
3920
+ payload: { sessionId }
3921
+ });
3922
+ };
3923
+ signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3924
+ return signer;
3925
+ }
3926
+ async function runSignerCall(ctx, sessionId, call) {
3927
+ try {
3928
+ return await call();
3929
+ } catch (err) {
3930
+ ctx.invalidateSession(sessionId);
3931
+ throw ctx.wrapError(err);
3932
+ } finally {
3933
+ ctx.clearCanceller(sessionId);
3934
+ }
3935
+ }
2910
3936
 
2911
3937
  // src/connector/chains/evm.ts
2912
3938
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3007,14 +4033,13 @@ async function _getEthSigner(ctx, sessionId) {
3007
4033
 
3008
4034
  // src/connector/chains/btc.ts
3009
4035
  import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
3010
- import { Psbt } from "bitcoinjs-lib";
4036
+ import { Psbt as Psbt2 } from "bitcoinjs-lib";
3011
4037
 
3012
4038
  // src/signer/SignerBtc.ts
3013
4039
  import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
3014
4040
  function hexToUtf8(hex) {
3015
4041
  return new TextDecoder().decode(hexToBytes2(hex));
3016
4042
  }
3017
- var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3018
4043
  var SignerBtc = class {
3019
4044
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3020
4045
  constructor(_sdk) {
@@ -3028,7 +4053,7 @@ var SignerBtc = class {
3028
4053
  return deviceActionToPromise(
3029
4054
  action,
3030
4055
  this.onInteraction,
3031
- void 0,
4056
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3032
4057
  this.onRegisterCanceller
3033
4058
  );
3034
4059
  }
@@ -3046,14 +4071,14 @@ var SignerBtc = class {
3046
4071
  const result = await deviceActionToPromise(
3047
4072
  action,
3048
4073
  this.onInteraction,
3049
- void 0,
4074
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3050
4075
  this.onRegisterCanceller
3051
4076
  );
3052
4077
  debugLog(
3053
4078
  "[SignerBtc] getExtendedPublicKey result type:",
3054
4079
  typeof result,
3055
4080
  "value:",
3056
- typeof result === "string" ? `${result.substring(0, 20)}...` : JSON.stringify(result).substring(0, 50)
4081
+ summarizeForLog(result)
3057
4082
  );
3058
4083
  if (typeof result === "string") return result;
3059
4084
  return result.extendedPublicKey;
@@ -3082,7 +4107,7 @@ var SignerBtc = class {
3082
4107
  return deviceActionToPromise(
3083
4108
  action,
3084
4109
  this.onInteraction,
3085
- INTERACTIVE_TIMEOUT_MS2,
4110
+ INTERACTIVE_TIMEOUT_MS,
3086
4111
  this.onRegisterCanceller
3087
4112
  );
3088
4113
  }
@@ -3095,7 +4120,7 @@ var SignerBtc = class {
3095
4120
  return deviceActionToPromise(
3096
4121
  action,
3097
4122
  this.onInteraction,
3098
- INTERACTIVE_TIMEOUT_MS2,
4123
+ INTERACTIVE_TIMEOUT_MS,
3099
4124
  this.onRegisterCanceller
3100
4125
  );
3101
4126
  }
@@ -3108,7 +4133,7 @@ var SignerBtc = class {
3108
4133
  return deviceActionToPromise(
3109
4134
  action,
3110
4135
  this.onInteraction,
3111
- INTERACTIVE_TIMEOUT_MS2,
4136
+ INTERACTIVE_TIMEOUT_MS,
3112
4137
  this.onRegisterCanceller
3113
4138
  );
3114
4139
  }
@@ -3131,7 +4156,21 @@ function _purposeToTemplate(purpose, DDT) {
3131
4156
  });
3132
4157
  }
3133
4158
  }
4159
+ function assertBitcoinMainnet(coin) {
4160
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4161
+ throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4162
+ code: HardwareErrorCode5.ChainNotSupported
4163
+ });
4164
+ }
4165
+ }
3134
4166
  async function btcGetAddress(ctx, sessionId, params) {
4167
+ assertBitcoinMainnet(params.coin);
4168
+ if (normalizePath(params.path).split("/").length !== 3) {
4169
+ throw Object.assign(
4170
+ new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4171
+ { code: HardwareErrorCode5.InvalidParams }
4172
+ );
4173
+ }
3135
4174
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3136
4175
  const path = normalizePath(params.path);
3137
4176
  try {
@@ -3162,6 +4201,7 @@ async function btcGetAddress(ctx, sessionId, params) {
3162
4201
  }
3163
4202
  }
3164
4203
  async function btcGetPublicKey(ctx, sessionId, params) {
4204
+ assertBitcoinMainnet(params.coin);
3165
4205
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3166
4206
  const path = normalizePath(params.path);
3167
4207
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -3169,7 +4209,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
3169
4209
  const xpub = await btcSigner.getExtendedPublicKey(path, {
3170
4210
  checkOnDevice: params.showOnDevice ?? false
3171
4211
  });
3172
- debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", `${xpub?.substring(0, 20)}...`);
4212
+ debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
3173
4213
  return { xpub, path: params.path };
3174
4214
  } catch (err) {
3175
4215
  debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
@@ -3290,7 +4330,7 @@ function _isScriptPathInput(input) {
3290
4330
  return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
3291
4331
  }
3292
4332
  function _applySignaturesToPsbt(psbtHex, signatures) {
3293
- const psbt = Psbt.fromHex(psbtHex);
4333
+ const psbt = Psbt2.fromHex(psbtHex);
3294
4334
  for (const sig of signatures) {
3295
4335
  const input = psbt.data.inputs[sig.inputIndex];
3296
4336
  if (!input) {
@@ -3339,7 +4379,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
3339
4379
  }
3340
4380
 
3341
4381
  // src/connector/chains/sol.ts
3342
- import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
4382
+ import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
4383
+ import bs58 from "bs58";
3343
4384
 
3344
4385
  // src/signer/SignerSol.ts
3345
4386
  var SignerSol = class {
@@ -3357,7 +4398,7 @@ var SignerSol = class {
3357
4398
  return deviceActionToPromise(
3358
4399
  action,
3359
4400
  this.onInteraction,
3360
- void 0,
4401
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3361
4402
  this.onRegisterCanceller
3362
4403
  );
3363
4404
  }
@@ -3369,7 +4410,7 @@ var SignerSol = class {
3369
4410
  return deviceActionToPromise(
3370
4411
  action,
3371
4412
  this.onInteraction,
3372
- void 0,
4413
+ INTERACTIVE_TIMEOUT_MS,
3373
4414
  this.onRegisterCanceller
3374
4415
  );
3375
4416
  }
@@ -3382,7 +4423,7 @@ var SignerSol = class {
3382
4423
  return deviceActionToPromise(
3383
4424
  action,
3384
4425
  this.onInteraction,
3385
- void 0,
4426
+ INTERACTIVE_TIMEOUT_MS,
3386
4427
  this.onRegisterCanceller
3387
4428
  );
3388
4429
  }
@@ -3423,8 +4464,21 @@ async function solSignMessage(ctx, sessionId, params) {
3423
4464
  const path = normalizePath(params.path);
3424
4465
  const messageBytes = hexToBytes3(params.message);
3425
4466
  try {
4467
+ if (params.messageVersion === 1) {
4468
+ const preparedMessage = prepareSolanaOffchainMessageV1({
4469
+ message: messageBytes,
4470
+ requiredSigners: params.requiredSigners
4471
+ });
4472
+ const { SignMessageVersion } = await ctx.importLedgerKit(
4473
+ "@ledgerhq/device-signer-kit-solana"
4474
+ );
4475
+ const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4476
+ version: SignMessageVersion.Raw
4477
+ });
4478
+ return { signature: decodeBase58Signature(result2.signature) };
4479
+ }
3426
4480
  const result = await solSigner.signMessage(path, messageBytes);
3427
- return { signature: result.signature };
4481
+ return { signature: decodeBase58EnvelopeSignature(result.signature) };
3428
4482
  } catch (err) {
3429
4483
  ctx.invalidateSession(sessionId);
3430
4484
  throw ctx.wrapError(err);
@@ -3432,11 +4486,27 @@ async function solSignMessage(ctx, sessionId, params) {
3432
4486
  ctx.clearCanceller(sessionId);
3433
4487
  }
3434
4488
  }
4489
+ function decodeBase58Signature(signature) {
4490
+ const bytes = bs58.decode(signature);
4491
+ if (bytes.length !== 64) {
4492
+ throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4493
+ }
4494
+ return bytesToHex(bytes);
4495
+ }
4496
+ function decodeBase58EnvelopeSignature(envelope) {
4497
+ const bytes = bs58.decode(envelope);
4498
+ if (bytes.length < 65 || bytes[0] !== 1) {
4499
+ throw new Error("Ledger Solana signature envelope is invalid");
4500
+ }
4501
+ return bytesToHex(bytes.subarray(1, 65));
4502
+ }
3435
4503
  async function _createSolSigner(ctx, sessionId) {
3436
4504
  const dmk = await ctx.getOrCreateDmk();
3437
- const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4505
+ const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4506
+ "@ledgerhq/context-module"
4507
+ );
3438
4508
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
3439
- const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4509
+ const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3440
4510
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
3441
4511
  const signer = new SignerSol(sdkSigner);
3442
4512
  signer.onInteraction = (interaction) => {
@@ -3452,361 +4522,147 @@ async function _createSolSigner(ctx, sessionId) {
3452
4522
  return signer;
3453
4523
  }
3454
4524
 
3455
- // src/connector/chains/tron.ts
3456
- import { HardwareErrorCode as HardwareErrorCode7 } from "@onekeyfe/hwk-adapter-core";
3457
- import Trx from "@ledgerhq/hw-app-trx";
3458
-
3459
- // src/connector/chains/legacyChainCall.ts
3460
- import { EConnectorInteraction as EConnectorInteraction3 } from "@onekeyfe/hwk-adapter-core";
4525
+ // src/connector/chains/zcash.ts
4526
+ import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
3461
4527
 
3462
- // src/app/AppManager.ts
3463
- import {
3464
- CloseAppCommand,
3465
- GetAppAndVersionCommand,
3466
- OpenAppCommand,
3467
- isSuccessCommandResult
3468
- } from "@ledgerhq/device-management-kit";
3469
- import { HardwareErrorCode as HardwareErrorCode6 } from "@onekeyfe/hwk-adapter-core";
3470
- var APP_NAME_MAP = {
3471
- ETH: "Ethereum",
3472
- BTC: "Bitcoin",
3473
- SOL: "Solana",
3474
- TRX: "Tron",
3475
- XRP: "XRP",
3476
- ADA: "Cardano",
3477
- DOT: "Polkadot",
3478
- ATOM: "Cosmos"
3479
- };
3480
- var DASHBOARD_APP_NAME = "BOLOS";
3481
- var AppManager = class {
3482
- constructor(dmk, options) {
3483
- this._dmk = dmk;
3484
- this._waitMs = options?.waitMs ?? 1e3;
3485
- this._maxRetries = options?.maxRetries ?? 10;
3486
- }
3487
- /**
3488
- * Return the Ledger app name for a given chain ticker,
3489
- * or undefined if the chain is not supported.
3490
- */
3491
- static getAppName(chain) {
3492
- return APP_NAME_MAP[chain];
3493
- }
3494
- /**
3495
- * Ensure the target app is open on the device identified by `sessionId`.
3496
- *
3497
- * Flow:
3498
- * 1. Check the currently running app.
3499
- * 2. If it is already the target, return immediately.
3500
- * 3. If a different app is running (not dashboard), close it first.
3501
- * 4. Open the target app.
3502
- * 5. Poll until the device confirms the target app is running.
3503
- */
3504
- /**
3505
- * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
3506
- * device is about to display "Open <app>" on screen and wait for the
3507
- * user's button press. UI consumers should show their "open app" prompt
3508
- * in response. NOT called when the target app is already open (no user
3509
- * interaction needed in that case).
3510
- *
3511
- * Important: OpenAppCommand is blocking. It does not resolve until the user
3512
- * has physically confirmed on the device, so anything that runs AFTER
3513
- * `await this._openApp(...)` lands AFTER the prompt is already gone.
3514
- * Hence the callback must fire BEFORE that await.
3515
- */
3516
- async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
3517
- const currentApp = await this._getCurrentApp(sessionId);
3518
- if (currentApp === targetAppName) {
3519
- return;
3520
- }
3521
- if (!this._isDashboard(currentApp)) {
3522
- await this._closeCurrentApp(sessionId);
3523
- await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
3524
- }
3525
- onConfirmOnDevice?.();
3526
- await this._openApp(sessionId, targetAppName);
3527
- await this._waitForApp(sessionId, targetAppName);
4528
+ // src/signer/SignerZcash.ts
4529
+ var SignerZcash = class {
4530
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4531
+ constructor(_sdk) {
4532
+ this._sdk = _sdk;
3528
4533
  }
3529
- // ---------------------------------------------------------------------------
3530
- // Private helpers
3531
- // ---------------------------------------------------------------------------
3532
- async _getCurrentApp(sessionId) {
3533
- const result = await this._dmk.sendCommand({
3534
- sessionId,
3535
- command: new GetAppAndVersionCommand()
3536
- });
3537
- if (isSuccessCommandResult(result)) {
3538
- debugLog("[AppManager] currentApp:", result.data.name);
3539
- return result.data.name;
3540
- }
3541
- const errResult = result;
3542
- const dmkErr = errResult.error ?? {};
3543
- const original = dmkErr.originalError;
3544
- debugLog(
3545
- "[AppManager] _getCurrentApp failed sessionId=",
3546
- sessionId,
3547
- "tag=",
3548
- dmkErr._tag,
3549
- "errorCode=",
3550
- dmkErr.errorCode,
3551
- "message=",
3552
- dmkErr.message,
3553
- "originalErrorMessage=",
3554
- original?.message ?? String(original ?? "")
3555
- );
3556
- throw Object.assign(
3557
- new Error(
3558
- dmkErr.message ?? "Failed to get current app from device"
3559
- ),
3560
- {
3561
- _tag: dmkErr._tag,
3562
- errorCode: dmkErr.errorCode,
3563
- originalError: original
3564
- }
4534
+ /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4535
+ async getFullViewingKey(derivationPath, options) {
4536
+ const action = this._sdk.getFullViewingKey(derivationPath, options);
4537
+ return deviceActionToPromise(
4538
+ action,
4539
+ this.onInteraction,
4540
+ void 0,
4541
+ this.onRegisterCanceller
3565
4542
  );
3566
4543
  }
3567
- async _openApp(sessionId, appName) {
3568
- const result = await this._dmk.sendCommand({
3569
- sessionId,
3570
- command: new OpenAppCommand({ appName })
3571
- });
3572
- if (!isSuccessCommandResult(result)) {
3573
- const dmkErr = result.error;
3574
- const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
3575
- const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
3576
- debugLog(
3577
- "[AppManager] openApp failed:",
3578
- appName,
3579
- "errorCode:",
3580
- errorCode,
3581
- "tag:",
3582
- dmkErr._tag
3583
- );
3584
- let code;
3585
- if (errorCode === "6807" || /unknown application/i.test(message)) {
3586
- code = HardwareErrorCode6.AppNotInstalled;
3587
- } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
3588
- code = HardwareErrorCode6.UserRejected;
3589
- }
3590
- throw Object.assign(new Error(`Failed to open "${appName}"`), {
3591
- _tag: ERROR_TAG.OpenAppCommand,
3592
- code,
3593
- errorCode,
3594
- statusCode: errorCode,
3595
- appName,
3596
- originalError: dmkErr
3597
- });
3598
- }
3599
- }
3600
- async _closeCurrentApp(sessionId) {
3601
- debugLog("[AppManager] closeCurrentApp");
3602
- await this._dmk.sendCommand({
3603
- sessionId,
3604
- command: new CloseAppCommand()
3605
- });
3606
- }
3607
- /**
3608
- * Poll the device until the expected app is reported as running,
3609
- * or throw after `_maxRetries` attempts.
3610
- */
3611
- async _waitForApp(sessionId, expectedAppName) {
3612
- let lastSeen = "";
3613
- for (let i = 0; i < this._maxRetries; i++) {
3614
- await this._wait();
3615
- const current = await this._getCurrentApp(sessionId);
3616
- lastSeen = current;
3617
- if (current === expectedAppName) {
3618
- return;
3619
- }
3620
- }
3621
- debugLog(
3622
- "[AppManager] waitForApp exhausted: expected=",
3623
- expectedAppName,
3624
- "lastSeen=",
3625
- lastSeen
3626
- );
3627
- throw new Error(
3628
- `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
4544
+ /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4545
+ async getShieldedAddress(derivationPath, options) {
4546
+ const action = this._sdk.getShieldedAddress(derivationPath, options);
4547
+ return deviceActionToPromise(
4548
+ action,
4549
+ this.onInteraction,
4550
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4551
+ this.onRegisterCanceller
3629
4552
  );
3630
4553
  }
3631
- _isDashboard(appName) {
3632
- return appName === DASHBOARD_APP_NAME;
3633
- }
3634
- _wait() {
3635
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3636
- }
3637
4554
  };
3638
4555
 
3639
- // src/connector/chains/legacyChainCall.ts
3640
- function isLegacyWrongAppError(err, _appName) {
3641
- return isWrongAppError(err);
4556
+ // src/connector/chains/zcash.ts
4557
+ async function zcashGetFullViewingKey(ctx, sessionId, params) {
4558
+ const signer = await _createZcashSigner(ctx, sessionId);
4559
+ const path = normalizePath(params.path);
4560
+ const mode = params.mode ?? "ufvk";
4561
+ return runSignerCall(ctx, sessionId, async () => {
4562
+ const result = await signer.getFullViewingKey(path, { mode });
4563
+ if (result.mode === "ufvk") {
4564
+ return { path: params.path, mode, ufvk: result.fullViewingKey };
4565
+ }
4566
+ return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
4567
+ });
3642
4568
  }
3643
- async function withLegacyChainCall(ctx, sessionId, options, action) {
3644
- const { appName, needsConfirmation } = options;
3645
- let openAppPromptShown = false;
3646
- const onAppOpenPrompt = () => {
3647
- openAppPromptShown = true;
3648
- ctx.emit("ui-event", {
3649
- type: EConnectorInteraction3.ConfirmOpenApp,
3650
- payload: { sessionId }
4569
+ async function zcashGetShieldedAddress(ctx, sessionId, params) {
4570
+ const signer = await _createZcashSigner(ctx, sessionId);
4571
+ const path = normalizePath(params.path);
4572
+ return runSignerCall(ctx, sessionId, async () => {
4573
+ const result = await signer.getShieldedAddress(path, {
4574
+ checkOnDevice: params.showOnDevice ?? false
3651
4575
  });
3652
- };
3653
- const closeOpenAppUiIfShown = () => {
3654
- if (openAppPromptShown) {
3655
- ctx.emit("ui-event", {
3656
- type: EConnectorInteraction3.InteractionComplete,
3657
- payload: { sessionId }
3658
- });
3659
- openAppPromptShown = false;
3660
- }
3661
- };
3662
- try {
3663
- await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
3664
- } catch (err) {
3665
- debugLog(
3666
- "[LegacyChainCall] pre-flight ensureAppOpen failed:",
3667
- appName,
3668
- err?.message
3669
- );
3670
- closeOpenAppUiIfShown();
3671
- throw ctx.wrapError(err, { defaultAppName: appName });
3672
- }
3673
- const runOnce = async () => {
3674
- let confirmEmitted = false;
3675
- if (needsConfirmation) {
3676
- ctx.emit("ui-event", {
3677
- type: EConnectorInteraction3.ConfirmOnDevice,
3678
- payload: { sessionId }
3679
- });
3680
- confirmEmitted = true;
3681
- }
3682
- try {
3683
- return await action(sessionId);
3684
- } finally {
3685
- if (confirmEmitted || openAppPromptShown) {
3686
- ctx.emit("ui-event", {
3687
- type: EConnectorInteraction3.InteractionComplete,
3688
- payload: { sessionId }
3689
- });
3690
- openAppPromptShown = false;
3691
- }
3692
- }
3693
- };
3694
- try {
3695
- return await runOnce();
3696
- } catch (err) {
3697
- if (!isLegacyWrongAppError(err, appName)) {
3698
- debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
3699
- ctx.invalidateSession(sessionId);
3700
- throw ctx.wrapError(err, { defaultAppName: appName });
3701
- }
3702
- debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
3703
- try {
3704
- await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
3705
- } catch (switchErr) {
3706
- debugLog(
3707
- "[LegacyChainCall] retry ensureAppOpen failed:",
3708
- appName,
3709
- switchErr?.message
3710
- );
3711
- closeOpenAppUiIfShown();
3712
- throw ctx.wrapError(switchErr, { defaultAppName: appName });
3713
- }
3714
- ctx.clearAllSigners();
3715
- const result = await runOnce();
3716
- debugLog("[LegacyChainCall] retry succeeded:", appName);
3717
- return result;
3718
- }
4576
+ return { address: result.address, path: params.path };
4577
+ });
3719
4578
  }
3720
- async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4579
+ async function _createZcashSigner(ctx, sessionId) {
3721
4580
  const dmk = await ctx.getOrCreateDmk();
3722
- const appManager = new AppManager(dmk);
3723
- await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4581
+ const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4582
+ const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4583
+ return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3724
4584
  }
3725
4585
 
3726
- // src/transport/DmkTransport.ts
3727
- import Transport from "@ledgerhq/hw-transport";
3728
- var DmkTransport = class extends Transport {
3729
- constructor(dmk, sessionId) {
3730
- super();
3731
- this._dmk = dmk;
3732
- this._sessionId = sessionId;
4586
+ // src/connector/chains/tron.ts
4587
+ import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
4588
+
4589
+ // src/signer/SignerTron.ts
4590
+ var SignerTron = class {
4591
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4592
+ constructor(_sdk) {
4593
+ this._sdk = _sdk;
4594
+ }
4595
+ /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4596
+ async getAddress(derivationPath, options) {
4597
+ const action = this._sdk.getAddress(derivationPath, options);
4598
+ const result = await deviceActionToPromise(
4599
+ action,
4600
+ this.onInteraction,
4601
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4602
+ this.onRegisterCanceller
4603
+ );
4604
+ return { address: result.address, publicKey: result.publicKey };
3733
4605
  }
3734
- async exchange(apdu) {
3735
- const response = await this._dmk.sendApdu({
3736
- sessionId: this._sessionId,
3737
- apdu: new Uint8Array(apdu)
3738
- });
3739
- const { data, statusCode } = response;
3740
- const result = Buffer.alloc(data.length + 2);
3741
- if (data.length > 0) {
3742
- result.set(data, 0);
3743
- }
3744
- result.set(statusCode, data.length);
3745
- return result;
4606
+ /** Sign a protobuf-encoded raw transaction. */
4607
+ async signTransaction(derivationPath, transaction, options) {
4608
+ const action = this._sdk.signTransaction(derivationPath, transaction, options);
4609
+ return deviceActionToPromise(
4610
+ action,
4611
+ this.onInteraction,
4612
+ INTERACTIVE_TIMEOUT_MS,
4613
+ this.onRegisterCanceller
4614
+ );
3746
4615
  }
3747
- async close() {
4616
+ /** Sign a personal message (TIP-191). */
4617
+ async signPersonalMessage(derivationPath, message, options) {
4618
+ const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4619
+ return deviceActionToPromise(
4620
+ action,
4621
+ this.onInteraction,
4622
+ INTERACTIVE_TIMEOUT_MS,
4623
+ this.onRegisterCanceller
4624
+ );
3748
4625
  }
3749
4626
  };
3750
4627
 
3751
4628
  // src/connector/chains/tron.ts
3752
4629
  async function tronGetAddress(ctx, sessionId, params) {
4630
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3753
4631
  const path = normalizePath(params.path);
3754
- const showOnDevice = params.showOnDevice ?? false;
3755
- return withLegacyChainCall(
3756
- ctx,
3757
- sessionId,
3758
- {
3759
- appName: "Tron",
3760
- // Only show "confirm on device" UI when the device is actually going
3761
- // to display the address for the user to verify.
3762
- needsConfirmation: showOnDevice
3763
- },
3764
- async (sid) => {
3765
- const trx = await _createTrx(ctx, sid);
3766
- const result = await trx.getAddress(path, showOnDevice);
3767
- return { address: result.address, publicKey: result.publicKey, path: params.path };
3768
- }
3769
- );
4632
+ return runSignerCall(ctx, sessionId, async () => {
4633
+ const result = await tronSigner.getAddress(path, {
4634
+ checkOnDevice: params.showOnDevice ?? false
4635
+ });
4636
+ return { address: result.address, publicKey: result.publicKey, path: params.path };
4637
+ });
3770
4638
  }
3771
4639
  async function tronSignTransaction(ctx, sessionId, params) {
3772
4640
  if (!params.rawTxHex) {
3773
4641
  throw Object.assign(
3774
4642
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
3775
- { code: HardwareErrorCode7.InvalidParams }
4643
+ { code: HardwareErrorCode6.InvalidParams }
3776
4644
  );
3777
4645
  }
4646
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3778
4647
  const path = normalizePath(params.path);
3779
- return withLegacyChainCall(
3780
- ctx,
3781
- sessionId,
3782
- { appName: "Tron", needsConfirmation: true },
3783
- async (sid) => {
3784
- const trx = await _createTrx(ctx, sid);
3785
- const signature = await trx.signTransaction(
3786
- path,
3787
- params.rawTxHex,
3788
- params.tokenSignatures ?? []
3789
- );
3790
- return { signature };
3791
- }
3792
- );
4648
+ return runSignerCall(ctx, sessionId, async () => {
4649
+ const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
4650
+ return { signature: bytesToHex3(signature) };
4651
+ });
3793
4652
  }
3794
4653
  async function tronSignMessage(ctx, sessionId, params) {
4654
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3795
4655
  const path = normalizePath(params.path);
3796
- return withLegacyChainCall(
3797
- ctx,
3798
- sessionId,
3799
- { appName: "Tron", needsConfirmation: true },
3800
- async (sid) => {
3801
- const trx = await _createTrx(ctx, sid);
3802
- const signature = await trx.signPersonalMessage(path, params.messageHex);
3803
- return { signature };
3804
- }
3805
- );
4656
+ return runSignerCall(ctx, sessionId, async () => {
4657
+ const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
4658
+ return { signature: bytesToHex3(signature) };
4659
+ });
3806
4660
  }
3807
- async function _createTrx(ctx, sessionId) {
4661
+ async function _createTronSigner(ctx, sessionId) {
3808
4662
  const dmk = await ctx.getOrCreateDmk();
3809
- return new Trx(new DmkTransport(dmk, sessionId));
4663
+ const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4664
+ const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4665
+ return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3810
4666
  }
3811
4667
 
3812
4668
  // src/device-apps/customActions.ts
@@ -3985,7 +4841,7 @@ var DeviceApps = class {
3985
4841
  seTargetId: v.seTargetId,
3986
4842
  mcuTargetId: v.mcuTargetId,
3987
4843
  seVersion: v.seVersion,
3988
- seFlagsHex: bytesToHex2(v.seFlags),
4844
+ seFlagsHex: bytesToHex4(v.seFlags),
3989
4845
  mcuSephVersion: v.mcuSephVersion,
3990
4846
  mcuBootloaderVersion: v.mcuBootloaderVersion,
3991
4847
  hwVersion: v.hwVersion
@@ -4059,7 +4915,7 @@ var DeviceApps = class {
4059
4915
  }
4060
4916
  }
4061
4917
  };
4062
- function bytesToHex2(bytes) {
4918
+ function bytesToHex4(bytes) {
4063
4919
  if (!bytes) return "";
4064
4920
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4065
4921
  }
@@ -4102,10 +4958,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
4102
4958
  evm: "Ethereum",
4103
4959
  btc: "Bitcoin",
4104
4960
  sol: "Solana",
4105
- tron: "Tron"
4961
+ tron: "Tron",
4962
+ zcash: "Zcash"
4106
4963
  };
4107
4964
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4108
- Object.values(HardwareErrorCode8).filter((value) => typeof value === "number")
4965
+ Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4109
4966
  );
4110
4967
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4111
4968
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4142,6 +4999,10 @@ async function defaultLedgerKitImporter(pkg) {
4142
4999
  return import("@ledgerhq/device-signer-kit-bitcoin");
4143
5000
  case "@ledgerhq/device-signer-kit-solana":
4144
5001
  return import("@ledgerhq/device-signer-kit-solana");
5002
+ case "@ledgerhq/device-signer-kit-tron":
5003
+ return import("@ledgerhq/device-signer-kit-tron");
5004
+ case "@ledgerhq/device-signer-kit-zcash":
5005
+ return import("@ledgerhq/device-signer-kit-zcash");
4145
5006
  case "@ledgerhq/context-module":
4146
5007
  return import("@ledgerhq/context-module");
4147
5008
  default:
@@ -4201,6 +5062,7 @@ var LedgerConnectorBase = class {
4201
5062
  this._ctx = {
4202
5063
  emit: (event, data) => this._emit(event, data),
4203
5064
  invalidateSession: (sid) => this._invalidateSession(sid),
5065
+ teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4204
5066
  wrapError: (err, opts) => this._wrapError(err, opts),
4205
5067
  getOrCreateDmk: () => this._getOrCreateDmk(),
4206
5068
  getDeviceManager: () => this._getDeviceManager(),
@@ -4300,7 +5162,7 @@ var LedgerConnectorBase = class {
4300
5162
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
4301
5163
  );
4302
5164
  err._tag = ERROR_TAG.BlePairingTimeout;
4303
- err.code = HardwareErrorCode8.BlePairingTimeout;
5165
+ err.code = HardwareErrorCode7.BlePairingTimeout;
4304
5166
  reject(err);
4305
5167
  }, HANG_CEILING_MS);
4306
5168
  });
@@ -4333,7 +5195,7 @@ var LedgerConnectorBase = class {
4333
5195
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
4334
5196
  );
4335
5197
  err._tag = ERROR_TAG.DeviceNotAdvertising;
4336
- err.code = HardwareErrorCode8.DeviceNotFound;
5198
+ err.code = HardwareErrorCode7.DeviceNotFound;
4337
5199
  throw err;
4338
5200
  };
4339
5201
  const doConnect = async (path) => {
@@ -4389,15 +5251,22 @@ var LedgerConnectorBase = class {
4389
5251
  } catch (err) {
4390
5252
  this._resetSignersAndSessions();
4391
5253
  if (isLedgerBleConnectionType(this.connectionType)) {
5254
+ if (isBleBondInvalidError(err)) {
5255
+ throw createHwkError2({
5256
+ code: HardwareErrorCode7.BleBondInvalid,
5257
+ message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
5258
+ _tag: ERROR_TAG.PeerRemovedPairing
5259
+ });
5260
+ }
4392
5261
  const tag = err?._tag;
4393
- if (isKnownConnectionTag(tag)) {
5262
+ if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4394
5263
  throw err;
4395
5264
  }
4396
5265
  const wrapped = new Error(
4397
5266
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
4398
5267
  );
4399
5268
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
4400
- wrapped.code = HardwareErrorCode8.BlePairingTimeout;
5269
+ wrapped.code = HardwareErrorCode7.BlePairingTimeout;
4401
5270
  wrapped.originalError = err;
4402
5271
  throw wrapped;
4403
5272
  }
@@ -4475,7 +5344,7 @@ var LedgerConnectorBase = class {
4475
5344
  this._unwatchSessionState(sessionId);
4476
5345
  this._signerManager?.invalidate(sessionId);
4477
5346
  this._cancellers.get(sessionId)?.({
4478
- code: HardwareErrorCode8.DeviceDisconnected,
5347
+ code: HardwareErrorCode7.DeviceDisconnected,
4479
5348
  tag: "DeviceDisconnected",
4480
5349
  message: "Device disconnected"
4481
5350
  });
@@ -4491,7 +5360,7 @@ var LedgerConnectorBase = class {
4491
5360
  // whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
4492
5361
  // locally (see LedgerAdapter._unwrapConnectorResult).
4493
5362
  async call(sessionId, method, params) {
4494
- debugLog("[DMK] call:", method, JSON.stringify(params));
5363
+ debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
4495
5364
  try {
4496
5365
  const payload = await this._dispatch(sessionId, method, params);
4497
5366
  return { success: true, payload };
@@ -4501,7 +5370,7 @@ var LedgerConnectorBase = class {
4501
5370
  success: false,
4502
5371
  error: serializeConnectorError(
4503
5372
  Object.assign(new Error("Ledger app is unresponsive"), {
4504
- code: HardwareErrorCode8.DeviceAppStuck,
5373
+ code: HardwareErrorCode7.DeviceAppStuck,
4505
5374
  _tag: ERROR_TAG.DeviceAppStuck,
4506
5375
  originalError: err
4507
5376
  })
@@ -4513,7 +5382,7 @@ var LedgerConnectorBase = class {
4513
5382
  success: false,
4514
5383
  error: serializeConnectorError(
4515
5384
  Object.assign(new Error("Device communication interrupted, please retry"), {
4516
- code: HardwareErrorCode8.TransportError,
5385
+ code: HardwareErrorCode7.TransportError,
4517
5386
  _tag: ERROR_TAG.DeviceTransportStuck,
4518
5387
  originalError: err
4519
5388
  })
@@ -4559,6 +5428,11 @@ var LedgerConnectorBase = class {
4559
5428
  return solSignTransaction(ctx, sessionId, params);
4560
5429
  case "solSignMessage":
4561
5430
  return solSignMessage(ctx, sessionId, params);
5431
+ // ZCASH
5432
+ case "zcashGetFullViewingKey":
5433
+ return zcashGetFullViewingKey(ctx, sessionId, params);
5434
+ case "zcashGetShieldedAddress":
5435
+ return zcashGetShieldedAddress(ctx, sessionId, params);
4562
5436
  // TRON
4563
5437
  case "tronGetAddress":
4564
5438
  return tronGetAddress(ctx, sessionId, params);
@@ -4583,7 +5457,7 @@ var LedgerConnectorBase = class {
4583
5457
  try {
4584
5458
  return await apps.install(p.appName, ({ progress }) => {
4585
5459
  ctx.emit("ui-event", {
4586
- type: EConnectorInteraction4.AppInstallProgress,
5460
+ type: EConnectorInteraction3.AppInstallProgress,
4587
5461
  payload: {
4588
5462
  sessionId,
4589
5463
  appName: p.appName,
@@ -4592,7 +5466,7 @@ var LedgerConnectorBase = class {
4592
5466
  });
4593
5467
  });
4594
5468
  } catch (err) {
4595
- ctx.invalidateSession(sessionId);
5469
+ ctx.teardownSecureChannelSession(sessionId);
4596
5470
  throw ctx.wrapError(err);
4597
5471
  } finally {
4598
5472
  ctx.clearCanceller(sessionId);
@@ -4682,7 +5556,7 @@ var LedgerConnectorBase = class {
4682
5556
  );
4683
5557
  return { isGenuine: output.isGenuine, deviceId };
4684
5558
  } catch (err) {
4685
- ctx.invalidateSession(sessionId);
5559
+ ctx.teardownSecureChannelSession(sessionId);
4686
5560
  throw ctx.wrapError(err);
4687
5561
  } finally {
4688
5562
  ctx.clearCanceller(sessionId);
@@ -4804,6 +5678,17 @@ var LedgerConnectorBase = class {
4804
5678
  _invalidateSession(sessionId) {
4805
5679
  this._signerManager?.invalidate(sessionId);
4806
5680
  }
5681
+ _teardownSecureChannelSession(sessionId) {
5682
+ const cancel = this._cancellers.get(sessionId);
5683
+ this._cancellers.delete(sessionId);
5684
+ if (cancel) {
5685
+ try {
5686
+ cancel();
5687
+ } catch {
5688
+ }
5689
+ }
5690
+ this._invalidateSession(sessionId);
5691
+ }
4807
5692
  /**
4808
5693
  * Replace an old session with a new one after app switch.
4809
5694
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -4888,7 +5773,7 @@ var LedgerConnectorBase = class {
4888
5773
  * at every catch site. Falls through unchanged for unknown methods.
4889
5774
  */
4890
5775
  _ctxForMethod(method) {
4891
- const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5776
+ const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4892
5777
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
4893
5778
  if (!defaultAppName) return this._ctx;
4894
5779
  return {
@@ -4922,6 +5807,209 @@ var LedgerConnectorBase = class {
4922
5807
  return error;
4923
5808
  }
4924
5809
  };
5810
+
5811
+ // src/transport/DmkTransport.ts
5812
+ import Transport from "@ledgerhq/hw-transport";
5813
+ var DmkTransport = class extends Transport {
5814
+ constructor(dmk, sessionId) {
5815
+ super();
5816
+ this._dmk = dmk;
5817
+ this._sessionId = sessionId;
5818
+ }
5819
+ async exchange(apdu) {
5820
+ const response = await this._dmk.sendApdu({
5821
+ sessionId: this._sessionId,
5822
+ apdu: new Uint8Array(apdu)
5823
+ });
5824
+ const { data, statusCode } = response;
5825
+ const result = Buffer.alloc(data.length + 2);
5826
+ if (data.length > 0) {
5827
+ result.set(data, 0);
5828
+ }
5829
+ result.set(statusCode, data.length);
5830
+ return result;
5831
+ }
5832
+ async close() {
5833
+ }
5834
+ };
5835
+
5836
+ // src/app/AppManager.ts
5837
+ import {
5838
+ CloseAppCommand,
5839
+ GetAppAndVersionCommand,
5840
+ OpenAppCommand,
5841
+ isSuccessCommandResult
5842
+ } from "@ledgerhq/device-management-kit";
5843
+ import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
5844
+ var APP_NAME_MAP = {
5845
+ ETH: "Ethereum",
5846
+ BTC: "Bitcoin",
5847
+ SOL: "Solana",
5848
+ TRX: "Tron",
5849
+ ZEC: "Zcash",
5850
+ XRP: "XRP",
5851
+ ADA: "Cardano",
5852
+ DOT: "Polkadot",
5853
+ ATOM: "Cosmos"
5854
+ };
5855
+ var DASHBOARD_APP_NAME = "BOLOS";
5856
+ var AppManager = class {
5857
+ constructor(dmk, options) {
5858
+ this._dmk = dmk;
5859
+ this._waitMs = options?.waitMs ?? 1e3;
5860
+ this._maxRetries = options?.maxRetries ?? 10;
5861
+ }
5862
+ /**
5863
+ * Return the Ledger app name for a given chain ticker,
5864
+ * or undefined if the chain is not supported.
5865
+ */
5866
+ static getAppName(chain) {
5867
+ return APP_NAME_MAP[chain];
5868
+ }
5869
+ /**
5870
+ * Ensure the target app is open on the device identified by `sessionId`.
5871
+ *
5872
+ * Flow:
5873
+ * 1. Check the currently running app.
5874
+ * 2. If it is already the target, return immediately.
5875
+ * 3. If a different app is running (not dashboard), close it first.
5876
+ * 4. Open the target app.
5877
+ * 5. Poll until the device confirms the target app is running.
5878
+ */
5879
+ /**
5880
+ * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5881
+ * device is about to display "Open <app>" on screen and wait for the
5882
+ * user's button press. UI consumers should show their "open app" prompt
5883
+ * in response. NOT called when the target app is already open (no user
5884
+ * interaction needed in that case).
5885
+ *
5886
+ * Important: OpenAppCommand is blocking. It does not resolve until the user
5887
+ * has physically confirmed on the device, so anything that runs AFTER
5888
+ * `await this._openApp(...)` lands AFTER the prompt is already gone.
5889
+ * Hence the callback must fire BEFORE that await.
5890
+ */
5891
+ async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5892
+ const currentApp = await this._getCurrentApp(sessionId);
5893
+ if (currentApp === targetAppName) {
5894
+ return;
5895
+ }
5896
+ if (!this._isDashboard(currentApp)) {
5897
+ await this._closeCurrentApp(sessionId);
5898
+ await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5899
+ }
5900
+ onConfirmOnDevice?.();
5901
+ await this._openApp(sessionId, targetAppName);
5902
+ await this._waitForApp(sessionId, targetAppName);
5903
+ }
5904
+ // ---------------------------------------------------------------------------
5905
+ // Private helpers
5906
+ // ---------------------------------------------------------------------------
5907
+ async _getCurrentApp(sessionId) {
5908
+ const result = await this._dmk.sendCommand({
5909
+ sessionId,
5910
+ command: new GetAppAndVersionCommand()
5911
+ });
5912
+ if (isSuccessCommandResult(result)) {
5913
+ debugLog("[AppManager] currentApp:", result.data.name);
5914
+ return result.data.name;
5915
+ }
5916
+ const errResult = result;
5917
+ const dmkErr = errResult.error ?? {};
5918
+ const original = dmkErr.originalError;
5919
+ debugLog(
5920
+ "[AppManager] _getCurrentApp failed sessionId=",
5921
+ sessionId,
5922
+ "tag=",
5923
+ dmkErr._tag,
5924
+ "errorCode=",
5925
+ dmkErr.errorCode,
5926
+ "message=",
5927
+ dmkErr.message,
5928
+ "originalErrorMessage=",
5929
+ original?.message ?? String(original ?? "")
5930
+ );
5931
+ throw Object.assign(
5932
+ new Error(
5933
+ dmkErr.message ?? "Failed to get current app from device"
5934
+ ),
5935
+ {
5936
+ _tag: dmkErr._tag,
5937
+ errorCode: dmkErr.errorCode,
5938
+ originalError: original
5939
+ }
5940
+ );
5941
+ }
5942
+ async _openApp(sessionId, appName) {
5943
+ const result = await this._dmk.sendCommand({
5944
+ sessionId,
5945
+ command: new OpenAppCommand({ appName })
5946
+ });
5947
+ if (!isSuccessCommandResult(result)) {
5948
+ const dmkErr = result.error;
5949
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5950
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5951
+ debugLog(
5952
+ "[AppManager] openApp failed:",
5953
+ appName,
5954
+ "errorCode:",
5955
+ errorCode,
5956
+ "tag:",
5957
+ dmkErr._tag
5958
+ );
5959
+ let code;
5960
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
5961
+ code = HardwareErrorCode8.AppNotInstalled;
5962
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5963
+ code = HardwareErrorCode8.UserRejected;
5964
+ }
5965
+ throw Object.assign(new Error(`Failed to open "${appName}"`), {
5966
+ _tag: ERROR_TAG.OpenAppCommand,
5967
+ code,
5968
+ errorCode,
5969
+ statusCode: errorCode,
5970
+ appName,
5971
+ originalError: dmkErr
5972
+ });
5973
+ }
5974
+ }
5975
+ async _closeCurrentApp(sessionId) {
5976
+ debugLog("[AppManager] closeCurrentApp");
5977
+ await this._dmk.sendCommand({
5978
+ sessionId,
5979
+ command: new CloseAppCommand()
5980
+ });
5981
+ }
5982
+ /**
5983
+ * Poll the device until the expected app is reported as running,
5984
+ * or throw after `_maxRetries` attempts.
5985
+ */
5986
+ async _waitForApp(sessionId, expectedAppName) {
5987
+ let lastSeen = "";
5988
+ for (let i = 0; i < this._maxRetries; i++) {
5989
+ await this._wait();
5990
+ const current = await this._getCurrentApp(sessionId);
5991
+ lastSeen = current;
5992
+ if (current === expectedAppName) {
5993
+ return;
5994
+ }
5995
+ }
5996
+ debugLog(
5997
+ "[AppManager] waitForApp exhausted: expected=",
5998
+ expectedAppName,
5999
+ "lastSeen=",
6000
+ lastSeen
6001
+ );
6002
+ throw new Error(
6003
+ `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
6004
+ );
6005
+ }
6006
+ _isDashboard(appName) {
6007
+ return appName === DASHBOARD_APP_NAME;
6008
+ }
6009
+ _wait() {
6010
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
6011
+ }
6012
+ };
4925
6013
  export {
4926
6014
  AppManager,
4927
6015
  DmkTransport,
@@ -4932,6 +6020,7 @@ export {
4932
6020
  SignerEth,
4933
6021
  SignerManager,
4934
6022
  SignerSol,
6023
+ SignerZcash,
4935
6024
  debugLog,
4936
6025
  deviceActionToPromise,
4937
6026
  isDeviceLockedError,