@onekeyfe/hwk-ledger-adapter 1.2.8-alpha.11 → 1.2.8-alpha.110
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 +92 -52
- package/dist/index.d.ts +92 -52
- package/dist/index.js +1950 -965
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1889 -879
- 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",
|
|
@@ -221,7 +222,16 @@ var ERROR_TAG = {
|
|
|
221
222
|
// DMK remote-network failures (manager-api HTTP / secure-channel WS).
|
|
222
223
|
WebSocketConnection: "WebSocketConnectionError",
|
|
223
224
|
HttpFetch: "FetchError",
|
|
224
|
-
|
|
225
|
+
NetworkDA: "NetworkDAError",
|
|
226
|
+
InvalidFirmwareMetadataResponse: "InvalidGetFirmwareMetadataResponseError",
|
|
227
|
+
ApplicationsMetadataTask: "GetApplicationsMetadataTaskError",
|
|
228
|
+
// DMK OS device actions. SecureChannelError is what mapInstallDAErrors() leaves
|
|
229
|
+
// after splitting out device answers, i.e. the relay itself broke.
|
|
230
|
+
SecureChannel: "SecureChannelError",
|
|
231
|
+
RefusedByUserDA: "RefusedByUserDAError",
|
|
232
|
+
AppAlreadyInstalledDA: "AppAlreadyInstalledDAError",
|
|
233
|
+
OutOfMemoryDA: "OutOfMemoryDAError",
|
|
234
|
+
DeviceNotOnboarded: "DeviceNotOnboardedError"
|
|
225
235
|
};
|
|
226
236
|
function isDeviceLockedError(err) {
|
|
227
237
|
if (!err || typeof err !== "object") return false;
|
|
@@ -251,7 +261,6 @@ function isBlePairingFailureError(err) {
|
|
|
251
261
|
return false;
|
|
252
262
|
}
|
|
253
263
|
var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
254
|
-
ERROR_TAG.DeviceLocked,
|
|
255
264
|
ERROR_TAG.DeviceNotAdvertising,
|
|
256
265
|
ERROR_TAG.BlePairingTimeout,
|
|
257
266
|
ERROR_TAG.BleGattBondingFailed,
|
|
@@ -263,6 +272,7 @@ var CONNECTION_LEVEL_TAGS = /* @__PURE__ */ new Set([
|
|
|
263
272
|
ERROR_TAG.DeviceSessionRefresher,
|
|
264
273
|
ERROR_TAG.DeviceNotInitialized,
|
|
265
274
|
ERROR_TAG.OpeningConnection,
|
|
275
|
+
ERROR_TAG.OpeningConnectionLegacy,
|
|
266
276
|
ERROR_TAG.DeviceDisconnectedBeforeSendingApdu,
|
|
267
277
|
ERROR_TAG.DeviceDisconnectedWhileSending,
|
|
268
278
|
ERROR_TAG.Disconnect,
|
|
@@ -277,7 +287,10 @@ var DEVICE_NOT_FOUND_TAGS = /* @__PURE__ */ new Set([
|
|
|
277
287
|
// Map to DeviceNotFound so non-BLE-direct paths get a sensible error code.
|
|
278
288
|
ERROR_TAG.DeviceNotInDiscoveryCache
|
|
279
289
|
]);
|
|
280
|
-
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
290
|
+
var DEVICE_BUSY_TAGS = /* @__PURE__ */ new Set([
|
|
291
|
+
ERROR_TAG.OpeningConnection,
|
|
292
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
293
|
+
]);
|
|
281
294
|
var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
282
295
|
ERROR_TAG.DeviceNotRecognized,
|
|
283
296
|
ERROR_TAG.DeviceSessionNotFound,
|
|
@@ -289,17 +302,18 @@ var DEVICE_DISCONNECTED_TAGS = /* @__PURE__ */ new Set([
|
|
|
289
302
|
ERROR_TAG.WebHIDDisconnect
|
|
290
303
|
]);
|
|
291
304
|
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;
|
|
305
|
+
return hasErrorTag(err, CONNECTION_LEVEL_TAGS);
|
|
299
306
|
}
|
|
300
307
|
function isKnownConnectionTag(tag) {
|
|
301
308
|
return typeof tag === "string" && CONNECTION_LEVEL_TAGS.has(tag);
|
|
302
309
|
}
|
|
310
|
+
var CONNECTION_OPENING_TAGS = /* @__PURE__ */ new Set([
|
|
311
|
+
ERROR_TAG.OpeningConnection,
|
|
312
|
+
ERROR_TAG.OpeningConnectionLegacy
|
|
313
|
+
]);
|
|
314
|
+
function isConnectionOpeningTag(tag) {
|
|
315
|
+
return typeof tag === "string" && CONNECTION_OPENING_TAGS.has(tag);
|
|
316
|
+
}
|
|
303
317
|
function hasStatusCode(err, codeSet) {
|
|
304
318
|
if (!err || typeof err !== "object") return false;
|
|
305
319
|
const e = err;
|
|
@@ -335,28 +349,28 @@ function hasInvalidArgumentCode(err) {
|
|
|
335
349
|
if (e.error != null && e._tag && hasInvalidArgumentCode(e.error)) return true;
|
|
336
350
|
return false;
|
|
337
351
|
}
|
|
338
|
-
function
|
|
352
|
+
function hasErrorTag(err, tags) {
|
|
339
353
|
if (!err || typeof err !== "object") return false;
|
|
340
|
-
const tag = err._tag;
|
|
341
|
-
if (tag && DEVICE_NOT_FOUND_TAGS.has(tag)) return true;
|
|
342
354
|
const e = err;
|
|
343
|
-
if (e.
|
|
344
|
-
if (e.
|
|
355
|
+
if (typeof e._tag === "string" && tags.has(e._tag)) return true;
|
|
356
|
+
if (e.originalError != null && hasErrorTag(e.originalError, tags)) return true;
|
|
357
|
+
if (e.error != null && e._tag && hasErrorTag(e.error, tags)) return true;
|
|
345
358
|
return false;
|
|
346
359
|
}
|
|
360
|
+
function isDeviceNotFoundError(err) {
|
|
361
|
+
return hasErrorTag(err, DEVICE_NOT_FOUND_TAGS);
|
|
362
|
+
}
|
|
347
363
|
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;
|
|
364
|
+
return hasErrorTag(err, DEVICE_BUSY_TAGS);
|
|
355
365
|
}
|
|
366
|
+
var USER_REJECTED_TAGS = /* @__PURE__ */ new Set([
|
|
367
|
+
ERROR_TAG.UserRefusedOnDevice,
|
|
368
|
+
ERROR_TAG.RefusedByUserDA
|
|
369
|
+
]);
|
|
356
370
|
function isUserRejectedError(err) {
|
|
357
371
|
if (!err || typeof err !== "object") return false;
|
|
358
372
|
const e = err;
|
|
359
|
-
if (
|
|
373
|
+
if (hasErrorTag(err, USER_REJECTED_TAGS)) return true;
|
|
360
374
|
if (typeof e.message === "string" && /denied|rejected|refused/i.test(e.message)) return true;
|
|
361
375
|
if (hasStatusCode(err, USER_REJECTED_CODES)) return true;
|
|
362
376
|
return false;
|
|
@@ -387,15 +401,33 @@ function isAppNotInstalledError(err) {
|
|
|
387
401
|
if (hasStatusCode(err, APP_NOT_INSTALLED_CODES)) return true;
|
|
388
402
|
return false;
|
|
389
403
|
}
|
|
404
|
+
var OUT_OF_MEMORY_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.OutOfMemoryDA]);
|
|
390
405
|
function isOutOfMemoryError(err) {
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
406
|
+
return hasErrorTag(err, OUT_OF_MEMORY_TAGS);
|
|
407
|
+
}
|
|
408
|
+
var APP_ALREADY_INSTALLED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.AppAlreadyInstalledDA]);
|
|
409
|
+
function isAppAlreadyInstalledError(err) {
|
|
410
|
+
return hasErrorTag(err, APP_ALREADY_INSTALLED_TAGS);
|
|
411
|
+
}
|
|
412
|
+
var DEVICE_NOT_ONBOARDED_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.DeviceNotOnboarded]);
|
|
413
|
+
function isDeviceNotOnboardedError(err) {
|
|
414
|
+
return hasErrorTag(err, DEVICE_NOT_ONBOARDED_TAGS);
|
|
415
|
+
}
|
|
416
|
+
var FIRMWARE_METADATA_TAGS = /* @__PURE__ */ new Set([
|
|
417
|
+
ERROR_TAG.InvalidFirmwareMetadataResponse,
|
|
418
|
+
ERROR_TAG.ApplicationsMetadataTask
|
|
419
|
+
]);
|
|
420
|
+
function isFirmwareMetadataError(err) {
|
|
421
|
+
return hasErrorTag(err, FIRMWARE_METADATA_TAGS);
|
|
422
|
+
}
|
|
423
|
+
var SECURE_CHANNEL_TAGS = /* @__PURE__ */ new Set([ERROR_TAG.SecureChannel]);
|
|
424
|
+
function isSecureChannelError(err) {
|
|
425
|
+
return hasErrorTag(err, SECURE_CHANNEL_TAGS);
|
|
394
426
|
}
|
|
395
427
|
var NETWORK_ERROR_TAGS = /* @__PURE__ */ new Set([
|
|
396
428
|
ERROR_TAG.WebSocketConnection,
|
|
397
429
|
ERROR_TAG.HttpFetch,
|
|
398
|
-
ERROR_TAG.
|
|
430
|
+
ERROR_TAG.NetworkDA
|
|
399
431
|
]);
|
|
400
432
|
function isNetworkError(err) {
|
|
401
433
|
if (!err || typeof err !== "object") return false;
|
|
@@ -445,23 +477,34 @@ function isTransportStuck(err) {
|
|
|
445
477
|
function isStuckAppStateError(err) {
|
|
446
478
|
return isAppStuckByApdu(err) || isTransportStuck(err);
|
|
447
479
|
}
|
|
480
|
+
var DMK_PLACEHOLDER_MESSAGE = "Unknown error.";
|
|
481
|
+
function nestedErrorMessage(nested) {
|
|
482
|
+
if (!nested || typeof nested !== "object") return void 0;
|
|
483
|
+
const { message } = nested;
|
|
484
|
+
if (typeof message !== "string") return void 0;
|
|
485
|
+
const trimmed = message.trim();
|
|
486
|
+
if (!trimmed || trimmed === DMK_PLACEHOLDER_MESSAGE) return void 0;
|
|
487
|
+
return message;
|
|
488
|
+
}
|
|
448
489
|
function mapLedgerError(err, opts) {
|
|
449
490
|
let originalMessage = "Unknown Ledger error";
|
|
450
491
|
if (err instanceof Error) {
|
|
451
492
|
originalMessage = err.message;
|
|
452
493
|
} else if (err && typeof err === "object") {
|
|
453
494
|
const e = err;
|
|
454
|
-
originalMessage = String(
|
|
495
|
+
originalMessage = String(
|
|
496
|
+
e.message ?? nestedErrorMessage(e.originalError) ?? e._tag ?? e.type ?? JSON.stringify(err)
|
|
497
|
+
);
|
|
455
498
|
}
|
|
456
499
|
let code;
|
|
457
500
|
if (isDeviceLockedError(err)) {
|
|
458
501
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceLocked;
|
|
459
502
|
} else if (isDeviceNotAdvertisingError(err) || isDeviceNotFoundError(err)) {
|
|
460
503
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotFound;
|
|
461
|
-
} else if (isDeviceBusyError(err)) {
|
|
462
|
-
code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
|
|
463
504
|
} else if (isBlePairingFailureError(err)) {
|
|
464
505
|
code = import_hwk_adapter_core.HardwareErrorCode.BlePairingTimeout;
|
|
506
|
+
} else if (isDeviceBusyError(err)) {
|
|
507
|
+
code = import_hwk_adapter_core.HardwareErrorCode.DeviceBusy;
|
|
465
508
|
} else if (isUserAbortedError(err)) {
|
|
466
509
|
code = import_hwk_adapter_core.HardwareErrorCode.UserAborted;
|
|
467
510
|
} else if (isUserRejectedError(err)) {
|
|
@@ -470,10 +513,18 @@ function mapLedgerError(err, opts) {
|
|
|
470
513
|
code = import_hwk_adapter_core.HardwareErrorCode.WrongApp;
|
|
471
514
|
} else if (isAppNotInstalledError(err)) {
|
|
472
515
|
code = import_hwk_adapter_core.HardwareErrorCode.AppNotInstalled;
|
|
516
|
+
} else if (isAppAlreadyInstalledError(err)) {
|
|
517
|
+
code = import_hwk_adapter_core.HardwareErrorCode.AppAlreadyInstalled;
|
|
473
518
|
} else if (isOutOfMemoryError(err)) {
|
|
474
519
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceOutOfMemory;
|
|
520
|
+
} else if (isDeviceNotOnboardedError(err)) {
|
|
521
|
+
code = import_hwk_adapter_core.HardwareErrorCode.DeviceNotInitialized;
|
|
522
|
+
} else if (isFirmwareMetadataError(err)) {
|
|
523
|
+
code = import_hwk_adapter_core.HardwareErrorCode.LedgerFirmwareMetadataError;
|
|
475
524
|
} else if (isNetworkError(err)) {
|
|
476
525
|
code = import_hwk_adapter_core.HardwareErrorCode.NetworkError;
|
|
526
|
+
} else if (isSecureChannelError(err)) {
|
|
527
|
+
code = import_hwk_adapter_core.HardwareErrorCode.LedgerSecureChannelError;
|
|
477
528
|
} else if (isDeviceDisconnectedError(err)) {
|
|
478
529
|
code = import_hwk_adapter_core.HardwareErrorCode.DeviceDisconnected;
|
|
479
530
|
} else if (isTimeoutError(err)) {
|
|
@@ -486,11 +537,25 @@ function mapLedgerError(err, opts) {
|
|
|
486
537
|
}
|
|
487
538
|
const errAppName = err && typeof err === "object" ? err.appName : void 0;
|
|
488
539
|
const appName = errAppName ?? opts?.defaultAppName;
|
|
489
|
-
return {
|
|
540
|
+
return {
|
|
541
|
+
code,
|
|
542
|
+
message: (0, import_hwk_adapter_core.enrichErrorMessage)(code, originalMessage),
|
|
543
|
+
origin: (0, import_hwk_adapter_core.defaultOriginForCode)(code),
|
|
544
|
+
appName
|
|
545
|
+
};
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
// src/utils/queueKey.ts
|
|
549
|
+
var LEDGER_DEFAULT_QUEUE_KEY = "__ledger_default__";
|
|
550
|
+
function ledgerQueueKey({
|
|
551
|
+
operationId,
|
|
552
|
+
connectId
|
|
553
|
+
}) {
|
|
554
|
+
return (operationId ?? connectId) || LEDGER_DEFAULT_QUEUE_KEY;
|
|
490
555
|
}
|
|
491
556
|
|
|
492
557
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
493
|
-
var
|
|
558
|
+
var import_hwk_adapter_core3 = require("@onekeyfe/hwk-adapter-core");
|
|
494
559
|
|
|
495
560
|
// src/utils/sdkEventBus.ts
|
|
496
561
|
var listeners = /* @__PURE__ */ new Set();
|
|
@@ -537,6 +602,32 @@ function debugError(...args) {
|
|
|
537
602
|
emitLog("error", ...args);
|
|
538
603
|
}
|
|
539
604
|
|
|
605
|
+
// src/utils/logSummary.ts
|
|
606
|
+
var import_hwk_adapter_core2 = require("@onekeyfe/hwk-adapter-core");
|
|
607
|
+
var import_bitcoinjs_lib = require("bitcoinjs-lib");
|
|
608
|
+
var HEX_RE = /^(0x)?[0-9a-fA-F]+$/;
|
|
609
|
+
var BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
|
|
610
|
+
function parsePsbt(input) {
|
|
611
|
+
if (typeof input !== "string") return import_bitcoinjs_lib.Psbt.fromBuffer(input);
|
|
612
|
+
if (HEX_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromHex(input.replace(/^0x/i, ""));
|
|
613
|
+
if (BASE64_RE.test(input)) return import_bitcoinjs_lib.Psbt.fromBase64(input);
|
|
614
|
+
return void 0;
|
|
615
|
+
}
|
|
616
|
+
var describePsbtForLog = (key, value) => {
|
|
617
|
+
if (key !== "psbt") return void 0;
|
|
618
|
+
try {
|
|
619
|
+
const psbt = parsePsbt(value);
|
|
620
|
+
if (!psbt) return void 0;
|
|
621
|
+
const unsignedTx = import_bitcoinjs_lib.Transaction.fromBuffer(psbt.data.globalMap.unsignedTx.toBuffer());
|
|
622
|
+
return `inputs=${psbt.inputCount} outputs=${psbt.txOutputs.length} txid=${unsignedTx.getId()}`;
|
|
623
|
+
} catch {
|
|
624
|
+
return void 0;
|
|
625
|
+
}
|
|
626
|
+
};
|
|
627
|
+
function summarizeForLog(value, options = {}) {
|
|
628
|
+
return (0, import_hwk_adapter_core2.summarizeForLog)(value, { ...options, describePayload: describePsbtForLog });
|
|
629
|
+
}
|
|
630
|
+
|
|
540
631
|
// src/adapter/methods/allNetworkGetAddress.ts
|
|
541
632
|
var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
542
633
|
tbtc: "Testnet",
|
|
@@ -547,57 +638,105 @@ var LEDGER_BTC_NETWORK_COIN_MAP = {
|
|
|
547
638
|
var LEDGER_UNSUPPORTED_ALLNETWORK_NETWORKS = /* @__PURE__ */ new Set(["doge", "dogecoin"]);
|
|
548
639
|
function createAllNetworkGetAddress({
|
|
549
640
|
callChain,
|
|
550
|
-
getChainFingerprint
|
|
641
|
+
getChainFingerprint,
|
|
642
|
+
retainOperation,
|
|
643
|
+
errorToFailure,
|
|
644
|
+
createCancelScope,
|
|
645
|
+
releaseBundle
|
|
551
646
|
}) {
|
|
552
647
|
return async function allNetworkGetAddress(connectId, _deviceId, params) {
|
|
553
|
-
debugLog("[LedgerAdapter][REQ]", {
|
|
554
|
-
|
|
648
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
649
|
+
method: "allNetworkGetAddress",
|
|
650
|
+
connectId,
|
|
651
|
+
itemCount: params.bundle.length
|
|
652
|
+
});
|
|
653
|
+
const target = (0, import_hwk_adapter_core3.resolveHardwareOperationTarget)(connectId, params.operationId, "ledger");
|
|
654
|
+
if (!target.success) return target;
|
|
655
|
+
const effectiveTargetId = target.payload.targetId ?? "";
|
|
656
|
+
let releaseOperationRetention;
|
|
657
|
+
try {
|
|
658
|
+
releaseOperationRetention = target.payload.operationId ? retainOperation(target.payload.operationId) : void 0;
|
|
659
|
+
} catch (error) {
|
|
660
|
+
return errorToFailure(error);
|
|
661
|
+
}
|
|
662
|
+
const cancelScope = createCancelScope(
|
|
663
|
+
ledgerQueueKey({ operationId: target.payload.operationId, connectId: effectiveTargetId })
|
|
664
|
+
);
|
|
665
|
+
const installContext = {
|
|
666
|
+
walletCheck: { expected: params.bundle.some((item) => Boolean(getItemDeviceId(item))) }
|
|
667
|
+
};
|
|
555
668
|
const commonParams = {
|
|
556
|
-
autoInstallApp: params.autoInstallApp
|
|
669
|
+
autoInstallApp: params.autoInstallApp,
|
|
670
|
+
operationId: target.payload.operationId,
|
|
671
|
+
knownConnections: params.knownConnections,
|
|
672
|
+
extra: params.extra,
|
|
673
|
+
allowDeviceSelection: params.allowDeviceSelection,
|
|
674
|
+
supportedTransports: params.supportedTransports
|
|
557
675
|
};
|
|
558
676
|
const chainFingerprints = /* @__PURE__ */ new Map();
|
|
559
|
-
const
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
677
|
+
const order = params.bundle.map((_item, index) => index).sort(
|
|
678
|
+
(a, b) => Number(Boolean(getItemDeviceId(params.bundle[b]))) - Number(Boolean(getItemDeviceId(params.bundle[a])))
|
|
679
|
+
);
|
|
680
|
+
try {
|
|
681
|
+
const ordered = await (0, import_hwk_adapter_core3.runAllNetworkGetAddress)({
|
|
682
|
+
connectId: effectiveTargetId,
|
|
683
|
+
deviceId: _deviceId,
|
|
684
|
+
params: { ...params, bundle: order.map((index) => params.bundle[index]) },
|
|
685
|
+
normalizeItem: normalizeLedgerAllNetworkItem,
|
|
686
|
+
buildUnsupportedNetworkResponse: (item) => isUnsupportedLedgerAllNetworkNetwork(item) ? buildUnsupportedNetworkResponse(item) : void 0,
|
|
687
|
+
callItem: async ({ method, chain, item }) => {
|
|
688
|
+
if (cancelScope.signal.aborted)
|
|
689
|
+
return (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelScope.signal);
|
|
690
|
+
const itemDeviceId = getItemDeviceId(item) ?? chainFingerprints.get(chain) ?? "";
|
|
691
|
+
return callAllNetworkMethod(
|
|
692
|
+
callChain,
|
|
693
|
+
effectiveTargetId,
|
|
694
|
+
itemDeviceId,
|
|
695
|
+
method,
|
|
696
|
+
item,
|
|
697
|
+
commonParams,
|
|
698
|
+
installContext
|
|
699
|
+
);
|
|
700
|
+
},
|
|
701
|
+
attachIdentity: async ({ item, chain, payload }) => attachLedgerIdentity(
|
|
702
|
+
getChainFingerprint,
|
|
703
|
+
effectiveTargetId,
|
|
572
704
|
item,
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
)
|
|
705
|
+
chain,
|
|
706
|
+
payload,
|
|
707
|
+
chainFingerprints,
|
|
708
|
+
installContext,
|
|
709
|
+
cancelScope.signal
|
|
710
|
+
),
|
|
711
|
+
shouldAbortBundle: isTopLevelAllNetworkFailure,
|
|
712
|
+
buildTopLevelFailure: (response) => {
|
|
713
|
+
const code = response.payload?.code ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch;
|
|
714
|
+
return (0, import_hwk_adapter_core3.failure)(
|
|
715
|
+
code,
|
|
716
|
+
response.payload?.error ?? "All-network get-address aborted",
|
|
717
|
+
response.payload?.params
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
let result = ordered;
|
|
722
|
+
if (ordered.success) {
|
|
723
|
+
const responses = [];
|
|
724
|
+
ordered.payload.forEach((response, position) => {
|
|
725
|
+
responses[order[position]] = response;
|
|
726
|
+
});
|
|
727
|
+
result = (0, import_hwk_adapter_core3.success)(responses);
|
|
593
728
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
729
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
730
|
+
method: "allNetworkGetAddress",
|
|
731
|
+
success: result.success,
|
|
732
|
+
payload: summarizeForLog(result, { method: "allNetworkGetAddress", role: "result" })
|
|
733
|
+
});
|
|
734
|
+
return result;
|
|
735
|
+
} finally {
|
|
736
|
+
await releaseBundle(installContext, cancelScope.signal).catch(() => void 0);
|
|
737
|
+
cancelScope.release();
|
|
738
|
+
releaseOperationRetention?.();
|
|
739
|
+
}
|
|
601
740
|
};
|
|
602
741
|
}
|
|
603
742
|
function isTopLevelAllNetworkFailure(response) {
|
|
@@ -605,7 +744,7 @@ function isTopLevelAllNetworkFailure(response) {
|
|
|
605
744
|
return false;
|
|
606
745
|
}
|
|
607
746
|
const code = response.payload?.code;
|
|
608
|
-
return
|
|
747
|
+
return (0, import_hwk_adapter_core3.isWalletSafetyFailure)(code) || (0, import_hwk_adapter_core3.isUserRefusal)(code) || (0, import_hwk_adapter_core3.isConnectionLost)(code);
|
|
609
748
|
}
|
|
610
749
|
function getItemDeviceId(item) {
|
|
611
750
|
const { deviceId } = item;
|
|
@@ -619,7 +758,7 @@ function buildUnsupportedNetworkResponse(item) {
|
|
|
619
758
|
...item,
|
|
620
759
|
success: false,
|
|
621
760
|
payload: {
|
|
622
|
-
code:
|
|
761
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.ChainNotSupported,
|
|
623
762
|
error: `Ledger allNetwork does not support ${item.network.toLowerCase() === "doge" ? "Dogecoin" : item.network}`
|
|
624
763
|
}
|
|
625
764
|
};
|
|
@@ -635,8 +774,18 @@ function normalizeLedgerAllNetworkItem(method, item) {
|
|
|
635
774
|
const coin = LEDGER_BTC_NETWORK_COIN_MAP[item.network];
|
|
636
775
|
return coin ? { ...item, coin } : item;
|
|
637
776
|
}
|
|
638
|
-
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints) {
|
|
639
|
-
const
|
|
777
|
+
async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain, payload, chainFingerprints, context, cancelSignal) {
|
|
778
|
+
const knownFingerprint = getItemDeviceId(item) || chainFingerprints.get(chain) || "";
|
|
779
|
+
if (!knownFingerprint && cancelSignal.aborted) {
|
|
780
|
+
const cancelled = (0, import_hwk_adapter_core3.buildAllNetworkCancelledFailure)(cancelSignal);
|
|
781
|
+
return { ...item, success: false, payload: cancelled.payload };
|
|
782
|
+
}
|
|
783
|
+
const fingerprint = knownFingerprint || await bootstrapChainFingerprint(
|
|
784
|
+
getChainFingerprint,
|
|
785
|
+
context.connection?.connectId ?? connectId,
|
|
786
|
+
chain,
|
|
787
|
+
context
|
|
788
|
+
);
|
|
640
789
|
if (!fingerprint) {
|
|
641
790
|
return buildFingerprintBootstrapFailure(item, chain);
|
|
642
791
|
}
|
|
@@ -657,8 +806,8 @@ async function attachLedgerIdentity(getChainFingerprint, connectId, item, chain,
|
|
|
657
806
|
}
|
|
658
807
|
};
|
|
659
808
|
}
|
|
660
|
-
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain) {
|
|
661
|
-
const response = await getChainFingerprint(connectId, chain);
|
|
809
|
+
async function bootstrapChainFingerprint(getChainFingerprint, connectId, chain, context) {
|
|
810
|
+
const response = await getChainFingerprint(connectId, chain, context);
|
|
662
811
|
return response.success ? response.payload : "";
|
|
663
812
|
}
|
|
664
813
|
function buildFingerprintBootstrapFailure(item, chain) {
|
|
@@ -666,7 +815,7 @@ function buildFingerprintBootstrapFailure(item, chain) {
|
|
|
666
815
|
...item,
|
|
667
816
|
success: false,
|
|
668
817
|
payload: {
|
|
669
|
-
code:
|
|
818
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch,
|
|
670
819
|
error: `Could not establish chain fingerprint for ${chain} after device call; refusing to return unverifiable result. Please retry.`
|
|
671
820
|
}
|
|
672
821
|
};
|
|
@@ -730,7 +879,7 @@ async function callAllNetworkMethod(callChain, connectId, deviceId, method, item
|
|
|
730
879
|
);
|
|
731
880
|
default:
|
|
732
881
|
throw Object.assign(new Error(`Unsupported allNetwork method: ${method}`), {
|
|
733
|
-
code:
|
|
882
|
+
code: import_hwk_adapter_core3.HardwareErrorCode.InvalidParams
|
|
734
883
|
});
|
|
735
884
|
}
|
|
736
885
|
}
|
|
@@ -751,6 +900,9 @@ function isLedgerBleDescriptor(connectionType, descriptor) {
|
|
|
751
900
|
function formatDeviceMismatchError(expected, actual) {
|
|
752
901
|
return `Wrong device: expected ${expected}, got ${actual}`;
|
|
753
902
|
}
|
|
903
|
+
function isLostConnectionError(err) {
|
|
904
|
+
return isDeviceDisconnectedError(err) || isDeviceNotAdvertisingError(err) || isTimeoutError(err) || isConnectionLevelError(err);
|
|
905
|
+
}
|
|
754
906
|
var BTC_HIGH_INDEX_THRESHOLD = 100;
|
|
755
907
|
function btcAccountIndexFromPath(path) {
|
|
756
908
|
const segments = path.replace(/^m\//, "").split("/");
|
|
@@ -762,10 +914,36 @@ function btcAccountIndexFromPath(path) {
|
|
|
762
914
|
var _LedgerAdapter = class _LedgerAdapter {
|
|
763
915
|
constructor(connector, options) {
|
|
764
916
|
this.vendor = "ledger";
|
|
765
|
-
|
|
917
|
+
// Cancel frees the DMK action and its intent-queue slot, but cannot retract a
|
|
918
|
+
// confirmation screen the device is already showing.
|
|
919
|
+
this.cancelCapability = "stops-waiting";
|
|
920
|
+
this.emitter = new import_hwk_adapter_core4.TypedEventEmitter();
|
|
921
|
+
this._operations = new import_hwk_adapter_core4.OperationRegistry({
|
|
922
|
+
vendor: "ledger",
|
|
923
|
+
onEnded: (operation, reason) => {
|
|
924
|
+
this._discardPendingBinding(this._pendingOperationBindings.get(operation.operationId));
|
|
925
|
+
this._pendingOperationBindings.delete(operation.operationId);
|
|
926
|
+
this.emitter.emit(import_hwk_adapter_core4.SDK.OPERATION_ENDED, {
|
|
927
|
+
type: import_hwk_adapter_core4.SDK.OPERATION_ENDED,
|
|
928
|
+
payload: { operationId: operation.operationId, reason }
|
|
929
|
+
});
|
|
930
|
+
if (reason === "timeout" && !this._bareCallMayUseConnection(operation)) {
|
|
931
|
+
void this._releaseOperationConnection(operation);
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
});
|
|
766
935
|
this._discoveredDevices = /* @__PURE__ */ new Map();
|
|
767
936
|
this._sessions = /* @__PURE__ */ new Map();
|
|
768
|
-
|
|
937
|
+
// An operation's BLE pick is saved by its first call that gets past the wallet check.
|
|
938
|
+
this._pendingOperationBindings = /* @__PURE__ */ new Map();
|
|
939
|
+
// A one-shot call's unchecked BLE pick, by connectId. It outlives the call only
|
|
940
|
+
// through an unlock retry; any other failure drops it with its session.
|
|
941
|
+
this._pendingPickBindings = /* @__PURE__ */ new Map();
|
|
942
|
+
// Transport each session was opened on, by sessionId. The adapter-wide
|
|
943
|
+
// `_activeConnectionType` moves with every discovery and can go stale.
|
|
944
|
+
this._sessionTransports = /* @__PURE__ */ new Map();
|
|
945
|
+
this._selectedBleReconnectTargets = /* @__PURE__ */ new Map();
|
|
946
|
+
this._uiRegistry = new import_hwk_adapter_core4.UiRequestRegistry();
|
|
769
947
|
// BTC App rejects account index >= 100 unless display=true. Cached per
|
|
770
948
|
// adapter instance: first 100+ path asks the user once via UI request,
|
|
771
949
|
// subsequent 100+ paths in the same session auto-promote silently.
|
|
@@ -778,21 +956,36 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
778
956
|
this._deviceAuthenticityQueueTail = Promise.resolve();
|
|
779
957
|
// Shared across concurrent callers — only `cancel()` aborts.
|
|
780
958
|
this._doConnectAbortController = null;
|
|
959
|
+
this._unsettledConnectorOperations = /* @__PURE__ */ new Map();
|
|
960
|
+
this._connectorIdleWaiters = /* @__PURE__ */ new Set();
|
|
961
|
+
this._resetPromise = null;
|
|
962
|
+
this._stateGeneration = 0;
|
|
963
|
+
this._connectorTeardownTail = Promise.resolve();
|
|
964
|
+
this._pendingConnectorTeardowns = 0;
|
|
965
|
+
this._activeOperationJobs = /* @__PURE__ */ new Set();
|
|
966
|
+
this._pendingOperationDisconnects = /* @__PURE__ */ new Set();
|
|
781
967
|
this._installProgressLastEmittedValue = -Infinity;
|
|
782
968
|
this.allNetworkGetAddress = createAllNetworkGetAddress({
|
|
783
969
|
callChain: this.callChain.bind(this),
|
|
784
|
-
getChainFingerprint: (connectId, chain) =>
|
|
970
|
+
getChainFingerprint: async (connectId, chain, context) => {
|
|
971
|
+
try {
|
|
972
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
973
|
+
chain,
|
|
974
|
+
(method, params) => this.connectorCall(connectId, method, params, void 0, void 0, void 0, context)
|
|
975
|
+
);
|
|
976
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
977
|
+
} catch (error) {
|
|
978
|
+
return this.errorToFailure(error);
|
|
979
|
+
}
|
|
980
|
+
},
|
|
981
|
+
retainOperation: (operationId) => this._operations.retain(operationId),
|
|
982
|
+
errorToFailure: (error) => this.errorToFailure(error),
|
|
983
|
+
createCancelScope: (queueKey) => this._jobQueue.createCancelScope(queueKey),
|
|
984
|
+
releaseBundle: (context, signal) => this._dropUncheckedBundlePick(context, signal)
|
|
785
985
|
});
|
|
786
986
|
// ---------------------------------------------------------------------------
|
|
787
987
|
// Private helpers
|
|
788
988
|
// ---------------------------------------------------------------------------
|
|
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
989
|
// Mutex for ensureConnected — prevents concurrent calls from establishing duplicate connections
|
|
797
990
|
this._connectingPromise = null;
|
|
798
991
|
// ---------------------------------------------------------------------------
|
|
@@ -802,26 +995,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
802
995
|
const deviceInfo = this.connectorDeviceToDeviceInfo(data.device);
|
|
803
996
|
this._discoveredDevices.set(deviceInfo.connectId, deviceInfo);
|
|
804
997
|
this._sessions.delete(deviceInfo.connectId);
|
|
805
|
-
this.emitter.emit(
|
|
806
|
-
type:
|
|
998
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.CONNECT, {
|
|
999
|
+
type: import_hwk_adapter_core4.DEVICE.CONNECT,
|
|
807
1000
|
payload: deviceInfo
|
|
808
1001
|
});
|
|
809
1002
|
};
|
|
810
1003
|
this.deviceDisconnectHandler = (data) => {
|
|
1004
|
+
const activeOperation = this._operations.findActiveByConnectionKey(data.connectId);
|
|
1005
|
+
if (activeOperation && this._activeOperationJobs.has(activeOperation.operationId)) {
|
|
1006
|
+
this._pendingOperationDisconnects.add(activeOperation.operationId);
|
|
1007
|
+
} else {
|
|
1008
|
+
this._operations.endByConnectionKey(data.connectId, "disconnect");
|
|
1009
|
+
}
|
|
811
1010
|
this._discoveredDevices.delete(data.connectId);
|
|
812
1011
|
this._sessions.delete(data.connectId);
|
|
813
|
-
this.emitter.emit(
|
|
814
|
-
type:
|
|
1012
|
+
this.emitter.emit(import_hwk_adapter_core4.DEVICE.DISCONNECT, {
|
|
1013
|
+
type: import_hwk_adapter_core4.DEVICE.DISCONNECT,
|
|
815
1014
|
payload: { connectId: data.connectId }
|
|
816
1015
|
});
|
|
817
1016
|
};
|
|
818
1017
|
// 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.
|
|
1018
|
+
// need to subscribe in one place. The AppInstallProgress variant re-keys
|
|
1019
|
+
// sessionId to connectId via `_sessions`, and drops if no mapping exists.
|
|
823
1020
|
this.uiEventForwarder = (event) => {
|
|
824
|
-
if (event.type ===
|
|
1021
|
+
if (event.type === import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress) {
|
|
825
1022
|
let connectId;
|
|
826
1023
|
for (const [cid, sid] of this._sessions) {
|
|
827
1024
|
if (sid === event.payload.sessionId) {
|
|
@@ -848,7 +1045,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
848
1045
|
}
|
|
849
1046
|
this._installProgressLastEmittedValue = progress;
|
|
850
1047
|
this.emitter.emit("ui-event", {
|
|
851
|
-
type:
|
|
1048
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
852
1049
|
payload: {
|
|
853
1050
|
connectId,
|
|
854
1051
|
appName,
|
|
@@ -861,14 +1058,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
861
1058
|
};
|
|
862
1059
|
this.connector = connector;
|
|
863
1060
|
this._defaultAutoInstallApp = options?.autoInstallApp ?? false;
|
|
864
|
-
this._jobQueue = new
|
|
1061
|
+
this._jobQueue = new import_hwk_adapter_core4.DeviceJobQueue();
|
|
865
1062
|
this.registerEventListeners();
|
|
866
1063
|
}
|
|
1064
|
+
_discardPendingBinding(owner, status = "cancelled") {
|
|
1065
|
+
const pending = owner?.pendingBinding;
|
|
1066
|
+
if (!owner || !pending) return;
|
|
1067
|
+
owner.pendingBinding = void 0;
|
|
1068
|
+
if (pending.requestId === this._bindingSelectionRequestId) this._finishBleBinding(status);
|
|
1069
|
+
}
|
|
1070
|
+
_finishBleBinding(status) {
|
|
1071
|
+
const selectionRequestId = this._bindingSelectionRequestId;
|
|
1072
|
+
this._bindingSelectionRequestId = void 0;
|
|
1073
|
+
if (selectionRequestId) (0, import_hwk_adapter_core4.emitDeviceBindingStatus)(this.emitter, selectionRequestId, status);
|
|
1074
|
+
}
|
|
1075
|
+
_isBleConnection() {
|
|
1076
|
+
return isLedgerBleConnectionType(this._activeConnectionType ?? this.connector.connectionType);
|
|
1077
|
+
}
|
|
867
1078
|
// Transport
|
|
868
1079
|
get activeTransport() {
|
|
869
|
-
return
|
|
1080
|
+
return this._isBleConnection() ? "ble" : "hid";
|
|
870
1081
|
}
|
|
871
1082
|
getAvailableTransports() {
|
|
1083
|
+
if (this.connector.availableTransports) {
|
|
1084
|
+
return this.connector.availableTransports.map(
|
|
1085
|
+
(transport) => transport === "ble" ? "ble" : "hid"
|
|
1086
|
+
);
|
|
1087
|
+
}
|
|
872
1088
|
return this.activeTransport ? [this.activeTransport] : [];
|
|
873
1089
|
}
|
|
874
1090
|
// Connector is bound at construction; switching requires a new adapter.
|
|
@@ -885,21 +1101,42 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
885
1101
|
* The next operation will re-discover and re-connect automatically.
|
|
886
1102
|
*/
|
|
887
1103
|
resetState() {
|
|
1104
|
+
void this._resetStateAndDisconnectSessions();
|
|
1105
|
+
}
|
|
1106
|
+
_resetStateAndDisconnectSessions() {
|
|
1107
|
+
if (this._resetPromise) return this._resetPromise;
|
|
1108
|
+
const sessionIds = new Set(this._sessions.values());
|
|
1109
|
+
this._stateGeneration += 1;
|
|
1110
|
+
this._finishBleBinding("cancelled");
|
|
1111
|
+
this._operations.endAll("runtime-reset");
|
|
1112
|
+
this._doConnectAbortController?.abort();
|
|
888
1113
|
this._discoveredDevices.clear();
|
|
889
1114
|
this._sessions.clear();
|
|
1115
|
+
this._sessionTransports.clear();
|
|
1116
|
+
this._pendingOperationBindings.clear();
|
|
1117
|
+
this._pendingPickBindings.clear();
|
|
1118
|
+
this._selectedBleReconnectTargets.clear();
|
|
890
1119
|
this._connectingPromise = null;
|
|
1120
|
+
this._doConnectAbortController = null;
|
|
891
1121
|
this._uiRegistry.reset();
|
|
892
1122
|
this._jobQueue.clear();
|
|
893
1123
|
this._btcHighIndexConfirmedThisSession = false;
|
|
1124
|
+
const resetPromise = this._runConnectorTeardown(async () => {
|
|
1125
|
+
for (const sessionId of sessionIds) {
|
|
1126
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
1127
|
+
}
|
|
1128
|
+
});
|
|
1129
|
+
this._resetPromise = resetPromise;
|
|
1130
|
+
return resetPromise.finally(() => {
|
|
1131
|
+
if (this._resetPromise === resetPromise) {
|
|
1132
|
+
this._resetPromise = null;
|
|
1133
|
+
}
|
|
1134
|
+
});
|
|
894
1135
|
}
|
|
895
1136
|
async dispose() {
|
|
896
|
-
this.
|
|
897
|
-
this._jobQueue.clear();
|
|
1137
|
+
await this._resetStateAndDisconnectSessions();
|
|
898
1138
|
this.unregisterEventListeners();
|
|
899
1139
|
this.connector.reset();
|
|
900
|
-
this._discoveredDevices.clear();
|
|
901
|
-
this._sessions.clear();
|
|
902
|
-
this._btcHighIndexConfirmedThisSession = false;
|
|
903
1140
|
this.emitter.removeAllListeners();
|
|
904
1141
|
}
|
|
905
1142
|
uiResponse(response) {
|
|
@@ -909,17 +1146,32 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
909
1146
|
// Device management
|
|
910
1147
|
// ---------------------------------------------------------------------------
|
|
911
1148
|
async searchDevices(options) {
|
|
1149
|
+
return this._searchDevices(options);
|
|
1150
|
+
}
|
|
1151
|
+
async _searchDevices(options, signal) {
|
|
912
1152
|
debugLog("[LedgerAdapter][REQ]", { method: "searchDevices", params: options });
|
|
913
1153
|
try {
|
|
914
1154
|
if (options?.resetSession) {
|
|
915
|
-
this.
|
|
916
|
-
|
|
917
|
-
this.
|
|
918
|
-
|
|
919
|
-
|
|
1155
|
+
await this._resetStateAndDisconnectSessions();
|
|
1156
|
+
} else {
|
|
1157
|
+
await this._connectorTeardownTail;
|
|
1158
|
+
}
|
|
1159
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1160
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1161
|
+
const stateGeneration = this._stateGeneration;
|
|
1162
|
+
const devices = await this.connector.searchDevices(
|
|
1163
|
+
options?.transportType ? {
|
|
1164
|
+
transportType: options.transportType,
|
|
1165
|
+
waitForAll: options.waitForAllTransports
|
|
1166
|
+
} : void 0
|
|
1167
|
+
);
|
|
1168
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1169
|
+
if (stateGeneration !== this._stateGeneration) {
|
|
1170
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1171
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1172
|
+
message: "Ledger discovery was reset"
|
|
1173
|
+
});
|
|
920
1174
|
}
|
|
921
|
-
await this._ensureDevicePermission();
|
|
922
|
-
const devices = await this.connector.searchDevices();
|
|
923
1175
|
this._discoveredDevices.clear();
|
|
924
1176
|
for (const d of devices) {
|
|
925
1177
|
if (d.connectId) {
|
|
@@ -927,7 +1179,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
927
1179
|
}
|
|
928
1180
|
}
|
|
929
1181
|
if (this._discoveredDevices.size === 0) {
|
|
930
|
-
await this._ensureDevicePermission();
|
|
1182
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
931
1183
|
}
|
|
932
1184
|
const result = Array.from(this._discoveredDevices.values());
|
|
933
1185
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -946,41 +1198,263 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
946
1198
|
throw err;
|
|
947
1199
|
}
|
|
948
1200
|
}
|
|
1201
|
+
async searchDeviceTargets(options) {
|
|
1202
|
+
const devices = await this.searchDevices(options);
|
|
1203
|
+
return devices.map((device) => (0, import_hwk_adapter_core4.toPhysicalDeviceSearchTarget)("ledger", device));
|
|
1204
|
+
}
|
|
949
1205
|
// USB single-session invariant: evict all sessions, best-effort (see connectDevice).
|
|
950
|
-
async _evictAllSessions() {
|
|
1206
|
+
async _evictAllSessions(preserveOperationId) {
|
|
1207
|
+
this._operations.endAll("explicit", preserveOperationId);
|
|
951
1208
|
if (this._sessions.size === 0) return;
|
|
952
1209
|
const stale = [...this._sessions.values()];
|
|
953
1210
|
this._sessions.clear();
|
|
954
|
-
for (const sid of stale)
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1211
|
+
for (const sid of stale) this._sessionTransports.delete(sid);
|
|
1212
|
+
await this._runConnectorTeardown(async () => {
|
|
1213
|
+
for (const sid of stale) {
|
|
1214
|
+
try {
|
|
1215
|
+
await this.connector.disconnect(sid);
|
|
1216
|
+
} catch {
|
|
1217
|
+
}
|
|
958
1218
|
}
|
|
959
|
-
}
|
|
1219
|
+
});
|
|
960
1220
|
}
|
|
961
1221
|
static _createDeviceBusyError(method) {
|
|
962
1222
|
return Object.assign(new Error(`Ledger device is busy while calling ${method}`), {
|
|
963
|
-
code:
|
|
1223
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceBusy
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
async connectDevice(searchTargetId) {
|
|
1227
|
+
try {
|
|
1228
|
+
return await this._jobQueue.enqueue(
|
|
1229
|
+
searchTargetId || "__ledger_connect__",
|
|
1230
|
+
async (signal) => {
|
|
1231
|
+
const connected = await this._connectTarget(searchTargetId, void 0, signal);
|
|
1232
|
+
if (!connected.success) return connected;
|
|
1233
|
+
return this._createOperation(searchTargetId, connected.payload);
|
|
1234
|
+
},
|
|
1235
|
+
{
|
|
1236
|
+
label: "connectDevice",
|
|
1237
|
+
rejectIfBusy: true,
|
|
1238
|
+
busyError: _LedgerAdapter._createDeviceBusyError("connectDevice")
|
|
1239
|
+
}
|
|
1240
|
+
);
|
|
1241
|
+
} catch (error) {
|
|
1242
|
+
return this.errorToFailure(error);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
/** Binds the picked BLE device; with a recorded wallet identity it must match first. */
|
|
1246
|
+
async bindBleDevice(params) {
|
|
1247
|
+
const identity = params.identity?.vendor === "ledger" ? params.identity : void 0;
|
|
1248
|
+
try {
|
|
1249
|
+
return await this._jobQueue.enqueue(
|
|
1250
|
+
"__ledger_bind_ble__",
|
|
1251
|
+
async (signal) => {
|
|
1252
|
+
if (!this.getAvailableTransports().includes("ble")) {
|
|
1253
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1254
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.TransportNotAvailable,
|
|
1255
|
+
message: "Ledger Bluetooth transport is not available"
|
|
1256
|
+
});
|
|
1257
|
+
}
|
|
1258
|
+
this._activeConnectionType = "ble";
|
|
1259
|
+
await this._ensureDevicePermission(void 0, void 0, signal);
|
|
1260
|
+
const attempt = {
|
|
1261
|
+
extra: params.extra,
|
|
1262
|
+
bindingReason: "manual-rebind",
|
|
1263
|
+
deferBindingSave: Boolean(identity)
|
|
1264
|
+
};
|
|
1265
|
+
try {
|
|
1266
|
+
const connectId = await this._connectFirstOrSelect(
|
|
1267
|
+
[],
|
|
1268
|
+
void 0,
|
|
1269
|
+
true,
|
|
1270
|
+
void 0,
|
|
1271
|
+
attempt,
|
|
1272
|
+
signal
|
|
1273
|
+
);
|
|
1274
|
+
const pending = attempt.pendingBinding;
|
|
1275
|
+
if (identity && pending) {
|
|
1276
|
+
attempt.pendingBinding = void 0;
|
|
1277
|
+
const sessionId = this._sessions.get(connectId);
|
|
1278
|
+
if (!sessionId) {
|
|
1279
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1280
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
1281
|
+
message: "Selected Ledger connection ended"
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
1285
|
+
identity.chain,
|
|
1286
|
+
(method, callParams) => this._runConnectorCall(
|
|
1287
|
+
connectId,
|
|
1288
|
+
method,
|
|
1289
|
+
callParams,
|
|
1290
|
+
signal,
|
|
1291
|
+
void 0,
|
|
1292
|
+
void 0,
|
|
1293
|
+
{ autoInstallApp: true },
|
|
1294
|
+
{ connection: { connectId, sessionId } }
|
|
1295
|
+
)
|
|
1296
|
+
);
|
|
1297
|
+
if (fingerprint !== identity.value) {
|
|
1298
|
+
await this._dropSession(connectId, signal);
|
|
1299
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1300
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
1301
|
+
message: formatDeviceMismatchError(identity.value, fingerprint)
|
|
1302
|
+
});
|
|
1303
|
+
}
|
|
1304
|
+
await this._saveSelectedBleBinding(
|
|
1305
|
+
connectId,
|
|
1306
|
+
pending.requestId,
|
|
1307
|
+
attempt,
|
|
1308
|
+
void 0,
|
|
1309
|
+
signal,
|
|
1310
|
+
identity
|
|
1311
|
+
);
|
|
1312
|
+
}
|
|
1313
|
+
if (!attempt.bindingSaved) {
|
|
1314
|
+
await this._dropSession(connectId, signal);
|
|
1315
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
1316
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1317
|
+
message: "Bluetooth binding could not be saved",
|
|
1318
|
+
origin: "host"
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1321
|
+
return (0, import_hwk_adapter_core4.success)(connectId);
|
|
1322
|
+
} catch (error) {
|
|
1323
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1324
|
+
throw error;
|
|
1325
|
+
}
|
|
1326
|
+
},
|
|
1327
|
+
{
|
|
1328
|
+
label: "bindBleDevice",
|
|
1329
|
+
rejectIfBusy: true,
|
|
1330
|
+
busyError: _LedgerAdapter._createDeviceBusyError("bindBleDevice")
|
|
1331
|
+
}
|
|
1332
|
+
);
|
|
1333
|
+
} catch (error) {
|
|
1334
|
+
return this.errorToFailure(error);
|
|
1335
|
+
}
|
|
1336
|
+
}
|
|
1337
|
+
async acquireOperation(connectId, context) {
|
|
1338
|
+
try {
|
|
1339
|
+
return await this._jobQueue.enqueue(
|
|
1340
|
+
connectId || "__ledger_acquire__",
|
|
1341
|
+
async (signal) => {
|
|
1342
|
+
const transport = this._isBleConnection() ? "ble" : "usb";
|
|
1343
|
+
const hint = context.knownConnections?.find(
|
|
1344
|
+
(connection) => connection.transport === transport
|
|
1345
|
+
);
|
|
1346
|
+
const target = hint && hint.transport !== "qr" ? hint.connectId : connectId;
|
|
1347
|
+
await this._ensureDevicePermission(target, void 0, signal);
|
|
1348
|
+
const attempt = {
|
|
1349
|
+
...context,
|
|
1350
|
+
extra: context.extra ? { ...context.extra } : void 0,
|
|
1351
|
+
// The operation's calls decide whether the pick is the right wallet.
|
|
1352
|
+
deferBindingSave: true
|
|
1353
|
+
};
|
|
1354
|
+
try {
|
|
1355
|
+
const resolvedConnectId = await this.ensureConnected(
|
|
1356
|
+
target,
|
|
1357
|
+
signal,
|
|
1358
|
+
true,
|
|
1359
|
+
void 0,
|
|
1360
|
+
attempt
|
|
1361
|
+
);
|
|
1362
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1363
|
+
const result = this._createOperation(connectId, resolvedConnectId);
|
|
1364
|
+
if (result.success && attempt.pendingBinding) {
|
|
1365
|
+
this._pendingOperationBindings.set(result.payload, attempt);
|
|
1366
|
+
}
|
|
1367
|
+
return result;
|
|
1368
|
+
} catch (error) {
|
|
1369
|
+
this._finishBleBinding(signal.aborted ? "cancelled" : "failed");
|
|
1370
|
+
throw error;
|
|
1371
|
+
}
|
|
1372
|
+
},
|
|
1373
|
+
{
|
|
1374
|
+
label: "acquireOperation",
|
|
1375
|
+
rejectIfBusy: true,
|
|
1376
|
+
busyError: _LedgerAdapter._createDeviceBusyError("acquireOperation")
|
|
1377
|
+
}
|
|
1378
|
+
);
|
|
1379
|
+
} catch (error) {
|
|
1380
|
+
return this.errorToFailure(error);
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
_createOperation(searchTargetId, resolvedConnectId) {
|
|
1384
|
+
this._operations.endByConnectionKey(resolvedConnectId, "explicit");
|
|
1385
|
+
const sessionId = this._sessions.get(resolvedConnectId);
|
|
1386
|
+
if (sessionId) this._operations.endByConnectionKey(sessionId, "explicit");
|
|
1387
|
+
const connectionType = sessionId && this._sessionTransports.get(sessionId) || (this._isBleConnection() ? "ble" : "usb");
|
|
1388
|
+
const device = this._discoveredDevices.get(resolvedConnectId) ?? {
|
|
1389
|
+
vendor: "ledger",
|
|
1390
|
+
model: "unknown",
|
|
1391
|
+
firmwareVersion: "",
|
|
1392
|
+
deviceId: "",
|
|
1393
|
+
connectId: resolvedConnectId,
|
|
1394
|
+
connectionType
|
|
1395
|
+
};
|
|
1396
|
+
const operation = this._operations.create({
|
|
1397
|
+
searchTargetId,
|
|
1398
|
+
connectId: resolvedConnectId,
|
|
1399
|
+
device,
|
|
1400
|
+
connectionType,
|
|
1401
|
+
connectionKeys: [this._sessions.get(resolvedConnectId) ?? ""]
|
|
964
1402
|
});
|
|
1403
|
+
return (0, import_hwk_adapter_core4.success)(operation.operationId);
|
|
965
1404
|
}
|
|
966
|
-
async
|
|
1405
|
+
async _connectTarget(connectId, preserveOperationId, signal) {
|
|
967
1406
|
debugLog("[LedgerAdapter][REQ]", { method: "connectDevice", connectId, params: { connectId } });
|
|
968
1407
|
try {
|
|
969
|
-
|
|
1408
|
+
this._assertConnectorReady("connectDevice");
|
|
1409
|
+
const discoveredType = this._discoveredDevices.get(connectId)?.connectionType;
|
|
1410
|
+
if (discoveredType === "usb" || discoveredType === "ble") {
|
|
1411
|
+
this._activeConnectionType = discoveredType;
|
|
1412
|
+
}
|
|
1413
|
+
if (this._isBleConnection() && !connectId) {
|
|
970
1414
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
971
|
-
code:
|
|
1415
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
972
1416
|
});
|
|
973
1417
|
}
|
|
974
|
-
|
|
975
|
-
|
|
1418
|
+
await this._ensureDevicePermission(connectId, void 0, signal);
|
|
1419
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1420
|
+
const isMultiTransport = (this.connector.availableTransports?.length ?? 0) > 1;
|
|
1421
|
+
if (!isMultiTransport && this._isBleConnection()) {
|
|
1422
|
+
const previousSessionId = this._sessions.get(connectId);
|
|
1423
|
+
this._operations.endByConnectionKey(connectId, "explicit", preserveOperationId);
|
|
1424
|
+
if (previousSessionId) {
|
|
1425
|
+
this._operations.endByConnectionKey(previousSessionId, "explicit", preserveOperationId);
|
|
1426
|
+
this._sessions.delete(connectId);
|
|
1427
|
+
await this.connector.disconnect(previousSessionId).catch(() => void 0);
|
|
1428
|
+
}
|
|
1429
|
+
} else {
|
|
1430
|
+
await this._evictAllSessions(preserveOperationId);
|
|
1431
|
+
}
|
|
1432
|
+
if (signal) _LedgerAdapter._throwIfAborted(signal);
|
|
1433
|
+
const stateGeneration = this._stateGeneration;
|
|
1434
|
+
const releaseOperation = this._retainConnectorOperation(`connect:${connectId}`);
|
|
1435
|
+
let session;
|
|
1436
|
+
this._connectingConnectId = connectId;
|
|
1437
|
+
try {
|
|
1438
|
+
session = this.connector.availableTransports?.length ? await this.connector.connect(connectId, {
|
|
1439
|
+
transportType: this._activeConnectionType ?? "usb"
|
|
1440
|
+
}) : await this.connector.connect(connectId);
|
|
1441
|
+
if (signal?.aborted || stateGeneration !== this._stateGeneration) {
|
|
1442
|
+
await this.connector.disconnect(session.sessionId).catch(() => void 0);
|
|
1443
|
+
throw Object.assign(new Error("Ledger connection aborted"), {
|
|
1444
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1445
|
+
});
|
|
1446
|
+
}
|
|
1447
|
+
} finally {
|
|
1448
|
+
if (this._connectingConnectId === connectId) this._connectingConnectId = void 0;
|
|
1449
|
+
releaseOperation();
|
|
976
1450
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
this.
|
|
1451
|
+
const resolvedConnectId = session.deviceInfo?.connectId || connectId;
|
|
1452
|
+
this._sessions.set(resolvedConnectId, session.sessionId);
|
|
1453
|
+
this._sessionTransports.set(session.sessionId, this._isBleConnection() ? "ble" : "usb");
|
|
980
1454
|
if (session.deviceInfo) {
|
|
981
|
-
this._discoveredDevices.set(
|
|
1455
|
+
this._discoveredDevices.set(resolvedConnectId, session.deviceInfo);
|
|
982
1456
|
}
|
|
983
|
-
const result = (0,
|
|
1457
|
+
const result = (0, import_hwk_adapter_core4.success)(resolvedConnectId);
|
|
984
1458
|
debugLog("[LedgerAdapter][RES]", { method: "connectDevice", success: true, payload: result });
|
|
985
1459
|
return result;
|
|
986
1460
|
} catch (err) {
|
|
@@ -993,30 +1467,84 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
993
1467
|
return failureResult;
|
|
994
1468
|
}
|
|
995
1469
|
}
|
|
996
|
-
async
|
|
1470
|
+
async releaseOperation(operationId) {
|
|
1471
|
+
const operation = this._operations.findActive(operationId);
|
|
1472
|
+
if (operation) this._cancelOperationWork(operation);
|
|
1473
|
+
const endedOperation = this._operations.release(operationId);
|
|
1474
|
+
if (!endedOperation || this._bareCallMayUseConnection(endedOperation)) return;
|
|
1475
|
+
const { connectId } = endedOperation;
|
|
997
1476
|
debugLog("[LedgerAdapter][REQ]", {
|
|
998
|
-
method: "
|
|
1477
|
+
method: "releaseOperation",
|
|
999
1478
|
connectId,
|
|
1000
1479
|
params: { connectId }
|
|
1001
1480
|
});
|
|
1002
1481
|
try {
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
await this.connector.disconnect(sessionId);
|
|
1006
|
-
this._sessions.delete(connectId);
|
|
1007
|
-
}
|
|
1008
|
-
debugLog("[LedgerAdapter][RES]", { method: "disconnectDevice", success: true });
|
|
1482
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1483
|
+
debugLog("[LedgerAdapter][RES]", { method: "releaseOperation", success: true });
|
|
1009
1484
|
} catch (err) {
|
|
1010
1485
|
const e = err;
|
|
1011
1486
|
debugLog("[LedgerAdapter][RES]", {
|
|
1012
|
-
method: "
|
|
1487
|
+
method: "releaseOperation",
|
|
1013
1488
|
success: false,
|
|
1014
1489
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1015
1490
|
});
|
|
1016
1491
|
throw err;
|
|
1017
1492
|
}
|
|
1018
1493
|
}
|
|
1019
|
-
|
|
1494
|
+
/**
|
|
1495
|
+
* Ends a released operation's calls and prompts before teardown, which otherwise waits on a call
|
|
1496
|
+
* that waits on a prompt nobody will answer. Device I/O already on the wire still drains.
|
|
1497
|
+
*/
|
|
1498
|
+
_cancelOperationWork(operation) {
|
|
1499
|
+
const { operationId } = operation;
|
|
1500
|
+
const reason = (0, import_hwk_adapter_core4.createHwkError)({
|
|
1501
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
1502
|
+
message: "Ledger operation was released",
|
|
1503
|
+
params: { operationId, reason: "explicit" }
|
|
1504
|
+
});
|
|
1505
|
+
const queueKey = ledgerQueueKey({ operationId });
|
|
1506
|
+
const ownsRunningCall = this._jobQueue.getActiveJob()?.deviceId === queueKey;
|
|
1507
|
+
this._jobQueue.cancelActiveAndPending(queueKey, reason);
|
|
1508
|
+
if (!ownsRunningCall) return;
|
|
1509
|
+
this._uiRegistry.cancel(void 0, void 0, operationId);
|
|
1510
|
+
void this.connector.cancel(this._sessions.get(operation.connectId) ?? operation.connectId);
|
|
1511
|
+
}
|
|
1512
|
+
/**
|
|
1513
|
+
* A running call by bare connectId (or still resolving its device by identity) may be on this
|
|
1514
|
+
* connection, e.g. waiting for an unlock; its later stages need it, so it stays cached for that
|
|
1515
|
+
* caller like any bare call's session. A lost connection is torn down regardless.
|
|
1516
|
+
*/
|
|
1517
|
+
_bareCallMayUseConnection(operation) {
|
|
1518
|
+
const activeKey = this._jobQueue.getActiveJob()?.deviceId;
|
|
1519
|
+
return activeKey !== void 0 && !(0, import_hwk_adapter_core4.isHardwareOperationId)(activeKey) && (activeKey === operation.connectId || activeKey === LEDGER_DEFAULT_QUEUE_KEY || operation.connectionKeys.includes(activeKey));
|
|
1520
|
+
}
|
|
1521
|
+
async _releaseOperationConnection(operation) {
|
|
1522
|
+
const sessionIds = /* @__PURE__ */ new Set();
|
|
1523
|
+
for (const [connectId, sessionId] of this._sessions) {
|
|
1524
|
+
if (connectId === operation.connectId || operation.connectionKeys.includes(connectId) || operation.connectionKeys.includes(sessionId)) {
|
|
1525
|
+
this._sessions.delete(connectId);
|
|
1526
|
+
sessionIds.add(sessionId);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
for (const sessionId of sessionIds) {
|
|
1530
|
+
await this._runConnectorTeardown(
|
|
1531
|
+
() => this.connector.disconnect(sessionId).catch(() => void 0)
|
|
1532
|
+
);
|
|
1533
|
+
}
|
|
1534
|
+
}
|
|
1535
|
+
async _releaseLostOperationConnection(operationId) {
|
|
1536
|
+
const endedOperation = this._operations.end(operationId, "disconnect");
|
|
1537
|
+
if (!endedOperation) return;
|
|
1538
|
+
this._discoveredDevices.delete(endedOperation.connectId);
|
|
1539
|
+
await this._releaseOperationConnection(endedOperation);
|
|
1540
|
+
}
|
|
1541
|
+
async getDeviceInfo(connectIdOrOperationId, deviceId) {
|
|
1542
|
+
let connectId;
|
|
1543
|
+
try {
|
|
1544
|
+
connectId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectIdOrOperationId) ? this._operations.resolve(connectIdOrOperationId).connectId : connectIdOrOperationId;
|
|
1545
|
+
} catch (error) {
|
|
1546
|
+
return this.errorToFailure(error);
|
|
1547
|
+
}
|
|
1020
1548
|
debugLog("[LedgerAdapter][REQ]", {
|
|
1021
1549
|
method: "getDeviceInfo",
|
|
1022
1550
|
connectId,
|
|
@@ -1026,7 +1554,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1026
1554
|
await this._ensureDevicePermission(connectId, deviceId);
|
|
1027
1555
|
const cached = this._discoveredDevices.get(connectId) ?? Array.from(this._discoveredDevices.values()).find((d) => d.deviceId === deviceId);
|
|
1028
1556
|
if (cached) {
|
|
1029
|
-
const result = (0,
|
|
1557
|
+
const result = (0, import_hwk_adapter_core4.success)(cached);
|
|
1030
1558
|
debugLog("[LedgerAdapter][RES]", {
|
|
1031
1559
|
method: "getDeviceInfo",
|
|
1032
1560
|
success: true,
|
|
@@ -1034,8 +1562,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1034
1562
|
});
|
|
1035
1563
|
return result;
|
|
1036
1564
|
}
|
|
1037
|
-
const notFound = (0,
|
|
1038
|
-
|
|
1565
|
+
const notFound = (0, import_hwk_adapter_core4.failure)(
|
|
1566
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
1039
1567
|
"Device not found in cache. Call searchDevices() or wait for a device-connected event first."
|
|
1040
1568
|
);
|
|
1041
1569
|
debugLog("[LedgerAdapter][RES]", {
|
|
@@ -1051,11 +1579,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1051
1579
|
success: false,
|
|
1052
1580
|
error: { message: e?.message, _tag: e?._tag, code: e?.code ?? e?.errorCode }
|
|
1053
1581
|
});
|
|
1054
|
-
|
|
1582
|
+
return this.errorToFailure(err);
|
|
1055
1583
|
}
|
|
1056
1584
|
}
|
|
1057
|
-
|
|
1058
|
-
|
|
1585
|
+
/** A bundle's BLE pick that no item got past the wallet check is not kept. */
|
|
1586
|
+
async _dropUncheckedBundlePick(context, signal) {
|
|
1587
|
+
const { connection } = context;
|
|
1588
|
+
const owner = connection ? this._pendingPickBindings.get(connection.connectId) : void 0;
|
|
1589
|
+
if (!connection || !owner) return;
|
|
1590
|
+
this._pendingPickBindings.delete(connection.connectId);
|
|
1591
|
+
this._discardPendingBinding(owner, signal.aborted ? "cancelled" : "failed");
|
|
1592
|
+
if (this._sessions.get(connection.connectId) === connection.sessionId) {
|
|
1593
|
+
await this._dropSession(connection.connectId, signal);
|
|
1594
|
+
}
|
|
1059
1595
|
}
|
|
1060
1596
|
// ---------------------------------------------------------------------------
|
|
1061
1597
|
// Chain call helper
|
|
@@ -1075,7 +1611,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1075
1611
|
commonParams,
|
|
1076
1612
|
installContext
|
|
1077
1613
|
);
|
|
1078
|
-
return (0,
|
|
1614
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1079
1615
|
} catch (err) {
|
|
1080
1616
|
return this.errorToFailure(err);
|
|
1081
1617
|
}
|
|
@@ -1091,13 +1627,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1091
1627
|
if (params && typeof params === "object") {
|
|
1092
1628
|
const {
|
|
1093
1629
|
autoInstallApp,
|
|
1630
|
+
operationId,
|
|
1094
1631
|
passphraseState: _passphraseState,
|
|
1095
1632
|
useEmptyPassphrase: _useEmptyPassphrase,
|
|
1633
|
+
knownConnections,
|
|
1634
|
+
extra,
|
|
1635
|
+
allowDeviceSelection,
|
|
1636
|
+
supportedTransports,
|
|
1096
1637
|
...rest
|
|
1097
1638
|
} = params;
|
|
1098
1639
|
return {
|
|
1099
1640
|
commonParams: {
|
|
1100
|
-
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0
|
|
1641
|
+
autoInstallApp: typeof autoInstallApp === "boolean" ? autoInstallApp : void 0,
|
|
1642
|
+
operationId: typeof operationId === "string" ? operationId : void 0,
|
|
1643
|
+
...(0, import_hwk_adapter_core4.pickConnectionContext)({
|
|
1644
|
+
knownConnections,
|
|
1645
|
+
extra,
|
|
1646
|
+
allowDeviceSelection,
|
|
1647
|
+
supportedTransports
|
|
1648
|
+
})
|
|
1101
1649
|
},
|
|
1102
1650
|
rest
|
|
1103
1651
|
};
|
|
@@ -1263,7 +1811,13 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1263
1811
|
params
|
|
1264
1812
|
);
|
|
1265
1813
|
}
|
|
1266
|
-
tronSignMessage(connectId, deviceId, params) {
|
|
1814
|
+
async tronSignMessage(connectId, deviceId, params) {
|
|
1815
|
+
if (params?.messageType !== "V2") {
|
|
1816
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1817
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1818
|
+
'Ledger signs TRON messages as TIP-191 signMessageV2 only (messageType: "V2")'
|
|
1819
|
+
);
|
|
1820
|
+
}
|
|
1267
1821
|
return this.callChainWithMergedParams(
|
|
1268
1822
|
connectId,
|
|
1269
1823
|
deviceId,
|
|
@@ -1273,14 +1827,33 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1273
1827
|
);
|
|
1274
1828
|
}
|
|
1275
1829
|
// ---------------------------------------------------------------------------
|
|
1276
|
-
//
|
|
1277
|
-
//
|
|
1278
|
-
|
|
1830
|
+
// Zcash chain methods (viewing key + shielded address reads; Zcash app >= 3.8.0)
|
|
1831
|
+
// ---------------------------------------------------------------------------
|
|
1832
|
+
zcashGetFullViewingKey(connectId, deviceId, params) {
|
|
1833
|
+
return this.callChainWithMergedParams(
|
|
1834
|
+
connectId,
|
|
1835
|
+
deviceId,
|
|
1836
|
+
"zcash",
|
|
1837
|
+
"zcashGetFullViewingKey",
|
|
1838
|
+
params
|
|
1839
|
+
);
|
|
1840
|
+
}
|
|
1841
|
+
zcashGetShieldedAddress(connectId, deviceId, params) {
|
|
1842
|
+
return this.callChainWithMergedParams(
|
|
1843
|
+
connectId,
|
|
1844
|
+
deviceId,
|
|
1845
|
+
"zcash",
|
|
1846
|
+
"zcashGetShieldedAddress",
|
|
1847
|
+
params
|
|
1848
|
+
);
|
|
1849
|
+
}
|
|
1850
|
+
// ---------------------------------------------------------------------------
|
|
1851
|
+
// App management: OS-level app install/list, no fingerprint or chain dispatch.
|
|
1279
1852
|
// ---------------------------------------------------------------------------
|
|
1280
1853
|
async installApp(connectId, appName) {
|
|
1281
1854
|
try {
|
|
1282
1855
|
await this.connectorCall(connectId, "installApp", { appName });
|
|
1283
|
-
return (0,
|
|
1856
|
+
return (0, import_hwk_adapter_core4.success)(void 0);
|
|
1284
1857
|
} catch (err) {
|
|
1285
1858
|
return this.errorToFailure(err);
|
|
1286
1859
|
}
|
|
@@ -1288,7 +1861,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1288
1861
|
async listInstalledApps(connectId) {
|
|
1289
1862
|
try {
|
|
1290
1863
|
const result = await this.connectorCall(connectId, "listInstalledApps", {});
|
|
1291
|
-
return (0,
|
|
1864
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1292
1865
|
} catch (err) {
|
|
1293
1866
|
return this.errorToFailure(err);
|
|
1294
1867
|
}
|
|
@@ -1297,7 +1870,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1297
1870
|
async listInstalledNames(connectId) {
|
|
1298
1871
|
try {
|
|
1299
1872
|
const result = await this.connectorCall(connectId, "listInstalledNames", {});
|
|
1300
|
-
return (0,
|
|
1873
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1301
1874
|
} catch (err) {
|
|
1302
1875
|
return this.errorToFailure(err);
|
|
1303
1876
|
}
|
|
@@ -1305,7 +1878,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1305
1878
|
async listAvailableApps(connectId) {
|
|
1306
1879
|
try {
|
|
1307
1880
|
const result = await this.connectorCall(connectId, "listAvailableApps", {});
|
|
1308
|
-
return (0,
|
|
1881
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1309
1882
|
} catch (err) {
|
|
1310
1883
|
return this.errorToFailure(err);
|
|
1311
1884
|
}
|
|
@@ -1313,7 +1886,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1313
1886
|
async getLedgerFirmwareVersion(connectId) {
|
|
1314
1887
|
try {
|
|
1315
1888
|
const result = await this.connectorCall(connectId, "getFirmwareVersion", {});
|
|
1316
|
-
return (0,
|
|
1889
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1317
1890
|
} catch (err) {
|
|
1318
1891
|
return this.errorToFailure(err);
|
|
1319
1892
|
}
|
|
@@ -1321,7 +1894,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1321
1894
|
async getLedgerDeviceInfo(connectId) {
|
|
1322
1895
|
try {
|
|
1323
1896
|
const result = await this.connectorCall(connectId, "getDeviceInfo", {});
|
|
1324
|
-
return (0,
|
|
1897
|
+
return (0, import_hwk_adapter_core4.success)(result);
|
|
1325
1898
|
} catch (err) {
|
|
1326
1899
|
return this.errorToFailure(err);
|
|
1327
1900
|
}
|
|
@@ -1355,28 +1928,28 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1355
1928
|
try {
|
|
1356
1929
|
if (relayUrl) {
|
|
1357
1930
|
if (!this.connector.configure) {
|
|
1358
|
-
return (0,
|
|
1359
|
-
|
|
1931
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1932
|
+
import_hwk_adapter_core4.HardwareErrorCode.MethodNotSupported,
|
|
1360
1933
|
"This Ledger connector does not support genuine-check relay configuration"
|
|
1361
1934
|
);
|
|
1362
1935
|
}
|
|
1363
1936
|
await this.connector.configure({ ledgerGenuineCheckWebSocketUrl: relayUrl });
|
|
1364
|
-
this.
|
|
1937
|
+
await this._resetStateAndDisconnectSessions();
|
|
1365
1938
|
}
|
|
1366
1939
|
const result = await this.connectorCall(connectId, "getDeviceGenuineCheck", {});
|
|
1367
1940
|
if (!result.isGenuine) {
|
|
1368
|
-
return (0,
|
|
1941
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1369
1942
|
vendor: "ledger",
|
|
1370
1943
|
verified: false
|
|
1371
1944
|
});
|
|
1372
1945
|
}
|
|
1373
1946
|
if (!result.deviceId) {
|
|
1374
|
-
return (0,
|
|
1375
|
-
|
|
1947
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
1948
|
+
import_hwk_adapter_core4.HardwareErrorCode.UnknownError,
|
|
1376
1949
|
`Genuine check completed (isGenuine=${result.isGenuine}) but no deviceId was captured`
|
|
1377
1950
|
);
|
|
1378
1951
|
}
|
|
1379
|
-
return (0,
|
|
1952
|
+
return (0, import_hwk_adapter_core4.success)({
|
|
1380
1953
|
vendor: "ledger",
|
|
1381
1954
|
verified: result.isGenuine,
|
|
1382
1955
|
deviceId: result.deviceId
|
|
@@ -1387,10 +1960,10 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1387
1960
|
if (relayUrl) {
|
|
1388
1961
|
try {
|
|
1389
1962
|
await this.connector.configure?.({ ledgerGenuineCheckWebSocketUrl: void 0 });
|
|
1390
|
-
this.
|
|
1963
|
+
await this._resetStateAndDisconnectSessions();
|
|
1391
1964
|
} catch {
|
|
1392
1965
|
this.connector.reset();
|
|
1393
|
-
this.
|
|
1966
|
+
await this._resetStateAndDisconnectSessions();
|
|
1394
1967
|
}
|
|
1395
1968
|
}
|
|
1396
1969
|
}
|
|
@@ -1402,8 +1975,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1402
1975
|
this.emitter.off(event, listener);
|
|
1403
1976
|
}
|
|
1404
1977
|
cancel(connectId) {
|
|
1978
|
+
const namedOperationIsLive = (id) => {
|
|
1979
|
+
try {
|
|
1980
|
+
this._operations.resolve(id);
|
|
1981
|
+
return true;
|
|
1982
|
+
} catch {
|
|
1983
|
+
return false;
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) && !namedOperationIsLive(connectId)) {
|
|
1987
|
+
debugLog("[LedgerAdapter] cancel target already ended; nothing to cancel", {
|
|
1988
|
+
connectId
|
|
1989
|
+
});
|
|
1990
|
+
return;
|
|
1991
|
+
}
|
|
1405
1992
|
const userAbortReason = Object.assign(new Error("User aborted operation"), {
|
|
1406
|
-
code:
|
|
1993
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1407
1994
|
_tag: ERROR_TAG.UserAborted
|
|
1408
1995
|
});
|
|
1409
1996
|
this._lastCancelReason = userAbortReason;
|
|
@@ -1412,60 +1999,143 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1412
1999
|
this._lastCancelReason = void 0;
|
|
1413
2000
|
}
|
|
1414
2001
|
}, 2e3);
|
|
1415
|
-
this.
|
|
1416
|
-
|
|
1417
|
-
|
|
2002
|
+
const activeJobId = this._jobQueue.getActiveJob()?.deviceId;
|
|
2003
|
+
let operationId;
|
|
2004
|
+
if ((0, import_hwk_adapter_core4.isHardwareOperationId)(connectId)) {
|
|
2005
|
+
operationId = connectId;
|
|
2006
|
+
} else if (!connectId && (0, import_hwk_adapter_core4.isHardwareOperationId)(activeJobId)) {
|
|
2007
|
+
operationId = activeJobId;
|
|
2008
|
+
}
|
|
2009
|
+
let resolvedConnectId = connectId;
|
|
2010
|
+
if (operationId) {
|
|
2011
|
+
try {
|
|
2012
|
+
resolvedConnectId = this._operations.resolve(operationId).connectId;
|
|
2013
|
+
} catch {
|
|
2014
|
+
resolvedConnectId = void 0;
|
|
2015
|
+
}
|
|
2016
|
+
}
|
|
2017
|
+
const interactionForPhysicalId = !operationId && connectId ? this._operations.findActiveByConnectionKey(connectId) : void 0;
|
|
2018
|
+
const pendingOperationId = operationId ?? interactionForPhysicalId?.operationId;
|
|
2019
|
+
if (!connectId) {
|
|
2020
|
+
this._uiRegistry.cancel();
|
|
2021
|
+
} else if (pendingOperationId) {
|
|
2022
|
+
this._uiRegistry.cancel(void 0, void 0, pendingOperationId);
|
|
2023
|
+
}
|
|
2024
|
+
this._finishBleBinding("cancelled");
|
|
2025
|
+
if (!connectId) this._pendingOperationBindings.clear();
|
|
2026
|
+
else if (pendingOperationId) this._pendingOperationBindings.delete(pendingOperationId);
|
|
2027
|
+
const queueKeys = /* @__PURE__ */ new Set();
|
|
2028
|
+
if (connectId) queueKeys.add(ledgerQueueKey({ connectId }));
|
|
2029
|
+
if (pendingOperationId) queueKeys.add(ledgerQueueKey({ operationId: pendingOperationId }));
|
|
2030
|
+
if (queueKeys.size) {
|
|
2031
|
+
let cancelledAnyJob = false;
|
|
2032
|
+
for (const key of queueKeys) {
|
|
2033
|
+
cancelledAnyJob = this._jobQueue.cancelActiveAndPending(key, userAbortReason) || cancelledAnyJob;
|
|
2034
|
+
}
|
|
2035
|
+
debugLog("[LedgerAdapter] cancel routed to queue keys", {
|
|
2036
|
+
queueKeys: [...queueKeys],
|
|
2037
|
+
cancelledAnyJob
|
|
2038
|
+
});
|
|
1418
2039
|
} else {
|
|
1419
2040
|
this._jobQueue.cancelActiveAndPending(void 0, userAbortReason);
|
|
1420
2041
|
}
|
|
1421
|
-
if (
|
|
1422
|
-
const sessionId = this._sessions.get(
|
|
2042
|
+
if (resolvedConnectId) {
|
|
2043
|
+
const sessionId = this._sessions.get(resolvedConnectId) ?? resolvedConnectId;
|
|
1423
2044
|
void this.connector.cancel(sessionId);
|
|
1424
2045
|
} else {
|
|
1425
2046
|
for (const sid of this._sessions.values()) void this.connector.cancel(sid);
|
|
1426
2047
|
}
|
|
1427
|
-
|
|
2048
|
+
const connectingConnectId = this._connectingConnectId;
|
|
2049
|
+
const targetKeys = new Set(
|
|
2050
|
+
[
|
|
2051
|
+
connectId,
|
|
2052
|
+
resolvedConnectId,
|
|
2053
|
+
...pendingOperationId ? this._operations.find(pendingOperationId)?.connectionKeys ?? [] : []
|
|
2054
|
+
].filter(Boolean)
|
|
2055
|
+
);
|
|
2056
|
+
const ownsPendingConnect = !connectId || activeJobId !== void 0 && queueKeys.has(activeJobId) || connectingConnectId !== void 0 && targetKeys.has(connectingConnectId);
|
|
2057
|
+
if (this._connectingPromise && ownsPendingConnect) {
|
|
1428
2058
|
this._doConnectAbortController?.abort(userAbortReason);
|
|
1429
2059
|
}
|
|
2060
|
+
if (connectingConnectId && ownsPendingConnect) void this.connector.cancel(connectingConnectId);
|
|
1430
2061
|
}
|
|
1431
2062
|
// ---------------------------------------------------------------------------
|
|
1432
2063
|
// Chain fingerprint
|
|
1433
2064
|
// ---------------------------------------------------------------------------
|
|
2065
|
+
/** A non-empty deviceId is an expected chain fingerprint, not a transport identifier. */
|
|
1434
2066
|
async getChainFingerprint(connectId, deviceId, chain) {
|
|
1435
2067
|
try {
|
|
1436
2068
|
const fingerprint = await this._computeChainFingerprint(
|
|
1437
2069
|
chain,
|
|
1438
2070
|
(method, params) => this.connectorCall(connectId, method, params, void 0, deviceId)
|
|
1439
2071
|
);
|
|
1440
|
-
|
|
2072
|
+
if (deviceId) {
|
|
2073
|
+
if (fingerprint !== deviceId) {
|
|
2074
|
+
return (0, import_hwk_adapter_core4.failure)(
|
|
2075
|
+
import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2076
|
+
formatDeviceMismatchError(deviceId, fingerprint)
|
|
2077
|
+
);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
return (0, import_hwk_adapter_core4.success)(fingerprint);
|
|
1441
2081
|
} catch (err) {
|
|
1442
2082
|
debugError("[LedgerAdapter] getChainFingerprint error:", chain, err);
|
|
1443
2083
|
return this.errorToFailure(err);
|
|
1444
2084
|
}
|
|
1445
2085
|
}
|
|
1446
|
-
/**
|
|
1447
|
-
|
|
1448
|
-
* Safe to call inside connectorCall without causing queue deadlock.
|
|
1449
|
-
*/
|
|
1450
|
-
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
1451
|
-
if (!deviceId) return { success: true };
|
|
2086
|
+
/** Saves a picked BLE endpoint; `identity` is set when its wallet was just checked. */
|
|
2087
|
+
async _saveSelectedBleBinding(connectId, selectionRequestId, context, operationId, signal, identity) {
|
|
1452
2088
|
try {
|
|
1453
|
-
const
|
|
1454
|
-
|
|
1455
|
-
|
|
2089
|
+
const outcome = await (0, import_hwk_adapter_core4.requestSaveDeviceBinding)(
|
|
2090
|
+
this.emitter,
|
|
2091
|
+
this._uiRegistry,
|
|
2092
|
+
{
|
|
2093
|
+
selectionRequestId,
|
|
2094
|
+
connection: { transport: "ble", connectId },
|
|
2095
|
+
...identity ? { identity } : {},
|
|
2096
|
+
extra: context?.extra,
|
|
2097
|
+
operationId
|
|
2098
|
+
},
|
|
2099
|
+
signal
|
|
1456
2100
|
);
|
|
1457
|
-
if (
|
|
1458
|
-
|
|
2101
|
+
if (context) context.bindingSaved = outcome.saved;
|
|
2102
|
+
if (!outcome.saved) {
|
|
2103
|
+
debugLog("[LedgerAdapter] BLE binding not persisted by host", {
|
|
2104
|
+
connectId,
|
|
2105
|
+
reason: outcome.reason
|
|
2106
|
+
});
|
|
1459
2107
|
}
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
2108
|
+
} catch (error) {
|
|
2109
|
+
await this._dropSession(connectId, signal);
|
|
2110
|
+
throw error;
|
|
2111
|
+
} finally {
|
|
2112
|
+
if (this._bindingSelectionRequestId === selectionRequestId) {
|
|
2113
|
+
this._bindingSelectionRequestId = void 0;
|
|
1465
2114
|
}
|
|
1466
|
-
throw err;
|
|
1467
2115
|
}
|
|
1468
2116
|
}
|
|
2117
|
+
async _dropSession(connectId, signal) {
|
|
2118
|
+
const sessionId = this._sessions.get(connectId);
|
|
2119
|
+
this._sessions.delete(connectId);
|
|
2120
|
+
if (!sessionId) return;
|
|
2121
|
+
this._sessionTransports.delete(sessionId);
|
|
2122
|
+
const teardown = this._runConnectorTeardown(() => this.connector.disconnect(sessionId)).catch(
|
|
2123
|
+
() => void 0
|
|
2124
|
+
);
|
|
2125
|
+
if (!signal.aborted) await teardown;
|
|
2126
|
+
}
|
|
2127
|
+
/** Verify on the acquired session without re-entering the job queue. */
|
|
2128
|
+
async _verifyDeviceFingerprintWithSession(sessionId, deviceId, chain) {
|
|
2129
|
+
if (!deviceId) return { success: true };
|
|
2130
|
+
const fingerprint = await this._computeChainFingerprint(
|
|
2131
|
+
chain,
|
|
2132
|
+
(method, params) => this._callConnector(sessionId, method, params)
|
|
2133
|
+
);
|
|
2134
|
+
if (fingerprint === deviceId) {
|
|
2135
|
+
return { success: true };
|
|
2136
|
+
}
|
|
2137
|
+
return { success: false, expected: deviceId, actual: fingerprint };
|
|
2138
|
+
}
|
|
1469
2139
|
/**
|
|
1470
2140
|
* Compute the chain fingerprint via a caller-supplied call strategy.
|
|
1471
2141
|
*
|
|
@@ -1485,7 +2155,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1485
2155
|
const result = await callMethod("btcGetMasterFingerprint", {});
|
|
1486
2156
|
return result.masterFingerprint;
|
|
1487
2157
|
}
|
|
1488
|
-
const path =
|
|
2158
|
+
const path = import_hwk_adapter_core4.CHAIN_FINGERPRINT_PATHS[chain];
|
|
1489
2159
|
let address;
|
|
1490
2160
|
if (chain === "evm") {
|
|
1491
2161
|
address = (await callMethod("evmGetAddress", { path, showOnDevice: false })).address.toLowerCase();
|
|
@@ -1493,10 +2163,19 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1493
2163
|
address = (await callMethod("solGetAddress", { path, showOnDevice: false })).address;
|
|
1494
2164
|
} else if (chain === "tron") {
|
|
1495
2165
|
address = (await callMethod("tronGetAddress", { path, showOnDevice: false })).address;
|
|
2166
|
+
} else if (chain === "zcash") {
|
|
2167
|
+
address = (await callMethod("zcashGetShieldedAddress", { path, showOnDevice: false })).address;
|
|
1496
2168
|
} else {
|
|
1497
2169
|
throw new Error(`Unsupported chain for fingerprint: ${chain}`);
|
|
1498
2170
|
}
|
|
1499
|
-
return (0,
|
|
2171
|
+
return (0, import_hwk_adapter_core4.deriveDeviceFingerprint)(address);
|
|
2172
|
+
}
|
|
2173
|
+
/**
|
|
2174
|
+
* Operation owning the running job, so a mid-call UI request can name it.
|
|
2175
|
+
* Undefined at cold start when no operation owns the job.
|
|
2176
|
+
*/
|
|
2177
|
+
_activeOperationId() {
|
|
2178
|
+
return this._operations.findOperationIdByJobKey(this._jobQueue.getActiveJob()?.deviceId);
|
|
1500
2179
|
}
|
|
1501
2180
|
// Ledger WebUSB won't expose a locked device, so we can't auto-detect unlock.
|
|
1502
2181
|
// The user must press Confirm after unlocking, which triggers a search retry.
|
|
@@ -1507,22 +2186,25 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1507
2186
|
if (signal?.aborted) {
|
|
1508
2187
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1509
2188
|
}
|
|
2189
|
+
const operationId = this._activeOperationId();
|
|
1510
2190
|
const waitPromise = this._uiRegistry.wait(
|
|
1511
|
-
|
|
2191
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
2192
|
+
{ operationId }
|
|
1512
2193
|
);
|
|
1513
|
-
this.emitter.emit(
|
|
1514
|
-
type:
|
|
2194
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT, {
|
|
2195
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT,
|
|
1515
2196
|
payload: {
|
|
1516
2197
|
vendor: "ledger",
|
|
1517
2198
|
reason: "device-not-found",
|
|
1518
|
-
message: "Please connect and unlock your Ledger device"
|
|
2199
|
+
message: "Please connect and unlock your Ledger device",
|
|
2200
|
+
operationId
|
|
1519
2201
|
}
|
|
1520
2202
|
});
|
|
1521
2203
|
let payload;
|
|
1522
2204
|
try {
|
|
1523
2205
|
if (signal) {
|
|
1524
2206
|
const onAbort = () => {
|
|
1525
|
-
this._uiRegistry.cancel(
|
|
2207
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_CONNECT);
|
|
1526
2208
|
};
|
|
1527
2209
|
signal.addEventListener("abort", onAbort, { once: true });
|
|
1528
2210
|
try {
|
|
@@ -1534,20 +2216,20 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1534
2216
|
payload = await waitPromise;
|
|
1535
2217
|
}
|
|
1536
2218
|
} catch (err) {
|
|
1537
|
-
this.emitter.emit(
|
|
1538
|
-
type:
|
|
2219
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2220
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1539
2221
|
payload: {}
|
|
1540
2222
|
});
|
|
1541
2223
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1542
2224
|
_tag: ERROR_TAG.UserAborted,
|
|
1543
|
-
code:
|
|
2225
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1544
2226
|
cause: err
|
|
1545
2227
|
});
|
|
1546
2228
|
}
|
|
1547
2229
|
if (!payload?.confirmed) {
|
|
1548
2230
|
throw Object.assign(new Error("User cancelled Ledger connection"), {
|
|
1549
2231
|
_tag: ERROR_TAG.UserAborted,
|
|
1550
|
-
code:
|
|
2232
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1551
2233
|
});
|
|
1552
2234
|
}
|
|
1553
2235
|
await new Promise((resolve) => {
|
|
@@ -1561,7 +2243,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1561
2243
|
* Returns the params to pass through (with `showOnDevice` possibly
|
|
1562
2244
|
* promoted), or `null` if the user declined.
|
|
1563
2245
|
*/
|
|
1564
|
-
async _gateBtcHighIndex(params) {
|
|
2246
|
+
async _gateBtcHighIndex(params, signal) {
|
|
1565
2247
|
const accountIndex = btcAccountIndexFromPath(params.path);
|
|
1566
2248
|
if (params.showOnDevice) return params;
|
|
1567
2249
|
if (accountIndex === null || accountIndex < BTC_HIGH_INDEX_THRESHOLD) {
|
|
@@ -1570,50 +2252,74 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1570
2252
|
if (this._btcHighIndexConfirmedThisSession) {
|
|
1571
2253
|
return { ...params, showOnDevice: true };
|
|
1572
2254
|
}
|
|
1573
|
-
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex);
|
|
2255
|
+
const confirmed = await this._waitForBtcHighIndexConfirm(params.path, accountIndex, signal);
|
|
1574
2256
|
if (!confirmed) return null;
|
|
1575
2257
|
this._btcHighIndexConfirmedThisSession = true;
|
|
1576
2258
|
return { ...params, showOnDevice: true };
|
|
1577
2259
|
}
|
|
1578
|
-
async _waitForBtcHighIndexConfirm(path, accountIndex) {
|
|
2260
|
+
async _waitForBtcHighIndexConfirm(path, accountIndex, signal) {
|
|
2261
|
+
const operationId = this._activeOperationId();
|
|
1579
2262
|
const waitPromise = this._uiRegistry.wait(
|
|
1580
|
-
|
|
2263
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2264
|
+
{ operationId }
|
|
1581
2265
|
);
|
|
1582
|
-
this.emitter.emit(
|
|
1583
|
-
type:
|
|
2266
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM, {
|
|
2267
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
1584
2268
|
payload: {
|
|
1585
2269
|
vendor: "ledger",
|
|
1586
2270
|
path,
|
|
1587
|
-
accountIndex
|
|
2271
|
+
accountIndex,
|
|
2272
|
+
operationId
|
|
1588
2273
|
}
|
|
1589
2274
|
});
|
|
1590
2275
|
try {
|
|
1591
|
-
const payload = await
|
|
2276
|
+
const payload = await this._awaitUiAnswer(
|
|
2277
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_BTC_HIGH_INDEX_CONFIRM,
|
|
2278
|
+
waitPromise,
|
|
2279
|
+
signal
|
|
2280
|
+
);
|
|
1592
2281
|
return !!payload?.confirmed;
|
|
1593
2282
|
} catch (err) {
|
|
1594
|
-
this.emitter.emit(
|
|
1595
|
-
type:
|
|
2283
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2284
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1596
2285
|
payload: {}
|
|
1597
2286
|
});
|
|
1598
2287
|
return false;
|
|
1599
2288
|
}
|
|
1600
2289
|
}
|
|
2290
|
+
/** A cancel of the job ends its open prompt, even when no operation names that prompt. */
|
|
2291
|
+
async _awaitUiAnswer(requestType, waitPromise, signal) {
|
|
2292
|
+
const onAbort = () => this._uiRegistry.cancel(requestType);
|
|
2293
|
+
if (signal.aborted) onAbort();
|
|
2294
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2295
|
+
try {
|
|
2296
|
+
return await waitPromise;
|
|
2297
|
+
} finally {
|
|
2298
|
+
signal.removeEventListener("abort", onAbort);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
1601
2301
|
// Ask the user whether to install a missing app (autoInstallApp flow).
|
|
1602
2302
|
// Same register-then-emit ordering as the BTC high-index gate.
|
|
1603
|
-
async _waitForInstallAppConfirm(appName) {
|
|
2303
|
+
async _waitForInstallAppConfirm(appName, signal) {
|
|
2304
|
+
const operationId = this._activeOperationId();
|
|
1604
2305
|
const waitPromise = this._uiRegistry.wait(
|
|
1605
|
-
|
|
2306
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2307
|
+
{ operationId }
|
|
1606
2308
|
);
|
|
1607
|
-
this.emitter.emit(
|
|
1608
|
-
type:
|
|
1609
|
-
payload: { vendor: "ledger", appName }
|
|
2309
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP, {
|
|
2310
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2311
|
+
payload: { vendor: "ledger", appName, operationId }
|
|
1610
2312
|
});
|
|
1611
2313
|
try {
|
|
1612
|
-
const payload = await
|
|
2314
|
+
const payload = await this._awaitUiAnswer(
|
|
2315
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_INSTALL_APP,
|
|
2316
|
+
waitPromise,
|
|
2317
|
+
signal
|
|
2318
|
+
);
|
|
1613
2319
|
return !!payload?.confirmed;
|
|
1614
2320
|
} catch (err) {
|
|
1615
|
-
this.emitter.emit(
|
|
1616
|
-
type:
|
|
2321
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
2322
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1617
2323
|
payload: {}
|
|
1618
2324
|
});
|
|
1619
2325
|
return false;
|
|
@@ -1622,34 +2328,44 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1622
2328
|
// Layer 1 entry. Caller signal only races the outer awaiter; the shared
|
|
1623
2329
|
// `_doConnect` runs under its own internal controller so caller A's cancel
|
|
1624
2330
|
// doesn't kill caller B's await.
|
|
1625
|
-
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false) {
|
|
2331
|
+
async ensureConnected(connectId, signal, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
1626
2332
|
if (signal.aborted) _LedgerAdapter._throwIfAborted(signal);
|
|
1627
|
-
|
|
2333
|
+
this._assertConnectorReady("connectDevice");
|
|
2334
|
+
if (this._isBleConnection() && !connectId && !allowUsbEphemeralFallback) {
|
|
1628
2335
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1629
|
-
code:
|
|
2336
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1630
2337
|
});
|
|
1631
2338
|
}
|
|
1632
2339
|
if (connectId && this._sessions.has(connectId)) return connectId;
|
|
1633
2340
|
if (!connectId && this._sessions.size > 0) {
|
|
1634
|
-
if (!
|
|
2341
|
+
if (!this._isBleConnection() && this._sessions.size > 1) {
|
|
1635
2342
|
throw Object.assign(
|
|
1636
2343
|
new Error(
|
|
1637
2344
|
"Ledger USB session invariant violated: more than one session is active. Please reconnect the device."
|
|
1638
2345
|
),
|
|
1639
|
-
{ code:
|
|
2346
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceOneDeviceOnly }
|
|
1640
2347
|
);
|
|
1641
2348
|
}
|
|
1642
2349
|
return this._sessions.keys().next().value;
|
|
1643
2350
|
}
|
|
1644
|
-
if (!this._connectingPromise) {
|
|
1645
|
-
|
|
1646
|
-
|
|
2351
|
+
if (!this._connectingPromise || this._doConnectAbortController?.signal.aborted) {
|
|
2352
|
+
const controller = new AbortController();
|
|
2353
|
+
this._doConnectAbortController = controller;
|
|
2354
|
+
const innerSignal = controller.signal;
|
|
1647
2355
|
this._connectingPromise = (async () => {
|
|
1648
2356
|
try {
|
|
1649
|
-
return await this._doConnect(
|
|
2357
|
+
return await this._doConnect(
|
|
2358
|
+
innerSignal,
|
|
2359
|
+
connectId,
|
|
2360
|
+
allowUsbEphemeralFallback,
|
|
2361
|
+
preserveOperationId,
|
|
2362
|
+
context
|
|
2363
|
+
);
|
|
1650
2364
|
} finally {
|
|
1651
|
-
this.
|
|
1652
|
-
|
|
2365
|
+
if (this._doConnectAbortController === controller) {
|
|
2366
|
+
this._connectingPromise = null;
|
|
2367
|
+
this._doConnectAbortController = null;
|
|
2368
|
+
}
|
|
1653
2369
|
}
|
|
1654
2370
|
})();
|
|
1655
2371
|
}
|
|
@@ -1658,45 +2374,86 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1658
2374
|
// Layer 1 main loop — the ONLY place in SDK that emits unlock dialog.
|
|
1659
2375
|
// Bounded by MAX_DOCONNECT_CONFIRMS — after N Confirms with no progress,
|
|
1660
2376
|
// 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
|
-
|
|
2377
|
+
async _doConnect(internalSignal, targetConnectId, allowUsbEphemeralFallback = false, preserveOperationId, context) {
|
|
2378
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2379
|
+
if (this.connector.availableTransports?.includes("usb") && this.connector.availableTransports.includes("ble")) {
|
|
2380
|
+
this._activeConnectionType = "usb";
|
|
2381
|
+
const usbDevices = context?.supportedTransports && !context.supportedTransports.includes("usb") ? [] : await this._searchDevices({ transportType: "usb" }, internalSignal);
|
|
2382
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2383
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2384
|
+
(connection) => connection.transport === "usb"
|
|
2385
|
+
);
|
|
2386
|
+
const usbTarget = knownUsb?.transport === "usb" ? knownUsb.connectId : usbDevices.find((device) => device.connectId === targetConnectId)?.connectId;
|
|
2387
|
+
if (usbDevices.length > 0 && (usbTarget || !targetConnectId || allowUsbEphemeralFallback)) {
|
|
2388
|
+
return this._connectFirstOrSelect(
|
|
2389
|
+
usbDevices,
|
|
2390
|
+
usbTarget,
|
|
2391
|
+
allowUsbEphemeralFallback,
|
|
2392
|
+
preserveOperationId,
|
|
2393
|
+
context,
|
|
2394
|
+
internalSignal
|
|
2395
|
+
);
|
|
2396
|
+
}
|
|
2397
|
+
if (context?.supportedTransports && !context.supportedTransports.includes("ble")) {
|
|
2398
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2399
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2400
|
+
message: "This Ledger model has no Bluetooth transport; connect it over USB"
|
|
2401
|
+
});
|
|
1676
2402
|
}
|
|
2403
|
+
this._activeConnectionType = "ble";
|
|
2404
|
+
const knownBle = context?.knownConnections?.find(
|
|
2405
|
+
(connection) => connection.transport === "ble"
|
|
2406
|
+
);
|
|
2407
|
+
if (knownBle?.transport === "ble") {
|
|
2408
|
+
return this._connectDeviceOrThrow(knownBle.connectId, preserveOperationId, internalSignal);
|
|
2409
|
+
}
|
|
2410
|
+
if (targetConnectId && context?.knownConnections === void 0) {
|
|
2411
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2412
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2413
|
+
message: "Ledger connection metadata is required before starting Bluetooth binding"
|
|
2414
|
+
});
|
|
2415
|
+
}
|
|
2416
|
+
const bleDevices = await this._searchDevices({ transportType: "ble" }, internalSignal);
|
|
2417
|
+
return this._connectFirstOrSelect(
|
|
2418
|
+
bleDevices,
|
|
2419
|
+
void 0,
|
|
2420
|
+
allowUsbEphemeralFallback,
|
|
2421
|
+
preserveOperationId,
|
|
2422
|
+
context,
|
|
2423
|
+
internalSignal
|
|
2424
|
+
);
|
|
2425
|
+
}
|
|
2426
|
+
if (this._isBleConnection() && targetConnectId) {
|
|
2427
|
+
return this._connectDeviceOrThrow(targetConnectId, preserveOperationId, internalSignal);
|
|
1677
2428
|
}
|
|
1678
2429
|
let confirms = 0;
|
|
1679
2430
|
while (!internalSignal.aborted) {
|
|
1680
2431
|
this.emitter.emit("ui-event", {
|
|
1681
|
-
type:
|
|
2432
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.Searching,
|
|
1682
2433
|
payload: { sessionId: "" }
|
|
1683
2434
|
});
|
|
1684
|
-
let devices = await this.
|
|
2435
|
+
let devices = await this._searchDevices(void 0, internalSignal);
|
|
2436
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1685
2437
|
if (devices.length === 0) {
|
|
1686
2438
|
for (let i = 0; i < 3 && !internalSignal.aborted; i += 1) {
|
|
1687
2439
|
await new Promise((resolve) => {
|
|
1688
|
-
setTimeout(resolve,
|
|
2440
|
+
setTimeout(resolve, import_hwk_adapter_core4.DEVICE_CONNECT_RETRY_DELAY_MS);
|
|
1689
2441
|
});
|
|
1690
|
-
|
|
2442
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
2443
|
+
devices = await this._searchDevices(void 0, internalSignal);
|
|
2444
|
+
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1691
2445
|
if (devices.length > 0) break;
|
|
1692
2446
|
}
|
|
1693
2447
|
}
|
|
1694
|
-
if (devices.length > 0) {
|
|
2448
|
+
if (devices.length > 0 || this._isBleConnection() && allowUsbEphemeralFallback) {
|
|
1695
2449
|
try {
|
|
1696
2450
|
return await this._connectFirstOrSelect(
|
|
1697
2451
|
devices,
|
|
1698
2452
|
targetConnectId,
|
|
1699
|
-
allowUsbEphemeralFallback
|
|
2453
|
+
allowUsbEphemeralFallback,
|
|
2454
|
+
preserveOperationId,
|
|
2455
|
+
context,
|
|
2456
|
+
internalSignal
|
|
1700
2457
|
);
|
|
1701
2458
|
} catch (err) {
|
|
1702
2459
|
if (!isDeviceLockedError(err) && !isDeviceNotAdvertisingError(err) && !isDeviceDisconnectedError(err)) {
|
|
@@ -1716,7 +2473,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1716
2473
|
new Error(
|
|
1717
2474
|
"Device not connected after multiple attempts. Please ensure your Ledger is awake, unlocked, and in range, then try again."
|
|
1718
2475
|
),
|
|
1719
|
-
{ code:
|
|
2476
|
+
{ code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound }
|
|
1720
2477
|
);
|
|
1721
2478
|
}
|
|
1722
2479
|
await this._waitForDeviceConnect(internalSignal);
|
|
@@ -1725,45 +2482,147 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1725
2482
|
_LedgerAdapter._throwIfAborted(internalSignal);
|
|
1726
2483
|
throw new Error("_doConnect aborted");
|
|
1727
2484
|
}
|
|
1728
|
-
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback
|
|
2485
|
+
async _connectFirstOrSelect(devices, targetConnectId, allowUsbEphemeralFallback, preserveOperationId, context, signal) {
|
|
2486
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
1729
2487
|
if (targetConnectId) {
|
|
1730
2488
|
const target = devices.find(
|
|
1731
2489
|
(d) => d.connectId === targetConnectId || d.deviceId === targetConnectId
|
|
1732
2490
|
);
|
|
1733
2491
|
if (target) {
|
|
1734
|
-
return this._connectDeviceOrThrow(target.connectId);
|
|
2492
|
+
return this._connectDeviceOrThrow(target.connectId, preserveOperationId, signal);
|
|
1735
2493
|
}
|
|
1736
|
-
if (!
|
|
2494
|
+
if (!this._isBleConnection() && devices.length === 1 && allowUsbEphemeralFallback) {
|
|
1737
2495
|
debugLog(
|
|
1738
2496
|
`[LedgerAdapter] target ${targetConnectId} not in fresh enumeration; accepting sole USB device ${devices[0].connectId} for fingerprint-verified recovery`
|
|
1739
2497
|
);
|
|
1740
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2498
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1741
2499
|
}
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
2500
|
+
if (!this._isBleConnection() || !allowUsbEphemeralFallback) {
|
|
2501
|
+
const err = Object.assign(new Error(`Target Ledger unavailable: ${targetConnectId}`), {
|
|
2502
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2503
|
+
});
|
|
2504
|
+
if (this._isBleConnection()) {
|
|
2505
|
+
err._tag = ERROR_TAG.DeviceNotAdvertising;
|
|
2506
|
+
}
|
|
2507
|
+
throw err;
|
|
1747
2508
|
}
|
|
1748
|
-
throw err;
|
|
1749
2509
|
}
|
|
1750
|
-
|
|
2510
|
+
const requiresBleSelection = this._isBleConnection();
|
|
2511
|
+
if (requiresBleSelection && !allowUsbEphemeralFallback) {
|
|
1751
2512
|
throw Object.assign(new Error("Ledger BLE connectId is required."), {
|
|
1752
|
-
code:
|
|
2513
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1753
2514
|
});
|
|
1754
2515
|
}
|
|
1755
|
-
if (
|
|
1756
|
-
|
|
2516
|
+
if (requiresBleSelection && context?.allowDeviceSelection !== false) {
|
|
2517
|
+
const bindingSessionId = context?.bindingSessionId ?? this._uiRegistry.createRequestId();
|
|
2518
|
+
if (context) context.bindingSessionId = bindingSessionId;
|
|
2519
|
+
const allowUsbFallback = context?.bindingReason !== "manual-rebind" && Boolean(this.connector.availableTransports?.includes("usb")) && (!context?.supportedTransports || context.supportedTransports.includes("usb"));
|
|
2520
|
+
const knownUsb = context?.knownConnections?.find(
|
|
2521
|
+
(connection) => connection.transport === "usb"
|
|
2522
|
+
);
|
|
2523
|
+
const usbConnectId = knownUsb?.transport === "usb" ? knownUsb.connectId : targetConnectId;
|
|
2524
|
+
const { device, requestId } = await (0, import_hwk_adapter_core4.requestBleDeviceSelection)({
|
|
2525
|
+
emitter: this.emitter,
|
|
2526
|
+
registry: this._uiRegistry,
|
|
2527
|
+
signal,
|
|
2528
|
+
allowUsbFallback,
|
|
2529
|
+
scan: async () => {
|
|
2530
|
+
if (allowUsbFallback) {
|
|
2531
|
+
const usbDevices = await this._searchDevices({ transportType: "usb" }, signal);
|
|
2532
|
+
const candidate = usbDevices.find(
|
|
2533
|
+
(device2) => device2.connectionType === "usb" && device2.connectId === usbConnectId
|
|
2534
|
+
) ?? (usbDevices.length === 1 && usbDevices[0].connectionType === "usb" ? usbDevices[0] : void 0);
|
|
2535
|
+
if (candidate) return [candidate];
|
|
2536
|
+
}
|
|
2537
|
+
return this._searchDevices({ transportType: "ble", waitForAllTransports: true }, signal);
|
|
2538
|
+
},
|
|
2539
|
+
request: {
|
|
2540
|
+
devices,
|
|
2541
|
+
bindingSessionId,
|
|
2542
|
+
context: {
|
|
2543
|
+
kind: "bind-connection",
|
|
2544
|
+
transport: "ble",
|
|
2545
|
+
reason: context?.bindingReason ?? (targetConnectId ? "known-connection-unavailable" : "missing-binding")
|
|
2546
|
+
},
|
|
2547
|
+
extra: context?.extra,
|
|
2548
|
+
operationId: preserveOperationId
|
|
2549
|
+
}
|
|
2550
|
+
});
|
|
2551
|
+
if (device.connectionType === "usb") {
|
|
2552
|
+
this._activeConnectionType = "usb";
|
|
2553
|
+
if (context) context.selectedConnection = void 0;
|
|
2554
|
+
this._bindingSelectionRequestId = requestId;
|
|
2555
|
+
this._finishBleBinding("cancelled");
|
|
2556
|
+
return this._connectDeviceOrThrow(device.connectId, preserveOperationId, signal);
|
|
2557
|
+
}
|
|
2558
|
+
this._bindingSelectionRequestId = requestId;
|
|
2559
|
+
const connected = await this._connectDeviceOrThrow(
|
|
2560
|
+
device.connectId,
|
|
2561
|
+
preserveOperationId,
|
|
2562
|
+
signal
|
|
2563
|
+
);
|
|
2564
|
+
if (context) context.selectedConnection = { connectId: connected, requestId };
|
|
2565
|
+
if (context?.deferBindingSave) {
|
|
2566
|
+
context.pendingBinding = { connectId: connected, requestId };
|
|
2567
|
+
} else {
|
|
2568
|
+
await this._saveSelectedBleBinding(
|
|
2569
|
+
connected,
|
|
2570
|
+
requestId,
|
|
2571
|
+
context,
|
|
2572
|
+
preserveOperationId,
|
|
2573
|
+
signal
|
|
2574
|
+
);
|
|
2575
|
+
}
|
|
2576
|
+
return connected;
|
|
2577
|
+
}
|
|
2578
|
+
if (devices.length > 0 && (devices.length > 1 || requiresBleSelection)) {
|
|
2579
|
+
if (context?.allowDeviceSelection === false || !this.emitter.listenerCount(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE)) {
|
|
2580
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2581
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound,
|
|
2582
|
+
message: "Select a Ledger device before continuing"
|
|
2583
|
+
});
|
|
2584
|
+
}
|
|
2585
|
+
const requestId = this._uiRegistry.createRequestId();
|
|
2586
|
+
const operationId = this._activeOperationId();
|
|
2587
|
+
const waitPromise = this._uiRegistry.wait(
|
|
2588
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2589
|
+
{ requestId, operationId }
|
|
2590
|
+
);
|
|
2591
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE, {
|
|
2592
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_SELECT_DEVICE,
|
|
2593
|
+
payload: {
|
|
2594
|
+
devices,
|
|
2595
|
+
requestId,
|
|
2596
|
+
operationId,
|
|
2597
|
+
context: requiresBleSelection ? {
|
|
2598
|
+
kind: "bind-connection",
|
|
2599
|
+
transport: "ble",
|
|
2600
|
+
reason: targetConnectId ? "known-connection-unavailable" : "missing-binding"
|
|
2601
|
+
} : { kind: "select-device", transport: "usb", reason: "multiple-candidates" },
|
|
2602
|
+
extra: context?.extra
|
|
2603
|
+
}
|
|
2604
|
+
});
|
|
2605
|
+
const { sdkConnectId } = await this._abortable(signal, waitPromise);
|
|
2606
|
+
_LedgerAdapter._throwIfAborted(signal);
|
|
2607
|
+
const selected = devices.find((device) => device.connectId === sdkConnectId);
|
|
2608
|
+
if (!selected) {
|
|
2609
|
+
throw Object.assign(new Error("Selected Ledger is no longer available"), {
|
|
2610
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
2611
|
+
});
|
|
2612
|
+
}
|
|
2613
|
+
if (context && requiresBleSelection)
|
|
2614
|
+
context.selectedConnection = { connectId: selected.connectId, requestId };
|
|
2615
|
+
return this._connectDeviceOrThrow(selected.connectId, preserveOperationId, signal);
|
|
1757
2616
|
}
|
|
1758
2617
|
if (devices.length !== 1) {
|
|
1759
2618
|
throw Object.assign(new Error("Ledger device not found."), {
|
|
1760
|
-
code:
|
|
2619
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceNotFound
|
|
1761
2620
|
});
|
|
1762
2621
|
}
|
|
1763
|
-
return this._connectDeviceOrThrow(devices[0].connectId);
|
|
2622
|
+
return this._connectDeviceOrThrow(devices[0].connectId, preserveOperationId, signal);
|
|
1764
2623
|
}
|
|
1765
|
-
async _connectDeviceOrThrow(chosenConnectId) {
|
|
1766
|
-
const result = await this.
|
|
2624
|
+
async _connectDeviceOrThrow(chosenConnectId, preserveOperationId, signal) {
|
|
2625
|
+
const result = await this._connectTarget(chosenConnectId, preserveOperationId, signal);
|
|
1767
2626
|
if (!result.success) {
|
|
1768
2627
|
const payload = result.payload;
|
|
1769
2628
|
const rethrow = Object.assign(new Error(payload.error), {
|
|
@@ -1774,16 +2633,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1774
2633
|
}
|
|
1775
2634
|
throw rethrow;
|
|
1776
2635
|
}
|
|
1777
|
-
return
|
|
2636
|
+
return result.payload;
|
|
1778
2637
|
}
|
|
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
2638
|
/**
|
|
1788
2639
|
* Unwrap a `ConnectorCallResult` back into the throw-based control flow this
|
|
1789
2640
|
* class relies on. On failure, rehydrate a FLAT Error (lifting `params.*`
|
|
@@ -1795,7 +2646,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1795
2646
|
*/
|
|
1796
2647
|
_unwrapConnectorResult(result) {
|
|
1797
2648
|
if (result.success) return result.payload;
|
|
1798
|
-
throw (0,
|
|
2649
|
+
throw (0, import_hwk_adapter_core4.rehydrateConnectorError)(result.error);
|
|
1799
2650
|
}
|
|
1800
2651
|
/**
|
|
1801
2652
|
* `connector.call` + result unwrap, optionally raced against an abort
|
|
@@ -1804,33 +2655,145 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1804
2655
|
* lives in one place.
|
|
1805
2656
|
*/
|
|
1806
2657
|
async _callConnector(sessionId, method, params, signal) {
|
|
1807
|
-
|
|
2658
|
+
this._assertConnectorReady(method);
|
|
2659
|
+
if (signal?.aborted) throw this._abortReason(signal);
|
|
2660
|
+
const releaseOperation = this._retainConnectorOperation(`call:${sessionId}`);
|
|
2661
|
+
let promise;
|
|
2662
|
+
try {
|
|
2663
|
+
promise = this.connector.call(sessionId, method, params).finally(releaseOperation);
|
|
2664
|
+
} catch (error) {
|
|
2665
|
+
releaseOperation();
|
|
2666
|
+
throw error;
|
|
2667
|
+
}
|
|
1808
2668
|
const result = signal ? await this._abortable(signal, promise) : await promise;
|
|
1809
2669
|
return this._unwrapConnectorResult(result);
|
|
1810
2670
|
}
|
|
2671
|
+
_assertConnectorReady(method) {
|
|
2672
|
+
if (this._resetPromise || this._pendingConnectorTeardowns > 0 || this._unsettledConnectorOperations.size > 0) {
|
|
2673
|
+
throw _LedgerAdapter._createDeviceBusyError(method);
|
|
2674
|
+
}
|
|
2675
|
+
}
|
|
2676
|
+
_runConnectorTeardown(task) {
|
|
2677
|
+
const previous = this._connectorTeardownTail;
|
|
2678
|
+
let releaseTail = () => void 0;
|
|
2679
|
+
this._connectorTeardownTail = new Promise((resolve) => {
|
|
2680
|
+
releaseTail = resolve;
|
|
2681
|
+
});
|
|
2682
|
+
this._pendingConnectorTeardowns += 1;
|
|
2683
|
+
return (async () => {
|
|
2684
|
+
try {
|
|
2685
|
+
await previous;
|
|
2686
|
+
await this._waitForConnectorOperationsToDrain();
|
|
2687
|
+
await task();
|
|
2688
|
+
} finally {
|
|
2689
|
+
this._pendingConnectorTeardowns -= 1;
|
|
2690
|
+
releaseTail();
|
|
2691
|
+
}
|
|
2692
|
+
})();
|
|
2693
|
+
}
|
|
2694
|
+
_waitForConnectorOperationsToDrain() {
|
|
2695
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2696
|
+
return Promise.resolve();
|
|
2697
|
+
}
|
|
2698
|
+
return new Promise((resolve) => {
|
|
2699
|
+
this._connectorIdleWaiters.add(resolve);
|
|
2700
|
+
});
|
|
2701
|
+
}
|
|
2702
|
+
_retainConnectorOperation(key) {
|
|
2703
|
+
this._unsettledConnectorOperations.set(
|
|
2704
|
+
key,
|
|
2705
|
+
(this._unsettledConnectorOperations.get(key) ?? 0) + 1
|
|
2706
|
+
);
|
|
2707
|
+
let released = false;
|
|
2708
|
+
return () => {
|
|
2709
|
+
if (released) return;
|
|
2710
|
+
released = true;
|
|
2711
|
+
const remaining = (this._unsettledConnectorOperations.get(key) ?? 1) - 1;
|
|
2712
|
+
if (remaining > 0) {
|
|
2713
|
+
this._unsettledConnectorOperations.set(key, remaining);
|
|
2714
|
+
} else {
|
|
2715
|
+
this._unsettledConnectorOperations.delete(key);
|
|
2716
|
+
}
|
|
2717
|
+
if (this._unsettledConnectorOperations.size === 0) {
|
|
2718
|
+
for (const resolve of this._connectorIdleWaiters) resolve();
|
|
2719
|
+
this._connectorIdleWaiters.clear();
|
|
2720
|
+
}
|
|
2721
|
+
};
|
|
2722
|
+
}
|
|
1811
2723
|
async connectorCall(connectId, method, params, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
1812
|
-
|
|
1813
|
-
|
|
2724
|
+
const positionalOperationId = (0, import_hwk_adapter_core4.isHardwareOperationId)(connectId) ? connectId : void 0;
|
|
2725
|
+
if (positionalOperationId && commonParams?.operationId && positionalOperationId !== commonParams.operationId) {
|
|
2726
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2727
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.InvalidParams,
|
|
2728
|
+
message: "Conflicting Ledger operation ids",
|
|
2729
|
+
params: {
|
|
2730
|
+
positionalOperationId,
|
|
2731
|
+
commonOperationId: commonParams.operationId
|
|
2732
|
+
}
|
|
2733
|
+
});
|
|
2734
|
+
}
|
|
2735
|
+
const operationId = commonParams?.operationId ?? positionalOperationId;
|
|
2736
|
+
const operation = operationId ? this._operations.resolve(operationId) : void 0;
|
|
2737
|
+
const releaseOperationRetention = operationId ? this._operations.retain(operationId) : void 0;
|
|
2738
|
+
const effectiveConnectId = operation?.connectId ?? connectId;
|
|
2739
|
+
debugLog("[LedgerAdapter][REQ]", {
|
|
2740
|
+
method,
|
|
2741
|
+
connectId: effectiveConnectId || "(empty)",
|
|
2742
|
+
params: summarizeForLog(params, { method })
|
|
2743
|
+
});
|
|
2744
|
+
const queueKey = ledgerQueueKey({ operationId, connectId: effectiveConnectId });
|
|
1814
2745
|
try {
|
|
1815
2746
|
const result = await this._jobQueue.enqueue(
|
|
1816
2747
|
queueKey,
|
|
1817
|
-
async (signal) =>
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
1825
|
-
|
|
1826
|
-
|
|
2748
|
+
async (signal) => {
|
|
2749
|
+
if (operationId) this._activeOperationJobs.add(operationId);
|
|
2750
|
+
try {
|
|
2751
|
+
return await this._runConnectorCall(
|
|
2752
|
+
effectiveConnectId,
|
|
2753
|
+
method,
|
|
2754
|
+
params,
|
|
2755
|
+
signal,
|
|
2756
|
+
fingerprint,
|
|
2757
|
+
permissionDeviceId,
|
|
2758
|
+
commonParams,
|
|
2759
|
+
installContext ?? {},
|
|
2760
|
+
operationId
|
|
2761
|
+
);
|
|
2762
|
+
} catch (error) {
|
|
2763
|
+
const status = signal.aborted ? "cancelled" : "failed";
|
|
2764
|
+
const bundleConnectId = installContext?.connection?.connectId;
|
|
2765
|
+
let keptBundlePick = false;
|
|
2766
|
+
for (const [pickedConnectId, owner] of this._pendingPickBindings) {
|
|
2767
|
+
if (pickedConnectId === bundleConnectId) {
|
|
2768
|
+
keptBundlePick = true;
|
|
2769
|
+
} else {
|
|
2770
|
+
this._pendingPickBindings.delete(pickedConnectId);
|
|
2771
|
+
this._discardPendingBinding(owner, status);
|
|
2772
|
+
await this._dropSession(pickedConnectId, signal);
|
|
2773
|
+
}
|
|
2774
|
+
}
|
|
2775
|
+
if (!keptBundlePick) this._finishBleBinding(status);
|
|
2776
|
+
throw error;
|
|
2777
|
+
} finally {
|
|
2778
|
+
if (operationId) {
|
|
2779
|
+
this._activeOperationJobs.delete(operationId);
|
|
2780
|
+
if (this._pendingOperationDisconnects.delete(operationId)) {
|
|
2781
|
+
await this._releaseLostOperationConnection(operationId);
|
|
2782
|
+
}
|
|
2783
|
+
}
|
|
2784
|
+
}
|
|
2785
|
+
},
|
|
1827
2786
|
{
|
|
1828
2787
|
label: method,
|
|
1829
2788
|
rejectIfBusy: true,
|
|
1830
2789
|
busyError: _LedgerAdapter._createDeviceBusyError(method)
|
|
1831
2790
|
}
|
|
1832
2791
|
);
|
|
1833
|
-
debugLog("[LedgerAdapter][RES]", {
|
|
2792
|
+
debugLog("[LedgerAdapter][RES]", {
|
|
2793
|
+
method,
|
|
2794
|
+
success: true,
|
|
2795
|
+
payload: summarizeForLog(result, { method, role: "result" })
|
|
2796
|
+
});
|
|
1834
2797
|
return result;
|
|
1835
2798
|
} catch (err) {
|
|
1836
2799
|
const e = err;
|
|
@@ -1844,15 +2807,22 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1844
2807
|
}
|
|
1845
2808
|
});
|
|
1846
2809
|
throw err;
|
|
2810
|
+
} finally {
|
|
2811
|
+
releaseOperationRetention?.();
|
|
1847
2812
|
}
|
|
1848
2813
|
}
|
|
2814
|
+
/** Hermes/RN polyfills don't always populate signal.reason; fall back. */
|
|
2815
|
+
_abortReason(signal) {
|
|
2816
|
+
return signal.reason ?? this._lastCancelReason ?? new Error("Aborted");
|
|
2817
|
+
}
|
|
1849
2818
|
/**
|
|
1850
2819
|
* Race a promise against an abort signal. On abort, rejects with
|
|
1851
2820
|
* signal.reason → instance _lastCancelReason → generic Error('Aborted').
|
|
1852
2821
|
*/
|
|
1853
2822
|
_abortable(signal, promise) {
|
|
1854
|
-
const getAbortReason = () =>
|
|
2823
|
+
const getAbortReason = () => this._abortReason(signal);
|
|
1855
2824
|
if (signal.aborted) {
|
|
2825
|
+
void promise.catch(() => void 0);
|
|
1856
2826
|
return Promise.reject(getAbortReason());
|
|
1857
2827
|
}
|
|
1858
2828
|
return new Promise((resolve, reject) => {
|
|
@@ -1879,39 +2849,89 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1879
2849
|
}
|
|
1880
2850
|
}
|
|
1881
2851
|
/** Actual work done under the job queue — connection, fingerprint, call, and recovery. */
|
|
1882
|
-
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext) {
|
|
2852
|
+
async _runConnectorCall(connectId, method, params, signal, fingerprint, permissionDeviceId, commonParams, installContext, operationId, lockedRetryBudget = _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET) {
|
|
1883
2853
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1884
|
-
|
|
1885
|
-
|
|
1886
|
-
|
|
1887
|
-
|
|
1888
|
-
|
|
2854
|
+
if (!operationId) {
|
|
2855
|
+
await this._ensureDevicePermission(
|
|
2856
|
+
connectId,
|
|
2857
|
+
permissionDeviceId ?? fingerprint?.deviceId,
|
|
2858
|
+
signal
|
|
2859
|
+
);
|
|
2860
|
+
}
|
|
1889
2861
|
_LedgerAdapter._throwIfAborted(signal);
|
|
1890
2862
|
let effectiveParams = params;
|
|
1891
2863
|
if (method === "btcGetPublicKey") {
|
|
1892
|
-
const gatedParams = await this._gateBtcHighIndex(params);
|
|
2864
|
+
const gatedParams = await this._gateBtcHighIndex(params, signal);
|
|
1893
2865
|
if (gatedParams === null) {
|
|
1894
2866
|
throw Object.assign(new Error("User cancelled BTC high-index confirmation"), {
|
|
1895
2867
|
_tag: ERROR_TAG.UserAborted,
|
|
1896
|
-
code:
|
|
2868
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted
|
|
1897
2869
|
});
|
|
1898
2870
|
}
|
|
1899
2871
|
effectiveParams = gatedParams;
|
|
1900
2872
|
}
|
|
1901
2873
|
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
1902
|
-
|
|
1903
|
-
|
|
2874
|
+
let businessCallStarted = false;
|
|
2875
|
+
const selectedBleTarget = connectId ? this._selectedBleReconnectTargets.get(connectId) : void 0;
|
|
2876
|
+
const knownTransport = this._isBleConnection() ? "ble" : "usb";
|
|
2877
|
+
const hintedConnectId = commonParams?.knownConnections?.find(
|
|
2878
|
+
(connection) => connection.transport === knownTransport
|
|
2879
|
+
);
|
|
2880
|
+
const inputConnectId = hintedConnectId && hintedConnectId.transport !== "qr" ? hintedConnectId.connectId : connectId;
|
|
2881
|
+
const preferredConnectId = fingerprint && !fingerprint.skipFingerprint && selectedBleTarget?.chain === fingerprint.chain && selectedBleTarget.fingerprint === fingerprint.deviceId ? selectedBleTarget.connectId : inputConnectId;
|
|
2882
|
+
const checksWallet = Boolean(
|
|
2883
|
+
fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId
|
|
2884
|
+
);
|
|
2885
|
+
const connectionAttempt = {
|
|
2886
|
+
...commonParams,
|
|
2887
|
+
deferBindingSave: checksWallet
|
|
2888
|
+
};
|
|
2889
|
+
const bundleConnection = installContext?.connection;
|
|
2890
|
+
if (bundleConnection && this._sessions.get(bundleConnection.connectId) !== bundleConnection.sessionId) {
|
|
2891
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2892
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
2893
|
+
message: "Ledger all-network connection ended"
|
|
2894
|
+
});
|
|
2895
|
+
}
|
|
2896
|
+
const resolvedConnectId = operationId ? this._operations.resolve(operationId).connectId : bundleConnection?.connectId ?? await this.ensureConnected(
|
|
2897
|
+
preferredConnectId,
|
|
1904
2898
|
signal,
|
|
1905
|
-
allowUsbEphemeralFallback
|
|
2899
|
+
allowUsbEphemeralFallback,
|
|
2900
|
+
void 0,
|
|
2901
|
+
connectionAttempt
|
|
1906
2902
|
);
|
|
2903
|
+
const walletCheck = installContext?.walletCheck;
|
|
2904
|
+
if (walletCheck && !checksWallet && (walletCheck.verified === false || walletCheck.expected && !walletCheck.verified)) {
|
|
2905
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2906
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch,
|
|
2907
|
+
message: "Ledger wallet is not verified on this connection; refusing to derive an unverifiable address"
|
|
2908
|
+
});
|
|
2909
|
+
}
|
|
1907
2910
|
const sessionId = this._sessions.get(resolvedConnectId);
|
|
2911
|
+
if (sessionId && installContext && !installContext.connection) {
|
|
2912
|
+
installContext.connection = { connectId: resolvedConnectId, sessionId };
|
|
2913
|
+
}
|
|
1908
2914
|
if (!sessionId) {
|
|
2915
|
+
if (operationId) {
|
|
2916
|
+
this._operations.end(operationId, "disconnect");
|
|
2917
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
2918
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.OperationEnded,
|
|
2919
|
+
message: "Ledger operation connection is no longer active",
|
|
2920
|
+
params: { operationId, reason: "disconnect" }
|
|
2921
|
+
});
|
|
2922
|
+
}
|
|
1909
2923
|
throw Object.assign(new Error("Auto-connect succeeded but no session found"), {
|
|
1910
2924
|
_tag: ERROR_TAG.DeviceSessionNotFound
|
|
1911
2925
|
});
|
|
1912
2926
|
}
|
|
1913
2927
|
try {
|
|
1914
|
-
|
|
2928
|
+
const isBleSession = this._sessionTransports.get(sessionId) === "ble";
|
|
2929
|
+
if (!operationId && connectionAttempt.pendingBinding) {
|
|
2930
|
+
this._pendingPickBindings.set(resolvedConnectId, connectionAttempt);
|
|
2931
|
+
}
|
|
2932
|
+
const bindingOwner = operationId ? this._pendingOperationBindings.get(operationId) : this._pendingPickBindings.get(resolvedConnectId);
|
|
2933
|
+
const pendingBinding = bindingOwner?.pendingBinding?.connectId === resolvedConnectId ? bindingOwner.pendingBinding : void 0;
|
|
2934
|
+
if (fingerprint && checksWallet) {
|
|
1915
2935
|
const fp = await this._abortable(
|
|
1916
2936
|
signal,
|
|
1917
2937
|
this._verifyDeviceFingerprintWithSession(
|
|
@@ -1921,14 +2941,68 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1921
2941
|
)
|
|
1922
2942
|
);
|
|
1923
2943
|
if (!fp.success) {
|
|
2944
|
+
if (pendingBinding) {
|
|
2945
|
+
this._discardPendingBinding(bindingOwner, "failed");
|
|
2946
|
+
this._pendingPickBindings.delete(resolvedConnectId);
|
|
2947
|
+
}
|
|
2948
|
+
if (operationId) {
|
|
2949
|
+
this._pendingOperationBindings.delete(operationId);
|
|
2950
|
+
this._operations.end(operationId, "explicit");
|
|
2951
|
+
await this._dropSession(resolvedConnectId, signal);
|
|
2952
|
+
}
|
|
1924
2953
|
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
1925
|
-
code:
|
|
2954
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch
|
|
1926
2955
|
});
|
|
1927
2956
|
}
|
|
2957
|
+
if (walletCheck) walletCheck.verified = true;
|
|
1928
2958
|
}
|
|
1929
|
-
|
|
2959
|
+
if (pendingBinding && bindingOwner) {
|
|
2960
|
+
bindingOwner.pendingBinding = void 0;
|
|
2961
|
+
if (operationId) this._pendingOperationBindings.delete(operationId);
|
|
2962
|
+
else this._pendingPickBindings.delete(resolvedConnectId);
|
|
2963
|
+
await this._saveSelectedBleBinding(
|
|
2964
|
+
pendingBinding.connectId,
|
|
2965
|
+
pendingBinding.requestId,
|
|
2966
|
+
bindingOwner,
|
|
2967
|
+
operationId,
|
|
2968
|
+
signal,
|
|
2969
|
+
fingerprint && checksWallet ? {
|
|
2970
|
+
vendor: "ledger",
|
|
2971
|
+
type: "chainFingerprint",
|
|
2972
|
+
chain: fingerprint.chain,
|
|
2973
|
+
value: fingerprint.deviceId
|
|
2974
|
+
} : void 0
|
|
2975
|
+
);
|
|
2976
|
+
}
|
|
2977
|
+
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId && !operationId && isBleSession && connectionAttempt.selectedConnection?.connectId === resolvedConnectId) {
|
|
2978
|
+
this._selectedBleReconnectTargets.set(connectId, {
|
|
2979
|
+
connectId: resolvedConnectId,
|
|
2980
|
+
chain: fingerprint.chain,
|
|
2981
|
+
fingerprint: fingerprint.deviceId
|
|
2982
|
+
});
|
|
2983
|
+
}
|
|
2984
|
+
businessCallStarted = true;
|
|
2985
|
+
const result = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
2986
|
+
if (walletCheck) walletCheck.derived = true;
|
|
2987
|
+
return result;
|
|
1930
2988
|
} catch (err) {
|
|
1931
2989
|
if (signal.aborted) throw err;
|
|
2990
|
+
if (isLostConnectionError(err)) {
|
|
2991
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
2992
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
2993
|
+
else {
|
|
2994
|
+
this._sessions.delete(resolvedConnectId);
|
|
2995
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
2996
|
+
}
|
|
2997
|
+
const ambiguous = businessCallStarted && !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
2998
|
+
const interactionParams = operationId ? { operationId, reason: "disconnect" } : void 0;
|
|
2999
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3000
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(err).code,
|
|
3001
|
+
message: "Ledger operation connection was lost; start a new operation",
|
|
3002
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId }) : interactionParams,
|
|
3003
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3004
|
+
});
|
|
3005
|
+
}
|
|
1932
3006
|
const errObj = err;
|
|
1933
3007
|
debugLog("[LedgerAdapter] connectorCall error:", method, {
|
|
1934
3008
|
message: errObj?.message,
|
|
@@ -1940,8 +3014,66 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1940
3014
|
isNotAdvertising: isDeviceNotAdvertisingError(err),
|
|
1941
3015
|
isStuckApp: isStuckAppStateError(err)
|
|
1942
3016
|
});
|
|
3017
|
+
const assertSessionCurrent = (message) => {
|
|
3018
|
+
if (this._sessions.get(resolvedConnectId) === sessionId) return;
|
|
3019
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3020
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : import_hwk_adapter_core4.HardwareErrorCode.DeviceDisconnected,
|
|
3021
|
+
message
|
|
3022
|
+
});
|
|
3023
|
+
};
|
|
3024
|
+
if ((isDeviceLockedError(err) || errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceLocked) && lockedRetryBudget > 0) {
|
|
3025
|
+
await this._waitForDeviceConnect(signal);
|
|
3026
|
+
assertSessionCurrent("Ledger connection ended while waiting for unlock");
|
|
3027
|
+
if (walletCheck?.derived) walletCheck.verified = false;
|
|
3028
|
+
return this._runConnectorCall(
|
|
3029
|
+
resolvedConnectId,
|
|
3030
|
+
method,
|
|
3031
|
+
effectiveParams,
|
|
3032
|
+
signal,
|
|
3033
|
+
fingerprint,
|
|
3034
|
+
permissionDeviceId,
|
|
3035
|
+
commonParams,
|
|
3036
|
+
installContext,
|
|
3037
|
+
operationId,
|
|
3038
|
+
lockedRetryBudget - 1
|
|
3039
|
+
);
|
|
3040
|
+
}
|
|
3041
|
+
if (businessCallStarted && isStuckAppStateError(err)) {
|
|
3042
|
+
await this._sleepAbortable(_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS, signal);
|
|
3043
|
+
assertSessionCurrent("Ledger connection ended during the app transition");
|
|
3044
|
+
try {
|
|
3045
|
+
const retried = await this._callConnector(sessionId, method, effectiveParams, signal);
|
|
3046
|
+
if (walletCheck) walletCheck.derived = true;
|
|
3047
|
+
return retried;
|
|
3048
|
+
} catch (retryErr) {
|
|
3049
|
+
if (isStuckAppStateError(retryErr)) throw err;
|
|
3050
|
+
if (isLostConnectionError(retryErr)) {
|
|
3051
|
+
if (operationId) await this._releaseLostOperationConnection(operationId);
|
|
3052
|
+
else {
|
|
3053
|
+
this._sessions.delete(resolvedConnectId);
|
|
3054
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3055
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3056
|
+
}
|
|
3057
|
+
const ambiguous = !(0, import_hwk_adapter_core4.canReplayHardwareMethodAfterTransportFailure)(method);
|
|
3058
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3059
|
+
code: operationId ? import_hwk_adapter_core4.HardwareErrorCode.OperationEnded : mapLedgerError(retryErr).code,
|
|
3060
|
+
message: `Ledger ${method} may have completed before the connection was lost`,
|
|
3061
|
+
params: ambiguous ? (0, import_hwk_adapter_core4.operationMayHaveCompletedParams)(method, { operationId, reason: "disconnect" }) : { operationId, reason: "disconnect" },
|
|
3062
|
+
recovery: ambiguous ? { scope: "unknown" } : void 0
|
|
3063
|
+
});
|
|
3064
|
+
}
|
|
3065
|
+
throw retryErr;
|
|
3066
|
+
}
|
|
3067
|
+
}
|
|
3068
|
+
if (!operationId && errObj?.code === import_hwk_adapter_core4.HardwareErrorCode.DeviceMismatch) {
|
|
3069
|
+
this._sessions.delete(resolvedConnectId);
|
|
3070
|
+
this._sessionTransports.delete(sessionId);
|
|
3071
|
+
this._discoveredDevices.delete(resolvedConnectId);
|
|
3072
|
+
await this.connector.disconnect(sessionId).catch(() => void 0);
|
|
3073
|
+
throw err;
|
|
3074
|
+
}
|
|
1943
3075
|
const autoInstallApp = commonParams?.autoInstallApp ?? this._defaultAutoInstallApp;
|
|
1944
|
-
const isAppMissing = isAppNotInstalledError(err) || err?.code ===
|
|
3076
|
+
const isAppMissing = isAppNotInstalledError(err) || err?.code === import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled;
|
|
1945
3077
|
if (autoInstallApp && isAppMissing) {
|
|
1946
3078
|
if (installContext?.deviceOutOfMemoryError) {
|
|
1947
3079
|
throw installContext.deviceOutOfMemoryError;
|
|
@@ -1949,30 +3081,30 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1949
3081
|
const appName = err?.appName ?? mapLedgerError(err).appName;
|
|
1950
3082
|
if (appName) {
|
|
1951
3083
|
if (installContext?.installAttemptedAppNames?.has(appName)) {
|
|
1952
|
-
throw (0,
|
|
1953
|
-
code:
|
|
3084
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3085
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.AppNotInstalled,
|
|
1954
3086
|
message: `${appName} install reported success but the app is still missing on device`,
|
|
1955
3087
|
_tag: ERROR_TAG.AppInstallVerifyFailed,
|
|
1956
3088
|
appName
|
|
1957
3089
|
});
|
|
1958
3090
|
}
|
|
1959
|
-
const confirmed = await this._waitForInstallAppConfirm(appName);
|
|
3091
|
+
const confirmed = await this._waitForInstallAppConfirm(appName, signal);
|
|
1960
3092
|
if (!confirmed) {
|
|
1961
|
-
throw (0,
|
|
1962
|
-
code:
|
|
3093
|
+
throw (0, import_hwk_adapter_core4.createHwkError)({
|
|
3094
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
1963
3095
|
message: `User declined to install ${appName}`,
|
|
1964
3096
|
_tag: ERROR_TAG.UserAborted,
|
|
1965
3097
|
appName
|
|
1966
3098
|
});
|
|
1967
3099
|
}
|
|
1968
3100
|
this.emitter.emit("ui-event", {
|
|
1969
|
-
type:
|
|
3101
|
+
type: import_hwk_adapter_core4.EConnectorInteraction.AppInstallProgress,
|
|
1970
3102
|
payload: { connectId: resolvedConnectId, appName, progress: 0 }
|
|
1971
3103
|
});
|
|
1972
3104
|
try {
|
|
1973
3105
|
await this._callConnector(sessionId, "installApp", { appName }, signal);
|
|
1974
3106
|
} catch (installErr) {
|
|
1975
|
-
if (mapLedgerError(installErr).code ===
|
|
3107
|
+
if (mapLedgerError(installErr).code === import_hwk_adapter_core4.HardwareErrorCode.DeviceOutOfMemory) {
|
|
1976
3108
|
if (installContext) {
|
|
1977
3109
|
installContext.deviceOutOfMemoryError = installErr;
|
|
1978
3110
|
}
|
|
@@ -1983,8 +3115,8 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1983
3115
|
installContext.installAttemptedAppNames = installContext.installAttemptedAppNames ?? /* @__PURE__ */ new Set();
|
|
1984
3116
|
installContext.installAttemptedAppNames.add(appName);
|
|
1985
3117
|
}
|
|
1986
|
-
this.emitter.emit(
|
|
1987
|
-
type:
|
|
3118
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3119
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
1988
3120
|
payload: {}
|
|
1989
3121
|
});
|
|
1990
3122
|
return await this._runConnectorCall(
|
|
@@ -1995,157 +3127,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
1995
3127
|
fingerprint,
|
|
1996
3128
|
permissionDeviceId,
|
|
1997
3129
|
commonParams,
|
|
1998
|
-
installContext
|
|
3130
|
+
installContext,
|
|
3131
|
+
operationId
|
|
1999
3132
|
);
|
|
2000
3133
|
}
|
|
2001
3134
|
}
|
|
2002
|
-
if (isStuckAppStateError(err)) {
|
|
2003
|
-
try {
|
|
2004
|
-
this._sessions.delete(resolvedConnectId);
|
|
2005
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2006
|
-
this.connector.reset?.();
|
|
2007
|
-
} catch {
|
|
2008
|
-
}
|
|
2009
|
-
debugLog(
|
|
2010
|
-
"[LedgerAdapter] stuck-app retry: method=",
|
|
2011
|
-
method,
|
|
2012
|
-
"delayMs=",
|
|
2013
|
-
_LedgerAdapter.STUCK_APP_RETRY_DELAY_MS,
|
|
2014
|
-
"_tag=",
|
|
2015
|
-
err?._tag
|
|
2016
|
-
);
|
|
2017
|
-
try {
|
|
2018
|
-
const retryResult = await this._retryAfterStuckApp(
|
|
2019
|
-
resolvedConnectId,
|
|
2020
|
-
method,
|
|
2021
|
-
effectiveParams,
|
|
2022
|
-
signal,
|
|
2023
|
-
err,
|
|
2024
|
-
fingerprint
|
|
2025
|
-
);
|
|
2026
|
-
debugLog("[LedgerAdapter] stuck-app retry succeeded: method=", method);
|
|
2027
|
-
return retryResult;
|
|
2028
|
-
} catch (retryErr) {
|
|
2029
|
-
if (signal.aborted) throw retryErr;
|
|
2030
|
-
if (isStuckAppStateError(retryErr)) {
|
|
2031
|
-
debugLog("[LedgerAdapter] stuck-app retry exhausted (2nd 6901): method=", method);
|
|
2032
|
-
throw err;
|
|
2033
|
-
}
|
|
2034
|
-
debugLog(
|
|
2035
|
-
"[LedgerAdapter] stuck-app retry threw non-stuck error: method=",
|
|
2036
|
-
method,
|
|
2037
|
-
"retryErrTag=",
|
|
2038
|
-
retryErr?._tag
|
|
2039
|
-
);
|
|
2040
|
-
throw retryErr;
|
|
2041
|
-
}
|
|
2042
|
-
}
|
|
2043
|
-
if (isDeviceLockedError(err) || isDeviceNotAdvertisingError(err) || isDeviceDisconnectedError(err)) {
|
|
2044
|
-
let lastErr = err;
|
|
2045
|
-
for (let attempt = 0; attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET; attempt += 1) {
|
|
2046
|
-
if (signal.aborted) throw lastErr;
|
|
2047
|
-
try {
|
|
2048
|
-
this._sessions.delete(resolvedConnectId);
|
|
2049
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2050
|
-
if (isDeviceDisconnectedError(lastErr)) {
|
|
2051
|
-
try {
|
|
2052
|
-
this.connector.reset?.();
|
|
2053
|
-
} catch {
|
|
2054
|
-
}
|
|
2055
|
-
}
|
|
2056
|
-
const reConnectId = await this.ensureConnected(
|
|
2057
|
-
resolvedConnectId,
|
|
2058
|
-
signal,
|
|
2059
|
-
allowUsbEphemeralFallback
|
|
2060
|
-
);
|
|
2061
|
-
const reSessionId = this._sessions.get(reConnectId);
|
|
2062
|
-
if (!reSessionId) throw lastErr;
|
|
2063
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2064
|
-
const fp = await this._abortable(
|
|
2065
|
-
signal,
|
|
2066
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2067
|
-
reSessionId,
|
|
2068
|
-
fingerprint.deviceId,
|
|
2069
|
-
fingerprint.chain
|
|
2070
|
-
)
|
|
2071
|
-
);
|
|
2072
|
-
if (!fp.success) {
|
|
2073
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2074
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2075
|
-
});
|
|
2076
|
-
}
|
|
2077
|
-
}
|
|
2078
|
-
return await this._callConnector(reSessionId, method, effectiveParams, signal);
|
|
2079
|
-
} catch (retryErr) {
|
|
2080
|
-
if (signal.aborted) throw retryErr;
|
|
2081
|
-
lastErr = retryErr;
|
|
2082
|
-
const canRetry = attempt < _LedgerAdapter.MAX_BUSINESS_RETRY_BUDGET - 1 && (isDeviceLockedError(retryErr) || isDeviceNotAdvertisingError(retryErr) || isDeviceDisconnectedError(retryErr));
|
|
2083
|
-
if (!canRetry) {
|
|
2084
|
-
throw retryErr;
|
|
2085
|
-
}
|
|
2086
|
-
}
|
|
2087
|
-
}
|
|
2088
|
-
throw lastErr;
|
|
2089
|
-
}
|
|
2090
|
-
if (isTimeoutError(err)) {
|
|
2091
|
-
debugLog("[LedgerAdapter] timeout, retrying with fresh connection...");
|
|
2092
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2093
|
-
return this._retryWithFreshConnection(
|
|
2094
|
-
resolvedConnectId,
|
|
2095
|
-
method,
|
|
2096
|
-
effectiveParams,
|
|
2097
|
-
signal,
|
|
2098
|
-
err,
|
|
2099
|
-
fingerprint
|
|
2100
|
-
);
|
|
2101
|
-
}
|
|
2102
|
-
if (isConnectionLevelError(err)) {
|
|
2103
|
-
debugLog("[LedgerAdapter] connection-level fail-closed reset");
|
|
2104
|
-
this._sessions.delete(resolvedConnectId);
|
|
2105
|
-
this._discoveredDevices.delete(resolvedConnectId);
|
|
2106
|
-
this.connector.reset();
|
|
2107
|
-
const codeNum = err?.code;
|
|
2108
|
-
throw Object.assign(err, {
|
|
2109
|
-
code: codeNum ?? import_hwk_adapter_core3.HardwareErrorCode.DeviceDisconnected
|
|
2110
|
-
});
|
|
2111
|
-
}
|
|
2112
3135
|
throw err;
|
|
2113
3136
|
}
|
|
2114
3137
|
}
|
|
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
3138
|
_sleepAbortable(ms, signal) {
|
|
2150
3139
|
return new Promise((resolve, reject) => {
|
|
2151
3140
|
if (signal.aborted) {
|
|
@@ -2164,115 +3153,26 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2164
3153
|
});
|
|
2165
3154
|
}
|
|
2166
3155
|
/**
|
|
2167
|
-
*
|
|
2168
|
-
*
|
|
2169
|
-
* Timeout recovery starts with a full connector reset. After an APDU
|
|
2170
|
-
* timeout, DMK/transport state may still emit malformed responses; retrying
|
|
2171
|
-
* on the same DMK can poison the next chain switch.
|
|
2172
|
-
*/
|
|
2173
|
-
async _retryWithFreshConnection(targetConnectId, method, params, signal, originalErr, fingerprint) {
|
|
2174
|
-
this.connector.reset();
|
|
2175
|
-
this._sessions.clear();
|
|
2176
|
-
this._discoveredDevices.clear();
|
|
2177
|
-
this._connectingPromise = null;
|
|
2178
|
-
const allowUsbEphemeralFallback = !!fingerprint?.deviceId && !fingerprint.skipFingerprint;
|
|
2179
|
-
const retryConnectId = await this.ensureConnected(
|
|
2180
|
-
targetConnectId,
|
|
2181
|
-
signal,
|
|
2182
|
-
allowUsbEphemeralFallback
|
|
2183
|
-
);
|
|
2184
|
-
const retrySessionId = this._sessions.get(retryConnectId);
|
|
2185
|
-
if (!retrySessionId) {
|
|
2186
|
-
throw originalErr;
|
|
2187
|
-
}
|
|
2188
|
-
try {
|
|
2189
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2190
|
-
const fp = await this._abortable(
|
|
2191
|
-
signal,
|
|
2192
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2193
|
-
retrySessionId,
|
|
2194
|
-
fingerprint.deviceId,
|
|
2195
|
-
fingerprint.chain
|
|
2196
|
-
)
|
|
2197
|
-
);
|
|
2198
|
-
if (!fp.success) {
|
|
2199
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2200
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2201
|
-
});
|
|
2202
|
-
}
|
|
2203
|
-
}
|
|
2204
|
-
return await this._callConnector(retrySessionId, method, params, signal);
|
|
2205
|
-
} catch (retryErr) {
|
|
2206
|
-
if (signal.aborted) throw retryErr;
|
|
2207
|
-
this.connector.reset();
|
|
2208
|
-
this._sessions.clear();
|
|
2209
|
-
this._discoveredDevices.clear();
|
|
2210
|
-
this._connectingPromise = null;
|
|
2211
|
-
if (!isDeviceDisconnectedError(retryErr) && !isTimeoutError(retryErr)) {
|
|
2212
|
-
throw retryErr;
|
|
2213
|
-
}
|
|
2214
|
-
debugLog(
|
|
2215
|
-
"[LedgerAdapter] fresh-session retry still failed; resetting connector and rebuilding DMK"
|
|
2216
|
-
);
|
|
2217
|
-
this.connector.reset();
|
|
2218
|
-
this._sessions.clear();
|
|
2219
|
-
this._discoveredDevices.clear();
|
|
2220
|
-
this._connectingPromise = null;
|
|
2221
|
-
const finalConnectId = await this.ensureConnected(
|
|
2222
|
-
targetConnectId,
|
|
2223
|
-
signal,
|
|
2224
|
-
allowUsbEphemeralFallback
|
|
2225
|
-
);
|
|
2226
|
-
const finalSessionId = this._sessions.get(finalConnectId);
|
|
2227
|
-
if (!finalSessionId) {
|
|
2228
|
-
throw originalErr;
|
|
2229
|
-
}
|
|
2230
|
-
if (fingerprint && !fingerprint.skipFingerprint && fingerprint.deviceId) {
|
|
2231
|
-
const fp = await this._abortable(
|
|
2232
|
-
signal,
|
|
2233
|
-
this._verifyDeviceFingerprintWithSession(
|
|
2234
|
-
finalSessionId,
|
|
2235
|
-
fingerprint.deviceId,
|
|
2236
|
-
fingerprint.chain
|
|
2237
|
-
)
|
|
2238
|
-
);
|
|
2239
|
-
if (!fp.success) {
|
|
2240
|
-
throw Object.assign(new Error(formatDeviceMismatchError(fp.expected, fp.actual)), {
|
|
2241
|
-
code: import_hwk_adapter_core3.HardwareErrorCode.DeviceMismatch
|
|
2242
|
-
});
|
|
2243
|
-
}
|
|
2244
|
-
}
|
|
2245
|
-
return this._callConnector(finalSessionId, method, params, signal);
|
|
2246
|
-
}
|
|
2247
|
-
}
|
|
2248
|
-
/**
|
|
2249
|
-
* Ensure OS-level device permission (Bluetooth / USB) before proceeding.
|
|
2250
|
-
*
|
|
2251
|
-
* Emits `REQUEST_DEVICE_PERMISSION` and awaits the consumer's
|
|
2252
|
-
* `RECEIVE_DEVICE_PERMISSION` reply (60s budget covers "probe → system
|
|
2253
|
-
* prompt → user tap" plus a generous margin). If the consumer never wires
|
|
2254
|
-
* a handler or never replies, the wait times out and the operation fails
|
|
2255
|
-
* fast so scanners/callers don't hang silently.
|
|
2256
|
-
*
|
|
2257
|
-
* - No connectId (searchDevices): environment-level permission
|
|
2258
|
-
* - With connectId (business methods): device-level permission
|
|
3156
|
+
* Ensure OS-level Bluetooth/USB permission; times out after 60s if the host never
|
|
3157
|
+
* replies. Without connectId the request is environment-level, else device-level.
|
|
2259
3158
|
*/
|
|
2260
3159
|
async _ensureDevicePermission(connectId, deviceId, signal) {
|
|
2261
3160
|
if (signal?.aborted) {
|
|
2262
3161
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2263
3162
|
}
|
|
2264
3163
|
const transportType = this.activeTransport ?? "hid";
|
|
3164
|
+
const operationId = this._activeOperationId();
|
|
2265
3165
|
const waitPromise = this._uiRegistry.wait(
|
|
2266
|
-
|
|
2267
|
-
{ timeoutMs: 6e4 }
|
|
3166
|
+
import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3167
|
+
{ timeoutMs: 6e4, operationId }
|
|
2268
3168
|
);
|
|
2269
|
-
this.emitter.emit(
|
|
2270
|
-
type:
|
|
2271
|
-
payload: { transportType, connectId, deviceId }
|
|
3169
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION, {
|
|
3170
|
+
type: import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION,
|
|
3171
|
+
payload: { transportType, connectId, deviceId, operationId }
|
|
2272
3172
|
});
|
|
2273
3173
|
let response;
|
|
2274
3174
|
const onAbort = () => {
|
|
2275
|
-
this._uiRegistry.cancel(
|
|
3175
|
+
this._uiRegistry.cancel(import_hwk_adapter_core4.UI_REQUEST.REQUEST_DEVICE_PERMISSION);
|
|
2276
3176
|
};
|
|
2277
3177
|
try {
|
|
2278
3178
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -2281,14 +3181,14 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2281
3181
|
if (signal?.aborted) {
|
|
2282
3182
|
_LedgerAdapter._throwIfAborted(signal);
|
|
2283
3183
|
}
|
|
2284
|
-
if (err?._tag ===
|
|
2285
|
-
this.emitter.emit(
|
|
2286
|
-
type:
|
|
3184
|
+
if (err?._tag === import_hwk_adapter_core4.UI_REQUEST_PREEMPTED_TAG) {
|
|
3185
|
+
this.emitter.emit(import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW, {
|
|
3186
|
+
type: import_hwk_adapter_core4.UI_REQUEST.CLOSE_UI_WINDOW,
|
|
2287
3187
|
payload: {}
|
|
2288
3188
|
});
|
|
2289
3189
|
throw Object.assign(new Error("Device permission request superseded"), {
|
|
2290
3190
|
_tag: ERROR_TAG.UserAborted,
|
|
2291
|
-
code:
|
|
3191
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.UserAborted,
|
|
2292
3192
|
cause: err
|
|
2293
3193
|
});
|
|
2294
3194
|
}
|
|
@@ -2299,7 +3199,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2299
3199
|
const { granted, reason, message } = response;
|
|
2300
3200
|
if (!granted) {
|
|
2301
3201
|
throw Object.assign(new Error(message ?? "Device permission denied"), {
|
|
2302
|
-
code:
|
|
3202
|
+
code: import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied,
|
|
2303
3203
|
reason
|
|
2304
3204
|
});
|
|
2305
3205
|
}
|
|
@@ -2313,8 +3213,16 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2313
3213
|
const tag = err && typeof err === "object" ? err._tag : void 0;
|
|
2314
3214
|
if (err && typeof err === "object" && "code" in err && typeof err.code === "number") {
|
|
2315
3215
|
const e = err;
|
|
2316
|
-
const params = e.code ===
|
|
2317
|
-
return ledgerFailure(
|
|
3216
|
+
const params = e.code === import_hwk_adapter_core4.HardwareErrorCode.DevicePermissionDenied && e.reason ? { permissionDeniedReason: e.reason } : e.params;
|
|
3217
|
+
return ledgerFailure(
|
|
3218
|
+
e.code,
|
|
3219
|
+
e.message ?? "Unknown error",
|
|
3220
|
+
e.appName,
|
|
3221
|
+
tag,
|
|
3222
|
+
params,
|
|
3223
|
+
void 0,
|
|
3224
|
+
(0, import_hwk_adapter_core4.isHwkRecoveryHint)(e.recovery) ? e.recovery : void 0
|
|
3225
|
+
);
|
|
2318
3226
|
}
|
|
2319
3227
|
const mapped = mapLedgerError(err);
|
|
2320
3228
|
return ledgerFailure(mapped.code, mapped.message, mapped.appName, tag);
|
|
@@ -2341,7 +3249,7 @@ var _LedgerAdapter = class _LedgerAdapter {
|
|
|
2341
3249
|
deviceId: device.deviceId,
|
|
2342
3250
|
connectId: device.connectId,
|
|
2343
3251
|
label: device.name,
|
|
2344
|
-
connectionType: this.connector.connectionType,
|
|
3252
|
+
connectionType: device.connectionType ?? this.connector.connectionType,
|
|
2345
3253
|
rssi: device.rssi,
|
|
2346
3254
|
isConnectable: device.isConnectable,
|
|
2347
3255
|
serialNumber: device.serialNumber,
|
|
@@ -2639,11 +3547,12 @@ var import_device_signer_kit_ethereum = require("@ledgerhq/device-signer-kit-eth
|
|
|
2639
3547
|
var import_context_module = require("@ledgerhq/context-module");
|
|
2640
3548
|
|
|
2641
3549
|
// src/signer/SignerEth.ts
|
|
2642
|
-
var
|
|
3550
|
+
var import_hwk_adapter_core5 = require("@onekeyfe/hwk-adapter-core");
|
|
2643
3551
|
|
|
2644
3552
|
// src/signer/deviceActionToPromise.ts
|
|
2645
3553
|
var import_device_management_kit = require("@ledgerhq/device-management-kit");
|
|
2646
3554
|
var IDLE_WATCHDOG_MS = 65e3;
|
|
3555
|
+
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2647
3556
|
function deviceActionToPromise(action, onInteraction, timeoutMs = IDLE_WATCHDOG_MS, onRegisterCanceller, onIntermediate) {
|
|
2648
3557
|
return new Promise((resolve, reject) => {
|
|
2649
3558
|
let settled = false;
|
|
@@ -2831,7 +3740,6 @@ function rejectWithStepContext(err, lastStep, observedSteps, reject) {
|
|
|
2831
3740
|
}
|
|
2832
3741
|
|
|
2833
3742
|
// src/signer/SignerEth.ts
|
|
2834
|
-
var INTERACTIVE_TIMEOUT_MS = 5 * 6e4;
|
|
2835
3743
|
var SignerEth = class {
|
|
2836
3744
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
2837
3745
|
constructor(_sdk) {
|
|
@@ -2852,7 +3760,7 @@ var SignerEth = class {
|
|
|
2852
3760
|
);
|
|
2853
3761
|
}
|
|
2854
3762
|
async signTransaction(derivationPath, serializedTxHex) {
|
|
2855
|
-
const action = this._sdk.signTransaction(derivationPath, (0,
|
|
3763
|
+
const action = this._sdk.signTransaction(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(serializedTxHex));
|
|
2856
3764
|
return deviceActionToPromise(
|
|
2857
3765
|
action,
|
|
2858
3766
|
this.onInteraction,
|
|
@@ -2861,7 +3769,7 @@ var SignerEth = class {
|
|
|
2861
3769
|
);
|
|
2862
3770
|
}
|
|
2863
3771
|
async signMessage(derivationPath, message) {
|
|
2864
|
-
const action = this._sdk.signMessage(derivationPath, (0,
|
|
3772
|
+
const action = this._sdk.signMessage(derivationPath, (0, import_hwk_adapter_core5.hexToBytes)(message));
|
|
2865
3773
|
return deviceActionToPromise(
|
|
2866
3774
|
action,
|
|
2867
3775
|
this.onInteraction,
|
|
@@ -2902,7 +3810,7 @@ var SignerManager = class _SignerManager {
|
|
|
2902
3810
|
return (args) => new import_device_signer_kit_ethereum.SignerEthBuilder(args);
|
|
2903
3811
|
}
|
|
2904
3812
|
static _createContextModule() {
|
|
2905
|
-
const contextModule = new import_context_module.ContextModuleBuilder({}).removeDefaultLoaders().build();
|
|
3813
|
+
const contextModule = new import_context_module.ContextModuleBuilder({}).setChain(import_context_module.ContextModuleChainID.Ethereum).removeDefaultLoaders().build();
|
|
2906
3814
|
return _SignerManager.wrapBlindSigningReportNonBlocking(contextModule);
|
|
2907
3815
|
}
|
|
2908
3816
|
static wrapBlindSigningReportNonBlocking(contextModule) {
|
|
@@ -2921,23 +3829,44 @@ var SignerManager = class _SignerManager {
|
|
|
2921
3829
|
};
|
|
2922
3830
|
|
|
2923
3831
|
// src/connector/chains/evm.ts
|
|
2924
|
-
var
|
|
3832
|
+
var import_hwk_adapter_core7 = require("@onekeyfe/hwk-adapter-core");
|
|
2925
3833
|
|
|
2926
3834
|
// src/connector/chains/utils.ts
|
|
2927
|
-
var
|
|
3835
|
+
var import_hwk_adapter_core6 = require("@onekeyfe/hwk-adapter-core");
|
|
2928
3836
|
function normalizePath(path) {
|
|
2929
3837
|
return path.startsWith("m/") ? path.slice(2) : path;
|
|
2930
3838
|
}
|
|
2931
3839
|
function collapseSignerInteraction(interaction) {
|
|
2932
3840
|
switch (interaction) {
|
|
2933
3841
|
case "confirm-open-app":
|
|
2934
|
-
return
|
|
3842
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOpenApp;
|
|
2935
3843
|
case "unlock-device":
|
|
2936
|
-
return
|
|
3844
|
+
return import_hwk_adapter_core6.EConnectorInteraction.UnlockDevice;
|
|
2937
3845
|
case "interaction-complete":
|
|
2938
|
-
return
|
|
3846
|
+
return import_hwk_adapter_core6.EConnectorInteraction.InteractionComplete;
|
|
2939
3847
|
default:
|
|
2940
|
-
return
|
|
3848
|
+
return import_hwk_adapter_core6.EConnectorInteraction.ConfirmOnDevice;
|
|
3849
|
+
}
|
|
3850
|
+
}
|
|
3851
|
+
function wireSignerToSession(ctx, sessionId, chain, signer) {
|
|
3852
|
+
signer.onInteraction = (interaction) => {
|
|
3853
|
+
debugLog(`[LedgerConnector] ${chain}.onInteraction:`, interaction);
|
|
3854
|
+
ctx.emit("ui-event", {
|
|
3855
|
+
type: collapseSignerInteraction(interaction),
|
|
3856
|
+
payload: { sessionId }
|
|
3857
|
+
});
|
|
3858
|
+
};
|
|
3859
|
+
signer.onRegisterCanceller = (cancel) => ctx.registerCanceller(sessionId, cancel);
|
|
3860
|
+
return signer;
|
|
3861
|
+
}
|
|
3862
|
+
async function runSignerCall(ctx, sessionId, call) {
|
|
3863
|
+
try {
|
|
3864
|
+
return await call();
|
|
3865
|
+
} catch (err) {
|
|
3866
|
+
ctx.invalidateSession(sessionId);
|
|
3867
|
+
throw ctx.wrapError(err);
|
|
3868
|
+
} finally {
|
|
3869
|
+
ctx.clearCanceller(sessionId);
|
|
2941
3870
|
}
|
|
2942
3871
|
}
|
|
2943
3872
|
|
|
@@ -2963,7 +3892,7 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2963
3892
|
new Error(
|
|
2964
3893
|
"Ledger requires a pre-serialized transaction (serializedTx). Provide an RLP-encoded hex string."
|
|
2965
3894
|
),
|
|
2966
|
-
{ code:
|
|
3895
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.InvalidParams }
|
|
2967
3896
|
);
|
|
2968
3897
|
}
|
|
2969
3898
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
@@ -2972,8 +3901,8 @@ async function evmSignTransaction(ctx, sessionId, params) {
|
|
|
2972
3901
|
const result = await signer.signTransaction(path, params.serializedTx);
|
|
2973
3902
|
return {
|
|
2974
3903
|
v: `0x${result.v.toString(16)}`,
|
|
2975
|
-
r: (0,
|
|
2976
|
-
s: (0,
|
|
3904
|
+
r: (0, import_hwk_adapter_core7.padHex64)(result.r),
|
|
3905
|
+
s: (0, import_hwk_adapter_core7.padHex64)(result.s)
|
|
2977
3906
|
};
|
|
2978
3907
|
} catch (err) {
|
|
2979
3908
|
ctx.invalidateSession(sessionId);
|
|
@@ -2987,8 +3916,8 @@ async function evmSignMessage(ctx, sessionId, params) {
|
|
|
2987
3916
|
const path = normalizePath(params.path);
|
|
2988
3917
|
try {
|
|
2989
3918
|
const result = await signer.signMessage(path, params.message);
|
|
2990
|
-
const rHex = (0,
|
|
2991
|
-
const sHex = (0,
|
|
3919
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3920
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
2992
3921
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
2993
3922
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
2994
3923
|
} catch (err) {
|
|
@@ -3004,15 +3933,15 @@ async function evmSignTypedData(ctx, sessionId, params) {
|
|
|
3004
3933
|
new Error(
|
|
3005
3934
|
'Ledger does not support hash-only EIP-712 signing. Use mode "full" with the complete typed data structure.'
|
|
3006
3935
|
),
|
|
3007
|
-
{ code:
|
|
3936
|
+
{ code: import_hwk_adapter_core7.HardwareErrorCode.MethodNotSupported }
|
|
3008
3937
|
);
|
|
3009
3938
|
}
|
|
3010
3939
|
const signer = await _getEthSigner(ctx, sessionId);
|
|
3011
3940
|
const path = normalizePath(params.path);
|
|
3012
3941
|
try {
|
|
3013
3942
|
const result = await signer.signTypedData(path, params.data);
|
|
3014
|
-
const rHex = (0,
|
|
3015
|
-
const sHex = (0,
|
|
3943
|
+
const rHex = (0, import_hwk_adapter_core7.stripHex)(result.r).padStart(64, "0");
|
|
3944
|
+
const sHex = (0, import_hwk_adapter_core7.stripHex)(result.s).padStart(64, "0");
|
|
3016
3945
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3017
3946
|
return { signature: `0x${rHex}${sHex}${vHex}` };
|
|
3018
3947
|
} catch (err) {
|
|
@@ -3039,15 +3968,14 @@ async function _getEthSigner(ctx, sessionId) {
|
|
|
3039
3968
|
}
|
|
3040
3969
|
|
|
3041
3970
|
// src/connector/chains/btc.ts
|
|
3042
|
-
var
|
|
3043
|
-
var
|
|
3971
|
+
var import_hwk_adapter_core9 = require("@onekeyfe/hwk-adapter-core");
|
|
3972
|
+
var import_bitcoinjs_lib2 = require("bitcoinjs-lib");
|
|
3044
3973
|
|
|
3045
3974
|
// src/signer/SignerBtc.ts
|
|
3046
|
-
var
|
|
3975
|
+
var import_hwk_adapter_core8 = require("@onekeyfe/hwk-adapter-core");
|
|
3047
3976
|
function hexToUtf8(hex) {
|
|
3048
|
-
return new TextDecoder().decode((0,
|
|
3977
|
+
return new TextDecoder().decode((0, import_hwk_adapter_core8.hexToBytes)(hex));
|
|
3049
3978
|
}
|
|
3050
|
-
var INTERACTIVE_TIMEOUT_MS2 = 5 * 6e4;
|
|
3051
3979
|
var SignerBtc = class {
|
|
3052
3980
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
3053
3981
|
constructor(_sdk) {
|
|
@@ -3061,7 +3989,7 @@ var SignerBtc = class {
|
|
|
3061
3989
|
return deviceActionToPromise(
|
|
3062
3990
|
action,
|
|
3063
3991
|
this.onInteraction,
|
|
3064
|
-
void 0,
|
|
3992
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3065
3993
|
this.onRegisterCanceller
|
|
3066
3994
|
);
|
|
3067
3995
|
}
|
|
@@ -3079,14 +4007,14 @@ var SignerBtc = class {
|
|
|
3079
4007
|
const result = await deviceActionToPromise(
|
|
3080
4008
|
action,
|
|
3081
4009
|
this.onInteraction,
|
|
3082
|
-
void 0,
|
|
4010
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3083
4011
|
this.onRegisterCanceller
|
|
3084
4012
|
);
|
|
3085
4013
|
debugLog(
|
|
3086
4014
|
"[SignerBtc] getExtendedPublicKey result type:",
|
|
3087
4015
|
typeof result,
|
|
3088
4016
|
"value:",
|
|
3089
|
-
|
|
4017
|
+
summarizeForLog(result)
|
|
3090
4018
|
);
|
|
3091
4019
|
if (typeof result === "string") return result;
|
|
3092
4020
|
return result.extendedPublicKey;
|
|
@@ -3115,7 +4043,7 @@ var SignerBtc = class {
|
|
|
3115
4043
|
return deviceActionToPromise(
|
|
3116
4044
|
action,
|
|
3117
4045
|
this.onInteraction,
|
|
3118
|
-
|
|
4046
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3119
4047
|
this.onRegisterCanceller
|
|
3120
4048
|
);
|
|
3121
4049
|
}
|
|
@@ -3128,7 +4056,7 @@ var SignerBtc = class {
|
|
|
3128
4056
|
return deviceActionToPromise(
|
|
3129
4057
|
action,
|
|
3130
4058
|
this.onInteraction,
|
|
3131
|
-
|
|
4059
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3132
4060
|
this.onRegisterCanceller
|
|
3133
4061
|
);
|
|
3134
4062
|
}
|
|
@@ -3141,7 +4069,7 @@ var SignerBtc = class {
|
|
|
3141
4069
|
return deviceActionToPromise(
|
|
3142
4070
|
action,
|
|
3143
4071
|
this.onInteraction,
|
|
3144
|
-
|
|
4072
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3145
4073
|
this.onRegisterCanceller
|
|
3146
4074
|
);
|
|
3147
4075
|
}
|
|
@@ -3160,11 +4088,25 @@ function _purposeToTemplate(purpose, DDT) {
|
|
|
3160
4088
|
return DDT.TAPROOT;
|
|
3161
4089
|
default:
|
|
3162
4090
|
throw Object.assign(new Error(`Unsupported BTC purpose: m/${purpose ?? "<undefined>"}'`), {
|
|
3163
|
-
code:
|
|
4091
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3164
4092
|
});
|
|
3165
4093
|
}
|
|
3166
4094
|
}
|
|
4095
|
+
function assertBitcoinMainnet(coin) {
|
|
4096
|
+
if (coin !== void 0 && !["btc", "bitcoin"].includes(coin.toLowerCase())) {
|
|
4097
|
+
throw Object.assign(new Error(`Ledger BTC supports Bitcoin mainnet only, not ${coin}`), {
|
|
4098
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.ChainNotSupported
|
|
4099
|
+
});
|
|
4100
|
+
}
|
|
4101
|
+
}
|
|
3167
4102
|
async function btcGetAddress(ctx, sessionId, params) {
|
|
4103
|
+
assertBitcoinMainnet(params.coin);
|
|
4104
|
+
if (normalizePath(params.path).split("/").length !== 3) {
|
|
4105
|
+
throw Object.assign(
|
|
4106
|
+
new Error("Ledger btcGetAddress takes an account path (e.g. m/84'/0'/0') plus addressIndex"),
|
|
4107
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
4108
|
+
);
|
|
4109
|
+
}
|
|
3168
4110
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3169
4111
|
const path = normalizePath(params.path);
|
|
3170
4112
|
try {
|
|
@@ -3195,6 +4137,7 @@ async function btcGetAddress(ctx, sessionId, params) {
|
|
|
3195
4137
|
}
|
|
3196
4138
|
}
|
|
3197
4139
|
async function btcGetPublicKey(ctx, sessionId, params) {
|
|
4140
|
+
assertBitcoinMainnet(params.coin);
|
|
3198
4141
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
3199
4142
|
const path = normalizePath(params.path);
|
|
3200
4143
|
debugLog("[LedgerConnector] btcGetPublicKey called, path:", path, "sessionId:", sessionId);
|
|
@@ -3202,7 +4145,7 @@ async function btcGetPublicKey(ctx, sessionId, params) {
|
|
|
3202
4145
|
const xpub = await btcSigner.getExtendedPublicKey(path, {
|
|
3203
4146
|
checkOnDevice: params.showOnDevice ?? false
|
|
3204
4147
|
});
|
|
3205
|
-
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:",
|
|
4148
|
+
debugLog("[LedgerConnector] btcGetPublicKey success, xpub:", summarizeForLog(xpub));
|
|
3206
4149
|
return { xpub, path: params.path };
|
|
3207
4150
|
} catch (err) {
|
|
3208
4151
|
debugError("[LedgerConnector] btcGetPublicKey error, path:", path, "err:", err);
|
|
@@ -3216,7 +4159,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3216
4159
|
if (!params.psbt) {
|
|
3217
4160
|
throw Object.assign(
|
|
3218
4161
|
new Error("Ledger requires PSBT format for BTC transaction signing. Provide params.psbt."),
|
|
3219
|
-
{ code:
|
|
4162
|
+
{ code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams }
|
|
3220
4163
|
);
|
|
3221
4164
|
}
|
|
3222
4165
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3230,7 +4173,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3230
4173
|
debugLog("[LedgerConnector] btcSignTransaction wallet:", { path, purpose, template });
|
|
3231
4174
|
const wallet = new DefaultWallet(path, template);
|
|
3232
4175
|
const signedTxHex = await btcSigner.signTransaction(wallet, params.psbt);
|
|
3233
|
-
return { serializedTx: (0,
|
|
4176
|
+
return { serializedTx: (0, import_hwk_adapter_core9.stripHex)(signedTxHex) };
|
|
3234
4177
|
} catch (err) {
|
|
3235
4178
|
ctx.invalidateSession(sessionId);
|
|
3236
4179
|
throw ctx.wrapError(err);
|
|
@@ -3241,7 +4184,7 @@ async function btcSignTransaction(ctx, sessionId, params) {
|
|
|
3241
4184
|
async function btcSignPsbt(ctx, sessionId, params) {
|
|
3242
4185
|
if (!params.psbt) {
|
|
3243
4186
|
throw Object.assign(new Error("btcSignPsbt requires params.psbt"), {
|
|
3244
|
-
code:
|
|
4187
|
+
code: import_hwk_adapter_core9.HardwareErrorCode.InvalidParams
|
|
3245
4188
|
});
|
|
3246
4189
|
}
|
|
3247
4190
|
const btcSigner = await _createBtcSigner(ctx, sessionId);
|
|
@@ -3271,8 +4214,8 @@ async function btcSignMessage(ctx, sessionId, params) {
|
|
|
3271
4214
|
try {
|
|
3272
4215
|
const result = await btcSigner.signMessage(path, params.message);
|
|
3273
4216
|
const vHex = result.v.toString(16).padStart(2, "0");
|
|
3274
|
-
const rHex = (0,
|
|
3275
|
-
const sHex = (0,
|
|
4217
|
+
const rHex = (0, import_hwk_adapter_core9.stripHex)(result.r).padStart(64, "0");
|
|
4218
|
+
const sHex = (0, import_hwk_adapter_core9.stripHex)(result.s).padStart(64, "0");
|
|
3276
4219
|
return { signature: `${vHex}${rHex}${sHex}` };
|
|
3277
4220
|
} catch (err) {
|
|
3278
4221
|
ctx.invalidateSession(sessionId);
|
|
@@ -3323,7 +4266,7 @@ function _isScriptPathInput(input) {
|
|
|
3323
4266
|
return !!(input.tapLeafScript && input.tapLeafScript.length > 0);
|
|
3324
4267
|
}
|
|
3325
4268
|
function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
3326
|
-
const psbt =
|
|
4269
|
+
const psbt = import_bitcoinjs_lib2.Psbt.fromHex(psbtHex);
|
|
3327
4270
|
for (const sig of signatures) {
|
|
3328
4271
|
const input = psbt.data.inputs[sig.inputIndex];
|
|
3329
4272
|
if (!input) {
|
|
@@ -3372,7 +4315,8 @@ function _applySignaturesToPsbt(psbtHex, signatures) {
|
|
|
3372
4315
|
}
|
|
3373
4316
|
|
|
3374
4317
|
// src/connector/chains/sol.ts
|
|
3375
|
-
var
|
|
4318
|
+
var import_hwk_adapter_core10 = require("@onekeyfe/hwk-adapter-core");
|
|
4319
|
+
var import_bs58 = __toESM(require("bs58"));
|
|
3376
4320
|
|
|
3377
4321
|
// src/signer/SignerSol.ts
|
|
3378
4322
|
var SignerSol = class {
|
|
@@ -3390,7 +4334,7 @@ var SignerSol = class {
|
|
|
3390
4334
|
return deviceActionToPromise(
|
|
3391
4335
|
action,
|
|
3392
4336
|
this.onInteraction,
|
|
3393
|
-
void 0,
|
|
4337
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
3394
4338
|
this.onRegisterCanceller
|
|
3395
4339
|
);
|
|
3396
4340
|
}
|
|
@@ -3402,7 +4346,7 @@ var SignerSol = class {
|
|
|
3402
4346
|
return deviceActionToPromise(
|
|
3403
4347
|
action,
|
|
3404
4348
|
this.onInteraction,
|
|
3405
|
-
|
|
4349
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3406
4350
|
this.onRegisterCanceller
|
|
3407
4351
|
);
|
|
3408
4352
|
}
|
|
@@ -3415,7 +4359,7 @@ var SignerSol = class {
|
|
|
3415
4359
|
return deviceActionToPromise(
|
|
3416
4360
|
action,
|
|
3417
4361
|
this.onInteraction,
|
|
3418
|
-
|
|
4362
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
3419
4363
|
this.onRegisterCanceller
|
|
3420
4364
|
);
|
|
3421
4365
|
}
|
|
@@ -3440,10 +4384,10 @@ async function solGetAddress(ctx, sessionId, params) {
|
|
|
3440
4384
|
async function solSignTransaction(ctx, sessionId, params) {
|
|
3441
4385
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3442
4386
|
const path = normalizePath(params.path);
|
|
3443
|
-
const txBytes = (0,
|
|
4387
|
+
const txBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.serializedTx);
|
|
3444
4388
|
try {
|
|
3445
4389
|
const result = await solSigner.signTransaction(path, txBytes);
|
|
3446
|
-
return { signature: (0,
|
|
4390
|
+
return { signature: (0, import_hwk_adapter_core10.bytesToHex)(result) };
|
|
3447
4391
|
} catch (err) {
|
|
3448
4392
|
ctx.invalidateSession(sessionId);
|
|
3449
4393
|
throw ctx.wrapError(err);
|
|
@@ -3454,10 +4398,23 @@ async function solSignTransaction(ctx, sessionId, params) {
|
|
|
3454
4398
|
async function solSignMessage(ctx, sessionId, params) {
|
|
3455
4399
|
const solSigner = await _createSolSigner(ctx, sessionId);
|
|
3456
4400
|
const path = normalizePath(params.path);
|
|
3457
|
-
const messageBytes = (0,
|
|
4401
|
+
const messageBytes = (0, import_hwk_adapter_core10.hexToBytes)(params.message);
|
|
3458
4402
|
try {
|
|
4403
|
+
if (params.messageVersion === 1) {
|
|
4404
|
+
const preparedMessage = (0, import_hwk_adapter_core10.prepareSolanaOffchainMessageV1)({
|
|
4405
|
+
message: messageBytes,
|
|
4406
|
+
requiredSigners: params.requiredSigners
|
|
4407
|
+
});
|
|
4408
|
+
const { SignMessageVersion } = await ctx.importLedgerKit(
|
|
4409
|
+
"@ledgerhq/device-signer-kit-solana"
|
|
4410
|
+
);
|
|
4411
|
+
const result2 = await solSigner.signMessage(path, preparedMessage.serializedMessage, {
|
|
4412
|
+
version: SignMessageVersion.Raw
|
|
4413
|
+
});
|
|
4414
|
+
return { signature: decodeBase58Signature(result2.signature) };
|
|
4415
|
+
}
|
|
3459
4416
|
const result = await solSigner.signMessage(path, messageBytes);
|
|
3460
|
-
return { signature: result.signature };
|
|
4417
|
+
return { signature: decodeBase58EnvelopeSignature(result.signature) };
|
|
3461
4418
|
} catch (err) {
|
|
3462
4419
|
ctx.invalidateSession(sessionId);
|
|
3463
4420
|
throw ctx.wrapError(err);
|
|
@@ -3465,11 +4422,27 @@ async function solSignMessage(ctx, sessionId, params) {
|
|
|
3465
4422
|
ctx.clearCanceller(sessionId);
|
|
3466
4423
|
}
|
|
3467
4424
|
}
|
|
4425
|
+
function decodeBase58Signature(signature) {
|
|
4426
|
+
const bytes = import_bs58.default.decode(signature);
|
|
4427
|
+
if (bytes.length !== 64) {
|
|
4428
|
+
throw new Error(`Ledger Solana signature must be 64 bytes, received ${bytes.length}`);
|
|
4429
|
+
}
|
|
4430
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes);
|
|
4431
|
+
}
|
|
4432
|
+
function decodeBase58EnvelopeSignature(envelope) {
|
|
4433
|
+
const bytes = import_bs58.default.decode(envelope);
|
|
4434
|
+
if (bytes.length < 65 || bytes[0] !== 1) {
|
|
4435
|
+
throw new Error("Ledger Solana signature envelope is invalid");
|
|
4436
|
+
}
|
|
4437
|
+
return (0, import_hwk_adapter_core10.bytesToHex)(bytes.subarray(1, 65));
|
|
4438
|
+
}
|
|
3468
4439
|
async function _createSolSigner(ctx, sessionId) {
|
|
3469
4440
|
const dmk = await ctx.getOrCreateDmk();
|
|
3470
|
-
const { ContextModuleBuilder: ContextModuleBuilder2 } = await ctx.importLedgerKit(
|
|
4441
|
+
const { ContextModuleBuilder: ContextModuleBuilder2, ContextModuleChainID: ContextModuleChainID2 } = await ctx.importLedgerKit(
|
|
4442
|
+
"@ledgerhq/context-module"
|
|
4443
|
+
);
|
|
3471
4444
|
const { SignerSolanaBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-solana");
|
|
3472
|
-
const contextModule = new ContextModuleBuilder2({}).removeDefaultLoaders().build();
|
|
4445
|
+
const contextModule = new ContextModuleBuilder2({}).setChain(ContextModuleChainID2.Solana).removeDefaultLoaders().build();
|
|
3473
4446
|
const sdkSigner = new SignerSolanaBuilder({ dmk, sessionId }).withContextModule(contextModule).build();
|
|
3474
4447
|
const signer = new SignerSol(sdkSigner);
|
|
3475
4448
|
signer.onInteraction = (interaction) => {
|
|
@@ -3485,316 +4458,119 @@ async function _createSolSigner(ctx, sessionId) {
|
|
|
3485
4458
|
return signer;
|
|
3486
4459
|
}
|
|
3487
4460
|
|
|
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
|
|
4461
|
+
// src/connector/chains/zcash.ts
|
|
3493
4462
|
var import_hwk_adapter_core11 = require("@onekeyfe/hwk-adapter-core");
|
|
3494
4463
|
|
|
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);
|
|
4464
|
+
// src/signer/SignerZcash.ts
|
|
4465
|
+
var SignerZcash = class {
|
|
4466
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4467
|
+
constructor(_sdk) {
|
|
4468
|
+
this._sdk = _sdk;
|
|
3556
4469
|
}
|
|
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
|
-
}
|
|
4470
|
+
/** GET_VK: UFVK string (default) or raw 96-byte Orchard FVK. */
|
|
4471
|
+
async getFullViewingKey(derivationPath, options) {
|
|
4472
|
+
const action = this._sdk.getFullViewingKey(derivationPath, options);
|
|
4473
|
+
return deviceActionToPromise(
|
|
4474
|
+
action,
|
|
4475
|
+
this.onInteraction,
|
|
4476
|
+
void 0,
|
|
4477
|
+
this.onRegisterCanceller
|
|
3593
4478
|
);
|
|
3594
4479
|
}
|
|
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})`
|
|
4480
|
+
/** GET_SHIELDED_ADDRESS: single-Orchard-receiver UA for a 5-level transparent path. */
|
|
4481
|
+
async getShieldedAddress(derivationPath, options) {
|
|
4482
|
+
const action = this._sdk.getShieldedAddress(derivationPath, options);
|
|
4483
|
+
return deviceActionToPromise(
|
|
4484
|
+
action,
|
|
4485
|
+
this.onInteraction,
|
|
4486
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4487
|
+
this.onRegisterCanceller
|
|
3657
4488
|
);
|
|
3658
4489
|
}
|
|
3659
|
-
_isDashboard(appName) {
|
|
3660
|
-
return appName === DASHBOARD_APP_NAME;
|
|
3661
|
-
}
|
|
3662
|
-
_wait() {
|
|
3663
|
-
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
3664
|
-
}
|
|
3665
4490
|
};
|
|
3666
4491
|
|
|
3667
|
-
// src/connector/chains/
|
|
3668
|
-
function
|
|
3669
|
-
|
|
4492
|
+
// src/connector/chains/zcash.ts
|
|
4493
|
+
async function zcashGetFullViewingKey(ctx, sessionId, params) {
|
|
4494
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4495
|
+
const path = normalizePath(params.path);
|
|
4496
|
+
const mode = params.mode ?? "ufvk";
|
|
4497
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4498
|
+
const result = await signer.getFullViewingKey(path, { mode });
|
|
4499
|
+
if (result.mode === "ufvk") {
|
|
4500
|
+
return { path: params.path, mode, ufvk: result.fullViewingKey };
|
|
4501
|
+
}
|
|
4502
|
+
return { path: params.path, mode, orchardFvk: (0, import_hwk_adapter_core11.bytesToHex)(result.fullViewingKey) };
|
|
4503
|
+
});
|
|
3670
4504
|
}
|
|
3671
|
-
async function
|
|
3672
|
-
const
|
|
3673
|
-
|
|
3674
|
-
|
|
3675
|
-
|
|
3676
|
-
|
|
3677
|
-
type: import_hwk_adapter_core11.EConnectorInteraction.ConfirmOpenApp,
|
|
3678
|
-
payload: { sessionId }
|
|
4505
|
+
async function zcashGetShieldedAddress(ctx, sessionId, params) {
|
|
4506
|
+
const signer = await _createZcashSigner(ctx, sessionId);
|
|
4507
|
+
const path = normalizePath(params.path);
|
|
4508
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4509
|
+
const result = await signer.getShieldedAddress(path, {
|
|
4510
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
3679
4511
|
});
|
|
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
|
-
}
|
|
4512
|
+
return { address: result.address, path: params.path };
|
|
4513
|
+
});
|
|
3747
4514
|
}
|
|
3748
|
-
async function
|
|
4515
|
+
async function _createZcashSigner(ctx, sessionId) {
|
|
3749
4516
|
const dmk = await ctx.getOrCreateDmk();
|
|
3750
|
-
const
|
|
3751
|
-
|
|
4517
|
+
const { SignerZcashBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-zcash");
|
|
4518
|
+
const sdkSigner = new SignerZcashBuilder({ dmk, sessionId }).build();
|
|
4519
|
+
return wireSignerToSession(ctx, sessionId, "zcash", new SignerZcash(sdkSigner));
|
|
3752
4520
|
}
|
|
3753
4521
|
|
|
3754
|
-
// src/
|
|
3755
|
-
var
|
|
3756
|
-
|
|
3757
|
-
|
|
3758
|
-
|
|
3759
|
-
|
|
3760
|
-
|
|
4522
|
+
// src/connector/chains/tron.ts
|
|
4523
|
+
var import_hwk_adapter_core12 = require("@onekeyfe/hwk-adapter-core");
|
|
4524
|
+
|
|
4525
|
+
// src/signer/SignerTron.ts
|
|
4526
|
+
var SignerTron = class {
|
|
4527
|
+
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
4528
|
+
constructor(_sdk) {
|
|
4529
|
+
this._sdk = _sdk;
|
|
3761
4530
|
}
|
|
3762
|
-
|
|
3763
|
-
|
|
3764
|
-
|
|
3765
|
-
|
|
3766
|
-
|
|
3767
|
-
|
|
3768
|
-
|
|
3769
|
-
|
|
3770
|
-
|
|
3771
|
-
}
|
|
3772
|
-
result.set(statusCode, data.length);
|
|
3773
|
-
return result;
|
|
4531
|
+
/** Base58 Tron address plus the uncompressed public key at `derivationPath`. */
|
|
4532
|
+
async getAddress(derivationPath, options) {
|
|
4533
|
+
const action = this._sdk.getAddress(derivationPath, options);
|
|
4534
|
+
const result = await deviceActionToPromise(
|
|
4535
|
+
action,
|
|
4536
|
+
this.onInteraction,
|
|
4537
|
+
options?.checkOnDevice ? INTERACTIVE_TIMEOUT_MS : void 0,
|
|
4538
|
+
this.onRegisterCanceller
|
|
4539
|
+
);
|
|
4540
|
+
return { address: result.address, publicKey: result.publicKey };
|
|
3774
4541
|
}
|
|
3775
|
-
|
|
4542
|
+
/** Sign a protobuf-encoded raw transaction. */
|
|
4543
|
+
async signTransaction(derivationPath, transaction, options) {
|
|
4544
|
+
const action = this._sdk.signTransaction(derivationPath, transaction, options);
|
|
4545
|
+
return deviceActionToPromise(
|
|
4546
|
+
action,
|
|
4547
|
+
this.onInteraction,
|
|
4548
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4549
|
+
this.onRegisterCanceller
|
|
4550
|
+
);
|
|
4551
|
+
}
|
|
4552
|
+
/** Sign a personal message (TIP-191). */
|
|
4553
|
+
async signPersonalMessage(derivationPath, message, options) {
|
|
4554
|
+
const action = this._sdk.signPersonalMessage(derivationPath, message, options);
|
|
4555
|
+
return deviceActionToPromise(
|
|
4556
|
+
action,
|
|
4557
|
+
this.onInteraction,
|
|
4558
|
+
INTERACTIVE_TIMEOUT_MS,
|
|
4559
|
+
this.onRegisterCanceller
|
|
4560
|
+
);
|
|
3776
4561
|
}
|
|
3777
4562
|
};
|
|
3778
4563
|
|
|
3779
4564
|
// src/connector/chains/tron.ts
|
|
3780
4565
|
async function tronGetAddress(ctx, sessionId, params) {
|
|
4566
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3781
4567
|
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
|
-
);
|
|
4568
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4569
|
+
const result = await tronSigner.getAddress(path, {
|
|
4570
|
+
checkOnDevice: params.showOnDevice ?? false
|
|
4571
|
+
});
|
|
4572
|
+
return { address: result.address, publicKey: result.publicKey, path: params.path };
|
|
4573
|
+
});
|
|
3798
4574
|
}
|
|
3799
4575
|
async function tronSignTransaction(ctx, sessionId, params) {
|
|
3800
4576
|
if (!params.rawTxHex) {
|
|
@@ -3803,42 +4579,30 @@ async function tronSignTransaction(ctx, sessionId, params) {
|
|
|
3803
4579
|
{ code: import_hwk_adapter_core12.HardwareErrorCode.InvalidParams }
|
|
3804
4580
|
);
|
|
3805
4581
|
}
|
|
4582
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3806
4583
|
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
|
-
);
|
|
4584
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4585
|
+
const signature = await tronSigner.signTransaction(path, (0, import_hwk_adapter_core12.hexToBytes)(params.rawTxHex));
|
|
4586
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4587
|
+
});
|
|
3821
4588
|
}
|
|
3822
4589
|
async function tronSignMessage(ctx, sessionId, params) {
|
|
4590
|
+
const tronSigner = await _createTronSigner(ctx, sessionId);
|
|
3823
4591
|
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
|
-
);
|
|
4592
|
+
return runSignerCall(ctx, sessionId, async () => {
|
|
4593
|
+
const signature = await tronSigner.signPersonalMessage(path, (0, import_hwk_adapter_core12.hexToBytes)(params.messageHex));
|
|
4594
|
+
return { signature: (0, import_hwk_adapter_core12.bytesToHex)(signature) };
|
|
4595
|
+
});
|
|
3834
4596
|
}
|
|
3835
|
-
async function
|
|
4597
|
+
async function _createTronSigner(ctx, sessionId) {
|
|
3836
4598
|
const dmk = await ctx.getOrCreateDmk();
|
|
3837
|
-
|
|
4599
|
+
const { SignerTrxBuilder } = await ctx.importLedgerKit("@ledgerhq/device-signer-kit-tron");
|
|
4600
|
+
const sdkSigner = new SignerTrxBuilder({ dmk, sessionId }).build();
|
|
4601
|
+
return wireSignerToSession(ctx, sessionId, "tron", new SignerTron(sdkSigner));
|
|
3838
4602
|
}
|
|
3839
4603
|
|
|
3840
4604
|
// src/device-apps/customActions.ts
|
|
3841
|
-
var
|
|
4605
|
+
var import_device_management_kit2 = require("@ledgerhq/device-management-kit");
|
|
3842
4606
|
var import_rxjs = require("rxjs");
|
|
3843
4607
|
var GetOsVersionDeviceAction = class {
|
|
3844
4608
|
// eslint-disable-next-line no-useless-constructor, no-empty-function
|
|
@@ -3852,7 +4616,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3852
4616
|
(async () => {
|
|
3853
4617
|
try {
|
|
3854
4618
|
subject.next({
|
|
3855
|
-
status:
|
|
4619
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3856
4620
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3857
4621
|
});
|
|
3858
4622
|
const result = await internalApi.sendCommand(new this._deps.GetOsVersionCommand());
|
|
@@ -3861,11 +4625,11 @@ var GetOsVersionDeviceAction = class {
|
|
|
3861
4625
|
const errObj = result?.error;
|
|
3862
4626
|
throw new Error(errObj?.message ?? "GetOsVersionCommand failed");
|
|
3863
4627
|
}
|
|
3864
|
-
subject.next({ status:
|
|
4628
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: result.data });
|
|
3865
4629
|
subject.complete();
|
|
3866
4630
|
} catch (err) {
|
|
3867
4631
|
if (cancelled) return;
|
|
3868
|
-
subject.next({ status:
|
|
4632
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3869
4633
|
subject.complete();
|
|
3870
4634
|
}
|
|
3871
4635
|
})();
|
|
@@ -3873,7 +4637,7 @@ var GetOsVersionDeviceAction = class {
|
|
|
3873
4637
|
observable: subject.asObservable(),
|
|
3874
4638
|
cancel: () => {
|
|
3875
4639
|
cancelled = true;
|
|
3876
|
-
subject.next({ status:
|
|
4640
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3877
4641
|
subject.complete();
|
|
3878
4642
|
}
|
|
3879
4643
|
};
|
|
@@ -3891,7 +4655,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3891
4655
|
(async () => {
|
|
3892
4656
|
try {
|
|
3893
4657
|
subject.next({
|
|
3894
|
-
status:
|
|
4658
|
+
status: import_device_management_kit2.DeviceActionStatus.Pending,
|
|
3895
4659
|
intermediateValue: { requiredUserInteraction: "none" }
|
|
3896
4660
|
});
|
|
3897
4661
|
const osVersionResult = await internalApi.sendCommand(new this._GetOsVersionCommand());
|
|
@@ -3908,11 +4672,11 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3908
4672
|
throw new Error(httpErr?.message ?? "Manager API getAppList failed");
|
|
3909
4673
|
}
|
|
3910
4674
|
const apps = either.extract();
|
|
3911
|
-
subject.next({ status:
|
|
4675
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Completed, output: apps });
|
|
3912
4676
|
subject.complete();
|
|
3913
4677
|
} catch (err) {
|
|
3914
4678
|
if (cancelled) return;
|
|
3915
|
-
subject.next({ status:
|
|
4679
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Error, error: err });
|
|
3916
4680
|
subject.complete();
|
|
3917
4681
|
}
|
|
3918
4682
|
})();
|
|
@@ -3920,7 +4684,7 @@ var ListAvailableAppsDeviceAction = class {
|
|
|
3920
4684
|
observable: subject.asObservable(),
|
|
3921
4685
|
cancel: () => {
|
|
3922
4686
|
cancelled = true;
|
|
3923
|
-
subject.next({ status:
|
|
4687
|
+
subject.next({ status: import_device_management_kit2.DeviceActionStatus.Stopped });
|
|
3924
4688
|
subject.complete();
|
|
3925
4689
|
}
|
|
3926
4690
|
};
|
|
@@ -4013,7 +4777,7 @@ var DeviceApps = class {
|
|
|
4013
4777
|
seTargetId: v.seTargetId,
|
|
4014
4778
|
mcuTargetId: v.mcuTargetId,
|
|
4015
4779
|
seVersion: v.seVersion,
|
|
4016
|
-
seFlagsHex:
|
|
4780
|
+
seFlagsHex: bytesToHex4(v.seFlags),
|
|
4017
4781
|
mcuSephVersion: v.mcuSephVersion,
|
|
4018
4782
|
mcuBootloaderVersion: v.mcuBootloaderVersion,
|
|
4019
4783
|
hwVersion: v.hwVersion
|
|
@@ -4087,7 +4851,7 @@ var DeviceApps = class {
|
|
|
4087
4851
|
}
|
|
4088
4852
|
}
|
|
4089
4853
|
};
|
|
4090
|
-
function
|
|
4854
|
+
function bytesToHex4(bytes) {
|
|
4091
4855
|
if (!bytes) return "";
|
|
4092
4856
|
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
4093
4857
|
}
|
|
@@ -4130,7 +4894,8 @@ var METHOD_PREFIX_TO_APP_NAME = {
|
|
|
4130
4894
|
evm: "Ethereum",
|
|
4131
4895
|
btc: "Bitcoin",
|
|
4132
4896
|
sol: "Solana",
|
|
4133
|
-
tron: "Tron"
|
|
4897
|
+
tron: "Tron",
|
|
4898
|
+
zcash: "Zcash"
|
|
4134
4899
|
};
|
|
4135
4900
|
var HARDWARE_ERROR_CODE_VALUES = new Set(
|
|
4136
4901
|
Object.values(import_hwk_adapter_core13.HardwareErrorCode).filter((value) => typeof value === "number")
|
|
@@ -4170,6 +4935,10 @@ async function defaultLedgerKitImporter(pkg) {
|
|
|
4170
4935
|
return import("@ledgerhq/device-signer-kit-bitcoin");
|
|
4171
4936
|
case "@ledgerhq/device-signer-kit-solana":
|
|
4172
4937
|
return import("@ledgerhq/device-signer-kit-solana");
|
|
4938
|
+
case "@ledgerhq/device-signer-kit-tron":
|
|
4939
|
+
return import("@ledgerhq/device-signer-kit-tron");
|
|
4940
|
+
case "@ledgerhq/device-signer-kit-zcash":
|
|
4941
|
+
return import("@ledgerhq/device-signer-kit-zcash");
|
|
4173
4942
|
case "@ledgerhq/context-module":
|
|
4174
4943
|
return import("@ledgerhq/context-module");
|
|
4175
4944
|
default:
|
|
@@ -4229,6 +4998,7 @@ var LedgerConnectorBase = class {
|
|
|
4229
4998
|
this._ctx = {
|
|
4230
4999
|
emit: (event, data) => this._emit(event, data),
|
|
4231
5000
|
invalidateSession: (sid) => this._invalidateSession(sid),
|
|
5001
|
+
teardownSecureChannelSession: (sid) => this._teardownSecureChannelSession(sid),
|
|
4232
5002
|
wrapError: (err, opts) => this._wrapError(err, opts),
|
|
4233
5003
|
getOrCreateDmk: () => this._getOrCreateDmk(),
|
|
4234
5004
|
getDeviceManager: () => this._getDeviceManager(),
|
|
@@ -4418,7 +5188,7 @@ var LedgerConnectorBase = class {
|
|
|
4418
5188
|
this._resetSignersAndSessions();
|
|
4419
5189
|
if (isLedgerBleConnectionType(this.connectionType)) {
|
|
4420
5190
|
const tag = err?._tag;
|
|
4421
|
-
if (isKnownConnectionTag(tag)) {
|
|
5191
|
+
if (isKnownConnectionTag(tag) && !isConnectionOpeningTag(tag)) {
|
|
4422
5192
|
throw err;
|
|
4423
5193
|
}
|
|
4424
5194
|
const wrapped = new Error(
|
|
@@ -4519,7 +5289,7 @@ var LedgerConnectorBase = class {
|
|
|
4519
5289
|
// whitelist (`toPlainError`). The SW-side adapter rehydrates and re-throws
|
|
4520
5290
|
// locally (see LedgerAdapter._unwrapConnectorResult).
|
|
4521
5291
|
async call(sessionId, method, params) {
|
|
4522
|
-
debugLog("[DMK] call:", method, JSON.stringify(params));
|
|
5292
|
+
debugLog("[DMK] call:", method, JSON.stringify(summarizeForLog(params, { method })));
|
|
4523
5293
|
try {
|
|
4524
5294
|
const payload = await this._dispatch(sessionId, method, params);
|
|
4525
5295
|
return { success: true, payload };
|
|
@@ -4587,6 +5357,11 @@ var LedgerConnectorBase = class {
|
|
|
4587
5357
|
return solSignTransaction(ctx, sessionId, params);
|
|
4588
5358
|
case "solSignMessage":
|
|
4589
5359
|
return solSignMessage(ctx, sessionId, params);
|
|
5360
|
+
// ZCASH
|
|
5361
|
+
case "zcashGetFullViewingKey":
|
|
5362
|
+
return zcashGetFullViewingKey(ctx, sessionId, params);
|
|
5363
|
+
case "zcashGetShieldedAddress":
|
|
5364
|
+
return zcashGetShieldedAddress(ctx, sessionId, params);
|
|
4590
5365
|
// TRON
|
|
4591
5366
|
case "tronGetAddress":
|
|
4592
5367
|
return tronGetAddress(ctx, sessionId, params);
|
|
@@ -4620,7 +5395,7 @@ var LedgerConnectorBase = class {
|
|
|
4620
5395
|
});
|
|
4621
5396
|
});
|
|
4622
5397
|
} catch (err) {
|
|
4623
|
-
ctx.
|
|
5398
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4624
5399
|
throw ctx.wrapError(err);
|
|
4625
5400
|
} finally {
|
|
4626
5401
|
ctx.clearCanceller(sessionId);
|
|
@@ -4710,7 +5485,7 @@ var LedgerConnectorBase = class {
|
|
|
4710
5485
|
);
|
|
4711
5486
|
return { isGenuine: output.isGenuine, deviceId };
|
|
4712
5487
|
} catch (err) {
|
|
4713
|
-
ctx.
|
|
5488
|
+
ctx.teardownSecureChannelSession(sessionId);
|
|
4714
5489
|
throw ctx.wrapError(err);
|
|
4715
5490
|
} finally {
|
|
4716
5491
|
ctx.clearCanceller(sessionId);
|
|
@@ -4832,6 +5607,17 @@ var LedgerConnectorBase = class {
|
|
|
4832
5607
|
_invalidateSession(sessionId) {
|
|
4833
5608
|
this._signerManager?.invalidate(sessionId);
|
|
4834
5609
|
}
|
|
5610
|
+
_teardownSecureChannelSession(sessionId) {
|
|
5611
|
+
const cancel = this._cancellers.get(sessionId);
|
|
5612
|
+
this._cancellers.delete(sessionId);
|
|
5613
|
+
if (cancel) {
|
|
5614
|
+
try {
|
|
5615
|
+
cancel();
|
|
5616
|
+
} catch {
|
|
5617
|
+
}
|
|
5618
|
+
}
|
|
5619
|
+
this._invalidateSession(sessionId);
|
|
5620
|
+
}
|
|
4835
5621
|
/**
|
|
4836
5622
|
* Replace an old session with a new one after app switch.
|
|
4837
5623
|
* Emits device-connect so the adapter updates its _sessions Map.
|
|
@@ -4916,7 +5702,7 @@ var LedgerConnectorBase = class {
|
|
|
4916
5702
|
* at every catch site. Falls through unchanged for unknown methods.
|
|
4917
5703
|
*/
|
|
4918
5704
|
_ctxForMethod(method) {
|
|
4919
|
-
const prefix = /^(evm|btc|sol|tron)/.exec(method)?.[1];
|
|
5705
|
+
const prefix = /^(evm|btc|sol|tron|zcash)/.exec(method)?.[1];
|
|
4920
5706
|
const defaultAppName = prefix ? METHOD_PREFIX_TO_APP_NAME[prefix] : void 0;
|
|
4921
5707
|
if (!defaultAppName) return this._ctx;
|
|
4922
5708
|
return {
|
|
@@ -4950,6 +5736,204 @@ var LedgerConnectorBase = class {
|
|
|
4950
5736
|
return error;
|
|
4951
5737
|
}
|
|
4952
5738
|
};
|
|
5739
|
+
|
|
5740
|
+
// src/transport/DmkTransport.ts
|
|
5741
|
+
var import_hw_transport = __toESM(require("@ledgerhq/hw-transport"));
|
|
5742
|
+
var DmkTransport = class extends import_hw_transport.default {
|
|
5743
|
+
constructor(dmk, sessionId) {
|
|
5744
|
+
super();
|
|
5745
|
+
this._dmk = dmk;
|
|
5746
|
+
this._sessionId = sessionId;
|
|
5747
|
+
}
|
|
5748
|
+
async exchange(apdu) {
|
|
5749
|
+
const response = await this._dmk.sendApdu({
|
|
5750
|
+
sessionId: this._sessionId,
|
|
5751
|
+
apdu: new Uint8Array(apdu)
|
|
5752
|
+
});
|
|
5753
|
+
const { data, statusCode } = response;
|
|
5754
|
+
const result = Buffer.alloc(data.length + 2);
|
|
5755
|
+
if (data.length > 0) {
|
|
5756
|
+
result.set(data, 0);
|
|
5757
|
+
}
|
|
5758
|
+
result.set(statusCode, data.length);
|
|
5759
|
+
return result;
|
|
5760
|
+
}
|
|
5761
|
+
async close() {
|
|
5762
|
+
}
|
|
5763
|
+
};
|
|
5764
|
+
|
|
5765
|
+
// src/app/AppManager.ts
|
|
5766
|
+
var import_device_management_kit3 = require("@ledgerhq/device-management-kit");
|
|
5767
|
+
var import_hwk_adapter_core14 = require("@onekeyfe/hwk-adapter-core");
|
|
5768
|
+
var APP_NAME_MAP = {
|
|
5769
|
+
ETH: "Ethereum",
|
|
5770
|
+
BTC: "Bitcoin",
|
|
5771
|
+
SOL: "Solana",
|
|
5772
|
+
TRX: "Tron",
|
|
5773
|
+
ZEC: "Zcash",
|
|
5774
|
+
XRP: "XRP",
|
|
5775
|
+
ADA: "Cardano",
|
|
5776
|
+
DOT: "Polkadot",
|
|
5777
|
+
ATOM: "Cosmos"
|
|
5778
|
+
};
|
|
5779
|
+
var DASHBOARD_APP_NAME = "BOLOS";
|
|
5780
|
+
var AppManager = class {
|
|
5781
|
+
constructor(dmk, options) {
|
|
5782
|
+
this._dmk = dmk;
|
|
5783
|
+
this._waitMs = options?.waitMs ?? 1e3;
|
|
5784
|
+
this._maxRetries = options?.maxRetries ?? 10;
|
|
5785
|
+
}
|
|
5786
|
+
/**
|
|
5787
|
+
* Return the Ledger app name for a given chain ticker,
|
|
5788
|
+
* or undefined if the chain is not supported.
|
|
5789
|
+
*/
|
|
5790
|
+
static getAppName(chain) {
|
|
5791
|
+
return APP_NAME_MAP[chain];
|
|
5792
|
+
}
|
|
5793
|
+
/**
|
|
5794
|
+
* Ensure the target app is open on the device identified by `sessionId`.
|
|
5795
|
+
*
|
|
5796
|
+
* Flow:
|
|
5797
|
+
* 1. Check the currently running app.
|
|
5798
|
+
* 2. If it is already the target, return immediately.
|
|
5799
|
+
* 3. If a different app is running (not dashboard), close it first.
|
|
5800
|
+
* 4. Open the target app.
|
|
5801
|
+
* 5. Poll until the device confirms the target app is running.
|
|
5802
|
+
*/
|
|
5803
|
+
/**
|
|
5804
|
+
* @param onConfirmOnDevice Called BEFORE OpenAppCommand is issued — the
|
|
5805
|
+
* device is about to display "Open <app>" on screen and wait for the
|
|
5806
|
+
* user's button press. UI consumers should show their "open app" prompt
|
|
5807
|
+
* in response. NOT called when the target app is already open (no user
|
|
5808
|
+
* interaction needed in that case).
|
|
5809
|
+
*
|
|
5810
|
+
* Important: OpenAppCommand is blocking. It does not resolve until the user
|
|
5811
|
+
* has physically confirmed on the device, so anything that runs AFTER
|
|
5812
|
+
* `await this._openApp(...)` lands AFTER the prompt is already gone.
|
|
5813
|
+
* Hence the callback must fire BEFORE that await.
|
|
5814
|
+
*/
|
|
5815
|
+
async ensureAppOpen(sessionId, targetAppName, onConfirmOnDevice) {
|
|
5816
|
+
const currentApp = await this._getCurrentApp(sessionId);
|
|
5817
|
+
if (currentApp === targetAppName) {
|
|
5818
|
+
return;
|
|
5819
|
+
}
|
|
5820
|
+
if (!this._isDashboard(currentApp)) {
|
|
5821
|
+
await this._closeCurrentApp(sessionId);
|
|
5822
|
+
await this._waitForApp(sessionId, DASHBOARD_APP_NAME);
|
|
5823
|
+
}
|
|
5824
|
+
onConfirmOnDevice?.();
|
|
5825
|
+
await this._openApp(sessionId, targetAppName);
|
|
5826
|
+
await this._waitForApp(sessionId, targetAppName);
|
|
5827
|
+
}
|
|
5828
|
+
// ---------------------------------------------------------------------------
|
|
5829
|
+
// Private helpers
|
|
5830
|
+
// ---------------------------------------------------------------------------
|
|
5831
|
+
async _getCurrentApp(sessionId) {
|
|
5832
|
+
const result = await this._dmk.sendCommand({
|
|
5833
|
+
sessionId,
|
|
5834
|
+
command: new import_device_management_kit3.GetAppAndVersionCommand()
|
|
5835
|
+
});
|
|
5836
|
+
if ((0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5837
|
+
debugLog("[AppManager] currentApp:", result.data.name);
|
|
5838
|
+
return result.data.name;
|
|
5839
|
+
}
|
|
5840
|
+
const errResult = result;
|
|
5841
|
+
const dmkErr = errResult.error ?? {};
|
|
5842
|
+
const original = dmkErr.originalError;
|
|
5843
|
+
debugLog(
|
|
5844
|
+
"[AppManager] _getCurrentApp failed sessionId=",
|
|
5845
|
+
sessionId,
|
|
5846
|
+
"tag=",
|
|
5847
|
+
dmkErr._tag,
|
|
5848
|
+
"errorCode=",
|
|
5849
|
+
dmkErr.errorCode,
|
|
5850
|
+
"message=",
|
|
5851
|
+
dmkErr.message,
|
|
5852
|
+
"originalErrorMessage=",
|
|
5853
|
+
original?.message ?? String(original ?? "")
|
|
5854
|
+
);
|
|
5855
|
+
throw Object.assign(
|
|
5856
|
+
new Error(
|
|
5857
|
+
dmkErr.message ?? "Failed to get current app from device"
|
|
5858
|
+
),
|
|
5859
|
+
{
|
|
5860
|
+
_tag: dmkErr._tag,
|
|
5861
|
+
errorCode: dmkErr.errorCode,
|
|
5862
|
+
originalError: original
|
|
5863
|
+
}
|
|
5864
|
+
);
|
|
5865
|
+
}
|
|
5866
|
+
async _openApp(sessionId, appName) {
|
|
5867
|
+
const result = await this._dmk.sendCommand({
|
|
5868
|
+
sessionId,
|
|
5869
|
+
command: new import_device_management_kit3.OpenAppCommand({ appName })
|
|
5870
|
+
});
|
|
5871
|
+
if (!(0, import_device_management_kit3.isSuccessCommandResult)(result)) {
|
|
5872
|
+
const dmkErr = result.error;
|
|
5873
|
+
const errorCode = "errorCode" in dmkErr && dmkErr.errorCode != null ? String(dmkErr.errorCode) : "";
|
|
5874
|
+
const message = "message" in dmkErr && typeof dmkErr.message === "string" ? dmkErr.message : "";
|
|
5875
|
+
debugLog(
|
|
5876
|
+
"[AppManager] openApp failed:",
|
|
5877
|
+
appName,
|
|
5878
|
+
"errorCode:",
|
|
5879
|
+
errorCode,
|
|
5880
|
+
"tag:",
|
|
5881
|
+
dmkErr._tag
|
|
5882
|
+
);
|
|
5883
|
+
let code;
|
|
5884
|
+
if (errorCode === "6807" || /unknown application/i.test(message)) {
|
|
5885
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.AppNotInstalled;
|
|
5886
|
+
} else if (errorCode === "5501" || dmkErr._tag === "ActionRefusedError") {
|
|
5887
|
+
code = import_hwk_adapter_core14.HardwareErrorCode.UserRejected;
|
|
5888
|
+
}
|
|
5889
|
+
throw Object.assign(new Error(`Failed to open "${appName}"`), {
|
|
5890
|
+
_tag: ERROR_TAG.OpenAppCommand,
|
|
5891
|
+
code,
|
|
5892
|
+
errorCode,
|
|
5893
|
+
statusCode: errorCode,
|
|
5894
|
+
appName,
|
|
5895
|
+
originalError: dmkErr
|
|
5896
|
+
});
|
|
5897
|
+
}
|
|
5898
|
+
}
|
|
5899
|
+
async _closeCurrentApp(sessionId) {
|
|
5900
|
+
debugLog("[AppManager] closeCurrentApp");
|
|
5901
|
+
await this._dmk.sendCommand({
|
|
5902
|
+
sessionId,
|
|
5903
|
+
command: new import_device_management_kit3.CloseAppCommand()
|
|
5904
|
+
});
|
|
5905
|
+
}
|
|
5906
|
+
/**
|
|
5907
|
+
* Poll the device until the expected app is reported as running,
|
|
5908
|
+
* or throw after `_maxRetries` attempts.
|
|
5909
|
+
*/
|
|
5910
|
+
async _waitForApp(sessionId, expectedAppName) {
|
|
5911
|
+
let lastSeen = "";
|
|
5912
|
+
for (let i = 0; i < this._maxRetries; i++) {
|
|
5913
|
+
await this._wait();
|
|
5914
|
+
const current = await this._getCurrentApp(sessionId);
|
|
5915
|
+
lastSeen = current;
|
|
5916
|
+
if (current === expectedAppName) {
|
|
5917
|
+
return;
|
|
5918
|
+
}
|
|
5919
|
+
}
|
|
5920
|
+
debugLog(
|
|
5921
|
+
"[AppManager] waitForApp exhausted: expected=",
|
|
5922
|
+
expectedAppName,
|
|
5923
|
+
"lastSeen=",
|
|
5924
|
+
lastSeen
|
|
5925
|
+
);
|
|
5926
|
+
throw new Error(
|
|
5927
|
+
`Ledger: failed to open "${expectedAppName}" after ${this._maxRetries} retries (last seen: ${lastSeen})`
|
|
5928
|
+
);
|
|
5929
|
+
}
|
|
5930
|
+
_isDashboard(appName) {
|
|
5931
|
+
return appName === DASHBOARD_APP_NAME;
|
|
5932
|
+
}
|
|
5933
|
+
_wait() {
|
|
5934
|
+
return new Promise((resolve) => setTimeout(resolve, this._waitMs));
|
|
5935
|
+
}
|
|
5936
|
+
};
|
|
4953
5937
|
// Annotate the CommonJS export names for ESM import in node:
|
|
4954
5938
|
0 && (module.exports = {
|
|
4955
5939
|
AppManager,
|
|
@@ -4961,6 +5945,7 @@ var LedgerConnectorBase = class {
|
|
|
4961
5945
|
SignerEth,
|
|
4962
5946
|
SignerManager,
|
|
4963
5947
|
SignerSol,
|
|
5948
|
+
SignerZcash,
|
|
4964
5949
|
debugLog,
|
|
4965
5950
|
deviceActionToPromise,
|
|
4966
5951
|
isDeviceLockedError,
|