@arkade-os/sdk 0.4.53 → 0.4.55

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-Do9Lqfsp.d.cts} +36 -2
  8. package/dist/{ark-B69ugeJw.d.ts → ark-Do9Lqfsp.d.ts} +36 -2
  9. package/dist/{asyncStorageTaskQueue-B0SUQMXw.d.cts → asyncStorageTaskQueue-C3DYxvAT.d.cts} +1 -1
  10. package/dist/{asyncStorageTaskQueue-DWqxuIAs.d.ts → asyncStorageTaskQueue-DOnBOEDn.d.ts} +1 -1
  11. package/dist/{chunk-CZTQLA55.cjs → chunk-C6UYPHTQ.cjs} +9 -9
  12. package/dist/{chunk-CZTQLA55.cjs.map → chunk-C6UYPHTQ.cjs.map} +1 -1
  13. package/dist/{chunk-4GB73TRR.cjs → chunk-CSS74VCN.cjs} +17 -17
  14. package/dist/{chunk-4GB73TRR.cjs.map → chunk-CSS74VCN.cjs.map} +1 -1
  15. package/dist/{chunk-LHYNNDY6.js → chunk-ENWR2F2P.js} +8 -1327
  16. package/dist/chunk-ENWR2F2P.js.map +1 -0
  17. package/dist/{chunk-RNMLFY2V.cjs → chunk-G7DOBFQN.cjs} +19 -1367
  18. package/dist/chunk-G7DOBFQN.cjs.map +1 -0
  19. package/dist/chunk-JCJ5WFS3.js +2326 -0
  20. package/dist/chunk-JCJ5WFS3.js.map +1 -0
  21. package/dist/{chunk-B4WZOJAI.js → chunk-LAONNMM5.js} +4 -4
  22. package/dist/{chunk-B4WZOJAI.js.map → chunk-LAONNMM5.js.map} +1 -1
  23. package/dist/chunk-OWCPXRGP.cjs +2415 -0
  24. package/dist/chunk-OWCPXRGP.cjs.map +1 -0
  25. package/dist/{chunk-UZLQUWYP.js → chunk-QMPNPZ2T.js} +23 -4
  26. package/dist/chunk-QMPNPZ2T.js.map +1 -0
  27. package/dist/{chunk-3MMUKLCI.js → chunk-QO3IKBYL.js} +827 -130
  28. package/dist/chunk-QO3IKBYL.js.map +1 -0
  29. package/dist/{chunk-3XWDMLOI.js → chunk-SG4X7SEC.js} +4 -4
  30. package/dist/{chunk-3XWDMLOI.js.map → chunk-SG4X7SEC.js.map} +1 -1
  31. package/dist/{chunk-IEMPH7J6.cjs → chunk-V2TOHHPW.cjs} +60 -40
  32. package/dist/chunk-V2TOHHPW.cjs.map +1 -0
  33. package/dist/{chunk-3YC3LQ2E.cjs → chunk-ZPL34T2Q.cjs} +1191 -471
  34. package/dist/chunk-ZPL34T2Q.cjs.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-C0iIBxen.d.cts} +1 -1
  40. package/dist/{delegate-BU-Cpyjw.d.ts → delegate-DmhFrtdq.d.ts} +1 -1
  41. package/dist/{index-BWF-C9eh.d.ts → index-BNt4wcSh.d.ts} +2 -2
  42. package/dist/{index-tzAInyiX.d.cts → index-BnLM1XxA.d.cts} +2 -2
  43. package/dist/index.cjs +348 -240
  44. package/dist/index.d.cts +424 -14
  45. package/dist/index.d.ts +424 -14
  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-nzJFH8qb.d.ts → taskRunner-Bgs-0I3x.d.ts} +1 -1
  56. package/dist/{taskRunner-B7svzMhT.d.cts → taskRunner-RwUvgQ5M.d.cts} +1 -1
  57. package/dist/wallet/expo/background.cjs +14 -14
  58. package/dist/wallet/expo/background.d.cts +3 -3
  59. package/dist/wallet/expo/background.d.ts +3 -3
  60. package/dist/wallet/expo/background.js +6 -6
  61. package/dist/wallet/expo/index.cjs +14 -14
  62. package/dist/wallet/expo/index.d.cts +5 -5
  63. package/dist/wallet/expo/index.d.ts +5 -5
  64. package/dist/wallet/expo/index.js +5 -5
  65. package/dist/{wallet-B6Xiferv.d.cts → wallet-5Aou-V5n.d.ts} +83 -6
  66. package/dist/{wallet-CuHAI-eW.d.ts → wallet-Ck7BH8zR.d.cts} +83 -6
  67. package/dist/worker/expo/index.cjs +9 -9
  68. package/dist/worker/expo/index.d.cts +4 -4
  69. package/dist/worker/expo/index.d.ts +4 -4
  70. package/dist/worker/expo/index.js +5 -5
  71. package/package.json +1 -1
  72. package/dist/chunk-3MMUKLCI.js.map +0 -1
  73. package/dist/chunk-3YC3LQ2E.cjs.map +0 -1
  74. package/dist/chunk-E7HB3GKK.cjs +0 -1030
  75. package/dist/chunk-E7HB3GKK.cjs.map +0 -1
  76. package/dist/chunk-EFNLTS6Q.js +0 -976
  77. package/dist/chunk-EFNLTS6Q.js.map +0 -1
  78. package/dist/chunk-IEMPH7J6.cjs.map +0 -1
  79. package/dist/chunk-LHYNNDY6.js.map +0 -1
  80. package/dist/chunk-RNMLFY2V.cjs.map +0 -1
  81. package/dist/chunk-UZLQUWYP.js.map +0 -1
@@ -1,1328 +1,9 @@
1
- import { VtxoScript, getSequence, sequenceToTimelock, DEFAULT_ARKADE_SERVER_URL, convertVtxo } from './chunk-EFNLTS6Q.js';
1
+ import { DEFAULT_ARKADE_SERVER_URL, eventSourceIterator, convertVtxo, isFetchTimeoutError, isEventSourceError, rateGate, baseFetch, toProviderUnavailable, ProviderUnavailableError, throwIfHttpUnavailable } from './chunk-JCJ5WFS3.js';
2
2
  import { __export } from './chunk-NSBPE2FW.js';
3
- import { OP, Script, SigHash, RawWitness, Transaction as Transaction$1, ScriptNum } from '@scure/btc-signer';
4
- import { schnorr } from '@noble/curves/secp256k1.js';
5
3
  import { hex } from '@scure/base';
4
+ import { schnorr } from '@noble/curves/secp256k1.js';
6
5
  import { compareBytes } from '@scure/btc-signer/utils.js';
7
6
 
