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

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",
@@ -183,7 +199,16 @@ var ERROR_TAG = {
183
199
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
184
200
  WebSocketConnection: "WebSocketConnectionError",
185
201
  HttpFetch: "FetchError",
186
- InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError"
202
+ NetworkDA: "NetworkDAError",
203
+ InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
204
+ ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
205
+ // DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
206
+ // after splitting out device answers, i.e. the relay itself broke.
207
+ SecureChannel: "SecureChannelError",
208
+ RefusedByUserDA: "RefusedByUserDAError",
209
+ AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
210
+ OutOfMemoryDA: "OutOfMemoryDAError",
211
+ DeviceNotOnboarded: "DeviceNotOnboardedError"
187
212
  };
188
213
  function isDeviceLockedError(err) {
189
214
  if (!err || typeof err !== "object") return false;
@@ -213,7 +238,6 @@ function isBlePairingFailureError(err) {
213
238
  return false;
214
239
  }
215
240
  var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
216
- ERROR_TAG.DeviceLocked,
217
241
  ERROR_TAG.DeviceNotAdvertising,
218
242
  ERROR_TAG.BlePairingTimeout,
219
243
  ERROR_TAG.BleGattBondingFailed,
@@ -225,6 +249,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
225
249
  ERROR_TAG.DeviceSessionRefresher,
226
250
  ERROR_TAG.DeviceNotInitialized,
227
251
  ERROR_TAG.OpeningConnection,
252
+ ERROR_TAG.OpeningConnectionLegacy,
228
253
  ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
229
254
  ERROR_TAG.DeviceDisconnectedWhileSending,
230
255
  ERROR_TAG.Disconnect,
@@ -239,7 +264,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
239
264
  // Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
240
265
  ERROR_TAG.DeviceNotInDiscoveryCache
241
266
  ]);
242
- var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OpeningConnection]);
267
+ var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
268
+ ERROR_TAG.OpeningConnection,
269
+ ERROR_TAG.OpeningConnectionLegacy
270
+ ]);
243
271
  var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
244
272
  ERROR_TAG.DeviceNotRecognized,
245
273
  ERROR_TAG.DeviceSessionNotFound,
@@ -251,17 +279,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
251
279
  ERROR_TAG.WebHIDDisconnect
252
280
  ]);
253
281
  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;
282
+ return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
261
283
  }
262
284
  function isKnownConnectionTag(tag) {
263
285
  return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
264
286
  }
287
+ var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
288
+ ERROR_TAG.OpeningConnection,
289
+ ERROR_TAG.OpeningConnectionLegacy
290
+ ]);
291
+ function isConnectionOpeningTag(tag) {
292
+ return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
293
+ }
265
294
  function hasStatusCode(err, codeSet) {
266
295
  if (!err || typeof err !== "object") return false;
267
296
  const e = err;
@@ -297,28 +326,28 @@ function hasInvalidArgumentCode(err) {
297
326
  if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
298
327
  return false;
299
328
  }
300
- function isDeviceNotFoundError(err) {
329
+ function hasErrorTag(err, tags) {
301
330
  if (!err || typeof err !== "object") return false;
302
- const tag = err._tag;
303
- if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
304
331
  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;
332
+ if (typeof e._tag === "string" && tags.has(e._tag)) return true;
333
+ if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
334
+ if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
307
335
  return false;
308
336
  }
337
+ function isDeviceNotFoundError(err) {
338
+ return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
339
+ }
309
340
  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;
341
+ return hasErrorTag(err, DEVICE_BUSY_TAGS);
317
342
  }
343
+ var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
344
+ ERROR_TAG.UserRefusedOnDevice,
345
+ ERROR_TAG.RefusedByUserDA
346
+ ]);
318
347
  function isUserRejectedError(err) {
319
348
  if (!err || typeof err !== "object") return false;
320
349
  const e = err;
321
- if (e._tag === ERROR_TAG.UserRefusedOnDevice) return true;
350
+ if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
322
351
  if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
323
352
  if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
324
353
  return false;
@@ -349,15 +378,33 @@ function isAppNotInstalledError(err) {
349
378
  if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
350
379
  return false;
351
380
  }
381
+ var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
352
382
  function isOutOfMemoryError(err) {
353
- if (!err || typeof err !== "object") return false;
354
- const e = err;
355
- return e._tag === "OutOfMemoryDAError";
383
+ return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
384
+ }
385
+ var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
386
+ function isAppAlreadyInstalledError(err) {
387
+ return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
388
+ }
389
+ var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
390
+ function isDeviceNotOnboardedError(err) {
391
+ return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
392
+ }
393
+ var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
394
+ ERROR_TAG.InvalidFirmwareMetadataResponse,
395
+ ERROR_TAG.ApplicationsMetadataTask
396
+ ]);
397
+ function isFirmwareMetadataError(err) {
398
+ return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
399
+ }
400
+ var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
401
+ function isSecureChannelError(err) {
402
+ return hasErrorTag(err, SECURE_CHANNEL_TAGS);
356
403
  }
357
404
  var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
358
405
  ERROR_TAG.WebSocketConnection,
359
406
  ERROR_TAG.HttpFetch,
360
- ERROR_TAG.InvalidFirmwareMetadataResponse
407
+ ERROR_TAG.NetworkDA
361
408
  ]);
362
409
  function isNetworkError(err) {
363
410
  if (!err || typeof err !== "object") return false;
@@ -407,23 +454,34 @@ function isTransportStuck(err) {
407
454
  function isStuckAppStateError(err) {
408
455
  return isAppStuckByApdu(err) || isTransportStuck(err);
409
456
  }
457
+ var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
458
+ function nestedErrorMessage(nested) {
459
+ if (!nested || typeof nested !== "object") return void 0;
460
+ const { message } = nested;
461
+ if (typeof message !== "string") return void 0;
462
+ const trimmed = message.trim();
463
+ if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
464
+ return message;
465
+ }
410
466
  function mapLedgerError(err, opts) {
411
467
  let originalMessage = "Unknown Ledger error";
412
468
  if (err instanceof Error) {
413
469
  originalMessage = err.message;
414
470
  } else if (err && typeof err === "object") {
415
471
  const e = err;
416
- originalMessage = String(e.message ?? e._tag ?? e.type ?? JSON.stringify(err));
472
+ originalMessage = String(
473
+ e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
474
+ );
417
475
  }
418
476
  let code;
419
477
  if (isDeviceLockedError(err)) {
420
478
  code = HardwareErrorCode.DeviceLocked;
421
479
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
422
480
  code = HardwareErrorCode.DeviceNotFound;
423
- } else if (isDeviceBusyError(err)) {
424
- code = HardwareErrorCode.DeviceBusy;
425
481
  } else if (isBlePairingFailureError(err)) {
426
482
  code = HardwareErrorCode.BlePairingTimeout;
483
+ } else if (isDeviceBusyError(err)) {
484
+ code = HardwareErrorCode.DeviceBusy;
427
485
  } else if (isUserAbortedError(err)) {
428
486
  code = HardwareErrorCode.UserAborted;
429
487
  } else if (isUserRejectedError(err)) {
@@ -432,10 +490,18 @@ function mapLedgerError(err, opts) {
432
490
  code = HardwareErrorCode.WrongApp;
433
491
  } else if (isAppNotInstalledError(err)) {
434
492
  code = HardwareErrorCode.AppNotInstalled;
493
+ } else if (isAppAlreadyInstalledError(err)) {
494
+ code = HardwareErrorCode.AppAlreadyInstalled;
435
495
  } else if (isOutOfMemoryError(err)) {
436
496
  code = HardwareErrorCode.DeviceOutOfMemory;
497
+ } else if (isDeviceNotOnboardedError(err)) {
498
+ code = HardwareErrorCode.DeviceNotInitialized;
499
+ } else if (isFirmwareMetadataError(err)) {
500
+ code = HardwareErrorCode.LedgerFirmwareMetadataError;
437
501
  } else if (isNetworkError(err)) {
438
502
  code = HardwareErrorCode.NetworkError;
503
+ } else if (isSecureChannelError(err)) {
504
+ code = HardwareErrorCode.LedgerSecureChannelError;
439
505
  } else if (isDeviceDisconnectedError(err)) {
440
506
  code = HardwareErrorCode.DeviceDisconnected;
441
507
  } else if (isTimeoutError(err)) {
@@ -448,11 +514,35 @@ function mapLedgerError(err, opts) {
448
514
  }
449
515
  const errAppName = err && typeof err === "object" ? err.appName : void 0;
450
516
  const appName = errAppName ?? opts?.defaultAppName;
451
- return { code, message: enrichErrorMessage(code, originalMessage), appName };
517
+ return {
518
+ code,
519
+ message: enrichErrorMessage(code, originalMessage),
520
+ origin: defaultOriginForCode(code),
521
+ appName
522
+ };
523
+ }
524
+
525
+ // src/utils/queueKey.ts
526
+ var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
527
+ function ledgerQueueKey({
528
+ operationId,
529
+ connectId
530
+ }) {
531
+ return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
452
532
  }
453
533
 
454
534
  // src/adapter/methods/allNetworkGetAddress.ts
455
- import { HardwareErrorCode as HardwareErrorCode2, failure, runAllNetworkGetAddress } from "@onekeyfe/hwk-adapter-core";
535
+ import {
536
+ HardwareErrorCode as HardwareErrorCode2,
537
+ buildAllNetworkCancelledFailure,
538
+ failure,
539
+ isConnectionLost,
540
+ isUserRefusal,
541
+ isWalletSafetyFailure,
542
+ resolveHardwareOperationTarget,
543
+ runAllNetworkGetAddress,
544
+ success
545
+ } from "@onekeyfe/hwk-adapter-core";
456
546
 
457
547
  // src/utils/sdkEventBus.ts
458
548
  var listeners = /* @__PURE__ */ new Set();
@@ -499,6 +589,32 @@ function debugError(...args) {
499
589
  emitLog("error", ...args);
500
590
  }
501
591
 
592
+ // src/utils/logSummary.ts
593
+ import { summarizeForLog as summarizeForLogCore } from "@onekeyfe/hwk-adapter-core";
594
+ import { Psbt, Transaction } from "bitcoinjs-lib";
595
+ var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
596
+ var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
597
+ function parsePsbt(input) {
598
+ if (typeof input !== "string") return Psbt.fromBuffer(input);
599
+ if (HEX_RE.test(input)) return Psbt.fromHex(input.replace(/^0x/i, ""));
600
+ if (BASE64_RE.test(input)) return Psbt.fromBase64(input);
601
+ return void 0;
602
+ }
603
+ var describePsbtForLog = (key, value) => {
604
+ if (key !== "psbt") return void 0;
605
+ try {
606
+ const psbt = parsePsbt(value);
607
+ if (!psbt) return void 0;
608
+ const unsignedTx = Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
609
+ return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
610
+ } catch {
611
+ return void 0;
612
+ }
613
+ };
614
+ function summarizeForLog(value, options = {}) {
615
+ return summarizeForLogCore(value, { ...options, describePayload: describePsbtForLog });
616
+ }
617
+
502
618
  // src/adapter/methods/allNetworkGetAddress.ts
503
619
  var LEDGER_BTC_NETWORK_COIN_MAP = {
504
620
  tbtc: "Testnet",
@@ -509,57 +625,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
509
625
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
510
626
  function createAllNetworkGetAddress({
511
627
  callChain,
512
- getChainFingerprint
628
+ getChainFingerprint,
629
+ retainOperation,
630
+ errorToFailure,
631
+ createCancelScope,
632
+ releaseBundle
513
633
  }) {
514
634
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
515
- debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
516
- const installContext = {};
635
+ debugLog("[LedgerAdapter][REQ]", {
636
+ method: "allNetworkGetAddress",
637
+ connectId,
638
+ itemCount: params.bundle.length
639
+ });
640
+ const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
641
+ if (!target.success) return target;
642
+ const effectiveTargetId = target.payload.targetId ?? "";
643
+ let releaseOperationRetention;
644
+ try {
645
+ releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
646
+ } catch (error) {
647
+ return errorToFailure(error);
648
+ }
649
+ const cancelScope = createCancelScope(
650
+ ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
651
+ );
652
+ const installContext = {
653
+ walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
654
+ };
517
655
  const commonParams = {
518
- autoInstallApp: params.autoInstallApp
656
+ autoInstallApp: params.autoInstallApp,
657
+ operationId: target.payload.operationId,
658
+ knownConnections: params.knownConnections,
659
+ extra: params.extra,
660
+ allowDeviceSelection: params.allowDeviceSelection,
661
+ supportedTransports: params.supportedTransports
519
662
  };
520
663
  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,
664
+ const order = params.bundle.map((_item, index) => index).sort(
665
+ (a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
666
+ );
667
+ try {
668
+ const ordered = await runAllNetworkGetAddress({
669
+ connectId: effectiveTargetId,
670
+ deviceId: _deviceId,
671
+ params: { ...params, bundle: order.map((index) => params.bundle[index]) },
672
+ normalizeItem: normalizeLedgerAllNetworkItem,
673
+ buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
674
+ callItem: async ({ method, chain, item }) => {
675
+ if (cancelScope.signal.aborted)
676
+ return buildAllNetworkCancelledFailure(cancelScope.signal);
677
+ const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
678
+ return callAllNetworkMethod(
679
+ callChain,
680
+ effectiveTargetId,
681
+ itemDeviceId,
682
+ method,
683
+ item,
684
+ commonParams,
685
+ installContext
686
+ );
687
+ },
688
+ attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
689
+ getChainFingerprint,
690
+ effectiveTargetId,
534
691
  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
- );
692
+ chain,
693
+ payload,
694
+ chainFingerprints,
695
+ installContext,
696
+ cancelScope.signal
697
+ ),
698
+ shouldAbortBundle: isTopLevelAllNetworkFailure,
699
+ buildTopLevelFailure: (response) => {
700
+ const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
701
+ return failure(
702
+ code,
703
+ response.payload?.error ?? "All-network get-address aborted",
704
+ response.payload?.params
705
+ );
706
+ }
707
+ });
708
+ let result = ordered;
709
+ if (ordered.success) {
710
+ const responses = [];
711
+ ordered.payload.forEach((response, position) => {
712
+ responses[order[position]] = response;
713
+ });
714
+ result = success(responses);
555
715
  }
556
- });
557
- debugLog("[LedgerAdapter][RES]", {
558
- method: "allNetworkGetAddress",
559
- success: result.success,
560
- payload: result
561
- });
562
- return result;
716
+ debugLog("[LedgerAdapter][RES]", {
717
+ method: "allNetworkGetAddress",
718
+ success: result.success,
719
+ payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
720
+ });
721
+ return result;
722
+ } finally {
723
+ await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
724
+ cancelScope.release();
725
+ releaseOperationRetention?.();
726
+ }
563
727
  };
564
728
  }
565
729
  function isTopLevelAllNetworkFailure(response) {
@@ -567,7 +731,7 @@ function isTopLevelAllNetworkFailure(response) {
567
731
  return false;
568
732
  }
569
733
  const code = response.payload?.code;
570
- return code === HardwareErrorCode2.DeviceMismatch || code === HardwareErrorCode2.UserAborted || code === HardwareErrorCode2.UserRejected;
734
+ return isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
571
735
  }
572
736
  function getItemDeviceId(item) {
573
737
  const { deviceId } = item;
@@ -597,8 +761,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
597
761
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
598
762
  return coin ? { ...item, coin } : item;
599
763
  }
600
- async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
601
- const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
764
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
765
+ const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
766
+ if (!knownFingerprint && cancelSignal.aborted) {
767
+ const cancelled = buildAllNetworkCancelledFailure(cancelSignal);
768
+ return { ...item, success: false, payload: cancelled.payload };
769
+ }
770
+ const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
771
+ getChainFingerprint,
772
+ context.connection?.connectId ?? connectId,
773
+ chain,
774
+ context
775
+ );
602
776
  if (!fingerprint) {
603
777
  return buildFingerprintBootstrapFailure(item, chain);
604
778
  }
