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

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,11 +1027,10 @@ 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) => {
1033
+ const operationId = this._activeOperationId();
786
1034
  if (event.type === EConnectorInteraction.AppInstallProgress) {
787
1035
  let connectId;
788
1036
  for (const [cid, sid] of this._sessions) {
@@ -811,6 +1059,7 @@ var _LedgerAdapter = class _LedgerAdapter {
811
1059
  this._installProgressLastEmittedValue = progress;
812
1060
  this.emitter.emit("ui-event", {
813
1061
  type: EConnectorInteraction.AppInstallProgress,
1062
+ ...operationId ? { operationId } : {},
814
1063
  payload: {
815
1064
  connectId,
816
1065
  appName,
@@ -819,18 +1068,37 @@ var _LedgerAdapter = class _LedgerAdapter {
819
1068
  });
820
1069
  return;
821
1070
  }
822
- this.emitter.emit("ui-event", event);
1071
+ this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
823
1072
  };
824
1073
  this.connector = connector;
825
1074
  this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
826
1075
  this._jobQueue = new DeviceJobQueue();
827
1076
  this.registerEventListeners();
828
1077
  }
1078
+ _discardPendingBinding(owner, status = "cancelled") {
1079
+ const pending = owner?.pendingBinding;
1080
+ if (!owner || !pending) return;
1081
+ owner.pendingBinding = void 0;
1082
+ if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1083
+ }
1084
+ _finishBleBinding(status) {
1085
+ const selectionRequestId = this._bindingSelectionRequestId;
1086
+ this._bindingSelectionRequestId = void 0;
1087
+ if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
1088
+ }
1089
+ _isBleConnection() {
1090
+ return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1091
+ }
829
1092
  // Transport
830
1093
  get activeTransport() {
831
- return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1094
+ return this._isBleConnection() ? "ble" : "hid";
832
1095
  }
833
1096
  getAvailableTransports() {
1097
+ if (this.connector.availableTransports) {
1098
+ return this.connector.availableTransports.map(
1099
+ (transport) => transport === "ble" ? "ble" : "hid"
1100
+ );
1101
+ }
834
1102
  return this.activeTransport ? [this.activeTransport] : [];
835
1103
  }
836
1104
  // Connector is bound at construction; switching requires a new adapter.
@@ -847,21 +1115,43 @@ var _LedgerAdapter = class _LedgerAdapter {
847
1115
  * The next operation will re-discover and re-connect automatically.
848
1116
  */
849
1117
  resetState() {
1118
+ void this._resetStateAndDisconnectSessions();
1119
+ }
1120
+ _resetStateAndDisconnectSessions() {
1121
+ if (this._resetPromise) return this._resetPromise;
1122
+ const sessionIds = new Set(this._sessions.values());
1123
+ this._stateGeneration += 1;
1124
+ this._finishBleBinding("cancelled");
1125
+ this._operations.endAll("runtime-reset");
1126
+ this._doConnectAbortController?.abort();
850
1127
  this._discoveredDevices.clear();
851
1128
  this._sessions.clear();
1129
+ this._sessionTransports.clear();
1130
+ this._activeConnectionType = void 0;
1131
+ this._pendingOperationBindings.clear();
1132
+ this._pendingPickBindings.clear();
1133
+ this._selectedBleReconnectTargets.clear();
852
1134
  this._connectingPromise = null;
1135
+ this._doConnectAbortController = null;
853
1136
  this._uiRegistry.reset();
854
1137
  this._jobQueue.clear();
855
1138
  this._btcHighIndexConfirmedThisSession = false;
1139
+ const resetPromise = this._runConnectorTeardown(async () => {
1140
+ for (const sessionId of sessionIds) {
1141
+ await this.connector.disconnect(sessionId).catch(() => void 0);
1142
+ }
1143
+ });
1144
+ this._resetPromise = resetPromise;
1145
+ return resetPromise.finally(() => {
1146
+ if (this._resetPromise === resetPromise) {
1147
+ this._resetPromise = null;
1148
+ }
1149
+ });
856
1150
  }
857
1151
  async dispose() {
858
- this._uiRegistry.reset();
859
- this._jobQueue.clear();
1152
+ await this._resetStateAndDisconnectSessions();
860
1153
  this.unregisterEventListeners();
861
1154
  this.connector.reset();
862
- this._discoveredDevices.clear();
863
- this._sessions.clear();
864
- this._btcHighIndexConfirmedThisSession = false;
865
1155
  this.emitter.removeAllListeners();
866
1156
  }
867
1157
  uiResponse(response) {
@@ -871,17 +1161,32 @@ var _LedgerAdapter = class _LedgerAdapter {
871
1161
  // Device management
872
1162
  // ---------------------------------------------------------------------------
873
1163
  async searchDevices(options) {
1164
+ return this._searchDevices(options);
1165
+ }
1166
+ async _searchDevices(options, signal) {
874
1167
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
875
1168
  try {
876
1169
  if (options?.resetSession) {
877
- this._doConnectAbortController?.abort();
878
- this._sessions.clear();
879
- this._connectingPromise = null;
880
- this._doConnectAbortController = null;
881
- this._btcHighIndexConfirmedThisSession = false;
1170
+ await this._resetStateAndDisconnectSessions();
1171
+ } else {
1172
+ await this._connectorTeardownTail;
1173
+ }
1174
+ await this._ensureDevicePermission(void 0, void 0, signal);
1175
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1176
+ const stateGeneration = this._stateGeneration;
1177
+ const devices = await this.connector.searchDevices(
1178
+ options?.transportType ? {
1179
+ transportType: options.transportType,
1180
+ waitForAll: options.waitForAllTransports
1181
+ } : void 0
1182
+ );
1183
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1184
+ if (stateGeneration !== this._stateGeneration) {
1185
+ throw createHwkError({
1186
+ code: HardwareErrorCode3.UserAborted,
1187
+ message: "Ledger discovery was reset"
1188
+ });
882
1189
  }
883
- await this._ensureDevicePermission();
884
- const devices = await this.connector.searchDevices();
885
1190
  this._discoveredDevices.clear();
886
1191
  for (const d of devices) {
887
1192
  if (d.connectId) {
@@ -889,7 +1194,7 @@ var _LedgerAdapter = class _LedgerAdapter {
889
1194
  }
890
1195
  }
891
1196
  if (this._discoveredDevices.size === 0) {
892
- await this._ensureDevicePermission();
1197
+ await this._ensureDevicePermission(void 0, void 0, signal);
893
1198
  }
894
1199
  const result = Array.from(this._discoveredDevices.values());
895
1200
  debugLog("[LedgerAdapter][RES]", {
@@ -908,41 +1213,267 @@ var _LedgerAdapter = class _LedgerAdapter {
908
1213
  throw err;
909
1214
  }
910
1215
  }
1216
+ async searchDeviceTargets(options) {
1217
+ const devices = await this.searchDevices(options);
1218
+ return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
1219
+ }
911
1220
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
912
- async _evictAllSessions() {
1221
+ async _evictAllSessions(preserveOperationId) {
1222
+ this._operations.endAll("explicit", preserveOperationId);
913
1223
  if (this._sessions.size === 0) return;
914
1224
  const stale = [...this._sessions.values()];
915
1225
  this._sessions.clear();
916
- for (const sid of stale) {
917
- try {
918
- await this.connector.disconnect(sid);
919
- } catch {
1226
+ for (const sid of stale) this._sessionTransports.delete(sid);
1227
+ await this._runConnectorTeardown(async () => {
1228
+ for (const sid of stale) {
1229
+ try {
1230
+ await this.connector.disconnect(sid);
1231
+ } catch {
1232
+ }
920
1233
  }
921
- }
1234
+ });
922
1235
  }
923
1236
  static _createDeviceBusyError(method) {
924
1237
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
925
1238
  code: HardwareErrorCode3.DeviceBusy
926
1239
  });
927
1240
  }
928
- async connectDevice(connectId) {
1241
+ async connectDevice(searchTargetId) {
1242
+ try {
1243
+ return await this._jobQueue.enqueue(
1244
+ searchTargetId || "__ledger_connect__",
1245
+ async (signal) => {
1246
+ const connected = await this._connectTarget(searchTargetId, void 0, signal);
1247
+ if (!connected.success) return connected;
1248
+ return this._createOperation(searchTargetId, connected.payload);
1249
+ },
1250
+ {
1251
+ label: "connectDevice",
1252
+ rejectIfBusy: true,
1253
+ busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1254
+ }
1255
+ );
1256
+ } catch (error) {
1257
+ return this.errorToFailure(error);
1258
+ }
1259
+ }
1260
+ /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1261
+ async bindBleDevice(params) {
1262
+ const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1263
+ const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
1264
+ try {
1265
+ return await this._jobQueue.enqueue(
1266
+ "__ledger_bind_ble__",
1267
+ async (signal) => {
1268
+ if (!this.getAvailableTransports().includes("ble")) {
1269
+ throw createHwkError({
1270
+ code: HardwareErrorCode3.TransportNotAvailable,
1271
+ message: "Ledger Bluetooth transport is not available"
1272
+ });
1273
+ }
1274
+ this._activeConnectionType = "ble";
1275
+ await this._ensureDevicePermission(void 0, void 0, signal);
1276
+ const attempt = {
1277
+ extra: params.extra,
1278
+ bindingReason: "manual-rebind",
1279
+ deferBindingSave: Boolean(identity)
1280
+ };
1281
+ try {
1282
+ const connectId = await this._connectFirstOrSelect(
1283
+ [],
1284
+ void 0,
1285
+ true,
1286
+ void 0,
1287
+ attempt,
1288
+ signal
1289
+ );
1290
+ const pending = attempt.pendingBinding;
1291
+ if (identity && pending) {
1292
+ attempt.pendingBinding = void 0;
1293
+ const sessionId = this._sessions.get(connectId);
1294
+ if (!sessionId) {
1295
+ throw createHwkError({
1296
+ code: HardwareErrorCode3.DeviceDisconnected,
1297
+ message: "Selected Ledger connection ended"
1298
+ });
1299
+ }
1300
+ const checked = await this._fingerprintFirstOpenableChain(
1301
+ identities,
1302
+ (chain, autoInstallApp) => this._computeChainFingerprint(
1303
+ chain,
1304
+ (method, callParams) => this._runConnectorCall(
1305
+ connectId,
1306
+ method,
1307
+ callParams,
1308
+ signal,
1309
+ void 0,
1310
+ void 0,
1311
+ { autoInstallApp },
1312
+ { connection: { connectId, sessionId } }
1313
+ )
1314
+ )
1315
+ );
1316
+ if (checked.fingerprint !== checked.identity.value) {
1317
+ await this._dropSession(connectId, signal);
1318
+ throw createHwkError({
1319
+ code: HardwareErrorCode3.DeviceMismatch,
1320
+ message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
1321
+ });
1322
+ }
1323
+ await this._saveSelectedBleBinding(
1324
+ connectId,
1325
+ pending.requestId,
1326
+ attempt,
1327
+ void 0,
1328
+ signal,
1329
+ checked.identity
1330
+ );
1331
+ }
1332
+ if (!attempt.bindingSaved) {
1333
+ await this._dropSession(connectId, signal);
1334
+ throw createHwkError({
1335
+ code: HardwareErrorCode3.UnknownError,
1336
+ message: "Bluetooth binding could not be saved",
1337
+ origin: "host"
1338
+ });
1339
+ }
1340
+ return success2(connectId);
1341
+ } catch (error) {
1342
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1343
+ throw error;
1344
+ }
1345
+ },
1346
+ {
1347
+ label: "bindBleDevice",
1348
+ rejectIfBusy: true,
1349
+ busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1350
+ }
1351
+ );
1352
+ } catch (error) {
1353
+ return this.errorToFailure(error);
1354
+ }
1355
+ }
1356
+ async acquireOperation(connectId, context) {
1357
+ try {
1358
+ return await this._jobQueue.enqueue(
1359
+ connectId || "__ledger_acquire__",
1360
+ async (signal) => {
1361
+ const transport = this._isBleConnection() ? "ble" : "usb";
1362
+ const hint = context.knownConnections?.find(
1363
+ (connection) => connection.transport === transport
1364
+ );
1365
+ const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1366
+ await this._ensureDevicePermission(target, void 0, signal);
1367
+ const attempt = {
1368
+ ...context,
1369
+ extra: context.extra ? { ...context.extra } : void 0,
1370
+ // The operation's calls decide whether the pick is the right wallet.
1371
+ deferBindingSave: true
1372
+ };
1373
+ try {
1374
+ const resolvedConnectId = await this.ensureConnected(
1375
+ target,
1376
+ signal,
1377
+ true,
1378
+ void 0,
1379
+ attempt
1380
+ );
1381
+ _LedgerAdapter._throwIfAborted(signal);
1382
+ const result = this._createOperation(connectId, resolvedConnectId);
1383
+ if (result.success && attempt.pendingBinding) {
1384
+ this._pendingOperationBindings.set(result.payload, attempt);
1385
+ }
1386
+ return result;
1387
+ } catch (error) {
1388
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1389
+ throw error;
1390
+ }
1391
+ },
1392
+ {
1393
+ label: "acquireOperation",
1394
+ rejectIfBusy: true,
1395
+ busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1396
+ }
1397
+ );
1398
+ } catch (error) {
1399
+ return this.errorToFailure(error);
1400
+ }
1401
+ }
1402
+ _createOperation(searchTargetId, resolvedConnectId) {
1403
+ this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1404
+ const sessionId = this._sessions.get(resolvedConnectId);
1405
+ if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1406
+ const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1407
+ const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1408
+ vendor: "ledger",
1409
+ model: "unknown",
1410
+ firmwareVersion: "",
1411
+ deviceId: "",
1412
+ connectId: resolvedConnectId,
1413
+ connectionType
1414
+ };
1415
+ const operation = this._operations.create({
1416
+ searchTargetId,
1417
+ connectId: resolvedConnectId,
1418
+ device,
1419
+ connectionType,
1420
+ connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
1421
+ });
1422
+ return success2(operation.operationId);
1423
+ }
1424
+ async _connectTarget(connectId, preserveOperationId, signal) {
929
1425
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
930
1426
  try {
931
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1427
+ this._assertConnectorReady("connectDevice");
1428
+ const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1429
+ if (discoveredType === "usb" || discoveredType === "ble") {
1430
+ this._activeConnectionType = discoveredType;
1431
+ }
1432
+ if (this._isBleConnection() && !connectId) {
932
1433
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
933
1434
  code: HardwareErrorCode3.DeviceNotFound
934
1435
  });
935
1436
  }
936
- if (!isLedgerBleConnectionType(this.connector.connectionType)) {
937
- await this._evictAllSessions();
1437
+ await this._ensureDevicePermission(connectId, void 0, signal);
1438
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1439
+ const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1440
+ if (!isMultiTransport && this._isBleConnection()) {
1441
+ const previousSessionId = this._sessions.get(connectId);
1442
+ this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1443
+ if (previousSessionId) {
1444
+ this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1445
+ this._sessions.delete(connectId);
1446
+ await this.connector.disconnect(previousSessionId).catch(() => void 0);
1447
+ }
1448
+ } else {
1449
+ await this._evictAllSessions(preserveOperationId);
1450
+ }
1451
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1452
+ const stateGeneration = this._stateGeneration;
1453
+ const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1454
+ let session;
1455
+ this._connectingConnectId = connectId;
1456
+ try {
1457
+ session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1458
+ transportType: this._activeConnectionType ?? "usb"
1459
+ }) : await this.connector.connect(connectId);
1460
+ if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1461
+ await this.connector.disconnect(session.sessionId).catch(() => void 0);
1462
+ throw Object.assign(new Error("Ledger connection aborted"), {
1463
+ code: HardwareErrorCode3.UserAborted
1464
+ });
1465
+ }
1466
+ } finally {
1467
+ if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1468
+ releaseOperation();
938
1469
  }
939
- await this._ensureDevicePermission(connectId);
940
- const session = await this.connector.connect(connectId);
941
- this._sessions.set(connectId, session.sessionId);
1470
+ const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1471
+ this._sessions.set(resolvedConnectId, session.sessionId);
1472
+ this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
942
1473
  if (session.deviceInfo) {
943
- this._discoveredDevices.set(connectId, session.deviceInfo);
1474
+ this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
944
1475
  }
945
- const result = success(connectId);
1476
+ const result = success2(resolvedConnectId);
946
1477
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
947
1478
  return result;
948
1479
  } catch (err) {
@@ -955,30 +1486,84 @@ var _LedgerAdapter = class _LedgerAdapter {
955
1486
  return failureResult;
956
1487
  }
957
1488
  }
958
- async disconnectDevice(connectId) {
1489
+ async releaseOperation(operationId) {
1490
+ const operation = this._operations.findActive(operationId);
1491
+ if (operation) this._cancelOperationWork(operation);
1492
+ const endedOperation = this._operations.release(operationId);
1493
+ if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
1494
+ const { connectId } = endedOperation;
959
1495
  debugLog("[LedgerAdapter][REQ]", {
960
- method: "disconnectDevice",
1496
+ method: "releaseOperation",
961
1497
  connectId,
962
1498
  params: { connectId }
963
1499
  });
964
1500
  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 });
1501
+ await this._releaseOperationConnection(endedOperation);
1502
+ debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
971
1503
  } catch (err) {
972
1504
  const e = err;
973
1505
  debugLog("[LedgerAdapter][RES]", {
974
- method: "disconnectDevice",
1506
+ method: "releaseOperation",
975
1507
  success: false,
976
1508
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
977
1509
  });
978
1510
  throw err;
979
1511
  }
980
1512
  }
981
- async getDeviceInfo(connectId, deviceId) {
1513
+ /**
1514
+ * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1515
+ * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1516
+ */
1517
+ _cancelOperationWork(operation) {
1518
+ const { operationId } = operation;
1519
+ const reason = createHwkError({
1520
+ code: HardwareErrorCode3.OperationEnded,
1521
+ message: "Ledger operation was released",
1522
+ params: { operationId, reason: "explicit" }
1523
+ });
1524
+ const queueKey = ledgerQueueKey({ operationId });
1525
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1526
+ this._jobQueue.cancelActiveAndPending(queueKey, reason);
1527
+ if (!ownsRunningCall) return;
1528
+ this._uiRegistry.cancel(void 0, void 0, operationId);
1529
+ void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
1530
+ }
1531
+ /**
1532
+ * A running call by bare connectId (or still resolving its device by identity) may be on this
1533
+ * connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
1534
+ * caller like any bare call's session. A lost connection is torn down regardless.
1535
+ */
1536
+ _bareCallMayUseConnection(operation) {
1537
+ const activeKey = this._jobQueue.getActiveJob()?.deviceId;
1538
+ return activeKey !== void 0 && !isHardwareOperationId(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
1539
+ }
1540
+ async _releaseOperationConnection(operation) {
1541
+ const sessionIds = /* @__PURE__ */ new Set();
1542
+ for (const [connectId, sessionId] of this._sessions) {
1543
+ if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1544
+ this._sessions.delete(connectId);
1545
+ sessionIds.add(sessionId);
1546
+ }
1547
+ }
1548
+ for (const sessionId of sessionIds) {
1549
+ await this._runConnectorTeardown(
1550
+ () => this.connector.disconnect(sessionId).catch(() => void 0)
1551
+ );
1552
+ }
1553
+ }
1554
+ async _releaseLostOperationConnection(operationId) {
1555
+ const endedOperation = this._operations.end(operationId, "disconnect");
1556
+ if (!endedOperation) return;
1557
+ this._discoveredDevices.delete(endedOperation.connectId);
1558
+ await this._releaseOperationConnection(endedOperation);
1559
+ }
1560
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1561
+ let connectId;
1562
+ try {
1563
+ connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1564
+ } catch (error) {
1565
+ return this.errorToFailure(error);
1566
+ }
982
1567
  debugLog("[LedgerAdapter][REQ]", {
983
1568
  method: "getDeviceInfo",
984
1569
  connectId,
@@ -988,7 +1573,7 @@ var _LedgerAdapter = class _LedgerAdapter {
988
1573
  await this._ensureDevicePermission(connectId, deviceId);
989
1574
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
990
1575
  if (cached) {
991
- const result = success(cached);
1576
+ const result = success2(cached);
992
1577
  debugLog("[LedgerAdapter][RES]", {
993
1578
  method: "getDeviceInfo",
994
1579
  success: true,
@@ -1013,11 +1598,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1013
1598
  success: false,
1014
1599
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1015
1600
  });
1016
- throw err;
1601
+ return this.errorToFailure(err);
1017
1602
  }
1018
1603
  }
1019
- getSupportedChains() {
1020
- return ["evm", "btc", "sol", "tron"];
1604
+ /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1605
+ async _dropUncheckedBundlePick(context, signal) {
1606
+ const { connection } = context;
1607
+ const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1608
+ if (!connection || !owner) return;
1609
+ this._pendingPickBindings.delete(connection.connectId);
1610
+ this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1611
+ if (this._sessions.get(connection.connectId) === connection.sessionId) {
1612
+ await this._dropSession(connection.connectId, signal);
1613
+ }
1021
1614
  }
1022
1615
  // ---------------------------------------------------------------------------
1023
1616
  // Chain call helper
@@ -1037,7 +1630,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1037
1630
  commonParams,
1038
1631
  installContext
1039
1632
  );
1040
- return success(result);
1633
+ return success2(result);
1041
1634
  } catch (err) {
1042
1635
  return this.errorToFailure(err);
1043
1636
  }
@@ -1053,13 +1646,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1053
1646
  if (params && typeof params === "object") {
1054
1647
  const {
1055
1648
  autoInstallApp,
1649
+ operationId,
1056
1650
  passphraseState: _passphraseState,
1057
1651
  useEmptyPassphrase: _useEmptyPassphrase,
1652
+ knownConnections,
1653
+ extra,
1654
+ allowDeviceSelection,
1655
+ supportedTransports,
1058
1656
  ...rest
1059
1657
  } = params;
1060
1658
  return {
1061
1659
  commonParams: {
1062
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1660
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1661
+ operationId: typeof operationId === "string" ? operationId : void 0,
1662
+ ...pickConnectionContext({
1663
+ knownConnections,
1664
+ extra,
1665
+ allowDeviceSelection,
1666
+ supportedTransports
1667
+ })
1063
1668
  },
1064
1669
  rest
1065
1670
  };
@@ -1225,7 +1830,13 @@ var _LedgerAdapter = class _LedgerAdapter {
1225
1830
  params
1226
1831
  );
1227
1832
  }
1228
- tronSignMessage(connectId, deviceId, params) {
1833
+ async tronSignMessage(connectId, deviceId, params) {
1834
+ if (params?.messageType !== "V2") {
1835
+ return failure2(
1836
+ HardwareErrorCode3.MethodNotSupported,
1837
+ 'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
1838
+ );
1839
+ }
1229
1840
  return this.callChainWithMergedParams(
1230
1841
  connectId,
1231
1842
  deviceId,
@@ -1235,14 +1846,33 @@ var _LedgerAdapter = class _LedgerAdapter {
1235
1846
  );
1236
1847
  }
1237
1848
  // ---------------------------------------------------------------------------
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.
1849
+ // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1850
+ // ---------------------------------------------------------------------------
1851
+ zcashGetFullViewingKey(connectId, deviceId, params) {
1852
+ return this.callChainWithMergedParams(
1853
+ connectId,
1854
+ deviceId,
1855
+ "zcash",
1856
+ "zcashGetFullViewingKey",
1857
+ params
1858
+ );
1859
+ }
1860
+ zcashGetShieldedAddress(connectId, deviceId, params) {
1861
+ return this.callChainWithMergedParams(
1862
+ connectId,
1863
+ deviceId,
1864
+ "zcash",
1865
+ "zcashGetShieldedAddress",
1866
+ params
1867
+ );
1868
+ }
1869
+ // ---------------------------------------------------------------------------
1870
+ // App management: OS-level app install/list, no fingerprint or chain dispatch.
1241
1871
  // ---------------------------------------------------------------------------
1242
1872
  async installApp(connectId, appName) {
1243
1873
  try {
1244
1874
  await this.connectorCall(connectId, "installApp", { appName });
1245
- return success(void 0);
1875
+ return success2(void 0);
1246
1876
  } catch (err) {
1247
1877
  return this.errorToFailure(err);
1248
1878
  }
@@ -1250,7 +1880,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1250
1880
  async listInstalledApps(connectId) {
1251
1881
  try {
1252
1882
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1253
- return success(result);
1883
+ return success2(result);
1254
1884
  } catch (err) {
1255
1885
  return this.errorToFailure(err);
1256
1886
  }
@@ -1259,7 +1889,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1259
1889
  async listInstalledNames(connectId) {
1260
1890
  try {
1261
1891
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1262
- return success(result);
1892
+ return success2(result);
1263
1893
  } catch (err) {
1264
1894
  return this.errorToFailure(err);
1265
1895
  }
@@ -1267,7 +1897,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1267
1897
  async listAvailableApps(connectId) {
1268
1898
  try {
1269
1899
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1270
- return success(result);
1900
+ return success2(result);
1271
1901
  } catch (err) {
1272
1902
  return this.errorToFailure(err);
1273
1903
  }
@@ -1275,7 +1905,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1275
1905
  async getLedgerFirmwareVersion(connectId) {
1276
1906
  try {
1277
1907
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1278
- return success(result);
1908
+ return success2(result);
1279
1909
  } catch (err) {
1280
1910
  return this.errorToFailure(err);
1281
1911
  }
@@ -1283,7 +1913,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1283
1913
  async getLedgerDeviceInfo(connectId) {
1284
1914
  try {
1285
1915
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1286
- return success(result);
1916
+ return success2(result);
1287
1917
  } catch (err) {
1288
1918
  return this.errorToFailure(err);
1289
1919
  }
@@ -1323,11 +1953,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1323
1953
  );
1324
1954
  }
1325
1955
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1326
- this.resetState();
1956
+ await this._resetStateAndDisconnectSessions();
1327
1957
  }
1328
1958
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1329
1959
  if (!result.isGenuine) {
1330
- return success({
1960
+ return success2({
1331
1961
  vendor: "ledger",
1332
1962
  verified: false
1333
1963
  });
@@ -1338,7 +1968,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1338
1968
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1339
1969
  );
1340
1970
  }
1341
- return success({
1971
+ return success2({
1342
1972
  vendor: "ledger",
1343
1973
  verified: result.isGenuine,
1344
1974
  deviceId: result.deviceId
@@ -1349,10 +1979,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1349
1979
  if (relayUrl) {
1350
1980
  try {
1351
1981
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1352
- this.resetState();
1982
+ await this._resetStateAndDisconnectSessions();
1353
1983
  } catch {
1354
1984
  this.connector.reset();
1355
- this.resetState();
1985
+ await this._resetStateAndDisconnectSessions();
1356
1986
  }
1357
1987
  }
1358
1988
  }
@@ -1364,6 +1994,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1364
1994
  this.emitter.off(event, listener);
1365
1995
  }
1366
1996
  cancel(connectId) {
1997
+ const namedOperationIsLive = (id) => {
1998
+ try {
1999
+ this._operations.resolve(id);
2000
+ return true;
2001
+ } catch {
2002
+ return false;
2003
+ }
2004
+ };
2005
+ if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
2006
+ debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
2007
+ connectId
2008
+ });
2009
+ return;
2010
+ }
1367
2011
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1368
2012
  code: HardwareErrorCode3.UserAborted,
1369
2013
  _tag: ERROR_TAG.UserAborted
@@ -1374,60 +2018,163 @@ var _LedgerAdapter = class _LedgerAdapter {
1374
2018
  this._lastCancelReason = void 0;
1375
2019
  }
1376
2020
  }, 2e3);
1377
- this._uiRegistry.cancel();
1378
- if (connectId) {
1379
- this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1380
- } else {
1381
- this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
2021
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
2022
+ let operationId;
2023
+ if (isHardwareOperationId(connectId)) {
2024
+ operationId = connectId;
2025
+ } else if (!connectId && isHardwareOperationId(activeJobId)) {
2026
+ operationId = activeJobId;
1382
2027
  }
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);
2028
+ let resolvedConnectId = connectId;
2029
+ if (operationId) {
2030
+ try {
2031
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
2032
+ } catch {
2033
+ resolvedConnectId = void 0;
2034
+ }
1388
2035
  }
1389
- if (this._connectingPromise) {
2036
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
2037
+ const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
2038
+ if (!connectId) {
2039
+ this._uiRegistry.cancel();
2040
+ } else if (pendingOperationId) {
2041
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
2042
+ }
2043
+ this._finishBleBinding("cancelled");
2044
+ if (!connectId) this._pendingOperationBindings.clear();
2045
+ else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
2046
+ const queueKeys = /* @__PURE__ */ new Set();
2047
+ if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
2048
+ if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
2049
+ if (queueKeys.size) {
2050
+ let cancelledAnyJob = false;
2051
+ for (const key of queueKeys) {
2052
+ cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
2053
+ }
2054
+ debugLog("[LedgerAdapter] cancel routed to queue keys", {
2055
+ queueKeys: [...queueKeys],
2056
+ cancelledAnyJob
2057
+ });
2058
+ } else {
2059
+ this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
2060
+ }
2061
+ const connectingConnectId = this._connectingConnectId;
2062
+ const targetKeys = new Set(
2063
+ [
2064
+ connectId,
2065
+ resolvedConnectId,
2066
+ ...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
2067
+ ].filter(Boolean)
2068
+ );
2069
+ const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
2070
+ if (activeJobId === void 0 || ownsPendingConnect) {
2071
+ if (resolvedConnectId) {
2072
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
2073
+ void this.connector.cancel(sessionId);
2074
+ } else {
2075
+ for (const sid of this._sessions.values()) void this.connector.cancel(sid);
2076
+ }
2077
+ }
2078
+ if (this._connectingPromise && ownsPendingConnect) {
1390
2079
  this._doConnectAbortController?.abort(userAbortReason);
1391
2080
  }
2081
+ if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
1392
2082
  }
1393
2083
  // ---------------------------------------------------------------------------
1394
2084
  // Chain fingerprint
1395
2085
  // ---------------------------------------------------------------------------
2086
+ /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
1396
2087
  async getChainFingerprint(connectId, deviceId, chain) {
1397
2088
  try {
1398
2089
  const fingerprint = await this._computeChainFingerprint(
1399
2090
  chain,
1400
2091
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
1401
2092
  );
1402
- return success(fingerprint);
2093
+ if (deviceId) {
2094
+ if (fingerprint !== deviceId) {
2095
+ return failure2(
2096
+ HardwareErrorCode3.DeviceMismatch,
2097
+ formatDeviceMismatchError(deviceId, fingerprint)
2098
+ );
2099
+ }
2100
+ }
2101
+ return success2(fingerprint);
1403
2102
  } catch (err) {
1404
2103
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
1405
2104
  return this.errorToFailure(err);
1406
2105
  }
1407
2106
  }
1408
2107
  /**
1409
- * Verify fingerprint using an existing sessionId directly.
1410
- * Safe to call inside connectorCall without causing queue deadlock.
2108
+ * Fingerprints the first recorded chain whose app the device can open. Only a missing app
2109
+ * moves on to the next chain; when every app is missing, the first chain offers its install.
1411
2110
  */
1412
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
1413
- if (!deviceId) return { success: true };
2111
+ async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
2112
+ const [first] = identities;
2113
+ if (identities.length > 1) {
2114
+ for (const identity of identities) {
2115
+ try {
2116
+ return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
2117
+ } catch (error) {
2118
+ const isAppMissing = isAppNotInstalledError(error) || error?.code === HardwareErrorCode3.AppNotInstalled;
2119
+ if (!isAppMissing) throw error;
2120
+ }
2121
+ }
2122
+ }
2123
+ return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
2124
+ }
2125
+ /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2126
+ async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
1414
2127
  try {
1415
- const fingerprint = await this._computeChainFingerprint(
1416
- chain,
1417
- (method, params) => this._callConnector(sessionId, method, params)
2128
+ const outcome = await requestSaveDeviceBinding(
2129
+ this.emitter,
2130
+ this._uiRegistry,
2131
+ {
2132
+ selectionRequestId,
2133
+ connection: { transport: "ble", connectId },
2134
+ ...identity ? { identity } : {},
2135
+ extra: context?.extra,
2136
+ operationId
2137
+ },
2138
+ signal
1418
2139
  );
1419
- if (fingerprint === deviceId) {
1420
- return { success: true };
2140
+ if (context) context.bindingSaved = outcome.saved;
2141
+ if (!outcome.saved) {
2142
+ debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2143
+ connectId,
2144
+ reason: outcome.reason
2145
+ });
1421
2146
  }
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 };
2147
+ } catch (error) {
2148
+ await this._dropSession(connectId, signal);
2149
+ throw error;
2150
+ } finally {
2151
+ if (this._bindingSelectionRequestId === selectionRequestId) {
2152
+ this._bindingSelectionRequestId = void 0;
1427
2153
  }
1428
- throw err;
1429
2154
  }
1430
2155
  }
2156
+ async _dropSession(connectId, signal) {
2157
+ const sessionId = this._sessions.get(connectId);
2158
+ this._sessions.delete(connectId);
2159
+ if (!sessionId) return;
2160
+ this._sessionTransports.delete(sessionId);
2161
+ const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2162
+ () => void 0
2163
+ );
2164
+ if (!signal.aborted) await teardown;
2165
+ }
2166
+ /** Verify on the acquired session without re-entering the job queue. */
2167
+ async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2168
+ if (!deviceId) return { success: true };
2169
+ const fingerprint = await this._computeChainFingerprint(
2170
+ chain,
2171
+ (method, params) => this._callConnector(sessionId, method, params)
2172
+ );
2173
+ if (fingerprint === deviceId) {
2174
+ return { success: true };
2175
+ }
2176
+ return { success: false, expected: deviceId, actual: fingerprint };
2177
+ }
1431
2178
  /**
1432
2179
  * Compute the chain fingerprint via a caller-supplied call strategy.
1433
2180
  *
@@ -1455,11 +2202,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1455
2202
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
1456
2203
  } else if (chain === "tron") {
1457
2204
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2205
+ } else if (chain === "zcash") {
2206
+ address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
1458
2207
  } else {
1459
2208
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
1460
2209
  }
1461
2210
  return deriveDeviceFingerprint(address);
1462
2211
  }
2212
+ /**
2213
+ * Operation owning the running job, so a mid-call UI request can name it.
2214
+ * Undefined at cold start when no operation owns the job.
2215
+ */
2216
+ _activeOperationId() {
2217
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2218
+ }
1463
2219
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
1464
2220
  // The user must press Confirm after unlocking, which triggers a search retry.
1465
2221
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -1469,15 +2225,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1469
2225
  if (signal?.aborted) {
1470
2226
  _LedgerAdapter._throwIfAborted(signal);
1471
2227
  }
2228
+ const operationId = this._activeOperationId();
1472
2229
  const waitPromise = this._uiRegistry.wait(
1473
- UI_REQUEST.REQUEST_DEVICE_CONNECT
2230
+ UI_REQUEST.REQUEST_DEVICE_CONNECT,
2231
+ { operationId }
1474
2232
  );
1475
2233
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1476
2234
  type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
1477
2235
  payload: {
1478
2236
  vendor: "ledger",
1479
2237
  reason: "device-not-found",
1480
- message: "Please connect and unlock your Ledger device"
2238
+ message: "Please connect and unlock your Ledger device",
2239
+ operationId
1481
2240
  }
1482
2241
  });
1483
2242
  let payload;
@@ -1498,7 +2257,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1498
2257
  } catch (err) {
1499
2258
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
1500
2259
  type: UI_REQUEST.CLOSE_UI_WINDOW,
1501
- payload: {}
2260
+ payload: { operationId }
1502
2261
  });
1503
2262
  throw Object.assign(new Error("User cancelled Ledger connection"), {
1504
2263
  _tag: ERROR_TAG.UserAborted,
@@ -1523,7 +2282,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1523
2282
  * Returns the params to pass through (with `showOnDevice` possibly
1524
2283
  * promoted), or `null` if the user declined.
1525
2284
  */
1526
- async _gateBtcHighIndex(params) {
2285
+ async _gateBtcHighIndex(params, signal) {
1527
2286
  const accountIndex = btcAccountIndexFromPath(params.path);
1528
2287
  if (params.showOnDevice) return params;
1529
2288
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -1532,51 +2291,75 @@ var _LedgerAdapter = class _LedgerAdapter {
1532
2291
  if (this._btcHighIndexConfirmedThisSession) {
1533
2292
  return { ...params, showOnDevice: true };
1534
2293
  }
1535
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2294
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1536
2295
  if (!confirmed) return null;
1537
2296
  this._btcHighIndexConfirmedThisSession = true;
1538
2297
  return { ...params, showOnDevice: true };
1539
2298
  }
1540
- async _waitForBtcHighIndexConfirm(path, accountIndex) {
2299
+ async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2300
+ const operationId = this._activeOperationId();
1541
2301
  const waitPromise = this._uiRegistry.wait(
1542
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2302
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2303
+ { operationId }
1543
2304
  );
1544
2305
  this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1545
2306
  type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1546
2307
  payload: {
1547
2308
  vendor: "ledger",
1548
2309
  path,
1549
- accountIndex
2310
+ accountIndex,
2311
+ operationId
1550
2312
  }
1551
2313
  });
1552
2314
  try {
1553
- const payload = await waitPromise;
2315
+ const payload = await this._awaitUiAnswer(
2316
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2317
+ waitPromise,
2318
+ signal
2319
+ );
1554
2320
  return !!payload?.confirmed;
1555
2321
  } catch (err) {
1556
2322
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
1557
2323
  type: UI_REQUEST.CLOSE_UI_WINDOW,
1558
- payload: {}
2324
+ payload: { operationId }
1559
2325
  });
1560
2326
  return false;
1561
2327
  }
1562
2328
  }
2329
+ /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2330
+ async _awaitUiAnswer(requestType, waitPromise, signal) {
2331
+ const onAbort = () => this._uiRegistry.cancel(requestType);
2332
+ if (signal.aborted) onAbort();
2333
+ signal.addEventListener("abort", onAbort, { once: true });
2334
+ try {
2335
+ return await waitPromise;
2336
+ } finally {
2337
+ signal.removeEventListener("abort", onAbort);
2338
+ }
2339
+ }
1563
2340
  // Ask the user whether to install a missing app (autoInstallApp flow).
1564
2341
  // Same register-then-emit ordering as the BTC high-index gate.
1565
- async _waitForInstallAppConfirm(appName) {
2342
+ async _waitForInstallAppConfirm(appName, signal) {
2343
+ const operationId = this._activeOperationId();
1566
2344
  const waitPromise = this._uiRegistry.wait(
1567
- UI_REQUEST.REQUEST_INSTALL_APP
2345
+ UI_REQUEST.REQUEST_INSTALL_APP,
2346
+ { operationId }
1568
2347
  );
1569
2348
  this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
1570
2349
  type: UI_REQUEST.REQUEST_INSTALL_APP,
1571
- payload: { vendor: "ledger", appName }
2350
+ payload: { vendor: "ledger", appName, operationId }
1572
2351
  });
1573
2352
  try {
1574
- const payload = await waitPromise;
2353
+ const payload = await this._awaitUiAnswer(
2354
+ UI_REQUEST.REQUEST_INSTALL_APP,
2355
+ waitPromise,
2356
+ signal
2357
+ );
1575
2358
  return !!payload?.confirmed;
1576
2359
  } catch (err) {
1577
2360
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
1578
2361
  type: UI_REQUEST.CLOSE_UI_WINDOW,
1579
- payload: {}
2362
+ payload: { operationId }
1580
2363
  });
1581
2364
  return false;
1582
2365
  }
