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