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

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" && !this._bareCallMayUseConnection(operation)) {
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,84 @@ 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 || this._bareCallMayUseConnection(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
+ /**
1500
+ * A running call by bare connectId (or still resolving its device by identity) may be on this
1501
+ * connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
1502
+ * caller like any bare call's session. A lost connection is torn down regardless.
1503
+ */
1504
+ _bareCallMayUseConnection(operation) {
1505
+ const activeKey = this._jobQueue.getActiveJob()?.deviceId;
1506
+ return activeKey !== void 0 && !isHardwareOperationId(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
1507
+ }
1508
+ async _releaseOperationConnection(operation) {
1509
+ const sessionIds = /* @__PURE__ */ new Set();
1510
+ for (const [connectId, sessionId] of this._sessions) {
1511
+ if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1512
+ this._sessions.delete(connectId);
1513
+ sessionIds.add(sessionId);
1514
+ }
1515
+ }
1516
+ for (const sessionId of sessionIds) {
1517
+ await this._runConnectorTeardown(
1518
+ () => this.connector.disconnect(sessionId).catch(() => void 0)
1519
+ );
1520
+ }
1521
+ }
1522
+ async _releaseLostOperationConnection(operationId) {
1523
+ const endedOperation = this._operations.end(operationId, "disconnect");
1524
+ if (!endedOperation) return;
1525
+ this._discoveredDevices.delete(endedOperation.connectId);
1526
+ await this._releaseOperationConnection(endedOperation);
1527
+ }
1528
+ async getDeviceInfo(connectIdOrOperationId, deviceId) {
1529
+ let connectId;
1530
+ try {
1531
+ connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1532
+ } catch (error) {
1533
+ return this.errorToFailure(error);
1534
+ }
982
1535
  debugLog("[LedgerAdapter][REQ]", {
983
1536
  method: "getDeviceInfo",
984
1537
  connectId,
@@ -988,7 +1541,7 @@ var _LedgerAdapter = class _LedgerAdapter {
988
1541
  await this._ensureDevicePermission(connectId, deviceId);
989
1542
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
990
1543
  if (cached) {
991
- const result = success(cached);
1544
+ const result = success2(cached);
992
1545
  debugLog("[LedgerAdapter][RES]", {
993
1546
  method: "getDeviceInfo",
994
1547
  success: true,
@@ -1013,11 +1566,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1013
1566
  success: false,
1014
1567
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1015
1568
  });
1016
- throw err;
1569
+ return this.errorToFailure(err);
1017
1570
  }
1018
1571
  }
1019
- getSupportedChains() {
1020
- return ["evm", "btc", "sol", "tron"];
1572
+ /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1573
+ async _dropUncheckedBundlePick(context, signal) {
1574
+ const { connection } = context;
1575
+ const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1576
+ if (!connection || !owner) return;
1577
+ this._pendingPickBindings.delete(connection.connectId);
1578
+ this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1579
+ if (this._sessions.get(connection.connectId) === connection.sessionId) {
1580
+ await this._dropSession(connection.connectId, signal);
1581
+ }
1021
1582
  }
1022
1583
  // ---------------------------------------------------------------------------
1023
1584
  // Chain call helper
@@ -1037,7 +1598,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1037
1598
  commonParams,
1038
1599
  installContext
1039
1600
  );
1040
- return success(result);
1601
+ return success2(result);
1041
1602
  } catch (err) {
1042
1603
  return this.errorToFailure(err);
1043
1604
  }
@@ -1053,13 +1614,25 @@ var _LedgerAdapter = class _LedgerAdapter {
1053
1614
  if (params && typeof params === "object") {
1054
1615
  const {
1055
1616
  autoInstallApp,
1617
+ operationId,
1056
1618
  passphraseState: _passphraseState,
1057
1619
  useEmptyPassphrase: _useEmptyPassphrase,
1620
+ knownConnections,
1621
+ extra,
1622
+ allowDeviceSelection,
1623
+ supportedTransports,
1058
1624
  ...rest
1059
1625
  } = params;
1060
1626
  return {
1061
1627
  commonParams: {
1062
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1628
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1629
+ operationId: typeof operationId === "string" ? operationId : void 0,
1630
+ ...pickConnectionContext({
1631
+ knownConnections,
1632
+ extra,
1633
+ allowDeviceSelection,
1634
+ supportedTransports
1635
+ })
1063
1636
  },
1064
1637
  rest
1065
1638
  };
@@ -1235,14 +1808,33 @@ var _LedgerAdapter = class _LedgerAdapter {
1235
1808
  );
1236
1809
  }
1237
1810
  // ---------------------------------------------------------------------------
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.
1811
+ // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1812
+ // ---------------------------------------------------------------------------
1813
+ zcashGetFullViewingKey(connectId, deviceId, params) {
1814
+ return this.callChainWithMergedParams(
1815
+ connectId,
1816
+ deviceId,
1817
+ "zcash",
1818
+ "zcashGetFullViewingKey",
1819
+ params
1820
+ );
1821
+ }
1822
+ zcashGetShieldedAddress(connectId, deviceId, params) {
1823
+ return this.callChainWithMergedParams(
1824
+ connectId,
1825
+ deviceId,
1826
+ "zcash",
1827
+ "zcashGetShieldedAddress",
1828
+ params
1829
+ );
1830
+ }
1831
+ // ---------------------------------------------------------------------------
1832
+ // App management: OS-level app install/list, no fingerprint or chain dispatch.
1241
1833
  // ---------------------------------------------------------------------------
1242
1834
  async installApp(connectId, appName) {
1243
1835
  try {
1244
1836
  await this.connectorCall(connectId, "installApp", { appName });
1245
- return success(void 0);
1837
+ return success2(void 0);
1246
1838
  } catch (err) {
1247
1839
  return this.errorToFailure(err);
1248
1840
  }
@@ -1250,7 +1842,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1250
1842
  async listInstalledApps(connectId) {
1251
1843
  try {
1252
1844
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1253
- return success(result);
1845
+ return success2(result);
1254
1846
  } catch (err) {
1255
1847
  return this.errorToFailure(err);
1256
1848
  }
@@ -1259,7 +1851,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1259
1851
  async listInstalledNames(connectId) {
1260
1852
  try {
1261
1853
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1262
- return success(result);
1854
+ return success2(result);
1263
1855
  } catch (err) {
1264
1856
  return this.errorToFailure(err);
1265
1857
  }
@@ -1267,7 +1859,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1267
1859
  async listAvailableApps(connectId) {
1268
1860
  try {
1269
1861
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1270
- return success(result);
1862
+ return success2(result);
1271
1863
  } catch (err) {
1272
1864
  return this.errorToFailure(err);
1273
1865
  }
@@ -1275,7 +1867,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1275
1867
  async getLedgerFirmwareVersion(connectId) {
1276
1868
  try {
1277
1869
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1278
- return success(result);
1870
+ return success2(result);
1279
1871
  } catch (err) {
1280
1872
  return this.errorToFailure(err);
1281
1873
  }
@@ -1283,7 +1875,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1283
1875
  async getLedgerDeviceInfo(connectId) {
1284
1876
  try {
1285
1877
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1286
- return success(result);
1878
+ return success2(result);
1287
1879
  } catch (err) {
1288
1880
  return this.errorToFailure(err);
1289
1881
  }
@@ -1323,11 +1915,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1323
1915
  );
1324
1916
  }
1325
1917
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1326
- this.resetState();
1918
+ await this._resetStateAndDisconnectSessions();
1327
1919
  }
1328
1920
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1329
1921
  if (!result.isGenuine) {
1330
- return success({
1922
+ return success2({
1331
1923
  vendor: "ledger",
1332
1924
  verified: false
1333
1925
  });
@@ -1338,7 +1930,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1338
1930
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1339
1931
  );
1340
1932
  }
1341
- return success({
1933
+ return success2({
1342
1934
  vendor: "ledger",
1343
1935
  verified: result.isGenuine,
1344
1936
  deviceId: result.deviceId
@@ -1349,10 +1941,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1349
1941
  if (relayUrl) {
1350
1942
  try {
1351
1943
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1352
- this.resetState();
1944
+ await this._resetStateAndDisconnectSessions();
1353
1945
  } catch {
1354
1946
  this.connector.reset();
1355
- this.resetState();
1947
+ await this._resetStateAndDisconnectSessions();
1356
1948
  }
1357
1949
  }
1358
1950
  }
@@ -1364,6 +1956,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1364
1956
  this.emitter.off(event, listener);
1365
1957
  }
1366
1958
  cancel(connectId) {
1959
+ const namedOperationIsLive = (id) => {
1960
+ try {
1961
+ this._operations.resolve(id);
1962
+ return true;
1963
+ } catch {
1964
+ return false;
1965
+ }
1966
+ };
1967
+ if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
1968
+ debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
1969
+ connectId
1970
+ });
1971
+ return;
1972
+ }
1367
1973
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1368
1974
  code: HardwareErrorCode3.UserAborted,
1369
1975
  _tag: ERROR_TAG.UserAborted
@@ -1374,60 +1980,143 @@ var _LedgerAdapter = class _LedgerAdapter {
1374
1980
  this._lastCancelReason = void 0;
1375
1981
  }
1376
1982
  }, 2e3);
1377
- this._uiRegistry.cancel();
1378
- if (connectId) {
1379
- this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1983
+ const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
1984
+ let operationId;
1985
+ if (isHardwareOperationId(connectId)) {
1986
+ operationId = connectId;
1987
+ } else if (!connectId && isHardwareOperationId(activeJobId)) {
1988
+ operationId = activeJobId;
1989
+ }
1990
+ let resolvedConnectId = connectId;
1991
+ if (operationId) {
1992
+ try {
1993
+ resolvedConnectId = this._operations.resolve(operationId).connectId;
1994
+ } catch {
1995
+ resolvedConnectId = void 0;
1996
+ }
1997
+ }
1998
+ const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1999
+ const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
2000
+ if (!connectId) {
2001
+ this._uiRegistry.cancel();
2002
+ } else if (pendingOperationId) {
2003
+ this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
2004
+ }
2005
+ this._finishBleBinding("cancelled");
2006
+ if (!connectId) this._pendingOperationBindings.clear();
2007
+ else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
2008
+ const queueKeys = /* @__PURE__ */ new Set();
2009
+ if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
2010
+ if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
2011
+ if (queueKeys.size) {
2012
+ let cancelledAnyJob = false;
2013
+ for (const key of queueKeys) {
2014
+ cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
2015
+ }
2016
+ debugLog("[LedgerAdapter] cancel routed to queue keys", {
2017
+ queueKeys: [...queueKeys],
2018
+ cancelledAnyJob
2019
+ });
1380
2020
  } else {
1381
2021
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1382
2022
  }
1383
- if (connectId) {
1384
- const sessionId = this._sessions.get(connectId) ?? connectId;
2023
+ if (resolvedConnectId) {
2024
+ const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1385
2025
  void this.connector.cancel(sessionId);
1386
2026
  } else {
1387
2027
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
1388
2028
  }
1389
- if (this._connectingPromise) {
2029
+ const connectingConnectId = this._connectingConnectId;
2030
+ const targetKeys = new Set(
2031
+ [
2032
+ connectId,
2033
+ resolvedConnectId,
2034
+ ...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
2035
+ ].filter(Boolean)
2036
+ );
2037
+ const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
2038
+ if (this._connectingPromise && ownsPendingConnect) {
1390
2039
  this._doConnectAbortController?.abort(userAbortReason);
1391
2040
  }
2041
+ if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
1392
2042
  }
1393
2043
  // ---------------------------------------------------------------------------
1394
2044
  // Chain fingerprint
1395
2045
  // ---------------------------------------------------------------------------
2046
+ /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
1396
2047
  async getChainFingerprint(connectId, deviceId, chain) {
1397
2048
  try {
1398
2049
  const fingerprint = await this._computeChainFingerprint(
1399
2050
  chain,
1400
2051
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
1401
2052
  );
1402
- return success(fingerprint);
2053
+ if (deviceId) {
2054
+ if (fingerprint !== deviceId) {
2055
+ return failure2(
2056
+ HardwareErrorCode3.DeviceMismatch,
2057
+ formatDeviceMismatchError(deviceId, fingerprint)
2058
+ );
2059
+ }
2060
+ }
2061
+ return success2(fingerprint);
1403
2062
  } catch (err) {
1404
2063
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
1405
2064
  return this.errorToFailure(err);
1406
2065
  }
1407
2066
  }
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 };
2067
+ /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2068
+ async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
1414
2069
  try {
1415
- const fingerprint = await this._computeChainFingerprint(
1416
- chain,
1417
- (method, params) => this._callConnector(sessionId, method, params)
2070
+ const outcome = await requestSaveDeviceBinding(
2071
+ this.emitter,
2072
+ this._uiRegistry,
2073
+ {
2074
+ selectionRequestId,
2075
+ connection: { transport: "ble", connectId },
2076
+ ...identity ? { identity } : {},
2077
+ extra: context?.extra,
2078
+ operationId
2079
+ },
2080
+ signal
1418
2081
  );
1419
- if (fingerprint === deviceId) {
1420
- return { success: true };
2082
+ if (context) context.bindingSaved = outcome.saved;
2083
+ if (!outcome.saved) {
2084
+ debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2085
+ connectId,
2086
+ reason: outcome.reason
2087
+ });
1421
2088
  }
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 };
2089
+ } catch (error) {
2090
+ await this._dropSession(connectId, signal);
2091
+ throw error;
2092
+ } finally {
2093
+ if (this._bindingSelectionRequestId === selectionRequestId) {
2094
+ this._bindingSelectionRequestId = void 0;
1427
2095
  }
1428
- throw err;
1429
2096
  }
1430
2097
  }
2098
+ async _dropSession(connectId, signal) {
2099
+ const sessionId = this._sessions.get(connectId);
2100
+ this._sessions.delete(connectId);
2101
+ if (!sessionId) return;
2102
+ this._sessionTransports.delete(sessionId);
2103
+ const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2104
+ () => void 0
2105
+ );
2106
+ if (!signal.aborted) await teardown;
2107
+ }
2108
+ /** Verify on the acquired session without re-entering the job queue. */
2109
+ async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2110
+ if (!deviceId) return { success: true };
2111
+ const fingerprint = await this._computeChainFingerprint(
2112
+ chain,
2113
+ (method, params) => this._callConnector(sessionId, method, params)
2114
+ );
2115
+ if (fingerprint === deviceId) {
2116
+ return { success: true };
2117
+ }
2118
+ return { success: false, expected: deviceId, actual: fingerprint };
2119
+ }
1431
2120
  /**
1432
2121
  * Compute the chain fingerprint via a caller-supplied call strategy.
1433
2122
  *
@@ -1455,11 +2144,20 @@ var _LedgerAdapter = class _LedgerAdapter {
1455
2144
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
1456
2145
  } else if (chain === "tron") {
1457
2146
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2147
+ } else if (chain === "zcash") {
2148
+ address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
1458
2149
  } else {
1459
2150
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
1460
2151
  }
1461
2152
  return deriveDeviceFingerprint(address);
1462
2153
  }
2154
+ /**
2155
+ * Operation owning the running job, so a mid-call UI request can name it.
2156
+ * Undefined at cold start when no operation owns the job.
2157
+ */
2158
+ _activeOperationId() {
2159
+ return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2160
+ }
1463
2161
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
1464
2162
  // The user must press Confirm after unlocking, which triggers a search retry.
1465
2163
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -1469,15 +2167,18 @@ var _LedgerAdapter = class _LedgerAdapter {
1469
2167
  if (signal?.aborted) {
1470
2168
  _LedgerAdapter._throwIfAborted(signal);
1471
2169
  }
2170
+ const operationId = this._activeOperationId();
1472
2171
  const waitPromise = this._uiRegistry.wait(
1473
- UI_REQUEST.REQUEST_DEVICE_CONNECT
2172
+ UI_REQUEST.REQUEST_DEVICE_CONNECT,
2173
+ { operationId }
1474
2174
  );
1475
2175
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
1476
2176
  type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
1477
2177
  payload: {
1478
2178
  vendor: "ledger",
1479
2179
  reason: "device-not-found",
1480
- message: "Please connect and unlock your Ledger device"
2180
+ message: "Please connect and unlock your Ledger device",
2181
+ operationId
1481
2182
  }
1482
2183
  });
1483
2184
  let payload;
@@ -1523,7 +2224,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1523
2224
  * Returns the params to pass through (with `showOnDevice` possibly
1524
2225
  * promoted), or `null` if the user declined.
1525
2226
  */
1526
- async _gateBtcHighIndex(params) {
2227
+ async _gateBtcHighIndex(params, signal) {
1527
2228
  const accountIndex = btcAccountIndexFromPath(params.path);
1528
2229
  if (params.showOnDevice) return params;
1529
2230
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -1532,25 +2233,32 @@ var _LedgerAdapter = class _LedgerAdapter {
1532
2233
  if (this._btcHighIndexConfirmedThisSession) {
1533
2234
  return { ...params, showOnDevice: true };
1534
2235
  }
1535
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2236
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1536
2237
  if (!confirmed) return null;
1537
2238
  this._btcHighIndexConfirmedThisSession = true;
1538
2239
  return { ...params, showOnDevice: true };
1539
2240
  }
1540
- async _waitForBtcHighIndexConfirm(path, accountIndex) {
2241
+ async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2242
+ const operationId = this._activeOperationId();
1541
2243
  const waitPromise = this._uiRegistry.wait(
1542
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2244
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2245
+ { operationId }
1543
2246
  );
1544
2247
  this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
1545
2248
  type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
1546
2249
  payload: {
1547
2250
  vendor: "ledger",
1548
2251
  path,
1549
- accountIndex
2252
+ accountIndex,
2253
+ operationId
1550
2254
  }
1551
2255
  });
1552
2256
  try {
1553
- const payload = await waitPromise;
2257
+ const payload = await this._awaitUiAnswer(
2258
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2259
+ waitPromise,
2260
+ signal
2261
+ );
1554
2262
  return !!payload?.confirmed;
1555
2263
  } catch (err) {
1556
2264
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1560,18 +2268,35 @@ var _LedgerAdapter = class _LedgerAdapter {
1560
2268
  return false;
1561
2269
  }
1562
2270
  }
2271
+ /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2272
+ async _awaitUiAnswer(requestType, waitPromise, signal) {
2273
+ const onAbort = () => this._uiRegistry.cancel(requestType);
2274
+ if (signal.aborted) onAbort();
2275
+ signal.addEventListener("abort", onAbort, { once: true });
2276
+ try {
2277
+ return await waitPromise;
2278
+ } finally {
2279
+ signal.removeEventListener("abort", onAbort);
2280
+ }
2281
+ }
1563
2282
  // Ask the user whether to install a missing app (autoInstallApp flow).
1564
2283
  // Same register-then-emit ordering as the BTC high-index gate.
1565
- async _waitForInstallAppConfirm(appName) {
2284
+ async _waitForInstallAppConfirm(appName, signal) {
2285
+ const operationId = this._activeOperationId();
1566
2286
  const waitPromise = this._uiRegistry.wait(
1567
- UI_REQUEST.REQUEST_INSTALL_APP
2287
+ UI_REQUEST.REQUEST_INSTALL_APP,
2288
+ { operationId }
1568
2289
  );
1569
2290
  this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
1570
2291
  type: UI_REQUEST.REQUEST_INSTALL_APP,
1571
- payload: { vendor: "ledger", appName }
2292
+ payload: { vendor: "ledger", appName, operationId }
1572
2293
  });
1573
2294
  try {
1574
- const payload = await waitPromise;
2295
+ const payload = await this._awaitUiAnswer(
2296
+ UI_REQUEST.REQUEST_INSTALL_APP,
2297
+ waitPromise,
2298
+ signal
2299
+ );
1575
2300
  return !!payload?.confirmed;
1576
2301
  } catch (err) {
1577
2302
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -1584,16 +2309,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1584
2309
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
1585
2310
  // `_doConnect` runs under its own internal controller so caller A's cancel
1586
2311
  // doesn't kill caller B's await.
1587
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2312
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1588
2313
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
1589
- if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2314
+ this._assertConnectorReady("connectDevice");
2315
+ if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1590
2316
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1591
2317
  code: HardwareErrorCode3.DeviceNotFound
1592
2318
  });
1593
2319
  }
1594
2320
  if (connectId && this._sessions.has(connectId)) return connectId;
1595
2321
  if (!connectId && this._sessions.size > 0) {
1596
- if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2322
+ if (!this._isBleConnection() && this._sessions.size > 1) {
1597
2323
  throw Object.assign(
1598
2324
  new Error(
1599
2325
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -1603,15 +2329,24 @@ var _LedgerAdapter = class _LedgerAdapter {
1603
2329
  }
1604
2330
  return this._sessions.keys().next().value;
1605
2331
  }
1606
- if (!this._connectingPromise) {
1607
- this._doConnectAbortController = new AbortController();
1608
- const innerSignal = this._doConnectAbortController.signal;
2332
+ if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2333
+ const controller = new AbortController();
2334
+ this._doConnectAbortController = controller;
2335
+ const innerSignal = controller.signal;
1609
2336
  this._connectingPromise = (async () => {
1610
2337
  try {
1611
- return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2338
+ return await this._doConnect(
2339
+ innerSignal,
2340
+ connectId,
2341
+ allowUsbEphemeralFallback,
2342
+ preserveOperationId,
2343
+ context
2344
+ );
1612
2345
  } finally {
1613
- this._connectingPromise = null;
1614
- this._doConnectAbortController = null;
2346
+ if (this._doConnectAbortController === controller) {
2347
+ this._connectingPromise = null;
2348
+ this._doConnectAbortController = null;
2349
+ }
1615
2350
  }
1616
2351
  })();
1617
2352
  }
@@ -1620,22 +2355,57 @@ var _LedgerAdapter = class _LedgerAdapter {
1620
2355
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
1621
2356
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
1622
2357
  // 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
- }
2358
+ async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2359
+ _LedgerAdapter._throwIfAborted(internalSignal);
2360
+ if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2361
+ this._activeConnectionType = "usb";
2362
+ const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2363
+ _LedgerAdapter._throwIfAborted(internalSignal);
2364
+ const knownUsb = context?.knownConnections?.find(
2365
+ (connection) => connection.transport === "usb"
2366
+ );
2367
+ const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2368
+ if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2369
+ return this._connectFirstOrSelect(
2370
+ usbDevices,
2371
+ usbTarget,
2372
+ allowUsbEphemeralFallback,
2373
+ preserveOperationId,
2374
+ context,
2375
+ internalSignal
2376
+ );
2377
+ }
2378
+ if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2379
+ throw createHwkError({
2380
+ code: HardwareErrorCode3.DeviceNotFound,
2381
+ message: "This Ledger model has no Bluetooth transport; connect it over USB"
2382
+ });
2383
+ }
2384
+ this._activeConnectionType = "ble";
2385
+ const knownBle = context?.knownConnections?.find(
2386
+ (connection) => connection.transport === "ble"
2387
+ );
2388
+ if (knownBle?.transport === "ble") {
2389
+ return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
1638
2390
  }
2391
+ if (targetConnectId && context?.knownConnections === void 0) {
2392
+ throw createHwkError({
2393
+ code: HardwareErrorCode3.DeviceNotFound,
2394
+ message: "Ledger connection metadata is required before starting Bluetooth binding"
2395
+ });
2396
+ }
2397
+ const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2398
+ return this._connectFirstOrSelect(
2399
+ bleDevices,
2400
+ void 0,
2401
+ allowUsbEphemeralFallback,
2402
+ preserveOperationId,
2403
+ context,
2404
+ internalSignal
2405
+ );
2406
+ }
2407
+ if (this._isBleConnection() && targetConnectId) {
2408
+ return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
1639
2409
  }
1640
2410
  let confirms = 0;
1641
2411
  while (!internalSignal.aborted) {
@@ -1643,22 +2413,28 @@ var _LedgerAdapter = class _LedgerAdapter {
1643
2413
  type: EConnectorInteraction.Searching,
1644
2414
  payload: { sessionId: "" }
1645
2415
  });
1646
- let devices = await this.searchDevices();
2416
+ let devices = await this._searchDevices(void 0, internalSignal);
2417
+ _LedgerAdapter._throwIfAborted(internalSignal);
1647
2418
  if (devices.length === 0) {
1648
2419
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
1649
2420
  await new Promise((resolve) => {
1650
2421
  setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
1651
2422
  });
1652
- devices = await this.searchDevices();
2423
+ _LedgerAdapter._throwIfAborted(internalSignal);
2424
+ devices = await this._searchDevices(void 0, internalSignal);
2425
+ _LedgerAdapter._throwIfAborted(internalSignal);
1653
2426
  if (devices.length > 0) break;
1654
2427
  }
1655
2428
  }