8
- var Transaction = class extends Transaction$1 {
9
- static ARK_TX_OPTS = {
10
- allowUnknown: true,
11
- allowUnknownOutputs: true,
12
- allowUnknownInputs: true
13
- };
14
- constructor(opts) {
15
- super(withArkOpts(opts));
16
- }
17
- static fromPSBT(psbt_, opts) {
18
- return Transaction$1.fromPSBT(psbt_, withArkOpts(opts));
19
- }
20
- static fromRaw(raw, opts) {
21
- return Transaction$1.fromRaw(raw, withArkOpts(opts));
22
- }
23
- };
24
- function withArkOpts(opts) {
25
- return { ...Transaction.ARK_TX_OPTS, ...opts };
26
- }
27
- var ArkPsbtFieldKey = /* @__PURE__ */ ((ArkPsbtFieldKey2) => {
28
- ArkPsbtFieldKey2["VtxoTaprootTree"] = "taptree";
29
- ArkPsbtFieldKey2["VtxoTreeExpiry"] = "expiry";
30
- ArkPsbtFieldKey2["Cosigner"] = "cosigner";
31
- ArkPsbtFieldKey2["ConditionWitness"] = "condition";
32
- ArkPsbtFieldKey2["PrevArkTx"] = "prevarktx";
33
- ArkPsbtFieldKey2["PrevoutTx"] = "prevouttx";
34
- return ArkPsbtFieldKey2;
35
- })(ArkPsbtFieldKey || {});
36
- var ArkPsbtFieldKeyType = 222;
37
- function setArkPsbtField(tx, inputIndex, coder, value) {
38
- tx.updateInput(inputIndex, {
39
- unknown: [...tx.getInput(inputIndex)?.unknown ?? [], coder.encode(value)]
40
- });
41
- }
42
- function getArkPsbtFields(tx, inputIndex, coder) {
43
- const unknown = tx.getInput(inputIndex)?.unknown ?? [];
44
- const fields = [];
45
- for (const u of unknown) {
46
- const v = coder.decode(u);
47
- if (v !== null) fields.push(v);
48
- }
49
- return fields;
50
- }
51
- var VtxoTaprootTree = {
52
- key: "taptree" /* VtxoTaprootTree */,
53
- encode: (value) => [
54
- {
55
- type: ArkPsbtFieldKeyType,
56
- key: encodedPsbtFieldKey["taptree" /* VtxoTaprootTree */]
57
- },
58
- value
59
- ],
60
- decode: (value) => nullIfCatch(() => {
61
- if (!checkKeyMatch(value[0], "taptree" /* VtxoTaprootTree */)) return null;
62
- return value[1];
63
- })
64
- };
65
- var ConditionWitness = {
66
- key: "condition" /* ConditionWitness */,
67
- encode: (value) => [
68
- {
69
- type: ArkPsbtFieldKeyType,
70
- key: encodedPsbtFieldKey["condition" /* ConditionWitness */]
71
- },
72
- RawWitness.encode(value)
73
- ],
74
- decode: (value) => nullIfCatch(() => {
75
- if (!checkKeyMatch(value[0], "condition" /* ConditionWitness */)) return null;
76
- return RawWitness.decode(value[1]);
77
- })
78
- };
79
- var PrevArkTxField = {
80
- key: "prevarktx" /* PrevArkTx */,
81
- encode: (value) => [
82
- {
83
- type: ArkPsbtFieldKeyType,
84
- key: encodedPsbtFieldKey["prevarktx" /* PrevArkTx */]
85
- },
86
- value
87
- ],
88
- decode: (value) => nullIfCatch(() => {
89
- if (!checkKeyMatch(value[0], "prevarktx" /* PrevArkTx */)) return null;
90
- return value[1];
91
- })
92
- };
93
- var PrevoutTxField = {
94
- key: "prevouttx" /* PrevoutTx */,
95
- encode: (value) => [
96
- {
97
- type: ArkPsbtFieldKeyType,
98
- key: encodedPsbtFieldKey["prevouttx" /* PrevoutTx */]
99
- },
100
- value
101
- ],
102
- decode: (value) => nullIfCatch(() => {
103
- if (!checkKeyMatch(value[0], "prevouttx" /* PrevoutTx */)) return null;
104
- return value[1];
105
- })
106
- };
107
- var CosignerPublicKey = {
108
- key: "cosigner" /* Cosigner */,
109
- encode: (value) => [
110
- {
111
- type: ArkPsbtFieldKeyType,
112
- key: new Uint8Array([...encodedPsbtFieldKey["cosigner" /* Cosigner */], value.index])
113
- },
114
- value.key
115
- ],
116
- decode: (unknown) => nullIfCatch(() => {
117
- if (!checkKeyMatch(unknown[0], "cosigner" /* Cosigner */, true)) return null;
118
- return {
119
- index: unknown[0].key[unknown[0].key.length - 1],
120
- key: unknown[1]
121
- };
122
- })
123
- };
124
- var VtxoTreeExpiry = {
125
- key: "expiry" /* VtxoTreeExpiry */,
126
- encode: (value) => [
127
- {
128
- type: ArkPsbtFieldKeyType,
129
- key: encodedPsbtFieldKey["expiry" /* VtxoTreeExpiry */]
130
- },
131
- ScriptNum(6, true).encode(value.value === 0n ? 0n : value.value)
132
- ],
133
- decode: (unknown) => nullIfCatch(() => {
134
- if (!checkKeyMatch(unknown[0], "expiry" /* VtxoTreeExpiry */)) return null;
135
- const v = ScriptNum(6, true).decode(unknown[1]);
136
- if (!v) return null;
137
- return sequenceToTimelock(Number(v));
138
- })
139
- };
140
- var encodedPsbtFieldKey = Object.fromEntries(
141
- Object.values(ArkPsbtFieldKey).map((key) => [key, new TextEncoder().encode(key)])
142
- );
143
- var nullIfCatch = (fn) => {
144
- try {
145
- return fn();
146
- } catch {
147
- return null;
148
- }
149
- };
150
- function checkKeyMatch(key, arkPsbtFieldKey, prefixOnly = false) {
151
- if (key.type !== ArkPsbtFieldKeyType) return false;
152
- const expected = encodedPsbtFieldKey[arkPsbtFieldKey];
153
- if (key.key.length < expected.length) return false;
154
- if (!prefixOnly && key.key.length !== expected.length) return false;
155
- for (let i = 0; i < expected.length; i++) {
156
- if (key.key[i] !== expected[i]) return false;
157
- }
158
- return true;
159
- }
160
-
161
- // package.json
162
- var version = "0.4.53";
163
-
164
- // src/utils/fetch.ts
165
- var buildVersion = "0.9.9";
166
- var sdkVersion = `ts-sdk/${version}`;
167
- var FetchError = class extends Error {
168
- /** The request URL that failed, when derivable from the `fetch` input. */
169
- url;
170
- /** The HTTP method of the failed request (defaults to `"GET"`). */
171
- method;
172
- constructor(message, options) {
173
- super(message, { cause: options.cause });
174
- this.name = "FetchError";
175
- this.url = options.url;
176
- this.method = options.method;
177
- }
178
- };
179
- function baseFetch(input, init) {
180
- if (typeof globalThis.fetch !== "function") {
181
- throw new Error("Fetch API is not available in this environment.");
182
- }
183
- return globalThis.fetch(input, init).catch((cause) => {
184
- const { url, method } = describeRequest(input, init);
185
- throw new FetchError(`Network request failed: ${method} ${url}`, { url, method, cause });
186
- });
187
- }
188
- function fetch(input, init) {
189
- const headers = new Headers(init?.headers);
190
- headers.set("X-Build-Version", buildVersion);
191
- headers.set("X-SDK-VERSION", sdkVersion);
192
- return baseFetch(input, { ...init, headers });
193
- }
194
- function describeRequest(input, init) {
195
- let url;
196
- if (typeof input === "string") {
197
- url = input;
198
- } else if (input instanceof URL) {
199
- url = input.href;
200
- } else {
201
- url = input.url;
202
- }
203
- let method;
204
- if (init?.method !== void 0) {
205
- method = init.method;
206
- } else if (input instanceof Request) {
207
- method = input.method;
208
- } else {
209
- method = "GET";
210
- }
211
- return { url, method };
212
- }
213
-
214
- // src/providers/errors.ts
215
- var ArkError = class extends Error {
216
- constructor(code, message, name, metadata) {
217
- super(message);
218
- this.code = code;
219
- this.message = message;
220
- this.name = name;
221
- this.metadata = metadata;
222
- }
223
- code;
224
- message;
225
- name;
226
- metadata;
227
- };
228
- var ArkErrorName = {
229
- DIGEST_MISMATCH: "DIGEST_MISMATCH",
230
- VTXO_ALREADY_SPENT: "VTXO_ALREADY_SPENT",
231
- INVALID_TX_FILTER: "INVALID_TX_FILTER",
232
- TX_FILTERS_LIMIT_EXCEEDED: "TX_FILTERS_LIMIT_EXCEEDED",
233
- /**
234
- * A CLTV closure was spent before its absolute locktime matured. Raised only by
235
- * `submitTx` (never `finalizeTx`), with metadata
236
- * `{ locktime, current_locktime, type: "height" | "time" }`.
237
- *
238
- * Self-healing, so defer and retry rather than fail: the server matures a
239
- * seconds-locktime against the **chain tip block's timestamp**, not its wall clock,
240
- * so a spend attempted promptly at maturity is rejected until a later block lands.
241
- */
242
- FORFEIT_CLOSURE_LOCKED: "FORFEIT_CLOSURE_LOCKED"
243
- };
244
- function isArkError(error, name) {
245
- return error instanceof ArkError && (name === void 0 || error.name === name);
246
- }
247
- var ProviderUnavailableError = class extends Error {
248
- /** Always `true`: this error type only ever wraps retryable conditions. */
249
- retryable = true;
250
- constructor(message, options) {
251
- super(message, { cause: options?.cause });
252
- this.name = "ProviderUnavailableError";
253
- }
254
- };
255
- function throwIfHttpUnavailable(response, kind, body) {
256
- if (body !== void 0 && maybeArkError(new Error(body))) return;
257
- if (response.status === 429 || response.status >= 500) {
258
- throw new ProviderUnavailableError(
259
- `${kind} unavailable: ${response.status} ${response.statusText}`
260
- );
261
- }
262
- }
263
- function toProviderUnavailable(err, kind) {
264
- if (err instanceof FetchError) {
265
- return new ProviderUnavailableError(`${kind} request failed`, { cause: err });
266
- }
267
- return err;
268
- }
269
- function maybeArkError(error) {
270
- try {
271
- if (!(error instanceof Error)) return void 0;
272
- const decoded = JSON.parse(error.message);
273
- if (Array.isArray(decoded.details)) {
274
- for (const details of decoded.details) {
275
- if (!("@type" in details)) continue;
276
- const type = details["@type"];
277
- if (type !== "type.googleapis.com/ark.v1.ErrorDetails") continue;
278
- if (!("code" in details)) continue;
279
- const code = details.code;
280
- if (!("message" in details)) continue;
281
- const message = details.message;
282
- if (!("name" in details)) continue;
283
- const name = details.name;
284
- let metadata;
285
- if ("metadata" in details && isMetadata(details.metadata)) {
286
- metadata = details.metadata;
287
- }
288
- return new ArkError(code, message, name, metadata);
289
- }
290
- }
291
- if (typeof decoded.message === "string") {
292
- const m = decoded.message.match(/^([A-Z][A-Z0-9_]*) \((\d+)\): ([\s\S]*)$/);
293
- if (m) return new ArkError(Number(m[2]), m[3], m[1]);
294
- }
295
- return void 0;
296
- } catch (e) {
297
- return void 0;
298
- }
299
- }
300
- function isMetadata(value) {
301
- return typeof value === "object" && value !== null && !Array.isArray(value);
302
- }
303
- var Intent;
304
- ((Intent2) => {
305
- function create(message, ins, outputs = []) {
306
- if (typeof message !== "string") {
307
- message = encodeMessage(message);
308
- }
309
- if (ins.length == 0) throw new Error("intent proof requires at least one input");
310
- const inputs = ins.map(prepareCoinAsIntentProofInput);
311
- if (!validateInputs(inputs)) ;
312
- if (!validateOutputs(outputs)) ;
313
- const toSpend = craftToSpendTx(message, inputs[0].witnessUtxo.script);
314
- return craftToSignTx(toSpend, inputs, outputs, message);
315
- }
316
- Intent2.create = create;
317
- function fee(proof) {
318
- let sumOfInputs = 0n;
319
- for (let i = 0; i < proof.inputsLength; i++) {
320
- const input = proof.getInput(i);
321
- if (input.witnessUtxo === void 0)
322
- throw new Error("intent proof input requires witness utxo");
323
- sumOfInputs += input.witnessUtxo.amount;
324
- }
325
- let sumOfOutputs = 0n;
326
- for (let i = 0; i < proof.outputsLength; i++) {
327
- const output = proof.getOutput(i);
328
- if (output.amount === void 0) throw new Error("intent proof output requires amount");
329
- sumOfOutputs += output.amount;
330
- }
331
- if (sumOfOutputs > sumOfInputs) {
332
- throw new Error(
333
- `intent proof output amount is greater than input amount: ${sumOfOutputs} > ${sumOfInputs}`
334
- );
335
- }
336
- return Number(sumOfInputs - sumOfOutputs);
337
- }
338
- Intent2.fee = fee;
339
- function encodeMessage(message) {
340
- switch (message.type) {
341
- case "register":
342
- return JSON.stringify({
343
- type: "register",
344
- onchain_output_indexes: message.onchain_output_indexes,
345
- valid_at: message.valid_at,
346
- expire_at: message.expire_at,
347
- cosigners_public_keys: message.cosigners_public_keys
348
- });
349
- case "delete":
350
- return JSON.stringify({
351
- type: "delete",
352
- expire_at: message.expire_at
353
- });
354
- case "get-pending-tx":
355
- return JSON.stringify({
356
- type: "get-pending-tx",
357
- expire_at: message.expire_at
358
- });
359
- }
360
- }
361
- Intent2.encodeMessage = encodeMessage;
362
- })(Intent || (Intent = {}));
363
- var OP_RETURN_EMPTY_PKSCRIPT = new Uint8Array([OP.RETURN]);
364
- var ZERO_32 = new Uint8Array(32).fill(0);
365
- var MAX_INDEX = 4294967295;
366
- var TAG_INTENT_PROOF = "ark-intent-proof-message";
367
- var PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE = 9;
368
- function validateInput(input) {
369
- if (input.index === void 0) throw new Error("intent proof input requires index");
370
- if (input.txid === void 0) throw new Error("intent proof input requires txid");
371
- if (input.witnessUtxo === void 0)
372
- throw new Error("intent proof input requires witness utxo");
373
- return true;
374
- }
375
- function validateInputs(inputs) {
376
- inputs.forEach(validateInput);
377
- return true;
378
- }
379
- function validateOutput(output) {
380
- if (output.amount === void 0) throw new Error("intent proof output requires amount");
381
- if (output.script === void 0) throw new Error("intent proof output requires script");
382
- return true;
383
- }
384
- function validateOutputs(outputs) {
385
- outputs.forEach(validateOutput);
386
- return true;
387
- }
388
- function craftToSpendTx(message, pkScript, tag = TAG_INTENT_PROOF) {
389
- const messageHash = hashMessage(message, tag);
390
- const tx = new Transaction({
391
- version: 0
392
- });
393
- tx.addInput({
394
- txid: ZERO_32,
395
- // zero hash
396
- index: MAX_INDEX,
397
- sequence: 0
398
- });
399
- tx.addOutput({
400
- amount: 0n,
401
- script: pkScript
402
- });
403
- tx.updateInput(0, {
404
- finalScriptSig: Script.encode(["OP_0", messageHash])
405
- });
406
- return tx;
407
- }
408
- function craftToSignTx(toSpend, inputs, outputs, message) {
409
- const firstInput = inputs[0];
410
- const tx = new Transaction({
411
- version: 2,
412
- lockTime: 0
413
- });
414
- tx.addInput({
415
- ...firstInput,
416
- txid: toSpend.id,
417
- index: 0,
418
- witnessUtxo: {
419
- script: firstInput.witnessUtxo.script,
420
- amount: 0n
421
- },
422
- sighashType: SigHash.ALL
423
- });
424
- for (const [i, input] of inputs.entries()) {
425
- tx.addInput({
426
- ...input,
427
- sighashType: SigHash.ALL
428
- });
429
- if (input.unknown?.length) {
430
- tx.updateInput(i + 1, {
431
- unknown: input.unknown
432
- });
433
- }
434
- }
435
- if (outputs.length === 0) {
436
- outputs = [
437
- {
438
- amount: 0n,
439
- script: OP_RETURN_EMPTY_PKSCRIPT
440
- }
441
- ];
442
- }
443
- for (const output of outputs) {
444
- tx.addOutput({
445
- amount: output.amount,
446
- script: output.script
447
- });
448
- }
449
- const global = tx.global;
450
- global.unknown = [
451
- ...global.unknown ?? [],
452
- [
453
- { type: PSBT_GLOBAL_GENERIC_SIGNED_MESSAGE, key: new Uint8Array() },
454
- new TextEncoder().encode(message)
455
- ]
456
- ];
457
- return tx;
458
- }
459
- function hashMessage(message, tag = TAG_INTENT_PROOF) {
460
- return schnorr.utils.taggedHash(tag, new TextEncoder().encode(message));
461
- }
462
- function prepareCoinAsIntentProofInput(coin) {
463
- if (!("tapTree" in coin)) {
464
- return coin;
465
- }
466
- const vtxoScript = VtxoScript.decode(coin.tapTree);
467
- const sequence = getSequence(coin.intentTapLeafScript);
468
- const unknown = [VtxoTaprootTree.encode(coin.tapTree)];
469
- if (coin.extraWitness) {
470
- unknown.push(ConditionWitness.encode(coin.extraWitness));
471
- }
472
- return {
473
- txid: hex.decode(coin.txid),
474
- index: coin.vout,
475
- witnessUtxo: {
476
- amount: BigInt(coin.value),
477
- script: vtxoScript.pkScript
478
- },
479
- sequence,
480
- tapLeafScript: [coin.intentTapLeafScript],
481
- unknown
482
- };
483
- }
484
-
485
- // src/providers/utils.ts
486
- function createAbortError() {
487
- const error = new Error("EventSource closed");
488
- error.name = "AbortError";
489
- return error;
490
- }
491
- function eventSourceIterator(eventSource) {
492
- const messageQueue = [];
493
- const errorQueue = [];
494
- let messageResolve = null;
495
- let errorResolve = null;
496
- let closed = false;
497
- let cleanedUp = false;
498
- const cleanup = () => {
499
- if (cleanedUp) return;
500
- cleanedUp = true;
501
- eventSource.removeEventListener("message", messageHandler);
502
- eventSource.removeEventListener("error", errorHandler);
503
- };
504
- const close = () => {
505
- if (closed) return;
506
- closed = true;
507
- messageQueue.length = 0;
508
- errorQueue.length = 0;
509
- eventSource.close();
510
- cleanup();
511
- if (errorResolve) {
512
- const reject = errorResolve;
513
- messageResolve = null;
514
- errorResolve = null;
515
- reject(createAbortError());
516
- }
517
- };
518
- const messageHandler = (event) => {
519
- if (closed) return;
520
- if (messageResolve) {
521
- const resolve = messageResolve;
522
- messageResolve = null;
523
- errorResolve = null;
524
- resolve(event);
525
- } else {
526
- messageQueue.push(event);
527
- }
528
- };
529
- const errorHandler = () => {
530
- if (closed) return;
531
- const error = new Error("EventSource error");
532
- error.name = "EventSourceError";
533
- if (errorResolve) {
534
- const reject = errorResolve;
535
- messageResolve = null;
536
- errorResolve = null;
537
- reject(error);
538
- } else {
539
- errorQueue.push(error);
540
- }
541
- };
542
- eventSource.addEventListener("message", messageHandler);
543
- eventSource.addEventListener("error", errorHandler);
544
- const gen = (async function* () {
545
- try {
546
- while (!closed) {
547
- if (messageQueue.length > 0) {
548
- yield messageQueue.shift();
549
- continue;
550
- }
551
- if (errorQueue.length > 0) {
552
- const error = errorQueue.shift();
553
- throw error;
554
- }
555
- const result = await new Promise((resolve, reject) => {
556
- messageResolve = resolve;
557
- errorResolve = reject;
558
- }).finally(() => {
559
- messageResolve = null;
560
- errorResolve = null;
561
- });
562
- if (!closed && result) {
563
- yield result;
564
- }
565
- }
566
- } finally {
567
- closed = true;
568
- cleanup();
569
- eventSource.close();
570
- }
571
- })();
572
- const origReturn = gen.return.bind(gen);
573
- const managed = gen;
574
- managed.close = close;
575
- managed.return = (value) => {
576
- close();
577
- return origReturn(value);
578
- };
579
- return managed;
580
- }
581
- function isEventSourceError(error) {
582
- return error instanceof Error && error.name === "EventSourceError";
583
- }
584
-
585
- // src/providers/rateGate.ts
586
- var DEFAULT_MAX_CONCURRENT = 6;
587
- var DEFAULT_COOLDOWN_MS = 5e3;
588
- var MAX_COOLDOWN_MS = 6e4;
589
- var DEFAULT_JITTER_MS = 500;
590
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
591
- function parseRetryAfterMs(header) {
592
- if (header === null || header === void 0) return void 0;
593
- const trimmed = header.trim();
594
- if (trimmed === "") return void 0;
595
- const seconds = Number(trimmed);
596
- if (Number.isFinite(seconds)) return seconds < 0 ? void 0 : seconds * 1e3;
597
- const at = Date.parse(trimmed);
598
- if (!Number.isNaN(at)) return Math.max(0, at - Date.now());
599
- return void 0;
600
- }
601
- function requestOrigin(input) {
602
- let url;
603
- if (typeof input === "string") {
604
- url = input;
605
- } else if (input instanceof URL) {
606
- url = input.href;
607
- } else {
608
- url = input.url;
609
- }
610
- try {
611
- return new URL(url).origin;
612
- } catch {
613
- return url;
614
- }
615
- }
616
- var OriginRateGate = class {
617
- states = /* @__PURE__ */ new Map();
618
- maxConcurrent;
619
- defaultCooldownMs;
620
- maxCooldownMs;
621
- jitterMs;
622
- constructor(options) {
623
- this.maxConcurrent = options?.maxConcurrent ?? DEFAULT_MAX_CONCURRENT;
624
- this.defaultCooldownMs = options?.defaultCooldownMs ?? DEFAULT_COOLDOWN_MS;
625
- this.maxCooldownMs = options?.maxCooldownMs ?? MAX_COOLDOWN_MS;
626
- this.jitterMs = options?.jitterMs ?? DEFAULT_JITTER_MS;
627
- }
628
- /**
629
- * Run `fn` under the origin's concurrency cap and behind any active
630
- * cooldown. Put only the request in `fn`: the slot is released as soon as
631
- * it settles, so body parsing doesn't hold one.
632
- */
633
- async run(input, fn) {
634
- const state = this.stateFor(requestOrigin(input));
635
- await this.acquire(state);
636
- try {
637
- for (; ; ) {
638
- const remaining = state.blockedUntil - Date.now();
639
- if (remaining <= 0) break;
640
- await sleep(remaining + Math.random() * this.jitterMs);
641
- }
642
- return await fn();
643
- } finally {
644
- this.release(state);
645
- }
646
- }
647
- /**
648
- * {@link run} for a request whose response the gate should inspect: a `429`
649
- * is recorded *before* the slot is released. Reporting after `run()` resolves
650
- * is too late — `release()` hands the slot to the next queued waiter, which
651
- * resumes, sees no cooldown, and sends into the limiter that just refused us.
652
- *
653
- * Prefer this over `run` for anything returning a `Response`.
654
- */
655
- runHttp(input, fn) {
656
- return this.run(input, async () => {
657
- const response = await fn();
658
- if (response.status === 429) {
659
- this.reportRateLimited(input, response.headers?.get("retry-after"));
660
- }
661
- return response;
662
- });
663
- }
664
- /**
665
- * Record an observed `429`, pausing every gated request to that origin.
666
- * Monotonic: a shorter cooldown never shortens one already in effect.
667
- */
668
- reportRateLimited(input, retryAfterHeader) {
669
- const cooldown = Math.min(
670
- parseRetryAfterMs(retryAfterHeader) ?? this.defaultCooldownMs,
671
- this.maxCooldownMs
672
- );
673
- const state = this.stateFor(requestOrigin(input));
674
- state.blockedUntil = Math.max(state.blockedUntil, Date.now() + cooldown);
675
- }
676
- /** Milliseconds left on `input` origin's cooldown; `0` when not cooling down. */
677
- cooldownRemainingMs(input) {
678
- const state = this.states.get(requestOrigin(input));
679
- if (!state) return 0;
680
- return Math.max(0, state.blockedUntil - Date.now());
681
- }
682
- /**
683
- * Drop all per-origin state, so test suites don't inherit each other's
684
- * cooldowns. Waiters queued on the discarded state still drain normally.
685
- */
686
- reset() {
687
- this.states.clear();
688
- }
689
- stateFor(origin) {
690
- let state = this.states.get(origin);
691
- if (!state) {
692
- state = { blockedUntil: 0, active: 0, queue: [] };
693
- this.states.set(origin, state);
694
- }
695
- return state;
696
- }
697
- acquire(state) {
698
- if (state.active < this.maxConcurrent) {
699
- state.active += 1;
700
- return Promise.resolve();
701
- }
702
- return new Promise((resolve) => {
703
- state.queue.push(() => {
704
- state.active += 1;
705
- resolve();
706
- });
707
- });
708
- }
709
- release(state) {
710
- state.active -= 1;
711
- const next = state.queue.shift();
712
- if (next) next();
713
- }
714
- };
715
- var rateGate = new OriginRateGate();
716
-
717
- // src/providers/ark.ts
718
- var DigestMismatchError = class extends Error {
719
- constructor(message) {
720
- super(message);
721
- this.name = "DigestMismatchError";
722
- }
723
- };
724
- var SettlementEventType = /* @__PURE__ */ ((SettlementEventType2) => {
725
- SettlementEventType2["BatchStarted"] = "batch_started";
726
- SettlementEventType2["BatchFinalization"] = "batch_finalization";
727
- SettlementEventType2["BatchFinalized"] = "batch_finalized";
728
- SettlementEventType2["BatchFailed"] = "batch_failed";
729
- SettlementEventType2["TreeSigningStarted"] = "tree_signing_started";
730
- SettlementEventType2["TreeNonces"] = "tree_nonces";
731
- SettlementEventType2["TreeTx"] = "tree_tx";
732
- SettlementEventType2["TreeSignature"] = "tree_signature";
733
- SettlementEventType2["StreamStarted"] = "stream_started";
734
- return SettlementEventType2;
735
- })(SettlementEventType || {});
736
- var RestArkProvider = class {
737
- constructor(serverUrl = DEFAULT_ARKADE_SERVER_URL) {
738
- this.serverUrl = serverUrl;
739
- }
740
- serverUrl;
741
- /**
742
- * Last server-info digest seen (from {@link getInfo}). Sent as `X-Digest`
743
- * on outgoing requests so arkd can reject a client whose cached info is
744
- * stale. Empty until the first {@link getInfo}.
745
- */
746
- _digest = "";
747
- _serverInfoListeners = /* @__PURE__ */ new Set();
748
- /**
749
- * Subscribe to server-info changes. Fired when a request is rejected with
750
- * `DIGEST_MISMATCH` and fresh info is re-fetched, so consumers (the wallet)
751
- * can re-derive signer-dependent state mid-session without polling. Returns
752
- * an unsubscribe function.
753
- */
754
- onServerInfoChanged(listener) {
755
- this._serverInfoListeners.add(listener);
756
- return () => {
757
- this._serverInfoListeners.delete(listener);
758
- };
759
- }
760
- emitServerInfoChanged(info) {
761
- for (const listener of this._serverInfoListeners) {
762
- try {
763
- listener(info);
764
- } catch (e) {
765
- console.warn("onServerInfoChanged listener threw", e);
766
- }
767
- }
768
- }
769
- /**
770
- * `fetch` wrapper for arkd requests that participates in server-info digest
771
- * negotiation. Sends the cached `X-Digest`; when arkd rejects a request with
772
- * `DIGEST_MISMATCH`, refreshes {@link getInfo} (updating the digest), fires
773
- * {@link onServerInfoChanged}, and THROWS {@link DigestMismatchError} — it
774
- * never silently retries, since the in-flight request was built against the
775
- * now-stale config. Dormant until arkd returns the error — then it is the
776
- * instant, event-driven signer-rotation trigger. {@link getInfo} itself never
777
- * routes through here: it is the refresh path and must not be digest-gated.
778
- */
779
- async authedFetch(url, init) {
780
- const digest = this._digest;
781
- const headers = {
782
- ...init.headers
783
- };
784
- if (digest) headers["X-Digest"] = digest;
785
- let response;
786
- try {
787
- response = await fetch(url, { ...init, headers });
788
- } catch (err) {
789
- throw toProviderUnavailable(err, "arkade");
790
- }
791
- if (response.ok) return response;
792
- if (response.status === 429) {
793
- rateGate.reportRateLimited(url, response.headers?.get("retry-after"));
794
- }
795
- let body;
796
- try {
797
- body = await response.clone().text();
798
- } catch (e) {
799
- console.warn("authedFetch could not read response body for digest check", e);
800
- throwIfHttpUnavailable(response, "arkade");
801
- return response;
802
- }
803
- const arkError = maybeArkError(new Error(body));
804
- if (!arkError) throwIfHttpUnavailable(response, "arkade");
805
- if (!isArkError(arkError, ArkErrorName.DIGEST_MISMATCH)) return response;
806
- this._digest = "";
807
- const info = await this.getInfo();
808
- this.emitServerInfoChanged(info);
809
- throw new DigestMismatchError(
810
- "Arkade server reported a configuration digest mismatch; server info was refreshed. Rebuild and retry the request under the new server info."
811
- );
812
- }
813
- async getInfo() {
814
- const url = `${this.serverUrl}/v1/info`;
815
- const response = await rateGate.runHttp(url, () => fetch(url));
816
- if (!response.ok) {
817
- const errorText = await response.text();
818
- throwIfHttpUnavailable(response, "arkade", errorText);
819
- handleError(errorText, `Failed to get server info: ${response.statusText}`);
820
- }
821
- const fromServer = await response.json();
822
- const info = {
823
- boardingExitDelay: BigInt(fromServer.boardingExitDelay ?? 0),
824
- checkpointTapscript: fromServer.checkpointTapscript ?? "",
825
- deprecatedSigners: fromServer.deprecatedSigners?.map((signer) => ({
826
- // arkd advertises `cutoffDate` as a non-nullable field, so it
827
- // is always a bigint here — `0n` is the sentinel for "no
828
- // cutoff" (the classifier maps it to DUE_NOW). The grpc-gateway
829
- // marshals with EmitUnpopulated, so an unset `cutoff_date`
830
- // already arrives as `"0"`; a genuinely missing field defaults
831
- // to `0n` too. Never collapse to `undefined`.
832
- cutoffDate: BigInt(signer.cutoffDate ?? 0),
833
- pubkey: signer.pubkey ?? ""
834
- })) ?? [],
835
- digest: fromServer.digest ?? "",
836
- dust: BigInt(fromServer.dust ?? 0),
837
- fees: {
838
- intentFee: fromServer.fees?.intentFee ?? {},
839
- txFeeRate: fromServer?.fees?.txFeeRate ?? ""
840
- },
841
- forfeitAddress: fromServer.forfeitAddress ?? "",
842
- forfeitPubkey: fromServer.forfeitPubkey ?? "",
843
- network: fromServer.network ?? "",
844
- scheduledSession: "scheduledSession" in fromServer && fromServer.scheduledSession != null ? {
845
- duration: BigInt(fromServer.scheduledSession.duration ?? 0),
846
- nextStartTime: BigInt(fromServer.scheduledSession.nextStartTime ?? 0),
847
- nextEndTime: BigInt(fromServer.scheduledSession.nextEndTime ?? 0),
848
- period: BigInt(fromServer.scheduledSession.period ?? 0),
849
- fees: fromServer.scheduledSession.fees ?? {}
850
- } : void 0,
851
- serviceStatus: fromServer.serviceStatus ?? {},
852
- sessionDuration: BigInt(fromServer.sessionDuration ?? 0),
853
- signerPubkey: fromServer.signerPubkey ?? "",
854
- unilateralExitDelay: BigInt(fromServer.unilateralExitDelay ?? 0),
855
- utxoMaxAmount: BigInt(fromServer.utxoMaxAmount ?? -1),
856
- utxoMinAmount: BigInt(fromServer.utxoMinAmount ?? 0),
857
- version: fromServer.version ?? "",
858
- vtxoMaxAmount: BigInt(fromServer.vtxoMaxAmount ?? -1),
859
- vtxoMinAmount: BigInt(fromServer.vtxoMinAmount ?? 0)
860
- };
861
- this._digest = info.digest;
862
- return info;
863
- }
864
- async submitTx(signedArkTx, checkpointTxs) {
865
- const url = `${this.serverUrl}/v1/tx/submit`;
866
- const response = await this.authedFetch(url, {
867
- method: "POST",
868
- headers: {
869
- "Content-Type": "application/json"
870
- },
871
- body: JSON.stringify({
872
- signedArkTx,
873
- checkpointTxs
874
- })
875
- });
876
- if (!response.ok) {
877
- const errorText = await response.text();
878
- handleError(errorText, `Failed to submit virtual transaction: ${errorText}`);
879
- }
880
- const data = await response.json();
881
- return {
882
- arkTxid: data.arkTxid,
883
- finalArkTx: data.finalArkTx,
884
- signedCheckpointTxs: data.signedCheckpointTxs
885
- };
886
- }
887
- async finalizeTx(arkTxid, finalCheckpointTxs) {
888
- const url = `${this.serverUrl}/v1/tx/finalize`;
889
- const response = await this.authedFetch(url, {
890
- method: "POST",
891
- headers: {
892
- "Content-Type": "application/json"
893
- },
894
- body: JSON.stringify({
895
- arkTxid,
896
- finalCheckpointTxs
897
- })
898
- });
899
- if (!response.ok) {
900
- const errorText = await response.text();
901
- handleError(errorText, `Failed to finalize offchain transaction: ${errorText}`);
902
- }
903
- }
904
- async registerIntent(intent) {
905
- const url = `${this.serverUrl}/v1/batch/registerIntent`;
906
- const response = await this.authedFetch(url, {
907
- method: "POST",
908
- headers: {
909
- "Content-Type": "application/json"
910
- },
911
- body: JSON.stringify({
912
- intent: {
913
- proof: intent.proof,
914
- message: Intent.encodeMessage(intent.message)
915
- }
916
- })
917
- });
918
- if (!response.ok) {
919
- const errorText = await response.text();
920
- handleError(errorText, `Failed to register intent: ${errorText}`);
921
- }
922
- const data = await response.json();
923
- return data.intentId;
924
- }
925
- async deleteIntent(intent) {
926
- const url = `${this.serverUrl}/v1/batch/deleteIntent`;
927
- const response = await this.authedFetch(url, {
928
- method: "POST",
929
- headers: {
930
- "Content-Type": "application/json"
931
- },
932
- body: JSON.stringify({
933
- intent: {
934
- proof: intent.proof,
935
- message: Intent.encodeMessage(intent.message)
936
- }
937
- })
938
- });
939
- if (!response.ok) {
940
- const errorText = await response.text();
941
- handleError(errorText, `Failed to delete intent: ${errorText}`);
942
- }
943
- }
944
- async confirmRegistration(intentId) {
945
- const url = `${this.serverUrl}/v1/batch/ack`;
946
- const response = await this.authedFetch(url, {
947
- method: "POST",
948
- headers: {
949
- "Content-Type": "application/json"
950
- },
951
- body: JSON.stringify({
952
- intentId
953
- })
954
- });
955
- if (!response.ok) {
956
- const errorText = await response.text();
957
- handleError(errorText, `Failed to confirm registration: ${errorText}`);
958
- }
959
- }
960
- async submitTreeNonces(batchId, pubkey, nonces) {
961
- const url = `${this.serverUrl}/v1/batch/tree/submitNonces`;
962
- const response = await this.authedFetch(url, {
963
- method: "POST",
964
- headers: {
965
- "Content-Type": "application/json"
966
- },
967
- body: JSON.stringify({
968
- batchId,
969
- pubkey,
970
- treeNonces: encodeMusig2Nonces(nonces)
971
- })
972
- });
973
- if (!response.ok) {
974
- const errorText = await response.text();
975
- handleError(errorText, `Failed to submit tree nonces: ${errorText}`);
976
- }
977
- }
978
- async submitTreeSignatures(batchId, pubkey, signatures) {
979
- const url = `${this.serverUrl}/v1/batch/tree/submitSignatures`;
980
- const response = await this.authedFetch(url, {
981
- method: "POST",
982
- headers: {
983
- "Content-Type": "application/json"
984
- },
985
- body: JSON.stringify({
986
- batchId,
987
- pubkey,
988
- treeSignatures: encodeMusig2Signatures(signatures)
989
- })
990
- });
991
- if (!response.ok) {
992
- const errorText = await response.text();
993
- handleError(errorText, `Failed to submit tree signatures: ${errorText}`);
994
- }
995
- }
996
- async submitSignedForfeitTxs(signedForfeitTxs, signedCommitmentTx) {
997
- const url = `${this.serverUrl}/v1/batch/submitForfeitTxs`;
998
- const response = await this.authedFetch(url, {
999
- method: "POST",
1000
- headers: {
1001
- "Content-Type": "application/json"
1002
- },
1003
- body: JSON.stringify({
1004
- signedForfeitTxs,
1005
- signedCommitmentTx
1006
- })
1007
- });
1008
- if (!response.ok) {
1009
- const errorText = await response.text();
1010
- handleError(errorText, `Failed to submit forfeit transactions: ${response.statusText}`);
1011
- }
1012
- }
1013
- getEventStream(signal, topics) {
1014
- const url = `${this.serverUrl}/v1/batch/events`;
1015
- const queryParams = topics.length > 0 ? `?${topics.map((topic) => `topics=${encodeURIComponent(topic)}`).join("&")}` : "";
1016
- let iterator = null;
1017
- const closeIterator = () => iterator?.close();
1018
- const self = this;
1019
- const gen = (async function* () {
1020
- const abortHandler = closeIterator;
1021
- signal?.addEventListener("abort", abortHandler);
1022
- try {
1023
- while (!signal?.aborted) {
1024
- const currentIterator = eventSourceIterator(new EventSource(url + queryParams));
1025
- iterator = currentIterator;
1026
- try {
1027
- for await (const event of currentIterator) {
1028
- if (signal?.aborted) break;
1029
- try {
1030
- const data = JSON.parse(event.data);
1031
- const settlementEvent = self.parseSettlementEvent(data);
1032
- if (settlementEvent) {
1033
- yield settlementEvent;
1034
- }
1035
- } catch (err) {
1036
- console.error("Failed to parse event:", err);
1037
- throw err;
1038
- }
1039
- }
1040
- } catch (error) {
1041
- if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
1042
- break;
1043
- }
1044
- if (isFetchTimeoutError(error)) {
1045
- console.debug("Timeout error ignored");
1046
- continue;
1047
- }
1048
- if (isEventSourceError(error)) {
1049
- throw error;
1050
- }
1051
- console.error("Event stream error:", error);
1052
- throw error;
1053
- } finally {
1054
- currentIterator.close();
1055
- iterator = null;
1056
- }
1057
- }
1058
- } finally {
1059
- signal?.removeEventListener("abort", abortHandler);
1060
- closeIterator();
1061
- }
1062
- })();
1063
- const origReturn = gen.return.bind(gen);
1064
- gen.return = (value) => {
1065
- closeIterator();
1066
- return origReturn(value);
1067
- };
1068
- return gen;
1069
- }
1070
- getTransactionsStream(signal) {
1071
- const url = `${this.serverUrl}/v1/txs`;
1072
- let iterator = null;
1073
- const closeIterator = () => iterator?.close();
1074
- const self = this;
1075
- const gen = (async function* () {
1076
- const abortHandler = closeIterator;
1077
- signal?.addEventListener("abort", abortHandler);
1078
- try {
1079
- while (!signal?.aborted) {
1080
- try {
1081
- const currentIterator = eventSourceIterator(new EventSource(url));
1082
- iterator = currentIterator;
1083
- for await (const event of currentIterator) {
1084
- if (signal?.aborted) break;
1085
- try {
1086
- const data = JSON.parse(event.data);
1087
- const txNotification = self.parseTransactionNotification(data);
1088
- if (txNotification) {
1089
- yield txNotification;
1090
- }
1091
- } catch (err) {
1092
- console.error("Failed to parse transaction notification:", err);
1093
- throw err;
1094
- }
1095
- }
1096
- } catch (error) {
1097
- if (signal?.aborted || error instanceof Error && error.name === "AbortError") {
1098
- break;
1099
- }
1100
- if (isFetchTimeoutError(error)) {
1101
- console.debug("Timeout error ignored");
1102
- continue;
1103
- }
1104
- if (isEventSourceError(error)) {
1105
- throw error;
1106
- }
1107
- console.error("Transaction stream error:", error);
1108
- throw error;
1109
- } finally {
1110
- closeIterator();
1111
- iterator = null;
1112
- }
1113
- }
1114
- } finally {
1115
- signal?.removeEventListener("abort", abortHandler);
1116
- closeIterator();
1117
- }
1118
- })();
1119
- const origReturn = gen.return.bind(gen);
1120
- gen.return = (value) => {
1121
- closeIterator();
1122
- return origReturn(value);
1123
- };
1124
- return gen;
1125
- }
1126
- async getPendingTxs(intent) {
1127
- const url = `${this.serverUrl}/v1/tx/pending`;
1128
- const response = await this.authedFetch(url, {
1129
- method: "POST",
1130
- headers: {
1131
- "Content-Type": "application/json"
1132
- },
1133
- body: JSON.stringify({
1134
- intent: {
1135
- proof: intent.proof,
1136
- message: Intent.encodeMessage(intent.message)
1137
- }
1138
- })
1139
- });
1140
- if (!response.ok) {
1141
- const errorText = await response.text();
1142
- handleError(errorText, `Failed to get pending transactions: ${errorText}`);
1143
- }
1144
- const data = await response.json();
1145
- return data.pendingTxs;
1146
- }
1147
- parseSettlementEvent(data) {
1148
- if (data.batchStarted) {
1149
- return {
1150
- type: "batch_started" /* BatchStarted */,
1151
- id: data.batchStarted.id,
1152
- intentIdHashes: data.batchStarted.intentIdHashes,
1153
- batchExpiry: BigInt(data.batchStarted.batchExpiry)
1154
- };
1155
- }
1156
- if (data.batchFinalization) {
1157
- return {
1158
- type: "batch_finalization" /* BatchFinalization */,
1159
- id: data.batchFinalization.id,
1160
- commitmentTx: data.batchFinalization.commitmentTx
1161
- };
1162
- }
1163
- if (data.batchFinalized) {
1164
- return {
1165
- type: "batch_finalized" /* BatchFinalized */,
1166
- id: data.batchFinalized.id,
1167
- commitmentTxid: data.batchFinalized.commitmentTxid
1168
- };
1169
- }
1170
- if (data.batchFailed) {
1171
- return {
1172
- type: "batch_failed" /* BatchFailed */,
1173
- id: data.batchFailed.id,
1174
- reason: data.batchFailed.reason
1175
- };
1176
- }
1177
- if (data.treeSigningStarted) {
1178
- return {
1179
- type: "tree_signing_started" /* TreeSigningStarted */,
1180
- id: data.treeSigningStarted.id,
1181
- cosignersPublicKeys: data.treeSigningStarted.cosignersPubkeys,
1182
- unsignedCommitmentTx: data.treeSigningStarted.unsignedCommitmentTx
1183
- };
1184
- }
1185
- if (data.treeNoncesAggregated) {
1186
- return null;
1187
- }
1188
- if (data.treeNonces) {
1189
- return {
1190
- type: "tree_nonces" /* TreeNonces */,
1191
- id: data.treeNonces.id,
1192
- topic: data.treeNonces.topic,
1193
- txid: data.treeNonces.txid,
1194
- nonces: decodeMusig2Nonces(data.treeNonces.nonces)
1195
- // pubkey -> public nonce
1196
- };
1197
- }
1198
- if (data.treeTx) {
1199
- const children = Object.fromEntries(
1200
- Object.entries(data.treeTx.children).map(([outputIndex, txid]) => {
1201
- return [parseInt(outputIndex), txid];
1202
- })
1203
- );
1204
- return {
1205
- type: "tree_tx" /* TreeTx */,
1206
- id: data.treeTx.id,
1207
- topic: data.treeTx.topic,
1208
- batchIndex: data.treeTx.batchIndex,
1209
- chunk: {
1210
- txid: data.treeTx.txid,
1211
- tx: data.treeTx.tx,
1212
- children
1213
- }
1214
- };
1215
- }
1216
- if (data.treeSignature) {
1217
- return {
1218
- type: "tree_signature" /* TreeSignature */,
1219
- id: data.treeSignature.id,
1220
- topic: data.treeSignature.topic,
1221
- batchIndex: data.treeSignature.batchIndex,
1222
- txid: data.treeSignature.txid,
1223
- signature: data.treeSignature.signature
1224
- };
1225
- }
1226
- if (data.streamStarted) {
1227
- return {
1228
- type: "stream_started" /* StreamStarted */,
1229
- id: data.streamStarted.id
1230
- };
1231
- }
1232
- if (data.heartbeat) {
1233
- return null;
1234
- }
1235
- console.warn("Unknown event type:", data);
1236
- return null;
1237
- }
1238
- parseTransactionNotification(data) {
1239
- if (data.commitmentTx) {
1240
- return {
1241
- commitmentTx: {
1242
- txid: data.commitmentTx.txid,
1243
- tx: data.commitmentTx.tx,
1244
- spentVtxos: data.commitmentTx.spentVtxos.map(mapVtxo),
1245
- spendableVtxos: data.commitmentTx.spendableVtxos.map(mapVtxo),
1246
- checkpointTxs: data.commitmentTx.checkpointTxs
1247
- }
1248
- };
1249
- }
1250
- if (data.arkTx) {
1251
- return {
1252
- arkTx: {
1253
- txid: data.arkTx.txid,
1254
- tx: data.arkTx.tx,
1255
- spentVtxos: data.arkTx.spentVtxos.map(mapVtxo),
1256
- spendableVtxos: data.arkTx.spendableVtxos.map(mapVtxo),
1257
- checkpointTxs: data.arkTx.checkpointTxs
1258
- }
1259
- };
1260
- }
1261
- if (data.heartbeat) {
1262
- return null;
1263
- }
1264
- console.warn("Unknown transaction notification type:", data);
1265
- return null;
1266
- }
1267
- };
1268
- function encodeMusig2Nonces(nonces) {
1269
- const noncesObject = {};
1270
- for (const [txid, nonce] of nonces) {
1271
- noncesObject[txid] = hex.encode(nonce.pubNonce);
1272
- }
1273
- return noncesObject;
1274
- }
1275
- function encodeMusig2Signatures(signatures) {
1276
- const sigObject = {};
1277
- for (const [txid, sig] of signatures) {
1278
- sigObject[txid] = hex.encode(sig.encode());
1279
- }
1280
- return sigObject;
1281
- }
1282
- function decodeMusig2Nonces(noncesObject) {
1283
- return new Map(
1284
- Object.entries(noncesObject).map(([txid, nonce]) => {
1285
- if (typeof nonce !== "string") {
1286
- throw new Error("invalid nonce");
1287
- }
1288
- return [txid, { pubNonce: hex.decode(nonce) }];
1289
- })
1290
- );
1291
- }
1292
- function isFetchTimeoutError(err) {
1293
- const checkError = (error) => {
1294
- if (!(error instanceof Error)) return false;
1295
- const isCloudflare524 = error.name === "TypeError" && error.message === "Failed to fetch";
1296
- return isCloudflare524 || error.name === "HeadersTimeoutError" || error.name === "BodyTimeoutError" || error.code === "UND_ERR_HEADERS_TIMEOUT" || error.code === "UND_ERR_BODY_TIMEOUT";
1297
- };
1298
- return checkError(err) || checkError(err.cause);
1299
- }
1300
- function mapVtxo(vtxo) {
1301
- return {
1302
- outpoint: {
1303
- txid: vtxo.outpoint.txid,
1304
- vout: vtxo.outpoint.vout
1305
- },
1306
- amount: vtxo.amount,
1307
- script: vtxo.script,
1308
- createdAt: vtxo.createdAt,
1309
- expiresAt: vtxo.expiresAt,
1310
- commitmentTxids: vtxo.commitmentTxids,
1311
- isPreconfirmed: vtxo.isPreconfirmed,
1312
- isSwept: vtxo.isSwept,
1313
- isUnrolled: vtxo.isUnrolled,
1314
- isSpent: vtxo.isSpent,
1315
- spentBy: vtxo.spentBy,
1316
- settledBy: vtxo.settledBy,
1317
- arkTxid: vtxo.arkTxid
1318
- };
1319
- }
1320
- function handleError(errorText, defaultMessage) {
1321
- const error = new Error(errorText);
1322
- const arkError = maybeArkError(error);
1323
- throw arkError ?? new Error(defaultMessage);
1324
- }
1325
-
1326
7
  // src/extension/asset/index.ts