@@ -1584,16 +2367,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1584
2367
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
1585
2368
  // `_doConnect` runs under its own internal controller so caller A's cancel
1586
2369
  // doesn't kill caller B's await.
1587
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2370
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1588
2371
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
1589
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2372
+ this._assertConnectorReady("connectDevice");
2373
+ if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1590
2374
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1591
2375
  code: HardwareErrorCode3.DeviceNotFound
1592
2376
  });
1593
2377
  }
1594
2378
  if (connectId && this._sessions.has(connectId)) return connectId;
1595
2379
  if (!connectId && this._sessions.size > 0) {
1596
- if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2380
+ if (!this._isBleConnection() && this._sessions.size > 1) {
1597
2381
  throw Object.assign(
1598
2382
  new Error(
1599
2383
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -1603,15 +2387,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1603
2387
  }
1604
2388
  return this._sessions.keys().next().value;
1605
2389
  }
1606
- if (!this._connectingPromise) {
1607
- this._doConnectAbortController = new AbortController();
1608
- const innerSignal = this._doConnectAbortController.signal;
2390
+ if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2391
+ const controller = new AbortController();
2392
+ this._doConnectAbortController = controller;
2393
+ const innerSignal = controller.signal;
1609
2394
  this._connectingPromise = (async () => {
1610
2395
  try {
1611
- return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2396
+ return await this._doConnect(
2397
+ innerSignal,
2398
+ connectId,
2399
+ allowUsbEphemeralFallback,
2400
+ preserveOperationId,
2401
+ context
2402
+ );
1612
2403
  } finally {
1613
- this._connectingPromise = null;
1614
- this._doConnectAbortController = null;
2404
+ if (this._doConnectAbortController === controller) {
2405
+ this._connectingPromise = null;
2406
+ this._doConnectAbortController = null;
2407
+ if (this._sessions.size === 0) this._activeConnectionType = void 0;
2408
+ }
1615
2409
  }
1616
2410
  })();
1617
2411
  }
@@ -1620,22 +2414,54 @@ var _LedgerAdapter = class _LedgerAdapter {
1620
2414
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
1621
2415
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
1622
2416
  // 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
- }
2417
+ async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2418
+ _LedgerAdapter._throwIfAborted(internalSignal);
2419
+ if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2420
+ this._activeConnectionType = "usb";
2421
+ const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2422
+ _LedgerAdapter._throwIfAborted(internalSignal);
2423
+ const knownUsb = context?.knownConnections?.find(
2424
+ (connection) => connection.transport === "usb"
2425
+ );
2426
+ const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2427
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2428
+ return this._connectFirstOrSelect(
2429
+ usbDevices,
2430
+ usbTarget,
2431
+ allowUsbEphemeralFallback,
2432
+ preserveOperationId,
2433
+ context,
2434
+ internalSignal
2435
+ );
2436
+ }
2437
+ if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2438
+ throw createHwkError({
2439
+ code: HardwareErrorCode3.DeviceNotFound,
2440
+ message: "This Ledger model has no Bluetooth transport; connect it over USB"
2441
+ });
2442
+ }
2443
+ this._activeConnectionType = "ble";
2444
+ const knownBle = context?.knownConnections?.find(
2445
+ (connection) => connection.transport === "ble"
2446
+ );
2447
+ if (knownBle?.transport === "ble") {
2448
+ return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
1638
2449
  }
