@arkade-os/sdk 0.4.52 → 0.4.54

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 (81) hide show
  1. package/dist/adapters/expo.cjs +5 -5
  2. package/dist/adapters/expo.d.cts +2 -2
  3. package/dist/adapters/expo.d.ts +2 -2
  4. package/dist/adapters/expo.js +3 -3
  5. package/dist/adapters/indexedDB.cjs +5 -5
  6. package/dist/adapters/indexedDB.js +4 -4
  7. package/dist/{ark-B69ugeJw.d.cts → ark-acFuA57I.d.cts} +2 -1
  8. package/dist/{ark-B69ugeJw.d.ts → ark-acFuA57I.d.ts} +2 -1
  9. package/dist/{asyncStorageTaskQueue-DScPdQAy.d.cts → asyncStorageTaskQueue-BO3cvMpP.d.cts} +1 -1
  10. package/dist/{asyncStorageTaskQueue-BImF14sj.d.ts → asyncStorageTaskQueue-DACXtP0I.d.ts} +1 -1
  11. package/dist/chunk-4EIKOJLD.js +2319 -0
  12. package/dist/chunk-4EIKOJLD.js.map +1 -0
  13. package/dist/{chunk-IEMPH7J6.cjs → chunk-53XNU2EL.cjs} +40 -40
  14. package/dist/{chunk-IEMPH7J6.cjs.map → chunk-53XNU2EL.cjs.map} +1 -1
  15. package/dist/{chunk-3ZGANANS.js → chunk-7L3P3EP5.js} +4 -4
  16. package/dist/{chunk-3ZGANANS.js.map → chunk-7L3P3EP5.js.map} +1 -1
  17. package/dist/{chunk-UZLQUWYP.js → chunk-A37WVZ5T.js} +3 -3
  18. package/dist/{chunk-UZLQUWYP.js.map → chunk-A37WVZ5T.js.map} +1 -1
  19. package/dist/{chunk-E6RT5XYB.cjs → chunk-BYJJIITU.cjs} +17 -17
  20. package/dist/{chunk-E6RT5XYB.cjs.map → chunk-BYJJIITU.cjs.map} +1 -1
  21. package/dist/{chunk-ML33GFCH.cjs → chunk-D5LUPJJP.cjs} +837 -437
  22. package/dist/chunk-D5LUPJJP.cjs.map +1 -0
  23. package/dist/chunk-GMUVWKOK.cjs +2407 -0
  24. package/dist/chunk-GMUVWKOK.cjs.map +1 -0
  25. package/dist/{chunk-WIVQWYPZ.js → chunk-QY2YVFZT.js} +4 -4
  26. package/dist/{chunk-WIVQWYPZ.js.map → chunk-QY2YVFZT.js.map} +1 -1
  27. package/dist/{chunk-FZPYPEWN.cjs → chunk-RNECH3TA.cjs} +19 -1367
  28. package/dist/chunk-RNECH3TA.cjs.map +1 -0
  29. package/dist/{chunk-AXCKRS2D.js → chunk-TEHJCEF3.js} +473 -91
  30. package/dist/chunk-TEHJCEF3.js.map +1 -0
  31. package/dist/{chunk-3Z5HK35D.cjs → chunk-YRLBZJYO.cjs} +9 -9
  32. package/dist/{chunk-3Z5HK35D.cjs.map → chunk-YRLBZJYO.cjs.map} +1 -1
  33. package/dist/{chunk-ZK3JITHP.js → chunk-ZOY5JSVA.js} +8 -1327
  34. package/dist/chunk-ZOY5JSVA.js.map +1 -0
  35. package/dist/contracts/handlers/index.cjs +8 -8
  36. package/dist/contracts/handlers/index.d.cts +3 -3
  37. package/dist/contracts/handlers/index.d.ts +3 -3
  38. package/dist/contracts/handlers/index.js +2 -2
  39. package/dist/{delegate-C_Y2YrXC.d.cts → delegate-Ca_wXiYE.d.cts} +1 -1
  40. package/dist/{delegate-BU-Cpyjw.d.ts → delegate-DjwZZi6L.d.ts} +1 -1
  41. package/dist/{index-tzAInyiX.d.cts → index-DFfefdpc.d.cts} +2 -2
  42. package/dist/{index-BWF-C9eh.d.ts → index-Ddq0mIKX.d.ts} +2 -2
  43. package/dist/index.cjs +319 -239
  44. package/dist/index.d.cts +300 -12
  45. package/dist/index.d.ts +300 -12
  46. package/dist/index.js +4 -4
  47. package/dist/repositories/realm/index.cjs +19 -19
  48. package/dist/repositories/realm/index.d.cts +2 -2
  49. package/dist/repositories/realm/index.d.ts +2 -2
  50. package/dist/repositories/realm/index.js +5 -5
  51. package/dist/repositories/sqlite/index.cjs +18 -18
  52. package/dist/repositories/sqlite/index.d.cts +2 -2
  53. package/dist/repositories/sqlite/index.d.ts +2 -2
  54. package/dist/repositories/sqlite/index.js +5 -5
  55. package/dist/{taskRunner-ClwI8jU8.d.cts → taskRunner-DEwlrgId.d.cts} +1 -1
  56. package/dist/{taskRunner-Cf80BqSy.d.ts → taskRunner-DbCNRP31.d.ts} +1 -1
  57. package/dist/wallet/expo/background.cjs +15 -15
  58. package/dist/wallet/expo/background.cjs.map +1 -1
  59. package/dist/wallet/expo/background.d.cts +3 -3
  60. package/dist/wallet/expo/background.d.ts +3 -3
  61. package/dist/wallet/expo/background.js +7 -7
  62. package/dist/wallet/expo/background.js.map +1 -1
  63. package/dist/wallet/expo/index.cjs +14 -14
  64. package/dist/wallet/expo/index.d.cts +4 -4
  65. package/dist/wallet/expo/index.d.ts +4 -4
  66. package/dist/wallet/expo/index.js +5 -5
  67. package/dist/{wallet-B6Xiferv.d.cts → wallet-B9rpddG2.d.ts} +2 -2
  68. package/dist/{wallet-CuHAI-eW.d.ts → wallet-ByjM6L20.d.cts} +2 -2
  69. package/dist/worker/expo/index.cjs +9 -9
  70. package/dist/worker/expo/index.d.cts +4 -4
  71. package/dist/worker/expo/index.d.ts +4 -4
  72. package/dist/worker/expo/index.js +5 -5
  73. package/package.json +1 -1
  74. package/dist/chunk-AXCKRS2D.js.map +0 -1
  75. package/dist/chunk-E7HB3GKK.cjs +0 -1030
  76. package/dist/chunk-E7HB3GKK.cjs.map +0 -1
  77. package/dist/chunk-EFNLTS6Q.js +0 -976
  78. package/dist/chunk-EFNLTS6Q.js.map +0 -1
  79. package/dist/chunk-FZPYPEWN.cjs.map +0 -1
  80. package/dist/chunk-ML33GFCH.cjs.map +0 -1
  81. package/dist/chunk-ZK3JITHP.js.map +0 -1
