@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.9 → 1.2.10-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +97 -52
- package/dist/index.d.ts +97 -52
- package/dist/index.js +2086 -992
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2034 -914
- 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,7 +925,16 @@ 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;
|
|
932
|
+
var APP_MANAGEMENT_METHODS = /* @__PURE__ */ new Set([
|
|
933
|
+
"installApp",
|
|
934
|
+
"listInstalledApps",
|
|
935
|
+
"listInstalledNames",
|
|
936
|
+
"listAvailableApps"
|
|
937
|
+
]);
|
|
755
938
|
function btcAccountIndexFromPath(path) {
|
|
756
939
|
const segments = path.replace(/^m\//, "").split("/");
|
|
757
940
|
if (segments.length < 3) return null;
|
|
@@ -762,10 +945,36 @@ function btcAccountIndexFromPath(path) {
|
|
|
762
945
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
763
946
|
constructor(connector, options) {
|
|
764
947
|
this.vendor = "ledger";
|
|
765
|
-
|
|
948
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
949
|
+
// confirmation screen the device is already showing.
|
|
950
|
+
this.cancelCapability = "stops-waiting";
|
|
951
|
+
this.emitter = new import_hwk_adapter_core4.TypedEventEmitter();
|
|
952
|
+
this._operations = new import_hwk_adapter_core4.OperationRegistry({
|
|
953
|
+
vendor: "ledger",
|
|
954
|
+
onEnded: (operation, reason) => {
|
|
955
|
+
this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
|
|
956
|
+
this._pendingOperationBindings.delete(operation.operationId);
|
|
957
|
+
this.emitter.emit(import_hwk_adapter_core4.SDK.OPERATION_ENDED, {
|
|
958
|
+
type: import_hwk_adapter_core4.SDK.OPERATION_ENDED,
|
|
959
|
+
payload: { operationId: operation.operationId, reason }
|
|
960
|
+
});
|
|
961
|
+
if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
|
|
962
|
+
void this._releaseOperationConnection(operation);
|
|
963
|
+
}
|
|
964
|
+
}
|
|
965
|
+
});
|
|
766
966
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
767
967
|
this._sessions = /* @__PURE__ */ new Map();
|
|
768
|
-
|
|
968
|
+
// An operation's BLE pick is saved by its first call that gets past the wallet check.
|
|
969
|
+
this._pendingOperationBindings = /* @__PURE__ */ new Map();
|
|
970
|
+
// A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
|
|
971
|
+
// through an unlock retry; any other failure drops it with its session.
|
|
972
|
+
this._pendingPickBindings = /* @__PURE__ */ new Map();
|
|
973
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
974
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
975
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
976
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
977
|
+
this._uiRegistry = new import_hwk_adapter_core4.UiRequestRegistry();
|
|
769
978
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
770
979
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
771
980
|
// subsequent 100+ paths in the same session auto-promote silently.
|
|
@@ -778,21 +987,36 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
987
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
779
988
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
780
989
|
this._doConnectAbortController = null;
|
|
990
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
991
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
992
|
+
this._resetPromise = null;
|
|
993
|
+
this._stateGeneration = 0;
|
|
994
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
995
|
+
this._pendingConnectorTeardowns = 0;
|
|
996
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
997
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
781
998
|
this._installProgressLastEmittedValue = -Infinity;
|
|
782
999
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
783
1000
|
callChain: this.callChain.bind(this),
|
|
784
|
-
getChainFingerprint: (connectId, chain) =>
|
|
1001
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
1002
|
+
try {
|
|
1003
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
1004
|
+
chain,
|
|
1005
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
1006
|
+
);
|
|
1007
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
return this.errorToFailure(error);
|
|
1010
|
+
}
|
|
1011
|
+
},
|
|
1012
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
1013
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
1014
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
|
|
1015
|
+
releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
|
|
785
1016
|
});
|
|
786
1017
|
// ---------------------------------------------------------------------------
|
|
787
1018
|
// Private helpers
|
|
788
1019
|
// ---------------------------------------------------------------------------
|
|
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
1020
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
797
1021
|
this._connectingPromise = null;
|
|
798
1022
|
// ---------------------------------------------------------------------------
|
|
@@ -802,26 +1026,31 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
802
1026
|
const deviceInfo = this.connectorDeviceToDeviceInfo(data.device);
|
|
803
1027
|
this._discoveredDevices.set(deviceInfo.connectId, deviceInfo);
|
|
804
1028
|
this._sessions.delete(deviceInfo.connectId);
|
|
805
|
-
this.emitter.emit(
|
|
806
|
-
type:
|
|
1029
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.CONNECT, {
|
|
1030
|
+
type: import_hwk_adapter_core4.DEVICE.CONNECT,
|
|
807
1031
|
payload: deviceInfo
|
|
808
1032
|
});
|
|
809
1033
|
};
|
|
810
1034
|
this.deviceDisconnectHandler = (data) => {
|
|
1035
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
1036
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
1037
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
1038
|
+
} else {
|
|
1039
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
1040
|
+
}
|
|
811
1041
|
this._discoveredDevices.delete(data.connectId);
|
|
812
1042
|
this._sessions.delete(data.connectId);
|
|
813
|
-
this.emitter.emit(
|
|
814
|
-
type:
|
|
1043
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.DISCONNECT, {
|
|
1044
|
+
type: import_hwk_adapter_core4.DEVICE.DISCONNECT,
|
|
815
1045
|
payload: { connectId: data.connectId }
|
|
816
1046
|
});
|
|
817
1047
|
};
|
|
818
1048
|
// 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.
|
|
1049
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
1050
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
823
1051
|
this.uiEventForwarder = (event) => {
|
|
824
|
-
|
|
1052
|
+
const operationId = this._activeOperationId();
|
|
1053
|
+
if (event.type === import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress) {
|
|
825
1054
|
let connectId;
|
|
826
1055
|
for (const [cid, sid] of this._sessions) {
|
|
827
1056
|
if (sid === event.payload.sessionId) {
|
|
@@ -848,7 +1077,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
848
1077
|
}
|
|
849
1078
|
this._installProgressLastEmittedValue = progress;
|
|
850
1079
|
this.emitter.emit("ui-event", {
|
|
851
|
-
type:
|
|
1080
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1081
|
+
...operationId ? { operationId } : {},
|
|
852
1082
|
payload: {
|
|
853
1083
|
connectId,
|
|
854
1084
|
appName,
|
|
@@ -857,18 +1087,37 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
857
1087
|
});
|
|
858
1088
|
return;
|
|
859
1089
|
}
|
|
860
|
-
this.emitter.emit("ui-event", event);
|
|
1090
|
+
this.emitter.emit("ui-event", operationId ? { ...event, operationId } : event);
|
|
861
1091
|
};
|
|
862
1092
|
this.connector = connector;
|
|
863
1093
|
this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
|
|
864
|
-
this._jobQueue = new
|
|
1094
|
+
this._jobQueue = new import_hwk_adapter_core4.DeviceJobQueue();
|
|
865
1095
|
this.registerEventListeners();
|
|
866
1096
|
}
|
|
1097
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1098
|
+
const pending = owner?.pendingBinding;
|
|
1099
|
+
if (!owner || !pending) return;
|
|
1100
|
+
owner.pendingBinding = void 0;
|
|
1101
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1102
|
+
}
|
|
1103
|
+
_finishBleBinding(status) {
|
|
1104
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1105
|
+
this._bindingSelectionRequestId = void 0;
|
|
1106
|
+
if (selectionRequestId) (0, import_hwk_adapter_core4.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
|
|
1107
|
+
}
|
|
1108
|
+
_isBleConnection() {
|
|
1109
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1110
|
+
}
|
|
867
1111
|
// Transport
|
|
868
1112
|
get activeTransport() {
|
|
869
|
-
return
|
|
1113
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
870
1114
|
}
|
|
871
1115
|
getAvailableTransports() {
|
|
1116
|
+
if (this.connector.availableTransports) {
|
|
1117
|
+
return this.connector.availableTransports.map(
|
|
1118
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1119
|
+
);
|
|
1120
|
+
}
|
|
872
1121
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
873
1122
|
}
|
|
874
1123
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -885,21 +1134,43 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
885
1134
|
* The next operation will re-discover and re-connect automatically.
|
|
886
1135
|
*/
|
|
887
1136
|
resetState() {
|
|
1137
|
+
void this._resetStateAndDisconnectSessions();
|
|
1138
|
+
}
|
|
1139
|
+
_resetStateAndDisconnectSessions() {
|
|
1140
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1141
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1142
|
+
this._stateGeneration += 1;
|
|
1143
|
+
this._finishBleBinding("cancelled");
|
|
1144
|
+
this._operations.endAll("runtime-reset");
|
|
1145
|
+
this._doConnectAbortController?.abort();
|
|
888
1146
|
this._discoveredDevices.clear();
|
|
889
1147
|
this._sessions.clear();
|
|
1148
|
+
this._sessionTransports.clear();
|
|
1149
|
+
this._activeConnectionType = void 0;
|
|
1150
|
+
this._pendingOperationBindings.clear();
|
|
1151
|
+
this._pendingPickBindings.clear();
|
|
1152
|
+
this._selectedBleReconnectTargets.clear();
|
|
890
1153
|
this._connectingPromise = null;
|
|
1154
|
+
this._doConnectAbortController = null;
|
|
891
1155
|
this._uiRegistry.reset();
|
|
892
1156
|
this._jobQueue.clear();
|
|
893
1157
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1158
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1159
|
+
for (const sessionId of sessionIds) {
|
|
1160
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1161
|
+
}
|
|
1162
|
+
});
|
|
1163
|
+
this._resetPromise = resetPromise;
|
|
1164
|
+
return resetPromise.finally(() => {
|
|
1165
|
+
if (this._resetPromise === resetPromise) {
|
|
1166
|
+
this._resetPromise = null;
|
|
1167
|
+
}
|
|
1168
|
+
});
|
|
894
1169
|
}
|
|
895
1170
|
async dispose() {
|
|
896
|
-
this.
|
|
897
|
-
this._jobQueue.clear();
|
|
1171
|
+
await this._resetStateAndDisconnectSessions();
|
|
898
1172
|
this.unregisterEventListeners();
|
|
899
1173
|
this.connector.reset();
|
|
900
|
-
this._discoveredDevices.clear();
|
|
901
|
-
this._sessions.clear();
|
|
902
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
903
1174
|
this.emitter.removeAllListeners();
|
|
904
1175
|
}
|
|
905
1176
|
uiResponse(response) {
|
|
@@ -909,17 +1180,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
909
1180
|
// Device management
|
|
910
1181
|
// ---------------------------------------------------------------------------
|
|
911
1182
|
async searchDevices(options) {
|
|
1183
|
+
return this._searchDevices(options);
|
|
1184
|
+
}
|
|
1185
|
+
async _searchDevices(options, signal) {
|
|
912
1186
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
913
1187
|
try {
|
|
914
1188
|
if (options?.resetSession) {
|
|
915
|
-
this.
|
|
916
|
-
|
|
917
|
-
this.
|
|
918
|
-
|
|
919
|
-
|
|
1189
|
+
await this._resetStateAndDisconnectSessions();
|
|
1190
|
+
} else {
|
|
1191
|
+
await this._connectorTeardownTail;
|
|
1192
|
+
}
|
|
1193
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1194
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1195
|
+
const stateGeneration = this._stateGeneration;
|
|
1196
|
+
const devices = await this.connector.searchDevices(
|
|
1197
|
+
options?.transportType ? {
|
|
1198
|
+
transportType: options.transportType,
|
|
1199
|
+
waitForAll: options.waitForAllTransports
|
|
1200
|
+
} : void 0
|
|
1201
|
+
);
|
|
1202
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1203
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1204
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1205
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1206
|
+
message: "Ledger discovery was reset"
|
|
1207
|
+
});
|
|
920
1208
|
}
|
|
921
|
-
await this._ensureDevicePermission();
|
|
922
|
-
const devices = await this.connector.searchDevices();
|
|
923
1209
|
this._discoveredDevices.clear();
|
|
924
1210
|
for (const d of devices) {
|
|
925
1211
|
if (d.connectId) {
|
|
@@ -927,7 +1213,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
927
1213
|
}
|
|
928
1214
|
}
|
|
929
1215
|
if (this._discoveredDevices.size === 0) {
|
|
930
|
-
await this._ensureDevicePermission();
|
|
1216
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
931
1217
|
}
|
|
932
1218
|
const result = Array.from(this._discoveredDevices.values());
|
|
933
1219
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -946,41 +1232,267 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
946
1232
|
throw err;
|
|
947
1233
|
}
|
|
948
1234
|
}
|
|
1235
|
+
async searchDeviceTargets(options) {
|
|
1236
|
+
const devices = await this.searchDevices(options);
|
|
1237
|
+
return devices.map((device) => (0, import_hwk_adapter_core4.toPhysicalDeviceSearchTarget)("ledger", device));
|
|
1238
|
+
}
|
|
949
1239
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
950
|
-
async _evictAllSessions() {
|
|
1240
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1241
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
951
1242
|
if (this._sessions.size === 0) return;
|
|
952
1243
|
const stale = [...this._sessions.values()];
|
|
953
1244
|
this._sessions.clear();
|
|
954
|
-
for (const sid of stale)
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1245
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1246
|
+
await this._runConnectorTeardown(async () => {
|
|
1247
|
+
for (const sid of stale) {
|
|
1248
|
+
try {
|
|
1249
|
+
await this.connector.disconnect(sid);
|
|
1250
|
+
} catch {
|
|
1251
|
+
}
|
|
958
1252
|
}
|
|
959
|
-
}
|
|
1253
|
+
});
|
|
960
1254
|
}
|
|
961
1255
|
static _createDeviceBusyError(method) {
|
|
962
1256
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
963
|
-
code:
|
|
1257
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceBusy
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
async connectDevice(searchTargetId) {
|
|
1261
|
+
try {
|
|
1262
|
+
return await this._jobQueue.enqueue(
|
|
1263
|
+
searchTargetId || "__ledger_connect__",
|
|
1264
|
+
async (signal) => {
|
|
1265
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1266
|
+
if (!connected.success) return connected;
|
|
1267
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1268
|
+
},
|
|
1269
|
+
{
|
|
1270
|
+
label: "connectDevice",
|
|
1271
|
+
rejectIfBusy: true,
|
|
1272
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1273
|
+
}
|
|
1274
|
+
);
|
|
1275
|
+
} catch (error) {
|
|
1276
|
+
return this.errorToFailure(error);
|
|
1277
|
+
}
|
|
1278
|
+
}
|
|
1279
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1280
|
+
async bindBleDevice(params) {
|
|
1281
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1282
|
+
const identities = identity ? [identity, ...params.fallbackIdentities ?? []] : [];
|
|
1283
|
+
try {
|
|
1284
|
+
return await this._jobQueue.enqueue(
|
|
1285
|
+
"__ledger_bind_ble__",
|
|
1286
|
+
async (signal) => {
|
|
1287
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1288
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1289
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.TransportNotAvailable,
|
|
1290
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
this._activeConnectionType = "ble";
|
|
1294
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1295
|
+
const attempt = {
|
|
1296
|
+
extra: params.extra,
|
|
1297
|
+
bindingReason: "manual-rebind",
|
|
1298
|
+
deferBindingSave: Boolean(identity)
|
|
1299
|
+
};
|
|
1300
|
+
try {
|
|
1301
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1302
|
+
[],
|
|
1303
|
+
void 0,
|
|
1304
|
+
true,
|
|
1305
|
+
void 0,
|
|
1306
|
+
attempt,
|
|
1307
|
+
signal
|
|
1308
|
+
);
|
|
1309
|
+
const pending = attempt.pendingBinding;
|
|
1310
|
+
if (identity && pending) {
|
|
1311
|
+
attempt.pendingBinding = void 0;
|
|
1312
|
+
const sessionId = this._sessions.get(connectId);
|
|
1313
|
+
if (!sessionId) {
|
|
1314
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1315
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
1316
|
+
message: "Selected Ledger connection ended"
|
|
1317
|
+
});
|
|
1318
|
+
}
|
|
1319
|
+
const checked = await this._fingerprintFirstOpenableChain(
|
|
1320
|
+
identities,
|
|
1321
|
+
(chain, autoInstallApp) => this._computeChainFingerprint(
|
|
1322
|
+
chain,
|
|
1323
|
+
(method, callParams) => this._runConnectorCall(
|
|
1324
|
+
connectId,
|
|
1325
|
+
method,
|
|
1326
|
+
callParams,
|
|
1327
|
+
signal,
|
|
1328
|
+
void 0,
|
|
1329
|
+
void 0,
|
|
1330
|
+
{ autoInstallApp },
|
|
1331
|
+
{ connection: { connectId, sessionId } }
|
|
1332
|
+
)
|
|
1333
|
+
)
|
|
1334
|
+
);
|
|
1335
|
+
if (checked.fingerprint !== checked.identity.value) {
|
|
1336
|
+
await this._dropSession(connectId, signal);
|
|
1337
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1338
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
1339
|
+
message: formatDeviceMismatchError(checked.identity.value, checked.fingerprint)
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
await this._saveSelectedBleBinding(
|
|
1343
|
+
connectId,
|
|
1344
|
+
pending.requestId,
|
|
1345
|
+
attempt,
|
|
1346
|
+
void 0,
|
|
1347
|
+
signal,
|
|
1348
|
+
checked.identity
|
|
1349
|
+
);
|
|
1350
|
+
}
|
|
1351
|
+
if (!attempt.bindingSaved) {
|
|
1352
|
+
await this._dropSession(connectId, signal);
|
|
1353
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1354
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1355
|
+
message: "Bluetooth binding could not be saved",
|
|
1356
|
+
origin: "host"
|
|
1357
|
+
});
|
|
1358
|
+
}
|
|
1359
|
+
return (0, import_hwk_adapter_core4.success)(connectId);
|
|
1360
|
+
} catch (error) {
|
|
1361
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1362
|
+
throw error;
|
|
1363
|
+
}
|
|
1364
|
+
},
|
|
1365
|
+
{
|
|
1366
|
+
label: "bindBleDevice",
|
|
1367
|
+
rejectIfBusy: true,
|
|
1368
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1369
|
+
}
|
|
1370
|
+
);
|
|
1371
|
+
} catch (error) {
|
|
1372
|
+
return this.errorToFailure(error);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
async acquireOperation(connectId, context) {
|
|
1376
|
+
try {
|
|
1377
|
+
return await this._jobQueue.enqueue(
|
|
1378
|
+
connectId || "__ledger_acquire__",
|
|
1379
|
+
async (signal) => {
|
|
1380
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1381
|
+
const hint = context.knownConnections?.find(
|
|
1382
|
+
(connection) => connection.transport === transport
|
|
1383
|
+
);
|
|
1384
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1385
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1386
|
+
const attempt = {
|
|
1387
|
+
...context,
|
|
1388
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1389
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1390
|
+
deferBindingSave: true
|
|
1391
|
+
};
|
|
1392
|
+
try {
|
|
1393
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1394
|
+
target,
|
|
1395
|
+
signal,
|
|
1396
|
+
true,
|
|
1397
|
+
void 0,
|
|
1398
|
+
attempt
|
|
1399
|
+
);
|
|
1400
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1401
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1402
|
+
if (result.success && attempt.pendingBinding) {
|
|
1403
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1404
|
+
}
|
|
1405
|
+
return result;
|
|
1406
|
+
} catch (error) {
|
|
1407
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1408
|
+
throw error;
|
|
1409
|
+
}
|
|
1410
|
+
},
|
|
1411
|
+
{
|
|
1412
|
+
label: "acquireOperation",
|
|
1413
|
+
rejectIfBusy: true,
|
|
1414
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1415
|
+
}
|
|
1416
|
+
);
|
|
1417
|
+
} catch (error) {
|
|
1418
|
+
return this.errorToFailure(error);
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1422
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1423
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1424
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1425
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1426
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1427
|
+
vendor: "ledger",
|
|
1428
|
+
model: "unknown",
|
|
1429
|
+
firmwareVersion: "",
|
|
1430
|
+
deviceId: "",
|
|
1431
|
+
connectId: resolvedConnectId,
|
|
1432
|
+
connectionType
|
|
1433
|
+
};
|
|
1434
|
+
const operation = this._operations.create({
|
|
1435
|
+
searchTargetId,
|
|
1436
|
+
connectId: resolvedConnectId,
|
|
1437
|
+
device,
|
|
1438
|
+
connectionType,
|
|
1439
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
964
1440
|
});
|
|
1441
|
+
return (0, import_hwk_adapter_core4.success)(operation.operationId);
|
|
965
1442
|
}
|
|
966
|
-
async
|
|
1443
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
967
1444
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
968
1445
|
try {
|
|
969
|
-
|
|
1446
|
+
this._assertConnectorReady("connectDevice");
|
|
1447
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1448
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1449
|
+
this._activeConnectionType = discoveredType;
|
|
1450
|
+
}
|
|
1451
|
+
if (this._isBleConnection() && !connectId) {
|
|
970
1452
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
971
|
-
code:
|
|
1453
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
972
1454
|
});
|
|
973
1455
|
}
|
|
974
|
-
|
|
975
|
-
|
|
1456
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1457
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1458
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1459
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1460
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1461
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1462
|
+
if (previousSessionId) {
|
|
1463
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1464
|
+
this._sessions.delete(connectId);
|
|
1465
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1466
|
+
}
|
|
1467
|
+
} else {
|
|
1468
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1469
|
+
}
|
|
1470
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1471
|
+
const stateGeneration = this._stateGeneration;
|
|
1472
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1473
|
+
let session;
|
|
1474
|
+
this._connectingConnectId = connectId;
|
|
1475
|
+
try {
|
|
1476
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1477
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1478
|
+
}) : await this.connector.connect(connectId);
|
|
1479
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1480
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1481
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1482
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1483
|
+
});
|
|
1484
|
+
}
|
|
1485
|
+
} finally {
|
|
1486
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1487
|
+
releaseOperation();
|
|
976
1488
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
this.
|
|
1489
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1490
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1491
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
980
1492
|
if (session.deviceInfo) {
|
|
981
|
-
this._discoveredDevices.set(
|
|
1493
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
982
1494
|
}
|
|
983
|
-
const result = (0,
|
|
1495
|
+
const result = (0, import_hwk_adapter_core4.success)(resolvedConnectId);
|
|
984
1496
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
985
1497
|
return result;
|
|
986
1498
|
} catch (err) {
|
|
@@ -993,30 +1505,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
993
1505
|
return failureResult;
|
|
994
1506
|
}
|
|
995
1507
|
}
|
|
996
|
-
async
|
|
1508
|
+
async releaseOperation(operationId) {
|
|
1509
|
+
const operation = this._operations.findActive(operationId);
|
|
1510
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1511
|
+
const endedOperation = this._operations.release(operationId);
|
|
1512
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1513
|
+
const { connectId } = endedOperation;
|
|
997
1514
|
debugLog("[LedgerAdapter][REQ]", {
|
|
998
|
-
method: "
|
|
1515
|
+
method: "releaseOperation",
|
|
999
1516
|
connectId,
|
|
1000
1517
|
params: { connectId }
|
|
1001
1518
|
});
|
|
1002
1519
|
try {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
await this.connector.disconnect(sessionId);
|
|
1006
|
-
this._sessions.delete(connectId);
|
|
1007
|
-
}
|
|
1008
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1520
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1521
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
1009
1522
|
} catch (err) {
|
|
1010
1523
|
const e = err;
|
|
1011
1524
|
debugLog("[LedgerAdapter][RES]", {
|
|
1012
|
-
method: "
|
|
1525
|
+
method: "releaseOperation",
|
|
1013
1526
|
success: false,
|
|
1014
1527
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1528
|
});
|
|
1016
1529
|
throw err;
|
|
1017
1530
|
}
|
|
1018
1531
|
}
|
|
1019
|
-
|
|
1532
|
+
/**
|
|
1533
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1534
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1535
|
+
*/
|
|
1536
|
+
_cancelOperationWork(operation) {
|
|
1537
|
+
const { operationId } = operation;
|
|
1538
|
+
const reason = (0, import_hwk_adapter_core4.createHwkError)({
|
|
1539
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
1540
|
+
message: "Ledger operation was released",
|
|
1541
|
+
params: { operationId, reason: "explicit" }
|
|
1542
|
+
});
|
|
1543
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1544
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1545
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1546
|
+
if (!ownsRunningCall) return;
|
|
1547
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1548
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1549
|
+
}
|
|
1550
|
+
/**
|
|
1551
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1552
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1553
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1554
|
+
*/
|
|
1555
|
+
_bareCallMayUseConnection(operation) {
|
|
1556
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1557
|
+
return activeKey !== void 0 && !(0, import_hwk_adapter_core4.isHardwareOperationId)(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1558
|
+
}
|
|
1559
|
+
async _releaseOperationConnection(operation) {
|
|
1560
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1561
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1562
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1563
|
+
this._sessions.delete(connectId);
|
|
1564
|
+
sessionIds.add(sessionId);
|
|
1565
|
+
}
|
|
1566
|
+
}
|
|
1567
|
+
for (const sessionId of sessionIds) {
|
|
1568
|
+
await this._runConnectorTeardown(
|
|
1569
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1570
|
+
);
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
1573
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1574
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1575
|
+
if (!endedOperation) return;
|
|
1576
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1577
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1578
|
+
}
|
|
1579
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1580
|
+
let connectId;
|
|
1581
|
+
try {
|
|
1582
|
+
connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1583
|
+
} catch (error) {
|
|
1584
|
+
return this.errorToFailure(error);
|
|
1585
|
+
}
|
|
1020
1586
|
debugLog("[LedgerAdapter][REQ]", {
|
|
1021
1587
|
method: "getDeviceInfo",
|
|
1022
1588
|
connectId,
|
|
@@ -1026,7 +1592,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1026
1592
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
1027
1593
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
1028
1594
|
if (cached) {
|
|
1029
|
-
const result = (0,
|
|
1595
|
+
const result = (0, import_hwk_adapter_core4.success)(cached);
|
|
1030
1596
|
debugLog("[LedgerAdapter][RES]", {
|
|
1031
1597
|
method: "getDeviceInfo",
|
|
1032
1598
|
success: true,
|
|
@@ -1034,8 +1600,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1034
1600
|
});
|
|
1035
1601
|
return result;
|
|
1036
1602
|
}
|
|
1037
|
-
const notFound = (0,
|
|
1038
|
-
|
|
1603
|
+
const notFound = (0, import_hwk_adapter_core4.failure)(
|
|
1604
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
1039
1605
|
"Device not found in cache. Call searchDevices() or wait for a device-connected event first."
|
|
1040
1606
|
);
|
|
1041
1607
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -1051,11 +1617,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1051
1617
|
success: false,
|
|
1052
1618
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1053
1619
|
});
|
|
1054
|
-
|
|
1620
|
+
return this.errorToFailure(err);
|
|
1055
1621
|
}
|
|
1056
1622
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1623
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1624
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1625
|
+
const { connection } = context;
|
|
1626
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1627
|
+
if (!connection || !owner) return;
|
|
1628
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1629
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1630
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1631
|
+
await this._dropSession(connection.connectId, signal);
|
|
1632
|
+
}
|
|
1059
1633
|
}
|
|
1060
1634
|
// ---------------------------------------------------------------------------
|
|
1061
1635
|
// Chain call helper
|
|
@@ -1075,7 +1649,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1075
1649
|
commonParams,
|
|
1076
1650
|
installContext
|
|
1077
1651
|
);
|
|
1078
|
-
return (0,
|
|
1652
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1079
1653
|
} catch (err) {
|
|
1080
1654
|
return this.errorToFailure(err);
|
|
1081
1655
|
}
|
|
@@ -1091,13 +1665,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1091
1665
|
if (params && typeof params === "object") {
|
|
1092
1666
|
const {
|
|
1093
1667
|
autoInstallApp,
|
|
1668
|
+
operationId,
|
|
1094
1669
|
passphraseState: _passphraseState,
|
|
1095
1670
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1671
|
+
knownConnections,
|
|
1672
|
+
extra,
|
|
1673
|
+
allowDeviceSelection,
|
|
1674
|
+
supportedTransports,
|
|
1096
1675
|
...rest
|
|
1097
1676
|
} = params;
|
|
1098
1677
|
return {
|
|
1099
1678
|
commonParams: {
|
|
1100
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1679
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1680
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1681
|
+
...(0, import_hwk_adapter_core4.pickConnectionContext)({
|
|
1682
|
+
knownConnections,
|
|
1683
|
+
extra,
|
|
1684
|
+
allowDeviceSelection,
|
|
1685
|
+
supportedTransports
|
|
1686
|
+
})
|
|
1101
1687
|
},
|
|
1102
1688
|
rest
|
|
1103
1689
|
};
|
|
@@ -1263,7 +1849,13 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1263
1849
|
params
|
|
1264
1850
|
);
|
|
1265
1851
|
}
|
|
1266
|
-
tronSignMessage(connectId, deviceId, params) {
|
|
1852
|
+
async tronSignMessage(connectId, deviceId, params) {
|
|
1853
|
+
if (params?.messageType !== "V2") {
|
|
1854
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1855
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1856
|
+
'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
|
|
1857
|
+
);
|
|
1858
|
+
}
|
|
1267
1859
|
return this.callChainWithMergedParams(
|
|
1268
1860
|
connectId,
|
|
1269
1861
|
deviceId,
|
|
@@ -1273,14 +1865,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1273
1865
|
);
|
|
1274
1866
|
}
|
|
1275
1867
|
// ---------------------------------------------------------------------------
|
|
1276
|
-
//
|
|
1277
|
-
//
|
|
1278
|
-
|
|
1868
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1869
|
+
// ---------------------------------------------------------------------------
|
|
1870
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1871
|
+
return this.callChainWithMergedParams(
|
|
1872
|
+
connectId,
|
|
1873
|
+
deviceId,
|
|
1874
|
+
"zcash",
|
|
1875
|
+
"zcashGetFullViewingKey",
|
|
1876
|
+
params
|
|
1877
|
+
);
|
|
1878
|
+
}
|
|
1879
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1880
|
+
return this.callChainWithMergedParams(
|
|
1881
|
+
connectId,
|
|
1882
|
+
deviceId,
|
|
1883
|
+
"zcash",
|
|
1884
|
+
"zcashGetShieldedAddress",
|
|
1885
|
+
params
|
|
1886
|
+
);
|
|
1887
|
+
}
|
|
1888
|
+
// ---------------------------------------------------------------------------
|
|
1889
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1279
1890
|
// ---------------------------------------------------------------------------
|
|
1280
1891
|
async installApp(connectId, appName) {
|
|
1281
1892
|
try {
|
|
1282
1893
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1283
|
-
return (0,
|
|
1894
|
+
return (0, import_hwk_adapter_core4.success)(void 0);
|
|
1284
1895
|
} catch (err) {
|
|
1285
1896
|
return this.errorToFailure(err);
|
|
1286
1897
|
}
|
|
@@ -1288,7 +1899,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1288
1899
|
async listInstalledApps(connectId) {
|
|
1289
1900
|
try {
|
|
1290
1901
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1291
|
-
return (0,
|
|
1902
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1292
1903
|
} catch (err) {
|
|
1293
1904
|
return this.errorToFailure(err);
|
|
1294
1905
|
}
|
|
@@ -1297,7 +1908,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1297
1908
|
async listInstalledNames(connectId) {
|
|
1298
1909
|
try {
|
|
1299
1910
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1300
|
-
return (0,
|
|
1911
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1301
1912
|
} catch (err) {
|
|
1302
1913
|
return this.errorToFailure(err);
|
|
1303
1914
|
}
|
|
@@ -1305,7 +1916,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1305
1916
|
async listAvailableApps(connectId) {
|
|
1306
1917
|
try {
|
|
1307
1918
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1308
|
-
return (0,
|
|
1919
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1309
1920
|
} catch (err) {
|
|
1310
1921
|
return this.errorToFailure(err);
|
|
1311
1922
|
}
|
|
@@ -1313,7 +1924,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1313
1924
|
async getLedgerFirmwareVersion(connectId) {
|
|
1314
1925
|
try {
|
|
1315
1926
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1316
|
-
return (0,
|
|
1927
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1317
1928
|
} catch (err) {
|
|
1318
1929
|
return this.errorToFailure(err);
|
|
1319
1930
|
}
|
|
@@ -1321,7 +1932,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1321
1932
|
async getLedgerDeviceInfo(connectId) {
|
|
1322
1933
|
try {
|
|
1323
1934
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1324
|
-
return (0,
|
|
1935
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1325
1936
|
} catch (err) {
|
|
1326
1937
|
return this.errorToFailure(err);
|
|
1327
1938
|
}
|
|
@@ -1355,28 +1966,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1355
1966
|
try {
|
|
1356
1967
|
if (relayUrl) {
|
|
1357
1968
|
if (!this.connector.configure) {
|
|
1358
|
-
return (0,
|
|
1359
|
-
|
|
1969
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1970
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1360
1971
|
"This Ledger connector does not support genuine-check relay configuration"
|
|
1361
1972
|
);
|
|
1362
1973
|
}
|
|
1363
1974
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1364
|
-
this.
|
|
1975
|
+
await this._resetStateAndDisconnectSessions();
|
|
1365
1976
|
}
|
|
1366
1977
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1367
1978
|
if (!result.isGenuine) {
|
|
1368
|
-
return (0,
|
|
1979
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1369
1980
|
vendor: "ledger",
|
|
1370
1981
|
verified: false
|
|
1371
1982
|
});
|
|
1372
1983
|
}
|
|
1373
1984
|
if (!result.deviceId) {
|
|
1374
|
-
return (0,
|
|
1375
|
-
|
|
1985
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1986
|
+
import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1376
1987
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1377
1988
|
);
|
|
1378
1989
|
}
|
|
1379
|
-
return (0,
|
|
1990
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1380
1991
|
vendor: "ledger",
|
|
1381
1992
|
verified: result.isGenuine,
|
|
1382
1993
|
deviceId: result.deviceId
|
|
@@ -1387,10 +1998,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1387
1998
|
if (relayUrl) {
|
|
1388
1999
|
try {
|
|
1389
2000
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1390
|
-
this.
|
|
2001
|
+
await this._resetStateAndDisconnectSessions();
|
|
1391
2002
|
} catch {
|
|
1392
2003
|
this.connector.reset();
|
|
1393
|
-
this.
|
|
2004
|
+
await this._resetStateAndDisconnectSessions();
|
|
1394
2005
|
}
|
|
1395
2006
|
}
|
|
1396
2007
|
}
|
|
@@ -1402,8 +2013,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1402
2013
|
this.emitter.off(event, listener);
|
|
1403
2014
|
}
|
|
1404
2015
|
cancel(connectId) {
|
|
2016
|
+
const namedOperationIsLive = (id) => {
|
|
2017
|
+
try {
|
|
2018
|
+
this._operations.resolve(id);
|
|
2019
|
+
return true;
|
|
2020
|
+
} catch {
|
|
2021
|
+
return false;
|
|
2022
|
+
}
|
|
2023
|
+
};
|
|
2024
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
|
|
2025
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
2026
|
+
connectId
|
|
2027
|
+
});
|
|
2028
|
+
return;
|
|
2029
|
+
}
|
|
1405
2030
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1406
|
-
code:
|
|
2031
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1407
2032
|
_tag: ERROR_TAG.UserAborted
|
|
1408
2033
|
});
|
|
1409
2034
|
this._lastCancelReason = userAbortReason;
|
|
@@ -1412,60 +2037,163 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1412
2037
|
this._lastCancelReason = void 0;
|
|
1413
2038
|
}
|
|
1414
2039
|
}, 2e3);
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
2040
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
2041
|
+
let operationId;
|
|
2042
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
|
|
2043
|
+
operationId = connectId;
|
|
2044
|
+
} else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
|
|
2045
|
+
operationId = activeJobId;
|
|
1420
2046
|
}
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
2047
|
+
let resolvedConnectId = connectId;
|
|
2048
|
+
if (operationId) {
|
|
2049
|
+
try {
|
|
2050
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2051
|
+
} catch {
|
|
2052
|
+
resolvedConnectId = void 0;
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2056
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2057
|
+
if (!connectId) {
|
|
2058
|
+
this._uiRegistry.cancel();
|
|
2059
|
+
} else if (pendingOperationId) {
|
|
2060
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2061
|
+
}
|
|
2062
|
+
this._finishBleBinding("cancelled");
|
|
2063
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2064
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2065
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2066
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2067
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2068
|
+
if (queueKeys.size) {
|
|
2069
|
+
let cancelledAnyJob = false;
|
|
2070
|
+
for (const key of queueKeys) {
|
|
2071
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2072
|
+
}
|
|
2073
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2074
|
+
queueKeys: [...queueKeys],
|
|
2075
|
+
cancelledAnyJob
|
|
2076
|
+
});
|
|
2077
|
+
} else {
|
|
2078
|
+
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
1429
2079
|
}
|
|
2080
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2081
|
+
const targetKeys = new Set(
|
|
2082
|
+
[
|
|
2083
|
+
connectId,
|
|
2084
|
+
resolvedConnectId,
|
|
2085
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2086
|
+
].filter(Boolean)
|
|
2087
|
+
);
|
|
2088
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2089
|
+
if (activeJobId === void 0 || ownsPendingConnect) {
|
|
2090
|
+
if (resolvedConnectId) {
|
|
2091
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
2092
|
+
void this.connector.cancel(sessionId);
|
|
2093
|
+
} else {
|
|
2094
|
+
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
2095
|
+
}
|
|
2096
|
+
}
|
|
2097
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
2098
|
+
this._doConnectAbortController?.abort(userAbortReason);
|
|
2099
|
+
}
|
|
2100
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1430
2101
|
}
|
|
1431
2102
|
// ---------------------------------------------------------------------------
|
|
1432
2103
|
// Chain fingerprint
|
|
1433
2104
|
// ---------------------------------------------------------------------------
|
|
2105
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1434
2106
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1435
2107
|
try {
|
|
1436
2108
|
const fingerprint = await this._computeChainFingerprint(
|
|
1437
2109
|
chain,
|
|
1438
2110
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1439
2111
|
);
|
|
1440
|
-
|
|
2112
|
+
if (deviceId) {
|
|
2113
|
+
if (fingerprint !== deviceId) {
|
|
2114
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
2115
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2116
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2117
|
+
);
|
|
2118
|
+
}
|
|
2119
|
+
}
|
|
2120
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1441
2121
|
} catch (err) {
|
|
1442
2122
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1443
2123
|
return this.errorToFailure(err);
|
|
1444
2124
|
}
|
|
1445
2125
|
}
|
|
1446
2126
|
/**
|
|
1447
|
-
*
|
|
1448
|
-
*
|
|
2127
|
+
* Fingerprints the first recorded chain whose app the device can open. Only a missing app
|
|
2128
|
+
* moves on to the next chain; when every app is missing, the first chain offers its install.
|
|
1449
2129
|
*/
|
|
1450
|
-
async
|
|
1451
|
-
|
|
2130
|
+
async _fingerprintFirstOpenableChain(identities, fingerprintOf) {
|
|
2131
|
+
const [first] = identities;
|
|
2132
|
+
if (identities.length > 1) {
|
|
2133
|
+
for (const identity of identities) {
|
|
2134
|
+
try {
|
|
2135
|
+
return { identity, fingerprint: await fingerprintOf(identity.chain, false) };
|
|
2136
|
+
} catch (error) {
|
|
2137
|
+
const isAppMissing = isAppNotInstalledError(error) || error?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
2138
|
+
if (!isAppMissing) throw error;
|
|
2139
|
+
}
|
|
2140
|
+
}
|
|
2141
|
+
}
|
|
2142
|
+
return { identity: first, fingerprint: await fingerprintOf(first.chain, true) };
|
|
2143
|
+
}
|
|
2144
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2145
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1452
2146
|
try {
|
|
1453
|
-
const
|
|
1454
|
-
|
|
1455
|
-
|
|
2147
|
+
const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
|
|
2148
|
+
this.emitter,
|
|
2149
|
+
this._uiRegistry,
|
|
2150
|
+
{
|
|
2151
|
+
selectionRequestId,
|
|
2152
|
+
connection: { transport: "ble", connectId },
|
|
2153
|
+
...identity ? { identity } : {},
|
|
2154
|
+
extra: context?.extra,
|
|
2155
|
+
operationId
|
|
2156
|
+
},
|
|
2157
|
+
signal
|
|
1456
2158
|
);
|
|
1457
|
-
if (
|
|
1458
|
-
|
|
2159
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2160
|
+
if (!outcome.saved) {
|
|
2161
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2162
|
+
connectId,
|
|
2163
|
+
reason: outcome.reason
|
|
2164
|
+
});
|
|
1459
2165
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
2166
|
+
} catch (error) {
|
|
2167
|
+
await this._dropSession(connectId, signal);
|
|
2168
|
+
throw error;
|
|
2169
|
+
} finally {
|
|
2170
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2171
|
+
this._bindingSelectionRequestId = void 0;
|
|
1465
2172
|
}
|
|
1466
|
-
throw err;
|
|
1467
2173
|
}
|
|
1468
2174
|
}
|
|
2175
|
+
async _dropSession(connectId, signal) {
|
|
2176
|
+
const sessionId = this._sessions.get(connectId);
|
|
2177
|
+
this._sessions.delete(connectId);
|
|
2178
|
+
if (!sessionId) return;
|
|
2179
|
+
this._sessionTransports.delete(sessionId);
|
|
2180
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2181
|
+
() => void 0
|
|
2182
|
+
);
|
|
2183
|
+
if (!signal.aborted) await teardown;
|
|
2184
|
+
}
|
|
2185
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2186
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2187
|
+
if (!deviceId) return { success: true };
|
|
2188
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2189
|
+
chain,
|
|
2190
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2191
|
+
);
|
|
2192
|
+
if (fingerprint === deviceId) {
|
|
2193
|
+
return { success: true };
|
|
2194
|
+
}
|
|
2195
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2196
|
+
}
|
|
1469
2197
|
/**
|
|
1470
2198
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1471
2199
|
*
|
|
@@ -1485,7 +2213,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1485
2213
|
const result = await callMethod("btcGetMasterFingerprint", {});
|
|
1486
2214
|
return result.masterFingerprint;
|
|
1487
2215
|
}
|
|
1488
|
-
const path =
|
|
2216
|
+
const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
|
|
1489
2217
|
let address;
|
|
1490
2218
|
if (chain === "evm") {
|
|
1491
2219
|
address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
|
|
@@ -1493,10 +2221,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1493
2221
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1494
2222
|
} else if (chain === "tron") {
|
|
1495
2223
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2224
|
+
} else if (chain === "zcash") {
|
|
2225
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1496
2226
|
} else {
|
|
1497
2227
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1498
2228
|
}
|
|
1499
|
-
return (0,
|
|
2229
|
+
return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
|
|
2230
|
+
}
|
|
2231
|
+
/**
|
|
2232
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2233
|
+
* Undefined at cold start when no operation owns the job.
|
|
2234
|
+
*/
|
|
2235
|
+
_activeOperationId() {
|
|
2236
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
1500
2237
|
}
|
|
1501
2238
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1502
2239
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
@@ -1507,22 +2244,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1507
2244
|
if (signal?.aborted) {
|
|
1508
2245
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1509
2246
|
}
|
|
2247
|
+
const operationId = this._activeOperationId();
|
|
1510
2248
|
const waitPromise = this._uiRegistry.wait(
|
|
1511
|
-
|
|
2249
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2250
|
+
{ operationId }
|
|
1512
2251
|
);
|
|
1513
|
-
this.emitter.emit(
|
|
1514
|
-
type:
|
|
2252
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
2253
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1515
2254
|
payload: {
|
|
1516
2255
|
vendor: "ledger",
|
|
1517
2256
|
reason: "device-not-found",
|
|
1518
|
-
message: "Please connect and unlock your Ledger device"
|
|
2257
|
+
message: "Please connect and unlock your Ledger device",
|
|
2258
|
+
operationId
|
|
1519
2259
|
}
|
|
1520
2260
|
});
|
|
1521
2261
|
let payload;
|
|
1522
2262
|
try {
|
|
1523
2263
|
if (signal) {
|
|
1524
2264
|
const onAbort = () => {
|
|
1525
|
-
this._uiRegistry.cancel(
|
|
2265
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
|
|
1526
2266
|
};
|
|
1527
2267
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
1528
2268
|
try {
|
|
@@ -1534,20 +2274,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1534
2274
|
payload = await waitPromise;
|
|
1535
2275
|
}
|
|
1536
2276
|
} catch (err) {
|
|
1537
|
-
this.emitter.emit(
|
|
1538
|
-
type:
|
|
1539
|
-
payload: {}
|
|
2277
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2278
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2279
|
+
payload: { operationId }
|
|
1540
2280
|
});
|
|
1541
2281
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1542
2282
|
_tag: ERROR_TAG.UserAborted,
|
|
1543
|
-
code:
|
|
2283
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1544
2284
|
cause: err
|
|
1545
2285
|
});
|
|
1546
2286
|
}
|
|
1547
2287
|
if (!payload?.confirmed) {
|
|
1548
2288
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1549
2289
|
_tag: ERROR_TAG.UserAborted,
|
|
1550
|
-
code:
|
|
2290
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1551
2291
|
});
|
|
1552
2292
|
}
|
|
1553
2293
|
await new Promise((resolve) => {
|
|
@@ -1561,7 +2301,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1561
2301
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1562
2302
|
* promoted), or `null` if the user declined.
|
|
1563
2303
|
*/
|
|
1564
|
-
async _gateBtcHighIndex(params) {
|
|
2304
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1565
2305
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1566
2306
|
if (params.showOnDevice) return params;
|
|
1567
2307
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1570,51 +2310,75 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1570
2310
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1571
2311
|
return { ...params, showOnDevice: true };
|
|
1572
2312
|
}
|
|
1573
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2313
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1574
2314
|
if (!confirmed) return null;
|
|
1575
2315
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1576
2316
|
return { ...params, showOnDevice: true };
|
|
1577
2317
|
}
|
|
1578
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2318
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2319
|
+
const operationId = this._activeOperationId();
|
|
1579
2320
|
const waitPromise = this._uiRegistry.wait(
|
|
1580
|
-
|
|
2321
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2322
|
+
{ operationId }
|
|
1581
2323
|
);
|
|
1582
|
-
this.emitter.emit(
|
|
1583
|
-
type:
|
|
2324
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
2325
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1584
2326
|
payload: {
|
|
1585
2327
|
vendor: "ledger",
|
|
1586
2328
|
path,
|
|
1587
|
-
accountIndex
|
|
2329
|
+
accountIndex,
|
|
2330
|
+
operationId
|
|
1588
2331
|
}
|
|
1589
2332
|
});
|
|
1590
2333
|
try {
|
|
1591
|
-
const payload = await
|
|
2334
|
+
const payload = await this._awaitUiAnswer(
|
|
2335
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2336
|
+
waitPromise,
|
|
2337
|
+
signal
|
|
2338
|
+
);
|
|
1592
2339
|
return !!payload?.confirmed;
|
|
1593
2340
|
} catch (err) {
|
|
1594
|
-
this.emitter.emit(
|
|
1595
|
-
type:
|
|
1596
|
-
payload: {}
|
|
2341
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2342
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2343
|
+
payload: { operationId }
|
|
1597
2344
|
});
|
|
1598
2345
|
return false;
|
|
1599
2346
|
}
|
|
1600
2347
|
}
|
|
2348
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2349
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2350
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2351
|
+
if (signal.aborted) onAbort();
|
|
2352
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2353
|
+
try {
|
|
2354
|
+
return await waitPromise;
|
|
2355
|
+
} finally {
|
|
2356
|
+
signal.removeEventListener("abort", onAbort);
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
1601
2359
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1602
2360
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1603
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2361
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2362
|
+
const operationId = this._activeOperationId();
|
|
1604
2363
|
const waitPromise = this._uiRegistry.wait(
|
|
1605
|
-
|
|
2364
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2365
|
+
{ operationId }
|
|
1606
2366
|
);
|
|
1607
|
-
this.emitter.emit(
|
|
1608
|
-
type:
|
|
1609
|
-
payload: { vendor: "ledger", appName }
|
|
2367
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
2368
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2369
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1610
2370
|
});
|
|
1611
2371
|
try {
|
|
1612
|
-
const payload = await
|
|
2372
|
+
const payload = await this._awaitUiAnswer(
|
|
2373
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2374
|
+
waitPromise,
|
|
2375
|
+
signal
|
|
2376
|
+
);
|
|
1613
2377
|
return !!payload?.confirmed;
|
|
1614
2378
|
} catch (err) {
|
|
1615
|
-
this.emitter.emit(
|
|
1616
|
-
type:
|
|
1617
|
-
payload: {}
|
|
2379
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2380
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2381
|
+
payload: { operationId }
|
|
1618
2382
|
});
|
|
1619
2383
|
return false;
|
|
1620
2384
|
}
|
|
@@ -1622,34 +2386,45 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1622
2386
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1623
2387
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1624
2388
|
// doesn't kill caller B's await.
|
|
1625
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2389
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1626
2390
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1627
|
-
|
|
2391
|
+
this._assertConnectorReady("connectDevice");
|
|
2392
|
+
if (!this.connector.availableTransports?.includes("usb") && this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1628
2393
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1629
|
-
code:
|
|
2394
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1630
2395
|
});
|
|
1631
2396
|
}
|
|
1632
2397
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1633
2398
|
if (!connectId && this._sessions.size > 0) {
|
|
1634
|
-
if (!
|
|
2399
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1635
2400
|
throw Object.assign(
|
|
1636
2401
|
new Error(
|
|
1637
2402
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
1638
2403
|
),
|
|
1639
|
-
{ code:
|
|
2404
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
|
|
1640
2405
|
);
|
|
1641
2406
|
}
|
|
1642
2407
|
return this._sessions.keys().next().value;
|
|
1643
2408
|
}
|
|
1644
|
-
if (!this._connectingPromise) {
|
|
1645
|
-
|
|
1646
|
-
|
|
2409
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2410
|
+
const controller = new AbortController();
|
|
2411
|
+
this._doConnectAbortController = controller;
|
|
2412
|
+
const innerSignal = controller.signal;
|
|
1647
2413
|
this._connectingPromise = (async () => {
|
|
1648
2414
|
try {
|
|
1649
|
-
return await this._doConnect(
|
|
2415
|
+
return await this._doConnect(
|
|
2416
|
+
innerSignal,
|
|
2417
|
+
connectId,
|
|
2418
|
+
allowUsbEphemeralFallback,
|
|
2419
|
+
preserveOperationId,
|
|
2420
|
+
context
|
|
2421
|
+
);
|
|
1650
2422
|
} finally {
|
|
1651
|
-
this.
|
|
1652
|
-
|
|
2423
|
+
if (this._doConnectAbortController === controller) {
|
|
2424
|
+
this._connectingPromise = null;
|
|
2425
|
+
this._doConnectAbortController = null;
|
|
2426
|
+
if (this._sessions.size === 0) this._activeConnectionType = void 0;
|
|
2427
|
+
}
|
|
1653
2428
|
}
|
|
1654
2429
|
})();
|
|
1655
2430
|
}
|
|
@@ -1658,45 +2433,83 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1658
2433
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1659
2434
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1660
2435
|
// 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
|
-
|
|
2436
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2437
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2438
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2439
|
+
this._activeConnectionType = "usb";
|
|
2440
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2441
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2442
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2443
|
+
(connection) => connection.transport === "usb"
|
|
2444
|
+
);
|
|
2445
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2446
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback || context?.takesPluggedUsb)) {
|
|
2447
|
+
return this._connectFirstOrSelect(
|
|
2448
|
+
usbDevices,
|
|
2449
|
+
usbTarget,
|
|
2450
|
+
allowUsbEphemeralFallback,
|
|
2451
|
+
preserveOperationId,
|
|
2452
|
+
context,
|
|
2453
|
+
internalSignal
|
|
2454
|
+
);
|
|
1676
2455
|
}
|
|
2456
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2457
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2458
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2459
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2460
|
+
});
|
|
2461
|
+
}
|
|
2462
|
+
this._activeConnectionType = "ble";
|
|
2463
|
+
const knownBle = context?.knownConnections?.find(
|
|
2464
|
+
(connection) => connection.transport === "ble"
|
|
2465
|
+
);
|
|
2466
|
+
if (knownBle?.transport === "ble") {
|
|
2467
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2468
|
+
}
|
|
2469
|
+
const bleContext = context ?? {};
|
|
2470
|
+
bleContext.allowBleSelection = true;
|
|
2471
|
+
bleContext.usbFallbackConnectId = usbTarget ?? targetConnectId;
|
|
2472
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2473
|
+
return this._connectFirstOrSelect(
|
|
2474
|
+
bleDevices,
|
|
2475
|
+
void 0,
|
|
2476
|
+
allowUsbEphemeralFallback,
|
|
2477
|
+
preserveOperationId,
|
|
2478
|
+
bleContext,
|
|
2479
|
+
internalSignal
|
|
2480
|
+
);
|
|
2481
|
+
}
|
|
2482
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2483
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1677
2484
|
}
|
|
1678
2485
|
let confirms = 0;
|
|
1679
2486
|
while (!internalSignal.aborted) {
|
|
1680
2487
|
this.emitter.emit("ui-event", {
|
|
1681
|
-
type:
|
|
2488
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
|
|
1682
2489
|
payload: { sessionId: "" }
|
|
1683
2490
|
});
|
|
1684
|
-
let devices = await this.
|
|
2491
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2492
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1685
2493
|
if (devices.length === 0) {
|
|
1686
2494
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1687
2495
|
await new Promise((resolve) => {
|
|
1688
|
-
setTimeout(resolve,
|
|
2496
|
+
setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1689
2497
|
});
|
|
1690
|
-
|
|
2498
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2499
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2500
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1691
2501
|
if (devices.length > 0) break;
|
|
1692
2502
|
}
|
|
1693
2503
|
}
|
|
1694
|
-
if (devices.length > 0) {
|
|
2504
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1695
2505
|
try {
|
|
1696
2506
|
return await this._connectFirstOrSelect(
|
|
1697
2507
|
devices,
|
|
1698
2508
|
targetConnectId,
|
|
1699
|
-
allowUsbEphemeralFallback
|
|
2509
|
+
allowUsbEphemeralFallback,
|
|
2510
|
+
preserveOperationId,
|
|
2511
|
+
context,
|
|
2512
|
+
internalSignal
|
|
1700
2513
|
);
|
|
1701
2514
|
} catch (err) {
|
|
1702
2515
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1716,7 +2529,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1716
2529
|
new Error(
|
|
1717
2530
|
"Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
|
|
1718
2531
|
),
|
|
1719
|
-
{ code:
|
|
2532
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
|
|
1720
2533
|
);
|
|
1721
2534
|
}
|
|
1722
2535
|
await this._waitForDeviceConnect(internalSignal);
|
|
@@ -1725,45 +2538,148 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1725
2538
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1726
2539
|
throw new Error("_doConnect aborted");
|
|
1727
2540
|
}
|
|
1728
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2541
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2542
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1729
2543
|
if (targetConnectId) {
|
|
1730
2544
|
const target = devices.find(
|
|
1731
2545
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1732
2546
|
);
|
|
1733
2547
|
if (target) {
|
|
1734
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2548
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1735
2549
|
}
|
|
1736
|
-
if (!
|
|
2550
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1737
2551
|
debugLog(
|
|
1738
2552
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1739
2553
|
);
|
|
1740
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2554
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1741
2555
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2556
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2557
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2558
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2559
|
+
});
|
|
2560
|
+
if (this._isBleConnection()) {
|
|
2561
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2562
|
+
}
|
|
2563
|
+
throw err;
|
|
1747
2564
|
}
|
|
1748
|
-
throw err;
|
|
1749
2565
|
}
|
|
1750
|
-
|
|
2566
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2567
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback && !context?.allowBleSelection) {
|
|
1751
2568
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1752
|
-
code:
|
|
2569
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1753
2570
|
});
|
|
1754
2571
|
}
|
|
1755
|
-
if (
|
|
1756
|
-
|
|
2572
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2573
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2574
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2575
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2576
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2577
|
+
(connection) => connection.transport === "usb"
|
|
2578
|
+
);
|
|
2579
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : context?.usbFallbackConnectId ?? targetConnectId;
|
|
2580
|
+
const maySelectAnyUsb = allowUsbEphemeralFallback || !usbConnectId && !context?.knownConnections?.some((connection) => connection.transport !== "qr");
|
|
2581
|
+
const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
|
|
2582
|
+
emitter: this.emitter,
|
|
2583
|
+
registry: this._uiRegistry,
|
|
2584
|
+
signal,
|
|
2585
|
+
allowUsbFallback,
|
|
2586
|
+
scan: async () => {
|
|
2587
|
+
if (allowUsbFallback) {
|
|
2588
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2589
|
+
const candidate = usbDevices.find(
|
|
2590
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2591
|
+
) ?? (maySelectAnyUsb && usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2592
|
+
if (candidate) return [candidate];
|
|
2593
|
+
}
|
|
2594
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2595
|
+
},
|
|
2596
|
+
request: {
|
|
2597
|
+
devices,
|
|
2598
|
+
bindingSessionId,
|
|
2599
|
+
context: {
|
|
2600
|
+
kind: "bind-connection",
|
|
2601
|
+
transport: "ble",
|
|
2602
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2603
|
+
},
|
|
2604
|
+
extra: context?.extra,
|
|
2605
|
+
operationId: preserveOperationId
|
|
2606
|
+
}
|
|
2607
|
+
});
|
|
2608
|
+
if (device.connectionType === "usb") {
|
|
2609
|
+
this._activeConnectionType = "usb";
|
|
2610
|
+
if (context) context.selectedConnection = void 0;
|
|
2611
|
+
this._bindingSelectionRequestId = requestId;
|
|
2612
|
+
this._finishBleBinding("cancelled");
|
|
2613
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2614
|
+
}
|
|
2615
|
+
this._bindingSelectionRequestId = requestId;
|
|
2616
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2617
|
+
device.connectId,
|
|
2618
|
+
preserveOperationId,
|
|
2619
|
+
signal
|
|
2620
|
+
);
|
|
2621
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2622
|
+
if (context?.deferBindingSave) {
|
|
2623
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2624
|
+
} else {
|
|
2625
|
+
await this._saveSelectedBleBinding(
|
|
2626
|
+
connected,
|
|
2627
|
+
requestId,
|
|
2628
|
+
context,
|
|
2629
|
+
preserveOperationId,
|
|
2630
|
+
signal
|
|
2631
|
+
);
|
|
2632
|
+
}
|
|
2633
|
+
return connected;
|
|
2634
|
+
}
|
|
2635
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2636
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2637
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2638
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2639
|
+
message: "Select a Ledger device before continuing"
|
|
2640
|
+
});
|
|
2641
|
+
}
|
|
2642
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2643
|
+
const operationId = this._activeOperationId();
|
|
2644
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2645
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2646
|
+
{ requestId, operationId }
|
|
2647
|
+
);
|
|
2648
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2649
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2650
|
+
payload: {
|
|
2651
|
+
devices,
|
|
2652
|
+
requestId,
|
|
2653
|
+
operationId,
|
|
2654
|
+
context: requiresBleSelection ? {
|
|
2655
|
+
kind: "bind-connection",
|
|
2656
|
+
transport: "ble",
|
|
2657
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2658
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2659
|
+
extra: context?.extra
|
|
2660
|
+
}
|
|
2661
|
+
});
|
|
2662
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2663
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2664
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2665
|
+
if (!selected) {
|
|
2666
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2667
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2668
|
+
});
|
|
2669
|
+
}
|
|
2670
|
+
if (context && requiresBleSelection)
|
|
2671
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2672
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1757
2673
|
}
|
|
1758
2674
|
if (devices.length !== 1) {
|
|
1759
2675
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1760
|
-
code:
|
|
2676
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1761
2677
|
});
|
|
1762
2678
|
}
|
|
1763
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2679
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1764
2680
|
}
|
|
1765
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1766
|
-
const result = await this.
|
|
2681
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2682
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1767
2683
|
if (!result.success) {
|
|
1768
2684
|
const payload = result.payload;
|
|
1769
2685
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1774,16 +2690,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1774
2690
|
}
|
|
1775
2691
|
throw rethrow;
|
|
1776
2692
|
}
|
|
1777
|
-
return
|
|
2693
|
+
return result.payload;
|
|
1778
2694
|
}
|
|
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
2695
|
/**
|
|
1788
2696
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1789
2697
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1795,7 +2703,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1795
2703
|
*/
|
|
1796
2704
|
_unwrapConnectorResult(result) {
|
|
1797
2705
|
if (result.success) return result.payload;
|
|
1798
|
-
throw (0,
|
|
2706
|
+
throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
|
|
1799
2707
|
}
|
|
1800
2708
|
/**
|
|
1801
2709
|
* `connector.call` + result unwrap, optionally raced against an abort
|
|
@@ -1804,33 +2712,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1804
2712
|
* lives in one place.
|
|
1805
2713
|
*/
|
|
1806
2714
|
async _callConnector(sessionId, method, params, signal) {
|
|
1807
|
-
|
|
2715
|
+
this._assertConnectorReady(method);
|
|
2716
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2717
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2718
|
+
let promise;
|
|
2719
|
+
try {
|
|
2720
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2721
|
+
} catch (error) {
|
|
2722
|
+
releaseOperation();
|
|
2723
|
+
throw error;
|
|
2724
|
+
}
|
|
1808
2725
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1809
2726
|
return this._unwrapConnectorResult(result);
|
|
1810
2727
|
}
|
|
2728
|
+
_assertConnectorReady(method) {
|
|
2729
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2730
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2731
|
+
}
|
|
2732
|
+
}
|
|
2733
|
+
_runConnectorTeardown(task) {
|
|
2734
|
+
const previous = this._connectorTeardownTail;
|
|
2735
|
+
let releaseTail = () => void 0;
|
|
2736
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2737
|
+
releaseTail = resolve;
|
|
2738
|
+
});
|
|
2739
|
+
this._pendingConnectorTeardowns += 1;
|
|
2740
|
+
return (async () => {
|
|
2741
|
+
try {
|
|
2742
|
+
await previous;
|
|
2743
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2744
|
+
await task();
|
|
2745
|
+
} finally {
|
|
2746
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2747
|
+
releaseTail();
|
|
2748
|
+
}
|
|
2749
|
+
})();
|
|
2750
|
+
}
|
|
2751
|
+
_waitForConnectorOperationsToDrain() {
|
|
2752
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2753
|
+
return Promise.resolve();
|
|
2754
|
+
}
|
|
2755
|
+
return new Promise((resolve) => {
|
|
2756
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2757
|
+
});
|
|
2758
|
+
}
|
|
2759
|
+
_retainConnectorOperation(key) {
|
|
2760
|
+
this._unsettledConnectorOperations.set(
|
|
2761
|
+
key,
|
|
2762
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2763
|
+
);
|
|
2764
|
+
let released = false;
|
|
2765
|
+
return () => {
|
|
2766
|
+
if (released) return;
|
|
2767
|
+
released = true;
|
|
2768
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2769
|
+
if (remaining > 0) {
|
|
2770
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2771
|
+
} else {
|
|
2772
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2773
|
+
}
|
|
2774
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2775
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2776
|
+
this._connectorIdleWaiters.clear();
|
|
2777
|
+
}
|
|
2778
|
+
};
|
|
2779
|
+
}
|
|
1811
2780
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1812
|
-
|
|
1813
|
-
|
|
2781
|
+
const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
|
|
2782
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2783
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2784
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
|
|
2785
|
+
message: "Conflicting Ledger operation ids",
|
|
2786
|
+
params: {
|
|
2787
|
+
positionalOperationId,
|
|
2788
|
+
commonOperationId: commonParams.operationId
|
|
2789
|
+
}
|
|
2790
|
+
});
|
|
2791
|
+
}
|
|
2792
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2793
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2794
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2795
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2796
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2797
|
+
method,
|
|
2798
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2799
|
+
params: summarizeForLog(params, { method })
|
|
2800
|
+
});
|
|
2801
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1814
2802
|
try {
|
|
1815
2803
|
const result = await this._jobQueue.enqueue(
|
|
1816
2804
|
queueKey,
|
|
1817
|
-
async (signal) =>
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2805
|
+
async (signal) => {
|
|
2806
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2807
|
+
try {
|
|
2808
|
+
return await this._runConnectorCall(
|
|
2809
|
+
effectiveConnectId,
|
|
2810
|
+
method,
|
|
2811
|
+
params,
|
|
2812
|
+
signal,
|
|
2813
|
+
fingerprint,
|
|
2814
|
+
permissionDeviceId,
|
|
2815
|
+
commonParams,
|
|
2816
|
+
installContext ?? {},
|
|
2817
|
+
operationId
|
|
2818
|
+
);
|
|
2819
|
+
} catch (error) {
|
|
2820
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2821
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2822
|
+
let keptBundlePick = false;
|
|
2823
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2824
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2825
|
+
keptBundlePick = true;
|
|
2826
|
+
} else {
|
|
2827
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2828
|
+
this._discardPendingBinding(owner, status);
|
|
2829
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2830
|
+
}
|
|
2831
|
+
}
|
|
2832
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2833
|
+
throw error;
|
|
2834
|
+
} finally {
|
|
2835
|
+
if (operationId) {
|
|
2836
|
+
this._activeOperationJobs.delete(operationId);
|
|
2837
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2838
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2839
|
+
}
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2842
|
+
},
|
|
1827
2843
|
{
|
|
1828
2844
|
label: method,
|
|
1829
2845
|
rejectIfBusy: true,
|
|
1830
2846
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1831
2847
|
}
|
|
1832
2848
|
);
|
|
1833
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2849
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2850
|
+
method,
|
|
2851
|
+
success: true,
|
|
2852
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2853
|
+
});
|
|
1834
2854
|
return result;
|
|
1835
2855
|
} catch (err) {
|
|
1836
2856
|
const e = err;
|
|
@@ -1844,15 +2864,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1844
2864
|
}
|
|
1845
2865
|
});
|
|
1846
2866
|
throw err;
|
|
2867
|
+
} finally {
|
|
2868
|
+
releaseOperationRetention?.();
|
|
1847
2869
|
}
|
|
1848
2870
|
}
|
|
2871
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2872
|
+
_abortReason(signal) {
|
|
2873
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2874
|
+
}
|
|
1849
2875
|
/**
|
|
1850
2876
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1851
2877
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1852
2878
|
*/
|
|
1853
2879
|
_abortable(signal, promise) {
|
|
1854
|
-
const getAbortReason = () =>
|
|
2880
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1855
2881
|
if (signal.aborted) {
|
|
2882
|
+
void promise.catch(() => void 0);
|
|
1856
2883
|
return Promise.reject(getAbortReason());
|
|
1857
2884
|
}
|
|
1858
2885
|
return new Promise((resolve, reject) => {
|
|
@@ -1879,39 +2906,101 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1879
2906
|
}
|
|
1880
2907
|
}
|
|
1881
2908
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1882
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2909
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1883
2910
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2911
|
+
const resolvesAppManagementTransport = APP_MANAGEMENT_METHODS.has(method) && this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble");
|
|
2912
|
+
if (!operationId && !resolvesAppManagementTransport) {
|
|
2913
|
+
await this._ensureDevicePermission(
|
|
2914
|
+
connectId,
|
|
2915
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2916
|
+
signal
|
|
2917
|
+
);
|
|
2918
|
+
}
|
|
1889
2919
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1890
2920
|
let effectiveParams = params;
|
|
1891
2921
|
if (method === "btcGetPublicKey") {
|
|
1892
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2922
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1893
2923
|
if (gatedParams === null) {
|
|
1894
2924
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1895
2925
|
_tag: ERROR_TAG.UserAborted,
|
|
1896
|
-
code:
|
|
2926
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1897
2927
|
});
|
|
1898
2928
|
}
|
|
1899
2929
|
effectiveParams = gatedParams;
|
|
1900
2930
|
}
|
|
1901
2931
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1902
|
-
|
|
1903
|
-
|
|
2932
|
+
let businessCallStarted = false;
|
|
2933
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2934
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2935
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2936
|
+
(connection) => connection.transport === knownTransport
|
|
2937
|
+
);
|
|
2938
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2939
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2940
|
+
const checksWallet = Boolean(
|
|
2941
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2942
|
+
);
|
|
2943
|
+
const connectionAttempt = {
|
|
2944
|
+
...commonParams,
|
|
2945
|
+
deferBindingSave: checksWallet,
|
|
2946
|
+
...APP_MANAGEMENT_METHODS.has(method) ? { takesPluggedUsb: true } : {}
|
|
2947
|
+
};
|
|
2948
|
+
const bundleConnection = installContext?.connection;
|
|
2949
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2950
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2951
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2952
|
+
message: "Ledger all-network connection ended"
|
|
2953
|
+
});
|
|
2954
|
+
}
|
|
2955
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2956
|
+
preferredConnectId,
|
|
1904
2957
|
signal,
|
|
1905
|
-
allowUsbEphemeralFallback
|
|
2958
|
+
allowUsbEphemeralFallback,
|
|
2959
|
+
void 0,
|
|
2960
|
+
connectionAttempt
|
|
1906
2961
|
);
|
|
2962
|
+
const walletCheck = installContext?.walletCheck;
|
|
2963
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2964
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2965
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2966
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2967
|
+
});
|
|
2968
|
+
}
|
|
1907
2969
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2970
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2971
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2972
|
+
}
|
|
1908
2973
|
if (!sessionId) {
|
|
2974
|
+
if (operationId) {
|
|
2975
|
+
this._operations.end(operationId, "disconnect");
|
|
2976
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2977
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
2978
|
+
message: "Ledger operation connection is no longer active",
|
|
2979
|
+
params: { operationId, reason: "disconnect" }
|
|
2980
|
+
});
|
|
2981
|
+
}
|
|
1909
2982
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1910
2983
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1911
2984
|
});
|
|
1912
2985
|
}
|
|
2986
|
+
if (!operationId && resolvesAppManagementTransport) {
|
|
2987
|
+
const transport = this._sessionTransports.get(sessionId);
|
|
2988
|
+
await this._ensureDevicePermission(
|
|
2989
|
+
resolvedConnectId,
|
|
2990
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2991
|
+
signal,
|
|
2992
|
+
transport && (isLedgerBleConnectionType(transport) ? "ble" : "hid")
|
|
2993
|
+
);
|
|
2994
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2995
|
+
}
|
|
1913
2996
|
try {
|
|
1914
|
-
|
|
2997
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2998
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2999
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
3000
|
+
}
|
|
3001
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
3002
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
3003
|
+
if (fingerprint && checksWallet) {
|
|
1915
3004
|
const fp = await this._abortable(
|
|
1916
3005
|
signal,
|
|
1917
3006
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1921,14 +3010,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1921
3010
|
)
|
|
1922
3011
|
);
|
|
1923
3012
|
if (!fp.success) {
|
|
3013
|
+
if (pendingBinding) {
|
|
3014
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
3015
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
3016
|
+
}
|
|
3017
|
+
if (operationId) {
|
|
3018
|
+
this._pendingOperationBindings.delete(operationId);
|
|
3019
|
+
this._operations.end(operationId, "explicit");
|
|
3020
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
3021
|
+
}
|
|
1924
3022
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1925
|
-
code:
|
|
3023
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
|
|
1926
3024
|
});
|
|
1927
3025
|
}
|
|
3026
|
+
if (walletCheck) walletCheck.verified = true;
|
|
3027
|
+
}
|
|
3028
|
+
if (pendingBinding && bindingOwner) {
|
|
3029
|
+
bindingOwner.pendingBinding = void 0;
|
|
3030
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
3031
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
3032
|
+
await this._saveSelectedBleBinding(
|
|
3033
|
+
pendingBinding.connectId,
|
|
3034
|
+
pendingBinding.requestId,
|
|
3035
|
+
bindingOwner,
|
|
3036
|
+
operationId,
|
|
3037
|
+
signal,
|
|
3038
|
+
fingerprint && checksWallet ? {
|
|
3039
|
+
vendor: "ledger",
|
|
3040
|
+
type: "chainFingerprint",
|
|
3041
|
+
chain: fingerprint.chain,
|
|
3042
|
+
value: fingerprint.deviceId
|
|
3043
|
+
} : void 0
|
|
3044
|
+
);
|
|
3045
|
+
}
|
|
3046
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
3047
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
3048
|
+
connectId: resolvedConnectId,
|
|
3049
|
+
chain: fingerprint.chain,
|
|
3050
|
+
fingerprint: fingerprint.deviceId
|
|
3051
|
+
});
|
|
1928
3052
|
}
|
|
1929
|
-
|
|
3053
|
+
businessCallStarted = true;
|
|
3054
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3055
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3056
|
+
return result;
|
|
1930
3057
|
} catch (err) {
|
|
1931
3058
|
if (signal.aborted) throw err;
|
|
3059
|
+
if (isLostConnectionError(err)) {
|
|
3060
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3061
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3062
|
+
else {
|
|
3063
|
+
this._sessions.delete(resolvedConnectId);
|
|
3064
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3065
|
+
}
|
|
3066
|
+
const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3067
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
3068
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3069
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
|
|
3070
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
3071
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
|
|
3072
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3073
|
+
});
|
|
3074
|
+
}
|
|
1932
3075
|
const errObj = err;
|
|
1933
3076
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1934
3077
|
message: errObj?.message,
|
|
@@ -1940,8 +3083,66 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1940
3083
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1941
3084
|
isStuckApp: isStuckAppStateError(err)
|
|
1942
3085
|
});
|
|
3086
|
+
const assertSessionCurrent = (message) => {
|
|
3087
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3088
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3089
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
3090
|
+
message
|
|
3091
|
+
});
|
|
3092
|
+
};
|
|
3093
|
+
if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3094
|
+
await this._waitForDeviceConnect(signal);
|
|
3095
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3096
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3097
|
+
return this._runConnectorCall(
|
|
3098
|
+
resolvedConnectId,
|
|
3099
|
+
method,
|
|
3100
|
+
effectiveParams,
|
|
3101
|
+
signal,
|
|
3102
|
+
fingerprint,
|
|
3103
|
+
permissionDeviceId,
|
|
3104
|
+
commonParams,
|
|
3105
|
+
installContext,
|
|
3106
|
+
operationId,
|
|
3107
|
+
lockedRetryBudget - 1
|
|
3108
|
+
);
|
|
3109
|
+
}
|
|
3110
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3111
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3112
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3113
|
+
try {
|
|
3114
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3115
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3116
|
+
return retried;
|
|
3117
|
+
} catch (retryErr) {
|
|
3118
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3119
|
+
if (isLostConnectionError(retryErr)) {
|
|
3120
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3121
|
+
else {
|
|
3122
|
+
this._sessions.delete(resolvedConnectId);
|
|
3123
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3124
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3125
|
+
}
|
|
3126
|
+
const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3127
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3128
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
|
|
3129
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3130
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3131
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3132
|
+
});
|
|
3133
|
+
}
|
|
3134
|
+
throw retryErr;
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
|
|
3138
|
+
this._sessions.delete(resolvedConnectId);
|
|
3139
|
+
this._sessionTransports.delete(sessionId);
|
|
3140
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3141
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3142
|
+
throw err;
|
|
3143
|
+
}
|
|
1943
3144
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1944
|
-
const isAppMissing = isAppNotInstalledError(err) || err?.code ===
|
|
3145
|
+
const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
1945
3146
|
if (autoInstallApp && isAppMissing) {
|
|
1946
3147
|
if (installContext?.deviceOutOfMemoryError) {
|
|
1947
3148
|
throw installContext.deviceOutOfMemoryError;
|
|
@@ -1949,30 +3150,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1949
3150
|
const appName = err?.appName ?? mapLedgerError(err).appName;
|
|
1950
3151
|
if (appName) {
|
|
1951
3152
|
if (installContext?.installAttemptedAppNames?.has(appName)) {
|
|
1952
|
-
throw (0,
|
|
1953
|
-
code:
|
|
3153
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3154
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
|
|
1954
3155
|
message: `${appName} install reported success but the app is still missing on device`,
|
|
1955
3156
|
_tag: ERROR_TAG.AppInstallVerifyFailed,
|
|
1956
3157
|
appName
|
|
1957
3158
|
});
|
|
1958
3159
|
}
|
|
1959
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3160
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1960
3161
|
if (!confirmed) {
|
|
1961
|
-
throw (0,
|
|
1962
|
-
code:
|
|
3162
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3163
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1963
3164
|
message: `User declined to install ${appName}`,
|
|
1964
3165
|
_tag: ERROR_TAG.UserAborted,
|
|
1965
3166
|
appName
|
|
1966
3167
|
});
|
|
1967
3168
|
}
|
|
1968
3169
|
this.emitter.emit("ui-event", {
|
|
1969
|
-
type:
|
|
3170
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1970
3171
|
payload: { connectId: resolvedConnectId, appName, progress: 0 }
|
|
1971
3172
|
});
|
|
1972
3173
|
try {
|
|
1973
3174
|
await this._callConnector(sessionId, "installApp", { appName }, signal);
|
|
1974
3175
|
} catch (installErr) {
|
|
1975
|
-
if (mapLedgerError(installErr).code ===
|
|
3176
|
+
if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
|
|
1976
3177
|
if (installContext) {
|
|
1977
3178
|
installContext.deviceOutOfMemoryError = installErr;
|
|
1978
3179
|
}
|
|
@@ -1983,9 +3184,9 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1983
3184
|
installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
|
|
1984
3185
|
installContext.installAttemptedAppNames.add(appName);
|
|
1985
3186
|
}
|
|
1986
|
-
this.emitter.emit(
|
|
1987
|
-
type:
|
|
1988
|
-
payload: {}
|
|
3187
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3188
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
3189
|
+
payload: { operationId }
|
|
1989
3190
|
});
|
|
1990
3191
|
return await this._runConnectorCall(
|
|
1991
3192
|
resolvedConnectId,
|
|
@@ -1995,157 +3196,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1995
3196
|
fingerprint,
|
|
1996
3197
|
permissionDeviceId,
|
|
1997
3198
|
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
|
|
3199
|
+
installContext,
|
|
3200
|
+
operationId
|
|
2025
3201
|
);
|
|
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
3202
|
}
|
|
2042
3203
|
}
|
|
2043
|
-
if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
|
|
2044
|
-
let lastErr = err;
|
|
2045
|
-
for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
|
|
2046
|
-
if (signal.aborted) throw lastErr;
|
|
2047
|
-
try {
|
|
2048
|
-
this._sessions.delete(resolvedConnectId);
|
|
2049
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2050
|
-
if (isDeviceDisconnectedError(lastErr)) {
|
|
2051
|
-
try {
|
|
2052
|
-
this.connector.reset?.();
|
|
2053
|
-
} catch {
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
const reConnectId = await this.ensureConnected(
|
|
2057
|
-
resolvedConnectId,
|
|
2058
|
-
signal,
|
|
2059
|
-
allowUsbEphemeralFallback
|
|
2060
|
-
);
|
|
2061
|
-
const reSessionId = this._sessions.get(reConnectId);
|
|
2062
|
-
if (!reSessionId) throw lastErr;
|
|
2063
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2064
|
-
const fp = await this._abortable(
|
|
2065
|
-
signal,
|
|
2066
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2067
|
-
reSessionId,
|
|
2068
|
-
fingerprint.deviceId,
|
|
2069
|
-
fingerprint.chain
|
|
2070
|
-
)
|
|
2071
|
-
);
|
|
2072
|
-
if (!fp.success) {
|
|
2073
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2074
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2075
|
-
});
|
|
2076
|
-
}
|
|
2077
|
-
}
|
|
2078
|
-
return await this._callConnector(reSessionId, method, effectiveParams, signal);
|
|
2079
|
-
} catch (retryErr) {
|
|
2080
|
-
if (signal.aborted) throw retryErr;
|
|
2081
|
-
lastErr = retryErr;
|
|
2082
|
-
const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
|
|
2083
|
-
if (!canRetry) {
|
|
2084
|
-
throw retryErr;
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
throw lastErr;
|
|
2089
|
-
}
|
|
2090
|
-
if (isTimeoutError(err)) {
|
|
2091
|
-
debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
|
|
2092
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2093
|
-
return this._retryWithFreshConnection(
|
|
2094
|
-
resolvedConnectId,
|
|
2095
|
-
method,
|
|
2096
|
-
effectiveParams,
|
|
2097
|
-
signal,
|
|
2098
|
-
err,
|
|
2099
|
-
fingerprint
|
|
2100
|
-
);
|
|
2101
|
-
}
|
|
2102
|
-
if (isConnectionLevelError(err)) {
|
|
2103
|
-
debugLog("[LedgerAdapter] connection-level fail-closed reset");
|
|
2104
|
-
this._sessions.delete(resolvedConnectId);
|
|
2105
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2106
|
-
this.connector.reset();
|
|
2107
|
-
const codeNum = err?.code;
|
|
2108
|
-
throw Object.assign(err, {
|
|
2109
|
-
code: codeNum ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected
|
|
2110
|
-
});
|
|
2111
|
-
}
|
|
2112
3204
|
throw err;
|
|
2113
3205
|
}
|
|
2114
3206
|
}
|
|
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
3207
|
_sleepAbortable(ms, signal) {
|
|
2150
3208
|
return new Promise((resolve, reject) => {
|
|
2151
3209
|
if (signal.aborted) {
|
|
@@ -2164,115 +3222,26 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2164
3222
|
});
|
|
2165
3223
|
}
|
|
2166
3224
|
/**
|
|
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.
|
|
3225
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3226
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2172
3227
|
*/
|
|
2173
|
-
async
|
|
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
|
|
2259
|
-
*/
|
|
2260
|
-
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
3228
|
+
async _ensureDevicePermission(connectId, deviceId, signal, transportOverride) {
|
|
2261
3229
|
if (signal?.aborted) {
|
|
2262
3230
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2263
3231
|
}
|
|
2264
|
-
const transportType = this.activeTransport ?? "hid";
|
|
3232
|
+
const transportType = transportOverride ?? this.activeTransport ?? "hid";
|
|
3233
|
+
const operationId = this._activeOperationId();
|
|
2265
3234
|
const waitPromise = this._uiRegistry.wait(
|
|
2266
|
-
|
|
2267
|
-
{ timeoutMs: 6e4 }
|
|
3235
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3236
|
+
{ timeoutMs: 6e4, operationId }
|
|
2268
3237
|
);
|
|
2269
|
-
this.emitter.emit(
|
|
2270
|
-
type:
|
|
2271
|
-
payload: { transportType, connectId, deviceId }
|
|
3238
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
3239
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3240
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2272
3241
|
});
|
|
2273
3242
|
let response;
|
|
2274
3243
|
const onAbort = () => {
|
|
2275
|
-
this._uiRegistry.cancel(
|
|
3244
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
|
|
2276
3245
|
};
|
|
2277
3246
|
try {
|
|
2278
3247
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -2281,14 +3250,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2281
3250
|
if (signal?.aborted) {
|
|
2282
3251
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2283
3252
|
}
|
|
2284
|
-
if (err?._tag ===
|
|
2285
|
-
this.emitter.emit(
|
|
2286
|
-
type:
|
|
2287
|
-
payload: {}
|
|
3253
|
+
if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
|
|
3254
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3255
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
3256
|
+
payload: { operationId }
|
|
2288
3257
|
});
|
|
2289
3258
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2290
3259
|
_tag: ERROR_TAG.UserAborted,
|
|
2291
|
-
code:
|
|
3260
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
2292
3261
|
cause: err
|
|
2293
3262
|
});
|
|
2294
3263
|
}
|
|
@@ -2299,7 +3268,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2299
3268
|
const { granted, reason, message } = response;
|
|
2300
3269
|
if (!granted) {
|
|
2301
3270
|
throw Object.assign(new Error(message ?? "Device permission denied"), {
|
|
2302
|
-
code:
|
|
3271
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
|
|
2303
3272
|
reason
|
|
2304
3273
|
});
|
|
2305
3274
|
}
|
|
@@ -2313,8 +3282,16 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2313
3282
|
const tag = err && typeof err === "object" ? err._tag : void 0;
|
|
2314
3283
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2315
3284
|
const e = err;
|
|
2316
|
-
const params = e.code ===
|
|
2317
|
-
return ledgerFailure(
|
|
3285
|
+
const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
3286
|
+
return ledgerFailure(
|
|
3287
|
+
e.code,
|
|
3288
|
+
e.message ?? "Unknown error",
|
|
3289
|
+
e.appName,
|
|
3290
|
+
tag,
|
|
3291
|
+
params,
|
|
3292
|
+
void 0,
|
|
3293
|
+
(0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
|
|
3294
|
+
);
|
|
2318
3295
|
}
|
|
2319
3296
|
const mapped = mapLedgerError(err);
|
|
2320
3297
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2341,7 +3318,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2341
3318
|
deviceId: device.deviceId,
|
|
2342
3319
|
connectId: device.connectId,
|
|
2343
3320
|
label: device.name,
|
|
2344
|
-
connectionType: this.connector.connectionType,
|
|
3321
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2345
3322
|
rssi: device.rssi,
|
|
2346
3323
|
isConnectable: device.isConnectable,
|
|
2347
3324
|
serialNumber: device.serialNumber,
|
|
@@ -2639,16 +3616,20 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
|
|
|
2639
3616
|
var import_context_module = require("@ledgerhq/context-module");
|
|
2640
3617
|
|
|
2641
3618
|
// src/signer/SignerEth.ts
|
|
2642
|
-
var
|
|
3619
|
+
var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
|
|
2643
3620
|
|
|
2644
3621
|
// src/signer/deviceActionToPromise.ts
|
|
2645
3622
|
var import_device_management_kit = require("@ledgerhq/device-management-kit");
|
|
2646
3623
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3624
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
3625
|
+
var INTERACTION_PROMPT_DELAY_MS = 500;
|
|
2647
3626
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2648
3627
|
return new Promise((resolve, reject) => {
|
|
2649
3628
|
let settled = false;
|
|
2650
3629
|
let lastStep;
|
|
2651
3630
|
let activeInteraction;
|
|
3631
|
+
let pendingInteraction;
|
|
3632
|
+
let pendingInteractionTimer = null;
|
|
2652
3633
|
const observedSteps = [];
|
|
2653
3634
|
let sub;
|
|
2654
3635
|
let timer = null;
|
|
@@ -2676,31 +3657,52 @@ function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_
|
|
|
2676
3657
|
}
|
|
2677
3658
|
return false;
|
|
2678
3659
|
};
|
|
3660
|
+
const cancelPendingInteraction = () => {
|
|
3661
|
+
if (pendingInteractionTimer) clearTimeout(pendingInteractionTimer);
|
|
3662
|
+
pendingInteractionTimer = null;
|
|
3663
|
+
pendingInteraction = void 0;
|
|
3664
|
+
};
|
|
3665
|
+
const showInteraction = (interactionName) => {
|
|
3666
|
+
activeInteraction = interactionName;
|
|
3667
|
+
debugLog(
|
|
3668
|
+
"[DeviceAction] requiredUserInteraction",
|
|
3669
|
+
`interaction=${interactionName}`,
|
|
3670
|
+
`step=${lastStep ?? "unknown"}`
|
|
3671
|
+
);
|
|
3672
|
+
if (interactionName === "unlock-device" && timer) {
|
|
3673
|
+
clearTimeout(timer);
|
|
3674
|
+
timer = null;
|
|
3675
|
+
}
|
|
3676
|
+
onInteraction?.(interactionName);
|
|
3677
|
+
};
|
|
2679
3678
|
const emitInteraction = (interaction) => {
|
|
2680
3679
|
if (!onInteraction) {
|
|
2681
3680
|
return;
|
|
2682
3681
|
}
|
|
2683
3682
|
if (!interaction || interaction === "none") {
|
|
3683
|
+
cancelPendingInteraction();
|
|
2684
3684
|
clearActiveInteraction();
|
|
2685
3685
|
return;
|
|
2686
3686
|
}
|
|
2687
3687
|
const interactionName = String(interaction);
|
|
2688
|
-
if (interactionName === activeInteraction) {
|
|
3688
|
+
if (interactionName === activeInteraction || interactionName === pendingInteraction) {
|
|
2689
3689
|
return;
|
|
2690
3690
|
}
|
|
2691
|
-
|
|
2692
|
-
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
);
|
|
2697
|
-
if (interaction === "unlock-device" && timer) {
|
|
2698
|
-
clearTimeout(timer);
|
|
2699
|
-
timer = null;
|
|
3691
|
+
cancelPendingInteraction();
|
|
3692
|
+
clearActiveInteraction();
|
|
3693
|
+
if (interactionName === "unlock-device") {
|
|
3694
|
+
showInteraction(interactionName);
|
|
3695
|
+
return;
|
|
2700
3696
|
}
|
|
2701
|
-
|
|
3697
|
+
pendingInteraction = interactionName;
|
|
3698
|
+
pendingInteractionTimer = setTimeout(() => {
|
|
3699
|
+
pendingInteractionTimer = null;
|
|
3700
|
+
pendingInteraction = void 0;
|
|
3701
|
+
if (!settled) showInteraction(interactionName);
|
|
3702
|
+
}, INTERACTION_PROMPT_DELAY_MS);
|
|
2702
3703
|
};
|
|
2703
3704
|
const completeInteraction = () => {
|
|
3705
|
+
cancelPendingInteraction();
|
|
2704
3706
|
if (!clearActiveInteraction()) {
|
|
2705
3707
|
onInteraction?.("interaction-complete");
|
|
2706
3708
|
}
|
|
@@ -2831,7 +3833,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2831
3833
|
}
|
|
2832
3834
|
|
|
2833
3835
|
// src/signer/SignerEth.ts
|
|
2834
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2835
3836
|
var SignerEth = class {
|
|
2836
3837
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2837
3838
|
constructor(_sdk) {
|
|
@@ -2852,7 +3853,7 @@ var SignerEth = class {
|
|
|
2852
3853
|
);
|
|
2853
3854
|
}
|
|
2854
3855
|
async signTransaction(derivationPath, serializedTxHex) {
|
|
2855
|
-
const action = this._sdk.signTransaction(derivationPath, (0,
|
|
3856
|
+
const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
|
|
2856
3857
|
return deviceActionToPromise(
|
|
2857
3858
|
action,
|
|
2858
3859
|
this.onInteraction,
|
|
@@ -2861,7 +3862,7 @@ var SignerEth = class {
|
|
|
2861
3862
|
);
|
|
2862
3863
|
}
|
|
2863
3864
|
async signMessage(derivationPath, message) {
|
|
2864
|
-
const action = this._sdk.signMessage(derivationPath, (0,
|
|
3865
|
+
const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
|
|
2865
3866
|
return deviceActionToPromise(
|
|
2866
3867
|
action,
|
|
2867
3868
|
this.onInteraction,
|
|
@@ -2902,7 +3903,7 @@ var SignerManager = class _SignerManager {
|
|
|
2902
3903
|
return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
|
|
2903
3904
|
}
|
|
2904
3905
|
static _createContextModule() {
|
|
2905
|
-
const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3906
|
+
const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2906
3907
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2907
3908
|
}
|
|
2908
3909
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2921,23 +3922,44 @@ var SignerManager = class _SignerManager {
|
|
|
2921
3922
|
};
|
|
2922
3923
|
|
|
2923
3924
|
// src/connector/chains/evm.ts
|
|
2924
|
-
var
|
|
3925
|
+
var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
|
|
2925
3926
|
|
|
2926
3927
|
// src/connector/chains/utils.ts
|
|
2927
|
-
var
|
|
3928
|
+
var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
|
|
2928
3929
|
function normalizePath(path) {
|
|
2929
3930
|
return path.startsWith("m/") ? path.slice(2) : path;
|
|
2930
3931
|
}
|
|
2931
3932
|
function collapseSignerInteraction(interaction) {
|
|
2932
3933
|
switch (interaction) {
|
|
2933
3934
|
case "confirm-open-app":
|
|
2934
|
-
return
|
|
3935
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
|
|
2935
3936
|
case "unlock-device":
|
|
2936
|
-
return
|
|
3937
|
+
return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
|
|
2937
3938
|
case "interaction-complete":
|
|
2938
|
-
return
|
|
3939
|
+
return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
|
|
2939
3940
|
default:
|
|
2940
|
-
return
|
|
3941
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
|
|
3942
|
+
}
|
|
3943
|
+
}
|
|
3944
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3945
|
+
signer.onInteraction = (interaction) => {
|
|
3946
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3947
|
+
ctx.emit("ui-event", {
|
|
3948
|
+
type: collapseSignerInteraction(interaction),
|
|
3949
|
+
payload: { sessionId }
|
|
3950
|
+
});
|
|
3951
|
+
};
|
|
3952
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3953
|
+
return signer;
|
|
3954
|
+
}
|
|
3955
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3956
|
+
try {
|
|
3957
|
+
return await call();
|
|
3958
|
+
} catch (err) {
|
|
3959
|
+
ctx.invalidateSession(sessionId);
|
|
3960
|
+
throw ctx.wrapError(err);
|
|
3961
|
+
} finally {
|
|
3962
|
+
ctx.clearCanceller(sessionId);
|
|
2941
3963
|
}
|
|
2942
3964
|
}
|
|
2943
3965
|
|
|
@@ -2963,7 +3985,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2963
3985
|
new Error(
|
|
2964
3986
|
"Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
|
|
2965
3987
|
),
|
|
2966
|
-
{ code:
|
|
3988
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
|
|
2967
3989
|
);
|
|
2968
3990
|
}
|
|
2969
3991
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
@@ -2972,8 +3994,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2972
3994
|
const result = await signer.signTransaction(path, params.serializedTx);
|
|
2973
3995
|
return {
|
|
2974
3996
|
v: `0x${result.v.toString(16)}`,
|
|
2975
|
-
r: (0,
|
|
2976
|
-
s: (0,
|
|
3997
|
+
r: (0, import_hwk_adapter_core7.padHex64)(result.r),
|
|
3998
|
+
s: (0, import_hwk_adapter_core7.padHex64)(result.s)
|
|
2977
3999
|
};
|
|
2978
4000
|
} catch (err) {
|
|
2979
4001
|
ctx.invalidateSession(sessionId);
|
|
@@ -2987,8 +4009,8 @@ async function evmSignMessage(ctx, sessionId, params) {
|
|
|
2987
4009
|
const path = normalizePath(params.path);
|
|
2988
4010
|
try {
|
|
2989
4011
|
const result = await signer.signMessage(path, params.message);
|
|
2990
|
-
const rHex = (0,
|
|
2991
|
-
const sHex = (0,
|
|
4012
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
4013
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
2992
4014
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
2993
4015
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
2994
4016
|
} catch (err) {
|
|
@@ -3004,15 +4026,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
|
|
|
3004
4026
|
new Error(
|
|
3005
4027
|
'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
|
|
3006
4028
|
),
|
|
3007
|
-
{ code:
|
|
4029
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
|
|
3008
4030
|
);
|
|
3009
4031
|
}
|
|
3010
4032
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
3011
4033
|
const path = normalizePath(params.path);
|
|
3012
4034
|
try {
|
|
3013
4035
|
const result = await signer.signTypedData(path, params.data);
|
|
3014
|
-
const rHex = (0,
|
|
3015
|
-
const sHex = (0,
|
|
4036
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
4037
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
3016
4038
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3017
4039
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
3018
4040
|
} catch (err) {
|
|
@@ -3039,15 +4061,14 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3039
4061
|
}
|
|
3040
4062
|
|
|
3041
4063
|
// src/connector/chains/btc.ts
|
|
3042
|
-
var
|
|
3043
|
-
var
|
|
4064
|
+
var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
|
|
4065
|
+
var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
|
|
3044
4066
|
|
|
3045
4067
|
// src/signer/SignerBtc.ts
|
|
3046
|
-
var
|
|
4068
|
+
var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
|
|
3047
4069
|
function hexToUtf8(hex) {
|
|
3048
|
-
return new TextDecoder().decode((0,
|
|
4070
|
+
return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
|
|
3049
4071
|
}
|
|
3050
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3051
4072
|
var SignerBtc = class {
|
|
3052
4073
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3053
4074
|
constructor(_sdk) {
|
|
@@ -3061,7 +4082,7 @@ var SignerBtc = class {
|
|
|
3061
4082
|
return deviceActionToPromise(
|
|
3062
4083
|
action,
|
|
3063
4084
|
this.onInteraction,
|
|
3064
|
-
void 0,
|
|
4085
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3065
4086
|
this.onRegisterCanceller
|
|
3066
4087
|
);
|
|
3067
4088
|
}
|
|
@@ -3079,14 +4100,14 @@ var SignerBtc = class {
|
|
|
3079
4100
|
const result = await deviceActionToPromise(
|
|
3080
4101
|
action,
|
|
3081
4102
|
this.onInteraction,
|
|
3082
|
-
void 0,
|
|
4103
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3083
4104
|
this.onRegisterCanceller
|
|
3084
4105
|
);
|
|
3085
4106
|
debugLog(
|
|
3086
4107
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3087
4108
|
typeof result,
|
|
3088
4109
|
"value:",
|
|
3089
|
-
|
|
4110
|
+
summarizeForLog(result)
|
|
3090
4111
|
);
|
|
3091
4112
|
if (typeof result === "string") return result;
|
|
3092
4113
|
return result.extendedPublicKey;
|
|
@@ -3115,7 +4136,7 @@ var SignerBtc = class {
|
|
|
3115
4136
|
return deviceActionToPromise(
|
|
3116
4137
|
action,
|
|
3117
4138
|
this.onInteraction,
|
|
3118
|
-
|
|
4139
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3119
4140
|
this.onRegisterCanceller
|
|
3120
4141
|
);
|
|
3121
4142
|
}
|
|
@@ -3128,7 +4149,7 @@ var SignerBtc = class {
|
|
|
3128
4149
|
return deviceActionToPromise(
|
|
3129
4150
|
action,
|
|
3130
4151
|
this.onInteraction,
|
|
3131
|
-
|
|
4152
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3132
4153
|
this.onRegisterCanceller
|
|
3133
4154
|
);
|
|
3134
4155
|
}
|
|
@@ -3141,7 +4162,7 @@ var SignerBtc = class {
|
|
|
3141
4162
|
return deviceActionToPromise(
|
|
3142
4163
|
action,
|
|
3143
4164
|
this.onInteraction,
|
|
3144
|
-
|
|
4165
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3145
4166
|
this.onRegisterCanceller
|
|
3146
4167
|
);
|
|
3147
4168
|
}
|
|
@@ -3160,11 +4181,25 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3160
4181
|
return DDT.TAPROOT;
|
|
3161
4182
|
default:
|
|
3162
4183
|
throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
|
|
3163
|
-
code:
|
|
4184
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3164
4185
|
});
|
|
3165
4186
|
}
|
|
3166
4187
|
}
|
|
4188
|
+
function assertBitcoinMainnet(coin) {
|
|
4189
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4190
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4191
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
|
|
4192
|
+
});
|
|
4193
|
+
}
|
|
4194
|
+
}
|
|
3167
4195
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4196
|
+
assertBitcoinMainnet(params.coin);
|
|
4197
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4198
|
+
throw Object.assign(
|
|
4199
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4200
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
4201
|
+
);
|
|
4202
|
+
}
|
|
3168
4203
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3169
4204
|
const path = normalizePath(params.path);
|
|
3170
4205
|
try {
|
|
@@ -3195,6 +4230,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3195
4230
|
}
|
|
3196
4231
|
}
|
|
3197
4232
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4233
|
+
assertBitcoinMainnet(params.coin);
|
|
3198
4234
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3199
4235
|
const path = normalizePath(params.path);
|
|
3200
4236
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3202,7 +4238,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3202
4238
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3203
4239
|
checkOnDevice: params.showOnDevice ?? false
|
|
3204
4240
|
});
|
|
3205
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4241
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3206
4242
|
return { xpub, path: params.path };
|
|
3207
4243
|
} catch (err) {
|
|
3208
4244
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3216,7 +4252,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3216
4252
|
if (!params.psbt) {
|
|
3217
4253
|
throw Object.assign(
|
|
3218
4254
|
new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
|
|
3219
|
-
{ code:
|
|
4255
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
3220
4256
|
);
|
|
3221
4257
|
}
|
|
3222
4258
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3230,7 +4266,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3230
4266
|
debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
|
|
3231
4267
|
const wallet = new DefaultWallet(path, template);
|
|
3232
4268
|
const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
|
|
3233
|
-
return { serializedTx: (0,
|
|
4269
|
+
return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
|
|
3234
4270
|
} catch (err) {
|
|
3235
4271
|
ctx.invalidateSession(sessionId);
|
|
3236
4272
|
throw ctx.wrapError(err);
|
|
@@ -3241,7 +4277,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3241
4277
|
async function btcSignPsbt(ctx, sessionId, params) {
|
|
3242
4278
|
if (!params.psbt) {
|
|
3243
4279
|
throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
|
|
3244
|
-
code:
|
|
4280
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3245
4281
|
});
|
|
3246
4282
|
}
|
|
3247
4283
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3271,8 +4307,8 @@ async function btcSignMessage(ctx, sessionId, params) {
|
|
|
3271
4307
|
try {
|
|
3272
4308
|
const result = await btcSigner.signMessage(path, params.message);
|
|
3273
4309
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3274
|
-
const rHex = (0,
|
|
3275
|
-
const sHex = (0,
|
|
4310
|
+
const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
|
|
4311
|
+
const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
|
|
3276
4312
|
return { signature: `${vHex}${rHex}${sHex}` };
|
|
3277
4313
|
} catch (err) {
|
|
3278
4314
|
ctx.invalidateSession(sessionId);
|
|
@@ -3323,7 +4359,7 @@ function _isScriptPathInput(input) {
|
|
|
3323
4359
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3324
4360
|
}
|
|
3325
4361
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3326
|
-
const psbt =
|
|
4362
|
+
const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
|
|
3327
4363
|
for (const sig of signatures) {
|
|
3328
4364
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3329
4365
|
if (!input) {
|
|
@@ -3372,7 +4408,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3372
4408
|
}
|
|
3373
4409
|
|
|
3374
4410
|
// src/connector/chains/sol.ts
|
|
3375
|
-
var
|
|
4411
|
+
var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
|
|
4412
|
+
var import_bs58 = __toESM(require("bs58"));
|
|
3376
4413
|
|
|
3377
4414
|
// src/signer/SignerSol.ts
|
|
3378
4415
|
var SignerSol = class {
|
|
@@ -3390,7 +4427,7 @@ var SignerSol = class {
|
|
|
3390
4427
|
return deviceActionToPromise(
|
|
3391
4428
|
action,
|
|
3392
4429
|
this.onInteraction,
|
|
3393
|
-
void 0,
|
|
4430
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3394
4431
|
this.onRegisterCanceller
|
|
3395
4432
|
);
|
|
3396
4433
|
}
|
|
@@ -3402,7 +4439,7 @@ var SignerSol = class {
|
|
|
3402
4439
|
return deviceActionToPromise(
|
|
3403
4440
|
action,
|
|
3404
4441
|
this.onInteraction,
|
|
3405
|
-
|
|
4442
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3406
4443
|
this.onRegisterCanceller
|
|
3407
4444
|
);
|
|
3408
4445
|
}
|
|
@@ -3415,7 +4452,7 @@ var SignerSol = class {
|
|
|
3415
4452
|
return deviceActionToPromise(
|
|
3416
4453
|
action,
|
|
3417
4454
|
this.onInteraction,
|
|
3418
|
-
|
|
4455
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3419
4456
|
this.onRegisterCanceller
|
|
3420
4457
|
);
|
|
3421
4458
|
}
|
|
@@ -3440,10 +4477,10 @@ async function solGetAddress(ctx, sessionId, params) {
|
|
|
3440
4477
|
async function solSignTransaction(ctx, sessionId, params) {
|
|
3441
4478
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3442
4479
|
const path = normalizePath(params.path);
|
|
3443
|
-
const txBytes = (0,
|
|
4480
|
+
const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
|
|
3444
4481
|
try {
|
|
3445
4482
|
const result = await solSigner.signTransaction(path, txBytes);
|
|
3446
|
-
return { signature: (0,
|
|
4483
|
+
return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
|
|
3447
4484
|
} catch (err) {
|
|
3448
4485
|
ctx.invalidateSession(sessionId);
|
|
3449
4486
|
throw ctx.wrapError(err);
|
|
@@ -3454,10 +4491,23 @@ async function solSignTransaction(ctx, sessionId, params) {
|
|
|
3454
4491
|
async function solSignMessage(ctx, sessionId, params) {
|
|
3455
4492
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3456
4493
|
const path = normalizePath(params.path);
|
|
3457
|
-
const messageBytes = (0,
|
|
4494
|
+
const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
|
|
3458
4495
|
try {
|
|
4496
|
+
if (params.messageVersion === 1) {
|
|
4497
|
+
const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
|
|
4498
|
+
message: messageBytes,
|
|
4499
|
+
requiredSigners: params.requiredSigners
|
|
4500
|
+
});
|
|
4501
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4502
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4503
|
+
);
|
|
4504
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4505
|
+
version: SignMessageVersion.Raw
|
|
4506
|
+
});
|
|
4507
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4508
|
+
}
|
|
3459
4509
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3460
|
-
return { signature: result.signature };
|
|
4510
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3461
4511
|
} catch (err) {
|
|
3462
4512
|
ctx.invalidateSession(sessionId);
|
|
3463
4513
|
throw ctx.wrapError(err);
|
|
@@ -3465,11 +4515,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3465
4515
|
ctx.clearCanceller(sessionId);
|
|
3466
4516
|
}
|
|
3467
4517
|
}
|
|
4518
|
+
function decodeBase58Signature(signature) {
|
|
4519
|
+
const bytes = import_bs58.default.decode(signature);
|
|
4520
|
+
if (bytes.length !== 64) {
|
|
4521
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4522
|
+
}
|
|
4523
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
|
|
4524
|
+
}
|
|
4525
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4526
|
+
const bytes = import_bs58.default.decode(envelope);
|
|
4527
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4528
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4529
|
+
}
|
|
4530
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
|
|
4531
|
+
}
|
|
3468
4532
|
async function _createSolSigner(ctx, sessionId) {
|
|
3469
4533
|
const dmk = await ctx.getOrCreateDmk();
|
|
3470
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4534
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4535
|
+
"@ledgerhq/context-module"
|
|
4536
|
+
);
|
|
3471
4537
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3472
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4538
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3473
4539
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3474
4540
|
const signer = new SignerSol(sdkSigner);
|
|
3475
4541
|
signer.onInteraction = (interaction) => {
|
|
@@ -3485,316 +4551,119 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3485
4551
|
return signer;
|
|
3486
4552
|
}
|
|
3487
4553
|
|
|
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
|
|
4554
|
+
// src/connector/chains/zcash.ts
|
|
3493
4555
|
var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
|
|
3494
4556
|
|
|
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);
|
|
4557
|
+
// src/signer/SignerZcash.ts
|
|
4558
|
+
var SignerZcash = class {
|
|
4559
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4560
|
+
constructor(_sdk) {
|
|
4561
|
+
this._sdk = _sdk;
|
|
3556
4562
|
}
|
|
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
|
-
}
|
|
4563
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4564
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4565
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4566
|
+
return deviceActionToPromise(
|
|
4567
|
+
action,
|
|
4568
|
+
this.onInteraction,
|
|
4569
|
+
void 0,
|
|
4570
|
+
this.onRegisterCanceller
|
|
3593
4571
|
);
|
|
3594
4572
|
}
|
|
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})`
|
|
4573
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4574
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4575
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4576
|
+
return deviceActionToPromise(
|
|
4577
|
+
action,
|
|
4578
|
+
this.onInteraction,
|
|
4579
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4580
|
+
this.onRegisterCanceller
|
|
3657
4581
|
);
|
|
3658
4582
|
}
|
|
3659
|
-
_isDashboard(appName) {
|
|
3660
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3661
|
-
}
|
|
3662
|
-
_wait() {
|
|
3663
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3664
|
-
}
|
|
3665
4583
|
};
|
|
3666
4584
|
|
|
3667
|
-
// src/connector/chains/
|
|
3668
|
-
function
|
|
3669
|
-
|
|
4585
|
+
// src/connector/chains/zcash.ts
|
|
4586
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4587
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4588
|
+
const path = normalizePath(params.path);
|
|
4589
|
+
const mode = params.mode ?? "ufvk";
|
|
4590
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4591
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4592
|
+
if (result.mode === "ufvk") {
|
|
4593
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4594
|
+
}
|
|
4595
|
+
return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
|
|
4596
|
+
});
|
|
3670
4597
|
}
|
|
3671
|
-
async function
|
|
3672
|
-
const
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
|
|
3678
|
-
payload: { sessionId }
|
|
4598
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4599
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4600
|
+
const path = normalizePath(params.path);
|
|
4601
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4602
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4603
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3679
4604
|
});
|
|
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
|
-
}
|
|
4605
|
+
return { address: result.address, path: params.path };
|
|
4606
|
+
});
|
|
3747
4607
|
}
|
|
3748
|
-
async function
|
|
4608
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3749
4609
|
const dmk = await ctx.getOrCreateDmk();
|
|
3750
|
-
const
|
|
3751
|
-
|
|
4610
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4611
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4612
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3752
4613
|
}
|
|
3753
4614
|
|
|
3754
|
-
// src/
|
|
3755
|
-
var
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
4615
|
+
// src/connector/chains/tron.ts
|
|
4616
|
+
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
4617
|
+
|
|
4618
|
+
// src/signer/SignerTron.ts
|
|
4619
|
+
var SignerTron = class {
|
|
4620
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4621
|
+
constructor(_sdk) {
|
|
4622
|
+
this._sdk = _sdk;
|
|
3761
4623
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
}
|
|
3772
|
-
result.set(statusCode, data.length);
|
|
3773
|
-
return result;
|
|
4624
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4625
|
+
async getAddress(derivationPath, options) {
|
|
4626
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4627
|
+
const result = await deviceActionToPromise(
|
|
4628
|
+
action,
|
|
4629
|
+
this.onInteraction,
|
|
4630
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4631
|
+
this.onRegisterCanceller
|
|
4632
|
+
);
|
|
4633
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3774
4634
|
}
|
|
3775
|
-
|
|
4635
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4636
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4637
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4638
|
+
return deviceActionToPromise(
|
|
4639
|
+
action,
|
|
4640
|
+
this.onInteraction,
|
|
4641
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4642
|
+
this.onRegisterCanceller
|
|
4643
|
+
);
|
|
4644
|
+
}
|
|
4645
|
+
/** Sign a personal message (TIP-191). */
|
|
4646
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4647
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4648
|
+
return deviceActionToPromise(
|
|
4649
|
+
action,
|
|
4650
|
+
this.onInteraction,
|
|
4651
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4652
|
+
this.onRegisterCanceller
|
|
4653
|
+
);
|
|
3776
4654
|
}
|
|
3777
4655
|
};
|
|
3778
4656
|
|
|
3779
4657
|
// src/connector/chains/tron.ts
|
|
3780
4658
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4659
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3781
4660
|
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
|
-
);
|
|
4661
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4662
|
+
const result = await tronSigner.getAddress(path, {
|
|
4663
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4664
|
+
});
|
|
4665
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4666
|
+
});
|
|
3798
4667
|
}
|
|
3799
4668
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3800
4669
|
if (!params.rawTxHex) {
|
|
@@ -3803,42 +4672,30 @@ async function tronSignTransaction(ctx, sessionId, params) {
|
|
|
3803
4672
|
{ code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
|
|
3804
4673
|
);
|
|
3805
4674
|
}
|
|
4675
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3806
4676
|
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
|
-
);
|
|
4677
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4678
|
+
const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
|
|
4679
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4680
|
+
});
|
|
3821
4681
|
}
|
|
3822
4682
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4683
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3823
4684
|
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
|
-
);
|
|
4685
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4686
|
+
const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
|
|
4687
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4688
|
+
});
|
|
3834
4689
|
}
|
|
3835
|
-
async function
|
|
4690
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3836
4691
|
const dmk = await ctx.getOrCreateDmk();
|
|
3837
|
-
|
|
4692
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4693
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4694
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3838
4695
|
}
|
|
3839
4696
|
|
|
3840
4697
|
// src/device-apps/customActions.ts
|
|
3841
|
-
var
|
|
4698
|
+
var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
|
|
3842
4699
|
var import_rxjs = require("rxjs");
|
|
3843
4700
|
var GetOsVersionDeviceAction = class {
|
|
3844
4701
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
@@ -3852,7 +4709,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3852
4709
|
(async () => {
|
|
3853
4710
|
try {
|
|
3854
4711
|
subject.next({
|
|
3855
|
-
status:
|
|
4712
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3856
4713
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3857
4714
|
});
|
|
3858
4715
|
const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
|
|
@@ -3861,11 +4718,11 @@ var GetOsVersionDeviceAction = class {
|
|
|
3861
4718
|
const errObj = result?.error;
|
|
3862
4719
|
throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
|
|
3863
4720
|
}
|
|
3864
|
-
subject.next({ status:
|
|
4721
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
|
|
3865
4722
|
subject.complete();
|
|
3866
4723
|
} catch (err) {
|
|
3867
4724
|
if (cancelled) return;
|
|
3868
|
-
subject.next({ status:
|
|
4725
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3869
4726
|
subject.complete();
|
|
3870
4727
|
}
|
|
3871
4728
|
})();
|
|
@@ -3873,7 +4730,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3873
4730
|
observable: subject.asObservable(),
|
|
3874
4731
|
cancel: () => {
|
|
3875
4732
|
cancelled = true;
|
|
3876
|
-
subject.next({ status:
|
|
4733
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3877
4734
|
subject.complete();
|
|
3878
4735
|
}
|
|
3879
4736
|
};
|
|
@@ -3891,7 +4748,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3891
4748
|
(async () => {
|
|
3892
4749
|
try {
|
|
3893
4750
|
subject.next({
|
|
3894
|
-
status:
|
|
4751
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3895
4752
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3896
4753
|
});
|
|
3897
4754
|
const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
|
|
@@ -3908,11 +4765,11 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3908
4765
|
throw new Error(httpErr?.message ?? "Manager API getAppList failed");
|
|
3909
4766
|
}
|
|
3910
4767
|
const apps = either.extract();
|
|
3911
|
-
subject.next({ status:
|
|
4768
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
|
|
3912
4769
|
subject.complete();
|
|
3913
4770
|
} catch (err) {
|
|
3914
4771
|
if (cancelled) return;
|
|
3915
|
-
subject.next({ status:
|
|
4772
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3916
4773
|
subject.complete();
|
|
3917
4774
|
}
|
|
3918
4775
|
})();
|
|
@@ -3920,7 +4777,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3920
4777
|
observable: subject.asObservable(),
|
|
3921
4778
|
cancel: () => {
|
|
3922
4779
|
cancelled = true;
|
|
3923
|
-
subject.next({ status:
|
|
4780
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3924
4781
|
subject.complete();
|
|
3925
4782
|
}
|
|
3926
4783
|
};
|
|
@@ -4013,7 +4870,7 @@ var DeviceApps = class {
|
|
|
4013
4870
|
seTargetId: v.seTargetId,
|
|
4014
4871
|
mcuTargetId: v.mcuTargetId,
|
|
4015
4872
|
seVersion: v.seVersion,
|
|
4016
|
-
seFlagsHex:
|
|
4873
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
4017
4874
|
mcuSephVersion: v.mcuSephVersion,
|
|
4018
4875
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
4019
4876
|
hwVersion: v.hwVersion
|
|
@@ -4087,7 +4944,7 @@ var DeviceApps = class {
|
|
|
4087
4944
|
}
|
|
4088
4945
|
}
|
|
4089
4946
|
};
|
|
4090
|
-
function
|
|
4947
|
+
function bytesToHex4(bytes) {
|
|
4091
4948
|
if (!bytes) return "";
|
|
4092
4949
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4093
4950
|
}
|
|
@@ -4130,8 +4987,17 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4130
4987
|
evm: "Ethereum",
|
|
4131
4988
|
btc: "Bitcoin",
|
|
4132
4989
|
sol: "Solana",
|
|
4133
|
-
tron: "Tron"
|
|
4990
|
+
tron: "Tron",
|
|
4991
|
+
zcash: "Zcash"
|
|
4134
4992
|
};
|
|
4993
|
+
function withOpenAppName(event, data, appName) {
|
|
4994
|
+
if (event !== "ui-event") return data;
|
|
4995
|
+
const uiEvent = data;
|
|
4996
|
+
if (uiEvent.type !== import_hwk_adapter_core13.EConnectorInteraction.ConfirmOpenApp || uiEvent.payload.appName) {
|
|
4997
|
+
return data;
|
|
4998
|
+
}
|
|
4999
|
+
return { ...uiEvent, payload: { ...uiEvent.payload, appName } };
|
|
5000
|
+
}
|
|
4135
5001
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4136
5002
|
Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
|
|
4137
5003
|
);
|
|
@@ -4170,6 +5036,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4170
5036
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4171
5037
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4172
5038
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
5039
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
5040
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
5041
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
5042
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4173
5043
|
case "@ledgerhq/context-module":
|
|
4174
5044
|
return import("@ledgerhq/context-module");
|
|
4175
5045
|
default:
|
|
@@ -4229,6 +5099,7 @@ var LedgerConnectorBase = class {
|
|
|
4229
5099
|
this._ctx = {
|
|
4230
5100
|
emit: (event, data) => this._emit(event, data),
|
|
4231
5101
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
5102
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4232
5103
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4233
5104
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4234
5105
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4417,8 +5288,15 @@ var LedgerConnectorBase = class {
|
|
|
4417
5288
|
} catch (err) {
|
|
4418
5289
|
this._resetSignersAndSessions();
|
|
4419
5290
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
5291
|
+
if (isBleBondInvalidError(err)) {
|
|
5292
|
+
throw (0, import_hwk_adapter_core13.createHwkError)({
|
|
5293
|
+
code: import_hwk_adapter_core13.HardwareErrorCode.BleBondInvalid,
|
|
5294
|
+
message: "Ledger Bluetooth pairing is no longer valid. Forget this device in system Bluetooth settings, then reconnect.",
|
|
5295
|
+
_tag: ERROR_TAG.PeerRemovedPairing
|
|
5296
|
+
});
|
|
5297
|
+
}
|
|
4420
5298
|
const tag = err?._tag;
|
|
4421
|
-
if (isKnownConnectionTag(tag)) {
|
|
5299
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4422
5300
|
throw err;
|
|
4423
5301
|
}
|
|
4424
5302
|
const wrapped = new Error(
|
|
@@ -4519,7 +5397,7 @@ var LedgerConnectorBase = class {
|
|
|
4519
5397
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4520
5398
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4521
5399
|
async call(sessionId, method, params) {
|
|
4522
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5400
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4523
5401
|
try {
|
|
4524
5402
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4525
5403
|
return { success: true, payload };
|
|
@@ -4587,6 +5465,11 @@ var LedgerConnectorBase = class {
|
|
|
4587
5465
|
return solSignTransaction(ctx, sessionId, params);
|
|
4588
5466
|
case "solSignMessage":
|
|
4589
5467
|
return solSignMessage(ctx, sessionId, params);
|
|
5468
|
+
// ZCASH
|
|
5469
|
+
case "zcashGetFullViewingKey":
|
|
5470
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5471
|
+
case "zcashGetShieldedAddress":
|
|
5472
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4590
5473
|
// TRON
|
|
4591
5474
|
case "tronGetAddress":
|
|
4592
5475
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4620,7 +5503,7 @@ var LedgerConnectorBase = class {
|
|
|
4620
5503
|
});
|
|
4621
5504
|
});
|
|
4622
5505
|
} catch (err) {
|
|
4623
|
-
ctx.
|
|
5506
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4624
5507
|
throw ctx.wrapError(err);
|
|
4625
5508
|
} finally {
|
|
4626
5509
|
ctx.clearCanceller(sessionId);
|
|
@@ -4710,7 +5593,7 @@ var LedgerConnectorBase = class {
|
|
|
4710
5593
|
);
|
|
4711
5594
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4712
5595
|
} catch (err) {
|
|
4713
|
-
ctx.
|
|
5596
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4714
5597
|
throw ctx.wrapError(err);
|
|
4715
5598
|
} finally {
|
|
4716
5599
|
ctx.clearCanceller(sessionId);
|
|
@@ -4832,6 +5715,17 @@ var LedgerConnectorBase = class {
|
|
|
4832
5715
|
_invalidateSession(sessionId) {
|
|
4833
5716
|
this._signerManager?.invalidate(sessionId);
|
|
4834
5717
|
}
|
|
5718
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5719
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5720
|
+
this._cancellers.delete(sessionId);
|
|
5721
|
+
if (cancel) {
|
|
5722
|
+
try {
|
|
5723
|
+
cancel();
|
|
5724
|
+
} catch {
|
|
5725
|
+
}
|
|
5726
|
+
}
|
|
5727
|
+
this._invalidateSession(sessionId);
|
|
5728
|
+
}
|
|
4835
5729
|
/**
|
|
4836
5730
|
* Replace an old session with a new one after app switch.
|
|
4837
5731
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4912,16 +5806,17 @@ var LedgerConnectorBase = class {
|
|
|
4912
5806
|
// ---------------------------------------------------------------------------
|
|
4913
5807
|
/**
|
|
4914
5808
|
* Return a per-call ctx with the chain's Ledger app name pre-bound to
|
|
4915
|
-
* wrapError, so chain handlers don't need to repeat
|
|
4916
|
-
*
|
|
5809
|
+
* UI prompts and wrapError, so chain handlers don't need to repeat the name.
|
|
5810
|
+
* Falls through unchanged for unknown methods.
|
|
4917
5811
|
*/
|
|
4918
5812
|
_ctxForMethod(method) {
|
|
4919
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5813
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4920
5814
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4921
5815
|
if (!defaultAppName) return this._ctx;
|
|
4922
5816
|
return {
|
|
4923
5817
|
...this._ctx,
|
|
4924
|
-
wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts })
|
|
5818
|
+
wrapError: (err, opts) => this._wrapError(err, { defaultAppName, ...opts }),
|
|
5819
|
+
emit: (event, data) => this._ctx.emit(event, withOpenAppName(event, data, defaultAppName))
|
|
4925
5820
|
};
|
|
4926
5821
|
}
|
|
4927
5822
|
_wrapError(err, opts) {
|
|
@@ -4950,6 +5845,204 @@ var LedgerConnectorBase = class {
|
|
|
4950
5845
|
return error;
|
|
4951
5846
|
}
|
|
4952
5847
|
};
|
|
5848
|
+
|
|
5849
|
+
// src/transport/DmkTransport.ts
|
|
5850
|
+
var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
|
|
5851
|
+
var DmkTransport = class extends import_hw_transport.default {
|
|
5852
|
+
constructor(dmk, sessionId) {
|
|
5853
|
+
super();
|
|
5854
|
+
this._dmk = dmk;
|
|
5855
|
+
this._sessionId = sessionId;
|
|
5856
|
+
}
|
|
5857
|
+
async exchange(apdu) {
|
|
5858
|
+
const response = await this._dmk.sendApdu({
|
|
5859
|
+
sessionId: this._sessionId,
|
|
5860
|
+
apdu: new Uint8Array(apdu)
|
|
5861
|
+
});
|
|
5862
|
+
const { data, statusCode } = response;
|
|
5863
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5864
|
+
if (data.length > 0) {
|
|
5865
|
+
result.set(data, 0);
|
|
5866
|
+
}
|
|
5867
|
+
result.set(statusCode, data.length);
|
|
5868
|
+
return result;
|
|
5869
|
+
}
|
|
5870
|
+
async close() {
|
|
5871
|
+
}
|
|
5872
|
+
};
|
|
5873
|
+
|
|
5874
|
+
// src/app/AppManager.ts
|
|
5875
|
+
var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
|
|
5876
|
+
var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
|
|
5877
|
+
var APP_NAME_MAP = {
|
|
5878
|
+
ETH: "Ethereum",
|
|
5879
|
+
BTC: "Bitcoin",
|
|
5880
|
+
SOL: "Solana",
|
|
5881
|
+
TRX: "Tron",
|
|
5882
|
+
ZEC: "Zcash",
|
|
5883
|
+
XRP: "XRP",
|
|
5884
|
+
ADA: "Cardano",
|
|
5885
|
+
DOT: "Polkadot",
|
|
5886
|
+
ATOM: "Cosmos"
|
|
5887
|
+
};
|
|
5888
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5889
|
+
var AppManager = class {
|
|
5890
|
+
constructor(dmk, options) {
|
|
5891
|
+
this._dmk = dmk;
|
|
5892
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5893
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5894
|
+
}
|
|
5895
|
+
/**
|
|
5896
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5897
|
+
* or undefined if the chain is not supported.
|
|
5898
|
+
*/
|
|
5899
|
+
static getAppName(chain) {
|
|
5900
|
+
return APP_NAME_MAP[chain];
|
|
5901
|
+
}
|
|
5902
|
+
/**
|
|
5903
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5904
|
+
*
|
|
5905
|
+
* Flow:
|
|
5906
|
+
* 1. Check the currently running app.
|
|
5907
|
+
* 2. If it is already the target, return immediately.
|
|
5908
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5909
|
+
* 4. Open the target app.
|
|
5910
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5911
|
+
*/
|
|
5912
|
+
/**
|
|
5913
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5914
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5915
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5916
|
+
* in response. NOT called when the target app is already open (no user
|
|
5917
|
+
* interaction needed in that case).
|
|
5918
|
+
*
|
|
5919
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5920
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5921
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5922
|
+
* Hence the callback must fire BEFORE that await.
|
|
5923
|
+
*/
|
|
5924
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5925
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5926
|
+
if (currentApp === targetAppName) {
|
|
5927
|
+
return;
|
|
5928
|
+
}
|
|
5929
|
+
if (!this._isDashboard(currentApp)) {
|
|
5930
|
+
await this._closeCurrentApp(sessionId);
|
|
5931
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5932
|
+
}
|
|
5933
|
+
onConfirmOnDevice?.();
|
|
5934
|
+
await this._openApp(sessionId, targetAppName);
|
|
5935
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5936
|
+
}
|
|
5937
|
+
// ---------------------------------------------------------------------------
|
|
5938
|
+
// Private helpers
|
|
5939
|
+
// ---------------------------------------------------------------------------
|
|
5940
|
+
async _getCurrentApp(sessionId) {
|
|
5941
|
+
const result = await this._dmk.sendCommand({
|
|
5942
|
+
sessionId,
|
|
5943
|
+
command: new import_device_management_kit3.GetAppAndVersionCommand()
|
|
5944
|
+
});
|
|
5945
|
+
if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5946
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5947
|
+
return result.data.name;
|
|
5948
|
+
}
|
|
5949
|
+
const errResult = result;
|
|
5950
|
+
const dmkErr = errResult.error ?? {};
|
|
5951
|
+
const original = dmkErr.originalError;
|
|
5952
|
+
debugLog(
|
|
5953
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5954
|
+
sessionId,
|
|
5955
|
+
"tag=",
|
|
5956
|
+
dmkErr._tag,
|
|
5957
|
+
"errorCode=",
|
|
5958
|
+
dmkErr.errorCode,
|
|
5959
|
+
"message=",
|
|
5960
|
+
dmkErr.message,
|
|
5961
|
+
"originalErrorMessage=",
|
|
5962
|
+
original?.message ?? String(original ?? "")
|
|
5963
|
+
);
|
|
5964
|
+
throw Object.assign(
|
|
5965
|
+
new Error(
|
|
5966
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5967
|
+
),
|
|
5968
|
+
{
|
|
5969
|
+
_tag: dmkErr._tag,
|
|
5970
|
+
errorCode: dmkErr.errorCode,
|
|
5971
|
+
originalError: original
|
|
5972
|
+
}
|
|
5973
|
+
);
|
|
5974
|
+
}
|
|
5975
|
+
async _openApp(sessionId, appName) {
|
|
5976
|
+
const result = await this._dmk.sendCommand({
|
|
5977
|
+
sessionId,
|
|
5978
|
+
command: new import_device_management_kit3.OpenAppCommand({ appName })
|
|
5979
|
+
});
|
|
5980
|
+
if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5981
|
+
const dmkErr = result.error;
|
|
5982
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5983
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5984
|
+
debugLog(
|
|
5985
|
+
"[AppManager] openApp failed:",
|
|
5986
|
+
appName,
|
|
5987
|
+
"errorCode:",
|
|
5988
|
+
errorCode,
|
|
5989
|
+
"tag:",
|
|
5990
|
+
dmkErr._tag
|
|
5991
|
+
);
|
|
5992
|
+
let code;
|
|
5993
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5994
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
|
|
5995
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5996
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
|
|
5997
|
+
}
|
|
5998
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5999
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
6000
|
+
code,
|
|
6001
|
+
errorCode,
|
|
6002
|
+
statusCode: errorCode,
|
|
6003
|
+
appName,
|
|
6004
|
+
originalError: dmkErr
|
|
6005
|
+
});
|
|
6006
|
+
}
|
|
6007
|
+
}
|
|
6008
|
+
async _closeCurrentApp(sessionId) {
|
|
6009
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
6010
|
+
await this._dmk.sendCommand({
|
|
6011
|
+
sessionId,
|
|
6012
|
+
command: new import_device_management_kit3.CloseAppCommand()
|
|
6013
|
+
});
|
|
6014
|
+
}
|
|
6015
|
+
/**
|
|
6016
|
+
* Poll the device until the expected app is reported as running,
|
|
6017
|
+
* or throw after `_maxRetries` attempts.
|
|
6018
|
+
*/
|
|
6019
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
6020
|
+
let lastSeen = "";
|
|
6021
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
6022
|
+
await this._wait();
|
|
6023
|
+
const current = await this._getCurrentApp(sessionId);
|
|
6024
|
+
lastSeen = current;
|
|
6025
|
+
if (current === expectedAppName) {
|
|
6026
|
+
return;
|
|
6027
|
+
}
|
|
6028
|
+
}
|
|
6029
|
+
debugLog(
|
|
6030
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
6031
|
+
expectedAppName,
|
|
6032
|
+
"lastSeen=",
|
|
6033
|
+
lastSeen
|
|
6034
|
+
);
|
|
6035
|
+
throw new Error(
|
|
6036
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
6037
|
+
);
|
|
6038
|
+
}
|
|
6039
|
+
_isDashboard(appName) {
|
|
6040
|
+
return appName === DASHBOARD_APP_NAME;
|
|
6041
|
+
}
|
|
6042
|
+
_wait() {
|
|
6043
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
6044
|
+
}
|
|
6045
|
+
};
|
|
4953
6046
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4954
6047
|
0 && (module.exports = {
|
|
4955
6048
|
AppManager,
|
|
@@ -4961,6 +6054,7 @@ var LedgerConnectorBase = class {
|
|
|
4961
6054
|
SignerEth,
|
|
4962
6055
|
SignerManager,
|
|
4963
6056
|
SignerSol,
|
|
6057
|
+
SignerZcash,
|
|
4964
6058
|
debugLog,
|
|
4965
6059
|
deviceActionToPromise,
|
|
4966
6060
|
isDeviceLockedError,
|