2450
+ const bleContext = context ?? {};
2451
+ bleContext.allowBleSelection = true;
2452
+ bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
2453
+ const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2454
+ return this._connectFirstOrSelect(
2455
+ bleDevices,
2456
+ void 0,
2457
+ allowUsbEphemeralFallback,
2458
+ preserveOperationId,
2459
+ bleContext,
2460
+ internalSignal
2461
+ );
2462
+ }
2463
+ if (this._isBleConnection() && targetConnectId) {
2464
+ return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
1639
2465
  }
1640
2466
  let confirms = 0;
1641
2467
  while (!internalSignal.aborted) {
@@ -1643,22 +2469,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1643
2469
  type: EConnectorInteraction.Searching,
1644
2470
  payload: { sessionId: "" }
1645
2471
  });
1646
- let devices = await this.searchDevices();
2472
+ let devices = await this._searchDevices(void 0, internalSignal);
2473
+ _LedgerAdapter._throwIfAborted(internalSignal);
1647
2474
  if (devices.length === 0) {
1648
2475
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
1649
2476
  await new Promise((resolve) => {
1650
2477
  setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
1651
2478
  });
1652
- devices = await this.searchDevices();
2479
+ _LedgerAdapter._throwIfAborted(internalSignal);
2480
+ devices = await this._searchDevices(void 0, internalSignal);
2481
+ _LedgerAdapter._throwIfAborted(internalSignal);
1653
2482
  if (devices.length > 0) break;
1654
2483
  }