@@ -619,8 +793,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
619
793
  }
620
794
  };
621
795
  }
622
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
623
- const response = await getChainFingerprint(connectId, chain);
796
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
797
+ const response = await getChainFingerprint(connectId, chain, context);
624
798
  return response.success ? response.payload : "";
625
799
  }
626
800
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -713,6 +887,9 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
713
887
  function formatDeviceMismatchError(expected, actual) {
714
888
  return `Wrong device: expected ${expected}, got ${actual}`;
715
889
  }
890
+ function isLostConnectionError(err) {
891
+ return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
892
+ }
716
893
  var BTC_HIGH_INDEX_THRESHOLD = 100;
717
894
  function btcAccountIndexFromPath(path) {
718
895
  const segments = path.replace(/^m\//, "").split("/");
@@ -724,9 +901,35 @@ function btcAccountIndexFromPath(path) {
724
901
  var _LedgerAdapter = class _LedgerAdapter {
725
902
  constructor(connector, options) {
726
903
  this.vendor = "ledger";
904
+ // Cancel frees the DMK action and its intent-queue slot, but cannot retract a
905
+ // confirmation screen the device is already showing.
906
+ this.cancelCapability = "stops-waiting";
727
907
  this.emitter = new TypedEventEmitter();
908
+ this._operations = new OperationRegistry({
909
+ vendor: "ledger",
910
+ onEnded: (operation, reason) => {
911
+ this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
912
+ this._pendingOperationBindings.delete(operation.operationId);
913
+ this.emitter.emit(SDK.OPERATION_ENDED, {
914
+ type: SDK.OPERATION_ENDED,
915
+ payload: { operationId: operation.operationId, reason }
916
+ });
917
+ if (reason === "timeout") {
918
+ void this._releaseOperationConnection(operation);
919
+ }
920
+ }
921
+ });
728
922
  this._discoveredDevices = /* @__PURE__ */ new Map();
729
923
  this._sessions = /* @__PURE__ */ new Map();
924
+ // An operation's BLE pick is saved by its first call that gets past the wallet check.
925
+ this._pendingOperationBindings = /* @__PURE__ */ new Map();
926
+ // A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
927
+ // through an unlock retry; any other failure drops it with its session.
928
+ this._pendingPickBindings = /* @__PURE__ */ new Map();
929
+ // Transport each session was opened on, by sessionId. The adapter-wide
930
+ // `_activeConnectionType` moves with every discovery and can go stale.
931
+ this._sessionTransports = /* @__PURE__ */ new Map();
932
+ this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
730
933
  this._uiRegistry = new UiRequestRegistry();
731
934
  // BTC App rejects account index >= 100 unless display=true. Cached per
732
935
  // adapter instance: first 100+ path asks the user once via UI request,
@@ -740,21 +943,36 @@ var _LedgerAdapter = class _LedgerAdapter {
740
943
  this._deviceAuthenticityQueueTail = Promise.resolve();
741
944
  // Shared across concurrent callers — only `cancel()` aborts.
742
945
  this._doConnectAbortController = null;
946
+ this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
947
+ this._connectorIdleWaiters = /* @__PURE__ */ new Set();
948
+ this._resetPromise = null;
949
+ this._stateGeneration = 0;
950
+ this._connectorTeardownTail = Promise.resolve();
951
+ this._pendingConnectorTeardowns = 0;
952
+ this._activeOperationJobs = /* @__PURE__ */ new Set();
953
+ this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
743
954
  this._installProgressLastEmittedValue = -Infinity;
744
955
  this.allNetworkGetAddress = createAllNetworkGetAddress({
745
956
  callChain: this.callChain.bind(this),
746
- getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
957
+ getChainFingerprint: async (connectId, chain, context) => {
958
+ try {
959
+ const fingerprint = await this._computeChainFingerprint(
960
+ chain,
961
+ (method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
962
+ );
963
+ return success2(fingerprint);
964
+ } catch (error) {
965
+ return this.errorToFailure(error);
966
+ }
967
+ },
968
+ retainOperation: (operationId) => this._operations.retain(operationId),
969
+ errorToFailure: (error) => this.errorToFailure(error),
970
+ createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
971
+ releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
747
972
  });
748
973
  // ---------------------------------------------------------------------------
749
974
  // Private helpers
750
975
  // ---------------------------------------------------------------------------
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
976
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
759
977
  this._connectingPromise = null;
760
978
  // ---------------------------------------------------------------------------
@@ -770,6 +988,12 @@ var _LedgerAdapter = class _LedgerAdapter {
770
988
  });
771
989
  };
772
990
  this.deviceDisconnectHandler = (data) => {
991
+ const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
992
+ if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
993
+ this._pendingOperationDisconnects.add(activeOperation.operationId);
994
+ } else {
995
+ this._operations.endByConnectionKey(data.connectId, "disconnect");
996
+ }
773
997
  this._discoveredDevices.delete(data.connectId);
774
998
  this._sessions.delete(data.connectId);
775
999
  this.emitter.emit(DEVICE.DISCONNECT, {
@@ -778,10 +1002,8 @@ var _LedgerAdapter = class _LedgerAdapter {
778
1002
  });
779
1003
  };
780
1004
  // 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.
1005
+ // need to subscribe in one place. The AppInstallProgress variant re-keys
1006
+ // sessionId to connectId via `_sessions`, and drops if no mapping exists.
785
1007
  this.uiEventForwarder = (event) => {
786
1008
  if (event.type === EConnectorInteraction.AppInstallProgress) {
787
1009
  let connectId;
@@ -826,11 +1048,30 @@ var _LedgerAdapter = class _LedgerAdapter {
826
1048
  this._jobQueue = new DeviceJobQueue();
827
1049
  this.registerEventListeners();
828
1050
  }
1051
+ _discardPendingBinding(owner, status = "cancelled") {
1052
+ const pending = owner?.pendingBinding;
1053
+ if (!owner || !pending) return;
1054
+ owner.pendingBinding = void 0;
1055
+ if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1056
+ }
1057
+ _finishBleBinding(status) {
1058
+ const selectionRequestId = this._bindingSelectionRequestId;
1059
+ this._bindingSelectionRequestId = void 0;
1060
+ if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
1061
+ }
1062
+ _isBleConnection() {
1063
+ return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1064
+ }
829
1065
  // Transport
830
1066
  get activeTransport() {
831
- return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1067
+ return this._isBleConnection() ? "ble" : "hid";
832
1068
  }
833
1069
  getAvailableTransports() {
1070
+ if (this.connector.availableTransports) {
1071
+ return this.connector.availableTransports.map(
1072
+ (transport) => transport === "ble" ? "ble" : "hid"
1073
+ );
1074
+ }
834
1075
  return this.activeTransport ? [this.activeTransport] : [];
835
1076
  }
836
1077
  // Connector is bound at construction; switching requires a new adapter.
@@ -847,21 +1088,42 @@ var _LedgerAdapter = class _LedgerAdapter {
847
1088
  * The next operation will re-discover and re-connect automatically.
848
1089
  */
849
1090
  resetState() {
1091
+ void this._resetStateAndDisconnectSessions();
1092
+ }
1093
+ _resetStateAndDisconnectSessions() {
1094
+ if (this._resetPromise) return this._resetPromise;
1095
+ const sessionIds = new Set(this._sessions.values());
1096
+ this._stateGeneration += 1;
1097
+ this._finishBleBinding("cancelled");
1098
+ this._operations.endAll("runtime-reset");
1099
+ this._doConnectAbortController?.abort();
850
1100
  this._discoveredDevices.clear();
851
1101
  this._sessions.clear();
1102
+ this._sessionTransports.clear();
1103
+ this._pendingOperationBindings.clear();
1104
+ this._pendingPickBindings.clear();
1105
+ this._selectedBleReconnectTargets.clear();
852
1106
  this._connectingPromise = null;
1107
+ this._doConnectAbortController = null;
853
1108
  this._uiRegistry.reset();
854
1109
  this._jobQueue.clear();
855
1110
  this._btcHighIndexConfirmedThisSession = false;
1111
+ const resetPromise = this._runConnectorTeardown(async () => {
1112
+ for (const sessionId of sessionIds) {
1113
+ await this.connector.disconnect(sessionId).catch(() => void 0);
1114
+ }
1115
+ });
1116
+ this._resetPromise = resetPromise;
1117
+ return resetPromise.finally(() => {
1118
+ if (this._resetPromise === resetPromise) {
1119
+ this._resetPromise = null;
1120
+ }
1121
+ });
856
1122
  }
857
1123
  async dispose() {
858
- this._uiRegistry.reset();
859
- this._jobQueue.clear();
1124
+ await this._resetStateAndDisconnectSessions();
860
1125
  this.unregisterEventListeners();
861
1126
  this.connector.reset();
862
- this._discoveredDevices.clear();
863
- this._sessions.clear();
864
- this._btcHighIndexConfirmedThisSession = false;
865
1127
  this.emitter.removeAllListeners();
866
1128
  }
867
1129
  uiResponse(response) {
@@ -871,17 +1133,32 @@ var _LedgerAdapter = class _LedgerAdapter {
871
1133
  // Device management
872
1134
  // ---------------------------------------------------------------------------
873
1135
  async searchDevices(options) {
1136
+ return this._searchDevices(options);
1137
+ }
1138
+ async _searchDevices(options, signal) {
874
1139
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
875
1140
  try {
876
1141
  if (options?.resetSession) {
877
- this._doConnectAbortController?.abort();
878
- this._sessions.clear();
879
- this._connectingPromise = null;
880
- this._doConnectAbortController = null;
881
- this._btcHighIndexConfirmedThisSession = false;
1142
+ await this._resetStateAndDisconnectSessions();
1143
+ } else {
1144
+ await this._connectorTeardownTail;
1145
+ }
1146
+ await this._ensureDevicePermission(void 0, void 0, signal);
1147
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1148
+ const stateGeneration = this._stateGeneration;
1149
+ const devices = await this.connector.searchDevices(
1150
+ options?.transportType ? {
1151
+ transportType: options.transportType,
1152
+ waitForAll: options.waitForAllTransports
1153
+ } : void 0
1154
+ );
1155
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1156
+ if (stateGeneration !== this._stateGeneration) {
1157
+ throw createHwkError({
1158
+ code: HardwareErrorCode3.UserAborted,
1159
+ message: "Ledger discovery was reset"
1160
+ });
882
1161
  }
883
- await this._ensureDevicePermission();
884
- const devices = await this.connector.searchDevices();
885
1162
  this._discoveredDevices.clear();
886
1163
  for (const d of devices) {
887
1164
  if (d.connectId) {
@@ -889,7 +1166,7 @@ var _LedgerAdapter = class _LedgerAdapter {
889
1166
  }
890
1167
  }
891
1168
  if (this._discoveredDevices.size === 0) {
892
- await this._ensureDevicePermission();
1169
+ await this._ensureDevicePermission(void 0, void 0, signal);
893
1170
  }
894
1171
  const result = Array.from(this._discoveredDevices.values());
895
1172
  debugLog("[LedgerAdapter][RES]", {
@@ -908,41 +1185,263 @@ var _LedgerAdapter = class _LedgerAdapter {
908
1185
  throw err;
909
1186
  }
910
1187
  }
1188
+ async searchDeviceTargets(options) {
1189
+ const devices = await this.searchDevices(options);
1190
+ return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
1191
+ }
911
1192
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
912
- async _evictAllSessions() {
1193
+ async _evictAllSessions(preserveOperationId) {
1194
+ this._operations.endAll("explicit", preserveOperationId);
913
1195
  if (this._sessions.size === 0) return;
914
1196
  const stale = [...this._sessions.values()];
915
1197
  this._sessions.clear();
916
- for (const sid of stale) {
917
- try {
918
- await this.connector.disconnect(sid);
919
- } catch {
1198
+ for (const sid of stale) this._sessionTransports.delete(sid);
1199
+ await this._runConnectorTeardown(async () => {
1200
+ for (const sid of stale) {
1201
+ try {
1202
+ await this.connector.disconnect(sid);
1203
+ } catch {
1204
+ }
920
1205
  }
921
- }
1206
+ });
922
1207
  }
923
1208
  static _createDeviceBusyError(method) {
924
1209
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
925
1210
  code: HardwareErrorCode3.DeviceBusy
926
1211
  });
927
1212
  }
928
- async connectDevice(connectId) {
1213
+ async connectDevice(searchTargetId) {
1214
+ try {
1215
+ return await this._jobQueue.enqueue(
1216
+ searchTargetId || "__ledger_connect__",
1217
+ async (signal) => {
1218
+ const connected = await this._connectTarget(searchTargetId, void 0, signal);
1219
+ if (!connected.success) return connected;
1220
+ return this._createOperation(searchTargetId, connected.payload);
1221
+ },
1222
+ {
1223
+ label: "connectDevice",
1224
+ rejectIfBusy: true,
1225
+ busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1226
+ }
1227
+ );
1228
+ } catch (error) {
1229
+ return this.errorToFailure(error);
1230
+ }
1231
+ }
1232
+ /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1233
+ async bindBleDevice(params) {
1234
+ const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1235
+ try {
1236
+ return await this._jobQueue.enqueue(
1237
+ "__ledger_bind_ble__",
1238
+ async (signal) => {
1239
+ if (!this.getAvailableTransports().includes("ble")) {
1240
+ throw createHwkError({
1241
+ code: HardwareErrorCode3.TransportNotAvailable,
1242
+ message: "Ledger Bluetooth transport is not available"
1243
+ });
1244
+ }
1245
+ this._activeConnectionType = "ble";
1246
+ await this._ensureDevicePermission(void 0, void 0, signal);
1247
+ const attempt = {
1248
+ extra: params.extra,
1249
+ bindingReason: "manual-rebind",
1250
+ deferBindingSave: Boolean(identity)
1251
+ };
1252
+ try {
1253
+ const connectId = await this._connectFirstOrSelect(
1254
+ [],
1255
+ void 0,
1256
+ true,
1257
+ void 0,
1258
+ attempt,
1259
+ signal
1260
+ );
1261
+ const pending = attempt.pendingBinding;
1262
+ if (identity && pending) {
1263
+ attempt.pendingBinding = void 0;
1264
+ const sessionId = this._sessions.get(connectId);
1265
+ if (!sessionId) {
1266
+ throw createHwkError({
1267
+ code: HardwareErrorCode3.DeviceDisconnected,
1268
+ message: "Selected Ledger connection ended"
1269
+ });
1270
+ }
1271
+ const fingerprint = await this._computeChainFingerprint(
1272
+ identity.chain,
1273
+ (method, callParams) => this._runConnectorCall(
1274
+ connectId,
1275
+ method,
1276
+ callParams,
1277
+ signal,
1278
+ void 0,
1279
+ void 0,
1280
+ { autoInstallApp: true },
1281
+ { connection: { connectId, sessionId } }
1282
+ )
1283
+ );
1284
+ if (fingerprint !== identity.value) {
1285
+ await this._dropSession(connectId, signal);
1286
+ throw createHwkError({
1287
+ code: HardwareErrorCode3.DeviceMismatch,
1288
+ message: formatDeviceMismatchError(identity.value, fingerprint)
1289
+ });
1290
+ }
1291
+ await this._saveSelectedBleBinding(
1292
+ connectId,
1293
+ pending.requestId,
1294
+ attempt,
1295
+ void 0,
1296
+ signal,
1297
+ identity
1298
+ );
1299
+ }
1300
+ if (!attempt.bindingSaved) {
1301
+ await this._dropSession(connectId, signal);
1302
+ throw createHwkError({
1303
+ code: HardwareErrorCode3.UnknownError,
1304
+ message: "Bluetooth binding could not be saved",
1305
+ origin: "host"
1306
+ });
1307
+ }
1308
+ return success2(connectId);
1309
+ } catch (error) {
1310
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1311
+ throw error;
1312
+ }
1313
+ },
1314
+ {
1315
+ label: "bindBleDevice",
1316
+ rejectIfBusy: true,
1317
+ busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1318
+ }
1319
+ );
1320
+ } catch (error) {
1321
+ return this.errorToFailure(error);
1322
+ }
1323
+ }
1324
+ async acquireOperation(connectId, context) {
1325
+ try {
1326
+ return await this._jobQueue.enqueue(
1327
+ connectId || "__ledger_acquire__",
1328
+ async (signal) => {
1329
+ const transport = this._isBleConnection() ? "ble" : "usb";
1330
+ const hint = context.knownConnections?.find(
1331
+ (connection) => connection.transport === transport
1332
+ );
1333
+ const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1334
+ await this._ensureDevicePermission(target, void 0, signal);
1335
+ const attempt = {
1336
+ ...context,
1337
+ extra: context.extra ? { ...context.extra } : void 0,
1338
+ // The operation's calls decide whether the pick is the right wallet.
1339
+ deferBindingSave: true
1340
+ };
1341
+ try {
1342
+ const resolvedConnectId = await this.ensureConnected(
1343
+ target,
1344
+ signal,
1345
+ true,
1346
+ void 0,
1347
+ attempt
1348
+ );
1349
+ _LedgerAdapter._throwIfAborted(signal);
1350
+ const result = this._createOperation(connectId, resolvedConnectId);
1351
+ if (result.success && attempt.pendingBinding) {
1352
+ this._pendingOperationBindings.set(result.payload, attempt);
1353
+ }
1354
+ return result;
1355
+ } catch (error) {
1356
+ this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1357
+ throw error;
1358
+ }
1359
+ },
1360
+ {
1361
+ label: "acquireOperation",
1362
+ rejectIfBusy: true,
1363
+ busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1364
+ }
1365
+ );
1366
+ } catch (error) {
1367
+ return this.errorToFailure(error);
1368
+ }
1369
+ }
1370
+ _createOperation(searchTargetId, resolvedConnectId) {
1371
+ this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1372
+ const sessionId = this._sessions.get(resolvedConnectId);
1373
+ if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1374
+ const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1375
+ const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1376
+ vendor: "ledger",
1377
+ model: "unknown",
1378
+ firmwareVersion: "",
1379
+ deviceId: "",
1380
+ connectId: resolvedConnectId,
1381
+ connectionType
1382
+ };
1383
+ const operation = this._operations.create({
1384
+ searchTargetId,
1385
+ connectId: resolvedConnectId,
1386
+ device,
1387
+ connectionType,
1388
+ connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
1389
+ });
1390
+ return success2(operation.operationId);
1391
+ }
1392
+ async _connectTarget(connectId, preserveOperationId, signal) {
929
1393
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
930
1394
  try {
931
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1395
+ this._assertConnectorReady("connectDevice");
1396
+ const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1397
+ if (discoveredType === "usb" || discoveredType === "ble") {
1398
+ this._activeConnectionType = discoveredType;
1399
+ }
1400
+ if (this._isBleConnection() && !connectId) {
932
1401
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
933
1402
  code: HardwareErrorCode3.DeviceNotFound
934
1403
  });
935
1404
  }
936
- if (!isLedgerBleConnectionType(this.connector.connectionType)) {
937
- await this._evictAllSessions();
1405
+ await this._ensureDevicePermission(connectId, void 0, signal);
1406
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1407
+ const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1408
+ if (!isMultiTransport && this._isBleConnection()) {
1409
+ const previousSessionId = this._sessions.get(connectId);
1410
+ this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1411
+ if (previousSessionId) {
1412
+ this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1413
+ this._sessions.delete(connectId);
1414
+ await this.connector.disconnect(previousSessionId).catch(() => void 0);
1415
+ }
1416
+ } else {
1417
+ await this._evictAllSessions(preserveOperationId);
1418
+ }
1419
+ if (signal) _LedgerAdapter._throwIfAborted(signal);
1420
+ const stateGeneration = this._stateGeneration;
1421
+ const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1422
+ let session;
1423
+ this._connectingConnectId = connectId;
1424
+ try {
1425
+ session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1426
+ transportType: this._activeConnectionType ?? "usb"
1427
+ }) : await this.connector.connect(connectId);
1428
+ if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1429
+ await this.connector.disconnect(session.sessionId).catch(() => void 0);
1430
+ throw Object.assign(new Error("Ledger connection aborted"), {
1431
+ code: HardwareErrorCode3.UserAborted
1432
+ });
1433
+ }
1434
+ } finally {
1435
+ if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1436
+ releaseOperation();
938
1437
  }
939
- await this._ensureDevicePermission(connectId);
940
- const session = await this.connector.connect(connectId);
941
- this._sessions.set(connectId, session.sessionId);
1438
+ const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1439
+ this._sessions.set(resolvedConnectId, session.sessionId);
1440
+ this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
942
1441
  if (session.deviceInfo) {
943
- this._discoveredDevices.set(connectId, session.deviceInfo);
1442
+ this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
944
1443
  }
945
- const result = success(connectId);
1444
+ const result = success2(resolvedConnectId);
946
1445
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
947
1446
  return result;
948
1447
  } catch (err) {
@@ -955,30 +1454,75 @@ var _LedgerAdapter = class _LedgerAdapter {
955
1454
  return failureResult;
956
1455
  }
957
1456
  }
958
- async disconnectDevice(connectId) {
1457
+ async releaseOperation(operationId) {
1458
+ const operation = this._operations.findActive(operationId);
1459
+ if (operation) this._cancelOperationWork(operation);
1460
+ const endedOperation = this._operations.release(operationId);
1461
+ if (!endedOperation) return;
1462
+ const { connectId } = endedOperation;
959
1463
  debugLog("[LedgerAdapter][REQ]", {
960
- method: "disconnectDevice",
1464
+ method: "releaseOperation",
961
1465
  connectId,
962
1466
  params: { connectId }
963
1467
  });
964
1468
  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 });
1469
+ await this._releaseOperationConnection(endedOperation);
1470
+ debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
971
1471
  } catch (err) {
972
1472
  const e = err;
973
1473
  debugLog("[LedgerAdapter][RES]", {
974
- method: "disconnectDevice",
1474
+ method: "releaseOperation",
975
1475
  success: false,
976
1476
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
977
1477
  });
978
1478
  throw err;
979
1479
  }
980
1480
  }
981
- async getDeviceInfo(connectId, deviceId) {
1481
+ /**
1482
+ * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1483
+ * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1484
+ */
1485
+ _cancelOperationWork(operation) {
1486
+ const { operationId } = operation;
1487
+ const reason = createHwkError({
1488
+ code: HardwareErrorCode3.OperationEnded,
1489
+ message: "Ledger operation was released",
1490
+ params: { operationId, reason: "explicit" }
1491
+ });
1492
+ const queueKey = ledgerQueueKey({ operationId });
1493
+ const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1494
+ this._jobQueue.cancelActiveAndPending(queueKey, reason);
1495
+ if (!ownsRunningCall) return;
1496
+ this._uiRegistry.cancel(void 0, void 0, operationId);
1497
+ void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
1498
+ }
1499
+ async _releaseOperationConnection(operation) {
1500
+ const sessionIds = /* @__PURE__ */ new Set();
1501
+ for (const [connectId, sessionId] of this._sessions) {
1502
+ if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1503
+ this._sessions.delete(connectId);
1504
+ sessionIds.add(sessionId);
1505
+ }
1506
+ }
1507
+ for (const sessionId of sessionIds) {
1508
+ await this._runConnectorTeardown(
1509
+ () => this.connector.disconnect(sessionId).catch(() => void 0)
1510
+ );
1511
+ }
1512
+ }
1513
+ async _releaseLostOperationConnection(operationId) {
1514
+ const endedOperation = this._operations.end(operationId, "disconnect");
1515
+ if (!endedOperation) return;
1516
+ this._discoveredDevices.delete(endedOperation.connectId);
1517
+ await this._releaseOperationConnection(endedOperation);
1518
+ }
1519
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1520
+ let connectId;
1521
+ try {
1522
+ connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1523
+ } catch (error) {
1524
+ return this.errorToFailure(error);
1525
+ }
982
1526
  debugLog("[LedgerAdapter][REQ]", {
983
1527
  method: "getDeviceInfo",
984
1528
  connectId,
@@ -988,7 +1532,7 @@ var _LedgerAdapter = class _LedgerAdapter {
988
1532
  await this._ensureDevicePermission(connectId, deviceId);
989
1533
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
990
1534
  if (cached) {
991
- const result = success(cached);
1535
+ const result = success2(cached);
992
1536
  debugLog("[LedgerAdapter][RES]", {
993
1537
  method: "getDeviceInfo",
994
1538
  success: true,
@@ -1013,11 +1557,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1013
1557
  success: false,
1014
1558
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1015
1559
  });
1016
- throw err;
1560
+ return this.errorToFailure(err);
1017
1561
  }
1018
1562
  }
1019
- getSupportedChains() {
1020
- return ["evm", "btc", "sol", "tron"];
1563
+ /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1564
+ async _dropUncheckedBundlePick(context, signal) {
1565
+ const { connection } = context;
1566
+ const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1567
+ if (!connection || !owner) return;
1568
+ this._pendingPickBindings.delete(connection.connectId);
1569
+ this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1570
+ if (this._sessions.get(connection.connectId) === connection.sessionId) {
1571
+ await this._dropSession(connection.connectId, signal);
1572
+ }
1021
1573
  }
1022
1574
  // ---------------------------------------------------------------------------
1023
1575
  // Chain call helper
@@ -1037,7 +1589,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1037
1589
  commonParams,
1038
1590
  installContext
1039
1591
  );
1040
- return success(result);
1592
+ return success2(result);
1041
1593
  } catch (err) {
1042
1594
  return this.errorToFailure(err);
1043
1595
  }
@@ -1053,13 +1605,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1053
1605
  if (params && typeof params === "object") {
1054
1606
  const {
1055
1607
  autoInstallApp,
1608
+ operationId,
1056
1609
  passphraseState: _passphraseState,
1057
1610
  useEmptyPassphrase: _useEmptyPassphrase,
1611
+ knownConnections,
1612
+ extra,
1613
+ allowDeviceSelection,
1614
+ supportedTransports,
1058
1615
  ...rest
1059
1616
  } = params;
1060
1617
  return {
1061
1618
  commonParams: {
1062
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1619
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1620
+ operationId: typeof operationId === "string" ? operationId : void 0,
1621
+ ...pickConnectionContext({
1622
+ knownConnections,
1623
+ extra,
1624
+ allowDeviceSelection,
1625
+ supportedTransports
1626
+ })
1063
1627
  },
1064
1628
  rest
1065
1629
  };
@@ -1235,14 +1799,33 @@ var _LedgerAdapter = class _LedgerAdapter {
1235
1799
  );
1236
1800
  }
1237
1801
  // ---------------------------------------------------------------------------
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.
1802
+ // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1803
+ // ---------------------------------------------------------------------------
1804
+ zcashGetFullViewingKey(connectId, deviceId, params) {
1805
+ return this.callChainWithMergedParams(
1806
+ connectId,
1807
+ deviceId,
1808
+ "zcash",
1809
+ "zcashGetFullViewingKey",
1810
+ params
1811
+ );
1812
+ }
1813
+ zcashGetShieldedAddress(connectId, deviceId, params) {
1814
+ return this.callChainWithMergedParams(
1815
+ connectId,
1816
+ deviceId,
1817
+ "zcash",
1818
+ "zcashGetShieldedAddress",
1819
+ params
1820
+ );
1821
+ }
1822
+ // ---------------------------------------------------------------------------
1823
+ // App management: OS-level app install/list, no fingerprint or chain dispatch.
1241
1824
  // ---------------------------------------------------------------------------
1242
1825
  async installApp(connectId, appName) {
1243
1826
  try {
1244
1827
  await this.connectorCall(connectId, "installApp", { appName });
1245
- return success(void 0);
1828
+ return success2(void 0);
1246
1829
  } catch (err) {
1247
1830
  return this.errorToFailure(err);
1248
1831
  }
@@ -1250,7 +1833,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1250
1833
  async listInstalledApps(connectId) {
1251
1834
  try {
1252
1835
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1253
- return success(result);
1836
+ return success2(result);
1254
1837
  } catch (err) {
1255
1838
  return this.errorToFailure(err);
1256
1839
  }
@@ -1259,7 +1842,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1259
1842
  async listInstalledNames(connectId) {
1260
1843
  try {
1261
1844
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1262
- return success(result);
1845
+ return success2(result);
1263
1846
  } catch (err) {
1264
1847
  return this.errorToFailure(err);
1265
1848
  }
@@ -1267,7 +1850,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1267
1850
  async listAvailableApps(connectId) {
1268
1851
  try {
1269
1852
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1270
- return success(result);
1853
+ return success2(result);
1271
1854
  } catch (err) {
1272
1855
  return this.errorToFailure(err);
1273
1856
  }
@@ -1275,7 +1858,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1275
1858
  async getLedgerFirmwareVersion(connectId) {
1276
1859
  try {
1277
1860
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1278
- return success(result);
1861
+ return success2(result);
1279
1862
  } catch (err) {
1280
1863
  return this.errorToFailure(err);
1281
1864
  }
@@ -1283,7 +1866,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1283
1866
  async getLedgerDeviceInfo(connectId) {
1284
1867
  try {
1285
1868
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1286
- return success(result);
1869
+ return success2(result);
1287
1870
  } catch (err) {
1288
1871
  return this.errorToFailure(err);
1289
1872
  }
@@ -1323,11 +1906,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1323
1906
  );
1324
1907
  }
1325
1908
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1326
- this.resetState();
1909
+ await this._resetStateAndDisconnectSessions();
1327
1910
  }
1328
1911
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1329
1912
  if (!result.isGenuine) {
1330
- return success({
1913
+ return success2({
1331
1914
  vendor: "ledger",
1332
1915
  verified: false
1333
1916
  });
@@ -1338,7 +1921,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1338
1921
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1339
1922
  );
1340
1923
  }
1341
- return success({
1924
+ return success2({
1342
1925
  vendor: "ledger",
1343
1926
  verified: result.isGenuine,
1344
1927
  deviceId: result.deviceId
@@ -1349,10 +1932,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1349
1932
  if (relayUrl) {
1350
1933
  try {
1351
1934
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1352
- this.resetState();
1935
+ await this._resetStateAndDisconnectSessions();
1353
1936
  } catch {
1354
1937
  this.connector.reset();
1355
- this.resetState();
1938
+ await this._resetStateAndDisconnectSessions();
1356
1939
  }
1357
1940
  }
1358
1941
  }
@@ -1364,6 +1947,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1364
1947
  this.emitter.off(event, listener);
1365
1948
  }
1366
1949
  cancel(connectId) {
1950
+ const namedOperationIsLive = (id) => {
1951
+ try {
1952
+ this._operations.resolve(id);
1953
+ return true;
1954
+ } catch {
1955
+ return false;
1956
+ }
1957
+ };
1958
+ if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
1959
+ debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
1960
+ connectId
1961
+ });
1962
+ return;
1963
+ }
1367
1964
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1368
1965
  code: HardwareErrorCode3.UserAborted,
1369
1966
  _tag: ERROR_TAG.UserAborted
@@ -1374,14 +1971,48 @@ var _LedgerAdapter = class _LedgerAdapter {
1374
1971
  this._lastCancelReason = void 0;
1375
1972
  }
1376
1973
  }, 2e3);
1377
- this._uiRegistry.cancel();
1378
- if (connectId) {
1379
- this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1974
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
1975
+ let operationId;
1976
+ if (isHardwareOperationId(connectId)) {
1977
+ operationId = connectId;
1978
+ } else if (!connectId && isHardwareOperationId(activeJobId)) {
1979
+ operationId = activeJobId;
1980
+ }
1981
+ let resolvedConnectId = connectId;
1982
+ if (operationId) {
1983
+ try {
1984
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
1985
+ } catch {
1986
+ resolvedConnectId = void 0;
1987
+ }
1988
+ }
1989
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1990
+ const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
1991
+ if (!connectId) {
1992
+ this._uiRegistry.cancel();
1993
+ } else if (pendingOperationId) {
1994
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
1995
+ }
1996
+ this._finishBleBinding("cancelled");
1997
+ if (!connectId) this._pendingOperationBindings.clear();
1998
+ else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
1999
+ const queueKeys = /* @__PURE__ */ new Set();
2000
+ if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
2001
+ if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
2002
+ if (queueKeys.size) {
2003
+ let cancelledAnyJob = false;
2004
+ for (const key of queueKeys) {
2005
+ cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
2006
+ }
2007
+ debugLog("[LedgerAdapter] cancel routed to queue keys", {
2008
+ queueKeys: [...queueKeys],
2009
+ cancelledAnyJob
2010
+ });
1380
2011
  } else {
1381
2012
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1382
2013
  }
1383
- if (connectId) {
1384
- const sessionId = this._sessions.get(connectId) ?? connectId;
2014
+ if (resolvedConnectId) {
2015
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1385
2016
  void this.connector.cancel(sessionId);
1386
2017
  } else {
1387
2018
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
@@ -1389,45 +2020,86 @@ var _LedgerAdapter = class _LedgerAdapter {
1389
2020
  if (this._connectingPromise) {
1390
2021
  this._doConnectAbortController?.abort(userAbortReason);
1391
2022
  }
2023
+ const connectingConnectId = this._connectingConnectId;
2024
+ if (connectingConnectId) void this.connector.cancel(connectingConnectId);
1392
2025
  }
1393
2026
  // ---------------------------------------------------------------------------
1394
2027
  // Chain fingerprint
1395
2028
  // ---------------------------------------------------------------------------
2029
+ /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
1396
2030
  async getChainFingerprint(connectId, deviceId, chain) {
1397
2031
  try {
1398
2032
  const fingerprint = await this._computeChainFingerprint(
1399
2033
  chain,
1400
2034
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
1401
2035
  );
1402
- return success(fingerprint);
2036
+ if (deviceId) {
2037
+ if (fingerprint !== deviceId) {
2038
+ return failure2(
2039
+ HardwareErrorCode3.DeviceMismatch,
2040
+ formatDeviceMismatchError(deviceId, fingerprint)
2041
+ );
2042
+ }
2043
+ }
2044
+ return success2(fingerprint);
1403
2045
  } catch (err) {
1404
2046
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
1405
2047
  return this.errorToFailure(err);
1406
2048
  }
1407
2049
  }
1408
- /**
1409
- * Verify fingerprint using an existing sessionId directly.
1410
- * Safe to call inside connectorCall without causing queue deadlock.
1411
- */
1412
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
1413
- if (!deviceId) return { success: true };
2050
+ /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2051
+ async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
1414
2052
  try {
1415
- const fingerprint = await this._computeChainFingerprint(
1416
- chain,
1417
- (method, params) => this._callConnector(sessionId, method, params)
1418
- );
1419
- if (fingerprint === deviceId) {
1420
- return { success: true };
2053
+ const outcome = await requestSaveDeviceBinding(
2054
+ this.emitter,
2055
+ this._uiRegistry,
2056
+ {
2057
+ selectionRequestId,
2058
+ connection: { transport: "ble", connectId },
2059
+ ...identity ? { identity } : {},
2060
+ extra: context?.extra,
2061
+ operationId
2062
+ },
2063
+ signal
2064
+ );
2065
+ if (context) context.bindingSaved = outcome.saved;
2066
+ if (!outcome.saved) {
2067
+ debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2068
+ connectId,
2069
+ reason: outcome.reason
2070
+ });
1421
2071
  }
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 };
2072
+ } catch (error) {
2073
+ await this._dropSession(connectId, signal);
2074
+ throw error;
2075
+ } finally {
2076
+ if (this._bindingSelectionRequestId === selectionRequestId) {
2077
+ this._bindingSelectionRequestId = void 0;
1427
2078
  }
1428
- throw err;
1429
2079
  }
1430
2080
  }
2081
+ async _dropSession(connectId, signal) {
2082
+ const sessionId = this._sessions.get(connectId);
2083
+ this._sessions.delete(connectId);
2084
+ if (!sessionId) return;
2085
+ this._sessionTransports.delete(sessionId);
2086
+ const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2087
+ () => void 0
2088
+ );
2089
+ if (!signal.aborted) await teardown;
2090
+ }
2091
+ /** Verify on the acquired session without re-entering the job queue. */
2092
+ async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2093
+ if (!deviceId) return { success: true };
2094
+ const fingerprint = await this._computeChainFingerprint(
2095
+ chain,
2096
+ (method, params) => this._callConnector(sessionId, method, params)
2097
+ );
2098
+ if (fingerprint === deviceId) {
2099
+ return { success: true };
2100
+ }
2101
+ return { success: false, expected: deviceId, actual: fingerprint };
2102
+ }
1431
2103
  /**
1432
2104
  * Compute the chain fingerprint via a caller-supplied call strategy.
1433
2105
  *
@@ -1455,11 +2127,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1455
2127
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
1456
2128
  } else if (chain === "tron") {
1457
2129
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2130
+ } else if (chain === "zcash") {
2131
+ address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
1458
2132
  } else {
1459
2133
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
1460
2134
  }
1461
2135
  return deriveDeviceFingerprint(address);
1462
2136
  }
2137
+ /**
2138
+ * Operation owning the running job, so a mid-call UI request can name it.
2139
+ * Undefined at cold start when no operation owns the job.
2140
+ */
2141
+ _activeOperationId() {
2142
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2143
+ }
1463
2144
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
1464
2145
  // The user must press Confirm after unlocking, which triggers a search retry.
1465
2146
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -1469,15 +2150,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1469
2150
  if (signal?.aborted) {
1470
2151
  _LedgerAdapter._throwIfAborted(signal);
1471
2152
  }
2153
+ const operationId = this._activeOperationId();
1472
2154
  const waitPromise = this._uiRegistry.wait(
1473
- UI_REQUEST.REQUEST_DEVICE_CONNECT
2155
+ UI_REQUEST.REQUEST_DEVICE_CONNECT,
2156
+ { operationId }
1474
2157
  );
1475
2158
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1476
2159
  type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
1477
2160
  payload: {
1478
2161
  vendor: "ledger",
1479
2162
  reason: "device-not-found",
1480
- message: "Please connect and unlock your Ledger device"
2163
+ message: "Please connect and unlock your Ledger device",
2164
+ operationId
1481
2165
  }
1482
2166
  });
1483
2167
  let payload;
@@ -1523,7 +2207,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1523
2207
  * Returns the params to pass through (with `showOnDevice` possibly
1524
2208
  * promoted), or `null` if the user declined.
1525
2209
  */
1526
- async _gateBtcHighIndex(params) {
2210
+ async _gateBtcHighIndex(params, signal) {
1527
2211
  const accountIndex = btcAccountIndexFromPath(params.path);
1528
2212
  if (params.showOnDevice) return params;
1529
2213
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -1532,25 +2216,32 @@ var _LedgerAdapter = class _LedgerAdapter {
1532
2216
  if (this._btcHighIndexConfirmedThisSession) {
1533
2217
  return { ...params, showOnDevice: true };
1534
2218
  }
1535
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2219
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1536
2220
  if (!confirmed) return null;
1537
2221
  this._btcHighIndexConfirmedThisSession = true;
1538
2222
  return { ...params, showOnDevice: true };
1539
2223
  }
1540
- async _waitForBtcHighIndexConfirm(path, accountIndex) {
2224
+ async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2225
+ const operationId = this._activeOperationId();
1541
2226
  const waitPromise = this._uiRegistry.wait(
1542
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2227
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2228
+ { operationId }
1543
2229
  );
1544
2230
  this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1545
2231
  type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1546
2232
  payload: {
1547
2233
  vendor: "ledger",
1548
2234
  path,
1549
- accountIndex
2235
+ accountIndex,
2236
+ operationId
1550
2237
  }
1551
2238
  });
1552
2239
  try {
1553
- const payload = await waitPromise;
2240
+ const payload = await this._awaitUiAnswer(
2241
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2242
+ waitPromise,
2243
+ signal
2244
+ );
1554
2245
  return !!payload?.confirmed;
1555
2246
  } catch (err) {
1556
2247
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1560,18 +2251,35 @@ var _LedgerAdapter = class _LedgerAdapter {
1560
2251
  return false;
1561
2252
  }
1562
2253
  }
2254
+ /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2255
+ async _awaitUiAnswer(requestType, waitPromise, signal) {
2256
+ const onAbort = () => this._uiRegistry.cancel(requestType);
2257
+ if (signal.aborted) onAbort();
2258
+ signal.addEventListener("abort", onAbort, { once: true });
2259
+ try {
2260
+ return await waitPromise;
2261
+ } finally {
2262
+ signal.removeEventListener("abort", onAbort);
2263
+ }
2264
+ }
1563
2265
  // Ask the user whether to install a missing app (autoInstallApp flow).
1564
2266
  // Same register-then-emit ordering as the BTC high-index gate.
1565
- async _waitForInstallAppConfirm(appName) {
2267
+ async _waitForInstallAppConfirm(appName, signal) {
2268
+ const operationId = this._activeOperationId();
1566
2269
  const waitPromise = this._uiRegistry.wait(
1567
- UI_REQUEST.REQUEST_INSTALL_APP
2270
+ UI_REQUEST.REQUEST_INSTALL_APP,
2271
+ { operationId }
1568
2272
  );
1569
2273
  this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
1570
2274
  type: UI_REQUEST.REQUEST_INSTALL_APP,
1571
- payload: { vendor: "ledger", appName }
2275
+ payload: { vendor: "ledger", appName, operationId }
1572
2276
  });
1573
2277
  try {
1574
- const payload = await waitPromise;
2278
+ const payload = await this._awaitUiAnswer(
2279
+ UI_REQUEST.REQUEST_INSTALL_APP,
2280
+ waitPromise,
2281
+ signal
2282
+ );
1575
2283
  return !!payload?.confirmed;
1576
2284
  } catch (err) {
1577
2285
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1584,16 +2292,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1584
2292
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
1585
2293
  // `_doConnect` runs under its own internal controller so caller A's cancel
1586
2294
  // doesn't kill caller B's await.
1587
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2295
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1588
2296
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
1589
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2297
+ this._assertConnectorReady("connectDevice");
2298
+ if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1590
2299
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1591
2300
  code: HardwareErrorCode3.DeviceNotFound
1592
2301
  });
1593
2302
  }
1594
2303
  if (connectId && this._sessions.has(connectId)) return connectId;
1595
2304
  if (!connectId && this._sessions.size > 0) {
1596
- if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2305
+ if (!this._isBleConnection() && this._sessions.size > 1) {
1597
2306
  throw Object.assign(
1598
2307
  new Error(
1599
2308
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -1603,15 +2312,24 @@ var _LedgerAdapter = class _LedgerAdapter {
1603
2312
  }
1604
2313
  return this._sessions.keys().next().value;
1605
2314
  }
1606
- if (!this._connectingPromise) {
1607
- this._doConnectAbortController = new AbortController();
1608
- const innerSignal = this._doConnectAbortController.signal;
2315
+ if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2316
+ const controller = new AbortController();
2317
+ this._doConnectAbortController = controller;
2318
+ const innerSignal = controller.signal;
1609
2319
  this._connectingPromise = (async () => {
1610
2320
  try {
1611
- return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2321
+ return await this._doConnect(
2322
+ innerSignal,
2323
+ connectId,
2324
+ allowUsbEphemeralFallback,
2325
+ preserveOperationId,
2326
+ context
2327
+ );
1612
2328
  } finally {
1613
- this._connectingPromise = null;
1614
- this._doConnectAbortController = null;
2329
+ if (this._doConnectAbortController === controller) {
2330
+ this._connectingPromise = null;
2331
+ this._doConnectAbortController = null;
2332
+ }
1615
2333
  }
1616
2334
  })();
1617
2335
  }
@@ -1620,22 +2338,57 @@ var _LedgerAdapter = class _LedgerAdapter {
1620
2338
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
1621
2339
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
1622
2340
  // 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
- }
2341
+ async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2342
+ _LedgerAdapter._throwIfAborted(internalSignal);
2343
+ if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2344
+ this._activeConnectionType = "usb";
2345
+ const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2346
+ _LedgerAdapter._throwIfAborted(internalSignal);
2347
+ const knownUsb = context?.knownConnections?.find(
2348
+ (connection) => connection.transport === "usb"
2349
+ );
2350
+ const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2351
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2352
+ return this._connectFirstOrSelect(
2353
+ usbDevices,
2354
+ usbTarget,
2355
+ allowUsbEphemeralFallback,
2356
+ preserveOperationId,
2357
+ context,
2358
+ internalSignal
2359
+ );
2360
+ }
2361
+ if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2362
+ throw createHwkError({
2363
+ code: HardwareErrorCode3.DeviceNotFound,
2364
+ message: "This Ledger model has no Bluetooth transport; connect it over USB"
2365
+ });
1638
2366
  }
2367
+ this._activeConnectionType = "ble";
2368
+ const knownBle = context?.knownConnections?.find(
2369
+ (connection) => connection.transport === "ble"
2370
+ );
2371
+ if (knownBle?.transport === "ble") {
2372
+ return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2373
+ }
2374
+ if (targetConnectId && context?.knownConnections === void 0) {
2375
+ throw createHwkError({
2376
+ code: HardwareErrorCode3.DeviceNotFound,
2377
+ message: "Ledger connection metadata is required before starting Bluetooth binding"
2378
+ });
2379
+ }
2380
+ const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2381
+ return this._connectFirstOrSelect(
2382
+ bleDevices,
2383
+ void 0,
2384
+ allowUsbEphemeralFallback,
2385
+ preserveOperationId,
2386
+ context,
2387
+ internalSignal
2388
+ );
2389
+ }
2390
+ if (this._isBleConnection() && targetConnectId) {
2391
+ return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
1639
2392
  }
1640
2393
  let confirms = 0;
1641
2394
  while (!internalSignal.aborted) {
@@ -1643,22 +2396,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1643
2396
  type: EConnectorInteraction.Searching,
1644
2397
  payload: { sessionId: "" }
1645
2398
  });
1646
- let devices = await this.searchDevices();
2399
+ let devices = await this._searchDevices(void 0, internalSignal);
2400
+ _LedgerAdapter._throwIfAborted(internalSignal);
1647
2401
  if (devices.length === 0) {
1648
2402
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
1649
2403
  await new Promise((resolve) => {
1650
2404
  setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
1651
2405
  });
1652
- devices = await this.searchDevices();
2406
+ _LedgerAdapter._throwIfAborted(internalSignal);
2407
+ devices = await this._searchDevices(void 0, internalSignal);
2408
+ _LedgerAdapter._throwIfAborted(internalSignal);
1653
2409
  if (devices.length > 0) break;
1654
2410
  }
1655
2411
  }
1656
- if (devices.length > 0) {
2412
+ if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1657
2413
  try {
1658
2414
  return await this._connectFirstOrSelect(
1659
2415
  devices,
1660
2416
  targetConnectId,
1661
- allowUsbEphemeralFallback
2417
+ allowUsbEphemeralFallback,
2418
+ preserveOperationId,
2419
+ context,
2420
+ internalSignal
1662
2421
  );
1663
2422
  } catch (err) {
1664
2423
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -1687,45 +2446,147 @@ var _LedgerAdapter = class _LedgerAdapter {
1687
2446
  _LedgerAdapter._throwIfAborted(internalSignal);
1688
2447
  throw new Error("_doConnect aborted");
1689
2448
  }
1690
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2449
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2450
+ _LedgerAdapter._throwIfAborted(signal);
1691
2451
  if (targetConnectId) {
1692
2452
  const target = devices.find(
1693
2453
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
1694
2454
  );
1695
2455
  if (target) {
1696
- return this._connectDeviceOrThrow(target.connectId);
2456
+ return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1697
2457
  }
1698
- if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2458
+ if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1699
2459
  debugLog(
1700
2460
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
1701
2461
  );
1702
- return this._connectDeviceOrThrow(devices[0].connectId);
2462
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1703
2463
  }
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;
2464
+ if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2465
+ const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2466
+ code: HardwareErrorCode3.DeviceNotFound
2467
+ });
2468
+ if (this._isBleConnection()) {
2469
+ err._tag = ERROR_TAG.DeviceNotAdvertising;
2470
+ }
2471
+ throw err;
1709
2472
  }
1710
- throw err;
1711
2473
  }
1712
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
2474
+ const requiresBleSelection = this._isBleConnection();
2475
+ if (requiresBleSelection && !allowUsbEphemeralFallback) {
1713
2476
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1714
2477
  code: HardwareErrorCode3.DeviceNotFound
1715
2478
  });
1716
2479
  }
1717
- if (devices.length > 1) {
1718
- throw createMultipleUsbLedgerDevicesError();
2480
+ if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2481
+ const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2482
+ if (context) context.bindingSessionId = bindingSessionId;
2483
+ const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2484
+ const knownUsb = context?.knownConnections?.find(
2485
+ (connection) => connection.transport === "usb"
2486
+ );
2487
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2488
+ const { device, requestId } = await requestBleDeviceSelection({
2489
+ emitter: this.emitter,
2490
+ registry: this._uiRegistry,
2491
+ signal,
2492
+ allowUsbFallback,
2493
+ scan: async () => {
2494
+ if (allowUsbFallback) {
2495
+ const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2496
+ const candidate = usbDevices.find(
2497
+ (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2498
+ ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2499
+ if (candidate) return [candidate];
2500
+ }
2501
+ return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2502
+ },
2503
+ request: {
2504
+ devices,
2505
+ bindingSessionId,
2506
+ context: {
2507
+ kind: "bind-connection",
2508
+ transport: "ble",
2509
+ reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2510
+ },
2511
+ extra: context?.extra,
2512
+ operationId: preserveOperationId
2513
+ }
2514
+ });
2515
+ if (device.connectionType === "usb") {
2516
+ this._activeConnectionType = "usb";
2517
+ if (context) context.selectedConnection = void 0;
2518
+ this._bindingSelectionRequestId = requestId;
2519
+ this._finishBleBinding("cancelled");
2520
+ return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2521
+ }
2522
+ this._bindingSelectionRequestId = requestId;
2523
+ const connected = await this._connectDeviceOrThrow(
2524
+ device.connectId,
2525
+ preserveOperationId,
2526
+ signal
2527
+ );
2528
+ if (context) context.selectedConnection = { connectId: connected, requestId };
2529
+ if (context?.deferBindingSave) {
2530
+ context.pendingBinding = { connectId: connected, requestId };
2531
+ } else {
2532
+ await this._saveSelectedBleBinding(
2533
+ connected,
2534
+ requestId,
2535
+ context,
2536
+ preserveOperationId,
2537
+ signal
2538
+ );
2539
+ }
2540
+ return connected;
2541
+ }
2542
+ if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2543
+ if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2544
+ throw createHwkError({
2545
+ code: HardwareErrorCode3.DeviceNotFound,
2546
+ message: "Select a Ledger device before continuing"
2547
+ });
2548
+ }
2549
+ const requestId = this._uiRegistry.createRequestId();
2550
+ const operationId = this._activeOperationId();
2551
+ const waitPromise = this._uiRegistry.wait(
2552
+ UI_REQUEST.REQUEST_SELECT_DEVICE,
2553
+ { requestId, operationId }
2554
+ );
2555
+ this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
2556
+ type: UI_REQUEST.REQUEST_SELECT_DEVICE,
2557
+ payload: {
2558
+ devices,
2559
+ requestId,
2560
+ operationId,
2561
+ context: requiresBleSelection ? {
2562
+ kind: "bind-connection",
2563
+ transport: "ble",
2564
+ reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2565
+ } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2566
+ extra: context?.extra
2567
+ }
2568
+ });
2569
+ const { sdkConnectId } = await this._abortable(signal, waitPromise);
2570
+ _LedgerAdapter._throwIfAborted(signal);
2571
+ const selected = devices.find((device) => device.connectId === sdkConnectId);
2572
+ if (!selected) {
2573
+ throw Object.assign(new Error("Selected Ledger is no longer available"), {
2574
+ code: HardwareErrorCode3.DeviceNotFound
2575
+ });
2576
+ }
2577
+ if (context && requiresBleSelection)
2578
+ context.selectedConnection = { connectId: selected.connectId, requestId };
2579
+ return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1719
2580
  }