1656
- if (devices.length > 0) {
2429
+ if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1657
2430
  try {
1658
2431
  return await this._connectFirstOrSelect(
1659
2432
  devices,
1660
2433
  targetConnectId,
1661
- allowUsbEphemeralFallback
2434
+ allowUsbEphemeralFallback,
2435
+ preserveOperationId,
2436
+ context,
2437
+ internalSignal
1662
2438
  );
1663
2439
  } catch (err) {
1664
2440
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -1687,45 +2463,147 @@ var _LedgerAdapter = class _LedgerAdapter {
1687
2463
  _LedgerAdapter._throwIfAborted(internalSignal);
1688
2464
  throw new Error("_doConnect aborted");
1689
2465
  }
1690
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2466
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2467
+ _LedgerAdapter._throwIfAborted(signal);
1691
2468
  if (targetConnectId) {
1692
2469
  const target = devices.find(
1693
2470
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
1694
2471
  );
1695
2472
  if (target) {
1696
- return this._connectDeviceOrThrow(target.connectId);
2473
+ return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1697
2474
  }
1698
- if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2475
+ if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1699
2476
  debugLog(
1700
2477
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
1701
2478
  );
1702
- return this._connectDeviceOrThrow(devices[0].connectId);
2479
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1703
2480
  }
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;
2481
+ if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2482
+ const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2483
+ code: HardwareErrorCode3.DeviceNotFound
2484
+ });
2485
+ if (this._isBleConnection()) {
2486
+ err._tag = ERROR_TAG.DeviceNotAdvertising;
2487
+ }
2488
+ throw err;
1709
2489
  }
