@arkade-os/sdk 0.4.19 → 0.4.20

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.
Files changed (59) hide show
  1. package/dist/cjs/contracts/contractWatcher.js +7 -1
  2. package/dist/cjs/contracts/handlers/default.js +10 -3
  3. package/dist/cjs/contracts/handlers/helpers.js +47 -5
  4. package/dist/cjs/contracts/handlers/vhtlc.js +4 -2
  5. package/dist/cjs/identity/descriptor.js +98 -0
  6. package/dist/cjs/identity/descriptorProvider.js +2 -0
  7. package/dist/cjs/identity/index.js +15 -1
  8. package/dist/cjs/identity/seedIdentity.js +91 -6
  9. package/dist/cjs/identity/serialize.js +166 -0
  10. package/dist/cjs/identity/staticDescriptorProvider.js +65 -0
  11. package/dist/cjs/index.js +6 -3
  12. package/dist/cjs/providers/ark.js +11 -3
  13. package/dist/cjs/providers/electrum.js +663 -0
  14. package/dist/cjs/providers/indexer.js +5 -1
  15. package/dist/cjs/providers/utils.js +4 -0
  16. package/dist/cjs/wallet/ramps.js +1 -1
  17. package/dist/cjs/wallet/serviceWorker/wallet-message-handler.js +10 -0
  18. package/dist/cjs/wallet/serviceWorker/wallet.js +137 -91
  19. package/dist/cjs/wallet/vtxo-manager.js +56 -8
  20. package/dist/cjs/wallet/wallet.js +3 -3
  21. package/dist/cjs/worker/messageBus.js +200 -56
  22. package/dist/esm/contracts/contractWatcher.js +7 -1
  23. package/dist/esm/contracts/handlers/default.js +10 -3
  24. package/dist/esm/contracts/handlers/helpers.js +47 -5
  25. package/dist/esm/contracts/handlers/vhtlc.js +4 -2
  26. package/dist/esm/identity/descriptor.js +92 -0
  27. package/dist/esm/identity/descriptorProvider.js +1 -0
  28. package/dist/esm/identity/index.js +6 -1
  29. package/dist/esm/identity/seedIdentity.js +89 -6
  30. package/dist/esm/identity/serialize.js +159 -0
  31. package/dist/esm/identity/staticDescriptorProvider.js +61 -0
  32. package/dist/esm/index.js +2 -1
  33. package/dist/esm/providers/ark.js +12 -4
  34. package/dist/esm/providers/electrum.js +658 -0
  35. package/dist/esm/providers/indexer.js +6 -2
  36. package/dist/esm/providers/utils.js +3 -0
  37. package/dist/esm/wallet/ramps.js +1 -1
  38. package/dist/esm/wallet/serviceWorker/wallet-message-handler.js +10 -0
  39. package/dist/esm/wallet/serviceWorker/wallet.js +137 -91
  40. package/dist/esm/wallet/vtxo-manager.js +56 -8
  41. package/dist/esm/wallet/wallet.js +3 -3
  42. package/dist/esm/worker/messageBus.js +201 -57
  43. package/dist/types/contracts/handlers/default.d.ts +1 -1
  44. package/dist/types/contracts/handlers/helpers.d.ts +1 -1
  45. package/dist/types/contracts/types.d.ts +11 -3
  46. package/dist/types/identity/descriptor.d.ts +35 -0
  47. package/dist/types/identity/descriptorProvider.d.ts +28 -0
  48. package/dist/types/identity/index.d.ts +7 -1
  49. package/dist/types/identity/seedIdentity.d.ts +41 -4
  50. package/dist/types/identity/serialize.d.ts +84 -0
  51. package/dist/types/identity/staticDescriptorProvider.d.ts +18 -0
  52. package/dist/types/index.d.ts +4 -2
  53. package/dist/types/providers/electrum.d.ts +212 -0
  54. package/dist/types/providers/utils.d.ts +1 -0
  55. package/dist/types/wallet/serviceWorker/wallet-message-handler.d.ts +11 -2
  56. package/dist/types/wallet/serviceWorker/wallet.d.ts +27 -10
  57. package/dist/types/wallet/vtxo-manager.d.ts +2 -0
  58. package/dist/types/worker/messageBus.d.ts +68 -8
  59. package/package.json +3 -2
