@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.13 → 1.2.8-alpha.14

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,43 +6,30 @@ import {
6
6
  DeviceJobQueue,
7
7
  EConnectorInteraction,
8
8
  HardwareErrorCode as HardwareErrorCode3,
9
- OperationRegistry,
10
- SDK,
11
9
  TypedEventEmitter,
12
10
  UI_REQUEST,
13
11
  UI_REQUEST_PREEMPTED_TAG,
14
12
  UiRequestRegistry,
15
- canReplayHardwareMethodAfterTransportFailure,
16
13
  createHwkError,
17
14
  deriveDeviceFingerprint,
18
- emitDeviceBindingStatus,
19
15
  failure as failure2,
20
- isHardwareOperationId,
21
- isHwkRecoveryHint,
22
- operationMayHaveCompletedParams,
23
- pickConnectionContext,
24
16
  rehydrateConnectorError,
25
- requestBleDeviceSelection,
26
- requestSaveDeviceBinding,
27
- success as success2,
28
- toPhysicalDeviceSearchTarget
17
+ success
29
18
  } from "@onekeyfe/hwk-adapter-core";
30
19
 
31
20
  // src/errors.ts
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) {
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) {
39
29
  const payload = { error, code };
40
30
  if (appName !== void 0) payload.appName = appName;
41
31
  if (tag !== void 0) payload._tag = tag;
42
32
  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);
46
33
  return { success: false, payload };
47
34
  }
48
35
  var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
@@ -183,10 +170,7 @@ var ERROR_TAG = {
183
170
  UnknownDevice: "UnknownDeviceError",
184
171
  DeviceSessionRefresher: "DeviceSessionRefresherError",
185
172
  DeviceNotInitialized: "DeviceNotInitializedError",
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",
173
+ OpeningConnection: "OpeningConnectionError",
190
174
  DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
191
175
  DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
192
176
  Disconnect: "DisconnectError",
@@ -199,16 +183,7 @@ var ERROR_TAG = {
199
183
  // DMK remote-network failures (manager-api HTTP / secure-channel WS).
200
184
  WebSocketConnection: "WebSocketConnectionError",
201
185
  HttpFetch: "FetchError",
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"
186
+ InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError"
212
187
  };
213
188
  function isDeviceLockedError(err) {
214
189
  if (!err || typeof err !== "object") return false;
@@ -238,6 +213,7 @@ function isBlePairingFailureError(err) {
238
213
  return false;
239
214
  }
240
215
  var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
216
+ ERROR_TAG.DeviceLocked,
241
217
  ERROR_TAG.DeviceNotAdvertising,
242
218
  ERROR_TAG.BlePairingTimeout,
243
219
  ERROR_TAG.BleGattBondingFailed,
@@ -249,7 +225,6 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
249
225
  ERROR_TAG.DeviceSessionRefresher,
250
226
  ERROR_TAG.DeviceNotInitialized,
251
227
  ERROR_TAG.OpeningConnection,
252
- ERROR_TAG.OpeningConnectionLegacy,
253
228
  ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
254
229
  ERROR_TAG.DeviceDisconnectedWhileSending,
255
230
  ERROR_TAG.Disconnect,
@@ -264,10 +239,7 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
264
239
  // Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
265
240
  ERROR_TAG.DeviceNotInDiscoveryCache
266
241
  ]);
267
- var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
268
- ERROR_TAG.OpeningConnection,
269
- ERROR_TAG.OpeningConnectionLegacy
270
- ]);
242
+ var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OpeningConnection]);
271
243
  var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
272
244
  ERROR_TAG.DeviceNotRecognized,
273
245
  ERROR_TAG.DeviceSessionNotFound,
@@ -279,18 +251,17 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
279
251
  ERROR_TAG.WebHIDDisconnect
280
252
  ]);
281
253
  function isConnectionLevelError(err) {
282
- return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
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;
283
261
  }
284
262
  function isKnownConnectionTag(tag) {
285
263
  return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
286
264
  }
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
- }
294
265
  function hasStatusCode(err, codeSet) {
295
266
  if (!err || typeof err !== "object") return false;
296
267
  const e = err;
@@ -326,28 +297,28 @@ function hasInvalidArgumentCode(err) {
326
297
  if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
327
298
  return false;
328
299
  }
329
- function hasErrorTag(err, tags) {
300
+ function isDeviceNotFoundError(err) {
330
301
  if (!err || typeof err !== "object") return false;
302
+ const tag = err._tag;
303
+ if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
331
304
  const e = err;
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;
305
+ if (e.originalError != null && isDeviceNotFoundError(e.originalError)) return true;
306
+ if (e.error != null && e._tag && isDeviceNotFoundError(e.error)) return true;
335
307
  return false;
336
308
  }
337
- function isDeviceNotFoundError(err) {
338
- return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
339
- }
340
309
  function isDeviceBusyError(err) {
341
- return hasErrorTag(err, DEVICE_BUSY_TAGS);
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;
342
317
  }
343
- var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
344
- ERROR_TAG.UserRefusedOnDevice,
345
- ERROR_TAG.RefusedByUserDA
346
- ]);
347
318
  function isUserRejectedError(err) {
348
319
  if (!err || typeof err !== "object") return false;
349
320
  const e = err;
350
- if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
321
+ if (e._tag === ERROR_TAG.UserRefusedOnDevice) return true;
351
322
  if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
352
323
  if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
353
324
  return false;
@@ -378,33 +349,15 @@ function isAppNotInstalledError(err) {
378
349
  if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
379
350
  return false;
380
351
  }
381
- var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
382
352
  function isOutOfMemoryError(err) {
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);
353
+ if (!err || typeof err !== "object") return false;
354
+ const e = err;
355
+ return e._tag === "OutOfMemoryDAError";
403
356
  }
404
357
  var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
405
358
  ERROR_TAG.WebSocketConnection,
406
359
  ERROR_TAG.HttpFetch,
407
- ERROR_TAG.NetworkDA
360
+ ERROR_TAG.InvalidFirmwareMetadataResponse
408
361
  ]);
409
362
  function isNetworkError(err) {
410
363
  if (!err || typeof err !== "object") return false;
@@ -454,34 +407,23 @@ function isTransportStuck(err) {
454
407
  function isStuckAppStateError(err) {
455
408
  return isAppStuckByApdu(err) || isTransportStuck(err);
456
409
  }
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
- }
466
410
  function mapLedgerError(err, opts) {
467
411
  let originalMessage = "Unknown Ledger error";
468
412
  if (err instanceof Error) {
469
413
  originalMessage = err.message;
470
414
  } else if (err && typeof err === "object") {
471
415
  const e = err;
472
- originalMessage = String(
473
- e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
474
- );
416
+ originalMessage = String(e.message ?? e._tag ?? e.type ?? JSON.stringify(err));
475
417
  }
476
418
  let code;
477
419
  if (isDeviceLockedError(err)) {
478
420
  code = HardwareErrorCode.DeviceLocked;
479
421
  } else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
480
422
  code = HardwareErrorCode.DeviceNotFound;
481
- } else if (isBlePairingFailureError(err)) {
482
- code = HardwareErrorCode.BlePairingTimeout;
483
423
  } else if (isDeviceBusyError(err)) {
484
424
  code = HardwareErrorCode.DeviceBusy;
425
+ } else if (isBlePairingFailureError(err)) {
426
+ code = HardwareErrorCode.BlePairingTimeout;
485
427
  } else if (isUserAbortedError(err)) {
486
428
  code = HardwareErrorCode.UserAborted;
487
429
  } else if (isUserRejectedError(err)) {
@@ -490,18 +432,10 @@ function mapLedgerError(err, opts) {
490
432
  code = HardwareErrorCode.WrongApp;
491
433
  } else if (isAppNotInstalledError(err)) {
492
434
  code = HardwareErrorCode.AppNotInstalled;
493
- } else if (isAppAlreadyInstalledError(err)) {
494
- code = HardwareErrorCode.AppAlreadyInstalled;
495
435
  } else if (isOutOfMemoryError(err)) {
496
436
  code = HardwareErrorCode.DeviceOutOfMemory;
497
- } else if (isDeviceNotOnboardedError(err)) {
498
- code = HardwareErrorCode.DeviceNotInitialized;
499
- } else if (isFirmwareMetadataError(err)) {
500
- code = HardwareErrorCode.LedgerFirmwareMetadataError;
501
437
  } else if (isNetworkError(err)) {
502
438
  code = HardwareErrorCode.NetworkError;
503
- } else if (isSecureChannelError(err)) {
504
- code = HardwareErrorCode.LedgerSecureChannelError;
505
439
  } else if (isDeviceDisconnectedError(err)) {
506
440
  code = HardwareErrorCode.DeviceDisconnected;
507
441
  } else if (isTimeoutError(err)) {
@@ -514,35 +448,11 @@ function mapLedgerError(err, opts) {
514
448
  }
515
449
  const errAppName = err && typeof err === "object" ? err.appName : void 0;
516
450
  const appName = errAppName ?? opts?.defaultAppName;
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;
451
+ return { code, message: enrichErrorMessage(code, originalMessage), appName };
532
452
  }
533
453
 
534
454
  // src/adapter/methods/allNetworkGetAddress.ts
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";
455
+ import { HardwareErrorCode as HardwareErrorCode2, failure, runAllNetworkGetAddress } from "@onekeyfe/hwk-adapter-core";
546
456
 
547
457
  // src/utils/sdkEventBus.ts
548
458
  var listeners = /* @__PURE__ */ new Set();
@@ -599,105 +509,57 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
599
509
  var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
600
510
  function createAllNetworkGetAddress({
601
511
  callChain,
602
- getChainFingerprint,
603
- retainOperation,
604
- errorToFailure,
605
- createCancelScope,
606
- releaseBundle
512
+ getChainFingerprint
607
513
  }) {
608
514
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
609
- debugLog("[LedgerAdapter][REQ]", {
610
- method: "allNetworkGetAddress",
611
- connectId,
612
- itemCount: params.bundle.length
613
- });
614
- const target = resolveHardwareOperationTarget(connectId, params.operationId, "ledger");
615
- if (!target.success) return target;
616
- const effectiveTargetId = target.payload.targetId ?? "";
617
- let releaseOperationRetention;
618
- try {
619
- releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
620
- } catch (error) {
621
- return errorToFailure(error);
622
- }
623
- const cancelScope = createCancelScope(
624
- ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
625
- );
626
- const installContext = {
627
- walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
628
- };
515
+ debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
516
+ const installContext = {};
629
517
  const commonParams = {
630
- autoInstallApp: params.autoInstallApp,
631
- operationId: target.payload.operationId,
632
- knownConnections: params.knownConnections,
633
- extra: params.extra,
634
- allowDeviceSelection: params.allowDeviceSelection,
635
- supportedTransports: params.supportedTransports
518
+ autoInstallApp: params.autoInstallApp
636
519
  };
637
520
  const chainFingerprints = /* @__PURE__ */ new Map();
638
- const order = params.bundle.map((_item, index) => index).sort(
639
- (a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
640
- );
641
- try {
642
- const ordered = await runAllNetworkGetAddress({
643
- connectId: effectiveTargetId,
644
- deviceId: _deviceId,
645
- params: { ...params, bundle: order.map((index) => params.bundle[index]) },
646
- normalizeItem: normalizeLedgerAllNetworkItem,
647
- buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
648
- callItem: async ({ method, chain, item }) => {
649
- if (cancelScope.signal.aborted)
650
- return buildAllNetworkCancelledFailure(cancelScope.signal);
651
- const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
652
- return callAllNetworkMethod(
653
- callChain,
654
- effectiveTargetId,
655
- itemDeviceId,
656
- method,
657
- item,
658
- commonParams,
659
- installContext
660
- );
661
- },
662
- attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
663
- getChainFingerprint,
664
- effectiveTargetId,
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,
665
534
  item,
666
- chain,
667
- payload,
668
- chainFingerprints,
669
- installContext,
670
- cancelScope.signal
671
- ),
672
- shouldAbortBundle: isTopLevelAllNetworkFailure,
673
- buildTopLevelFailure: (response) => {
674
- const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
675
- return failure(
676
- code,
677
- response.payload?.error ?? "All-network get-address aborted",
678
- response.payload?.params
679
- );
680
- }
681
- });
682
- let result = ordered;
683
- if (ordered.success) {
684
- const responses = [];
685
- ordered.payload.forEach((response, position) => {
686
- responses[order[position]] = response;
687
- });
688
- result = success(responses);
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
+ );
689
555
  }
690
- debugLog("[LedgerAdapter][RES]", {
691
- method: "allNetworkGetAddress",
692
- success: result.success,
693
- payload: result
694
- });
695
- return result;
696
- } finally {
697
- await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
698
- cancelScope.release();
699
- releaseOperationRetention?.();
700
- }
556
+ });
557
+ debugLog("[LedgerAdapter][RES]", {
558
+ method: "allNetworkGetAddress",
559
+ success: result.success,
560
+ payload: result
561
+ });
562
+ return result;
701
563
  };
702
564
  }
703
565
  function isTopLevelAllNetworkFailure(response) {
@@ -705,7 +567,7 @@ function isTopLevelAllNetworkFailure(response) {
705
567
  return false;
706
568
  }
707
569
  const code = response.payload?.code;
708
- return isWalletSafetyFailure(code) || isUserRefusal(code) || isConnectionLost(code);
570
+ return code === HardwareErrorCode2.DeviceMismatch || code === HardwareErrorCode2.UserAborted || code === HardwareErrorCode2.UserRejected;
709
571
  }
710
572
  function getItemDeviceId(item) {
711
573
  const { deviceId } = item;
@@ -735,18 +597,8 @@ function normalizeLedgerAllNetworkItem(method, item) {
735
597
  const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
736
598
  return coin ? { ...item, coin } : item;
737
599
  }
738
- async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
739
- const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
740
- if (!knownFingerprint && cancelSignal.aborted) {
741
- const cancelled = buildAllNetworkCancelledFailure(cancelSignal);
742
- return { ...item, success: false, payload: cancelled.payload };
743
- }
744
- const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
745
- getChainFingerprint,
746
- context.connection?.connectId ?? connectId,
747
- chain,
748
- context
749
- );
600
+ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
601
+ const fingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || await bootstrapChainFingerprint(getChainFingerprint, connectId, chain);
750
602
  if (!fingerprint) {
751
603
  return buildFingerprintBootstrapFailure(item, chain);
752
604
  }
@@ -767,8 +619,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
767
619
  }
768
620
  };
769
621
  }
770
- async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
771
- const response = await getChainFingerprint(connectId, chain, context);
622
+ async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
623
+ const response = await getChainFingerprint(connectId, chain);
772
624
  return response.success ? response.payload : "";
773
625
  }