1710
- throw err;
1711
2490
  }
1712
- if (isLedgerBleConnectionType(this.connector.connectionType)) {
2491
+ const requiresBleSelection = this._isBleConnection();
2492
+ if (requiresBleSelection && !allowUsbEphemeralFallback) {
1713
2493
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1714
2494
  code: HardwareErrorCode3.DeviceNotFound
1715
2495
  });
1716
2496
  }
1717
- if (devices.length > 1) {
1718
- throw createMultipleUsbLedgerDevicesError();
2497
+ if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2498
+ const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2499
+ if (context) context.bindingSessionId = bindingSessionId;
2500
+ const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2501
+ const knownUsb = context?.knownConnections?.find(
2502
+ (connection) => connection.transport === "usb"
2503
+ );
2504
+ const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2505
+ const { device, requestId } = await requestBleDeviceSelection({
2506
+ emitter: this.emitter,
2507
+ registry: this._uiRegistry,
2508
+ signal,
2509
+ allowUsbFallback,
2510
+ scan: async () => {
2511
+ if (allowUsbFallback) {
2512
+ const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2513
+ const candidate = usbDevices.find(
2514
+ (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2515
+ ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2516
+ if (candidate) return [candidate];
2517
+ }
2518
+ return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2519
+ },
2520
+ request: {
2521
+ devices,
2522
+ bindingSessionId,
2523
+ context: {
2524
+ kind: "bind-connection",
2525
+ transport: "ble",
2526
+ reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2527
+ },
2528
+ extra: context?.extra,
2529
+ operationId: preserveOperationId
2530
+ }
2531
+ });
2532
+ if (device.connectionType === "usb") {
2533
+ this._activeConnectionType = "usb";
2534
+ if (context) context.selectedConnection = void 0;
2535
+ this._bindingSelectionRequestId = requestId;
2536
+ this._finishBleBinding("cancelled");
2537
+ return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2538
+ }
2539
+ this._bindingSelectionRequestId = requestId;
2540
+ const connected = await this._connectDeviceOrThrow(
2541
+ device.connectId,
2542
+ preserveOperationId,
2543
+ signal
2544
+ );
2545
+ if (context) context.selectedConnection = { connectId: connected, requestId };
2546
+ if (context?.deferBindingSave) {
2547
+ context.pendingBinding = { connectId: connected, requestId };
2548
+ } else {
2549
+ await this._saveSelectedBleBinding(
2550
+ connected,
2551
+ requestId,
2552
+ context,
2553
+ preserveOperationId,
2554
+ signal
2555
+ );
2556
+ }
2557
+ return connected;
2558
+ }
2559
+ if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2560
+ if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2561
+ throw createHwkError({
2562
+ code: HardwareErrorCode3.DeviceNotFound,
2563
+ message: "Select a Ledger device before continuing"
2564
+ });
2565
+ }
2566
+ const requestId = this._uiRegistry.createRequestId();
2567
+ const operationId = this._activeOperationId();
2568
+ const waitPromise = this._uiRegistry.wait(
2569
+ UI_REQUEST.REQUEST_SELECT_DEVICE,
2570
+ { requestId, operationId }
2571
+ );
2572
+ this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
2573
+ type: UI_REQUEST.REQUEST_SELECT_DEVICE,
2574
+ payload: {
2575
+ devices,
2576
+ requestId,
2577
+ operationId,
2578
+ context: requiresBleSelection ? {
2579
+ kind: "bind-connection",
2580
+ transport: "ble",
2581
+ reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2582
+ } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2583
+ extra: context?.extra
2584
+ }
2585
+ });
2586
+ const { sdkConnectId } = await this._abortable(signal, waitPromise);
2587
+ _LedgerAdapter._throwIfAborted(signal);
2588
+ const selected = devices.find((device) => device.connectId === sdkConnectId);
2589
+ if (!selected) {
2590
+ throw Object.assign(new Error("Selected Ledger is no longer available"), {
2591
+ code: HardwareErrorCode3.DeviceNotFound
2592
+ });
2593
+ }
2594
+ if (context && requiresBleSelection)
2595
+ context.selectedConnection = { connectId: selected.connectId, requestId };
2596
+ return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1719
2597
  }
1720
2598
  if (devices.length !== 1) {
1721
2599
  throw Object.assign(new Error("Ledger device not found."), {
1722
2600
  code: HardwareErrorCode3.DeviceNotFound
1723
2601
  });
1724
2602
  }
1725
- return this._connectDeviceOrThrow(devices[0].connectId);
2603
+ return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1726
2604
  }
