@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.12 → 1.2.8-alpha.121
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 +97 -52
- package/dist/index.d.ts +97 -52
- package/dist/index.js +2064 -988
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2004 -902
- package/dist/index.mjs.map +1 -1
- package/package.json +14 -11
package/dist/index.js
CHANGED
|
@@ -39,6 +39,7 @@ __export(index_exports, {
|
|
|
39
39
|
SignerEth: () => SignerEth,
|
|
40
40
|
SignerManager: () => SignerManager,
|
|
41
41
|
SignerSol: () => SignerSol,
|
|
42
|
+
SignerZcash: () => SignerZcash,
|
|
42
43
|
debugLog: () => debugLog,
|
|
43
44
|
deviceActionToPromise: () => deviceActionToPromise,
|
|
44
45
|
isDeviceLockedError: () => isDeviceLockedError,
|
|
@@ -53,21 +54,18 @@ __export(index_exports, {
|
|
|
53
54
|
module.exports = __toCommonJS(index_exports);
|
|
54
55
|
|
|
55
56
|
// src/adapter/LedgerAdapter.ts
|
|
56
|
-
var
|
|
57
|
+
var import_hwk_adapter_core4 = require("@onekeyfe/hwk-adapter-core");
|
|
57
58
|
|
|
58
59
|
// src/errors.ts
|
|
59
60
|
var import_hwk_adapter_core = require("@onekeyfe/hwk-adapter-core");
|
|
60
|
-
|
|
61
|
-
function createMultipleUsbLedgerDevicesError() {
|
|
62
|
-
return Object.assign(new Error(MULTIPLE_USB_LEDGER_DEVICES_ERROR_MESSAGE), {
|
|
63
|
-
code: import_hwk_adapter_core.HardwareErrorCode.DeviceOneDeviceOnly
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
function ledgerFailure(code, error, appName, tag, params) {
|
|
61
|
+
function ledgerFailure(code, error, appName, tag, params, origin, recovery) {
|
|
67
62
|
const payload = { error, code };
|
|
68
63
|
if (appName !== void 0) payload.appName = appName;
|
|
69
64
|
if (tag !== void 0) payload._tag = tag;
|
|
70
65
|
if (params !== void 0) payload.params = params;
|
|
66
|
+
const resolvedOrigin = origin ?? (0, import_hwk_adapter_core.defaultOriginForCode)(code);
|
|
67
|
+
if (resolvedOrigin !== void 0) payload.origin = resolvedOrigin;
|
|
68
|
+
payload.recovery = recovery ?? (0, import_hwk_adapter_core.defaultRecoveryForCode)(code);
|
|
71
69
|
return { success: false, payload };
|
|
72
70
|
}
|
|
73
71
|
var LOCKED_ERROR_CODES = /* @__PURE__ */ new Set(["5515", "21781", "6982", "27010", "5303", "21251"]);
|
|
@@ -208,7 +206,10 @@ var ERROR_TAG = {
|
|
|
208
206
|
UnknownDevice: "UnknownDeviceError",
|
|
209
207
|
DeviceSessionRefresher: "DeviceSessionRefresherError",
|
|
210
208
|
DeviceNotInitialized: "DeviceNotInitializedError",
|
|
211
|
-
|
|
209
|
+
// DMK class OpeningConnectionError carries `_tag` "ConnectionOpeningError"; both
|
|
210
|
+
// spellings are kept so a DMK release that aligns them still classifies.
|
|
211
|
+
OpeningConnection: "ConnectionOpeningError",
|
|
212
|
+
OpeningConnectionLegacy: "OpeningConnectionError",
|
|
212
213
|
DeviceDisconnectedBeforeSendingApdu: "DeviceDisconnectedBeforeSendingApdu",
|
|
213
214
|
DeviceDisconnectedWhileSending: "DeviceDisconnectedWhileSendingError",
|
|
214
215
|
Disconnect: "DisconnectError",
|
|
@@ -218,10 +219,20 @@ var ERROR_TAG = {
|
|
|
218
219
|
// outcome when the user doesn't confirm pairing on the device, or the
|
|
219
220
|
// existing bond is invalid. Observed in production after ~30s.
|
|
220
221
|
PairingRefused: "PairingRefusedError",
|
|
222
|
+
PeerRemovedPairing: "PeerRemovedPairingError",
|
|
221
223
|
// DMK remote-network failures (manager-api HTTP / secure-channel WS).
|
|
222
224
|
WebSocketConnection: "WebSocketConnectionError",
|
|
223
225
|
HttpFetch: "FetchError",
|
|
224
|
-
|
|
226
|
+
NetworkDA: "NetworkDAError",
|
|
227
|
+
InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
|
|
228
|
+
ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
|
|
229
|
+
// DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
|
|
230
|
+
// after splitting out device answers, i.e. the relay itself broke.
|
|
231
|
+
SecureChannel: "SecureChannelError",
|
|
232
|
+
RefusedByUserDA: "RefusedByUserDAError",
|
|
233
|
+
AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
|
|
234
|
+
OutOfMemoryDA: "OutOfMemoryDAError",
|
|
235
|
+
DeviceNotOnboarded: "DeviceNotOnboardedError"
|
|
225
236
|
};
|
|
226
237
|
function isDeviceLockedError(err) {
|
|
227
238
|
if (!err || typeof err !== "object") return false;
|
|
@@ -237,6 +248,27 @@ function isDeviceNotAdvertisingError(err) {
|
|
|
237
248
|
if (!err || typeof err !== "object") return false;
|
|
238
249
|
return err._tag === ERROR_TAG.DeviceNotAdvertising;
|
|
239
250
|
}
|
|
251
|
+
function isBleBondInvalidError(err) {
|
|
252
|
+
const pending = [err];
|
|
253
|
+
const seen = /* @__PURE__ */ new Set();
|
|
254
|
+
while (pending.length > 0) {
|
|
255
|
+
const candidate = pending.pop();
|
|
256
|
+
if (candidate && typeof candidate === "object" && !seen.has(candidate)) {
|
|
257
|
+
seen.add(candidate);
|
|
258
|
+
const e = candidate;
|
|
259
|
+
if (e._tag === ERROR_TAG.PeerRemovedPairing || e.iosErrorCode === 14 || e.attErrorCode === 5 || e.nativeErrorDomain === "CBErrorDomain" && e.nativeErrorCode === 14) {
|
|
260
|
+
return true;
|
|
261
|
+
}
|
|
262
|
+
const reason = typeof e.reason === "string" ? e.reason : "";
|
|
263
|
+
const message = typeof e.message === "string" ? e.message : "";
|
|
264
|
+
if (/\bCBErrorDomain:14(?:\s|$)/.test(message) || reason.includes("Peer removed pairing information") || reason.includes("GATT_INSUF_AUTHENTICATION")) {
|
|
265
|
+
return true;
|
|
266
|
+
}
|
|
267
|
+
pending.push(e.originalError, e.err);
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return false;
|
|
271
|
+
}
|
|
240
272
|
var PAIRING_FAILURE_TAGS = /* @__PURE__ */ new Set([
|
|
241
273
|
ERROR_TAG.BlePairingTimeout,
|
|
242
274
|
ERROR_TAG.BleGattBondingFailed,
|
|
@@ -251,11 +283,11 @@ function isBlePairingFailureError(err) {
|
|
|
251
283
|
return false;
|
|
252
284
|
}
|
|
253
285
|
var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
254
|
-
ERROR_TAG.DeviceLocked,
|
|
255
286
|
ERROR_TAG.DeviceNotAdvertising,
|
|
256
287
|
ERROR_TAG.BlePairingTimeout,
|
|
257
288
|
ERROR_TAG.BleGattBondingFailed,
|
|
258
289
|
ERROR_TAG.PairingRefused,
|
|
290
|
+
ERROR_TAG.PeerRemovedPairing,
|
|
259
291
|
ERROR_TAG.DeviceNotRecognized,
|
|
260
292
|
ERROR_TAG.NoAccessibleDevice,
|
|
261
293
|
ERROR_TAG.UnknownDevice,
|
|
@@ -263,6 +295,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
|
263
295
|
ERROR_TAG.DeviceSessionRefresher,
|
|
264
296
|
ERROR_TAG.DeviceNotInitialized,
|
|
265
297
|
ERROR_TAG.OpeningConnection,
|
|
298
|
+
ERROR_TAG.OpeningConnectionLegacy,
|
|
266
299
|
ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
|
|
267
300
|
ERROR_TAG.DeviceDisconnectedWhileSending,
|
|
268
301
|
ERROR_TAG.Disconnect,
|
|
@@ -277,7 +310,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
|
|
|
277
310
|
// Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
|
|
278
311
|
ERROR_TAG.DeviceNotInDiscoveryCache
|
|
279
312
|
]);
|
|
280
|
-
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
313
|
+
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
314
|
+
ERROR_TAG.OpeningConnection,
|
|
315
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
316
|
+
]);
|
|
281
317
|
var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
282
318
|
ERROR_TAG.DeviceNotRecognized,
|
|
283
319
|
ERROR_TAG.DeviceSessionNotFound,
|
|
@@ -289,17 +325,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
|
289
325
|
ERROR_TAG.WebHIDDisconnect
|
|
290
326
|
]);
|
|
291
327
|
function isConnectionLevelError(err) {
|
|
292
|
-
|
|
293
|
-
const tag = err._tag;
|
|
294
|
-
if (tag && CONNECTION_LEVEL_TAGS.has(tag)) return true;
|
|
295
|
-
const e = err;
|
|
296
|
-
if (e.originalError != null && isConnectionLevelError(e.originalError)) return true;
|
|
297
|
-
if (e.error != null && e._tag && isConnectionLevelError(e.error)) return true;
|
|
298
|
-
return false;
|
|
328
|
+
return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
|
|
299
329
|
}
|
|
300
330
|
function isKnownConnectionTag(tag) {
|
|
301
331
|
return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
|
|
302
332
|
}
|
|
333
|
+
var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
|
|
334
|
+
ERROR_TAG.OpeningConnection,
|
|
335
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
336
|
+
]);
|
|
337
|
+
function isConnectionOpeningTag(tag) {
|
|
338
|
+
return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
|
|
339
|
+
}
|
|
303
340
|
function hasStatusCode(err, codeSet) {
|
|
304
341
|
if (!err || typeof err !== "object") return false;
|
|
305
342
|
const e = err;
|
|
@@ -335,28 +372,28 @@ function hasInvalidArgumentCode(err) {
|
|
|
335
372
|
if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
|
|
336
373
|
return false;
|
|
337
374
|
}
|
|
338
|
-
function
|
|
375
|
+
function hasErrorTag(err, tags) {
|
|
339
376
|
if (!err || typeof err !== "object") return false;
|
|
340
|
-
const tag = err._tag;
|
|
341
|
-
if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
|
|
342
377
|
const e = err;
|
|
343
|
-
if (e.
|
|
344
|
-
if (e.
|
|
378
|
+
if (typeof e._tag === "string" && tags.has(e._tag)) return true;
|
|
379
|
+
if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
|
|
380
|
+
if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
|
|
345
381
|
return false;
|
|
346
382
|
}
|
|
383
|
+
function isDeviceNotFoundError(err) {
|
|
384
|
+
return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
|
|
385
|
+
}
|
|
347
386
|
function isDeviceBusyError(err) {
|
|
348
|
-
|
|
349
|
-
const tag = err._tag;
|
|
350
|
-
if (tag && DEVICE_BUSY_TAGS.has(tag)) return true;
|
|
351
|
-
const e = err;
|
|
352
|
-
if (e.originalError != null && isDeviceBusyError(e.originalError)) return true;
|
|
353
|
-
if (e.error != null && e._tag && isDeviceBusyError(e.error)) return true;
|
|
354
|
-
return false;
|
|
387
|
+
return hasErrorTag(err, DEVICE_BUSY_TAGS);
|
|
355
388
|
}
|
|
389
|
+
var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
390
|
+
ERROR_TAG.UserRefusedOnDevice,
|
|
391
|
+
ERROR_TAG.RefusedByUserDA
|
|
392
|
+
]);
|
|
356
393
|
function isUserRejectedError(err) {
|
|
357
394
|
if (!err || typeof err !== "object") return false;
|
|
358
395
|
const e = err;
|
|
359
|
-
if (
|
|
396
|
+
if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
|
|
360
397
|
if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
|
|
361
398
|
if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
|
|
362
399
|
return false;
|
|
@@ -387,15 +424,33 @@ function isAppNotInstalledError(err) {
|
|
|
387
424
|
if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
|
|
388
425
|
return false;
|
|
389
426
|
}
|
|
427
|
+
var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
|
|
390
428
|
function isOutOfMemoryError(err) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
429
|
+
return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
|
|
430
|
+
}
|
|
431
|
+
var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
|
|
432
|
+
function isAppAlreadyInstalledError(err) {
|
|
433
|
+
return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
|
|
434
|
+
}
|
|
435
|
+
var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
|
|
436
|
+
function isDeviceNotOnboardedError(err) {
|
|
437
|
+
return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
|
|
438
|
+
}
|
|
439
|
+
var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
|
|
440
|
+
ERROR_TAG.InvalidFirmwareMetadataResponse,
|
|
441
|
+
ERROR_TAG.ApplicationsMetadataTask
|
|
442
|
+
]);
|
|
443
|
+
function isFirmwareMetadataError(err) {
|
|
444
|
+
return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
|
|
445
|
+
}
|
|
446
|
+
var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
|
|
447
|
+
function isSecureChannelError(err) {
|
|
448
|
+
return hasErrorTag(err, SECURE_CHANNEL_TAGS);
|
|
394
449
|
}
|
|
395
450
|
var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
|
|
396
451
|
ERROR_TAG.WebSocketConnection,
|
|
397
452
|
ERROR_TAG.HttpFetch,
|
|
398
|
-
ERROR_TAG.
|
|
453
|
+
ERROR_TAG.NetworkDA
|
|
399
454
|
]);
|
|
400
455
|
function isNetworkError(err) {
|
|
401
456
|
if (!err || typeof err !== "object") return false;
|
|
@@ -445,23 +500,36 @@ function isTransportStuck(err) {
|
|
|
445
500
|
function isStuckAppStateError(err) {
|
|
446
501
|
return isAppStuckByApdu(err) || isTransportStuck(err);
|
|
447
502
|
}
|
|
503
|
+
var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
|
|
504
|
+
function nestedErrorMessage(nested) {
|
|
505
|
+
if (!nested || typeof nested !== "object") return void 0;
|
|
506
|
+
const { message } = nested;
|
|
507
|
+
if (typeof message !== "string") return void 0;
|
|
508
|
+
const trimmed = message.trim();
|
|
509
|
+
if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
|
|
510
|
+
return message;
|
|
511
|
+
}
|
|
448
512
|
function mapLedgerError(err, opts) {
|
|
449
513
|
let originalMessage = "Unknown Ledger error";
|
|
450
514
|
if (err instanceof Error) {
|
|
451
515
|
originalMessage = err.message;
|
|
452
516
|
} else if (err && typeof err === "object") {
|
|
453
517
|
const e = err;
|
|
454
|
-
originalMessage = String(
|
|
518
|
+
originalMessage = String(
|
|
519
|
+
e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
|
|
520
|
+
);
|
|
455
521
|
}
|
|
456
522
|
let code;
|
|
457
523
|
if (isDeviceLockedError(err)) {
|
|
458
524
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceLocked;
|
|
459
525
|
} else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
|
|
460
526
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotFound;
|
|
461
|
-
} else if (
|
|
462
|
-
code = import_hwk_adapter_core.HardwareErrorCode.
|
|
527
|
+
} else if (isBleBondInvalidError(err)) {
|
|
528
|
+
code = import_hwk_adapter_core.HardwareErrorCode.BleBondInvalid;
|
|
463
529
|
} else if (isBlePairingFailureError(err)) {
|
|
464
530
|
code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
|
|
531
|
+
} else if (isDeviceBusyError(err)) {
|
|
532
|
+
code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
|
|
465
533
|
} else if (isUserAbortedError(err)) {
|
|
466
534
|
code = import_hwk_adapter_core.HardwareErrorCode.UserAborted;
|
|
467
535
|
} else if (isUserRejectedError(err)) {
|
|
@@ -470,10 +538,18 @@ function mapLedgerError(err, opts) {
|
|
|
470
538
|
code = import_hwk_adapter_core.HardwareErrorCode.WrongApp;
|
|
471
539
|
} else if (isAppNotInstalledError(err)) {
|
|
472
540
|
code = import_hwk_adapter_core.HardwareErrorCode.AppNotInstalled;
|
|
541
|
+
} else if (isAppAlreadyInstalledError(err)) {
|
|
542
|
+
code = import_hwk_adapter_core.HardwareErrorCode.AppAlreadyInstalled;
|
|
473
543
|
} else if (isOutOfMemoryError(err)) {
|
|
474
544
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceOutOfMemory;
|
|
545
|
+
} else if (isDeviceNotOnboardedError(err)) {
|
|
546
|
+
code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotInitialized;
|
|
547
|
+
} else if (isFirmwareMetadataError(err)) {
|
|
548
|
+
code = import_hwk_adapter_core.HardwareErrorCode.LedgerFirmwareMetadataError;
|
|
475
549
|
} else if (isNetworkError(err)) {
|
|
476
550
|
code = import_hwk_adapter_core.HardwareErrorCode.NetworkError;
|
|
551
|
+
} else if (isSecureChannelError(err)) {
|
|
552
|
+
code = import_hwk_adapter_core.HardwareErrorCode.LedgerSecureChannelError;
|
|
477
553
|
} else if (isDeviceDisconnectedError(err)) {
|
|
478
554
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceDisconnected;
|
|
479
555
|
} else if (isTimeoutError(err)) {
|
|
@@ -486,11 +562,25 @@ function mapLedgerError(err, opts) {
|
|
|
486
562
|
}
|
|
487
563
|
const errAppName = err && typeof err === "object" ? err.appName : void 0;
|
|
488
564
|
const appName = errAppName ?? opts?.defaultAppName;
|
|
489
|
-
return {
|
|
565
|
+
return {
|
|
566
|
+
code,
|
|
567
|
+
message: (0, import_hwk_adapter_core.enrichErrorMessage)(code, originalMessage),
|
|
568
|
+
origin: (0, import_hwk_adapter_core.defaultOriginForCode)(code),
|
|
569
|
+
appName
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
// src/utils/queueKey.ts
|
|
574
|
+
var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
|
|
575
|
+
function ledgerQueueKey({
|
|
576
|
+
operationId,
|
|
577
|
+
connectId
|
|
578
|
+
}) {
|
|
579
|
+
return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
|
|
490
580
|
}
|
|
491
581
|
|
|
492
582
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
493
|
-
var
|
|
583
|
+
var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
|
|
494
584
|
|
|
495
585
|
// src/utils/sdkEventBus.ts
|
|
496
586
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -537,6 +627,32 @@ function debugError(...args) {
|
|
|
537
627
|
emitLog("error", ...args);
|
|
538
628
|
}
|
|
539
629
|
|
|
630
|
+
// src/utils/logSummary.ts
|
|
631
|
+
var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
|
|
632
|
+
var import_bitcoinjs_lib = require("bitcoinjs-lib");
|
|
633
|
+
var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
|
|
634
|
+
var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
635
|
+
function parsePsbt(input) {
|
|
636
|
+
if (typeof input !== "string") return import_bitcoinjs_lib.Psbt.fromBuffer(input);
|
|
637
|
+
if (HEX_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromHex(input.replace(/^0x/i, ""));
|
|
638
|
+
if (BASE64_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromBase64(input);
|
|
639
|
+
return void 0;
|
|
640
|
+
}
|
|
641
|
+
var describePsbtForLog = (key, value) => {
|
|
642
|
+
if (key !== "psbt") return void 0;
|
|
643
|
+
try {
|
|
644
|
+
const psbt = parsePsbt(value);
|
|
645
|
+
if (!psbt) return void 0;
|
|
646
|
+
const unsignedTx = import_bitcoinjs_lib.Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
|
|
647
|
+
return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
|
|
648
|
+
} catch {
|
|
649
|
+
return void 0;
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
function summarizeForLog(value, options = {}) {
|
|
653
|
+
return (0, import_hwk_adapter_core2.summarizeForLog)(value, { ...options, describePayload: describePsbtForLog });
|
|
654
|
+
}
|
|
655
|
+
|
|
540
656
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
541
657
|
var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
542
658
|
tbtc: "Testnet",
|
|
@@ -547,57 +663,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
|
547
663
|
var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
|
|
548
664
|
function createAllNetworkGetAddress({
|
|
549
665
|
callChain,
|
|
550
|
-
getChainFingerprint
|
|
666
|
+
getChainFingerprint,
|
|
667
|
+
retainOperation,
|
|
668
|
+
errorToFailure,
|
|
669
|
+
createCancelScope,
|
|
670
|
+
releaseBundle
|
|
551
671
|
}) {
|
|
552
672
|
return async function allNetworkGetAddress(connectId, _deviceId, params) {
|
|
553
|
-
debugLog("[LedgerAdapter][REQ]", {
|
|
554
|
-
|
|
673
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
674
|
+
method: "allNetworkGetAddress",
|
|
675
|
+
connectId,
|
|
676
|
+
itemCount: params.bundle.length
|
|
677
|
+
});
|
|
678
|
+
const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(connectId, params.operationId, "ledger");
|
|
679
|
+
if (!target.success) return target;
|
|
680
|
+
const effectiveTargetId = target.payload.targetId ?? "";
|
|
681
|
+
let releaseOperationRetention;
|
|
682
|
+
try {
|
|
683
|
+
releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
|
|
684
|
+
} catch (error) {
|
|
685
|
+
return errorToFailure(error);
|
|
686
|
+
}
|
|
687
|
+
const cancelScope = createCancelScope(
|
|
688
|
+
ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
|
|
689
|
+
);
|
|
690
|
+
const installContext = {
|
|
691
|
+
walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
|
|
692
|
+
};
|
|
555
693
|
const commonParams = {
|
|
556
|
-
autoInstallApp: params.autoInstallApp
|
|
694
|
+
autoInstallApp: params.autoInstallApp,
|
|
695
|
+
operationId: target.payload.operationId,
|
|
696
|
+
knownConnections: params.knownConnections,
|
|
697
|
+
extra: params.extra,
|
|
698
|
+
allowDeviceSelection: params.allowDeviceSelection,
|
|
699
|
+
supportedTransports: params.supportedTransports
|
|
557
700
|
};
|
|
558
701
|
const chainFingerprints = /* @__PURE__ */ new Map();
|
|
559
|
-
const
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
702
|
+
const order = params.bundle.map((_item, index) => index).sort(
|
|
703
|
+
(a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
|
|
704
|
+
);
|
|
705
|
+
try {
|
|
706
|
+
const ordered = await (0, import_hwk_adapter_core3.runAllNetworkGetAddress)({
|
|
707
|
+
connectId: effectiveTargetId,
|
|
708
|
+
deviceId: _deviceId,
|
|
709
|
+
params: { ...params, bundle: order.map((index) => params.bundle[index]) },
|
|
710
|
+
normalizeItem: normalizeLedgerAllNetworkItem,
|
|
711
|
+
buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
|
|
712
|
+
callItem: async ({ method, chain, item }) => {
|
|
713
|
+
if (cancelScope.signal.aborted)
|
|
714
|
+
return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelScope.signal);
|
|
715
|
+
const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
|
|
716
|
+
return callAllNetworkMethod(
|
|
717
|
+
callChain,
|
|
718
|
+
effectiveTargetId,
|
|
719
|
+
itemDeviceId,
|
|
720
|
+
method,
|
|
721
|
+
item,
|
|
722
|
+
commonParams,
|
|
723
|
+
installContext
|
|
724
|
+
);
|
|
725
|
+
},
|
|
726
|
+
attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
|
|
727
|
+
getChainFingerprint,
|
|
728
|
+
effectiveTargetId,
|
|
572
729
|
item,
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
)
|
|
730
|
+
chain,
|
|
731
|
+
payload,
|
|
732
|
+
chainFingerprints,
|
|
733
|
+
installContext,
|
|
734
|
+
cancelScope.signal
|
|
735
|
+
),
|
|
736
|
+
shouldAbortBundle: isTopLevelAllNetworkFailure,
|
|
737
|
+
buildTopLevelFailure: (response) => {
|
|
738
|
+
const code = response.payload?.code ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch;
|
|
739
|
+
return (0, import_hwk_adapter_core3.failure)(
|
|
740
|
+
code,
|
|
741
|
+
response.payload?.error ?? "All-network get-address aborted",
|
|
742
|
+
response.payload?.params
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
});
|
|
746
|
+
let result = ordered;
|
|
747
|
+
if (ordered.success) {
|
|
748
|
+
const responses = [];
|
|
749
|
+
ordered.payload.forEach((response, position) => {
|
|
750
|
+
responses[order[position]] = response;
|
|
751
|
+
});
|
|
752
|
+
result = (0, import_hwk_adapter_core3.success)(responses);
|
|
593
753
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
754
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
755
|
+
method: "allNetworkGetAddress",
|
|
756
|
+
success: result.success,
|
|
757
|
+
payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
|
|
758
|
+
});
|
|
759
|
+
return result;
|
|
760
|
+
} finally {
|
|
761
|
+
await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
|
|
762
|
+
cancelScope.release();
|
|
763
|
+
releaseOperationRetention?.();
|
|
764
|
+
}
|
|
601
765
|
};
|
|
602
766
|
}
|
|
603
767
|
function isTopLevelAllNetworkFailure(response) {
|
|
@@ -605,7 +769,7 @@ function isTopLevelAllNetworkFailure(response) {
|
|
|
605
769
|
return false;
|
|
606
770
|
}
|
|
607
771
|
const code = response.payload?.code;
|
|
608
|
-
return
|
|
772
|
+
return (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
|
|
609
773
|
}
|
|
610
774
|
function getItemDeviceId(item) {
|
|
611
775
|
const { deviceId } = item;
|
|
@@ -619,7 +783,7 @@ function buildUnsupportedNetworkResponse(item) {
|
|
|
619
783
|
...item,
|
|
620
784
|
success: false,
|
|
621
785
|
payload: {
|
|
622
|
-
code:
|
|
786
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
|
|
623
787
|
error: `Ledger allNetwork does not support ${item.network.toLowerCase() === "doge" ? "Dogecoin" : item.network}`
|
|
624
788
|
}
|
|
625
789
|
};
|
|
@@ -635,8 +799,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
|
|
|
635
799
|
const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
|
|
636
800
|
return coin ? { ...item, coin } : item;
|
|
637
801
|
}
|
|
638
|
-
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
|
|
639
|
-
const
|
|
802
|
+
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
|
|
803
|
+
const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
|
|
804
|
+
if (!knownFingerprint && cancelSignal.aborted) {
|
|
805
|
+
const cancelled = (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelSignal);
|
|
806
|
+
return { ...item, success: false, payload: cancelled.payload };
|
|
807
|
+
}
|
|
808
|
+
const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
|
|
809
|
+
getChainFingerprint,
|
|
810
|
+
context.connection?.connectId ?? connectId,
|
|
811
|
+
chain,
|
|
812
|
+
context
|
|
813
|
+
);
|
|
640
814
|
if (!fingerprint) {
|
|
641
815
|
return buildFingerprintBootstrapFailure(item, chain);
|
|
642
816
|
}
|
|
@@ -657,8 +831,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
|
|
|
657
831
|
}
|
|
658
832
|
};
|
|
659
833
|
}
|
|
660
|
-
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
|
|
661
|
-
const response = await getChainFingerprint(connectId, chain);
|
|
834
|
+
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
|
|
835
|
+
const response = await getChainFingerprint(connectId, chain, context);
|
|
662
836
|
return response.success ? response.payload : "";
|
|
663
837
|
}
|
|
664
838
|
function buildFingerprintBootstrapFailure(item, chain) {
|
|
@@ -666,7 +840,7 @@ function buildFingerprintBootstrapFailure(item, chain) {
|
|
|
666
840
|
...item,
|
|
667
841
|
success: false,
|
|
668
842
|
payload: {
|
|
669
|
-
code:
|
|
843
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
|
|
670
844
|
error: `Could not establish chain fingerprint for ${chain} after device call; refusing to return unverifiable result. Please retry.`
|
|
671
845
|
}
|
|
672
846
|
};
|
|
@@ -730,7 +904,7 @@ async function callAllNetworkMethod(callChain, connectId, deviceId, method, item
|
|
|
730
904
|
);
|
|
731
905
|
default:
|
|
732
906
|
throw Object.assign(new Error(`Unsupported allNetwork method: ${method}`), {
|
|
733
|
-
code:
|
|
907
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams
|
|
734
908
|
});
|
|
735
909
|
}
|
|
736
910
|
}
|
|
@@ -751,6 +925,9 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
|
|
|
751
925
|
function formatDeviceMismatchError(expected, actual) {
|
|
752
926
|
return `Wrong device: expected ${expected}, got ${actual}`;
|
|
753
927
|
}
|
|
928
|
+
function isLostConnectionError(err) {
|
|
929
|
+
return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
|
|
930
|
+
}
|
|
754
931
|
var BTC_HIGH_INDEX_THRESHOLD = 100;
|
|
755
932
|
function btcAccountIndexFromPath(path) {
|
|
756
933
|
const segments = path.replace(/^m\//, "").split("/");
|
|
@@ -762,10 +939,36 @@ function btcAccountIndexFromPath(path) {
|
|
|
762
939
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
763
940
|
constructor(connector, options) {
|
|
764
941
|
this.vendor = "ledger";
|
|
765
|
-
|
|
942
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
943
|
+
// confirmation screen the device is already showing.
|
|
944
|
+
this.cancelCapability = "stops-waiting";
|
|
945
|
+
this.emitter = new import_hwk_adapter_core4.TypedEventEmitter();
|
|
946
|
+
this._operations = new import_hwk_adapter_core4.OperationRegistry({
|
|
947
|
+
vendor: "ledger",
|
|
948
|
+
onEnded: (operation, reason) => {
|
|
949
|
+
this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
|
|
950
|
+
this._pendingOperationBindings.delete(operation.operationId);
|
|
951
|
+
this.emitter.emit(import_hwk_adapter_core4.SDK.OPERATION_ENDED, {
|
|
952
|
+
type: import_hwk_adapter_core4.SDK.OPERATION_ENDED,
|
|
953
|
+
payload: { operationId: operation.operationId, reason }
|
|
954
|
+
});
|
|
955
|
+
if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
|
|
956
|
+
void this._releaseOperationConnection(operation);
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
});
|
|
766
960
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
767
961
|
this._sessions = /* @__PURE__ */ new Map();
|
|
768
|
-
|
|
962
|
+
// An operation's BLE pick is saved by its first call that gets past the wallet check.
|
|
963
|
+
this._pendingOperationBindings = /* @__PURE__ */ new Map();
|
|
964
|
+
// A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
|
|
965
|
+
// through an unlock retry; any other failure drops it with its session.
|
|
966
|
+
this._pendingPickBindings = /* @__PURE__ */ new Map();
|
|
967
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
968
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
969
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
970
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
971
|
+
this._uiRegistry = new import_hwk_adapter_core4.UiRequestRegistry();
|
|
769
972
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
770
973
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
771
974
|
// subsequent 100+ paths in the same session auto-promote silently.
|
|
@@ -778,21 +981,36 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
981
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
779
982
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
780
983
|
this._doConnectAbortController = null;
|
|
984
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
985
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
986
|
+
this._resetPromise = null;
|
|
987
|
+
this._stateGeneration = 0;
|
|
988
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
989
|
+
this._pendingConnectorTeardowns = 0;
|
|
990
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
991
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
781
992
|
this._installProgressLastEmittedValue = -Infinity;
|
|
782
993
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
783
994
|
callChain: this.callChain.bind(this),
|
|
784
|
-
getChainFingerprint: (connectId, chain) =>
|
|
995
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
996
|
+
try {
|
|
997
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
998
|
+
chain,
|
|
999
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
1000
|
+
);
|
|
1001
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1002
|
+
} catch (error) {
|
|
1003
|
+
return this.errorToFailure(error);
|
|
1004
|
+
}
|
|
1005
|
+
},
|
|
1006
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
1007
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
1008
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
|
|
1009
|
+
releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
|
|
785
1010
|
});
|
|
786
1011
|
// ---------------------------------------------------------------------------
|
|
787
1012
|
// Private helpers
|
|
788
1013
|
// ---------------------------------------------------------------------------
|
|
789
|
-
/**
|
|
790
|
-
* Ensure at least one device is connected and return a valid connectId.
|
|
791
|
-
*
|
|
792
|
-
* - If a session already exists for the given connectId, reuse it.
|
|
793
|
-
* - If ANY session exists (Ledger IDs are ephemeral), reuse it.
|
|
794
|
-
* - Otherwise: search → exactly 1 USB device auto-connects; multiple or none throws.
|
|
795
|
-
*/
|
|
796
1014
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
797
1015
|
this._connectingPromise = null;
|
|
798
1016
|
// ---------------------------------------------------------------------------
|
|
@@ -802,26 +1020,31 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
802
1020
|
const deviceInfo = this.connectorDeviceToDeviceInfo(data.device);
|
|
803
1021
|
this._discoveredDevices.set(deviceInfo.connectId, deviceInfo);
|
|
804
1022
|
this._sessions.delete(deviceInfo.connectId);
|
|
805
|
-
this.emitter.emit(
|
|
806
|
-
type:
|
|
1023
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.CONNECT, {
|
|
1024
|
+
type: import_hwk_adapter_core4.DEVICE.CONNECT,
|
|
807
1025
|
payload: deviceInfo
|
|
808
1026
|
});
|
|
809
1027
|
};
|
|
810
1028
|
this.deviceDisconnectHandler = (data) => {
|
|
1029
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
1030
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
1031
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
1032
|
+
} else {
|
|
1033
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
1034
|
+
}
|
|
811
1035
|
this._discoveredDevices.delete(data.connectId);
|
|
812
1036
|
this._sessions.delete(data.connectId);
|
|
813
|
-
this.emitter.emit(
|
|
814
|
-
type:
|
|
1037
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.DISCONNECT, {
|
|
1038
|
+
type: import_hwk_adapter_core4.DEVICE.DISCONNECT,
|
|
815
1039
|
payload: { connectId: data.connectId }
|
|
816
1040
|
});
|
|
817
1041
|
};
|
|
818
1042
|
// Forward connector `ui-event` to the public hw.emitter so consumers only
|
|
819
|
-
// need to subscribe in one place.
|
|
820
|
-
//
|
|
821
|
-
// exists (race during teardown) we drop. All other variants pass through
|
|
822
|
-
// unchanged.
|
|
1043
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
1044
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
823
1045
|
this.uiEventForwarder = (event) => {
|
|
824
|
-
|
|
1046
|
+
const operationId = this._activeOperationId();
|
|
1047
|
+
if (event.type === import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress) {
|
|
825
1048
|
let connectId;
|
|
826
1049
|
for (const [cid, sid] of this._sessions) {
|
|
827
1050
|
if (sid === event.payload.sessionId) {
|
|
@@ -848,7 +1071,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
848
1071
|
}
|
|
849
1072
|
this._installProgressLastEmittedValue = progress;
|
|
850
1073
|
this.emitter.emit("ui-event", {
|
|
851
|
-
type:
|
|
1074
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1075
|
+
...operationId ? { operationId } : {},
|
|
852
1076
|
payload: {
|
|
853
1077
|
connectId,
|
|
854
1078
|
appName,
|
|
@@ -857,18 +1081,37 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
857
1081
|
});
|
|
858
1082
|
return;
|
|
859
1083
|
}
|
|
860
|
-
this.emitter.emit("ui-event", event);
|
|
1084
|
+
this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
|
|
861
1085
|
};
|
|
862
1086
|
this.connector = connector;
|
|
863
1087
|
this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
|
|
864
|
-
this._jobQueue = new
|
|
1088
|
+
this._jobQueue = new import_hwk_adapter_core4.DeviceJobQueue();
|
|
865
1089
|
this.registerEventListeners();
|
|
866
1090
|
}
|
|
1091
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1092
|
+
const pending = owner?.pendingBinding;
|
|
1093
|
+
if (!owner || !pending) return;
|
|
1094
|
+
owner.pendingBinding = void 0;
|
|
1095
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1096
|
+
}
|
|
1097
|
+
_finishBleBinding(status) {
|
|
1098
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1099
|
+
this._bindingSelectionRequestId = void 0;
|
|
1100
|
+
if (selectionRequestId) (0, import_hwk_adapter_core4.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
|
|
1101
|
+
}
|
|
1102
|
+
_isBleConnection() {
|
|
1103
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1104
|
+
}
|
|
867
1105
|
// Transport
|
|
868
1106
|
get activeTransport() {
|
|
869
|
-
return
|
|
1107
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
870
1108
|
}
|
|
871
1109
|
getAvailableTransports() {
|
|
1110
|
+
if (this.connector.availableTransports) {
|
|
1111
|
+
return this.connector.availableTransports.map(
|
|
1112
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1113
|
+
);
|
|
1114
|
+
}
|
|
872
1115
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
873
1116
|
}
|
|
874
1117
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -885,21 +1128,43 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
885
1128
|
* The next operation will re-discover and re-connect automatically.
|
|
886
1129
|
*/
|
|
887
1130
|
resetState() {
|
|
1131
|
+
void this._resetStateAndDisconnectSessions();
|
|
1132
|
+
}
|
|
1133
|
+
_resetStateAndDisconnectSessions() {
|
|
1134
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1135
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1136
|
+
this._stateGeneration += 1;
|
|
1137
|
+
this._finishBleBinding("cancelled");
|
|
1138
|
+
this._operations.endAll("runtime-reset");
|
|
1139
|
+
this._doConnectAbortController?.abort();
|
|
888
1140
|
this._discoveredDevices.clear();
|
|
889
1141
|
this._sessions.clear();
|
|
1142
|
+
this._sessionTransports.clear();
|
|
1143
|
+
this._activeConnectionType = void 0;
|
|
1144
|
+
this._pendingOperationBindings.clear();
|
|
1145
|
+
this._pendingPickBindings.clear();
|
|
1146
|
+
this._selectedBleReconnectTargets.clear();
|
|
890
1147
|
this._connectingPromise = null;
|
|
1148
|
+
this._doConnectAbortController = null;
|
|
891
1149
|
this._uiRegistry.reset();
|
|
892
1150
|
this._jobQueue.clear();
|
|
893
1151
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1152
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1153
|
+
for (const sessionId of sessionIds) {
|
|
1154
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1155
|
+
}
|
|
1156
|
+
});
|
|
1157
|
+
this._resetPromise = resetPromise;
|
|
1158
|
+
return resetPromise.finally(() => {
|
|
1159
|
+
if (this._resetPromise === resetPromise) {
|
|
1160
|
+
this._resetPromise = null;
|
|
1161
|
+
}
|
|
1162
|
+
});
|
|
894
1163
|
}
|
|
895
1164
|
async dispose() {
|
|
896
|
-
this.
|
|
897
|
-
this._jobQueue.clear();
|
|
1165
|
+
await this._resetStateAndDisconnectSessions();
|
|
898
1166
|
this.unregisterEventListeners();
|
|
899
1167
|
this.connector.reset();
|
|
900
|
-
this._discoveredDevices.clear();
|
|
901
|
-
this._sessions.clear();
|
|
902
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
903
1168
|
this.emitter.removeAllListeners();
|
|
904
1169
|
}
|
|
905
1170
|
uiResponse(response) {
|
|
@@ -909,17 +1174,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
909
1174
|
// Device management
|
|
910
1175
|
// ---------------------------------------------------------------------------
|
|
911
1176
|
async searchDevices(options) {
|
|
1177
|
+
return this._searchDevices(options);
|
|
1178
|
+
}
|
|
1179
|
+
async _searchDevices(options, signal) {
|
|
912
1180
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
913
1181
|
try {
|
|
914
1182
|
if (options?.resetSession) {
|
|
915
|
-
this.
|
|
916
|
-
|
|
917
|
-
this.
|
|
918
|
-
|
|
919
|
-
|
|
1183
|
+
await this._resetStateAndDisconnectSessions();
|
|
1184
|
+
} else {
|
|
1185
|
+
await this._connectorTeardownTail;
|
|
1186
|
+
}
|
|
1187
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1188
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1189
|
+
const stateGeneration = this._stateGeneration;
|
|
1190
|
+
const devices = await this.connector.searchDevices(
|
|
1191
|
+
options?.transportType ? {
|
|
1192
|
+
transportType: options.transportType,
|
|
1193
|
+
waitForAll: options.waitForAllTransports
|
|
1194
|
+
} : void 0
|
|
1195
|
+
);
|
|
1196
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1197
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1198
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1199
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1200
|
+
message: "Ledger discovery was reset"
|
|
1201
|
+
});
|
|
920
1202
|
}
|
|
921
|
-
await this._ensureDevicePermission();
|
|
922
|
-
const devices = await this.connector.searchDevices();
|
|
923
1203
|
this._discoveredDevices.clear();
|
|
924
1204
|
for (const d of devices) {
|
|
925
1205
|
if (d.connectId) {
|
|
@@ -927,7 +1207,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
927
1207
|
}
|
|
928
1208
|
}
|
|
929
1209
|
if (this._discoveredDevices.size === 0) {
|
|
930
|
-
await this._ensureDevicePermission();
|
|
1210
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
931
1211
|
}
|
|
932
1212
|
const result = Array.from(this._discoveredDevices.values());
|
|
933
1213
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -946,41 +1226,267 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
946
1226
|
throw err;
|
|
947
1227
|
}
|
|
948
1228
|
}
|
|
1229
|
+
async searchDeviceTargets(options) {
|
|
1230
|
+
const devices = await this.searchDevices(options);
|
|
1231
|
+
return devices.map((device) => (0, import_hwk_adapter_core4.toPhysicalDeviceSearchTarget)("ledger", device));
|
|
1232
|
+
}
|
|
949
1233
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
950
|
-
async _evictAllSessions() {
|
|
1234
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1235
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
951
1236
|
if (this._sessions.size === 0) return;
|
|
952
1237
|
const stale = [...this._sessions.values()];
|
|
953
1238
|
this._sessions.clear();
|
|
954
|
-
for (const sid of stale)
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1239
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1240
|
+
await this._runConnectorTeardown(async () => {
|
|
1241
|
+
for (const sid of stale) {
|
|
1242
|
+
try {
|
|
1243
|
+
await this.connector.disconnect(sid);
|
|
1244
|
+
} catch {
|
|
1245
|
+
}
|
|
958
1246
|
}
|
|
959
|
-
}
|
|
1247
|
+
});
|
|
960
1248
|
}
|
|
961
1249
|
static _createDeviceBusyError(method) {
|
|
962
1250
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
963
|
-
code:
|
|
1251
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceBusy
|
|
1252
|
+
});
|
|
1253
|
+
}
|
|
1254
|
+
async connectDevice(searchTargetId) {
|
|
1255
|
+
try {
|
|
1256
|
+
return await this._jobQueue.enqueue(
|
|
1257
|
+
searchTargetId || "__ledger_connect__",
|
|
1258
|
+
async (signal) => {
|
|
1259
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1260
|
+
if (!connected.success) return connected;
|
|
1261
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1262
|
+
},
|
|
1263
|
+
{
|
|
1264
|
+
label: "connectDevice",
|
|
1265
|
+
rejectIfBusy: true,
|
|
1266
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1267
|
+
}
|
|
1268
|
+
);
|
|
1269
|
+
} catch (error) {
|
|
1270
|
+
return this.errorToFailure(error);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1274
|
+
async bindBleDevice(params) {
|
|
1275
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1276
|
+
const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
|
|
1277
|
+
try {
|
|
1278
|
+
return await this._jobQueue.enqueue(
|
|
1279
|
+
"__ledger_bind_ble__",
|
|
1280
|
+
async (signal) => {
|
|
1281
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1282
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1283
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.TransportNotAvailable,
|
|
1284
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
this._activeConnectionType = "ble";
|
|
1288
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1289
|
+
const attempt = {
|
|
1290
|
+
extra: params.extra,
|
|
1291
|
+
bindingReason: "manual-rebind",
|
|
1292
|
+
deferBindingSave: Boolean(identity)
|
|
1293
|
+
};
|
|
1294
|
+
try {
|
|
1295
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1296
|
+
[],
|
|
1297
|
+
void 0,
|
|
1298
|
+
true,
|
|
1299
|
+
void 0,
|
|
1300
|
+
attempt,
|
|
1301
|
+
signal
|
|
1302
|
+
);
|
|
1303
|
+
const pending = attempt.pendingBinding;
|
|
1304
|
+
if (identity && pending) {
|
|
1305
|
+
attempt.pendingBinding = void 0;
|
|
1306
|
+
const sessionId = this._sessions.get(connectId);
|
|
1307
|
+
if (!sessionId) {
|
|
1308
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1309
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
1310
|
+
message: "Selected Ledger connection ended"
|
|
1311
|
+
});
|
|
1312
|
+
}
|
|
1313
|
+
const checked = await this._fingerprintFirstOpenableChain(
|
|
1314
|
+
identities,
|
|
1315
|
+
(chain, autoInstallApp) => this._computeChainFingerprint(
|
|
1316
|
+
chain,
|
|
1317
|
+
(method, callParams) => this._runConnectorCall(
|
|
1318
|
+
connectId,
|
|
1319
|
+
method,
|
|
1320
|
+
callParams,
|
|
1321
|
+
signal,
|
|
1322
|
+
void 0,
|
|
1323
|
+
void 0,
|
|
1324
|
+
{ autoInstallApp },
|
|
1325
|
+
{ connection: { connectId, sessionId } }
|
|
1326
|
+
)
|
|
1327
|
+
)
|
|
1328
|
+
);
|
|
1329
|
+
if (checked.fingerprint !== checked.identity.value) {
|
|
1330
|
+
await this._dropSession(connectId, signal);
|
|
1331
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1332
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
1333
|
+
message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
|
|
1334
|
+
});
|
|
1335
|
+
}
|
|
1336
|
+
await this._saveSelectedBleBinding(
|
|
1337
|
+
connectId,
|
|
1338
|
+
pending.requestId,
|
|
1339
|
+
attempt,
|
|
1340
|
+
void 0,
|
|
1341
|
+
signal,
|
|
1342
|
+
checked.identity
|
|
1343
|
+
);
|
|
1344
|
+
}
|
|
1345
|
+
if (!attempt.bindingSaved) {
|
|
1346
|
+
await this._dropSession(connectId, signal);
|
|
1347
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1348
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1349
|
+
message: "Bluetooth binding could not be saved",
|
|
1350
|
+
origin: "host"
|
|
1351
|
+
});
|
|
1352
|
+
}
|
|
1353
|
+
return (0, import_hwk_adapter_core4.success)(connectId);
|
|
1354
|
+
} catch (error) {
|
|
1355
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1356
|
+
throw error;
|
|
1357
|
+
}
|
|
1358
|
+
},
|
|
1359
|
+
{
|
|
1360
|
+
label: "bindBleDevice",
|
|
1361
|
+
rejectIfBusy: true,
|
|
1362
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1363
|
+
}
|
|
1364
|
+
);
|
|
1365
|
+
} catch (error) {
|
|
1366
|
+
return this.errorToFailure(error);
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
async acquireOperation(connectId, context) {
|
|
1370
|
+
try {
|
|
1371
|
+
return await this._jobQueue.enqueue(
|
|
1372
|
+
connectId || "__ledger_acquire__",
|
|
1373
|
+
async (signal) => {
|
|
1374
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1375
|
+
const hint = context.knownConnections?.find(
|
|
1376
|
+
(connection) => connection.transport === transport
|
|
1377
|
+
);
|
|
1378
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1379
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1380
|
+
const attempt = {
|
|
1381
|
+
...context,
|
|
1382
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1383
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1384
|
+
deferBindingSave: true
|
|
1385
|
+
};
|
|
1386
|
+
try {
|
|
1387
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1388
|
+
target,
|
|
1389
|
+
signal,
|
|
1390
|
+
true,
|
|
1391
|
+
void 0,
|
|
1392
|
+
attempt
|
|
1393
|
+
);
|
|
1394
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1395
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1396
|
+
if (result.success && attempt.pendingBinding) {
|
|
1397
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1398
|
+
}
|
|
1399
|
+
return result;
|
|
1400
|
+
} catch (error) {
|
|
1401
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1402
|
+
throw error;
|
|
1403
|
+
}
|
|
1404
|
+
},
|
|
1405
|
+
{
|
|
1406
|
+
label: "acquireOperation",
|
|
1407
|
+
rejectIfBusy: true,
|
|
1408
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1409
|
+
}
|
|
1410
|
+
);
|
|
1411
|
+
} catch (error) {
|
|
1412
|
+
return this.errorToFailure(error);
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1416
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1417
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1418
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1419
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1420
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1421
|
+
vendor: "ledger",
|
|
1422
|
+
model: "unknown",
|
|
1423
|
+
firmwareVersion: "",
|
|
1424
|
+
deviceId: "",
|
|
1425
|
+
connectId: resolvedConnectId,
|
|
1426
|
+
connectionType
|
|
1427
|
+
};
|
|
1428
|
+
const operation = this._operations.create({
|
|
1429
|
+
searchTargetId,
|
|
1430
|
+
connectId: resolvedConnectId,
|
|
1431
|
+
device,
|
|
1432
|
+
connectionType,
|
|
1433
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
964
1434
|
});
|
|
1435
|
+
return (0, import_hwk_adapter_core4.success)(operation.operationId);
|
|
965
1436
|
}
|
|
966
|
-
async
|
|
1437
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
967
1438
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
968
1439
|
try {
|
|
969
|
-
|
|
1440
|
+
this._assertConnectorReady("connectDevice");
|
|
1441
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1442
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1443
|
+
this._activeConnectionType = discoveredType;
|
|
1444
|
+
}
|
|
1445
|
+
if (this._isBleConnection() && !connectId) {
|
|
970
1446
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
971
|
-
code:
|
|
1447
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
972
1448
|
});
|
|
973
1449
|
}
|
|
974
|
-
|
|
975
|
-
|
|
1450
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1451
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1452
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1453
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1454
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1455
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1456
|
+
if (previousSessionId) {
|
|
1457
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1458
|
+
this._sessions.delete(connectId);
|
|
1459
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1460
|
+
}
|
|
1461
|
+
} else {
|
|
1462
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1463
|
+
}
|
|
1464
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1465
|
+
const stateGeneration = this._stateGeneration;
|
|
1466
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1467
|
+
let session;
|
|
1468
|
+
this._connectingConnectId = connectId;
|
|
1469
|
+
try {
|
|
1470
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1471
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1472
|
+
}) : await this.connector.connect(connectId);
|
|
1473
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1474
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1475
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1476
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1477
|
+
});
|
|
1478
|
+
}
|
|
1479
|
+
} finally {
|
|
1480
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1481
|
+
releaseOperation();
|
|
976
1482
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
this.
|
|
1483
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1484
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1485
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
980
1486
|
if (session.deviceInfo) {
|
|
981
|
-
this._discoveredDevices.set(
|
|
1487
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
982
1488
|
}
|
|
983
|
-
const result = (0,
|
|
1489
|
+
const result = (0, import_hwk_adapter_core4.success)(resolvedConnectId);
|
|
984
1490
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
985
1491
|
return result;
|
|
986
1492
|
} catch (err) {
|
|
@@ -993,30 +1499,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
993
1499
|
return failureResult;
|
|
994
1500
|
}
|
|
995
1501
|
}
|
|
996
|
-
async
|
|
1502
|
+
async releaseOperation(operationId) {
|
|
1503
|
+
const operation = this._operations.findActive(operationId);
|
|
1504
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1505
|
+
const endedOperation = this._operations.release(operationId);
|
|
1506
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1507
|
+
const { connectId } = endedOperation;
|
|
997
1508
|
debugLog("[LedgerAdapter][REQ]", {
|
|
998
|
-
method: "
|
|
1509
|
+
method: "releaseOperation",
|
|
999
1510
|
connectId,
|
|
1000
1511
|
params: { connectId }
|
|
1001
1512
|
});
|
|
1002
1513
|
try {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
await this.connector.disconnect(sessionId);
|
|
1006
|
-
this._sessions.delete(connectId);
|
|
1007
|
-
}
|
|
1008
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1514
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1515
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
1009
1516
|
} catch (err) {
|
|
1010
1517
|
const e = err;
|
|
1011
1518
|
debugLog("[LedgerAdapter][RES]", {
|
|
1012
|
-
method: "
|
|
1519
|
+
method: "releaseOperation",
|
|
1013
1520
|
success: false,
|
|
1014
1521
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1522
|
});
|
|
1016
1523
|
throw err;
|
|
1017
1524
|
}
|
|
1018
1525
|
}
|
|
1019
|
-
|
|
1526
|
+
/**
|
|
1527
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1528
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1529
|
+
*/
|
|
1530
|
+
_cancelOperationWork(operation) {
|
|
1531
|
+
const { operationId } = operation;
|
|
1532
|
+
const reason = (0, import_hwk_adapter_core4.createHwkError)({
|
|
1533
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
1534
|
+
message: "Ledger operation was released",
|
|
1535
|
+
params: { operationId, reason: "explicit" }
|
|
1536
|
+
});
|
|
1537
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1538
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1539
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1540
|
+
if (!ownsRunningCall) return;
|
|
1541
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1542
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1543
|
+
}
|
|
1544
|
+
/**
|
|
1545
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1546
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1547
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1548
|
+
*/
|
|
1549
|
+
_bareCallMayUseConnection(operation) {
|
|
1550
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1551
|
+
return activeKey !== void 0 && !(0, import_hwk_adapter_core4.isHardwareOperationId)(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1552
|
+
}
|
|
1553
|
+
async _releaseOperationConnection(operation) {
|
|
1554
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1555
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1556
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1557
|
+
this._sessions.delete(connectId);
|
|
1558
|
+
sessionIds.add(sessionId);
|
|
1559
|
+
}
|
|
1560
|
+
}
|
|
1561
|
+
for (const sessionId of sessionIds) {
|
|
1562
|
+
await this._runConnectorTeardown(
|
|
1563
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1564
|
+
);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1568
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1569
|
+
if (!endedOperation) return;
|
|
1570
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1571
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1572
|
+
}
|
|
1573
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1574
|
+
let connectId;
|
|
1575
|
+
try {
|
|
1576
|
+
connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1577
|
+
} catch (error) {
|
|
1578
|
+
return this.errorToFailure(error);
|
|
1579
|
+
}
|
|
1020
1580
|
debugLog("[LedgerAdapter][REQ]", {
|
|
1021
1581
|
method: "getDeviceInfo",
|
|
1022
1582
|
connectId,
|
|
@@ -1026,7 +1586,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1026
1586
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
1027
1587
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
1028
1588
|
if (cached) {
|
|
1029
|
-
const result = (0,
|
|
1589
|
+
const result = (0, import_hwk_adapter_core4.success)(cached);
|
|
1030
1590
|
debugLog("[LedgerAdapter][RES]", {
|
|
1031
1591
|
method: "getDeviceInfo",
|
|
1032
1592
|
success: true,
|
|
@@ -1034,8 +1594,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1034
1594
|
});
|
|
1035
1595
|
return result;
|
|
1036
1596
|
}
|
|
1037
|
-
const notFound = (0,
|
|
1038
|
-
|
|
1597
|
+
const notFound = (0, import_hwk_adapter_core4.failure)(
|
|
1598
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
1039
1599
|
"Device not found in cache. Call searchDevices() or wait for a device-connected event first."
|
|
1040
1600
|
);
|
|
1041
1601
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -1051,11 +1611,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1051
1611
|
success: false,
|
|
1052
1612
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1053
1613
|
});
|
|
1054
|
-
|
|
1614
|
+
return this.errorToFailure(err);
|
|
1055
1615
|
}
|
|
1056
1616
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1617
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1618
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1619
|
+
const { connection } = context;
|
|
1620
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1621
|
+
if (!connection || !owner) return;
|
|
1622
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1623
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1624
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1625
|
+
await this._dropSession(connection.connectId, signal);
|
|
1626
|
+
}
|
|
1059
1627
|
}
|
|
1060
1628
|
// ---------------------------------------------------------------------------
|
|
1061
1629
|
// Chain call helper
|
|
@@ -1075,7 +1643,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1075
1643
|
commonParams,
|
|
1076
1644
|
installContext
|
|
1077
1645
|
);
|
|
1078
|
-
return (0,
|
|
1646
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1079
1647
|
} catch (err) {
|
|
1080
1648
|
return this.errorToFailure(err);
|
|
1081
1649
|
}
|
|
@@ -1091,13 +1659,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1091
1659
|
if (params && typeof params === "object") {
|
|
1092
1660
|
const {
|
|
1093
1661
|
autoInstallApp,
|
|
1662
|
+
operationId,
|
|
1094
1663
|
passphraseState: _passphraseState,
|
|
1095
1664
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1665
|
+
knownConnections,
|
|
1666
|
+
extra,
|
|
1667
|
+
allowDeviceSelection,
|
|
1668
|
+
supportedTransports,
|
|
1096
1669
|
...rest
|
|
1097
1670
|
} = params;
|
|
1098
1671
|
return {
|
|
1099
1672
|
commonParams: {
|
|
1100
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1673
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1674
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1675
|
+
...(0, import_hwk_adapter_core4.pickConnectionContext)({
|
|
1676
|
+
knownConnections,
|
|
1677
|
+
extra,
|
|
1678
|
+
allowDeviceSelection,
|
|
1679
|
+
supportedTransports
|
|
1680
|
+
})
|
|
1101
1681
|
},
|
|
1102
1682
|
rest
|
|
1103
1683
|
};
|
|
@@ -1263,7 +1843,13 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1263
1843
|
params
|
|
1264
1844
|
);
|
|
1265
1845
|
}
|
|
1266
|
-
tronSignMessage(connectId, deviceId, params) {
|
|
1846
|
+
async tronSignMessage(connectId, deviceId, params) {
|
|
1847
|
+
if (params?.messageType !== "V2") {
|
|
1848
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1849
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1850
|
+
'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
|
|
1851
|
+
);
|
|
1852
|
+
}
|
|
1267
1853
|
return this.callChainWithMergedParams(
|
|
1268
1854
|
connectId,
|
|
1269
1855
|
deviceId,
|
|
@@ -1273,14 +1859,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1273
1859
|
);
|
|
1274
1860
|
}
|
|
1275
1861
|
// ---------------------------------------------------------------------------
|
|
1276
|
-
//
|
|
1277
|
-
//
|
|
1278
|
-
|
|
1862
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1863
|
+
// ---------------------------------------------------------------------------
|
|
1864
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1865
|
+
return this.callChainWithMergedParams(
|
|
1866
|
+
connectId,
|
|
1867
|
+
deviceId,
|
|
1868
|
+
"zcash",
|
|
1869
|
+
"zcashGetFullViewingKey",
|
|
1870
|
+
params
|
|
1871
|
+
);
|
|
1872
|
+
}
|
|
1873
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1874
|
+
return this.callChainWithMergedParams(
|
|
1875
|
+
connectId,
|
|
1876
|
+
deviceId,
|
|
1877
|
+
"zcash",
|
|
1878
|
+
"zcashGetShieldedAddress",
|
|
1879
|
+
params
|
|
1880
|
+
);
|
|
1881
|
+
}
|
|
1882
|
+
// ---------------------------------------------------------------------------
|
|
1883
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1279
1884
|
// ---------------------------------------------------------------------------
|
|
1280
1885
|
async installApp(connectId, appName) {
|
|
1281
1886
|
try {
|
|
1282
1887
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1283
|
-
return (0,
|
|
1888
|
+
return (0, import_hwk_adapter_core4.success)(void 0);
|
|
1284
1889
|
} catch (err) {
|
|
1285
1890
|
return this.errorToFailure(err);
|
|
1286
1891
|
}
|
|
@@ -1288,7 +1893,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1288
1893
|
async listInstalledApps(connectId) {
|
|
1289
1894
|
try {
|
|
1290
1895
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1291
|
-
return (0,
|
|
1896
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1292
1897
|
} catch (err) {
|
|
1293
1898
|
return this.errorToFailure(err);
|
|
1294
1899
|
}
|
|
@@ -1297,7 +1902,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1297
1902
|
async listInstalledNames(connectId) {
|
|
1298
1903
|
try {
|
|
1299
1904
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1300
|
-
return (0,
|
|
1905
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1301
1906
|
} catch (err) {
|
|
1302
1907
|
return this.errorToFailure(err);
|
|
1303
1908
|
}
|
|
@@ -1305,7 +1910,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1305
1910
|
async listAvailableApps(connectId) {
|
|
1306
1911
|
try {
|
|
1307
1912
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1308
|
-
return (0,
|
|
1913
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1309
1914
|
} catch (err) {
|
|
1310
1915
|
return this.errorToFailure(err);
|
|
1311
1916
|
}
|
|
@@ -1313,7 +1918,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1313
1918
|
async getLedgerFirmwareVersion(connectId) {
|
|
1314
1919
|
try {
|
|
1315
1920
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1316
|
-
return (0,
|
|
1921
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1317
1922
|
} catch (err) {
|
|
1318
1923
|
return this.errorToFailure(err);
|
|
1319
1924
|
}
|
|
@@ -1321,7 +1926,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1321
1926
|
async getLedgerDeviceInfo(connectId) {
|
|
1322
1927
|
try {
|
|
1323
1928
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1324
|
-
return (0,
|
|
1929
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1325
1930
|
} catch (err) {
|
|
1326
1931
|
return this.errorToFailure(err);
|
|
1327
1932
|
}
|
|
@@ -1355,28 +1960,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1355
1960
|
try {
|
|
1356
1961
|
if (relayUrl) {
|
|
1357
1962
|
if (!this.connector.configure) {
|
|
1358
|
-
return (0,
|
|
1359
|
-
|
|
1963
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1964
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1360
1965
|
"This Ledger connector does not support genuine-check relay configuration"
|
|
1361
1966
|
);
|
|
1362
1967
|
}
|
|
1363
1968
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1364
|
-
this.
|
|
1969
|
+
await this._resetStateAndDisconnectSessions();
|
|
1365
1970
|
}
|
|
1366
1971
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1367
1972
|
if (!result.isGenuine) {
|
|
1368
|
-
return (0,
|
|
1973
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1369
1974
|
vendor: "ledger",
|
|
1370
1975
|
verified: false
|
|
1371
1976
|
});
|
|
1372
1977
|
}
|
|
1373
1978
|
if (!result.deviceId) {
|
|
1374
|
-
return (0,
|
|
1375
|
-
|
|
1979
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1980
|
+
import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1376
1981
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1377
1982
|
);
|
|
1378
1983
|
}
|
|
1379
|
-
return (0,
|
|
1984
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1380
1985
|
vendor: "ledger",
|
|
1381
1986
|
verified: result.isGenuine,
|
|
1382
1987
|
deviceId: result.deviceId
|
|
@@ -1387,10 +1992,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1387
1992
|
if (relayUrl) {
|
|
1388
1993
|
try {
|
|
1389
1994
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1390
|
-
this.
|
|
1995
|
+
await this._resetStateAndDisconnectSessions();
|
|
1391
1996
|
} catch {
|
|
1392
1997
|
this.connector.reset();
|
|
1393
|
-
this.
|
|
1998
|
+
await this._resetStateAndDisconnectSessions();
|
|
1394
1999
|
}
|
|
1395
2000
|
}
|
|
1396
2001
|
}
|
|
@@ -1402,8 +2007,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1402
2007
|
this.emitter.off(event, listener);
|
|
1403
2008
|
}
|
|
1404
2009
|
cancel(connectId) {
|
|
2010
|
+
const namedOperationIsLive = (id) => {
|
|
2011
|
+
try {
|
|
2012
|
+
this._operations.resolve(id);
|
|
2013
|
+
return true;
|
|
2014
|
+
} catch {
|
|
2015
|
+
return false;
|
|
2016
|
+
}
|
|
2017
|
+
};
|
|
2018
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
|
|
2019
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
2020
|
+
connectId
|
|
2021
|
+
});
|
|
2022
|
+
return;
|
|
2023
|
+
}
|
|
1405
2024
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1406
|
-
code:
|
|
2025
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1407
2026
|
_tag: ERROR_TAG.UserAborted
|
|
1408
2027
|
});
|
|
1409
2028
|
this._lastCancelReason = userAbortReason;
|
|
@@ -1412,60 +2031,163 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1412
2031
|
this._lastCancelReason = void 0;
|
|
1413
2032
|
}
|
|
1414
2033
|
}, 2e3);
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
2034
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
2035
|
+
let operationId;
|
|
2036
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
|
|
2037
|
+
operationId = connectId;
|
|
2038
|
+
} else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
|
|
2039
|
+
operationId = activeJobId;
|
|
1420
2040
|
}
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
2041
|
+
let resolvedConnectId = connectId;
|
|
2042
|
+
if (operationId) {
|
|
2043
|
+
try {
|
|
2044
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2045
|
+
} catch {
|
|
2046
|
+
resolvedConnectId = void 0;
|
|
2047
|
+
}
|
|
1426
2048
|
}
|
|
1427
|
-
|
|
2049
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2050
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2051
|
+
if (!connectId) {
|
|
2052
|
+
this._uiRegistry.cancel();
|
|
2053
|
+
} else if (pendingOperationId) {
|
|
2054
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2055
|
+
}
|
|
2056
|
+
this._finishBleBinding("cancelled");
|
|
2057
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2058
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2059
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2060
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2061
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2062
|
+
if (queueKeys.size) {
|
|
2063
|
+
let cancelledAnyJob = false;
|
|
2064
|
+
for (const key of queueKeys) {
|
|
2065
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2066
|
+
}
|
|
2067
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2068
|
+
queueKeys: [...queueKeys],
|
|
2069
|
+
cancelledAnyJob
|
|
2070
|
+
});
|
|
2071
|
+
} else {
|
|
2072
|
+
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
2073
|
+
}
|
|
2074
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2075
|
+
const targetKeys = new Set(
|
|
2076
|
+
[
|
|
2077
|
+
connectId,
|
|
2078
|
+
resolvedConnectId,
|
|
2079
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2080
|
+
].filter(Boolean)
|
|
2081
|
+
);
|
|
2082
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2083
|
+
if (activeJobId === void 0 || ownsPendingConnect) {
|
|
2084
|
+
if (resolvedConnectId) {
|
|
2085
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
2086
|
+
void this.connector.cancel(sessionId);
|
|
2087
|
+
} else {
|
|
2088
|
+
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
2089
|
+
}
|
|
2090
|
+
}
|
|
2091
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
1428
2092
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1429
2093
|
}
|
|
2094
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1430
2095
|
}
|
|
1431
2096
|
// ---------------------------------------------------------------------------
|
|
1432
2097
|
// Chain fingerprint
|
|
1433
2098
|
// ---------------------------------------------------------------------------
|
|
2099
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1434
2100
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1435
2101
|
try {
|
|
1436
2102
|
const fingerprint = await this._computeChainFingerprint(
|
|
1437
2103
|
chain,
|
|
1438
2104
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1439
2105
|
);
|
|
1440
|
-
|
|
2106
|
+
if (deviceId) {
|
|
2107
|
+
if (fingerprint !== deviceId) {
|
|
2108
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
2109
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2110
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2111
|
+
);
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1441
2115
|
} catch (err) {
|
|
1442
2116
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1443
2117
|
return this.errorToFailure(err);
|
|
1444
2118
|
}
|
|
1445
2119
|
}
|
|
1446
2120
|
/**
|
|
1447
|
-
*
|
|
1448
|
-
*
|
|
2121
|
+
* Fingerprints the first recorded chain whose app the device can open. Only a missing app
|
|
2122
|
+
* moves on to the next chain; when every app is missing, the first chain offers its install.
|
|
1449
2123
|
*/
|
|
1450
|
-
async
|
|
1451
|
-
|
|
2124
|
+
async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
|
|
2125
|
+
const [first] = identities;
|
|
2126
|
+
if (identities.length > 1) {
|
|
2127
|
+
for (const identity of identities) {
|
|
2128
|
+
try {
|
|
2129
|
+
return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
|
|
2130
|
+
} catch (error) {
|
|
2131
|
+
const isAppMissing = isAppNotInstalledError(error) || error?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
2132
|
+
if (!isAppMissing) throw error;
|
|
2133
|
+
}
|
|
2134
|
+
}
|
|
2135
|
+
}
|
|
2136
|
+
return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
|
|
2137
|
+
}
|
|
2138
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2139
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1452
2140
|
try {
|
|
1453
|
-
const
|
|
1454
|
-
|
|
1455
|
-
|
|
2141
|
+
const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
|
|
2142
|
+
this.emitter,
|
|
2143
|
+
this._uiRegistry,
|
|
2144
|
+
{
|
|
2145
|
+
selectionRequestId,
|
|
2146
|
+
connection: { transport: "ble", connectId },
|
|
2147
|
+
...identity ? { identity } : {},
|
|
2148
|
+
extra: context?.extra,
|
|
2149
|
+
operationId
|
|
2150
|
+
},
|
|
2151
|
+
signal
|
|
1456
2152
|
);
|
|
1457
|
-
if (
|
|
1458
|
-
|
|
2153
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2154
|
+
if (!outcome.saved) {
|
|
2155
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2156
|
+
connectId,
|
|
2157
|
+
reason: outcome.reason
|
|
2158
|
+
});
|
|
1459
2159
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
2160
|
+
} catch (error) {
|
|
2161
|
+
await this._dropSession(connectId, signal);
|
|
2162
|
+
throw error;
|
|
2163
|
+
} finally {
|
|
2164
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2165
|
+
this._bindingSelectionRequestId = void 0;
|
|
1465
2166
|
}
|
|
1466
|
-
throw err;
|
|
1467
2167
|
}
|
|
1468
2168
|
}
|
|
2169
|
+
async _dropSession(connectId, signal) {
|
|
2170
|
+
const sessionId = this._sessions.get(connectId);
|
|
2171
|
+
this._sessions.delete(connectId);
|
|
2172
|
+
if (!sessionId) return;
|
|
2173
|
+
this._sessionTransports.delete(sessionId);
|
|
2174
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2175
|
+
() => void 0
|
|
2176
|
+
);
|
|
2177
|
+
if (!signal.aborted) await teardown;
|
|
2178
|
+
}
|
|
2179
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2180
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2181
|
+
if (!deviceId) return { success: true };
|
|
2182
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2183
|
+
chain,
|
|
2184
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2185
|
+
);
|
|
2186
|
+
if (fingerprint === deviceId) {
|
|
2187
|
+
return { success: true };
|
|
2188
|
+
}
|
|
2189
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2190
|
+
}
|
|
1469
2191
|
/**
|
|
1470
2192
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1471
2193
|
*
|
|
@@ -1485,7 +2207,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1485
2207
|
const result = await callMethod("btcGetMasterFingerprint", {});
|
|
1486
2208
|
return result.masterFingerprint;
|
|
1487
2209
|
}
|
|
1488
|
-
const path =
|
|
2210
|
+
const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
|
|
1489
2211
|
let address;
|
|
1490
2212
|
if (chain === "evm") {
|
|
1491
2213
|
address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
|
|
@@ -1493,10 +2215,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1493
2215
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1494
2216
|
} else if (chain === "tron") {
|
|
1495
2217
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2218
|
+
} else if (chain === "zcash") {
|
|
2219
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1496
2220
|
} else {
|
|
1497
2221
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1498
2222
|
}
|
|
1499
|
-
return (0,
|
|
2223
|
+
return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
|
|
2224
|
+
}
|
|
2225
|
+
/**
|
|
2226
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2227
|
+
* Undefined at cold start when no operation owns the job.
|
|
2228
|
+
*/
|
|
2229
|
+
_activeOperationId() {
|
|
2230
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
1500
2231
|
}
|
|
1501
2232
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1502
2233
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
@@ -1507,22 +2238,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1507
2238
|
if (signal?.aborted) {
|
|
1508
2239
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1509
2240
|
}
|
|
2241
|
+
const operationId = this._activeOperationId();
|
|
1510
2242
|
const waitPromise = this._uiRegistry.wait(
|
|
1511
|
-
|
|
2243
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2244
|
+
{ operationId }
|
|
1512
2245
|
);
|
|
1513
|
-
this.emitter.emit(
|
|
1514
|
-
type:
|
|
2246
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
2247
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1515
2248
|
payload: {
|
|
1516
2249
|
vendor: "ledger",
|
|
1517
2250
|
reason: "device-not-found",
|
|
1518
|
-
message: "Please connect and unlock your Ledger device"
|
|
2251
|
+
message: "Please connect and unlock your Ledger device",
|
|
2252
|
+
operationId
|
|
1519
2253
|
}
|
|
1520
2254
|
});
|
|
1521
2255
|
let payload;
|
|
1522
2256
|
try {
|
|
1523
2257
|
if (signal) {
|
|
1524
2258
|
const onAbort = () => {
|
|
1525
|
-
this._uiRegistry.cancel(
|
|
2259
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
|
|
1526
2260
|
};
|
|
1527
2261
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
1528
2262
|
try {
|
|
@@ -1534,20 +2268,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1534
2268
|
payload = await waitPromise;
|
|
1535
2269
|
}
|
|
1536
2270
|
} catch (err) {
|
|
1537
|
-
this.emitter.emit(
|
|
1538
|
-
type:
|
|
1539
|
-
payload: {}
|
|
2271
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2272
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2273
|
+
payload: { operationId }
|
|
1540
2274
|
});
|
|
1541
2275
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1542
2276
|
_tag: ERROR_TAG.UserAborted,
|
|
1543
|
-
code:
|
|
2277
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1544
2278
|
cause: err
|
|
1545
2279
|
});
|
|
1546
2280
|
}
|
|
1547
2281
|
if (!payload?.confirmed) {
|
|
1548
2282
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1549
2283
|
_tag: ERROR_TAG.UserAborted,
|
|
1550
|
-
code:
|
|
2284
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1551
2285
|
});
|
|
1552
2286
|
}
|
|
1553
2287
|
await new Promise((resolve) => {
|
|
@@ -1561,7 +2295,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1561
2295
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1562
2296
|
* promoted), or `null` if the user declined.
|
|
1563
2297
|
*/
|
|
1564
|
-
async _gateBtcHighIndex(params) {
|
|
2298
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1565
2299
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1566
2300
|
if (params.showOnDevice) return params;
|
|
1567
2301
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1570,51 +2304,75 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1570
2304
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1571
2305
|
return { ...params, showOnDevice: true };
|
|
1572
2306
|
}
|
|
1573
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2307
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1574
2308
|
if (!confirmed) return null;
|
|
1575
2309
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1576
2310
|
return { ...params, showOnDevice: true };
|
|
1577
2311
|
}
|
|
1578
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2312
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2313
|
+
const operationId = this._activeOperationId();
|
|
1579
2314
|
const waitPromise = this._uiRegistry.wait(
|
|
1580
|
-
|
|
2315
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2316
|
+
{ operationId }
|
|
1581
2317
|
);
|
|
1582
|
-
this.emitter.emit(
|
|
1583
|
-
type:
|
|
2318
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
2319
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1584
2320
|
payload: {
|
|
1585
2321
|
vendor: "ledger",
|
|
1586
2322
|
path,
|
|
1587
|
-
accountIndex
|
|
2323
|
+
accountIndex,
|
|
2324
|
+
operationId
|
|
1588
2325
|
}
|
|
1589
2326
|
});
|
|
1590
2327
|
try {
|
|
1591
|
-
const payload = await
|
|
2328
|
+
const payload = await this._awaitUiAnswer(
|
|
2329
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2330
|
+
waitPromise,
|
|
2331
|
+
signal
|
|
2332
|
+
);
|
|
1592
2333
|
return !!payload?.confirmed;
|
|
1593
2334
|
} catch (err) {
|
|
1594
|
-
this.emitter.emit(
|
|
1595
|
-
type:
|
|
1596
|
-
payload: {}
|
|
2335
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2336
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2337
|
+
payload: { operationId }
|
|
1597
2338
|
});
|
|
1598
2339
|
return false;
|
|
1599
2340
|
}
|
|
1600
2341
|
}
|
|
2342
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2343
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2344
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2345
|
+
if (signal.aborted) onAbort();
|
|
2346
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2347
|
+
try {
|
|
2348
|
+
return await waitPromise;
|
|
2349
|
+
} finally {
|
|
2350
|
+
signal.removeEventListener("abort", onAbort);
|
|
2351
|
+
}
|
|
2352
|
+
}
|
|
1601
2353
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1602
2354
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1603
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2355
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2356
|
+
const operationId = this._activeOperationId();
|
|
1604
2357
|
const waitPromise = this._uiRegistry.wait(
|
|
1605
|
-
|
|
2358
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2359
|
+
{ operationId }
|
|
1606
2360
|
);
|
|
1607
|
-
this.emitter.emit(
|
|
1608
|
-
type:
|
|
1609
|
-
payload: { vendor: "ledger", appName }
|
|
2361
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
2362
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2363
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1610
2364
|
});
|
|
1611
2365
|
try {
|
|
1612
|
-
const payload = await
|
|
2366
|
+
const payload = await this._awaitUiAnswer(
|
|
2367
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2368
|
+
waitPromise,
|
|
2369
|
+
signal
|
|
2370
|
+
);
|
|
1613
2371
|
return !!payload?.confirmed;
|
|
1614
2372
|
} catch (err) {
|
|
1615
|
-
this.emitter.emit(
|
|
1616
|
-
type:
|
|
1617
|
-
payload: {}
|
|
2373
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2374
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2375
|
+
payload: { operationId }
|
|
1618
2376
|
});
|
|
1619
2377
|
return false;
|
|
1620
2378
|
}
|
|
@@ -1622,34 +2380,45 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1622
2380
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1623
2381
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1624
2382
|
// doesn't kill caller B's await.
|
|
1625
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2383
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1626
2384
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1627
|
-
|
|
2385
|
+
this._assertConnectorReady("connectDevice");
|
|
2386
|
+
if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1628
2387
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1629
|
-
code:
|
|
2388
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1630
2389
|
});
|
|
1631
2390
|
}
|
|
1632
2391
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1633
2392
|
if (!connectId && this._sessions.size > 0) {
|
|
1634
|
-
if (!
|
|
2393
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1635
2394
|
throw Object.assign(
|
|
1636
2395
|
new Error(
|
|
1637
2396
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
1638
2397
|
),
|
|
1639
|
-
{ code:
|
|
2398
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
|
|
1640
2399
|
);
|
|
1641
2400
|
}
|
|
1642
2401
|
return this._sessions.keys().next().value;
|
|
1643
2402
|
}
|
|
1644
|
-
if (!this._connectingPromise) {
|
|
1645
|
-
|
|
1646
|
-
|
|
2403
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2404
|
+
const controller = new AbortController();
|
|
2405
|
+
this._doConnectAbortController = controller;
|
|
2406
|
+
const innerSignal = controller.signal;
|
|
1647
2407
|
this._connectingPromise = (async () => {
|
|
1648
2408
|
try {
|
|
1649
|
-
return await this._doConnect(
|
|
2409
|
+
return await this._doConnect(
|
|
2410
|
+
innerSignal,
|
|
2411
|
+
connectId,
|
|
2412
|
+
allowUsbEphemeralFallback,
|
|
2413
|
+
preserveOperationId,
|
|
2414
|
+
context
|
|
2415
|
+
);
|
|
1650
2416
|
} finally {
|
|
1651
|
-
this.
|
|
1652
|
-
|
|
2417
|
+
if (this._doConnectAbortController === controller) {
|
|
2418
|
+
this._connectingPromise = null;
|
|
2419
|
+
this._doConnectAbortController = null;
|
|
2420
|
+
if (this._sessions.size === 0) this._activeConnectionType = void 0;
|
|
2421
|
+
}
|
|
1653
2422
|
}
|
|
1654
2423
|
})();
|
|
1655
2424
|
}
|
|
@@ -1658,45 +2427,83 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1658
2427
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1659
2428
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1660
2429
|
// throw DeviceNotFound so the user is kicked out of the loop.
|
|
1661
|
-
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false) {
|
|
1662
|
-
|
|
1663
|
-
|
|
1664
|
-
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
|
|
1669
|
-
|
|
1670
|
-
|
|
1671
|
-
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
1675
|
-
|
|
2430
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2431
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2432
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2433
|
+
this._activeConnectionType = "usb";
|
|
2434
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2435
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2436
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2437
|
+
(connection) => connection.transport === "usb"
|
|
2438
|
+
);
|
|
2439
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2440
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
|
|
2441
|
+
return this._connectFirstOrSelect(
|
|
2442
|
+
usbDevices,
|
|
2443
|
+
usbTarget,
|
|
2444
|
+
allowUsbEphemeralFallback,
|
|
2445
|
+
preserveOperationId,
|
|
2446
|
+
context,
|
|
2447
|
+
internalSignal
|
|
2448
|
+
);
|
|
1676
2449
|
}
|
|
2450
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2451
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2452
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2453
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2454
|
+
});
|
|
2455
|
+
}
|
|
2456
|
+
this._activeConnectionType = "ble";
|
|
2457
|
+
const knownBle = context?.knownConnections?.find(
|
|
2458
|
+
(connection) => connection.transport === "ble"
|
|
2459
|
+
);
|
|
2460
|
+
if (knownBle?.transport === "ble") {
|
|
2461
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2462
|
+
}
|
|
2463
|
+
const bleContext = context ?? {};
|
|
2464
|
+
bleContext.allowBleSelection = true;
|
|
2465
|
+
bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
|
|
2466
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2467
|
+
return this._connectFirstOrSelect(
|
|
2468
|
+
bleDevices,
|
|
2469
|
+
void 0,
|
|
2470
|
+
allowUsbEphemeralFallback,
|
|
2471
|
+
preserveOperationId,
|
|
2472
|
+
bleContext,
|
|
2473
|
+
internalSignal
|
|
2474
|
+
);
|
|
2475
|
+
}
|
|
2476
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2477
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1677
2478
|
}
|
|
1678
2479
|
let confirms = 0;
|
|
1679
2480
|
while (!internalSignal.aborted) {
|
|
1680
2481
|
this.emitter.emit("ui-event", {
|
|
1681
|
-
type:
|
|
2482
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
|
|
1682
2483
|
payload: { sessionId: "" }
|
|
1683
2484
|
});
|
|
1684
|
-
let devices = await this.
|
|
2485
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2486
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1685
2487
|
if (devices.length === 0) {
|
|
1686
2488
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1687
2489
|
await new Promise((resolve) => {
|
|
1688
|
-
setTimeout(resolve,
|
|
2490
|
+
setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1689
2491
|
});
|
|
1690
|
-
|
|
2492
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2493
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2494
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1691
2495
|
if (devices.length > 0) break;
|
|
1692
2496
|
}
|
|
1693
2497
|
}
|
|
1694
|
-
if (devices.length > 0) {
|
|
2498
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1695
2499
|
try {
|
|
1696
2500
|
return await this._connectFirstOrSelect(
|
|
1697
2501
|
devices,
|
|
1698
2502
|
targetConnectId,
|
|
1699
|
-
allowUsbEphemeralFallback
|
|
2503
|
+
allowUsbEphemeralFallback,
|
|
2504
|
+
preserveOperationId,
|
|
2505
|
+
context,
|
|
2506
|
+
internalSignal
|
|
1700
2507
|
);
|
|
1701
2508
|
} catch (err) {
|
|
1702
2509
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1716,7 +2523,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1716
2523
|
new Error(
|
|
1717
2524
|
"Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
|
|
1718
2525
|
),
|
|
1719
|
-
{ code:
|
|
2526
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
|
|
1720
2527
|
);
|
|
1721
2528
|
}
|
|
1722
2529
|
await this._waitForDeviceConnect(internalSignal);
|
|
@@ -1725,45 +2532,148 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1725
2532
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1726
2533
|
throw new Error("_doConnect aborted");
|
|
1727
2534
|
}
|
|
1728
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2535
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2536
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1729
2537
|
if (targetConnectId) {
|
|
1730
2538
|
const target = devices.find(
|
|
1731
2539
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1732
2540
|
);
|
|
1733
2541
|
if (target) {
|
|
1734
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2542
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1735
2543
|
}
|
|
1736
|
-
if (!
|
|
2544
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1737
2545
|
debugLog(
|
|
1738
2546
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1739
2547
|
);
|
|
1740
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2548
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1741
2549
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2550
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2551
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2552
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2553
|
+
});
|
|
2554
|
+
if (this._isBleConnection()) {
|
|
2555
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2556
|
+
}
|
|
2557
|
+
throw err;
|
|
1747
2558
|
}
|
|
1748
|
-
throw err;
|
|
1749
2559
|
}
|
|
1750
|
-
|
|
2560
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2561
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
|
|
1751
2562
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1752
|
-
code:
|
|
2563
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1753
2564
|
});
|
|
1754
2565
|
}
|
|
1755
|
-
if (
|
|
1756
|
-
|
|
2566
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2567
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2568
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2569
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2570
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2571
|
+
(connection) => connection.transport === "usb"
|
|
2572
|
+
);
|
|
2573
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
|
|
2574
|
+
const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
|
|
2575
|
+
const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
|
|
2576
|
+
emitter: this.emitter,
|
|
2577
|
+
registry: this._uiRegistry,
|
|
2578
|
+
signal,
|
|
2579
|
+
allowUsbFallback,
|
|
2580
|
+
scan: async () => {
|
|
2581
|
+
if (allowUsbFallback) {
|
|
2582
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2583
|
+
const candidate = usbDevices.find(
|
|
2584
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2585
|
+
) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2586
|
+
if (candidate) return [candidate];
|
|
2587
|
+
}
|
|
2588
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2589
|
+
},
|
|
2590
|
+
request: {
|
|
2591
|
+
devices,
|
|
2592
|
+
bindingSessionId,
|
|
2593
|
+
context: {
|
|
2594
|
+
kind: "bind-connection",
|
|
2595
|
+
transport: "ble",
|
|
2596
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2597
|
+
},
|
|
2598
|
+
extra: context?.extra,
|
|
2599
|
+
operationId: preserveOperationId
|
|
2600
|
+
}
|
|
2601
|
+
});
|
|
2602
|
+
if (device.connectionType === "usb") {
|
|
2603
|
+
this._activeConnectionType = "usb";
|
|
2604
|
+
if (context) context.selectedConnection = void 0;
|
|
2605
|
+
this._bindingSelectionRequestId = requestId;
|
|
2606
|
+
this._finishBleBinding("cancelled");
|
|
2607
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2608
|
+
}
|
|
2609
|
+
this._bindingSelectionRequestId = requestId;
|
|
2610
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2611
|
+
device.connectId,
|
|
2612
|
+
preserveOperationId,
|
|
2613
|
+
signal
|
|
2614
|
+
);
|
|
2615
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2616
|
+
if (context?.deferBindingSave) {
|
|
2617
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2618
|
+
} else {
|
|
2619
|
+
await this._saveSelectedBleBinding(
|
|
2620
|
+
connected,
|
|
2621
|
+
requestId,
|
|
2622
|
+
context,
|
|
2623
|
+
preserveOperationId,
|
|
2624
|
+
signal
|
|
2625
|
+
);
|
|
2626
|
+
}
|
|
2627
|
+
return connected;
|
|
2628
|
+
}
|
|
2629
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2630
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2631
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2632
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2633
|
+
message: "Select a Ledger device before continuing"
|
|
2634
|
+
});
|
|
2635
|
+
}
|
|
2636
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2637
|
+
const operationId = this._activeOperationId();
|
|
2638
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2639
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2640
|
+
{ requestId, operationId }
|
|
2641
|
+
);
|
|
2642
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2643
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2644
|
+
payload: {
|
|
2645
|
+
devices,
|
|
2646
|
+
requestId,
|
|
2647
|
+
operationId,
|
|
2648
|
+
context: requiresBleSelection ? {
|
|
2649
|
+
kind: "bind-connection",
|
|
2650
|
+
transport: "ble",
|
|
2651
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2652
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2653
|
+
extra: context?.extra
|
|
2654
|
+
}
|
|
2655
|
+
});
|
|
2656
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2657
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2658
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2659
|
+
if (!selected) {
|
|
2660
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2661
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2662
|
+
});
|
|
2663
|
+
}
|
|
2664
|
+
if (context && requiresBleSelection)
|
|
2665
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2666
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1757
2667
|
}
|
|
1758
2668
|
if (devices.length !== 1) {
|
|
1759
2669
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1760
|
-
code:
|
|
2670
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1761
2671
|
});
|
|
1762
2672
|
}
|
|
1763
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2673
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1764
2674
|
}
|
|
1765
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1766
|
-
const result = await this.
|
|
2675
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2676
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1767
2677
|
if (!result.success) {
|
|
1768
2678
|
const payload = result.payload;
|
|
1769
2679
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1774,16 +2684,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1774
2684
|
}
|
|
1775
2685
|
throw rethrow;
|
|
1776
2686
|
}
|
|
1777
|
-
return
|
|
2687
|
+
return result.payload;
|
|
1778
2688
|
}
|
|
1779
|
-
/**
|
|
1780
|
-
* Call the connector with automatic session resolution and disconnect retry.
|
|
1781
|
-
*
|
|
1782
|
-
* 1. Resolves a valid connectId via ensureConnected()
|
|
1783
|
-
* 2. Looks up sessionId from _sessions
|
|
1784
|
-
* 3. Calls connector.call()
|
|
1785
|
-
* 4. On disconnect error: clears stale session, re-connects, retries once
|
|
1786
|
-
*/
|
|
1787
2689
|
/**
|
|
1788
2690
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1789
2691
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1795,7 +2697,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1795
2697
|
*/
|
|
1796
2698
|
_unwrapConnectorResult(result) {
|
|
1797
2699
|
if (result.success) return result.payload;
|
|
1798
|
-
throw (0,
|
|
2700
|
+
throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
|
|
1799
2701
|
}
|
|
1800
2702
|
/**
|
|
1801
2703
|
* `connector.call` + result unwrap, optionally raced against an abort
|
|
@@ -1804,33 +2706,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1804
2706
|
* lives in one place.
|
|
1805
2707
|
*/
|
|
1806
2708
|
async _callConnector(sessionId, method, params, signal) {
|
|
1807
|
-
|
|
2709
|
+
this._assertConnectorReady(method);
|
|
2710
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2711
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2712
|
+
let promise;
|
|
2713
|
+
try {
|
|
2714
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2715
|
+
} catch (error) {
|
|
2716
|
+
releaseOperation();
|
|
2717
|
+
throw error;
|
|
2718
|
+
}
|
|
1808
2719
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1809
2720
|
return this._unwrapConnectorResult(result);
|
|
1810
2721
|
}
|
|
2722
|
+
_assertConnectorReady(method) {
|
|
2723
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2724
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2725
|
+
}
|
|
2726
|
+
}
|
|
2727
|
+
_runConnectorTeardown(task) {
|
|
2728
|
+
const previous = this._connectorTeardownTail;
|
|
2729
|
+
let releaseTail = () => void 0;
|
|
2730
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2731
|
+
releaseTail = resolve;
|
|
2732
|
+
});
|
|
2733
|
+
this._pendingConnectorTeardowns += 1;
|
|
2734
|
+
return (async () => {
|
|
2735
|
+
try {
|
|
2736
|
+
await previous;
|
|
2737
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2738
|
+
await task();
|
|
2739
|
+
} finally {
|
|
2740
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2741
|
+
releaseTail();
|
|
2742
|
+
}
|
|
2743
|
+
})();
|
|
2744
|
+
}
|
|
2745
|
+
_waitForConnectorOperationsToDrain() {
|
|
2746
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2747
|
+
return Promise.resolve();
|
|
2748
|
+
}
|
|
2749
|
+
return new Promise((resolve) => {
|
|
2750
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2751
|
+
});
|
|
2752
|
+
}
|
|
2753
|
+
_retainConnectorOperation(key) {
|
|
2754
|
+
this._unsettledConnectorOperations.set(
|
|
2755
|
+
key,
|
|
2756
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2757
|
+
);
|
|
2758
|
+
let released = false;
|
|
2759
|
+
return () => {
|
|
2760
|
+
if (released) return;
|
|
2761
|
+
released = true;
|
|
2762
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2763
|
+
if (remaining > 0) {
|
|
2764
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2765
|
+
} else {
|
|
2766
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2767
|
+
}
|
|
2768
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2769
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2770
|
+
this._connectorIdleWaiters.clear();
|
|
2771
|
+
}
|
|
2772
|
+
};
|
|
2773
|
+
}
|
|
1811
2774
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1812
|
-
|
|
1813
|
-
|
|
2775
|
+
const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
|
|
2776
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2777
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2778
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
|
|
2779
|
+
message: "Conflicting Ledger operation ids",
|
|
2780
|
+
params: {
|
|
2781
|
+
positionalOperationId,
|
|
2782
|
+
commonOperationId: commonParams.operationId
|
|
2783
|
+
}
|
|
2784
|
+
});
|
|
2785
|
+
}
|
|
2786
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2787
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2788
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2789
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2790
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2791
|
+
method,
|
|
2792
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2793
|
+
params: summarizeForLog(params, { method })
|
|
2794
|
+
});
|
|
2795
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1814
2796
|
try {
|
|
1815
2797
|
const result = await this._jobQueue.enqueue(
|
|
1816
2798
|
queueKey,
|
|
1817
|
-
async (signal) =>
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2799
|
+
async (signal) => {
|
|
2800
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2801
|
+
try {
|
|
2802
|
+
return await this._runConnectorCall(
|
|
2803
|
+
effectiveConnectId,
|
|
2804
|
+
method,
|
|
2805
|
+
params,
|
|
2806
|
+
signal,
|
|
2807
|
+
fingerprint,
|
|
2808
|
+
permissionDeviceId,
|
|
2809
|
+
commonParams,
|
|
2810
|
+
installContext ?? {},
|
|
2811
|
+
operationId
|
|
2812
|
+
);
|
|
2813
|
+
} catch (error) {
|
|
2814
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2815
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2816
|
+
let keptBundlePick = false;
|
|
2817
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2818
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2819
|
+
keptBundlePick = true;
|
|
2820
|
+
} else {
|
|
2821
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2822
|
+
this._discardPendingBinding(owner, status);
|
|
2823
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2824
|
+
}
|
|
2825
|
+
}
|
|
2826
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2827
|
+
throw error;
|
|
2828
|
+
} finally {
|
|
2829
|
+
if (operationId) {
|
|
2830
|
+
this._activeOperationJobs.delete(operationId);
|
|
2831
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2832
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2833
|
+
}
|
|
2834
|
+
}
|
|
2835
|
+
}
|
|
2836
|
+
},
|
|
1827
2837
|
{
|
|
1828
2838
|
label: method,
|
|
1829
2839
|
rejectIfBusy: true,
|
|
1830
2840
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1831
2841
|
}
|
|
1832
2842
|
);
|
|
1833
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2843
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2844
|
+
method,
|
|
2845
|
+
success: true,
|
|
2846
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2847
|
+
});
|
|
1834
2848
|
return result;
|
|
1835
2849
|
} catch (err) {
|
|
1836
2850
|
const e = err;
|
|
@@ -1844,15 +2858,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1844
2858
|
}
|
|
1845
2859
|
});
|
|
1846
2860
|
throw err;
|
|
2861
|
+
} finally {
|
|
2862
|
+
releaseOperationRetention?.();
|
|
1847
2863
|
}
|
|
1848
2864
|
}
|
|
2865
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2866
|
+
_abortReason(signal) {
|
|
2867
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2868
|
+
}
|
|
1849
2869
|
/**
|
|
1850
2870
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1851
2871
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1852
2872
|
*/
|
|
1853
2873
|
_abortable(signal, promise) {
|
|
1854
|
-
const getAbortReason = () =>
|
|
2874
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1855
2875
|
if (signal.aborted) {
|
|
2876
|
+
void promise.catch(() => void 0);
|
|
1856
2877
|
return Promise.reject(getAbortReason());
|
|
1857
2878
|
}
|
|
1858
2879
|
return new Promise((resolve, reject) => {
|
|
@@ -1879,39 +2900,89 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1879
2900
|
}
|
|
1880
2901
|
}
|
|
1881
2902
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1882
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2903
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1883
2904
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2905
|
+
if (!operationId) {
|
|
2906
|
+
await this._ensureDevicePermission(
|
|
2907
|
+
connectId,
|
|
2908
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2909
|
+
signal
|
|
2910
|
+
);
|
|
2911
|
+
}
|
|
1889
2912
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1890
2913
|
let effectiveParams = params;
|
|
1891
2914
|
if (method === "btcGetPublicKey") {
|
|
1892
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2915
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1893
2916
|
if (gatedParams === null) {
|
|
1894
2917
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1895
2918
|
_tag: ERROR_TAG.UserAborted,
|
|
1896
|
-
code:
|
|
2919
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1897
2920
|
});
|
|
1898
2921
|
}
|
|
1899
2922
|
effectiveParams = gatedParams;
|
|
1900
2923
|
}
|
|
1901
2924
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1902
|
-
|
|
1903
|
-
|
|
2925
|
+
let businessCallStarted = false;
|
|
2926
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2927
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2928
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2929
|
+
(connection) => connection.transport === knownTransport
|
|
2930
|
+
);
|
|
2931
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2932
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2933
|
+
const checksWallet = Boolean(
|
|
2934
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2935
|
+
);
|
|
2936
|
+
const connectionAttempt = {
|
|
2937
|
+
...commonParams,
|
|
2938
|
+
deferBindingSave: checksWallet
|
|
2939
|
+
};
|
|
2940
|
+
const bundleConnection = installContext?.connection;
|
|
2941
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2942
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2943
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2944
|
+
message: "Ledger all-network connection ended"
|
|
2945
|
+
});
|
|
2946
|
+
}
|
|
2947
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2948
|
+
preferredConnectId,
|
|
1904
2949
|
signal,
|
|
1905
|
-
allowUsbEphemeralFallback
|
|
2950
|
+
allowUsbEphemeralFallback,
|
|
2951
|
+
void 0,
|
|
2952
|
+
connectionAttempt
|
|
1906
2953
|
);
|
|
2954
|
+
const walletCheck = installContext?.walletCheck;
|
|
2955
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2956
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2957
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2958
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2959
|
+
});
|
|
2960
|
+
}
|
|
1907
2961
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2962
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2963
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2964
|
+
}
|
|
1908
2965
|
if (!sessionId) {
|
|
2966
|
+
if (operationId) {
|
|
2967
|
+
this._operations.end(operationId, "disconnect");
|
|
2968
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2969
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
2970
|
+
message: "Ledger operation connection is no longer active",
|
|
2971
|
+
params: { operationId, reason: "disconnect" }
|
|
2972
|
+
});
|
|
2973
|
+
}
|
|
1909
2974
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1910
2975
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1911
2976
|
});
|
|
1912
2977
|
}
|
|
1913
2978
|
try {
|
|
1914
|
-
|
|
2979
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2980
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2981
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2982
|
+
}
|
|
2983
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2984
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2985
|
+
if (fingerprint && checksWallet) {
|
|
1915
2986
|
const fp = await this._abortable(
|
|
1916
2987
|
signal,
|
|
1917
2988
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1921,14 +2992,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1921
2992
|
)
|
|
1922
2993
|
);
|
|
1923
2994
|
if (!fp.success) {
|
|
2995
|
+
if (pendingBinding) {
|
|
2996
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
2997
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
2998
|
+
}
|
|
2999
|
+
if (operationId) {
|
|
3000
|
+
this._pendingOperationBindings.delete(operationId);
|
|
3001
|
+
this._operations.end(operationId, "explicit");
|
|
3002
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
3003
|
+
}
|
|
1924
3004
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1925
|
-
code:
|
|
3005
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
|
|
1926
3006
|
});
|
|
1927
3007
|
}
|
|
3008
|
+
if (walletCheck) walletCheck.verified = true;
|
|
1928
3009
|
}
|
|
1929
|
-
|
|
3010
|
+
if (pendingBinding && bindingOwner) {
|
|
3011
|
+
bindingOwner.pendingBinding = void 0;
|
|
3012
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
3013
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
3014
|
+
await this._saveSelectedBleBinding(
|
|
3015
|
+
pendingBinding.connectId,
|
|
3016
|
+
pendingBinding.requestId,
|
|
3017
|
+
bindingOwner,
|
|
3018
|
+
operationId,
|
|
3019
|
+
signal,
|
|
3020
|
+
fingerprint && checksWallet ? {
|
|
3021
|
+
vendor: "ledger",
|
|
3022
|
+
type: "chainFingerprint",
|
|
3023
|
+
chain: fingerprint.chain,
|
|
3024
|
+
value: fingerprint.deviceId
|
|
3025
|
+
} : void 0
|
|
3026
|
+
);
|
|
3027
|
+
}
|
|
3028
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
3029
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
3030
|
+
connectId: resolvedConnectId,
|
|
3031
|
+
chain: fingerprint.chain,
|
|
3032
|
+
fingerprint: fingerprint.deviceId
|
|
3033
|
+
});
|
|
3034
|
+
}
|
|
3035
|
+
businessCallStarted = true;
|
|
3036
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3037
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3038
|
+
return result;
|
|
1930
3039
|
} catch (err) {
|
|
1931
3040
|
if (signal.aborted) throw err;
|
|
3041
|
+
if (isLostConnectionError(err)) {
|
|
3042
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3043
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3044
|
+
else {
|
|
3045
|
+
this._sessions.delete(resolvedConnectId);
|
|
3046
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3047
|
+
}
|
|
3048
|
+
const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3049
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
3050
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3051
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
|
|
3052
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
3053
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
|
|
3054
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3055
|
+
});
|
|
3056
|
+
}
|
|
1932
3057
|
const errObj = err;
|
|
1933
3058
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1934
3059
|
message: errObj?.message,
|
|
@@ -1940,8 +3065,66 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1940
3065
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1941
3066
|
isStuckApp: isStuckAppStateError(err)
|
|
1942
3067
|
});
|
|
3068
|
+
const assertSessionCurrent = (message) => {
|
|
3069
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3070
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3071
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
3072
|
+
message
|
|
3073
|
+
});
|
|
3074
|
+
};
|
|
3075
|
+
if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3076
|
+
await this._waitForDeviceConnect(signal);
|
|
3077
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3078
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3079
|
+
return this._runConnectorCall(
|
|
3080
|
+
resolvedConnectId,
|
|
3081
|
+
method,
|
|
3082
|
+
effectiveParams,
|
|
3083
|
+
signal,
|
|
3084
|
+
fingerprint,
|
|
3085
|
+
permissionDeviceId,
|
|
3086
|
+
commonParams,
|
|
3087
|
+
installContext,
|
|
3088
|
+
operationId,
|
|
3089
|
+
lockedRetryBudget - 1
|
|
3090
|
+
);
|
|
3091
|
+
}
|
|
3092
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3093
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3094
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3095
|
+
try {
|
|
3096
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3097
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3098
|
+
return retried;
|
|
3099
|
+
} catch (retryErr) {
|
|
3100
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3101
|
+
if (isLostConnectionError(retryErr)) {
|
|
3102
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3103
|
+
else {
|
|
3104
|
+
this._sessions.delete(resolvedConnectId);
|
|
3105
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3106
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3107
|
+
}
|
|
3108
|
+
const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3109
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3110
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
|
|
3111
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3112
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3113
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3114
|
+
});
|
|
3115
|
+
}
|
|
3116
|
+
throw retryErr;
|
|
3117
|
+
}
|
|
3118
|
+
}
|
|
3119
|
+
if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
|
|
3120
|
+
this._sessions.delete(resolvedConnectId);
|
|
3121
|
+
this._sessionTransports.delete(sessionId);
|
|
3122
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3123
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3124
|
+
throw err;
|
|
3125
|
+
}
|
|
1943
3126
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1944
|
-
const isAppMissing = isAppNotInstalledError(err) || err?.code ===
|
|
3127
|
+
const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
1945
3128
|
if (autoInstallApp && isAppMissing) {
|
|
1946
3129
|
if (installContext?.deviceOutOfMemoryError) {
|
|
1947
3130
|
throw installContext.deviceOutOfMemoryError;
|
|
@@ -1949,30 +3132,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1949
3132
|
const appName = err?.appName ?? mapLedgerError(err).appName;
|
|
1950
3133
|
if (appName) {
|
|
1951
3134
|
if (installContext?.installAttemptedAppNames?.has(appName)) {
|
|
1952
|
-
throw (0,
|
|
1953
|
-
code:
|
|
3135
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3136
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
|
|
1954
3137
|
message: `${appName} install reported success but the app is still missing on device`,
|
|
1955
3138
|
_tag: ERROR_TAG.AppInstallVerifyFailed,
|
|
1956
3139
|
appName
|
|
1957
3140
|
});
|
|
1958
3141
|
}
|
|
1959
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3142
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1960
3143
|
if (!confirmed) {
|
|
1961
|
-
throw (0,
|
|
1962
|
-
code:
|
|
3144
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3145
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1963
3146
|
message: `User declined to install ${appName}`,
|
|
1964
3147
|
_tag: ERROR_TAG.UserAborted,
|
|
1965
3148
|
appName
|
|
1966
3149
|
});
|
|
1967
3150
|
}
|
|
1968
3151
|
this.emitter.emit("ui-event", {
|
|
1969
|
-
type:
|
|
3152
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1970
3153
|
payload: { connectId: resolvedConnectId, appName, progress: 0 }
|
|
1971
3154
|
});
|
|
1972
3155
|
try {
|
|
1973
3156
|
await this._callConnector(sessionId, "installApp", { appName }, signal);
|
|
1974
3157
|
} catch (installErr) {
|
|
1975
|
-
if (mapLedgerError(installErr).code ===
|
|
3158
|
+
if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
|
|
1976
3159
|
if (installContext) {
|
|
1977
3160
|
installContext.deviceOutOfMemoryError = installErr;
|
|
1978
3161
|
}
|
|
@@ -1983,9 +3166,9 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1983
3166
|
installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
|
|
1984
3167
|
installContext.installAttemptedAppNames.add(appName);
|
|
1985
3168
|
}
|
|
1986
|
-
this.emitter.emit(
|
|
1987
|
-
type:
|
|
1988
|
-
payload: {}
|
|
3169
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3170
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
3171
|
+
payload: { operationId }
|
|
1989
3172
|
});
|
|
1990
3173
|
return await this._runConnectorCall(
|
|
1991
3174
|
resolvedConnectId,
|
|
@@ -1995,157 +3178,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1995
3178
|
fingerprint,
|
|
1996
3179
|
permissionDeviceId,
|
|
1997
3180
|
commonParams,
|
|
1998
|
-
installContext
|
|
3181
|
+
installContext,
|
|
3182
|
+
operationId
|
|
1999
3183
|
);
|
|
2000
3184
|
}
|
|
2001
3185
|
}
|
|
2002
|
-
if (isStuckAppStateError(err)) {
|
|
2003
|
-
try {
|
|
2004
|
-
this._sessions.delete(resolvedConnectId);
|
|
2005
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2006
|
-
this.connector.reset?.();
|
|
2007
|
-
} catch {
|
|
2008
|
-
}
|
|
2009
|
-
debugLog(
|
|
2010
|
-
"[LedgerAdapter] stuck-app retry: method=",
|
|
2011
|
-
method,
|
|
2012
|
-
"delayMs=",
|
|
2013
|
-
_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
|
|
2014
|
-
"_tag=",
|
|
2015
|
-
err?._tag
|
|
2016
|
-
);
|
|
2017
|
-
try {
|
|
2018
|
-
const retryResult = await this._retryAfterStuckApp(
|
|
2019
|
-
resolvedConnectId,
|
|
2020
|
-
method,
|
|
2021
|
-
effectiveParams,
|
|
2022
|
-
signal,
|
|
2023
|
-
err,
|
|
2024
|
-
fingerprint
|
|
2025
|
-
);
|
|
2026
|
-
debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
|
|
2027
|
-
return retryResult;
|
|
2028
|
-
} catch (retryErr) {
|
|
2029
|
-
if (signal.aborted) throw retryErr;
|
|
2030
|
-
if (isStuckAppStateError(retryErr)) {
|
|
2031
|
-
debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
|
|
2032
|
-
throw err;
|
|
2033
|
-
}
|
|
2034
|
-
debugLog(
|
|
2035
|
-
"[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
|
|
2036
|
-
method,
|
|
2037
|
-
"retryErrTag=",
|
|
2038
|
-
retryErr?._tag
|
|
2039
|
-
);
|
|
2040
|
-
throw retryErr;
|
|
2041
|
-
}
|
|
2042
|
-
}
|
|
2043
|
-
if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
|
|
2044
|
-
let lastErr = err;
|
|
2045
|
-
for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
|
|
2046
|
-
if (signal.aborted) throw lastErr;
|
|
2047
|
-
try {
|
|
2048
|
-
this._sessions.delete(resolvedConnectId);
|
|
2049
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2050
|
-
if (isDeviceDisconnectedError(lastErr)) {
|
|
2051
|
-
try {
|
|
2052
|
-
this.connector.reset?.();
|
|
2053
|
-
} catch {
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
const reConnectId = await this.ensureConnected(
|
|
2057
|
-
resolvedConnectId,
|
|
2058
|
-
signal,
|
|
2059
|
-
allowUsbEphemeralFallback
|
|
2060
|
-
);
|
|
2061
|
-
const reSessionId = this._sessions.get(reConnectId);
|
|
2062
|
-
if (!reSessionId) throw lastErr;
|
|
2063
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2064
|
-
const fp = await this._abortable(
|
|
2065
|
-
signal,
|
|
2066
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2067
|
-
reSessionId,
|
|
2068
|
-
fingerprint.deviceId,
|
|
2069
|
-
fingerprint.chain
|
|
2070
|
-
)
|
|
2071
|
-
);
|
|
2072
|
-
if (!fp.success) {
|
|
2073
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2074
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2075
|
-
});
|
|
2076
|
-
}
|
|
2077
|
-
}
|
|
2078
|
-
return await this._callConnector(reSessionId, method, effectiveParams, signal);
|
|
2079
|
-
} catch (retryErr) {
|
|
2080
|
-
if (signal.aborted) throw retryErr;
|
|
2081
|
-
lastErr = retryErr;
|
|
2082
|
-
const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
|
|
2083
|
-
if (!canRetry) {
|
|
2084
|
-
throw retryErr;
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
throw lastErr;
|
|
2089
|
-
}
|
|
2090
|
-
if (isTimeoutError(err)) {
|
|
2091
|
-
debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
|
|
2092
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2093
|
-
return this._retryWithFreshConnection(
|
|
2094
|
-
resolvedConnectId,
|
|
2095
|
-
method,
|
|
2096
|
-
effectiveParams,
|
|
2097
|
-
signal,
|
|
2098
|
-
err,
|
|
2099
|
-
fingerprint
|
|
2100
|
-
);
|
|
2101
|
-
}
|
|
2102
|
-
if (isConnectionLevelError(err)) {
|
|
2103
|
-
debugLog("[LedgerAdapter] connection-level fail-closed reset");
|
|
2104
|
-
this._sessions.delete(resolvedConnectId);
|
|
2105
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2106
|
-
this.connector.reset();
|
|
2107
|
-
const codeNum = err?.code;
|
|
2108
|
-
throw Object.assign(err, {
|
|
2109
|
-
code: codeNum ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected
|
|
2110
|
-
});
|
|
2111
|
-
}
|
|
2112
3186
|
throw err;
|
|
2113
3187
|
}
|
|
2114
3188
|
}
|
|
2115
|
-
/**
|
|
2116
|
-
* Stuck-app recovery: pause for the device's UI transition, then retry once.
|
|
2117
|
-
*
|
|
2118
|
-
* Caller has already cleared the session + reset connector. We wait so Stax
|
|
2119
|
-
* finishes its post-CloseApp animation, then go through ensureConnected +
|
|
2120
|
-
* fingerprint check + call exactly once. Caller decides what to do on a
|
|
2121
|
-
* second stuck-app hit.
|
|
2122
|
-
*/
|
|
2123
|
-
async _retryAfterStuckApp(resolvedConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2124
|
-
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
2125
|
-
const retryConnectId = await this.ensureConnected(
|
|
2126
|
-
resolvedConnectId,
|
|
2127
|
-
signal,
|
|
2128
|
-
!!fingerprint?.deviceId && !fingerprint.skipFingerprint
|
|
2129
|
-
);
|
|
2130
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2131
|
-
if (!retrySessionId) throw originalErr;
|
|
2132
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2133
|
-
const fp = await this._abortable(
|
|
2134
|
-
signal,
|
|
2135
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2136
|
-
retrySessionId,
|
|
2137
|
-
fingerprint.deviceId,
|
|
2138
|
-
fingerprint.chain
|
|
2139
|
-
)
|
|
2140
|
-
);
|
|
2141
|
-
if (!fp.success) {
|
|
2142
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2143
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2144
|
-
});
|
|
2145
|
-
}
|
|
2146
|
-
}
|
|
2147
|
-
return this._callConnector(retrySessionId, method, params, signal);
|
|
2148
|
-
}
|
|
2149
3189
|
_sleepAbortable(ms, signal) {
|
|
2150
3190
|
return new Promise((resolve, reject) => {
|
|
2151
3191
|
if (signal.aborted) {
|
|
@@ -2164,115 +3204,26 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2164
3204
|
});
|
|
2165
3205
|
}
|
|
2166
3206
|
/**
|
|
2167
|
-
*
|
|
2168
|
-
*
|
|
2169
|
-
* Timeout recovery starts with a full connector reset. After an APDU
|
|
2170
|
-
* timeout, DMK/transport state may still emit malformed responses; retrying
|
|
2171
|
-
* on the same DMK can poison the next chain switch.
|
|
2172
|
-
*/
|
|
2173
|
-
async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2174
|
-
this.connector.reset();
|
|
2175
|
-
this._sessions.clear();
|
|
2176
|
-
this._discoveredDevices.clear();
|
|
2177
|
-
this._connectingPromise = null;
|
|
2178
|
-
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
2179
|
-
const retryConnectId = await this.ensureConnected(
|
|
2180
|
-
targetConnectId,
|
|
2181
|
-
signal,
|
|
2182
|
-
allowUsbEphemeralFallback
|
|
2183
|
-
);
|
|
2184
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2185
|
-
if (!retrySessionId) {
|
|
2186
|
-
throw originalErr;
|
|
2187
|
-
}
|
|
2188
|
-
try {
|
|
2189
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2190
|
-
const fp = await this._abortable(
|
|
2191
|
-
signal,
|
|
2192
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2193
|
-
retrySessionId,
|
|
2194
|
-
fingerprint.deviceId,
|
|
2195
|
-
fingerprint.chain
|
|
2196
|
-
)
|
|
2197
|
-
);
|
|
2198
|
-
if (!fp.success) {
|
|
2199
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2200
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2201
|
-
});
|
|
2202
|
-
}
|
|
2203
|
-
}
|
|
2204
|
-
return await this._callConnector(retrySessionId, method, params, signal);
|
|
2205
|
-
} catch (retryErr) {
|
|
2206
|
-
if (signal.aborted) throw retryErr;
|
|
2207
|
-
this.connector.reset();
|
|
2208
|
-
this._sessions.clear();
|
|
2209
|
-
this._discoveredDevices.clear();
|
|
2210
|
-
this._connectingPromise = null;
|
|
2211
|
-
if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
|
|
2212
|
-
throw retryErr;
|
|
2213
|
-
}
|
|
2214
|
-
debugLog(
|
|
2215
|
-
"[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
|
|
2216
|
-
);
|
|
2217
|
-
this.connector.reset();
|
|
2218
|
-
this._sessions.clear();
|
|
2219
|
-
this._discoveredDevices.clear();
|
|
2220
|
-
this._connectingPromise = null;
|
|
2221
|
-
const finalConnectId = await this.ensureConnected(
|
|
2222
|
-
targetConnectId,
|
|
2223
|
-
signal,
|
|
2224
|
-
allowUsbEphemeralFallback
|
|
2225
|
-
);
|
|
2226
|
-
const finalSessionId = this._sessions.get(finalConnectId);
|
|
2227
|
-
if (!finalSessionId) {
|
|
2228
|
-
throw originalErr;
|
|
2229
|
-
}
|
|
2230
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2231
|
-
const fp = await this._abortable(
|
|
2232
|
-
signal,
|
|
2233
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2234
|
-
finalSessionId,
|
|
2235
|
-
fingerprint.deviceId,
|
|
2236
|
-
fingerprint.chain
|
|
2237
|
-
)
|
|
2238
|
-
);
|
|
2239
|
-
if (!fp.success) {
|
|
2240
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2241
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2242
|
-
});
|
|
2243
|
-
}
|
|
2244
|
-
}
|
|
2245
|
-
return this._callConnector(finalSessionId, method, params, signal);
|
|
2246
|
-
}
|
|
2247
|
-
}
|
|
2248
|
-
/**
|
|
2249
|
-
* Ensure OS-level device permission (Bluetooth / USB) before proceeding.
|
|
2250
|
-
*
|
|
2251
|
-
* Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
|
|
2252
|
-
* `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
|
|
2253
|
-
* prompt → user tap" plus a generous margin). If the consumer never wires
|
|
2254
|
-
* a handler or never replies, the wait times out and the operation fails
|
|
2255
|
-
* fast so scanners/callers don't hang silently.
|
|
2256
|
-
*
|
|
2257
|
-
* - No connectId (searchDevices): environment-level permission
|
|
2258
|
-
* - With connectId (business methods): device-level permission
|
|
3207
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3208
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2259
3209
|
*/
|
|
2260
3210
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2261
3211
|
if (signal?.aborted) {
|
|
2262
3212
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2263
3213
|
}
|
|
2264
3214
|
const transportType = this.activeTransport ?? "hid";
|
|
3215
|
+
const operationId = this._activeOperationId();
|
|
2265
3216
|
const waitPromise = this._uiRegistry.wait(
|
|
2266
|
-
|
|
2267
|
-
{ timeoutMs: 6e4 }
|
|
3217
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3218
|
+
{ timeoutMs: 6e4, operationId }
|
|
2268
3219
|
);
|
|
2269
|
-
this.emitter.emit(
|
|
2270
|
-
type:
|
|
2271
|
-
payload: { transportType, connectId, deviceId }
|
|
3220
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
3221
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3222
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2272
3223
|
});
|
|
2273
3224
|
let response;
|
|
2274
3225
|
const onAbort = () => {
|
|
2275
|
-
this._uiRegistry.cancel(
|
|
3226
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
|
|
2276
3227
|
};
|
|
2277
3228
|
try {
|
|
2278
3229
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -2281,14 +3232,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2281
3232
|
if (signal?.aborted) {
|
|
2282
3233
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2283
3234
|
}
|
|
2284
|
-
if (err?._tag ===
|
|
2285
|
-
this.emitter.emit(
|
|
2286
|
-
type:
|
|
2287
|
-
payload: {}
|
|
3235
|
+
if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
|
|
3236
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3237
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
3238
|
+
payload: { operationId }
|
|
2288
3239
|
});
|
|
2289
3240
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2290
3241
|
_tag: ERROR_TAG.UserAborted,
|
|
2291
|
-
code:
|
|
3242
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
2292
3243
|
cause: err
|
|
2293
3244
|
});
|
|
2294
3245
|
}
|
|
@@ -2299,7 +3250,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2299
3250
|
const { granted, reason, message } = response;
|
|
2300
3251
|
if (!granted) {
|
|
2301
3252
|
throw Object.assign(new Error(message ?? "Device permission denied"), {
|
|
2302
|
-
code:
|
|
3253
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
|
|
2303
3254
|
reason
|
|
2304
3255
|
});
|
|
2305
3256
|
}
|
|
@@ -2313,8 +3264,16 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2313
3264
|
const tag = err && typeof err === "object" ? err._tag : void 0;
|
|
2314
3265
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2315
3266
|
const e = err;
|
|
2316
|
-
const params = e.code ===
|
|
2317
|
-
return ledgerFailure(
|
|
3267
|
+
const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
3268
|
+
return ledgerFailure(
|
|
3269
|
+
e.code,
|
|
3270
|
+
e.message ?? "Unknown error",
|
|
3271
|
+
e.appName,
|
|
3272
|
+
tag,
|
|
3273
|
+
params,
|
|
3274
|
+
void 0,
|
|
3275
|
+
(0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
|
|
3276
|
+
);
|
|
2318
3277
|
}
|
|
2319
3278
|
const mapped = mapLedgerError(err);
|
|
2320
3279
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2341,7 +3300,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2341
3300
|
deviceId: device.deviceId,
|
|
2342
3301
|
connectId: device.connectId,
|
|
2343
3302
|
label: device.name,
|
|
2344
|
-
connectionType: this.connector.connectionType,
|
|
3303
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2345
3304
|
rssi: device.rssi,
|
|
2346
3305
|
isConnectable: device.isConnectable,
|
|
2347
3306
|
serialNumber: device.serialNumber,
|
|
@@ -2639,16 +3598,20 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
|
|
|
2639
3598
|
var import_context_module = require("@ledgerhq/context-module");
|
|
2640
3599
|
|
|
2641
3600
|
// src/signer/SignerEth.ts
|
|
2642
|
-
var
|
|
3601
|
+
var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
|
|
2643
3602
|
|
|
2644
3603
|
// src/signer/deviceActionToPromise.ts
|
|
2645
3604
|
var import_device_management_kit = require("@ledgerhq/device-management-kit");
|
|
2646
3605
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3606
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
3607
|
+
var INTERACTION_PROMPT_DELAY_MS = 500;
|
|
2647
3608
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2648
3609
|
return new Promise((resolve, reject) => {
|
|
2649
3610
|
let settled = false;
|
|
2650
3611
|
let lastStep;
|
|
2651
3612
|
let activeInteraction;
|
|
3613
|
+
let pendingInteraction;
|
|
3614
|
+
let pendingInteractionTimer = null;
|
|
2652
3615
|
const observedSteps = [];
|
|
2653
3616
|
let sub;
|
|
2654
3617
|
let timer = null;
|
|
@@ -2676,31 +3639,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
|
|
|
2676
3639
|
}
|
|
2677
3640
|
return false;
|
|
2678
3641
|
};
|
|
3642
|
+
const cancelPendingInteraction = () => {
|
|
3643
|
+
if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
|
|
3644
|
+
pendingInteractionTimer = null;
|
|
3645
|
+
pendingInteraction = void 0;
|
|
3646
|
+
};
|
|
3647
|
+
const showInteraction = (interactionName) => {
|
|
3648
|
+
activeInteraction = interactionName;
|
|
3649
|
+
debugLog(
|
|
3650
|
+
"[DeviceAction] requiredUserInteraction",
|
|
3651
|
+
`interaction=${interactionName}`,
|
|
3652
|
+
`step=${lastStep ?? "unknown"}`
|
|
3653
|
+
);
|
|
3654
|
+
if (interactionName === "unlock-device" && timer) {
|
|
3655
|
+
clearTimeout(timer);
|
|
3656
|
+
timer = null;
|
|
3657
|
+
}
|
|
3658
|
+
onInteraction?.(interactionName);
|
|
3659
|
+
};
|
|
2679
3660
|
const emitInteraction = (interaction) => {
|
|
2680
3661
|
if (!onInteraction) {
|
|
2681
3662
|
return;
|
|
2682
3663
|
}
|
|
2683
3664
|
if (!interaction || interaction === "none") {
|
|
3665
|
+
cancelPendingInteraction();
|
|
2684
3666
|
clearActiveInteraction();
|
|
2685
3667
|
return;
|
|
2686
3668
|
}
|
|
2687
3669
|
const interactionName = String(interaction);
|
|
2688
|
-
if (interactionName === activeInteraction) {
|
|
3670
|
+
if (interactionName === activeInteraction || interactionName === pendingInteraction) {
|
|
2689
3671
|
return;
|
|
2690
3672
|
}
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
);
|
|
2697
|
-
if (interaction === "unlock-device" && timer) {
|
|
2698
|
-
clearTimeout(timer);
|
|
2699
|
-
timer = null;
|
|
3673
|
+
cancelPendingInteraction();
|
|
3674
|
+
clearActiveInteraction();
|
|
3675
|
+
if (interactionName === "unlock-device") {
|
|
3676
|
+
showInteraction(interactionName);
|
|
3677
|
+
return;
|
|
2700
3678
|
}
|
|
2701
|
-
|
|
3679
|
+
pendingInteraction = interactionName;
|
|
3680
|
+
pendingInteractionTimer = setTimeout(() => {
|
|
3681
|
+
pendingInteractionTimer = null;
|
|
3682
|
+
pendingInteraction = void 0;
|
|
3683
|
+
if (!settled) showInteraction(interactionName);
|
|
3684
|
+
}, INTERACTION_PROMPT_DELAY_MS);
|
|
2702
3685
|
};
|
|
2703
3686
|
const completeInteraction = () => {
|
|
3687
|
+
cancelPendingInteraction();
|
|
2704
3688
|
if (!clearActiveInteraction()) {
|
|
2705
3689
|
onInteraction?.("interaction-complete");
|
|
2706
3690
|
}
|
|
@@ -2831,7 +3815,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2831
3815
|
}
|
|
2832
3816
|
|
|
2833
3817
|
// src/signer/SignerEth.ts
|
|
2834
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2835
3818
|
var SignerEth = class {
|
|
2836
3819
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2837
3820
|
constructor(_sdk) {
|
|
@@ -2852,7 +3835,7 @@ var SignerEth = class {
|
|
|
2852
3835
|
);
|
|
2853
3836
|
}
|
|
2854
3837
|
async signTransaction(derivationPath, serializedTxHex) {
|
|
2855
|
-
const action = this._sdk.signTransaction(derivationPath, (0,
|
|
3838
|
+
const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
|
|
2856
3839
|
return deviceActionToPromise(
|
|
2857
3840
|
action,
|
|
2858
3841
|
this.onInteraction,
|
|
@@ -2861,7 +3844,7 @@ var SignerEth = class {
|
|
|
2861
3844
|
);
|
|
2862
3845
|
}
|
|
2863
3846
|
async signMessage(derivationPath, message) {
|
|
2864
|
-
const action = this._sdk.signMessage(derivationPath, (0,
|
|
3847
|
+
const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
|
|
2865
3848
|
return deviceActionToPromise(
|
|
2866
3849
|
action,
|
|
2867
3850
|
this.onInteraction,
|
|
@@ -2902,7 +3885,7 @@ var SignerManager = class _SignerManager {
|
|
|
2902
3885
|
return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
|
|
2903
3886
|
}
|
|
2904
3887
|
static _createContextModule() {
|
|
2905
|
-
const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3888
|
+
const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2906
3889
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2907
3890
|
}
|
|
2908
3891
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2921,23 +3904,44 @@ var SignerManager = class _SignerManager {
|
|
|
2921
3904
|
};
|
|
2922
3905
|
|
|
2923
3906
|
// src/connector/chains/evm.ts
|
|
2924
|
-
var
|
|
3907
|
+
var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
|
|
2925
3908
|
|
|
2926
3909
|
// src/connector/chains/utils.ts
|
|
2927
|
-
var
|
|
3910
|
+
var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
|
|
2928
3911
|
function normalizePath(path) {
|
|
2929
3912
|
return path.startsWith("m/") ? path.slice(2) : path;
|
|
2930
3913
|
}
|
|
2931
3914
|
function collapseSignerInteraction(interaction) {
|
|
2932
3915
|
switch (interaction) {
|
|
2933
3916
|
case "confirm-open-app":
|
|
2934
|
-
return
|
|
3917
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
|
|
2935
3918
|
case "unlock-device":
|
|
2936
|
-
return
|
|
3919
|
+
return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
|
|
2937
3920
|
case "interaction-complete":
|
|
2938
|
-
return
|
|
3921
|
+
return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
|
|
2939
3922
|
default:
|
|
2940
|
-
return
|
|
3923
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
|
|
3924
|
+
}
|
|
3925
|
+
}
|
|
3926
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3927
|
+
signer.onInteraction = (interaction) => {
|
|
3928
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3929
|
+
ctx.emit("ui-event", {
|
|
3930
|
+
type: collapseSignerInteraction(interaction),
|
|
3931
|
+
payload: { sessionId }
|
|
3932
|
+
});
|
|
3933
|
+
};
|
|
3934
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3935
|
+
return signer;
|
|
3936
|
+
}
|
|
3937
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3938
|
+
try {
|
|
3939
|
+
return await call();
|
|
3940
|
+
} catch (err) {
|
|
3941
|
+
ctx.invalidateSession(sessionId);
|
|
3942
|
+
throw ctx.wrapError(err);
|
|
3943
|
+
} finally {
|
|
3944
|
+
ctx.clearCanceller(sessionId);
|
|
2941
3945
|
}
|
|
2942
3946
|
}
|
|
2943
3947
|
|
|
@@ -2963,7 +3967,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2963
3967
|
new Error(
|
|
2964
3968
|
"Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
|
|
2965
3969
|
),
|
|
2966
|
-
{ code:
|
|
3970
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
|
|
2967
3971
|
);
|
|
2968
3972
|
}
|
|
2969
3973
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
@@ -2972,8 +3976,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2972
3976
|
const result = await signer.signTransaction(path, params.serializedTx);
|
|
2973
3977
|
return {
|
|
2974
3978
|
v: `0x${result.v.toString(16)}`,
|
|
2975
|
-
r: (0,
|
|
2976
|
-
s: (0,
|
|
3979
|
+
r: (0, import_hwk_adapter_core7.padHex64)(result.r),
|
|
3980
|
+
s: (0, import_hwk_adapter_core7.padHex64)(result.s)
|
|
2977
3981
|
};
|
|
2978
3982
|
} catch (err) {
|
|
2979
3983
|
ctx.invalidateSession(sessionId);
|
|
@@ -2987,8 +3991,8 @@ async function evmSignMessage(ctx, sessionId, params) {
|
|
|
2987
3991
|
const path = normalizePath(params.path);
|
|
2988
3992
|
try {
|
|
2989
3993
|
const result = await signer.signMessage(path, params.message);
|
|
2990
|
-
const rHex = (0,
|
|
2991
|
-
const sHex = (0,
|
|
3994
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3995
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
2992
3996
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
2993
3997
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
2994
3998
|
} catch (err) {
|
|
@@ -3004,15 +4008,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
|
|
|
3004
4008
|
new Error(
|
|
3005
4009
|
'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
|
|
3006
4010
|
),
|
|
3007
|
-
{ code:
|
|
4011
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
|
|
3008
4012
|
);
|
|
3009
4013
|
}
|
|
3010
4014
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
3011
4015
|
const path = normalizePath(params.path);
|
|
3012
4016
|
try {
|
|
3013
4017
|
const result = await signer.signTypedData(path, params.data);
|
|
3014
|
-
const rHex = (0,
|
|
3015
|
-
const sHex = (0,
|
|
4018
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
4019
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
3016
4020
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3017
4021
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
3018
4022
|
} catch (err) {
|
|
@@ -3039,15 +4043,14 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3039
4043
|
}
|
|
3040
4044
|
|
|
3041
4045
|
// src/connector/chains/btc.ts
|
|
3042
|
-
var
|
|
3043
|
-
var
|
|
4046
|
+
var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
|
|
4047
|
+
var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
|
|
3044
4048
|
|
|
3045
4049
|
// src/signer/SignerBtc.ts
|
|
3046
|
-
var
|
|
4050
|
+
var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
|
|
3047
4051
|
function hexToUtf8(hex) {
|
|
3048
|
-
return new TextDecoder().decode((0,
|
|
4052
|
+
return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
|
|
3049
4053
|
}
|
|
3050
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3051
4054
|
var SignerBtc = class {
|
|
3052
4055
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3053
4056
|
constructor(_sdk) {
|
|
@@ -3061,7 +4064,7 @@ var SignerBtc = class {
|
|
|
3061
4064
|
return deviceActionToPromise(
|
|
3062
4065
|
action,
|
|
3063
4066
|
this.onInteraction,
|
|
3064
|
-
void 0,
|
|
4067
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3065
4068
|
this.onRegisterCanceller
|
|
3066
4069
|
);
|
|
3067
4070
|
}
|
|
@@ -3079,14 +4082,14 @@ var SignerBtc = class {
|
|
|
3079
4082
|
const result = await deviceActionToPromise(
|
|
3080
4083
|
action,
|
|
3081
4084
|
this.onInteraction,
|
|
3082
|
-
void 0,
|
|
4085
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3083
4086
|
this.onRegisterCanceller
|
|
3084
4087
|
);
|
|
3085
4088
|
debugLog(
|
|
3086
4089
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3087
4090
|
typeof result,
|
|
3088
4091
|
"value:",
|
|
3089
|
-
|
|
4092
|
+
summarizeForLog(result)
|
|
3090
4093
|
);
|
|
3091
4094
|
if (typeof result === "string") return result;
|
|
3092
4095
|
return result.extendedPublicKey;
|
|
@@ -3115,7 +4118,7 @@ var SignerBtc = class {
|
|
|
3115
4118
|
return deviceActionToPromise(
|
|
3116
4119
|
action,
|
|
3117
4120
|
this.onInteraction,
|
|
3118
|
-
|
|
4121
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3119
4122
|
this.onRegisterCanceller
|
|
3120
4123
|
);
|
|
3121
4124
|
}
|
|
@@ -3128,7 +4131,7 @@ var SignerBtc = class {
|
|
|
3128
4131
|
return deviceActionToPromise(
|
|
3129
4132
|
action,
|
|
3130
4133
|
this.onInteraction,
|
|
3131
|
-
|
|
4134
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3132
4135
|
this.onRegisterCanceller
|
|
3133
4136
|
);
|
|
3134
4137
|
}
|
|
@@ -3141,7 +4144,7 @@ var SignerBtc = class {
|
|
|
3141
4144
|
return deviceActionToPromise(
|
|
3142
4145
|
action,
|
|
3143
4146
|
this.onInteraction,
|
|
3144
|
-
|
|
4147
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3145
4148
|
this.onRegisterCanceller
|
|
3146
4149
|
);
|
|
3147
4150
|
}
|
|
@@ -3160,11 +4163,25 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3160
4163
|
return DDT.TAPROOT;
|
|
3161
4164
|
default:
|
|
3162
4165
|
throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
|
|
3163
|
-
code:
|
|
4166
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3164
4167
|
});
|
|
3165
4168
|
}
|
|
3166
4169
|
}
|
|
4170
|
+
function assertBitcoinMainnet(coin) {
|
|
4171
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4172
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4173
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
|
|
4174
|
+
});
|
|
4175
|
+
}
|
|
4176
|
+
}
|
|
3167
4177
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4178
|
+
assertBitcoinMainnet(params.coin);
|
|
4179
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4180
|
+
throw Object.assign(
|
|
4181
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4182
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
4183
|
+
);
|
|
4184
|
+
}
|
|
3168
4185
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3169
4186
|
const path = normalizePath(params.path);
|
|
3170
4187
|
try {
|
|
@@ -3195,6 +4212,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3195
4212
|
}
|
|
3196
4213
|
}
|
|
3197
4214
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4215
|
+
assertBitcoinMainnet(params.coin);
|
|
3198
4216
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3199
4217
|
const path = normalizePath(params.path);
|
|
3200
4218
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3202,7 +4220,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3202
4220
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3203
4221
|
checkOnDevice: params.showOnDevice ?? false
|
|
3204
4222
|
});
|
|
3205
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4223
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3206
4224
|
return { xpub, path: params.path };
|
|
3207
4225
|
} catch (err) {
|
|
3208
4226
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3216,7 +4234,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3216
4234
|
if (!params.psbt) {
|
|
3217
4235
|
throw Object.assign(
|
|
3218
4236
|
new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
|
|
3219
|
-
{ code:
|
|
4237
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
3220
4238
|
);
|
|
3221
4239
|
}
|
|
3222
4240
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3230,7 +4248,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3230
4248
|
debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
|
|
3231
4249
|
const wallet = new DefaultWallet(path, template);
|
|
3232
4250
|
const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
|
|
3233
|
-
return { serializedTx: (0,
|
|
4251
|
+
return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
|
|
3234
4252
|
} catch (err) {
|
|
3235
4253
|
ctx.invalidateSession(sessionId);
|
|
3236
4254
|
throw ctx.wrapError(err);
|
|
@@ -3241,7 +4259,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3241
4259
|
async function btcSignPsbt(ctx, sessionId, params) {
|
|
3242
4260
|
if (!params.psbt) {
|
|
3243
4261
|
throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
|
|
3244
|
-
code:
|
|
4262
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3245
4263
|
});
|
|
3246
4264
|
}
|
|
3247
4265
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3271,8 +4289,8 @@ async function btcSignMessage(ctx, sessionId, params) {
|
|
|
3271
4289
|
try {
|
|
3272
4290
|
const result = await btcSigner.signMessage(path, params.message);
|
|
3273
4291
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3274
|
-
const rHex = (0,
|
|
3275
|
-
const sHex = (0,
|
|
4292
|
+
const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
|
|
4293
|
+
const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
|
|
3276
4294
|
return { signature: `${vHex}${rHex}${sHex}` };
|
|
3277
4295
|
} catch (err) {
|
|
3278
4296
|
ctx.invalidateSession(sessionId);
|
|
@@ -3323,7 +4341,7 @@ function _isScriptPathInput(input) {
|
|
|
3323
4341
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3324
4342
|
}
|
|
3325
4343
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3326
|
-
const psbt =
|
|
4344
|
+
const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
|
|
3327
4345
|
for (const sig of signatures) {
|
|
3328
4346
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3329
4347
|
if (!input) {
|
|
@@ -3372,7 +4390,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3372
4390
|
}
|
|
3373
4391
|
|
|
3374
4392
|
// src/connector/chains/sol.ts
|
|
3375
|
-
var
|
|
4393
|
+
var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
|
|
4394
|
+
var import_bs58 = __toESM(require("bs58"));
|
|
3376
4395
|
|
|
3377
4396
|
// src/signer/SignerSol.ts
|
|
3378
4397
|
var SignerSol = class {
|
|
@@ -3390,7 +4409,7 @@ var SignerSol = class {
|
|
|
3390
4409
|
return deviceActionToPromise(
|
|
3391
4410
|
action,
|
|
3392
4411
|
this.onInteraction,
|
|
3393
|
-
void 0,
|
|
4412
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3394
4413
|
this.onRegisterCanceller
|
|
3395
4414
|
);
|
|
3396
4415
|
}
|
|
@@ -3402,7 +4421,7 @@ var SignerSol = class {
|
|
|
3402
4421
|
return deviceActionToPromise(
|
|
3403
4422
|
action,
|
|
3404
4423
|
this.onInteraction,
|
|
3405
|
-
|
|
4424
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3406
4425
|
this.onRegisterCanceller
|
|
3407
4426
|
);
|
|
3408
4427
|
}
|
|
@@ -3415,7 +4434,7 @@ var SignerSol = class {
|
|
|
3415
4434
|
return deviceActionToPromise(
|
|
3416
4435
|
action,
|
|
3417
4436
|
this.onInteraction,
|
|
3418
|
-
|
|
4437
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3419
4438
|
this.onRegisterCanceller
|
|
3420
4439
|
);
|
|
3421
4440
|
}
|
|
@@ -3440,10 +4459,10 @@ async function solGetAddress(ctx, sessionId, params) {
|
|
|
3440
4459
|
async function solSignTransaction(ctx, sessionId, params) {
|
|
3441
4460
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3442
4461
|
const path = normalizePath(params.path);
|
|
3443
|
-
const txBytes = (0,
|
|
4462
|
+
const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
|
|
3444
4463
|
try {
|
|
3445
4464
|
const result = await solSigner.signTransaction(path, txBytes);
|
|
3446
|
-
return { signature: (0,
|
|
4465
|
+
return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
|
|
3447
4466
|
} catch (err) {
|
|
3448
4467
|
ctx.invalidateSession(sessionId);
|
|
3449
4468
|
throw ctx.wrapError(err);
|
|
@@ -3454,10 +4473,23 @@ async function solSignTransaction(ctx, sessionId, params) {
|
|
|
3454
4473
|
async function solSignMessage(ctx, sessionId, params) {
|
|
3455
4474
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3456
4475
|
const path = normalizePath(params.path);
|
|
3457
|
-
const messageBytes = (0,
|
|
4476
|
+
const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
|
|
3458
4477
|
try {
|
|
4478
|
+
if (params.messageVersion === 1) {
|
|
4479
|
+
const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
|
|
4480
|
+
message: messageBytes,
|
|
4481
|
+
requiredSigners: params.requiredSigners
|
|
4482
|
+
});
|
|
4483
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4484
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4485
|
+
);
|
|
4486
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4487
|
+
version: SignMessageVersion.Raw
|
|
4488
|
+
});
|
|
4489
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4490
|
+
}
|
|
3459
4491
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3460
|
-
return { signature: result.signature };
|
|
4492
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3461
4493
|
} catch (err) {
|
|
3462
4494
|
ctx.invalidateSession(sessionId);
|
|
3463
4495
|
throw ctx.wrapError(err);
|
|
@@ -3465,11 +4497,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3465
4497
|
ctx.clearCanceller(sessionId);
|
|
3466
4498
|
}
|
|
3467
4499
|
}
|
|
4500
|
+
function decodeBase58Signature(signature) {
|
|
4501
|
+
const bytes = import_bs58.default.decode(signature);
|
|
4502
|
+
if (bytes.length !== 64) {
|
|
4503
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4504
|
+
}
|
|
4505
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
|
|
4506
|
+
}
|
|
4507
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4508
|
+
const bytes = import_bs58.default.decode(envelope);
|
|
4509
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4510
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4511
|
+
}
|
|
4512
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
|
|
4513
|
+
}
|
|
3468
4514
|
async function _createSolSigner(ctx, sessionId) {
|
|
3469
4515
|
const dmk = await ctx.getOrCreateDmk();
|
|
3470
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4516
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4517
|
+
"@ledgerhq/context-module"
|
|
4518
|
+
);
|
|
3471
4519
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3472
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4520
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3473
4521
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3474
4522
|
const signer = new SignerSol(sdkSigner);
|
|
3475
4523
|
signer.onInteraction = (interaction) => {
|
|
@@ -3485,316 +4533,119 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3485
4533
|
return signer;
|
|
3486
4534
|
}
|
|
3487
4535
|
|
|
3488
|
-
// src/connector/chains/
|
|
3489
|
-
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
3490
|
-
var import_hw_app_trx = __toESM(require("@ledgerhq/hw-app-trx"));
|
|
3491
|
-
|
|
3492
|
-
// src/connector/chains/legacyChainCall.ts
|
|
4536
|
+
// src/connector/chains/zcash.ts
|
|
3493
4537
|
var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
|
|
3494
4538
|
|
|
3495
|
-
// src/
|
|
3496
|
-
var
|
|
3497
|
-
|
|
3498
|
-
|
|
3499
|
-
|
|
3500
|
-
BTC: "Bitcoin",
|
|
3501
|
-
SOL: "Solana",
|
|
3502
|
-
TRX: "Tron",
|
|
3503
|
-
XRP: "XRP",
|
|
3504
|
-
ADA: "Cardano",
|
|
3505
|
-
DOT: "Polkadot",
|
|
3506
|
-
ATOM: "Cosmos"
|
|
3507
|
-
};
|
|
3508
|
-
var DASHBOARD_APP_NAME = "BOLOS";
|
|
3509
|
-
var AppManager = class {
|
|
3510
|
-
constructor(dmk, options) {
|
|
3511
|
-
this._dmk = dmk;
|
|
3512
|
-
this._waitMs = options?.waitMs ?? 1e3;
|
|
3513
|
-
this._maxRetries = options?.maxRetries ?? 10;
|
|
3514
|
-
}
|
|
3515
|
-
/**
|
|
3516
|
-
* Return the Ledger app name for a given chain ticker,
|
|
3517
|
-
* or undefined if the chain is not supported.
|
|
3518
|
-
*/
|
|
3519
|
-
static getAppName(chain) {
|
|
3520
|
-
return APP_NAME_MAP[chain];
|
|
3521
|
-
}
|
|
3522
|
-
/**
|
|
3523
|
-
* Ensure the target app is open on the device identified by `sessionId`.
|
|
3524
|
-
*
|
|
3525
|
-
* Flow:
|
|
3526
|
-
* 1. Check the currently running app.
|
|
3527
|
-
* 2. If it is already the target, return immediately.
|
|
3528
|
-
* 3. If a different app is running (not dashboard), close it first.
|
|
3529
|
-
* 4. Open the target app.
|
|
3530
|
-
* 5. Poll until the device confirms the target app is running.
|
|
3531
|
-
*/
|
|
3532
|
-
/**
|
|
3533
|
-
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
3534
|
-
* device is about to display "Open <app>" on screen and wait for the
|
|
3535
|
-
* user's button press. UI consumers should show their "open app" prompt
|
|
3536
|
-
* in response. NOT called when the target app is already open (no user
|
|
3537
|
-
* interaction needed in that case).
|
|
3538
|
-
*
|
|
3539
|
-
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
3540
|
-
* has physically confirmed on the device, so anything that runs AFTER
|
|
3541
|
-
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
3542
|
-
* Hence the callback must fire BEFORE that await.
|
|
3543
|
-
*/
|
|
3544
|
-
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
3545
|
-
const currentApp = await this._getCurrentApp(sessionId);
|
|
3546
|
-
if (currentApp === targetAppName) {
|
|
3547
|
-
return;
|
|
3548
|
-
}
|
|
3549
|
-
if (!this._isDashboard(currentApp)) {
|
|
3550
|
-
await this._closeCurrentApp(sessionId);
|
|
3551
|
-
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
3552
|
-
}
|
|
3553
|
-
onConfirmOnDevice?.();
|
|
3554
|
-
await this._openApp(sessionId, targetAppName);
|
|
3555
|
-
await this._waitForApp(sessionId, targetAppName);
|
|
4539
|
+
// src/signer/SignerZcash.ts
|
|
4540
|
+
var SignerZcash = class {
|
|
4541
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4542
|
+
constructor(_sdk) {
|
|
4543
|
+
this._sdk = _sdk;
|
|
3556
4544
|
}
|
|
3557
|
-
|
|
3558
|
-
|
|
3559
|
-
|
|
3560
|
-
|
|
3561
|
-
|
|
3562
|
-
|
|
3563
|
-
|
|
3564
|
-
|
|
3565
|
-
if ((0, import_device_management_kit2.isSuccessCommandResult)(result)) {
|
|
3566
|
-
debugLog("[AppManager] currentApp:", result.data.name);
|
|
3567
|
-
return result.data.name;
|
|
3568
|
-
}
|
|
3569
|
-
const errResult = result;
|
|
3570
|
-
const dmkErr = errResult.error ?? {};
|
|
3571
|
-
const original = dmkErr.originalError;
|
|
3572
|
-
debugLog(
|
|
3573
|
-
"[AppManager] _getCurrentApp failed sessionId=",
|
|
3574
|
-
sessionId,
|
|
3575
|
-
"tag=",
|
|
3576
|
-
dmkErr._tag,
|
|
3577
|
-
"errorCode=",
|
|
3578
|
-
dmkErr.errorCode,
|
|
3579
|
-
"message=",
|
|
3580
|
-
dmkErr.message,
|
|
3581
|
-
"originalErrorMessage=",
|
|
3582
|
-
original?.message ?? String(original ?? "")
|
|
3583
|
-
);
|
|
3584
|
-
throw Object.assign(
|
|
3585
|
-
new Error(
|
|
3586
|
-
dmkErr.message ?? "Failed to get current app from device"
|
|
3587
|
-
),
|
|
3588
|
-
{
|
|
3589
|
-
_tag: dmkErr._tag,
|
|
3590
|
-
errorCode: dmkErr.errorCode,
|
|
3591
|
-
originalError: original
|
|
3592
|
-
}
|
|
4545
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4546
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4547
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4548
|
+
return deviceActionToPromise(
|
|
4549
|
+
action,
|
|
4550
|
+
this.onInteraction,
|
|
4551
|
+
void 0,
|
|
4552
|
+
this.onRegisterCanceller
|
|
3593
4553
|
);
|
|
3594
4554
|
}
|
|
3595
|
-
|
|
3596
|
-
|
|
3597
|
-
|
|
3598
|
-
|
|
3599
|
-
|
|
3600
|
-
|
|
3601
|
-
|
|
3602
|
-
|
|
3603
|
-
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
3604
|
-
debugLog(
|
|
3605
|
-
"[AppManager] openApp failed:",
|
|
3606
|
-
appName,
|
|
3607
|
-
"errorCode:",
|
|
3608
|
-
errorCode,
|
|
3609
|
-
"tag:",
|
|
3610
|
-
dmkErr._tag
|
|
3611
|
-
);
|
|
3612
|
-
let code;
|
|
3613
|
-
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
3614
|
-
code = import_hwk_adapter_core10.HardwareErrorCode.AppNotInstalled;
|
|
3615
|
-
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
3616
|
-
code = import_hwk_adapter_core10.HardwareErrorCode.UserRejected;
|
|
3617
|
-
}
|
|
3618
|
-
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
3619
|
-
_tag: ERROR_TAG.OpenAppCommand,
|
|
3620
|
-
code,
|
|
3621
|
-
errorCode,
|
|
3622
|
-
statusCode: errorCode,
|
|
3623
|
-
appName,
|
|
3624
|
-
originalError: dmkErr
|
|
3625
|
-
});
|
|
3626
|
-
}
|
|
3627
|
-
}
|
|
3628
|
-
async _closeCurrentApp(sessionId) {
|
|
3629
|
-
debugLog("[AppManager] closeCurrentApp");
|
|
3630
|
-
await this._dmk.sendCommand({
|
|
3631
|
-
sessionId,
|
|
3632
|
-
command: new import_device_management_kit2.CloseAppCommand()
|
|
3633
|
-
});
|
|
3634
|
-
}
|
|
3635
|
-
/**
|
|
3636
|
-
* Poll the device until the expected app is reported as running,
|
|
3637
|
-
* or throw after `_maxRetries` attempts.
|
|
3638
|
-
*/
|
|
3639
|
-
async _waitForApp(sessionId, expectedAppName) {
|
|
3640
|
-
let lastSeen = "";
|
|
3641
|
-
for (let i = 0; i < this._maxRetries; i++) {
|
|
3642
|
-
await this._wait();
|
|
3643
|
-
const current = await this._getCurrentApp(sessionId);
|
|
3644
|
-
lastSeen = current;
|
|
3645
|
-
if (current === expectedAppName) {
|
|
3646
|
-
return;
|
|
3647
|
-
}
|
|
3648
|
-
}
|
|
3649
|
-
debugLog(
|
|
3650
|
-
"[AppManager] waitForApp exhausted: expected=",
|
|
3651
|
-
expectedAppName,
|
|
3652
|
-
"lastSeen=",
|
|
3653
|
-
lastSeen
|
|
3654
|
-
);
|
|
3655
|
-
throw new Error(
|
|
3656
|
-
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
4555
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4556
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4557
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4558
|
+
return deviceActionToPromise(
|
|
4559
|
+
action,
|
|
4560
|
+
this.onInteraction,
|
|
4561
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4562
|
+
this.onRegisterCanceller
|
|
3657
4563
|
);
|
|
3658
4564
|
}
|
|
3659
|
-
_isDashboard(appName) {
|
|
3660
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3661
|
-
}
|
|
3662
|
-
_wait() {
|
|
3663
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3664
|
-
}
|
|
3665
4565
|
};
|
|
3666
4566
|
|
|
3667
|
-
// src/connector/chains/
|
|
3668
|
-
function
|
|
3669
|
-
|
|
4567
|
+
// src/connector/chains/zcash.ts
|
|
4568
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4569
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4570
|
+
const path = normalizePath(params.path);
|
|
4571
|
+
const mode = params.mode ?? "ufvk";
|
|
4572
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4573
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4574
|
+
if (result.mode === "ufvk") {
|
|
4575
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4576
|
+
}
|
|
4577
|
+
return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
|
|
4578
|
+
});
|
|
3670
4579
|
}
|
|
3671
|
-
async function
|
|
3672
|
-
const
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
|
|
3678
|
-
payload: { sessionId }
|
|
4580
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4581
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4582
|
+
const path = normalizePath(params.path);
|
|
4583
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4584
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4585
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3679
4586
|
});
|
|
3680
|
-
|
|
3681
|
-
|
|
3682
|
-
if (openAppPromptShown) {
|
|
3683
|
-
ctx.emit("ui-event", {
|
|
3684
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.InteractionComplete,
|
|
3685
|
-
payload: { sessionId }
|
|
3686
|
-
});
|
|
3687
|
-
openAppPromptShown = false;
|
|
3688
|
-
}
|
|
3689
|
-
};
|
|
3690
|
-
try {
|
|
3691
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3692
|
-
} catch (err) {
|
|
3693
|
-
debugLog(
|
|
3694
|
-
"[LegacyChainCall] pre-flight ensureAppOpen failed:",
|
|
3695
|
-
appName,
|
|
3696
|
-
err?.message
|
|
3697
|
-
);
|
|
3698
|
-
closeOpenAppUiIfShown();
|
|
3699
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3700
|
-
}
|
|
3701
|
-
const runOnce = async () => {
|
|
3702
|
-
let confirmEmitted = false;
|
|
3703
|
-
if (needsConfirmation) {
|
|
3704
|
-
ctx.emit("ui-event", {
|
|
3705
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOnDevice,
|
|
3706
|
-
payload: { sessionId }
|
|
3707
|
-
});
|
|
3708
|
-
confirmEmitted = true;
|
|
3709
|
-
}
|
|
3710
|
-
try {
|
|
3711
|
-
return await action(sessionId);
|
|
3712
|
-
} finally {
|
|
3713
|
-
if (confirmEmitted || openAppPromptShown) {
|
|
3714
|
-
ctx.emit("ui-event", {
|
|
3715
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.InteractionComplete,
|
|
3716
|
-
payload: { sessionId }
|
|
3717
|
-
});
|
|
3718
|
-
openAppPromptShown = false;
|
|
3719
|
-
}
|
|
3720
|
-
}
|
|
3721
|
-
};
|
|
3722
|
-
try {
|
|
3723
|
-
return await runOnce();
|
|
3724
|
-
} catch (err) {
|
|
3725
|
-
if (!isLegacyWrongAppError(err, appName)) {
|
|
3726
|
-
debugLog("[LegacyChainCall] non-wrong-app failure:", appName, err?.message);
|
|
3727
|
-
ctx.invalidateSession(sessionId);
|
|
3728
|
-
throw ctx.wrapError(err, { defaultAppName: appName });
|
|
3729
|
-
}
|
|
3730
|
-
debugLog("[LegacyChainCall] wrong-app detected, retrying:", appName);
|
|
3731
|
-
try {
|
|
3732
|
-
await _ensureAppOpen(ctx, sessionId, appName, onAppOpenPrompt);
|
|
3733
|
-
} catch (switchErr) {
|
|
3734
|
-
debugLog(
|
|
3735
|
-
"[LegacyChainCall] retry ensureAppOpen failed:",
|
|
3736
|
-
appName,
|
|
3737
|
-
switchErr?.message
|
|
3738
|
-
);
|
|
3739
|
-
closeOpenAppUiIfShown();
|
|
3740
|
-
throw ctx.wrapError(switchErr, { defaultAppName: appName });
|
|
3741
|
-
}
|
|
3742
|
-
ctx.clearAllSigners();
|
|
3743
|
-
const result = await runOnce();
|
|
3744
|
-
debugLog("[LegacyChainCall] retry succeeded:", appName);
|
|
3745
|
-
return result;
|
|
3746
|
-
}
|
|
4587
|
+
return { address: result.address, path: params.path };
|
|
4588
|
+
});
|
|
3747
4589
|
}
|
|
3748
|
-
async function
|
|
4590
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3749
4591
|
const dmk = await ctx.getOrCreateDmk();
|
|
3750
|
-
const
|
|
3751
|
-
|
|
4592
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4593
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4594
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3752
4595
|
}
|
|
3753
4596
|
|
|
3754
|
-
// src/
|
|
3755
|
-
var
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
4597
|
+
// src/connector/chains/tron.ts
|
|
4598
|
+
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
4599
|
+
|
|
4600
|
+
// src/signer/SignerTron.ts
|
|
4601
|
+
var SignerTron = class {
|
|
4602
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4603
|
+
constructor(_sdk) {
|
|
4604
|
+
this._sdk = _sdk;
|
|
3761
4605
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
}
|
|
3772
|
-
result.set(statusCode, data.length);
|
|
3773
|
-
return result;
|
|
4606
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4607
|
+
async getAddress(derivationPath, options) {
|
|
4608
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4609
|
+
const result = await deviceActionToPromise(
|
|
4610
|
+
action,
|
|
4611
|
+
this.onInteraction,
|
|
4612
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4613
|
+
this.onRegisterCanceller
|
|
4614
|
+
);
|
|
4615
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3774
4616
|
}
|
|
3775
|
-
|
|
4617
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4618
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4619
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4620
|
+
return deviceActionToPromise(
|
|
4621
|
+
action,
|
|
4622
|
+
this.onInteraction,
|
|
4623
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4624
|
+
this.onRegisterCanceller
|
|
4625
|
+
);
|
|
4626
|
+
}
|
|
4627
|
+
/** Sign a personal message (TIP-191). */
|
|
4628
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4629
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4630
|
+
return deviceActionToPromise(
|
|
4631
|
+
action,
|
|
4632
|
+
this.onInteraction,
|
|
4633
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4634
|
+
this.onRegisterCanceller
|
|
4635
|
+
);
|
|
3776
4636
|
}
|
|
3777
4637
|
};
|
|
3778
4638
|
|
|
3779
4639
|
// src/connector/chains/tron.ts
|
|
3780
4640
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4641
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3781
4642
|
const path = normalizePath(params.path);
|
|
3782
|
-
|
|
3783
|
-
|
|
3784
|
-
|
|
3785
|
-
|
|
3786
|
-
{
|
|
3787
|
-
|
|
3788
|
-
// Only show "confirm on device" UI when the device is actually going
|
|
3789
|
-
// to display the address for the user to verify.
|
|
3790
|
-
needsConfirmation: showOnDevice
|
|
3791
|
-
},
|
|
3792
|
-
async (sid) => {
|
|
3793
|
-
const trx = await _createTrx(ctx, sid);
|
|
3794
|
-
const result = await trx.getAddress(path, showOnDevice);
|
|
3795
|
-
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
3796
|
-
}
|
|
3797
|
-
);
|
|
4643
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4644
|
+
const result = await tronSigner.getAddress(path, {
|
|
4645
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4646
|
+
});
|
|
4647
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4648
|
+
});
|
|
3798
4649
|
}
|
|
3799
4650
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3800
4651
|
if (!params.rawTxHex) {
|
|
@@ -3803,42 +4654,30 @@ async function tronSignTransaction(ctx, sessionId, params) {
|
|
|
3803
4654
|
{ code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
|
|
3804
4655
|
);
|
|
3805
4656
|
}
|
|
4657
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3806
4658
|
const path = normalizePath(params.path);
|
|
3807
|
-
return
|
|
3808
|
-
|
|
3809
|
-
|
|
3810
|
-
|
|
3811
|
-
async (sid) => {
|
|
3812
|
-
const trx = await _createTrx(ctx, sid);
|
|
3813
|
-
const signature = await trx.signTransaction(
|
|
3814
|
-
path,
|
|
3815
|
-
params.rawTxHex,
|
|
3816
|
-
params.tokenSignatures ?? []
|
|
3817
|
-
);
|
|
3818
|
-
return { signature };
|
|
3819
|
-
}
|
|
3820
|
-
);
|
|
4659
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4660
|
+
const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
|
|
4661
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4662
|
+
});
|
|
3821
4663
|
}
|
|
3822
4664
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4665
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3823
4666
|
const path = normalizePath(params.path);
|
|
3824
|
-
return
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
async (sid) => {
|
|
3829
|
-
const trx = await _createTrx(ctx, sid);
|
|
3830
|
-
const signature = await trx.signPersonalMessage(path, params.messageHex);
|
|
3831
|
-
return { signature };
|
|
3832
|
-
}
|
|
3833
|
-
);
|
|
4667
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4668
|
+
const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
|
|
4669
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4670
|
+
});
|
|
3834
4671
|
}
|
|
3835
|
-
async function
|
|
4672
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3836
4673
|
const dmk = await ctx.getOrCreateDmk();
|
|
3837
|
-
|
|
4674
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4675
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4676
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3838
4677
|
}
|
|
3839
4678
|
|
|
3840
4679
|
// src/device-apps/customActions.ts
|
|
3841
|
-
var
|
|
4680
|
+
var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
|
|
3842
4681
|
var import_rxjs = require("rxjs");
|
|
3843
4682
|
var GetOsVersionDeviceAction = class {
|
|
3844
4683
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
@@ -3852,7 +4691,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3852
4691
|
(async () => {
|
|
3853
4692
|
try {
|
|
3854
4693
|
subject.next({
|
|
3855
|
-
status:
|
|
4694
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3856
4695
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3857
4696
|
});
|
|
3858
4697
|
const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
|
|
@@ -3861,11 +4700,11 @@ var GetOsVersionDeviceAction = class {
|
|
|
3861
4700
|
const errObj = result?.error;
|
|
3862
4701
|
throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
|
|
3863
4702
|
}
|
|
3864
|
-
subject.next({ status:
|
|
4703
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
|
|
3865
4704
|
subject.complete();
|
|
3866
4705
|
} catch (err) {
|
|
3867
4706
|
if (cancelled) return;
|
|
3868
|
-
subject.next({ status:
|
|
4707
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3869
4708
|
subject.complete();
|
|
3870
4709
|
}
|
|
3871
4710
|
})();
|
|
@@ -3873,7 +4712,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3873
4712
|
observable: subject.asObservable(),
|
|
3874
4713
|
cancel: () => {
|
|
3875
4714
|
cancelled = true;
|
|
3876
|
-
subject.next({ status:
|
|
4715
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3877
4716
|
subject.complete();
|
|
3878
4717
|
}
|
|
3879
4718
|
};
|
|
@@ -3891,7 +4730,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3891
4730
|
(async () => {
|
|
3892
4731
|
try {
|
|
3893
4732
|
subject.next({
|
|
3894
|
-
status:
|
|
4733
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3895
4734
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3896
4735
|
});
|
|
3897
4736
|
const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
|
|
@@ -3908,11 +4747,11 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3908
4747
|
throw new Error(httpErr?.message ?? "Manager API getAppList failed");
|
|
3909
4748
|
}
|
|
3910
4749
|
const apps = either.extract();
|
|
3911
|
-
subject.next({ status:
|
|
4750
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
|
|
3912
4751
|
subject.complete();
|
|
3913
4752
|
} catch (err) {
|
|
3914
4753
|
if (cancelled) return;
|
|
3915
|
-
subject.next({ status:
|
|
4754
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3916
4755
|
subject.complete();
|
|
3917
4756
|
}
|
|
3918
4757
|
})();
|
|
@@ -3920,7 +4759,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3920
4759
|
observable: subject.asObservable(),
|
|
3921
4760
|
cancel: () => {
|
|
3922
4761
|
cancelled = true;
|
|
3923
|
-
subject.next({ status:
|
|
4762
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3924
4763
|
subject.complete();
|
|
3925
4764
|
}
|
|
3926
4765
|
};
|
|
@@ -4013,7 +4852,7 @@ var DeviceApps = class {
|
|
|
4013
4852
|
seTargetId: v.seTargetId,
|
|
4014
4853
|
mcuTargetId: v.mcuTargetId,
|
|
4015
4854
|
seVersion: v.seVersion,
|
|
4016
|
-
seFlagsHex:
|
|
4855
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
4017
4856
|
mcuSephVersion: v.mcuSephVersion,
|
|
4018
4857
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
4019
4858
|
hwVersion: v.hwVersion
|
|
@@ -4087,7 +4926,7 @@ var DeviceApps = class {
|
|
|
4087
4926
|
}
|
|
4088
4927
|
}
|
|
4089
4928
|
};
|
|
4090
|
-
function
|
|
4929
|
+
function bytesToHex4(bytes) {
|
|
4091
4930
|
if (!bytes) return "";
|
|
4092
4931
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4093
4932
|
}
|
|
@@ -4130,8 +4969,17 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4130
4969
|
evm: "Ethereum",
|
|
4131
4970
|
btc: "Bitcoin",
|
|
4132
4971
|
sol: "Solana",
|
|
4133
|
-
tron: "Tron"
|
|
4972
|
+
tron: "Tron",
|
|
4973
|
+
zcash: "Zcash"
|
|
4134
4974
|
};
|
|
4975
|
+
function withOpenAppName(event, data, appName) {
|
|
4976
|
+
if (event !== "ui-event") return data;
|
|
4977
|
+
const uiEvent = data;
|
|
4978
|
+
if (uiEvent.type !== import_hwk_adapter_core13.EConnectorInteraction.ConfirmOpenApp || uiEvent.payload.appName) {
|
|
4979
|
+
return data;
|
|
4980
|
+
}
|
|
4981
|
+
return { ...uiEvent, payload: { ...uiEvent.payload, appName } };
|
|
4982
|
+
}
|
|
4135
4983
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4136
4984
|
Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
|
|
4137
4985
|
);
|
|
@@ -4170,6 +5018,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4170
5018
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4171
5019
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4172
5020
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
5021
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
5022
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
5023
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
5024
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4173
5025
|
case "@ledgerhq/context-module":
|
|
4174
5026
|
return import("@ledgerhq/context-module");
|
|
4175
5027
|
default:
|
|
@@ -4229,6 +5081,7 @@ var LedgerConnectorBase = class {
|
|
|
4229
5081
|
this._ctx = {
|
|
4230
5082
|
emit: (event, data) => this._emit(event, data),
|
|
4231
5083
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
5084
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4232
5085
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4233
5086
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4234
5087
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4417,8 +5270,15 @@ var LedgerConnectorBase = class {
|
|
|
4417
5270
|
} catch (err) {
|
|
4418
5271
|
this._resetSignersAndSessions();
|
|
4419
5272
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
5273
|
+
if (isBleBondInvalidError(err)) {
|
|
5274
|
+
throw (0, import_hwk_adapter_core13.createHwkError)({
|
|
5275
|
+
code: import_hwk_adapter_core13.HardwareErrorCode.BleBondInvalid,
|
|
5276
|
+
message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
|
|
5277
|
+
_tag: ERROR_TAG.PeerRemovedPairing
|
|
5278
|
+
});
|
|
5279
|
+
}
|
|
4420
5280
|
const tag = err?._tag;
|
|
4421
|
-
if (isKnownConnectionTag(tag)) {
|
|
5281
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4422
5282
|
throw err;
|
|
4423
5283
|
}
|
|
4424
5284
|
const wrapped = new Error(
|
|
@@ -4519,7 +5379,7 @@ var LedgerConnectorBase = class {
|
|
|
4519
5379
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4520
5380
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4521
5381
|
async call(sessionId, method, params) {
|
|
4522
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5382
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4523
5383
|
try {
|
|
4524
5384
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4525
5385
|
return { success: true, payload };
|
|
@@ -4587,6 +5447,11 @@ var LedgerConnectorBase = class {
|
|
|
4587
5447
|
return solSignTransaction(ctx, sessionId, params);
|
|
4588
5448
|
case "solSignMessage":
|
|
4589
5449
|
return solSignMessage(ctx, sessionId, params);
|
|
5450
|
+
// ZCASH
|
|
5451
|
+
case "zcashGetFullViewingKey":
|
|
5452
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5453
|
+
case "zcashGetShieldedAddress":
|
|
5454
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4590
5455
|
// TRON
|
|
4591
5456
|
case "tronGetAddress":
|
|
4592
5457
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4620,7 +5485,7 @@ var LedgerConnectorBase = class {
|
|
|
4620
5485
|
});
|
|
4621
5486
|
});
|
|
4622
5487
|
} catch (err) {
|
|
4623
|
-
ctx.
|
|
5488
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4624
5489
|
throw ctx.wrapError(err);
|
|
4625
5490
|
} finally {
|
|
4626
5491
|
ctx.clearCanceller(sessionId);
|
|
@@ -4710,7 +5575,7 @@ var LedgerConnectorBase = class {
|
|
|
4710
5575
|
);
|
|
4711
5576
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4712
5577
|
} catch (err) {
|
|
4713
|
-
ctx.
|
|
5578
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4714
5579
|
throw ctx.wrapError(err);
|
|
4715
5580
|
} finally {
|
|
4716
5581
|
ctx.clearCanceller(sessionId);
|
|
@@ -4832,6 +5697,17 @@ var LedgerConnectorBase = class {
|
|
|
4832
5697
|
_invalidateSession(sessionId) {
|
|
4833
5698
|
this._signerManager?.invalidate(sessionId);
|
|
4834
5699
|
}
|
|
5700
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5701
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5702
|
+
this._cancellers.delete(sessionId);
|
|
5703
|
+
if (cancel) {
|
|
5704
|
+
try {
|
|
5705
|
+
cancel();
|
|
5706
|
+
} catch {
|
|
5707
|
+
}
|
|
5708
|
+
}
|
|
5709
|
+
this._invalidateSession(sessionId);
|
|
5710
|
+
}
|
|
4835
5711
|
/**
|
|
4836
5712
|
* Replace an old session with a new one after app switch.
|
|
4837
5713
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4912,16 +5788,17 @@ var LedgerConnectorBase = class {
|
|
|
4912
5788
|
// ---------------------------------------------------------------------------
|
|
4913
5789
|
/**
|
|
4914
5790
|
* Return a per-call ctx with the chain's Ledger app name pre-bound to
|
|
4915
|
-
* wrapError, so chain handlers don't need to repeat
|
|
4916
|
-
*
|
|
5791
|
+
* UI prompts and wrapError, so chain handlers don't need to repeat the name.
|
|
5792
|
+
* Falls through unchanged for unknown methods.
|
|
4917
5793
|
*/
|
|
4918
5794
|
_ctxForMethod(method) {
|
|
4919
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5795
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4920
5796
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4921
5797
|
if (!defaultAppName) return this._ctx;
|
|
4922
5798
|
return {
|
|
4923
5799
|
...this._ctx,
|
|
4924
|
-
wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts })
|
|
5800
|
+
wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts }),
|
|
5801
|
+
emit: (event, data) => this._ctx.emit(event, withOpenAppName(event, data, defaultAppName))
|
|
4925
5802
|
};
|
|
4926
5803
|
}
|
|
4927
5804
|
_wrapError(err, opts) {
|
|
@@ -4950,6 +5827,204 @@ var LedgerConnectorBase = class {
|
|
|
4950
5827
|
return error;
|
|
4951
5828
|
}
|
|
4952
5829
|
};
|
|
5830
|
+
|
|
5831
|
+
// src/transport/DmkTransport.ts
|
|
5832
|
+
var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
|
|
5833
|
+
var DmkTransport = class extends import_hw_transport.default {
|
|
5834
|
+
constructor(dmk, sessionId) {
|
|
5835
|
+
super();
|
|
5836
|
+
this._dmk = dmk;
|
|
5837
|
+
this._sessionId = sessionId;
|
|
5838
|
+
}
|
|
5839
|
+
async exchange(apdu) {
|
|
5840
|
+
const response = await this._dmk.sendApdu({
|
|
5841
|
+
sessionId: this._sessionId,
|
|
5842
|
+
apdu: new Uint8Array(apdu)
|
|
5843
|
+
});
|
|
5844
|
+
const { data, statusCode } = response;
|
|
5845
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5846
|
+
if (data.length > 0) {
|
|
5847
|
+
result.set(data, 0);
|
|
5848
|
+
}
|
|
5849
|
+
result.set(statusCode, data.length);
|
|
5850
|
+
return result;
|
|
5851
|
+
}
|
|
5852
|
+
async close() {
|
|
5853
|
+
}
|
|
5854
|
+
};
|
|
5855
|
+
|
|
5856
|
+
// src/app/AppManager.ts
|
|
5857
|
+
var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
|
|
5858
|
+
var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
|
|
5859
|
+
var APP_NAME_MAP = {
|
|
5860
|
+
ETH: "Ethereum",
|
|
5861
|
+
BTC: "Bitcoin",
|
|
5862
|
+
SOL: "Solana",
|
|
5863
|
+
TRX: "Tron",
|
|
5864
|
+
ZEC: "Zcash",
|
|
5865
|
+
XRP: "XRP",
|
|
5866
|
+
ADA: "Cardano",
|
|
5867
|
+
DOT: "Polkadot",
|
|
5868
|
+
ATOM: "Cosmos"
|
|
5869
|
+
};
|
|
5870
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5871
|
+
var AppManager = class {
|
|
5872
|
+
constructor(dmk, options) {
|
|
5873
|
+
this._dmk = dmk;
|
|
5874
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5875
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5876
|
+
}
|
|
5877
|
+
/**
|
|
5878
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5879
|
+
* or undefined if the chain is not supported.
|
|
5880
|
+
*/
|
|
5881
|
+
static getAppName(chain) {
|
|
5882
|
+
return APP_NAME_MAP[chain];
|
|
5883
|
+
}
|
|
5884
|
+
/**
|
|
5885
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5886
|
+
*
|
|
5887
|
+
* Flow:
|
|
5888
|
+
* 1. Check the currently running app.
|
|
5889
|
+
* 2. If it is already the target, return immediately.
|
|
5890
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5891
|
+
* 4. Open the target app.
|
|
5892
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5893
|
+
*/
|
|
5894
|
+
/**
|
|
5895
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5896
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5897
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5898
|
+
* in response. NOT called when the target app is already open (no user
|
|
5899
|
+
* interaction needed in that case).
|
|
5900
|
+
*
|
|
5901
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5902
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5903
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5904
|
+
* Hence the callback must fire BEFORE that await.
|
|
5905
|
+
*/
|
|
5906
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5907
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5908
|
+
if (currentApp === targetAppName) {
|
|
5909
|
+
return;
|
|
5910
|
+
}
|
|
5911
|
+
if (!this._isDashboard(currentApp)) {
|
|
5912
|
+
await this._closeCurrentApp(sessionId);
|
|
5913
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5914
|
+
}
|
|
5915
|
+
onConfirmOnDevice?.();
|
|
5916
|
+
await this._openApp(sessionId, targetAppName);
|
|
5917
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5918
|
+
}
|
|
5919
|
+
// ---------------------------------------------------------------------------
|
|
5920
|
+
// Private helpers
|
|
5921
|
+
// ---------------------------------------------------------------------------
|
|
5922
|
+
async _getCurrentApp(sessionId) {
|
|
5923
|
+
const result = await this._dmk.sendCommand({
|
|
5924
|
+
sessionId,
|
|
5925
|
+
command: new import_device_management_kit3.GetAppAndVersionCommand()
|
|
5926
|
+
});
|
|
5927
|
+
if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5928
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5929
|
+
return result.data.name;
|
|
5930
|
+
}
|
|
5931
|
+
const errResult = result;
|
|
5932
|
+
const dmkErr = errResult.error ?? {};
|
|
5933
|
+
const original = dmkErr.originalError;
|
|
5934
|
+
debugLog(
|
|
5935
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5936
|
+
sessionId,
|
|
5937
|
+
"tag=",
|
|
5938
|
+
dmkErr._tag,
|
|
5939
|
+
"errorCode=",
|
|
5940
|
+
dmkErr.errorCode,
|
|
5941
|
+
"message=",
|
|
5942
|
+
dmkErr.message,
|
|
5943
|
+
"originalErrorMessage=",
|
|
5944
|
+
original?.message ?? String(original ?? "")
|
|
5945
|
+
);
|
|
5946
|
+
throw Object.assign(
|
|
5947
|
+
new Error(
|
|
5948
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5949
|
+
),
|
|
5950
|
+
{
|
|
5951
|
+
_tag: dmkErr._tag,
|
|
5952
|
+
errorCode: dmkErr.errorCode,
|
|
5953
|
+
originalError: original
|
|
5954
|
+
}
|
|
5955
|
+
);
|
|
5956
|
+
}
|
|
5957
|
+
async _openApp(sessionId, appName) {
|
|
5958
|
+
const result = await this._dmk.sendCommand({
|
|
5959
|
+
sessionId,
|
|
5960
|
+
command: new import_device_management_kit3.OpenAppCommand({ appName })
|
|
5961
|
+
});
|
|
5962
|
+
if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5963
|
+
const dmkErr = result.error;
|
|
5964
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5965
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5966
|
+
debugLog(
|
|
5967
|
+
"[AppManager] openApp failed:",
|
|
5968
|
+
appName,
|
|
5969
|
+
"errorCode:",
|
|
5970
|
+
errorCode,
|
|
5971
|
+
"tag:",
|
|
5972
|
+
dmkErr._tag
|
|
5973
|
+
);
|
|
5974
|
+
let code;
|
|
5975
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5976
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
|
|
5977
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5978
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
|
|
5979
|
+
}
|
|
5980
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5981
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5982
|
+
code,
|
|
5983
|
+
errorCode,
|
|
5984
|
+
statusCode: errorCode,
|
|
5985
|
+
appName,
|
|
5986
|
+
originalError: dmkErr
|
|
5987
|
+
});
|
|
5988
|
+
}
|
|
5989
|
+
}
|
|
5990
|
+
async _closeCurrentApp(sessionId) {
|
|
5991
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5992
|
+
await this._dmk.sendCommand({
|
|
5993
|
+
sessionId,
|
|
5994
|
+
command: new import_device_management_kit3.CloseAppCommand()
|
|
5995
|
+
});
|
|
5996
|
+
}
|
|
5997
|
+
/**
|
|
5998
|
+
* Poll the device until the expected app is reported as running,
|
|
5999
|
+
* or throw after `_maxRetries` attempts.
|
|
6000
|
+
*/
|
|
6001
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
6002
|
+
let lastSeen = "";
|
|
6003
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
6004
|
+
await this._wait();
|
|
6005
|
+
const current = await this._getCurrentApp(sessionId);
|
|
6006
|
+
lastSeen = current;
|
|
6007
|
+
if (current === expectedAppName) {
|
|
6008
|
+
return;
|
|
6009
|
+
}
|
|
6010
|
+
}
|
|
6011
|
+
debugLog(
|
|
6012
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
6013
|
+
expectedAppName,
|
|
6014
|
+
"lastSeen=",
|
|
6015
|
+
lastSeen
|
|
6016
|
+
);
|
|
6017
|
+
throw new Error(
|
|
6018
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
6019
|
+
);
|
|
6020
|
+
}
|
|
6021
|
+
_isDashboard(appName) {
|
|
6022
|
+
return appName === DASHBOARD_APP_NAME;
|
|
6023
|
+
}
|
|
6024
|
+
_wait() {
|
|
6025
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
6026
|
+
}
|
|
6027
|
+
};
|
|
4953
6028
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4954
6029
|
0 && (module.exports = {
|
|
4955
6030
|
AppManager,
|
|
@@ -4961,6 +6036,7 @@ var LedgerConnectorBase = class {
|
|
|
4961
6036
|
SignerEth,
|
|
4962
6037
|
SignerManager,
|
|
4963
6038
|
SignerSol,
|
|
6039
|
+
SignerZcash,
|
|
4964
6040
|
debugLog,
|
|
4965
6041
|
deviceActionToPromise,
|
|
4966
6042
|
isDeviceLockedError,
|