@neuraiproject/neurai-sign-esp32 0.3.1 → 0.3.2

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.cjs CHANGED
@@ -48,8 +48,7 @@ $parcel$export(module.exports, "neuraiLegacyTestnet", () => $8eddb774c9d38ccb$ex
48
48
  *
49
49
  * Handles USB Serial connection, JSON command/response protocol,
50
50
  * and line-based buffering matching the NeuraiHW firmware protocol.
51
- */ // Default USB filters for ESP32 devices
52
- const $a48f33fba55d0d0b$var$DEFAULT_FILTERS = [
51
+ */ const $a48f33fba55d0d0b$var$DEFAULT_FILTERS = [
53
52
  {
54
53
  usbVendorId: 0x303a,
55
54
  usbProductId: 0x1001
@@ -90,15 +89,10 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
90
89
  this.baudRate = options?.baudRate ?? $a48f33fba55d0d0b$var$DEFAULT_BAUD_RATE;
91
90
  this.filters = options?.filters ?? $a48f33fba55d0d0b$var$DEFAULT_FILTERS;
92
91
  }
93
- /**
94
- * Check if Web Serial API is available.
95
- */ static isSupported() {
92
+ static isSupported() {
96
93
  return typeof navigator !== "undefined" && "serial" in navigator;
97
94
  }
98
- /**
99
- * Open a serial connection to the ESP32.
100
- * Triggers browser port selection dialog.
101
- */ async open() {
95
+ async open() {
102
96
  if (!$a48f33fba55d0d0b$export$f93edba7156cc57b.isSupported()) throw new Error("Web Serial API not supported. Use Chrome, Edge, or Opera.");
103
97
  this.port = await navigator.serial.requestPort({
104
98
  filters: this.filters
@@ -111,24 +105,18 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
111
105
  flowControl: "none",
112
106
  bufferSize: 8192
113
107
  });
114
- // Set up readable stream (text decoding)
115
108
  const decoder = new TextDecoderStream();
116
109
  this.readableStreamClosed = this.port.readable.pipeTo(decoder.writable);
117
110
  this.reader = decoder.readable.getReader();
118
- // Set up writable stream (text encoding)
119
111
  const encoder = new TextEncoderStream();
120
112
  this.writableStreamClosed = encoder.readable.pipeTo(this.port.writable);
121
113
  this.writer = encoder.writable.getWriter();
122
- // Start background read loop
123
114
  this.isReading = true;
124
115
  this.readLoop();
125
- // Give the ESP32 CDC port time to settle after connect/re-enumeration.
126
116
  await this.delay(1200);
127
117
  this.responseQueue = [];
128
118
  }
129
- /**
130
- * Close the serial connection.
131
- */ async close() {
119
+ async close() {
132
120
  this.isReading = false;
133
121
  if (this.reader) {
134
122
  await this.reader.cancel();
@@ -146,23 +134,12 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
146
134
  }
147
135
  this.responseQueue = [];
148
136
  }
149
- /**
150
- * Whether the serial port is currently connected.
151
- */ get connected() {
137
+ get connected() {
152
138
  return this.port !== null && this.writer !== null;
153
139
  }
154
- /**
155
- * Send a JSON command to the device and wait for a JSON response.
156
- *
157
- * @param command - The command object (e.g. { action: "info" })
158
- * @param timeoutMs - Response timeout in milliseconds (default: 65000 for sign operations)
159
- * @returns The parsed device response
160
- */ async sendCommand(command, timeoutMs = 65000) {
140
+ async sendCommand(command, timeoutMs = 65000) {
161
141
  if (!this.writer) throw new Error("Serial port not connected");
162
- // Clear stale responses
163
142
  this.responseQueue = [];
164
- // Send JSON in small chunks, then newline to trigger processing.
165
- // The ESP32 CDC serial buffer can lose data if sent too fast in one write.
166
143
  const json = JSON.stringify(command);
167
144
  console.debug("[NeuraiESP32 Serial] Sending command", {
168
145
  action: command.action,
@@ -172,15 +149,11 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
172
149
  await this.writeChunked(json);
173
150
  await this.writer.ready;
174
151
  await this.writer.write("\n");
175
- // Wait for response
176
152
  const response = await this.waitForResponse(timeoutMs);
177
153
  if (!response) throw new Error("Device response timeout");
178
154
  return response;
179
155
  }
180
- /**
181
- * Send a command and wait, skipping intermediate "processing" status messages.
182
- * Useful for sign_psbt which sends a processing ACK before the actual response.
183
- */ async sendCommandFinal(command, timeoutMs = 65000) {
156
+ async sendCommandFinal(command, timeoutMs = 65000) {
184
157
  if (!this.writer) throw new Error("Serial port not connected");
185
158
  this.responseQueue = [];
186
159
  const json = JSON.stringify(command);
@@ -192,31 +165,26 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
192
165
  await this.writeChunked(json);
193
166
  await this.writer.ready;
194
167
  await this.writer.write("\n");
195
- // Wait for a non-processing response
196
168
  const startTime = Date.now();
197
169
  while(Date.now() - startTime < timeoutMs){
198
170
  const response = await this.waitForResponse(timeoutMs - (Date.now() - startTime));
199
171
  if (!response) throw new Error("Device response timeout");
200
- // Skip intermediate "processing" status
201
172
  if (response.status === "processing") continue;
202
173
  return response;
203
174
  }
204
175
  throw new Error("Device response timeout");
205
176
  }
206
- // ─── Private ──────────────────────────────────────────────────────────────
207
177
  async readLoop() {
208
178
  let buffer = "";
209
179
  while(this.isReading && this.reader)try {
210
180
  const { value: value, done: done } = await this.reader.read();
211
181
  if (done) break;
212
182
  buffer += value;
213
- // Process complete lines
214
183
  const lines = buffer.split("\n");
215
- buffer = lines.pop() ?? ""; // Keep incomplete line in buffer
184
+ buffer = lines.pop() ?? "";
216
185
  for (const rawLine of lines){
217
186
  const line = rawLine.trim().replace(/\r/g, "");
218
187
  if (line.length === 0) continue;
219
- // Try to parse as JSON response
220
188
  if (line.startsWith("{")) try {
221
189
  const data = JSON.parse(line);
222
190
  console.debug("[NeuraiESP32 Serial] JSON line received", data);
@@ -253,20 +221,53 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
253
221
  check();
254
222
  });
255
223
  }
256
- /**
257
- * Write data in small chunks with pauses between them.
258
- *
259
- * The ESP32 CDC serial buffer can lose data when the host sends a large
260
- * payload in a single write. Splitting into 32-byte chunks with a 4 ms
261
- * pause gives the firmware time to drain its receive buffer.
262
- */ async writeChunked(data, chunkSize = 32, pauseMs = 4) {
224
+ async writeChunked(data, chunkSize = 256, pauseMs = 8) {
263
225
  if (!this.writer) throw new Error("Serial port not connected");
264
- for(let offset = 0; offset < data.length; offset += chunkSize){
226
+ const totalChunks = Math.ceil(data.length / chunkSize);
227
+ const startedAt = Date.now();
228
+ let totalReadyMs = 0;
229
+ let totalWriteMs = 0;
230
+ let totalPauseMs = 0;
231
+ console.debug("[NeuraiESP32 Serial][writeChunked] start", {
232
+ totalBytes: data.length,
233
+ chunkSize: chunkSize,
234
+ pauseMs: pauseMs,
235
+ totalChunks: totalChunks
236
+ });
237
+ for(let offset = 0, chunkIndex = 0; offset < data.length; offset += chunkSize, chunkIndex += 1){
265
238
  const chunk = data.slice(offset, offset + chunkSize);
239
+ const readyStartedAt = Date.now();
266
240
  await this.writer.ready;
241
+ const readyMs = Date.now() - readyStartedAt;
242
+ totalReadyMs += readyMs;
243
+ const writeStartedAt = Date.now();
267
244
  await this.writer.write(chunk);
268
- if (offset + chunkSize < data.length) await this.delay(pauseMs);
245
+ const writeMs = Date.now() - writeStartedAt;
246
+ totalWriteMs += writeMs;
247
+ let actualPauseMs = 0;
248
+ if (pauseMs > 0 && offset + chunkSize < data.length) {
249
+ const pauseStartedAt = Date.now();
250
+ await this.delay(pauseMs);
251
+ actualPauseMs = Date.now() - pauseStartedAt;
252
+ totalPauseMs += actualPauseMs;
253
+ }
254
+ console.debug("[NeuraiESP32 Serial][writeChunked] chunk", {
255
+ chunkIndex: chunkIndex + 1,
256
+ totalChunks: totalChunks,
257
+ chunkBytes: chunk.length,
258
+ readyMs: readyMs,
259
+ writeMs: writeMs,
260
+ pauseMs: actualPauseMs
261
+ });
269
262
  }
263
+ console.debug("[NeuraiESP32 Serial][writeChunked] complete", {
264
+ totalBytes: data.length,
265
+ totalChunks: totalChunks,
266
+ totalMs: Date.now() - startedAt,
267
+ totalReadyMs: totalReadyMs,
268
+ totalWriteMs: totalWriteMs,
269
+ totalPauseMs: totalPauseMs
270
+ });
270
271
  }
271
272
  delay(ms) {
272
273
  return new Promise((resolve)=>setTimeout(resolve, ms));
@@ -348,7 +349,7 @@ function $8eddb774c9d38ccb$export$7de4970ebfd8206d(network) {
348
349
  }
349
350
 
350
351
 
351
- const $5da7d5b3a851268c$var$DEFAULT_FEE_RATE = 1024; // sat/byte
352
+ const $5da7d5b3a851268c$var$DEFAULT_FEE_RATE = 1024;
352
353
  const $5da7d5b3a851268c$var$TX_OVERHEAD = 10;
353
354
  const $5da7d5b3a851268c$var$INPUT_SIZE = 148;
354
355
  const $5da7d5b3a851268c$var$OUTPUT_SIZE = 34;
@@ -359,6 +360,33 @@ function $5da7d5b3a851268c$var$parseMasterFingerprint(hex) {
359
360
  if (hex.length !== 8) throw new Error(`Invalid master fingerprint: expected 8 hex chars, got ${hex.length}`);
360
361
  return (0, $8zHUo$buffer.Buffer).from(hex, "hex");
361
362
  }
363
+ function $5da7d5b3a851268c$var$getSignatureHashType(signature) {
364
+ return signature[signature.length - 1] ?? 1;
365
+ }
366
+ function $5da7d5b3a851268c$var$checkPartialSigSighashes(input) {
367
+ if (!input.sighashType || !input.partialSig) return;
368
+ let normalizedSighashType = input.sighashType;
369
+ input.partialSig.forEach((pSig)=>{
370
+ const hashType = $5da7d5b3a851268c$var$getSignatureHashType(pSig.signature);
371
+ if (normalizedSighashType !== hashType) {
372
+ console.warn("[NeuraiSignESP32] Adjusting input sighashType to match returned signature", {
373
+ previousSighashType: normalizedSighashType,
374
+ returnedHashType: hashType
375
+ });
376
+ normalizedSighashType = hashType;
377
+ }
378
+ });
379
+ input.sighashType = normalizedSighashType;
380
+ }
381
+ function $5da7d5b3a851268c$var$nonWitnessUtxoTxFromCache(cache, input, inputIndex) {
382
+ const existing = cache.__NON_WITNESS_UTXO_TX_CACHE?.[inputIndex];
383
+ if (existing) return existing;
384
+ if (!input.nonWitnessUtxo) throw new Error(`Missing nonWitnessUtxo for input #${inputIndex}`);
385
+ const tx = $8zHUo$bitcoinjslib.Transaction.fromBuffer(input.nonWitnessUtxo);
386
+ cache.__NON_WITNESS_UTXO_TX_CACHE ??= {};
387
+ cache.__NON_WITNESS_UTXO_TX_CACHE[inputIndex] = tx;
388
+ return tx;
389
+ }
362
390
  function $5da7d5b3a851268c$export$236ea1e009011592(options) {
363
391
  const { network: network, utxos: utxos, outputs: outputs, changeAddress: changeAddress, pubkey: pubkey, masterFingerprint: masterFingerprint, derivationPath: derivationPath, feeRate: feeRate = $5da7d5b3a851268c$var$DEFAULT_FEE_RATE } = options;
364
392
  if (utxos.length === 0) throw new Error("No UTXOs provided");
@@ -409,19 +437,21 @@ function $5da7d5b3a851268c$export$e0e3d6f226ea0b0a(options) {
409
437
  const input = tx.ins[index];
410
438
  const metadata = options.inputs[index];
411
439
  if (!metadata) throw new Error(`Missing input metadata for input #${index}`);
412
- psbt.addInput({
440
+ const inputData = {
413
441
  hash: metadata.txid,
414
442
  index: metadata.vout,
415
443
  sequence: metadata.sequence ?? input.sequence,
416
- nonWitnessUtxo: (0, $8zHUo$buffer.Buffer).from(metadata.rawTxHex, "hex"),
417
- bip32Derivation: [
418
- {
419
- masterFingerprint: $5da7d5b3a851268c$var$parseMasterFingerprint(metadata.masterFingerprint),
420
- path: metadata.derivationPath,
421
- pubkey: (0, $8zHUo$buffer.Buffer).from(metadata.pubkey, "hex")
422
- }
423
- ]
424
- });
444
+ nonWitnessUtxo: (0, $8zHUo$buffer.Buffer).from(metadata.rawTxHex, "hex")
445
+ };
446
+ if (metadata.masterFingerprint && metadata.derivationPath && metadata.pubkey) inputData.bip32Derivation = [
447
+ {
448
+ masterFingerprint: $5da7d5b3a851268c$var$parseMasterFingerprint(metadata.masterFingerprint),
449
+ path: metadata.derivationPath,
450
+ pubkey: (0, $8zHUo$buffer.Buffer).from(metadata.pubkey, "hex")
451
+ }
452
+ ];
453
+ if (metadata.sighashType !== undefined) inputData.sighashType = metadata.sighashType;
454
+ psbt.addInput(inputData);
425
455
  }
426
456
  for (const output of tx.outs)psbt.addOutput({
427
457
  script: (0, $8zHUo$buffer.Buffer).from(output.script),
@@ -433,8 +463,8 @@ function $5da7d5b3a851268c$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
433
463
  const psbt = $8zHUo$bitcoinjslib.Psbt.fromBase64(signedPsbtBase64, {
434
464
  network: (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network)
435
465
  });
436
- psbt.finalizeAllInputs();
437
- const tx = psbt.extractTransaction();
466
+ $5da7d5b3a851268c$var$finalizeNeuraiP2pkhInputs(psbt, true);
467
+ const tx = $5da7d5b3a851268c$var$extractFinalizableTransaction(psbt, true);
438
468
  return {
439
469
  txHex: tx.toHex(),
440
470
  txId: tx.getId()
@@ -464,12 +494,9 @@ function $5da7d5b3a851268c$export$3a31c64c43aacd3(originalPsbtBase64, signedPsbt
464
494
  });
465
495
  });
466
496
  }
467
- try {
468
- psbt.finalizeAllInputs();
469
- } catch {
470
- $5da7d5b3a851268c$var$finalizeLegacyP2pkhInputs(psbt);
471
- }
472
- const tx = psbt.extractTransaction(true);
497
+ psbt.data.inputs.forEach((input)=>$5da7d5b3a851268c$var$checkPartialSigSighashes(input));
498
+ $5da7d5b3a851268c$var$finalizeNeuraiP2pkhInputs(psbt, false);
499
+ const tx = $5da7d5b3a851268c$var$extractFinalizableTransaction(psbt, false);
473
500
  return {
474
501
  txHex: tx.toHex(),
475
502
  txId: tx.getId()
@@ -543,17 +570,27 @@ function $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset) {
543
570
  }
544
571
  throw new Error("PSBT values larger than 32 bits are not supported");
545
572
  }
546
- function $5da7d5b3a851268c$var$finalizeLegacyP2pkhInputs(psbt) {
573
+ function $5da7d5b3a851268c$var$finalizeNeuraiP2pkhInputs(psbt, requireAllInputs) {
574
+ let finalizedCount = 0;
547
575
  for(let index = 0; index < psbt.inputCount; index += 1){
548
576
  const input = psbt.data.inputs[index];
549
- if (input.finalScriptSig || input.finalScriptWitness) continue;
577
+ if (input.finalScriptSig || input.finalScriptWitness) {
578
+ finalizedCount += 1;
579
+ continue;
580
+ }
550
581
  const partialSig = input.partialSig?.[0];
551
582
  const nonWitnessUtxo = input.nonWitnessUtxo;
552
583
  const txInput = psbt.txInputs[index];
553
- if (!partialSig || !nonWitnessUtxo || !txInput) throw new Error(`Missing data to finalize input #${index}`);
584
+ if (!partialSig || !nonWitnessUtxo || !txInput) {
585
+ if (requireAllInputs) throw new Error(`Missing data to finalize input #${index}`);
586
+ continue;
587
+ }
554
588
  const prevTx = $8zHUo$bitcoinjslib.Transaction.fromBuffer(nonWitnessUtxo);
555
589
  const prevOut = prevTx.outs[txInput.index];
556
- if (!prevOut) throw new Error(`Missing prevout to finalize input #${index}`);
590
+ if (!prevOut) {
591
+ if (requireAllInputs) throw new Error(`Missing prevout to finalize input #${index}`);
592
+ continue;
593
+ }
557
594
  psbt.finalizeInput(index, ()=>({
558
595
  finalScriptSig: $8zHUo$bitcoinjslib.script.compile([
559
596
  partialSig.signature,
@@ -561,7 +598,62 @@ function $5da7d5b3a851268c$var$finalizeLegacyP2pkhInputs(psbt) {
561
598
  ]),
562
599
  finalScriptWitness: undefined
563
600
  }));
601
+ finalizedCount += 1;
564
602
  }
603
+ if (requireAllInputs && finalizedCount !== psbt.inputCount) throw new Error(`Not all inputs were finalized (${finalizedCount}/${psbt.inputCount})`);
604
+ }
605
+ function $5da7d5b3a851268c$var$extractFinalizableTransaction(psbt, requireAllInputs) {
606
+ const cache = psbt.__CACHE;
607
+ const baseTx = cache?.__TX;
608
+ if (!baseTx || !cache) {
609
+ if (requireAllInputs) return psbt.extractTransaction(true);
610
+ return psbt.extractTransaction();
611
+ }
612
+ const tx = baseTx.clone();
613
+ $5da7d5b3a851268c$var$inputFinalizeGetAmtsPartial(psbt.data.inputs, tx, cache, requireAllInputs);
614
+ return tx;
615
+ }
616
+ function $5da7d5b3a851268c$var$inputFinalizeGetAmtsPartial(inputs, tx, cache, requireAllInputs) {
617
+ let inputAmount = 0n;
618
+ inputs.forEach((input, idx)=>{
619
+ if (input.finalScriptSig) tx.ins[idx].script = input.finalScriptSig;
620
+ if (input.finalScriptWitness) tx.ins[idx].witness = $5da7d5b3a851268c$var$scriptWitnessToWitnessStack(input.finalScriptWitness);
621
+ if (input.witnessUtxo) {
622
+ inputAmount += input.witnessUtxo.value;
623
+ return;
624
+ }
625
+ if (input.nonWitnessUtxo) {
626
+ const nwTx = $5da7d5b3a851268c$var$nonWitnessUtxoTxFromCache(cache, input, idx);
627
+ const vout = tx.ins[idx].index;
628
+ const out = nwTx.outs[vout];
629
+ if (!out) {
630
+ if (requireAllInputs) throw new Error(`Missing prevout amount for input #${idx}`);
631
+ return;
632
+ }
633
+ inputAmount += out.value;
634
+ return;
635
+ }
636
+ if (requireAllInputs) throw new Error(`Missing UTXO data for input #${idx}`);
637
+ });
638
+ const outputAmount = tx.outs.reduce((total, o)=>total + o.value, 0n);
639
+ const fee = inputAmount - outputAmount;
640
+ cache.__FEE = fee >= 0n ? fee : 0n;
641
+ cache.__EXTRACTED_TX = tx;
642
+ cache.__FEE_RATE = fee > 0n ? Math.floor(Number(fee / BigInt(tx.virtualSize()))) : 0;
643
+ }
644
+ function $5da7d5b3a851268c$var$scriptWitnessToWitnessStack(finalScriptWitness) {
645
+ const buffer = (0, $8zHUo$buffer.Buffer).from(finalScriptWitness);
646
+ let offset = 0;
647
+ const count = $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset);
648
+ offset += count.size;
649
+ const stack = [];
650
+ for(let i = 0; i < count.value; i += 1){
651
+ const itemLen = $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset);
652
+ offset += itemLen.size;
653
+ stack.push(buffer.subarray(offset, offset + itemLen.value));
654
+ offset += itemLen.value;
655
+ }
656
+ return stack;
565
657
  }
566
658
 
567
659
 
@@ -570,39 +662,23 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
570
662
  this.deviceInfo = null;
571
663
  this.serial = new (0, $a48f33fba55d0d0b$export$f93edba7156cc57b)(options);
572
664
  }
573
- /**
574
- * Check if Web Serial API is supported in this browser.
575
- */ static isSupported() {
665
+ static isSupported() {
576
666
  return (0, $a48f33fba55d0d0b$export$f93edba7156cc57b).isSupported();
577
667
  }
578
- /**
579
- * Whether the device is currently connected.
580
- */ get connected() {
668
+ get connected() {
581
669
  return this.serial.connected;
582
670
  }
583
- /**
584
- * Cached device info from the last getInfo() call.
585
- */ get info() {
671
+ get info() {
586
672
  return this.deviceInfo;
587
673
  }
588
- // ─── Connection ─────────────────────────────────────────────────────────
589
- /**
590
- * Connect to the ESP32 hardware wallet.
591
- * Opens the browser port selection dialog.
592
- */ async connect() {
674
+ async connect() {
593
675
  await this.serial.open();
594
676
  }
595
- /**
596
- * Disconnect from the device.
597
- */ async disconnect() {
677
+ async disconnect() {
598
678
  this.deviceInfo = null;
599
679
  await this.serial.close();
600
680
  }
601
- // ─── Device commands ────────────────────────────────────────────────────
602
- /**
603
- * Get device information (no user confirmation needed).
604
- * Returns device name, version, network, address, pubkey, etc.
605
- */ async getInfo() {
681
+ async getInfo() {
606
682
  const response = await this.serial.sendCommand({
607
683
  action: "info"
608
684
  }, 5000);
@@ -610,36 +686,21 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
610
686
  this.deviceInfo = response;
611
687
  return this.deviceInfo;
612
688
  }
613
- /**
614
- * Request the device address and public key.
615
- * Requires user physical confirmation on the device (30s timeout).
616
- */ async getAddress() {
689
+ async getAddress() {
617
690
  const response = await this.serial.sendCommand({
618
691
  action: "get_address"
619
692
  }, 35000);
620
693
  this.assertSuccess(response);
621
694
  return response;
622
695
  }
623
- /**
624
- * Request the BIP32 account extended public key (xpub).
625
- * Requires user physical confirmation on the device (30s timeout).
626
- */ async getBip32Pubkey() {
696
+ async getBip32Pubkey() {
627
697
  const response = await this.serial.sendCommand({
628
698
  action: "get_bip32_pubkey"
629
699
  }, 35000);
630
700
  this.assertSuccess(response);
631
701
  return response;
632
702
  }
633
- /**
634
- * Sign a message to prove address ownership.
635
- * Requires user physical confirmation on the device (30s timeout).
636
- *
637
- * The signature is base64-encoded, compatible with Bitcoin/Neurai message
638
- * signing (recoverable ECDSA with "Neurai Signed Message:\n" prefix).
639
- *
640
- * @param message - The message string to sign (max 1024 bytes)
641
- * @returns Signature (base64), address, and the original message
642
- */ async signMessage(message) {
703
+ async signMessage(message) {
643
704
  const response = await this.serial.sendCommand({
644
705
  action: "sign_message",
645
706
  message: message
@@ -647,42 +708,18 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
647
708
  this.assertSuccess(response);
648
709
  return response;
649
710
  }
650
- /**
651
- * Send a raw PSBT (base64) to the device for signing.
652
- * Requires user physical confirmation on the device (60s timeout).
653
- *
654
- * Use this if you build the PSBT yourself.
655
- */ async signPsbt(psbtBase64, display) {
711
+ async signPsbt(psbtBase64, display) {
656
712
  const response = await this.serial.sendCommandFinal({
657
713
  action: "sign_psbt",
658
714
  psbt: psbtBase64,
659
715
  ...display ? {
660
716
  display: display
661
717
  } : {}
662
- }, 65000);
718
+ }, 120000);
663
719
  this.assertSuccess(response);
664
720
  return response;
665
721
  }
666
- // ─── High-level transaction flow ────────────────────────────────────────
667
- /**
668
- * Build, sign, and finalize a transaction in one call.
669
- *
670
- * This is the main method for sending XNA. It:
671
- * 1. Builds an unsigned PSBT from the provided UTXOs and outputs
672
- * 2. Sends it to the ESP32 for signing (user confirms on device)
673
- * 3. Finalizes the signed PSBT and extracts the raw transaction
674
- *
675
- * @param options.network - Network type (default: uses device info)
676
- * @param options.utxos - UTXOs to spend (must include rawTxHex)
677
- * @param options.outputs - Destination outputs [{address, value}]
678
- * @param options.changeAddress - Address for change (typically device address)
679
- * @param options.pubkey - Compressed public key hex (from getAddress)
680
- * @param options.masterFingerprint - From getInfo().master_fingerprint
681
- * @param options.derivationPath - From getAddress().path
682
- * @param options.feeRate - Fee rate in sat/byte (default: 1024)
683
- * @returns ISignResult with txHex ready to broadcast
684
- */ async signTransaction(options) {
685
- // Use cached device info if available for defaults
722
+ async signTransaction(options) {
686
723
  const info = this.deviceInfo;
687
724
  const network = options.network ?? this.inferNetworkType(info);
688
725
  const pubkey = options.pubkey ?? info?.pubkey;
@@ -691,7 +728,6 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
691
728
  if (!pubkey) throw new Error("pubkey required. Call getInfo() first or provide it explicitly.");
692
729
  if (!masterFingerprint) throw new Error("masterFingerprint required. Call getInfo() first or provide it explicitly.");
693
730
  if (!derivationPath) throw new Error("derivationPath required. Call getInfo() first or provide it explicitly.");
694
- // 1. Build unsigned PSBT
695
731
  const psbtBase64 = (0, $5da7d5b3a851268c$export$236ea1e009011592)({
696
732
  network: network,
697
733
  utxos: options.utxos,
@@ -702,9 +738,7 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
702
738
  derivationPath: derivationPath,
703
739
  feeRate: options.feeRate
704
740
  });
705
- // 2. Send to ESP32 for signing
706
741
  const signResponse = await this.signPsbt(psbtBase64, options.display);
707
- // 3. Finalize and extract raw transaction
708
742
  const { txHex: txHex, txId: txId } = (0, $5da7d5b3a851268c$export$3a31c64c43aacd3)(psbtBase64, signResponse.psbt, network);
709
743
  return {
710
744
  signedPsbtBase64: signResponse.psbt,
@@ -713,18 +747,15 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
713
747
  signedInputs: signResponse.signed_inputs
714
748
  };
715
749
  }
716
- // ─── Private helpers ────────────────────────────────────────────────────
717
750
  assertSuccess(response) {
718
751
  if (response.status === "error") throw new Error(`Device error: ${response.message}`);
719
752
  }
720
- /**
721
- * Infer the NetworkType from cached device info.
722
- */ inferNetworkType(info) {
723
- if (!info) return "xna"; // default
724
- const networkName = info.network?.toLowerCase() ?? "";
725
- const coinType = info.coin_type;
726
- if (networkName.includes("test")) return coinType === 1900 ? "xna-test" : "xna-legacy-test";
727
- if (networkName.includes("legacy") || coinType === 0) return "xna-legacy";
753
+ inferNetworkType(info) {
754
+ if (!info) return "xna";
755
+ const name = (info.network ?? "").toLowerCase();
756
+ if (name.includes("legacy") && name.includes("test")) return "xna-legacy-test";
757
+ if (name.includes("legacy")) return "xna-legacy";
758
+ if (name.includes("test")) return "xna-test";
728
759
  return "xna";
729
760
  }
730
761
  }