1727
- async _connectDeviceOrThrow(chosenConnectId) {
1728
- const result = await this.connectDevice(chosenConnectId);
2605
+ async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2606
+ const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1729
2607
  if (!result.success) {
1730
2608
  const payload = result.payload;
1731
2609
  const rethrow = Object.assign(new Error(payload.error), {
@@ -1736,16 +2614,8 @@ var _LedgerAdapter = class _LedgerAdapter {
1736
2614
  }
1737
2615
  throw rethrow;
1738
2616
  }
1739
- return chosenConnectId;
2617
+ return result.payload;
1740
2618
  }
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
2619
  /**
1750
2620
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
1751
2621
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -1766,33 +2636,145 @@ var _LedgerAdapter = class _LedgerAdapter {
1766
2636
  * lives in one place.
1767
2637
  */
1768
2638
  async _callConnector(sessionId, method, params, signal) {
1769
- const promise = this.connector.call(sessionId, method, params);
2639
+ this._assertConnectorReady(method);
2640
+ if (signal?.aborted) throw this._abortReason(signal);
2641
+ const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2642
+ let promise;
2643
+ try {
2644
+ promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2645
+ } catch (error) {
2646
+ releaseOperation();
2647
+ throw error;
2648
+ }
1770
2649
  const result = signal ? await this._abortable(signal, promise) : await promise;
1771
2650
  return this._unwrapConnectorResult(result);
1772
2651
  }
2652
+ _assertConnectorReady(method) {
2653
+ if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2654
+ throw _LedgerAdapter._createDeviceBusyError(method);
2655
+ }
2656
+ }
2657
+ _runConnectorTeardown(task) {
2658
+ const previous = this._connectorTeardownTail;
2659
+ let releaseTail = () => void 0;
2660
+ this._connectorTeardownTail = new Promise((resolve) => {
2661
+ releaseTail = resolve;
2662
+ });
2663
+ this._pendingConnectorTeardowns += 1;
2664
+ return (async () => {
2665
+ try {
2666
+ await previous;
2667
+ await this._waitForConnectorOperationsToDrain();
2668
+ await task();
2669
+ } finally {
2670
+ this._pendingConnectorTeardowns -= 1;
2671
+ releaseTail();
2672
+ }
2673
+ })();
2674
+ }
2675
+ _waitForConnectorOperationsToDrain() {
2676
+ if (this._unsettledConnectorOperations.size === 0) {
2677
+ return Promise.resolve();
2678
+ }
2679
+ return new Promise((resolve) => {
2680
+ this._connectorIdleWaiters.add(resolve);
2681
+ });
2682
+ }
2683
+ _retainConnectorOperation(key) {
2684
+ this._unsettledConnectorOperations.set(
2685
+ key,
2686
+ (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2687
+ );
2688
+ let released = false;
2689
+ return () => {
2690
+ if (released) return;
2691
+ released = true;
2692
+ const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2693
+ if (remaining > 0) {
2694
+ this._unsettledConnectorOperations.set(key, remaining);
2695
+ } else {
2696
+ this._unsettledConnectorOperations.delete(key);
2697
+ }
2698
+ if (this._unsettledConnectorOperations.size === 0) {
2699
+ for (const resolve of this._connectorIdleWaiters) resolve();
2700
+ this._connectorIdleWaiters.clear();
2701
+ }
2702
+ };
2703
+ }
1773
2704
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1774
- debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1775
- const queueKey = connectId || "__ledger_default__";
2705
+ const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
2706
+ if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2707
+ throw createHwkError({
2708
+ code: HardwareErrorCode3.InvalidParams,
2709
+ message: "Conflicting Ledger operation ids",
2710
+ params: {
2711
+ positionalOperationId,
2712
+ commonOperationId: commonParams.operationId
2713
+ }
2714
+ });
2715
+ }
2716
+ const operationId = commonParams?.operationId ?? positionalOperationId;
2717
+ const operation = operationId ? this._operations.resolve(operationId) : void 0;
2718
+ const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2719
+ const effectiveConnectId = operation?.connectId ?? connectId;
2720
+ debugLog("[LedgerAdapter][REQ]", {
2721
+ method,
2722
+ connectId: effectiveConnectId || "(empty)",
2723
+ params: summarizeForLog(params, { method })
2724
+ });
2725
+ const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1776
2726
  try {
1777
2727
  const result = await this._jobQueue.enqueue(
1778
2728
  queueKey,
1779
- async (signal) => this._runConnectorCall(
1780
- connectId,
1781
- method,
1782
- params,
1783
- signal,
1784
- fingerprint,
1785
- permissionDeviceId,
1786
- commonParams,
1787
- installContext
1788
- ),
2729
+ async (signal) => {
2730
+ if (operationId) this._activeOperationJobs.add(operationId);
2731
+ try {
2732
+ return await this._runConnectorCall(
2733
+ effectiveConnectId,
2734
+ method,
2735
+ params,
2736
+ signal,
2737
+ fingerprint,
2738
+ permissionDeviceId,
2739
+ commonParams,
2740
+ installContext ?? {},
2741
+ operationId
2742
+ );
2743
+ } catch (error) {
2744
+ const status = signal.aborted ? "cancelled" : "failed";
2745
+ const bundleConnectId = installContext?.connection?.connectId;
2746
+ let keptBundlePick = false;
2747
+ for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2748
+ if (pickedConnectId === bundleConnectId) {
2749
+ keptBundlePick = true;
2750
+ } else {
2751
+ this._pendingPickBindings.delete(pickedConnectId);
2752
+ this._discardPendingBinding(owner, status);
2753
+ await this._dropSession(pickedConnectId, signal);
2754
+ }
2755
+ }
2756
+ if (!keptBundlePick) this._finishBleBinding(status);
2757
+ throw error;
2758
+ } finally {
2759
+ if (operationId) {
2760
+ this._activeOperationJobs.delete(operationId);
2761
+ if (this._pendingOperationDisconnects.delete(operationId)) {
2762
+ await this._releaseLostOperationConnection(operationId);
2763
+ }
2764
+ }
2765
+ }
2766
+ },
1789
2767
  {
1790
2768
  label: method,
1791
2769
  rejectIfBusy: true,
1792
2770
  busyError: _LedgerAdapter._createDeviceBusyError(method)
1793
2771
  }
1794
2772
  );
1795
- debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2773
+ debugLog("[LedgerAdapter][RES]", {
2774
+ method,
2775
+ success: true,
2776
+ payload: summarizeForLog(result, { method, role: "result" })
2777
+ });
1796
2778
  return result;
1797
2779
  } catch (err) {
1798
2780
  const e = err;
@@ -1806,15 +2788,22 @@ var _LedgerAdapter = class _LedgerAdapter {
1806
2788
  }
1807
2789
  });
1808
2790
  throw err;
2791
+ } finally {
2792
+ releaseOperationRetention?.();
1809
2793
  }
1810
2794
  }
2795
+ /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2796
+ _abortReason(signal) {
2797
+ return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2798
+ }
1811
2799
  /**
1812
2800
  * Race a promise against an abort signal. On abort, rejects with
1813
2801
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
1814
2802
  */
1815
2803
  _abortable(signal, promise) {
1816
- const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2804
+ const getAbortReason = () => this._abortReason(signal);
1817
2805
  if (signal.aborted) {
2806
+ void promise.catch(() => void 0);
1818
2807
  return Promise.reject(getAbortReason());
1819
2808
  }
1820
2809
  return new Promise((resolve, reject) => {
@@ -1841,17 +2830,19 @@ var _LedgerAdapter = class _LedgerAdapter {
1841
2830
  }
1842
2831
  }
1843
2832
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
1844
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2833
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1845
2834
  _LedgerAdapter._throwIfAborted(signal);
1846
- await this._ensureDevicePermission(
1847
- connectId,
1848
- permissionDeviceId ?? fingerprint?.deviceId,
1849
- signal
1850
- );
2835
+ if (!operationId) {
2836
+ await this._ensureDevicePermission(
2837
+ connectId,
2838
+ permissionDeviceId ?? fingerprint?.deviceId,
2839
+ signal
2840
+ );
2841
+ }
1851
2842
  _LedgerAdapter._throwIfAborted(signal);
1852
2843
  let effectiveParams = params;
1853
2844
  if (method === "btcGetPublicKey") {
1854
- const gatedParams = await this._gateBtcHighIndex(params);
2845
+ const gatedParams = await this._gateBtcHighIndex(params, signal);
1855
2846
  if (gatedParams === null) {
1856
2847
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
1857
2848
  _tag: ERROR_TAG.UserAborted,
@@ -1861,19 +2852,67 @@ var _LedgerAdapter = class _LedgerAdapter {
1861
2852
  effectiveParams = gatedParams;
1862
2853
  }
1863
2854
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
1864
- const resolvedConnectId = await this.ensureConnected(
1865
- connectId,
2855
+ let businessCallStarted = false;
2856
+ const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2857
+ const knownTransport = this._isBleConnection() ? "ble" : "usb";
2858
+ const hintedConnectId = commonParams?.knownConnections?.find(
2859
+ (connection) => connection.transport === knownTransport
2860
+ );
2861
+ const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2862
+ const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2863
+ const checksWallet = Boolean(
2864
+ fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2865
+ );
2866
+ const connectionAttempt = {
2867
+ ...commonParams,
2868
+ deferBindingSave: checksWallet
2869
+ };
2870
+ const bundleConnection = installContext?.connection;
2871
+ if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2872
+ throw createHwkError({
2873
+ code: HardwareErrorCode3.DeviceDisconnected,
2874
+ message: "Ledger all-network connection ended"
2875
+ });
2876
+ }
2877
+ const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2878
+ preferredConnectId,
1866
2879
  signal,
1867
- allowUsbEphemeralFallback
2880
+ allowUsbEphemeralFallback,
2881
+ void 0,
2882
+ connectionAttempt
1868
2883
  );
2884
+ const walletCheck = installContext?.walletCheck;
2885
+ if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2886
+ throw createHwkError({
2887
+ code: HardwareErrorCode3.DeviceMismatch,
2888
+ message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2889
+ });
2890
+ }
1869
2891
  const sessionId = this._sessions.get(resolvedConnectId);
2892
+ if (sessionId && installContext && !installContext.connection) {
2893
+ installContext.connection = { connectId: resolvedConnectId, sessionId };
2894
+ }
1870
2895
  if (!sessionId) {
2896
+ if (operationId) {
2897
+ this._operations.end(operationId, "disconnect");
2898
+ throw createHwkError({
2899
+ code: HardwareErrorCode3.OperationEnded,
2900
+ message: "Ledger operation connection is no longer active",
2901
+ params: { operationId, reason: "disconnect" }
2902
+ });
2903
+ }
1871
2904
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
1872
2905
  _tag: ERROR_TAG.DeviceSessionNotFound
1873
2906
  });
1874
2907
  }
1875
2908
  try {
1876
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2909
+ const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2910
+ if (!operationId && connectionAttempt.pendingBinding) {
2911
+ this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2912
+ }
2913
+ const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2914
+ const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2915
+ if (fingerprint && checksWallet) {
1877
2916
  const fp = await this._abortable(
1878
2917
  signal,
1879
2918
  this._verifyDeviceFingerprintWithSession(
@@ -1883,14 +2922,68 @@ var _LedgerAdapter = class _LedgerAdapter {
1883
2922
  )
1884
2923
  );
1885
2924
  if (!fp.success) {
2925
+ if (pendingBinding) {
2926
+ this._discardPendingBinding(bindingOwner, "failed");
2927
+ this._pendingPickBindings.delete(resolvedConnectId);
2928
+ }
2929
+ if (operationId) {
2930
+ this._pendingOperationBindings.delete(operationId);
2931
+ this._operations.end(operationId, "explicit");
2932
+ await this._dropSession(resolvedConnectId, signal);
2933
+ }
1886
2934
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
1887
2935
  code: HardwareErrorCode3.DeviceMismatch
1888
2936
  });
1889
2937
  }
2938
+ if (walletCheck) walletCheck.verified = true;
1890
2939
  }