774
626
  function buildFingerprintBootstrapFailure(item, chain) {
@@ -861,20 +713,6 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
861
713
  function formatDeviceMismatchError(expected, actual) {
862
714
  return `Wrong device: expected ${expected}, got ${actual}`;
863
715
  }
864
- var LOG_REDACTED_RESULT_KEYS = ["ufvk", "orchardFvk"];
865
- function isSigningMethod(method) {
866
- return /sign/i.test(method);
867
- }
868
- function redactResultForLog(result, method) {
869
- if (isSigningMethod(method)) return "[redacted]";
870
- if (!result || typeof result !== "object") return result;
871
- const keys = LOG_REDACTED_RESULT_KEYS.filter((key) => key in result);
872
- if (!keys.length) return result;
873
- return { ...result, ...Object.fromEntries(keys.map((key) => [key, "[redacted]"])) };
874
- }
875
- function isLostConnectionError(err) {
876
- return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
877
- }
878
716
  var BTC_HIGH_INDEX_THRESHOLD = 100;
879
717
  function btcAccountIndexFromPath(path) {
880
718
  const segments = path.replace(/^m\//, "").split("/");
@@ -886,35 +724,9 @@ function btcAccountIndexFromPath(path) {
886
724
  var _LedgerAdapter = class _LedgerAdapter {
887
725
  constructor(connector, options) {
888
726
  this.vendor = "ledger";
889
- // Cancel frees the DMK action and its intent-queue slot, but cannot retract a
890
- // confirmation screen the device is already showing.
891
- this.cancelCapability = "stops-waiting";
892
727
  this.emitter = new TypedEventEmitter();
893
- this._operations = new OperationRegistry({
894
- vendor: "ledger",
895
- onEnded: (operation, reason) => {
896
- this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
897
- this._pendingOperationBindings.delete(operation.operationId);
898
- this.emitter.emit(SDK.OPERATION_ENDED, {
899
- type: SDK.OPERATION_ENDED,
900
- payload: { operationId: operation.operationId, reason }
901
- });
902
- if (reason === "timeout") {
903
- void this._releaseOperationConnection(operation);
904
- }
905
- }
906
- });
907
728
  this._discoveredDevices = /* @__PURE__ */ new Map();
908
729
  this._sessions = /* @__PURE__ */ new Map();
909
- // An operation's BLE pick is saved by its first call that gets past the wallet check.
910
- this._pendingOperationBindings = /* @__PURE__ */ new Map();
911
- // A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
912
- // through an unlock retry; any other failure drops it with its session.
913
- this._pendingPickBindings = /* @__PURE__ */ new Map();
914
- // Transport each session was opened on, by sessionId. The adapter-wide
915
- // `_activeConnectionType` moves with every discovery and can go stale.
916
- this._sessionTransports = /* @__PURE__ */ new Map();
917
- this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
918
730
  this._uiRegistry = new UiRequestRegistry();
919
731
  // BTC App rejects account index >= 100 unless display=true. Cached per
920
732
  // adapter instance: first 100+ path asks the user once via UI request,
@@ -928,36 +740,21 @@ var _LedgerAdapter = class _LedgerAdapter {
928
740
  this._deviceAuthenticityQueueTail = Promise.resolve();
929
741
  // Shared across concurrent callers — only `cancel()` aborts.
930
742
  this._doConnectAbortController = null;
931
- this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
932
- this._connectorIdleWaiters = /* @__PURE__ */ new Set();
933
- this._resetPromise = null;
934
- this._stateGeneration = 0;
935
- this._connectorTeardownTail = Promise.resolve();
936
- this._pendingConnectorTeardowns = 0;
937
- this._activeOperationJobs = /* @__PURE__ */ new Set();
938
- this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
939
743
  this._installProgressLastEmittedValue = -Infinity;
940
744
  this.allNetworkGetAddress = createAllNetworkGetAddress({
941
745
  callChain: this.callChain.bind(this),
942
- getChainFingerprint: async (connectId, chain, context) => {
943
- try {
944
- const fingerprint = await this._computeChainFingerprint(
945
- chain,
946
- (method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
947
- );
948
- return success2(fingerprint);
949
- } catch (error) {
950
- return this.errorToFailure(error);
951
- }
952
- },
953
- retainOperation: (operationId) => this._operations.retain(operationId),
954
- errorToFailure: (error) => this.errorToFailure(error),
955
- createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
956
- releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
746
+ getChainFingerprint: (connectId, chain) => this.getChainFingerprint(connectId, "", chain)
957
747
  });
958
748
  // ---------------------------------------------------------------------------
959
749
  // Private helpers
960
750
  // ---------------------------------------------------------------------------
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
+ */
961
758
  // Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
962
759
  this._connectingPromise = null;
963
760
  // ---------------------------------------------------------------------------
@@ -973,12 +770,6 @@ var _LedgerAdapter = class _LedgerAdapter {
973
770
  });
974
771
  };
975
772
  this.deviceDisconnectHandler = (data) => {
976
- const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
977
- if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
978
- this._pendingOperationDisconnects.add(activeOperation.operationId);
979
- } else {
980
- this._operations.endByConnectionKey(data.connectId, "disconnect");
981
- }
982
773
  this._discoveredDevices.delete(data.connectId);
983
774
  this._sessions.delete(data.connectId);
984
775
  this.emitter.emit(DEVICE.DISCONNECT, {
@@ -987,8 +778,10 @@ var _LedgerAdapter = class _LedgerAdapter {
987
778
  });
988
779
  };
989
780
  // Forward connector `ui-event` to the public hw.emitter so consumers only
990
- // need to subscribe in one place. The AppInstallProgress variant re-keys
991
- // sessionId to connectId via `_sessions`, and drops if no mapping exists.
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.
992
785
  this.uiEventForwarder = (event) => {
993
786
  if (event.type === EConnectorInteraction.AppInstallProgress) {
994
787
  let connectId;
@@ -1033,30 +826,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1033
826
  this._jobQueue = new DeviceJobQueue();
1034
827
  this.registerEventListeners();
1035
828
  }
1036
- _discardPendingBinding(owner, status = "cancelled") {
1037
- const pending = owner?.pendingBinding;
1038
- if (!owner || !pending) return;
1039
- owner.pendingBinding = void 0;
1040
- if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
1041
- }
1042
- _finishBleBinding(status) {
1043
- const selectionRequestId = this._bindingSelectionRequestId;
1044
- this._bindingSelectionRequestId = void 0;
1045
- if (selectionRequestId) emitDeviceBindingStatus(this.emitter, selectionRequestId, status);
1046
- }
1047
- _isBleConnection() {
1048
- return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
1049
- }
1050
829
  // Transport
1051
830
  get activeTransport() {
1052
- return this._isBleConnection() ? "ble" : "hid";
831
+ return isLedgerBleConnectionType(this.connector.connectionType) ? "ble" : "hid";
1053
832
  }
1054
833
  getAvailableTransports() {
1055
- if (this.connector.availableTransports) {
1056
- return this.connector.availableTransports.map(
1057
- (transport) => transport === "ble" ? "ble" : "hid"
1058
- );
1059
- }
1060
834
  return this.activeTransport ? [this.activeTransport] : [];
1061
835
  }
1062
836
  // Connector is bound at construction; switching requires a new adapter.
@@ -1073,42 +847,21 @@ var _LedgerAdapter = class _LedgerAdapter {
1073
847
  * The next operation will re-discover and re-connect automatically.
1074
848
  */
1075
849
  resetState() {
1076
- void this._resetStateAndDisconnectSessions();
1077
- }
1078
- _resetStateAndDisconnectSessions() {
1079
- if (this._resetPromise) return this._resetPromise;
1080
- const sessionIds = new Set(this._sessions.values());
1081
- this._stateGeneration += 1;
1082
- this._finishBleBinding("cancelled");
1083
- this._operations.endAll("runtime-reset");
1084
- this._doConnectAbortController?.abort();
1085
850
  this._discoveredDevices.clear();
1086
851
  this._sessions.clear();
1087
- this._sessionTransports.clear();
1088
- this._pendingOperationBindings.clear();
1089
- this._pendingPickBindings.clear();
1090
- this._selectedBleReconnectTargets.clear();
1091
852
  this._connectingPromise = null;
1092
- this._doConnectAbortController = null;
1093
853
  this._uiRegistry.reset();
1094
854
  this._jobQueue.clear();
1095
855
  this._btcHighIndexConfirmedThisSession = false;
1096
- const resetPromise = this._runConnectorTeardown(async () => {
1097
- for (const sessionId of sessionIds) {
1098
- await this.connector.disconnect(sessionId).catch(() => void 0);
1099
- }
1100
- });
1101
- this._resetPromise = resetPromise;
1102
- return resetPromise.finally(() => {
1103
- if (this._resetPromise === resetPromise) {
1104
- this._resetPromise = null;
1105
- }
1106
- });
1107
856
  }
1108
857
  async dispose() {
1109
- await this._resetStateAndDisconnectSessions();
858
+ this._uiRegistry.reset();
859
+ this._jobQueue.clear();
1110
860
  this.unregisterEventListeners();
1111
861
  this.connector.reset();
862
+ this._discoveredDevices.clear();
863
+ this._sessions.clear();
864
+ this._btcHighIndexConfirmedThisSession = false;
1112
865
  this.emitter.removeAllListeners();
1113
866
  }
1114
867
  uiResponse(response) {
@@ -1118,32 +871,17 @@ var _LedgerAdapter = class _LedgerAdapter {
1118
871
  // Device management
1119
872
  // ---------------------------------------------------------------------------
1120
873
  async searchDevices(options) {
1121
- return this._searchDevices(options);
1122
- }
1123
- async _searchDevices(options, signal) {
1124
874
  debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
1125
875
  try {
1126
876
  if (options?.resetSession) {
1127
- await this._resetStateAndDisconnectSessions();
1128
- } else {
1129
- await this._connectorTeardownTail;
1130
- }
1131
- await this._ensureDevicePermission(void 0, void 0, signal);
1132
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1133
- const stateGeneration = this._stateGeneration;
1134
- const devices = await this.connector.searchDevices(
1135
- options?.transportType ? {
1136
- transportType: options.transportType,
1137
- waitForAll: options.waitForAllTransports
1138
- } : void 0
1139
- );
1140
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1141
- if (stateGeneration !== this._stateGeneration) {
1142
- throw createHwkError({
1143
- code: HardwareErrorCode3.UserAborted,
1144
- message: "Ledger discovery was reset"
1145
- });
877
+ this._doConnectAbortController?.abort();
878
+ this._sessions.clear();
879
+ this._connectingPromise = null;
880
+ this._doConnectAbortController = null;
881
+ this._btcHighIndexConfirmedThisSession = false;
1146
882
  }
883
+ await this._ensureDevicePermission();
884
+ const devices = await this.connector.searchDevices();
1147
885
  this._discoveredDevices.clear();
1148
886
  for (const d of devices) {
1149
887
  if (d.connectId) {
@@ -1151,7 +889,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1151
889
  }
1152
890
  }
1153
891
  if (this._discoveredDevices.size === 0) {
1154
- await this._ensureDevicePermission(void 0, void 0, signal);
892
+ await this._ensureDevicePermission();
1155
893
  }
1156
894
  const result = Array.from(this._discoveredDevices.values());
1157
895
  debugLog("[LedgerAdapter][RES]", {
@@ -1170,263 +908,41 @@ var _LedgerAdapter = class _LedgerAdapter {
1170
908
  throw err;
1171
909
  }
1172
910
  }
1173
- async searchDeviceTargets(options) {
1174
- const devices = await this.searchDevices(options);
1175
- return devices.map((device) => toPhysicalDeviceSearchTarget("ledger", device));
1176
- }
1177
911
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
1178
- async _evictAllSessions(preserveOperationId) {
1179
- this._operations.endAll("explicit", preserveOperationId);
912
+ async _evictAllSessions() {
1180
913
  if (this._sessions.size === 0) return;
1181
914
  const stale = [...this._sessions.values()];
1182
915
  this._sessions.clear();
1183
- for (const sid of stale) this._sessionTransports.delete(sid);
1184
- await this._runConnectorTeardown(async () => {
1185
- for (const sid of stale) {
1186
- try {
1187
- await this.connector.disconnect(sid);
1188
- } catch {
1189
- }
916
+ for (const sid of stale) {
917
+ try {
918
+ await this.connector.disconnect(sid);
919
+ } catch {
1190
920
  }
1191
- });
921
+ }
1192
922
  }
1193
923
  static _createDeviceBusyError(method) {
1194
924
  return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
1195
925
  code: HardwareErrorCode3.DeviceBusy
1196
926
  });
1197
927
  }
1198
- async connectDevice(searchTargetId) {
1199
- try {
1200
- return await this._jobQueue.enqueue(
1201
- searchTargetId || "__ledger_connect__",
1202
- async (signal) => {
1203
- const connected = await this._connectTarget(searchTargetId, void 0, signal);
1204
- if (!connected.success) return connected;
1205
- return this._createOperation(searchTargetId, connected.payload);
1206
- },
1207
- {
1208
- label: "connectDevice",
1209
- rejectIfBusy: true,
1210
- busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
1211
- }
1212
- );
1213
- } catch (error) {
1214
- return this.errorToFailure(error);
1215
- }
1216
- }
1217
- /** Binds the picked BLE device; with a recorded wallet identity it must match first. */
1218
- async bindBleDevice(params) {
1219
- const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
1220
- try {
1221
- return await this._jobQueue.enqueue(
1222
- "__ledger_bind_ble__",
1223
- async (signal) => {
1224
- if (!this.getAvailableTransports().includes("ble")) {
1225
- throw createHwkError({
1226
- code: HardwareErrorCode3.TransportNotAvailable,
1227
- message: "Ledger Bluetooth transport is not available"
1228
- });
1229
- }
1230
- this._activeConnectionType = "ble";
1231
- await this._ensureDevicePermission(void 0, void 0, signal);
1232
- const attempt = {
1233
- extra: params.extra,
1234
- bindingReason: "manual-rebind",
1235
- deferBindingSave: Boolean(identity)
1236
- };
1237
- try {
1238
- const connectId = await this._connectFirstOrSelect(
1239
- [],
1240
- void 0,
1241
- true,
1242
- void 0,
1243
- attempt,
1244
- signal
1245
- );
1246
- const pending = attempt.pendingBinding;
1247
- if (identity && pending) {
1248
- attempt.pendingBinding = void 0;
1249
- const sessionId = this._sessions.get(connectId);
1250
- if (!sessionId) {
1251
- throw createHwkError({
1252
- code: HardwareErrorCode3.DeviceDisconnected,
1253
- message: "Selected Ledger connection ended"
1254
- });
1255
- }
1256
- const fingerprint = await this._computeChainFingerprint(
1257
- identity.chain,
1258
- (method, callParams) => this._runConnectorCall(
1259
- connectId,
1260
- method,
1261
- callParams,
1262
- signal,
1263
- void 0,
1264
- void 0,
1265
- { autoInstallApp: true },
1266
- { connection: { connectId, sessionId } }
1267
- )
1268
- );
1269
- if (fingerprint !== identity.value) {
1270
- await this._dropSession(connectId, signal);
1271
- throw createHwkError({
1272
- code: HardwareErrorCode3.DeviceMismatch,
1273
- message: formatDeviceMismatchError(identity.value, fingerprint)
1274
- });
1275
- }
1276
- await this._saveSelectedBleBinding(
1277
- connectId,
1278
- pending.requestId,
1279
- attempt,
1280
- void 0,
1281
- signal,
1282
- identity
1283
- );
1284
- }
1285
- if (!attempt.bindingSaved) {
1286
- await this._dropSession(connectId, signal);
1287
- throw createHwkError({
1288
- code: HardwareErrorCode3.UnknownError,
1289
- message: "Bluetooth binding could not be saved",
1290
- origin: "host"
1291
- });
1292
- }
1293
- return success2(connectId);
1294
- } catch (error) {
1295
- this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1296
- throw error;
1297
- }
1298
- },
1299
- {
1300
- label: "bindBleDevice",
1301
- rejectIfBusy: true,
1302
- busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
1303
- }
1304
- );
1305
- } catch (error) {
1306
- return this.errorToFailure(error);
1307
- }
1308
- }
1309
- async acquireOperation(connectId, context) {
1310
- try {
1311
- return await this._jobQueue.enqueue(
1312
- connectId || "__ledger_acquire__",
1313
- async (signal) => {
1314
- const transport = this._isBleConnection() ? "ble" : "usb";
1315
- const hint = context.knownConnections?.find(
1316
- (connection) => connection.transport === transport
1317
- );
1318
- const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
1319
- await this._ensureDevicePermission(target, void 0, signal);
1320
- const attempt = {
1321
- ...context,
1322
- extra: context.extra ? { ...context.extra } : void 0,
1323
- // The operation's calls decide whether the pick is the right wallet.
1324
- deferBindingSave: true
1325
- };
1326
- try {
1327
- const resolvedConnectId = await this.ensureConnected(
1328
- target,
1329
- signal,
1330
- true,
1331
- void 0,
1332
- attempt
1333
- );
1334
- _LedgerAdapter._throwIfAborted(signal);
1335
- const result = this._createOperation(connectId, resolvedConnectId);
1336
- if (result.success && attempt.pendingBinding) {
1337
- this._pendingOperationBindings.set(result.payload, attempt);
1338
- }
1339
- return result;
1340
- } catch (error) {
1341
- this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
1342
- throw error;
1343
- }
1344
- },
1345
- {
1346
- label: "acquireOperation",
1347
- rejectIfBusy: true,
1348
- busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
1349
- }
1350
- );
1351
- } catch (error) {
1352
- return this.errorToFailure(error);
1353
- }
1354
- }
1355
- _createOperation(searchTargetId, resolvedConnectId) {
1356
- this._operations.endByConnectionKey(resolvedConnectId, "explicit");
1357
- const sessionId = this._sessions.get(resolvedConnectId);
1358
- if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
1359
- const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
1360
- const device = this._discoveredDevices.get(resolvedConnectId) ?? {
1361
- vendor: "ledger",
1362
- model: "unknown",
1363
- firmwareVersion: "",
1364
- deviceId: "",
1365
- connectId: resolvedConnectId,
1366
- connectionType
1367
- };
1368
- const operation = this._operations.create({
1369
- searchTargetId,
1370
- connectId: resolvedConnectId,
1371
- device,
1372
- connectionType,
1373
- connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
1374
- });
1375
- return success2(operation.operationId);
1376
- }
1377
- async _connectTarget(connectId, preserveOperationId, signal) {
928
+ async connectDevice(connectId) {
1378
929
  debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
1379
930
  try {
1380
- this._assertConnectorReady("connectDevice");
1381
- const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
1382
- if (discoveredType === "usb" || discoveredType === "ble") {
1383
- this._activeConnectionType = discoveredType;
1384
- }
1385
- if (this._isBleConnection() && !connectId) {
931
+ if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
1386
932
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
1387
933
  code: HardwareErrorCode3.DeviceNotFound
1388
934
  });
1389
935
  }
1390
- await this._ensureDevicePermission(connectId, void 0, signal);
1391
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1392
- const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
1393
- if (!isMultiTransport && this._isBleConnection()) {
1394
- const previousSessionId = this._sessions.get(connectId);
1395
- this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
1396
- if (previousSessionId) {
1397
- this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
1398
- this._sessions.delete(connectId);
1399
- await this.connector.disconnect(previousSessionId).catch(() => void 0);
1400
- }
1401
- } else {
1402
- await this._evictAllSessions(preserveOperationId);
1403
- }
1404
- if (signal) _LedgerAdapter._throwIfAborted(signal);
1405
- const stateGeneration = this._stateGeneration;
1406
- const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
1407
- let session;
1408
- this._connectingConnectId = connectId;
1409
- try {
1410
- session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
1411
- transportType: this._activeConnectionType ?? "usb"
1412
- }) : await this.connector.connect(connectId);
1413
- if (signal?.aborted || stateGeneration !== this._stateGeneration) {
1414
- await this.connector.disconnect(session.sessionId).catch(() => void 0);
1415
- throw Object.assign(new Error("Ledger connection aborted"), {
1416
- code: HardwareErrorCode3.UserAborted
1417
- });
1418
- }
1419
- } finally {
1420
- if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
1421
- releaseOperation();
936
+ if (!isLedgerBleConnectionType(this.connector.connectionType)) {
937
+ await this._evictAllSessions();
1422
938
  }
1423
- const resolvedConnectId = session.deviceInfo?.connectId || connectId;
1424
- this._sessions.set(resolvedConnectId, session.sessionId);
1425
- this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
939
+ await this._ensureDevicePermission(connectId);
940
+ const session = await this.connector.connect(connectId);
941
+ this._sessions.set(connectId, session.sessionId);
1426
942
  if (session.deviceInfo) {
1427
- this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
943
+ this._discoveredDevices.set(connectId, session.deviceInfo);
1428
944
  }
1429
- const result = success2(resolvedConnectId);
945
+ const result = success(connectId);
1430
946
  debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
1431
947
  return result;
1432
948
  } catch (err) {
@@ -1439,73 +955,30 @@ var _LedgerAdapter = class _LedgerAdapter {
1439
955
  return failureResult;
1440
956
  }
1441
957
  }
1442
- async releaseOperation(operationId) {
1443
- const operation = this._operations.findActive(operationId);
1444
- if (operation) this._cancelOperationWork(operation);
1445
- const endedOperation = this._operations.release(operationId);
1446
- if (!endedOperation) return;
1447
- const { connectId } = endedOperation;
958
+ async disconnectDevice(connectId) {
1448
959
  debugLog("[LedgerAdapter][REQ]", {
1449
- method: "releaseOperation",
960
+ method: "disconnectDevice",
1450
961
  connectId,
1451
962
  params: { connectId }
1452
963
  });
1453
964
  try {
1454
- await this._releaseOperationConnection(endedOperation);
1455
- debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
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 });
1456
971
  } catch (err) {
1457
972
  const e = err;
1458
973
  debugLog("[LedgerAdapter][RES]", {
1459
- method: "releaseOperation",
974
+ method: "disconnectDevice",
1460
975
  success: false,
1461
976
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1462
977
  });
1463
978
  throw err;
1464
979
  }
1465
980
  }
1466
- /**
1467
- * Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
1468
- * that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
1469
- */
1470
- _cancelOperationWork(operation) {
1471
- const { operationId } = operation;
1472
- const reason = createHwkError({
1473
- code: HardwareErrorCode3.OperationEnded,
1474
- message: "Ledger operation was released",
1475
- params: { operationId, reason: "explicit" }
1476
- });
1477
- const queueKey = ledgerQueueKey({ operationId });
1478
- const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
1479
- this._jobQueue.cancelActiveAndPending(queueKey, reason);
1480
- if (ownsRunningCall) this._uiRegistry.cancel(void 0, void 0, operationId);
1481
- }
1482
- async _releaseOperationConnection(operation) {
1483
- const sessionIds = /* @__PURE__ */ new Set();
1484
- for (const [connectId, sessionId] of this._sessions) {
1485
- if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
1486
- this._sessions.delete(connectId);
1487
- sessionIds.add(sessionId);
1488
- }
1489
- }
1490
- for (const sessionId of sessionIds) {
1491
- await this._runConnectorTeardown(
1492
- () => this.connector.disconnect(sessionId).catch(() => void 0)
1493
- );
1494
- }
1495
- }
1496
- async _releaseLostOperationConnection(operationId) {
1497
- const endedOperation = this._operations.end(operationId, "disconnect");
1498
- if (!endedOperation) return;
1499
- this._discoveredDevices.delete(endedOperation.connectId);
1500
- await this._releaseOperationConnection(endedOperation);
1501
- }
1502
- async getDeviceInfo(connectIdOrOperationId, deviceId) {
1503
- let connectId;
1504
- try {
1505
- connectId = isHardwareOperationId(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
1506
- } catch (error) {
1507
- return this.errorToFailure(error);
1508
- }
981
+ async getDeviceInfo(connectId, deviceId) {
1509
982
  debugLog("[LedgerAdapter][REQ]", {
1510
983
  method: "getDeviceInfo",
1511
984
  connectId,
@@ -1515,7 +988,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1515
988
  await this._ensureDevicePermission(connectId, deviceId);
1516
989
  const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
1517
990
  if (cached) {
1518
- const result = success2(cached);
991
+ const result = success(cached);
1519
992
  debugLog("[LedgerAdapter][RES]", {
1520
993
  method: "getDeviceInfo",
1521
994
  success: true,
@@ -1540,19 +1013,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1540
1013
  success: false,
1541
1014
  error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1542
1015
  });
1543
- return this.errorToFailure(err);
1016
+ throw err;
1544
1017
  }
1545
1018
  }
1546
- /** A bundle's BLE pick that no item got past the wallet check is not kept. */
1547
- async _dropUncheckedBundlePick(context, signal) {
1548
- const { connection } = context;
1549
- const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
1550
- if (!connection || !owner) return;
1551
- this._pendingPickBindings.delete(connection.connectId);
1552
- this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
1553
- if (this._sessions.get(connection.connectId) === connection.sessionId) {
1554
- await this._dropSession(connection.connectId, signal);
1555
- }
1019
+ getSupportedChains() {
1020
+ return ["evm", "btc", "sol", "tron"];
1556
1021
  }
1557
1022
  // ---------------------------------------------------------------------------
1558
1023
  // Chain call helper
@@ -1572,7 +1037,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1572
1037
  commonParams,
1573
1038
  installContext
1574
1039
  );
1575
- return success2(result);
1040
+ return success(result);
1576
1041
  } catch (err) {
1577
1042
  return this.errorToFailure(err);
1578
1043
  }
@@ -1588,25 +1053,13 @@ var _LedgerAdapter = class _LedgerAdapter {
1588
1053
  if (params && typeof params === "object") {
1589
1054
  const {
1590
1055
  autoInstallApp,
1591
- operationId,
1592
1056
  passphraseState: _passphraseState,
1593
1057
  useEmptyPassphrase: _useEmptyPassphrase,
1594
- knownConnections,
1595
- extra,
1596
- allowDeviceSelection,
1597
- supportedTransports,
1598
1058
  ...rest
1599
1059
  } = params;
1600
1060
  return {
1601
1061
  commonParams: {
1602
- autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
1603
- operationId: typeof operationId === "string" ? operationId : void 0,
1604
- ...pickConnectionContext({
1605
- knownConnections,
1606
- extra,
1607
- allowDeviceSelection,
1608
- supportedTransports
1609
- })
1062
+ autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
1610
1063
  },
1611
1064
  rest
1612
1065
  };
@@ -1782,33 +1235,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1782
1235
  );
1783
1236
  }
1784
1237
  // ---------------------------------------------------------------------------
1785
- // Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
1786
- // ---------------------------------------------------------------------------
1787
- zcashGetFullViewingKey(connectId, deviceId, params) {
1788
- return this.callChainWithMergedParams(
1789
- connectId,
1790
- deviceId,
1791
- "zcash",
1792
- "zcashGetFullViewingKey",
1793
- params
1794
- );
1795
- }
1796
- zcashGetShieldedAddress(connectId, deviceId, params) {
1797
- return this.callChainWithMergedParams(
1798
- connectId,
1799
- deviceId,
1800
- "zcash",
1801
- "zcashGetShieldedAddress",
1802
- params
1803
- );
1804
- }
1805
- // ---------------------------------------------------------------------------
1806
- // App management: OS-level app install/list, no fingerprint or chain dispatch.
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.
1807
1241
  // ---------------------------------------------------------------------------
1808
1242
  async installApp(connectId, appName) {
1809
1243
  try {
1810
1244
  await this.connectorCall(connectId, "installApp", { appName });
1811
- return success2(void 0);
1245
+ return success(void 0);
1812
1246
  } catch (err) {
1813
1247
  return this.errorToFailure(err);
1814
1248
  }
@@ -1816,7 +1250,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1816
1250
  async listInstalledApps(connectId) {
1817
1251
  try {
1818
1252
  const result = await this.connectorCall(connectId, "listInstalledApps", {});
1819
- return success2(result);
1253
+ return success(result);
1820
1254
  } catch (err) {
1821
1255
  return this.errorToFailure(err);
1822
1256
  }
@@ -1825,7 +1259,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1825
1259
  async listInstalledNames(connectId) {
1826
1260
  try {
1827
1261
  const result = await this.connectorCall(connectId, "listInstalledNames", {});
1828
- return success2(result);
1262
+ return success(result);
1829
1263
  } catch (err) {
1830
1264
  return this.errorToFailure(err);
1831
1265
  }
@@ -1833,7 +1267,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1833
1267
  async listAvailableApps(connectId) {
1834
1268
  try {
1835
1269
  const result = await this.connectorCall(connectId, "listAvailableApps", {});
1836
- return success2(result);
1270
+ return success(result);
1837
1271
  } catch (err) {
1838
1272
  return this.errorToFailure(err);
1839
1273
  }
@@ -1841,7 +1275,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1841
1275
  async getLedgerFirmwareVersion(connectId) {
1842
1276
  try {
1843
1277
  const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
1844
- return success2(result);
1278
+ return success(result);
1845
1279
  } catch (err) {
1846
1280
  return this.errorToFailure(err);
1847
1281
  }
@@ -1849,7 +1283,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1849
1283
  async getLedgerDeviceInfo(connectId) {
1850
1284
  try {
1851
1285
  const result = await this.connectorCall(connectId, "getDeviceInfo", {});
1852
- return success2(result);
1286
+ return success(result);
1853
1287
  } catch (err) {
1854
1288
  return this.errorToFailure(err);
1855
1289
  }
@@ -1889,11 +1323,11 @@ var _LedgerAdapter = class _LedgerAdapter {
1889
1323
  );
1890
1324
  }
1891
1325
  await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
1892
- await this._resetStateAndDisconnectSessions();
1326
+ this.resetState();
1893
1327
  }
1894
1328
  const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
1895
1329
  if (!result.isGenuine) {
1896
- return success2({
1330
+ return success({
1897
1331
  vendor: "ledger",
1898
1332
  verified: false
1899
1333
  });
@@ -1904,7 +1338,7 @@ var _LedgerAdapter = class _LedgerAdapter {
1904
1338
  `Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
1905
1339
  );
1906
1340
  }
1907
- return success2({
1341
+ return success({
1908
1342
  vendor: "ledger",
1909
1343
  verified: result.isGenuine,
1910
1344
  deviceId: result.deviceId
@@ -1915,10 +1349,10 @@ var _LedgerAdapter = class _LedgerAdapter {
1915
1349
  if (relayUrl) {
1916
1350
  try {
1917
1351
  await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
1918
- await this._resetStateAndDisconnectSessions();
1352
+ this.resetState();
1919
1353
  } catch {
1920
1354
  this.connector.reset();
1921
- await this._resetStateAndDisconnectSessions();
1355
+ this.resetState();
1922
1356
  }
1923
1357
  }
1924
1358
  }
@@ -1930,20 +1364,6 @@ var _LedgerAdapter = class _LedgerAdapter {
1930
1364
  this.emitter.off(event, listener);
1931
1365
  }
1932
1366
  cancel(connectId) {
1933
- const namedOperationIsLive = (id) => {
1934
- try {
1935
- this._operations.resolve(id);
1936
- return true;
1937
- } catch {
1938
- return false;
1939
- }
1940
- };
1941
- if (isHardwareOperationId(connectId) && !namedOperationIsLive(connectId)) {
1942
- debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
1943
- connectId
1944
- });
1945
- return;
1946
- }
1947
1367
  const userAbortReason = Object.assign(new Error("User aborted operation"), {
1948
1368
  code: HardwareErrorCode3.UserAborted,
1949
1369
  _tag: ERROR_TAG.UserAborted
@@ -1954,48 +1374,14 @@ var _LedgerAdapter = class _LedgerAdapter {
1954
1374
  this._lastCancelReason = void 0;
1955
1375
  }
1956
1376
  }, 2e3);
1957
- const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
1958
- let operationId;
1959
- if (isHardwareOperationId(connectId)) {
1960
- operationId = connectId;
1961
- } else if (!connectId && isHardwareOperationId(activeJobId)) {
1962
- operationId = activeJobId;
1963
- }
1964
- let resolvedConnectId = connectId;
1965
- if (operationId) {
1966
- try {
1967
- resolvedConnectId = this._operations.resolve(operationId).connectId;
1968
- } catch {
1969
- resolvedConnectId = void 0;
1970
- }
1971
- }
1972
- const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
1973
- const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
1974
- if (!connectId) {
1975
- this._uiRegistry.cancel();
1976
- } else if (pendingOperationId) {
1977
- this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
1978
- }
1979
- this._finishBleBinding("cancelled");
1980
- if (!connectId) this._pendingOperationBindings.clear();
1981
- else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
1982
- const queueKeys = /* @__PURE__ */ new Set();
1983
- if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
1984
- if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
1985
- if (queueKeys.size) {
1986
- let cancelledAnyJob = false;
1987
- for (const key of queueKeys) {
1988
- cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
1989
- }
1990
- debugLog("[LedgerAdapter] cancel routed to queue keys", {
1991
- queueKeys: [...queueKeys],
1992
- cancelledAnyJob
1993
- });
1377
+ this._uiRegistry.cancel();
1378
+ if (connectId) {
1379
+ this._jobQueue.cancelActiveAndPending(connectId, userAbortReason);
1994
1380
  } else {
1995
1381
  this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
1996
1382
  }
1997
- if (resolvedConnectId) {
1998
- const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
1383
+ if (connectId) {
1384
+ const sessionId = this._sessions.get(connectId) ?? connectId;
1999
1385
  void this.connector.cancel(sessionId);
2000
1386
  } else {
2001
1387
  for (const sid of this._sessions.values()) void this.connector.cancel(sid);
@@ -2003,86 +1389,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2003
1389
  if (this._connectingPromise) {
2004
1390
  this._doConnectAbortController?.abort(userAbortReason);
2005
1391
  }
2006
- const connectingConnectId = this._connectingConnectId;
2007
- if (connectingConnectId) void this.connector.cancel(connectingConnectId);
2008
1392
  }
2009
1393
  // ---------------------------------------------------------------------------
2010
1394
  // Chain fingerprint
2011
1395
  // ---------------------------------------------------------------------------
2012
- /** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
2013
1396
  async getChainFingerprint(connectId, deviceId, chain) {
2014
1397
  try {
2015
1398
  const fingerprint = await this._computeChainFingerprint(
2016
1399
  chain,
2017
1400
  (method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
2018
1401
  );
2019
- if (deviceId) {
2020
- if (fingerprint !== deviceId) {
2021
- return failure2(
2022
- HardwareErrorCode3.DeviceMismatch,
2023
- formatDeviceMismatchError(deviceId, fingerprint)
2024
- );
2025
- }
2026
- }
2027
- return success2(fingerprint);
1402
+ return success(fingerprint);
2028
1403
  } catch (err) {
2029
1404
  debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
2030
1405
  return this.errorToFailure(err);
2031
1406
  }
2032
1407
  }
2033
- /** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
2034
- async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
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 };
2035
1414
  try {
2036
- const outcome = await requestSaveDeviceBinding(
2037
- this.emitter,
2038
- this._uiRegistry,
2039
- {
2040
- selectionRequestId,
2041
- connection: { transport: "ble", connectId },
2042
- ...identity ? { identity } : {},
2043
- extra: context?.extra,
2044
- operationId
2045
- },
2046
- signal
1415
+ const fingerprint = await this._computeChainFingerprint(
1416
+ chain,
1417
+ (method, params) => this._callConnector(sessionId, method, params)
2047
1418
  );
2048
- if (context) context.bindingSaved = outcome.saved;
2049
- if (!outcome.saved) {
2050
- debugLog("[LedgerAdapter] BLE binding not persisted by host", {
2051
- connectId,
2052
- reason: outcome.reason
2053
- });
1419
+ if (fingerprint === deviceId) {
1420
+ return { success: true };
2054
1421
  }
2055
- } catch (error) {
2056
- await this._dropSession(connectId, signal);
2057
- throw error;
2058
- } finally {
2059
- if (this._bindingSelectionRequestId === selectionRequestId) {
2060
- this._bindingSelectionRequestId = void 0;
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 };
2061
1427
  }
1428
+ throw err;
2062
1429
  }
2063
1430
  }
2064
- async _dropSession(connectId, signal) {
2065
- const sessionId = this._sessions.get(connectId);
2066
- this._sessions.delete(connectId);
2067
- if (!sessionId) return;
2068
- this._sessionTransports.delete(sessionId);
2069
- const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
2070
- () => void 0
2071
- );
2072
- if (!signal.aborted) await teardown;
2073
- }
2074
- /** Verify on the acquired session without re-entering the job queue. */
2075
- async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
2076
- if (!deviceId) return { success: true };
2077
- const fingerprint = await this._computeChainFingerprint(
2078
- chain,
2079
- (method, params) => this._callConnector(sessionId, method, params)
2080
- );
2081
- if (fingerprint === deviceId) {
2082
- return { success: true };
2083
- }
2084
- return { success: false, expected: deviceId, actual: fingerprint };
2085
- }
2086
1431
  /**
2087
1432
  * Compute the chain fingerprint via a caller-supplied call strategy.
2088
1433
  *
@@ -2110,20 +1455,11 @@ var _LedgerAdapter = class _LedgerAdapter {
2110
1455
  address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
2111
1456
  } else if (chain === "tron") {
2112
1457
  address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
2113
- } else if (chain === "zcash") {
2114
- address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
2115
1458
  } else {
2116
1459
  throw new Error(`Unsupported chain for fingerprint: ${chain}`);
2117
1460
  }
2118
1461
  return deriveDeviceFingerprint(address);
2119
1462
  }
2120
- /**
2121
- * Operation owning the running job, so a mid-call UI request can name it.
2122
- * Undefined at cold start when no operation owns the job.
2123
- */
2124
- _activeOperationId() {
2125
- return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
2126
- }
2127
1463
  // Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
2128
1464
  // The user must press Confirm after unlocking, which triggers a search retry.
2129
1465
  // If `signal` is provided, an abort cancels the pending UI request so the
@@ -2133,18 +1469,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2133
1469
  if (signal?.aborted) {
2134
1470
  _LedgerAdapter._throwIfAborted(signal);
2135
1471
  }
2136
- const operationId = this._activeOperationId();
2137
1472
  const waitPromise = this._uiRegistry.wait(
2138
- UI_REQUEST.REQUEST_DEVICE_CONNECT,
2139
- { operationId }
1473
+ UI_REQUEST.REQUEST_DEVICE_CONNECT
2140
1474
  );
2141
1475
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_CONNECT, {
2142
1476
  type: UI_REQUEST.REQUEST_DEVICE_CONNECT,
2143
1477
  payload: {
2144
1478
  vendor: "ledger",
2145
1479
  reason: "device-not-found",
2146
- message: "Please connect and unlock your Ledger device",
2147
- operationId
1480
+ message: "Please connect and unlock your Ledger device"
2148
1481
  }
2149
1482
  });
2150
1483
  let payload;
@@ -2190,7 +1523,7 @@ var _LedgerAdapter = class _LedgerAdapter {
2190
1523
  * Returns the params to pass through (with `showOnDevice` possibly
2191
1524
  * promoted), or `null` if the user declined.
2192
1525
  */
2193
- async _gateBtcHighIndex(params, signal) {
1526
+ async _gateBtcHighIndex(params) {
2194
1527
  const accountIndex = btcAccountIndexFromPath(params.path);
2195
1528
  if (params.showOnDevice) return params;
2196
1529
  if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
@@ -2199,32 +1532,25 @@ var _LedgerAdapter = class _LedgerAdapter {
2199
1532
  if (this._btcHighIndexConfirmedThisSession) {
2200
1533
  return { ...params, showOnDevice: true };
2201
1534
  }
2202
- const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
1535
+ const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
2203
1536
  if (!confirmed) return null;
2204
1537
  this._btcHighIndexConfirmedThisSession = true;
2205
1538
  return { ...params, showOnDevice: true };
2206
1539
  }
2207
- async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
2208
- const operationId = this._activeOperationId();
1540
+ async _waitForBtcHighIndexConfirm(path, accountIndex) {
2209
1541
  const waitPromise = this._uiRegistry.wait(
2210
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2211
- { operationId }
1542
+ UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM
2212
1543
  );
2213
1544
  this.emitter.emit(UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
2214
1545
  type: UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2215
1546
  payload: {
2216
1547
  vendor: "ledger",
2217
1548
  path,
2218
- accountIndex,
2219
- operationId
1549
+ accountIndex
2220
1550
  }
2221
1551
  });
2222
1552
  try {
2223
- const payload = await this._awaitUiAnswer(
2224
- UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
2225
- waitPromise,
2226
- signal
2227
- );
1553
+ const payload = await waitPromise;
2228
1554
  return !!payload?.confirmed;
2229
1555
  } catch (err) {
2230
1556
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -2234,35 +1560,18 @@ var _LedgerAdapter = class _LedgerAdapter {
2234
1560
  return false;
2235
1561
  }
2236
1562
  }
2237
- /** A cancel of the job ends its open prompt, even when no operation names that prompt. */
2238
- async _awaitUiAnswer(requestType, waitPromise, signal) {
2239
- const onAbort = () => this._uiRegistry.cancel(requestType);
2240
- if (signal.aborted) onAbort();
2241
- signal.addEventListener("abort", onAbort, { once: true });
2242
- try {
2243
- return await waitPromise;
2244
- } finally {
2245
- signal.removeEventListener("abort", onAbort);
2246
- }
2247
- }
2248
1563
  // Ask the user whether to install a missing app (autoInstallApp flow).
2249
1564
  // Same register-then-emit ordering as the BTC high-index gate.
2250
- async _waitForInstallAppConfirm(appName, signal) {
2251
- const operationId = this._activeOperationId();
1565
+ async _waitForInstallAppConfirm(appName) {
2252
1566
  const waitPromise = this._uiRegistry.wait(
2253
- UI_REQUEST.REQUEST_INSTALL_APP,
2254
- { operationId }
1567
+ UI_REQUEST.REQUEST_INSTALL_APP
2255
1568
  );
2256
1569
  this.emitter.emit(UI_REQUEST.REQUEST_INSTALL_APP, {
2257
1570
  type: UI_REQUEST.REQUEST_INSTALL_APP,
2258
- payload: { vendor: "ledger", appName, operationId }
1571
+ payload: { vendor: "ledger", appName }
2259
1572
  });
2260
1573
  try {
2261
- const payload = await this._awaitUiAnswer(
2262
- UI_REQUEST.REQUEST_INSTALL_APP,
2263
- waitPromise,
2264
- signal
2265
- );
1574
+ const payload = await waitPromise;
2266
1575
  return !!payload?.confirmed;
2267
1576
  } catch (err) {
2268
1577
  this.emitter.emit(UI_REQUEST.CLOSE_UI_WINDOW, {
@@ -2275,17 +1584,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2275
1584
  // Layer 1 entry. Caller signal only races the outer awaiter; the shared
2276
1585
  // `_doConnect` runs under its own internal controller so caller A's cancel
2277
1586
  // doesn't kill caller B's await.
2278
- async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
1587
+ async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
2279
1588
  if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
2280
- this._assertConnectorReady("connectDevice");
2281
- if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
1589
+ if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
2282
1590
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2283
1591
  code: HardwareErrorCode3.DeviceNotFound
2284
1592
  });
2285
1593
  }
2286
1594
  if (connectId && this._sessions.has(connectId)) return connectId;
2287
1595
  if (!connectId && this._sessions.size > 0) {
2288
- if (!this._isBleConnection() && this._sessions.size > 1) {
1596
+ if (!isLedgerBleConnectionType(this.connector.connectionType) && this._sessions.size > 1) {
2289
1597
  throw Object.assign(
2290
1598
  new Error(
2291
1599
  "Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
@@ -2295,24 +1603,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2295
1603
  }
2296
1604
  return this._sessions.keys().next().value;
2297
1605
  }
2298
- if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
2299
- const controller = new AbortController();
2300
- this._doConnectAbortController = controller;
2301
- const innerSignal = controller.signal;
1606
+ if (!this._connectingPromise) {
1607
+ this._doConnectAbortController = new AbortController();
1608
+ const innerSignal = this._doConnectAbortController.signal;
2302
1609
  this._connectingPromise = (async () => {
2303
1610
  try {
2304
- return await this._doConnect(
2305
- innerSignal,
2306
- connectId,
2307
- allowUsbEphemeralFallback,
2308
- preserveOperationId,
2309
- context
2310
- );
1611
+ return await this._doConnect(innerSignal, connectId, allowUsbEphemeralFallback);
2311
1612
  } finally {
2312
- if (this._doConnectAbortController === controller) {
2313
- this._connectingPromise = null;
2314
- this._doConnectAbortController = null;
2315
- }
1613
+ this._connectingPromise = null;
1614
+ this._doConnectAbortController = null;
2316
1615
  }
2317
1616
  })();
2318
1617
  }
@@ -2321,57 +1620,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2321
1620
  // Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
2322
1621
  // Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
2323
1622
  // throw DeviceNotFound so the user is kicked out of the loop.
2324
- async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
2325
- _LedgerAdapter._throwIfAborted(internalSignal);
2326
- if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
2327
- this._activeConnectionType = "usb";
2328
- const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
2329
- _LedgerAdapter._throwIfAborted(internalSignal);
2330
- const knownUsb = context?.knownConnections?.find(
2331
- (connection) => connection.transport === "usb"
2332
- );
2333
- const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
2334
- if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
2335
- return this._connectFirstOrSelect(
2336
- usbDevices,
2337
- usbTarget,
2338
- allowUsbEphemeralFallback,
2339
- preserveOperationId,
2340
- context,
2341
- internalSignal
2342
- );
2343
- }
2344
- if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
2345
- throw createHwkError({
2346
- code: HardwareErrorCode3.DeviceNotFound,
2347
- message: "This Ledger model has no Bluetooth transport; connect it over USB"
2348
- });
2349
- }
2350
- this._activeConnectionType = "ble";
2351
- const knownBle = context?.knownConnections?.find(
2352
- (connection) => connection.transport === "ble"
2353
- );
2354
- if (knownBle?.transport === "ble") {
2355
- return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
2356
- }
2357
- if (targetConnectId && context?.knownConnections === void 0) {
2358
- throw createHwkError({
2359
- code: HardwareErrorCode3.DeviceNotFound,
2360
- message: "Ledger connection metadata is required before starting Bluetooth binding"
2361
- });
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
+ }
2362
1638
  }
2363
- const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
2364
- return this._connectFirstOrSelect(
2365
- bleDevices,
2366
- void 0,
2367
- allowUsbEphemeralFallback,
2368
- preserveOperationId,
2369
- context,
2370
- internalSignal
2371
- );
2372
- }
2373
- if (this._isBleConnection() && targetConnectId) {
2374
- return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
2375
1639
  }
2376
1640
  let confirms = 0;
2377
1641
  while (!internalSignal.aborted) {
@@ -2379,28 +1643,22 @@ var _LedgerAdapter = class _LedgerAdapter {
2379
1643
  type: EConnectorInteraction.Searching,
2380
1644
  payload: { sessionId: "" }
2381
1645
  });
2382
- let devices = await this._searchDevices(void 0, internalSignal);
2383
- _LedgerAdapter._throwIfAborted(internalSignal);
1646
+ let devices = await this.searchDevices();
2384
1647
  if (devices.length === 0) {
2385
1648
  for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
2386
1649
  await new Promise((resolve) => {
2387
1650
  setTimeout(resolve, DEVICE_CONNECT_RETRY_DELAY_MS);
2388
1651
  });
2389
- _LedgerAdapter._throwIfAborted(internalSignal);
2390
- devices = await this._searchDevices(void 0, internalSignal);
2391
- _LedgerAdapter._throwIfAborted(internalSignal);
1652
+ devices = await this.searchDevices();
2392
1653
  if (devices.length > 0) break;
2393
1654
  }
2394
1655
  }
2395
- if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
1656
+ if (devices.length > 0) {
2396
1657
  try {
2397
1658
  return await this._connectFirstOrSelect(
2398
1659
  devices,
2399
1660
  targetConnectId,
2400
- allowUsbEphemeralFallback,
2401
- preserveOperationId,
2402
- context,
2403
- internalSignal
1661
+ allowUsbEphemeralFallback
2404
1662
  );
2405
1663
  } catch (err) {
2406
1664
  if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
@@ -2429,147 +1687,45 @@ var _LedgerAdapter = class _LedgerAdapter {
2429
1687
  _LedgerAdapter._throwIfAborted(internalSignal);
2430
1688
  throw new Error("_doConnect aborted");
2431
1689
  }
2432
- async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
2433
- _LedgerAdapter._throwIfAborted(signal);
1690
+ async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback = false) {
2434
1691
  if (targetConnectId) {
2435
1692
  const target = devices.find(
2436
1693
  (d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
2437
1694
  );
2438
1695
  if (target) {
2439
- return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
1696
+ return this._connectDeviceOrThrow(target.connectId);
2440
1697
  }
2441
- if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
1698
+ if (!isLedgerBleConnectionType(this.connector.connectionType) && devices.length === 1 && allowUsbEphemeralFallback) {
2442
1699
  debugLog(
2443
1700
  `[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
2444
1701
  );
2445
- return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1702
+ return this._connectDeviceOrThrow(devices[0].connectId);
2446
1703
  }
2447
- if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
2448
- const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
2449
- code: HardwareErrorCode3.DeviceNotFound
2450
- });
2451
- if (this._isBleConnection()) {
2452
- err._tag = ERROR_TAG.DeviceNotAdvertising;
2453
- }
2454
- throw err;
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;
2455
1709
  }
1710
+ throw err;
2456
1711
  }
2457
- const requiresBleSelection = this._isBleConnection();
2458
- if (requiresBleSelection && !allowUsbEphemeralFallback) {
1712
+ if (isLedgerBleConnectionType(this.connector.connectionType)) {
2459
1713
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
2460
1714
  code: HardwareErrorCode3.DeviceNotFound
2461
1715
  });
2462
1716
  }
2463
- if (requiresBleSelection && context?.allowDeviceSelection !== false) {
2464
- const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
2465
- if (context) context.bindingSessionId = bindingSessionId;
2466
- const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
2467
- const knownUsb = context?.knownConnections?.find(
2468
- (connection) => connection.transport === "usb"
2469
- );
2470
- const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
2471
- const { device, requestId } = await requestBleDeviceSelection({
2472
- emitter: this.emitter,
2473
- registry: this._uiRegistry,
2474
- signal,
2475
- allowUsbFallback,
2476
- scan: async () => {
2477
- if (allowUsbFallback) {
2478
- const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
2479
- const candidate = usbDevices.find(
2480
- (device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
2481
- ) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
2482
- if (candidate) return [candidate];
2483
- }
2484
- return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
2485
- },
2486
- request: {
2487
- devices,
2488
- bindingSessionId,
2489
- context: {
2490
- kind: "bind-connection",
2491
- transport: "ble",
2492
- reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
2493
- },
2494
- extra: context?.extra,
2495
- operationId: preserveOperationId
2496
- }
2497
- });
2498
- if (device.connectionType === "usb") {
2499
- this._activeConnectionType = "usb";
2500
- if (context) context.selectedConnection = void 0;
2501
- this._bindingSelectionRequestId = requestId;
2502
- this._finishBleBinding("cancelled");
2503
- return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
2504
- }
2505
- this._bindingSelectionRequestId = requestId;
2506
- const connected = await this._connectDeviceOrThrow(
2507
- device.connectId,
2508
- preserveOperationId,
2509
- signal
2510
- );
2511
- if (context) context.selectedConnection = { connectId: connected, requestId };
2512
- if (context?.deferBindingSave) {
2513
- context.pendingBinding = { connectId: connected, requestId };
2514
- } else {
2515
- await this._saveSelectedBleBinding(
2516
- connected,
2517
- requestId,
2518
- context,
2519
- preserveOperationId,
2520
- signal
2521
- );
2522
- }
2523
- return connected;
2524
- }
2525
- if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
2526
- if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(UI_REQUEST.REQUEST_SELECT_DEVICE)) {
2527
- throw createHwkError({
2528
- code: HardwareErrorCode3.DeviceNotFound,
2529
- message: "Select a Ledger device before continuing"
2530
- });
2531
- }
2532
- const requestId = this._uiRegistry.createRequestId();
2533
- const operationId = this._activeOperationId();
2534
- const waitPromise = this._uiRegistry.wait(
2535
- UI_REQUEST.REQUEST_SELECT_DEVICE,
2536
- { requestId, operationId }
2537
- );
2538
- this.emitter.emit(UI_REQUEST.REQUEST_SELECT_DEVICE, {
2539
- type: UI_REQUEST.REQUEST_SELECT_DEVICE,
2540
- payload: {
2541
- devices,
2542
- requestId,
2543
- operationId,
2544
- context: requiresBleSelection ? {
2545
- kind: "bind-connection",
2546
- transport: "ble",
2547
- reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
2548
- } : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
2549
- extra: context?.extra
2550
- }
2551
- });
2552
- const { sdkConnectId } = await this._abortable(signal, waitPromise);
2553
- _LedgerAdapter._throwIfAborted(signal);
2554
- const selected = devices.find((device) => device.connectId === sdkConnectId);
2555
- if (!selected) {
2556
- throw Object.assign(new Error("Selected Ledger is no longer available"), {
2557
- code: HardwareErrorCode3.DeviceNotFound
2558
- });
2559
- }
2560
- if (context && requiresBleSelection)
2561
- context.selectedConnection = { connectId: selected.connectId, requestId };
2562
- return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
1717
+ if (devices.length > 1) {
1718
+ throw createMultipleUsbLedgerDevicesError();
2563
1719
  }
2564
1720
  if (devices.length !== 1) {
2565
1721
  throw Object.assign(new Error("Ledger device not found."), {
2566
1722
  code: HardwareErrorCode3.DeviceNotFound
2567
1723
  });
2568
1724
  }
2569
- return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
1725
+ return this._connectDeviceOrThrow(devices[0].connectId);
2570
1726
  }
2571
- async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
2572
- const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
1727
+ async _connectDeviceOrThrow(chosenConnectId) {
1728
+ const result = await this.connectDevice(chosenConnectId);
2573
1729
  if (!result.success) {
2574
1730
  const payload = result.payload;
2575
1731
  const rethrow = Object.assign(new Error(payload.error), {
@@ -2580,8 +1736,16 @@ var _LedgerAdapter = class _LedgerAdapter {
2580
1736
  }
2581
1737
  throw rethrow;
2582
1738
  }
2583
- return result.payload;
1739
+ return chosenConnectId;
2584
1740
  }
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
+ */
2585
1749
  /**
2586
1750
  * Unwrap a `ConnectorCallResult` back into the throw-based control flow this
2587
1751
  * class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
@@ -2602,145 +1766,33 @@ var _LedgerAdapter = class _LedgerAdapter {
2602
1766
  * lives in one place.
2603
1767
  */
2604
1768
  async _callConnector(sessionId, method, params, signal) {
2605
- this._assertConnectorReady(method);
2606
- if (signal?.aborted) throw this._abortReason(signal);
2607
- const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
2608
- let promise;
2609
- try {
2610
- promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
2611
- } catch (error) {
2612
- releaseOperation();
2613
- throw error;
2614
- }
1769
+ const promise = this.connector.call(sessionId, method, params);
2615
1770
  const result = signal ? await this._abortable(signal, promise) : await promise;
2616
1771
  return this._unwrapConnectorResult(result);
2617
1772
  }
2618
- _assertConnectorReady(method) {
2619
- if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
2620
- throw _LedgerAdapter._createDeviceBusyError(method);
2621
- }
2622
- }
2623
- _runConnectorTeardown(task) {
2624
- const previous = this._connectorTeardownTail;
2625
- let releaseTail = () => void 0;
2626
- this._connectorTeardownTail = new Promise((resolve) => {
2627
- releaseTail = resolve;
2628
- });
2629
- this._pendingConnectorTeardowns += 1;
2630
- return (async () => {
2631
- try {
2632
- await previous;
2633
- await this._waitForConnectorOperationsToDrain();
2634
- await task();
2635
- } finally {
2636
- this._pendingConnectorTeardowns -= 1;
2637
- releaseTail();
2638
- }
2639
- })();
2640
- }
2641
- _waitForConnectorOperationsToDrain() {
2642
- if (this._unsettledConnectorOperations.size === 0) {
2643
- return Promise.resolve();
2644
- }
2645
- return new Promise((resolve) => {
2646
- this._connectorIdleWaiters.add(resolve);
2647
- });
2648
- }
2649
- _retainConnectorOperation(key) {
2650
- this._unsettledConnectorOperations.set(
2651
- key,
2652
- (this._unsettledConnectorOperations.get(key) ?? 0) + 1
2653
- );
2654
- let released = false;
2655
- return () => {
2656
- if (released) return;
2657
- released = true;
2658
- const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
2659
- if (remaining > 0) {
2660
- this._unsettledConnectorOperations.set(key, remaining);
2661
- } else {
2662
- this._unsettledConnectorOperations.delete(key);
2663
- }
2664
- if (this._unsettledConnectorOperations.size === 0) {
2665
- for (const resolve of this._connectorIdleWaiters) resolve();
2666
- this._connectorIdleWaiters.clear();
2667
- }
2668
- };
2669
- }
2670
1773
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
2671
- const positionalOperationId = isHardwareOperationId(connectId) ? connectId : void 0;
2672
- if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
2673
- throw createHwkError({
2674
- code: HardwareErrorCode3.InvalidParams,
2675
- message: "Conflicting Ledger operation ids",
2676
- params: {
2677
- positionalOperationId,
2678
- commonOperationId: commonParams.operationId
2679
- }
2680
- });
2681
- }
2682
- const operationId = commonParams?.operationId ?? positionalOperationId;
2683
- const operation = operationId ? this._operations.resolve(operationId) : void 0;
2684
- const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
2685
- const effectiveConnectId = operation?.connectId ?? connectId;
2686
- debugLog("[LedgerAdapter][REQ]", {
2687
- method,
2688
- connectId: effectiveConnectId || "(empty)",
2689
- params: isSigningMethod(method) ? "[redacted]" : params
2690
- });
2691
- const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
1774
+ debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1775
+ const queueKey = connectId || "__ledger_default__";
2692
1776
  try {
2693
1777
  const result = await this._jobQueue.enqueue(
2694
1778
  queueKey,
2695
- async (signal) => {
2696
- if (operationId) this._activeOperationJobs.add(operationId);
2697
- try {
2698
- return await this._runConnectorCall(
2699
- effectiveConnectId,
2700
- method,
2701
- params,
2702
- signal,
2703
- fingerprint,
2704
- permissionDeviceId,
2705
- commonParams,
2706
- installContext ?? {},
2707
- operationId
2708
- );
2709
- } catch (error) {
2710
- const status = signal.aborted ? "cancelled" : "failed";
2711
- const bundleConnectId = installContext?.connection?.connectId;
2712
- let keptBundlePick = false;
2713
- for (const [pickedConnectId, owner] of this._pendingPickBindings) {
2714
- if (pickedConnectId === bundleConnectId) {
2715
- keptBundlePick = true;
2716
- } else {
2717
- this._pendingPickBindings.delete(pickedConnectId);
2718
- this._discardPendingBinding(owner, status);
2719
- await this._dropSession(pickedConnectId, signal);
2720
- }
2721
- }
2722
- if (!keptBundlePick) this._finishBleBinding(status);
2723
- throw error;
2724
- } finally {
2725
- if (operationId) {
2726
- this._activeOperationJobs.delete(operationId);
2727
- if (this._pendingOperationDisconnects.delete(operationId)) {
2728
- await this._releaseLostOperationConnection(operationId);
2729
- }
2730
- }
2731
- }
2732
- },
1779
+ async (signal) => this._runConnectorCall(
1780
+ connectId,
1781
+ method,
1782
+ params,
1783
+ signal,
1784
+ fingerprint,
1785
+ permissionDeviceId,
1786
+ commonParams,
1787
+ installContext
1788
+ ),
2733
1789
  {
2734
1790
  label: method,
2735
1791
  rejectIfBusy: true,
2736
1792
  busyError: _LedgerAdapter._createDeviceBusyError(method)
2737
1793
  }
2738
1794
  );
2739
- debugLog("[LedgerAdapter][RES]", {
2740
- method,
2741
- success: true,
2742
- payload: redactResultForLog(result, method)
2743
- });
1795
+ debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
2744
1796
  return result;
2745
1797
  } catch (err) {
2746
1798
  const e = err;
@@ -2754,22 +1806,15 @@ var _LedgerAdapter = class _LedgerAdapter {
2754
1806
  }
2755
1807
  });
2756
1808
  throw err;
2757
- } finally {
2758
- releaseOperationRetention?.();
2759
1809
  }
2760
1810
  }
2761
- /** Hermes/RN polyfills don't always populate signal.reason; fall back. */
2762
- _abortReason(signal) {
2763
- return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2764
- }
2765
1811
  /**
2766
1812
  * Race a promise against an abort signal. On abort, rejects with
2767
1813
  * signal.reason → instance _lastCancelReason → generic Error('Aborted').
2768
1814
  */
2769
1815
  _abortable(signal, promise) {
2770
- const getAbortReason = () => this._abortReason(signal);
1816
+ const getAbortReason = () => signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
2771
1817
  if (signal.aborted) {
2772
- void promise.catch(() => void 0);
2773
1818
  return Promise.reject(getAbortReason());
2774
1819
  }
2775
1820
  return new Promise((resolve, reject) => {
@@ -2796,19 +1841,17 @@ var _LedgerAdapter = class _LedgerAdapter {
2796
1841
  }
2797
1842
  }
2798
1843
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
2799
- async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
1844
+ async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
2800
1845
  _LedgerAdapter._throwIfAborted(signal);
2801
- if (!operationId) {
2802
- await this._ensureDevicePermission(
2803
- connectId,
2804
- permissionDeviceId ?? fingerprint?.deviceId,
2805
- signal
2806
- );
2807
- }
1846
+ await this._ensureDevicePermission(
1847
+ connectId,
1848
+ permissionDeviceId ?? fingerprint?.deviceId,
1849
+ signal
1850
+ );
2808
1851
  _LedgerAdapter._throwIfAborted(signal);
2809
1852
  let effectiveParams = params;
2810
1853
  if (method === "btcGetPublicKey") {
2811
- const gatedParams = await this._gateBtcHighIndex(params, signal);
1854
+ const gatedParams = await this._gateBtcHighIndex(params);
2812
1855
  if (gatedParams === null) {
2813
1856
  throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
2814
1857
  _tag: ERROR_TAG.UserAborted,
@@ -2818,67 +1861,19 @@ var _LedgerAdapter = class _LedgerAdapter {
2818
1861
  effectiveParams = gatedParams;
2819
1862
  }
2820
1863
  const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
2821
- let businessCallStarted = false;
2822
- const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
2823
- const knownTransport = this._isBleConnection() ? "ble" : "usb";
2824
- const hintedConnectId = commonParams?.knownConnections?.find(
2825
- (connection) => connection.transport === knownTransport
2826
- );
2827
- const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
2828
- const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
2829
- const checksWallet = Boolean(
2830
- fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
2831
- );
2832
- const connectionAttempt = {
2833
- ...commonParams,
2834
- deferBindingSave: checksWallet
2835
- };
2836
- const bundleConnection = installContext?.connection;
2837
- if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
2838
- throw createHwkError({
2839
- code: HardwareErrorCode3.DeviceDisconnected,
2840
- message: "Ledger all-network connection ended"
2841
- });
2842
- }
2843
- const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
2844
- preferredConnectId,
1864
+ const resolvedConnectId = await this.ensureConnected(
1865
+ connectId,
2845
1866
  signal,
2846
- allowUsbEphemeralFallback,
2847
- void 0,
2848
- connectionAttempt
1867
+ allowUsbEphemeralFallback
2849
1868
  );
2850
- const walletCheck = installContext?.walletCheck;
2851
- if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
2852
- throw createHwkError({
2853
- code: HardwareErrorCode3.DeviceMismatch,
2854
- message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
2855
- });
2856
- }
2857
1869
  const sessionId = this._sessions.get(resolvedConnectId);
2858
- if (sessionId && installContext && !installContext.connection) {
2859
- installContext.connection = { connectId: resolvedConnectId, sessionId };
2860
- }
2861
1870
  if (!sessionId) {
2862
- if (operationId) {
2863
- this._operations.end(operationId, "disconnect");
2864
- throw createHwkError({
2865
- code: HardwareErrorCode3.OperationEnded,
2866
- message: "Ledger operation connection is no longer active",
2867
- params: { operationId, reason: "disconnect" }
2868
- });
2869
- }
2870
1871
  throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
2871
1872
  _tag: ERROR_TAG.DeviceSessionNotFound
2872
1873
  });
2873
1874
  }
2874
1875
  try {
2875
- const isBleSession = this._sessionTransports.get(sessionId) === "ble";
2876
- if (!operationId && connectionAttempt.pendingBinding) {
2877
- this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
2878
- }
2879
- const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
2880
- const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
2881
- if (fingerprint && checksWallet) {
1876
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2882
1877
  const fp = await this._abortable(
2883
1878
  signal,
2884
1879
  this._verifyDeviceFingerprintWithSession(
@@ -2888,68 +1883,14 @@ var _LedgerAdapter = class _LedgerAdapter {
2888
1883
  )
2889
1884
  );
2890
1885
  if (!fp.success) {
2891
- if (pendingBinding) {
2892
- this._discardPendingBinding(bindingOwner, "failed");
2893
- this._pendingPickBindings.delete(resolvedConnectId);
2894
- }
2895
- if (operationId) {
2896
- this._pendingOperationBindings.delete(operationId);
2897
- this._operations.end(operationId, "explicit");
2898
- await this._dropSession(resolvedConnectId, signal);
2899
- }
2900
1886
  throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2901
1887
  code: HardwareErrorCode3.DeviceMismatch
2902
1888
  });
2903
1889
  }
2904
- if (walletCheck) walletCheck.verified = true;
2905
- }
2906
- if (pendingBinding && bindingOwner) {
2907
- bindingOwner.pendingBinding = void 0;
2908
- if (operationId) this._pendingOperationBindings.delete(operationId);
2909
- else this._pendingPickBindings.delete(resolvedConnectId);
2910
- await this._saveSelectedBleBinding(
2911
- pendingBinding.connectId,
2912
- pendingBinding.requestId,
2913
- bindingOwner,
2914
- operationId,
2915
- signal,
2916
- fingerprint && checksWallet ? {
2917
- vendor: "ledger",
2918
- type: "chainFingerprint",
2919
- chain: fingerprint.chain,
2920
- value: fingerprint.deviceId
2921
- } : void 0
2922
- );
2923
1890
  }
2924
- if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
2925
- this._selectedBleReconnectTargets.set(connectId, {
2926
- connectId: resolvedConnectId,
2927
- chain: fingerprint.chain,
2928
- fingerprint: fingerprint.deviceId
2929
- });
2930
- }
2931
- businessCallStarted = true;
2932
- const result = await this._callConnector(sessionId, method, effectiveParams, signal);
2933
- if (walletCheck) walletCheck.derived = true;
2934
- return result;
1891
+ return await this._callConnector(sessionId, method, effectiveParams, signal);
2935
1892
  } catch (err) {
2936
1893
  if (signal.aborted) throw err;
2937
- if (isLostConnectionError(err)) {
2938
- this._discoveredDevices.delete(resolvedConnectId);
2939
- if (operationId) await this._releaseLostOperationConnection(operationId);
2940
- else {
2941
- this._sessions.delete(resolvedConnectId);
2942
- await this.connector.disconnect(sessionId).catch(() => void 0);
2943
- }
2944
- const ambiguous = businessCallStarted && !canReplayHardwareMethodAfterTransportFailure(method);
2945
- const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
2946
- throw createHwkError({
2947
- code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(err).code,
2948
- message: "Ledger operation connection was lost; start a new operation",
2949
- params: ambiguous ? operationMayHaveCompletedParams(method, { operationId }) : interactionParams,
2950
- recovery: ambiguous ? { scope: "unknown" } : void 0
2951
- });
2952
- }
2953
1894
  const errObj = err;
2954
1895
  debugLog("[LedgerAdapter] connectorCall error:", method, {
2955
1896
  message: errObj?.message,
@@ -2961,64 +1902,6 @@ var _LedgerAdapter = class _LedgerAdapter {
2961
1902
  isNotAdvertising: isDeviceNotAdvertisingError(err),
2962
1903
  isStuckApp: isStuckAppStateError(err)
2963
1904
  });
2964
- const assertSessionCurrent = (message) => {
2965
- if (this._sessions.get(resolvedConnectId) === sessionId) return;
2966
- throw createHwkError({
2967
- code: operationId ? HardwareErrorCode3.OperationEnded : HardwareErrorCode3.DeviceDisconnected,
2968
- message
2969
- });
2970
- };
2971
- if ((isDeviceLockedError(err) || errObj?.code === HardwareErrorCode3.DeviceLocked) && lockedRetryBudget > 0) {
2972
- await this._waitForDeviceConnect(signal);
2973
- assertSessionCurrent("Ledger connection ended while waiting for unlock");
2974
- if (walletCheck?.derived) walletCheck.verified = false;
2975
- return this._runConnectorCall(
2976
- resolvedConnectId,
2977
- method,
2978
- effectiveParams,
2979
- signal,
2980
- fingerprint,
2981
- permissionDeviceId,
2982
- commonParams,
2983
- installContext,
2984
- operationId,
2985
- lockedRetryBudget - 1
2986
- );
2987
- }
2988
- if (businessCallStarted && isStuckAppStateError(err)) {
2989
- await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
2990
- assertSessionCurrent("Ledger connection ended during the app transition");
2991
- try {
2992
- const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
2993
- if (walletCheck) walletCheck.derived = true;
2994
- return retried;
2995
- } catch (retryErr) {
2996
- if (isStuckAppStateError(retryErr)) throw err;
2997
- if (isLostConnectionError(retryErr)) {
2998
- if (operationId) await this._releaseLostOperationConnection(operationId);
2999
- else {
3000
- this._sessions.delete(resolvedConnectId);
3001
- this._discoveredDevices.delete(resolvedConnectId);
3002
- await this.connector.disconnect(sessionId).catch(() => void 0);
3003
- }
3004
- const ambiguous = !canReplayHardwareMethodAfterTransportFailure(method);
3005
- throw createHwkError({
3006
- code: operationId ? HardwareErrorCode3.OperationEnded : mapLedgerError(retryErr).code,
3007
- message: `Ledger ${method} may have completed before the connection was lost`,
3008
- params: ambiguous ? operationMayHaveCompletedParams(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
3009
- recovery: ambiguous ? { scope: "unknown" } : void 0
3010
- });
3011
- }
3012
- throw retryErr;
3013
- }
3014
- }
3015
- if (!operationId && errObj?.code === HardwareErrorCode3.DeviceMismatch) {
3016
- this._sessions.delete(resolvedConnectId);
3017
- this._sessionTransports.delete(sessionId);
3018
- this._discoveredDevices.delete(resolvedConnectId);
3019
- await this.connector.disconnect(sessionId).catch(() => void 0);
3020
- throw err;
3021
- }
3022
1905
  const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
3023
1906
  const isAppMissing = isAppNotInstalledError(err) || err?.code === HardwareErrorCode3.AppNotInstalled;
3024
1907
  if (autoInstallApp && isAppMissing) {
@@ -3035,7 +1918,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3035
1918
  appName
3036
1919
  });
3037
1920
  }
3038
- const confirmed = await this._waitForInstallAppConfirm(appName, signal);
1921
+ const confirmed = await this._waitForInstallAppConfirm(appName);
3039
1922
  if (!confirmed) {
3040
1923
  throw createHwkError({
3041
1924
  code: HardwareErrorCode3.UserAborted,
@@ -3074,14 +1957,157 @@ var _LedgerAdapter = class _LedgerAdapter {
3074
1957
  fingerprint,
3075
1958
  permissionDeviceId,
3076
1959
  commonParams,
3077
- installContext,
3078
- operationId
1960
+ installContext
3079
1961
  );
3080
1962
  }
3081
1963
  }
1964
+ if (isStuckAppStateError(err)) {
1965
+ try {
1966
+ this._sessions.delete(resolvedConnectId);
1967
+ this._discoveredDevices.delete(resolvedConnectId);
1968
+ this.connector.reset?.();
1969
+ } catch {
1970
+ }
1971
+ debugLog(
1972
+ "[LedgerAdapter] stuck-app retry: method=",
1973
+ method,
1974
+ "delayMs=",
1975
+ _LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
1976
+ "_tag=",
1977
+ err?._tag
1978
+ );
1979
+ try {
1980
+ const retryResult = await this._retryAfterStuckApp(
1981
+ resolvedConnectId,
1982
+ method,
1983
+ effectiveParams,
1984
+ signal,
1985
+ err,
1986
+ fingerprint
1987
+ );
1988
+ debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
1989
+ return retryResult;
1990
+ } catch (retryErr) {
1991
+ if (signal.aborted) throw retryErr;
1992
+ if (isStuckAppStateError(retryErr)) {
1993
+ debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
1994
+ throw err;
1995
+ }
1996
+ debugLog(
1997
+ "[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
1998
+ method,
1999
+ "retryErrTag=",
2000
+ retryErr?._tag
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
+ }
3082
2074
  throw err;
3083
2075
  }
3084
2076
  }
2077
+ /**
2078
+ * Stuck-app recovery: pause for the device's UI transition, then retry once.
2079
+ *
2080
+ * Caller has already cleared the session + reset connector. We wait so Stax
2081
+ * finishes its post-CloseApp animation, then go through ensureConnected +
2082
+ * fingerprint check + call exactly once. Caller decides what to do on a
2083
+ * second stuck-app hit.
2084
+ */
2085
+ async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
2086
+ await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
2087
+ const retryConnectId = await this.ensureConnected(
2088
+ resolvedConnectId,
2089
+ signal,
2090
+ !!fingerprint?.deviceId && !fingerprint.skipFingerprint
2091
+ );
2092
+ const retrySessionId = this._sessions.get(retryConnectId);
2093
+ if (!retrySessionId) throw originalErr;
2094
+ if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
2095
+ const fp = await this._abortable(
2096
+ signal,
2097
+ this._verifyDeviceFingerprintWithSession(
2098
+ retrySessionId,
2099
+ fingerprint.deviceId,
2100
+ fingerprint.chain
2101
+ )
2102
+ );
2103
+ if (!fp.success) {
2104
+ throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
2105
+ code: HardwareErrorCode3.DeviceMismatch
2106
+ });
2107
+ }
2108
+ }
2109
+ return this._callConnector(retrySessionId, method, params, signal);
2110
+ }
3085
2111
  _sleepAbortable(ms, signal) {
3086
2112
  return new Promise((resolve, reject) => {
3087
2113
  if (signal.aborted) {
@@ -3100,22 +2126,111 @@ var _LedgerAdapter = class _LedgerAdapter {
3100
2126
  });
3101
2127
  }
3102
2128
  /**
3103
- * Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
3104
- * replies. Without connectId the request is environment-level, else device-level.
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
3105
2221
  */
3106
2222
  async _ensureDevicePermission(connectId, deviceId, signal) {
3107
2223
  if (signal?.aborted) {
3108
2224
  _LedgerAdapter._throwIfAborted(signal);
3109
2225
  }
3110
2226
  const transportType = this.activeTransport ?? "hid";
3111
- const operationId = this._activeOperationId();
3112
2227
  const waitPromise = this._uiRegistry.wait(
3113
2228
  UI_REQUEST.REQUEST_DEVICE_PERMISSION,
3114
- { timeoutMs: 6e4, operationId }
2229
+ { timeoutMs: 6e4 }
3115
2230
  );
3116
2231
  this.emitter.emit(UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
3117
2232
  type: UI_REQUEST.REQUEST_DEVICE_PERMISSION,
3118
- payload: { transportType, connectId, deviceId, operationId }
2233
+ payload: { transportType, connectId, deviceId }
3119
2234
  });
3120
2235
  let response;
3121
2236
  const onAbort = () => {
@@ -3161,15 +2276,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3161
2276
  if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
3162
2277
  const e = err;
3163
2278
  const params = e.code === HardwareErrorCode3.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
3164
- return ledgerFailure(
3165
- e.code,
3166
- e.message ?? "Unknown error",
3167
- e.appName,
3168
- tag,
3169
- params,
3170
- void 0,
3171
- isHwkRecoveryHint(e.recovery) ? e.recovery : void 0
3172
- );
2279
+ return ledgerFailure(e.code, e.message ?? "Unknown error", e.appName, tag, params);
3173
2280
  }
3174
2281
  const mapped = mapLedgerError(err);
3175
2282
  return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
@@ -3196,7 +2303,7 @@ var _LedgerAdapter = class _LedgerAdapter {
3196
2303
  deviceId: device.deviceId,
3197
2304
  connectId: device.connectId,
3198
2305
  label: device.name,
3199
- connectionType: device.connectionType ?? this.connector.connectionType,
2306
+ connectionType: this.connector.connectionType,
3200
2307
  rssi: device.rssi,
3201
2308
  isConnectable: device.isConnectable,
3202
2309
  serialNumber: device.serialNumber,
@@ -3222,8 +2329,8 @@ var LedgerAdapter = _LedgerAdapter;
3222
2329
 
3223
2330
  // src/connector/LedgerConnectorBase.ts
3224
2331
  import {
3225
- EConnectorInteraction as EConnectorInteraction3,
3226
- HardwareErrorCode as HardwareErrorCode7,
2332
+ EConnectorInteraction as EConnectorInteraction4,
2333
+ HardwareErrorCode as HardwareErrorCode8,
3227
2334
  isKnownNonTargetHardwareVendor,
3228
2335
  serializeConnectorError
3229
2336
  } from "@onekeyfe/hwk-adapter-core";
@@ -3496,7 +2603,7 @@ var LedgerDeviceManager = class {
3496
2603
 
3497
2604
  // src/signer/SignerManager.ts
3498
2605
  import { SignerEthBuilder } from "@ledgerhq/device-signer-kit-ethereum";
3499
- import { ContextModuleBuilder, ContextModuleChainID } from "@ledgerhq/context-module";
2606
+ import { ContextModuleBuilder } from "@ledgerhq/context-module";
3500
2607
 
3501
2608
  // src/signer/SignerEth.ts
3502
2609
  import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
@@ -3504,7 +2611,6 @@ import { hexToBytes } from "@onekeyfe/hwk-adapter-core";
3504
2611
  // src/signer/deviceActionToPromise.ts
3505
2612
  import { DeviceActionStatus } from "@ledgerhq/device-management-kit";
3506
2613
  var IDLE_WATCHDOG_MS = 65e3;
3507
- var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3508
2614
  function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
3509
2615
  return new Promise((resolve, reject) => {
3510
2616
  let settled = false;
@@ -3692,6 +2798,7 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
3692
2798
  }
3693
2799
 
3694
2800
  // src/signer/SignerEth.ts
2801
+ var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
3695
2802
  var SignerEth = class {
3696
2803
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3697
2804
  constructor(_sdk) {
@@ -3762,7 +2869,7 @@ var SignerManager = class _SignerManager {
3762
2869
  return (args) => new SignerEthBuilder(args);
3763
2870
  }
3764
2871
  static _createContextModule() {
3765
- const contextModule = new ContextModuleBuilder({}).setChain(ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
2872
+ const contextModule = new ContextModuleBuilder({}).removeDefaultLoaders().build();
3766
2873
  return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
3767
2874
  }
3768
2875
  static wrapBlindSigningReportNonBlocking(contextModule) {
@@ -3800,27 +2907,6 @@ function collapseSignerInteraction(interaction) {
3800
2907
  return EConnectorInteraction2.ConfirmOnDevice;
3801
2908
  }
3802
2909
  }
3803
- function wireSignerToSession(ctx, sessionId, chain, signer) {
3804
- signer.onInteraction = (interaction) => {
3805
- debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
3806
- ctx.emit("ui-event", {
3807
- type: collapseSignerInteraction(interaction),
3808
- payload: { sessionId }
3809
- });
3810
- };
3811
- signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
3812
- return signer;
3813
- }
3814
- async function runSignerCall(ctx, sessionId, call) {
3815
- try {
3816
- return await call();
3817
- } catch (err) {
3818
- ctx.invalidateSession(sessionId);
3819
- throw ctx.wrapError(err);
3820
- } finally {
3821
- ctx.clearCanceller(sessionId);
3822
- }
3823
- }
3824
2910
 
3825
2911
  // src/connector/chains/evm.ts
3826
2912
  async function evmGetAddress(ctx, sessionId, params) {
@@ -3928,6 +3014,7 @@ import { hexToBytes as hexToBytes2 } from "@onekeyfe/hwk-adapter-core";
3928
3014
  function hexToUtf8(hex) {
3929
3015
  return new TextDecoder().decode(hexToBytes2(hex));
3930
3016
  }
3017
+ var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
3931
3018
  var SignerBtc = class {
3932
3019
  // eslint-disable-next-line no-useless-constructor, no-empty-function
3933
3020
  constructor(_sdk) {
@@ -3941,7 +3028,7 @@ var SignerBtc = class {
3941
3028
  return deviceActionToPromise(
3942
3029
  action,
3943
3030
  this.onInteraction,
3944
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3031
+ void 0,
3945
3032
  this.onRegisterCanceller
3946
3033
  );
3947
3034
  }
@@ -3959,7 +3046,7 @@ var SignerBtc = class {
3959
3046
  const result = await deviceActionToPromise(
3960
3047
  action,
3961
3048
  this.onInteraction,
3962
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3049
+ void 0,
3963
3050
  this.onRegisterCanceller
3964
3051
  );
3965
3052
  debugLog(
@@ -3995,7 +3082,7 @@ var SignerBtc = class {
3995
3082
  return deviceActionToPromise(
3996
3083
  action,
3997
3084
  this.onInteraction,
3998
- INTERACTIVE_TIMEOUT_MS,
3085
+ INTERACTIVE_TIMEOUT_MS2,
3999
3086
  this.onRegisterCanceller
4000
3087
  );
4001
3088
  }
@@ -4008,7 +3095,7 @@ var SignerBtc = class {
4008
3095
  return deviceActionToPromise(
4009
3096
  action,
4010
3097
  this.onInteraction,
4011
- INTERACTIVE_TIMEOUT_MS,
3098
+ INTERACTIVE_TIMEOUT_MS2,
4012
3099
  this.onRegisterCanceller
4013
3100
  );
4014
3101
  }
@@ -4021,7 +3108,7 @@ var SignerBtc = class {
4021
3108
  return deviceActionToPromise(
4022
3109
  action,
4023
3110
  this.onInteraction,
4024
- INTERACTIVE_TIMEOUT_MS,
3111
+ INTERACTIVE_TIMEOUT_MS2,
4025
3112
  this.onRegisterCanceller
4026
3113
  );
4027
3114
  }
@@ -4044,21 +3131,7 @@ function _purposeToTemplate(purpose, DDT) {
4044
3131
  });
4045
3132
  }
4046
3133
  }
4047
- function assertBitcoinMainnet(coin) {
4048
- if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
4049
- throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
4050
- code: HardwareErrorCode5.ChainNotSupported
4051
- });
4052
- }
4053
- }
4054
3134
  async function btcGetAddress(ctx, sessionId, params) {
4055
- assertBitcoinMainnet(params.coin);
4056
- if (normalizePath(params.path).split("/").length !== 3) {
4057
- throw Object.assign(
4058
- new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
4059
- { code: HardwareErrorCode5.InvalidParams }
4060
- );
4061
- }
4062
3135
  const btcSigner = await _createBtcSigner(ctx, sessionId);
4063
3136
  const path = normalizePath(params.path);
4064
3137
  try {
@@ -4089,7 +3162,6 @@ async function btcGetAddress(ctx, sessionId, params) {
4089
3162
  }
4090
3163
  }
4091
3164
  async function btcGetPublicKey(ctx, sessionId, params) {
4092
- assertBitcoinMainnet(params.coin);
4093
3165
  const btcSigner = await _createBtcSigner(ctx, sessionId);
4094
3166
  const path = normalizePath(params.path);
4095
3167
  debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
@@ -4267,8 +3339,7 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
4267
3339
  }
4268
3340
 
4269
3341
  // src/connector/chains/sol.ts
4270
- import { bytesToHex, hexToBytes as hexToBytes3, prepareSolanaOffchainMessageV1 } from "@onekeyfe/hwk-adapter-core";
4271
- import bs58 from "bs58";
3342
+ import { bytesToHex, hexToBytes as hexToBytes3 } from "@onekeyfe/hwk-adapter-core";
4272
3343
 
4273
3344
  // src/signer/SignerSol.ts
4274
3345
  var SignerSol = class {
@@ -4286,7 +3357,7 @@ var SignerSol = class {
4286
3357
  return deviceActionToPromise(
4287
3358
  action,
4288
3359
  this.onInteraction,
4289
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
3360
+ void 0,
4290
3361
  this.onRegisterCanceller
4291
3362
  );
4292
3363
  }
@@ -4298,7 +3369,7 @@ var SignerSol = class {
4298
3369
  return deviceActionToPromise(
4299
3370
  action,
4300
3371
  this.onInteraction,
4301
- INTERACTIVE_TIMEOUT_MS,
3372
+ void 0,
4302
3373
  this.onRegisterCanceller
4303
3374
  );
4304
3375
  }
@@ -4311,7 +3382,7 @@ var SignerSol = class {
4311
3382
  return deviceActionToPromise(
4312
3383
  action,
4313
3384
  this.onInteraction,
4314
- INTERACTIVE_TIMEOUT_MS,
3385
+ void 0,
4315
3386
  this.onRegisterCanceller
4316
3387
  );
4317
3388
  }
@@ -4352,21 +3423,8 @@ async function solSignMessage(ctx, sessionId, params) {
4352
3423
  const path = normalizePath(params.path);
4353
3424
  const messageBytes = hexToBytes3(params.message);
4354
3425
  try {
4355
- if (params.messageVersion === 1) {
4356
- const preparedMessage = prepareSolanaOffchainMessageV1({
4357
- message: messageBytes,
4358
- requiredSigners: params.requiredSigners
4359
- });
4360
- const { SignMessageVersion } = await ctx.importLedgerKit(
4361
- "@ledgerhq/device-signer-kit-solana"
4362
- );
4363
- const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
4364
- version: SignMessageVersion.Raw
4365
- });
4366
- return { signature: decodeBase58Signature(result2.signature) };
4367
- }
4368
3426
  const result = await solSigner.signMessage(path, messageBytes);
4369
- return { signature: decodeBase58EnvelopeSignature(result.signature) };
3427
+ return { signature: result.signature };
4370
3428
  } catch (err) {
4371
3429
  ctx.invalidateSession(sessionId);
4372
3430
  throw ctx.wrapError(err);
@@ -4374,27 +3432,11 @@ async function solSignMessage(ctx, sessionId, params) {
4374
3432
  ctx.clearCanceller(sessionId);
4375
3433
  }
4376
3434
  }
4377
- function decodeBase58Signature(signature) {
4378
- const bytes = bs58.decode(signature);
4379
- if (bytes.length !== 64) {
4380
- throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
4381
- }
4382
- return bytesToHex(bytes);
4383
- }
4384
- function decodeBase58EnvelopeSignature(envelope) {
4385
- const bytes = bs58.decode(envelope);
4386
- if (bytes.length < 65 || bytes[0] !== 1) {
4387
- throw new Error("Ledger Solana signature envelope is invalid");
4388
- }
4389
- return bytesToHex(bytes.subarray(1, 65));
4390
- }
4391
3435
  async function _createSolSigner(ctx, sessionId) {
4392
3436
  const dmk = await ctx.getOrCreateDmk();
4393
- const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
4394
- "@ledgerhq/context-module"
4395
- );
3437
+ const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit("@ledgerhq/context-module");
4396
3438
  const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
4397
- const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
3439
+ const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
4398
3440
  const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
4399
3441
  const signer = new SignerSol(sdkSigner);
4400
3442
  signer.onInteraction = (interaction) => {
@@ -4410,147 +3452,361 @@ async function _createSolSigner(ctx, sessionId) {
4410
3452
  return signer;
4411
3453
  }
4412
3454
 
4413
- // src/connector/chains/zcash.ts
4414
- import { bytesToHex as bytesToHex2 } from "@onekeyfe/hwk-adapter-core";
3455
+ // src/connector/chains/tron.ts
3456
+ import { HardwareErrorCode as HardwareErrorCode7 } from "@onekeyfe/hwk-adapter-core";
3457
+ import Trx from "@ledgerhq/hw-app-trx";
4415
3458
 
4416
- // src/signer/SignerZcash.ts
4417
- var SignerZcash = class {
4418
- // eslint-disable-next-line no-useless-constructor, no-empty-function
4419
- constructor(_sdk) {
4420
- this._sdk = _sdk;
3459
+ // src/connector/chains/legacyChainCall.ts
3460
+ import { EConnectorInteraction as EConnectorInteraction3 } from "@onekeyfe/hwk-adapter-core";
3461
+
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;
4421
3486
  }
4422
- /** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
4423
- async getFullViewingKey(derivationPath, options) {
4424
- const action = this._sdk.getFullViewingKey(derivationPath, options);
4425
- return deviceActionToPromise(
4426
- action,
4427
- this.onInteraction,
4428
- void 0,
4429
- this.onRegisterCanceller
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);
3528
+ }
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
+ }
4430
3565
  );
4431
3566
  }
4432
- /** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
4433
- async getShieldedAddress(derivationPath, options) {
4434
- const action = this._sdk.getShieldedAddress(derivationPath, options);
4435
- return deviceActionToPromise(
4436
- action,
4437
- this.onInteraction,
4438
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4439
- this.onRegisterCanceller
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})`
4440
3629
  );
4441
3630
  }
3631
+ _isDashboard(appName) {
3632
+ return appName === DASHBOARD_APP_NAME;
3633
+ }
3634
+ _wait() {
3635
+ return new Promise((resolve) => setTimeout(resolve, this._waitMs));
3636
+ }
4442
3637
  };
4443
3638
 
4444
- // src/connector/chains/zcash.ts
4445
- async function zcashGetFullViewingKey(ctx, sessionId, params) {
4446
- const signer = await _createZcashSigner(ctx, sessionId);
4447
- const path = normalizePath(params.path);
4448
- const mode = params.mode ?? "ufvk";
4449
- return runSignerCall(ctx, sessionId, async () => {
4450
- const result = await signer.getFullViewingKey(path, { mode });
4451
- if (result.mode === "ufvk") {
4452
- return { path: params.path, mode, ufvk: result.fullViewingKey };
4453
- }
4454
- return { path: params.path, mode, orchardFvk: bytesToHex2(result.fullViewingKey) };
4455
- });
3639
+ // src/connector/chains/legacyChainCall.ts
3640
+ function isLegacyWrongAppError(err, _appName) {
3641
+ return isWrongAppError(err);
4456
3642
  }
4457
- async function zcashGetShieldedAddress(ctx, sessionId, params) {
4458
- const signer = await _createZcashSigner(ctx, sessionId);
4459
- const path = normalizePath(params.path);
4460
- return runSignerCall(ctx, sessionId, async () => {
4461
- const result = await signer.getShieldedAddress(path, {
4462
- checkOnDevice: params.showOnDevice ?? false
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 }
4463
3651
  });
4464
- return { address: result.address, path: params.path };
4465
- });
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
+ }
4466
3719
  }
4467
- async function _createZcashSigner(ctx, sessionId) {
3720
+ async function _ensureAppOpen(ctx, sessionId, appName, onPrompt) {
4468
3721
  const dmk = await ctx.getOrCreateDmk();
4469
- const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
4470
- const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
4471
- return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
3722
+ const appManager = new AppManager(dmk);
3723
+ await appManager.ensureAppOpen(sessionId, appName, onPrompt);
4472
3724
  }
4473
3725
 
4474
- // src/connector/chains/tron.ts
4475
- import { HardwareErrorCode as HardwareErrorCode6, bytesToHex as bytesToHex3, hexToBytes as hexToBytes4 } from "@onekeyfe/hwk-adapter-core";
4476
-
4477
- // src/signer/SignerTron.ts
4478
- var SignerTron = class {
4479
- // eslint-disable-next-line no-useless-constructor, no-empty-function
4480
- constructor(_sdk) {
4481
- this._sdk = _sdk;
4482
- }
4483
- /** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
4484
- async getAddress(derivationPath, options) {
4485
- const action = this._sdk.getAddress(derivationPath, options);
4486
- const result = await deviceActionToPromise(
4487
- action,
4488
- this.onInteraction,
4489
- options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
4490
- this.onRegisterCanceller
4491
- );
4492
- return { address: result.address, publicKey: result.publicKey };
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;
4493
3733
  }
4494
- /** Sign a protobuf-encoded raw transaction. */
4495
- async signTransaction(derivationPath, transaction, options) {
4496
- const action = this._sdk.signTransaction(derivationPath, transaction, options);
4497
- return deviceActionToPromise(
4498
- action,
4499
- this.onInteraction,
4500
- INTERACTIVE_TIMEOUT_MS,
4501
- this.onRegisterCanceller
4502
- );
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;
4503
3746
  }
4504
- /** Sign a personal message (TIP-191). */
4505
- async signPersonalMessage(derivationPath, message, options) {
4506
- const action = this._sdk.signPersonalMessage(derivationPath, message, options);
4507
- return deviceActionToPromise(
4508
- action,
4509
- this.onInteraction,
4510
- INTERACTIVE_TIMEOUT_MS,
4511
- this.onRegisterCanceller
4512
- );
3747
+ async close() {
4513
3748
  }
4514
3749
  };
4515
3750
 
4516
3751
  // src/connector/chains/tron.ts
4517
3752
  async function tronGetAddress(ctx, sessionId, params) {
4518
- const tronSigner = await _createTronSigner(ctx, sessionId);
4519
3753
  const path = normalizePath(params.path);
4520
- return runSignerCall(ctx, sessionId, async () => {
4521
- const result = await tronSigner.getAddress(path, {
4522
- checkOnDevice: params.showOnDevice ?? false
4523
- });
4524
- return { address: result.address, publicKey: result.publicKey, path: params.path };
4525
- });
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
+ );
4526
3770
  }
4527
3771
  async function tronSignTransaction(ctx, sessionId, params) {
4528
3772
  if (!params.rawTxHex) {
4529
3773
  throw Object.assign(
4530
3774
  new Error("TRON signing requires a protobuf-encoded raw transaction hex (rawTxHex)."),
4531
- { code: HardwareErrorCode6.InvalidParams }
3775
+ { code: HardwareErrorCode7.InvalidParams }
4532
3776
  );
4533
3777
  }
4534
- const tronSigner = await _createTronSigner(ctx, sessionId);
4535
3778
  const path = normalizePath(params.path);
4536
- return runSignerCall(ctx, sessionId, async () => {
4537
- const signature = await tronSigner.signTransaction(path, hexToBytes4(params.rawTxHex));
4538
- return { signature: bytesToHex3(signature) };
4539
- });
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
+ );
4540
3793
  }
4541
3794
  async function tronSignMessage(ctx, sessionId, params) {
4542
- const tronSigner = await _createTronSigner(ctx, sessionId);
4543
3795
  const path = normalizePath(params.path);
4544
- return runSignerCall(ctx, sessionId, async () => {
4545
- const signature = await tronSigner.signPersonalMessage(path, hexToBytes4(params.messageHex));
4546
- return { signature: bytesToHex3(signature) };
4547
- });
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
+ );
4548
3806
  }
4549
- async function _createTronSigner(ctx, sessionId) {
3807
+ async function _createTrx(ctx, sessionId) {
4550
3808
  const dmk = await ctx.getOrCreateDmk();
4551
- const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
4552
- const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
4553
- return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
3809
+ return new Trx(new DmkTransport(dmk, sessionId));
4554
3810
  }
4555
3811
 
4556
3812
  // src/device-apps/customActions.ts
@@ -4729,7 +3985,7 @@ var DeviceApps = class {
4729
3985
  seTargetId: v.seTargetId,
4730
3986
  mcuTargetId: v.mcuTargetId,
4731
3987
  seVersion: v.seVersion,
4732
- seFlagsHex: bytesToHex4(v.seFlags),
3988
+ seFlagsHex: bytesToHex2(v.seFlags),
4733
3989
  mcuSephVersion: v.mcuSephVersion,
4734
3990
  mcuBootloaderVersion: v.mcuBootloaderVersion,
4735
3991
  hwVersion: v.hwVersion
@@ -4803,7 +4059,7 @@ var DeviceApps = class {
4803
4059
  }
4804
4060
  }
4805
4061
  };
4806
- function bytesToHex4(bytes) {
4062
+ function bytesToHex2(bytes) {
4807
4063
  if (!bytes) return "";
4808
4064
  return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
4809
4065
  }
@@ -4846,11 +4102,10 @@ var METHOD_PREFIX_TO_APP_NAME = {
4846
4102
  evm: "Ethereum",
4847
4103
  btc: "Bitcoin",
4848
4104
  sol: "Solana",
4849
- tron: "Tron",
4850
- zcash: "Zcash"
4105
+ tron: "Tron"
4851
4106
  };
4852
4107
  var HARDWARE_ERROR_CODE_VALUES = new Set(
4853
- Object.values(HardwareErrorCode7).filter((value) => typeof value === "number")
4108
+ Object.values(HardwareErrorCode8).filter((value) => typeof value === "number")
4854
4109
  );
4855
4110
  var BLE_CONNECT_SCAN_TIMEOUT_MS = 1500;
4856
4111
  var LEDGER_RELAY_ALLOWED_ROOT_DOMAINS = ["onekeytest.com", "onekey.com"];
@@ -4887,10 +4142,6 @@ async function defaultLedgerKitImporter(pkg) {
4887
4142
  return import("@ledgerhq/device-signer-kit-bitcoin");
4888
4143
  case "@ledgerhq/device-signer-kit-solana":
4889
4144
  return import("@ledgerhq/device-signer-kit-solana");
4890
- case "@ledgerhq/device-signer-kit-tron":
4891
- return import("@ledgerhq/device-signer-kit-tron");
4892
- case "@ledgerhq/device-signer-kit-zcash":
4893
- return import("@ledgerhq/device-signer-kit-zcash");
4894
4145
  case "@ledgerhq/context-module":
4895
4146
  return import("@ledgerhq/context-module");
4896
4147
  default:
@@ -4950,7 +4201,6 @@ var LedgerConnectorBase = class {
4950
4201
  this._ctx = {
4951
4202
  emit: (event, data) => this._emit(event, data),
4952
4203
  invalidateSession: (sid) => this._invalidateSession(sid),
4953
- teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
4954
4204
  wrapError: (err, opts) => this._wrapError(err, opts),
4955
4205
  getOrCreateDmk: () => this._getOrCreateDmk(),
4956
4206
  getDeviceManager: () => this._getDeviceManager(),
@@ -5050,7 +4300,7 @@ var LedgerConnectorBase = class {
5050
4300
  `Ledger BLE connect did not return within ${HANG_CEILING_MS / 6e4}min \u2014 DMK hang fallback.`
5051
4301
  );
5052
4302
  err._tag = ERROR_TAG.BlePairingTimeout;
5053
- err.code = HardwareErrorCode7.BlePairingTimeout;
4303
+ err.code = HardwareErrorCode8.BlePairingTimeout;
5054
4304
  reject(err);
5055
4305
  }, HANG_CEILING_MS);
5056
4306
  });
@@ -5083,7 +4333,7 @@ var LedgerConnectorBase = class {
5083
4333
  "Ledger device is not currently advertising. Wake up and unlock the device, keep it nearby, then try again."
5084
4334
  );
5085
4335
  err._tag = ERROR_TAG.DeviceNotAdvertising;
5086
- err.code = HardwareErrorCode7.DeviceNotFound;
4336
+ err.code = HardwareErrorCode8.DeviceNotFound;
5087
4337
  throw err;
5088
4338
  };
5089
4339
  const doConnect = async (path) => {
@@ -5140,14 +4390,14 @@ var LedgerConnectorBase = class {
5140
4390
  this._resetSignersAndSessions();
5141
4391
  if (isLedgerBleConnectionType(this.connectionType)) {
5142
4392
  const tag = err?._tag;
5143
- if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
4393
+ if (isKnownConnectionTag(tag)) {
5144
4394
  throw err;
5145
4395
  }
5146
4396
  const wrapped = new Error(
5147
4397
  "Ledger Bluetooth pairing failed. Make sure the device is unlocked and nearby, then try again."
5148
4398
  );
5149
4399
  wrapped._tag = ERROR_TAG.BleGattBondingFailed;
5150
- wrapped.code = HardwareErrorCode7.BlePairingTimeout;
4400
+ wrapped.code = HardwareErrorCode8.BlePairingTimeout;
5151
4401
  wrapped.originalError = err;
5152
4402
  throw wrapped;
5153
4403
  }
@@ -5225,7 +4475,7 @@ var LedgerConnectorBase = class {
5225
4475
  this._unwatchSessionState(sessionId);
5226
4476
  this._signerManager?.invalidate(sessionId);
5227
4477
  this._cancellers.get(sessionId)?.({
5228
- code: HardwareErrorCode7.DeviceDisconnected,
4478
+ code: HardwareErrorCode8.DeviceDisconnected,
5229
4479
  tag: "DeviceDisconnected",
5230
4480
  message: "Device disconnected"
5231
4481
  });
@@ -5251,7 +4501,7 @@ var LedgerConnectorBase = class {
5251
4501
  success: false,
5252
4502
  error: serializeConnectorError(
5253
4503
  Object.assign(new Error("Ledger app is unresponsive"), {
5254
- code: HardwareErrorCode7.DeviceAppStuck,
4504
+ code: HardwareErrorCode8.DeviceAppStuck,
5255
4505
  _tag: ERROR_TAG.DeviceAppStuck,
5256
4506
  originalError: err
5257
4507
  })
@@ -5263,7 +4513,7 @@ var LedgerConnectorBase = class {
5263
4513
  success: false,
5264
4514
  error: serializeConnectorError(
5265
4515
  Object.assign(new Error("Device communication interrupted, please retry"), {
5266
- code: HardwareErrorCode7.TransportError,
4516
+ code: HardwareErrorCode8.TransportError,
5267
4517
  _tag: ERROR_TAG.DeviceTransportStuck,
5268
4518
  originalError: err
5269
4519
  })
@@ -5309,11 +4559,6 @@ var LedgerConnectorBase = class {
5309
4559
  return solSignTransaction(ctx, sessionId, params);
5310
4560
  case "solSignMessage":
5311
4561
  return solSignMessage(ctx, sessionId, params);
5312
- // ZCASH
5313
- case "zcashGetFullViewingKey":
5314
- return zcashGetFullViewingKey(ctx, sessionId, params);
5315
- case "zcashGetShieldedAddress":
5316
- return zcashGetShieldedAddress(ctx, sessionId, params);
5317
4562
  // TRON
5318
4563
  case "tronGetAddress":
5319
4564
  return tronGetAddress(ctx, sessionId, params);
@@ -5338,7 +4583,7 @@ var LedgerConnectorBase = class {
5338
4583
  try {
5339
4584
  return await apps.install(p.appName, ({ progress }) => {
5340
4585
  ctx.emit("ui-event", {
5341
- type: EConnectorInteraction3.AppInstallProgress,
4586
+ type: EConnectorInteraction4.AppInstallProgress,
5342
4587
  payload: {
5343
4588
  sessionId,
5344
4589
  appName: p.appName,
@@ -5347,7 +4592,7 @@ var LedgerConnectorBase = class {
5347
4592
  });
5348
4593
  });
5349
4594
  } catch (err) {
5350
- ctx.teardownSecureChannelSession(sessionId);
4595
+ ctx.invalidateSession(sessionId);
5351
4596
  throw ctx.wrapError(err);
5352
4597
  } finally {
5353
4598
  ctx.clearCanceller(sessionId);
@@ -5437,7 +4682,7 @@ var LedgerConnectorBase = class {
5437
4682
  );
5438
4683
  return { isGenuine: output.isGenuine, deviceId };
5439
4684
  } catch (err) {
5440
- ctx.teardownSecureChannelSession(sessionId);
4685
+ ctx.invalidateSession(sessionId);
5441
4686
  throw ctx.wrapError(err);
5442
4687
  } finally {
5443
4688
  ctx.clearCanceller(sessionId);
@@ -5559,17 +4804,6 @@ var LedgerConnectorBase = class {
5559
4804
  _invalidateSession(sessionId) {
5560
4805
  this._signerManager?.invalidate(sessionId);
5561
4806
  }
5562
- _teardownSecureChannelSession(sessionId) {
5563
- const cancel = this._cancellers.get(sessionId);
5564
- this._cancellers.delete(sessionId);
5565
- if (cancel) {
5566
- try {
5567
- cancel();
5568
- } catch {
5569
- }
5570
- }
5571
- this._invalidateSession(sessionId);
5572
- }
5573
4807
  /**
5574
4808
  * Replace an old session with a new one after app switch.
5575
4809
  * Emits device-connect so the adapter updates its _sessions Map.
@@ -5654,7 +4888,7 @@ var LedgerConnectorBase = class {
5654
4888
  * at every catch site. Falls through unchanged for unknown methods.
5655
4889
  */
5656
4890
  _ctxForMethod(method) {
5657
- const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
4891
+ const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
5658
4892
  const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
5659
4893
  if (!defaultAppName) return this._ctx;
5660
4894
  return {
@@ -5688,209 +4922,6 @@ var LedgerConnectorBase = class {
5688
4922
  return error;
5689
4923
  }
5690
4924
  };
5691
-
5692
- // src/transport/DmkTransport.ts
5693
- import Transport from "@ledgerhq/hw-transport";
5694
- var DmkTransport = class extends Transport {
5695
- constructor(dmk, sessionId) {
5696
- super();
5697
- this._dmk = dmk;
5698
- this._sessionId = sessionId;
5699
- }
5700
- async exchange(apdu) {
5701
- const response = await this._dmk.sendApdu({
5702
- sessionId: this._sessionId,
5703
- apdu: new Uint8Array(apdu)
5704
- });
5705
- const { data, statusCode } = response;
5706
- const result = Buffer.alloc(data.length + 2);
5707
- if (data.length > 0) {
5708
- result.set(data, 0);
5709
- }
5710
- result.set(statusCode, data.length);
5711
- return result;
5712
- }
5713
- async close() {
5714
- }
5715
- };
5716
-
5717
- // src/app/AppManager.ts
5718
- import {
5719
- CloseAppCommand,
5720
- GetAppAndVersionCommand,
5721
- OpenAppCommand,
5722
- isSuccessCommandResult
5723
- } from "@ledgerhq/device-management-kit";
5724
- import { HardwareErrorCode as HardwareErrorCode8 } from "@onekeyfe/hwk-adapter-core";
5725
- var APP_NAME_MAP = {
5726
- ETH: "Ethereum",
5727
- BTC: "Bitcoin",
5728
- SOL: "Solana",
5729
- TRX: "Tron",
5730
- ZEC: "Zcash",
5731
- XRP: "XRP",
5732
- ADA: "Cardano",
5733
- DOT: "Polkadot",
5734
- ATOM: "Cosmos"
5735
- };
5736
- var DASHBOARD_APP_NAME = "BOLOS";
5737
- var AppManager = class {
5738
- constructor(dmk, options) {
5739
- this._dmk = dmk;
5740
- this._waitMs = options?.waitMs ?? 1e3;
5741
- this._maxRetries = options?.maxRetries ?? 10;
5742
- }
5743
- /**
5744
- * Return the Ledger app name for a given chain ticker,
5745
- * or undefined if the chain is not supported.
5746
- */
5747
- static getAppName(chain) {
5748
- return APP_NAME_MAP[chain];
5749
- }
5750
- /**
5751
- * Ensure the target app is open on the device identified by `sessionId`.
5752
- *
5753
- * Flow:
5754
- * 1. Check the currently running app.
5755
- * 2. If it is already the target, return immediately.
5756
- * 3. If a different app is running (not dashboard), close it first.
5757
- * 4. Open the target app.
5758
- * 5. Poll until the device confirms the target app is running.
5759
- */
5760
- /**
5761
- * @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
5762
- * device is about to display "Open <app>" on screen and wait for the
5763
- * user's button press. UI consumers should show their "open app" prompt
5764
- * in response. NOT called when the target app is already open (no user
5765
- * interaction needed in that case).
5766
- *
5767
- * Important: OpenAppCommand is blocking. It does not resolve until the user
5768
- * has physically confirmed on the device, so anything that runs AFTER
5769
- * `await this._openApp(...)` lands AFTER the prompt is already gone.
5770
- * Hence the callback must fire BEFORE that await.
5771
- */
5772
- async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
5773
- const currentApp = await this._getCurrentApp(sessionId);
5774
- if (currentApp === targetAppName) {
5775
- return;
5776
- }
5777
- if (!this._isDashboard(currentApp)) {
5778
- await this._closeCurrentApp(sessionId);
5779
- await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
5780
- }
5781
- onConfirmOnDevice?.();
5782
- await this._openApp(sessionId, targetAppName);
5783
- await this._waitForApp(sessionId, targetAppName);
5784
- }
5785
- // ---------------------------------------------------------------------------
5786
- // Private helpers
5787
- // ---------------------------------------------------------------------------
5788
- async _getCurrentApp(sessionId) {
5789
- const result = await this._dmk.sendCommand({
5790
- sessionId,
5791
- command: new GetAppAndVersionCommand()
5792
- });
5793
- if (isSuccessCommandResult(result)) {
5794
- debugLog("[AppManager] currentApp:", result.data.name);
5795
- return result.data.name;
5796
- }
5797
- const errResult = result;
5798
- const dmkErr = errResult.error ?? {};
5799
- const original = dmkErr.originalError;
5800
- debugLog(
5801
- "[AppManager] _getCurrentApp failed sessionId=",
5802
- sessionId,
5803
- "tag=",
5804
- dmkErr._tag,
5805
- "errorCode=",
5806
- dmkErr.errorCode,
5807
- "message=",
5808
- dmkErr.message,
5809
- "originalErrorMessage=",
5810
- original?.message ?? String(original ?? "")
5811
- );
5812
- throw Object.assign(
5813
- new Error(
5814
- dmkErr.message ?? "Failed to get current app from device"
5815
- ),
5816
- {
5817
- _tag: dmkErr._tag,
5818
- errorCode: dmkErr.errorCode,
5819
- originalError: original
5820
- }
5821
- );
5822
- }
5823
- async _openApp(sessionId, appName) {
5824
- const result = await this._dmk.sendCommand({
5825
- sessionId,
5826
- command: new OpenAppCommand({ appName })
5827
- });
5828
- if (!isSuccessCommandResult(result)) {
5829
- const dmkErr = result.error;
5830
- const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
5831
- const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
5832
- debugLog(
5833
- "[AppManager] openApp failed:",
5834
- appName,
5835
- "errorCode:",
5836
- errorCode,
5837
- "tag:",
5838
- dmkErr._tag
5839
- );
5840
- let code;
5841
- if (errorCode === "6807" || /unknown application/i.test(message)) {
5842
- code = HardwareErrorCode8.AppNotInstalled;
5843
- } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
5844
- code = HardwareErrorCode8.UserRejected;
5845
- }
5846
- throw Object.assign(new Error(`Failed to open "${appName}"`), {
5847
- _tag: ERROR_TAG.OpenAppCommand,
5848
- code,
5849
- errorCode,
5850
- statusCode: errorCode,
5851
- appName,
5852
- originalError: dmkErr
5853
- });
5854
- }
5855
- }
5856
- async _closeCurrentApp(sessionId) {
5857
- debugLog("[AppManager] closeCurrentApp");
5858
- await this._dmk.sendCommand({
5859
- sessionId,
5860
- command: new CloseAppCommand()
5861
- });
5862
- }
5863
- /**
5864
- * Poll the device until the expected app is reported as running,
5865
- * or throw after `_maxRetries` attempts.
5866
- */
5867
- async _waitForApp(sessionId, expectedAppName) {
5868
- let lastSeen = "";
5869
- for (let i = 0; i < this._maxRetries; i++) {
5870
- await this._wait();
5871
- const current = await this._getCurrentApp(sessionId);
5872
- lastSeen = current;
5873
- if (current === expectedAppName) {
5874
- return;
5875
- }
5876
- }
5877
- debugLog(
5878
- "[AppManager] waitForApp exhausted: expected=",
5879
- expectedAppName,
5880
- "lastSeen=",
5881
- lastSeen
5882
- );
5883
- throw new Error(
5884
- `Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
5885
- );
5886
- }
5887
- _isDashboard(appName) {
5888
- return appName === DASHBOARD_APP_NAME;
5889
- }
5890
- _wait() {
5891
- return new Promise((resolve) => setTimeout(resolve, this._waitMs));
5892
- }
5893
- };
5894
4925
  export {
5895
4926
  AppManager,
5896
4927
  DmkTransport,
@@ -5901,7 +4932,6 @@ export {
5901
4932
  SignerEth,
5902
4933
  SignerManager,
5903
4934
  SignerSol,
5904
- SignerZcash,
5905
4935
  debugLog,
5906
4936
  deviceActionToPromise,
5907
4937
  isDeviceLockedError,