1720
2581
  if (devices.length !== 1) {
1721
2582
  throw Object.assign(new Error("Ledger device not found."), {
1722
2583
  code: HardwareErrorCode3.DeviceNotFound
1723
2584
  });
1724
2585
  }
1725
- return this._connectDeviceOrThrow(devices[0].connectId);
2586
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1726
2587
  }
1727
- async _connectDeviceOrThrow(chosenConnectId) {
1728
- const result = await this.connectDevice(chosenConnectId);
2588
+ async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2589
+ const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1729
2590
  if (!result.success) {
1730
2591
  const payload = result.payload;
1731
2592
  const rethrow = Object.assign(new Error(payload.error), {
@@ -1736,16 +2597,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1736
2597
  }
1737
2598
  throw rethrow;
1738
2599
  }
1739
- return chosenConnectId;
2600
+ return result.payload;
1740
2601
  }
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
2602
  /**
1750
2603
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
1751
2604
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -1766,33 +2619,145 @@ var _LedgerAdapter = class _LedgerAdapter {
1766
2619
  * lives in one place.
1767
2620
  */
1768
2621
  async _callConnector(sessionId, method, params, signal) {
1769
- const promise = this.connector.call(sessionId, method, params);
2622
+ this._assertConnectorReady(method);
2623
+ if (signal?.aborted) throw this._abortReason(signal);
2624
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2625
+ let promise;
2626
+ try {
2627
+ promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2628
+ } catch (error) {
2629
+ releaseOperation();
2630
+ throw error;
2631
+ }
1770
2632
  const result = signal ? await this._abortable(signal, promise) : await promise;
1771
2633
  return this._unwrapConnectorResult(result);
1772
2634
  }
2635
+ _assertConnectorReady(method) {
2636
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2637
+ throw _LedgerAdapter._createDeviceBusyError(method);
2638
+ }
2639
+ }
2640
+ _runConnectorTeardown(task) {
2641
+ const previous = this._connectorTeardownTail;
2642
+ let releaseTail = () => void 0;
2643
+ this._connectorTeardownTail = new Promise((resolve) => {
2644
+ releaseTail = resolve;
2645
+ });
2646
+ this._pendingConnectorTeardowns += 1;
2647
+ return (async () => {
2648
+ try {
2649
+ await previous;
2650
+ await this._waitForConnectorOperationsToDrain();
2651
+ await task();
2652
+ } finally {
2653
+ this._pendingConnectorTeardowns -= 1;
2654
+ releaseTail();
2655
+ }
2656
+ })();
2657
+ }
2658
+ _waitForConnectorOperationsToDrain() {
2659
+ if (this._unsettledConnectorOperations.size === 0) {
2660
+ return Promise.resolve();
2661
+ }
2662
+ return new Promise((resolve) => {
2663
+ this._connectorIdleWaiters.add(resolve);
2664
+ });
2665
+ }
2666
+ _retainConnectorOperation(key) {
2667
+ this._unsettledConnectorOperations.set(
2668
+ key,
2669
+ (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2670
+ );
2671
+ let released = false;
2672
+ return () => {
2673
+ if (released) return;
2674
+ released = true;
2675
+ const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2676
+ if (remaining > 0) {
2677
+ this._unsettledConnectorOperations.set(key, remaining);
2678
+ } else {
2679
+ this._unsettledConnectorOperations.delete(key);
2680
+ }
2681
+ if (this._unsettledConnectorOperations.size === 0) {
2682
+ for (const resolve of this._connectorIdleWaiters) resolve();
2683
+ this._connectorIdleWaiters.clear();
2684
+ }
2685
+ };
2686
+ }
1773
2687
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1774
- debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1775
- const queueKey = connectId || "__ledger_default__";
2688
+ const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
2689
+ if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2690
+ throw createHwkError({
2691
+ code: HardwareErrorCode3.InvalidParams,
2692
+ message: "Conflicting Ledger operation ids",
2693
+ params: {
2694
+ positionalOperationId,
2695
+ commonOperationId: commonParams.operationId
2696
+ }
2697
+ });
2698
+ }
2699
+ const operationId = commonParams?.operationId ?? positionalOperationId;
2700
+ const operation = operationId ? this._operations.resolve(operationId) : void 0;
2701
+ const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2702
+ const effectiveConnectId = operation?.connectId ?? connectId;
2703
+ debugLog("[LedgerAdapter][REQ]", {
2704
+ method,
2705
+ connectId: effectiveConnectId || "(empty)",
2706
+ params: summarizeForLog(params, { method })
2707
+ });
2708
+ const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1776
2709
  try {
1777
2710
  const result = await this._jobQueue.enqueue(
1778
2711
  queueKey,
1779
- async (signal) => this._runConnectorCall(
1780
- connectId,
1781
- method,
1782
- params,
1783
- signal,
1784
- fingerprint,
1785
- permissionDeviceId,
1786
- commonParams,
1787
- installContext
1788
- ),
2712
+ async (signal) => {
2713
+ if (operationId) this._activeOperationJobs.add(operationId);
2714
+ try {
2715
+ return await this._runConnectorCall(
2716
+ effectiveConnectId,
2717
+ method,
2718
+ params,
2719
+ signal,
2720
+ fingerprint,
2721
+ permissionDeviceId,
2722
+ commonParams,
2723
+ installContext ?? {},
2724
+ operationId
2725
+ );
2726
+ } catch (error) {
2727
+ const status = signal.aborted ? "cancelled" : "failed";
2728
+ const bundleConnectId = installContext?.connection?.connectId;
2729
+ let keptBundlePick = false;
2730
+ for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2731
+ if (pickedConnectId === bundleConnectId) {
2732
+ keptBundlePick = true;
2733
+ } else {
2734
+ this._pendingPickBindings.delete(pickedConnectId);
2735
+ this._discardPendingBinding(owner, status);
2736
+ await this._dropSession(pickedConnectId, signal);
2737
+ }
2738
+ }
2739
+ if (!keptBundlePick) this._finishBleBinding(status);
2740
+ throw error;
2741
+ } finally {
2742
+ if (operationId) {
2743
+ this._activeOperationJobs.delete(operationId);
2744
+ if (this._pendingOperationDisconnects.delete(operationId)) {
2745
+ await this._releaseLostOperationConnection(operationId);
2746
+ }
2747
+ }
2748
+ }
2749
+ },
1789
2750
  {
1790
2751
  label: method,
1791
2752
  rejectIfBusy: true,
1792
2753
  busyError: _LedgerAdapter._createDeviceBusyError(method)
1793
2754
  }
1794
2755
  );