@@ -0,0 +1,2319 @@
1
+ import { ScriptNum, OP, p2tr_ms, Script, SigHash, p2tr, TAPROOT_UNSPENDABLE_KEY, Address, RawWitness, Transaction as Transaction$1 } from '@scure/btc-signer';
2
+ import * as bip68 from 'bip68';
3
+ import { TEST_NETWORK, NETWORK } from '@scure/btc-signer/utils.js';
4
+ import { hex, bech32m } from '@scure/base';
5
+ import { Script as Script$1 } from '@scure/btc-signer/script.js';
6
+ import { TAP_LEAF_VERSION } from '@scure/btc-signer/payment.js';
7
+ import { PSBTOutput } from '@scure/btc-signer/psbt.js';
8
+ import { schnorr } from '@noble/curves/secp256k1.js';
9
+
10
+ // src/utils/transaction.ts
11
+ var Transaction = class extends Transaction$1 {
12
+ static ARK_TX_OPTS = {
13
+ allowUnknown: true,
14
+ allowUnknownOutputs: true,
15
+ allowUnknownInputs: true
16
+ };
17
+ constructor(opts) {
18
+ super(withArkOpts(opts));
19
+ }
20
+ static fromPSBT(psbt_, opts) {
21
+ return Transaction$1.fromPSBT(psbt_, withArkOpts(opts));
22
+ }
23
+ static fromRaw(raw, opts) {
24
+ return Transaction$1.fromRaw(raw, withArkOpts(opts));
25
+ }
26
+ };
27
+ function withArkOpts(opts) {
28
+ return { ...Transaction.ARK_TX_OPTS, ...opts };
29
+ }
30
+ function timelockToSequence(timelock) {
31
+ return bip68.encode(
32
+ timelock.type === "blocks" ? { blocks: Number(timelock.value) } : { seconds: Number(timelock.value) }
33
+ );
34
+ }
35
+ function sequenceToTimelock(sequence) {
36
+ const decoded = bip68.decode(sequence);
37
+ if ("blocks" in decoded && decoded.blocks !== void 0) {
38
+ return { type: "blocks", value: BigInt(decoded.blocks) };
39
+ }
40
+ if ("seconds" in decoded && decoded.seconds !== void 0) {
41
+ return { type: "seconds", value: BigInt(decoded.seconds) };
42
+ }
43
+ throw new Error(`Invalid BIP68 sequence: ${sequence}`);
44
+ }
45
+ var ArkPsbtFieldKey = /* @__PURE__ */ ((ArkPsbtFieldKey2) => {
46
+ ArkPsbtFieldKey2["VtxoTaprootTree"] = "taptree";
47
+ ArkPsbtFieldKey2["VtxoTreeExpiry"] = "expiry";
48
+ ArkPsbtFieldKey2["Cosigner"] = "cosigner";
49
+ ArkPsbtFieldKey2["ConditionWitness"] = "condition";
50
+ ArkPsbtFieldKey2["PrevArkTx"] = "prevarktx";
51
+ ArkPsbtFieldKey2["PrevoutTx"] = "prevouttx";
52
+ return ArkPsbtFieldKey2;
53
+ })(ArkPsbtFieldKey || {});
54
+ var ArkPsbtFieldKeyType = 222;
55
+ function setArkPsbtField(tx, inputIndex, coder, value) {
56
+ tx.updateInput(inputIndex, {
57
+ unknown: [...tx.getInput(inputIndex)?.unknown ?? [], coder.encode(value)]
58
+ });
59
+ }
60
+ function getArkPsbtFields(tx, inputIndex, coder) {
61
+ const unknown = tx.getInput(inputIndex)?.unknown ?? [];
62
+ const fields = [];
63
+ for (const u of unknown) {
64
+ const v = coder.decode(u);
65
+ if (v !== null) fields.push(v);
66
+ }
67
+ return fields;
68
+ }
69
+ var VtxoTaprootTree = {
70
+ key: "taptree" /* VtxoTaprootTree */,
71
+ encode: (value) => [
72
+ {
73
+ type: ArkPsbtFieldKeyType,
74
+ key: encodedPsbtFieldKey["taptree" /* VtxoTaprootTree */]
75
+ },
76
+ value
77
+ ],
78
+ decode: (value) => nullIfCatch(() => {
79
+ if (!checkKeyMatch(value[0], "taptree" /* VtxoTaprootTree */)) return null;
80
+ return value[1];
81
+ })
82
+ };
83
+ var ConditionWitness = {
84
+ key: "condition" /* ConditionWitness */,
85
+ encode: (value) => [
86
+ {
87
+ type: ArkPsbtFieldKeyType,
88
+ key: encodedPsbtFieldKey["condition" /* ConditionWitness */]
89
+ },
90
+ RawWitness.encode(value)
91
+ ],
92
+ decode: (value) => nullIfCatch(() => {
93
+ if (!checkKeyMatch(value[0], "condition" /* ConditionWitness */)) return null;
94
+ return RawWitness.decode(value[1]);
95
+ })
96
+ };
97
+ var PrevArkTxField = {
98
+ key: "prevarktx" /* PrevArkTx */,
99
+ encode: (value) => [
100
+ {
101
+ type: ArkPsbtFieldKeyType,
102
+ key: encodedPsbtFieldKey["prevarktx" /* PrevArkTx */]
103
+ },
104
+ value
105
+ ],
106
+ decode: (value) => nullIfCatch(() => {
107
+ if (!checkKeyMatch(value[0], "prevarktx" /* PrevArkTx */)) return null;
108
+ return value[1];
109
+ })
110
+ };
111
+ var PrevoutTxField = {
112
+ key: "prevouttx" /* PrevoutTx */,
113
+ encode: (value) => [
114
+ {
115
+ type: ArkPsbtFieldKeyType,
116
+ key: encodedPsbtFieldKey["prevouttx" /* PrevoutTx */]
117
+ },
118
+ value
119
+ ],
120
+ decode: (value) => nullIfCatch(() => {
121
+ if (!checkKeyMatch(value[0], "prevouttx" /* PrevoutTx */)) return null;
122
+ return value[1];
123
+ })
124
+ };
125
+ var CosignerPublicKey = {
126
+ key: "cosigner" /* Cosigner */,
127
+ encode: (value) => [
128
+ {
129
+ type: ArkPsbtFieldKeyType,
130
+ key: new Uint8Array([...encodedPsbtFieldKey["cosigner" /* Cosigner */], value.index])
131
+ },
132
+ value.key
133
+ ],
134
+ decode: (unknown) => nullIfCatch(() => {
135
+ if (!checkKeyMatch(unknown[0], "cosigner" /* Cosigner */, true)) return null;
136
+ return {
137
+ index: unknown[0].key[unknown[0].key.length - 1],
138
+ key: unknown[1]
139
+ };
140
+ })
141
+ };
142
+ var VtxoTreeExpiry = {
143
+ key: "expiry" /* VtxoTreeExpiry */,
144
+ encode: (value) => [
145
+ {
146
+ type: ArkPsbtFieldKeyType,
147
+ key: encodedPsbtFieldKey["expiry" /* VtxoTreeExpiry */]
148
+ },
149
+ ScriptNum(6, true).encode(value.value === 0n ? 0n : value.value)
150
+ ],
151
+ decode: (unknown) => nullIfCatch(() => {
152
+ if (!checkKeyMatch(unknown[0], "expiry" /* VtxoTreeExpiry */)) return null;
153
+ const v = ScriptNum(6, true).decode(unknown[1]);
154
+ if (!v) return null;
155
+ return sequenceToTimelock(Number(v));
156
+ })
157
+ };
158
+ var encodedPsbtFieldKey = Object.fromEntries(
159
+ Object.values(ArkPsbtFieldKey).map((key) => [key, new TextEncoder().encode(key)])
160
+ );
161
+ var nullIfCatch = (fn) => {
162
+ try {
163
+ return fn();
164
+ } catch {
165
+ return null;
166
+ }
167
+ };
168
+ function checkKeyMatch(key, arkPsbtFieldKey, prefixOnly = false) {
169
+ if (key.type !== ArkPsbtFieldKeyType) return false;
170
+ const expected = encodedPsbtFieldKey[arkPsbtFieldKey];
171
+ if (key.key.length < expected.length) return false;
172
+ if (!prefixOnly && key.key.length !== expected.length) return false;
173
+ for (let i = 0; i < expected.length; i++) {
174
+ if (key.key[i] !== expected[i]) return false;
175
+ }
176
+ return true;
177
+ }
178
+ var getNetwork = (network) => {
179
+ const found = networks[network];
180
+ if (!found) throw new Error(`Unsupported network: ${network}`);
181
+ return found;
182
+ };
183
+ var networks = {
184
+ bitcoin: withArkPrefix(NETWORK, "ark"),
185
+ testnet: withArkPrefix(TEST_NETWORK, "tark"),
186
+ signet: withArkPrefix(TEST_NETWORK, "tark"),
187
+ mutinynet: withArkPrefix(TEST_NETWORK, "tark"),
188
+ regtest: withArkPrefix(
189
+ {
190
+ ...TEST_NETWORK,
191
+ bech32: "bcrt",
192
+ pubKeyHash: 111,
193
+ scriptHash: 196
194
+ },
195
+ "tark"
196
+ )
197
+ };
198
+ function withArkPrefix(network, prefix) {
199
+ return {
200
+ ...network,
201
+ hrp: prefix
202
+ };
203
+ }
204
+ var DEFAULT_ARKADE_SERVER_URL = "https://arkade.computer";
205
+ var DEFAULT_NETWORK = networks.bitcoin;
206
+ var DEFAULT_NETWORK_NAME = "bitcoin";
207
+ var ArkAddress = class _ArkAddress {
208
+ /**
209
+ * Create an Arkade address from its server public key, Taproot output key, and prefix.
210
+ *
211
+ * @param serverPubKey - 32-byte Arkade server public key
212
+ * @param vtxoTaprootKey - 32-byte Taproot output key (a.k.a. tweaked public key)
213
+ * @param hrp - Bech32 human-readable prefix
214
+ * @param version - Address version byte
215
+ * @defaultValue `version = 0`
216
+ * @throws Error if either public key is not 32 bytes long
217
+ */
218
+ constructor(serverPubKey, vtxoTaprootKey, hrp = DEFAULT_NETWORK.hrp, version2 = 0) {
219
+ this.serverPubKey = serverPubKey;
220
+ this.vtxoTaprootKey = vtxoTaprootKey;
221
+ this.hrp = hrp;
222
+ this.version = version2;
223
+ if (serverPubKey.length !== 32) {
224
+ throw new Error(
225
+ "Invalid server public key length, expected 32 bytes, got " + serverPubKey.length
226
+ );
227
+ }
228
+ if (vtxoTaprootKey.length !== 32) {
229
+ throw new Error(
230
+ "Invalid vtxo taproot public key length, expected 32 bytes, got " + vtxoTaprootKey.length
231
+ );
232
+ }
233
+ }
234
+ serverPubKey;
235
+ vtxoTaprootKey;
236
+ hrp;
237
+ version;
238
+ /**
239
+ * Decode an Arkade address from its bech32m string form.
240
+ *
241
+ * @param address - Bech32m-encoded Arkade address
242
+ * @returns Decoded Arkade address
243
+ * @throws Error if the address is malformed or has an invalid payload length
244
+ * @see encode
245
+ */
246
+ static decode(address) {
247
+ const decoded = bech32m.decodeUnsafe(address, 1023);
248
+ if (!decoded) {
249
+ throw new Error("Invalid address");
250
+ }
251
+ const data = new Uint8Array(bech32m.fromWords(decoded.words));
252
+ if (data.length !== 1 + 32 + 32) {
253
+ throw new Error("Invalid data length, expected 65 bytes, got " + data.length);
254
+ }
255
+ const version2 = data[0];
256
+ const serverPubKey = data.slice(1, 33);
257
+ const vtxoTaprootPubKey = data.slice(33, 65);
258
+ return new _ArkAddress(serverPubKey, vtxoTaprootPubKey, decoded.prefix, version2);
259
+ }
260
+ /**
261
+ * Encode the address to its bech32m string form.
262
+ *
263
+ * @returns Bech32m-encoded Arkade address
264
+ * @see decode
265
+ */
266
+ encode() {
267
+ const data = new Uint8Array(1 + 32 + 32);
268
+ data[0] = this.version;
269
+ data.set(this.serverPubKey, 1);
270
+ data.set(this.vtxoTaprootKey, 33);
271
+ const words = bech32m.toWords(data);
272
+ return bech32m.encode(this.hrp, words, 1023);
273
+ }
274
+ /** ScriptPubKey used to send non-dust funds to the address. */
275
+ get pkScript() {
276
+ return Script$1.encode(["OP_1", this.vtxoTaprootKey]);
277
+ }
278
+ /** ScriptPubKey used to send sub-dust funds to the address. */
279
+ get subdustPkScript() {
280
+ return Script$1.encode(["RETURN", this.vtxoTaprootKey]);
281
+ }
282
+ };
283
+ var MinimalScriptNum = ScriptNum(void 0, true);
284
+ function decodeTapscript(script) {
285
+ const types = [
286
+ MultisigTapscript,
287
+ CSVMultisigTapscript,
288
+ ConditionCSVMultisigTapscript,
289
+ ConditionMultisigTapscript,
290
+ CLTVMultisigTapscript
291
+ ];
292
+ for (const type of types) {
293
+ try {
294
+ return type.decode(script);
295
+ } catch (error) {
296
+ continue;
297
+ }
298
+ }
299
+ throw new Error(`Failed to decode: script ${hex.encode(script)} is not a valid tapscript`);
300
+ }
301
+ var MultisigTapscript;
302
+ ((MultisigTapscript2) => {
303
+ ((MultisigType2) => {
304
+ MultisigType2[MultisigType2["CHECKSIG"] = 0] = "CHECKSIG";
305
+ MultisigType2[MultisigType2["CHECKSIGADD"] = 1] = "CHECKSIGADD";
306
+ })(MultisigTapscript2.MultisigType || (MultisigTapscript2.MultisigType = {}));
307
+ function encode2(params) {
308
+ if (params.pubkeys.length === 0) {
309
+ throw new Error("At least 1 pubkey is required");
310
+ }
311
+ for (const pubkey of params.pubkeys) {
312
+ if (pubkey.length !== 32) {
313
+ throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);
314
+ }
315
+ }
316
+ if (!params.type) {
317
+ params.type = 0 /* CHECKSIG */;
318
+ }
319
+ if (params.type === 1 /* CHECKSIGADD */) {
320
+ return {
321
+ type: "multisig" /* Multisig */,
322
+ params,
323
+ script: p2tr_ms(params.pubkeys.length, params.pubkeys).script
324
+ };
325
+ }
326
+ const asm = [];
327
+ for (let i = 0; i < params.pubkeys.length; i++) {
328
+ asm.push(params.pubkeys[i]);
329
+ if (i < params.pubkeys.length - 1) {
330
+ asm.push("CHECKSIGVERIFY");
331
+ } else {
332
+ asm.push("CHECKSIG");
333
+ }
334
+ }
335
+ return {
336
+ type: "multisig" /* Multisig */,
337
+ params,
338
+ script: Script.encode(asm)
339
+ };
340
+ }
341
+ MultisigTapscript2.encode = encode2;
342
+ function decode2(script) {
343
+ if (script.length === 0) {
344
+ throw new Error("Failed to decode: script is empty");
345
+ }
346
+ try {
347
+ return decodeChecksigAdd(script);
348
+ } catch (error) {
349
+ try {
350
+ return decodeChecksig(script);
351
+ } catch (error2) {
352
+ throw new Error(
353
+ `Failed to decode script: ${error2 instanceof Error ? error2.message : String(error2)}`
354
+ );
355
+ }
356
+ }
357
+ }
358
+ MultisigTapscript2.decode = decode2;
359
+ function decodeChecksigAdd(script) {
360
+ const asm = Script.decode(script);
361
+ const pubkeys = [];
362
+ let foundNumEqual = false;
363
+ for (let i = 0; i < asm.length; i++) {
364
+ const op = asm[i];
365
+ if (typeof op !== "string" && typeof op !== "number") {
366
+ if (op.length !== 32) {
367
+ throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);
368
+ }
369
+ pubkeys.push(op);
370
+ if (i + 1 >= asm.length || asm[i + 1] !== "CHECKSIGADD" && asm[i + 1] !== "CHECKSIG") {
371
+ throw new Error("Expected CHECKSIGADD or CHECKSIG after pubkey");
372
+ }
373
+ i++;
374
+ continue;
375
+ }
376
+ if (i === asm.length - 1) {
377
+ if (op !== "NUMEQUAL") {
378
+ throw new Error("Expected NUMEQUAL at end of script");
379
+ }
380
+ foundNumEqual = true;
381
+ }
382
+ }
383
+ if (!foundNumEqual) {
384
+ throw new Error("Missing NUMEQUAL operation");
385
+ }
386
+ if (pubkeys.length === 0) {
387
+ throw new Error("Invalid script: must have at least 1 pubkey");
388
+ }
389
+ const reconstructed = encode2({
390
+ pubkeys,
391
+ type: 1 /* CHECKSIGADD */
392
+ });
393
+ if (hex.encode(reconstructed.script) !== hex.encode(script)) {
394
+ throw new Error("Invalid script format: script reconstruction mismatch");
395
+ }
396
+ return {
397
+ type: "multisig" /* Multisig */,
398
+ params: { pubkeys, type: 1 /* CHECKSIGADD */ },
399
+ script
400
+ };
401
+ }
402
+ function decodeChecksig(script) {
403
+ const asm = Script.decode(script);
404
+ const pubkeys = [];
405
+ for (let i = 0; i < asm.length; i++) {
406
+ const op = asm[i];
407
+ if (typeof op !== "string" && typeof op !== "number") {
408
+ if (op.length !== 32) {
409
+ throw new Error(`Invalid pubkey length: expected 32, got ${op.length}`);
410
+ }
411
+ pubkeys.push(op);
412
+ if (i + 1 >= asm.length) {
413
+ throw new Error("Unexpected end of script");
414
+ }
415
+ const nextOp = asm[i + 1];
416
+ if (nextOp !== "CHECKSIGVERIFY" && nextOp !== "CHECKSIG") {
417
+ throw new Error("Expected CHECKSIGVERIFY or CHECKSIG after pubkey");
418
+ }
419
+ if (i === asm.length - 2 && nextOp !== "CHECKSIG") {
420
+ throw new Error("Last operation must be CHECKSIG");
421
+ }
422
+ i++;
423
+ continue;
424
+ }
425
+ }
426
+ if (pubkeys.length === 0) {
427
+ throw new Error("Invalid script: must have at least 1 pubkey");
428
+ }
429
+ const reconstructed = encode2({ pubkeys, type: 0 /* CHECKSIG */ });
430
+ if (hex.encode(reconstructed.script) !== hex.encode(script)) {
431
+ throw new Error("Invalid script format: script reconstruction mismatch");
432
+ }
433
+ return {
434
+ type: "multisig" /* Multisig */,
435
+ params: { pubkeys, type: 0 /* CHECKSIG */ },
436
+ script
437
+ };
438
+ }
439
+ function is(tapscript) {
440
+ return tapscript.type === "multisig" /* Multisig */;
441
+ }
442
+ MultisigTapscript2.is = is;
443
+ })(MultisigTapscript || (MultisigTapscript = {}));
444
+ var CSVMultisigTapscript;
445
+ ((CSVMultisigTapscript2) => {
446
+ function encode2(params) {
447
+ for (const pubkey of params.pubkeys) {
448
+ if (pubkey.length !== 32) {
449
+ throw new Error(`Invalid pubkey length: expected 32, got ${pubkey.length}`);
450
+ }
451
+ }
452
+ const sequence = MinimalScriptNum.encode(BigInt(timelockToSequence(params.timelock)));
453
+ const asm = [
454
+ sequence.length === 1 ? sequence[0] : sequence,
455
+ "CHECKSEQUENCEVERIFY",
456
+ "DROP"
457
+ ];
458
+ const multisigScript = MultisigTapscript.encode(params);
459
+ const script = new Uint8Array([...Script.encode(asm), ...multisigScript.script]);
460
+ return {
461
+ type: "csv-multisig" /* CSVMultisig */,
462
+ params,
463
+ script
464
+ };
465
+ }
466
+ CSVMultisigTapscript2.encode = encode2;
467
+ function decode2(script) {
468
+ if (script.length === 0) {
469
+ throw new Error("Failed to decode: script is empty");
470
+ }
471
+ const isValid = isScriptValid(script);
472
+ if (isValid instanceof Error) {
473
+ throw isValid;
474
+ }
475
+ const asm = Script.decode(script);
476
+ const sequence = asm[0];
477
+ const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));
478
+ let multisig;
479
+ try {
480
+ multisig = MultisigTapscript.decode(multisigScript);
481
+ } catch (error) {
482
+ throw new Error(
483
+ `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`
484
+ );
485
+ }
486
+ let sequenceNum;
487
+ if (typeof sequence === "number") {
488
+ sequenceNum = sequence;
489
+ } else {
490
+ sequenceNum = Number(MinimalScriptNum.decode(sequence));
491
+ }
492
+ const timelock = sequenceToTimelock(sequenceNum);
493
+ const reconstructed = encode2({
494
+ timelock,
495
+ ...multisig.params
496
+ });
497
+ if (hex.encode(reconstructed.script) !== hex.encode(script)) {
498
+ throw new Error("Invalid script format: script reconstruction mismatch");
499
+ }
500
+ return {
501
+ type: "csv-multisig" /* CSVMultisig */,
502
+ params: {
503
+ timelock,
504
+ ...multisig.params
505
+ },
506
+ script
507
+ };
508
+ }
509
+ CSVMultisigTapscript2.decode = decode2;
510
+ function is(tapscript) {
511
+ return tapscript.type === "csv-multisig" /* CSVMultisig */;
512
+ }
513
+ CSVMultisigTapscript2.is = is;
514
+ function isScriptValid(script) {
515
+ const asm = Script.decode(script);
516
+ if (asm.length < 3) {
517
+ return new Error(`Invalid script: too short (expected at least 3)`);
518
+ }
519
+ const sequence = asm[0];
520
+ if (typeof sequence === "string") {
521
+ return new Error("Invalid script: expected sequence number");
522
+ }
523
+ if (asm[1] !== "CHECKSEQUENCEVERIFY" || asm[2] !== "DROP") {
524
+ return new Error("Invalid script: expected CHECKSEQUENCEVERIFY DROP");
525
+ }
526
+ return true;
527
+ }
528
+ CSVMultisigTapscript2.isScriptValid = isScriptValid;
529
+ })(CSVMultisigTapscript || (CSVMultisigTapscript = {}));
530
+ var ConditionCSVMultisigTapscript;
531
+ ((ConditionCSVMultisigTapscript2) => {
532
+ function encode2(params) {
533
+ const script = new Uint8Array([
534
+ ...params.conditionScript,
535
+ ...Script.encode(["VERIFY"]),
536
+ ...CSVMultisigTapscript.encode(params).script
537
+ ]);
538
+ return {
539
+ type: "condition-csv-multisig" /* ConditionCSVMultisig */,
540
+ params,
541
+ script
542
+ };
543
+ }
544
+ ConditionCSVMultisigTapscript2.encode = encode2;
545
+ function decode2(script) {
546
+ if (script.length === 0) {
547
+ throw new Error("Failed to decode: script is empty");
548
+ }
549
+ const isValid = isScriptValid(script);
550
+ if (isValid instanceof Error) {
551
+ throw isValid;
552
+ }
553
+ const asm = Script.decode(script);
554
+ let verifyIndex = getVerifyIndex(asm);
555
+ if (verifyIndex === -1) {
556
+ throw Error("Invalid script: missing VERIFY operation");
557
+ }
558
+ const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));
559
+ const csvMultisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));
560
+ let csvMultisig;
561
+ try {
562
+ csvMultisig = CSVMultisigTapscript.decode(csvMultisigScript);
563
+ } catch (error) {
564
+ throw new Error(
565
+ `Invalid CSV multisig script: ${error instanceof Error ? error.message : String(error)}`
566
+ );
567
+ }
568
+ const reconstructed = encode2({
569
+ conditionScript,
570
+ ...csvMultisig.params
571
+ });
572
+ if (hex.encode(reconstructed.script) !== hex.encode(script)) {
573
+ throw new Error("Invalid script format: script reconstruction mismatch");
574
+ }
575
+ return {
576
+ type: "condition-csv-multisig" /* ConditionCSVMultisig */,
577
+ params: {
578
+ conditionScript,
579
+ ...csvMultisig.params
580
+ },
581
+ script
582
+ };
583
+ }
584
+ ConditionCSVMultisigTapscript2.decode = decode2;
585
+ function is(tapscript) {
586
+ return tapscript.type === "condition-csv-multisig" /* ConditionCSVMultisig */;
587
+ }
588
+ ConditionCSVMultisigTapscript2.is = is;
589
+ function getVerifyIndex(asm) {
590
+ let verifyIndex = -1;
591
+ for (let i = asm.length - 1; i >= 0; i--) {
592
+ if (asm[i] === "VERIFY") {
593
+ verifyIndex = i;
594
+ return verifyIndex;
595
+ }
596
+ }
597
+ return verifyIndex;
598
+ }
599
+ function isScriptValid(script) {
600
+ const asm = Script.decode(script);
601
+ if (asm.length < 1) {
602
+ return new Error(`Invalid script: too short (expected at least 1)`);
603
+ }
604
+ let verifyIndex = getVerifyIndex(asm);
605
+ if (verifyIndex === -1) {
606
+ return new Error("Invalid script: missing VERIFY operation");
607
+ }
608
+ return true;
609
+ }
610
+ ConditionCSVMultisigTapscript2.isScriptValid = isScriptValid;
611
+ })(ConditionCSVMultisigTapscript || (ConditionCSVMultisigTapscript = {}));
612
+ var ConditionMultisigTapscript;
613
+ ((ConditionMultisigTapscript2) => {
614
+ function encode2(params) {
615
+ const script = new Uint8Array([
616
+ ...params.conditionScript,
617
+ ...Script.encode(["VERIFY"]),
618
+ ...MultisigTapscript.encode(params).script
619
+ ]);
620
+ return {
621
+ type: "condition-multisig" /* ConditionMultisig */,
622
+ params,
623
+ script
624
+ };
625
+ }
626
+ ConditionMultisigTapscript2.encode = encode2;
627
+ function decode2(script) {
628
+ if (script.length === 0) {
629
+ throw new Error("Failed to decode: script is empty");
630
+ }
631
+ const isValid = isScriptValid(script);
632
+ if (isValid instanceof Error) {
633
+ throw isValid;
634
+ }
635
+ const asm = Script.decode(script);
636
+ let verifyIndex = getVerifyIndex(asm);
637
+ if (verifyIndex === -1) {
638
+ throw Error("Invalid script: missing VERIFY operation");
639
+ }
640
+ const conditionScript = new Uint8Array(Script.encode(asm.slice(0, verifyIndex)));
641
+ const multisigScript = new Uint8Array(Script.encode(asm.slice(verifyIndex + 1)));
642
+ let multisig;
643
+ try {
644
+ multisig = MultisigTapscript.decode(multisigScript);
645
+ } catch (error) {
646
+ throw new Error(
647
+ `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`
648
+ );
649
+ }
650
+ const reconstructed = encode2({
651
+ conditionScript,
652
+ ...multisig.params
653
+ });
654
+ if (hex.encode(reconstructed.script) !== hex.encode(script)) {
655
+ throw new Error("Invalid script format: script reconstruction mismatch");
656
+ }
657
+ return {
658
+ type: "condition-multisig" /* ConditionMultisig */,
659
+ params: {
660
+ conditionScript,
661
+ ...multisig.params
662
+ },
663
+ script
664
+ };
665
+ }
666
+ ConditionMultisigTapscript2.decode = decode2;
667
+ function is(tapscript) {
668
+ return tapscript.type === "condition-multisig" /* ConditionMultisig */;
669
+ }
670
+ ConditionMultisigTapscript2.is = is;
671
+ function getVerifyIndex(asm) {
672
+ let verifyIndex = -1;
673
+ for (let i = asm.length - 1; i >= 0; i--) {
674
+ if (asm[i] === "VERIFY") {
675
+ verifyIndex = i;
676
+ return verifyIndex;
677
+ }
678
+ }
679
+ return verifyIndex;
680
+ }
681
+ function isScriptValid(script) {
682
+ const asm = Script.decode(script);
683
+ if (asm.length < 1) {
684
+ return new Error(`Invalid script: too short (expected at least 1)`);
685
+ }
686
+ let verifyIndex = getVerifyIndex(asm);
687
+ if (verifyIndex === -1) {
688
+ return new Error("Invalid script: missing VERIFY operation");
689
+ }
690
+ return true;
691
+ }
692
+ ConditionMultisigTapscript2.isScriptValid = isScriptValid;
693
+ })(ConditionMultisigTapscript || (ConditionMultisigTapscript = {}));
694
+ var CLTVMultisigTapscript;
695
+ ((CLTVMultisigTapscript2) => {
696
+ function encode2(params) {
697
+ const locktime = MinimalScriptNum.encode(params.absoluteTimelock);
698
+ const asm = [
699
+ locktime.length === 1 ? locktime[0] : locktime,
700
+ "CHECKLOCKTIMEVERIFY",
701
+ "DROP"
702
+ ];
703
+ const timelockedScript = Script.encode(asm);
704
+ const script = new Uint8Array([
705
+ ...timelockedScript,
706
+ ...MultisigTapscript.encode(params).script
707
+ ]);
708
+ return {
709
+ type: "cltv-multisig" /* CLTVMultisig */,
710
+ params,
711
+ script
712
+ };
713
+ }
714
+ CLTVMultisigTapscript2.encode = encode2;
715
+ function decode2(script) {
716
+ if (script.length === 0) {
717
+ throw new Error("Failed to decode: script is empty");
718
+ }
719
+ const isValid = isScriptValid(script);
720
+ if (isValid instanceof Error) {
721
+ throw isValid;
722
+ }
723
+ const asm = Script.decode(script);
724
+ const locktime = asm[0];
725
+ if (typeof locktime === "string") {
726
+ throw new Error("Invalid script: expected locktime number");
727
+ }
728
+ if (asm[1] !== "CHECKLOCKTIMEVERIFY" || asm[2] !== "DROP") {
729
+ throw new Error("Invalid script: expected CHECKLOCKTIMEVERIFY DROP");
730
+ }
731
+ const multisigScript = new Uint8Array(Script.encode(asm.slice(3)));
732
+ let multisig;
733
+ try {
734
+ multisig = MultisigTapscript.decode(multisigScript);
735
+ } catch (error) {
736
+ throw new Error(
737
+ `Invalid multisig script: ${error instanceof Error ? error.message : String(error)}`
738
+ );
739
+ }
740
+ let absoluteTimelock;
741
+ if (typeof locktime === "number") {
742
+ absoluteTimelock = BigInt(locktime);
743
+ } else {
744
+ absoluteTimelock = MinimalScriptNum.decode(locktime);
745
+ }
746
+ const reconstructed = encode2({
747
+ absoluteTimelock,
748
+ ...multisig.params
749
+ });
750
+ if (hex.encode(reconstructed.script) !== hex.encode(script)) {
751
+ throw new Error("Invalid script format: script reconstruction mismatch");
752
+ }
753
+ return {
754
+ type: "cltv-multisig" /* CLTVMultisig */,
755
+ params: {
756
+ absoluteTimelock,
757
+ ...multisig.params
758
+ },
759
+ script
760
+ };
761
+ }
762
+ CLTVMultisigTapscript2.decode = decode2;
763
+ function is(tapscript) {
764
+ return tapscript.type === "cltv-multisig" /* CLTVMultisig */;
765
+ }
766
+ CLTVMultisigTapscript2.is = is;
767
+ function isScriptValid(script) {
768
+ const asm = Script.decode(script);
769
+ if (asm.length < 3) {
770
+ return new Error(`Invalid script: too short (expected at least 3)`);
771
+ }
772
+ const locktime = asm[0];
773
+ if (typeof locktime === "string") {
774
+ return new Error("Invalid script: expected locktime as number or bytes");
775
+ }
776
+ if (asm[1] !== "CHECKLOCKTIMEVERIFY" || asm[2] !== "DROP") {
777
+ return new Error("Invalid script: expected CHECKLOCKTIMEVERIFY DROP");
778
+ }
779
+ return true;
780
+ }
781
+ CLTVMultisigTapscript2.isScriptValid = isScriptValid;
782
+ })(CLTVMultisigTapscript || (CLTVMultisigTapscript = {}));
783
+ function assembleBtcdTaprootTree(scripts) {
784
+ if (scripts.length === 0) {
785
+ throw new Error("assembleBtcdTaprootTree: empty scripts list");
786
+ }
787
+ const leaves = scripts.map((script) => ({
788
+ script,
789
+ leafVersion: TAP_LEAF_VERSION
790
+ }));
791
+ if (leaves.length === 1) {
792
+ return leaves[0];
793
+ }
794
+ const branches = [];
795
+ for (let i = 0; i < leaves.length; i += 2) {
796
+ if (i === leaves.length - 1) {
797
+ const last = branches.pop();
798
+ if (last === void 0) {
799
+ throw new Error(
800
+ `assembleBtcdTaprootTree: unexpected odd leaf at i=${i} with no prior branch`
801
+ );
802
+ }
803
+ branches.push([last, leaves[i]]);
804
+ } else {
805
+ branches.push([leaves[i], leaves[i + 1]]);
806
+ }
807
+ }
808
+ while (branches.length >= 2) {
809
+ const left = branches.shift();
810
+ const right = branches.shift();
811
+ branches.push([left, right]);
812
+ }
813
+ return branches[0];
814
+ }
815
+ var TapTreeCoder = PSBTOutput.tapTree[2];
816
+ function scriptFromTapLeafScript(leaf) {
817
+ return leaf[1].subarray(0, leaf[1].length - 1);
818
+ }
819
+ var VtxoScript = class _VtxoScript {
820
+ /**
821
+ * Create a virtual output script from its tapleaf scripts.
822
+ *
823
+ * The Taproot script tree is assembled using btcd's algorithm
824
+ * (`txscript.AssembleTaprootScriptTree`) so the derived taproot output
825
+ * key agrees with arkd for any leaf count. `@scure/btc-signer`'s
826
+ * default `taprootListToTree` is a Huffman builder that only agrees
827
+ * with arkd for power-of-2 leaf counts.
828
+ *
829
+ * @param scripts - Raw tapscript bytes for each leaf
830
+ * @throws Error if the provided leaves cannot produce a valid Taproot tree
831
+ */
832
+ constructor(scripts) {
833
+ this.scripts = scripts;
834
+ const tapTree = assembleBtcdTaprootTree(scripts);
835
+ const payment = p2tr(TAPROOT_UNSPENDABLE_KEY, tapTree, void 0, true);
836
+ if (!payment.tapLeafScript || payment.tapLeafScript.length !== scripts.length) {
837
+ throw new Error("invalid scripts");
838
+ }
839
+ this.leaves = payment.tapLeafScript;
840
+ this.tweakedPublicKey = payment.tweakedPubkey;
841
+ this.pkScript = payment.script;
842
+ }
843
+ scripts;
844
+ leaves;
845
+ tweakedPublicKey;
846
+ pkScript;
847
+ /**
848
+ * Decode a virtual output script from an encoded TapTree.
849
+ *
850
+ * @param tapTree - Encoded TapTree bytes
851
+ * @returns Decoded virtual output script
852
+ * @throws Error if the TapTree cannot be decoded into a valid script set
853
+ * @see encode
854
+ */
855
+ static decode(tapTree) {
856
+ const leaves = TapTreeCoder.decode(tapTree);
857
+ const scripts = leaves.map((leaf) => leaf.script);
858
+ return new _VtxoScript(scripts);
859
+ }
860
+ /**
861
+ * Encode the virtual output script to a TapTree byte representation.
862
+ *
863
+ * @returns Encoded TapTree bytes
864
+ * @see decode
865
+ */
866
+ encode() {
867
+ const tapTree = TapTreeCoder.encode(
868
+ this.scripts.map((script) => ({
869
+ depth: 1,
870
+ version: TAP_LEAF_VERSION,
871
+ script
872
+ }))
873
+ );
874
+ return tapTree;
875
+ }
876
+ /**
877
+ * Build the Arkade address corresponding to this virtual output script.
878
+ *
879
+ * @param prefix - Bech32 human-readable prefix
880
+ * @param serverPubKey - 32-byte Arkade server public key
881
+ * @returns Arkade address for this script
882
+ * @see ArkAddress
883
+ */
884
+ address(prefix = DEFAULT_NETWORK.hrp, serverPubKey) {
885
+ return new ArkAddress(serverPubKey, this.tweakedPublicKey, prefix);
886
+ }
887
+ /**
888
+ * Build the Taproot onchain address corresponding to this virtual output script.
889
+ *
890
+ * @param network - Bitcoin network descriptor
891
+ * @returns Taproot onchain address
892
+ * @see address
893
+ */
894
+ onchainAddress(network = DEFAULT_NETWORK) {
895
+ return Address(network).encode({
896
+ type: "tr",
897
+ pubkey: this.tweakedPublicKey
898
+ });
899
+ }
900
+ /**
901
+ * Look up a tapleaf script by its hex-encoded tapscript body.
902
+ *
903
+ * @param scriptHex - Hex-encoded tapscript body without the leaf version byte
904
+ * @returns Matching tapleaf script
905
+ * @throws Error if no matching leaf exists
906
+ */
907
+ findLeaf(scriptHex) {
908
+ const leaf = this.leaves.find(
909
+ (leaf2) => hex.encode(scriptFromTapLeafScript(leaf2)) === scriptHex
910
+ );
911
+ if (!leaf) {
912
+ throw new Error(`leaf '${scriptHex}' not found`);
913
+ }
914
+ return leaf;
915
+ }
916
+ /**
917
+ * Return all unilateral exit paths embedded in the virtual output script.
918
+ *
919
+ * @returns CSV-based exit paths found in the leaves
920
+ * @see getSequence
921
+ */
922
+ exitPaths() {
923
+ const paths = [];
924
+ for (const leaf of this.leaves) {
925
+ try {
926
+ const script = scriptFromTapLeafScript(leaf);
927
+ if (CSVMultisigTapscript.isScriptValid(script) === true) {
928
+ const tapScript = CSVMultisigTapscript.decode(script);
929
+ paths.push(tapScript);
930
+ } else if (ConditionCSVMultisigTapscript.isScriptValid(script) === true) {
931
+ const tapScript = ConditionCSVMultisigTapscript.decode(script);
932
+ paths.push(tapScript);
933
+ }
934
+ } catch (e) {
935
+ console.debug("Failed to decode script", e);
936
+ }
937
+ }
938
+ return paths;
939
+ }
940
+ };
941
+ function getSequence(tapLeafScript) {
942
+ let sequence = void 0;
943
+ try {
944
+ const scriptWithLeafVersion = tapLeafScript[1];
945
+ const script = scriptWithLeafVersion.subarray(0, scriptWithLeafVersion.length - 1);
946
+ try {
947
+ const params = CSVMultisigTapscript.decode(script).params;
948
+ sequence = timelockToSequence(params.timelock);
949
+ } catch {
950
+ const params = CLTVMultisigTapscript.decode(script).params;
951
+ sequence = Number(params.absoluteTimelock);
952
+ }
953
+ } catch {
954
+ }
955
+ return sequence;
956
+ }
957
+
958
+ // package.json
959
+ var version = "0.4.54";
960
+
961
+ // src/utils/fetch.ts
962
+ var buildVersion = "0.9.9";
963
+ var sdkVersion = `ts-sdk/${version}`;
964
+ var FetchError = class extends Error {
965
+ /** The request URL that failed, when derivable from the `fetch` input. */
966
+ url;
967
+ /** The HTTP method of the failed request (defaults to `"GET"`). */
968
+ method;
969
+ constructor(message, options) {
970
+ super(message, { cause: options.cause });
971
+ this.name = "FetchError";
972
+ this.url = options.url;
973
+ this.method = options.method;
974
+ }
975
+ };
976
+ function baseFetch(input, init) {
977
+ if (typeof globalThis.fetch !== "function") {
978
+ throw new Error("Fetch API is not available in this environment.");
979
+ }
980
+ return globalThis.fetch(input, init).catch((cause) => {
981
+ const { url, method } = describeRequest(input, init);
982
+ throw new FetchError(`Network request failed: ${method} ${url}`, { url, method, cause });
983
+ });
984
+ }
985
+ function fetch(input, init) {
986
+ const headers = new Headers(init?.headers);
987
+ headers.set("X-Build-Version", buildVersion);
988
+ headers.set("X-SDK-VERSION", sdkVersion);
989
+ return baseFetch(input, { ...init, headers });
990
+ }
991
+ function describeRequest(input, init) {
992
+ let url;
993
+ if (typeof input === "string") {
994
+ url = input;
995
+ } else if (input instanceof URL) {
996
+ url = input.href;
997
+ } else {
998
+ url = input.url;
999
+ }
1000
+ let method;
1001
+ if (init?.method !== void 0) {
1002
+ method = init.method;
1003
+ } else if (input instanceof Request) {
1004
+ method = input.method;
1005
+ } else {
1006
+ method = "GET";
1007
+ }
1008
+ return { url, method };
1009
+ }
1010
+
1011
+ // src/providers/errors.ts
1012
+ var ArkError = class extends Error {
1013
+ constructor(code, message, name, metadata) {
1014
+ super(message);
1015
+ this.code = code;
1016
+ this.message = message;
1017
+ this.name = name;
1018
+ this.metadata = metadata;
1019
+ }
1020
+ code;
1021
+ message;
1022
+ name;
1023
+ metadata;
1024
+ };
1025
+ var ArkErrorName = {
1026
+ DIGEST_MISMATCH: "DIGEST_MISMATCH",
1027
+ VTXO_ALREADY_SPENT: "VTXO_ALREADY_SPENT",
1028
+ INVALID_TX_FILTER: "INVALID_TX_FILTER",
1029
+ TX_FILTERS_LIMIT_EXCEEDED: "TX_FILTERS_LIMIT_EXCEEDED",
1030
+ /**
1031
+ * A CLTV closure was spent before its absolute locktime matured. Raised only by
1032
+ * `submitTx` (never `finalizeTx`), with metadata
1033
+ * `{ locktime, current_locktime, type: "height" | "time" }`.
1034
+ *
1035
+ * Self-healing, so defer and retry rather than fail: the server matures a
1036
+ * seconds-locktime against the **chain tip block's timestamp**, not its wall clock,
1037
+ * so a spend attempted promptly at maturity is rejected until a later block lands.
1038
+ */
1039
+ FORFEIT_CLOSURE_LOCKED: "FORFEIT_CLOSURE_LOCKED"
1040
+ };
1041
+ function isArkError(error, name) {
1042
+ return error instanceof ArkError && (name === void 0 || error.name === name);
1043
+ }
1044
+ var ProviderUnavailableError = class extends Error {
1045
+ /** Always `true`: this error type only ever wraps retryable conditions. */
1046
+ retryable = true;
1047
+ constructor(message, options) {
1048
+ super(message, { cause: options?.cause });
1049
+ this.name = "ProviderUnavailableError";
1050
+ }
1051
+ };
1052
+ function throwIfHttpUnavailable(response, kind, body) {
1053
+ if (body !== void 0 && maybeArkError(new Error(body))) return;
1054
+ if (response.status === 429 || response.status >= 500) {
1055
+ throw new ProviderUnavailableError(
1056
+ `${kind} unavailable: ${response.status} ${response.statusText}`
1057
+ );
1058
+ }
1059
+ }
1060
+ function toProviderUnavailable(err, kind) {
1061
+ if (err instanceof FetchError) {
1062
+ return new ProviderUnavailableError(`${kind} request failed`, { cause: err });
1063
+ }
1064
+ return err;
1065
+ }
1066
+ function maybeArkError(error) {
1067
+ try {
1068
+ if (!(error instanceof Error)) return void 0;
1069
+ const decoded = JSON.parse(error.message);
1070
+ if (Array.isArray(decoded.details)) {
1071
+ for (const details of decoded.details) {
1072
+ if (!("@type" in details)) continue;
1073
+ const type = details["@type"];
1074
+ if (type !== "type.googleapis.com/ark.v1.ErrorDetails") continue;
1075
+ if (!("code" in details)) continue;
1076
+ const code = details.code;
1077
+ if (!("message" in details)) continue;
1078
+ const message = details.message;
1079
+ if (!("name" in details)) continue;
1080
+ const name = details.name;
1081
+ let metadata;
1082
+ if ("metadata" in details && isMetadata(details.metadata)) {
1083
+ metadata = details.metadata;
1084
+ }
1085
+ return new ArkError(code, message, name, metadata);
1086
+ }
1087
+ }
1088
+ if (typeof decoded.message === "string") {
1089
+ const m = decoded.message.match(/^([A-Z][A-Z0-9_]*) \((\d+)\): ([\s\S]*)$/);
1090
+ if (m) return new ArkError(Number(m[2]), m[3], m[1]);
1091
+ }
1092
+ return void 0;
1093
+ } catch (e) {
1094
+ return void 0;
1095
+ }
1096
+ }
1097
+ function isMetadata(value) {
1098
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1099
+ }
1100
+ var Intent;
1101
+ ((Intent2) => {
1102
+ function create(message, ins, outputs = []) {
1103
+ if (typeof message !== "string") {
1104
+ message = encodeMessage(message);
1105
+ }
1106
+ if (ins.length == 0) throw new Error("intent proof requires at least one input");
1107
+ const inputs = ins.map(prepareCoinAsIntentProofInput);
1108
+ if (!validateInputs(inputs)) ;
1109
+ if (!validateOutputs(outputs)) ;
1110
+ const toSpend = craftToSpendTx(message, inputs[0].witnessUtxo.script);
1111
+ return craftToSignTx(toSpend, inputs, outputs, message);
1112
+ }
1113
+ Intent2.create = create;
1114
+ function fee(proof) {
1115
+ let sumOfInputs = 0n;
1116
+ for (let i = 0; i < proof.inputsLength; i++) {
1117
+ const input = proof.getInput(i);
1118
+ if (input.witnessUtxo === void 0)
1119
+ throw new Error("intent proof input requires witness utxo");
1120
+ sumOfInputs += input.witnessUtxo.amount;
1121
+ }
1122
+ let sumOfOutputs = 0n;
1123
+ for (let i = 0; i < proof.outputsLength; i++) {
1124
+ const output = proof.getOutput(i);
1125
+ if (output.amount === void 0) throw new Error("intent proof output requires amount");
1126
+ sumOfOutputs += output.amount;
1127
+ }
1128
+ if (sumOfOutputs > sumOfInputs) {
1129
+ throw new Error(
1130
+ `intent proof output amount is greater than input amount: ${sumOfOutputs} > ${sumOfInputs}`
1131
+ );
1132
+ }
1133
+ return Number(sumOfInputs - sumOfOutputs);
1134
+ }
1135
+ Intent2.fee = fee;
1136
+ function encodeMessage(message) {
1137
+ switch (message.type) {
1138
+ case "register":
1139
+ return JSON.stringify({
1140
+ type: "register",
1141
+ onchain_output_indexes: message.onchain_output_indexes,
1142
+ valid_at: message.valid_at,
1143
+ expire_at: message.expire_at,
1144
+ cosigners_public_keys: message.cosigners_public_keys
1145
+ });
1146
+ case "delete":
1147
+ return JSON.stringify({
1148
+ type: "delete",
1149
+ expire_at: message.expire_at
1150
+ });
1151
+ case "get-pending-tx":
1152
+ return JSON.stringify({
1153
+ type: "get-pending-tx",
1154
+ expire_at: message.expire_at
1155
+ });
1156
+ }
1157
+ }
1158
+ Intent2.encodeMessage = encodeMessage;
1159
+ })(Intent || (Intent = {}));
1160
+ var OP_RETURN_EMPTY_PKSCRIPT = new Uint8Array([OP.RETURN]);
1161
+ var ZERO_32 = new Uint8Array(32).fill(0);
1162
+ var MAX_INDEX = 4294967295;
1163
+ var TAG_INTENT_PROOF = "ark-intent-proof-message";
1164
+ var PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE = 9;
1165
+ function validateInput(input) {
1166
+ if (input.index === void 0) throw new Error("intent proof input requires index");
1167
+ if (input.txid === void 0) throw new Error("intent proof input requires txid");
1168
+ if (input.witnessUtxo === void 0)
1169
+ throw new Error("intent proof input requires witness utxo");
1170
+ return true;
1171
+ }
1172
+ function validateInputs(inputs) {
1173
+ inputs.forEach(validateInput);
1174
+ return true;
1175
+ }
1176
+ function validateOutput(output) {
1177
+ if (output.amount === void 0) throw new Error("intent proof output requires amount");
1178
+ if (output.script === void 0) throw new Error("intent proof output requires script");
1179
+ return true;
1180
+ }
1181
+ function validateOutputs(outputs) {
1182
+ outputs.forEach(validateOutput);
1183
+ return true;
1184
+ }
1185
+ function craftToSpendTx(message, pkScript, tag = TAG_INTENT_PROOF) {
1186
+ const messageHash = hashMessage(message, tag);
1187
+ const tx = new Transaction({
1188
+ version: 0
1189
+ });
1190
+ tx.addInput({
1191
+ txid: ZERO_32,
1192
+ // zero hash
1193
+ index: MAX_INDEX,
1194
+ sequence: 0
1195
+ });
1196
+ tx.addOutput({
1197
+ amount: 0n,
1198
+ script: pkScript
1199
+ });
1200
+ tx.updateInput(0, {
1201
+ finalScriptSig: Script.encode(["OP_0", messageHash])
1202
+ });
1203
+ return tx;
1204
+ }
1205
+ function craftToSignTx(toSpend, inputs, outputs, message) {
1206
+ const firstInput = inputs[0];
1207
+ const tx = new Transaction({
1208
+ version: 2,
1209
+ lockTime: 0
1210
+ });
1211
+ tx.addInput({
1212
+ ...firstInput,
1213
+ txid: toSpend.id,
1214
+ index: 0,
1215
+ witnessUtxo: {
1216
+ script: firstInput.witnessUtxo.script,
1217
+ amount: 0n
1218
+ },
1219
+ sighashType: SigHash.ALL
1220
+ });
1221
+ for (const [i, input] of inputs.entries()) {
1222
+ tx.addInput({
1223
+ ...input,
1224
+ sighashType: SigHash.ALL
1225
+ });
1226
+ if (input.unknown?.length) {
1227
+ tx.updateInput(i + 1, {
1228
+ unknown: input.unknown
1229
+ });
1230
+ }
1231
+ }
1232
+ if (outputs.length === 0) {
1233
+ outputs = [
1234
+ {
1235
+ amount: 0n,
1236
+ script: OP_RETURN_EMPTY_PKSCRIPT
1237
+ }
1238
+ ];
1239
+ }
1240
+ for (const output of outputs) {
1241
+ tx.addOutput({
1242
+ amount: output.amount,
1243
+ script: output.script
1244
+ });
1245
+ }
1246
+ const global = tx.global;
1247
+ global.unknown = [
1248
+ ...global.unknown ?? [],
1249
+ [
1250
+ { type: PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE, key: new Uint8Array() },
1251
+ new TextEncoder().encode(message)
1252
+ ]
1253
+ ];
1254
+ return tx;
1255
+ }
1256
+ function hashMessage(message, tag = TAG_INTENT_PROOF) {
1257
+ return schnorr.utils.taggedHash(tag, new TextEncoder().encode(message));
1258
+ }
1259
+ function prepareCoinAsIntentProofInput(coin) {
1260
+ if (!("tapTree" in coin)) {
1261
+ return coin;
1262
+ }
1263
+ const vtxoScript = VtxoScript.decode(coin.tapTree);
1264
+ const sequence = getSequence(coin.intentTapLeafScript);
1265
+ const unknown = [VtxoTaprootTree.encode(coin.tapTree)];
1266
+ if (coin.extraWitness) {
1267
+ unknown.push(ConditionWitness.encode(coin.extraWitness));
1268
+ }
1269
+ return {
1270
+ txid: hex.decode(coin.txid),
1271
+ index: coin.vout,
1272
+ witnessUtxo: {
1273
+ amount: BigInt(coin.value),
1274
+ script: vtxoScript.pkScript
1275
+ },
1276
+ sequence,
1277
+ tapLeafScript: [coin.intentTapLeafScript],
1278
+ unknown
1279
+ };
1280
+ }
1281
+
1282
+ // src/providers/utils.ts
1283
+ function createAbortError() {
1284
+ const error = new Error("EventSource closed");
1285
+ error.name = "AbortError";
1286
+ return error;
1287
+ }
1288
+ function eventSourceIterator(eventSource) {
1289
+ const messageQueue = [];
1290
+ const errorQueue = [];
1291
+ let messageResolve = null;
1292
+ let errorResolve = null;
1293
+ let closed = false;
1294
+ let cleanedUp = false;
1295
+ const cleanup = () => {
1296
+ if (cleanedUp) return;
1297
+ cleanedUp = true;
1298
+ eventSource.removeEventListener("message", messageHandler);
1299
+ eventSource.removeEventListener("error", errorHandler);
1300
+ };
1301
+ const close = () => {
1302
+ if (closed) return;
1303
+ closed = true;
1304
+ messageQueue.length = 0;
1305
+ errorQueue.length = 0;
1306
+ eventSource.close();
1307
+ cleanup();
1308
+ if (errorResolve) {
1309
+ const reject = errorResolve;
1310
+ messageResolve = null;
1311
+ errorResolve = null;
1312
+ reject(createAbortError());
1313
+ }
1314
+ };
1315
+ const messageHandler = (event) => {
1316
+ if (closed) return;
1317
+ if (messageResolve) {
1318
+ const resolve = messageResolve;
1319
+ messageResolve = null;
1320
+ errorResolve = null;
1321
+ resolve(event);
1322
+ } else {
1323
+ messageQueue.push(event);
1324
+ }
1325
+ };
1326
+ const errorHandler = () => {
1327
+ if (closed) return;
1328
+ const error = new Error("EventSource error");
1329
+ error.name = "EventSourceError";
1330
+ if (errorResolve) {
1331
+ const reject = errorResolve;
1332
+ messageResolve = null;
1333
+ errorResolve = null;
1334
+ reject(error);
1335
+ } else {
1336
+ errorQueue.push(error);
1337
+ }
1338
+ };
1339
+ eventSource.addEventListener("message", messageHandler);
1340
+ eventSource.addEventListener("error", errorHandler);
1341
+ const gen = (async function* () {
1342
+ try {
1343
+ while (!closed) {
1344
+ if (messageQueue.length > 0) {
1345
+ yield messageQueue.shift();
1346
+ continue;
1347
+ }
1348
+ if (errorQueue.length > 0) {
1349
+ const error = errorQueue.shift();
1350
+ throw error;
1351
+ }
1352
+ const result = await new Promise((resolve, reject) => {
1353
+ messageResolve = resolve;
1354
+ errorResolve = reject;
1355
+ }).finally(() => {
1356
+ messageResolve = null;
1357
+ errorResolve = null;
1358
+ });
1359
+ if (!closed && result) {
1360
+ yield result;
1361
+ }
1362
+ }
1363
+ } finally {
1364
+ closed = true;
1365
+ cleanup();
1366
+ eventSource.close();
1367
+ }
1368
+ })();
1369
+ const origReturn = gen.return.bind(gen);
1370
+ const managed = gen;
1371
+ managed.close = close;
1372
+ managed.return = (value) => {
1373
+ close();
1374
+ return origReturn(value);
1375
+ };
1376
+ return managed;
1377
+ }
1378
+ function isEventSourceError(error) {
1379
+ return error instanceof Error && error.name === "EventSourceError";
1380
+ }
1381
+
1382
+ // src/providers/rateGate.ts
1383
+ var DEFAULT_MAX_CONCURRENT = 6;
1384
+ var DEFAULT_COOLDOWN_MS = 5e3;
1385
+ var MAX_COOLDOWN_MS = 6e4;
1386
+ var DEFAULT_JITTER_MS = 500;
1387
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1388
+ function parseRetryAfterMs(header) {
1389
+ if (header === null || header === void 0) return void 0;
1390
+ const trimmed = header.trim();
1391
+ if (trimmed === "") return void 0;
1392
+ const seconds = Number(trimmed);
1393
+ if (Number.isFinite(seconds)) return seconds < 0 ? void 0 : seconds * 1e3;
1394
+ const at = Date.parse(trimmed);
1395
+ if (!Number.isNaN(at)) return Math.max(0, at - Date.now());
1396
+ return void 0;
1397
+ }
1398
+ function requestOrigin(input) {
1399
+ let url;
1400
+ if (typeof input === "string") {
1401
+ url = input;
1402
+ } else if (input instanceof URL) {
1403
+ url = input.href;
1404
+ } else {
1405
+ url = input.url;
1406
+ }
1407
+ try {
1408
+ return new URL(url).origin;
1409
+ } catch {
1410
+ return url;
1411
+ }
1412
+ }
1413
+ var OriginRateGate = class {
1414
+ states = /* @__PURE__ */ new Map();
1415
+ maxConcurrent;
1416
+ defaultCooldownMs;
1417
+ maxCooldownMs;
1418
+ jitterMs;
1419
+ constructor(options) {
1420
+ this.maxConcurrent = options?.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;
1421
+ this.defaultCooldownMs = options?.defaultCooldownMs ?? DEFAULT_COOLDOWN_MS;
1422
+ this.maxCooldownMs = options?.maxCooldownMs ?? MAX_COOLDOWN_MS;
1423
+ this.jitterMs = options?.jitterMs ?? DEFAULT_JITTER_MS;
1424
+ }
1425
+ /**
1426
+ * Run `fn` under the origin's concurrency cap and behind any active
1427
+ * cooldown. Put only the request in `fn`: the slot is released as soon as
1428
+ * it settles, so body parsing doesn't hold one.
1429
+ */
1430
+ async run(input, fn) {
1431
+ const state = this.stateFor(requestOrigin(input));
1432
+ await this.acquire(state);
1433
+ try {
1434
+ for (; ; ) {
1435
+ const remaining = state.blockedUntil - Date.now();
1436
+ if (remaining <= 0) break;
1437
+ await sleep(remaining + Math.random() * this.jitterMs);
1438
+ }
1439
+ return await fn();
1440
+ } finally {
1441
+ this.release(state);
1442
+ }
1443
+ }
1444
+ /**
1445
+ * {@link run} for a request whose response the gate should inspect: a `429`
1446
+ * is recorded *before* the slot is released. Reporting after `run()` resolves
1447
+ * is too late — `release()` hands the slot to the next queued waiter, which
1448
+ * resumes, sees no cooldown, and sends into the limiter that just refused us.
1449
+ *
1450
+ * Prefer this over `run` for anything returning a `Response`.
1451
+ */
1452
+ runHttp(input, fn) {
1453
+ return this.run(input, async () => {
1454
+ const response = await fn();
1455
+ if (response.status === 429) {
1456
+ this.reportRateLimited(input, response.headers?.get("retry-after"));
1457
+ }
1458
+ return response;
1459
+ });
1460
+ }
1461
+ /**
1462
+ * Record an observed `429`, pausing every gated request to that origin.
1463
+ * Monotonic: a shorter cooldown never shortens one already in effect.
1464
+ */
1465
+ reportRateLimited(input, retryAfterHeader) {
1466
+ const cooldown = Math.min(
1467
+ parseRetryAfterMs(retryAfterHeader) ?? this.defaultCooldownMs,
1468
+ this.maxCooldownMs
1469
+ );
1470
+ const state = this.stateFor(requestOrigin(input));
1471
+ state.blockedUntil = Math.max(state.blockedUntil, Date.now() + cooldown);
1472
+ }
1473
+ /** Milliseconds left on `input` origin's cooldown; `0` when not cooling down. */
1474
+ cooldownRemainingMs(input) {
1475
+ const state = this.states.get(requestOrigin(input));
1476
+ if (!state) return 0;
1477
+ return Math.max(0, state.blockedUntil - Date.now());
1478
+ }
1479
+ /**
1480
+ * Drop all per-origin state, so test suites don't inherit each other's
1481
+ * cooldowns. Waiters queued on the discarded state still drain normally.
1482
+ */
1483
+ reset() {
1484
+ this.states.clear();
1485
+ }
1486
+ stateFor(origin) {
1487
+ let state = this.states.get(origin);
1488
+ if (!state) {
1489
+ state = { blockedUntil: 0, active: 0, queue: [] };
1490
+ this.states.set(origin, state);
1491
+ }
1492
+ return state;
1493
+ }
1494
+ acquire(state) {
1495
+ if (state.active < this.maxConcurrent) {
1496
+ state.active += 1;
1497
+ return Promise.resolve();
1498
+ }
1499
+ return new Promise((resolve) => {
1500
+ state.queue.push(() => {
1501
+ state.active += 1;
1502
+ resolve();
1503
+ });
1504
+ });
1505
+ }
1506
+ release(state) {
1507
+ state.active -= 1;
1508
+ const next = state.queue.shift();
1509
+ if (next) next();
1510
+ }
1511
+ };
1512
+ var rateGate = new OriginRateGate();
1513
+
1514
+ // src/providers/ark.ts
1515
+ var DigestMismatchError = class extends Error {
1516
+ constructor(message) {
1517
+ super(message);
1518
+ this.name = "DigestMismatchError";
1519
+ }
1520
+ };
1521
+ var SettlementEventType = /* @__PURE__ */ ((SettlementEventType2) => {
1522
+ SettlementEventType2["BatchStarted"] = "batch_started";
1523
+ SettlementEventType2["BatchFinalization"] = "batch_finalization";
1524
+ SettlementEventType2["BatchFinalized"] = "batch_finalized";
1525
+ SettlementEventType2["BatchFailed"] = "batch_failed";
1526
+ SettlementEventType2["TreeSigningStarted"] = "tree_signing_started";
1527
+ SettlementEventType2["TreeNonces"] = "tree_nonces";
1528
+ SettlementEventType2["TreeTx"] = "tree_tx";
1529
+ SettlementEventType2["TreeSignature"] = "tree_signature";
1530
+ SettlementEventType2["StreamStarted"] = "stream_started";
1531
+ return SettlementEventType2;
1532
+ })(SettlementEventType || {});
1533
+ var RestArkProvider = class {
1534
+ constructor(serverUrl = DEFAULT_ARKADE_SERVER_URL) {
1535
+ this.serverUrl = serverUrl;
1536
+ }
1537
+ serverUrl;
1538
+ /**
1539
+ * Last server-info digest seen (from {@link getInfo}). Sent as `X-Digest`
1540
+ * on outgoing requests so arkd can reject a client whose cached info is
1541
+ * stale. Empty until the first {@link getInfo}.
1542
+ */
1543
+ _digest = "";
1544
+ _serverInfoListeners = /* @__PURE__ */ new Set();
1545
+ /**
1546
+ * Subscribe to server-info changes. Fired when a request is rejected with
1547
+ * `DIGEST_MISMATCH` and fresh info is re-fetched, so consumers (the wallet)
1548
+ * can re-derive signer-dependent state mid-session without polling. Returns
1549
+ * an unsubscribe function.
1550
+ */
1551
+ onServerInfoChanged(listener) {
1552
+ this._serverInfoListeners.add(listener);
1553
+ return () => {
1554
+ this._serverInfoListeners.delete(listener);
1555
+ };
1556
+ }
1557
+ emitServerInfoChanged(info) {
1558
+ for (const listener of this._serverInfoListeners) {
1559
+ try {
1560
+ listener(info);
1561
+ } catch (e) {
1562
+ console.warn("onServerInfoChanged listener threw", e);
1563
+ }
1564
+ }
1565
+ }
1566
+ /**
1567
+ * `fetch` wrapper for arkd requests that participates in server-info digest
1568
+ * negotiation. Sends the cached `X-Digest`; when arkd rejects a request with
1569
+ * `DIGEST_MISMATCH`, refreshes {@link getInfo} (updating the digest), fires
1570
+ * {@link onServerInfoChanged}, and THROWS {@link DigestMismatchError} — it
1571
+ * never silently retries, since the in-flight request was built against the
1572
+ * now-stale config. Dormant until arkd returns the error — then it is the
1573
+ * instant, event-driven signer-rotation trigger. {@link getInfo} itself never
1574
+ * routes through here: it is the refresh path and must not be digest-gated.
1575
+ */
1576
+ async authedFetch(url, init) {
1577
+ const digest = this._digest;
1578
+ const headers = {
1579
+ ...init.headers
1580
+ };
1581
+ if (digest) headers["X-Digest"] = digest;
1582
+ let response;
1583
+ try {
1584
+ response = await fetch(url, { ...init, headers });
1585
+ } catch (err) {
1586
+ throw toProviderUnavailable(err, "arkade");
1587
+ }
1588
+ if (response.ok) return response;
1589
+ if (response.status === 429) {
1590
+ rateGate.reportRateLimited(url, response.headers?.get("retry-after"));
1591
+ }
1592
+ let body;
1593
+ try {
1594
+ body = await response.clone().text();
1595
+ } catch (e) {
1596
+ console.warn("authedFetch could not read response body for digest check", e);
1597
+ throwIfHttpUnavailable(response, "arkade");
1598
+ return response;
1599
+ }
1600
+ const arkError = maybeArkError(new Error(body));
1601
+ if (!arkError) throwIfHttpUnavailable(response, "arkade");
1602
+ if (!isArkError(arkError, ArkErrorName.DIGEST_MISMATCH)) return response;
1603
+ this._digest = "";
1604
+ const info = await this.getInfo();
1605
+ this.emitServerInfoChanged(info);
1606
+ throw new DigestMismatchError(
1607
+ "Arkade server reported a configuration digest mismatch; server info was refreshed. Rebuild and retry the request under the new server info."
1608
+ );
1609
+ }
1610
+ async getInfo() {
1611
+ const url = `${this.serverUrl}/v1/info`;
1612
+ const response = await rateGate.runHttp(url, () => fetch(url));
1613
+ if (!response.ok) {
1614
+ const errorText = await response.text();
1615
+ throwIfHttpUnavailable(response, "arkade", errorText);
1616
+ handleError(errorText, `Failed to get server info: ${response.statusText}`);
1617
+ }
1618
+ const fromServer = await response.json();
1619
+ const info = {
1620
+ boardingExitDelay: BigInt(fromServer.boardingExitDelay ?? 0),
1621
+ checkpointTapscript: fromServer.checkpointTapscript ?? "",
1622
+ deprecatedSigners: fromServer.deprecatedSigners?.map((signer) => ({
1623
+ // arkd advertises `cutoffDate` as a non-nullable field, so it
1624
+ // is always a bigint here — `0n` is the sentinel for "no
1625
+ // cutoff" (the classifier maps it to DUE_NOW). The grpc-gateway
1626
+ // marshals with EmitUnpopulated, so an unset `cutoff_date`
1627
+ // already arrives as `"0"`; a genuinely missing field defaults
1628
+ // to `0n` too. Never collapse to `undefined`.
1629
+ cutoffDate: BigInt(signer.cutoffDate ?? 0),
1630
+ pubkey: signer.pubkey ?? ""
1631
+ })) ?? [],
1632
+ digest: fromServer.digest ?? "",
1633
+ dust: BigInt(fromServer.dust ?? 0),
1634
+ fees: {
1635
+ intentFee: fromServer.fees?.intentFee ?? {},
1636
+ txFeeRate: fromServer?.fees?.txFeeRate ?? ""
1637
+ },
1638
+ forfeitAddress: fromServer.forfeitAddress ?? "",
1639
+ forfeitPubkey: fromServer.forfeitPubkey ?? "",
1640
+ network: fromServer.network ?? "",
1641
+ scheduledSession: "scheduledSession" in fromServer && fromServer.scheduledSession != null ? {
1642
+ duration: BigInt(fromServer.scheduledSession.duration ?? 0),
1643
+ nextStartTime: BigInt(fromServer.scheduledSession.nextStartTime ?? 0),
1644
+ nextEndTime: BigInt(fromServer.scheduledSession.nextEndTime ?? 0),
1645
+ period: BigInt(fromServer.scheduledSession.period ?? 0),
1646
+ fees: fromServer.scheduledSession.fees ?? {}
1647
+ } : void 0,
1648
+ serviceStatus: fromServer.serviceStatus ?? {},
1649
+ sessionDuration: BigInt(fromServer.sessionDuration ?? 0),
1650
+ signerPubkey: fromServer.signerPubkey ?? "",
1651
+ unilateralExitDelay: BigInt(fromServer.unilateralExitDelay ?? 0),
1652
+ utxoMaxAmount: BigInt(fromServer.utxoMaxAmount ?? -1),
1653
+ utxoMinAmount: BigInt(fromServer.utxoMinAmount ?? 0),
1654
+ version: fromServer.version ?? "",
1655
+ vtxoMaxAmount: BigInt(fromServer.vtxoMaxAmount ?? -1),
1656
+ vtxoMinAmount: BigInt(fromServer.vtxoMinAmount ?? 0)
1657
+ };
1658
+ this._digest = info.digest;
1659
+ return info;
1660
+ }
1661
+ async submitTx(signedArkTx, checkpointTxs) {
1662
+ const url = `${this.serverUrl}/v1/tx/submit`;
1663
+ const response = await this.authedFetch(url, {
1664
+ method: "POST",
1665
+ headers: {
1666
+ "Content-Type": "application/json"
1667
+ },
1668
+ body: JSON.stringify({
1669
+ signedArkTx,
1670
+ checkpointTxs
1671
+ })
1672
+ });
1673
+ if (!response.ok) {
1674
+ const errorText = await response.text();
1675
+ handleError(errorText, `Failed to submit virtual transaction: ${errorText}`);
1676
+ }
1677
+ const data = await response.json();
1678
+ return {
1679
+ arkTxid: data.arkTxid,
1680
+ finalArkTx: data.finalArkTx,
1681
+ signedCheckpointTxs: data.signedCheckpointTxs
1682
+ };
1683
+ }
1684
+ async finalizeTx(arkTxid, finalCheckpointTxs) {
1685
+ const url = `${this.serverUrl}/v1/tx/finalize`;
1686
+ const response = await this.authedFetch(url, {
1687
+ method: "POST",
1688
+ headers: {
1689
+ "Content-Type": "application/json"
1690
+ },
1691
+ body: JSON.stringify({
1692
+ arkTxid,
1693
+ finalCheckpointTxs
1694
+ })
1695
+ });
1696
+ if (!response.ok) {
1697
+ const errorText = await response.text();
1698
+ handleError(errorText, `Failed to finalize offchain transaction: ${errorText}`);
1699
+ }
1700
+ }
1701
+ async registerIntent(intent) {
1702
+ const url = `${this.serverUrl}/v1/batch/registerIntent`;
1703
+ const response = await this.authedFetch(url, {
1704
+ method: "POST",
1705
+ headers: {
1706
+ "Content-Type": "application/json"
1707
+ },
1708
+ body: JSON.stringify({
1709
+ intent: {
1710
+ proof: intent.proof,
1711
+ message: Intent.encodeMessage(intent.message)
1712
+ }
1713
+ })
1714
+ });
1715
+ if (!response.ok) {
1716
+ const errorText = await response.text();
1717
+ handleError(errorText, `Failed to register intent: ${errorText}`);
1718
+ }
1719
+ const data = await response.json();
1720
+ return data.intentId;
1721
+ }
1722
+ async deleteIntent(intent) {
1723
+ const url = `${this.serverUrl}/v1/batch/deleteIntent`;
1724
+ const response = await this.authedFetch(url, {
1725
+ method: "POST",
1726
+ headers: {
1727
+ "Content-Type": "application/json"
1728
+ },
1729
+ body: JSON.stringify({
1730
+ intent: {
1731
+ proof: intent.proof,
1732
+ message: Intent.encodeMessage(intent.message)
1733
+ }
1734
+ })
1735
+ });
1736
+ if (!response.ok) {
1737
+ const errorText = await response.text();
1738
+ handleError(errorText, `Failed to delete intent: ${errorText}`);
1739
+ }
1740
+ }
1741
+ async confirmRegistration(intentId) {
1742
+ const url = `${this.serverUrl}/v1/batch/ack`;
1743
+ const response = await this.authedFetch(url, {
1744
+ method: "POST",
1745
+ headers: {
1746
+ "Content-Type": "application/json"
1747
+ },
1748
+ body: JSON.stringify({
1749
+ intentId
1750
+ })
1751
+ });
1752
+ if (!response.ok) {
1753
+ const errorText = await response.text();
1754
+ handleError(errorText, `Failed to confirm registration: ${errorText}`);
1755
+ }
1756
+ }
1757
+ async submitTreeNonces(batchId, pubkey, nonces) {
1758
+ const url = `${this.serverUrl}/v1/batch/tree/submitNonces`;
1759
+ const response = await this.authedFetch(url, {
1760
+ method: "POST",
1761
+ headers: {
1762
+ "Content-Type": "application/json"
1763
+ },
1764
+ body: JSON.stringify({
1765
+ batchId,
1766
+ pubkey,
1767
+ treeNonces: encodeMusig2Nonces(nonces)
1768
+ })
1769
+ });
1770
+ if (!response.ok) {
1771
+ const errorText = await response.text();
1772
+ handleError(errorText, `Failed to submit tree nonces: ${errorText}`);
1773
+ }
1774
+ }
1775
+ async submitTreeSignatures(batchId, pubkey, signatures) {
1776
+ const url = `${this.serverUrl}/v1/batch/tree/submitSignatures`;
1777
+ const response = await this.authedFetch(url, {
1778
+ method: "POST",
1779
+ headers: {
1780
+ "Content-Type": "application/json"
1781
+ },
1782
+ body: JSON.stringify({
1783
+ batchId,
1784
+ pubkey,
1785
+ treeSignatures: encodeMusig2Signatures(signatures)
1786
+ })
1787
+ });
1788
+ if (!response.ok) {
1789
+ const errorText = await response.text();
1790
+ handleError(errorText, `Failed to submit tree signatures: ${errorText}`);
1791
+ }
1792
+ }
1793
+ async submitSignedForfeitTxs(signedForfeitTxs, signedCommitmentTx) {
1794
+ const url = `${this.serverUrl}/v1/batch/submitForfeitTxs`;
1795
+ const response = await this.authedFetch(url, {
1796
+ method: "POST",
1797
+ headers: {
1798
+ "Content-Type": "application/json"
1799
+ },
1800
+ body: JSON.stringify({
1801
+ signedForfeitTxs,
1802
+ signedCommitmentTx
1803
+ })
1804
+ });
1805
+ if (!response.ok) {
1806
+ const errorText = await response.text();
1807
+ handleError(errorText, `Failed to submit forfeit transactions: ${response.statusText}`);
1808
+ }
1809
+ }
1810
+ getEventStream(signal, topics) {
1811
+ const url = `${this.serverUrl}/v1/batch/events`;
1812
+ const queryParams = topics.length > 0 ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join("&")}` : "";
1813
+ let iterator = null;
1814
+ const closeIterator = () => iterator?.close();
1815
+ const self = this;
1816
+ const gen = (async function* () {
1817
+ const abortHandler = closeIterator;
1818
+ signal?.addEventListener("abort", abortHandler);
1819
+ try {
1820
+ while (!signal?.aborted) {
1821
+ const currentIterator = eventSourceIterator(new EventSource(url + queryParams));
1822
+ iterator = currentIterator;
1823
+ try {
1824
+ for await (const event of currentIterator) {
1825
+ if (signal?.aborted) break;
1826
+ try {
1827
+ const data = JSON.parse(event.data);
1828
+ const settlementEvent = self.parseSettlementEvent(data);
1829
+ if (settlementEvent) {
1830
+ yield settlementEvent;
1831
+ }
1832
+ } catch (err) {
1833
+ console.error("Failed to parse event:", err);
1834
+ throw err;
1835
+ }
1836
+ }
1837
+ } catch (error) {
1838
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
1839
+ break;
1840
+ }
1841
+ if (isFetchTimeoutError(error)) {
1842
+ console.debug("Timeout error ignored");
1843
+ continue;
1844
+ }
1845
+ if (isEventSourceError(error)) {
1846
+ throw error;
1847
+ }
1848
+ console.error("Event stream error:", error);
1849
+ throw error;
1850
+ } finally {
1851
+ currentIterator.close();
1852
+ iterator = null;
1853
+ }
1854
+ }
1855
+ } finally {
1856
+ signal?.removeEventListener("abort", abortHandler);
1857
+ closeIterator();
1858
+ }
1859
+ })();
1860
+ const origReturn = gen.return.bind(gen);
1861
+ gen.return = (value) => {
1862
+ closeIterator();
1863
+ return origReturn(value);
1864
+ };
1865
+ return gen;
1866
+ }
1867
+ getTransactionsStream(signal) {
1868
+ const url = `${this.serverUrl}/v1/txs`;
1869
+ let iterator = null;
1870
+ const closeIterator = () => iterator?.close();
1871
+ const self = this;
1872
+ const gen = (async function* () {
1873
+ const abortHandler = closeIterator;
1874
+ signal?.addEventListener("abort", abortHandler);
1875
+ try {
1876
+ while (!signal?.aborted) {
1877
+ try {
1878
+ const currentIterator = eventSourceIterator(new EventSource(url));
1879
+ iterator = currentIterator;
1880
+ for await (const event of currentIterator) {
1881
+ if (signal?.aborted) break;
1882
+ try {
1883
+ const data = JSON.parse(event.data);
1884
+ const txNotification = self.parseTransactionNotification(data);
1885
+ if (txNotification) {
1886
+ yield txNotification;
1887
+ }
1888
+ } catch (err) {
1889
+ console.error("Failed to parse transaction notification:", err);
1890
+ throw err;
1891
+ }
1892
+ }
1893
+ } catch (error) {
1894
+ if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
1895
+ break;
1896
+ }
1897
+ if (isFetchTimeoutError(error)) {
1898
+ console.debug("Timeout error ignored");
1899
+ continue;
1900
+ }
1901
+ if (isEventSourceError(error)) {
1902
+ throw error;
1903
+ }
1904
+ console.error("Transaction stream error:", error);
1905
+ throw error;
1906
+ } finally {
1907
+ closeIterator();
1908
+ iterator = null;
1909
+ }
1910
+ }
1911
+ } finally {
1912
+ signal?.removeEventListener("abort", abortHandler);
1913
+ closeIterator();
1914
+ }
1915
+ })();
1916
+ const origReturn = gen.return.bind(gen);
1917
+ gen.return = (value) => {
1918
+ closeIterator();
1919
+ return origReturn(value);
1920
+ };
1921
+ return gen;
1922
+ }
1923
+ async getPendingTxs(intent) {
1924
+ const url = `${this.serverUrl}/v1/tx/pending`;
1925
+ const response = await this.authedFetch(url, {
1926
+ method: "POST",
1927
+ headers: {
1928
+ "Content-Type": "application/json"
1929
+ },
1930
+ body: JSON.stringify({
1931
+ intent: {
1932
+ proof: intent.proof,
1933
+ message: Intent.encodeMessage(intent.message)
1934
+ }
1935
+ })
1936
+ });
1937
+ if (!response.ok) {
1938
+ const errorText = await response.text();
1939
+ handleError(errorText, `Failed to get pending transactions: ${errorText}`);
1940
+ }
1941
+ const data = await response.json();
1942
+ return data.pendingTxs;
1943
+ }
1944
+ parseSettlementEvent(data) {
1945
+ if (data.batchStarted) {
1946
+ return {
1947
+ type: "batch_started" /* BatchStarted */,
1948
+ id: data.batchStarted.id,
1949
+ intentIdHashes: data.batchStarted.intentIdHashes,
1950
+ batchExpiry: BigInt(data.batchStarted.batchExpiry)
1951
+ };
1952
+ }
1953
+ if (data.batchFinalization) {
1954
+ return {
1955
+ type: "batch_finalization" /* BatchFinalization */,
1956
+ id: data.batchFinalization.id,
1957
+ commitmentTx: data.batchFinalization.commitmentTx
1958
+ };
1959
+ }
1960
+ if (data.batchFinalized) {
1961
+ return {
1962
+ type: "batch_finalized" /* BatchFinalized */,
1963
+ id: data.batchFinalized.id,
1964
+ commitmentTxid: data.batchFinalized.commitmentTxid
1965
+ };
1966
+ }
1967
+ if (data.batchFailed) {
1968
+ return {
1969
+ type: "batch_failed" /* BatchFailed */,
1970
+ id: data.batchFailed.id,
1971
+ reason: data.batchFailed.reason
1972
+ };
1973
+ }
1974
+ if (data.treeSigningStarted) {
1975
+ return {
1976
+ type: "tree_signing_started" /* TreeSigningStarted */,
1977
+ id: data.treeSigningStarted.id,
1978
+ cosignersPublicKeys: data.treeSigningStarted.cosignersPubkeys,
1979
+ unsignedCommitmentTx: data.treeSigningStarted.unsignedCommitmentTx
1980
+ };
1981
+ }
1982
+ if (data.treeNoncesAggregated) {
1983
+ return null;
1984
+ }
1985
+ if (data.treeNonces) {
1986
+ return {
1987
+ type: "tree_nonces" /* TreeNonces */,
1988
+ id: data.treeNonces.id,
1989
+ topic: data.treeNonces.topic,
1990
+ txid: data.treeNonces.txid,
1991
+ nonces: decodeMusig2Nonces(data.treeNonces.nonces)
1992
+ // pubkey -> public nonce
1993
+ };
1994
+ }
1995
+ if (data.treeTx) {
1996
+ const children = Object.fromEntries(
1997
+ Object.entries(data.treeTx.children).map(([outputIndex, txid]) => {
1998
+ return [parseInt(outputIndex), txid];
1999
+ })
2000
+ );
2001
+ return {
2002
+ type: "tree_tx" /* TreeTx */,
2003
+ id: data.treeTx.id,
2004
+ topic: data.treeTx.topic,
2005
+ batchIndex: data.treeTx.batchIndex,
2006
+ chunk: {
2007
+ txid: data.treeTx.txid,
2008
+ tx: data.treeTx.tx,
2009
+ children
2010
+ }
2011
+ };
2012
+ }
2013
+ if (data.treeSignature) {
2014
+ return {
2015
+ type: "tree_signature" /* TreeSignature */,
2016
+ id: data.treeSignature.id,
2017
+ topic: data.treeSignature.topic,
2018
+ batchIndex: data.treeSignature.batchIndex,
2019
+ txid: data.treeSignature.txid,
2020
+ signature: data.treeSignature.signature
2021
+ };
2022
+ }
2023
+ if (data.streamStarted) {
2024
+ return {
2025
+ type: "stream_started" /* StreamStarted */,
2026
+ id: data.streamStarted.id
2027
+ };
2028
+ }
2029
+ if (data.heartbeat) {
2030
+ return null;
2031
+ }
2032
+ console.warn("Unknown event type:", data);
2033
+ return null;
2034
+ }
2035
+ parseTransactionNotification(data) {
2036
+ if (data.commitmentTx) {
2037
+ return {
2038
+ commitmentTx: {
2039
+ txid: data.commitmentTx.txid,
2040
+ tx: data.commitmentTx.tx,
2041
+ spentVtxos: data.commitmentTx.spentVtxos.map(mapVtxo),
2042
+ spendableVtxos: data.commitmentTx.spendableVtxos.map(mapVtxo),
2043
+ checkpointTxs: data.commitmentTx.checkpointTxs
2044
+ }
2045
+ };
2046
+ }
2047
+ if (data.arkTx) {
2048
+ return {
2049
+ arkTx: {
2050
+ txid: data.arkTx.txid,
2051
+ tx: data.arkTx.tx,
2052
+ spentVtxos: data.arkTx.spentVtxos.map(mapVtxo),
2053
+ spendableVtxos: data.arkTx.spendableVtxos.map(mapVtxo),
2054
+ checkpointTxs: data.arkTx.checkpointTxs
2055
+ }
2056
+ };
2057
+ }
2058
+ if (data.heartbeat) {
2059
+ return null;
2060
+ }
2061
+ console.warn("Unknown transaction notification type:", data);
2062
+ return null;
2063
+ }
2064
+ };
2065
+ function encodeMusig2Nonces(nonces) {
2066
+ const noncesObject = {};
2067
+ for (const [txid, nonce] of nonces) {
2068
+ noncesObject[txid] = hex.encode(nonce.pubNonce);
2069
+ }
2070
+ return noncesObject;
2071
+ }
2072
+ function encodeMusig2Signatures(signatures) {
2073
+ const sigObject = {};
2074
+ for (const [txid, sig] of signatures) {
2075
+ sigObject[txid] = hex.encode(sig.encode());
2076
+ }
2077
+ return sigObject;
2078
+ }
2079
+ function decodeMusig2Nonces(noncesObject) {
2080
+ return new Map(
2081
+ Object.entries(noncesObject).map(([txid, nonce]) => {
2082
+ if (typeof nonce !== "string") {
2083
+ throw new Error("invalid nonce");
2084
+ }
2085
+ return [txid, { pubNonce: hex.decode(nonce) }];
2086
+ })
2087
+ );
2088
+ }
2089
+ function isFetchTimeoutError(err) {
2090
+ const checkError = (error) => {
2091
+ if (!(error instanceof Error)) return false;
2092
+ const isCloudflare524 = error.name === "TypeError" && error.message === "Failed to fetch";
2093
+ return isCloudflare524 || error.name === "HeadersTimeoutError" || error.name === "BodyTimeoutError" || error.code === "UND_ERR_HEADERS_TIMEOUT" || error.code === "UND_ERR_BODY_TIMEOUT";
2094
+ };
2095
+ return checkError(err) || checkError(err.cause);
2096
+ }
2097
+ function mapVtxo(vtxo) {
2098
+ return {
2099
+ outpoint: {
2100
+ txid: vtxo.outpoint.txid,
2101
+ vout: vtxo.outpoint.vout
2102
+ },
2103
+ amount: vtxo.amount,
2104
+ script: vtxo.script,
2105
+ createdAt: vtxo.createdAt,
2106
+ expiresAt: vtxo.expiresAt,
2107
+ commitmentTxids: vtxo.commitmentTxids,
2108
+ isPreconfirmed: vtxo.isPreconfirmed,
2109
+ isSwept: vtxo.isSwept,
2110
+ isUnrolled: vtxo.isUnrolled,
2111
+ isSpent: vtxo.isSpent,
2112
+ spentBy: vtxo.spentBy,
2113
+ settledBy: vtxo.settledBy,
2114
+ arkTxid: vtxo.arkTxid
2115
+ };
2116
+ }
2117
+ function handleError(errorText, defaultMessage) {
2118
+ const error = new Error(errorText);
2119
+ const arkError = maybeArkError(error);
2120
+ throw arkError ?? new Error(defaultMessage);
2121
+ }
2122
+
2123
+ // src/providers/availability.ts
2124
+ function isRetryableProviderError(error) {
2125
+ return error instanceof ProviderUnavailableError || error instanceof FetchError || isFetchTimeoutError(error);
2126
+ }
2127
+
2128
+ // src/contracts/constants.ts
2129
+ var DEFAULT_PAGE_SIZE = 500;
2130
+ var SCRIPT_QUERY_CHUNK_SIZE = 32;
2131
+ var OUTPOINT_QUERY_CHUNK_SIZE = 64;
2132
+
2133
+ // src/wallet/vtxo.ts
2134
+ var EXPIRY_MIN_PLAUSIBLE_MS = Date.UTC(2025, 0, 1);
2135
+ async function resolveTimeHeight(provider) {
2136
+ const timestamp = /* @__PURE__ */ new Date();
2137
+ if (!provider) return { timestamp };
2138
+ try {
2139
+ const tip = await provider.getChainTip();
2140
+ return { timestamp, height: tip.height };
2141
+ } catch (e) {
2142
+ console.warn("Failed to fetch chain tip; height-based expiry will not be evaluated", e);
2143
+ return { timestamp };
2144
+ }
2145
+ }
2146
+ function parseWireExpiry(raw) {
2147
+ if (raw === null || raw === void 0 || raw === "") return {};
2148
+ const n = Number(raw);
2149
+ if (!Number.isFinite(n) || n <= 0) return {};
2150
+ const ms = n * 1e3;
2151
+ if (ms >= EXPIRY_MIN_PLAUSIBLE_MS) return { expiresAt: new Date(ms) };
2152
+ return { expiresAtHeight: n };
2153
+ }
2154
+ function toBatchExpiry(c) {
2155
+ if (c.expiresAt !== void 0) return c.expiresAt.getTime();
2156
+ if (c.expiresAtHeight !== void 0) return c.expiresAtHeight * 1e3;
2157
+ return void 0;
2158
+ }
2159
+ function parseLegacyExpiry(batchExpiry) {
2160
+ if (batchExpiry === void 0 || batchExpiry <= 0) return {};
2161
+ if (batchExpiry >= EXPIRY_MIN_PLAUSIBLE_MS) return { expiresAt: new Date(batchExpiry) };
2162
+ return { expiresAtHeight: batchExpiry / 1e3 };
2163
+ }
2164
+ function toVirtualStatus(c) {
2165
+ return {
2166
+ // Precedence is load-bearing: consumers bucket on this label, so any other order silently
2167
+ // moves VTXOs between buckets.
2168
+ state: c.isSpent ? "spent" : c.isSwept ? "swept" : c.isPreconfirmed ? "preconfirmed" : "settled",
2169
+ commitmentTxIds: c.commitmentTxIds,
2170
+ batchExpiry: toBatchExpiry(c)
2171
+ };
2172
+ }
2173
+ function normalizeVtxo(v) {
2174
+ const state = v.virtualStatus?.state;
2175
+ const canonicalExpiry = v.expiresAt !== void 0 || v.expiresAtHeight !== void 0;
2176
+ const expiry = canonicalExpiry ? (
2177
+ // Coerce: a backend that persists through JSON hands back an ISO string, which typechecks
2178
+ // as `Date` but returns NaN from `.getTime()` — comparing false against everything.
2179
+ {
2180
+ expiresAt: v.expiresAt === void 0 ? void 0 : new Date(v.expiresAt),
2181
+ expiresAtHeight: v.expiresAtHeight
2182
+ }
2183
+ ) : parseLegacyExpiry(v.virtualStatus?.batchExpiry);
2184
+ const isSpent = v.isSpent ?? state === "spent";
2185
+ const isSwept = v.isSwept ?? state === "swept";
2186
+ const isPreconfirmed = v.isPreconfirmed ?? state === "preconfirmed";
2187
+ const commitmentTxIds = v.commitmentTxIds ?? v.virtualStatus?.commitmentTxIds ?? [];
2188
+ return {
2189
+ ...v,
2190
+ isSpent,
2191
+ isSwept,
2192
+ isPreconfirmed,
2193
+ spentBy: v.spentBy ?? "",
2194
+ commitmentTxIds,
2195
+ ...expiry,
2196
+ virtualStatus: v.virtualStatus ?? toVirtualStatus({ isSpent, isSwept, isPreconfirmed, commitmentTxIds, ...expiry })
2197
+ };
2198
+ }
2199
+ function convertVtxo(vtxo) {
2200
+ const expiry = parseWireExpiry(vtxo.expiresAt);
2201
+ const facts = {
2202
+ isSpent: vtxo.isSpent,
2203
+ isSwept: vtxo.isSwept,
2204
+ isPreconfirmed: vtxo.isPreconfirmed,
2205
+ commitmentTxIds: vtxo.commitmentTxids,
2206
+ ...expiry
2207
+ };
2208
+ return {
2209
+ txid: vtxo.outpoint.txid,
2210
+ vout: vtxo.outpoint.vout,
2211
+ value: Number(vtxo.amount),
2212
+ status: {
2213
+ confirmed: !vtxo.isSwept && !vtxo.isPreconfirmed,
2214
+ isLeaf: !vtxo.isPreconfirmed
2215
+ },
2216
+ ...facts,
2217
+ virtualStatus: toVirtualStatus(facts),
2218
+ spentBy: vtxo.spentBy ?? "",
2219
+ settledBy: vtxo.settledBy,
2220
+ arkTxId: vtxo.arkTxid,
2221
+ createdAt: new Date(Number(vtxo.createdAt) * 1e3),
2222
+ isUnrolled: vtxo.isUnrolled,
2223
+ script: vtxo.script,
2224
+ assets: vtxo.assets?.map((a) => ({
2225
+ assetId: a.assetId,
2226
+ amount: BigInt(a.amount)
2227
+ }))
2228
+ };
2229
+ }
2230
+ async function getNormalizedVtxos(provider, opts) {
2231
+ const { vtxos, page } = await provider.getVtxos(opts);
2232
+ return { vtxos: vtxos.map(normalizeVtxo), page };
2233
+ }
2234
+ async function getAllNormalizedVtxos(provider, scripts, opts = {}) {
2235
+ const { pageSize = DEFAULT_PAGE_SIZE, ...filters } = opts;
2236
+ const all = [];
2237
+ for (let i = 0; i < scripts.length; i += SCRIPT_QUERY_CHUNK_SIZE) {
2238
+ const chunk = scripts.slice(i, i + SCRIPT_QUERY_CHUNK_SIZE);
2239
+ let pageIndex = 0;
2240
+ let hasMore = true;
2241
+ while (hasMore) {
2242
+ const { vtxos, page } = await getNormalizedVtxos(provider, {
2243
+ ...filters,
2244
+ scripts: chunk,
2245
+ pageIndex,
2246
+ pageSize
2247
+ });
2248
+ all.push(...vtxos);
2249
+ hasMore = page ? vtxos.length === pageSize : false;
2250
+ pageIndex++;
2251
+ if (hasMore) await new Promise((r) => setTimeout(r, 500));
2252
+ }
2253
+ }
2254
+ return all;
2255
+ }
2256
+ async function fetchVtxoCreatedAtByTxid(provider, txids) {
2257
+ const unique = [...new Set(txids)].filter((txid) => txid !== "");
2258
+ const createdAt = /* @__PURE__ */ new Map();
2259
+ for (let i = 0; i < unique.length; i += OUTPOINT_QUERY_CHUNK_SIZE) {
2260
+ const chunk = unique.slice(i, i + OUTPOINT_QUERY_CHUNK_SIZE);
2261
+ try {
2262
+ const { vtxos } = await getNormalizedVtxos(provider, {
2263
+ outpoints: chunk.map((txid) => ({ txid, vout: 0 })),
2264
+ pageSize: DEFAULT_PAGE_SIZE
2265
+ });
2266
+ for (const v of vtxos) {
2267
+ createdAt.set(v.txid, v.createdAt.getTime());
2268
+ }
2269
+ } catch (err) {
2270
+ if (!isRetryableProviderError(err)) throw err;
2271
+ }
2272
+ }
2273
+ return createdAt;
2274
+ }
2275
+ function hasTerminalSpend(vtxo) {
2276
+ const n = normalizeVtxo(vtxo);
2277
+ return !!n.isSpent || !!n.spentBy || !!n.settledBy;
2278
+ }
2279
+ function isPastExpiry(vtxo, now) {
2280
+ const n = normalizeVtxo(vtxo);
2281
+ if (n.expiresAt !== void 0 && now.timestamp.getTime() >= n.expiresAt.getTime()) return true;
2282
+ return n.expiresAtHeight !== void 0 && now.height !== void 0 && now.height >= n.expiresAtHeight;
2283
+ }
2284
+ function canSpendOffchain(vtxo, now) {
2285
+ const n = normalizeVtxo(vtxo);
2286
+ return !hasTerminalSpend(n) && !(n.isSwept || isPastExpiry(n, now));
2287
+ }
2288
+ function canRecoverOnchain(vtxo, now) {
2289
+ const n = normalizeVtxo(vtxo);
2290
+ return !hasTerminalSpend(n) && (n.isSwept || isPastExpiry(n, now));
2291
+ }
2292
+ function toOffchainInputFeeParams(vtxo) {
2293
+ const batchExpiry = toBatchExpiry(vtxo);
2294
+ return {
2295
+ amount: BigInt(vtxo.value),
2296
+ type: vtxo.isSwept ? "recoverable" : "vtxo",
2297
+ weight: 0,
2298
+ birth: vtxo.createdAt,
2299
+ expiry: batchExpiry ? new Date(batchExpiry) : void 0
2300
+ };
2301
+ }
2302
+ function isVirtualCoin(input) {
2303
+ return typeof input === "object" && input !== null && typeof input.script === "string";
2304
+ }
2305
+ function isSpendable(vtxo) {
2306
+ return !hasTerminalSpend(vtxo);
2307
+ }
2308
+ function isRecoverable(vtxo) {
2309
+ const n = normalizeVtxo(vtxo);
2310
+ return n.isSwept && !hasTerminalSpend(n);
2311
+ }
2312
+ function isExpired(vtxo) {
2313
+ const n = normalizeVtxo(vtxo);
2314
+ return n.isSwept || n.expiresAt !== void 0 && n.expiresAt.getTime() <= Date.now();
2315
+ }
2316
+
2317
+ export { ArkAddress, ArkError, ArkErrorName, ArkPsbtFieldKey, ArkPsbtFieldKeyType, CLTVMultisigTapscript, CSVMultisigTapscript, ConditionCSVMultisigTapscript, ConditionMultisigTapscript, ConditionWitness, CosignerPublicKey, DEFAULT_ARKADE_SERVER_URL, DEFAULT_NETWORK, DEFAULT_NETWORK_NAME, DEFAULT_PAGE_SIZE, DigestMismatchError, FetchError, Intent, MultisigTapscript, OP_RETURN_EMPTY_PKSCRIPT, PrevArkTxField, PrevoutTxField, ProviderUnavailableError, RestArkProvider, SCRIPT_QUERY_CHUNK_SIZE, SettlementEventType, TapTreeCoder, Transaction, VtxoScript, VtxoTaprootTree, VtxoTreeExpiry, assembleBtcdTaprootTree, baseFetch, buildVersion, canRecoverOnchain, canSpendOffchain, convertVtxo, craftToSpendTx, decodeTapscript, eventSourceIterator, fetch, fetchVtxoCreatedAtByTxid, getAllNormalizedVtxos, getArkPsbtFields, getNetwork, getNormalizedVtxos, getSequence, hasTerminalSpend, isArkError, isEventSourceError, isExpired, isFetchTimeoutError, isPastExpiry, isRecoverable, isRetryableProviderError, isSpendable, isVirtualCoin, maybeArkError, networks, normalizeVtxo, parseLegacyExpiry, rateGate, resolveTimeHeight, scriptFromTapLeafScript, sdkVersion, sequenceToTimelock, setArkPsbtField, throwIfHttpUnavailable, timelockToSequence, toBatchExpiry, toOffchainInputFeeParams, toProviderUnavailable, toVirtualStatus };
2318
+ //# sourceMappingURL=chunk-4EIKOJLD.js.map
2319
+ //# sourceMappingURL=chunk-4EIKOJLD.js.map