1655
2484
  }
1656
- if (devices.length > 0) {
2485
+ if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1657
2486
  try {
1658
2487
  return await this._connectFirstOrSelect(
1659
2488
  devices,
1660
2489
  targetConnectId,
1661
- allowUsbEphemeralFallback
2490
+ allowUsbEphemeralFallback,
2491
+ preserveOperationId,
2492
+ context,
2493
+ internalSignal
1662
2494
  );
1663
2495
  } catch (err) {
1664
2496
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -1687,45 +2519,148 @@ var _LedgerAdapter = class _LedgerAdapter {
1687
2519
  _LedgerAdapter._throwIfAborted(internalSignal);
1688
2520
  throw new Error("_doConnect aborted");
1689
2521
  }
1690
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2522
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2523
+ _LedgerAdapter._throwIfAborted(signal);
1691
2524
  if (targetConnectId) {
1692
2525
  const target = devices.find(
1693
2526
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
1694
2527
  );
1695
2528
  if (target) {
1696
- return this._connectDeviceOrThrow(target.connectId);
2529
+ return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1697
2530
  }
1698
- if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2531
+ if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1699
2532
  debugLog(
1700
2533
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
1701
2534
  );
1702
- return this._connectDeviceOrThrow(devices[0].connectId);
2535
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1703
2536
  }
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;
2537
+ if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2538
+ const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2539
+ code: HardwareErrorCode3.DeviceNotFound
2540
+ });
2541
+ if (this._isBleConnection()) {
2542
+ err._tag = ERROR_TAG.DeviceNotAdvertising;
2543
+ }
2544
+ throw err;
1709
2545
  }
1710
- throw err;
1711
2546
  }
1712
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
2547
+ const requiresBleSelection = this._isBleConnection();
2548
+ if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
1713
2549
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1714
2550
  code: HardwareErrorCode3.DeviceNotFound
1715
2551
  });
1716
2552
  }
1717
- if (devices.length > 1) {
1718
- throw createMultipleUsbLedgerDevicesError();
2553
+ if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2554
+ const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2555
+ if (context) context.bindingSessionId = bindingSessionId;
2556
+ const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2557
+ const knownUsb = context?.knownConnections?.find(
2558
+ (connection) => connection.transport === "usb"
2559
+ );
2560
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
2561
+ const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
2562
+ const { device, requestId } = await requestBleDeviceSelection({
2563
+ emitter: this.emitter,
2564
+ registry: this._uiRegistry,
2565
+ signal,
2566
+ allowUsbFallback,
2567
+ scan: async () => {
2568
+ if (allowUsbFallback) {
2569
+ const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2570
+ const candidate = usbDevices.find(
2571
+ (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2572
+ ) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2573
+ if (candidate) return [candidate];
2574
+ }
2575
+ return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2576
+ },
2577
+ request: {
2578
+ devices,
2579
+ bindingSessionId,
2580
+ context: {
2581
+ kind: "bind-connection",
2582
+ transport: "ble",
2583
+ reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2584
+ },
2585
+ extra: context?.extra,
2586
+ operationId: preserveOperationId
2587
+ }
2588
+ });
2589
+ if (device.connectionType === "usb") {
2590
+ this._activeConnectionType = "usb";
2591
+ if (context) context.selectedConnection = void 0;
2592
+ this._bindingSelectionRequestId = requestId;
2593
+ this._finishBleBinding("cancelled");
2594
+ return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2595
+ }
2596
+ this._bindingSelectionRequestId = requestId;
2597
+ const connected = await this._connectDeviceOrThrow(
2598
+ device.connectId,
2599
+ preserveOperationId,
2600
+ signal
2601
+ );
2602
+ if (context) context.selectedConnection = { connectId: connected, requestId };
2603
+ if (context?.deferBindingSave) {
2604
+ context.pendingBinding = { connectId: connected, requestId };
2605
+ } else {
2606
+ await this._saveSelectedBleBinding(
2607
+ connected,
2608
+ requestId,
2609
+ context,
2610
+ preserveOperationId,
2611
+ signal
2612
+ );
2613
+ }
2614
+ return connected;
2615
+ }
2616
+ if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2617
+ if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2618
+ throw createHwkError({
2619
+ code: HardwareErrorCode3.DeviceNotFound,
2620
+ message: "Select a Ledger device before continuing"
2621
+ });
2622
+ }
2623
+ const requestId = this._uiRegistry.createRequestId();
2624
+ const operationId = this._activeOperationId();
2625
+ const waitPromise = this._uiRegistry.wait(
2626
+ UI_REQUEST.REQUEST_SELECT_DEVICE,
2627
+ { requestId, operationId }
2628
+ );
2629
+ this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
2630
+ type: UI_REQUEST.REQUEST_SELECT_DEVICE,
2631
+ payload: {
2632
+ devices,
2633
+ requestId,
2634
+ operationId,
2635
+ context: requiresBleSelection ? {
2636
+ kind: "bind-connection",
2637
+ transport: "ble",
2638
+ reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2639
+ } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2640
+ extra: context?.extra
2641
+ }
2642
+ });
2643
+ const { sdkConnectId } = await this._abortable(signal, waitPromise);
2644
+ _LedgerAdapter._throwIfAborted(signal);
2645
+ const selected = devices.find((device) => device.connectId === sdkConnectId);
2646
+ if (!selected) {
2647
+ throw Object.assign(new Error("Selected Ledger is no longer available"), {
2648
+ code: HardwareErrorCode3.DeviceNotFound
2649
+ });
2650
+ }
2651
+ if (context && requiresBleSelection)
2652
+ context.selectedConnection = { connectId: selected.connectId, requestId };
2653
+ return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1719
2654
  }
1720
2655
  if (devices.length !== 1) {
1721
2656
  throw Object.assign(new Error("Ledger device not found."), {
1722
2657
  code: HardwareErrorCode3.DeviceNotFound
1723
2658
  });
1724
2659
  }
1725
- return this._connectDeviceOrThrow(devices[0].connectId);
2660
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1726
2661
  }
1727
- async _connectDeviceOrThrow(chosenConnectId) {
1728
- const result = await this.connectDevice(chosenConnectId);
2662
+ async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2663
+ const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1729
2664
  if (!result.success) {
1730
2665
  const payload = result.payload;
1731
2666
  const rethrow = Object.assign(new Error(payload.error), {
@@ -1736,16 +2671,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1736
2671
  }
1737
2672
  throw rethrow;
1738
2673
  }
1739
- return chosenConnectId;
2674
+ return result.payload;
1740
2675
  }
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
2676
  /**
1750
2677
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
1751
2678
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -1766,33 +2693,145 @@ var _LedgerAdapter = class _LedgerAdapter {
1766
2693
  * lives in one place.
1767
2694
  */
1768
2695
  async _callConnector(sessionId, method, params, signal) {
1769
- const promise = this.connector.call(sessionId, method, params);
2696
+ this._assertConnectorReady(method);
2697
+ if (signal?.aborted) throw this._abortReason(signal);
2698
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2699
+ let promise;
2700
+ try {
2701
+ promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2702
+ } catch (error) {
2703
+ releaseOperation();
2704
+ throw error;
2705
+ }
1770
2706
  const result = signal ? await this._abortable(signal, promise) : await promise;
1771
2707
  return this._unwrapConnectorResult(result);
1772
2708
  }
2709
+ _assertConnectorReady(method) {
2710
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2711
+ throw _LedgerAdapter._createDeviceBusyError(method);
2712
+ }
2713
+ }
2714
+ _runConnectorTeardown(task) {
2715
+ const previous = this._connectorTeardownTail;
2716
+ let releaseTail = () => void 0;
2717
+ this._connectorTeardownTail = new Promise((resolve) => {
2718
+ releaseTail = resolve;
2719
+ });
2720
+ this._pendingConnectorTeardowns += 1;
2721
+ return (async () => {
2722
+ try {
2723
+ await previous;
2724
+ await this._waitForConnectorOperationsToDrain();
2725
+ await task();
2726
+ } finally {
2727
+ this._pendingConnectorTeardowns -= 1;
2728
+ releaseTail();
2729
+ }
2730
+ })();
2731
+ }
2732
+ _waitForConnectorOperationsToDrain() {
2733
+ if (this._unsettledConnectorOperations.size === 0) {
2734
+ return Promise.resolve();
2735
+ }
2736
+ return new Promise((resolve) => {
2737
+ this._connectorIdleWaiters.add(resolve);
2738
+ });
2739
+ }
2740
+ _retainConnectorOperation(key) {
2741
+ this._unsettledConnectorOperations.set(
2742
+ key,
2743
+ (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2744
+ );
2745
+ let released = false;
2746
+ return () => {
2747
+ if (released) return;
2748
+ released = true;
2749
+ const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2750
+ if (remaining > 0) {
2751
+ this._unsettledConnectorOperations.set(key, remaining);
2752
+ } else {
2753
+ this._unsettledConnectorOperations.delete(key);
2754
+ }
2755
+ if (this._unsettledConnectorOperations.size === 0) {
2756
+ for (const resolve of this._connectorIdleWaiters) resolve();
2757
+ this._connectorIdleWaiters.clear();
2758
+ }
2759
+ };
2760
+ }
1773
2761
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1774
- debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1775
- const queueKey = connectId || "__ledger_default__";
2762
+ const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
2763
+ if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2764
+ throw createHwkError({
2765
+ code: HardwareErrorCode3.InvalidParams,
2766
+ message: "Conflicting Ledger operation ids",
2767
+ params: {
2768
+ positionalOperationId,
2769
+ commonOperationId: commonParams.operationId
2770
+ }
2771
+ });
2772
+ }
2773
+ const operationId = commonParams?.operationId ?? positionalOperationId;
2774
+ const operation = operationId ? this._operations.resolve(operationId) : void 0;
2775
+ const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2776
+ const effectiveConnectId = operation?.connectId ?? connectId;
2777
+ debugLog("[LedgerAdapter][REQ]", {
2778
+ method,
2779
+ connectId: effectiveConnectId || "(empty)",
2780
+ params: summarizeForLog(params, { method })
2781
+ });
2782
+ const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1776
2783
  try {
1777
2784
  const result = await this._jobQueue.enqueue(
1778
2785
  queueKey,
1779
- async (signal) => this._runConnectorCall(
1780
- connectId,
1781
- method,
1782
- params,
1783
- signal,
1784
- fingerprint,
1785
- permissionDeviceId,
1786
- commonParams,
1787
- installContext
1788
- ),
2786
+ async (signal) => {
2787
+ if (operationId) this._activeOperationJobs.add(operationId);
2788
+ try {
2789
+ return await this._runConnectorCall(
2790
+ effectiveConnectId,
2791
+ method,
2792
+ params,
2793
+ signal,
2794
+ fingerprint,
2795
+ permissionDeviceId,
2796
+ commonParams,
2797
+ installContext ?? {},
2798
+ operationId
2799
+ );
2800
+ } catch (error) {
2801
+ const status = signal.aborted ? "cancelled" : "failed";
2802
+ const bundleConnectId = installContext?.connection?.connectId;
2803
+ let keptBundlePick = false;
2804
+ for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2805
+ if (pickedConnectId === bundleConnectId) {
2806
+ keptBundlePick = true;
2807
+ } else {
2808
+ this._pendingPickBindings.delete(pickedConnectId);
2809
+ this._discardPendingBinding(owner, status);
2810
+ await this._dropSession(pickedConnectId, signal);
2811
+ }
2812
+ }
2813
+ if (!keptBundlePick) this._finishBleBinding(status);
2814
+ throw error;
2815
+ } finally {
2816
+ if (operationId) {
2817
+ this._activeOperationJobs.delete(operationId);
2818
+ if (this._pendingOperationDisconnects.delete(operationId)) {
2819
+ await this._releaseLostOperationConnection(operationId);
2820
+ }
2821
+ }
2822
+ }
2823
+ },
1789
2824
  {
1790
2825
  label: method,
1791
2826
  rejectIfBusy: true,
1792
2827
  busyError: _LedgerAdapter._createDeviceBusyError(method)
1793
2828
  }
1794
2829
  );