1795
- debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2756
+ debugLog("[LedgerAdapter][RES]", {
2757
+ method,
2758
+ success: true,
2759
+ payload: summarizeForLog(result, { method, role: "result" })
2760
+ });
1796
2761
  return result;
1797
2762
  } catch (err) {
1798
2763
  const e = err;
@@ -1806,15 +2771,22 @@ var _LedgerAdapter = class _LedgerAdapter {
1806
2771
  }
1807
2772
  });
1808
2773
  throw err;
2774
+ } finally {
2775
+ releaseOperationRetention?.();
1809
2776
  }
1810
2777
  }
2778
+ /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2779
+ _abortReason(signal) {
2780
+ return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2781
+ }
1811
2782
  /**
1812
2783
  * Race a promise against an abort signal. On abort, rejects with
1813
2784
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
1814
2785
  */
1815
2786
  _abortable(signal, promise) {
1816
- const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2787
+ const getAbortReason = () => this._abortReason(signal);
1817
2788
  if (signal.aborted) {
2789
+ void promise.catch(() => void 0);
1818
2790
  return Promise.reject(getAbortReason());
1819
2791
  }
1820
2792
  return new Promise((resolve, reject) => {
@@ -1841,17 +2813,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1841
2813
  }
1842
2814
  }
1843
2815
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
1844
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2816
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1845
2817
  _LedgerAdapter._throwIfAborted(signal);
1846
- await this._ensureDevicePermission(
1847
- connectId,
1848
- permissionDeviceId ?? fingerprint?.deviceId,
1849
- signal
1850
- );
2818
+ if (!operationId) {
2819
+ await this._ensureDevicePermission(
2820
+ connectId,
2821
+ permissionDeviceId ?? fingerprint?.deviceId,
2822
+ signal
2823
+ );
2824
+ }
1851
2825
  _LedgerAdapter._throwIfAborted(signal);
1852
2826
  let effectiveParams = params;
1853
2827
  if (method === "btcGetPublicKey") {
1854
- const gatedParams = await this._gateBtcHighIndex(params);
2828
+ const gatedParams = await this._gateBtcHighIndex(params, signal);
1855
2829
  if (gatedParams === null) {
1856
2830
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
1857
2831
  _tag: ERROR_TAG.UserAborted,
@@ -1861,19 +2835,67 @@ var _LedgerAdapter = class _LedgerAdapter {
1861
2835
  effectiveParams = gatedParams;
1862
2836
  }
1863
2837
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
1864
- const resolvedConnectId = await this.ensureConnected(
1865
- connectId,
2838
+ let businessCallStarted = false;
2839
+ const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2840
+ const knownTransport = this._isBleConnection() ? "ble" : "usb";
2841
+ const hintedConnectId = commonParams?.knownConnections?.find(
2842
+ (connection) => connection.transport === knownTransport
2843
+ );
2844
+ const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2845
+ const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2846
+ const checksWallet = Boolean(
2847
+ fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2848
+ );
2849
+ const connectionAttempt = {
2850
+ ...commonParams,
2851
+ deferBindingSave: checksWallet
2852
+ };
2853
+ const bundleConnection = installContext?.connection;
2854
+ if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2855
+ throw createHwkError({
2856
+ code: HardwareErrorCode3.DeviceDisconnected,
2857
+ message: "Ledger all-network connection ended"
2858
+ });
2859
+ }
2860
+ const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2861
+ preferredConnectId,
1866
2862
  signal,
1867
- allowUsbEphemeralFallback
2863
+ allowUsbEphemeralFallback,
2864
+ void 0,
2865
+ connectionAttempt
1868
2866
  );
2867
+ const walletCheck = installContext?.walletCheck;
2868
+ if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2869
+ throw createHwkError({
2870
+ code: HardwareErrorCode3.DeviceMismatch,
2871
+ message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2872
+ });
2873
+ }
1869
2874
  const sessionId = this._sessions.get(resolvedConnectId);
2875
+ if (sessionId && installContext && !installContext.connection) {
2876
+ installContext.connection = { connectId: resolvedConnectId, sessionId };
2877
+ }
1870
2878
  if (!sessionId) {
2879
+ if (operationId) {
2880
+ this._operations.end(operationId, "disconnect");
2881
+ throw createHwkError({
2882
+ code: HardwareErrorCode3.OperationEnded,
2883
+ message: "Ledger operation connection is no longer active",
2884
+ params: { operationId, reason: "disconnect" }
2885
+ });
2886
+ }
1871
2887
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
1872
2888
  _tag: ERROR_TAG.DeviceSessionNotFound
1873
2889
  });
