@onekeyfe/hwk-keystone-adapter 1.2.2-alpha.100

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.mjs ADDED
@@ -0,0 +1,1565 @@
1
+ // src/urEngine/KeystoneUrEngine.ts
2
+ import { generateAddressFromXpub } from "@keystonehq/bc-ur-registry-eth";
3
+ import { Curve, KeystoneSDK, QRHardwareCallVersion, UR } from "@keystonehq/keystone-sdk";
4
+ import bs58check from "bs58check";
5
+ import * as bitcoin from "bitcoinjs-lib";
6
+ import HDKey from "hdkey";
7
+ import { parse as uuidParse, stringify as uuidStringify } from "uuid";
8
+
9
+ // src/urEngine/TronSignRequest.ts
10
+ import {
11
+ CryptoKeypath,
12
+ DataItem,
13
+ PathComponent,
14
+ RegistryItem,
15
+ RegistryType,
16
+ RegistryTypes,
17
+ extend
18
+ } from "@keystonehq/bc-ur-registry";
19
+ var { decodeToDataItem } = extend;
20
+ var TRON_SIGN_REQUEST_TYPE = new RegistryType("tron-sign-request", 5201);
21
+ var TronSignRequest = class _TronSignRequest extends RegistryItem {
22
+ constructor(args) {
23
+ super();
24
+ this.getRegistryType = () => TRON_SIGN_REQUEST_TYPE;
25
+ this.getRequestId = () => this.requestId;
26
+ this.getSignData = () => this.signData;
27
+ this.getSignType = () => this.signType;
28
+ this.getDerivationPath = () => this.derivationPath.getPath();
29
+ this.toDataItem = () => {
30
+ const map = {};
31
+ if (this.requestId) {
32
+ map[1 /* requestId */] = new DataItem(this.requestId, RegistryTypes.UUID.getTag());
33
+ }
34
+ if (this.address) map[4 /* address */] = this.address;
35
+ if (this.origin) map[5 /* origin */] = this.origin;
36
+ map[2 /* signData */] = this.signData;
37
+ map[6 /* signType */] = this.signType;
38
+ const keyPath = this.derivationPath.toDataItem();
39
+ keyPath.setTag(this.derivationPath.getRegistryType().getTag());
40
+ map[3 /* derivationPath */] = keyPath;
41
+ return new DataItem(map);
42
+ };
43
+ this.requestId = args.requestId;
44
+ this.signData = args.signData;
45
+ this.derivationPath = args.derivationPath;
46
+ this.address = args.address;
47
+ this.origin = args.origin;
48
+ this.signType = args.signType;
49
+ }
50
+ static fromDataItem(dataItem) {
51
+ const map = dataItem.getData();
52
+ const signData = map[2 /* signData */];
53
+ const derivationPath = CryptoKeypath.fromDataItem(map[3 /* derivationPath */]);
54
+ const address = map[4 /* address */];
55
+ const requestIdItem = map[1 /* requestId */];
56
+ const requestId = requestIdItem?.getData();
57
+ const origin = map[5 /* origin */];
58
+ const signType = map[6 /* signType */];
59
+ return new _TronSignRequest({ requestId, signData, derivationPath, address, origin, signType });
60
+ }
61
+ static fromCBOR(cborPayload) {
62
+ return _TronSignRequest.fromDataItem(decodeToDataItem(cborPayload));
63
+ }
64
+ static parsePath(path, xfp) {
65
+ const segments = path.replace(/^[mM]\//, "").split("/");
66
+ const components = segments.map((segment) => {
67
+ const hardened = segment.endsWith("'");
68
+ return new PathComponent({
69
+ index: parseInt(hardened ? segment.slice(0, -1) : segment, 10),
70
+ hardened
71
+ });
72
+ });
73
+ return new CryptoKeypath(components, Buffer.from(xfp, "hex"));
74
+ }
75
+ };
76
+
77
+ // src/urEngine/TronSignature.ts
78
+ import {
79
+ DataItem as DataItem2,
80
+ RegistryItem as RegistryItem2,
81
+ RegistryType as RegistryType2,
82
+ RegistryTypes as RegistryTypes2,
83
+ extend as extend2
84
+ } from "@keystonehq/bc-ur-registry";
85
+ var { decodeToDataItem: decodeToDataItem2 } = extend2;
86
+ var TRON_SIGNATURE_TYPE = new RegistryType2("tron-signature", 5202);
87
+ var TronSignature = class _TronSignature extends RegistryItem2 {
88
+ constructor(signature, requestId) {
89
+ super();
90
+ this.getRegistryType = () => TRON_SIGNATURE_TYPE;
91
+ this.getRequestId = () => this.requestId;
92
+ this.getSignature = () => this.signatureBytes;
93
+ this.toDataItem = () => {
94
+ const map = {};
95
+ if (this.requestId) {
96
+ map[1 /* requestId */] = new DataItem2(this.requestId, RegistryTypes2.UUID.getTag());
97
+ }
98
+ map[2 /* signature */] = this.signatureBytes;
99
+ return new DataItem2(map);
100
+ };
101
+ this.signatureBytes = signature;
102
+ this.requestId = requestId;
103
+ }
104
+ static fromDataItem(dataItem) {
105
+ const map = dataItem.getData();
106
+ const signature = map[2 /* signature */];
107
+ const requestIdItem = map[1 /* requestId */];
108
+ const requestId = requestIdItem?.getData();
109
+ return new _TronSignature(signature, requestId);
110
+ }
111
+ static fromCBOR(cborPayload) {
112
+ return _TronSignature.fromDataItem(decodeToDataItem2(cborPayload));
113
+ }
114
+ };
115
+
116
+ // src/urEngine/KeystoneUrEngine.ts
117
+ var TRON_ADDRESS_PREFIX = 65;
118
+ function stripHexPrefix(hex) {
119
+ return hex.replace(/^0x/i, "");
120
+ }
121
+ var ETH_DATA_TYPE = {
122
+ transaction: 1,
123
+ typedData: 2,
124
+ personalMessage: 3,
125
+ typedTransaction: 4
126
+ };
127
+ var DERIVATION_CURVE = {
128
+ secp256k1: Curve.secp256k1,
129
+ ed25519: Curve.ed25519
130
+ };
131
+ function toSdkUr(ur) {
132
+ return new UR(Buffer.from(ur.urData, "hex"), ur.urType);
133
+ }
134
+ function fromSdkUr(ur) {
135
+ return { urType: ur.type, urData: ur.cbor.toString("hex") };
136
+ }
137
+ function splitSignature65(hex) {
138
+ return { r: hex.slice(0, 64), s: hex.slice(64, 128), v: hex.slice(128) };
139
+ }
140
+ var KeystoneUrEngine = class {
141
+ constructor(origin = "OneKey") {
142
+ this.sdk = new KeystoneSDK({ origin });
143
+ }
144
+ // --- Account sync (works for both a device-initiated QR export and a
145
+ // wallet-initiated KeyDerivation request/response over either channel) ---
146
+ parseMultiAccounts(ur) {
147
+ const parsed = this.sdk.parseMultiAccounts(toSdkUr(ur));
148
+ return {
149
+ masterFingerprint: parsed.masterFingerprint.toLowerCase(),
150
+ device: parsed.device,
151
+ deviceId: parsed.deviceId,
152
+ deviceVersion: parsed.deviceVersion,
153
+ accounts: parsed.keys.map(
154
+ (key) => ({
155
+ chain: key.chain,
156
+ path: key.path,
157
+ publicKey: key.publicKey,
158
+ extendedPublicKey: key.extendedPublicKey,
159
+ xfp: key.xfp,
160
+ name: key.name
161
+ })
162
+ )
163
+ };
164
+ }
165
+ parseHDKey(ur) {
166
+ const key = this.sdk.parseHDKey(toSdkUr(ur));
167
+ return {
168
+ chain: key.chain,
169
+ path: key.path,
170
+ publicKey: key.publicKey,
171
+ extendedPublicKey: key.extendedPublicKey,
172
+ xfp: key.xfp,
173
+ name: key.name
174
+ };
175
+ }
176
+ /**
177
+ * Build a `qr-hardware-call` (KeyDerivation) request: the host asks for
178
+ * specific paths instead of waiting for whatever the device happens to be
179
+ * showing. The device replies with a `crypto-multi-accounts` UR — parse it
180
+ * with `parseMultiAccounts`. Used for the implicit "sync this wallet's xfp
181
+ * before the first sign" round trip as well as an explicit account import.
182
+ *
183
+ * `version: V1` is required — verified against real Keystone hardware and
184
+ * `keystone3-firmware`'s `CheckHardwareCallRequestIsLegal` source: an
185
+ * unversioned/V0 request is validated as a legacy Cardano-only request
186
+ * (`m/1852'/1815'/...`) and firmware rejects every other chain's path with
187
+ * `PRS_PARSING_ERROR` (device-shown message: "路径不受支持" / "path not
188
+ * supported"), regardless of the path's shape. V1 is what actually enables
189
+ * the general per-chain path whitelist (includes `m/44'/60'` for ETH, the
190
+ * standard BTC purposes, etc.). The SDK itself defaults to V0 unless a
191
+ * truthy `version` is passed — omitting this silently produces a request
192
+ * every non-Cardano device rejects.
193
+ */
194
+ buildKeyDerivationRequest(input) {
195
+ const ur = this.sdk.generateKeyDerivationCall({
196
+ schemas: input.schemas.map((schema) => ({
197
+ path: schema.path,
198
+ curve: DERIVATION_CURVE[schema.curve ?? "secp256k1"]
199
+ })),
200
+ origin: input.origin,
201
+ version: QRHardwareCallVersion.V1
202
+ });
203
+ return fromSdkUr(ur);
204
+ }
205
+ /**
206
+ * Parse the response to a KeyDerivation request (or a device-initiated
207
+ * account export): `crypto-multi-accounts` for a multi-schema request,
208
+ * `crypto-hdkey` for a single-key response some firmware paths use instead.
209
+ * Both are normalized to the same `KeystoneParsedMultiAccounts` shape — a
210
+ * single `crypto-hdkey` becomes a one-entry account list, with its own
211
+ * `origin.sourceFingerprint` promoted to `masterFingerprint` (correct for a
212
+ * key derived directly from the seed, which every request this engine
213
+ * builds asks for).
214
+ */
215
+ parseAccountResponse(ur) {
216
+ if (ur.urType === "crypto-hdkey") {
217
+ const account = this.parseHDKey(ur);
218
+ if (!account.xfp) {
219
+ throw new Error("Keystone crypto-hdkey response is missing its source fingerprint");
220
+ }
221
+ return { masterFingerprint: account.xfp.toLowerCase(), accounts: [account] };
222
+ }
223
+ return this.parseMultiAccounts(ur);
224
+ }
225
+ // --- EVM ---
226
+ buildEthSignRequest(input) {
227
+ const ur = this.sdk.eth.generateSignRequest({
228
+ requestId: input.requestId,
229
+ signData: input.unsignedTxHex,
230
+ dataType: ETH_DATA_TYPE[input.dataType],
231
+ path: input.path,
232
+ xfp: input.xfp,
233
+ chainId: input.chainId,
234
+ address: input.address,
235
+ origin: input.origin
236
+ });
237
+ return fromSdkUr(ur);
238
+ }
239
+ parseEthSignature(ur) {
240
+ const signature = this.sdk.eth.parseSignature(toSdkUr(ur));
241
+ return { requestId: signature.requestId, ...splitSignature65(signature.signature) };
242
+ }
243
+ /**
244
+ * Derive one EVM address offline from an already-synced account xpub —
245
+ * verified against the same `@keystonehq/bc-ur-registry-eth` helper the
246
+ * Keystone-based OneKey air-gap demo uses in production
247
+ * (`generateAddressFromXpub`), so no unverified assumption about what a
248
+ * leaf-path KeyDerivation request would return. `relativeDerivePath` is
249
+ * relative to the xpub's own depth, e.g. `'0/0'` for an account xpub.
250
+ */
251
+ deriveEvmAddressFromXpub(xpub, relativeDerivePath) {
252
+ return generateAddressFromXpub(xpub, `m/${relativeDerivePath.replace(/^m\//i, "")}`);
253
+ }
254
+ // --- BTC (PSBT transaction signing + plain message signing) ---
255
+ /**
256
+ * Derive one BTC address offline from an already-synced account xpub, the
257
+ * same way `deriveEvmAddressFromXpub` does. Keystone's `CryptoHDKey`
258
+ * always emits standard mainnet-xpub version bytes (`0488B21E`) regardless
259
+ * of the account's purpose/script type (verified against
260
+ * `@keystonehq/bc-ur-registry`'s `CryptoHDKey.getBip32Key`, which hardcodes
261
+ * that version rather than switching to a SLIP-132 ypub/zpub prefix per
262
+ * script type) — so `hdkey.fromExtendedKey` parses it correctly for every
263
+ * `scriptType` without needing custom version bytes configured.
264
+ *
265
+ * `p2tr` is deliberately not handled: taproot output-key tweaking (BIP-341)
266
+ * needs an elliptic-curve library wired via bitcoinjs-lib's `initEccLib`,
267
+ * which this package doesn't set up yet — every other payment function
268
+ * here needs no such library.
269
+ */
270
+ deriveBtcAddressFromXpub(xpub, relativeDerivePath, scriptType) {
271
+ const node = HDKey.fromExtendedKey(xpub).derive(`m/${relativeDerivePath.replace(/^m\//i, "")}`);
272
+ if (!node.publicKey) throw new Error("HDKey derivation did not produce a public key");
273
+ const pubkey = Buffer.from(node.publicKey);
274
+ const network = bitcoin.networks.bitcoin;
275
+ switch (scriptType) {
276
+ case "p2pkh": {
277
+ const { address } = bitcoin.payments.p2pkh({ pubkey, network });
278
+ if (!address) throw new Error("Failed to derive a P2PKH address from this xpub");
279
+ return address;
280
+ }
281
+ case "p2sh-p2wpkh": {
282
+ const { address } = bitcoin.payments.p2sh({
283
+ redeem: bitcoin.payments.p2wpkh({ pubkey, network }),
284
+ network
285
+ });
286
+ if (!address) throw new Error("Failed to derive a P2SH-P2WPKH address from this xpub");
287
+ return address;
288
+ }
289
+ case "p2wpkh": {
290
+ const { address } = bitcoin.payments.p2wpkh({ pubkey, network });
291
+ if (!address) throw new Error("Failed to derive a P2WPKH address from this xpub");
292
+ return address;
293
+ }
294
+ case "p2tr":
295
+ throw new Error(
296
+ "BTC P2TR (taproot) address derivation is not supported yet \u2014 needs an elliptic-curve library for BIP-341 tweaking"
297
+ );
298
+ default: {
299
+ const exhaustive = scriptType;
300
+ throw new Error(`Unsupported BTC script type: ${String(exhaustive)}`);
301
+ }
302
+ }
303
+ }
304
+ buildBtcPsbtRequest(unsignedPsbtHex) {
305
+ const ur = this.sdk.btc.generatePSBT(Buffer.from(unsignedPsbtHex, "hex"));
306
+ return fromSdkUr(ur);
307
+ }
308
+ /** Returns the hex-encoded (possibly still-unsigned-in-part) PSBT the device replied with. */
309
+ parseBtcPsbt(ur) {
310
+ return this.sdk.btc.parsePSBT(toSdkUr(ur));
311
+ }
312
+ buildBtcMessageSignRequest(params) {
313
+ const ur = this.sdk.btc.generateSignRequest({
314
+ requestId: params.requestId,
315
+ signData: params.messageHex,
316
+ dataType: 1,
317
+ // BtcSignRequest.DataType.message — PSBT signing never goes through this path.
318
+ accounts: params.accounts,
319
+ origin: params.origin
320
+ });
321
+ return fromSdkUr(ur);
322
+ }
323
+ parseBtcSignature(ur) {
324
+ const signature = this.sdk.btc.parseSignature(toSdkUr(ur));
325
+ return {
326
+ requestId: signature.requestId,
327
+ publicKey: signature.publicKey,
328
+ signature: signature.signature
329
+ };
330
+ }
331
+ // --- SOL ---
332
+ buildSolSignRequest(input) {
333
+ const ur = this.sdk.sol.generateSignRequest({
334
+ requestId: input.requestId,
335
+ signData: input.unsignedPayloadHex,
336
+ dataType: input.dataType === "transaction" ? 1 : 2,
337
+ path: input.path,
338
+ xfp: input.xfp,
339
+ address: input.address,
340
+ origin: input.origin
341
+ });
342
+ return fromSdkUr(ur);
343
+ }
344
+ parseSolSignature(ur) {
345
+ const signature = this.sdk.sol.parseSignature(toSdkUr(ur));
346
+ return { requestId: signature.requestId, signature: signature.signature };
347
+ }
348
+ // --- TRON ---
349
+ /**
350
+ * `@keystonehq/keystone-sdk`'s own bundled `sdk.tron` module is
351
+ * deliberately NOT used here — see `TronSignRequest.ts`'s doc comment for
352
+ * why: it's a different (gzip/protobuf) protocol with response semantics
353
+ * this package has no way to verify, whereas `TronSignRequest`/
354
+ * `TronSignature` are a direct port of OneKey's own already-proven
355
+ * production QR-wallet TRON implementation (a plain CBOR-native
356
+ * sign-request/signature pair, same shape as eth/sol). The device decodes
357
+ * `rawTxHex` itself — no client-side contract-type pre-parsing or
358
+ * `tokenInfo` needed, unlike the public SDK's module.
359
+ */
360
+ buildTronSignRequest(input) {
361
+ const request = new TronSignRequest({
362
+ requestId: Buffer.from(uuidParse(input.requestId)),
363
+ signData: Buffer.from(stripHexPrefix(input.rawTxHex), "hex"),
364
+ signType: 0 /* Transaction */,
365
+ derivationPath: TronSignRequest.parsePath(input.path, input.xfp),
366
+ origin: input.origin
367
+ });
368
+ return fromSdkUr(request.toUR());
369
+ }
370
+ parseTronSignature(ur) {
371
+ if (ur.urType !== "tron-signature") {
372
+ throw new Error(`Expected a tron-signature UR, got ${ur.urType}`);
373
+ }
374
+ const signature = TronSignature.fromCBOR(Buffer.from(ur.urData, "hex"));
375
+ const requestId = signature.getRequestId();
376
+ return {
377
+ requestId: requestId ? uuidStringify(requestId) : void 0,
378
+ signature: signature.getSignature().toString("hex")
379
+ };
380
+ }
381
+ /**
382
+ * Derive one TRON address offline from an already-synced account xpub.
383
+ * TRON reuses EVM's exact secp256k1-pubkey → keccak256 → last-20-bytes
384
+ * derivation (verified against Keystone's own `formatAddress()` in
385
+ * `keystone-sdk`'s TRON chain source) — only the final text encoding
386
+ * differs (base58check with a `0x41` version byte, not checksummed hex).
387
+ * Reusing `generateAddressFromXpub` here means no new hashing dependency:
388
+ * strip its "0x" and re-encode the same 20 bytes.
389
+ */
390
+ deriveTronAddressFromXpub(xpub, relativeDerivePath) {
391
+ const evmStyleHex = generateAddressFromXpub(
392
+ xpub,
393
+ `m/${relativeDerivePath.replace(/^m\//i, "")}`
394
+ );
395
+ const addressBytes = Buffer.concat([
396
+ Buffer.from([TRON_ADDRESS_PREFIX]),
397
+ Buffer.from(evmStyleHex.replace(/^0x/i, ""), "hex")
398
+ ]);
399
+ return bs58check.encode(addressBytes);
400
+ }
401
+ };
402
+
403
+ // src/adapter/KeystoneAdapter.ts
404
+ import bs58 from "bs58";
405
+ import { v4 as uuidv4 } from "uuid";
406
+ import {
407
+ CHAIN_FINGERPRINT_PATHS,
408
+ DEVICE,
409
+ DeviceJobQueue,
410
+ HardwareErrorCode,
411
+ TypedEventEmitter,
412
+ UI_REQUEST,
413
+ UI_REQUEST_CANCELLED_TAG,
414
+ UI_REQUEST_PREEMPTED_TAG,
415
+ UI_REQUEST_TIMEOUT_TAG,
416
+ UI_RESPONSE,
417
+ UiRequestRegistry,
418
+ createHwkError,
419
+ deriveDeviceFingerprint,
420
+ ensure0x,
421
+ failure,
422
+ rehydrateConnectorError,
423
+ runAllNetworkGetAddress,
424
+ stripHex,
425
+ success
426
+ } from "@onekeyfe/hwk-adapter-core";
427
+
428
+ // src/adapter/pathUtils.ts
429
+ function normalizePath(path) {
430
+ const trimmed = path.trim();
431
+ return /^m\//i.test(trimmed) ? `m/${trimmed.slice(2)}` : `m/${trimmed}`;
432
+ }
433
+ function splitAccountPath(path) {
434
+ const normalized = normalizePath(path);
435
+ const segments = normalized.slice(2).split("/");
436
+ if (segments.length <= 3) {
437
+ return { accountPath: normalized, relativeDerivePath: "" };
438
+ }
439
+ const accountSegments = segments.slice(0, segments.length - 2);
440
+ const relativeSegments = segments.slice(segments.length - 2);
441
+ return {
442
+ accountPath: `m/${accountSegments.join("/")}`,
443
+ relativeDerivePath: relativeSegments.join("/")
444
+ };
445
+ }
446
+ function btcScriptTypeFromPath(path) {
447
+ const match = normalizePath(path).match(/^m\/(\d+)'/);
448
+ if (!match) return void 0;
449
+ switch (Number(match[1])) {
450
+ case 44:
451
+ return "p2pkh";
452
+ case 49:
453
+ return "p2sh-p2wpkh";
454
+ case 84:
455
+ return "p2wpkh";
456
+ case 86:
457
+ return "p2tr";
458
+ default:
459
+ return void 0;
460
+ }
461
+ }
462
+
463
+ // src/adapter/deviceTable.ts
464
+ var QR_CONNECT_ID_PREFIX = "keystone-qr:";
465
+ function qrConnectId(masterFingerprint) {
466
+ return `${QR_CONNECT_ID_PREFIX}${masterFingerprint}`;
467
+ }
468
+ function accountKey(hwkChain, path) {
469
+ return `${hwkChain}:${normalizePath(path)}`;
470
+ }
471
+ function createDeviceRecord(masterFingerprint) {
472
+ return {
473
+ masterFingerprint,
474
+ connectId: qrConnectId(masterFingerprint),
475
+ accounts: /* @__PURE__ */ new Map(),
476
+ importedAt: Date.now()
477
+ };
478
+ }
479
+ var CAPABILITIES = { persistentDeviceIdentity: true };
480
+ function toDeviceInfo(record) {
481
+ let availableChannels = ["qr"];
482
+ if (record.usbSessionId) {
483
+ availableChannels = record.qrSynced ? ["qr", "usb"] : ["usb"];
484
+ }
485
+ return {
486
+ vendor: "keystone",
487
+ model: record.model ?? "unknown",
488
+ modelName: record.model,
489
+ firmwareVersion: record.deviceVersion ?? "0.0.0",
490
+ deviceId: record.masterFingerprint,
491
+ connectId: record.connectId,
492
+ connectionType: record.usbSessionId ? "usb" : "qr",
493
+ capabilities: CAPABILITIES,
494
+ raw: { availableChannels }
495
+ };
496
+ }
497
+ function placeholderDeviceInfo() {
498
+ return {
499
+ vendor: "keystone",
500
+ model: "unknown",
501
+ firmwareVersion: "0.0.0",
502
+ deviceId: "",
503
+ connectId: "",
504
+ connectionType: "qr",
505
+ capabilities: CAPABILITIES
506
+ };
507
+ }
508
+
509
+ // src/adapter/KeystoneAdapter.ts
510
+ var COLD_START_JOB_LABEL = "keystone-cold-start";
511
+ var BIP44_COIN_TYPE_TO_CHAIN = {
512
+ 60: "evm",
513
+ 0: "btc",
514
+ 501: "sol",
515
+ 195: "tron"
516
+ };
517
+ function inferHwkChainFromPath(path) {
518
+ const match = normalizePath(path).match(/^m\/\d+'\/(\d+)'/);
519
+ return match ? BIP44_COIN_TYPE_TO_CHAIN[Number(match[1])] : void 0;
520
+ }
521
+ var DEFAULT_IMPORT_SCHEMAS = [
522
+ { hwkChain: "evm", path: CHAIN_FINGERPRINT_PATHS.evm.replace(/\/0\/0$/, "") },
523
+ // The 3 BTC purposes this package can actually derive addresses for
524
+ // (btcScriptTypeFromPath: 44'→P2PKH, 49'→P2SH-P2WPKH, 84'→P2WPKH) —
525
+ // explicitly requested, not left to chance on whether the device
526
+ // volunteers the others unprompted. Still one combined round trip: these
527
+ // are 3 more entries in the same qr-hardware-call, not 3 more scans.
528
+ // 86' (P2TR/taproot) deliberately excluded — `deriveBtcAddressFromXpub`
529
+ // can't use it yet (needs an elliptic-curve library not wired in), and
530
+ // unlike app-monorepo's own sync-all bundle (which also requests 86', but
531
+ // to compute a "full xfp" — a need this adapter doesn't have, since its
532
+ // mfp already comes for free from the response envelope), there's no
533
+ // other use for that xpub here — so it stays out until P2TR is real.
534
+ { hwkChain: "btc", path: CHAIN_FINGERPRINT_PATHS.btc },
535
+ { hwkChain: "btc", path: "m/49'/0'/0'" },
536
+ { hwkChain: "btc", path: "m/84'/0'/0'" },
537
+ { hwkChain: "sol", path: CHAIN_FINGERPRINT_PATHS.sol },
538
+ { hwkChain: "tron", path: CHAIN_FINGERPRINT_PATHS.tron.replace(/\/0\/0$/, "") }
539
+ ];
540
+ var KeystoneAdapter = class _KeystoneAdapter {
541
+ constructor(options) {
542
+ this.vendor = "keystone";
543
+ this.emitter = new TypedEventEmitter();
544
+ this._uiRegistry = new UiRequestRegistry();
545
+ this._devices = /* @__PURE__ */ new Map();
546
+ // ---------------------------------------------------------------------------
547
+ // All-network bundle — dispatches to the same per-chain methods below, so
548
+ // there's exactly one implementation of each chain's address logic.
549
+ // ---------------------------------------------------------------------------
550
+ this.allNetworkGetAddress = async (connectId, deviceId, params) => {
551
+ try {
552
+ return await runAllNetworkGetAddress({
553
+ connectId,
554
+ deviceId,
555
+ params,
556
+ callItem: async ({ chain, item }) => {
557
+ const commonArgs = { path: item.path, showOnDevice: item.showOnDevice };
558
+ switch (chain) {
559
+ case "evm":
560
+ return this.evmGetAddress(connectId, deviceId, commonArgs);
561
+ case "btc":
562
+ return this.btcGetAddress(connectId, deviceId, commonArgs);
563
+ case "sol":
564
+ return this.solGetAddress(connectId, deviceId, commonArgs);
565
+ case "tron":
566
+ return this.tronGetAddress(connectId, deviceId, commonArgs);
567
+ default:
568
+ return failure(HardwareErrorCode.MethodNotSupported, `Unsupported chain: ${chain}`);
569
+ }
570
+ },
571
+ attachIdentity: (context) => {
572
+ const mfp = deviceId ? deviceId.toLowerCase() : void 0;
573
+ return Promise.resolve({
574
+ ...context.item,
575
+ success: true,
576
+ payload: {
577
+ ...context.payload,
578
+ deviceIdentity: mfp ? { vendor: "keystone", type: "masterFingerprint", value: mfp } : void 0
579
+ }
580
+ });
581
+ }
582
+ });
583
+ } catch (err) {
584
+ return this._errorToFailure(err);
585
+ }
586
+ };
587
+ this._origin = options?.origin ?? "OneKey";
588
+ this._qrTimeoutMs = options?.qrTimeoutMs;
589
+ this.urEngine = new KeystoneUrEngine(this._origin);
590
+ this._jobQueue = new DeviceJobQueue();
591
+ this._usbConnector = options?.usbConnector;
592
+ }
593
+ // ---------------------------------------------------------------------------
594
+ // Lifecycle / transport
595
+ // ---------------------------------------------------------------------------
596
+ get activeTransport() {
597
+ if (this._devices.size === 0) return null;
598
+ const hasUsbSession = Array.from(this._devices.values()).some((r) => r.usbSessionId);
599
+ return hasUsbSession ? "usb" : "qr";
600
+ }
601
+ getAvailableTransports() {
602
+ return this._usbConnector ? ["qr", "usb"] : ["qr"];
603
+ }
604
+ /** Pins subsequent calls to 'qr' or 'usb' (routing otherwise defaults to "USB when the target wallet has a live session, else QR" — see `_resolveUr`). Any other value clears the pin back to auto. */
605
+ switchTransport(type) {
606
+ this._forcedTransport = type === "qr" || type === "usb" ? type : void 0;
607
+ return Promise.resolve();
608
+ }
609
+ init(_config) {
610
+ return Promise.resolve();
611
+ }
612
+ dispose() {
613
+ this._uiRegistry.cancel();
614
+ this._jobQueue.clear();
615
+ this.emitter.removeAllListeners();
616
+ this._devices.clear();
617
+ this._usbConnector?.reset();
618
+ return Promise.resolve();
619
+ }
620
+ // ---------------------------------------------------------------------------
621
+ // Device table
622
+ // ---------------------------------------------------------------------------
623
+ /**
624
+ * QR-synced wallets are always included (this instance's own state — no
625
+ * enumeration exists for QR). When a USB connector is configured, its raw
626
+ * scan results are appended as-is: a USB descriptor has no mfp until
627
+ * `connectDevice()` actually opens+claims it (see
628
+ * `KeystoneUsbConnectorBase.searchDevices`), so these entries carry an
629
+ * empty `deviceId` and exist purely so a host can list "plugged in, click
630
+ * to connect" candidates.
631
+ */
632
+ async searchDevices(_options) {
633
+ const known = Array.from(this._devices.values()).map(toDeviceInfo);
634
+ if (!this._usbConnector) return known;
635
+ let usbDevices;
636
+ try {
637
+ usbDevices = await this._usbConnector.searchDevices();
638
+ } catch {
639
+ return known;
640
+ }
641
+ const placeholders = usbDevices.map((d) => ({
642
+ vendor: "keystone",
643
+ model: d.model ?? "unknown",
644
+ modelName: d.modelName,
645
+ firmwareVersion: "0.0.0",
646
+ deviceId: d.deviceId,
647
+ connectId: d.connectId,
648
+ connectionType: "usb",
649
+ capabilities: d.capabilities ?? { persistentDeviceIdentity: true }
650
+ }));
651
+ return [...known, ...placeholders];
652
+ }
653
+ async connectDevice(connectId) {
654
+ const existing = this._findByConnectId(connectId);
655
+ if (existing) return success(existing.connectId);
656
+ if (!this._usbConnector) {
657
+ return failure(HardwareErrorCode.DeviceNotFound, `Unknown Keystone connectId: ${connectId}`);
658
+ }
659
+ const result = await this._connectUsb();
660
+ if (!result.success) return result;
661
+ return success(result.payload.connectId);
662
+ }
663
+ /**
664
+ * QR has no persistent connection to tear down — the account cache
665
+ * survives so a later call resumes without re-syncing. For a USB session,
666
+ * this closes the connector session and either demotes the record back to
667
+ * QR-only (if it was ever QR-synced) or removes it entirely (pure-USB
668
+ * wallet that was never seen over QR) — see §4.2 of the design doc.
669
+ */
670
+ async disconnectDevice(connectId) {
671
+ const record = this._findByConnectId(connectId);
672
+ if (!record?.usbSessionId) return;
673
+ if (this._usbConnector) {
674
+ try {
675
+ await this._usbConnector.disconnect(record.usbSessionId);
676
+ } catch {
677
+ }
678
+ }
679
+ record.usbSessionId = void 0;
680
+ if (record.qrSynced) {
681
+ const info = toDeviceInfo(record);
682
+ this.emitter.emit(DEVICE.CHANGED, { type: DEVICE.CHANGED, payload: info });
683
+ } else {
684
+ this._devices.delete(record.masterFingerprint);
685
+ const info = toDeviceInfo(record);
686
+ this.emitter.emit(DEVICE.DISCONNECT, { type: DEVICE.DISCONNECT, payload: info });
687
+ }
688
+ }
689
+ getDeviceInfo(connectId, deviceId) {
690
+ const record = this._findByConnectId(connectId) ?? this._devices.get(deviceId.toLowerCase());
691
+ if (!record) {
692
+ return Promise.resolve(
693
+ failure(
694
+ HardwareErrorCode.DeviceNotFound,
695
+ `Unknown Keystone device: ${connectId || deviceId}`
696
+ )
697
+ );
698
+ }
699
+ return Promise.resolve(success(toDeviceInfo(record)));
700
+ }
701
+ getSupportedChains() {
702
+ return ["evm", "btc", "sol", "tron"];
703
+ }
704
+ cancel(connectId) {
705
+ const reason = createHwkError({
706
+ code: HardwareErrorCode.UserAborted,
707
+ message: "User aborted operation"
708
+ });
709
+ this._uiRegistry.cancel();
710
+ this._jobQueue.cancelActiveAndPending(connectId, reason);
711
+ }
712
+ getChainFingerprint(connectId, deviceId, chain) {
713
+ const mfp = deviceId ? deviceId.toLowerCase() : this._mfpFromConnectId(connectId);
714
+ if (!mfp) {
715
+ return Promise.resolve(failure(HardwareErrorCode.DeviceNotFound, "Unknown Keystone device"));
716
+ }
717
+ return Promise.resolve(success(deriveDeviceFingerprint(`keystone:${chain}:${mfp}`)));
718
+ }
719
+ uiResponse(response) {
720
+ if (response.type === UI_RESPONSE.CANCEL) {
721
+ this.cancel();
722
+ return;
723
+ }
724
+ this._uiRegistry.resolve(response.type, response.payload);
725
+ }
726
+ on(event, listener) {
727
+ this.emitter.on(event, listener);
728
+ }
729
+ off(event, listener) {
730
+ this.emitter.off(event, listener);
731
+ }
732
+ // ---------------------------------------------------------------------------
733
+ // Explicit account import — the recommended entry point before signing, so
734
+ // signing calls don't each pay for their own cold-sync round trip.
735
+ // ---------------------------------------------------------------------------
736
+ async importFromQr(options = {}) {
737
+ try {
738
+ return await this._jobQueue.enqueue(COLD_START_JOB_LABEL, async (signal) => {
739
+ const displayDevice = placeholderDeviceInfo();
740
+ let responseUr;
741
+ let requestedChains;
742
+ if (options.mode === "scan") {
743
+ responseUr = await this._requestQrScanAndAwaitResponse(displayDevice);
744
+ } else {
745
+ const schemas = options.paths?.length ? options.paths : DEFAULT_IMPORT_SCHEMAS;
746
+ requestedChains = schemas.map((s) => s.hwkChain);
747
+ const requestUr = this.urEngine.buildKeyDerivationRequest({
748
+ schemas: schemas.map((s) => ({
749
+ path: s.path,
750
+ curve: s.hwkChain === "sol" ? "ed25519" : "secp256k1"
751
+ })),
752
+ origin: this._origin
753
+ });
754
+ responseUr = await this._requestQrDisplayAndAwaitResponse(displayDevice, {
755
+ ...requestUr,
756
+ animated: false
757
+ });
758
+ }
759
+ _KeystoneAdapter._throwIfAborted(signal);
760
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
761
+ const record = this._upsertDeviceRecord(parsed);
762
+ for (const account of parsed.accounts) {
763
+ const hwkChain = requestedChains?.length === 1 ? requestedChains[0] : inferHwkChainFromPath(account.path);
764
+ if (hwkChain) {
765
+ const entry = { ...account, hwkChain };
766
+ record.accounts.set(accountKey(hwkChain, account.path), entry);
767
+ }
768
+ }
769
+ return success(toDeviceInfo(record));
770
+ });
771
+ } catch (err) {
772
+ return this._errorToFailure(err);
773
+ }
774
+ }
775
+ // ---------------------------------------------------------------------------
776
+ // EVM
777
+ // ---------------------------------------------------------------------------
778
+ async evmGetAddress(connectIdArg, deviceIdArg, paramsArg) {
779
+ const connectId = connectIdArg ?? void 0;
780
+ const deviceId = deviceIdArg ?? void 0;
781
+ const params = paramsArg;
782
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params");
783
+ if (!params.path)
784
+ return failure(HardwareErrorCode.InvalidParams, "evmGetAddress requires params.path");
785
+ const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
786
+ if (!relativeDerivePath) {
787
+ return failure(
788
+ HardwareErrorCode.InvalidParams,
789
+ "evmGetAddress requires a full leaf path, e.g. m/44'/60'/0'/0/0"
790
+ );
791
+ }
792
+ try {
793
+ return await this._jobQueue.enqueue(
794
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
795
+ async (signal) => {
796
+ const { account } = await this._ensureAccountSynced(
797
+ connectId,
798
+ deviceId,
799
+ "evm",
800
+ accountPath,
801
+ signal
802
+ );
803
+ _KeystoneAdapter._throwIfAborted(signal);
804
+ if (!account.extendedPublicKey) {
805
+ throw createHwkError({
806
+ code: HardwareErrorCode.MethodNotSupported,
807
+ message: "Keystone did not return an extended public key for this account path"
808
+ });
809
+ }
810
+ const address = this.urEngine.deriveEvmAddressFromXpub(
811
+ account.extendedPublicKey,
812
+ relativeDerivePath
813
+ );
814
+ return success({ address, path: normalizePath(params.path) });
815
+ }
816
+ );
817
+ } catch (err) {
818
+ return this._errorToFailure(err);
819
+ }
820
+ }
821
+ async evmSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
822
+ const connectId = connectIdArg ?? void 0;
823
+ const deviceId = deviceIdArg ?? void 0;
824
+ const params = paramsArg;
825
+ if (!params)
826
+ return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params");
827
+ if (!params.path) {
828
+ return failure(HardwareErrorCode.InvalidParams, "evmSignTransaction requires params.path");
829
+ }
830
+ if (!("serializedTx" in params) || typeof params.serializedTx !== "string" || !params.serializedTx) {
831
+ return failure(
832
+ HardwareErrorCode.MethodNotSupported,
833
+ "Keystone only signs a fully RLP-serialized transaction (params.serializedTx) \u2014 structured-field signing is not supported"
834
+ );
835
+ }
836
+ const rawTxHex = stripHex(params.serializedTx);
837
+ const path = normalizePath(params.path);
838
+ try {
839
+ return await this._jobQueue.enqueue(
840
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
841
+ async (signal) => {
842
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "evm", signal);
843
+ _KeystoneAdapter._throwIfAborted(signal);
844
+ const requestId = uuidv4();
845
+ const dataType = parseInt(rawTxHex.slice(0, 2), 16) < 192 ? "typedTransaction" : "transaction";
846
+ const requestUr = this.urEngine.buildEthSignRequest({
847
+ requestId,
848
+ unsignedTxHex: rawTxHex,
849
+ dataType,
850
+ path,
851
+ xfp: record.masterFingerprint,
852
+ chainId: params.chainId
853
+ });
854
+ const responseUr = await this._resolveUr(record, requestUr, true);
855
+ _KeystoneAdapter._throwIfAborted(signal);
856
+ const sig = this.urEngine.parseEthSignature(responseUr);
857
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
858
+ return success({
859
+ v: ensure0x(sig.v),
860
+ r: ensure0x(sig.r),
861
+ s: ensure0x(sig.s)
862
+ });
863
+ }
864
+ );
865
+ } catch (err) {
866
+ return this._errorToFailure(err);
867
+ }
868
+ }
869
+ async evmSignMessage(connectIdArg, deviceIdArg, paramsArg) {
870
+ const connectId = connectIdArg ?? void 0;
871
+ const deviceId = deviceIdArg ?? void 0;
872
+ const params = paramsArg;
873
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "evmSignMessage requires params");
874
+ if (!params.path || params.message === void 0) {
875
+ return failure(
876
+ HardwareErrorCode.InvalidParams,
877
+ "evmSignMessage requires params.path and params.message"
878
+ );
879
+ }
880
+ const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
881
+ const path = normalizePath(params.path);
882
+ try {
883
+ return await this._jobQueue.enqueue(
884
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
885
+ async (signal) => {
886
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "evm", signal);
887
+ _KeystoneAdapter._throwIfAborted(signal);
888
+ const requestId = uuidv4();
889
+ const requestUr = this.urEngine.buildEthSignRequest({
890
+ requestId,
891
+ unsignedTxHex: messageHex,
892
+ dataType: "personalMessage",
893
+ path,
894
+ xfp: record.masterFingerprint,
895
+ chainId: params.chainId
896
+ });
897
+ const responseUr = await this._resolveUr(record, requestUr, true);
898
+ _KeystoneAdapter._throwIfAborted(signal);
899
+ const sig = this.urEngine.parseEthSignature(responseUr);
900
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
901
+ return success({ signature: ensure0x(sig.r + sig.s + sig.v) });
902
+ }
903
+ );
904
+ } catch (err) {
905
+ return this._errorToFailure(err);
906
+ }
907
+ }
908
+ async evmSignTypedData(connectIdArg, deviceIdArg, paramsArg) {
909
+ const connectId = connectIdArg ?? void 0;
910
+ const deviceId = deviceIdArg ?? void 0;
911
+ const params = paramsArg;
912
+ if (!params)
913
+ return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params");
914
+ if (!params.path) {
915
+ return failure(HardwareErrorCode.InvalidParams, "evmSignTypedData requires params.path");
916
+ }
917
+ if (params.mode === "hash") {
918
+ return failure(
919
+ HardwareErrorCode.MethodNotSupported,
920
+ "Keystone always displays the full EIP-712 payload for on-device review \u2014 pre-hashed signing is not supported"
921
+ );
922
+ }
923
+ const signDataHex = Buffer.from(JSON.stringify(params.data), "utf8").toString("hex");
924
+ const path = normalizePath(params.path);
925
+ try {
926
+ return await this._jobQueue.enqueue(
927
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
928
+ async (signal) => {
929
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "evm", signal);
930
+ _KeystoneAdapter._throwIfAborted(signal);
931
+ const requestId = uuidv4();
932
+ const requestUr = this.urEngine.buildEthSignRequest({
933
+ requestId,
934
+ unsignedTxHex: signDataHex,
935
+ dataType: "typedData",
936
+ path,
937
+ xfp: record.masterFingerprint,
938
+ chainId: params.chainId
939
+ });
940
+ const responseUr = await this._resolveUr(record, requestUr, true);
941
+ _KeystoneAdapter._throwIfAborted(signal);
942
+ const sig = this.urEngine.parseEthSignature(responseUr);
943
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
944
+ return success({ signature: ensure0x(sig.r + sig.s + sig.v) });
945
+ }
946
+ );
947
+ } catch (err) {
948
+ return this._errorToFailure(err);
949
+ }
950
+ }
951
+ // ---------------------------------------------------------------------------
952
+ // BTC — PSBT signing and message signing only for now. Address/pubkey
953
+ // derivation needs script-type-aware xpub decoding (P2WPKH/P2TR/…) this
954
+ // phase doesn't wire in yet; structured-field tx signing needs host-side
955
+ // PSBT construction. Both are real, bounded follow-ups, not silent gaps.
956
+ // ---------------------------------------------------------------------------
957
+ async btcGetAddress(connectIdArg, deviceIdArg, paramsArg) {
958
+ const connectId = connectIdArg ?? void 0;
959
+ const deviceId = deviceIdArg ?? void 0;
960
+ const params = paramsArg;
961
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params");
962
+ if (!params.path)
963
+ return failure(HardwareErrorCode.InvalidParams, "btcGetAddress requires params.path");
964
+ const scriptType = btcScriptTypeFromPath(params.path);
965
+ if (!scriptType) {
966
+ return failure(
967
+ HardwareErrorCode.InvalidParams,
968
+ "btcGetAddress requires a path whose purpose is 44'/49'/84'/86' (P2PKH/P2SH-P2WPKH/P2WPKH/P2TR)"
969
+ );
970
+ }
971
+ if (scriptType === "p2tr") {
972
+ return this._unsupported(
973
+ "btcGetAddress",
974
+ "P2TR (purpose 86') needs an elliptic-curve library for BIP-341 tweaking, not yet wired in \u2014 44'/49'/84' work"
975
+ );
976
+ }
977
+ const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
978
+ if (!relativeDerivePath) {
979
+ return failure(
980
+ HardwareErrorCode.InvalidParams,
981
+ "btcGetAddress requires a full leaf path, e.g. m/84'/0'/0'/0/0"
982
+ );
983
+ }
984
+ try {
985
+ return await this._jobQueue.enqueue(
986
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
987
+ async (signal) => {
988
+ const { account } = await this._ensureAccountSynced(
989
+ connectId,
990
+ deviceId,
991
+ "btc",
992
+ accountPath,
993
+ signal
994
+ );
995
+ _KeystoneAdapter._throwIfAborted(signal);
996
+ if (!account.extendedPublicKey) {
997
+ throw createHwkError({
998
+ code: HardwareErrorCode.MethodNotSupported,
999
+ message: "Keystone did not return an extended public key for this account path"
1000
+ });
1001
+ }
1002
+ const address = this.urEngine.deriveBtcAddressFromXpub(
1003
+ account.extendedPublicKey,
1004
+ relativeDerivePath,
1005
+ scriptType
1006
+ );
1007
+ return success({ address, path: normalizePath(params.path) });
1008
+ }
1009
+ );
1010
+ } catch (err) {
1011
+ return this._errorToFailure(err);
1012
+ }
1013
+ }
1014
+ async btcGetPublicKey(_connectId, _deviceId, _params) {
1015
+ return this._unsupported(
1016
+ "btcGetPublicKey",
1017
+ "not yet wired \u2014 the underlying synced xpub/chainCode data already exists in the device table"
1018
+ );
1019
+ }
1020
+ async btcSignTransaction(_connectId, _deviceId, _params) {
1021
+ return this._unsupported(
1022
+ "btcSignTransaction",
1023
+ "use btcSignPsbt \u2014 structured input/output signing needs host-side PSBT construction, not yet wired in"
1024
+ );
1025
+ }
1026
+ async btcSignPsbt(connectIdArg, deviceIdArg, paramsArg) {
1027
+ const connectId = connectIdArg ?? void 0;
1028
+ const deviceId = deviceIdArg ?? void 0;
1029
+ const params = paramsArg;
1030
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params");
1031
+ if (!params.psbt)
1032
+ return failure(HardwareErrorCode.InvalidParams, "btcSignPsbt requires params.psbt");
1033
+ try {
1034
+ return await this._jobQueue.enqueue(
1035
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1036
+ async (signal) => {
1037
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "btc", signal);
1038
+ _KeystoneAdapter._throwIfAborted(signal);
1039
+ const requestUr = this.urEngine.buildBtcPsbtRequest(stripHex(params.psbt));
1040
+ const responseUr = await this._resolveUr(record, requestUr, true);
1041
+ _KeystoneAdapter._throwIfAborted(signal);
1042
+ const signedPsbt = this.urEngine.parseBtcPsbt(responseUr);
1043
+ return success({ signedPsbt });
1044
+ }
1045
+ );
1046
+ } catch (err) {
1047
+ return this._errorToFailure(err);
1048
+ }
1049
+ }
1050
+ async btcSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1051
+ const connectId = connectIdArg ?? void 0;
1052
+ const deviceId = deviceIdArg ?? void 0;
1053
+ const params = paramsArg;
1054
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "btcSignMessage requires params");
1055
+ if (!params.path || params.message === void 0) {
1056
+ return failure(
1057
+ HardwareErrorCode.InvalidParams,
1058
+ "btcSignMessage requires params.path and params.message"
1059
+ );
1060
+ }
1061
+ const messageHex = params.hex ? stripHex(params.message) : Buffer.from(params.message, "utf8").toString("hex");
1062
+ const path = normalizePath(params.path);
1063
+ try {
1064
+ return await this._jobQueue.enqueue(
1065
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1066
+ async (signal) => {
1067
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "btc", signal);
1068
+ _KeystoneAdapter._throwIfAborted(signal);
1069
+ const requestId = uuidv4();
1070
+ const requestUr = this.urEngine.buildBtcMessageSignRequest({
1071
+ requestId,
1072
+ messageHex,
1073
+ accounts: [{ path, xfp: record.masterFingerprint }]
1074
+ });
1075
+ const responseUr = await this._resolveUr(record, requestUr, true);
1076
+ _KeystoneAdapter._throwIfAborted(signal);
1077
+ const sig = this.urEngine.parseBtcSignature(responseUr);
1078
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
1079
+ return success({ signature: sig.signature });
1080
+ }
1081
+ );
1082
+ } catch (err) {
1083
+ return this._errorToFailure(err);
1084
+ }
1085
+ }
1086
+ async btcGetMasterFingerprint(connectIdArg, deviceIdArg) {
1087
+ const connectId = connectIdArg ?? void 0;
1088
+ const deviceId = deviceIdArg ?? void 0;
1089
+ try {
1090
+ return await this._jobQueue.enqueue(
1091
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1092
+ async (signal) => {
1093
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "btc", signal);
1094
+ return success({ masterFingerprint: record.masterFingerprint });
1095
+ }
1096
+ );
1097
+ } catch (err) {
1098
+ return this._errorToFailure(err);
1099
+ }
1100
+ }
1101
+ // ---------------------------------------------------------------------------
1102
+ // SOL
1103
+ // ---------------------------------------------------------------------------
1104
+ async solGetAddress(connectIdArg, deviceIdArg, paramsArg) {
1105
+ const connectId = connectIdArg ?? void 0;
1106
+ const deviceId = deviceIdArg ?? void 0;
1107
+ const params = paramsArg;
1108
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params");
1109
+ if (!params.path)
1110
+ return failure(HardwareErrorCode.InvalidParams, "solGetAddress requires params.path");
1111
+ const path = normalizePath(params.path);
1112
+ try {
1113
+ return await this._jobQueue.enqueue(
1114
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1115
+ async (signal) => {
1116
+ const { account } = await this._ensureAccountSynced(
1117
+ connectId,
1118
+ deviceId,
1119
+ "sol",
1120
+ path,
1121
+ signal
1122
+ );
1123
+ _KeystoneAdapter._throwIfAborted(signal);
1124
+ const address = bs58.encode(Buffer.from(account.publicKey, "hex"));
1125
+ return success({ address, path });
1126
+ }
1127
+ );
1128
+ } catch (err) {
1129
+ return this._errorToFailure(err);
1130
+ }
1131
+ }
1132
+ async solSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1133
+ const connectId = connectIdArg ?? void 0;
1134
+ const deviceId = deviceIdArg ?? void 0;
1135
+ const params = paramsArg;
1136
+ if (!params)
1137
+ return failure(HardwareErrorCode.InvalidParams, "solSignTransaction requires params");
1138
+ if (!params.path || !params.serializedTx) {
1139
+ return failure(
1140
+ HardwareErrorCode.InvalidParams,
1141
+ "solSignTransaction requires params.path and params.serializedTx"
1142
+ );
1143
+ }
1144
+ const path = normalizePath(params.path);
1145
+ try {
1146
+ return await this._jobQueue.enqueue(
1147
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1148
+ async (signal) => {
1149
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "sol", signal);
1150
+ _KeystoneAdapter._throwIfAborted(signal);
1151
+ const requestId = uuidv4();
1152
+ const requestUr = this.urEngine.buildSolSignRequest({
1153
+ requestId,
1154
+ unsignedPayloadHex: stripHex(params.serializedTx),
1155
+ dataType: "transaction",
1156
+ path,
1157
+ xfp: record.masterFingerprint
1158
+ });
1159
+ const responseUr = await this._resolveUr(record, requestUr, true);
1160
+ _KeystoneAdapter._throwIfAborted(signal);
1161
+ const sig = this.urEngine.parseSolSignature(responseUr);
1162
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
1163
+ return success({ signature: sig.signature });
1164
+ }
1165
+ );
1166
+ } catch (err) {
1167
+ return this._errorToFailure(err);
1168
+ }
1169
+ }
1170
+ async solSignMessage(connectIdArg, deviceIdArg, paramsArg) {
1171
+ const connectId = connectIdArg ?? void 0;
1172
+ const deviceId = deviceIdArg ?? void 0;
1173
+ const params = paramsArg;
1174
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "solSignMessage requires params");
1175
+ if (!params.path || !params.message) {
1176
+ return failure(
1177
+ HardwareErrorCode.InvalidParams,
1178
+ "solSignMessage requires params.path and params.message"
1179
+ );
1180
+ }
1181
+ const path = normalizePath(params.path);
1182
+ try {
1183
+ return await this._jobQueue.enqueue(
1184
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1185
+ async (signal) => {
1186
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "sol", signal);
1187
+ _KeystoneAdapter._throwIfAborted(signal);
1188
+ const requestId = uuidv4();
1189
+ const requestUr = this.urEngine.buildSolSignRequest({
1190
+ requestId,
1191
+ unsignedPayloadHex: stripHex(params.message),
1192
+ dataType: "message",
1193
+ path,
1194
+ xfp: record.masterFingerprint
1195
+ });
1196
+ const responseUr = await this._resolveUr(record, requestUr, true);
1197
+ _KeystoneAdapter._throwIfAborted(signal);
1198
+ const sig = this.urEngine.parseSolSignature(responseUr);
1199
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
1200
+ return success({ signature: sig.signature });
1201
+ }
1202
+ );
1203
+ } catch (err) {
1204
+ return this._errorToFailure(err);
1205
+ }
1206
+ }
1207
+ // ---------------------------------------------------------------------------
1208
+ // TRON — routed through `TronSignRequest`/`TronSignature` (see
1209
+ // urEngine/TronSignRequest.ts), a port of OneKey's own already-proven
1210
+ // production TRON QR-wallet implementation — NOT keystone-sdk's own
1211
+ // bundled `sdk.tron` module (different, protobuf-based protocol with
1212
+ // unverified response semantics).
1213
+ // ---------------------------------------------------------------------------
1214
+ async tronGetAddress(connectIdArg, deviceIdArg, paramsArg) {
1215
+ const connectId = connectIdArg ?? void 0;
1216
+ const deviceId = deviceIdArg ?? void 0;
1217
+ const params = paramsArg;
1218
+ if (!params) return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params");
1219
+ if (!params.path)
1220
+ return failure(HardwareErrorCode.InvalidParams, "tronGetAddress requires params.path");
1221
+ const { accountPath, relativeDerivePath } = splitAccountPath(params.path);
1222
+ if (!relativeDerivePath) {
1223
+ return failure(
1224
+ HardwareErrorCode.InvalidParams,
1225
+ "tronGetAddress requires a full leaf path, e.g. m/44'/195'/0'/0/0"
1226
+ );
1227
+ }
1228
+ try {
1229
+ return await this._jobQueue.enqueue(
1230
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1231
+ async (signal) => {
1232
+ const { account } = await this._ensureAccountSynced(
1233
+ connectId,
1234
+ deviceId,
1235
+ "tron",
1236
+ accountPath,
1237
+ signal
1238
+ );
1239
+ _KeystoneAdapter._throwIfAborted(signal);
1240
+ if (!account.extendedPublicKey) {
1241
+ throw createHwkError({
1242
+ code: HardwareErrorCode.MethodNotSupported,
1243
+ message: "Keystone did not return an extended public key for this account path"
1244
+ });
1245
+ }
1246
+ const address = this.urEngine.deriveTronAddressFromXpub(
1247
+ account.extendedPublicKey,
1248
+ relativeDerivePath
1249
+ );
1250
+ return success({ address, path: normalizePath(params.path) });
1251
+ }
1252
+ );
1253
+ } catch (err) {
1254
+ return this._errorToFailure(err);
1255
+ }
1256
+ }
1257
+ async tronSignTransaction(connectIdArg, deviceIdArg, paramsArg) {
1258
+ const connectId = connectIdArg ?? void 0;
1259
+ const deviceId = deviceIdArg ?? void 0;
1260
+ const params = paramsArg;
1261
+ if (!params)
1262
+ return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params");
1263
+ if (!params.path) {
1264
+ return failure(HardwareErrorCode.InvalidParams, "tronSignTransaction requires params.path");
1265
+ }
1266
+ if (!params.rawTxHex) {
1267
+ return failure(
1268
+ HardwareErrorCode.InvalidParams,
1269
+ "Keystone only signs a fully protobuf-serialized TRON transaction (params.rawTxHex) \u2014 the Trezor-style structured contract fields have no equivalent here"
1270
+ );
1271
+ }
1272
+ const rawTxHex = stripHex(params.rawTxHex);
1273
+ const path = normalizePath(params.path);
1274
+ try {
1275
+ return await this._jobQueue.enqueue(
1276
+ deviceId ?? connectId ?? COLD_START_JOB_LABEL,
1277
+ async (signal) => {
1278
+ const { record } = await this._ensureMfpKnown(connectId, deviceId, "tron", signal);
1279
+ _KeystoneAdapter._throwIfAborted(signal);
1280
+ const requestId = uuidv4();
1281
+ const requestUr = this.urEngine.buildTronSignRequest({
1282
+ requestId,
1283
+ rawTxHex,
1284
+ path,
1285
+ xfp: record.masterFingerprint
1286
+ });
1287
+ const responseUr = await this._resolveUr(record, requestUr, true);
1288
+ _KeystoneAdapter._throwIfAborted(signal);
1289
+ const sig = this.urEngine.parseTronSignature(responseUr);
1290
+ _KeystoneAdapter._assertRequestIdMatches(requestId, sig.requestId);
1291
+ return success({ signature: sig.signature });
1292
+ }
1293
+ );
1294
+ } catch (err) {
1295
+ return this._errorToFailure(err);
1296
+ }
1297
+ }
1298
+ async tronSignMessage(_connectId, _deviceId, _params) {
1299
+ return this._unsupported(
1300
+ "tronSignMessage",
1301
+ "Keystone TRON message signing needs signType V1-vs-V2 verified against real hardware first \u2014 not wired in"
1302
+ );
1303
+ }
1304
+ // ---------------------------------------------------------------------------
1305
+ // Internals
1306
+ // ---------------------------------------------------------------------------
1307
+ _mfpFromConnectId(connectId) {
1308
+ return connectId?.startsWith(QR_CONNECT_ID_PREFIX) ? connectId.slice(QR_CONNECT_ID_PREFIX.length) : void 0;
1309
+ }
1310
+ /**
1311
+ * Handles both connectId shapes a caller might hand back: the QR-style
1312
+ * `keystone-qr:<mfp>` prefix, and a bare mfp — which is exactly what a
1313
+ * USB session's `sessionId`/`connectId` is (see `KeystoneUsbConnectorBase`
1314
+ * and `_connectUsb`).
1315
+ */
1316
+ _findByConnectId(connectId) {
1317
+ const mfp = this._mfpFromConnectId(connectId) ?? connectId?.toLowerCase();
1318
+ return mfp ? this._devices.get(mfp) : void 0;
1319
+ }
1320
+ /**
1321
+ * Folds a parsed account-response UR into the device table. `viaUsb`
1322
+ * (defaults false) says which channel actually carried this round trip —
1323
+ * `_resolveUr` routes a KeyDerivation sync over USB when the target record
1324
+ * already has a live session, so this must NOT unconditionally mark
1325
+ * `qrSynced`, or a USB-only wallet would wrongly survive a later USB
1326
+ * disconnect as a "QR-synced, demote to QR-only" entry instead of being
1327
+ * dropped outright (see `disconnectDevice`).
1328
+ */
1329
+ _upsertDeviceRecord(parsed, options) {
1330
+ const mfp = parsed.masterFingerprint;
1331
+ let record = this._devices.get(mfp);
1332
+ const isNew = !record;
1333
+ if (!record) {
1334
+ record = createDeviceRecord(mfp);
1335
+ this._devices.set(mfp, record);
1336
+ }
1337
+ record.model = parsed.device ?? record.model;
1338
+ record.deviceVersion = parsed.deviceVersion ?? record.deviceVersion;
1339
+ if (!options?.viaUsb) record.qrSynced = true;
1340
+ const info = toDeviceInfo(record);
1341
+ const eventType = isNew ? DEVICE.CONNECT : DEVICE.CHANGED;
1342
+ this.emitter.emit(eventType, { type: eventType, payload: info });
1343
+ return record;
1344
+ }
1345
+ /**
1346
+ * Opens+claims whatever Keystone the USB connector currently has
1347
+ * permission for, learns its mfp via `getAppConfig`, and merges it into
1348
+ * the device table by that mfp — a QR-synced entry becomes
1349
+ * `{qr, usb}`-capable in place (one `device-changed`, not a second
1350
+ * `device-connect`); a wallet never seen before becomes a new USB-only
1351
+ * entry. See §4.2 of the design doc.
1352
+ */
1353
+ async _connectUsb() {
1354
+ if (!this._usbConnector) {
1355
+ return failure(
1356
+ HardwareErrorCode.TransportNotAvailable,
1357
+ "No USB connector configured for this Keystone adapter"
1358
+ );
1359
+ }
1360
+ try {
1361
+ const session = await this._usbConnector.connect();
1362
+ const mfp = session.deviceInfo.deviceId.toLowerCase();
1363
+ let record = this._devices.get(mfp);
1364
+ const isNew = !record;
1365
+ if (!record) {
1366
+ record = createDeviceRecord(mfp);
1367
+ this._devices.set(mfp, record);
1368
+ }
1369
+ record.model = session.deviceInfo.modelName ?? session.deviceInfo.model ?? record.model;
1370
+ record.deviceVersion = session.deviceInfo.firmwareVersion ?? record.deviceVersion;
1371
+ record.usbSessionId = session.sessionId;
1372
+ const info = toDeviceInfo(record);
1373
+ const eventType = isNew ? DEVICE.CONNECT : DEVICE.CHANGED;
1374
+ this.emitter.emit(eventType, { type: eventType, payload: info });
1375
+ return success(info);
1376
+ } catch (err) {
1377
+ return this._errorToFailure(err);
1378
+ }
1379
+ }
1380
+ /**
1381
+ * The one place that decides QR vs. USB for a UR round trip and carries it
1382
+ * out. `record` is the (possibly not-yet-existing, for a true cold start)
1383
+ * device row for the target wallet — USB is only used when `record`
1384
+ * already has a live `usbSessionId` (a session comes from an explicit
1385
+ * `connectDevice()`, never conjured mid-call — see the class doc). A
1386
+ * `switchTransport('qr')` pin forces QR even for a USB-attached wallet;
1387
+ * `switchTransport('usb')` on a wallet with no live USB session fails
1388
+ * closed rather than silently falling back to QR.
1389
+ */
1390
+ async _resolveUr(record, requestUr, animated) {
1391
+ const wantUsb = this._forcedTransport === "usb" || this._forcedTransport !== "qr" && Boolean(record?.usbSessionId);
1392
+ if (wantUsb) {
1393
+ if (!record?.usbSessionId || !this._usbConnector) {
1394
+ throw createHwkError({
1395
+ code: HardwareErrorCode.TransportNotAvailable,
1396
+ message: "USB channel is not connected for this Keystone wallet"
1397
+ });
1398
+ }
1399
+ const result = await this._usbConnector.call(record.usbSessionId, "resolveUr", requestUr);
1400
+ if (!result.success) throw rehydrateConnectorError(result.error);
1401
+ return result.payload;
1402
+ }
1403
+ const displayDevice = record ? toDeviceInfo(record) : placeholderDeviceInfo();
1404
+ return this._requestQrDisplayAndAwaitResponse(displayDevice, { ...requestUr, animated });
1405
+ }
1406
+ /**
1407
+ * Resolve (syncing over QR if needed) the account cached for `hwkChain` at
1408
+ * `syncPath`. Drives the "implicit account sync, then the real request" two
1409
+ * hop flow the first time a wallet/path pair is seen; a cache hit skips
1410
+ * straight to the caller's own round trip.
1411
+ */
1412
+ async _ensureAccountSynced(connectId, deviceId, hwkChain, syncPath, signal) {
1413
+ const wantMfp = deviceId ? deviceId.toLowerCase() : this._mfpFromConnectId(connectId ?? "");
1414
+ const key = accountKey(hwkChain, syncPath);
1415
+ const existingRecord = wantMfp ? this._devices.get(wantMfp) : void 0;
1416
+ const cached = existingRecord?.accounts.get(key);
1417
+ if (existingRecord && cached) {
1418
+ return { record: existingRecord, account: cached };
1419
+ }
1420
+ const requestUr = this.urEngine.buildKeyDerivationRequest({
1421
+ schemas: [{ path: syncPath, curve: hwkChain === "sol" ? "ed25519" : "secp256k1" }],
1422
+ origin: this._origin
1423
+ });
1424
+ const responseUr = await this._resolveUr(existingRecord, requestUr, false);
1425
+ _KeystoneAdapter._throwIfAborted(signal);
1426
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1427
+ if (wantMfp && parsed.masterFingerprint !== wantMfp) {
1428
+ throw createHwkError({
1429
+ code: HardwareErrorCode.DeviceMismatch,
1430
+ message: `Scanned Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested device (${wantMfp})`
1431
+ });
1432
+ }
1433
+ const record = this._upsertDeviceRecord(parsed, {
1434
+ viaUsb: Boolean(existingRecord?.usbSessionId)
1435
+ });
1436
+ const account = parsed.accounts.find((a) => normalizePath(a.path) === syncPath);
1437
+ if (!account) {
1438
+ throw createHwkError({
1439
+ code: HardwareErrorCode.DeviceMismatch,
1440
+ message: `Keystone did not return the requested derivation path (${syncPath})`
1441
+ });
1442
+ }
1443
+ const entry = { ...account, hwkChain };
1444
+ record.accounts.set(key, entry);
1445
+ return { record, account: entry };
1446
+ }
1447
+ /**
1448
+ * Like `_ensureAccountSynced`, but for operations (PSBT signing, master
1449
+ * fingerprint) that only need to know WHICH wallet is attached, not a
1450
+ * specific cached path. Syncs the account-level path for `chain` as a
1451
+ * throwaway probe when the mfp isn't already known.
1452
+ *
1453
+ * `CHAIN_FINGERPRINT_PATHS[chain]` is a 5-segment LEAF path for `evm`
1454
+ * (`m/44'/60'/0'/0/0`) — sending that verbatim as a KeyDerivation request
1455
+ * asks Keystone for a non-standard path. Keystone's own docs
1456
+ * (dev.keyst.one's multichain KeyDerivation example) show the ETH
1457
+ * account-level path as `m/44'/60'/0'` (3 segments), same as what
1458
+ * `DEFAULT_IMPORT_SCHEMAS`/`_ensureAccountSynced` already request — so
1459
+ * truncate through `splitAccountPath` here too instead of using the raw
1460
+ * fingerprint leaf path. `btc`/`sol` are already 3-segment account paths
1461
+ * and pass through unchanged.
1462
+ */
1463
+ async _ensureMfpKnown(connectId, deviceId, chain, signal) {
1464
+ const wantMfp = deviceId ? deviceId.toLowerCase() : this._mfpFromConnectId(connectId ?? "");
1465
+ const existing = wantMfp ? this._devices.get(wantMfp) : void 0;
1466
+ if (existing) return { record: existing };
1467
+ const { accountPath } = splitAccountPath(CHAIN_FINGERPRINT_PATHS[chain]);
1468
+ const requestUr = this.urEngine.buildKeyDerivationRequest({
1469
+ schemas: [{ path: accountPath, curve: chain === "sol" ? "ed25519" : "secp256k1" }],
1470
+ origin: this._origin
1471
+ });
1472
+ const responseUr = await this._resolveUr(void 0, requestUr, false);
1473
+ _KeystoneAdapter._throwIfAborted(signal);
1474
+ const parsed = this.urEngine.parseAccountResponse(responseUr);
1475
+ if (wantMfp && parsed.masterFingerprint !== wantMfp) {
1476
+ throw createHwkError({
1477
+ code: HardwareErrorCode.DeviceMismatch,
1478
+ message: `Scanned Keystone wallet (mfp ${parsed.masterFingerprint}) does not match the requested device (${wantMfp})`
1479
+ });
1480
+ }
1481
+ return { record: this._upsertDeviceRecord(parsed) };
1482
+ }
1483
+ async _requestQrDisplayAndAwaitResponse(device, data) {
1484
+ const waitPromise = this._uiRegistry.wait(
1485
+ UI_REQUEST.REQUEST_QR_DISPLAY,
1486
+ { timeoutMs: this._qrTimeoutMs }
1487
+ );
1488
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_DISPLAY, {
1489
+ type: UI_REQUEST.REQUEST_QR_DISPLAY,
1490
+ payload: { device, data }
1491
+ });
1492
+ const response = await waitPromise;
1493
+ return { urType: response.urType, urData: response.urData };
1494
+ }
1495
+ async _requestQrScanAndAwaitResponse(device) {
1496
+ const waitPromise = this._uiRegistry.wait(
1497
+ UI_REQUEST.REQUEST_QR_SCAN,
1498
+ { timeoutMs: this._qrTimeoutMs }
1499
+ );
1500
+ this.emitter.emit(UI_REQUEST.REQUEST_QR_SCAN, {
1501
+ type: UI_REQUEST.REQUEST_QR_SCAN,
1502
+ payload: { device }
1503
+ });
1504
+ const response = await waitPromise;
1505
+ return { urType: response.urType, urData: response.urData };
1506
+ }
1507
+ static _throwIfAborted(signal) {
1508
+ if (signal.aborted) {
1509
+ throw signal.reason instanceof Error ? signal.reason : new Error("Operation aborted");
1510
+ }
1511
+ }
1512
+ static _assertRequestIdMatches(expected, actual) {
1513
+ if (actual && actual.toLowerCase() !== expected.toLowerCase()) {
1514
+ throw createHwkError({
1515
+ code: HardwareErrorCode.DeviceMismatch,
1516
+ message: "Keystone response requestId does not match the pending request \u2014 discarding a stale or unrelated scan"
1517
+ });
1518
+ }
1519
+ }
1520
+ _unsupported(method, reason) {
1521
+ return Promise.resolve(
1522
+ failure(
1523
+ HardwareErrorCode.MethodNotSupported,
1524
+ `KeystoneAdapter.${method} is not implemented yet: ${reason}`
1525
+ )
1526
+ );
1527
+ }
1528
+ _errorToFailure(err) {
1529
+ if (err && typeof err === "object") {
1530
+ const e = err;
1531
+ if (typeof e.code === "number") {
1532
+ return failure(e.code, e.message ?? "Unknown error", e.params);
1533
+ }
1534
+ if (e._tag === UI_REQUEST_CANCELLED_TAG || e._tag === UI_REQUEST_PREEMPTED_TAG) {
1535
+ return failure(
1536
+ HardwareErrorCode.UserAborted,
1537
+ e.message ?? "Keystone QR interaction was cancelled"
1538
+ );
1539
+ }
1540
+ if (e._tag === UI_REQUEST_TIMEOUT_TAG) {
1541
+ return failure(
1542
+ HardwareErrorCode.OperationTimeout,
1543
+ e.message ?? "Keystone QR interaction timed out"
1544
+ );
1545
+ }
1546
+ }
1547
+ const message = err instanceof Error ? err.message : String(err);
1548
+ const params = err instanceof Error && err.stack ? { stack: err.stack } : void 0;
1549
+ return failure(HardwareErrorCode.UnknownError, message, params);
1550
+ }
1551
+ };
1552
+ export {
1553
+ KeystoneAdapter,
1554
+ KeystoneUrEngine,
1555
+ QR_CONNECT_ID_PREFIX,
1556
+ accountKey,
1557
+ btcScriptTypeFromPath,
1558
+ createDeviceRecord,
1559
+ normalizePath,
1560
+ placeholderDeviceInfo,
1561
+ qrConnectId,
1562
+ splitAccountPath,
1563
+ toDeviceInfo
1564
+ };
1565
+ //# sourceMappingURL=index.mjs.map