1795
- debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2830
+ debugLog("[LedgerAdapter][RES]", {
2831
+ method,
2832
+ success: true,
2833
+ payload: summarizeForLog(result, { method, role: "result" })
2834
+ });
1796
2835
  return result;
1797
2836
  } catch (err) {
1798
2837
  const e = err;
@@ -1806,15 +2845,22 @@ var _LedgerAdapter = class _LedgerAdapter {
1806
2845
  }
1807
2846
  });
1808
2847
  throw err;
2848
+ } finally {
2849
+ releaseOperationRetention?.();
1809
2850
  }
1810
2851
  }
2852
+ /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2853
+ _abortReason(signal) {
2854
+ return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2855
+ }
1811
2856
  /**
1812
2857
  * Race a promise against an abort signal. On abort, rejects with
1813
2858
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
1814
2859
  */
1815
2860
  _abortable(signal, promise) {
1816
- const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2861
+ const getAbortReason = () => this._abortReason(signal);
1817
2862
  if (signal.aborted) {
2863
+ void promise.catch(() => void 0);
1818
2864
  return Promise.reject(getAbortReason());
1819
2865
  }
1820
2866
  return new Promise((resolve, reject) => {
@@ -1841,17 +2887,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1841
2887
  }
1842
2888
  }
1843
2889
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
1844
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2890
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1845
2891
  _LedgerAdapter._throwIfAborted(signal);
1846
- await this._ensureDevicePermission(
1847
- connectId,
1848
- permissionDeviceId ?? fingerprint?.deviceId,
1849
- signal
1850
- );
2892
+ if (!operationId) {
2893
+ await this._ensureDevicePermission(
2894
+ connectId,
2895
+ permissionDeviceId ?? fingerprint?.deviceId,
2896
+ signal
2897
+ );
2898
+ }
1851
2899
  _LedgerAdapter._throwIfAborted(signal);
1852
2900
  let effectiveParams = params;
1853
2901
  if (method === "btcGetPublicKey") {
1854
- const gatedParams = await this._gateBtcHighIndex(params);
2902
+ const gatedParams = await this._gateBtcHighIndex(params, signal);
1855
2903
  if (gatedParams === null) {
1856
2904
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
1857
2905
  _tag: ERROR_TAG.UserAborted,
@@ -1861,19 +2909,67 @@ var _LedgerAdapter = class _LedgerAdapter {
1861
2909
  effectiveParams = gatedParams;
1862
2910
  }
1863
2911
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
1864
- const resolvedConnectId = await this.ensureConnected(
1865
- connectId,
2912
+ let businessCallStarted = false;
2913
+ const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2914
+ const knownTransport = this._isBleConnection() ? "ble" : "usb";
2915
+ const hintedConnectId = commonParams?.knownConnections?.find(
2916
+ (connection) => connection.transport === knownTransport
2917
+ );
2918
+ const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2919
+ const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2920
+ const checksWallet = Boolean(
2921
+ fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2922
+ );
2923
+ const connectionAttempt = {
2924
+ ...commonParams,
2925
+ deferBindingSave: checksWallet
2926
+ };
2927
+ const bundleConnection = installContext?.connection;
2928
+ if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2929
+ throw createHwkError({
2930
+ code: HardwareErrorCode3.DeviceDisconnected,
2931
+ message: "Ledger all-network connection ended"
2932
+ });
2933
+ }
2934
+ const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2935
+ preferredConnectId,
1866
2936
  signal,
1867
- allowUsbEphemeralFallback
2937
+ allowUsbEphemeralFallback,
2938
+ void 0,
2939
+ connectionAttempt
1868
2940
  );
2941
+ const walletCheck = installContext?.walletCheck;
2942
+ if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2943
+ throw createHwkError({
2944
+ code: HardwareErrorCode3.DeviceMismatch,
2945
+ message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2946
+ });
2947
+ }
1869
2948
  const sessionId = this._sessions.get(resolvedConnectId);
2949
+ if (sessionId && installContext && !installContext.connection) {
2950
+ installContext.connection = { connectId: resolvedConnectId, sessionId };
2951
+ }
1870
2952
  if (!sessionId) {
2953
+ if (operationId) {
2954
+ this._operations.end(operationId, "disconnect");
2955
+ throw createHwkError({
2956
+ code: HardwareErrorCode3.OperationEnded,
2957
+ message: "Ledger operation connection is no longer active",
2958
+ params: { operationId, reason: "disconnect" }
2959
+ });
2960
+ }
1871
2961
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
1872
2962
  _tag: ERROR_TAG.DeviceSessionNotFound
1873
2963
  });
1874
2964
  }
1875
2965
  try {
1876
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2966
+ const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2967
+ if (!operationId && connectionAttempt.pendingBinding) {
2968
+ this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2969
+ }
2970
+ const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2971
+ const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2972
+ if (fingerprint && checksWallet) {
1877
2973
  const fp = await this._abortable(
1878
2974
  signal,
1879
2975
  this._verifyDeviceFingerprintWithSession(
@@ -1883,14 +2979,68 @@ var _LedgerAdapter = class _LedgerAdapter {
1883
2979
  )
1884
2980
  );
1885
2981
  if (!fp.success) {
2982
+ if (pendingBinding) {
2983
+ this._discardPendingBinding(bindingOwner, "failed");
2984
+ this._pendingPickBindings.delete(resolvedConnectId);
2985
+ }
2986
+ if (operationId) {
2987
+ this._pendingOperationBindings.delete(operationId);
2988
+ this._operations.end(operationId, "explicit");
2989
+ await this._dropSession(resolvedConnectId, signal);
2990
+ }
1886
2991
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
1887
2992
  code: HardwareErrorCode3.DeviceMismatch
1888
2993
  });
1889
2994
  }
2995
+ if (walletCheck) walletCheck.verified = true;
2996
+ }
2997
+ if (pendingBinding && bindingOwner) {
2998
+ bindingOwner.pendingBinding = void 0;
2999
+ if (operationId) this._pendingOperationBindings.delete(operationId);
3000
+ else this._pendingPickBindings.delete(resolvedConnectId);
3001
+ await this._saveSelectedBleBinding(
3002
+ pendingBinding.connectId,
3003
+ pendingBinding.requestId,
3004
+ bindingOwner,
3005
+ operationId,
3006
+ signal,
3007
+ fingerprint && checksWallet ? {
3008
+ vendor: "ledger",
3009
+ type: "chainFingerprint",
3010
+ chain: fingerprint.chain,
3011
+ value: fingerprint.deviceId
3012
+ } : void 0
3013
+ );
1890
3014
  }
1891
- return await this._callConnector(sessionId, method, effectiveParams, signal);
3015
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
3016
+ this._selectedBleReconnectTargets.set(connectId, {
3017
+ connectId: resolvedConnectId,
3018
+ chain: fingerprint.chain,
3019
+ fingerprint: fingerprint.deviceId
3020
+ });
3021
+ }
3022
+ businessCallStarted = true;
3023
+ const result = await this._callConnector(sessionId, method, effectiveParams, signal);
3024
+ if (walletCheck) walletCheck.derived = true;
3025
+ return result;
1892
3026
  } catch (err) {
1893
3027
  if (signal.aborted) throw err;
3028
+ if (isLostConnectionError(err)) {
3029
+ this._discoveredDevices.delete(resolvedConnectId);
3030
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3031
+ else {
3032
+ this._sessions.delete(resolvedConnectId);
3033
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3034
+ }
3035
+ const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
3036
+ const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
3037
+ throw createHwkError({
3038
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
3039
+ message: "Ledger operation connection was lost; start a new operation",
3040
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
3041
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3042
+ });
3043
+ }
1894
3044
  const errObj = err;
1895
3045
  debugLog("[LedgerAdapter] connectorCall error:", method, {
1896
3046
  message: errObj?.message,
@@ -1902,6 +3052,64 @@ var _LedgerAdapter = class _LedgerAdapter {
1902
3052
  isNotAdvertising: isDeviceNotAdvertisingError(err),
1903
3053
  isStuckApp: isStuckAppStateError(err)
1904
3054
  });
3055
+ const assertSessionCurrent = (message) => {
3056
+ if (this._sessions.get(resolvedConnectId) === sessionId) return;
3057
+ throw createHwkError({
3058
+ code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
3059
+ message
3060
+ });
3061
+ };
3062
+ if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
3063
+ await this._waitForDeviceConnect(signal);
3064
+ assertSessionCurrent("Ledger connection ended while waiting for unlock");
3065
+ if (walletCheck?.derived) walletCheck.verified = false;
3066
+ return this._runConnectorCall(
3067
+ resolvedConnectId,
3068
+ method,
3069
+ effectiveParams,
3070
+ signal,
3071
+ fingerprint,
3072
+ permissionDeviceId,
3073
+ commonParams,
3074
+ installContext,
3075
+ operationId,
3076
+ lockedRetryBudget - 1
3077
+ );
3078
+ }
3079
+ if (businessCallStarted && isStuckAppStateError(err)) {
3080
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
3081
+ assertSessionCurrent("Ledger connection ended during the app transition");
3082
+ try {
3083
+ const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
3084
+ if (walletCheck) walletCheck.derived = true;
3085
+ return retried;
3086
+ } catch (retryErr) {
3087
+ if (isStuckAppStateError(retryErr)) throw err;
3088
+ if (isLostConnectionError(retryErr)) {
3089
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3090
+ else {
3091
+ this._sessions.delete(resolvedConnectId);
3092
+ this._discoveredDevices.delete(resolvedConnectId);
3093
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3094
+ }
3095
+ const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
3096
+ throw createHwkError({
3097
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
3098
+ message: `Ledger ${method} may have completed before the connection was lost`,
3099
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3100
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3101
+ });
3102
+ }
3103
+ throw retryErr;
3104
+ }
3105
+ }
3106
+ if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
3107
+ this._sessions.delete(resolvedConnectId);
3108
+ this._sessionTransports.delete(sessionId);
3109
+ this._discoveredDevices.delete(resolvedConnectId);
3110
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3111
+ throw err;
3112
+ }
1905
3113
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
1906
3114
  const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
1907
3115
  if (autoInstallApp && isAppMissing) {
@@ -1918,7 +3126,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1918
3126
  appName
1919
3127
  });
1920
3128
  }
1921
- const confirmed = await this._waitForInstallAppConfirm(appName);
3129
+ const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1922
3130
  if (!confirmed) {
1923
3131
  throw createHwkError({
1924
3132
  code: HardwareErrorCode3.UserAborted,
@@ -1947,7 +3155,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1947
3155
  }
1948
3156
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
1949
3157
  type: UI_REQUEST.CLOSE_UI_WINDOW,
1950
- payload: {}
3158
+ payload: { operationId }
1951
3159
  });
1952
3160
  return await this._runConnectorCall(
1953
3161
  resolvedConnectId,
@@ -1957,157 +3165,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1957
3165
  fingerprint,
1958
3166
  permissionDeviceId,
1959
3167
  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
3168
+ installContext,
3169
+ operationId
2001
3170
  );
2002
- throw retryErr;
2003
- }
2004
- }
2005
- if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
2006
- let lastErr = err;
2007
- for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
2008
- if (signal.aborted) throw lastErr;
2009
- try {
2010
- this._sessions.delete(resolvedConnectId);
2011
- this._discoveredDevices.delete(resolvedConnectId);
2012
- if (isDeviceDisconnectedError(lastErr)) {
2013
- try {
2014
- this.connector.reset?.();
2015
- } catch {
2016
- }
2017
- }
2018
- const reConnectId = await this.ensureConnected(
2019
- resolvedConnectId,
2020
- signal,
2021
- allowUsbEphemeralFallback
2022
- );
2023
- const reSessionId = this._sessions.get(reConnectId);
2024
- if (!reSessionId) throw lastErr;
2025
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2026
- const fp = await this._abortable(
2027
- signal,
2028
- this._verifyDeviceFingerprintWithSession(
2029
- reSessionId,
2030
- fingerprint.deviceId,
2031
- fingerprint.chain
2032
- )
2033
- );
2034
- if (!fp.success) {
2035
- throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2036
- code: HardwareErrorCode3.DeviceMismatch
2037
- });
2038
- }
2039
- }
2040
- return await this._callConnector(reSessionId, method, effectiveParams, signal);
2041
- } catch (retryErr) {
2042
- if (signal.aborted) throw retryErr;
2043
- lastErr = retryErr;
2044
- const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
2045
- if (!canRetry) {
2046
- throw retryErr;
2047
- }
2048
- }
2049
3171
  }
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
3172
  }
2074
3173
  throw err;
2075
3174
  }