@@ -0,0 +1,658 @@
1
+ import { Address, OutScript, Transaction } from "@scure/btc-signer";
2
+ import { sha256 } from "@scure/btc-signer/utils.js";
3
+ import { hex } from "@scure/base";
4
+ // Electrum protocol method names
5
+ const BroadcastTransaction = "blockchain.transaction.broadcast";
6
+ const BroadcastPackageMethod = "blockchain.transaction.broadcast_package";
7
+ const EstimateFee = "blockchain.estimatefee";
8
+ const GetBlockHeader = "blockchain.block.header";
9
+ const GetHistoryMethod = "blockchain.scripthash.get_history";
10
+ const GetTransactionMethod = "blockchain.transaction.get";
11
+ const SubscribeStatusMethod = "blockchain.scripthash";
12
+ const SubscribeHeadersMethod = "blockchain.headers";
13
+ const GetRelayFeeMethod = "blockchain.relayfee";
14
+ const ListUnspentMethod = "blockchain.scripthash.listunspent";
15
+ const MISSING_TRANSACTION = "missingtransaction";
16
+ const MAX_FETCH_TRANSACTIONS_ATTEMPTS = 5;
17
+ // Bitcoin block header is 80 bytes
18
+ const BLOCK_HEADER_SIZE = 80;
19
+ /**
20
+ * Parse a raw block header (80 bytes hex = 160 chars) to extract fields.
21
+ * Bitcoin block header layout:
22
+ * - version: 4 bytes (LE)
23
+ * - prevHash: 32 bytes
24
+ * - merkleRoot: 32 bytes
25
+ * - timestamp: 4 bytes (LE)
26
+ * - bits: 4 bytes
27
+ * - nonce: 4 bytes
28
+ */
29
+ function parseBlockHeader(headerHex) {
30
+ const headerBytes = hex.decode(headerHex);
31
+ if (headerBytes.length !== BLOCK_HEADER_SIZE) {
32
+ throw new Error(`Invalid block header size: ${headerBytes.length}, expected ${BLOCK_HEADER_SIZE}`);
33
+ }
34
+ // timestamp is at offset 68 (4+32+32), 4 bytes little-endian
35
+ const view = new DataView(headerBytes.buffer, headerBytes.byteOffset);
36
+ const timestamp = view.getUint32(68, true);
37
+ // block hash = double SHA256 of header, reversed
38
+ const hash1 = sha256(headerBytes);
39
+ const hash2 = sha256(hash1);
40
+ const hashStr = hex.encode(new Uint8Array(hash2).reverse());
41
+ return { hash: hashStr, timestamp };
42
+ }
43
+ /**
44
+ * WebSocket-based Electrum chain source using ws-electrumx-client.
45
+ * Provides low-level methods for the Electrum protocol.
46
+ *
47
+ * @example
48
+ * ```typescript
49
+ * import { ElectrumWS } from "ws-electrumx-client";
50
+ * import { WsElectrumChainSource } from './providers/electrum.js';
51
+ * import { networks } from './networks.js';
52
+ *
53
+ * const ws = new ElectrumWS("wss://electrum.blockstream.info:50004");
54
+ * const chain = new WsElectrumChainSource(ws, networks.bitcoin);
55
+ *
56
+ * const history = await chain.fetchHistories([script]);
57
+ * await chain.close();
58
+ * ```
59
+ */
60
+ export class WsElectrumChainSource {
61
+ constructor(ws, network) {
62
+ this.ws = ws;
63
+ this.network = network;
64
+ // Cached chain tip kept fresh by the headers subscription. Initialized
65
+ // lazily on first call to subscribeHeaders().
66
+ this.cachedTip = null;
67
+ this.headersSubscribePromise = null;
68
+ }
69
+ async fetchTransactions(txids) {
70
+ const requests = txids.map((txid) => ({
71
+ method: GetTransactionMethod,
72
+ params: [txid],
73
+ }));
74
+ for (let i = 0; i < MAX_FETCH_TRANSACTIONS_ATTEMPTS; i++) {
75
+ try {
76
+ const responses = await this.ws.batchRequest(...requests);
77
+ return responses.map((hexStr, i) => ({
78
+ txID: txids[i],
79
+ hex: hexStr,
80
+ }));
81
+ }
82
+ catch (e) {
83
+ const msg = e instanceof Error ? e.message : String(e);
84
+ if (msg.toLowerCase().includes(MISSING_TRANSACTION)) {
85
+ console.warn("missing transaction error, retrying");
86
+ await new Promise((resolve) => setTimeout(resolve, 1000));
87
+ continue;
88
+ }
89
+ throw e;
90
+ }
91
+ }
92
+ throw new Error("Unable to fetch transactions: " + txids);
93
+ }
94
+ async fetchVerboseTransaction(txid) {
95
+ return this.ws.request(GetTransactionMethod, txid, true);
96
+ }
97
+ async fetchVerboseTransactions(txids) {
98
+ if (txids.length === 0)
99
+ return [];
100
+ const requests = txids.map((txid) => ({
101
+ method: GetTransactionMethod,
102
+ params: [txid, true],
103
+ }));
104
+ return this.ws.batchRequest(...requests);
105
+ }
106
+ async unsubscribeScriptStatus(script) {
107
+ await this.ws
108
+ .unsubscribe(SubscribeStatusMethod, toScriptHash(script))
109
+ .catch(() => { });
110
+ }
111
+ async subscribeScriptStatus(script, callback) {
112
+ const scriptHash = toScriptHash(script);
113
+ await this.ws.subscribe(SubscribeStatusMethod, (scripthash, status) => {
114
+ if (scripthash === scriptHash) {
115
+ callback(scripthash, status);
116
+ }
117
+ }, scriptHash);
118
+ }
119
+ async fetchHistories(scripts) {
120
+ const scriptsHashes = scripts.map((s) => toScriptHash(s));
121
+ const responses = await this.ws.batchRequest(...scriptsHashes.map((s) => ({
122
+ method: GetHistoryMethod,
123
+ params: [s],
124
+ })));
125
+ return responses;
126
+ }
127
+ async fetchHistory(script) {
128
+ const scriptHash = toScriptHash(script);
129
+ return this.ws.request(GetHistoryMethod, scriptHash);
130
+ }
131
+ async fetchBlockHeaders(heights) {
132
+ const responses = await this.ws.batchRequest(...heights.map((h) => ({ method: GetBlockHeader, params: [h] })));
133
+ return responses.map((hexStr, i) => ({
134
+ height: heights[i],
135
+ hex: hexStr,
136
+ }));
137
+ }
138
+ async fetchBlockHeader(height) {
139
+ const headerHex = await this.ws.request(GetBlockHeader, height);
140
+ return { height, hex: headerHex };
141
+ }
142
+ /**
143
+ * Returns the current chain tip and keeps it fresh via a single
144
+ * server-side subscription. Subsequent calls return the cached tip
145
+ * (updated by background notifications) without round-tripping to the
146
+ * server. Previously each call issued `blockchain.headers.subscribe` as
147
+ * a regular request, leaving a stale subscription on the server every
148
+ * time — under polling that adds up. ws-electrumx-client deduplicates
149
+ * `subscribe()` by method+params, so registering once is enough.
150
+ */
151
+ async subscribeHeaders() {
152
+ if (this.cachedTip)
153
+ return this.cachedTip;
154
+ if (this.headersSubscribePromise)
155
+ return this.headersSubscribePromise;
156
+ this.headersSubscribePromise = new Promise((resolve, reject) => {
157
+ let resolved = false;
158
+ this.ws
159
+ .subscribe(SubscribeHeadersMethod, (header) => {
160
+ if (!isHeaderSubscribeResult(header))
161
+ return;
162
+ this.cachedTip = header;
163
+ if (!resolved) {
164
+ resolved = true;
165
+ resolve(header);
166
+ }
167
+ })
168
+ .catch((err) => {
169
+ if (!resolved) {
170
+ resolved = true;
171
+ reject(err);
172
+ }
173
+ });
174
+ });
175
+ try {
176
+ return await this.headersSubscribePromise;
177
+ }
178
+ catch (err) {
179
+ // Allow the next call to retry from scratch.
180
+ this.headersSubscribePromise = null;
181
+ throw err;
182
+ }
183
+ }
184
+ async estimateFees(targetNumberBlocks) {
185
+ const feeRate = await this.ws.request(EstimateFee, targetNumberBlocks);
186
+ return feeRate;
187
+ }
188
+ async broadcastTransaction(txHex) {
189
+ return this.ws.request(BroadcastTransaction, txHex);
190
+ }
191
+ /**
192
+ * Submit a package of raw transactions atomically via Fulcrum's
193
+ * `blockchain.transaction.broadcast_package` method, the on-the-wire
194
+ * equivalent of bitcoind's `submitpackage` RPC.
195
+ *
196
+ * Required for TRUC (BIP 431) 1P1C relay where the parent has zero
197
+ * (or below-minfee) fee and depends on the child to pay for both via
198
+ * CPFP — sequential broadcast cannot work in that case because the
199
+ * parent would be rejected from the mempool on its own.
200
+ *
201
+ * @param txHexes - Topologically sorted raw transactions; child must
202
+ * be the last element. Currently must be a 1P1C pair
203
+ * (length 2). Parents may not depend on each other.
204
+ * @returns The child transaction id (the last entry in the array),
205
+ * computed locally — `broadcast_package` itself returns
206
+ * `{success, errors}` rather than a txid.
207
+ * @throws If the server does not implement `broadcast_package` (e.g.
208
+ * ElectrumX, or older Fulcrum, or Fulcrum backed by bitcoind
209
+ * < v28.0.0). Callers must surface this clearly to users —
210
+ * this method does NOT silently fall back to sequential
211
+ * broadcasts because doing so would let TRUC packages fail
212
+ * in subtle ways.
213
+ * @throws If the server returns `success=false`, surfacing the
214
+ * underlying mempool rejection in the error message.
215
+ */
216
+ async broadcastPackage(txHexes) {
217
+ const result = await this.ws.request(BroadcastPackageMethod, txHexes, false);
218
+ if (!result.success) {
219
+ const detail = result.errors
220
+ ? JSON.stringify(result.errors)
221
+ : "unknown error";
222
+ throw new Error(`Package broadcast rejected: ${detail}`);
223
+ }
224
+ // The child txid is not in the response — derive it from the raw
225
+ // bytes (double-SHA256 of the serialized tx, reversed).
226
+ return childTxidFromHex(txHexes[txHexes.length - 1]);
227
+ }
228
+ async getRelayFee() {
229
+ return this.ws.request(GetRelayFeeMethod);
230
+ }
231
+ async close() {
232
+ try {
233
+ await this.ws.close("close");
234
+ }
235
+ catch (e) {
236
+ console.debug("error closing ws:", e);
237
+ }
238
+ }
239
+ waitForAddressReceivesTx(addr) {
240
+ return new Promise((resolve, reject) => {
241
+ const script = OutScript.encode(Address(this.network).decode(addr));
242
+ this.subscribeScriptStatus(script, (_, status) => {
243
+ if (status !== null) {
244
+ resolve();
245
+ }
246
+ }).catch(reject);
247
+ });
248
+ }
249
+ async listUnspents(addr) {
250
+ const script = OutScript.encode(Address(this.network).decode(addr));
251
+ const scriptHash = toScriptHash(script);
252
+ const unspentsFromElectrum = await this.ws.request(ListUnspentMethod, scriptHash);
253
+ const txs = await this.fetchTransactions(unspentsFromElectrum.map((u) => u.tx_hash));
254
+ return unspentsFromElectrum.map((u, index) => {
255
+ const tx = Transaction.fromRaw(hex.decode(txs[index].hex), {
256
+ allowUnknownOutputs: true,
257
+ });
258
+ const output = tx.getOutput(u.tx_pos);
259
+ if (!output.script || output.amount === undefined) {
260
+ throw new Error(`Missing output data for ${u.tx_hash}:${u.tx_pos}`);
261
+ }
262
+ return {
263
+ txid: u.tx_hash,
264
+ vout: u.tx_pos,
265
+ witnessUtxo: {
266
+ script: output.script,
267
+ value: output.amount,
268
+ },
269
+ };
270
+ });
271
+ }
272
+ /**
273
+ * Get the address string for a script output, if decodable.
274
+ */
275
+ addressForScript(scriptHex) {
276
+ try {
277
+ const script = hex.decode(scriptHex);
278
+ return Address(this.network).encode(OutScript.decode(script));
279
+ }
280
+ catch {
281
+ return undefined;
282
+ }
283
+ }
284
+ }
285
+ /**
286
+ * Electrum-based implementation of the OnchainProvider interface.
287
+ * Replaces esplora polling with electrum subscriptions where possible.
288
+ *
289
+ * @example
290
+ * ```typescript
291
+ * import { ElectrumWS } from "ws-electrumx-client";
292
+ * import { ElectrumOnchainProvider } from './providers/electrum.js';
293
+ * import { networks } from './networks.js';
294
+ *
295
+ * const ws = new ElectrumWS("wss://electrum.blockstream.info:50004");
296
+ * const provider = new ElectrumOnchainProvider(ws, networks.bitcoin);
297
+ *
298
+ * const coins = await provider.getCoins("bc1q...");
299
+ * ```
300
+ */
301
+ export class ElectrumOnchainProvider {
302
+ constructor(ws, network) {
303
+ this.ws = ws;
304
+ this.network = network;
305
+ this.chain = new WsElectrumChainSource(ws, network);
306
+ }
307
+ async getCoins(address) {
308
+ const script = this.encodeAddress(address);
309
+ const scriptHash = toScriptHash(script);
310
+ const unspents = await this.ws.request(ListUnspentMethod, scriptHash);
311
+ return unspents.map((u) => ({
312
+ txid: u.tx_hash,
313
+ vout: u.tx_pos,
314
+ value: u.value,
315
+ status: {
316
+ confirmed: u.height > 0,
317
+ block_height: u.height > 0 ? u.height : undefined,
318
+ },
319
+ }));
320
+ }
321
+ async getFeeRate() {
322
+ // electrum returns BTC/kB, we need sat/vB
323
+ // 1 BTC = 100_000_000 sat, 1 kB = 1000 bytes
324
+ // sat/vB = (BTC/kB) * 100_000_000 / 1000 = (BTC/kB) * 100_000
325
+ const feePerKb = await this.chain.estimateFees(1);
326
+ if (feePerKb < 0) {
327
+ // -1 means the daemon cannot estimate
328
+ return undefined;
329
+ }
330
+ return Math.max(1, Math.ceil(feePerKb * 100000));
331
+ }
332
+ /**
333
+ * Broadcast a single transaction or a TRUC (BIP 431) 1P1C package
334
+ * atomically.
335
+ *
336
+ * **Server requirements for 1P1C packages:** the backing Electrum
337
+ * server must implement `blockchain.transaction.broadcast_package`
338
+ * (Fulcrum ≥ 1.10) and be backed by bitcoind ≥ v28.0.0. ElectrumX
339
+ * does not implement this method. There is **no fallback** to
340
+ * sequential parent-then-child broadcast: TRUC packages typically
341
+ * have a zero-fee parent and would be rejected from the mempool on
342
+ * their own, so a fallback would silently fail in subtle ways.
343
+ * Callers receiving a "method not found" error here should route
344
+ * through a different provider for that submission.
345
+ *
346
+ * @param txs - One transaction (single broadcast) or two
347
+ * topologically-sorted transactions (parent first,
348
+ * child last) for 1P1C package relay.
349
+ * @returns The broadcast txid (or the child txid for 1P1C packages).
350
+ */
351
+ async broadcastTransaction(...txs) {
352
+ if (txs.length === 1) {
353
+ return this.chain.broadcastTransaction(txs[0]);
354
+ }
355
+ if (txs.length === 2) {
356
+ return this.chain.broadcastPackage(txs);
357
+ }
358
+ throw new Error("Only 1 or 1P1C package can be broadcast");
359
+ }
360
+ async getTxOutspends(txid) {
361
+ // Step 1: fetch the creating tx to get its output scripts (1 round trip)
362
+ const [txResult] = await this.chain.fetchTransactions([txid]);
363
+ const tx = Transaction.fromRaw(hex.decode(txResult.hex), {
364
+ allowUnknownOutputs: true,
365
+ });
366
+ const outputCount = tx.outputsLength;
367
+ const outputScriptHashes = [];
368
+ for (let i = 0; i < outputCount; i++) {
369
+ const output = tx.getOutput(i);
370
+ outputScriptHashes.push(output.script ? toScriptHash(output.script) : undefined);
371
+ }
372
+ const validScriptHashes = outputScriptHashes.filter((h) => h !== undefined);
373
+ const results = Array.from({ length: outputCount }, () => ({ spent: false, txid: "" }));
374
+ if (validScriptHashes.length === 0)
375
+ return results;
376
+ // Step 2: batch listunspent for all output scripthashes (1 round trip)
377
+ // This tells us exactly which txid:vout pairs are still unspent.
378
+ const unspentBatch = await this.ws.batchRequest(...validScriptHashes.map((sh) => ({
379
+ method: ListUnspentMethod,
380
+ params: [sh],
381
+ })));
382
+ const unspentSet = new Set();
383
+ let validIdx = 0;
384
+ for (let i = 0; i < outputCount; i++) {
385
+ if (outputScriptHashes[i] !== undefined) {
386
+ for (const u of unspentBatch[validIdx]) {
387
+ unspentSet.add(`${u.tx_hash}:${u.tx_pos}`);
388
+ }
389
+ validIdx++;
390
+ }
391
+ }
392
+ // Step 3: batch get_history only for spent outputs (1 round trip)
393
+ const spentIndices = [];
394
+ const spentScriptHashes = [];
395
+ for (let i = 0; i < outputCount; i++) {
396
+ const sh = outputScriptHashes[i];
397
+ if (sh && !unspentSet.has(`${txid}:${i}`)) {
398
+ spentIndices.push(i);
399
+ spentScriptHashes.push(sh);
400
+ }
401
+ }
402
+ if (spentIndices.length === 0)
403
+ return results;
404
+ const histories = await this.ws.batchRequest(...spentScriptHashes.map((sh) => ({
405
+ method: GetHistoryMethod,
406
+ params: [sh],
407
+ })));
408
+ // For each spent output find the spender in its history.
409
+ // Common case: history has exactly 2 entries (creating + spending tx).
410
+ // Ambiguous case (same script reused): batch-fetch all candidates at once.
411
+ const ambiguousIndices = [];
412
+ const ambiguousCandidates = [];
413
+ for (let j = 0; j < spentIndices.length; j++) {
414
+ const i = spentIndices[j];
415
+ const candidates = histories[j]
416
+ .map((h) => h.tx_hash)
417
+ .filter((hash) => hash !== txid);
418
+ if (candidates.length === 1) {
419
+ // Fast path: one candidate = the spender
420
+ results[i] = { spent: true, txid: candidates[0] };
421
+ }
422
+ else if (candidates.length > 1) {
423
+ ambiguousIndices.push(i);
424
+ ambiguousCandidates.push(candidates);
425
+ }
426
+ // candidates.length === 0 → mempool eviction, treat as unspent
427
+ }
428
+ // Step 4 (rare): batch-fetch all ambiguous candidate txs at once
429
+ if (ambiguousIndices.length > 0) {
430
+ const allCandidateTxids = [...new Set(ambiguousCandidates.flat())];
431
+ const fetched = await this.chain.fetchTransactions(allCandidateTxids);
432
+ const txMap = new Map(fetched.map((t) => [t.txID, t.hex]));
433
+ for (let j = 0; j < ambiguousIndices.length; j++) {
434
+ const i = ambiguousIndices[j];
435
+ for (const candidateTxid of ambiguousCandidates[j]) {
436
+ const rawHex = txMap.get(candidateTxid);
437
+ if (!rawHex)
438
+ continue;
439
+ const candidateTx = Transaction.fromRaw(hex.decode(rawHex), { allowUnknownOutputs: true, allowUnknownInputs: true });
440
+ let found = false;
441
+ for (let k = 0; k < candidateTx.inputsLength; k++) {
442
+ const input = candidateTx.getInput(k);
443
+ if (input.txid &&
444
+ hex.encode(input.txid) === txid &&
445
+ input.index === i) {
446
+ results[i] = { spent: true, txid: candidateTxid };
447
+ found = true;
448
+ break;
449
+ }
450
+ }
451
+ if (found)
452
+ break;
453
+ }
454
+ }
455
+ }
456
+ return results;
457
+ }
458
+ async getTransactions(address) {
459
+ const script = this.encodeAddress(address);
460
+ const history = await this.chain.fetchHistory(script);
461
+ if (history.length === 0)
462
+ return [];
463
+ const txids = history.map((h) => h.tx_hash);
464
+ const verboseTxs = await this.chain.fetchVerboseTransactions(txids);
465
+ return verboseTxs.map((vtx) => this.verboseToExplorer(vtx));
466
+ }
467
+ /**
468
+ * Map an electrum verbose transaction to the ExplorerTransaction shape.
469
+ *
470
+ * Output values are derived from the raw transaction hex when available,
471
+ * never from the floating-point `value` field returned by the daemon.
472
+ * That field has 8 decimal places and `Math.round(value * 1e8)` is safe
473
+ * in the common case but a footgun for protocol-level money handling —
474
+ * the raw bytes are exact.
475
+ */
476
+ verboseToExplorer(vtx) {
477
+ const exactValuesByVout = parseExactSats(vtx);
478
+ return {
479
+ txid: vtx.txid,
480
+ vout: vtx.vout.map((v) => ({
481
+ scriptpubkey_address: v.scriptPubKey.address ||
482
+ v.scriptPubKey.addresses?.[0] ||
483
+ this.chain.addressForScript(v.scriptPubKey.hex) ||
484
+ "",
485
+ value: exactValuesByVout?.get(v.n) ??
486
+ String(Math.round(v.value * 1e8)),
487
+ })),
488
+ status: {
489
+ confirmed: vtx.confirmations > 0,
490
+ block_time: vtx.blocktime || vtx.time || 0,
491
+ },
492
+ };
493
+ }
494
+ /**
495
+ * Decode `address` into its scriptPubKey, throwing a clear error if the
496
+ * input is malformed. @scure/btc-signer raises a generic decode error
497
+ * which is hard to map back to user input — this wraps it.
498
+ */
499
+ encodeAddress(address) {
500
+ try {
501
+ return OutScript.encode(Address(this.network).decode(address));
502
+ }
503
+ catch (err) {
504
+ const reason = err instanceof Error ? err.message : String(err);
505
+ throw new Error(`Invalid address ${address}: ${reason}`);
506
+ }
507
+ }
508
+ async getTxStatus(txid) {
509
+ const vtx = await this.chain.fetchVerboseTransaction(txid);
510
+ if (vtx.confirmations <= 0) {
511
+ return { confirmed: false };
512
+ }
513
+ // Get block height from the verbose tx's blockhash
514
+ // We need the height, which is confirmations-based:
515
+ // height = tipHeight - confirmations + 1
516
+ const tip = await this.chain.subscribeHeaders();
517
+ const blockHeight = tip.height - vtx.confirmations + 1;
518
+ return {
519
+ confirmed: true,
520
+ blockTime: vtx.blocktime || vtx.time || 0,
521
+ blockHeight,
522
+ };
523
+ }
524
+ async getChainTip() {
525
+ const tip = await this.chain.subscribeHeaders();
526
+ const { hash, timestamp } = parseBlockHeader(tip.hex);
527
+ return {
528
+ height: tip.height,
529
+ time: timestamp,
530
+ hash,
531
+ };
532
+ }
533
+ async watchAddresses(addresses, eventCallback) {
534
+ const scripts = addresses.map((addr) => this.encodeAddress(addr));
535
+ const scriptHashes = scripts.map(toScriptHash);
536
+ // O(1) scripthash → script lookup, kept in sync with the
537
+ // scripts/scriptHashes arrays. Server notifications hit this on
538
+ // every push, so the previous indexOf was O(n) per event.
539
+ const scriptByHash = new Map(scriptHashes.map((h, i) => [h, scripts[i]]));
540
+ // Track known history per script to detect new txs.
541
+ const knownTxids = new Map();
542
+ // Initialize known-set in parallel — for a wallet watching many
543
+ // addresses this avoids n sequential round trips on first call.
544
+ const initialHistories = await Promise.all(scripts.map((s) => this.chain.fetchHistory(s)));
545
+ initialHistories.forEach((history, i) => {
546
+ knownTxids.set(scriptHashes[i], new Set(history.map((h) => h.tx_hash)));
547
+ });
548
+ // Per-scripthash mutex serializing concurrent notifications so
549
+ // two pushes for the same address can't fetch history in parallel
550
+ // and emit duplicate events. Each call chains onto the previous
551
+ // one's tail; failures are swallowed to keep the chain alive.
552
+ const inFlight = new Map();
553
+ const processStatusChange = async (scripthash) => {
554
+ const script = scriptByHash.get(scripthash);
555
+ if (!script)
556
+ return;
557
+ const history = await this.chain.fetchHistory(script);
558
+ const known = knownTxids.get(scripthash) ?? new Set();
559
+ const newTxids = history
560
+ .map((h) => h.tx_hash)
561
+ .filter((txid) => !known.has(txid));
562
+ if (newTxids.length === 0)
563
+ return;
564
+ for (const txid of newTxids)
565
+ known.add(txid);
566
+ knownTxids.set(scripthash, known);
567
+ const verboseTxs = await this.chain.fetchVerboseTransactions(newTxids);
568
+ eventCallback(verboseTxs.map((vtx) => this.verboseToExplorer(vtx)));
569
+ };
570
+ const handleStatusChange = (scripthash) => {
571
+ const previous = inFlight.get(scripthash) ?? Promise.resolve();
572
+ const next = previous.then(() => processStatusChange(scripthash));
573
+ // Keep the chain alive even when one link rejects.
574
+ inFlight.set(scripthash, next.catch(() => undefined));
575
+ return next;
576
+ };
577
+ // Register all subscriptions in parallel; if any one fails, tear
578
+ // down the others so we don't leak server-side subscriptions on
579
+ // a connection the caller never gets a stop() handle for.
580
+ const subscribed = [];
581
+ try {
582
+ await Promise.all(scripts.map(async (script) => {
583
+ await this.chain.subscribeScriptStatus(script, (scripthash, status) => {
584
+ if (status !== null) {
585
+ handleStatusChange(scripthash).catch(console.error);
586
+ }
587
+ });
588
+ subscribed.push(script);
589
+ }));
590
+ }
591
+ catch (err) {
592
+ await Promise.allSettled(subscribed.map((s) => this.chain.unsubscribeScriptStatus(s)));
593
+ throw err;
594
+ }
595
+ return () => {
596
+ for (const script of scripts) {
597
+ this.chain.unsubscribeScriptStatus(script).catch(() => { });
598
+ }
599
+ };
600
+ }
601
+ /** Close the underlying WebSocket connection. */
602
+ async close() {
603
+ await this.chain.close();
604
+ }
605
+ }
606
+ function toScriptHash(script) {
607
+ return hex.encode(sha256(script).reverse());
608
+ }
609
+ function isHeaderSubscribeResult(v) {
610
+ if (typeof v !== "object" || v === null)
611
+ return false;
612
+ const obj = v;
613
+ return typeof obj.height === "number" && typeof obj.hex === "string";
614
+ }
615
+ /**
616
+ * Compute the txid of a serialized transaction. For segwit transactions
617
+ * (every Ark transaction), the broadcast hex includes witness data, but
618
+ * the txid is the double-SHA256 of the legacy (witness-stripped)
619
+ * serialization. Hashing the raw broadcast bytes directly would yield
620
+ * the wtxid instead — silently breaking any caller that tracks the tx
621
+ * by id (round settlement, forfeit monitoring, exit paths).
622
+ *
623
+ * Delegating to `Transaction.fromRaw(...).id` lets @scure/btc-signer
624
+ * handle the witness-stripping correctly.
625
+ */
626
+ function childTxidFromHex(txHex) {
627
+ const tx = Transaction.fromRaw(hex.decode(txHex), {
628
+ allowUnknownOutputs: true,
629
+ allowUnknownInputs: true,
630
+ });
631
+ return tx.id;
632
+ }
633
+ /**
634
+ * Decode `vtx.hex` (when the daemon includes it) and return a map of
635
+ * vout-index → exact sat amount as a base-10 string. Returns `null` if
636
+ * the hex is missing or unparseable; callers should fall back to the
637
+ * float-derived value in that case.
638
+ */
639
+ function parseExactSats(vtx) {
640
+ if (!vtx.hex)
641
+ return null;
642
+ try {
643
+ const tx = Transaction.fromRaw(hex.decode(vtx.hex), {
644
+ allowUnknownOutputs: true,
645
+ });
646
+ const result = new Map();
647
+ for (let i = 0; i < tx.outputsLength; i++) {
648
+ const output = tx.getOutput(i);
649
+ if (output.amount === undefined)
650
+ continue;
651
+ result.set(i, output.amount.toString());
652
+ }
653
+ return result;
654
+ }
655
+ catch {
656
+ return null;
657
+ }
658
+ }
@@ -1,6 +1,6 @@
1
1
  import { hex } from "@scure/base";