1874
2890
  }
1875
2891
  try {
1876
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2892
+ const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2893
+ if (!operationId && connectionAttempt.pendingBinding) {
2894
+ this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2895
+ }
2896
+ const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2897
+ const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2898
+ if (fingerprint && checksWallet) {
1877
2899
  const fp = await this._abortable(
1878
2900
  signal,
1879
2901
  this._verifyDeviceFingerprintWithSession(
@@ -1883,14 +2905,68 @@ var _LedgerAdapter = class _LedgerAdapter {
1883
2905
  )
1884
2906
  );
1885
2907
  if (!fp.success) {
2908
+ if (pendingBinding) {
2909
+ this._discardPendingBinding(bindingOwner, "failed");
2910
+ this._pendingPickBindings.delete(resolvedConnectId);
2911
+ }
2912
+ if (operationId) {
2913
+ this._pendingOperationBindings.delete(operationId);
2914
+ this._operations.end(operationId, "explicit");
2915
+ await this._dropSession(resolvedConnectId, signal);
2916
+ }
1886
2917
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
1887
2918
  code: HardwareErrorCode3.DeviceMismatch
1888
2919
  });
1889
2920
  }
2921
+ if (walletCheck) walletCheck.verified = true;
1890
2922
  }
1891
- return await this._callConnector(sessionId, method, effectiveParams, signal);
2923
+ if (pendingBinding && bindingOwner) {
2924
+ bindingOwner.pendingBinding = void 0;
2925
+ if (operationId) this._pendingOperationBindings.delete(operationId);
2926
+ else this._pendingPickBindings.delete(resolvedConnectId);
2927
+ await this._saveSelectedBleBinding(
2928
+ pendingBinding.connectId,
2929
+ pendingBinding.requestId,
2930
+ bindingOwner,
2931
+ operationId,
2932
+ signal,
2933
+ fingerprint && checksWallet ? {
2934
+ vendor: "ledger",
2935
+ type: "chainFingerprint",
2936
+ chain: fingerprint.chain,
2937
+ value: fingerprint.deviceId
2938
+ } : void 0
2939
+ );
2940
+ }
2941
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
2942
+ this._selectedBleReconnectTargets.set(connectId, {
2943
+ connectId: resolvedConnectId,
2944
+ chain: fingerprint.chain,
2945
+ fingerprint: fingerprint.deviceId
2946
+ });
2947
+ }
2948
+ businessCallStarted = true;
2949
+ const result = await this._callConnector(sessionId, method, effectiveParams, signal);
2950
+ if (walletCheck) walletCheck.derived = true;
2951
+ return result;
1892
2952
  } catch (err) {
1893
2953
  if (signal.aborted) throw err;
2954
+ if (isLostConnectionError(err)) {
2955
+ this._discoveredDevices.delete(resolvedConnectId);
2956
+ if (operationId) await this._releaseLostOperationConnection(operationId);
2957
+ else {
2958
+ this._sessions.delete(resolvedConnectId);
2959
+ await this.connector.disconnect(sessionId).catch(() => void 0);
2960
+ }
2961
+ const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
2962
+ const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
2963
+ throw createHwkError({
2964
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
2965
+ message: "Ledger operation connection was lost; start a new operation",
2966
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
2967
+ recovery: ambiguous ? { scope: "unknown" } : void 0
2968
+ });
2969
+ }
1894
2970
  const errObj = err;
1895
2971
  debugLog("[LedgerAdapter] connectorCall error:", method, {
1896
2972
  message: errObj?.message,
@@ -1902,6 +2978,64 @@ var _LedgerAdapter = class _LedgerAdapter {
1902
2978
  isNotAdvertising: isDeviceNotAdvertisingError(err),
1903
2979
  isStuckApp: isStuckAppStateError(err)
1904
2980
  });
2981
+ const assertSessionCurrent = (message) => {
2982
+ if (this._sessions.get(resolvedConnectId) === sessionId) return;
2983
+ throw createHwkError({
2984
+ code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
2985
+ message
2986
+ });
2987
+ };
2988
+ if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
2989
+ await this._waitForDeviceConnect(signal);
2990
+ assertSessionCurrent("Ledger connection ended while waiting for unlock");
2991
+ if (walletCheck?.derived) walletCheck.verified = false;
2992
+ return this._runConnectorCall(
2993
+ resolvedConnectId,
2994
+ method,
2995
+ effectiveParams,
2996
+ signal,
2997
+ fingerprint,
2998
+ permissionDeviceId,
2999
+ commonParams,
3000
+ installContext,
3001
+ operationId,
3002
+ lockedRetryBudget - 1
3003
+ );
3004
+ }
3005
+ if (businessCallStarted && isStuckAppStateError(err)) {
3006
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
3007
+ assertSessionCurrent("Ledger connection ended during the app transition");
3008
+ try {
3009
+ const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
3010
+ if (walletCheck) walletCheck.derived = true;
3011
+ return retried;
3012
+ } catch (retryErr) {
3013
+ if (isStuckAppStateError(retryErr)) throw err;
3014
+ if (isLostConnectionError(retryErr)) {
3015
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3016
+ else {
3017
+ this._sessions.delete(resolvedConnectId);
3018
+ this._discoveredDevices.delete(resolvedConnectId);
3019
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3020
+ }
3021
+ const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
3022
+ throw createHwkError({
3023
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
3024
+ message: `Ledger ${method} may have completed before the connection was lost`,
3025
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3026
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3027
+ });
3028
+ }
3029
+ throw retryErr;
3030
+ }
3031
+ }
3032
+ if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
3033
+ this._sessions.delete(resolvedConnectId);
3034
+ this._sessionTransports.delete(sessionId);
3035
+ this._discoveredDevices.delete(resolvedConnectId);
3036
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3037
+ throw err;
3038
+ }
1905
3039
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
1906
3040
  const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