2076
3175
  }
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
3176
  _sleepAbortable(ms, signal) {
2112
3177
  return new Promise((resolve, reject) => {
2113
3178
  if (signal.aborted) {
@@ -2126,111 +3191,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2126
3191
  });
2127
3192
  }
2128
3193
  /**
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
3194
+ * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3195
+ * replies. Without connectId the request is environment-level, else device-level.
2221
3196
  */
2222
3197
  async _ensureDevicePermission(connectId, deviceId, signal) {
2223
3198
  if (signal?.aborted) {
2224
3199
  _LedgerAdapter._throwIfAborted(signal);
2225
3200
  }
2226
3201
  const transportType = this.activeTransport ?? "hid";
3202
+ const operationId = this._activeOperationId();
2227
3203
  const waitPromise = this._uiRegistry.wait(
2228
3204
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2229
- { timeoutMs: 6e4 }
3205
+ { timeoutMs: 6e4, operationId }
2230
3206
  );
2231
3207
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2232
3208
  type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2233
- payload: { transportType, connectId, deviceId }
3209
+ payload: { transportType, connectId, deviceId, operationId }
2234
3210
  });
2235
3211
  let response;
2236
3212
  const onAbort = () => {
@@ -2246,7 +3222,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2246
3222
  if (err?._tag === UI_REQUEST_PREEMPTED_TAG) {
2247
3223
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
2248
3224
  type: UI_REQUEST.CLOSE_UI_WINDOW,
2249
- payload: {}
3225
+ payload: { operationId }
2250
3226
  });
2251
3227
  throw Object.assign(new Error("Device permission request superseded"), {
2252
3228
  _tag: ERROR_TAG.UserAborted,
@@ -2276,7 +3252,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2276
3252
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
2277
3253
  const e = err;
2278
3254
  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);
3255
+ return ledgerFailure(
3256
+ e.code,
3257
+ e.message ?? "Unknown error",
3258
+ e.appName,
3259
+ tag,
3260
+ params,
3261
+ void 0,
3262
+ isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
3263
+ );
2280
3264
  }
2281
3265
  const mapped = mapLedgerError(err);
2282
3266
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -2303,7 +3287,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2303
3287
  deviceId: device.deviceId,
2304
3288
  connectId: device.connectId,
2305
3289
  label: device.name,
2306
- connectionType: this.connector.connectionType,
3290
+ connectionType: device.connectionType ?? this.connector.connectionType,
2307
3291
  rssi: device.rssi,
2308
3292
  isConnectable: device.isConnectable,
2309
3293
  serialNumber: device.serialNumber,
@@ -2329,8 +3313,9 @@ var LedgerAdapter = _LedgerAdapter;
2329
3313
 
2330
3314
  // src/connector/LedgerConnectorBase.ts
2331
3315
  import {
2332
- EConnectorInteraction as EConnectorInteraction4,
2333
- HardwareErrorCode as HardwareErrorCode8,
3316
+ EConnectorInteraction as EConnectorInteraction3,
3317
+ HardwareErrorCode as HardwareErrorCode7,
3318
+ createHwkError as createHwkError2,
2334
3319
  isKnownNonTargetHardwareVendor,
2335
3320
  serializeConnectorError
2336
3321
  } from "@onekeyfe/hwk-adapter-core";