2
2
  import { isFetchTimeoutError } from './ark.js';
3
- import { eventSourceIterator } from './utils.js';
3
+ import { eventSourceIterator, isEventSourceError } from './utils.js';
4
4
  import { MetadataList } from '../extension/asset/index.js';
5
5
  export var IndexerTxType;
6
6
  (function (IndexerTxType) {
@@ -193,7 +193,8 @@ export class RestIndexerProvider {
193
193
  }
194
194
  }
195
195
  catch (error) {
196
- if (error instanceof Error && error.name === "AbortError") {
196
+ if (abortSignal?.aborted ||
197
+ (error instanceof Error && error.name === "AbortError")) {
197
198
  break;
198
199
  }
199
200
  // ignore timeout errors, they're expected when the server is not sending anything for 5 min
@@ -201,6 +202,9 @@ export class RestIndexerProvider {
201
202
  console.debug("Timeout error ignored");
202
203
  continue;
203
204
  }
205
+ if (isEventSourceError(error)) {
206
+ throw error;
207
+ }
204
208
  console.error("Subscription error:", error);
205
209
  throw error;
206
210
  }
@@ -66,3 +66,6 @@ export function eventSourceIterator(eventSource) {
66
66
  }
67
67
  })();
68
68
  }
69
+ export function isEventSourceError(error) {
70
+ return error instanceof Error && error.name === "EventSourceError";
71
+ }