1327
8
  var asset_exports = {};
1328
9
  __export(asset_exports, {
@@ -2603,7 +1284,7 @@ async function indexerFetch(input, init) {
2603
1284
  } catch (err) {
2604
1285
  const mapped = toProviderUnavailable(err, "indexer");
2605
1286
  if (lastAttempt || !(mapped instanceof ProviderUnavailableError)) throw mapped;
2606
- await sleep2(retryDelayMs(attempt));
1287
+ await sleep(retryDelayMs(attempt));
2607
1288
  continue;
2608
1289
  }
2609
1290
  if (res.ok) return res;
@@ -2617,7 +1298,7 @@ async function indexerFetch(input, init) {
2617
1298
  throwIfHttpUnavailable(res, "indexer", body);
2618
1299
  } catch (err) {
2619
1300
  if (lastAttempt) throw err;
2620
- await sleep2(retryDelayMs(attempt));
1301
+ await sleep(retryDelayMs(attempt));
2621
1302
  continue;
2622
1303
  }
2623
1304
  return res;
@@ -2626,7 +1307,7 @@ async function indexerFetch(input, init) {
2626
1307
  function retryDelayMs(attempt) {
2627
1308
  return INDEXER_RETRY_BASE_MS * 2 ** (attempt - 1);
2628
1309
  }
2629
- var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1310
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2630
1311
  var IndexerTxType = /* @__PURE__ */ ((IndexerTxType2) => {
2631
1312
  IndexerTxType2[IndexerTxType2["INDEXER_TX_TYPE_UNSPECIFIED"] = 0] = "INDEXER_TX_TYPE_UNSPECIFIED";
2632
1313
  IndexerTxType2[IndexerTxType2["INDEXER_TX_TYPE_RECEIVED"] = 1] = "INDEXER_TX_TYPE_RECEIVED";
@@ -3101,6 +1782,6 @@ var Response;
3101
1782
  Response2.isGetAssetResponse = isGetAssetResponse;
3102
1783
  })(Response || (Response = {}));
3103
1784
 
3104
- export { ArkError, ArkErrorName, ArkPsbtFieldKey, ArkPsbtFieldKeyType, AssetGroup, AssetId, AssetInput, AssetOutput, AssetRef, BufferReader, BufferWriter, ChainTxType, ConditionWitness, CosignerPublicKey, DigestMismatchError, FetchError, IndexerTxType, Intent, Metadata, OP_RETURN_EMPTY_PKSCRIPT, Packet, PrevArkTxField, PrevoutTxField, ProviderUnavailableError, RestArkProvider, RestIndexerProvider, SettlementEventType, Transaction, VtxoTaprootTree, VtxoTreeExpiry, asset_exports, baseFetch, buildVersion, craftToSpendTx, fetch, getArkPsbtFields, isArkError, isEventSourceError, isFetchTimeoutError, maybeArkError, rateGate, sdkVersion, setArkPsbtField };
3105
- //# sourceMappingURL=chunk-LHYNNDY6.js.map
3106
- //# sourceMappingURL=chunk-LHYNNDY6.js.map
1785
+ export { AssetGroup, AssetId, AssetInput, AssetOutput, AssetRef, BufferReader, BufferWriter, ChainTxType, IndexerTxType, Metadata, Packet, RestIndexerProvider, asset_exports };
1786
+ //# sourceMappingURL=chunk-ENWR2F2P.js.map
1787
+ //# sourceMappingURL=chunk-ENWR2F2P.js.map