1907
3041
  if (autoInstallApp && isAppMissing) {
@@ -1918,7 +3052,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1918
3052
  appName
1919
3053
  });
1920
3054
  }
1921
- const confirmed = await this._waitForInstallAppConfirm(appName);
3055
+ const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1922
3056
  if (!confirmed) {
1923
3057
  throw createHwkError({
1924
3058
  code: HardwareErrorCode3.UserAborted,
@@ -1957,157 +3091,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1957
3091
  fingerprint,
1958
3092
  permissionDeviceId,
1959
3093
  commonParams,
1960
- installContext
3094
+ installContext,
3095
+ operationId
1961
3096
  );
1962
3097
  }
1963
3098
  }
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
2001
- );
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
- }
2050
- throw lastErr;
2051
- }
2052
- if (isTimeoutError(err)) {
2053
- debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
2054
- this._discoveredDevices.delete(resolvedConnectId);
2055
- return this._retryWithFreshConnection(
2056
- resolvedConnectId,
2057
- method,
2058
- effectiveParams,
2059
- signal,
2060
- err,
2061
- fingerprint
2062
- );
2063
- }
2064
- if (isConnectionLevelError(err)) {
2065
- debugLog("[LedgerAdapter] connection-level fail-closed reset");
2066
- this._sessions.delete(resolvedConnectId);
2067
- this._discoveredDevices.delete(resolvedConnectId);
2068
- this.connector.reset();
2069
- const codeNum = err?.code;
2070
- throw Object.assign(err, {
2071
- code: codeNum ?? HardwareErrorCode3.DeviceDisconnected
2072
- });
2073
- }
2074
3099
  throw err;
2075
3100
  }
2076
3101
  }
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
3102
  _sleepAbortable(ms, signal) {
2112
3103
  return new Promise((resolve, reject) => {
2113
3104
  if (signal.aborted) {
@@ -2126,111 +3117,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2126
3117
  });
2127
3118
  }
2128
3119
  /**
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
3120
+ * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3121
+ * replies. Without connectId the request is environment-level, else device-level.
2221
3122
  */
2222
3123
  async _ensureDevicePermission(connectId, deviceId, signal) {
2223
3124
  if (signal?.aborted) {
2224
3125
  _LedgerAdapter._throwIfAborted(signal);
2225
3126
  }
2226
3127
  const transportType = this.activeTransport ?? "hid";
3128
+ const operationId = this._activeOperationId();
2227
3129
  const waitPromise = this._uiRegistry.wait(
2228
3130
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2229
- { timeoutMs: 6e4 }
3131
+ { timeoutMs: 6e4, operationId }
2230
3132
  );
2231
3133
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2232
3134
  type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2233
- payload: { transportType, connectId, deviceId }
3135
+ payload: { transportType, connectId, deviceId, operationId }
2234
3136
  });
2235
3137
  let response;
2236
3138
  const onAbort = () => {
@@ -2276,7 +3178,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2276
3178
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
2277
3179
  const e = err;
2278
3180
  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);
3181
+ return ledgerFailure(
3182
+ e.code,
3183
+ e.message ?? "Unknown error",
3184
+ e.appName,
3185
+ tag,
3186
+ params,
3187
+ void 0,
3188
+ isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
3189
+ );
2280
3190
  }
2281
3191
  const mapped = mapLedgerError(err);
2282
3192
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -2303,7 +3213,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2303
3213
  deviceId: device.deviceId,
2304
3214
  connectId: device.connectId,
2305
3215
  label: device.name,
2306
- connectionType: this.connector.connectionType,
3216
+ connectionType: device.connectionType ?? this.connector.connectionType,
2307
3217
  rssi: device.rssi,
2308
3218
  isConnectable: device.isConnectable,
2309
3219
  serialNumber: device.serialNumber,
@@ -2329,8 +3239,8 @@ var LedgerAdapter = _LedgerAdapter;
2329
3239
 
2330
3240
  // src/connector/LedgerConnectorBase.ts
2331
3241
  import {
2332
- EConnectorInteraction as EConnectorInteraction4,
2333
- HardwareErrorCode as HardwareErrorCode8,
3242
+ EConnectorInteraction as EConnectorInteraction3,
3243
+ HardwareErrorCode as HardwareErrorCode7,
2334
3244
  isKnownNonTargetHardwareVendor,
2335
3245
  serializeConnectorError
2336
3246
  } from "@onekeyfe/hwk-adapter-core";
