@onekeyfe/hwk-ledger-adapter 1.1.27-alpha.4 → 1.1.27-alpha.41

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.d.mts CHANGED
@@ -1,106 +1,30 @@
1
- import { IHardwareWallet, IConnector, TransportType, UiResponseEvent, SearchDevicesOptions, DeviceInfo, Response, ChainCapability, EvmGetAddressParams, EvmAddress, EvmSignTxParams, EvmSignedTx, EvmSignMsgParams, EvmSignature, EvmSignTypedDataParams, BtcGetAddressParams, BtcAddress, BtcGetPublicKeyParams, BtcPublicKey, BtcSignTxParams, BtcSignedTx, BtcSignPsbtParams, BtcSignedPsbt, BtcSignMsgParams, BtcSignature, SolGetAddressParams, SolAddress, SolSignTxParams, SolSignedTx, SolSignMsgParams, SolSignature, TronGetAddressParams, TronAddress, TronSignTxParams, TronSignedTx, TronSignMsgParams, TronSignature, HardwareEventMap, DeviceEventListener, ChainForFingerprint, DeviceDescriptor, DeviceChangeEvent, ConnectionType, ConnectorDevice, ConnectorSession, ConnectorEventType, ConnectorEventMap, Failure, HardwareErrorCode } from '@onekeyfe/hwk-adapter-core';
1
+ import { IHardwareWallet, IConnector, TransportType, UiResponseEvent, DeviceInfo, Response, ChainCapability, EvmGetAddressParams, EvmAddress, EvmSignTxParams, EvmSignedTx, EvmSignMsgParams, EvmSignature, EvmSignTypedDataParams, BtcGetAddressParams, BtcAddress, BtcGetPublicKeyParams, BtcPublicKey, BtcSignTxParams, BtcSignedTx, BtcSignPsbtParams, BtcSignedPsbt, BtcSignMsgParams, BtcSignature, SolGetAddressParams, SolAddress, SolSignTxParams, SolSignedTx, SolSignMsgParams, SolSignature, TronGetAddressParams, TronAddress, TronSignTxParams, TronSignedTx, TronSignMsgParams, TronSignature, HardwareEventMap, DeviceEventListener, ChainForFingerprint, DeviceDescriptor, DeviceChangeEvent, ConnectionType, ConnectorDevice, ConnectorSession, ConnectorEventType, ConnectorEventMap, Failure, HardwareErrorCode } from '@onekeyfe/hwk-adapter-core';
2
2
  import { DeviceActionState as DeviceActionState$1, DiscoveredDevice, ExecuteDeviceActionReturnType, DeviceManagementKit } from '@ledgerhq/device-management-kit';
3
3
  import { Address, Signature, SignerEth as SignerEth$1, TypedData } from '@ledgerhq/device-signer-kit-ethereum';
4
- import { ContextModule } from '@ledgerhq/context-module';
5
4
  import { SignerBtc as SignerBtc$1 } from '@ledgerhq/device-signer-kit-bitcoin';
6
5
  import { SignerSolana } from '@ledgerhq/device-signer-kit-solana';
7
6
  import Transport from '@ledgerhq/hw-transport';
8
7
 