@@ -2603,7 +3588,7 @@ var LedgerDeviceManager = class {
2603
3588
 
2604
3589
  // src/signer/SignerManager.ts
2605
3590
  import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
2606
- import { ContextModuleBuilder } from "@ledgerhq/context-module";
3591
+ import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
2607
3592
 
2608
3593
  // src/signer/SignerEth.ts
2609
3594
  import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
@@ -2611,11 +3596,15 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
2611
3596
  // src/signer/deviceActionToPromise.ts
2612
3597
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
2613
3598
  var IDLE_WATCHDOG_MS = 65e3;
3599
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3600
+ var INTERACTION_PROMPT_DELAY_MS = 500;
2614
3601
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
2615
3602
  return new Promise((resolve, reject) => {
2616
3603
  let settled = false;
2617
3604
  let lastStep;
2618
3605
  let activeInteraction;
3606
+ let pendingInteraction;
3607
+ let pendingInteractionTimer = null;
2619
3608
  const observedSteps = [];
2620
3609
  let sub;
2621
3610
  let timer = null;
@@ -2643,31 +3632,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
2643
3632
  }
2644
3633
  return false;
2645
3634
  };
3635
+ const cancelPendingInteraction = () => {
3636
+ if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
3637
+ pendingInteractionTimer = null;
3638
+ pendingInteraction = void 0;
3639
+ };
3640
+ const showInteraction = (interactionName) => {
3641
+ activeInteraction = interactionName;
3642
+ debugLog(
3643
+ "[DeviceAction] requiredUserInteraction",
3644
+ `interaction=${interactionName}`,
3645
+ `step=${lastStep ?? "unknown"}`
3646
+ );
3647
+ if (interactionName === "unlock-device" && timer) {
3648
+ clearTimeout(timer);
3649
+ timer = null;
3650
+ }
3651
+ onInteraction?.(interactionName);
3652
+ };
2646
3653
  const emitInteraction = (interaction) => {
2647
3654
  if (!onInteraction) {
2648
3655
  return;
2649
3656
  }
2650
3657
  if (!interaction || interaction === "none") {
3658
+ cancelPendingInteraction();
2651
3659
  clearActiveInteraction();
2652
3660
  return;
2653
3661
  }
2654
3662
  const interactionName = String(interaction);
2655
- if (interactionName === activeInteraction) {
3663
+ if (interactionName === activeInteraction || interactionName === pendingInteraction) {
2656
3664
  return;
2657
3665
  }
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;
3666
+ cancelPendingInteraction();
3667
+ clearActiveInteraction();
3668
+ if (interactionName === "unlock-device") {
3669
+ showInteraction(interactionName);
3670
+ return;
2667
3671
  }
2668
- onInteraction(interactionName);
3672
+ pendingInteraction = interactionName;
3673
+ pendingInteractionTimer = setTimeout(() => {
3674
+ pendingInteractionTimer = null;
3675
+ pendingInteraction = void 0;
3676
+ if (!settled) showInteraction(interactionName);
3677
+ }, INTERACTION_PROMPT_DELAY_MS);
2669
3678
  };
2670
3679
  const completeInteraction = () => {
3680
+ cancelPendingInteraction();
2671
3681
  if (!clearActiveInteraction()) {
2672
3682
  onInteraction?.("interaction-complete");
2673
3683
  }
@@ -2798,7 +3808,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
2798
3808
  }
2799
3809
 
2800
3810
  // src/signer/SignerEth.ts
2801
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2802
3811
  var SignerEth = class {
2803
3812
  // eslint-disable-next-line no-useless-constructor, no-empty-function
2804
3813
  constructor(_sdk) {
@@ -2869,7 +3878,7 @@ var SignerManager = class _SignerManager {
2869
3878
  return (args) => new SignerEthBuilder(args);
2870
3879
  }
2871
3880
  static _createContextModule() {
2872
- const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
3881
+ const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2873
3882
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
2874
3883
  }
2875
3884
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -2907,6 +3916,27 @@ function collapseSignerInteraction(interaction) {
2907
3916
  return EConnectorInteraction2.ConfirmOnDevice;
2908
3917
  }
2909
3918
  }
3919
+ function wireSignerToSession(ctx, sessionId, chain, signer) {
3920
+ signer.onInteraction = (interaction) => {
3921
+ debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3922
+ ctx.emit("ui-event", {
3923
+ type: collapseSignerInteraction(interaction),
3924
+ payload: { sessionId }
3925
+ });
3926
+ };
3927
+ signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3928
+ return signer;
3929
+ }
3930
+ async function runSignerCall(ctx, sessionId, call) {
3931
+ try {
3932
+ return await call();
3933
+ } catch (err) {
3934
+ ctx.invalidateSession(sessionId);
3935
+ throw ctx.wrapError(err);
3936
+ } finally {
3937
+ ctx.clearCanceller(sessionId);
3938
+ }
3939
+ }
2910
3940
 
2911
3941
  // src/connector/chains/evm.ts
2912
3942
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3007,14 +4037,13 @@ async function _getEthSigner(ctx, sessionId) {
3007
4037
 
3008
4038
  // src/connector/chains/btc.ts
3009
4039
  import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
3010
- import { Psbt } from "bitcoinjs-lib";
4040
+ import { Psbt as Psbt2 } from "bitcoinjs-lib";
3011
4041
 
3012
4042
  // src/signer/SignerBtc.ts
3013
4043
  import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
3014
4044
  function hexToUtf8(hex) {
3015
4045
  return new TextDecoder().decode(hexToBytes2(hex));
3016
4046
  }
3017
- var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3018
4047
  var SignerBtc = class {
3019
4048
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3020
4049
  constructor(_sdk) {
@@ -3028,7 +4057,7 @@ var SignerBtc = class {
3028
4057
  return deviceActionToPromise(
3029
4058
  action,
3030
4059
  this.onInteraction,
3031
- void 0,
4060
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3032
4061
  this.onRegisterCanceller
3033
4062
  );
3034
4063
  }
@@ -3046,14 +4075,14 @@ var SignerBtc = class {
3046
4075
  const result = await deviceActionToPromise(
3047
4076
  action,
3048
4077
  this.onInteraction,
3049
- void 0,
4078
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3050
4079
  this.onRegisterCanceller
3051
4080
  );
3052
4081
  debugLog(
3053
4082
  "[SignerBtc] getExtendedPublicKey result type:",
3054
4083
  typeof result,
3055
4084
  "value:",
3056
- typeof result === "string" ? `${result.substring(0, 20)}...` : JSON.stringify(result).substring(0, 50)
4085
+ summarizeForLog(result)
3057
4086
  );
3058
4087
  if (typeof result === "string") return result;
3059
4088
  return result.extendedPublicKey;
@@ -3082,7 +4111,7 @@ var SignerBtc = class {
3082
4111
  return deviceActionToPromise(
3083
4112
  action,
3084
4113
  this.onInteraction,
3085
- INTERACTIVE_TIMEOUT_MS2,
4114
+ INTERACTIVE_TIMEOUT_MS,
3086
4115
  this.onRegisterCanceller
3087
4116
  );
3088
4117
  }
@@ -3095,7 +4124,7 @@ var SignerBtc = class {
3095
4124
  return deviceActionToPromise(
3096
4125
  action,
3097
4126
  this.onInteraction,
3098
- INTERACTIVE_TIMEOUT_MS2,
4127
+ INTERACTIVE_TIMEOUT_MS,
3099
4128
  this.onRegisterCanceller
3100
4129
  );
3101
4130
  }
@@ -3108,7 +4137,7 @@ var SignerBtc = class {
3108
4137
  return deviceActionToPromise(
3109
4138
  action,
3110
4139
  this.onInteraction,
3111
- INTERACTIVE_TIMEOUT_MS2,
4140
+ INTERACTIVE_TIMEOUT_MS,
3112
4141
  this.onRegisterCanceller
3113
4142
  );
3114
4143
  }
@@ -3131,7 +4160,21 @@ function _purposeToTemplate(purpose, DDT) {
3131
4160
  });
3132
4161
  }
3133
4162
  }
4163
+ function assertBitcoinMainnet(coin) {
4164
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4165
+ throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4166
+ code: HardwareErrorCode5.ChainNotSupported
4167
+ });
4168
+ }
4169
+ }
3134
4170
  async function btcGetAddress(ctx, sessionId, params) {
4171
+ assertBitcoinMainnet(params.coin);
4172
+ if (normalizePath(params.path).split("/").length !== 3) {
4173
+ throw Object.assign(
4174
+ new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4175
+ { code: HardwareErrorCode5.InvalidParams }
4176
+ );
4177
+ }
3135
4178
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3136
4179
  const path = normalizePath(params.path);
3137
4180
  try {
@@ -3162,6 +4205,7 @@ async function btcGetAddress(ctx, sessionId, params) {
3162
4205
  }
3163
4206
  }
3164
4207
  async function btcGetPublicKey(ctx, sessionId, params) {
4208
+ assertBitcoinMainnet(params.coin);
3165
4209
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3166
4210
  const path = normalizePath(params.path);
3167
4211
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -3169,7 +4213,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
3169
4213
  const xpub = await btcSigner.getExtendedPublicKey(path, {
3170
4214
  checkOnDevice: params.showOnDevice ?? false
3171
4215
  });
3172
- debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", `${xpub?.substring(0, 20)}...`);
4216
+ debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
3173
4217
  return { xpub, path: params.path };
3174
4218
  } catch (err) {
3175
4219
  debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
@@ -3290,7 +4334,7 @@ function _isScriptPathInput(input) {
3290
4334
  return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
3291
4335
  }
3292
4336
  function _applySignaturesToPsbt(psbtHex, signatures) {
3293
- const psbt = Psbt.fromHex(psbtHex);
4337
+ const psbt = Psbt2.fromHex(psbtHex);
3294
4338
  for (const sig of signatures) {
3295
4339
  const input = psbt.data.inputs[sig.inputIndex];
3296
4340
  if (!input) {
@@ -3339,7 +4383,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
3339
4383
  }
3340
4384
 
3341
4385
  // src/connector/chains/sol.ts
3342
- import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
4386
+ import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
4387
+ import bs58 from "bs58";
3343
4388
 
3344
4389
  // src/signer/SignerSol.ts
3345
4390
  var SignerSol = class {
@@ -3357,7 +4402,7 @@ var SignerSol = class {
3357
4402
  return deviceActionToPromise(
3358
4403
  action,
3359
4404
  this.onInteraction,
3360
- void 0,
4405
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3361
4406
  this.onRegisterCanceller
3362
4407
  );
3363
4408
  }
@@ -3369,7 +4414,7 @@ var SignerSol = class {
3369
4414
  return deviceActionToPromise(
3370
4415
  action,
3371
4416
  this.onInteraction,
3372
- void 0,
4417
+ INTERACTIVE_TIMEOUT_MS,
3373
4418
  this.onRegisterCanceller
3374
4419
  );
3375
4420
  }
@@ -3382,7 +4427,7 @@ var SignerSol = class {
3382
4427
  return deviceActionToPromise(
3383
4428
  action,
3384
4429
  this.onInteraction,
3385
- void 0,
4430
+ INTERACTIVE_TIMEOUT_MS,
3386
4431
  this.onRegisterCanceller
3387
4432
  );
3388
4433
  }
@@ -3423,8 +4468,21 @@ async function solSignMessage(ctx, sessionId, params) {
3423
4468
  const path = normalizePath(params.path);
3424
4469
  const messageBytes = hexToBytes3(params.message);
3425
4470
  try {
4471
+ if (params.messageVersion === 1) {
4472
+ const preparedMessage = prepareSolanaOffchainMessageV1({
4473
+ message: messageBytes,
4474
+ requiredSigners: params.requiredSigners
4475
+ });
4476
+ const { SignMessageVersion } = await ctx.importLedgerKit(
4477
+ "@ledgerhq/device-signer-kit-solana"
4478
+ );
4479
+ const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4480
+ version: SignMessageVersion.Raw
4481
+ });
4482
+ return { signature: decodeBase58Signature(result2.signature) };
4483
+ }
3426
4484
  const result = await solSigner.signMessage(path, messageBytes);
3427
- return { signature: result.signature };
4485
+ return { signature: decodeBase58EnvelopeSignature(result.signature) };
3428
4486
  } catch (err) {
3429
4487
  ctx.invalidateSession(sessionId);
3430
4488
  throw ctx.wrapError(err);
@@ -3432,11 +4490,27 @@ async function solSignMessage(ctx, sessionId, params) {
3432
4490
  ctx.clearCanceller(sessionId);
3433
4491
  }
3434
4492
  }
4493
+ function decodeBase58Signature(signature) {
4494
+ const bytes = bs58.decode(signature);
4495
+ if (bytes.length !== 64) {
4496
+ throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4497
+ }
4498
+ return bytesToHex(bytes);
4499
+ }
4500
+ function decodeBase58EnvelopeSignature(envelope) {
4501
+ const bytes = bs58.decode(envelope);
4502
+ if (bytes.length < 65 || bytes[0] !== 1) {
4503
+ throw new Error("Ledger Solana signature envelope is invalid");
4504
+ }
4505
+ return bytesToHex(bytes.subarray(1, 65));
4506
+ }
3435
4507
  async function _createSolSigner(ctx, sessionId) {
3436
4508
  const dmk = await ctx.getOrCreateDmk();
3437
- const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4509
+ const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4510
+ "@ledgerhq/context-module"
4511
+ );
3438
4512
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
3439
- const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4513
+ const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3440
4514
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
3441
4515
  const signer = new SignerSol(sdkSigner);
3442
4516
  signer.onInteraction = (interaction) => {
@@ -3452,361 +4526,147 @@ async function _createSolSigner(ctx, sessionId) {
3452
4526
  return signer;
3453
4527
  }
3454
4528
 
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";
4529
+ // src/connector/chains/zcash.ts
4530
+ import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
3461
4531
 
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);
4532
+ // src/signer/SignerZcash.ts
4533
+ var SignerZcash = class {
4534
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4535
+ constructor(_sdk) {
4536
+ this._sdk = _sdk;
3528
4537
  }
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
- }
4538
+ /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4539
+ async getFullViewingKey(derivationPath, options) {
4540
+ const action = this._sdk.getFullViewingKey(derivationPath, options);
4541
+ return deviceActionToPromise(
4542
+ action,
4543
+ this.onInteraction,
4544
+ void 0,
4545
+ this.onRegisterCanceller
3565
4546
  );
3566
4547
  }
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})`
4548
+ /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4549
+ async getShieldedAddress(derivationPath, options) {
4550
+ const action = this._sdk.getShieldedAddress(derivationPath, options);
4551
+ return deviceActionToPromise(
4552
+ action,
4553
+ this.onInteraction,
4554
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4555
+ this.onRegisterCanceller
3629
4556
  );
3630
4557
  }
3631
- _isDashboard(appName) {
3632
- return appName === DASHBOARD_APP_NAME;
3633
- }
3634
- _wait() {
3635
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3636
- }
3637
4558
  };
3638
4559
 
3639
- // src/connector/chains/legacyChainCall.ts
3640
- function isLegacyWrongAppError(err, _appName) {
3641
- return isWrongAppError(err);
4560
+ // src/connector/chains/zcash.ts
4561
+ async function zcashGetFullViewingKey(ctx, sessionId, params) {
4562
+ const signer = await _createZcashSigner(ctx, sessionId);
4563
+ const path = normalizePath(params.path);
4564
+ const mode = params.mode ?? "ufvk";
4565
+ return runSignerCall(ctx, sessionId, async () => {
4566
+ const result = await signer.getFullViewingKey(path, { mode });
4567
+ if (result.mode === "ufvk") {
4568
+ return { path: params.path, mode, ufvk: result.fullViewingKey };
4569
+ }
4570
+ return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
4571
+ });
3642
4572
  }
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 }
4573
+ async function zcashGetShieldedAddress(ctx, sessionId, params) {
4574
+ const signer = await _createZcashSigner(ctx, sessionId);
4575
+ const path = normalizePath(params.path);
4576
+ return runSignerCall(ctx, sessionId, async () => {
4577
+ const result = await signer.getShieldedAddress(path, {
4578
+ checkOnDevice: params.showOnDevice ?? false
3651
4579
  });
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
- }
4580
+ return { address: result.address, path: params.path };
4581
+ });
3719
4582
  }
3720
- async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4583
+ async function _createZcashSigner(ctx, sessionId) {
3721
4584
  const dmk = await ctx.getOrCreateDmk();
3722
- const appManager = new AppManager(dmk);
3723
- await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4585
+ const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4586
+ const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4587
+ return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3724
4588
  }
3725
4589
 
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;
4590
+ // src/connector/chains/tron.ts
4591
+ import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
4592
+
4593
+ // src/signer/SignerTron.ts
4594
+ var SignerTron = class {
4595
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4596
+ constructor(_sdk) {
4597
+ this._sdk = _sdk;
4598
+ }
4599
+ /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4600
+ async getAddress(derivationPath, options) {
4601
+ const action = this._sdk.getAddress(derivationPath, options);
4602
+ const result = await deviceActionToPromise(
4603
+ action,
4604
+ this.onInteraction,
4605
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4606
+ this.onRegisterCanceller
4607
+ );
4608
+ return { address: result.address, publicKey: result.publicKey };
3733
4609
  }
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;
4610
+ /** Sign a protobuf-encoded raw transaction. */
4611
+ async signTransaction(derivationPath, transaction, options) {
4612
+ const action = this._sdk.signTransaction(derivationPath, transaction, options);
4613
+ return deviceActionToPromise(
4614
+ action,
4615
+ this.onInteraction,
4616
+ INTERACTIVE_TIMEOUT_MS,
4617
+ this.onRegisterCanceller
4618
+ );
3746
4619
  }
3747
- async close() {
4620
+ /** Sign a personal message (TIP-191). */
4621
+ async signPersonalMessage(derivationPath, message, options) {
4622
+ const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4623
+ return deviceActionToPromise(
4624
+ action,
4625
+ this.onInteraction,
4626
+ INTERACTIVE_TIMEOUT_MS,
4627
+ this.onRegisterCanceller
4628
+ );
3748
4629
  }
3749
4630
  };
3750
4631
 
3751
4632
  // src/connector/chains/tron.ts
3752
4633
  async function tronGetAddress(ctx, sessionId, params) {
4634
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3753
4635
  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
- );
4636
+ return runSignerCall(ctx, sessionId, async () => {
4637
+ const result = await tronSigner.getAddress(path, {
4638
+ checkOnDevice: params.showOnDevice ?? false
4639
+ });
4640
+ return { address: result.address, publicKey: result.publicKey, path: params.path };
4641
+ });
3770
4642
  }
3771
4643
  async function tronSignTransaction(ctx, sessionId, params) {
3772
4644
  if (!params.rawTxHex) {
3773
4645
  throw Object.assign(
3774
4646
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
3775
- { code: HardwareErrorCode7.InvalidParams }
4647
+ { code: HardwareErrorCode6.InvalidParams }
3776
4648
  );
3777
4649
  }
4650
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3778
4651
  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
- );
4652
+ return runSignerCall(ctx, sessionId, async () => {
4653
+ const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
4654
+ return { signature: bytesToHex3(signature) };
4655
+ });
3793
4656
  }
3794
4657
  async function tronSignMessage(ctx, sessionId, params) {
4658
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3795
4659
  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
- );
4660
+ return runSignerCall(ctx, sessionId, async () => {
4661
+ const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
4662
+ return { signature: bytesToHex3(signature) };
4663
+ });
3806
4664
  }
3807
- async function _createTrx(ctx, sessionId) {
4665
+ async function _createTronSigner(ctx, sessionId) {
3808
4666
  const dmk = await ctx.getOrCreateDmk();
3809
- return new Trx(new DmkTransport(dmk, sessionId));
4667
+ const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4668
+ const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4669
+ return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3810
4670
  }
3811
4671
 
3812
4672
  // src/device-apps/customActions.ts
@@ -3985,7 +4845,7 @@ var DeviceApps = class {
3985
4845
  seTargetId: v.seTargetId,
3986
4846
  mcuTargetId: v.mcuTargetId,
3987
4847
  seVersion: v.seVersion,
3988
- seFlagsHex: bytesToHex2(v.seFlags),
4848
+ seFlagsHex: bytesToHex4(v.seFlags),
3989
4849
  mcuSephVersion: v.mcuSephVersion,
3990
4850
  mcuBootloaderVersion: v.mcuBootloaderVersion,
3991
4851
  hwVersion: v.hwVersion
@@ -4059,7 +4919,7 @@ var DeviceApps = class {
4059
4919
  }
4060
4920
  }
4061
4921
  };
4062
- function bytesToHex2(bytes) {
4922
+ function bytesToHex4(bytes) {
4063
4923
  if (!bytes) return "";
4064
4924
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4065
4925
  }
@@ -4102,10 +4962,19 @@ var METHOD_PREFIX_TO_APP_NAME = {
4102
4962
  evm: "Ethereum",
4103
4963
  btc: "Bitcoin",
4104
4964
  sol: "Solana",
4105
- tron: "Tron"
4965
+ tron: "Tron",
4966
+ zcash: "Zcash"
4106
4967
  };
4968
+ function withOpenAppName(event, data, appName) {
4969
+ if (event !== "ui-event") return data;
4970
+ const uiEvent = data;
4971
+ if (uiEvent.type !== EConnectorInteraction3.ConfirmOpenApp || uiEvent.payload.appName) {
4972
+ return data;
4973
+ }
4974
+ return { ...uiEvent, payload: { ...uiEvent.payload, appName } };
4975
+ }
4107
4976
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4108
- Object.values(HardwareErrorCode8).filter((value) => typeof value === "number")
4977
+ Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4109
4978
  );
4110
4979
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4111
4980
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4142,6 +5011,10 @@ async function defaultLedgerKitImporter(pkg) {
4142
5011
  return import("@ledgerhq/device-signer-kit-bitcoin");
4143
5012
  case "@ledgerhq/device-signer-kit-solana":
4144
5013
  return import("@ledgerhq/device-signer-kit-solana");
5014
+ case "@ledgerhq/device-signer-kit-tron":
5015
+ return import("@ledgerhq/device-signer-kit-tron");
5016
+ case "@ledgerhq/device-signer-kit-zcash":
5017
+ return import("@ledgerhq/device-signer-kit-zcash");
4145
5018
  case "@ledgerhq/context-module":
4146
5019
  return import("@ledgerhq/context-module");
4147
5020
  default:
@@ -4201,6 +5074,7 @@ var LedgerConnectorBase = class {
4201
5074
  this._ctx = {
4202
5075
  emit: (event, data) => this._emit(event, data),
4203
5076
  invalidateSession: (sid) => this._invalidateSession(sid),
5077
+ teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4204
5078
  wrapError: (err, opts) => this._wrapError(err, opts),
4205
5079
  getOrCreateDmk: () => this._getOrCreateDmk(),
4206
5080
  getDeviceManager: () => this._getDeviceManager(),
@@ -4300,7 +5174,7 @@ var LedgerConnectorBase = class {
4300
5174
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
4301
5175
  );
4302
5176
  err._tag = ERROR_TAG.BlePairingTimeout;
4303
- err.code = HardwareErrorCode8.BlePairingTimeout;
5177
+ err.code = HardwareErrorCode7.BlePairingTimeout;
4304
5178
  reject(err);
4305
5179
  }, HANG_CEILING_MS);
4306
5180
  });
@@ -4333,7 +5207,7 @@ var LedgerConnectorBase = class {
4333
5207
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
4334
5208
  );
4335
5209
  err._tag = ERROR_TAG.DeviceNotAdvertising;
4336
- err.code = HardwareErrorCode8.DeviceNotFound;
5210
+ err.code = HardwareErrorCode7.DeviceNotFound;
4337
5211
  throw err;
4338
5212
  };
4339
5213
  const doConnect = async (path) => {
@@ -4389,15 +5263,22 @@ var LedgerConnectorBase = class {
4389
5263
  } catch (err) {
4390
5264
  this._resetSignersAndSessions();
4391
5265
  if (isLedgerBleConnectionType(this.connectionType)) {
5266
+ if (isBleBondInvalidError(err)) {
5267
+ throw createHwkError2({
5268
+ code: HardwareErrorCode7.BleBondInvalid,
5269
+ message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
5270
+ _tag: ERROR_TAG.PeerRemovedPairing
5271
+ });
5272
+ }
4392
5273
  const tag = err?._tag;
4393
- if (isKnownConnectionTag(tag)) {
5274
+ if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4394
5275
  throw err;
4395
5276
  }
4396
5277
  const wrapped = new Error(
4397
5278
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
4398
5279
  );
4399
5280
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
4400
- wrapped.code = HardwareErrorCode8.BlePairingTimeout;
5281
+ wrapped.code = HardwareErrorCode7.BlePairingTimeout;
4401
5282
  wrapped.originalError = err;
4402
5283
  throw wrapped;
4403
5284
  }
@@ -4475,7 +5356,7 @@ var LedgerConnectorBase = class {
4475
5356
  this._unwatchSessionState(sessionId);
4476
5357
  this._signerManager?.invalidate(sessionId);
4477
5358
  this._cancellers.get(sessionId)?.({
4478
- code: HardwareErrorCode8.DeviceDisconnected,
5359
+ code: HardwareErrorCode7.DeviceDisconnected,
4479
5360
  tag: "DeviceDisconnected",
4480
5361
  message: "Device disconnected"
4481
5362
  });
@@ -4491,7 +5372,7 @@ var LedgerConnectorBase = class {
4491
5372
  // whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
4492
5373
  // locally (see LedgerAdapter._unwrapConnectorResult).
4493
5374
  async call(sessionId, method, params) {
4494
- debugLog("[DMK] call:", method, JSON.stringify(params));
5375
+ debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
4495
5376
  try {
4496
5377
  const payload = await this._dispatch(sessionId, method, params);
4497
5378
  return { success: true, payload };
@@ -4501,7 +5382,7 @@ var LedgerConnectorBase = class {
4501
5382
  success: false,
4502
5383
  error: serializeConnectorError(
4503
5384
  Object.assign(new Error("Ledger app is unresponsive"), {
4504
- code: HardwareErrorCode8.DeviceAppStuck,
5385
+ code: HardwareErrorCode7.DeviceAppStuck,
4505
5386
  _tag: ERROR_TAG.DeviceAppStuck,
4506
5387
  originalError: err
4507
5388
  })
@@ -4513,7 +5394,7 @@ var LedgerConnectorBase = class {
4513
5394
  success: false,
4514
5395
  error: serializeConnectorError(
4515
5396
  Object.assign(new Error("Device communication interrupted, please retry"), {
4516
- code: HardwareErrorCode8.TransportError,
5397
+ code: HardwareErrorCode7.TransportError,
4517
5398
  _tag: ERROR_TAG.DeviceTransportStuck,
4518
5399
  originalError: err
4519
5400
  })
@@ -4559,6 +5440,11 @@ var LedgerConnectorBase = class {
4559
5440
  return solSignTransaction(ctx, sessionId, params);
4560
5441
  case "solSignMessage":
4561
5442
  return solSignMessage(ctx, sessionId, params);
5443
+ // ZCASH
5444
+ case "zcashGetFullViewingKey":
5445
+ return zcashGetFullViewingKey(ctx, sessionId, params);
5446
+ case "zcashGetShieldedAddress":
5447
+ return zcashGetShieldedAddress(ctx, sessionId, params);
4562
5448
  // TRON
4563
5449
  case "tronGetAddress":
4564
5450
  return tronGetAddress(ctx, sessionId, params);
@@ -4583,7 +5469,7 @@ var LedgerConnectorBase = class {
4583
5469
  try {
4584
5470
  return await apps.install(p.appName, ({ progress }) => {
4585
5471
  ctx.emit("ui-event", {
4586
- type: EConnectorInteraction4.AppInstallProgress,
5472
+ type: EConnectorInteraction3.AppInstallProgress,
4587
5473
  payload: {
4588
5474
  sessionId,
4589
5475
  appName: p.appName,
@@ -4592,7 +5478,7 @@ var LedgerConnectorBase = class {
4592
5478
  });
4593
5479
  });
4594
5480
  } catch (err) {
4595
- ctx.invalidateSession(sessionId);
5481
+ ctx.teardownSecureChannelSession(sessionId);
4596
5482
  throw ctx.wrapError(err);
4597
5483
  } finally {
4598
5484
  ctx.clearCanceller(sessionId);
@@ -4682,7 +5568,7 @@ var LedgerConnectorBase = class {
4682
5568
  );
4683
5569
  return { isGenuine: output.isGenuine, deviceId };
4684
5570
  } catch (err) {
4685
- ctx.invalidateSession(sessionId);
5571
+ ctx.teardownSecureChannelSession(sessionId);
4686
5572
  throw ctx.wrapError(err);
4687
5573
  } finally {
4688
5574
  ctx.clearCanceller(sessionId);
@@ -4804,6 +5690,17 @@ var LedgerConnectorBase = class {
4804
5690
  _invalidateSession(sessionId) {
4805
5691
  this._signerManager?.invalidate(sessionId);
4806
5692
  }
5693
+ _teardownSecureChannelSession(sessionId) {
5694
+ const cancel = this._cancellers.get(sessionId);
5695
+ this._cancellers.delete(sessionId);
5696
+ if (cancel) {
5697
+ try {
5698
+ cancel();
5699
+ } catch {
5700
+ }
5701
+ }
5702
+ this._invalidateSession(sessionId);
5703
+ }
4807
5704
  /**
4808
5705
  * Replace an old session with a new one after app switch.
4809
5706
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -4884,16 +5781,17 @@ var LedgerConnectorBase = class {
4884
5781
  // ---------------------------------------------------------------------------
4885
5782
  /**
4886
5783
  * Return a per-call ctx with the chain's Ledger app name pre-bound to
4887
- * wrapError, so chain handlers don't need to repeat `{ defaultAppName: 'X' }`
4888
- * at every catch site. Falls through unchanged for unknown methods.
5784
+ * UI prompts and wrapError, so chain handlers don't need to repeat the name.
5785
+ * Falls through unchanged for unknown methods.
4889
5786
  */
4890
5787
  _ctxForMethod(method) {
4891
- const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5788
+ const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4892
5789
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
4893
5790
  if (!defaultAppName) return this._ctx;
4894
5791
  return {
4895
5792
  ...this._ctx,
4896
- wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts })
5793
+ wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts }),
5794
+ emit: (event, data) => this._ctx.emit(event, withOpenAppName(event, data, defaultAppName))
4897
5795
  };
4898
5796
  }
4899
5797
  _wrapError(err, opts) {
@@ -4922,6 +5820,209 @@ var LedgerConnectorBase = class {
4922
5820
  return error;
4923
5821
  }
4924
5822
  };
5823
+
5824
+ // src/transport/DmkTransport.ts
5825
+ import Transport from "@ledgerhq/hw-transport";
5826
+ var DmkTransport = class extends Transport {
5827
+ constructor(dmk, sessionId) {
5828
+ super();
5829
+ this._dmk = dmk;
5830
+ this._sessionId = sessionId;
5831
+ }
5832
+ async exchange(apdu) {
5833
+ const response = await this._dmk.sendApdu({
5834
+ sessionId: this._sessionId,
5835
+ apdu: new Uint8Array(apdu)
5836
+ });
5837
+ const { data, statusCode } = response;
5838
+ const result = Buffer.alloc(data.length + 2);
5839
+ if (data.length > 0) {
5840
+ result.set(data, 0);
5841
+ }
5842
+ result.set(statusCode, data.length);
5843
+ return result;
5844
+ }
5845
+ async close() {
5846
+ }
5847
+ };
5848
+
5849
+ // src/app/AppManager.ts
5850
+ import {
5851
+ CloseAppCommand,
5852
+ GetAppAndVersionCommand,
5853
+ OpenAppCommand,
5854
+ isSuccessCommandResult
5855
+ } from "@ledgerhq/device-management-kit";
5856
+ import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
5857
+ var APP_NAME_MAP = {
5858
+ ETH: "Ethereum",
5859
+ BTC: "Bitcoin",
5860
+ SOL: "Solana",
5861
+ TRX: "Tron",
5862
+ ZEC: "Zcash",
5863
+ XRP: "XRP",
5864
+ ADA: "Cardano",
5865
+ DOT: "Polkadot",
5866
+ ATOM: "Cosmos"
5867
+ };
5868
+ var DASHBOARD_APP_NAME = "BOLOS";
5869
+ var AppManager = class {
5870
+ constructor(dmk, options) {
5871
+ this._dmk = dmk;
5872
+ this._waitMs = options?.waitMs ?? 1e3;
5873
+ this._maxRetries = options?.maxRetries ?? 10;
5874
+ }
5875
+ /**
5876
+ * Return the Ledger app name for a given chain ticker,
5877
+ * or undefined if the chain is not supported.
5878
+ */
5879
+ static getAppName(chain) {
5880
+ return APP_NAME_MAP[chain];
5881
+ }
5882
+ /**
5883
+ * Ensure the target app is open on the device identified by `sessionId`.
5884
+ *
5885
+ * Flow:
5886
+ * 1. Check the currently running app.
5887
+ * 2. If it is already the target, return immediately.
5888
+ * 3. If a different app is running (not dashboard), close it first.
5889
+ * 4. Open the target app.
5890
+ * 5. Poll until the device confirms the target app is running.
5891
+ */
5892
+ /**
5893
+ * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5894
+ * device is about to display "Open <app>" on screen and wait for the
5895
+ * user's button press. UI consumers should show their "open app" prompt
5896
+ * in response. NOT called when the target app is already open (no user
5897
+ * interaction needed in that case).
5898
+ *
5899
+ * Important: OpenAppCommand is blocking. It does not resolve until the user
5900
+ * has physically confirmed on the device, so anything that runs AFTER
5901
+ * `await this._openApp(...)` lands AFTER the prompt is already gone.
5902
+ * Hence the callback must fire BEFORE that await.
5903
+ */
5904
+ async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5905
+ const currentApp = await this._getCurrentApp(sessionId);
5906
+ if (currentApp === targetAppName) {
5907
+ return;
5908
+ }
5909
+ if (!this._isDashboard(currentApp)) {
5910
+ await this._closeCurrentApp(sessionId);
5911
+ await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5912
+ }
5913
+ onConfirmOnDevice?.();
5914
+ await this._openApp(sessionId, targetAppName);
5915
+ await this._waitForApp(sessionId, targetAppName);
5916
+ }
5917
+ // ---------------------------------------------------------------------------
5918
+ // Private helpers
5919
+ // ---------------------------------------------------------------------------
5920
+ async _getCurrentApp(sessionId) {
5921
+ const result = await this._dmk.sendCommand({
5922
+ sessionId,
5923
+ command: new GetAppAndVersionCommand()
5924
+ });
5925
+ if (isSuccessCommandResult(result)) {
5926
+ debugLog("[AppManager] currentApp:", result.data.name);
5927
+ return result.data.name;
5928
+ }
5929
+ const errResult = result;
5930
+ const dmkErr = errResult.error ?? {};
5931
+ const original = dmkErr.originalError;
5932
+ debugLog(
5933
+ "[AppManager] _getCurrentApp failed sessionId=",
5934
+ sessionId,
5935
+ "tag=",
5936
+ dmkErr._tag,
5937
+ "errorCode=",
5938
+ dmkErr.errorCode,
5939
+ "message=",
5940
+ dmkErr.message,
5941
+ "originalErrorMessage=",
5942
+ original?.message ?? String(original ?? "")
5943
+ );
5944
+ throw Object.assign(
5945
+ new Error(
5946
+ dmkErr.message ?? "Failed to get current app from device"
5947
+ ),
5948
+ {
5949
+ _tag: dmkErr._tag,
5950
+ errorCode: dmkErr.errorCode,
5951
+ originalError: original
5952
+ }
5953
+ );
5954
+ }
5955
+ async _openApp(sessionId, appName) {
5956
+ const result = await this._dmk.sendCommand({
5957
+ sessionId,
5958
+ command: new OpenAppCommand({ appName })
5959
+ });
5960
+ if (!isSuccessCommandResult(result)) {
5961
+ const dmkErr = result.error;
5962
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5963
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5964
+ debugLog(
5965
+ "[AppManager] openApp failed:",
5966
+ appName,
5967
+ "errorCode:",
5968
+ errorCode,
5969
+ "tag:",
5970
+ dmkErr._tag
5971
+ );
5972
+ let code;
5973
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
5974
+ code = HardwareErrorCode8.AppNotInstalled;
5975
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5976
+ code = HardwareErrorCode8.UserRejected;
5977
+ }
5978
+ throw Object.assign(new Error(`Failed to open "${appName}"`), {
5979
+ _tag: ERROR_TAG.OpenAppCommand,
5980
+ code,
5981
+ errorCode,
5982
+ statusCode: errorCode,
5983
+ appName,
5984
+ originalError: dmkErr
5985
+ });
5986
+ }
5987
+ }
5988
+ async _closeCurrentApp(sessionId) {
5989
+ debugLog("[AppManager] closeCurrentApp");
5990
+ await this._dmk.sendCommand({
5991
+ sessionId,
5992
+ command: new CloseAppCommand()
5993
+ });
5994
+ }
5995
+ /**
5996
+ * Poll the device until the expected app is reported as running,
5997
+ * or throw after `_maxRetries` attempts.
5998
+ */
5999
+ async _waitForApp(sessionId, expectedAppName) {
6000
+ let lastSeen = "";
6001
+ for (let i = 0; i < this._maxRetries; i++) {
6002
+ await this._wait();
6003
+ const current = await this._getCurrentApp(sessionId);
6004
+ lastSeen = current;
6005
+ if (current === expectedAppName) {
6006
+ return;
6007
+ }
6008
+ }
6009
+ debugLog(
6010
+ "[AppManager] waitForApp exhausted: expected=",
6011
+ expectedAppName,
6012
+ "lastSeen=",
6013
+ lastSeen
6014
+ );
6015
+ throw new Error(
6016
+ `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
6017
+ );
6018
+ }
6019
+ _isDashboard(appName) {
6020
+ return appName === DASHBOARD_APP_NAME;
6021
+ }
6022
+ _wait() {
6023
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
6024
+ }
6025
+ };
4925
6026
  export {
4926
6027
  AppManager,
4927
6028
  DmkTransport,
@@ -4932,6 +6033,7 @@ export {
4932
6033
  SignerEth,
4933
6034
  SignerManager,
4934
6035
  SignerSol,
6036
+ SignerZcash,
4935
6037
  debugLog,
4936
6038
  deviceActionToPromise,
4937
6039
  isDeviceLockedError,