@@ -2603,7 +3513,7 @@ var LedgerDeviceManager = class {
2603
3513
 
2604
3514
  // src/signer/SignerManager.ts
2605
3515
  import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
2606
- import { ContextModuleBuilder } from "@ledgerhq/context-module";
3516
+ import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
2607
3517
 
2608
3518
  // src/signer/SignerEth.ts
2609
3519
  import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
@@ -2611,6 +3521,7 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
2611
3521
  // src/signer/deviceActionToPromise.ts
2612
3522
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
2613
3523
  var IDLE_WATCHDOG_MS = 65e3;
3524
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2614
3525
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
2615
3526
  return new Promise((resolve, reject) => {
2616
3527
  let settled = false;
@@ -2798,7 +3709,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
2798
3709
  }
2799
3710
 
2800
3711
  // src/signer/SignerEth.ts
2801
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2802
3712
  var SignerEth = class {
2803
3713
  // eslint-disable-next-line no-useless-constructor, no-empty-function
2804
3714
  constructor(_sdk) {
@@ -2869,7 +3779,7 @@ var SignerManager = class _SignerManager {
2869
3779
  return (args) => new SignerEthBuilder(args);
2870
3780
  }
2871
3781
  static _createContextModule() {
2872
- const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
3782
+ const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2873
3783
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
2874
3784
  }
2875
3785
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -2907,6 +3817,27 @@ function collapseSignerInteraction(interaction) {
2907
3817
  return EConnectorInteraction2.ConfirmOnDevice;
2908
3818
  }
2909
3819
  }
3820
+ function wireSignerToSession(ctx, sessionId, chain, signer) {
3821
+ signer.onInteraction = (interaction) => {
3822
+ debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3823
+ ctx.emit("ui-event", {
3824
+ type: collapseSignerInteraction(interaction),
3825
+ payload: { sessionId }
3826
+ });
3827
+ };
3828
+ signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3829
+ return signer;
3830
+ }
3831
+ async function runSignerCall(ctx, sessionId, call) {
3832
+ try {
3833
+ return await call();
3834
+ } catch (err) {
3835
+ ctx.invalidateSession(sessionId);
3836
+ throw ctx.wrapError(err);
3837
+ } finally {
3838
+ ctx.clearCanceller(sessionId);
3839
+ }
3840
+ }
2910
3841
 
2911
3842
  // src/connector/chains/evm.ts
2912
3843
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3007,14 +3938,13 @@ async function _getEthSigner(ctx, sessionId) {
3007
3938
 
3008
3939
  // src/connector/chains/btc.ts
3009
3940
  import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
3010
- import { Psbt } from "bitcoinjs-lib";
3941
+ import { Psbt as Psbt2 } from "bitcoinjs-lib";
3011
3942
 
3012
3943
  // src/signer/SignerBtc.ts
3013
3944
  import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
3014
3945
  function hexToUtf8(hex) {
3015
3946
  return new TextDecoder().decode(hexToBytes2(hex));
3016
3947
  }
3017
- var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3018
3948
  var SignerBtc = class {
3019
3949
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3020
3950
  constructor(_sdk) {
@@ -3028,7 +3958,7 @@ var SignerBtc = class {
3028
3958
  return deviceActionToPromise(
3029
3959
  action,
3030
3960
  this.onInteraction,
3031
- void 0,
3961
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3032
3962
  this.onRegisterCanceller
3033
3963
  );
3034
3964
  }
@@ -3046,14 +3976,14 @@ var SignerBtc = class {
3046
3976
  const result = await deviceActionToPromise(
3047
3977
  action,
3048
3978
  this.onInteraction,
3049
- void 0,
3979
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3050
3980
  this.onRegisterCanceller
3051
3981
  );
3052
3982
  debugLog(
3053
3983
  "[SignerBtc] getExtendedPublicKey result type:",
3054
3984
  typeof result,
3055
3985
  "value:",
3056
- typeof result === "string" ? `${result.substring(0, 20)}...` : JSON.stringify(result).substring(0, 50)
3986
+ summarizeForLog(result)
3057
3987
  );
3058
3988
  if (typeof result === "string") return result;
3059
3989
  return result.extendedPublicKey;
@@ -3082,7 +4012,7 @@ var SignerBtc = class {
3082
4012
  return deviceActionToPromise(
3083
4013
  action,
3084
4014
  this.onInteraction,
3085
- INTERACTIVE_TIMEOUT_MS2,
4015
+ INTERACTIVE_TIMEOUT_MS,
3086
4016
  this.onRegisterCanceller
3087
4017
  );
3088
4018
  }
@@ -3095,7 +4025,7 @@ var SignerBtc = class {
3095
4025
  return deviceActionToPromise(
3096
4026
  action,
3097
4027
  this.onInteraction,
3098
- INTERACTIVE_TIMEOUT_MS2,
4028
+ INTERACTIVE_TIMEOUT_MS,
3099
4029
  this.onRegisterCanceller
3100
4030
  );
3101
4031
  }
@@ -3108,7 +4038,7 @@ var SignerBtc = class {
3108
4038
  return deviceActionToPromise(
3109
4039
  action,
3110
4040
  this.onInteraction,
3111
- INTERACTIVE_TIMEOUT_MS2,
4041
+ INTERACTIVE_TIMEOUT_MS,
3112
4042
  this.onRegisterCanceller
3113
4043
  );
3114
4044
  }
@@ -3131,7 +4061,21 @@ function _purposeToTemplate(purpose, DDT) {
3131
4061
  });
3132
4062
  }
3133
4063
  }
4064
+ function assertBitcoinMainnet(coin) {
4065
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4066
+ throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4067
+ code: HardwareErrorCode5.ChainNotSupported
4068
+ });
4069
+ }
4070
+ }
3134
4071
  async function btcGetAddress(ctx, sessionId, params) {
4072
+ assertBitcoinMainnet(params.coin);
4073
+ if (normalizePath(params.path).split("/").length !== 3) {
4074
+ throw Object.assign(
4075
+ new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4076
+ { code: HardwareErrorCode5.InvalidParams }
4077
+ );
4078
+ }
3135
4079
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3136
4080
  const path = normalizePath(params.path);
3137
4081
  try {
@@ -3162,6 +4106,7 @@ async function btcGetAddress(ctx, sessionId, params) {
3162
4106
  }
3163
4107
  }
3164
4108
  async function btcGetPublicKey(ctx, sessionId, params) {
4109
+ assertBitcoinMainnet(params.coin);
3165
4110
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3166
4111
  const path = normalizePath(params.path);
3167
4112
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -3169,7 +4114,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
3169
4114
  const xpub = await btcSigner.getExtendedPublicKey(path, {
3170
4115
  checkOnDevice: params.showOnDevice ?? false
3171
4116
  });
3172
- debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", `${xpub?.substring(0, 20)}...`);
4117
+ debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
3173
4118
  return { xpub, path: params.path };
3174
4119
  } catch (err) {
3175
4120
  debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
@@ -3290,7 +4235,7 @@ function _isScriptPathInput(input) {
3290
4235
  return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
3291
4236
  }
3292
4237
  function _applySignaturesToPsbt(psbtHex, signatures) {
3293
- const psbt = Psbt.fromHex(psbtHex);
4238
+ const psbt = Psbt2.fromHex(psbtHex);
3294
4239
  for (const sig of signatures) {
3295
4240
  const input = psbt.data.inputs[sig.inputIndex];
3296
4241
  if (!input) {
@@ -3339,7 +4284,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
3339
4284
  }
3340
4285
 
3341
4286
  // src/connector/chains/sol.ts
3342
- import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
4287
+ import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
4288
+ import bs58 from "bs58";
3343
4289
 
3344
4290
  // src/signer/SignerSol.ts
3345
4291
  var SignerSol = class {
@@ -3357,7 +4303,7 @@ var SignerSol = class {
3357
4303
  return deviceActionToPromise(
3358
4304
  action,
3359
4305
  this.onInteraction,
3360
- void 0,
4306
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3361
4307
  this.onRegisterCanceller
3362
4308
  );
3363
4309
  }
@@ -3369,7 +4315,7 @@ var SignerSol = class {
3369
4315
  return deviceActionToPromise(
3370
4316
  action,
3371
4317
  this.onInteraction,
3372
- void 0,
4318
+ INTERACTIVE_TIMEOUT_MS,
3373
4319
  this.onRegisterCanceller
3374
4320
  );
3375
4321
  }
@@ -3382,7 +4328,7 @@ var SignerSol = class {
3382
4328
  return deviceActionToPromise(
3383
4329
  action,
3384
4330
  this.onInteraction,
3385
- void 0,
4331
+ INTERACTIVE_TIMEOUT_MS,
3386
4332
  this.onRegisterCanceller
3387
4333
  );
3388
4334
  }
@@ -3423,8 +4369,21 @@ async function solSignMessage(ctx, sessionId, params) {
3423
4369
  const path = normalizePath(params.path);
3424
4370
  const messageBytes = hexToBytes3(params.message);
3425
4371
  try {
4372
+ if (params.messageVersion === 1) {
4373
+ const preparedMessage = prepareSolanaOffchainMessageV1({
4374
+ message: messageBytes,
4375
+ requiredSigners: params.requiredSigners
4376
+ });
4377
+ const { SignMessageVersion } = await ctx.importLedgerKit(
4378
+ "@ledgerhq/device-signer-kit-solana"
4379
+ );
4380
+ const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4381
+ version: SignMessageVersion.Raw
4382
+ });
4383
+ return { signature: decodeBase58Signature(result2.signature) };
4384
+ }
3426
4385
  const result = await solSigner.signMessage(path, messageBytes);
3427
- return { signature: result.signature };
4386
+ return { signature: decodeBase58EnvelopeSignature(result.signature) };
3428
4387
  } catch (err) {
3429
4388
  ctx.invalidateSession(sessionId);
3430
4389
  throw ctx.wrapError(err);
@@ -3432,11 +4391,27 @@ async function solSignMessage(ctx, sessionId, params) {
3432
4391
  ctx.clearCanceller(sessionId);
3433
4392
  }
3434
4393
  }
4394
+ function decodeBase58Signature(signature) {
4395
+ const bytes = bs58.decode(signature);
4396
+ if (bytes.length !== 64) {
4397
+ throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4398
+ }
4399
+ return bytesToHex(bytes);
4400
+ }
4401
+ function decodeBase58EnvelopeSignature(envelope) {
4402
+ const bytes = bs58.decode(envelope);
4403
+ if (bytes.length < 65 || bytes[0] !== 1) {
4404
+ throw new Error("Ledger Solana signature envelope is invalid");
4405
+ }
4406
+ return bytesToHex(bytes.subarray(1, 65));
4407
+ }
3435
4408
  async function _createSolSigner(ctx, sessionId) {
3436
4409
  const dmk = await ctx.getOrCreateDmk();
3437
- const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4410
+ const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4411
+ "@ledgerhq/context-module"
4412
+ );
3438
4413
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
3439
- const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4414
+ const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3440
4415
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
3441
4416
  const signer = new SignerSol(sdkSigner);
3442
4417
  signer.onInteraction = (interaction) => {
@@ -3452,361 +4427,147 @@ async function _createSolSigner(ctx, sessionId) {
3452
4427
  return signer;
3453
4428
  }
3454
4429
 
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";
4430
+ // src/connector/chains/zcash.ts
4431
+ import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
3461
4432
 
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);
4433
+ // src/signer/SignerZcash.ts
4434
+ var SignerZcash = class {
4435
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4436
+ constructor(_sdk) {
4437
+ this._sdk = _sdk;
3528
4438
  }
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
- }
4439
+ /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4440
+ async getFullViewingKey(derivationPath, options) {
4441
+ const action = this._sdk.getFullViewingKey(derivationPath, options);
4442
+ return deviceActionToPromise(
4443
+ action,
4444
+ this.onInteraction,
4445
+ void 0,
4446
+ this.onRegisterCanceller
3565
4447
  );
3566
4448
  }
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})`
4449
+ /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4450
+ async getShieldedAddress(derivationPath, options) {
4451
+ const action = this._sdk.getShieldedAddress(derivationPath, options);
4452
+ return deviceActionToPromise(
4453
+ action,
4454
+ this.onInteraction,
4455
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4456
+ this.onRegisterCanceller
3629
4457
  );
3630
4458
  }
3631
- _isDashboard(appName) {
3632
- return appName === DASHBOARD_APP_NAME;
3633
- }
3634
- _wait() {
3635
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3636
- }
3637
4459
  };
3638
4460
 
3639
- // src/connector/chains/legacyChainCall.ts
3640
- function isLegacyWrongAppError(err, _appName) {
3641
- return isWrongAppError(err);
4461
+ // src/connector/chains/zcash.ts
4462
+ async function zcashGetFullViewingKey(ctx, sessionId, params) {
4463
+ const signer = await _createZcashSigner(ctx, sessionId);
4464
+ const path = normalizePath(params.path);
4465
+ const mode = params.mode ?? "ufvk";
4466
+ return runSignerCall(ctx, sessionId, async () => {
4467
+ const result = await signer.getFullViewingKey(path, { mode });
4468
+ if (result.mode === "ufvk") {
4469
+ return { path: params.path, mode, ufvk: result.fullViewingKey };
4470
+ }
4471
+ return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
4472
+ });
3642
4473
  }
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 }
4474
+ async function zcashGetShieldedAddress(ctx, sessionId, params) {
4475
+ const signer = await _createZcashSigner(ctx, sessionId);
4476
+ const path = normalizePath(params.path);
4477
+ return runSignerCall(ctx, sessionId, async () => {
4478
+ const result = await signer.getShieldedAddress(path, {
4479
+ checkOnDevice: params.showOnDevice ?? false
3651
4480
  });
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
- }
4481
+ return { address: result.address, path: params.path };
4482
+ });
3719
4483
  }
3720
- async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4484
+ async function _createZcashSigner(ctx, sessionId) {
3721
4485
  const dmk = await ctx.getOrCreateDmk();
3722
- const appManager = new AppManager(dmk);
3723
- await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4486
+ const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4487
+ const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4488
+ return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3724
4489
  }
3725
4490
 
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;
4491
+ // src/connector/chains/tron.ts
4492
+ import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
4493
+
4494
+ // src/signer/SignerTron.ts
4495
+ var SignerTron = class {
4496
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4497
+ constructor(_sdk) {
4498
+ this._sdk = _sdk;
4499
+ }
4500
+ /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4501
+ async getAddress(derivationPath, options) {
4502
+ const action = this._sdk.getAddress(derivationPath, options);
4503
+ const result = await deviceActionToPromise(
4504
+ action,
4505
+ this.onInteraction,
4506
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4507
+ this.onRegisterCanceller
4508
+ );
4509
+ return { address: result.address, publicKey: result.publicKey };
3733
4510
  }
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;
4511
+ /** Sign a protobuf-encoded raw transaction. */
4512
+ async signTransaction(derivationPath, transaction, options) {
4513
+ const action = this._sdk.signTransaction(derivationPath, transaction, options);
4514
+ return deviceActionToPromise(
4515
+ action,
4516
+ this.onInteraction,
4517
+ INTERACTIVE_TIMEOUT_MS,
4518
+ this.onRegisterCanceller
4519
+ );
3746
4520
  }
3747
- async close() {
4521
+ /** Sign a personal message (TIP-191). */
4522
+ async signPersonalMessage(derivationPath, message, options) {
4523
+ const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4524
+ return deviceActionToPromise(
4525
+ action,
4526
+ this.onInteraction,
4527
+ INTERACTIVE_TIMEOUT_MS,
4528
+ this.onRegisterCanceller
4529
+ );
3748
4530
  }
3749
4531
  };
3750
4532
 
3751
4533
  // src/connector/chains/tron.ts
3752
4534
  async function tronGetAddress(ctx, sessionId, params) {
4535
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3753
4536
  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
- );
4537
+ return runSignerCall(ctx, sessionId, async () => {
4538
+ const result = await tronSigner.getAddress(path, {
4539
+ checkOnDevice: params.showOnDevice ?? false
4540
+ });
4541
+ return { address: result.address, publicKey: result.publicKey, path: params.path };
4542
+ });
3770
4543
  }
3771
4544
  async function tronSignTransaction(ctx, sessionId, params) {
3772
4545
  if (!params.rawTxHex) {
3773
4546
  throw Object.assign(
3774
4547
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
3775
- { code: HardwareErrorCode7.InvalidParams }
4548
+ { code: HardwareErrorCode6.InvalidParams }
3776
4549
  );
3777
4550
  }
4551
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3778
4552
  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
- );
4553
+ return runSignerCall(ctx, sessionId, async () => {
4554
+ const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
4555
+ return { signature: bytesToHex3(signature) };
4556
+ });
3793
4557
  }
3794
4558
  async function tronSignMessage(ctx, sessionId, params) {
4559
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3795
4560
  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
- );
4561
+ return runSignerCall(ctx, sessionId, async () => {
4562
+ const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
4563
+ return { signature: bytesToHex3(signature) };
4564
+ });
3806
4565
  }
3807
- async function _createTrx(ctx, sessionId) {
4566
+ async function _createTronSigner(ctx, sessionId) {
3808
4567
  const dmk = await ctx.getOrCreateDmk();
3809
- return new Trx(new DmkTransport(dmk, sessionId));
4568
+ const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4569
+ const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4570
+ return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3810
4571
  }
3811
4572
 
3812
4573
  // src/device-apps/customActions.ts
@@ -3985,7 +4746,7 @@ var DeviceApps = class {
3985
4746
  seTargetId: v.seTargetId,
3986
4747
  mcuTargetId: v.mcuTargetId,
3987
4748
  seVersion: v.seVersion,
3988
- seFlagsHex: bytesToHex2(v.seFlags),
4749
+ seFlagsHex: bytesToHex4(v.seFlags),
3989
4750
  mcuSephVersion: v.mcuSephVersion,
3990
4751
  mcuBootloaderVersion: v.mcuBootloaderVersion,
3991
4752
  hwVersion: v.hwVersion
@@ -4059,7 +4820,7 @@ var DeviceApps = class {
4059
4820
  }
4060
4821
  }
4061
4822
  };
4062
- function bytesToHex2(bytes) {
4823
+ function bytesToHex4(bytes) {
4063
4824
  if (!bytes) return "";
4064
4825
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4065
4826
  }
@@ -4102,10 +4863,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
4102
4863
  evm: "Ethereum",
4103
4864
  btc: "Bitcoin",
4104
4865
  sol: "Solana",
4105
- tron: "Tron"
4866
+ tron: "Tron",
4867
+ zcash: "Zcash"
4106
4868
  };
4107
4869
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4108
- Object.values(HardwareErrorCode8).filter((value) => typeof value === "number")
4870
+ Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4109
4871
  );
4110
4872
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4111
4873
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4142,6 +4904,10 @@ async function defaultLedgerKitImporter(pkg) {
4142
4904
  return import("@ledgerhq/device-signer-kit-bitcoin");
4143
4905
  case "@ledgerhq/device-signer-kit-solana":
4144
4906
  return import("@ledgerhq/device-signer-kit-solana");
4907
+ case "@ledgerhq/device-signer-kit-tron":
4908
+ return import("@ledgerhq/device-signer-kit-tron");
4909
+ case "@ledgerhq/device-signer-kit-zcash":
4910
+ return import("@ledgerhq/device-signer-kit-zcash");
4145
4911
  case "@ledgerhq/context-module":
4146
4912
  return import("@ledgerhq/context-module");
4147
4913
  default:
@@ -4201,6 +4967,7 @@ var LedgerConnectorBase = class {
4201
4967
  this._ctx = {
4202
4968
  emit: (event, data) => this._emit(event, data),
4203
4969
  invalidateSession: (sid) => this._invalidateSession(sid),
4970
+ teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4204
4971
  wrapError: (err, opts) => this._wrapError(err, opts),
4205
4972
  getOrCreateDmk: () => this._getOrCreateDmk(),
4206
4973
  getDeviceManager: () => this._getDeviceManager(),
@@ -4300,7 +5067,7 @@ var LedgerConnectorBase = class {
4300
5067
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
4301
5068
  );
4302
5069
  err._tag = ERROR_TAG.BlePairingTimeout;
4303
- err.code = HardwareErrorCode8.BlePairingTimeout;
5070
+ err.code = HardwareErrorCode7.BlePairingTimeout;
4304
5071
  reject(err);
4305
5072
  }, HANG_CEILING_MS);
4306
5073
  });
@@ -4333,7 +5100,7 @@ var LedgerConnectorBase = class {
4333
5100
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
4334
5101
  );
4335
5102
  err._tag = ERROR_TAG.DeviceNotAdvertising;
4336
- err.code = HardwareErrorCode8.DeviceNotFound;
5103
+ err.code = HardwareErrorCode7.DeviceNotFound;
4337
5104
  throw err;
4338
5105
  };
4339
5106
  const doConnect = async (path) => {
@@ -4390,14 +5157,14 @@ var LedgerConnectorBase = class {
4390
5157
  this._resetSignersAndSessions();
4391
5158
  if (isLedgerBleConnectionType(this.connectionType)) {
4392
5159
  const tag = err?._tag;
4393
- if (isKnownConnectionTag(tag)) {
5160
+ if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4394
5161
  throw err;
4395
5162
  }
4396
5163
  const wrapped = new Error(
4397
5164
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
4398
5165
  );
4399
5166
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
4400
- wrapped.code = HardwareErrorCode8.BlePairingTimeout;
5167
+ wrapped.code = HardwareErrorCode7.BlePairingTimeout;
4401
5168
  wrapped.originalError = err;
4402
5169
  throw wrapped;
4403
5170
  }
@@ -4475,7 +5242,7 @@ var LedgerConnectorBase = class {
4475
5242
  this._unwatchSessionState(sessionId);
4476
5243
  this._signerManager?.invalidate(sessionId);
4477
5244
  this._cancellers.get(sessionId)?.({
4478
- code: HardwareErrorCode8.DeviceDisconnected,
5245
+ code: HardwareErrorCode7.DeviceDisconnected,
4479
5246
  tag: "DeviceDisconnected",
4480
5247
  message: "Device disconnected"
4481
5248
  });
@@ -4491,7 +5258,7 @@ var LedgerConnectorBase = class {
4491
5258
  // whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
4492
5259
  // locally (see LedgerAdapter._unwrapConnectorResult).
4493
5260
  async call(sessionId, method, params) {
4494
- debugLog("[DMK] call:", method, JSON.stringify(params));
5261
+ debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
4495
5262
  try {
4496
5263
  const payload = await this._dispatch(sessionId, method, params);
4497
5264
  return { success: true, payload };
@@ -4501,7 +5268,7 @@ var LedgerConnectorBase = class {
4501
5268
  success: false,
4502
5269
  error: serializeConnectorError(
4503
5270
  Object.assign(new Error("Ledger app is unresponsive"), {
4504
- code: HardwareErrorCode8.DeviceAppStuck,
5271
+ code: HardwareErrorCode7.DeviceAppStuck,
4505
5272
  _tag: ERROR_TAG.DeviceAppStuck,
4506
5273
  originalError: err
4507
5274
  })
@@ -4513,7 +5280,7 @@ var LedgerConnectorBase = class {
4513
5280
  success: false,
4514
5281
  error: serializeConnectorError(
4515
5282
  Object.assign(new Error("Device communication interrupted, please retry"), {
4516
- code: HardwareErrorCode8.TransportError,
5283
+ code: HardwareErrorCode7.TransportError,
4517
5284
  _tag: ERROR_TAG.DeviceTransportStuck,
4518
5285
  originalError: err
4519
5286
  })
@@ -4559,6 +5326,11 @@ var LedgerConnectorBase = class {
4559
5326
  return solSignTransaction(ctx, sessionId, params);
4560
5327
  case "solSignMessage":
4561
5328
  return solSignMessage(ctx, sessionId, params);
5329
+ // ZCASH
5330
+ case "zcashGetFullViewingKey":
5331
+ return zcashGetFullViewingKey(ctx, sessionId, params);
5332
+ case "zcashGetShieldedAddress":
5333
+ return zcashGetShieldedAddress(ctx, sessionId, params);
4562
5334
  // TRON
4563
5335
  case "tronGetAddress":
4564
5336
  return tronGetAddress(ctx, sessionId, params);
@@ -4583,7 +5355,7 @@ var LedgerConnectorBase = class {
4583
5355
  try {
4584
5356
  return await apps.install(p.appName, ({ progress }) => {
4585
5357
  ctx.emit("ui-event", {
4586
- type: EConnectorInteraction4.AppInstallProgress,
5358
+ type: EConnectorInteraction3.AppInstallProgress,
4587
5359
  payload: {
4588
5360
  sessionId,
4589
5361
  appName: p.appName,
@@ -4592,7 +5364,7 @@ var LedgerConnectorBase = class {
4592
5364
  });
4593
5365
  });
4594
5366
  } catch (err) {
4595
- ctx.invalidateSession(sessionId);
5367
+ ctx.teardownSecureChannelSession(sessionId);
4596
5368
  throw ctx.wrapError(err);
4597
5369
  } finally {
4598
5370
  ctx.clearCanceller(sessionId);
@@ -4682,7 +5454,7 @@ var LedgerConnectorBase = class {
4682
5454
  );
4683
5455
  return { isGenuine: output.isGenuine, deviceId };
4684
5456
  } catch (err) {
4685
- ctx.invalidateSession(sessionId);
5457
+ ctx.teardownSecureChannelSession(sessionId);
4686
5458
  throw ctx.wrapError(err);
4687
5459
  } finally {
4688
5460
  ctx.clearCanceller(sessionId);
@@ -4804,6 +5576,17 @@ var LedgerConnectorBase = class {
4804
5576
  _invalidateSession(sessionId) {
4805
5577
  this._signerManager?.invalidate(sessionId);
4806
5578
  }
5579
+ _teardownSecureChannelSession(sessionId) {
5580
+ const cancel = this._cancellers.get(sessionId);
5581
+ this._cancellers.delete(sessionId);
5582
+ if (cancel) {
5583
+ try {
5584
+ cancel();
5585
+ } catch {
5586
+ }
5587
+ }
5588
+ this._invalidateSession(sessionId);
5589
+ }
4807
5590
  /**
4808
5591
  * Replace an old session with a new one after app switch.
4809
5592
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -4888,7 +5671,7 @@ var LedgerConnectorBase = class {
4888
5671
  * at every catch site. Falls through unchanged for unknown methods.
4889
5672
  */
4890
5673
  _ctxForMethod(method) {
4891
- const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5674
+ const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4892
5675
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
4893
5676
  if (!defaultAppName) return this._ctx;
4894
5677
  return {
@@ -4922,6 +5705,209 @@ var LedgerConnectorBase = class {
4922
5705
  return error;
4923
5706
  }
4924
5707
  };
5708
+
5709
+ // src/transport/DmkTransport.ts
5710
+ import Transport from "@ledgerhq/hw-transport";
5711
+ var DmkTransport = class extends Transport {
5712
+ constructor(dmk, sessionId) {
5713
+ super();
5714
+ this._dmk = dmk;
5715
+ this._sessionId = sessionId;
5716
+ }
5717
+ async exchange(apdu) {
5718
+ const response = await this._dmk.sendApdu({
5719
+ sessionId: this._sessionId,
5720
+ apdu: new Uint8Array(apdu)
5721
+ });
5722
+ const { data, statusCode } = response;
5723
+ const result = Buffer.alloc(data.length + 2);
5724
+ if (data.length > 0) {
5725
+ result.set(data, 0);
5726
+ }
5727
+ result.set(statusCode, data.length);
5728
+ return result;
5729
+ }
5730
+ async close() {
5731
+ }
5732
+ };
5733
+
5734
+ // src/app/AppManager.ts
5735
+ import {
5736
+ CloseAppCommand,
5737
+ GetAppAndVersionCommand,
5738
+ OpenAppCommand,
5739
+ isSuccessCommandResult
5740
+ } from "@ledgerhq/device-management-kit";
5741
+ import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
5742
+ var APP_NAME_MAP = {
5743
+ ETH: "Ethereum",
5744
+ BTC: "Bitcoin",
5745
+ SOL: "Solana",
5746
+ TRX: "Tron",
5747
+ ZEC: "Zcash",
5748
+ XRP: "XRP",
5749
+ ADA: "Cardano",
5750
+ DOT: "Polkadot",
5751
+ ATOM: "Cosmos"
5752
+ };
5753
+ var DASHBOARD_APP_NAME = "BOLOS";
5754
+ var AppManager = class {
5755
+ constructor(dmk, options) {
5756
+ this._dmk = dmk;
5757
+ this._waitMs = options?.waitMs ?? 1e3;
5758
+ this._maxRetries = options?.maxRetries ?? 10;
5759
+ }
5760
+ /**
5761
+ * Return the Ledger app name for a given chain ticker,
5762
+ * or undefined if the chain is not supported.
5763
+ */
5764
+ static getAppName(chain) {
5765
+ return APP_NAME_MAP[chain];
5766
+ }
5767
+ /**
5768
+ * Ensure the target app is open on the device identified by `sessionId`.
5769
+ *
5770
+ * Flow:
5771
+ * 1. Check the currently running app.
5772
+ * 2. If it is already the target, return immediately.
5773
+ * 3. If a different app is running (not dashboard), close it first.
5774
+ * 4. Open the target app.
5775
+ * 5. Poll until the device confirms the target app is running.
5776
+ */
5777
+ /**
5778
+ * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5779
+ * device is about to display "Open <app>" on screen and wait for the
5780
+ * user's button press. UI consumers should show their "open app" prompt
5781
+ * in response. NOT called when the target app is already open (no user
5782
+ * interaction needed in that case).
5783
+ *
5784
+ * Important: OpenAppCommand is blocking. It does not resolve until the user
5785
+ * has physically confirmed on the device, so anything that runs AFTER
5786
+ * `await this._openApp(...)` lands AFTER the prompt is already gone.
5787
+ * Hence the callback must fire BEFORE that await.
5788
+ */
5789
+ async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5790
+ const currentApp = await this._getCurrentApp(sessionId);
5791
+ if (currentApp === targetAppName) {
5792
+ return;
5793
+ }
5794
+ if (!this._isDashboard(currentApp)) {
5795
+ await this._closeCurrentApp(sessionId);
5796
+ await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5797
+ }
5798
+ onConfirmOnDevice?.();
5799
+ await this._openApp(sessionId, targetAppName);
5800
+ await this._waitForApp(sessionId, targetAppName);
5801
+ }
5802
+ // ---------------------------------------------------------------------------
5803
+ // Private helpers
5804
+ // ---------------------------------------------------------------------------
5805
+ async _getCurrentApp(sessionId) {
5806
+ const result = await this._dmk.sendCommand({
5807
+ sessionId,
5808
+ command: new GetAppAndVersionCommand()
5809
+ });
5810
+ if (isSuccessCommandResult(result)) {
5811
+ debugLog("[AppManager] currentApp:", result.data.name);
5812
+ return result.data.name;
5813
+ }
5814
+ const errResult = result;
5815
+ const dmkErr = errResult.error ?? {};
5816
+ const original = dmkErr.originalError;
5817
+ debugLog(
5818
+ "[AppManager] _getCurrentApp failed sessionId=",
5819
+ sessionId,
5820
+ "tag=",
5821
+ dmkErr._tag,
5822
+ "errorCode=",
5823
+ dmkErr.errorCode,
5824
+ "message=",
5825
+ dmkErr.message,
5826
+ "originalErrorMessage=",
5827
+ original?.message ?? String(original ?? "")
5828
+ );
5829
+ throw Object.assign(
5830
+ new Error(
5831
+ dmkErr.message ?? "Failed to get current app from device"
5832
+ ),
5833
+ {
5834
+ _tag: dmkErr._tag,
5835
+ errorCode: dmkErr.errorCode,
5836
+ originalError: original
5837
+ }
5838
+ );
5839
+ }
5840
+ async _openApp(sessionId, appName) {
5841
+ const result = await this._dmk.sendCommand({
5842
+ sessionId,
5843
+ command: new OpenAppCommand({ appName })
5844
+ });
5845
+ if (!isSuccessCommandResult(result)) {
5846
+ const dmkErr = result.error;
5847
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5848
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5849
+ debugLog(
5850
+ "[AppManager] openApp failed:",
5851
+ appName,
5852
+ "errorCode:",
5853
+ errorCode,
5854
+ "tag:",
5855
+ dmkErr._tag
5856
+ );
5857
+ let code;
5858
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
5859
+ code = HardwareErrorCode8.AppNotInstalled;
5860
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5861
+ code = HardwareErrorCode8.UserRejected;
5862
+ }
5863
+ throw Object.assign(new Error(`Failed to open "${appName}"`), {
5864
+ _tag: ERROR_TAG.OpenAppCommand,
5865
+ code,
5866
+ errorCode,
5867
+ statusCode: errorCode,
5868
+ appName,
5869
+ originalError: dmkErr
5870
+ });
5871
+ }
5872
+ }
5873
+ async _closeCurrentApp(sessionId) {
5874
+ debugLog("[AppManager] closeCurrentApp");
5875
+ await this._dmk.sendCommand({
5876
+ sessionId,
5877
+ command: new CloseAppCommand()
5878
+ });
5879
+ }
5880
+ /**
5881
+ * Poll the device until the expected app is reported as running,
5882
+ * or throw after `_maxRetries` attempts.
5883
+ */
5884
+ async _waitForApp(sessionId, expectedAppName) {
5885
+ let lastSeen = "";
5886
+ for (let i = 0; i < this._maxRetries; i++) {
5887
+ await this._wait();
5888
+ const current = await this._getCurrentApp(sessionId);
5889
+ lastSeen = current;
5890
+ if (current === expectedAppName) {
5891
+ return;
5892
+ }
5893
+ }
5894
+ debugLog(
5895
+ "[AppManager] waitForApp exhausted: expected=",
5896
+ expectedAppName,
5897
+ "lastSeen=",
5898
+ lastSeen
5899
+ );
5900
+ throw new Error(
5901
+ `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
5902
+ );
5903
+ }
5904
+ _isDashboard(appName) {
5905
+ return appName === DASHBOARD_APP_NAME;
5906
+ }
5907
+ _wait() {
5908
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
5909
+ }
5910
+ };
4925
5911
  export {
4926
5912
  AppManager,
4927
5913
  DmkTransport,
@@ -4932,6 +5918,7 @@ export {
4932
5918
  SignerEth,
4933
5919
  SignerManager,
4934
5920
  SignerSol,
5921
+ SignerZcash,
4935
5922
  debugLog,
4936
5923
  deviceActionToPromise,
4937
5924
  isDeviceLockedError,