9
- /**
10
- * Re-export DMK types under local aliases for backward compatibility.
11
- * These replace the previous duck-typed interfaces with the real SDK types.
12
- */
13
- type DmkDiscoveredDevice = DiscoveredDevice;
14
- /**
15
- * DMK DeviceAction — the Observable-based return type of all DMK signer methods.
16
- *
17
- * This is a permissive alias for `ExecuteDeviceActionReturnType` that accepts
18
- * any Error and IntermediateValue generics. Signer wrapper code only cares about
19
- * the Output type and the observable/cancel shape.
20
- */
21
- type DeviceAction<T> = ExecuteDeviceActionReturnType<T, any, any>;
22
- /**
23
- * DMK DeviceActionState — re-exported with permissive Error/IntermediateValue.
24
- * The real type is a discriminated union on `status`.
25
- */
26
- type DeviceActionState<T> = DeviceActionState$1<T, any, any>;
27
- /** ETH address result — re-exported from DMK for backward compatibility. */
28
- type SignerEvmAddress = Address;
29
- /** ETH signature result — re-exported from DMK for backward compatibility. */
30
- type SignerEvmSignature = Signature;
31
- /** BTC address result (WalletAddress not exported from DMK top-level). */
32
- interface SignerBtcAddress {
33
- address: string;
34
- }
35
-
36
- /** Optional context attached to the rejection when a canceller fires. */
37
- interface CancelReason {
38
- code?: number;
39
- tag?: string;
40
- message?: string;
41
- }
42
- /**
43
- * Convert a DMK DeviceAction (Observable-based) into a Promise.
44
- * Handles pending -> completed/error state transitions and interaction callbacks.
45
- *
46
- * Tracks the last DMK step observed (e.g. `signer.eth.steps.blindSignTransactionFallback`)
47
- * and attaches it to the rejected error as a non-enumerable `_lastStep` property,
48
- * so upstream error classifiers can distinguish failure contexts (e.g. Blind signing
49
- * disabled vs. generic Invalid data).
50
- *
51
- * @param timeoutMs Idle watchdog ms. Re-armed on each emission, paused
52
- * during interactive pending. 0 disables. Default 65s
53
- * (covers DMK's 60s + margin; we're a backstop only).
54
- * @param onRegisterCanceller Optional callback that receives a function which, when
55
- * called, unsubscribes and cancels the underlying DeviceAction
56
- * (releases DMK's IntentQueue slot). Caller is responsible
57
- * for invoking the canceller on timeout/abort scenarios.
58
- */
59
- declare function deviceActionToPromise<T>(action: DeviceAction<T>, onInteraction?: (interaction: string) => void, timeoutMs?: number, onRegisterCanceller?: (cancel: (reason?: CancelReason) => void) => void, onIntermediate?: (intermediateValue: unknown) => void): Promise<T>;
60
-
61
- interface AppMetadata {
62
- versionName: string;
63
- versionId: number;
64
- version: string;
65
- versionDisplayName: string | null;
66
- description: string | null;
67
- icon: string | null;
68
- bytes: number | null;
69
- currencyId: string | null;
70
- isDevTools: boolean;
71
- }
72
- interface FirmwareVersion {
73
- /** BOLOS version on the secure element — the user-facing firmware version. */
74
- seVersion: string;
75
- /** MCU SEPH (SE–MCU link protocol) version. */
76
- mcuSephVersion: string;
77
- /** MCU bootloader version. */
78
- mcuBootloaderVersion: string;
79
- /** Hardware revision (e.g. "00" / "01" on Nano X). */
80
- hwVersion: string;
81
- }
82
- /** Full GetOsVersionResponse projected to a plain serializable shape. */
83
- interface LedgerDeviceInfo extends FirmwareVersion {
84
- isBootloader: boolean;
85
- isOsu: boolean;
86
- targetId: number;
87
- seTargetId?: number;
88
- mcuTargetId?: number;
89
- /** Secure element flags as hex string (raw bytes turned readable). */
90
- seFlagsHex: string;
8
+ interface LedgerAdapterOptions {
9
+ /**
10
+ * `true` emit `REQUEST_SELECT_DEVICE` on multi-device discovery and await
11
+ * `uiResponse({ type: RECEIVE_SELECT_DEVICE, payload: { sdkConnectId } })`.
12
+ * `false` (default) — silently pick the first device.
13
+ */
14
+ handleSelectDevice?: boolean;
91
15
  }
92
-
93
16
  declare class LedgerAdapter implements IHardwareWallet {
94
17
  readonly vendor: "ledger";
95
18
  private readonly connector;
96
19
  private readonly emitter;
20
+ private readonly _handleSelectDevice;
97
21
  private _discoveredDevices;
98
22
  private _sessions;
99
23
  private readonly _uiRegistry;
100
24
  private _btcHighIndexConfirmedThisSession;
101
25
  private readonly _jobQueue;
102
26
  private _doConnectAbortController;
103
- constructor(connector: IConnector);
27
+ constructor(connector: IConnector, options?: LedgerAdapterOptions);
104
28
  get activeTransport(): TransportType | null;
105
29
  getAvailableTransports(): TransportType[];
106
30
  switchTransport(_type: TransportType): Promise<void>;
@@ -113,10 +37,8 @@ declare class LedgerAdapter implements IHardwareWallet {
113
37
  resetState(): void;
114
38
  dispose(): Promise<void>;
115
39
  uiResponse(response: UiResponseEvent): void;
116
- searchDevices(options?: SearchDevicesOptions): Promise<DeviceInfo[]>;
117
- private _evictAllSessions;
40
+ searchDevices(): Promise<DeviceInfo[]>;
118
41
  private static readonly MAX_BUSINESS_RETRY_BUDGET;
119
- private static readonly STUCK_APP_RETRY_DELAY_MS;
120
42
  private static readonly MAX_DOCONNECT_CONFIRMS;
121
43
  private _lastCancelReason;
122
44
  private static _createDeviceBusyError;
@@ -143,11 +65,6 @@ declare class LedgerAdapter implements IHardwareWallet {
143
65
  tronGetAddress(connectId: string, deviceId: string, params: TronGetAddressParams): Promise<Response<TronAddress>>;
144
66
  tronSignTransaction(connectId: string, deviceId: string, params: TronSignTxParams): Promise<Response<TronSignedTx>>;
145
67
  tronSignMessage(connectId: string, deviceId: string, params: TronSignMsgParams): Promise<Response<TronSignature>>;
146
- installApp(connectId: string, appName: string): Promise<Response<void>>;
147
- listInstalledApps(connectId: string): Promise<Response<AppMetadata[]>>;
148
- listAvailableApps(connectId: string): Promise<Response<AppMetadata[]>>;
149
- getLedgerFirmwareVersion(connectId: string): Promise<Response<FirmwareVersion>>;
150
- getLedgerDeviceInfo(connectId: string): Promise<Response<LedgerDeviceInfo>>;
151
68
  on<K extends keyof HardwareEventMap>(event: K, listener: (event: HardwareEventMap[K]) => void): void;
152
69
  on(event: string, listener: DeviceEventListener): void;
153
70
  off<K extends keyof HardwareEventMap>(event: K, listener: (event: HardwareEventMap[K]) => void): void;
@@ -179,7 +96,7 @@ declare class LedgerAdapter implements IHardwareWallet {
179
96
  *
180
97
  * - If a session already exists for the given connectId, reuse it.
181
98
  * - If ANY session exists (Ledger IDs are ephemeral), reuse it.
182
- * - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
99
+ * - Otherwise: search → 1 device: auto-connect, multiple: ask user, 0: throw.
183
100
  */
184
101
  private _connectingPromise;
185
102
  private _waitForDeviceConnect;
@@ -196,6 +113,7 @@ declare class LedgerAdapter implements IHardwareWallet {
196
113
  private _doConnect;
197
114
  private _connectFirstOrSelect;
198
115
  private _connectDeviceOrThrow;
116
+ private _chooseDeviceFromList;
199
117
  /**
200
118
  * Call the connector with automatic session resolution and disconnect retry.
201
119
  *
@@ -214,16 +132,6 @@ declare class LedgerAdapter implements IHardwareWallet {
214
132
  private static _throwIfAborted;
215
133
  /** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
216
134
  private _runConnectorCall;
217
- /**
218
- * Stuck-app recovery: pause for the device's UI transition, then retry once.
219
- *
220
- * Caller has already cleared the session + reset connector. We wait so Stax
221
- * finishes its post-CloseApp animation, then go through ensureConnected +
222
- * fingerprint check + call exactly once. Caller decides what to do on a
223
- * second stuck-app hit.
224
- */
225
- private _retryAfterStuckApp;
226
- private _sleepAbortable;
227
135
  /**
228
136
  * Clear stale session, reconnect, and retry the call.
229
137
  *
@@ -253,12 +161,38 @@ declare class LedgerAdapter implements IHardwareWallet {
253
161
  private deviceConnectHandler;
254
162
  private deviceDisconnectHandler;
255
163
  private uiEventForwarder;
256
- private appInstallProgressForwarder;
257
164
  private registerEventListeners;
258
165
  private unregisterEventListeners;
259
166
  private connectorDeviceToDeviceInfo;
260
167
  }
261
168
 
169
+ /**
170
+ * Re-export DMK types under local aliases for backward compatibility.
171
+ * These replace the previous duck-typed interfaces with the real SDK types.
172
+ */
173
+ type DmkDiscoveredDevice = DiscoveredDevice;
174
+ /**
175
+ * DMK DeviceAction — the Observable-based return type of all DMK signer methods.
176
+ *
177
+ * This is a permissive alias for `ExecuteDeviceActionReturnType` that accepts
178
+ * any Error and IntermediateValue generics. Signer wrapper code only cares about
179
+ * the Output type and the observable/cancel shape.
180
+ */
181
+ type DeviceAction<T> = ExecuteDeviceActionReturnType<T, any, any>;
182
+ /**
183
+ * DMK DeviceActionState — re-exported with permissive Error/IntermediateValue.
184
+ * The real type is a discriminated union on `status`.
185
+ */
186
+ type DeviceActionState<T> = DeviceActionState$1<T, any, any>;
187
+ /** ETH address result — re-exported from DMK for backward compatibility. */
188
+ type SignerEvmAddress = Address;
189
+ /** ETH signature result — re-exported from DMK for backward compatibility. */
190
+ type SignerEvmSignature = Signature;
191
+ /** BTC address result (WalletAddress not exported from DMK top-level). */
192
+ interface SignerBtcAddress {
193
+ address: string;
194
+ }
195
+
262
196
  /**
263
197
  * Manages device discovery, connection, and session tracking.
264
198
  * Wraps DMK's Observable APIs into simpler imperative calls.
@@ -310,14 +244,6 @@ declare class LedgerDeviceManager {
310
244
  requestDevice(): Promise<void>;
311
245
  /** Lookup a previously-discovered device's display name. */
312
246
  getDeviceName(deviceId: string): string | undefined;
313
- /** Lookup minimal model/signal info from a previously-discovered device. */
314
- getDiscoveredDeviceInfo(deviceId: string): {
315
- model?: string;
316
- modelName?: string;
317
- name?: string;
318
- rssi?: number | null;
319
- } | undefined;
320
- hasDiscoveredDevice(deviceId: string): boolean;
321
247
  /** Connect to a previously discovered device. Returns sessionId. */
322
248
  connect(deviceId: string): Promise<string>;
323
249
  /** Disconnect a session. */
@@ -362,24 +288,22 @@ interface LedgerConnectorBaseOptions {
362
288
  * Subclasses only need to:
363
289
  * 1. Supply a transport factory via the constructor.
364
290
  * 2. Optionally override `_resolveConnectId()` for transport-specific
365
- * device identity resolution.
366
- *
367
- * Invariant: one instance = one transport. `connectionType` is fixed at
368
- * construction. To switch transport (e.g. desktop BLE ↔ WebHID), the host
369
- * must build a new connector instance and replace the old one — don't add
370
- * multiple transports to a single instance. Lifting this constraint would
371
- * require routing `connectionType` from `descriptor.transport` per-device
372
- * and updating every `this.connectionType` branch in this file.
291
+ * device identity resolution (e.g. BLE hex ID extraction).
373
292
  */
374
293
  declare class LedgerConnectorBase implements IConnector {
375
294
  private _deviceManager;
376
295
  private _signerManager;
377
- private _deviceAppsManager;
378
296
  private _dmk;
379
297
  private readonly _eventHandlers;
380
298
  private readonly _providedDmk;
381
299
  private readonly _createTransport;
382
300
  readonly connectionType: ConnectionType;
301
+ private _connectIdToPath;
302
+ private _pathToConnectId;
303
+ /** Get DMK path from external connectId. Falls back to connectId itself. */
304
+ private _getPathForConnectId;
305
+ /** Get external connectId from DMK path. Falls back to path itself. */
306
+ private _getConnectIdForPath;
383
307
  private readonly _cancellers;
384
308
  private readonly _sessionStateSubs;
385
309
  /**
@@ -390,10 +314,6 @@ declare class LedgerConnectorBase implements IConnector {
390
314
  protected _importLedgerKit: (pkg: string) => Promise<any>;
391
315
  /** Context object passed to per-chain handler functions. */
392
316
  private readonly _ctx;
393
- /** When true, BLE direct-connect throws NotAdvertising if the pre-flight
394
- * scan can't see the device — guard for GATT stacks that wedge on
395
- * non-advertising peripherals (iOS). */
396
- private readonly _requirePreFlightScan;
397
317
  constructor(createTransport: TransportFactory, options?: {
398
318
  connectionType?: ConnectionType;
399
319
  dmk?: DeviceManagementKit;
@@ -403,13 +323,11 @@ declare class LedgerConnectorBase implements IConnector {
403
323
  * For Metro (React Native): pass a resolver that uses CJS paths.
404
324
  */
405
325
  importLedgerKit?: (pkg: string) => Promise<any>;
406
- /** Default false. RN-iOS subclass should pass `true`. */
407
- requirePreFlightScan?: boolean;
408
326
  });
409
327
  /**
410
328
  * Resolve the connectId for a discovered device descriptor.
411
329
  * Default: use the DMK path (ephemeral UUID).
412
- * Override in subclasses only when the public connectId differs from the transport path.
330
+ * Override in subclasses to extract stable identifiers (e.g. BLE hex ID).
413
331
  */
414
332
  protected _resolveConnectId(descriptor: DeviceDescriptor): string;
415
333
  /**
@@ -428,7 +346,8 @@ declare class LedgerConnectorBase implements IConnector {
428
346
  * `LedgerAdapter._sessions` map would hold a dead session entry until
429
347
  * the next call hit `DeviceSessionNotFound`.
430
348
  *
431
- * Subscribe failure is fatal see the inline note at the subscribe call.
349
+ * Best-effort: any error subscribing is swallowed so a flaky DMK
350
+ * doesn't break the connect path.
432
351
  */
433
352
  private _watchSessionState;
434
353
  private _unwatchSessionState;
@@ -449,15 +368,15 @@ declare class LedgerConnectorBase implements IConnector {
449
368
  private _initManagers;
450
369
  private _getDeviceManager;
451
370
  private _getSignerManager;
452
- private _getDeviceAppsManager;
453
371
  private _invalidateSession;
454
372
  /**
455
373
  * Replace an old session with a new one after app switch.
456
- * Emits device-connect so the adapter updates its _sessions Map.
374
+ * Updates the connectId→path mapping so subsequent calls() use the new session,
375
+ * and emits device-connect so the adapter updates its _sessions Map.
457
376
  */
458
377
  private _replaceSession;
459
378
  /**
460
- * Light reset: clear signer/session state but keep DMK alive.
379
+ * Light reset: clear signer/session state but keep DMK and ID mapping alive.
461
380
  * Used by connect() retry — we want to re-discover with the same transport.
462
381
  *
463
382
  * Note: drops the device manager but tears down its RxJS subs first via
@@ -476,6 +395,31 @@ declare class LedgerConnectorBase implements IConnector {
476
395
  private _wrapError;
477
396
  }
478
397
 
398
+ /** Optional context attached to the rejection when a canceller fires. */
399
+ interface CancelReason {
400
+ code?: number;
401
+ tag?: string;
402
+ message?: string;
403
+ }
404
+ /**
405
+ * Convert a DMK DeviceAction (Observable-based) into a Promise.
406
+ * Handles pending -> completed/error state transitions and interaction callbacks.
407
+ *
408
+ * Tracks the last DMK step observed (e.g. `signer.eth.steps.blindSignTransactionFallback`)
409
+ * and attaches it to the rejected error as a non-enumerable `_lastStep` property,
410
+ * so upstream error classifiers can distinguish failure contexts (e.g. Blind signing
411
+ * disabled vs. generic Invalid data).
412
+ *
413
+ * @param timeoutMs Idle watchdog ms. Re-armed on each emission, paused
414
+ * during interactive pending. 0 disables. Default 65s
415
+ * (covers DMK's 60s + margin; we're a backstop only).
416
+ * @param onRegisterCanceller Optional callback that receives a function which, when
417
+ * called, unsubscribes and cancels the underlying DeviceAction
418
+ * (releases DMK's IntentQueue slot). Caller is responsible
419
+ * for invoking the canceller on timeout/abort scenarios.
420
+ */
421
+ declare function deviceActionToPromise<T>(action: DeviceAction<T>, onInteraction?: (interaction: string) => void, timeoutMs?: number, onRegisterCanceller?: (cancel: (reason?: CancelReason) => void) => void): Promise<T>;
422
+
479
423
  /**
480
424
  * Wraps Ledger's SDK signer (Observable-based DeviceActions) into
481
425
  * a simple async interface returning plain serializable data.
@@ -502,14 +446,8 @@ type SignerEthBuilderFn = (args: {
502
446
  dmk: DeviceManagementKit;
503
447
  sessionId: string;
504
448
  }) => {
505
- withContextModule?(contextModule: ContextModule): {
506
- build(): SignerEth$1;
507
- };
508
449
  build(): SignerEth$1;
509
450
  } | Promise<{
510
- withContextModule?(contextModule: ContextModule): {
511
- build(): SignerEth$1;
512
- };
513
451
  build(): SignerEth$1;
514
452
  }>;
515
453
  /**
@@ -525,8 +463,6 @@ declare class SignerManager {
525
463
  invalidate(_sessionId: string): void;
526
464
  clearAll(): void;
527
465
  private static _defaultBuilder;
528
- private static _createContextModule;
529
- static wrapBlindSigningReportNonBlocking<T extends ContextModule>(contextModule: T): T;
530
466
  }
531
467
 
532
468
  type BtcWallet = Parameters<SignerBtc$1['getWalletAddress']>[0];
@@ -719,7 +655,12 @@ type SdkEventListener = (event: SdkEvent) => void;
719
655
  declare function onSdkEvent(listener: SdkEventListener): () => void;
720
656
  declare function offSdkEvent(listener: SdkEventListener): void;
721
657
 
722
- declare function debugLog(...args: unknown[]): void;
658
+ /**
659
+ * Extract the stable 4-digit HEX identifier from a Ledger BLE device name.
660
+ * e.g., "Nano X 123A" -> "123A", "Ledger Nano X AB12" -> "AB12"
661
+ * Returns undefined if no valid HEX suffix found.
662
+ */
663
+ declare function extractBleHexId(name?: string): string | undefined;
723
664
 
724
665
  /**
725
666
  * Ledger DMK transport identifiers that represent BLE devices.
@@ -734,5 +675,6 @@ declare function debugLog(...args: unknown[]): void;
734
675
  declare function isLedgerDmkBleTransport(transport?: string): boolean;
735
676
  declare function isLedgerBleConnectionType(connectionType?: ConnectionType): boolean;
736
677
  declare function isLedgerBleDescriptor(connectionType: ConnectionType, descriptor: DeviceDescriptor): boolean;
678
+ declare function isValidLedgerBleConnectId(connectId?: string): boolean;
737
679
 
738
- export { AppManager, type DeviceActionState, type DmkDiscoveredDevice, DmkTransport, LedgerAdapter, LedgerConnectorBase, type LedgerConnectorBaseOptions, LedgerDeviceManager, type LedgerFailure, type SdkEvent, type SdkEventListener, type SdkLogEvent, SignerBtc, type SignerBtcAddress, SignerEth, type SignerEvmAddress, type SignerEvmSignature, SignerManager, SignerSol, type TransportFactory, debugLog, deviceActionToPromise, isDeviceLockedError, isLedgerBleConnectionType, isLedgerBleDescriptor, isLedgerDmkBleTransport, ledgerFailure, mapLedgerError, offSdkEvent, onSdkEvent };
680
+ export { AppManager, type DeviceActionState, type DmkDiscoveredDevice, DmkTransport, LedgerAdapter, LedgerConnectorBase, type LedgerConnectorBaseOptions, LedgerDeviceManager, type LedgerFailure, type SdkEvent, type SdkEventListener, type SdkLogEvent, SignerBtc, type SignerBtcAddress, SignerEth, type SignerEvmAddress, type SignerEvmSignature, SignerManager, SignerSol, type TransportFactory, deviceActionToPromise, extractBleHexId, isDeviceLockedError, isLedgerBleConnectionType, isLedgerBleDescriptor, isLedgerDmkBleTransport, isValidLedgerBleConnectId, ledgerFailure, mapLedgerError, offSdkEvent, onSdkEvent };