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

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