@neuraiproject/neurai-sign-esp32 0.1.0

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,558 @@
1
+ import {Psbt as $hgUW1$Psbt} from "bitcoinjs-lib";
2
+ import {ECPairFactory as $hgUW1$ECPairFactory} from "ecpair";
3
+ import $hgUW1$bitcoinerlabsecp256k1 from "@bitcoinerlab/secp256k1";
4
+
5
+ /**
6
+ * @neuraiproject/neurai-sign-esp32
7
+ *
8
+ * Library for creating and signing Neurai (XNA) PSBTs
9
+ * via ESP32 hardware wallet (NeuraiHW).
10
+ */ // Main class
11
+ /**
12
+ * NeuraiESP32 — Main class for interacting with a NeuraiHW hardware wallet.
13
+ *
14
+ * Orchestrates:
15
+ * - USB Serial connection via Web Serial API
16
+ * - Device info, address, and BIP32 pubkey retrieval
17
+ * - PSBT creation, signing, and finalization
18
+ *
19
+ * Usage:
20
+ * ```ts
21
+ * const device = new NeuraiESP32();
22
+ * await device.connect();
23
+ * const info = await device.getInfo();
24
+ * const { address, pubkey } = await device.getAddress();
25
+ * const result = await device.signTransaction({ utxos, outputs, changeAddress: address });
26
+ * console.log(result.txHex); // ready to broadcast
27
+ * await device.disconnect();
28
+ * ```
29
+ */ /**
30
+ * Web Serial API communication layer for ESP32 hardware wallet.
31
+ *
32
+ * Handles USB Serial connection, JSON command/response protocol,
33
+ * and line-based buffering matching the NeuraiHW firmware protocol.
34
+ */ // Default USB filters for ESP32 devices
35
+ const $f1b85200f32d8427$var$DEFAULT_FILTERS = [
36
+ {
37
+ usbVendorId: 0x303a,
38
+ usbProductId: 0x1001
39
+ },
40
+ {
41
+ usbVendorId: 0x303a
42
+ },
43
+ {
44
+ usbVendorId: 0x10c4,
45
+ usbProductId: 0xea60
46
+ },
47
+ {
48
+ usbVendorId: 0x1a86,
49
+ usbProductId: 0x7523
50
+ },
51
+ {
52
+ usbVendorId: 0x0403,
53
+ usbProductId: 0x6001
54
+ },
55
+ {
56
+ usbVendorId: 0x067b,
57
+ usbProductId: 0x2303
58
+ },
59
+ {
60
+ usbVendorId: 0x2886
61
+ }
62
+ ];
63
+ const $f1b85200f32d8427$var$DEFAULT_BAUD_RATE = 115200;
64
+ class $f1b85200f32d8427$export$f93edba7156cc57b {
65
+ constructor(options){
66
+ this.port = null;
67
+ this.reader = null;
68
+ this.writer = null;
69
+ this.readableStreamClosed = null;
70
+ this.writableStreamClosed = null;
71
+ this.isReading = false;
72
+ this.responseQueue = [];
73
+ this.baudRate = options?.baudRate ?? $f1b85200f32d8427$var$DEFAULT_BAUD_RATE;
74
+ this.filters = options?.filters ?? $f1b85200f32d8427$var$DEFAULT_FILTERS;
75
+ }
76
+ /**
77
+ * Check if Web Serial API is available.
78
+ */ static isSupported() {
79
+ return typeof navigator !== "undefined" && "serial" in navigator;
80
+ }
81
+ /**
82
+ * Open a serial connection to the ESP32.
83
+ * Triggers browser port selection dialog.
84
+ */ async open() {
85
+ if (!$f1b85200f32d8427$export$f93edba7156cc57b.isSupported()) throw new Error("Web Serial API not supported. Use Chrome, Edge, or Opera.");
86
+ this.port = await navigator.serial.requestPort({
87
+ filters: this.filters
88
+ });
89
+ await this.port.open({
90
+ baudRate: this.baudRate
91
+ });
92
+ // Set up readable stream (text decoding)
93
+ const decoder = new TextDecoderStream();
94
+ this.readableStreamClosed = this.port.readable.pipeTo(decoder.writable);
95
+ this.reader = decoder.readable.getReader();
96
+ // Set up writable stream (text encoding)
97
+ const encoder = new TextEncoderStream();
98
+ this.writableStreamClosed = encoder.readable.pipeTo(this.port.writable);
99
+ this.writer = encoder.writable.getWriter();
100
+ // Start background read loop
101
+ this.isReading = true;
102
+ this.readLoop();
103
+ }
104
+ /**
105
+ * Close the serial connection.
106
+ */ async close() {
107
+ this.isReading = false;
108
+ if (this.reader) {
109
+ await this.reader.cancel();
110
+ await this.readableStreamClosed?.catch(()=>{});
111
+ this.reader = null;
112
+ }
113
+ if (this.writer) {
114
+ await this.writer.close();
115
+ await this.writableStreamClosed;
116
+ this.writer = null;
117
+ }
118
+ if (this.port) {
119
+ await this.port.close();
120
+ this.port = null;
121
+ }
122
+ this.responseQueue = [];
123
+ }
124
+ /**
125
+ * Whether the serial port is currently connected.
126
+ */ get connected() {
127
+ return this.port !== null && this.writer !== null;
128
+ }
129
+ /**
130
+ * Send a JSON command to the device and wait for a JSON response.
131
+ *
132
+ * @param command - The command object (e.g. { action: "info" })
133
+ * @param timeoutMs - Response timeout in milliseconds (default: 65000 for sign operations)
134
+ * @returns The parsed device response
135
+ */ async sendCommand(command, timeoutMs = 65000) {
136
+ if (!this.writer) throw new Error("Serial port not connected");
137
+ // Clear stale responses
138
+ this.responseQueue = [];
139
+ // Send JSON in small chunks, then newline to trigger processing.
140
+ // The ESP32 CDC serial buffer can lose data if sent too fast in one write.
141
+ const json = JSON.stringify(command);
142
+ await this.writeChunked(json);
143
+ await this.writer.write("\n");
144
+ // Wait for response
145
+ const response = await this.waitForResponse(timeoutMs);
146
+ if (!response) throw new Error("Device response timeout");
147
+ return response;
148
+ }
149
+ /**
150
+ * Send a command and wait, skipping intermediate "processing" status messages.
151
+ * Useful for sign_psbt which sends a processing ACK before the actual response.
152
+ */ async sendCommandFinal(command, timeoutMs = 65000) {
153
+ if (!this.writer) throw new Error("Serial port not connected");
154
+ this.responseQueue = [];
155
+ const json = JSON.stringify(command);
156
+ await this.writeChunked(json);
157
+ await this.writer.write("\n");
158
+ // Wait for a non-processing response
159
+ const startTime = Date.now();
160
+ while(Date.now() - startTime < timeoutMs){
161
+ const response = await this.waitForResponse(timeoutMs - (Date.now() - startTime));
162
+ if (!response) throw new Error("Device response timeout");
163
+ // Skip intermediate "processing" status
164
+ if (response.status === "processing") continue;
165
+ return response;
166
+ }
167
+ throw new Error("Device response timeout");
168
+ }
169
+ // ─── Private ──────────────────────────────────────────────────────────────
170
+ async readLoop() {
171
+ let buffer = "";
172
+ while(this.isReading && this.reader)try {
173
+ const { value: value, done: done } = await this.reader.read();
174
+ if (done) break;
175
+ buffer += value;
176
+ // Process complete lines
177
+ const lines = buffer.split("\n");
178
+ buffer = lines.pop() ?? ""; // Keep incomplete line in buffer
179
+ for (const rawLine of lines){
180
+ const line = rawLine.trim().replace(/\r/g, "");
181
+ if (line.length === 0) continue;
182
+ // Try to parse as JSON response
183
+ if (line.startsWith("{")) try {
184
+ const data = JSON.parse(line);
185
+ this.responseQueue.push(data);
186
+ } catch {
187
+ // Not valid JSON — debug output from firmware, ignore
188
+ }
189
+ // Non-JSON lines are firmware debug output, ignored
190
+ }
191
+ } catch {
192
+ break;
193
+ }
194
+ }
195
+ waitForResponse(timeoutMs) {
196
+ return new Promise((resolve)=>{
197
+ const startTime = Date.now();
198
+ const check = ()=>{
199
+ if (this.responseQueue.length > 0) resolve(this.responseQueue.shift());
200
+ else if (Date.now() - startTime > timeoutMs) resolve(null);
201
+ else setTimeout(check, 50);
202
+ };
203
+ check();
204
+ });
205
+ }
206
+ /**
207
+ * Write data in small chunks with pauses between them.
208
+ *
209
+ * The ESP32 CDC serial buffer can lose data when the host sends a large
210
+ * payload in a single write. Splitting into 32-byte chunks with a 4 ms
211
+ * pause gives the firmware time to drain its receive buffer.
212
+ */ async writeChunked(data, chunkSize = 32, pauseMs = 4) {
213
+ if (!this.writer) throw new Error("Serial port not connected");
214
+ for(let offset = 0; offset < data.length; offset += chunkSize){
215
+ const chunk = data.slice(offset, offset + chunkSize);
216
+ await this.writer.write(chunk);
217
+ if (offset + chunkSize < data.length) await this.delay(pauseMs);
218
+ }
219
+ }
220
+ delay(ms) {
221
+ return new Promise((resolve)=>setTimeout(resolve, ms));
222
+ }
223
+ }
224
+
225
+
226
+ /**
227
+ * PSBT builder for Neurai P2PKH transactions.
228
+ *
229
+ * Creates unsigned PSBTs compatible with the NeuraiHW ESP32 firmware.
230
+ * The ESP32 signs inputs that match its BIP32 derivation path and
231
+ * master fingerprint.
232
+ *
233
+ * Requirements for each UTXO:
234
+ * - rawTxHex: Full raw transaction hex (P2PKH needs nonWitnessUtxo)
235
+ * - scriptPubKey: The output script being spent
236
+ *
237
+ * The PSBT includes BIP32 derivation metadata so the ESP32 can
238
+ * verify and locate the correct signing key.
239
+ */
240
+
241
+
242
+ /**
243
+ * Neurai network configurations for bitcoinjs-lib
244
+ *
245
+ * Defines all Neurai networks (mainnet, testnet, legacy variants)
246
+ * in the format required by bitcoinjs-lib v7.
247
+ */ const $ab66056610f04b01$export$6b5a4442fe3d94ae = {
248
+ messagePrefix: "Neurai Signed Message:\n",
249
+ bech32: "",
250
+ bip32: {
251
+ public: 76067358,
252
+ private: 76066276
253
+ },
254
+ pubKeyHash: 53,
255
+ scriptHash: 117,
256
+ wif: 128
257
+ };
258
+ const $ab66056610f04b01$export$7eb3dea33add35cf = {
259
+ messagePrefix: "Neurai Signed Message:\n",
260
+ bech32: "",
261
+ bip32: {
262
+ public: 70617039,
263
+ private: 70615956
264
+ },
265
+ pubKeyHash: 127,
266
+ scriptHash: 196,
267
+ wif: 239
268
+ };
269
+ const $ab66056610f04b01$export$688657d38fcd7269 = {
270
+ messagePrefix: "Neurai Signed Message:\n",
271
+ bech32: "",
272
+ bip32: {
273
+ public: 76067358,
274
+ private: 76066276
275
+ },
276
+ pubKeyHash: 53,
277
+ scriptHash: 117,
278
+ wif: 128
279
+ };
280
+ const $ab66056610f04b01$export$68e8f8241c8185fe = {
281
+ messagePrefix: "Neurai Signed Message:\n",
282
+ bech32: "",
283
+ bip32: {
284
+ public: 70617039,
285
+ private: 70615956
286
+ },
287
+ pubKeyHash: 127,
288
+ scriptHash: 196,
289
+ wif: 239
290
+ };
291
+ // ─── Network map ─────────────────────────────────────────────────────────────
292
+ const $ab66056610f04b01$var$networkMap = {
293
+ xna: $ab66056610f04b01$export$6b5a4442fe3d94ae,
294
+ "xna-test": $ab66056610f04b01$export$7eb3dea33add35cf,
295
+ "xna-legacy": $ab66056610f04b01$export$688657d38fcd7269,
296
+ "xna-legacy-test": $ab66056610f04b01$export$68e8f8241c8185fe
297
+ };
298
+ function $ab66056610f04b01$export$7de4970ebfd8206d(network) {
299
+ const net = $ab66056610f04b01$var$networkMap[network];
300
+ if (!net) throw new Error(`Unknown network: ${network}`);
301
+ return net;
302
+ }
303
+
304
+
305
+ const $68e2926fe257f2e4$var$ECPair = (0, $hgUW1$ECPairFactory)((0, $hgUW1$bitcoinerlabsecp256k1));
306
+ const $68e2926fe257f2e4$var$DEFAULT_FEE_RATE = 1024; // sat/byte
307
+ // Estimated P2PKH tx sizes for fee calculation
308
+ const $68e2926fe257f2e4$var$TX_OVERHEAD = 10; // version(4) + locktime(4) + varint(2)
309
+ const $68e2926fe257f2e4$var$INPUT_SIZE = 148; // P2PKH input with signature
310
+ const $68e2926fe257f2e4$var$OUTPUT_SIZE = 34; // P2PKH output
311
+ /**
312
+ * Estimate transaction size in bytes for P2PKH.
313
+ */ function $68e2926fe257f2e4$var$estimateTxSize(inputCount, outputCount) {
314
+ return $68e2926fe257f2e4$var$TX_OVERHEAD + inputCount * $68e2926fe257f2e4$var$INPUT_SIZE + outputCount * $68e2926fe257f2e4$var$OUTPUT_SIZE;
315
+ }
316
+ /**
317
+ * Parse a master fingerprint hex string (8 chars) into a 4-byte Buffer.
318
+ */ function $68e2926fe257f2e4$var$parseMasterFingerprint(hex) {
319
+ if (hex.length !== 8) throw new Error(`Invalid master fingerprint: expected 8 hex chars, got ${hex.length}`);
320
+ return Buffer.from(hex, "hex");
321
+ }
322
+ /**
323
+ * Parse a BIP44 derivation path string into an array of uint32 indices.
324
+ * e.g. "m/44'/1900'/0'/0/0" → [0x8000002C, 0x8000076C, 0x80000000, 0, 0]
325
+ */ function $68e2926fe257f2e4$var$parseDerivationPath(path) {
326
+ return path.replace(/^m\//, "").split("/").map((part)=>{
327
+ const hardened = part.endsWith("'");
328
+ const index = parseInt(hardened ? part.slice(0, -1) : part, 10);
329
+ return hardened ? index + 0x80000000 : index;
330
+ });
331
+ }
332
+ function $68e2926fe257f2e4$export$236ea1e009011592(options) {
333
+ const { network: networkType, utxos: utxos, outputs: outputs, changeAddress: changeAddress, pubkey: pubkey, masterFingerprint: masterFingerprint, derivationPath: derivationPath, feeRate: feeRate = $68e2926fe257f2e4$var$DEFAULT_FEE_RATE } = options;
334
+ if (utxos.length === 0) throw new Error("No UTXOs provided");
335
+ if (outputs.length === 0) throw new Error("No outputs provided");
336
+ const network = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(networkType);
337
+ const pubkeyBuffer = Buffer.from(pubkey, "hex");
338
+ const fingerprintBuffer = $68e2926fe257f2e4$var$parseMasterFingerprint(masterFingerprint);
339
+ const bip32Path = $68e2926fe257f2e4$var$parseDerivationPath(derivationPath);
340
+ // Calculate total output amount
341
+ const totalOutputValue = outputs.reduce((sum, o)=>sum + o.value, 0);
342
+ // Select UTXOs (use all provided — caller is responsible for UTXO selection)
343
+ const totalInputValue = utxos.reduce((sum, u)=>sum + u.satoshis, 0);
344
+ // Estimate fee: outputs + possible change output
345
+ const estimatedSize = $68e2926fe257f2e4$var$estimateTxSize(utxos.length, outputs.length + 1);
346
+ const fee = estimatedSize * feeRate;
347
+ const change = totalInputValue - totalOutputValue - fee;
348
+ if (change < 0) throw new Error(`Insufficient funds: inputs=${totalInputValue}, outputs=${totalOutputValue}, fee=${fee}`);
349
+ // Build PSBT
350
+ const psbt = new $hgUW1$Psbt({
351
+ network: network
352
+ });
353
+ // BIP32 derivation metadata (same for all inputs from this device)
354
+ const bip32Derivation = [
355
+ {
356
+ masterFingerprint: fingerprintBuffer,
357
+ path: derivationPath,
358
+ pubkey: pubkeyBuffer
359
+ }
360
+ ];
361
+ // Add inputs
362
+ for (const utxo of utxos)psbt.addInput({
363
+ hash: utxo.txid,
364
+ index: utxo.vout,
365
+ nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
366
+ bip32Derivation: bip32Derivation
367
+ });
368
+ // Add destination outputs
369
+ for (const output of outputs)psbt.addOutput({
370
+ address: output.address,
371
+ value: BigInt(output.value)
372
+ });
373
+ // Add change output (if change > dust threshold)
374
+ const DUST_THRESHOLD = 546; // standard dust for P2PKH
375
+ if (change >= DUST_THRESHOLD) psbt.addOutput({
376
+ address: changeAddress,
377
+ value: BigInt(change),
378
+ bip32Derivation: bip32Derivation
379
+ });
380
+ return psbt.toBase64();
381
+ }
382
+ function $68e2926fe257f2e4$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
383
+ const net = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network);
384
+ const psbt = $hgUW1$Psbt.fromBase64(signedPsbtBase64, {
385
+ network: net
386
+ });
387
+ psbt.finalizeAllInputs();
388
+ const tx = psbt.extractTransaction();
389
+ return {
390
+ txHex: tx.toHex(),
391
+ txId: tx.getId()
392
+ };
393
+ }
394
+ function $68e2926fe257f2e4$export$78a5723c75e7be9(psbtBase64, network) {
395
+ try {
396
+ const net = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network);
397
+ $hgUW1$Psbt.fromBase64(psbtBase64, {
398
+ network: net
399
+ });
400
+ return true;
401
+ } catch {
402
+ return false;
403
+ }
404
+ }
405
+
406
+
407
+ class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
408
+ constructor(options){
409
+ this.deviceInfo = null;
410
+ this.serial = new (0, $f1b85200f32d8427$export$f93edba7156cc57b)(options);
411
+ }
412
+ /**
413
+ * Check if Web Serial API is supported in this browser.
414
+ */ static isSupported() {
415
+ return (0, $f1b85200f32d8427$export$f93edba7156cc57b).isSupported();
416
+ }
417
+ /**
418
+ * Whether the device is currently connected.
419
+ */ get connected() {
420
+ return this.serial.connected;
421
+ }
422
+ /**
423
+ * Cached device info from the last getInfo() call.
424
+ */ get info() {
425
+ return this.deviceInfo;
426
+ }
427
+ // ─── Connection ─────────────────────────────────────────────────────────
428
+ /**
429
+ * Connect to the ESP32 hardware wallet.
430
+ * Opens the browser port selection dialog.
431
+ */ async connect() {
432
+ await this.serial.open();
433
+ }
434
+ /**
435
+ * Disconnect from the device.
436
+ */ async disconnect() {
437
+ this.deviceInfo = null;
438
+ await this.serial.close();
439
+ }
440
+ // ─── Device commands ────────────────────────────────────────────────────
441
+ /**
442
+ * Get device information (no user confirmation needed).
443
+ * Returns device name, version, network, address, pubkey, etc.
444
+ */ async getInfo() {
445
+ const response = await this.serial.sendCommand({
446
+ action: "info"
447
+ }, 5000);
448
+ this.assertSuccess(response);
449
+ this.deviceInfo = response;
450
+ return this.deviceInfo;
451
+ }
452
+ /**
453
+ * Request the device address and public key.
454
+ * Requires user physical confirmation on the device (30s timeout).
455
+ */ async getAddress() {
456
+ const response = await this.serial.sendCommand({
457
+ action: "get_address"
458
+ }, 35000);
459
+ this.assertSuccess(response);
460
+ return response;
461
+ }
462
+ /**
463
+ * Request the BIP32 account extended public key (xpub).
464
+ * Requires user physical confirmation on the device (30s timeout).
465
+ */ async getBip32Pubkey() {
466
+ const response = await this.serial.sendCommand({
467
+ action: "get_bip32_pubkey"
468
+ }, 35000);
469
+ this.assertSuccess(response);
470
+ return response;
471
+ }
472
+ /**
473
+ * Send a raw PSBT (base64) to the device for signing.
474
+ * Requires user physical confirmation on the device (60s timeout).
475
+ *
476
+ * Use this if you build the PSBT yourself.
477
+ */ async signPsbt(psbtBase64) {
478
+ const response = await this.serial.sendCommandFinal({
479
+ action: "sign_psbt",
480
+ psbt: psbtBase64
481
+ }, 65000);
482
+ this.assertSuccess(response);
483
+ return response;
484
+ }
485
+ // ─── High-level transaction flow ────────────────────────────────────────
486
+ /**
487
+ * Build, sign, and finalize a transaction in one call.
488
+ *
489
+ * This is the main method for sending XNA. It:
490
+ * 1. Builds an unsigned PSBT from the provided UTXOs and outputs
491
+ * 2. Sends it to the ESP32 for signing (user confirms on device)
492
+ * 3. Finalizes the signed PSBT and extracts the raw transaction
493
+ *
494
+ * @param options.network - Network type (default: uses device info)
495
+ * @param options.utxos - UTXOs to spend (must include rawTxHex)
496
+ * @param options.outputs - Destination outputs [{address, value}]
497
+ * @param options.changeAddress - Address for change (typically device address)
498
+ * @param options.pubkey - Compressed public key hex (from getAddress)
499
+ * @param options.masterFingerprint - From getInfo().master_fingerprint
500
+ * @param options.derivationPath - From getAddress().path
501
+ * @param options.feeRate - Fee rate in sat/byte (default: 1024)
502
+ * @returns ISignResult with txHex ready to broadcast
503
+ */ async signTransaction(options) {
504
+ // Use cached device info if available for defaults
505
+ const info = this.deviceInfo;
506
+ const network = options.network ?? this.inferNetworkType(info);
507
+ const pubkey = options.pubkey ?? info?.pubkey;
508
+ const masterFingerprint = options.masterFingerprint ?? info?.master_fingerprint;
509
+ const derivationPath = options.derivationPath ?? info?.path;
510
+ if (!pubkey) throw new Error("pubkey required. Call getInfo() first or provide it explicitly.");
511
+ if (!masterFingerprint) throw new Error("masterFingerprint required. Call getInfo() first or provide it explicitly.");
512
+ if (!derivationPath) throw new Error("derivationPath required. Call getInfo() first or provide it explicitly.");
513
+ // 1. Build unsigned PSBT
514
+ const psbtBase64 = (0, $68e2926fe257f2e4$export$236ea1e009011592)({
515
+ network: network,
516
+ utxos: options.utxos,
517
+ outputs: options.outputs,
518
+ changeAddress: options.changeAddress,
519
+ pubkey: pubkey,
520
+ masterFingerprint: masterFingerprint,
521
+ derivationPath: derivationPath,
522
+ feeRate: options.feeRate
523
+ });
524
+ // 2. Send to ESP32 for signing
525
+ const signResponse = await this.signPsbt(psbtBase64);
526
+ // 3. Finalize and extract raw transaction
527
+ const { txHex: txHex, txId: txId } = (0, $68e2926fe257f2e4$export$ce839c4c9bcf7b77)(signResponse.psbt, network);
528
+ return {
529
+ signedPsbtBase64: signResponse.psbt,
530
+ txHex: txHex,
531
+ txId: txId,
532
+ signedInputs: signResponse.signed_inputs
533
+ };
534
+ }
535
+ // ─── Private helpers ────────────────────────────────────────────────────
536
+ assertSuccess(response) {
537
+ if (response.status === "error") throw new Error(`Device error: ${response.message}`);
538
+ }
539
+ /**
540
+ * Infer the NetworkType from cached device info.
541
+ */ inferNetworkType(info) {
542
+ if (!info) return "xna"; // default
543
+ const networkName = info.network?.toLowerCase() ?? "";
544
+ const coinType = info.coin_type;
545
+ if (networkName.includes("test")) return coinType === 1900 ? "xna-test" : "xna-legacy-test";
546
+ if (networkName.includes("legacy") || coinType === 0) return "xna-legacy";
547
+ return "xna";
548
+ }
549
+ }
550
+
551
+
552
+
553
+
554
+
555
+
556
+
557
+ export {$a6c8409f4f68b3eb$export$fa10ee8b91a777b7 as NeuraiESP32, $68e2926fe257f2e4$export$236ea1e009011592 as buildPSBT, $68e2926fe257f2e4$export$ce839c4c9bcf7b77 as finalizePSBT, $68e2926fe257f2e4$export$78a5723c75e7be9 as validatePSBT, $f1b85200f32d8427$export$f93edba7156cc57b as SerialConnection, $ab66056610f04b01$export$7de4970ebfd8206d as getNetwork, $ab66056610f04b01$export$6b5a4442fe3d94ae as neuraiMainnet, $ab66056610f04b01$export$7eb3dea33add35cf as neuraiTestnet, $ab66056610f04b01$export$688657d38fcd7269 as neuraiLegacyMainnet, $ab66056610f04b01$export$68e8f8241c8185fe as neuraiLegacyTestnet};
558
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"mappings":";;;;AAAA;;;;;CAKC,GAED,aAAa;ACPb;;;;;;;;;;;;;;;;;;ACAA;;;;;CAKC,GAID,wCAAwC;AACxC,MAAM,wCAAsC;IAC1C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;IACtB;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;CACvB;AAED,MAAM,0CAAoB;AAEnB,MAAM;IAWX,YAAY,OAAwB,CAAE;aAV9B,OAA0B;aAC1B,SAAqD;aACrD,SAAqD;aACrD,uBAA6C;aAC7C,uBAA6C;aAC7C,YAAY;aACZ,gBAAkC,EAAE;QAK1C,IAAI,CAAC,QAAQ,GAAG,SAAS,YAAY;QACrC,I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7D;IAEA;;GAEC,GACD,AAAQ,iBAAiB,IAAwB,EAAe;QAC9D,IAAI,CAAC,MACH,OAAO,OAAO,UAAU;QAG1B,MAAM,cAAc,KAAK,OAAO,EAAE,iBAAiB;QACnD,MAAM,WAAW,KAAK,SAAS;QAE/B,IAAI,YAAY,QAAQ,CAAC,SACvB,OAAO,aAAa,OAAO,aAAa;QAE1C,IAAI,YAAY,QAAQ,CAAC,aAAa,aAAa,GACjD,OAAO;QAET,OAAO;IACT;AACF;","sources":["src/index.ts","src/NeuraiESP32.ts","src/serial.ts","src/psbt.ts","src/networks.ts"],"sourcesContent":["/**\n * @neuraiproject/neurai-sign-esp32\n *\n * Library for creating and signing Neurai (XNA) PSBTs\n * via ESP32 hardware wallet (NeuraiHW).\n */\n\n// Main class\nexport { NeuraiESP32 } from \"./NeuraiESP32.js\";\n\n// PSBT utilities\nexport { buildPSBT, finalizePSBT, validatePSBT } from \"./psbt.js\";\n\n// Serial connection (for advanced use)\nexport { SerialConnection } from \"./serial.js\";\n\n// Network configs\nexport {\n getNetwork,\n neuraiMainnet,\n neuraiTestnet,\n neuraiLegacyMainnet,\n neuraiLegacyTestnet,\n} from \"./networks.js\";\n\n// Types\nexport type {\n IUTXO,\n ITxOutput,\n IBuildPSBTOptions,\n IDeviceInfo,\n IAddressResponse,\n IBip32PubkeyResponse,\n ISignPsbtResponse,\n IErrorResponse,\n ISerialOptions,\n ISignResult,\n NetworkType,\n} from \"./types.js\";\n","/**\n * NeuraiESP32 — Main class for interacting with a NeuraiHW hardware wallet.\n *\n * Orchestrates:\n * - USB Serial connection via Web Serial API\n * - Device info, address, and BIP32 pubkey retrieval\n * - PSBT creation, signing, and finalization\n *\n * Usage:\n * ```ts\n * const device = new NeuraiESP32();\n * await device.connect();\n * const info = await device.getInfo();\n * const { address, pubkey } = await device.getAddress();\n * const result = await device.signTransaction({ utxos, outputs, changeAddress: address });\n * console.log(result.txHex); // ready to broadcast\n * await device.disconnect();\n * ```\n */\n\nimport { SerialConnection } from \"./serial.js\";\nimport { buildPSBT, finalizePSBT } from \"./psbt.js\";\nimport type {\n DeviceResponse,\n IAddressResponse,\n IBip32PubkeyResponse,\n IDeviceInfo,\n IErrorResponse,\n ISerialOptions,\n ISignPsbtResponse,\n ISignResult,\n IUTXO,\n ITxOutput,\n NetworkType,\n} from \"./types.js\";\n\nexport class NeuraiESP32 {\n private serial: SerialConnection;\n private deviceInfo: IDeviceInfo | null = null;\n\n constructor(options?: ISerialOptions) {\n this.serial = new SerialConnection(options);\n }\n\n /**\n * Check if Web Serial API is supported in this browser.\n */\n static isSupported(): boolean {\n return SerialConnection.isSupported();\n }\n\n /**\n * Whether the device is currently connected.\n */\n get connected(): boolean {\n return this.serial.connected;\n }\n\n /**\n * Cached device info from the last getInfo() call.\n */\n get info(): IDeviceInfo | null {\n return this.deviceInfo;\n }\n\n // ─── Connection ─────────────────────────────────────────────────────────\n\n /**\n * Connect to the ESP32 hardware wallet.\n * Opens the browser port selection dialog.\n */\n async connect(): Promise<void> {\n await this.serial.open();\n }\n\n /**\n * Disconnect from the device.\n */\n async disconnect(): Promise<void> {\n this.deviceInfo = null;\n await this.serial.close();\n }\n\n // ─── Device commands ────────────────────────────────────────────────────\n\n /**\n * Get device information (no user confirmation needed).\n * Returns device name, version, network, address, pubkey, etc.\n */\n async getInfo(): Promise<IDeviceInfo> {\n const response = await this.serial.sendCommand(\n { action: \"info\" },\n 5000\n );\n\n this.assertSuccess(response);\n this.deviceInfo = response as IDeviceInfo;\n return this.deviceInfo;\n }\n\n /**\n * Request the device address and public key.\n * Requires user physical confirmation on the device (30s timeout).\n */\n async getAddress(): Promise<IAddressResponse> {\n const response = await this.serial.sendCommand(\n { action: \"get_address\" },\n 35000\n );\n\n this.assertSuccess(response);\n return response as IAddressResponse;\n }\n\n /**\n * Request the BIP32 account extended public key (xpub).\n * Requires user physical confirmation on the device (30s timeout).\n */\n async getBip32Pubkey(): Promise<IBip32PubkeyResponse> {\n const response = await this.serial.sendCommand(\n { action: \"get_bip32_pubkey\" },\n 35000\n );\n\n this.assertSuccess(response);\n return response as IBip32PubkeyResponse;\n }\n\n /**\n * Send a raw PSBT (base64) to the device for signing.\n * Requires user physical confirmation on the device (60s timeout).\n *\n * Use this if you build the PSBT yourself.\n */\n async signPsbt(psbtBase64: string): Promise<ISignPsbtResponse> {\n const response = await this.serial.sendCommandFinal(\n { action: \"sign_psbt\", psbt: psbtBase64 },\n 65000\n );\n\n this.assertSuccess(response);\n return response as ISignPsbtResponse;\n }\n\n // ─── High-level transaction flow ────────────────────────────────────────\n\n /**\n * Build, sign, and finalize a transaction in one call.\n *\n * This is the main method for sending XNA. It:\n * 1. Builds an unsigned PSBT from the provided UTXOs and outputs\n * 2. Sends it to the ESP32 for signing (user confirms on device)\n * 3. Finalizes the signed PSBT and extracts the raw transaction\n *\n * @param options.network - Network type (default: uses device info)\n * @param options.utxos - UTXOs to spend (must include rawTxHex)\n * @param options.outputs - Destination outputs [{address, value}]\n * @param options.changeAddress - Address for change (typically device address)\n * @param options.pubkey - Compressed public key hex (from getAddress)\n * @param options.masterFingerprint - From getInfo().master_fingerprint\n * @param options.derivationPath - From getAddress().path\n * @param options.feeRate - Fee rate in sat/byte (default: 1024)\n * @returns ISignResult with txHex ready to broadcast\n */\n async signTransaction(options: {\n network?: NetworkType;\n utxos: IUTXO[];\n outputs: ITxOutput[];\n changeAddress: string;\n pubkey?: string;\n masterFingerprint?: string;\n derivationPath?: string;\n feeRate?: number;\n }): Promise<ISignResult> {\n // Use cached device info if available for defaults\n const info = this.deviceInfo;\n\n const network =\n options.network ?? this.inferNetworkType(info);\n const pubkey =\n options.pubkey ?? info?.pubkey;\n const masterFingerprint =\n options.masterFingerprint ?? info?.master_fingerprint;\n const derivationPath =\n options.derivationPath ?? info?.path;\n\n if (!pubkey) {\n throw new Error(\n \"pubkey required. Call getInfo() first or provide it explicitly.\"\n );\n }\n if (!masterFingerprint) {\n throw new Error(\n \"masterFingerprint required. Call getInfo() first or provide it explicitly.\"\n );\n }\n if (!derivationPath) {\n throw new Error(\n \"derivationPath required. Call getInfo() first or provide it explicitly.\"\n );\n }\n\n // 1. Build unsigned PSBT\n const psbtBase64 = buildPSBT({\n network,\n utxos: options.utxos,\n outputs: options.outputs,\n changeAddress: options.changeAddress,\n pubkey,\n masterFingerprint,\n derivationPath,\n feeRate: options.feeRate,\n });\n\n // 2. Send to ESP32 for signing\n const signResponse = await this.signPsbt(psbtBase64);\n\n // 3. Finalize and extract raw transaction\n const { txHex, txId } = finalizePSBT(signResponse.psbt, network);\n\n return {\n signedPsbtBase64: signResponse.psbt,\n txHex,\n txId,\n signedInputs: signResponse.signed_inputs,\n };\n }\n\n // ─── Private helpers ────────────────────────────────────────────────────\n\n private assertSuccess(response: DeviceResponse): void {\n if (response.status === \"error\") {\n throw new Error(\n `Device error: ${(response as IErrorResponse).message}`\n );\n }\n }\n\n /**\n * Infer the NetworkType from cached device info.\n */\n private inferNetworkType(info: IDeviceInfo | null): NetworkType {\n if (!info) {\n return \"xna\"; // default\n }\n\n const networkName = info.network?.toLowerCase() ?? \"\";\n const coinType = info.coin_type;\n\n if (networkName.includes(\"test\")) {\n return coinType === 1900 ? \"xna-test\" : \"xna-legacy-test\";\n }\n if (networkName.includes(\"legacy\") || coinType === 0) {\n return \"xna-legacy\";\n }\n return \"xna\";\n }\n}\n","/**\n * Web Serial API communication layer for ESP32 hardware wallet.\n *\n * Handles USB Serial connection, JSON command/response protocol,\n * and line-based buffering matching the NeuraiHW firmware protocol.\n */\n\nimport type { DeviceResponse, ISerialOptions } from \"./types.js\";\n\n// Default USB filters for ESP32 devices\nconst DEFAULT_FILTERS: SerialPortFilter[] = [\n { usbVendorId: 0x303a, usbProductId: 0x1001 }, // ESP32-S3 USB JTAG/Serial\n { usbVendorId: 0x303a }, // Espressif generic\n { usbVendorId: 0x10c4, usbProductId: 0xea60 }, // Silicon Labs CP210x\n { usbVendorId: 0x1a86, usbProductId: 0x7523 }, // CH340\n { usbVendorId: 0x0403, usbProductId: 0x6001 }, // FTDI FT232\n { usbVendorId: 0x067b, usbProductId: 0x2303 }, // Prolific PL2303\n { usbVendorId: 0x2886 }, // Seeed Studio (XIAO)\n];\n\nconst DEFAULT_BAUD_RATE = 115200;\n\nexport class SerialConnection {\n private port: SerialPort | null = null;\n private reader: ReadableStreamDefaultReader<string> | null = null;\n private writer: WritableStreamDefaultWriter<string> | null = null;\n private readableStreamClosed: Promise<void> | null = null;\n private writableStreamClosed: Promise<void> | null = null;\n private isReading = false;\n private responseQueue: DeviceResponse[] = [];\n private baudRate: number;\n private filters: SerialPortFilter[];\n\n constructor(options?: ISerialOptions) {\n this.baudRate = options?.baudRate ?? DEFAULT_BAUD_RATE;\n this.filters = options?.filters ?? DEFAULT_FILTERS;\n }\n\n /**\n * Check if Web Serial API is available.\n */\n static isSupported(): boolean {\n return typeof navigator !== \"undefined\" && \"serial\" in navigator;\n }\n\n /**\n * Open a serial connection to the ESP32.\n * Triggers browser port selection dialog.\n */\n async open(): Promise<void> {\n if (!SerialConnection.isSupported()) {\n throw new Error(\n \"Web Serial API not supported. Use Chrome, Edge, or Opera.\"\n );\n }\n\n this.port = await navigator.serial.requestPort({ filters: this.filters });\n await this.port.open({ baudRate: this.baudRate });\n\n // Set up readable stream (text decoding)\n const decoder = new TextDecoderStream();\n this.readableStreamClosed = this.port.readable!.pipeTo(decoder.writable as unknown as WritableStream<Uint8Array>);\n this.reader = decoder.readable.getReader();\n\n // Set up writable stream (text encoding)\n const encoder = new TextEncoderStream();\n this.writableStreamClosed = encoder.readable.pipeTo(this.port.writable!);\n this.writer = encoder.writable.getWriter();\n\n // Start background read loop\n this.isReading = true;\n this.readLoop();\n }\n\n /**\n * Close the serial connection.\n */\n async close(): Promise<void> {\n this.isReading = false;\n\n if (this.reader) {\n await this.reader.cancel();\n await this.readableStreamClosed?.catch(() => {});\n this.reader = null;\n }\n\n if (this.writer) {\n await this.writer.close();\n await this.writableStreamClosed;\n this.writer = null;\n }\n\n if (this.port) {\n await this.port.close();\n this.port = null;\n }\n\n this.responseQueue = [];\n }\n\n /**\n * Whether the serial port is currently connected.\n */\n get connected(): boolean {\n return this.port !== null && this.writer !== null;\n }\n\n /**\n * Send a JSON command to the device and wait for a JSON response.\n *\n * @param command - The command object (e.g. { action: \"info\" })\n * @param timeoutMs - Response timeout in milliseconds (default: 65000 for sign operations)\n * @returns The parsed device response\n */\n async sendCommand(\n command: Record<string, unknown>,\n timeoutMs = 65000\n ): Promise<DeviceResponse> {\n if (!this.writer) {\n throw new Error(\"Serial port not connected\");\n }\n\n // Clear stale responses\n this.responseQueue = [];\n\n // Send JSON in small chunks, then newline to trigger processing.\n // The ESP32 CDC serial buffer can lose data if sent too fast in one write.\n const json = JSON.stringify(command);\n await this.writeChunked(json);\n await this.writer.write(\"\\n\");\n\n // Wait for response\n const response = await this.waitForResponse(timeoutMs);\n if (!response) {\n throw new Error(\"Device response timeout\");\n }\n\n return response;\n }\n\n /**\n * Send a command and wait, skipping intermediate \"processing\" status messages.\n * Useful for sign_psbt which sends a processing ACK before the actual response.\n */\n async sendCommandFinal(\n command: Record<string, unknown>,\n timeoutMs = 65000\n ): Promise<DeviceResponse> {\n if (!this.writer) {\n throw new Error(\"Serial port not connected\");\n }\n\n this.responseQueue = [];\n\n const json = JSON.stringify(command);\n await this.writeChunked(json);\n await this.writer.write(\"\\n\");\n\n // Wait for a non-processing response\n const startTime = Date.now();\n while (Date.now() - startTime < timeoutMs) {\n const response = await this.waitForResponse(\n timeoutMs - (Date.now() - startTime)\n );\n if (!response) {\n throw new Error(\"Device response timeout\");\n }\n // Skip intermediate \"processing\" status\n if (response.status === \"processing\") {\n continue;\n }\n return response;\n }\n\n throw new Error(\"Device response timeout\");\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n private async readLoop(): Promise<void> {\n let buffer = \"\";\n\n while (this.isReading && this.reader) {\n try {\n const { value, done } = await this.reader.read();\n if (done) break;\n\n buffer += value;\n\n // Process complete lines\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\"; // Keep incomplete line in buffer\n\n for (const rawLine of lines) {\n const line = rawLine.trim().replace(/\\r/g, \"\");\n if (line.length === 0) continue;\n\n // Try to parse as JSON response\n if (line.startsWith(\"{\")) {\n try {\n const data = JSON.parse(line) as DeviceResponse;\n this.responseQueue.push(data);\n } catch {\n // Not valid JSON — debug output from firmware, ignore\n }\n }\n // Non-JSON lines are firmware debug output, ignored\n }\n } catch {\n // Read error — connection may have been closed\n break;\n }\n }\n }\n\n private waitForResponse(timeoutMs: number): Promise<DeviceResponse | null> {\n return new Promise((resolve) => {\n const startTime = Date.now();\n const check = () => {\n if (this.responseQueue.length > 0) {\n resolve(this.responseQueue.shift()!);\n } else if (Date.now() - startTime > timeoutMs) {\n resolve(null);\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n /**\n * Write data in small chunks with pauses between them.\n *\n * The ESP32 CDC serial buffer can lose data when the host sends a large\n * payload in a single write. Splitting into 32-byte chunks with a 4 ms\n * pause gives the firmware time to drain its receive buffer.\n */\n private async writeChunked(\n data: string,\n chunkSize = 32,\n pauseMs = 4\n ): Promise<void> {\n if (!this.writer) {\n throw new Error(\"Serial port not connected\");\n }\n\n for (let offset = 0; offset < data.length; offset += chunkSize) {\n const chunk = data.slice(offset, offset + chunkSize);\n await this.writer.write(chunk);\n if (offset + chunkSize < data.length) {\n await this.delay(pauseMs);\n }\n }\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * PSBT builder for Neurai P2PKH transactions.\n *\n * Creates unsigned PSBTs compatible with the NeuraiHW ESP32 firmware.\n * The ESP32 signs inputs that match its BIP32 derivation path and\n * master fingerprint.\n *\n * Requirements for each UTXO:\n * - rawTxHex: Full raw transaction hex (P2PKH needs nonWitnessUtxo)\n * - scriptPubKey: The output script being spent\n *\n * The PSBT includes BIP32 derivation metadata so the ESP32 can\n * verify and locate the correct signing key.\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { ECPairFactory } from \"ecpair\";\nimport ecc from \"@bitcoinerlab/secp256k1\";\nimport { getNetwork } from \"./networks.js\";\nimport type { IBuildPSBTOptions, IUTXO } from \"./types.js\";\n\nconst ECPair = ECPairFactory(ecc);\n\nconst DEFAULT_FEE_RATE = 1024; // sat/byte\n\n// Estimated P2PKH tx sizes for fee calculation\nconst TX_OVERHEAD = 10; // version(4) + locktime(4) + varint(2)\nconst INPUT_SIZE = 148; // P2PKH input with signature\nconst OUTPUT_SIZE = 34; // P2PKH output\n\n/**\n * Estimate transaction size in bytes for P2PKH.\n */\nfunction estimateTxSize(inputCount: number, outputCount: number): number {\n return TX_OVERHEAD + inputCount * INPUT_SIZE + outputCount * OUTPUT_SIZE;\n}\n\n/**\n * Parse a master fingerprint hex string (8 chars) into a 4-byte Buffer.\n */\nfunction parseMasterFingerprint(hex: string): Buffer {\n if (hex.length !== 8) {\n throw new Error(\n `Invalid master fingerprint: expected 8 hex chars, got ${hex.length}`\n );\n }\n return Buffer.from(hex, \"hex\");\n}\n\n/**\n * Parse a BIP44 derivation path string into an array of uint32 indices.\n * e.g. \"m/44'/1900'/0'/0/0\" → [0x8000002C, 0x8000076C, 0x80000000, 0, 0]\n */\nfunction parseDerivationPath(path: string): number[] {\n return path\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .map((part) => {\n const hardened = part.endsWith(\"'\");\n const index = parseInt(hardened ? part.slice(0, -1) : part, 10);\n return hardened ? index + 0x80000000 : index;\n });\n}\n\n/**\n * Build an unsigned PSBT for Neurai P2PKH, ready to send to the ESP32.\n *\n * @returns Base64-encoded PSBT string\n */\nexport function buildPSBT(options: IBuildPSBTOptions): string {\n const {\n network: networkType,\n utxos,\n outputs,\n changeAddress,\n pubkey,\n masterFingerprint,\n derivationPath,\n feeRate = DEFAULT_FEE_RATE,\n } = options;\n\n if (utxos.length === 0) {\n throw new Error(\"No UTXOs provided\");\n }\n if (outputs.length === 0) {\n throw new Error(\"No outputs provided\");\n }\n\n const network = getNetwork(networkType);\n const pubkeyBuffer = Buffer.from(pubkey, \"hex\");\n const fingerprintBuffer = parseMasterFingerprint(masterFingerprint);\n const bip32Path = parseDerivationPath(derivationPath);\n\n // Calculate total output amount\n const totalOutputValue = outputs.reduce((sum, o) => sum + o.value, 0);\n\n // Select UTXOs (use all provided — caller is responsible for UTXO selection)\n const totalInputValue = utxos.reduce((sum, u) => sum + u.satoshis, 0);\n\n // Estimate fee: outputs + possible change output\n const estimatedSize = estimateTxSize(utxos.length, outputs.length + 1);\n const fee = estimatedSize * feeRate;\n\n const change = totalInputValue - totalOutputValue - fee;\n\n if (change < 0) {\n throw new Error(\n `Insufficient funds: inputs=${totalInputValue}, outputs=${totalOutputValue}, fee=${fee}`\n );\n }\n\n // Build PSBT\n const psbt = new bitcoin.Psbt({ network });\n\n // BIP32 derivation metadata (same for all inputs from this device)\n const bip32Derivation = [\n {\n masterFingerprint: fingerprintBuffer,\n path: derivationPath,\n pubkey: pubkeyBuffer,\n },\n ];\n\n // Add inputs\n for (const utxo of utxos) {\n psbt.addInput({\n hash: utxo.txid,\n index: utxo.vout,\n nonWitnessUtxo: Buffer.from(utxo.rawTxHex, \"hex\"),\n bip32Derivation,\n });\n }\n\n // Add destination outputs\n for (const output of outputs) {\n psbt.addOutput({\n address: output.address,\n value: BigInt(output.value),\n });\n }\n\n // Add change output (if change > dust threshold)\n const DUST_THRESHOLD = 546; // standard dust for P2PKH\n if (change >= DUST_THRESHOLD) {\n psbt.addOutput({\n address: changeAddress,\n value: BigInt(change),\n bip32Derivation,\n });\n }\n\n return psbt.toBase64();\n}\n\n/**\n * Finalize a signed PSBT and extract the raw transaction.\n *\n * Call this after receiving the signed PSBT back from the ESP32.\n *\n * @param signedPsbtBase64 - Base64-encoded signed PSBT from the device\n * @param network - Network type\n * @returns Object with txHex (raw tx for broadcast) and txId\n */\nexport function finalizePSBT(\n signedPsbtBase64: string,\n network: \"xna\" | \"xna-test\" | \"xna-legacy\" | \"xna-legacy-test\"\n): { txHex: string; txId: string } {\n const net = getNetwork(network);\n const psbt = bitcoin.Psbt.fromBase64(signedPsbtBase64, { network: net });\n\n psbt.finalizeAllInputs();\n\n const tx = psbt.extractTransaction();\n return {\n txHex: tx.toHex(),\n txId: tx.getId(),\n };\n}\n\n/**\n * Validate that a PSBT base64 string is parseable.\n */\nexport function validatePSBT(\n psbtBase64: string,\n network: \"xna\" | \"xna-test\" | \"xna-legacy\" | \"xna-legacy-test\"\n): boolean {\n try {\n const net = getNetwork(network);\n bitcoin.Psbt.fromBase64(psbtBase64, { network: net });\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Neurai network configurations for bitcoinjs-lib\n *\n * Defines all Neurai networks (mainnet, testnet, legacy variants)\n * in the format required by bitcoinjs-lib v7.\n */\n\nimport type { Network } from \"bitcoinjs-lib\";\nimport type { NetworkType } from \"./types.js\";\n\n// ─── Neurai Mainnet (coin type 1900) ────────────────────────────────────────\n\nexport const neuraiMainnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 76067358,\n private: 76066276,\n },\n pubKeyHash: 53, // 0x35 → prefix \"N\"\n scriptHash: 117, // 0x75\n wif: 128, // 0x80\n};\n\n// ─── Neurai Testnet ──────────────────────────────────────────────────────────\n\nexport const neuraiTestnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 70617039,\n private: 70615956,\n },\n pubKeyHash: 127, // 0x7f\n scriptHash: 196, // 0xc4\n wif: 239, // 0xef\n};\n\n// ─── Neurai Legacy Mainnet (coin type 0) ─────────────────────────────────────\n\nexport const neuraiLegacyMainnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 76067358,\n private: 76066276,\n },\n pubKeyHash: 53,\n scriptHash: 117,\n wif: 128,\n};\n\n// ─── Neurai Legacy Testnet ───────────────────────────────────────────────────\n\nexport const neuraiLegacyTestnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 70617039,\n private: 70615956,\n },\n pubKeyHash: 127,\n scriptHash: 196,\n wif: 239,\n};\n\n// ─── Network map ─────────────────────────────────────────────────────────────\n\nconst networkMap: Record<NetworkType, Network> = {\n xna: neuraiMainnet,\n \"xna-test\": neuraiTestnet,\n \"xna-legacy\": neuraiLegacyMainnet,\n \"xna-legacy-test\": neuraiLegacyTestnet,\n};\n\n/**\n * Get the bitcoinjs-lib Network object for a given Neurai network type.\n */\nexport function getNetwork(network: NetworkType): Network {\n const net = networkMap[network];\n if (!net) {\n throw new Error(`Unknown network: ${network}`);\n }\n return net;\n}\n"],"names":[],"version":3,"file":"index.mjs.map"}