1891
- return await this._callConnector(sessionId, method, effectiveParams, signal);
2940
+ if (pendingBinding && bindingOwner) {
2941
+ bindingOwner.pendingBinding = void 0;
2942
+ if (operationId) this._pendingOperationBindings.delete(operationId);
2943
+ else this._pendingPickBindings.delete(resolvedConnectId);
2944
+ await this._saveSelectedBleBinding(
2945
+ pendingBinding.connectId,
2946
+ pendingBinding.requestId,
2947
+ bindingOwner,
2948
+ operationId,
2949
+ signal,
2950
+ fingerprint && checksWallet ? {
2951
+ vendor: "ledger",
2952
+ type: "chainFingerprint",
2953
+ chain: fingerprint.chain,
2954
+ value: fingerprint.deviceId
2955
+ } : void 0
2956
+ );
2957
+ }
2958
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
2959
+ this._selectedBleReconnectTargets.set(connectId, {
2960
+ connectId: resolvedConnectId,
2961
+ chain: fingerprint.chain,
2962
+ fingerprint: fingerprint.deviceId
2963
+ });
2964
+ }
2965
+ businessCallStarted = true;
2966
+ const result = await this._callConnector(sessionId, method, effectiveParams, signal);
2967
+ if (walletCheck) walletCheck.derived = true;
2968
+ return result;
1892
2969
  } catch (err) {
1893
2970
  if (signal.aborted) throw err;
2971
+ if (isLostConnectionError(err)) {
2972
+ this._discoveredDevices.delete(resolvedConnectId);
2973
+ if (operationId) await this._releaseLostOperationConnection(operationId);
2974
+ else {
2975
+ this._sessions.delete(resolvedConnectId);
2976
+ await this.connector.disconnect(sessionId).catch(() => void 0);
2977
+ }
2978
+ const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
2979
+ const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
2980
+ throw createHwkError({
2981
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
2982
+ message: "Ledger operation connection was lost; start a new operation",
2983
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
2984
+ recovery: ambiguous ? { scope: "unknown" } : void 0
2985
+ });
2986
+ }
1894
2987
  const errObj = err;
1895
2988
  debugLog("[LedgerAdapter] connectorCall error:", method, {
1896
2989
  message: errObj?.message,
@@ -1902,6 +2995,64 @@ var _LedgerAdapter = class _LedgerAdapter {
1902
2995
  isNotAdvertising: isDeviceNotAdvertisingError(err),
1903
2996
  isStuckApp: isStuckAppStateError(err)
1904
2997
  });
2998
+ const assertSessionCurrent = (message) => {
2999
+ if (this._sessions.get(resolvedConnectId) === sessionId) return;
3000
+ throw createHwkError({
3001
+ code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
3002
+ message
3003
+ });
3004
+ };
3005
+ if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
3006
+ await this._waitForDeviceConnect(signal);
3007
+ assertSessionCurrent("Ledger connection ended while waiting for unlock");
3008
+ if (walletCheck?.derived) walletCheck.verified = false;
3009
+ return this._runConnectorCall(
3010
+ resolvedConnectId,
3011
+ method,
3012
+ effectiveParams,
3013
+ signal,
3014
+ fingerprint,
3015
+ permissionDeviceId,
3016
+ commonParams,
3017
+ installContext,
3018
+ operationId,
3019
+ lockedRetryBudget - 1
3020
+ );
3021
+ }
3022
+ if (businessCallStarted && isStuckAppStateError(err)) {
3023
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
3024
+ assertSessionCurrent("Ledger connection ended during the app transition");
3025
+ try {
3026
+ const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
3027
+ if (walletCheck) walletCheck.derived = true;
3028
+ return retried;
3029
+ } catch (retryErr) {
3030
+ if (isStuckAppStateError(retryErr)) throw err;
3031
+ if (isLostConnectionError(retryErr)) {
3032
+ if (operationId) await this._releaseLostOperationConnection(operationId);
3033
+ else {
3034
+ this._sessions.delete(resolvedConnectId);
3035
+ this._discoveredDevices.delete(resolvedConnectId);
3036
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3037
+ }
3038
+ const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
3039
+ throw createHwkError({
3040
+ code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
3041
+ message: `Ledger ${method} may have completed before the connection was lost`,
3042
+ params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3043
+ recovery: ambiguous ? { scope: "unknown" } : void 0
3044
+ });
3045
+ }
3046
+ throw retryErr;
3047
+ }
3048
+ }
3049
+ if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
3050
+ this._sessions.delete(resolvedConnectId);
3051
+ this._sessionTransports.delete(sessionId);
3052
+ this._discoveredDevices.delete(resolvedConnectId);
3053
+ await this.connector.disconnect(sessionId).catch(() => void 0);
3054
+ throw err;
3055
+ }
1905
3056
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
1906
3057
  const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
1907
3058
  if (autoInstallApp && isAppMissing) {
@@ -1918,7 +3069,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1918
3069
  appName
1919
3070
  });
1920
3071
  }
1921
- const confirmed = await this._waitForInstallAppConfirm(appName);
3072
+ const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1922
3073
  if (!confirmed) {
1923
3074
  throw createHwkError({
1924
3075
  code: HardwareErrorCode3.UserAborted,
@@ -1957,157 +3108,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1957
3108
  fingerprint,
1958
3109
  permissionDeviceId,
1959
3110
  commonParams,
1960
- installContext
3111
+ installContext,
3112
+ operationId
1961
3113
  );
1962
3114
  }
1963
3115
  }
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
3116
  throw err;
2075
3117
  }
2076
3118
  }
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
3119
  _sleepAbortable(ms, signal) {
2112
3120
  return new Promise((resolve, reject) => {
2113
3121
  if (signal.aborted) {
@@ -2126,111 +3134,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2126
3134
  });
2127
3135
  }
2128
3136
  /**
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
3137
+ * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3138
+ * replies. Without connectId the request is environment-level, else device-level.
2221
3139
  */
2222
3140
  async _ensureDevicePermission(connectId, deviceId, signal) {
2223
3141
  if (signal?.aborted) {
2224
3142
  _LedgerAdapter._throwIfAborted(signal);
2225
3143
  }
2226
3144
  const transportType = this.activeTransport ?? "hid";
3145
+ const operationId = this._activeOperationId();
2227
3146
  const waitPromise = this._uiRegistry.wait(
2228
3147
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2229
- { timeoutMs: 6e4 }
3148
+ { timeoutMs: 6e4, operationId }
2230
3149
  );
2231
3150
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
2232
3151
  type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
2233
- payload: { transportType, connectId, deviceId }
3152
+ payload: { transportType, connectId, deviceId, operationId }
2234
3153
  });
2235
3154
  let response;
2236
3155
  const onAbort = () => {
@@ -2276,7 +3195,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2276
3195
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
2277
3196
  const e = err;
2278
3197
  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);
3198
+ return ledgerFailure(
3199
+ e.code,
3200
+ e.message ?? "Unknown error",
3201
+ e.appName,
3202
+ tag,
3203
+ params,
3204
+ void 0,
3205
+ isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
3206
+ );
2280
3207
  }
2281
3208
  const mapped = mapLedgerError(err);
2282
3209
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -2303,7 +3230,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2303
3230
  deviceId: device.deviceId,
2304
3231
  connectId: device.connectId,
2305
3232
  label: device.name,
2306
- connectionType: this.connector.connectionType,
3233
+ connectionType: device.connectionType ?? this.connector.connectionType,
2307
3234
  rssi: device.rssi,
2308
3235
  isConnectable: device.isConnectable,
2309
3236
  serialNumber: device.serialNumber,
@@ -2329,8 +3256,8 @@ var LedgerAdapter = _LedgerAdapter;
2329
3256
 
2330
3257
  // src/connector/LedgerConnectorBase.ts
2331
3258
  import {
2332
- EConnectorInteraction as EConnectorInteraction4,
2333
- HardwareErrorCode as HardwareErrorCode8,
3259
+ EConnectorInteraction as EConnectorInteraction3,
3260
+ HardwareErrorCode as HardwareErrorCode7,
2334
3261
  isKnownNonTargetHardwareVendor,
2335
3262
  serializeConnectorError
2336
3263
  } from "@onekeyfe/hwk-adapter-core";
