@onekeyfe/hwk-ledger-adapter 1.1.27-alpha.7 → 1.1.27-patch.1

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
@@ -452,6 +452,53 @@ function mapLedgerError(err, opts) {
452
452
 
453
453
  // src/adapter/methods/allNetworkGetAddress.ts
454
454
  import { HardwareErrorCode as HardwareErrorCode2, failure, success } from "@onekeyfe/hwk-adapter-core";
455
+
456
+ // src/utils/sdkEventBus.ts
457
+ var listeners = /* @__PURE__ */ new Set();
458
+ function onSdkEvent(listener) {
459
+ listeners.add(listener);
460
+ return () => {
461
+ listeners.delete(listener);
462
+ };
463
+ }
464
+ function offSdkEvent(listener) {
465
+ listeners.delete(listener);
466
+ }
467
+ function emitSdkEvent(event) {
468
+ if (listeners.size === 0) return;
469
+ for (const listener of listeners) {
470
+ try {
471
+ listener(event);
472
+ } catch {
473
+ }
474
+ }
475
+ }
476
+ function emitLog(level, ...args) {
477
+ if (listeners.size === 0) return;
478
+ const message = args.map((a) => typeof a === "string" ? a : safeStringify(a)).join(" ");
479
+ emitSdkEvent({ type: "log", level, message });
480
+ }
481
+ function safeStringify(value) {
482
+ if (value instanceof Error) {
483
+ return value.stack ? `${value.message}
484
+ ${value.stack}` : value.message;
485
+ }
486
+ try {
487
+ return JSON.stringify(value);
488
+ } catch {
489
+ return String(value);
490
+ }
491
+ }
492
+
493
+ // src/utils/debugLog.ts
494
+ function debugLog(...args) {
495
+ emitLog("debug", ...args);
496
+ }
497
+ function debugError(...args) {
498
+ emitLog("error", ...args);
499
+ }
500
+
501
+ // src/adapter/methods/allNetworkGetAddress.ts
455
502
  var LEDGER_BTC_NETWORK_COIN_MAP = {
456
503
  tbtc: "Testnet",
457
504
  bch: "Bcash",
@@ -464,6 +511,7 @@ function createAllNetworkGetAddress({
464
511
  getChainFingerprint
465
512
  }) {
466
513
  return async function allNetworkGetAddress(connectId, _deviceId, params) {
514
+ debugLog("[LedgerAdapter][REQ]", { method: "allNetworkGetAddress", connectId, params });
467
515
  const installContext = {};
468
516
  const commonParams = {
469
517
  autoInstallApp: params.autoInstallApp
@@ -491,23 +539,37 @@ function createAllNetworkGetAddress({
491
539
  chainFingerprints
492
540
  );
493
541
  if (isTopLevelAllNetworkFailure(response)) {
494
- return failure(
495
- HardwareErrorCode2.DeviceMismatch,
496
- response.payload?.error ?? "Device mismatch",
542
+ const code = response.payload?.code ?? HardwareErrorCode2.DeviceMismatch;
543
+ const result2 = failure(
544
+ code,
545
+ response.payload?.error ?? "All-network get-address aborted",
497
546
  response.payload?.params
498
547
  );
548
+ debugLog("[LedgerAdapter][RES]", {
549
+ method: "allNetworkGetAddress",
550
+ success: false,
551
+ payload: result2
552
+ });
553
+ return result2;
499
554
  }
500
555
  responses.push(response);
501
556
  }
502
557
  }
503
- return success(responses);
558
+ const result = success(responses);
559
+ debugLog("[LedgerAdapter][RES]", {
560
+ method: "allNetworkGetAddress",
561
+ success: true,
562
+ payload: result
563
+ });
564
+ return result;
504
565
  };
505
566
  }
506
567
  function isTopLevelAllNetworkFailure(response) {
507
568
  if (response.success) {
508
569
  return false;
509
570
  }
510
- return response.payload?.code === HardwareErrorCode2.DeviceMismatch;
571
+ const code = response.payload?.code;
572
+ return code === HardwareErrorCode2.DeviceMismatch || code === HardwareErrorCode2.UserAborted || code === HardwareErrorCode2.UserRejected;
511
573
  }
512
574
  function getItemDeviceId(item) {
513
575
  const { deviceId } = item;
@@ -682,51 +744,6 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
682
744
  return isLedgerBleConnectionType(connectionType) || isLedgerDmkBleTransport(descriptor.transport);
683
745
  }
684
746
 
685
- // src/utils/sdkEventBus.ts
686
- var listeners = /* @__PURE__ */ new Set();
687
- function onSdkEvent(listener) {
688
- listeners.add(listener);
689
- return () => {
690
- listeners.delete(listener);
691
- };
692
- }
693
- function offSdkEvent(listener) {
694
- listeners.delete(listener);
695
- }
696
- function emitSdkEvent(event) {
697
- if (listeners.size === 0) return;
698
- for (const listener of listeners) {
699
- try {
700
- listener(event);
701
- } catch {
702
- }
703
- }
704
- }
705
- function emitLog(level, ...args) {
706
- if (listeners.size === 0) return;
707
- const message = args.map((a) => typeof a === "string" ? a : safeStringify(a)).join(" ");
708
- emitSdkEvent({ type: "log", level, message });
709
- }
710
- function safeStringify(value) {
711
- if (value instanceof Error) {
712
- return value.stack ? `${value.message}
713
- ${value.stack}` : value.message;
714
- }
715
- try {
716
- return JSON.stringify(value);
717
- } catch {
718
- return String(value);
719
- }
720
- }
721
-
722
- // src/utils/debugLog.ts
723
- function debugLog(...args) {
724
- emitLog("debug", ...args);
725
- }
726
- function debugError(...args) {
727
- emitLog("error", ...args);
728
- }
729
-
730
747
  // src/adapter/LedgerAdapter.ts
731
748
  function formatDeviceMismatchError(expected, actual) {
732
749
  return `Wrong device: expected ${expected}, got ${actual}`;
@@ -885,30 +902,42 @@ var _LedgerAdapter = class _LedgerAdapter {
885
902
  // Device management
886
903
  // ---------------------------------------------------------------------------
887
904
  async searchDevices(options) {
888
- if (options?.resetSession) {
889
- this._doConnectAbortController?.abort();
890
- this._sessions.clear();
891
- this._connectingPromise = null;
892
- this._doConnectAbortController = null;
893
- this._btcHighIndexConfirmedThisSession = false;
894
- }
895
- await this._ensureDevicePermission();
896
- const devices = await this.connector.searchDevices();
897
- this._discoveredDevices.clear();
898
- for (const d of devices) {
899
- if (d.connectId) {
900
- this._discoveredDevices.set(d.connectId, this.connectorDeviceToDeviceInfo(d));
905
+ debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
906
+ try {
907
+ if (options?.resetSession) {
908
+ this._doConnectAbortController?.abort();
909
+ this._sessions.clear();
910
+ this._connectingPromise = null;
911
+ this._doConnectAbortController = null;
912
+ this._btcHighIndexConfirmedThisSession = false;
901
913
  }
902
- }
903
- if (this._discoveredDevices.size === 0) {
904
914
  await this._ensureDevicePermission();
915
+ const devices = await this.connector.searchDevices();
916
+ this._discoveredDevices.clear();
917
+ for (const d of devices) {
918
+ if (d.connectId) {
919
+ this._discoveredDevices.set(d.connectId, this.connectorDeviceToDeviceInfo(d));
920
+ }
921
+ }
922
+ if (this._discoveredDevices.size === 0) {
923
+ await this._ensureDevicePermission();
924
+ }
925
+ const result = Array.from(this._discoveredDevices.values());
926
+ debugLog("[LedgerAdapter][RES]", {
927
+ method: "searchDevices",
928
+ success: true,
929
+ payload: result
930
+ });
931
+ return result;
932
+ } catch (err) {
933
+ const e = err;
934
+ debugLog("[LedgerAdapter][RES]", {
935
+ method: "searchDevices",
936
+ success: false,
937
+ error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
938
+ });
939
+ throw err;
905
940
  }
906
- debugLog(
907
- `[LedgerAdapter] searchDevices() return count=${this._discoveredDevices.size} ids=[${[
908
- ...this._discoveredDevices.keys()
909
- ].join(",")}]`
910
- );
911
- return Array.from(this._discoveredDevices.values());
912
941
  }
913
942
  // USB single-session invariant: evict all sessions, best-effort (see connectDevice).
914
943
  async _evictAllSessions() {
@@ -928,6 +957,7 @@ var _LedgerAdapter = class _LedgerAdapter {
928
957
  });
929
958
  }
930
959
  async connectDevice(connectId) {
960
+ debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
931
961
  try {
932
962
  if (isLedgerBleConnectionType(this.connector.connectionType) && !connectId) {
933
963
  throw Object.assign(new Error("Ledger BLE connectId is required."), {
@@ -943,28 +973,79 @@ var _LedgerAdapter = class _LedgerAdapter {
943
973
  if (session.deviceInfo) {
944
974
  this._discoveredDevices.set(connectId, session.deviceInfo);
945
975
  }
946
- return success2(connectId);
976
+ const result = success2(connectId);
977
+ debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
978
+ return result;
947
979
  } catch (err) {
948
- return this.errorToFailure(err);
980
+ const failureResult = this.errorToFailure(err);
981
+ debugLog("[LedgerAdapter][RES]", {
982
+ method: "connectDevice",
983
+ success: false,
984
+ payload: failureResult
985
+ });
986
+ return failureResult;
949
987
  }
950
988
  }
951
989
  async disconnectDevice(connectId) {
952
- const sessionId = this._sessions.get(connectId);
953
- if (sessionId) {
954
- await this.connector.disconnect(sessionId);
955
- this._sessions.delete(connectId);
990
+ debugLog("[LedgerAdapter][REQ]", {
991
+ method: "disconnectDevice",
992
+ connectId,
993
+ params: { connectId }
994
+ });
995
+ try {
996
+ const sessionId = this._sessions.get(connectId);
997
+ if (sessionId) {
998
+ await this.connector.disconnect(sessionId);
999
+ this._sessions.delete(connectId);
1000
+ }
1001
+ debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
1002
+ } catch (err) {
1003
+ const e = err;
1004
+ debugLog("[LedgerAdapter][RES]", {
1005
+ method: "disconnectDevice",
1006
+ success: false,
1007
+ error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1008
+ });
1009
+ throw err;
956
1010
  }
957
1011
  }
958
1012
  async getDeviceInfo(connectId, deviceId) {
959
- await this._ensureDevicePermission(connectId, deviceId);
960
- const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
961
- if (cached) {
962
- return success2(cached);
1013
+ debugLog("[LedgerAdapter][REQ]", {
1014
+ method: "getDeviceInfo",
1015
+ connectId,
1016
+ params: { connectId, deviceId }
1017
+ });
1018
+ try {
1019
+ await this._ensureDevicePermission(connectId, deviceId);
1020
+ const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
1021
+ if (cached) {
1022
+ const result = success2(cached);
1023
+ debugLog("[LedgerAdapter][RES]", {
1024
+ method: "getDeviceInfo",
1025
+ success: true,
1026
+ payload: result
1027
+ });
1028
+ return result;
1029
+ }
1030
+ const notFound = failure2(
1031
+ HardwareErrorCode3.DeviceNotFound,
1032
+ "Device not found in cache. Call searchDevices() or wait for a device-connected event first."
1033
+ );
1034
+ debugLog("[LedgerAdapter][RES]", {
1035
+ method: "getDeviceInfo",
1036
+ success: false,
1037
+ payload: notFound
1038
+ });
1039
+ return notFound;
1040
+ } catch (err) {
1041
+ const e = err;
1042
+ debugLog("[LedgerAdapter][RES]", {
1043
+ method: "getDeviceInfo",
1044
+ success: false,
1045
+ error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
1046
+ });
1047
+ throw err;
963
1048
  }
964
- return failure2(
965
- HardwareErrorCode3.DeviceNotFound,
966
- "Device not found in cache. Call searchDevices() or wait for a device-connected event first."
967
- );
968
1049
  }
969
1050
  getSupportedChains() {
970
1051
  return ["evm", "btc", "sol", "tron"];
@@ -1632,26 +1713,42 @@ var _LedgerAdapter = class _LedgerAdapter {
1632
1713
  return this._unwrapConnectorResult(result);
1633
1714
  }
1634
1715
  async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
1635
- debugLog("[LedgerAdapter] connectorCall:", method, "connectId:", connectId || "(empty)");
1716
+ debugLog("[LedgerAdapter][REQ]", { method, connectId: connectId || "(empty)", params });
1636
1717
  const queueKey = connectId || "__ledger_default__";
1637
- return this._jobQueue.enqueue(
1638
- queueKey,
1639
- async (signal) => this._runConnectorCall(
1640
- connectId,
1718
+ try {
1719
+ const result = await this._jobQueue.enqueue(
1720
+ queueKey,
1721
+ async (signal) => this._runConnectorCall(
1722
+ connectId,
1723
+ method,
1724
+ params,
1725
+ signal,
1726
+ fingerprint,
1727
+ permissionDeviceId,
1728
+ commonParams,
1729
+ installContext
1730
+ ),
1731
+ {
1732
+ label: method,
1733
+ rejectIfBusy: true,
1734
+ busyError: _LedgerAdapter._createDeviceBusyError(method)
1735
+ }
1736
+ );
1737
+ debugLog("[LedgerAdapter][RES]", { method, success: true, payload: result });
1738
+ return result;
1739
+ } catch (err) {
1740
+ const e = err;
1741
+ debugLog("[LedgerAdapter][RES]", {
1641
1742
  method,
1642
- params,
1643
- signal,
1644
- fingerprint,
1645
- permissionDeviceId,
1646
- commonParams,
1647
- installContext
1648
- ),
1649
- {
1650
- label: method,
1651
- rejectIfBusy: true,
1652
- busyError: _LedgerAdapter._createDeviceBusyError(method)
1653
- }
1654
- );
1743
+ success: false,
1744
+ error: {
1745
+ message: e?.message,
1746
+ _tag: e?._tag,
1747
+ code: e?.code ?? e?.errorCode
1748
+ }
1749
+ });
1750
+ throw err;
1751
+ }
1655
1752
  }
1656
1753
  /**
1657
1754
  * Race a promise against an abort signal. On abort, rejects with
@@ -1755,14 +1852,6 @@ var _LedgerAdapter = class _LedgerAdapter {
1755
1852
  }
1756
1853
  const appName = err?.appName ?? mapLedgerError(err).appName;
1757
1854
  if (appName) {
1758
- if (installContext?.declinedAppNames?.has(appName)) {
1759
- throw createHwkError({
1760
- code: HardwareErrorCode3.UserAborted,
1761
- message: `User declined to install ${appName}`,
1762
- _tag: ERROR_TAG.UserAborted,
1763
- appName
1764
- });
1765
- }
1766
1855
  if (installContext?.installAttemptedAppNames?.has(appName)) {
1767
1856
  throw createHwkError({
1768
1857
  code: HardwareErrorCode3.AppNotInstalled,
@@ -1773,10 +1862,6 @@ var _LedgerAdapter = class _LedgerAdapter {
1773
1862
  }
1774
1863
  const confirmed = await this._waitForInstallAppConfirm(appName);
1775
1864
  if (!confirmed) {
1776
- if (installContext) {
1777
- installContext.declinedAppNames = installContext.declinedAppNames ?? /* @__PURE__ */ new Set();
1778
- installContext.declinedAppNames.add(appName);
1779
- }
1780
1865
  throw createHwkError({
1781
1866
  code: HardwareErrorCode3.UserAborted,
1782
1867
  message: `User declined to install ${appName}`,
@@ -3426,15 +3511,30 @@ var AppManager = class {
3426
3511
  command: new OpenAppCommand({ appName })
3427
3512
  });
3428
3513
  if (!isSuccessCommandResult(result)) {
3429
- const { statusCode } = result;
3430
- const hasStatusCode2 = statusCode != null && statusCode !== "";
3431
- debugLog("[AppManager] openApp failed:", appName, "statusCode:", statusCode);
3514
+ const dmkErr = result.error;
3515
+ const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
3516
+ const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
3517
+ debugLog(
3518
+ "[AppManager] openApp failed:",
3519
+ appName,
3520
+ "errorCode:",
3521
+ errorCode,
3522
+ "tag:",
3523
+ dmkErr._tag
3524
+ );
3525
+ let code;
3526
+ if (errorCode === "6807" || /unknown application/i.test(message)) {
3527
+ code = HardwareErrorCode6.AppNotInstalled;
3528
+ } else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
3529
+ code = HardwareErrorCode6.UserRejected;
3530
+ }
3432
3531
  throw Object.assign(new Error(`Failed to open "${appName}"`), {
3433
3532
  _tag: ERROR_TAG.OpenAppCommand,
3434
- code: hasStatusCode2 ? void 0 : HardwareErrorCode6.AppNotInstalled,
3435
- errorCode: String(statusCode ?? ""),
3436
- statusCode,
3437
- appName
3533
+ code,
3534
+ errorCode,
3535
+ statusCode: errorCode,
3536
+ appName,
3537
+ originalError: dmkErr
3438
3538
  });
3439
3539
  }
3440
3540
  }
@@ -3853,6 +3953,22 @@ var DeviceApps = class {
3853
3953
  async install(appName, onProgress, options) {
3854
3954
  if (!appName) throw new Error("DeviceApps.install: appName is required");
3855
3955
  debugLog("[DeviceApps] install:", appName);
3956
+ const refreshAction = this._dmk.executeDeviceAction({
3957
+ sessionId: this._sessionId,
3958
+ deviceAction: new this._ledgerKit.GetDeviceMetadataDeviceAction({
3959
+ input: {
3960
+ useSecureChannel: true,
3961
+ forceUpdate: true,
3962
+ unlockTimeout: options?.unlockTimeout
3963
+ }
3964
+ })
3965
+ });
3966
+ await deviceActionToPromise(
3967
+ refreshAction,
3968
+ this.onInteraction,
3969
+ INSTALL_TIMEOUT_MS,
3970
+ this.onRegisterCanceller
3971
+ );
3856
3972
  const action = this._dmk.executeDeviceAction({
3857
3973
  sessionId: this._sessionId,
3858
3974
  deviceAction: new this._ledgerKit.InstallOrUpdateAppsDeviceAction({