@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.11 → 1.2.8-alpha.111
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 +95 -50
- package/dist/index.d.ts +95 -50
- package/dist/index.js +2043 -980
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1991 -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,30 @@ 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
|
-
if (event.type ===
|
|
1046
|
+
if (event.type === import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress) {
|
|
825
1047
|
let connectId;
|
|
826
1048
|
for (const [cid, sid] of this._sessions) {
|
|
827
1049
|
if (sid === event.payload.sessionId) {
|
|
@@ -848,7 +1070,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
848
1070
|
}
|
|
849
1071
|
this._installProgressLastEmittedValue = progress;
|
|
850
1072
|
this.emitter.emit("ui-event", {
|
|
851
|
-
type:
|
|
1073
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
852
1074
|
payload: {
|
|
853
1075
|
connectId,
|
|
854
1076
|
appName,
|
|
@@ -861,14 +1083,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
861
1083
|
};
|
|
862
1084
|
this.connector = connector;
|
|
863
1085
|
this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
|
|
864
|
-
this._jobQueue = new
|
|
1086
|
+
this._jobQueue = new import_hwk_adapter_core4.DeviceJobQueue();
|
|
865
1087
|
this.registerEventListeners();
|
|
866
1088
|
}
|
|
1089
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1090
|
+
const pending = owner?.pendingBinding;
|
|
1091
|
+
if (!owner || !pending) return;
|
|
1092
|
+
owner.pendingBinding = void 0;
|
|
1093
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1094
|
+
}
|
|
1095
|
+
_finishBleBinding(status) {
|
|
1096
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1097
|
+
this._bindingSelectionRequestId = void 0;
|
|
1098
|
+
if (selectionRequestId) (0, import_hwk_adapter_core4.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
|
|
1099
|
+
}
|
|
1100
|
+
_isBleConnection() {
|
|
1101
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1102
|
+
}
|
|
867
1103
|
// Transport
|
|
868
1104
|
get activeTransport() {
|
|
869
|
-
return
|
|
1105
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
870
1106
|
}
|
|
871
1107
|
getAvailableTransports() {
|
|
1108
|
+
if (this.connector.availableTransports) {
|
|
1109
|
+
return this.connector.availableTransports.map(
|
|
1110
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1111
|
+
);
|
|
1112
|
+
}
|
|
872
1113
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
873
1114
|
}
|
|
874
1115
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -885,21 +1126,43 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
885
1126
|
* The next operation will re-discover and re-connect automatically.
|
|
886
1127
|
*/
|
|
887
1128
|
resetState() {
|
|
1129
|
+
void this._resetStateAndDisconnectSessions();
|
|
1130
|
+
}
|
|
1131
|
+
_resetStateAndDisconnectSessions() {
|
|
1132
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1133
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1134
|
+
this._stateGeneration += 1;
|
|
1135
|
+
this._finishBleBinding("cancelled");
|
|
1136
|
+
this._operations.endAll("runtime-reset");
|
|
1137
|
+
this._doConnectAbortController?.abort();
|
|
888
1138
|
this._discoveredDevices.clear();
|
|
889
1139
|
this._sessions.clear();
|
|
1140
|
+
this._sessionTransports.clear();
|
|
1141
|
+
this._activeConnectionType = void 0;
|
|
1142
|
+
this._pendingOperationBindings.clear();
|
|
1143
|
+
this._pendingPickBindings.clear();
|
|
1144
|
+
this._selectedBleReconnectTargets.clear();
|
|
890
1145
|
this._connectingPromise = null;
|
|
1146
|
+
this._doConnectAbortController = null;
|
|
891
1147
|
this._uiRegistry.reset();
|
|
892
1148
|
this._jobQueue.clear();
|
|
893
1149
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1150
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1151
|
+
for (const sessionId of sessionIds) {
|
|
1152
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1153
|
+
}
|
|
1154
|
+
});
|
|
1155
|
+
this._resetPromise = resetPromise;
|
|
1156
|
+
return resetPromise.finally(() => {
|
|
1157
|
+
if (this._resetPromise === resetPromise) {
|
|
1158
|
+
this._resetPromise = null;
|
|
1159
|
+
}
|
|
1160
|
+
});
|
|
894
1161
|
}
|
|
895
1162
|
async dispose() {
|
|
896
|
-
this.
|
|
897
|
-
this._jobQueue.clear();
|
|
1163
|
+
await this._resetStateAndDisconnectSessions();
|
|
898
1164
|
this.unregisterEventListeners();
|
|
899
1165
|
this.connector.reset();
|
|
900
|
-
this._discoveredDevices.clear();
|
|
901
|
-
this._sessions.clear();
|
|
902
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
903
1166
|
this.emitter.removeAllListeners();
|
|
904
1167
|
}
|
|
905
1168
|
uiResponse(response) {
|
|
@@ -909,17 +1172,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
909
1172
|
// Device management
|
|
910
1173
|
// ---------------------------------------------------------------------------
|
|
911
1174
|
async searchDevices(options) {
|
|
1175
|
+
return this._searchDevices(options);
|
|
1176
|
+
}
|
|
1177
|
+
async _searchDevices(options, signal) {
|
|
912
1178
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
913
1179
|
try {
|
|
914
1180
|
if (options?.resetSession) {
|
|
915
|
-
this.
|
|
916
|
-
|
|
917
|
-
this.
|
|
918
|
-
|
|
919
|
-
|
|
1181
|
+
await this._resetStateAndDisconnectSessions();
|
|
1182
|
+
} else {
|
|
1183
|
+
await this._connectorTeardownTail;
|
|
1184
|
+
}
|
|
1185
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1186
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1187
|
+
const stateGeneration = this._stateGeneration;
|
|
1188
|
+
const devices = await this.connector.searchDevices(
|
|
1189
|
+
options?.transportType ? {
|
|
1190
|
+
transportType: options.transportType,
|
|
1191
|
+
waitForAll: options.waitForAllTransports
|
|
1192
|
+
} : void 0
|
|
1193
|
+
);
|
|
1194
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1195
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1196
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1197
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1198
|
+
message: "Ledger discovery was reset"
|
|
1199
|
+
});
|
|
920
1200
|
}
|
|
921
|
-
await this._ensureDevicePermission();
|
|
922
|
-
const devices = await this.connector.searchDevices();
|
|
923
1201
|
this._discoveredDevices.clear();
|
|
924
1202
|
for (const d of devices) {
|
|
925
1203
|
if (d.connectId) {
|
|
@@ -927,7 +1205,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
927
1205
|
}
|
|
928
1206
|
}
|
|
929
1207
|
if (this._discoveredDevices.size === 0) {
|
|
930
|
-
await this._ensureDevicePermission();
|
|
1208
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
931
1209
|
}
|
|
932
1210
|
const result = Array.from(this._discoveredDevices.values());
|
|
933
1211
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -946,41 +1224,267 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
946
1224
|
throw err;
|
|
947
1225
|
}
|
|
948
1226
|
}
|
|
1227
|
+
async searchDeviceTargets(options) {
|
|
1228
|
+
const devices = await this.searchDevices(options);
|
|
1229
|
+
return devices.map((device) => (0, import_hwk_adapter_core4.toPhysicalDeviceSearchTarget)("ledger", device));
|
|
1230
|
+
}
|
|
949
1231
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
950
|
-
async _evictAllSessions() {
|
|
1232
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1233
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
951
1234
|
if (this._sessions.size === 0) return;
|
|
952
1235
|
const stale = [...this._sessions.values()];
|
|
953
1236
|
this._sessions.clear();
|
|
954
|
-
for (const sid of stale)
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1237
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1238
|
+
await this._runConnectorTeardown(async () => {
|
|
1239
|
+
for (const sid of stale) {
|
|
1240
|
+
try {
|
|
1241
|
+
await this.connector.disconnect(sid);
|
|
1242
|
+
} catch {
|
|
1243
|
+
}
|
|
958
1244
|
}
|
|
959
|
-
}
|
|
1245
|
+
});
|
|
960
1246
|
}
|
|
961
1247
|
static _createDeviceBusyError(method) {
|
|
962
1248
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
963
|
-
code:
|
|
1249
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceBusy
|
|
1250
|
+
});
|
|
1251
|
+
}
|
|
1252
|
+
async connectDevice(searchTargetId) {
|
|
1253
|
+
try {
|
|
1254
|
+
return await this._jobQueue.enqueue(
|
|
1255
|
+
searchTargetId || "__ledger_connect__",
|
|
1256
|
+
async (signal) => {
|
|
1257
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1258
|
+
if (!connected.success) return connected;
|
|
1259
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1260
|
+
},
|
|
1261
|
+
{
|
|
1262
|
+
label: "connectDevice",
|
|
1263
|
+
rejectIfBusy: true,
|
|
1264
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1265
|
+
}
|
|
1266
|
+
);
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
return this.errorToFailure(error);
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1272
|
+
async bindBleDevice(params) {
|
|
1273
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1274
|
+
const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
|
|
1275
|
+
try {
|
|
1276
|
+
return await this._jobQueue.enqueue(
|
|
1277
|
+
"__ledger_bind_ble__",
|
|
1278
|
+
async (signal) => {
|
|
1279
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1280
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1281
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.TransportNotAvailable,
|
|
1282
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1283
|
+
});
|
|
1284
|
+
}
|
|
1285
|
+
this._activeConnectionType = "ble";
|
|
1286
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1287
|
+
const attempt = {
|
|
1288
|
+
extra: params.extra,
|
|
1289
|
+
bindingReason: "manual-rebind",
|
|
1290
|
+
deferBindingSave: Boolean(identity)
|
|
1291
|
+
};
|
|
1292
|
+
try {
|
|
1293
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1294
|
+
[],
|
|
1295
|
+
void 0,
|
|
1296
|
+
true,
|
|
1297
|
+
void 0,
|
|
1298
|
+
attempt,
|
|
1299
|
+
signal
|
|
1300
|
+
);
|
|
1301
|
+
const pending = attempt.pendingBinding;
|
|
1302
|
+
if (identity && pending) {
|
|
1303
|
+
attempt.pendingBinding = void 0;
|
|
1304
|
+
const sessionId = this._sessions.get(connectId);
|
|
1305
|
+
if (!sessionId) {
|
|
1306
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1307
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
1308
|
+
message: "Selected Ledger connection ended"
|
|
1309
|
+
});
|
|
1310
|
+
}
|
|
1311
|
+
const checked = await this._fingerprintFirstOpenableChain(
|
|
1312
|
+
identities,
|
|
1313
|
+
(chain, autoInstallApp) => this._computeChainFingerprint(
|
|
1314
|
+
chain,
|
|
1315
|
+
(method, callParams) => this._runConnectorCall(
|
|
1316
|
+
connectId,
|
|
1317
|
+
method,
|
|
1318
|
+
callParams,
|
|
1319
|
+
signal,
|
|
1320
|
+
void 0,
|
|
1321
|
+
void 0,
|
|
1322
|
+
{ autoInstallApp },
|
|
1323
|
+
{ connection: { connectId, sessionId } }
|
|
1324
|
+
)
|
|
1325
|
+
)
|
|
1326
|
+
);
|
|
1327
|
+
if (checked.fingerprint !== checked.identity.value) {
|
|
1328
|
+
await this._dropSession(connectId, signal);
|
|
1329
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1330
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
1331
|
+
message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
|
|
1332
|
+
});
|
|
1333
|
+
}
|
|
1334
|
+
await this._saveSelectedBleBinding(
|
|
1335
|
+
connectId,
|
|
1336
|
+
pending.requestId,
|
|
1337
|
+
attempt,
|
|
1338
|
+
void 0,
|
|
1339
|
+
signal,
|
|
1340
|
+
checked.identity
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
if (!attempt.bindingSaved) {
|
|
1344
|
+
await this._dropSession(connectId, signal);
|
|
1345
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1346
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1347
|
+
message: "Bluetooth binding could not be saved",
|
|
1348
|
+
origin: "host"
|
|
1349
|
+
});
|
|
1350
|
+
}
|
|
1351
|
+
return (0, import_hwk_adapter_core4.success)(connectId);
|
|
1352
|
+
} catch (error) {
|
|
1353
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1354
|
+
throw error;
|
|
1355
|
+
}
|
|
1356
|
+
},
|
|
1357
|
+
{
|
|
1358
|
+
label: "bindBleDevice",
|
|
1359
|
+
rejectIfBusy: true,
|
|
1360
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1361
|
+
}
|
|
1362
|
+
);
|
|
1363
|
+
} catch (error) {
|
|
1364
|
+
return this.errorToFailure(error);
|
|
1365
|
+
}
|
|
1366
|
+
}
|
|
1367
|
+
async acquireOperation(connectId, context) {
|
|
1368
|
+
try {
|
|
1369
|
+
return await this._jobQueue.enqueue(
|
|
1370
|
+
connectId || "__ledger_acquire__",
|
|
1371
|
+
async (signal) => {
|
|
1372
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1373
|
+
const hint = context.knownConnections?.find(
|
|
1374
|
+
(connection) => connection.transport === transport
|
|
1375
|
+
);
|
|
1376
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1377
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1378
|
+
const attempt = {
|
|
1379
|
+
...context,
|
|
1380
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1381
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1382
|
+
deferBindingSave: true
|
|
1383
|
+
};
|
|
1384
|
+
try {
|
|
1385
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1386
|
+
target,
|
|
1387
|
+
signal,
|
|
1388
|
+
true,
|
|
1389
|
+
void 0,
|
|
1390
|
+
attempt
|
|
1391
|
+
);
|
|
1392
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1393
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1394
|
+
if (result.success && attempt.pendingBinding) {
|
|
1395
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1396
|
+
}
|
|
1397
|
+
return result;
|
|
1398
|
+
} catch (error) {
|
|
1399
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1400
|
+
throw error;
|
|
1401
|
+
}
|
|
1402
|
+
},
|
|
1403
|
+
{
|
|
1404
|
+
label: "acquireOperation",
|
|
1405
|
+
rejectIfBusy: true,
|
|
1406
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1407
|
+
}
|
|
1408
|
+
);
|
|
1409
|
+
} catch (error) {
|
|
1410
|
+
return this.errorToFailure(error);
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1414
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1415
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1416
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1417
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1418
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1419
|
+
vendor: "ledger",
|
|
1420
|
+
model: "unknown",
|
|
1421
|
+
firmwareVersion: "",
|
|
1422
|
+
deviceId: "",
|
|
1423
|
+
connectId: resolvedConnectId,
|
|
1424
|
+
connectionType
|
|
1425
|
+
};
|
|
1426
|
+
const operation = this._operations.create({
|
|
1427
|
+
searchTargetId,
|
|
1428
|
+
connectId: resolvedConnectId,
|
|
1429
|
+
device,
|
|
1430
|
+
connectionType,
|
|
1431
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
964
1432
|
});
|
|
1433
|
+
return (0, import_hwk_adapter_core4.success)(operation.operationId);
|
|
965
1434
|
}
|
|
966
|
-
async
|
|
1435
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
967
1436
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
968
1437
|
try {
|
|
969
|
-
|
|
1438
|
+
this._assertConnectorReady("connectDevice");
|
|
1439
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1440
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1441
|
+
this._activeConnectionType = discoveredType;
|
|
1442
|
+
}
|
|
1443
|
+
if (this._isBleConnection() && !connectId) {
|
|
970
1444
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
971
|
-
code:
|
|
1445
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
972
1446
|
});
|
|
973
1447
|
}
|
|
974
|
-
|
|
975
|
-
|
|
1448
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1449
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1450
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1451
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1452
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1453
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1454
|
+
if (previousSessionId) {
|
|
1455
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1456
|
+
this._sessions.delete(connectId);
|
|
1457
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1458
|
+
}
|
|
1459
|
+
} else {
|
|
1460
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1461
|
+
}
|
|
1462
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1463
|
+
const stateGeneration = this._stateGeneration;
|
|
1464
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1465
|
+
let session;
|
|
1466
|
+
this._connectingConnectId = connectId;
|
|
1467
|
+
try {
|
|
1468
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1469
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1470
|
+
}) : await this.connector.connect(connectId);
|
|
1471
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1472
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1473
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1474
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
} finally {
|
|
1478
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1479
|
+
releaseOperation();
|
|
976
1480
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
this.
|
|
1481
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1482
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1483
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
980
1484
|
if (session.deviceInfo) {
|
|
981
|
-
this._discoveredDevices.set(
|
|
1485
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
982
1486
|
}
|
|
983
|
-
const result = (0,
|
|
1487
|
+
const result = (0, import_hwk_adapter_core4.success)(resolvedConnectId);
|
|
984
1488
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
985
1489
|
return result;
|
|
986
1490
|
} catch (err) {
|
|
@@ -993,30 +1497,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
993
1497
|
return failureResult;
|
|
994
1498
|
}
|
|
995
1499
|
}
|
|
996
|
-
async
|
|
1500
|
+
async releaseOperation(operationId) {
|
|
1501
|
+
const operation = this._operations.findActive(operationId);
|
|
1502
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1503
|
+
const endedOperation = this._operations.release(operationId);
|
|
1504
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1505
|
+
const { connectId } = endedOperation;
|
|
997
1506
|
debugLog("[LedgerAdapter][REQ]", {
|
|
998
|
-
method: "
|
|
1507
|
+
method: "releaseOperation",
|
|
999
1508
|
connectId,
|
|
1000
1509
|
params: { connectId }
|
|
1001
1510
|
});
|
|
1002
1511
|
try {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
await this.connector.disconnect(sessionId);
|
|
1006
|
-
this._sessions.delete(connectId);
|
|
1007
|
-
}
|
|
1008
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1512
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1513
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
1009
1514
|
} catch (err) {
|
|
1010
1515
|
const e = err;
|
|
1011
1516
|
debugLog("[LedgerAdapter][RES]", {
|
|
1012
|
-
method: "
|
|
1517
|
+
method: "releaseOperation",
|
|
1013
1518
|
success: false,
|
|
1014
1519
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1520
|
});
|
|
1016
1521
|
throw err;
|
|
1017
1522
|
}
|
|
1018
1523
|
}
|
|
1019
|
-
|
|
1524
|
+
/**
|
|
1525
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1526
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1527
|
+
*/
|
|
1528
|
+
_cancelOperationWork(operation) {
|
|
1529
|
+
const { operationId } = operation;
|
|
1530
|
+
const reason = (0, import_hwk_adapter_core4.createHwkError)({
|
|
1531
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
1532
|
+
message: "Ledger operation was released",
|
|
1533
|
+
params: { operationId, reason: "explicit" }
|
|
1534
|
+
});
|
|
1535
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1536
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1537
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1538
|
+
if (!ownsRunningCall) return;
|
|
1539
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1540
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1541
|
+
}
|
|
1542
|
+
/**
|
|
1543
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1544
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1545
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1546
|
+
*/
|
|
1547
|
+
_bareCallMayUseConnection(operation) {
|
|
1548
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1549
|
+
return activeKey !== void 0 && !(0, import_hwk_adapter_core4.isHardwareOperationId)(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1550
|
+
}
|
|
1551
|
+
async _releaseOperationConnection(operation) {
|
|
1552
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1553
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1554
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1555
|
+
this._sessions.delete(connectId);
|
|
1556
|
+
sessionIds.add(sessionId);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
for (const sessionId of sessionIds) {
|
|
1560
|
+
await this._runConnectorTeardown(
|
|
1561
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1562
|
+
);
|
|
1563
|
+
}
|
|
1564
|
+
}
|
|
1565
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1566
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1567
|
+
if (!endedOperation) return;
|
|
1568
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1569
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1570
|
+
}
|
|
1571
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1572
|
+
let connectId;
|
|
1573
|
+
try {
|
|
1574
|
+
connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1575
|
+
} catch (error) {
|
|
1576
|
+
return this.errorToFailure(error);
|
|
1577
|
+
}
|
|
1020
1578
|
debugLog("[LedgerAdapter][REQ]", {
|
|
1021
1579
|
method: "getDeviceInfo",
|
|
1022
1580
|
connectId,
|
|
@@ -1026,7 +1584,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1026
1584
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
1027
1585
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
1028
1586
|
if (cached) {
|
|
1029
|
-
const result = (0,
|
|
1587
|
+
const result = (0, import_hwk_adapter_core4.success)(cached);
|
|
1030
1588
|
debugLog("[LedgerAdapter][RES]", {
|
|
1031
1589
|
method: "getDeviceInfo",
|
|
1032
1590
|
success: true,
|
|
@@ -1034,8 +1592,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1034
1592
|
});
|
|
1035
1593
|
return result;
|
|
1036
1594
|
}
|
|
1037
|
-
const notFound = (0,
|
|
1038
|
-
|
|
1595
|
+
const notFound = (0, import_hwk_adapter_core4.failure)(
|
|
1596
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
1039
1597
|
"Device not found in cache. Call searchDevices() or wait for a device-connected event first."
|
|
1040
1598
|
);
|
|
1041
1599
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -1051,11 +1609,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1051
1609
|
success: false,
|
|
1052
1610
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1053
1611
|
});
|
|
1054
|
-
|
|
1612
|
+
return this.errorToFailure(err);
|
|
1055
1613
|
}
|
|
1056
1614
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1615
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1616
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1617
|
+
const { connection } = context;
|
|
1618
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1619
|
+
if (!connection || !owner) return;
|
|
1620
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1621
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1622
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1623
|
+
await this._dropSession(connection.connectId, signal);
|
|
1624
|
+
}
|
|
1059
1625
|
}
|
|
1060
1626
|
// ---------------------------------------------------------------------------
|
|
1061
1627
|
// Chain call helper
|
|
@@ -1075,7 +1641,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1075
1641
|
commonParams,
|
|
1076
1642
|
installContext
|
|
1077
1643
|
);
|
|
1078
|
-
return (0,
|
|
1644
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1079
1645
|
} catch (err) {
|
|
1080
1646
|
return this.errorToFailure(err);
|
|
1081
1647
|
}
|
|
@@ -1091,13 +1657,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1091
1657
|
if (params && typeof params === "object") {
|
|
1092
1658
|
const {
|
|
1093
1659
|
autoInstallApp,
|
|
1660
|
+
operationId,
|
|
1094
1661
|
passphraseState: _passphraseState,
|
|
1095
1662
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1663
|
+
knownConnections,
|
|
1664
|
+
extra,
|
|
1665
|
+
allowDeviceSelection,
|
|
1666
|
+
supportedTransports,
|
|
1096
1667
|
...rest
|
|
1097
1668
|
} = params;
|
|
1098
1669
|
return {
|
|
1099
1670
|
commonParams: {
|
|
1100
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1671
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1672
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1673
|
+
...(0, import_hwk_adapter_core4.pickConnectionContext)({
|
|
1674
|
+
knownConnections,
|
|
1675
|
+
extra,
|
|
1676
|
+
allowDeviceSelection,
|
|
1677
|
+
supportedTransports
|
|
1678
|
+
})
|
|
1101
1679
|
},
|
|
1102
1680
|
rest
|
|
1103
1681
|
};
|
|
@@ -1263,7 +1841,13 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1263
1841
|
params
|
|
1264
1842
|
);
|
|
1265
1843
|
}
|
|
1266
|
-
tronSignMessage(connectId, deviceId, params) {
|
|
1844
|
+
async tronSignMessage(connectId, deviceId, params) {
|
|
1845
|
+
if (params?.messageType !== "V2") {
|
|
1846
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1847
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1848
|
+
'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
|
|
1849
|
+
);
|
|
1850
|
+
}
|
|
1267
1851
|
return this.callChainWithMergedParams(
|
|
1268
1852
|
connectId,
|
|
1269
1853
|
deviceId,
|
|
@@ -1273,14 +1857,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1273
1857
|
);
|
|
1274
1858
|
}
|
|
1275
1859
|
// ---------------------------------------------------------------------------
|
|
1276
|
-
//
|
|
1277
|
-
//
|
|
1278
|
-
|
|
1860
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1861
|
+
// ---------------------------------------------------------------------------
|
|
1862
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1863
|
+
return this.callChainWithMergedParams(
|
|
1864
|
+
connectId,
|
|
1865
|
+
deviceId,
|
|
1866
|
+
"zcash",
|
|
1867
|
+
"zcashGetFullViewingKey",
|
|
1868
|
+
params
|
|
1869
|
+
);
|
|
1870
|
+
}
|
|
1871
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1872
|
+
return this.callChainWithMergedParams(
|
|
1873
|
+
connectId,
|
|
1874
|
+
deviceId,
|
|
1875
|
+
"zcash",
|
|
1876
|
+
"zcashGetShieldedAddress",
|
|
1877
|
+
params
|
|
1878
|
+
);
|
|
1879
|
+
}
|
|
1880
|
+
// ---------------------------------------------------------------------------
|
|
1881
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1279
1882
|
// ---------------------------------------------------------------------------
|
|
1280
1883
|
async installApp(connectId, appName) {
|
|
1281
1884
|
try {
|
|
1282
1885
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1283
|
-
return (0,
|
|
1886
|
+
return (0, import_hwk_adapter_core4.success)(void 0);
|
|
1284
1887
|
} catch (err) {
|
|
1285
1888
|
return this.errorToFailure(err);
|
|
1286
1889
|
}
|
|
@@ -1288,7 +1891,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1288
1891
|
async listInstalledApps(connectId) {
|
|
1289
1892
|
try {
|
|
1290
1893
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1291
|
-
return (0,
|
|
1894
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1292
1895
|
} catch (err) {
|
|
1293
1896
|
return this.errorToFailure(err);
|
|
1294
1897
|
}
|
|
@@ -1297,7 +1900,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1297
1900
|
async listInstalledNames(connectId) {
|
|
1298
1901
|
try {
|
|
1299
1902
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1300
|
-
return (0,
|
|
1903
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1301
1904
|
} catch (err) {
|
|
1302
1905
|
return this.errorToFailure(err);
|
|
1303
1906
|
}
|
|
@@ -1305,7 +1908,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1305
1908
|
async listAvailableApps(connectId) {
|
|
1306
1909
|
try {
|
|
1307
1910
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1308
|
-
return (0,
|
|
1911
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1309
1912
|
} catch (err) {
|
|
1310
1913
|
return this.errorToFailure(err);
|
|
1311
1914
|
}
|
|
@@ -1313,7 +1916,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1313
1916
|
async getLedgerFirmwareVersion(connectId) {
|
|
1314
1917
|
try {
|
|
1315
1918
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1316
|
-
return (0,
|
|
1919
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1317
1920
|
} catch (err) {
|
|
1318
1921
|
return this.errorToFailure(err);
|
|
1319
1922
|
}
|
|
@@ -1321,7 +1924,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1321
1924
|
async getLedgerDeviceInfo(connectId) {
|
|
1322
1925
|
try {
|
|
1323
1926
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1324
|
-
return (0,
|
|
1927
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1325
1928
|
} catch (err) {
|
|
1326
1929
|
return this.errorToFailure(err);
|
|
1327
1930
|
}
|
|
@@ -1355,28 +1958,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1355
1958
|
try {
|
|
1356
1959
|
if (relayUrl) {
|
|
1357
1960
|
if (!this.connector.configure) {
|
|
1358
|
-
return (0,
|
|
1359
|
-
|
|
1961
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1962
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1360
1963
|
"This Ledger connector does not support genuine-check relay configuration"
|
|
1361
1964
|
);
|
|
1362
1965
|
}
|
|
1363
1966
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1364
|
-
this.
|
|
1967
|
+
await this._resetStateAndDisconnectSessions();
|
|
1365
1968
|
}
|
|
1366
1969
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1367
1970
|
if (!result.isGenuine) {
|
|
1368
|
-
return (0,
|
|
1971
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1369
1972
|
vendor: "ledger",
|
|
1370
1973
|
verified: false
|
|
1371
1974
|
});
|
|
1372
1975
|
}
|
|
1373
1976
|
if (!result.deviceId) {
|
|
1374
|
-
return (0,
|
|
1375
|
-
|
|
1977
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1978
|
+
import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1376
1979
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1377
1980
|
);
|
|
1378
1981
|
}
|
|
1379
|
-
return (0,
|
|
1982
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1380
1983
|
vendor: "ledger",
|
|
1381
1984
|
verified: result.isGenuine,
|
|
1382
1985
|
deviceId: result.deviceId
|
|
@@ -1387,10 +1990,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1387
1990
|
if (relayUrl) {
|
|
1388
1991
|
try {
|
|
1389
1992
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1390
|
-
this.
|
|
1993
|
+
await this._resetStateAndDisconnectSessions();
|
|
1391
1994
|
} catch {
|
|
1392
1995
|
this.connector.reset();
|
|
1393
|
-
this.
|
|
1996
|
+
await this._resetStateAndDisconnectSessions();
|
|
1394
1997
|
}
|
|
1395
1998
|
}
|
|
1396
1999
|
}
|
|
@@ -1402,8 +2005,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1402
2005
|
this.emitter.off(event, listener);
|
|
1403
2006
|
}
|
|
1404
2007
|
cancel(connectId) {
|
|
2008
|
+
const namedOperationIsLive = (id) => {
|
|
2009
|
+
try {
|
|
2010
|
+
this._operations.resolve(id);
|
|
2011
|
+
return true;
|
|
2012
|
+
} catch {
|
|
2013
|
+
return false;
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
|
|
2017
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
2018
|
+
connectId
|
|
2019
|
+
});
|
|
2020
|
+
return;
|
|
2021
|
+
}
|
|
1405
2022
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1406
|
-
code:
|
|
2023
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1407
2024
|
_tag: ERROR_TAG.UserAborted
|
|
1408
2025
|
});
|
|
1409
2026
|
this._lastCancelReason = userAbortReason;
|
|
@@ -1412,60 +2029,161 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1412
2029
|
this._lastCancelReason = void 0;
|
|
1413
2030
|
}
|
|
1414
2031
|
}, 2e3);
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
if (connectId) {
|
|
1422
|
-
const sessionId = this._sessions.get(connectId) ?? connectId;
|
|
1423
|
-
void this.connector.cancel(sessionId);
|
|
1424
|
-
} else {
|
|
1425
|
-
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
2032
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
2033
|
+
let operationId;
|
|
2034
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
|
|
2035
|
+
operationId = connectId;
|
|
2036
|
+
} else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
|
|
2037
|
+
operationId = activeJobId;
|
|
1426
2038
|
}
|
|
1427
|
-
|
|
2039
|
+
let resolvedConnectId = connectId;
|
|
2040
|
+
if (operationId) {
|
|
2041
|
+
try {
|
|
2042
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2043
|
+
} catch {
|
|
2044
|
+
resolvedConnectId = void 0;
|
|
2045
|
+
}
|
|
2046
|
+
}
|
|
2047
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2048
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2049
|
+
if (!connectId) {
|
|
2050
|
+
this._uiRegistry.cancel();
|
|
2051
|
+
} else if (pendingOperationId) {
|
|
2052
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2053
|
+
}
|
|
2054
|
+
this._finishBleBinding("cancelled");
|
|
2055
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2056
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2057
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2058
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2059
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2060
|
+
if (queueKeys.size) {
|
|
2061
|
+
let cancelledAnyJob = false;
|
|
2062
|
+
for (const key of queueKeys) {
|
|
2063
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2064
|
+
}
|
|
2065
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2066
|
+
queueKeys: [...queueKeys],
|
|
2067
|
+
cancelledAnyJob
|
|
2068
|
+
});
|
|
2069
|
+
} else {
|
|
2070
|
+
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
2071
|
+
}
|
|
2072
|
+
if (resolvedConnectId) {
|
|
2073
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
2074
|
+
void this.connector.cancel(sessionId);
|
|
2075
|
+
} else {
|
|
2076
|
+
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
2077
|
+
}
|
|
2078
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2079
|
+
const targetKeys = new Set(
|
|
2080
|
+
[
|
|
2081
|
+
connectId,
|
|
2082
|
+
resolvedConnectId,
|
|
2083
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2084
|
+
].filter(Boolean)
|
|
2085
|
+
);
|
|
2086
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2087
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
1428
2088
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1429
2089
|
}
|
|
2090
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1430
2091
|
}
|
|
1431
2092
|
// ---------------------------------------------------------------------------
|
|
1432
2093
|
// Chain fingerprint
|
|
1433
2094
|
// ---------------------------------------------------------------------------
|
|
2095
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1434
2096
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1435
2097
|
try {
|
|
1436
2098
|
const fingerprint = await this._computeChainFingerprint(
|
|
1437
2099
|
chain,
|
|
1438
2100
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1439
2101
|
);
|
|
1440
|
-
|
|
2102
|
+
if (deviceId) {
|
|
2103
|
+
if (fingerprint !== deviceId) {
|
|
2104
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
2105
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2106
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2107
|
+
);
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1441
2111
|
} catch (err) {
|
|
1442
2112
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1443
2113
|
return this.errorToFailure(err);
|
|
1444
2114
|
}
|
|
1445
2115
|
}
|
|
1446
2116
|
/**
|
|
1447
|
-
*
|
|
1448
|
-
*
|
|
2117
|
+
* Fingerprints the first recorded chain whose app the device can open. Only a missing app
|
|
2118
|
+
* moves on to the next chain; when every app is missing, the first chain offers its install.
|
|
1449
2119
|
*/
|
|
1450
|
-
async
|
|
1451
|
-
|
|
2120
|
+
async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
|
|
2121
|
+
const [first] = identities;
|
|
2122
|
+
if (identities.length > 1) {
|
|
2123
|
+
for (const identity of identities) {
|
|
2124
|
+
try {
|
|
2125
|
+
return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
|
|
2126
|
+
} catch (error) {
|
|
2127
|
+
const isAppMissing = isAppNotInstalledError(error) || error?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
2128
|
+
if (!isAppMissing) throw error;
|
|
2129
|
+
}
|
|
2130
|
+
}
|
|
2131
|
+
}
|
|
2132
|
+
return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
|
|
2133
|
+
}
|
|
2134
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2135
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1452
2136
|
try {
|
|
1453
|
-
const
|
|
1454
|
-
|
|
1455
|
-
|
|
2137
|
+
const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
|
|
2138
|
+
this.emitter,
|
|
2139
|
+
this._uiRegistry,
|
|
2140
|
+
{
|
|
2141
|
+
selectionRequestId,
|
|
2142
|
+
connection: { transport: "ble", connectId },
|
|
2143
|
+
...identity ? { identity } : {},
|
|
2144
|
+
extra: context?.extra,
|
|
2145
|
+
operationId
|
|
2146
|
+
},
|
|
2147
|
+
signal
|
|
1456
2148
|
);
|
|
1457
|
-
if (
|
|
1458
|
-
|
|
2149
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2150
|
+
if (!outcome.saved) {
|
|
2151
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2152
|
+
connectId,
|
|
2153
|
+
reason: outcome.reason
|
|
2154
|
+
});
|
|
1459
2155
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
2156
|
+
} catch (error) {
|
|
2157
|
+
await this._dropSession(connectId, signal);
|
|
2158
|
+
throw error;
|
|
2159
|
+
} finally {
|
|
2160
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2161
|
+
this._bindingSelectionRequestId = void 0;
|
|
1465
2162
|
}
|
|
1466
|
-
throw err;
|
|
1467
2163
|
}
|
|
1468
2164
|
}
|
|
2165
|
+
async _dropSession(connectId, signal) {
|
|
2166
|
+
const sessionId = this._sessions.get(connectId);
|
|
2167
|
+
this._sessions.delete(connectId);
|
|
2168
|
+
if (!sessionId) return;
|
|
2169
|
+
this._sessionTransports.delete(sessionId);
|
|
2170
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2171
|
+
() => void 0
|
|
2172
|
+
);
|
|
2173
|
+
if (!signal.aborted) await teardown;
|
|
2174
|
+
}
|
|
2175
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2176
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2177
|
+
if (!deviceId) return { success: true };
|
|
2178
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2179
|
+
chain,
|
|
2180
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2181
|
+
);
|
|
2182
|
+
if (fingerprint === deviceId) {
|
|
2183
|
+
return { success: true };
|
|
2184
|
+
}
|
|
2185
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2186
|
+
}
|
|
1469
2187
|
/**
|
|
1470
2188
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1471
2189
|
*
|
|
@@ -1485,7 +2203,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1485
2203
|
const result = await callMethod("btcGetMasterFingerprint", {});
|
|
1486
2204
|
return result.masterFingerprint;
|
|
1487
2205
|
}
|
|
1488
|
-
const path =
|
|
2206
|
+
const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
|
|
1489
2207
|
let address;
|
|
1490
2208
|
if (chain === "evm") {
|
|
1491
2209
|
address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
|
|
@@ -1493,10 +2211,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1493
2211
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1494
2212
|
} else if (chain === "tron") {
|
|
1495
2213
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2214
|
+
} else if (chain === "zcash") {
|
|
2215
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1496
2216
|
} else {
|
|
1497
2217
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1498
2218
|
}
|
|
1499
|
-
return (0,
|
|
2219
|
+
return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
|
|
2220
|
+
}
|
|
2221
|
+
/**
|
|
2222
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2223
|
+
* Undefined at cold start when no operation owns the job.
|
|
2224
|
+
*/
|
|
2225
|
+
_activeOperationId() {
|
|
2226
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
1500
2227
|
}
|
|
1501
2228
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1502
2229
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
@@ -1507,22 +2234,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1507
2234
|
if (signal?.aborted) {
|
|
1508
2235
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1509
2236
|
}
|
|
2237
|
+
const operationId = this._activeOperationId();
|
|
1510
2238
|
const waitPromise = this._uiRegistry.wait(
|
|
1511
|
-
|
|
2239
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2240
|
+
{ operationId }
|
|
1512
2241
|
);
|
|
1513
|
-
this.emitter.emit(
|
|
1514
|
-
type:
|
|
2242
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
2243
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1515
2244
|
payload: {
|
|
1516
2245
|
vendor: "ledger",
|
|
1517
2246
|
reason: "device-not-found",
|
|
1518
|
-
message: "Please connect and unlock your Ledger device"
|
|
2247
|
+
message: "Please connect and unlock your Ledger device",
|
|
2248
|
+
operationId
|
|
1519
2249
|
}
|
|
1520
2250
|
});
|
|
1521
2251
|
let payload;
|
|
1522
2252
|
try {
|
|
1523
2253
|
if (signal) {
|
|
1524
2254
|
const onAbort = () => {
|
|
1525
|
-
this._uiRegistry.cancel(
|
|
2255
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
|
|
1526
2256
|
};
|
|
1527
2257
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
1528
2258
|
try {
|
|
@@ -1534,20 +2264,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1534
2264
|
payload = await waitPromise;
|
|
1535
2265
|
}
|
|
1536
2266
|
} catch (err) {
|
|
1537
|
-
this.emitter.emit(
|
|
1538
|
-
type:
|
|
2267
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2268
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1539
2269
|
payload: {}
|
|
1540
2270
|
});
|
|
1541
2271
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1542
2272
|
_tag: ERROR_TAG.UserAborted,
|
|
1543
|
-
code:
|
|
2273
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1544
2274
|
cause: err
|
|
1545
2275
|
});
|
|
1546
2276
|
}
|
|
1547
2277
|
if (!payload?.confirmed) {
|
|
1548
2278
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1549
2279
|
_tag: ERROR_TAG.UserAborted,
|
|
1550
|
-
code:
|
|
2280
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1551
2281
|
});
|
|
1552
2282
|
}
|
|
1553
2283
|
await new Promise((resolve) => {
|
|
@@ -1561,7 +2291,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1561
2291
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1562
2292
|
* promoted), or `null` if the user declined.
|
|
1563
2293
|
*/
|
|
1564
|
-
async _gateBtcHighIndex(params) {
|
|
2294
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1565
2295
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1566
2296
|
if (params.showOnDevice) return params;
|
|
1567
2297
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1570,50 +2300,74 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1570
2300
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1571
2301
|
return { ...params, showOnDevice: true };
|
|
1572
2302
|
}
|
|
1573
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2303
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1574
2304
|
if (!confirmed) return null;
|
|
1575
2305
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1576
2306
|
return { ...params, showOnDevice: true };
|
|
1577
2307
|
}
|
|
1578
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2308
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2309
|
+
const operationId = this._activeOperationId();
|
|
1579
2310
|
const waitPromise = this._uiRegistry.wait(
|
|
1580
|
-
|
|
2311
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2312
|
+
{ operationId }
|
|
1581
2313
|
);
|
|
1582
|
-
this.emitter.emit(
|
|
1583
|
-
type:
|
|
2314
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
2315
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1584
2316
|
payload: {
|
|
1585
2317
|
vendor: "ledger",
|
|
1586
2318
|
path,
|
|
1587
|
-
accountIndex
|
|
2319
|
+
accountIndex,
|
|
2320
|
+
operationId
|
|
1588
2321
|
}
|
|
1589
2322
|
});
|
|
1590
2323
|
try {
|
|
1591
|
-
const payload = await
|
|
2324
|
+
const payload = await this._awaitUiAnswer(
|
|
2325
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2326
|
+
waitPromise,
|
|
2327
|
+
signal
|
|
2328
|
+
);
|
|
1592
2329
|
return !!payload?.confirmed;
|
|
1593
2330
|
} catch (err) {
|
|
1594
|
-
this.emitter.emit(
|
|
1595
|
-
type:
|
|
2331
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2332
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1596
2333
|
payload: {}
|
|
1597
2334
|
});
|
|
1598
2335
|
return false;
|
|
1599
2336
|
}
|
|
1600
2337
|
}
|
|
2338
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2339
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2340
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2341
|
+
if (signal.aborted) onAbort();
|
|
2342
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2343
|
+
try {
|
|
2344
|
+
return await waitPromise;
|
|
2345
|
+
} finally {
|
|
2346
|
+
signal.removeEventListener("abort", onAbort);
|
|
2347
|
+
}
|
|
2348
|
+
}
|
|
1601
2349
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1602
2350
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1603
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2351
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2352
|
+
const operationId = this._activeOperationId();
|
|
1604
2353
|
const waitPromise = this._uiRegistry.wait(
|
|
1605
|
-
|
|
2354
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2355
|
+
{ operationId }
|
|
1606
2356
|
);
|
|
1607
|
-
this.emitter.emit(
|
|
1608
|
-
type:
|
|
1609
|
-
payload: { vendor: "ledger", appName }
|
|
2357
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
2358
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2359
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1610
2360
|
});
|
|
1611
2361
|
try {
|
|
1612
|
-
const payload = await
|
|
2362
|
+
const payload = await this._awaitUiAnswer(
|
|
2363
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2364
|
+
waitPromise,
|
|
2365
|
+
signal
|
|
2366
|
+
);
|
|
1613
2367
|
return !!payload?.confirmed;
|
|
1614
2368
|
} catch (err) {
|
|
1615
|
-
this.emitter.emit(
|
|
1616
|
-
type:
|
|
2369
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2370
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1617
2371
|
payload: {}
|
|
1618
2372
|
});
|
|
1619
2373
|
return false;
|
|
@@ -1622,34 +2376,45 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1622
2376
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1623
2377
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1624
2378
|
// doesn't kill caller B's await.
|
|
1625
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2379
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1626
2380
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1627
|
-
|
|
2381
|
+
this._assertConnectorReady("connectDevice");
|
|
2382
|
+
if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1628
2383
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1629
|
-
code:
|
|
2384
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1630
2385
|
});
|
|
1631
2386
|
}
|
|
1632
2387
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1633
2388
|
if (!connectId && this._sessions.size > 0) {
|
|
1634
|
-
if (!
|
|
2389
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1635
2390
|
throw Object.assign(
|
|
1636
2391
|
new Error(
|
|
1637
2392
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
1638
2393
|
),
|
|
1639
|
-
{ code:
|
|
2394
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
|
|
1640
2395
|
);
|
|
1641
2396
|
}
|
|
1642
2397
|
return this._sessions.keys().next().value;
|
|
1643
2398
|
}
|
|
1644
|
-
if (!this._connectingPromise) {
|
|
1645
|
-
|
|
1646
|
-
|
|
2399
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2400
|
+
const controller = new AbortController();
|
|
2401
|
+
this._doConnectAbortController = controller;
|
|
2402
|
+
const innerSignal = controller.signal;
|
|
1647
2403
|
this._connectingPromise = (async () => {
|
|
1648
2404
|
try {
|
|
1649
|
-
return await this._doConnect(
|
|
2405
|
+
return await this._doConnect(
|
|
2406
|
+
innerSignal,
|
|
2407
|
+
connectId,
|
|
2408
|
+
allowUsbEphemeralFallback,
|
|
2409
|
+
preserveOperationId,
|
|
2410
|
+
context
|
|
2411
|
+
);
|
|
1650
2412
|
} finally {
|
|
1651
|
-
this.
|
|
1652
|
-
|
|
2413
|
+
if (this._doConnectAbortController === controller) {
|
|
2414
|
+
this._connectingPromise = null;
|
|
2415
|
+
this._doConnectAbortController = null;
|
|
2416
|
+
if (this._sessions.size === 0) this._activeConnectionType = void 0;
|
|
2417
|
+
}
|
|
1653
2418
|
}
|
|
1654
2419
|
})();
|
|
1655
2420
|
}
|
|
@@ -1658,45 +2423,83 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1658
2423
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1659
2424
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1660
2425
|
// 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
|
-
|
|
2426
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2427
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2428
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2429
|
+
this._activeConnectionType = "usb";
|
|
2430
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2431
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2432
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2433
|
+
(connection) => connection.transport === "usb"
|
|
2434
|
+
);
|
|
2435
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2436
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
|
|
2437
|
+
return this._connectFirstOrSelect(
|
|
2438
|
+
usbDevices,
|
|
2439
|
+
usbTarget,
|
|
2440
|
+
allowUsbEphemeralFallback,
|
|
2441
|
+
preserveOperationId,
|
|
2442
|
+
context,
|
|
2443
|
+
internalSignal
|
|
2444
|
+
);
|
|
2445
|
+
}
|
|
2446
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2447
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2448
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2449
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2450
|
+
});
|
|
2451
|
+
}
|
|
2452
|
+
this._activeConnectionType = "ble";
|
|
2453
|
+
const knownBle = context?.knownConnections?.find(
|
|
2454
|
+
(connection) => connection.transport === "ble"
|
|
2455
|
+
);
|
|
2456
|
+
if (knownBle?.transport === "ble") {
|
|
2457
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
1676
2458
|
}
|
|
2459
|
+
const bleContext = context ?? {};
|
|
2460
|
+
bleContext.allowBleSelection = true;
|
|
2461
|
+
bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
|
|
2462
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2463
|
+
return this._connectFirstOrSelect(
|
|
2464
|
+
bleDevices,
|
|
2465
|
+
void 0,
|
|
2466
|
+
allowUsbEphemeralFallback,
|
|
2467
|
+
preserveOperationId,
|
|
2468
|
+
bleContext,
|
|
2469
|
+
internalSignal
|
|
2470
|
+
);
|
|
2471
|
+
}
|
|
2472
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2473
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1677
2474
|
}
|
|
1678
2475
|
let confirms = 0;
|
|
1679
2476
|
while (!internalSignal.aborted) {
|
|
1680
2477
|
this.emitter.emit("ui-event", {
|
|
1681
|
-
type:
|
|
2478
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
|
|
1682
2479
|
payload: { sessionId: "" }
|
|
1683
2480
|
});
|
|
1684
|
-
let devices = await this.
|
|
2481
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2482
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1685
2483
|
if (devices.length === 0) {
|
|
1686
2484
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1687
2485
|
await new Promise((resolve) => {
|
|
1688
|
-
setTimeout(resolve,
|
|
2486
|
+
setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1689
2487
|
});
|
|
1690
|
-
|
|
2488
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2489
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2490
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1691
2491
|
if (devices.length > 0) break;
|
|
1692
2492
|
}
|
|
1693
2493
|
}
|
|
1694
|
-
if (devices.length > 0) {
|
|
2494
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1695
2495
|
try {
|
|
1696
2496
|
return await this._connectFirstOrSelect(
|
|
1697
2497
|
devices,
|
|
1698
2498
|
targetConnectId,
|
|
1699
|
-
allowUsbEphemeralFallback
|
|
2499
|
+
allowUsbEphemeralFallback,
|
|
2500
|
+
preserveOperationId,
|
|
2501
|
+
context,
|
|
2502
|
+
internalSignal
|
|
1700
2503
|
);
|
|
1701
2504
|
} catch (err) {
|
|
1702
2505
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1716,7 +2519,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1716
2519
|
new Error(
|
|
1717
2520
|
"Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
|
|
1718
2521
|
),
|
|
1719
|
-
{ code:
|
|
2522
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
|
|
1720
2523
|
);
|
|
1721
2524
|
}
|
|
1722
2525
|
await this._waitForDeviceConnect(internalSignal);
|
|
@@ -1725,45 +2528,148 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1725
2528
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1726
2529
|
throw new Error("_doConnect aborted");
|
|
1727
2530
|
}
|
|
1728
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2531
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2532
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1729
2533
|
if (targetConnectId) {
|
|
1730
2534
|
const target = devices.find(
|
|
1731
2535
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1732
2536
|
);
|
|
1733
2537
|
if (target) {
|
|
1734
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2538
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1735
2539
|
}
|
|
1736
|
-
if (!
|
|
2540
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1737
2541
|
debugLog(
|
|
1738
2542
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1739
2543
|
);
|
|
1740
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2544
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1741
2545
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2546
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2547
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2548
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2549
|
+
});
|
|
2550
|
+
if (this._isBleConnection()) {
|
|
2551
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2552
|
+
}
|
|
2553
|
+
throw err;
|
|
1747
2554
|
}
|
|
1748
|
-
throw err;
|
|
1749
2555
|
}
|
|
1750
|
-
|
|
2556
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2557
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
|
|
1751
2558
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1752
|
-
code:
|
|
2559
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1753
2560
|
});
|
|
1754
2561
|
}
|
|
1755
|
-
if (
|
|
1756
|
-
|
|
2562
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2563
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2564
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2565
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2566
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2567
|
+
(connection) => connection.transport === "usb"
|
|
2568
|
+
);
|
|
2569
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
|
|
2570
|
+
const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
|
|
2571
|
+
const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
|
|
2572
|
+
emitter: this.emitter,
|
|
2573
|
+
registry: this._uiRegistry,
|
|
2574
|
+
signal,
|
|
2575
|
+
allowUsbFallback,
|
|
2576
|
+
scan: async () => {
|
|
2577
|
+
if (allowUsbFallback) {
|
|
2578
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2579
|
+
const candidate = usbDevices.find(
|
|
2580
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2581
|
+
) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2582
|
+
if (candidate) return [candidate];
|
|
2583
|
+
}
|
|
2584
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2585
|
+
},
|
|
2586
|
+
request: {
|
|
2587
|
+
devices,
|
|
2588
|
+
bindingSessionId,
|
|
2589
|
+
context: {
|
|
2590
|
+
kind: "bind-connection",
|
|
2591
|
+
transport: "ble",
|
|
2592
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2593
|
+
},
|
|
2594
|
+
extra: context?.extra,
|
|
2595
|
+
operationId: preserveOperationId
|
|
2596
|
+
}
|
|
2597
|
+
});
|
|
2598
|
+
if (device.connectionType === "usb") {
|
|
2599
|
+
this._activeConnectionType = "usb";
|
|
2600
|
+
if (context) context.selectedConnection = void 0;
|
|
2601
|
+
this._bindingSelectionRequestId = requestId;
|
|
2602
|
+
this._finishBleBinding("cancelled");
|
|
2603
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2604
|
+
}
|
|
2605
|
+
this._bindingSelectionRequestId = requestId;
|
|
2606
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2607
|
+
device.connectId,
|
|
2608
|
+
preserveOperationId,
|
|
2609
|
+
signal
|
|
2610
|
+
);
|
|
2611
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2612
|
+
if (context?.deferBindingSave) {
|
|
2613
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2614
|
+
} else {
|
|
2615
|
+
await this._saveSelectedBleBinding(
|
|
2616
|
+
connected,
|
|
2617
|
+
requestId,
|
|
2618
|
+
context,
|
|
2619
|
+
preserveOperationId,
|
|
2620
|
+
signal
|
|
2621
|
+
);
|
|
2622
|
+
}
|
|
2623
|
+
return connected;
|
|
2624
|
+
}
|
|
2625
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2626
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2627
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2628
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2629
|
+
message: "Select a Ledger device before continuing"
|
|
2630
|
+
});
|
|
2631
|
+
}
|
|
2632
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2633
|
+
const operationId = this._activeOperationId();
|
|
2634
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2635
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2636
|
+
{ requestId, operationId }
|
|
2637
|
+
);
|
|
2638
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2639
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2640
|
+
payload: {
|
|
2641
|
+
devices,
|
|
2642
|
+
requestId,
|
|
2643
|
+
operationId,
|
|
2644
|
+
context: requiresBleSelection ? {
|
|
2645
|
+
kind: "bind-connection",
|
|
2646
|
+
transport: "ble",
|
|
2647
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2648
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2649
|
+
extra: context?.extra
|
|
2650
|
+
}
|
|
2651
|
+
});
|
|
2652
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2653
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2654
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2655
|
+
if (!selected) {
|
|
2656
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2657
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2658
|
+
});
|
|
2659
|
+
}
|
|
2660
|
+
if (context && requiresBleSelection)
|
|
2661
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2662
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1757
2663
|
}
|
|
1758
2664
|
if (devices.length !== 1) {
|
|
1759
2665
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1760
|
-
code:
|
|
2666
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1761
2667
|
});
|
|
1762
2668
|
}
|
|
1763
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2669
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1764
2670
|
}
|
|
1765
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1766
|
-
const result = await this.
|
|
2671
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2672
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1767
2673
|
if (!result.success) {
|
|
1768
2674
|
const payload = result.payload;
|
|
1769
2675
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1774,16 +2680,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1774
2680
|
}
|
|
1775
2681
|
throw rethrow;
|
|
1776
2682
|
}
|
|
1777
|
-
return
|
|
2683
|
+
return result.payload;
|
|
1778
2684
|
}
|
|
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
2685
|
/**
|
|
1788
2686
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1789
2687
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1795,7 +2693,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1795
2693
|
*/
|
|
1796
2694
|
_unwrapConnectorResult(result) {
|
|
1797
2695
|
if (result.success) return result.payload;
|
|
1798
|
-
throw (0,
|
|
2696
|
+
throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
|
|
1799
2697
|
}
|
|
1800
2698
|
/**
|
|
1801
2699
|
* `connector.call` + result unwrap, optionally raced against an abort
|
|
@@ -1804,33 +2702,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1804
2702
|
* lives in one place.
|
|
1805
2703
|
*/
|
|
1806
2704
|
async _callConnector(sessionId, method, params, signal) {
|
|
1807
|
-
|
|
2705
|
+
this._assertConnectorReady(method);
|
|
2706
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2707
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2708
|
+
let promise;
|
|
2709
|
+
try {
|
|
2710
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2711
|
+
} catch (error) {
|
|
2712
|
+
releaseOperation();
|
|
2713
|
+
throw error;
|
|
2714
|
+
}
|
|
1808
2715
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1809
2716
|
return this._unwrapConnectorResult(result);
|
|
1810
2717
|
}
|
|
2718
|
+
_assertConnectorReady(method) {
|
|
2719
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2720
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2721
|
+
}
|
|
2722
|
+
}
|
|
2723
|
+
_runConnectorTeardown(task) {
|
|
2724
|
+
const previous = this._connectorTeardownTail;
|
|
2725
|
+
let releaseTail = () => void 0;
|
|
2726
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2727
|
+
releaseTail = resolve;
|
|
2728
|
+
});
|
|
2729
|
+
this._pendingConnectorTeardowns += 1;
|
|
2730
|
+
return (async () => {
|
|
2731
|
+
try {
|
|
2732
|
+
await previous;
|
|
2733
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2734
|
+
await task();
|
|
2735
|
+
} finally {
|
|
2736
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2737
|
+
releaseTail();
|
|
2738
|
+
}
|
|
2739
|
+
})();
|
|
2740
|
+
}
|
|
2741
|
+
_waitForConnectorOperationsToDrain() {
|
|
2742
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2743
|
+
return Promise.resolve();
|
|
2744
|
+
}
|
|
2745
|
+
return new Promise((resolve) => {
|
|
2746
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2747
|
+
});
|
|
2748
|
+
}
|
|
2749
|
+
_retainConnectorOperation(key) {
|
|
2750
|
+
this._unsettledConnectorOperations.set(
|
|
2751
|
+
key,
|
|
2752
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2753
|
+
);
|
|
2754
|
+
let released = false;
|
|
2755
|
+
return () => {
|
|
2756
|
+
if (released) return;
|
|
2757
|
+
released = true;
|
|
2758
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2759
|
+
if (remaining > 0) {
|
|
2760
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2761
|
+
} else {
|
|
2762
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2763
|
+
}
|
|
2764
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2765
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2766
|
+
this._connectorIdleWaiters.clear();
|
|
2767
|
+
}
|
|
2768
|
+
};
|
|
2769
|
+
}
|
|
1811
2770
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1812
|
-
|
|
1813
|
-
|
|
2771
|
+
const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
|
|
2772
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2773
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2774
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
|
|
2775
|
+
message: "Conflicting Ledger operation ids",
|
|
2776
|
+
params: {
|
|
2777
|
+
positionalOperationId,
|
|
2778
|
+
commonOperationId: commonParams.operationId
|
|
2779
|
+
}
|
|
2780
|
+
});
|
|
2781
|
+
}
|
|
2782
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2783
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2784
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2785
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2786
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2787
|
+
method,
|
|
2788
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2789
|
+
params: summarizeForLog(params, { method })
|
|
2790
|
+
});
|
|
2791
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1814
2792
|
try {
|
|
1815
2793
|
const result = await this._jobQueue.enqueue(
|
|
1816
2794
|
queueKey,
|
|
1817
|
-
async (signal) =>
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2795
|
+
async (signal) => {
|
|
2796
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2797
|
+
try {
|
|
2798
|
+
return await this._runConnectorCall(
|
|
2799
|
+
effectiveConnectId,
|
|
2800
|
+
method,
|
|
2801
|
+
params,
|
|
2802
|
+
signal,
|
|
2803
|
+
fingerprint,
|
|
2804
|
+
permissionDeviceId,
|
|
2805
|
+
commonParams,
|
|
2806
|
+
installContext ?? {},
|
|
2807
|
+
operationId
|
|
2808
|
+
);
|
|
2809
|
+
} catch (error) {
|
|
2810
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2811
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2812
|
+
let keptBundlePick = false;
|
|
2813
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2814
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2815
|
+
keptBundlePick = true;
|
|
2816
|
+
} else {
|
|
2817
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2818
|
+
this._discardPendingBinding(owner, status);
|
|
2819
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2820
|
+
}
|
|
2821
|
+
}
|
|
2822
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2823
|
+
throw error;
|
|
2824
|
+
} finally {
|
|
2825
|
+
if (operationId) {
|
|
2826
|
+
this._activeOperationJobs.delete(operationId);
|
|
2827
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2828
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2829
|
+
}
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
},
|
|
1827
2833
|
{
|
|
1828
2834
|
label: method,
|
|
1829
2835
|
rejectIfBusy: true,
|
|
1830
2836
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1831
2837
|
}
|
|
1832
2838
|
);
|
|
1833
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2839
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2840
|
+
method,
|
|
2841
|
+
success: true,
|
|
2842
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2843
|
+
});
|
|
1834
2844
|
return result;
|
|
1835
2845
|
} catch (err) {
|
|
1836
2846
|
const e = err;
|
|
@@ -1844,15 +2854,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1844
2854
|
}
|
|
1845
2855
|
});
|
|
1846
2856
|
throw err;
|
|
2857
|
+
} finally {
|
|
2858
|
+
releaseOperationRetention?.();
|
|
1847
2859
|
}
|
|
1848
2860
|
}
|
|
2861
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2862
|
+
_abortReason(signal) {
|
|
2863
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2864
|
+
}
|
|
1849
2865
|
/**
|
|
1850
2866
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1851
2867
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1852
2868
|
*/
|
|
1853
2869
|
_abortable(signal, promise) {
|
|
1854
|
-
const getAbortReason = () =>
|
|
2870
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1855
2871
|
if (signal.aborted) {
|
|
2872
|
+
void promise.catch(() => void 0);
|
|
1856
2873
|
return Promise.reject(getAbortReason());
|
|
1857
2874
|
}
|
|
1858
2875
|
return new Promise((resolve, reject) => {
|
|
@@ -1879,39 +2896,89 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1879
2896
|
}
|
|
1880
2897
|
}
|
|
1881
2898
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1882
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2899
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1883
2900
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2901
|
+
if (!operationId) {
|
|
2902
|
+
await this._ensureDevicePermission(
|
|
2903
|
+
connectId,
|
|
2904
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2905
|
+
signal
|
|
2906
|
+
);
|
|
2907
|
+
}
|
|
1889
2908
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1890
2909
|
let effectiveParams = params;
|
|
1891
2910
|
if (method === "btcGetPublicKey") {
|
|
1892
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2911
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1893
2912
|
if (gatedParams === null) {
|
|
1894
2913
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1895
2914
|
_tag: ERROR_TAG.UserAborted,
|
|
1896
|
-
code:
|
|
2915
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1897
2916
|
});
|
|
1898
2917
|
}
|
|
1899
2918
|
effectiveParams = gatedParams;
|
|
1900
2919
|
}
|
|
1901
2920
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1902
|
-
|
|
1903
|
-
|
|
2921
|
+
let businessCallStarted = false;
|
|
2922
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2923
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2924
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2925
|
+
(connection) => connection.transport === knownTransport
|
|
2926
|
+
);
|
|
2927
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2928
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2929
|
+
const checksWallet = Boolean(
|
|
2930
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2931
|
+
);
|
|
2932
|
+
const connectionAttempt = {
|
|
2933
|
+
...commonParams,
|
|
2934
|
+
deferBindingSave: checksWallet
|
|
2935
|
+
};
|
|
2936
|
+
const bundleConnection = installContext?.connection;
|
|
2937
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2938
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2939
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2940
|
+
message: "Ledger all-network connection ended"
|
|
2941
|
+
});
|
|
2942
|
+
}
|
|
2943
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2944
|
+
preferredConnectId,
|
|
1904
2945
|
signal,
|
|
1905
|
-
allowUsbEphemeralFallback
|
|
2946
|
+
allowUsbEphemeralFallback,
|
|
2947
|
+
void 0,
|
|
2948
|
+
connectionAttempt
|
|
1906
2949
|
);
|
|
2950
|
+
const walletCheck = installContext?.walletCheck;
|
|
2951
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2952
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2953
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2954
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2955
|
+
});
|
|
2956
|
+
}
|
|
1907
2957
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2958
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2959
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2960
|
+
}
|
|
1908
2961
|
if (!sessionId) {
|
|
2962
|
+
if (operationId) {
|
|
2963
|
+
this._operations.end(operationId, "disconnect");
|
|
2964
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2965
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
2966
|
+
message: "Ledger operation connection is no longer active",
|
|
2967
|
+
params: { operationId, reason: "disconnect" }
|
|
2968
|
+
});
|
|
2969
|
+
}
|
|
1909
2970
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1910
2971
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1911
2972
|
});
|
|
1912
2973
|
}
|
|
1913
2974
|
try {
|
|
1914
|
-
|
|
2975
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2976
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2977
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2978
|
+
}
|
|
2979
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2980
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2981
|
+
if (fingerprint && checksWallet) {
|
|
1915
2982
|
const fp = await this._abortable(
|
|
1916
2983
|
signal,
|
|
1917
2984
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1921,14 +2988,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1921
2988
|
)
|
|
1922
2989
|
);
|
|
1923
2990
|
if (!fp.success) {
|
|
2991
|
+
if (pendingBinding) {
|
|
2992
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
2993
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
2994
|
+
}
|
|
2995
|
+
if (operationId) {
|
|
2996
|
+
this._pendingOperationBindings.delete(operationId);
|
|
2997
|
+
this._operations.end(operationId, "explicit");
|
|
2998
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
2999
|
+
}
|
|
1924
3000
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1925
|
-
code:
|
|
3001
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
|
|
1926
3002
|
});
|
|
1927
3003
|
}
|
|
3004
|
+
if (walletCheck) walletCheck.verified = true;
|
|
1928
3005
|
}
|
|
1929
|
-
|
|
3006
|
+
if (pendingBinding && bindingOwner) {
|
|
3007
|
+
bindingOwner.pendingBinding = void 0;
|
|
3008
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
3009
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
3010
|
+
await this._saveSelectedBleBinding(
|
|
3011
|
+
pendingBinding.connectId,
|
|
3012
|
+
pendingBinding.requestId,
|
|
3013
|
+
bindingOwner,
|
|
3014
|
+
operationId,
|
|
3015
|
+
signal,
|
|
3016
|
+
fingerprint && checksWallet ? {
|
|
3017
|
+
vendor: "ledger",
|
|
3018
|
+
type: "chainFingerprint",
|
|
3019
|
+
chain: fingerprint.chain,
|
|
3020
|
+
value: fingerprint.deviceId
|
|
3021
|
+
} : void 0
|
|
3022
|
+
);
|
|
3023
|
+
}
|
|
3024
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
3025
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
3026
|
+
connectId: resolvedConnectId,
|
|
3027
|
+
chain: fingerprint.chain,
|
|
3028
|
+
fingerprint: fingerprint.deviceId
|
|
3029
|
+
});
|
|
3030
|
+
}
|
|
3031
|
+
businessCallStarted = true;
|
|
3032
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3033
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3034
|
+
return result;
|
|
1930
3035
|
} catch (err) {
|
|
1931
3036
|
if (signal.aborted) throw err;
|
|
3037
|
+
if (isLostConnectionError(err)) {
|
|
3038
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3039
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3040
|
+
else {
|
|
3041
|
+
this._sessions.delete(resolvedConnectId);
|
|
3042
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3043
|
+
}
|
|
3044
|
+
const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3045
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
3046
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3047
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
|
|
3048
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
3049
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
|
|
3050
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3051
|
+
});
|
|
3052
|
+
}
|
|
1932
3053
|
const errObj = err;
|
|
1933
3054
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1934
3055
|
message: errObj?.message,
|
|
@@ -1940,8 +3061,66 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1940
3061
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1941
3062
|
isStuckApp: isStuckAppStateError(err)
|
|
1942
3063
|
});
|
|
3064
|
+
const assertSessionCurrent = (message) => {
|
|
3065
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3066
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3067
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
3068
|
+
message
|
|
3069
|
+
});
|
|
3070
|
+
};
|
|
3071
|
+
if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3072
|
+
await this._waitForDeviceConnect(signal);
|
|
3073
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3074
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3075
|
+
return this._runConnectorCall(
|
|
3076
|
+
resolvedConnectId,
|
|
3077
|
+
method,
|
|
3078
|
+
effectiveParams,
|
|
3079
|
+
signal,
|
|
3080
|
+
fingerprint,
|
|
3081
|
+
permissionDeviceId,
|
|
3082
|
+
commonParams,
|
|
3083
|
+
installContext,
|
|
3084
|
+
operationId,
|
|
3085
|
+
lockedRetryBudget - 1
|
|
3086
|
+
);
|
|
3087
|
+
}
|
|
3088
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3089
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3090
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3091
|
+
try {
|
|
3092
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3093
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3094
|
+
return retried;
|
|
3095
|
+
} catch (retryErr) {
|
|
3096
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3097
|
+
if (isLostConnectionError(retryErr)) {
|
|
3098
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3099
|
+
else {
|
|
3100
|
+
this._sessions.delete(resolvedConnectId);
|
|
3101
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3102
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3103
|
+
}
|
|
3104
|
+
const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3105
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3106
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
|
|
3107
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3108
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3109
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3110
|
+
});
|
|
3111
|
+
}
|
|
3112
|
+
throw retryErr;
|
|
3113
|
+
}
|
|
3114
|
+
}
|
|
3115
|
+
if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
|
|
3116
|
+
this._sessions.delete(resolvedConnectId);
|
|
3117
|
+
this._sessionTransports.delete(sessionId);
|
|
3118
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3119
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3120
|
+
throw err;
|
|
3121
|
+
}
|
|
1943
3122
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1944
|
-
const isAppMissing = isAppNotInstalledError(err) || err?.code ===
|
|
3123
|
+
const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
1945
3124
|
if (autoInstallApp && isAppMissing) {
|
|
1946
3125
|
if (installContext?.deviceOutOfMemoryError) {
|
|
1947
3126
|
throw installContext.deviceOutOfMemoryError;
|
|
@@ -1949,30 +3128,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1949
3128
|
const appName = err?.appName ?? mapLedgerError(err).appName;
|
|
1950
3129
|
if (appName) {
|
|
1951
3130
|
if (installContext?.installAttemptedAppNames?.has(appName)) {
|
|
1952
|
-
throw (0,
|
|
1953
|
-
code:
|
|
3131
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3132
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
|
|
1954
3133
|
message: `${appName} install reported success but the app is still missing on device`,
|
|
1955
3134
|
_tag: ERROR_TAG.AppInstallVerifyFailed,
|
|
1956
3135
|
appName
|
|
1957
3136
|
});
|
|
1958
3137
|
}
|
|
1959
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3138
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1960
3139
|
if (!confirmed) {
|
|
1961
|
-
throw (0,
|
|
1962
|
-
code:
|
|
3140
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3141
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1963
3142
|
message: `User declined to install ${appName}`,
|
|
1964
3143
|
_tag: ERROR_TAG.UserAborted,
|
|
1965
3144
|
appName
|
|
1966
3145
|
});
|
|
1967
3146
|
}
|
|
1968
3147
|
this.emitter.emit("ui-event", {
|
|
1969
|
-
type:
|
|
3148
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1970
3149
|
payload: { connectId: resolvedConnectId, appName, progress: 0 }
|
|
1971
3150
|
});
|
|
1972
3151
|
try {
|
|
1973
3152
|
await this._callConnector(sessionId, "installApp", { appName }, signal);
|
|
1974
3153
|
} catch (installErr) {
|
|
1975
|
-
if (mapLedgerError(installErr).code ===
|
|
3154
|
+
if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
|
|
1976
3155
|
if (installContext) {
|
|
1977
3156
|
installContext.deviceOutOfMemoryError = installErr;
|
|
1978
3157
|
}
|
|
@@ -1983,8 +3162,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1983
3162
|
installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
|
|
1984
3163
|
installContext.installAttemptedAppNames.add(appName);
|
|
1985
3164
|
}
|
|
1986
|
-
this.emitter.emit(
|
|
1987
|
-
type:
|
|
3165
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3166
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1988
3167
|
payload: {}
|
|
1989
3168
|
});
|
|
1990
3169
|
return await this._runConnectorCall(
|
|
@@ -1995,157 +3174,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1995
3174
|
fingerprint,
|
|
1996
3175
|
permissionDeviceId,
|
|
1997
3176
|
commonParams,
|
|
1998
|
-
installContext
|
|
1999
|
-
|
|
2000
|
-
}
|
|
2001
|
-
}
|
|
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
|
|
3177
|
+
installContext,
|
|
3178
|
+
operationId
|
|
2025
3179
|
);
|
|
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
3180
|
}
|
|
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
3181
|
}
|
|
2112
3182
|
throw err;
|
|
2113
3183
|
}
|
|
2114
3184
|
}
|
|
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
3185
|
_sleepAbortable(ms, signal) {
|
|
2150
3186
|
return new Promise((resolve, reject) => {
|
|
2151
3187
|
if (signal.aborted) {
|
|
@@ -2164,115 +3200,26 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2164
3200
|
});
|
|
2165
3201
|
}
|
|
2166
3202
|
/**
|
|
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
|
|
3203
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3204
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2259
3205
|
*/
|
|
2260
3206
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2261
3207
|
if (signal?.aborted) {
|
|
2262
3208
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2263
3209
|
}
|
|
2264
3210
|
const transportType = this.activeTransport ?? "hid";
|
|
3211
|
+
const operationId = this._activeOperationId();
|
|
2265
3212
|
const waitPromise = this._uiRegistry.wait(
|
|
2266
|
-
|
|
2267
|
-
{ timeoutMs: 6e4 }
|
|
3213
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3214
|
+
{ timeoutMs: 6e4, operationId }
|
|
2268
3215
|
);
|
|
2269
|
-
this.emitter.emit(
|
|
2270
|
-
type:
|
|
2271
|
-
payload: { transportType, connectId, deviceId }
|
|
3216
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
3217
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3218
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2272
3219
|
});
|
|
2273
3220
|
let response;
|
|
2274
3221
|
const onAbort = () => {
|
|
2275
|
-
this._uiRegistry.cancel(
|
|
3222
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
|
|
2276
3223
|
};
|
|
2277
3224
|
try {
|
|
2278
3225
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -2281,14 +3228,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2281
3228
|
if (signal?.aborted) {
|
|
2282
3229
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2283
3230
|
}
|
|
2284
|
-
if (err?._tag ===
|
|
2285
|
-
this.emitter.emit(
|
|
2286
|
-
type:
|
|
3231
|
+
if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
|
|
3232
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3233
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2287
3234
|
payload: {}
|
|
2288
3235
|
});
|
|
2289
3236
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2290
3237
|
_tag: ERROR_TAG.UserAborted,
|
|
2291
|
-
code:
|
|
3238
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
2292
3239
|
cause: err
|
|
2293
3240
|
});
|
|
2294
3241
|
}
|
|
@@ -2299,7 +3246,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2299
3246
|
const { granted, reason, message } = response;
|
|
2300
3247
|
if (!granted) {
|
|
2301
3248
|
throw Object.assign(new Error(message ?? "Device permission denied"), {
|
|
2302
|
-
code:
|
|
3249
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
|
|
2303
3250
|
reason
|
|
2304
3251
|
});
|
|
2305
3252
|
}
|
|
@@ -2313,8 +3260,16 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2313
3260
|
const tag = err && typeof err === "object" ? err._tag : void 0;
|
|
2314
3261
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2315
3262
|
const e = err;
|
|
2316
|
-
const params = e.code ===
|
|
2317
|
-
return ledgerFailure(
|
|
3263
|
+
const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
3264
|
+
return ledgerFailure(
|
|
3265
|
+
e.code,
|
|
3266
|
+
e.message ?? "Unknown error",
|
|
3267
|
+
e.appName,
|
|
3268
|
+
tag,
|
|
3269
|
+
params,
|
|
3270
|
+
void 0,
|
|
3271
|
+
(0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
|
|
3272
|
+
);
|
|
2318
3273
|
}
|
|
2319
3274
|
const mapped = mapLedgerError(err);
|
|
2320
3275
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2341,7 +3296,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2341
3296
|
deviceId: device.deviceId,
|
|
2342
3297
|
connectId: device.connectId,
|
|
2343
3298
|
label: device.name,
|
|
2344
|
-
connectionType: this.connector.connectionType,
|
|
3299
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2345
3300
|
rssi: device.rssi,
|
|
2346
3301
|
isConnectable: device.isConnectable,
|
|
2347
3302
|
serialNumber: device.serialNumber,
|
|
@@ -2639,16 +3594,20 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
|
|
|
2639
3594
|
var import_context_module = require("@ledgerhq/context-module");
|
|
2640
3595
|
|
|
2641
3596
|
// src/signer/SignerEth.ts
|
|
2642
|
-
var
|
|
3597
|
+
var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
|
|
2643
3598
|
|
|
2644
3599
|
// src/signer/deviceActionToPromise.ts
|
|
2645
3600
|
var import_device_management_kit = require("@ledgerhq/device-management-kit");
|
|
2646
3601
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3602
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
3603
|
+
var INTERACTION_PROMPT_DELAY_MS = 500;
|
|
2647
3604
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2648
3605
|
return new Promise((resolve, reject) => {
|
|
2649
3606
|
let settled = false;
|
|
2650
3607
|
let lastStep;
|
|
2651
3608
|
let activeInteraction;
|
|
3609
|
+
let pendingInteraction;
|
|
3610
|
+
let pendingInteractionTimer = null;
|
|
2652
3611
|
const observedSteps = [];
|
|
2653
3612
|
let sub;
|
|
2654
3613
|
let timer = null;
|
|
@@ -2676,31 +3635,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
|
|
|
2676
3635
|
}
|
|
2677
3636
|
return false;
|
|
2678
3637
|
};
|
|
3638
|
+
const cancelPendingInteraction = () => {
|
|
3639
|
+
if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
|
|
3640
|
+
pendingInteractionTimer = null;
|
|
3641
|
+
pendingInteraction = void 0;
|
|
3642
|
+
};
|
|
3643
|
+
const showInteraction = (interactionName) => {
|
|
3644
|
+
activeInteraction = interactionName;
|
|
3645
|
+
debugLog(
|
|
3646
|
+
"[DeviceAction] requiredUserInteraction",
|
|
3647
|
+
`interaction=${interactionName}`,
|
|
3648
|
+
`step=${lastStep ?? "unknown"}`
|
|
3649
|
+
);
|
|
3650
|
+
if (interactionName === "unlock-device" && timer) {
|
|
3651
|
+
clearTimeout(timer);
|
|
3652
|
+
timer = null;
|
|
3653
|
+
}
|
|
3654
|
+
onInteraction?.(interactionName);
|
|
3655
|
+
};
|
|
2679
3656
|
const emitInteraction = (interaction) => {
|
|
2680
3657
|
if (!onInteraction) {
|
|
2681
3658
|
return;
|
|
2682
3659
|
}
|
|
2683
3660
|
if (!interaction || interaction === "none") {
|
|
3661
|
+
cancelPendingInteraction();
|
|
2684
3662
|
clearActiveInteraction();
|
|
2685
3663
|
return;
|
|
2686
3664
|
}
|
|
2687
3665
|
const interactionName = String(interaction);
|
|
2688
|
-
if (interactionName === activeInteraction) {
|
|
3666
|
+
if (interactionName === activeInteraction || interactionName === pendingInteraction) {
|
|
2689
3667
|
return;
|
|
2690
3668
|
}
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
);
|
|
2697
|
-
if (interaction === "unlock-device" && timer) {
|
|
2698
|
-
clearTimeout(timer);
|
|
2699
|
-
timer = null;
|
|
3669
|
+
cancelPendingInteraction();
|
|
3670
|
+
clearActiveInteraction();
|
|
3671
|
+
if (interactionName === "unlock-device") {
|
|
3672
|
+
showInteraction(interactionName);
|
|
3673
|
+
return;
|
|
2700
3674
|
}
|
|
2701
|
-
|
|
3675
|
+
pendingInteraction = interactionName;
|
|
3676
|
+
pendingInteractionTimer = setTimeout(() => {
|
|
3677
|
+
pendingInteractionTimer = null;
|
|
3678
|
+
pendingInteraction = void 0;
|
|
3679
|
+
if (!settled) showInteraction(interactionName);
|
|
3680
|
+
}, INTERACTION_PROMPT_DELAY_MS);
|
|
2702
3681
|
};
|
|
2703
3682
|
const completeInteraction = () => {
|
|
3683
|
+
cancelPendingInteraction();
|
|
2704
3684
|
if (!clearActiveInteraction()) {
|
|
2705
3685
|
onInteraction?.("interaction-complete");
|
|
2706
3686
|
}
|
|
@@ -2831,7 +3811,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2831
3811
|
}
|
|
2832
3812
|
|
|
2833
3813
|
// src/signer/SignerEth.ts
|
|
2834
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2835
3814
|
var SignerEth = class {
|
|
2836
3815
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2837
3816
|
constructor(_sdk) {
|
|
@@ -2852,7 +3831,7 @@ var SignerEth = class {
|
|
|
2852
3831
|
);
|
|
2853
3832
|
}
|
|
2854
3833
|
async signTransaction(derivationPath, serializedTxHex) {
|
|
2855
|
-
const action = this._sdk.signTransaction(derivationPath, (0,
|
|
3834
|
+
const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
|
|
2856
3835
|
return deviceActionToPromise(
|
|
2857
3836
|
action,
|
|
2858
3837
|
this.onInteraction,
|
|
@@ -2861,7 +3840,7 @@ var SignerEth = class {
|
|
|
2861
3840
|
);
|
|
2862
3841
|
}
|
|
2863
3842
|
async signMessage(derivationPath, message) {
|
|
2864
|
-
const action = this._sdk.signMessage(derivationPath, (0,
|
|
3843
|
+
const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
|
|
2865
3844
|
return deviceActionToPromise(
|
|
2866
3845
|
action,
|
|
2867
3846
|
this.onInteraction,
|
|
@@ -2902,7 +3881,7 @@ var SignerManager = class _SignerManager {
|
|
|
2902
3881
|
return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
|
|
2903
3882
|
}
|
|
2904
3883
|
static _createContextModule() {
|
|
2905
|
-
const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3884
|
+
const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2906
3885
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2907
3886
|
}
|
|
2908
3887
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2921,23 +3900,44 @@ var SignerManager = class _SignerManager {
|
|
|
2921
3900
|
};
|
|
2922
3901
|
|
|
2923
3902
|
// src/connector/chains/evm.ts
|
|
2924
|
-
var
|
|
3903
|
+
var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
|
|
2925
3904
|
|
|
2926
3905
|
// src/connector/chains/utils.ts
|
|
2927
|
-
var
|
|
3906
|
+
var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
|
|
2928
3907
|
function normalizePath(path) {
|
|
2929
3908
|
return path.startsWith("m/") ? path.slice(2) : path;
|
|
2930
3909
|
}
|
|
2931
3910
|
function collapseSignerInteraction(interaction) {
|
|
2932
3911
|
switch (interaction) {
|
|
2933
3912
|
case "confirm-open-app":
|
|
2934
|
-
return
|
|
3913
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
|
|
2935
3914
|
case "unlock-device":
|
|
2936
|
-
return
|
|
3915
|
+
return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
|
|
2937
3916
|
case "interaction-complete":
|
|
2938
|
-
return
|
|
3917
|
+
return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
|
|
2939
3918
|
default:
|
|
2940
|
-
return
|
|
3919
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3923
|
+
signer.onInteraction = (interaction) => {
|
|
3924
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3925
|
+
ctx.emit("ui-event", {
|
|
3926
|
+
type: collapseSignerInteraction(interaction),
|
|
3927
|
+
payload: { sessionId }
|
|
3928
|
+
});
|
|
3929
|
+
};
|
|
3930
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3931
|
+
return signer;
|
|
3932
|
+
}
|
|
3933
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3934
|
+
try {
|
|
3935
|
+
return await call();
|
|
3936
|
+
} catch (err) {
|
|
3937
|
+
ctx.invalidateSession(sessionId);
|
|
3938
|
+
throw ctx.wrapError(err);
|
|
3939
|
+
} finally {
|
|
3940
|
+
ctx.clearCanceller(sessionId);
|
|
2941
3941
|
}
|
|
2942
3942
|
}
|
|
2943
3943
|
|
|
@@ -2963,7 +3963,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2963
3963
|
new Error(
|
|
2964
3964
|
"Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
|
|
2965
3965
|
),
|
|
2966
|
-
{ code:
|
|
3966
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
|
|
2967
3967
|
);
|
|
2968
3968
|
}
|
|
2969
3969
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
@@ -2972,8 +3972,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2972
3972
|
const result = await signer.signTransaction(path, params.serializedTx);
|
|
2973
3973
|
return {
|
|
2974
3974
|
v: `0x${result.v.toString(16)}`,
|
|
2975
|
-
r: (0,
|
|
2976
|
-
s: (0,
|
|
3975
|
+
r: (0, import_hwk_adapter_core7.padHex64)(result.r),
|
|
3976
|
+
s: (0, import_hwk_adapter_core7.padHex64)(result.s)
|
|
2977
3977
|
};
|
|
2978
3978
|
} catch (err) {
|
|
2979
3979
|
ctx.invalidateSession(sessionId);
|
|
@@ -2987,8 +3987,8 @@ async function evmSignMessage(ctx, sessionId, params) {
|
|
|
2987
3987
|
const path = normalizePath(params.path);
|
|
2988
3988
|
try {
|
|
2989
3989
|
const result = await signer.signMessage(path, params.message);
|
|
2990
|
-
const rHex = (0,
|
|
2991
|
-
const sHex = (0,
|
|
3990
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3991
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
2992
3992
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
2993
3993
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
2994
3994
|
} catch (err) {
|
|
@@ -3004,15 +4004,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
|
|
|
3004
4004
|
new Error(
|
|
3005
4005
|
'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
|
|
3006
4006
|
),
|
|
3007
|
-
{ code:
|
|
4007
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
|
|
3008
4008
|
);
|
|
3009
4009
|
}
|
|
3010
4010
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
3011
4011
|
const path = normalizePath(params.path);
|
|
3012
4012
|
try {
|
|
3013
4013
|
const result = await signer.signTypedData(path, params.data);
|
|
3014
|
-
const rHex = (0,
|
|
3015
|
-
const sHex = (0,
|
|
4014
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
4015
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
3016
4016
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3017
4017
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
3018
4018
|
} catch (err) {
|
|
@@ -3039,15 +4039,14 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3039
4039
|
}
|
|
3040
4040
|
|
|
3041
4041
|
// src/connector/chains/btc.ts
|
|
3042
|
-
var
|
|
3043
|
-
var
|
|
4042
|
+
var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
|
|
4043
|
+
var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
|
|
3044
4044
|
|
|
3045
4045
|
// src/signer/SignerBtc.ts
|
|
3046
|
-
var
|
|
4046
|
+
var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
|
|
3047
4047
|
function hexToUtf8(hex) {
|
|
3048
|
-
return new TextDecoder().decode((0,
|
|
4048
|
+
return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
|
|
3049
4049
|
}
|
|
3050
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3051
4050
|
var SignerBtc = class {
|
|
3052
4051
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3053
4052
|
constructor(_sdk) {
|
|
@@ -3061,7 +4060,7 @@ var SignerBtc = class {
|
|
|
3061
4060
|
return deviceActionToPromise(
|
|
3062
4061
|
action,
|
|
3063
4062
|
this.onInteraction,
|
|
3064
|
-
void 0,
|
|
4063
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3065
4064
|
this.onRegisterCanceller
|
|
3066
4065
|
);
|
|
3067
4066
|
}
|
|
@@ -3079,14 +4078,14 @@ var SignerBtc = class {
|
|
|
3079
4078
|
const result = await deviceActionToPromise(
|
|
3080
4079
|
action,
|
|
3081
4080
|
this.onInteraction,
|
|
3082
|
-
void 0,
|
|
4081
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3083
4082
|
this.onRegisterCanceller
|
|
3084
4083
|
);
|
|
3085
4084
|
debugLog(
|
|
3086
4085
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3087
4086
|
typeof result,
|
|
3088
4087
|
"value:",
|
|
3089
|
-
|
|
4088
|
+
summarizeForLog(result)
|
|
3090
4089
|
);
|
|
3091
4090
|
if (typeof result === "string") return result;
|
|
3092
4091
|
return result.extendedPublicKey;
|
|
@@ -3115,7 +4114,7 @@ var SignerBtc = class {
|
|
|
3115
4114
|
return deviceActionToPromise(
|
|
3116
4115
|
action,
|
|
3117
4116
|
this.onInteraction,
|
|
3118
|
-
|
|
4117
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3119
4118
|
this.onRegisterCanceller
|
|
3120
4119
|
);
|
|
3121
4120
|
}
|
|
@@ -3128,7 +4127,7 @@ var SignerBtc = class {
|
|
|
3128
4127
|
return deviceActionToPromise(
|
|
3129
4128
|
action,
|
|
3130
4129
|
this.onInteraction,
|
|
3131
|
-
|
|
4130
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3132
4131
|
this.onRegisterCanceller
|
|
3133
4132
|
);
|
|
3134
4133
|
}
|
|
@@ -3141,7 +4140,7 @@ var SignerBtc = class {
|
|
|
3141
4140
|
return deviceActionToPromise(
|
|
3142
4141
|
action,
|
|
3143
4142
|
this.onInteraction,
|
|
3144
|
-
|
|
4143
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3145
4144
|
this.onRegisterCanceller
|
|
3146
4145
|
);
|
|
3147
4146
|
}
|
|
@@ -3160,11 +4159,25 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3160
4159
|
return DDT.TAPROOT;
|
|
3161
4160
|
default:
|
|
3162
4161
|
throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
|
|
3163
|
-
code:
|
|
4162
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3164
4163
|
});
|
|
3165
4164
|
}
|
|
3166
4165
|
}
|
|
4166
|
+
function assertBitcoinMainnet(coin) {
|
|
4167
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4168
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4169
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
|
|
4170
|
+
});
|
|
4171
|
+
}
|
|
4172
|
+
}
|
|
3167
4173
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4174
|
+
assertBitcoinMainnet(params.coin);
|
|
4175
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4176
|
+
throw Object.assign(
|
|
4177
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4178
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
4179
|
+
);
|
|
4180
|
+
}
|
|
3168
4181
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3169
4182
|
const path = normalizePath(params.path);
|
|
3170
4183
|
try {
|
|
@@ -3195,6 +4208,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3195
4208
|
}
|
|
3196
4209
|
}
|
|
3197
4210
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4211
|
+
assertBitcoinMainnet(params.coin);
|
|
3198
4212
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3199
4213
|
const path = normalizePath(params.path);
|
|
3200
4214
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3202,7 +4216,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3202
4216
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3203
4217
|
checkOnDevice: params.showOnDevice ?? false
|
|
3204
4218
|
});
|
|
3205
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4219
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3206
4220
|
return { xpub, path: params.path };
|
|
3207
4221
|
} catch (err) {
|
|
3208
4222
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3216,7 +4230,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3216
4230
|
if (!params.psbt) {
|
|
3217
4231
|
throw Object.assign(
|
|
3218
4232
|
new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
|
|
3219
|
-
{ code:
|
|
4233
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
3220
4234
|
);
|
|
3221
4235
|
}
|
|
3222
4236
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3230,7 +4244,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3230
4244
|
debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
|
|
3231
4245
|
const wallet = new DefaultWallet(path, template);
|
|
3232
4246
|
const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
|
|
3233
|
-
return { serializedTx: (0,
|
|
4247
|
+
return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
|
|
3234
4248
|
} catch (err) {
|
|
3235
4249
|
ctx.invalidateSession(sessionId);
|
|
3236
4250
|
throw ctx.wrapError(err);
|
|
@@ -3241,7 +4255,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3241
4255
|
async function btcSignPsbt(ctx, sessionId, params) {
|
|
3242
4256
|
if (!params.psbt) {
|
|
3243
4257
|
throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
|
|
3244
|
-
code:
|
|
4258
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3245
4259
|
});
|
|
3246
4260
|
}
|
|
3247
4261
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3271,8 +4285,8 @@ async function btcSignMessage(ctx, sessionId, params) {
|
|
|
3271
4285
|
try {
|
|
3272
4286
|
const result = await btcSigner.signMessage(path, params.message);
|
|
3273
4287
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3274
|
-
const rHex = (0,
|
|
3275
|
-
const sHex = (0,
|
|
4288
|
+
const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
|
|
4289
|
+
const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
|
|
3276
4290
|
return { signature: `${vHex}${rHex}${sHex}` };
|
|
3277
4291
|
} catch (err) {
|
|
3278
4292
|
ctx.invalidateSession(sessionId);
|
|
@@ -3323,7 +4337,7 @@ function _isScriptPathInput(input) {
|
|
|
3323
4337
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3324
4338
|
}
|
|
3325
4339
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3326
|
-
const psbt =
|
|
4340
|
+
const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
|
|
3327
4341
|
for (const sig of signatures) {
|
|
3328
4342
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3329
4343
|
if (!input) {
|
|
@@ -3372,7 +4386,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3372
4386
|
}
|
|
3373
4387
|
|
|
3374
4388
|
// src/connector/chains/sol.ts
|
|
3375
|
-
var
|
|
4389
|
+
var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
|
|
4390
|
+
var import_bs58 = __toESM(require("bs58"));
|
|
3376
4391
|
|
|
3377
4392
|
// src/signer/SignerSol.ts
|
|
3378
4393
|
var SignerSol = class {
|
|
@@ -3390,7 +4405,7 @@ var SignerSol = class {
|
|
|
3390
4405
|
return deviceActionToPromise(
|
|
3391
4406
|
action,
|
|
3392
4407
|
this.onInteraction,
|
|
3393
|
-
void 0,
|
|
4408
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3394
4409
|
this.onRegisterCanceller
|
|
3395
4410
|
);
|
|
3396
4411
|
}
|
|
@@ -3402,7 +4417,7 @@ var SignerSol = class {
|
|
|
3402
4417
|
return deviceActionToPromise(
|
|
3403
4418
|
action,
|
|
3404
4419
|
this.onInteraction,
|
|
3405
|
-
|
|
4420
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3406
4421
|
this.onRegisterCanceller
|
|
3407
4422
|
);
|
|
3408
4423
|
}
|
|
@@ -3415,7 +4430,7 @@ var SignerSol = class {
|
|
|
3415
4430
|
return deviceActionToPromise(
|
|
3416
4431
|
action,
|
|
3417
4432
|
this.onInteraction,
|
|
3418
|
-
|
|
4433
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3419
4434
|
this.onRegisterCanceller
|
|
3420
4435
|
);
|
|
3421
4436
|
}
|
|
@@ -3440,10 +4455,10 @@ async function solGetAddress(ctx, sessionId, params) {
|
|
|
3440
4455
|
async function solSignTransaction(ctx, sessionId, params) {
|
|
3441
4456
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3442
4457
|
const path = normalizePath(params.path);
|
|
3443
|
-
const txBytes = (0,
|
|
4458
|
+
const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
|
|
3444
4459
|
try {
|
|
3445
4460
|
const result = await solSigner.signTransaction(path, txBytes);
|
|
3446
|
-
return { signature: (0,
|
|
4461
|
+
return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
|
|
3447
4462
|
} catch (err) {
|
|
3448
4463
|
ctx.invalidateSession(sessionId);
|
|
3449
4464
|
throw ctx.wrapError(err);
|
|
@@ -3454,10 +4469,23 @@ async function solSignTransaction(ctx, sessionId, params) {
|
|
|
3454
4469
|
async function solSignMessage(ctx, sessionId, params) {
|
|
3455
4470
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3456
4471
|
const path = normalizePath(params.path);
|
|
3457
|
-
const messageBytes = (0,
|
|
4472
|
+
const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
|
|
3458
4473
|
try {
|
|
4474
|
+
if (params.messageVersion === 1) {
|
|
4475
|
+
const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
|
|
4476
|
+
message: messageBytes,
|
|
4477
|
+
requiredSigners: params.requiredSigners
|
|
4478
|
+
});
|
|
4479
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4480
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4481
|
+
);
|
|
4482
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4483
|
+
version: SignMessageVersion.Raw
|
|
4484
|
+
});
|
|
4485
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4486
|
+
}
|
|
3459
4487
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3460
|
-
return { signature: result.signature };
|
|
4488
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3461
4489
|
} catch (err) {
|
|
3462
4490
|
ctx.invalidateSession(sessionId);
|
|
3463
4491
|
throw ctx.wrapError(err);
|
|
@@ -3465,11 +4493,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3465
4493
|
ctx.clearCanceller(sessionId);
|
|
3466
4494
|
}
|
|
3467
4495
|
}
|
|
4496
|
+
function decodeBase58Signature(signature) {
|
|
4497
|
+
const bytes = import_bs58.default.decode(signature);
|
|
4498
|
+
if (bytes.length !== 64) {
|
|
4499
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4500
|
+
}
|
|
4501
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
|
|
4502
|
+
}
|
|
4503
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4504
|
+
const bytes = import_bs58.default.decode(envelope);
|
|
4505
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4506
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4507
|
+
}
|
|
4508
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
|
|
4509
|
+
}
|
|
3468
4510
|
async function _createSolSigner(ctx, sessionId) {
|
|
3469
4511
|
const dmk = await ctx.getOrCreateDmk();
|
|
3470
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4512
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4513
|
+
"@ledgerhq/context-module"
|
|
4514
|
+
);
|
|
3471
4515
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3472
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4516
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3473
4517
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3474
4518
|
const signer = new SignerSol(sdkSigner);
|
|
3475
4519
|
signer.onInteraction = (interaction) => {
|
|
@@ -3485,316 +4529,119 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3485
4529
|
return signer;
|
|
3486
4530
|
}
|
|
3487
4531
|
|
|
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
|
|
4532
|
+
// src/connector/chains/zcash.ts
|
|
3493
4533
|
var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
|
|
3494
4534
|
|
|
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);
|
|
4535
|
+
// src/signer/SignerZcash.ts
|
|
4536
|
+
var SignerZcash = class {
|
|
4537
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4538
|
+
constructor(_sdk) {
|
|
4539
|
+
this._sdk = _sdk;
|
|
3556
4540
|
}
|
|
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
|
-
}
|
|
4541
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4542
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4543
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4544
|
+
return deviceActionToPromise(
|
|
4545
|
+
action,
|
|
4546
|
+
this.onInteraction,
|
|
4547
|
+
void 0,
|
|
4548
|
+
this.onRegisterCanceller
|
|
3593
4549
|
);
|
|
3594
4550
|
}
|
|
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})`
|
|
4551
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4552
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4553
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4554
|
+
return deviceActionToPromise(
|
|
4555
|
+
action,
|
|
4556
|
+
this.onInteraction,
|
|
4557
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4558
|
+
this.onRegisterCanceller
|
|
3657
4559
|
);
|
|
3658
4560
|
}
|
|
3659
|
-
_isDashboard(appName) {
|
|
3660
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3661
|
-
}
|
|
3662
|
-
_wait() {
|
|
3663
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3664
|
-
}
|
|
3665
4561
|
};
|
|
3666
4562
|
|
|
3667
|
-
// src/connector/chains/
|
|
3668
|
-
function
|
|
3669
|
-
|
|
4563
|
+
// src/connector/chains/zcash.ts
|
|
4564
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4565
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4566
|
+
const path = normalizePath(params.path);
|
|
4567
|
+
const mode = params.mode ?? "ufvk";
|
|
4568
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4569
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4570
|
+
if (result.mode === "ufvk") {
|
|
4571
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4572
|
+
}
|
|
4573
|
+
return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
|
|
4574
|
+
});
|
|
3670
4575
|
}
|
|
3671
|
-
async function
|
|
3672
|
-
const
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
|
|
3678
|
-
payload: { sessionId }
|
|
4576
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4577
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4578
|
+
const path = normalizePath(params.path);
|
|
4579
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4580
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4581
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3679
4582
|
});
|
|
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
|
-
}
|
|
4583
|
+
return { address: result.address, path: params.path };
|
|
4584
|
+
});
|
|
3747
4585
|
}
|
|
3748
|
-
async function
|
|
4586
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3749
4587
|
const dmk = await ctx.getOrCreateDmk();
|
|
3750
|
-
const
|
|
3751
|
-
|
|
4588
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4589
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4590
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3752
4591
|
}
|
|
3753
4592
|
|
|
3754
|
-
// src/
|
|
3755
|
-
var
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
4593
|
+
// src/connector/chains/tron.ts
|
|
4594
|
+
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
4595
|
+
|
|
4596
|
+
// src/signer/SignerTron.ts
|
|
4597
|
+
var SignerTron = class {
|
|
4598
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4599
|
+
constructor(_sdk) {
|
|
4600
|
+
this._sdk = _sdk;
|
|
3761
4601
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
}
|
|
3772
|
-
result.set(statusCode, data.length);
|
|
3773
|
-
return result;
|
|
4602
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4603
|
+
async getAddress(derivationPath, options) {
|
|
4604
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4605
|
+
const result = await deviceActionToPromise(
|
|
4606
|
+
action,
|
|
4607
|
+
this.onInteraction,
|
|
4608
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4609
|
+
this.onRegisterCanceller
|
|
4610
|
+
);
|
|
4611
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3774
4612
|
}
|
|
3775
|
-
|
|
4613
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4614
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4615
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4616
|
+
return deviceActionToPromise(
|
|
4617
|
+
action,
|
|
4618
|
+
this.onInteraction,
|
|
4619
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4620
|
+
this.onRegisterCanceller
|
|
4621
|
+
);
|
|
4622
|
+
}
|
|
4623
|
+
/** Sign a personal message (TIP-191). */
|
|
4624
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4625
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4626
|
+
return deviceActionToPromise(
|
|
4627
|
+
action,
|
|
4628
|
+
this.onInteraction,
|
|
4629
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4630
|
+
this.onRegisterCanceller
|
|
4631
|
+
);
|
|
3776
4632
|
}
|
|
3777
4633
|
};
|
|
3778
4634
|
|
|
3779
4635
|
// src/connector/chains/tron.ts
|
|
3780
4636
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4637
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3781
4638
|
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
|
-
);
|
|
4639
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4640
|
+
const result = await tronSigner.getAddress(path, {
|
|
4641
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4642
|
+
});
|
|
4643
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4644
|
+
});
|
|
3798
4645
|
}
|
|
3799
4646
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3800
4647
|
if (!params.rawTxHex) {
|
|
@@ -3803,42 +4650,30 @@ async function tronSignTransaction(ctx, sessionId, params) {
|
|
|
3803
4650
|
{ code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
|
|
3804
4651
|
);
|
|
3805
4652
|
}
|
|
4653
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3806
4654
|
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
|
-
);
|
|
4655
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4656
|
+
const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
|
|
4657
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4658
|
+
});
|
|
3821
4659
|
}
|
|
3822
4660
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4661
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3823
4662
|
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
|
-
);
|
|
4663
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4664
|
+
const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
|
|
4665
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4666
|
+
});
|
|
3834
4667
|
}
|
|
3835
|
-
async function
|
|
4668
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3836
4669
|
const dmk = await ctx.getOrCreateDmk();
|
|
3837
|
-
|
|
4670
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4671
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4672
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3838
4673
|
}
|
|
3839
4674
|
|
|
3840
4675
|
// src/device-apps/customActions.ts
|
|
3841
|
-
var
|
|
4676
|
+
var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
|
|
3842
4677
|
var import_rxjs = require("rxjs");
|
|
3843
4678
|
var GetOsVersionDeviceAction = class {
|
|
3844
4679
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
@@ -3852,7 +4687,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3852
4687
|
(async () => {
|
|
3853
4688
|
try {
|
|
3854
4689
|
subject.next({
|
|
3855
|
-
status:
|
|
4690
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3856
4691
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3857
4692
|
});
|
|
3858
4693
|
const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
|
|
@@ -3861,11 +4696,11 @@ var GetOsVersionDeviceAction = class {
|
|
|
3861
4696
|
const errObj = result?.error;
|
|
3862
4697
|
throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
|
|
3863
4698
|
}
|
|
3864
|
-
subject.next({ status:
|
|
4699
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
|
|
3865
4700
|
subject.complete();
|
|
3866
4701
|
} catch (err) {
|
|
3867
4702
|
if (cancelled) return;
|
|
3868
|
-
subject.next({ status:
|
|
4703
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3869
4704
|
subject.complete();
|
|
3870
4705
|
}
|
|
3871
4706
|
})();
|
|
@@ -3873,7 +4708,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3873
4708
|
observable: subject.asObservable(),
|
|
3874
4709
|
cancel: () => {
|
|
3875
4710
|
cancelled = true;
|
|
3876
|
-
subject.next({ status:
|
|
4711
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3877
4712
|
subject.complete();
|
|
3878
4713
|
}
|
|
3879
4714
|
};
|
|
@@ -3891,7 +4726,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3891
4726
|
(async () => {
|
|
3892
4727
|
try {
|
|
3893
4728
|
subject.next({
|
|
3894
|
-
status:
|
|
4729
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3895
4730
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3896
4731
|
});
|
|
3897
4732
|
const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
|
|
@@ -3908,11 +4743,11 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3908
4743
|
throw new Error(httpErr?.message ?? "Manager API getAppList failed");
|
|
3909
4744
|
}
|
|
3910
4745
|
const apps = either.extract();
|
|
3911
|
-
subject.next({ status:
|
|
4746
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
|
|
3912
4747
|
subject.complete();
|
|
3913
4748
|
} catch (err) {
|
|
3914
4749
|
if (cancelled) return;
|
|
3915
|
-
subject.next({ status:
|
|
4750
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3916
4751
|
subject.complete();
|
|
3917
4752
|
}
|
|
3918
4753
|
})();
|
|
@@ -3920,7 +4755,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3920
4755
|
observable: subject.asObservable(),
|
|
3921
4756
|
cancel: () => {
|
|
3922
4757
|
cancelled = true;
|
|
3923
|
-
subject.next({ status:
|
|
4758
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3924
4759
|
subject.complete();
|
|
3925
4760
|
}
|
|
3926
4761
|
};
|
|
@@ -4013,7 +4848,7 @@ var DeviceApps = class {
|
|
|
4013
4848
|
seTargetId: v.seTargetId,
|
|
4014
4849
|
mcuTargetId: v.mcuTargetId,
|
|
4015
4850
|
seVersion: v.seVersion,
|
|
4016
|
-
seFlagsHex:
|
|
4851
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
4017
4852
|
mcuSephVersion: v.mcuSephVersion,
|
|
4018
4853
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
4019
4854
|
hwVersion: v.hwVersion
|
|
@@ -4087,7 +4922,7 @@ var DeviceApps = class {
|
|
|
4087
4922
|
}
|
|
4088
4923
|
}
|
|
4089
4924
|
};
|
|
4090
|
-
function
|
|
4925
|
+
function bytesToHex4(bytes) {
|
|
4091
4926
|
if (!bytes) return "";
|
|
4092
4927
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4093
4928
|
}
|
|
@@ -4130,7 +4965,8 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4130
4965
|
evm: "Ethereum",
|
|
4131
4966
|
btc: "Bitcoin",
|
|
4132
4967
|
sol: "Solana",
|
|
4133
|
-
tron: "Tron"
|
|
4968
|
+
tron: "Tron",
|
|
4969
|
+
zcash: "Zcash"
|
|
4134
4970
|
};
|
|
4135
4971
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4136
4972
|
Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
|
|
@@ -4170,6 +5006,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4170
5006
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4171
5007
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4172
5008
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
5009
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
5010
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
5011
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
5012
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4173
5013
|
case "@ledgerhq/context-module":
|
|
4174
5014
|
return import("@ledgerhq/context-module");
|
|
4175
5015
|
default:
|
|
@@ -4229,6 +5069,7 @@ var LedgerConnectorBase = class {
|
|
|
4229
5069
|
this._ctx = {
|
|
4230
5070
|
emit: (event, data) => this._emit(event, data),
|
|
4231
5071
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
5072
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4232
5073
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4233
5074
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4234
5075
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4417,8 +5258,15 @@ var LedgerConnectorBase = class {
|
|
|
4417
5258
|
} catch (err) {
|
|
4418
5259
|
this._resetSignersAndSessions();
|
|
4419
5260
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
5261
|
+
if (isBleBondInvalidError(err)) {
|
|
5262
|
+
throw (0, import_hwk_adapter_core13.createHwkError)({
|
|
5263
|
+
code: import_hwk_adapter_core13.HardwareErrorCode.BleBondInvalid,
|
|
5264
|
+
message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
|
|
5265
|
+
_tag: ERROR_TAG.PeerRemovedPairing
|
|
5266
|
+
});
|
|
5267
|
+
}
|
|
4420
5268
|
const tag = err?._tag;
|
|
4421
|
-
if (isKnownConnectionTag(tag)) {
|
|
5269
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4422
5270
|
throw err;
|
|
4423
5271
|
}
|
|
4424
5272
|
const wrapped = new Error(
|
|
@@ -4519,7 +5367,7 @@ var LedgerConnectorBase = class {
|
|
|
4519
5367
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4520
5368
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4521
5369
|
async call(sessionId, method, params) {
|
|
4522
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5370
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4523
5371
|
try {
|
|
4524
5372
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4525
5373
|
return { success: true, payload };
|
|
@@ -4587,6 +5435,11 @@ var LedgerConnectorBase = class {
|
|
|
4587
5435
|
return solSignTransaction(ctx, sessionId, params);
|
|
4588
5436
|
case "solSignMessage":
|
|
4589
5437
|
return solSignMessage(ctx, sessionId, params);
|
|
5438
|
+
// ZCASH
|
|
5439
|
+
case "zcashGetFullViewingKey":
|
|
5440
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5441
|
+
case "zcashGetShieldedAddress":
|
|
5442
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4590
5443
|
// TRON
|
|
4591
5444
|
case "tronGetAddress":
|
|
4592
5445
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4620,7 +5473,7 @@ var LedgerConnectorBase = class {
|
|
|
4620
5473
|
});
|
|
4621
5474
|
});
|
|
4622
5475
|
} catch (err) {
|
|
4623
|
-
ctx.
|
|
5476
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4624
5477
|
throw ctx.wrapError(err);
|
|
4625
5478
|
} finally {
|
|
4626
5479
|
ctx.clearCanceller(sessionId);
|
|
@@ -4710,7 +5563,7 @@ var LedgerConnectorBase = class {
|
|
|
4710
5563
|
);
|
|
4711
5564
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4712
5565
|
} catch (err) {
|
|
4713
|
-
ctx.
|
|
5566
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4714
5567
|
throw ctx.wrapError(err);
|
|
4715
5568
|
} finally {
|
|
4716
5569
|
ctx.clearCanceller(sessionId);
|
|
@@ -4832,6 +5685,17 @@ var LedgerConnectorBase = class {
|
|
|
4832
5685
|
_invalidateSession(sessionId) {
|
|
4833
5686
|
this._signerManager?.invalidate(sessionId);
|
|
4834
5687
|
}
|
|
5688
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5689
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5690
|
+
this._cancellers.delete(sessionId);
|
|
5691
|
+
if (cancel) {
|
|
5692
|
+
try {
|
|
5693
|
+
cancel();
|
|
5694
|
+
} catch {
|
|
5695
|
+
}
|
|
5696
|
+
}
|
|
5697
|
+
this._invalidateSession(sessionId);
|
|
5698
|
+
}
|
|
4835
5699
|
/**
|
|
4836
5700
|
* Replace an old session with a new one after app switch.
|
|
4837
5701
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4916,7 +5780,7 @@ var LedgerConnectorBase = class {
|
|
|
4916
5780
|
* at every catch site. Falls through unchanged for unknown methods.
|
|
4917
5781
|
*/
|
|
4918
5782
|
_ctxForMethod(method) {
|
|
4919
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5783
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4920
5784
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4921
5785
|
if (!defaultAppName) return this._ctx;
|
|
4922
5786
|
return {
|
|
@@ -4950,6 +5814,204 @@ var LedgerConnectorBase = class {
|
|
|
4950
5814
|
return error;
|
|
4951
5815
|
}
|
|
4952
5816
|
};
|
|
5817
|
+
|
|
5818
|
+
// src/transport/DmkTransport.ts
|
|
5819
|
+
var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
|
|
5820
|
+
var DmkTransport = class extends import_hw_transport.default {
|
|
5821
|
+
constructor(dmk, sessionId) {
|
|
5822
|
+
super();
|
|
5823
|
+
this._dmk = dmk;
|
|
5824
|
+
this._sessionId = sessionId;
|
|
5825
|
+
}
|
|
5826
|
+
async exchange(apdu) {
|
|
5827
|
+
const response = await this._dmk.sendApdu({
|
|
5828
|
+
sessionId: this._sessionId,
|
|
5829
|
+
apdu: new Uint8Array(apdu)
|
|
5830
|
+
});
|
|
5831
|
+
const { data, statusCode } = response;
|
|
5832
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5833
|
+
if (data.length > 0) {
|
|
5834
|
+
result.set(data, 0);
|
|
5835
|
+
}
|
|
5836
|
+
result.set(statusCode, data.length);
|
|
5837
|
+
return result;
|
|
5838
|
+
}
|
|
5839
|
+
async close() {
|
|
5840
|
+
}
|
|
5841
|
+
};
|
|
5842
|
+
|
|
5843
|
+
// src/app/AppManager.ts
|
|
5844
|
+
var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
|
|
5845
|
+
var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
|
|
5846
|
+
var APP_NAME_MAP = {
|
|
5847
|
+
ETH: "Ethereum",
|
|
5848
|
+
BTC: "Bitcoin",
|
|
5849
|
+
SOL: "Solana",
|
|
5850
|
+
TRX: "Tron",
|
|
5851
|
+
ZEC: "Zcash",
|
|
5852
|
+
XRP: "XRP",
|
|
5853
|
+
ADA: "Cardano",
|
|
5854
|
+
DOT: "Polkadot",
|
|
5855
|
+
ATOM: "Cosmos"
|
|
5856
|
+
};
|
|
5857
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5858
|
+
var AppManager = class {
|
|
5859
|
+
constructor(dmk, options) {
|
|
5860
|
+
this._dmk = dmk;
|
|
5861
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5862
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5863
|
+
}
|
|
5864
|
+
/**
|
|
5865
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5866
|
+
* or undefined if the chain is not supported.
|
|
5867
|
+
*/
|
|
5868
|
+
static getAppName(chain) {
|
|
5869
|
+
return APP_NAME_MAP[chain];
|
|
5870
|
+
}
|
|
5871
|
+
/**
|
|
5872
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5873
|
+
*
|
|
5874
|
+
* Flow:
|
|
5875
|
+
* 1. Check the currently running app.
|
|
5876
|
+
* 2. If it is already the target, return immediately.
|
|
5877
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5878
|
+
* 4. Open the target app.
|
|
5879
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5880
|
+
*/
|
|
5881
|
+
/**
|
|
5882
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5883
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5884
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5885
|
+
* in response. NOT called when the target app is already open (no user
|
|
5886
|
+
* interaction needed in that case).
|
|
5887
|
+
*
|
|
5888
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5889
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5890
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5891
|
+
* Hence the callback must fire BEFORE that await.
|
|
5892
|
+
*/
|
|
5893
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5894
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5895
|
+
if (currentApp === targetAppName) {
|
|
5896
|
+
return;
|
|
5897
|
+
}
|
|
5898
|
+
if (!this._isDashboard(currentApp)) {
|
|
5899
|
+
await this._closeCurrentApp(sessionId);
|
|
5900
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5901
|
+
}
|
|
5902
|
+
onConfirmOnDevice?.();
|
|
5903
|
+
await this._openApp(sessionId, targetAppName);
|
|
5904
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5905
|
+
}
|
|
5906
|
+
// ---------------------------------------------------------------------------
|
|
5907
|
+
// Private helpers
|
|
5908
|
+
// ---------------------------------------------------------------------------
|
|
5909
|
+
async _getCurrentApp(sessionId) {
|
|
5910
|
+
const result = await this._dmk.sendCommand({
|
|
5911
|
+
sessionId,
|
|
5912
|
+
command: new import_device_management_kit3.GetAppAndVersionCommand()
|
|
5913
|
+
});
|
|
5914
|
+
if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5915
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5916
|
+
return result.data.name;
|
|
5917
|
+
}
|
|
5918
|
+
const errResult = result;
|
|
5919
|
+
const dmkErr = errResult.error ?? {};
|
|
5920
|
+
const original = dmkErr.originalError;
|
|
5921
|
+
debugLog(
|
|
5922
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5923
|
+
sessionId,
|
|
5924
|
+
"tag=",
|
|
5925
|
+
dmkErr._tag,
|
|
5926
|
+
"errorCode=",
|
|
5927
|
+
dmkErr.errorCode,
|
|
5928
|
+
"message=",
|
|
5929
|
+
dmkErr.message,
|
|
5930
|
+
"originalErrorMessage=",
|
|
5931
|
+
original?.message ?? String(original ?? "")
|
|
5932
|
+
);
|
|
5933
|
+
throw Object.assign(
|
|
5934
|
+
new Error(
|
|
5935
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5936
|
+
),
|
|
5937
|
+
{
|
|
5938
|
+
_tag: dmkErr._tag,
|
|
5939
|
+
errorCode: dmkErr.errorCode,
|
|
5940
|
+
originalError: original
|
|
5941
|
+
}
|
|
5942
|
+
);
|
|
5943
|
+
}
|
|
5944
|
+
async _openApp(sessionId, appName) {
|
|
5945
|
+
const result = await this._dmk.sendCommand({
|
|
5946
|
+
sessionId,
|
|
5947
|
+
command: new import_device_management_kit3.OpenAppCommand({ appName })
|
|
5948
|
+
});
|
|
5949
|
+
if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5950
|
+
const dmkErr = result.error;
|
|
5951
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5952
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5953
|
+
debugLog(
|
|
5954
|
+
"[AppManager] openApp failed:",
|
|
5955
|
+
appName,
|
|
5956
|
+
"errorCode:",
|
|
5957
|
+
errorCode,
|
|
5958
|
+
"tag:",
|
|
5959
|
+
dmkErr._tag
|
|
5960
|
+
);
|
|
5961
|
+
let code;
|
|
5962
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5963
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
|
|
5964
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5965
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
|
|
5966
|
+
}
|
|
5967
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5968
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5969
|
+
code,
|
|
5970
|
+
errorCode,
|
|
5971
|
+
statusCode: errorCode,
|
|
5972
|
+
appName,
|
|
5973
|
+
originalError: dmkErr
|
|
5974
|
+
});
|
|
5975
|
+
}
|
|
5976
|
+
}
|
|
5977
|
+
async _closeCurrentApp(sessionId) {
|
|
5978
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5979
|
+
await this._dmk.sendCommand({
|
|
5980
|
+
sessionId,
|
|
5981
|
+
command: new import_device_management_kit3.CloseAppCommand()
|
|
5982
|
+
});
|
|
5983
|
+
}
|
|
5984
|
+
/**
|
|
5985
|
+
* Poll the device until the expected app is reported as running,
|
|
5986
|
+
* or throw after `_maxRetries` attempts.
|
|
5987
|
+
*/
|
|
5988
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
5989
|
+
let lastSeen = "";
|
|
5990
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
5991
|
+
await this._wait();
|
|
5992
|
+
const current = await this._getCurrentApp(sessionId);
|
|
5993
|
+
lastSeen = current;
|
|
5994
|
+
if (current === expectedAppName) {
|
|
5995
|
+
return;
|
|
5996
|
+
}
|
|
5997
|
+
}
|
|
5998
|
+
debugLog(
|
|
5999
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
6000
|
+
expectedAppName,
|
|
6001
|
+
"lastSeen=",
|
|
6002
|
+
lastSeen
|
|
6003
|
+
);
|
|
6004
|
+
throw new Error(
|
|
6005
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
6006
|
+
);
|
|
6007
|
+
}
|
|
6008
|
+
_isDashboard(appName) {
|
|
6009
|
+
return appName === DASHBOARD_APP_NAME;
|
|
6010
|
+
}
|
|
6011
|
+
_wait() {
|
|
6012
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
6013
|
+
}
|
|
6014
|
+
};
|
|
4953
6015
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4954
6016
|
0 && (module.exports = {
|
|
4955
6017
|
AppManager,
|
|
@@ -4961,6 +6023,7 @@ var LedgerConnectorBase = class {
|
|
|
4961
6023
|
SignerEth,
|
|
4962
6024
|
SignerManager,
|
|
4963
6025
|
SignerSol,
|
|
6026
|
+
SignerZcash,
|
|
4964
6027
|
debugLog,
|
|
4965
6028
|
deviceActionToPromise,
|
|
4966
6029
|
isDeviceLockedError,
|