@@ -2603,7 +3530,7 @@ var LedgerDeviceManager = class {
2603
3530
 
2604
3531
  // src/signer/SignerManager.ts
2605
3532
  import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
2606
- import { ContextModuleBuilder } from "@ledgerhq/context-module";
3533
+ import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
2607
3534
 
2608
3535
  // src/signer/SignerEth.ts
2609
3536
  import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
@@ -2611,6 +3538,7 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
2611
3538
  // src/signer/deviceActionToPromise.ts
2612
3539
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
2613
3540
  var IDLE_WATCHDOG_MS = 65e3;
3541
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2614
3542
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
2615
3543
  return new Promise((resolve, reject) => {
2616
3544
  let settled = false;
@@ -2798,7 +3726,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
2798
3726
  }
2799
3727
 
2800
3728
  // src/signer/SignerEth.ts
2801
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
2802
3729
  var SignerEth = class {
2803
3730
  // eslint-disable-next-line no-useless-constructor, no-empty-function
2804
3731
  constructor(_sdk) {
@@ -2869,7 +3796,7 @@ var SignerManager = class _SignerManager {
2869
3796
  return (args) => new SignerEthBuilder(args);
2870
3797
  }
2871
3798
  static _createContextModule() {
2872
- const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
3799
+ const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2873
3800
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
2874
3801
  }
2875
3802
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -2907,6 +3834,27 @@ function collapseSignerInteraction(interaction) {
2907
3834
  return EConnectorInteraction2.ConfirmOnDevice;
2908
3835
  }
2909
3836
  }
3837
+ function wireSignerToSession(ctx, sessionId, chain, signer) {
3838
+ signer.onInteraction = (interaction) => {
3839
+ debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3840
+ ctx.emit("ui-event", {
3841
+ type: collapseSignerInteraction(interaction),
3842
+ payload: { sessionId }
3843
+ });
3844
+ };
3845
+ signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3846
+ return signer;
3847
+ }
3848
+ async function runSignerCall(ctx, sessionId, call) {
3849
+ try {
3850
+ return await call();
3851
+ } catch (err) {
3852
+ ctx.invalidateSession(sessionId);
3853
+ throw ctx.wrapError(err);
3854
+ } finally {
3855
+ ctx.clearCanceller(sessionId);
3856
+ }
3857
+ }
2910
3858
 
2911
3859
  // src/connector/chains/evm.ts
2912
3860
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3007,14 +3955,13 @@ async function _getEthSigner(ctx, sessionId) {
3007
3955
 
3008
3956
  // src/connector/chains/btc.ts
3009
3957
  import { HardwareErrorCode as HardwareErrorCode5, stripHex as stripHex2 } from "@onekeyfe/hwk-adapter-core";
3010
- import { Psbt } from "bitcoinjs-lib";
3958
+ import { Psbt as Psbt2 } from "bitcoinjs-lib";
3011
3959
 
3012
3960
  // src/signer/SignerBtc.ts
3013
3961
  import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
3014
3962
  function hexToUtf8(hex) {
3015
3963
  return new TextDecoder().decode(hexToBytes2(hex));
3016
3964
  }
3017
- var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3018
3965
  var SignerBtc = class {
3019
3966
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3020
3967
  constructor(_sdk) {
@@ -3028,7 +3975,7 @@ var SignerBtc = class {
3028
3975
  return deviceActionToPromise(
3029
3976
  action,
3030
3977
  this.onInteraction,
3031
- void 0,
3978
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3032
3979
  this.onRegisterCanceller
3033
3980
  );
3034
3981
  }
@@ -3046,14 +3993,14 @@ var SignerBtc = class {
3046
3993
  const result = await deviceActionToPromise(
3047
3994
  action,
3048
3995
  this.onInteraction,
3049
- void 0,
3996
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3050
3997
  this.onRegisterCanceller
3051
3998
  );
3052
3999
  debugLog(
3053
4000
  "[SignerBtc] getExtendedPublicKey result type:",
3054
4001
  typeof result,
3055
4002
  "value:",
3056
- typeof result === "string" ? `${result.substring(0, 20)}...` : JSON.stringify(result).substring(0, 50)
4003
+ summarizeForLog(result)
3057
4004
  );
3058
4005
  if (typeof result === "string") return result;
3059
4006
  return result.extendedPublicKey;
@@ -3082,7 +4029,7 @@ var SignerBtc = class {
3082
4029
  return deviceActionToPromise(
3083
4030
  action,
3084
4031
  this.onInteraction,
3085
- INTERACTIVE_TIMEOUT_MS2,
4032
+ INTERACTIVE_TIMEOUT_MS,
3086
4033
  this.onRegisterCanceller
3087
4034
  );
3088
4035
  }
@@ -3095,7 +4042,7 @@ var SignerBtc = class {
3095
4042
  return deviceActionToPromise(
3096
4043
  action,
3097
4044
  this.onInteraction,
3098
- INTERACTIVE_TIMEOUT_MS2,
4045
+ INTERACTIVE_TIMEOUT_MS,
3099
4046
  this.onRegisterCanceller
3100
4047
  );
3101
4048
  }
@@ -3108,7 +4055,7 @@ var SignerBtc = class {
3108
4055
  return deviceActionToPromise(
3109
4056
  action,
3110
4057
  this.onInteraction,
3111
- INTERACTIVE_TIMEOUT_MS2,
4058
+ INTERACTIVE_TIMEOUT_MS,
3112
4059
  this.onRegisterCanceller
3113
4060
  );
3114
4061
  }
@@ -3131,7 +4078,21 @@ function _purposeToTemplate(purpose, DDT) {
3131
4078
  });
3132
4079
  }
3133
4080
  }
4081
+ function assertBitcoinMainnet(coin) {
4082
+ if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4083
+ throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4084
+ code: HardwareErrorCode5.ChainNotSupported
4085
+ });
4086
+ }
4087
+ }
3134
4088
  async function btcGetAddress(ctx, sessionId, params) {
4089
+ assertBitcoinMainnet(params.coin);
4090
+ if (normalizePath(params.path).split("/").length !== 3) {
4091
+ throw Object.assign(
4092
+ new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4093
+ { code: HardwareErrorCode5.InvalidParams }
4094
+ );
4095
+ }
3135
4096
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3136
4097
  const path = normalizePath(params.path);
3137
4098
  try {
@@ -3162,6 +4123,7 @@ async function btcGetAddress(ctx, sessionId, params) {
3162
4123
  }
3163
4124
  }
3164
4125
  async function btcGetPublicKey(ctx, sessionId, params) {
4126
+ assertBitcoinMainnet(params.coin);
3165
4127
  const btcSigner = await _createBtcSigner(ctx, sessionId);
3166
4128
  const path = normalizePath(params.path);
3167
4129
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -3169,7 +4131,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
3169
4131
  const xpub = await btcSigner.getExtendedPublicKey(path, {
3170
4132
  checkOnDevice: params.showOnDevice ?? false
3171
4133
  });
3172
- debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", `${xpub?.substring(0, 20)}...`);
4134
+ debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
3173
4135
  return { xpub, path: params.path };
3174
4136
  } catch (err) {
3175
4137
  debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
@@ -3290,7 +4252,7 @@ function _isScriptPathInput(input) {
3290
4252
  return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
3291
4253
  }
3292
4254
  function _applySignaturesToPsbt(psbtHex, signatures) {
3293
- const psbt = Psbt.fromHex(psbtHex);
4255
+ const psbt = Psbt2.fromHex(psbtHex);
3294
4256
  for (const sig of signatures) {
3295
4257
  const input = psbt.data.inputs[sig.inputIndex];
3296
4258
  if (!input) {
@@ -3339,7 +4301,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
3339
4301
  }
3340
4302
 
3341
4303
  // src/connector/chains/sol.ts
3342
- import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
4304
+ import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
4305
+ import bs58 from "bs58";
3343
4306
 
3344
4307
  // src/signer/SignerSol.ts
3345
4308
  var SignerSol = class {
@@ -3357,7 +4320,7 @@ var SignerSol = class {
3357
4320
  return deviceActionToPromise(
3358
4321
  action,
3359
4322
  this.onInteraction,
3360
- void 0,
4323
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3361
4324
  this.onRegisterCanceller
3362
4325
  );
3363
4326
  }
@@ -3369,7 +4332,7 @@ var SignerSol = class {
3369
4332
  return deviceActionToPromise(
3370
4333
  action,
3371
4334
  this.onInteraction,
3372
- void 0,
4335
+ INTERACTIVE_TIMEOUT_MS,
3373
4336
  this.onRegisterCanceller
3374
4337
  );
3375
4338
  }
@@ -3382,7 +4345,7 @@ var SignerSol = class {
3382
4345
  return deviceActionToPromise(
3383
4346
  action,
3384
4347
  this.onInteraction,
3385
- void 0,
4348
+ INTERACTIVE_TIMEOUT_MS,
3386
4349
  this.onRegisterCanceller
3387
4350
  );
3388
4351
  }
@@ -3423,8 +4386,21 @@ async function solSignMessage(ctx, sessionId, params) {
3423
4386
  const path = normalizePath(params.path);
3424
4387
  const messageBytes = hexToBytes3(params.message);
3425
4388
  try {
4389
+ if (params.messageVersion === 1) {
4390
+ const preparedMessage = prepareSolanaOffchainMessageV1({
4391
+ message: messageBytes,
4392
+ requiredSigners: params.requiredSigners
4393
+ });
4394
+ const { SignMessageVersion } = await ctx.importLedgerKit(
4395
+ "@ledgerhq/device-signer-kit-solana"
4396
+ );
4397
+ const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4398
+ version: SignMessageVersion.Raw
4399
+ });
4400
+ return { signature: decodeBase58Signature(result2.signature) };
4401
+ }
3426
4402
  const result = await solSigner.signMessage(path, messageBytes);
3427
- return { signature: result.signature };
4403
+ return { signature: decodeBase58EnvelopeSignature(result.signature) };
3428
4404
  } catch (err) {
3429
4405
  ctx.invalidateSession(sessionId);
3430
4406
  throw ctx.wrapError(err);
@@ -3432,11 +4408,27 @@ async function solSignMessage(ctx, sessionId, params) {
3432
4408
  ctx.clearCanceller(sessionId);
3433
4409
  }
3434
4410
  }
4411
+ function decodeBase58Signature(signature) {
4412
+ const bytes = bs58.decode(signature);
4413
+ if (bytes.length !== 64) {
4414
+ throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4415
+ }
4416
+ return bytesToHex(bytes);
4417
+ }
4418
+ function decodeBase58EnvelopeSignature(envelope) {
4419
+ const bytes = bs58.decode(envelope);
4420
+ if (bytes.length < 65 || bytes[0] !== 1) {
4421
+ throw new Error("Ledger Solana signature envelope is invalid");
4422
+ }
4423
+ return bytesToHex(bytes.subarray(1, 65));
4424
+ }
3435
4425
  async function _createSolSigner(ctx, sessionId) {
3436
4426
  const dmk = await ctx.getOrCreateDmk();
3437
- const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4427
+ const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4428
+ "@ledgerhq/context-module"
4429
+ );
3438
4430
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
3439
- const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4431
+ const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3440
4432
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
3441
4433
  const signer = new SignerSol(sdkSigner);
3442
4434
  signer.onInteraction = (interaction) => {
@@ -3452,361 +4444,147 @@ async function _createSolSigner(ctx, sessionId) {
3452
4444
  return signer;
3453
4445
  }
3454
4446
 
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";
4447
+ // src/connector/chains/zcash.ts
4448
+ import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
3461
4449
 
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);
4450
+ // src/signer/SignerZcash.ts
4451
+ var SignerZcash = class {
4452
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4453
+ constructor(_sdk) {
4454
+ this._sdk = _sdk;
3528
4455
  }
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
- }
4456
+ /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4457
+ async getFullViewingKey(derivationPath, options) {
4458
+ const action = this._sdk.getFullViewingKey(derivationPath, options);
4459
+ return deviceActionToPromise(
4460
+ action,
4461
+ this.onInteraction,
4462
+ void 0,
4463
+ this.onRegisterCanceller
3565
4464
  );
3566
4465
  }
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})`
4466
+ /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4467
+ async getShieldedAddress(derivationPath, options) {
4468
+ const action = this._sdk.getShieldedAddress(derivationPath, options);
4469
+ return deviceActionToPromise(
4470
+ action,
4471
+ this.onInteraction,
4472
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4473
+ this.onRegisterCanceller
3629
4474
  );
3630
4475
  }
3631
- _isDashboard(appName) {
3632
- return appName === DASHBOARD_APP_NAME;
3633
- }
3634
- _wait() {
3635
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3636
- }
3637
4476
  };
3638
4477
 
3639
- // src/connector/chains/legacyChainCall.ts
3640
- function isLegacyWrongAppError(err, _appName) {
3641
- return isWrongAppError(err);
4478
+ // src/connector/chains/zcash.ts
4479
+ async function zcashGetFullViewingKey(ctx, sessionId, params) {
4480
+ const signer = await _createZcashSigner(ctx, sessionId);
4481
+ const path = normalizePath(params.path);
4482
+ const mode = params.mode ?? "ufvk";
4483
+ return runSignerCall(ctx, sessionId, async () => {
4484
+ const result = await signer.getFullViewingKey(path, { mode });
4485
+ if (result.mode === "ufvk") {
4486
+ return { path: params.path, mode, ufvk: result.fullViewingKey };
4487
+ }
4488
+ return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
4489
+ });
3642
4490
  }
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 }
4491
+ async function zcashGetShieldedAddress(ctx, sessionId, params) {
4492
+ const signer = await _createZcashSigner(ctx, sessionId);
4493
+ const path = normalizePath(params.path);
4494
+ return runSignerCall(ctx, sessionId, async () => {
4495
+ const result = await signer.getShieldedAddress(path, {
4496
+ checkOnDevice: params.showOnDevice ?? false
3651
4497
  });
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
- }
4498
+ return { address: result.address, path: params.path };
4499
+ });
3719
4500
  }
3720
- async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4501
+ async function _createZcashSigner(ctx, sessionId) {
3721
4502
  const dmk = await ctx.getOrCreateDmk();
3722
- const appManager = new AppManager(dmk);
3723
- await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4503
+ const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4504
+ const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4505
+ return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3724
4506
  }
3725
4507
 
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;
4508
+ // src/connector/chains/tron.ts
4509
+ import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
4510
+
4511
+ // src/signer/SignerTron.ts
4512
+ var SignerTron = class {
4513
+ // eslint-disable-next-line no-useless-constructor, no-empty-function
4514
+ constructor(_sdk) {
4515
+ this._sdk = _sdk;
4516
+ }
4517
+ /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4518
+ async getAddress(derivationPath, options) {
4519
+ const action = this._sdk.getAddress(derivationPath, options);
4520
+ const result = await deviceActionToPromise(
4521
+ action,
4522
+ this.onInteraction,
4523
+ options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4524
+ this.onRegisterCanceller
4525
+ );
4526
+ return { address: result.address, publicKey: result.publicKey };
3733
4527
  }
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;
4528
+ /** Sign a protobuf-encoded raw transaction. */
4529
+ async signTransaction(derivationPath, transaction, options) {
4530
+ const action = this._sdk.signTransaction(derivationPath, transaction, options);
4531
+ return deviceActionToPromise(
4532
+ action,
4533
+ this.onInteraction,
4534
+ INTERACTIVE_TIMEOUT_MS,
4535
+ this.onRegisterCanceller
4536
+ );
3746
4537
  }
3747
- async close() {
4538
+ /** Sign a personal message (TIP-191). */
4539
+ async signPersonalMessage(derivationPath, message, options) {
4540
+ const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4541
+ return deviceActionToPromise(
4542
+ action,
4543
+ this.onInteraction,
4544
+ INTERACTIVE_TIMEOUT_MS,
4545
+ this.onRegisterCanceller
4546
+ );
3748
4547
  }
3749
4548
  };
3750
4549
 
3751
4550
  // src/connector/chains/tron.ts
3752
4551
  async function tronGetAddress(ctx, sessionId, params) {
4552
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3753
4553
  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
- );
4554
+ return runSignerCall(ctx, sessionId, async () => {
4555
+ const result = await tronSigner.getAddress(path, {
4556
+ checkOnDevice: params.showOnDevice ?? false
4557
+ });
4558
+ return { address: result.address, publicKey: result.publicKey, path: params.path };
4559
+ });
3770
4560
  }
3771
4561
  async function tronSignTransaction(ctx, sessionId, params) {
3772
4562
  if (!params.rawTxHex) {
3773
4563
  throw Object.assign(
3774
4564
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
3775
- { code: HardwareErrorCode7.InvalidParams }
4565
+ { code: HardwareErrorCode6.InvalidParams }
3776
4566
  );
3777
4567
  }
4568
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3778
4569
  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
- );
4570
+ return runSignerCall(ctx, sessionId, async () => {
4571
+ const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
4572
+ return { signature: bytesToHex3(signature) };
4573
+ });
3793
4574
  }
3794
4575
  async function tronSignMessage(ctx, sessionId, params) {
4576
+ const tronSigner = await _createTronSigner(ctx, sessionId);
3795
4577
  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
- );
4578
+ return runSignerCall(ctx, sessionId, async () => {
4579
+ const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
4580
+ return { signature: bytesToHex3(signature) };
4581
+ });
3806
4582
  }
3807
- async function _createTrx(ctx, sessionId) {
4583
+ async function _createTronSigner(ctx, sessionId) {
3808
4584
  const dmk = await ctx.getOrCreateDmk();
3809
- return new Trx(new DmkTransport(dmk, sessionId));
4585
+ const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4586
+ const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4587
+ return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3810
4588
  }
3811
4589
 
3812
4590
  // src/device-apps/customActions.ts
@@ -3985,7 +4763,7 @@ var DeviceApps = class {
3985
4763
  seTargetId: v.seTargetId,
3986
4764
  mcuTargetId: v.mcuTargetId,
3987
4765
  seVersion: v.seVersion,
3988
- seFlagsHex: bytesToHex2(v.seFlags),
4766
+ seFlagsHex: bytesToHex4(v.seFlags),
3989
4767
  mcuSephVersion: v.mcuSephVersion,
3990
4768
  mcuBootloaderVersion: v.mcuBootloaderVersion,
3991
4769
  hwVersion: v.hwVersion
@@ -4059,7 +4837,7 @@ var DeviceApps = class {
4059
4837
  }
4060
4838
  }
4061
4839
  };
4062
- function bytesToHex2(bytes) {
4840
+ function bytesToHex4(bytes) {
4063
4841
  if (!bytes) return "";
4064
4842
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4065
4843
  }
@@ -4102,10 +4880,11 @@ var METHOD_PREFIX_TO_APP_NAME = {
4102
4880
  evm: "Ethereum",
4103
4881
  btc: "Bitcoin",
4104
4882
  sol: "Solana",
4105
- tron: "Tron"
4883
+ tron: "Tron",
4884
+ zcash: "Zcash"
4106
4885
  };
4107
4886
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4108
- Object.values(HardwareErrorCode8).filter((value) => typeof value === "number")
4887
+ Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4109
4888
  );
4110
4889
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4111
4890
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4142,6 +4921,10 @@ async function defaultLedgerKitImporter(pkg) {
4142
4921
  return import("@ledgerhq/device-signer-kit-bitcoin");
4143
4922
  case "@ledgerhq/device-signer-kit-solana":
4144
4923
  return import("@ledgerhq/device-signer-kit-solana");
4924
+ case "@ledgerhq/device-signer-kit-tron":
4925
+ return import("@ledgerhq/device-signer-kit-tron");
4926
+ case "@ledgerhq/device-signer-kit-zcash":
4927
+ return import("@ledgerhq/device-signer-kit-zcash");
4145
4928
  case "@ledgerhq/context-module":
4146
4929
  return import("@ledgerhq/context-module");
4147
4930
  default:
@@ -4201,6 +4984,7 @@ var LedgerConnectorBase = class {
4201
4984
  this._ctx = {
4202
4985
  emit: (event, data) => this._emit(event, data),
4203
4986
  invalidateSession: (sid) => this._invalidateSession(sid),
4987
+ teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4204
4988
  wrapError: (err, opts) => this._wrapError(err, opts),
4205
4989
  getOrCreateDmk: () => this._getOrCreateDmk(),
4206
4990
  getDeviceManager: () => this._getDeviceManager(),
@@ -4300,7 +5084,7 @@ var LedgerConnectorBase = class {
4300
5084
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
4301
5085
  );
4302
5086
  err._tag = ERROR_TAG.BlePairingTimeout;
4303
- err.code = HardwareErrorCode8.BlePairingTimeout;
5087
+ err.code = HardwareErrorCode7.BlePairingTimeout;
4304
5088
  reject(err);
4305
5089
  }, HANG_CEILING_MS);
4306
5090
  });
@@ -4333,7 +5117,7 @@ var LedgerConnectorBase = class {
4333
5117
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
4334
5118
  );
4335
5119
  err._tag = ERROR_TAG.DeviceNotAdvertising;
4336
- err.code = HardwareErrorCode8.DeviceNotFound;
5120
+ err.code = HardwareErrorCode7.DeviceNotFound;
4337
5121
  throw err;
4338
5122
  };
4339
5123
  const doConnect = async (path) => {
@@ -4390,14 +5174,14 @@ var LedgerConnectorBase = class {
4390
5174
  this._resetSignersAndSessions();
4391
5175
  if (isLedgerBleConnectionType(this.connectionType)) {
4392
5176
  const tag = err?._tag;
4393
- if (isKnownConnectionTag(tag)) {
5177
+ if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4394
5178
  throw err;
4395
5179
  }
4396
5180
  const wrapped = new Error(
4397
5181
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
4398
5182
  );
4399
5183
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
4400
- wrapped.code = HardwareErrorCode8.BlePairingTimeout;
5184
+ wrapped.code = HardwareErrorCode7.BlePairingTimeout;
4401
5185
  wrapped.originalError = err;
4402
5186
  throw wrapped;
4403
5187
  }
@@ -4475,7 +5259,7 @@ var LedgerConnectorBase = class {
4475
5259
  this._unwatchSessionState(sessionId);
4476
5260
  this._signerManager?.invalidate(sessionId);
4477
5261
  this._cancellers.get(sessionId)?.({
4478
- code: HardwareErrorCode8.DeviceDisconnected,
5262
+ code: HardwareErrorCode7.DeviceDisconnected,
4479
5263
  tag: "DeviceDisconnected",
4480
5264
  message: "Device disconnected"
4481
5265
  });
@@ -4491,7 +5275,7 @@ var LedgerConnectorBase = class {
4491
5275
  // whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
4492
5276
  // locally (see LedgerAdapter._unwrapConnectorResult).
4493
5277
  async call(sessionId, method, params) {
4494
- debugLog("[DMK] call:", method, JSON.stringify(params));
5278
+ debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
4495
5279
  try {
4496
5280
  const payload = await this._dispatch(sessionId, method, params);
4497
5281
  return { success: true, payload };
@@ -4501,7 +5285,7 @@ var LedgerConnectorBase = class {
4501
5285
  success: false,
4502
5286
  error: serializeConnectorError(
4503
5287
  Object.assign(new Error("Ledger app is unresponsive"), {
4504
- code: HardwareErrorCode8.DeviceAppStuck,
5288
+ code: HardwareErrorCode7.DeviceAppStuck,
4505
5289
  _tag: ERROR_TAG.DeviceAppStuck,
4506
5290
  originalError: err
4507
5291
  })
@@ -4513,7 +5297,7 @@ var LedgerConnectorBase = class {
4513
5297
  success: false,
4514
5298
  error: serializeConnectorError(
4515
5299
  Object.assign(new Error("Device communication interrupted, please retry"), {
4516
- code: HardwareErrorCode8.TransportError,
5300
+ code: HardwareErrorCode7.TransportError,
4517
5301
  _tag: ERROR_TAG.DeviceTransportStuck,
4518
5302
  originalError: err
4519
5303
  })
@@ -4559,6 +5343,11 @@ var LedgerConnectorBase = class {
4559
5343
  return solSignTransaction(ctx, sessionId, params);
4560
5344
  case "solSignMessage":
4561
5345
  return solSignMessage(ctx, sessionId, params);
5346
+ // ZCASH
5347
+ case "zcashGetFullViewingKey":
5348
+ return zcashGetFullViewingKey(ctx, sessionId, params);
5349
+ case "zcashGetShieldedAddress":
5350
+ return zcashGetShieldedAddress(ctx, sessionId, params);
4562
5351
  // TRON
4563
5352
  case "tronGetAddress":
4564
5353
  return tronGetAddress(ctx, sessionId, params);
@@ -4583,7 +5372,7 @@ var LedgerConnectorBase = class {
4583
5372
  try {
4584
5373
  return await apps.install(p.appName, ({ progress }) => {
4585
5374
  ctx.emit("ui-event", {
4586
- type: EConnectorInteraction4.AppInstallProgress,
5375
+ type: EConnectorInteraction3.AppInstallProgress,
4587
5376
  payload: {
4588
5377
  sessionId,
4589
5378
  appName: p.appName,
@@ -4592,7 +5381,7 @@ var LedgerConnectorBase = class {
4592
5381
  });
4593
5382
  });
4594
5383
  } catch (err) {
4595
- ctx.invalidateSession(sessionId);
5384
+ ctx.teardownSecureChannelSession(sessionId);
4596
5385
  throw ctx.wrapError(err);
4597
5386
  } finally {
4598
5387
  ctx.clearCanceller(sessionId);
@@ -4682,7 +5471,7 @@ var LedgerConnectorBase = class {
4682
5471
  );
4683
5472
  return { isGenuine: output.isGenuine, deviceId };
4684
5473
  } catch (err) {
4685
- ctx.invalidateSession(sessionId);
5474
+ ctx.teardownSecureChannelSession(sessionId);
4686
5475
  throw ctx.wrapError(err);
4687
5476
  } finally {
4688
5477
  ctx.clearCanceller(sessionId);
@@ -4804,6 +5593,17 @@ var LedgerConnectorBase = class {
4804
5593
  _invalidateSession(sessionId) {
4805
5594
  this._signerManager?.invalidate(sessionId);
4806
5595
  }
5596
+ _teardownSecureChannelSession(sessionId) {
5597
+ const cancel = this._cancellers.get(sessionId);
5598
+ this._cancellers.delete(sessionId);
5599
+ if (cancel) {
5600
+ try {
5601
+ cancel();
5602
+ } catch {
5603
+ }
5604
+ }
5605
+ this._invalidateSession(sessionId);
5606
+ }
4807
5607
  /**
4808
5608
  * Replace an old session with a new one after app switch.
4809
5609
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -4888,7 +5688,7 @@ var LedgerConnectorBase = class {
4888
5688
  * at every catch site. Falls through unchanged for unknown methods.
4889
5689
  */
4890
5690
  _ctxForMethod(method) {
4891
- const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5691
+ const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4892
5692
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
4893
5693
  if (!defaultAppName) return this._ctx;
4894
5694
  return {
@@ -4922,6 +5722,209 @@ var LedgerConnectorBase = class {
4922
5722
  return error;
4923
5723
  }
4924
5724
  };
5725
+
5726
+ // src/transport/DmkTransport.ts
5727
+ import Transport from "@ledgerhq/hw-transport";
5728
+ var DmkTransport = class extends Transport {
5729
+ constructor(dmk, sessionId) {
5730
+ super();
5731
+ this._dmk = dmk;
5732
+ this._sessionId = sessionId;
5733
+ }
5734
+ async exchange(apdu) {
5735
+ const response = await this._dmk.sendApdu({
5736
+ sessionId: this._sessionId,
5737
+ apdu: new Uint8Array(apdu)
5738
+ });
5739
+ const { data, statusCode } = response;
5740
+ const result = Buffer.alloc(data.length + 2);
5741
+ if (data.length > 0) {
5742
+ result.set(data, 0);
5743
+ }
5744
+ result.set(statusCode, data.length);
5745
+ return result;
5746
+ }
5747
+ async close() {
5748
+ }
5749
+ };
5750
+
5751
+ // src/app/AppManager.ts
5752
+ import {
5753
+ CloseAppCommand,
5754
+ GetAppAndVersionCommand,
5755
+ OpenAppCommand,
5756
+ isSuccessCommandResult
5757
+ } from "@ledgerhq/device-management-kit";
5758
+ import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
5759
+ var APP_NAME_MAP = {
5760
+ ETH: "Ethereum",
5761
+ BTC: "Bitcoin",
5762
+ SOL: "Solana",
5763
+ TRX: "Tron",
5764
+ ZEC: "Zcash",
5765
+ XRP: "XRP",
5766
+ ADA: "Cardano",
5767
+ DOT: "Polkadot",
5768
+ ATOM: "Cosmos"
5769
+ };
5770
+ var DASHBOARD_APP_NAME = "BOLOS";
5771
+ var AppManager = class {
5772
+ constructor(dmk, options) {
5773
+ this._dmk = dmk;
5774
+ this._waitMs = options?.waitMs ?? 1e3;
5775
+ this._maxRetries = options?.maxRetries ?? 10;
5776
+ }
5777
+ /**
5778
+ * Return the Ledger app name for a given chain ticker,
5779
+ * or undefined if the chain is not supported.
5780
+ */
5781
+ static getAppName(chain) {
5782
+ return APP_NAME_MAP[chain];
5783
+ }
5784
+ /**
5785
+ * Ensure the target app is open on the device identified by `sessionId`.
5786
+ *
5787
+ * Flow:
5788
+ * 1. Check the currently running app.
5789
+ * 2. If it is already the target, return immediately.
5790
+ * 3. If a different app is running (not dashboard), close it first.
5791
+ * 4. Open the target app.
5792
+ * 5. Poll until the device confirms the target app is running.
5793
+ */
5794
+ /**
5795
+ * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5796
+ * device is about to display "Open <app>" on screen and wait for the
5797
+ * user's button press. UI consumers should show their "open app" prompt
5798
+ * in response. NOT called when the target app is already open (no user
5799
+ * interaction needed in that case).
5800
+ *
5801
+ * Important: OpenAppCommand is blocking. It does not resolve until the user
5802
+ * has physically confirmed on the device, so anything that runs AFTER
5803
+ * `await this._openApp(...)` lands AFTER the prompt is already gone.
5804
+ * Hence the callback must fire BEFORE that await.
5805
+ */
5806
+ async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5807
+ const currentApp = await this._getCurrentApp(sessionId);
5808
+ if (currentApp === targetAppName) {
5809
+ return;
5810
+ }
5811
+ if (!this._isDashboard(currentApp)) {
5812
+ await this._closeCurrentApp(sessionId);
5813
+ await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5814
+ }
5815
+ onConfirmOnDevice?.();
5816
+ await this._openApp(sessionId, targetAppName);
5817
+ await this._waitForApp(sessionId, targetAppName);
5818
+ }
5819
+ // ---------------------------------------------------------------------------
5820
+ // Private helpers
5821
+ // ---------------------------------------------------------------------------
5822
+ async _getCurrentApp(sessionId) {
5823
+ const result = await this._dmk.sendCommand({
5824
+ sessionId,
5825
+ command: new GetAppAndVersionCommand()
5826
+ });
5827
+ if (isSuccessCommandResult(result)) {
5828
+ debugLog("[AppManager] currentApp:", result.data.name);
5829
+ return result.data.name;
5830
+ }
5831
+ const errResult = result;
5832
+ const dmkErr = errResult.error ?? {};
5833
+ const original = dmkErr.originalError;
5834
+ debugLog(
5835
+ "[AppManager] _getCurrentApp failed sessionId=",
5836
+ sessionId,
5837
+ "tag=",
5838
+ dmkErr._tag,
5839
+ "errorCode=",
5840
+ dmkErr.errorCode,
5841
+ "message=",
5842
+ dmkErr.message,
5843
+ "originalErrorMessage=",
5844
+ original?.message ?? String(original ?? "")
5845
+ );
5846
+ throw Object.assign(
5847
+ new Error(
5848
+ dmkErr.message ?? "Failed to get current app from device"
5849
+ ),
5850
+ {
5851
+ _tag: dmkErr._tag,
5852
+ errorCode: dmkErr.errorCode,
5853
+ originalError: original
5854
+ }
5855
+ );
5856
+ }
5857
+ async _openApp(sessionId, appName) {
5858
+ const result = await this._dmk.sendCommand({
5859
+ sessionId,
5860
+ command: new OpenAppCommand({ appName })
5861
+ });
5862
+ if (!isSuccessCommandResult(result)) {
5863
+ const dmkErr = result.error;
5864
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5865
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5866
+ debugLog(
5867
+ "[AppManager] openApp failed:",
5868
+ appName,
5869
+ "errorCode:",
5870
+ errorCode,
5871
+ "tag:",
5872
+ dmkErr._tag
5873
+ );
5874
+ let code;
5875
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
5876
+ code = HardwareErrorCode8.AppNotInstalled;
5877
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5878
+ code = HardwareErrorCode8.UserRejected;
5879
+ }
5880
+ throw Object.assign(new Error(`Failed to open "${appName}"`), {
5881
+ _tag: ERROR_TAG.OpenAppCommand,
5882
+ code,
5883
+ errorCode,
5884
+ statusCode: errorCode,
5885
+ appName,
5886
+ originalError: dmkErr
5887
+ });
5888
+ }
5889
+ }
5890
+ async _closeCurrentApp(sessionId) {
5891
+ debugLog("[AppManager] closeCurrentApp");
5892
+ await this._dmk.sendCommand({
5893
+ sessionId,
5894
+ command: new CloseAppCommand()
5895
+ });
5896
+ }
5897
+ /**
5898
+ * Poll the device until the expected app is reported as running,
5899
+ * or throw after `_maxRetries` attempts.
5900
+ */
5901
+ async _waitForApp(sessionId, expectedAppName) {
5902
+ let lastSeen = "";
5903
+ for (let i = 0; i < this._maxRetries; i++) {
5904
+ await this._wait();
5905
+ const current = await this._getCurrentApp(sessionId);
5906
+ lastSeen = current;
5907
+ if (current === expectedAppName) {
5908
+ return;
5909
+ }
5910
+ }
5911
+ debugLog(
5912
+ "[AppManager] waitForApp exhausted: expected=",
5913
+ expectedAppName,
5914
+ "lastSeen=",
5915
+ lastSeen
5916
+ );
5917
+ throw new Error(
5918
+ `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
5919
+ );
5920
+ }
5921
+ _isDashboard(appName) {
5922
+ return appName === DASHBOARD_APP_NAME;
5923
+ }
5924
+ _wait() {
5925
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
5926
+ }
5927
+ };
4925
5928
  export {
4926
5929
  AppManager,
4927
5930
  DmkTransport,
@@ -4932,6 +5935,7 @@ export {
4932
5935
  SignerEth,
4933
5936
  SignerManager,
4934
5937
  SignerSol,
5938
+ SignerZcash,
4935
5939
  debugLog,
4936
5940
  deviceActionToPromise,
4937
5941
  isDeviceLockedError,