@arkade-os/swap 0.1.0-rc.8 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +45 -10
  2. package/dist/advanced.cjs +6429 -3083
  3. package/dist/advanced.d.cts +325 -282
  4. package/dist/advanced.d.ts +325 -282
  5. package/dist/advanced.js +343 -34
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-FMRAV77W.js +3065 -0
  8. package/dist/{chunk-HV7EIUE2.js → chunk-HRMWBULL.js} +1773 -634
  9. package/dist/chunk-WKJFXXSR.js +3382 -0
  10. package/dist/index.cjs +6868 -3837
  11. package/dist/index.d.cts +71 -243
  12. package/dist/index.d.ts +71 -243
  13. package/dist/index.js +139 -167
  14. package/dist/lockupContract-D7BNjksX.d.ts +148 -0
  15. package/dist/lockupContract-G-9CNRMq.d.cts +148 -0
  16. package/dist/node/index.cjs +61 -10
  17. package/dist/node/index.d.cts +310 -639
  18. package/dist/node/index.d.ts +310 -639
  19. package/dist/node/index.js +65 -10
  20. package/dist/nostr.cjs +428 -49
  21. package/dist/nostr.d.cts +59 -70
  22. package/dist/nostr.d.ts +59 -70
  23. package/dist/nostr.js +268 -36
  24. package/dist/offer-CcJfx5Fj.d.cts +269 -0
  25. package/dist/offer-DdB1M6FZ.d.ts +269 -0
  26. package/dist/offerFillPlan-BII0PW92.d.cts +1642 -0
  27. package/dist/offerFillPlan-CNTLVD7j.d.ts +1642 -0
  28. package/dist/protocol.cjs +5591 -4064
  29. package/dist/protocol.d.cts +258 -355
  30. package/dist/protocol.d.ts +258 -355
  31. package/dist/protocol.js +209 -228
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-DmPzpbd7.d.ts +2342 -0
  41. package/dist/repository-DqdLVrVv.d.cts +2342 -0
  42. package/dist/rfq-C0tHOvn6.d.cts +983 -0
  43. package/dist/rfq-C0tHOvn6.d.ts +983 -0
  44. package/dist/watch-BonYT9af.d.cts +74 -0
  45. package/dist/watch-CmJQDtsy.d.ts +74 -0
  46. package/package.json +12 -12
  47. package/dist/chunk-4PATNGYQ.js +0 -3297
  48. package/dist/chunk-ARYFNDJY.js +0 -1432
  49. package/dist/chunk-U7VWWTL6.js +0 -66
  50. package/dist/errors-CSpOUdCN.d.ts +0 -2216
  51. package/dist/errors-DVn92LQd.d.cts +0 -2216
  52. package/dist/lockupContract-6TYZOBbn.d.ts +0 -490
  53. package/dist/lockupContract-aLCQQiSu.d.cts +0 -490
  54. package/dist/repository-D0gFF_GA.d.cts +0 -3491
  55. package/dist/repository-tDT8p-Nx.d.ts +0 -3491
  56. package/dist/rfq-DhkgiwQ7.d.cts +0 -1126
  57. package/dist/rfq-DhkgiwQ7.d.ts +0 -1126
  58. package/dist/watch-C4cMEeZT.d.cts +0 -96
  59. package/dist/watch-DbWXdpzm.d.ts +0 -96
@@ -1,3297 +0,0 @@
1
- import {
2
- L1_NETWORKS,
3
- ONCHAIN_CLAIM_MARGIN_SECONDS,
4
- RFQ_TERMINAL_STATES,
5
- classifyOnchainHtlc,
6
- l1NetworkFromArk,
7
- lockupContractParams,
8
- onchainHtlcScript,
9
- registerLockupContract
10
- } from "./chunk-ARYFNDJY.js";
11
-
12
- // src/store.ts
13
- import { hex } from "@scure/base";
14
- import { sha256 } from "@noble/hashes/sha2.js";
15
- import { contractPreimage } from "@arkade-os/sdk";
16
- var BTC_ASSET_ID = "btc";
17
- var byNewest = (a, b) => b.createdAt - a.createdAt;
18
- var getAssetSwapsOrThrow = async (repository) => {
19
- return (await repository.getAllSwaps()).filter(
20
- (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
21
- // the payment hash instead — either marks a valid record
22
- (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
23
- ).sort(byNewest);
24
- };
25
- var getAssetSwaps = async (repository) => {
26
- try {
27
- return await getAssetSwapsOrThrow(repository);
28
- } catch {
29
- return [];
30
- }
31
- };
32
- var saveSwapOrThrow = async (repository, swap) => {
33
- try {
34
- await repository.saveSwap(swap);
35
- } catch (error) {
36
- const reason = error instanceof Error ? error.message : String(error);
37
- throw new Error(`failed to save swap ${swap.id}: ${reason}`);
38
- }
39
- };
40
- var addAssetSwap = async (repository, swap) => {
41
- const swaps = await getAssetSwapsOrThrow(repository);
42
- if (swaps.some((s) => s.id === swap.id)) return swaps;
43
- await saveSwapOrThrow(repository, swap);
44
- const at2 = swaps.findIndex((s) => byNewest(swap, s) <= 0);
45
- const merged = [...swaps];
46
- merged.splice(at2 === -1 ? merged.length : at2, 0, swap);
47
- return merged;
48
- };
49
- var updateAssetSwap = async (repository, id, changes) => {
50
- const swaps = (await getAssetSwapsOrThrow(repository)).map(
51
- (s) => s.id === id ? { ...s, ...changes } : s
52
- );
53
- const updated = swaps.find((s) => s.id === id);
54
- if (updated) await saveSwapOrThrow(repository, updated);
55
- return swaps;
56
- };
57
- var updateAssetSwapBestEffort = async (repository, id, changes) => {
58
- try {
59
- return { swaps: await updateAssetSwap(repository, id, changes), persisted: true };
60
- } catch (error) {
61
- console.warn(`[swap] failed to persist update for swap ${id}`, error);
62
- const swaps = (await getAssetSwaps(repository)).map(
63
- (s) => s.id === id ? { ...s, ...changes } : s
64
- );
65
- return { swaps, persisted: false };
66
- }
67
- };
68
- var swapSecretsToRecord = (secrets) => ({
69
- signingDescriptor: secrets.descriptor,
70
- ..."mustPersistPreimage" in secrets && secrets.mustPersistPreimage ? { preimageHex: hex.encode(secrets.preimage) } : {},
71
- ..."preimageSalt" in secrets && secrets.preimageSalt ? { preimageSaltHex: hex.encode(secrets.preimageSalt) } : {}
72
- });
73
- var decodeHex32 = (value, field) => {
74
- const bytes = hex.decode(value);
75
- if (bytes.length !== 32) {
76
- throw new Error(`${field} must be 32 bytes, got ${bytes.length}`);
77
- }
78
- return bytes;
79
- };
80
- var PreimageNotRecoverableError = class extends Error {
81
- constructor(reason, message, options) {
82
- super(message, options);
83
- this.reason = reason;
84
- }
85
- reason;
86
- name = "PreimageNotRecoverableError";
87
- };
88
- var preimageForSwapRecord = async (wallet, record) => {
89
- if (!record.signingDescriptor) {
90
- throw new PreimageNotRecoverableError(
91
- "no-secrets",
92
- "this swap record carries no signing descriptor"
93
- );
94
- }
95
- let stored;
96
- let salt;
97
- try {
98
- stored = record.preimageHex ? decodeHex32(record.preimageHex, "preimageHex") : void 0;
99
- salt = record.preimageSaltHex ? decodeHex32(record.preimageSaltHex, "preimageSaltHex") : void 0;
100
- } catch (cause) {
101
- throw new PreimageNotRecoverableError(
102
- "malformed-record",
103
- `this swap record's secrets projection is unreadable: ${String(cause)}`,
104
- { cause }
105
- );
106
- }
107
- let preimage;
108
- try {
109
- preimage = await contractPreimage(wallet, record.signingDescriptor, { stored, salt });
110
- } catch (cause) {
111
- throw new PreimageNotRecoverableError(
112
- "not-derivable",
113
- `this wallet cannot produce the preimage for ${record.signingDescriptor}`,
114
- { cause }
115
- );
116
- }
117
- if (record.paymentHash && hex.encode(sha256(preimage)) !== record.paymentHash.toLowerCase()) {
118
- throw new PreimageNotRecoverableError(
119
- "hash-mismatch",
120
- "the derived preimage does not match this swap's payment hash: wrong wallet, or a tampered salt"
121
- );
122
- }
123
- return preimage;
124
- };
125
-
126
- // src/offer.ts
127
- import { hex as hex2 } from "@scure/base";
128
- import { concatBytes } from "@scure/btc-signer/utils.js";
129
- import {
130
- ArkAddress,
131
- arkade,
132
- asset,
133
- networkFromArkadeInfo,
134
- resolveEmulatorPubkey,
135
- toXOnlySignerHex
136
- } from "@arkade-os/sdk";
137
-
138
- // src/swap-want-asset.program.json
139
- var swap_want_asset_program_default = {
140
- version: 0,
141
- name: "banco-btc-to-asset",
142
- params: [
143
- { name: "makerWP", type: "pubkey" },
144
- { name: "wantAmount", type: "int" },
145
- { name: "wantAssetTxid", type: "hash" },
146
- { name: "wantAssetGroupIndex", type: "int" },
147
- { name: "server", type: "pubkey" },
148
- { name: "user", type: "pubkey" }
149
- ],
150
- functions: {
151
- fulfill: {
152
- tapscript: { signers: ["$server"] },
153
- arkadeScript: {
154
- asm: [
155
- 0,
156
- "$wantAssetTxid",
157
- "$wantAssetGroupIndex",
158
- "INSPECTOUTASSETLOOKUP",
159
- "VERIFY",
160
- "$wantAmount",
161
- "GREATERTHANOREQUAL",
162
- "VERIFY",
163
- 0,
164
- "INSPECTOUTPUTSCRIPTPUBKEY",
165
- 1,
166
- "EQUALVERIFY",
167
- "$makerWP",
168
- "EQUAL"
169
- ]
170
- }
171
- },
172
- cancel: {
173
- tapscript: { signers: ["$user", "$server"] }
174
- }
175
- }
176
- };
177
-
178
- // src/swap-want-btc.program.json
179
- var swap_want_btc_program_default = {
180
- version: 0,
181
- name: "banco-asset-to-btc",
182
- params: [
183
- { name: "makerWP", type: "pubkey" },
184
- { name: "wantAmount", type: "int" },
185
- { name: "server", type: "pubkey" },
186
- { name: "user", type: "pubkey" }
187
- ],
188
- functions: {
189
- fulfill: {
190
- tapscript: { signers: ["$server"] },
191
- arkadeScript: {
192
- asm: [
193
- 0,
194
- "INSPECTOUTPUTVALUE",
195
- "$wantAmount",
196
- "GREATERTHANOREQUAL",
197
- "VERIFY",
198
- 0,
199
- "INSPECTOUTPUTSCRIPTPUBKEY",
200
- 1,
201
- "EQUALVERIFY",
202
- "$makerWP",
203
- "EQUAL"
204
- ]
205
- }
206
- },
207
- cancel: {
208
- tapscript: { signers: ["$user", "$server"] }
209
- }
210
- }
211
- };
212
-
213
- // src/coverage.ts
214
- var RETIRABLE = ["fulfilled", "cancelled"];
215
- var LOCKUP_RETIRABLE = ["settled", "refunded"];
216
- var issuedAt = /* @__PURE__ */ new Map();
217
- var inFlight = /* @__PURE__ */ new Map();
218
- async function serialize(script, task) {
219
- const previous = inFlight.get(script) ?? Promise.resolve();
220
- const result = previous.then(task, task);
221
- const settled = result.then(
222
- () => {
223
- },
224
- () => {
225
- }
226
- );
227
- inFlight.set(script, settled);
228
- void settled.then(() => {
229
- if (inFlight.get(script) === settled) inFlight.delete(script);
230
- });
231
- return result;
232
- }
233
- function addressOutstanding(swaps, script) {
234
- const issued = issuedAt.get(script);
235
- if (issued === void 0) return false;
236
- if (swaps.some((s) => s.swapPkScript === script && s.createdAt >= issued)) {
237
- issuedAt.delete(script);
238
- return false;
239
- }
240
- return true;
241
- }
242
- async function promoteOfferContract(manager, script, issued = Date.now()) {
243
- await serialize(script, async () => {
244
- await manager.setContractWatchState(script, "watched");
245
- issuedAt.set(script, issued);
246
- });
247
- }
248
- async function retireOfferContract(manager, swaps, script) {
249
- await serialize(script, async () => {
250
- if (swaps.some((s) => s.swapPkScript === script && !RETIRABLE.includes(s.status))) return;
251
- if (addressOutstanding(swaps, script)) return;
252
- try {
253
- await manager.setContractWatchState(script, "retained");
254
- } catch (err) {
255
- console.warn(`[swap] could not retire offer contract ${script}`, err);
256
- }
257
- });
258
- }
259
- async function retireSettledOfferContracts(manager, swaps) {
260
- const settled = new Set(
261
- swaps.filter((s) => RETIRABLE.includes(s.status)).map((s) => s.swapPkScript)
262
- );
263
- for (const script of settled) await retireOfferContract(manager, swaps, script);
264
- }
265
-
266
- // src/offer.ts
267
- var swapPrograms = {
268
- wantAsset: arkade.parseArtifact(swap_want_asset_program_default),
269
- wantBtc: arkade.parseArtifact(swap_want_btc_program_default)
270
- };
271
- function withExitClosure(program, exit) {
272
- if (!exit) return program;
273
- return {
274
- ...program,
275
- // typed params are authoritative: an undeclared `$exitDelay` fails
276
- // validateProgram instead of compiling against an unbound value
277
- params: [...program.params ?? [], { name: "exitDelay", type: "int" }],
278
- functions: {
279
- ...program.functions,
280
- exit: {
281
- tapscript: { signers: ["$user"], csv: { type: exit.type, value: "$exitDelay" } }
282
- }
283
- }
284
- };
285
- }
286
- function swapProgramBinding(offer, operatorPubkey) {
287
- if (offer.makerPkScript.length !== FIELDS.makerPkScript.width) {
288
- throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
289
- }
290
- return {
291
- program: withExitClosure(
292
- offer.wantAsset ? swapPrograms.wantAsset : swapPrograms.wantBtc,
293
- offer.exitDelay
294
- ),
295
- args: {
296
- makerWP: offer.makerPkScript.subarray(2),
297
- wantAmount: offer.wantAmount,
298
- server: operatorPubkey,
299
- user: offer.makerPublicKey,
300
- // internal byte order
301
- ...offer.wantAsset && {
302
- wantAssetTxid: offer.wantAsset.txid.slice().reverse(),
303
- wantAssetGroupIndex: offer.wantAsset.groupIndex
304
- },
305
- ...offer.exitDelay && { exitDelay: offer.exitDelay.value }
306
- },
307
- keys: {
308
- serverKey: operatorPubkey,
309
- userKey: offer.makerPublicKey,
310
- emulatorKey: offer.emulatorPubkey
311
- }
312
- };
313
- }
314
- function offerContract(offer, operatorPubkey) {
315
- const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
316
- return new arkade.ArkadeProgramScript(program, args, keys);
317
- }
318
- var OFFER_PACKET_TYPE = 3;
319
- var FIELDS = {
320
- swapPkScript: { tag: 1, width: 34 },
321
- wantAmount: { tag: 2, width: 8 },
322
- wantAsset: { tag: 3, width: void 0 },
323
- makerPkScript: { tag: 5, width: 34 },
324
- makerPublicKey: { tag: 7, width: 32 },
325
- emulatorPubkey: { tag: 8, width: 32 },
326
- ratioNum: { tag: 9, width: 8 },
327
- ratioDen: { tag: 10, width: 8 },
328
- offerAsset: { tag: 11, width: void 0 },
329
- exitTimelock: { tag: 12, width: 9 }
330
- };
331
- var EXIT_TYPES = ["blocks", "seconds"];
332
- var NAMES = Object.fromEntries(Object.entries(FIELDS).map(([k, f]) => [f.tag, k]));
333
- function u64(name, value) {
334
- if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
335
- throw new Error(`${name} does not fit the offer wire format (u64)`);
336
- }
337
- const out = new Uint8Array(FIELDS.wantAmount.width);
338
- new DataView(out.buffer).setBigUint64(0, value, false);
339
- return out;
340
- }
341
- var readU64 = (value) => new DataView(value.buffer, value.byteOffset).getBigUint64(0, false);
342
- var setRatio = (name, value) => {
343
- if (value === void 0 || value === BigInt(0)) return void 0;
344
- if (value < BigInt(0)) throw new Error(`${name} does not fit the offer wire format (u64)`);
345
- return value;
346
- };
347
- function tlv(type, value) {
348
- if (value.length > 65535) throw new Error("TLV value exceeds the u16 length field");
349
- return concatBytes(Uint8Array.of(type, value.length >> 8 & 255, value.length & 255), value);
350
- }
351
- function encodeOffer(offer) {
352
- if (Boolean(offer.wantAsset) === Boolean(offer.offerAsset)) {
353
- throw new Error("offer must carry exactly one of wantAsset or offerAsset");
354
- }
355
- for (const name of [
356
- "swapPkScript",
357
- "makerPkScript",
358
- "makerPublicKey",
359
- "emulatorPubkey"
360
- ]) {
361
- if (offer[name].length !== FIELDS[name].width) {
362
- throw new Error(`${name} must be ${FIELDS[name].width} bytes`);
363
- }
364
- }
365
- const ratioNum = setRatio("ratioNum", offer.ratioNum);
366
- const ratioDen = setRatio("ratioDen", offer.ratioDen);
367
- if (ratioNum === void 0 !== (ratioDen === void 0)) {
368
- throw new Error("offer must carry both ratioNum and ratioDen, or neither");
369
- }
370
- const recs = [
371
- tlv(FIELDS.swapPkScript.tag, offer.swapPkScript),
372
- tlv(FIELDS.wantAmount.tag, u64("wantAmount", offer.wantAmount))
373
- ];
374
- if (offer.wantAsset) recs.push(tlv(FIELDS.wantAsset.tag, offer.wantAsset.serialize()));
375
- if (ratioNum !== void 0) recs.push(tlv(FIELDS.ratioNum.tag, u64("ratioNum", ratioNum)));
376
- if (ratioDen !== void 0) recs.push(tlv(FIELDS.ratioDen.tag, u64("ratioDen", ratioDen)));
377
- if (offer.offerAsset) recs.push(tlv(FIELDS.offerAsset.tag, offer.offerAsset.serialize()));
378
- recs.push(
379
- tlv(FIELDS.makerPkScript.tag, offer.makerPkScript),
380
- tlv(FIELDS.makerPublicKey.tag, offer.makerPublicKey),
381
- tlv(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey)
382
- );
383
- if (offer.exitDelay) recs.push(tlv(FIELDS.exitTimelock.tag, encodeExitDelay(offer.exitDelay)));
384
- return concatBytes(...recs);
385
- }
386
- function encodeExitDelay(exit) {
387
- return concatBytes(
388
- Uint8Array.of(EXIT_TYPES.indexOf(assertExitDelay(exit).type)),
389
- u64("exitDelay", exit.value)
390
- );
391
- }
392
- function assertExitDelay(exit) {
393
- if (EXIT_TYPES.indexOf(exit.type) < 0) {
394
- throw new Error(`unknown exitDelay locktime type: ${exit.type}`);
395
- }
396
- if (exit.value <= BigInt(0)) {
397
- throw new Error("exitDelay must be a positive relative locktime");
398
- }
399
- if (exit.value >> BigInt(32) > BigInt(0)) {
400
- throw new Error("exitDelay does not fit the locktime field (u32)");
401
- }
402
- return exit;
403
- }
404
- function decodeOffer(data) {
405
- const fields = {};
406
- let off = 0;
407
- while (off < data.length) {
408
- if (off + 3 > data.length) throw new Error("truncated TLV header");
409
- const type = data[off];
410
- const length = data[off + 1] << 8 | data[off + 2];
411
- off += 3;
412
- if (off + length > data.length)
413
- throw new Error(`truncated TLV value for type 0x${type.toString(16)}`);
414
- const name = NAMES[type];
415
- if (!name) throw new Error(`unknown TLV type: 0x${type.toString(16)}`);
416
- if (fields[name] !== void 0) throw new Error(`duplicate TLV record: ${name}`);
417
- fields[name] = data.slice(off, off + length);
418
- off += length;
419
- }
420
- for (const name of ["wantAsset", "offerAsset"]) {
421
- if (fields[name]?.length === 0) throw new Error(`missing/invalid ${name}`);
422
- }
423
- for (const [name, value] of Object.entries(fields)) {
424
- const width = FIELDS[name].width;
425
- if (width !== void 0 && value.length !== width) {
426
- throw new Error(`missing/invalid ${name}`);
427
- }
428
- }
429
- const need = (name) => {
430
- const v = fields[name];
431
- const len = FIELDS[name].width;
432
- if (!v || len !== void 0 && v.length !== len)
433
- throw new Error(`missing/invalid ${name}`);
434
- return v;
435
- };
436
- const amount = need("wantAmount");
437
- if (Boolean(fields.wantAsset) === Boolean(fields.offerAsset)) {
438
- throw new Error("offer must carry exactly one of wantAsset or offerAsset");
439
- }
440
- const readRatio = (name) => {
441
- const raw = fields[name];
442
- if (!raw) return void 0;
443
- const value = readU64(raw);
444
- if (value === BigInt(0)) throw new Error(`missing/invalid ${name}`);
445
- return value;
446
- };
447
- const ratioNum = readRatio("ratioNum");
448
- const ratioDen = readRatio("ratioDen");
449
- if (ratioNum === void 0 !== (ratioDen === void 0)) {
450
- throw new Error("offer must carry both ratioNum and ratioDen, or neither");
451
- }
452
- return {
453
- swapPkScript: need("swapPkScript"),
454
- wantAmount: readU64(amount),
455
- ...fields.wantAsset && { wantAsset: asset.AssetId.fromBytes(fields.wantAsset) },
456
- ...fields.offerAsset && { offerAsset: asset.AssetId.fromBytes(fields.offerAsset) },
457
- makerPkScript: need("makerPkScript"),
458
- makerPublicKey: need("makerPublicKey"),
459
- emulatorPubkey: need("emulatorPubkey"),
460
- ...ratioNum !== void 0 && { ratioNum },
461
- ...ratioDen !== void 0 && { ratioDen },
462
- ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) }
463
- };
464
- }
465
- function decodeExitDelay(value) {
466
- const type = EXIT_TYPES[value[0]];
467
- if (!type) throw new Error(`unknown exitDelay locktime type: 0x${value[0].toString(16)}`);
468
- return { type, value: readU64(value.subarray(1)) };
469
- }
470
- var OFFER_CONTRACT_LABEL = "Arkade swap offer";
471
- var OFFER_CONTRACT_KIND = "asset-swap-offer";
472
- async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
473
- const contractManager = await wallet.getContractManager();
474
- const client = await arkade.Arkade.connect({
475
- // Registration derives and persists; it never broadcasts and never
476
- // reads UTXOs, so the only thing the client needs off the server is the
477
- // info the caller already resolved. Handing that back — rather than a
478
- // provider built from a URL — is what lets `createOffer` take just a
479
- // wallet, and spares a second `/v1/info` round-trip.
480
- arkade: { getInfo: async () => info },
481
- identity: wallet.identity,
482
- // without this the row's `address` would be derived against the SDK's
483
- // default network while its script is right — a row that disagrees with
484
- // the address the user is about to fund
485
- network: networkFromArkadeInfo(info),
486
- contractManager
487
- });
488
- await contractManager.createContract(
489
- offerContractParams(client, binding, operatorPubkey, expectedPkScript)
490
- );
491
- await promoteOfferContract(contractManager, hex2.encode(expectedPkScript));
492
- }
493
- function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
494
- const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
495
- const contract = new arkade.ArkadeContract(client, program, args, keys);
496
- if (hex2.encode(contract.pkScript) !== hex2.encode(expectedPkScript)) {
497
- throw new Error("derived covenant does not match the offer's swapPkScript");
498
- }
499
- return {
500
- ...contract.toContractParams(),
501
- label: OFFER_CONTRACT_LABEL,
502
- metadata: { genericallySpendable: false, kind: OFFER_CONTRACT_KIND }
503
- };
504
- }
505
- async function restoreOfferCoverage(wallet, swaps) {
506
- const live = swaps.filter((swap) => !RETIRABLE.includes(swap.status));
507
- if (live.length === 0) return;
508
- const [info, contractManager] = await Promise.all([
509
- wallet.getArkadeInfo({ requireLive: true }),
510
- wallet.getContractManager()
511
- ]);
512
- const operatorPubkey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
513
- const client = await arkade.Arkade.connect({
514
- arkade: { getInfo: async () => info },
515
- identity: wallet.identity,
516
- network: networkFromArkadeInfo(info),
517
- contractManager
518
- });
519
- const seen = /* @__PURE__ */ new Set();
520
- const covenants = [];
521
- for (const swap of live) {
522
- if (seen.has(swap.swapPkScript)) continue;
523
- seen.add(swap.swapPkScript);
524
- try {
525
- const { swapPkScript: _, ...binding } = decodeOffer(hex2.decode(swap.offerHex));
526
- covenants.push({
527
- script: swap.swapPkScript,
528
- issued: swap.createdAt,
529
- params: offerContractParams(
530
- client,
531
- binding,
532
- operatorPubkey,
533
- hex2.decode(swap.swapPkScript)
534
- )
535
- });
536
- } catch (error) {
537
- console.warn(`[swap] could not restore coverage for ${swap.swapPkScript}`, error);
538
- }
539
- }
540
- const params = covenants.map((covenant) => covenant.params);
541
- if (contractManager.createContracts) {
542
- await contractManager.createContracts(params);
543
- } else {
544
- for (const contract of params) await contractManager.createContract(contract);
545
- }
546
- for (const covenant of covenants) {
547
- await promoteOfferContract(contractManager, covenant.script, covenant.issued);
548
- }
549
- }
550
- function serverExitDelay(delay) {
551
- if (typeof delay !== "bigint" || delay <= BigInt(0)) {
552
- throw new Error(
553
- "the server reports no usable unilateralExitDelay; pass `exitDelay` to set the offer's exit closure explicitly, or `noExit: true` to publish without one"
554
- );
555
- }
556
- return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
557
- }
558
- async function createOffer(wallet, params) {
559
- if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
560
- throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
561
- }
562
- const [info, makerAddress, makerPublicKey] = await Promise.all([
563
- // requireLive: this info binds signerPubkey into the covenant — a
564
- // snapshot could derive an address the operator no longer co-signs
565
- // for, so an unreachable operator fails the call instead (fail closed,
566
- // the same behaviour the pre-#734 caller-held provider had)
567
- wallet.getArkadeInfo({ requireLive: true }),
568
- wallet.getAddress(),
569
- wallet.identity.xOnlyPublicKey()
570
- ]);
571
- const operatorPubKey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
572
- const network = networkFromArkadeInfo(info);
573
- const emuKey = hex2.decode(
574
- toXOnlySignerHex(resolveEmulatorPubkey(network, params.emulatorPubkey))
575
- );
576
- const binding = {
577
- wantAmount: params.wantAmount,
578
- wantAsset: params.wantAsset,
579
- offerAsset: params.offerAsset,
580
- makerPkScript: ArkAddress.decode(makerAddress).pkScript,
581
- makerPublicKey,
582
- emulatorPubkey: emuKey,
583
- // checked HERE, before the covenant is derived and registered below:
584
- // deferring it to `encodeOffer` leaves a registered contract behind for
585
- // an offer that then fails to encode. @see assertExitDelay
586
- exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
587
- };
588
- const script = offerContract(binding, operatorPubKey);
589
- const offer = { ...binding, swapPkScript: script.pkScript };
590
- await registerOfferContract(wallet, info, binding, operatorPubKey, script.pkScript);
591
- const payload = encodeOffer(offer);
592
- return {
593
- offerHex: hex2.encode(payload),
594
- extension: { type: OFFER_PACKET_TYPE, payload },
595
- // the contract's .address() builds the address; assembling an ArkAddress
596
- // from tweakedPublicKey here would silently miss any future step it gains
597
- address: script.address(network.hrp, operatorPubKey).encode(),
598
- swapPkScript: script.pkScript
599
- };
600
- }
601
- async function cancelOffer(wallet, offerHex, opts) {
602
- const { repository, fundingTxid, swapAddress } = opts;
603
- const prepared = await prepareOfferCancel(wallet, offerHex, {
604
- ...fundingTxid === void 0 ? {} : { fundingTxid },
605
- ...swapAddress === void 0 ? {} : { swapAddress }
606
- });
607
- const swapId = fundingTxid ?? prepared.vtxo.txid;
608
- const hasLocalRecord = (await getAssetSwapsOrThrow(repository)).some((s) => s.id === swapId);
609
- if (hasLocalRecord) await updateAssetSwap(repository, swapId, { status: "cancelling" });
610
- const txid = await prepared.send();
611
- if (hasLocalRecord) {
612
- const { persisted, swaps } = await updateAssetSwapBestEffort(repository, swapId, {
613
- status: "cancelled",
614
- spentTxid: txid
615
- });
616
- if (persisted) {
617
- const contractManager = await wallet.getContractManager();
618
- await retireOfferContract(
619
- contractManager,
620
- swaps,
621
- hex2.encode(prepared.offer.swapPkScript)
622
- );
623
- }
624
- }
625
- return txid;
626
- }
627
- var OFFER_COVENANT_MISMATCH = "rebuilt covenant does not match the offer's swapPkScript";
628
- var NoSpendableDepositError = class extends Error {
629
- name = "NoSpendableDepositError";
630
- constructor(options) {
631
- super("no spendable VTXO at the swap address", options);
632
- }
633
- };
634
- var OfferCovenantMismatchError = class extends Error {
635
- constructor(swapPkScript, options) {
636
- super(
637
- `${OFFER_COVENANT_MISMATCH} \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt`,
638
- options
639
- );
640
- this.swapPkScript = swapPkScript;
641
- }
642
- swapPkScript;
643
- name = "OfferCovenantMismatchError";
644
- };
645
- async function prepareOfferCancel(wallet, offerHex, opts) {
646
- const { fundingTxid, swapAddress } = opts;
647
- const offer = decodeOffer(hex2.decode(offerHex));
648
- const [contractManager, info, reader, broadcaster] = await Promise.all([
649
- wallet.getContractManager(),
650
- wallet.getArkadeInfo({ requireLive: true }),
651
- wallet.getArkadeReader(),
652
- wallet.getArkadeBroadcaster()
653
- ]);
654
- const client = await arkade.Arkade.connect({
655
- // info the wallet already holds, plus its broadcast pair — the shape
656
- // `ArkadeServerProvider` describes, without a second `/v1/info`
657
- arkade: { getInfo: async () => info, ...broadcaster },
658
- indexer: reader,
659
- identity: wallet.identity,
660
- // registered offers resolve their VTXOs from the contract repository
661
- // instead of a direct indexer query; the indexer above stays as the
662
- // fallback for offers created before registration existed
663
- contractManager
664
- // no `network`, unlike registerOfferContract: the row lookup is by
665
- // script and the payout script comes from wallet.getAddress(), so the
666
- // client's network (which only shapes address derivation) is unused here
667
- });
668
- const operatorPubkey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
669
- const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
670
- let rebuilt;
671
- try {
672
- rebuilt = new arkade.ArkadeProgramScript(program, args, keys);
673
- } catch (cause) {
674
- throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript), { cause });
675
- }
676
- if (hex2.encode(rebuilt.pkScript) !== hex2.encode(offer.swapPkScript)) {
677
- throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript));
678
- }
679
- const contract = new arkade.ArkadeContract(client, program, args, keys);
680
- const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
681
- if (!fundingTxid && vtxos.length > 1) {
682
- throw new Error(
683
- "multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
684
- );
685
- }
686
- const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
687
- if (!vtxo) throw new NoSpendableDepositError();
688
- const makerPkScript = ArkAddress.decode(makerAddress).pkScript;
689
- const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
690
- for (const a of vtxo.assets ?? []) {
691
- cancel.withAsset({
692
- assetId: a.assetId,
693
- inputs: [{ vin: 0, amount: BigInt(a.amount) }],
694
- outputs: [{ vout: 0, amount: BigInt(a.amount) }]
695
- });
696
- }
697
- return {
698
- offer,
699
- vtxo: { txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value },
700
- send: async () => (await cancel.send()).txid
701
- };
702
- }
703
-
704
- // src/rfqCorridor.ts
705
- var RfqCorridorRegistry = class {
706
- handlers = /* @__PURE__ */ new Map();
707
- register(handler) {
708
- if (this.handlers.has(handler.kind)) {
709
- throw new Error(
710
- `RFQ corridor handler for kind '${handler.kind}' is already registered`
711
- );
712
- }
713
- this.handlers.set(handler.kind, handler);
714
- }
715
- /** Takes a bare `string`, deliberately, where {@link RfqCorridorHandler.kind}
716
- * is the manager's union: a lookup key comes off a record a backend handed
717
- * back, and that it typechecks as a `kind` is a claim about the type, not
718
- * about what was stored. Narrowing this would read as a check already made. */
719
- get(kind) {
720
- return this.handlers.get(kind);
721
- }
722
- /**
723
- * The handler for a kind, or a loud failure.
724
- *
725
- * A record whose corridor is not registered cannot be restored, and
726
- * guessing would monitor a swap with no idea how to drive it. Names the
727
- * registered kinds so a missing `register()` call is obvious.
728
- */
729
- getOrThrow(kind) {
730
- const handler = this.get(kind);
731
- if (!handler) {
732
- throw new Error(
733
- `no RFQ corridor handler registered for kind '${kind}'; registered: ${this.registeredKinds().join(", ") || "none"}`
734
- );
735
- }
736
- return handler;
737
- }
738
- has(kind) {
739
- return this.handlers.has(kind);
740
- }
741
- registeredKinds() {
742
- return [...this.handlers.keys()];
743
- }
744
- /** Test seam, mirroring the contract registry's. */
745
- unregister(kind) {
746
- return this.handlers.delete(kind);
747
- }
748
- };
749
- var rfqCorridorHandlers = new RfqCorridorRegistry();
750
-
751
- // src/rfqProfileParts.ts
752
- var rfqSecretsProfile = (secrets, paymentHash) => {
753
- const { signingDescriptor, ...preimage } = swapSecretsToRecord(secrets);
754
- return {
755
- signer: { signingDescriptor },
756
- ...paymentHash ? { hashlock: { paymentHash, ...preimage } } : {}
757
- };
758
- };
759
- var parseHex32 = (value, field) => {
760
- if (typeof value !== "string" || !/^[0-9a-fA-F]{64}$/.test(value)) {
761
- throw new Error(`${field} must be 32 bytes of hex, got ${JSON.stringify(value)}`);
762
- }
763
- return value.toLowerCase();
764
- };
765
- var parseSigner = (value) => {
766
- const signingDescriptor = value?.signingDescriptor;
767
- if (typeof signingDescriptor !== "string" || signingDescriptor.length === 0) {
768
- throw new Error(
769
- `rfq profile.signer carries no signingDescriptor (got ${JSON.stringify(signingDescriptor)})`
770
- );
771
- }
772
- return { signingDescriptor };
773
- };
774
- var parsePayoutAddress = (value, kind) => {
775
- if (typeof value !== "string" || value.length === 0) {
776
- throw new Error(
777
- `this ${kind} record's claim destination is unusable: expected an Arkade address, got ${JSON.stringify(value)}`
778
- );
779
- }
780
- return value;
781
- };
782
- var parseHashlock = (value) => {
783
- const raw = value ?? {};
784
- const hashlock = {
785
- paymentHash: parseHex32(raw.paymentHash, "rfq profile.hashlock.paymentHash")
786
- };
787
- if (raw.preimageHex !== void 0) {
788
- hashlock.preimageHex = parseHex32(raw.preimageHex, "rfq profile.hashlock.preimageHex");
789
- }
790
- if (raw.preimageSaltHex !== void 0) {
791
- hashlock.preimageSaltHex = parseHex32(
792
- raw.preimageSaltHex,
793
- "rfq profile.hashlock.preimageSaltHex"
794
- );
795
- }
796
- return hashlock;
797
- };
798
- var hydrateHashlock = (profile) => {
799
- try {
800
- return { paymentHash: parseHashlock(profile.hashlock).paymentHash };
801
- } catch (cause) {
802
- throw new Error(
803
- `rfq record carries no usable hashlock; it cannot verify a preimage: ${String(cause)}`,
804
- { cause }
805
- );
806
- }
807
- };
808
- var rfqSignerOf = (record) => {
809
- const signer = record.profile.signer;
810
- if (signer === void 0) return void 0;
811
- return parseSigner(signer);
812
- };
813
- var rfqClaimSecretOf = (record) => {
814
- const handler = rfqCorridorHandlers.getOrThrow(record.kind);
815
- if (!handler.claimSecret) return void 0;
816
- try {
817
- const claim = handler.claimSecret(record.profile);
818
- return { ...parseSigner(claim), ...parseHashlock(claim) };
819
- } catch (cause) {
820
- throw new PreimageNotRecoverableError(
821
- "malformed-record",
822
- `this ${record.kind} record's claim secret is unreadable: ${String(cause)}`,
823
- { cause }
824
- );
825
- }
826
- };
827
- var rfqClaimDestinationOf = (record) => {
828
- const handler = rfqCorridorHandlers.getOrThrow(record.kind);
829
- if (!handler.claimDestination) return void 0;
830
- return parsePayoutAddress(handler.claimDestination(record.profile), record.kind);
831
- };
832
-
833
- // src/rfqCorridors.ts
834
- import { hex as hex3 } from "@scure/base";
835
- var LightningSendCorridor = {
836
- kind: "lightning_send",
837
- project: () => ({}),
838
- hydrate: (profile) => hydrateHashlock(profile)
839
- // No `claimSecret`, deliberately: `provisionRefundKey` mints no preimage at
840
- // all, and deriving one off the refund descriptor would fail the payment
841
- // hash check — a `hash-mismatch` on a swap that was never broken.
842
- };
843
- var LightningReceiveCorridor = {
844
- kind: "lightning_receive",
845
- // What the manager holds: the amount gate, and its own claim once it lands.
846
- // `payoutAddress` comes from the request result and never changes, so the
847
- // caller writes it once and this leaves it alone.
848
- project: (swap) => {
849
- const receive = swap;
850
- return {
851
- expectedAmount: receive.expectedAmount,
852
- ...receive.claimTxid ? { claimTxid: receive.claimTxid } : {}
853
- };
854
- },
855
- hydrate(profile) {
856
- if (typeof profile.expectedAmount !== "number" || !Number.isFinite(profile.expectedAmount)) {
857
- throw new Error("lightning_receive record carries no expectedAmount; it cannot claim");
858
- }
859
- return {
860
- ...hydrateHashlock(profile),
861
- expectedAmount: profile.expectedAmount,
862
- ...profile.claimTxid ? { claimTxid: profile.claimTxid } : {}
863
- };
864
- },
865
- // We are the claimant here, so the preimage material on the hashlock is
866
- // ours to use.
867
- claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
868
- // The other half of claiming: where it pays. Written once at request time
869
- // and left alone by `project` above, so this hands back what was stored.
870
- claimDestination: (profile) => profile.payoutAddress,
871
- activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
872
- };
873
- function onchainSendProfile(result) {
874
- return {
875
- claimKey: hex3.encode(result.htlcParams.claimKey),
876
- refundKey: hex3.encode(result.htlcParams.refundKey),
877
- htlcLocktime: result.htlcParams.refundLocktime,
878
- network: result.l1Network,
879
- htlcAddress: result.htlc.address,
880
- minConfirmations: result.minConfirmations,
881
- payoutPkScript: hex3.encode(result.payoutPkScript)
882
- };
883
- }
884
- var OnchainSendCorridor = {
885
- kind: "onchain_send",
886
- // The L1 keys and the network are only in the request result — nothing on
887
- // `OnchainSendSwap` carries them — so the caller writes them once. What the
888
- // manager learns as it drives the swap is the fill and our own claim.
889
- project: (swap) => {
890
- const send = swap;
891
- return {
892
- ...send.funding ? { funding: send.funding } : {},
893
- ...send.claimTxid ? { claimTxid: send.claimTxid } : {}
894
- };
895
- },
896
- hydrate(profile) {
897
- const { paymentHash } = hydrateHashlock(profile);
898
- if (!profile.claimKey || !profile.refundKey) {
899
- throw new Error(
900
- "onchain_send record carries no L1 keys; its HTLC cannot be rebuilt and its refund window would pass unwatched"
901
- );
902
- }
903
- if (!Number.isInteger(profile.minConfirmations) || profile.minConfirmations < 1) {
904
- throw new Error(
905
- `onchain_send record carries no usable minConfirmations (${String(profile.minConfirmations)}); the confirmation gate cannot be checked \u2014 refusing to restore a swap that would claim an unconfirmed fill`
906
- );
907
- }
908
- const htlc = onchainHtlcScript(
909
- {
910
- // From the profile, not the covenant: the lockup commits to
911
- // `hash160(P)`, and the HTLC needs `sha256(P)`. One P
912
- // unlocks both legs, but only one of the two hashes of it
913
- // is recoverable here.
914
- paymentHash,
915
- claimKey: hex3.decode(profile.claimKey),
916
- refundKey: hex3.decode(profile.refundKey),
917
- refundLocktime: profile.htlcLocktime
918
- },
919
- profile.network
920
- );
921
- if (htlc.address !== profile.htlcAddress) {
922
- throw new Error(
923
- `onchain_send record's L1 inputs derive ${htlc.address}, but the fill was expected at ${String(profile.htlcAddress)} \u2014 these are not this swap's`
924
- );
925
- }
926
- return {
927
- paymentHash,
928
- htlc,
929
- minConfirmations: profile.minConfirmations,
930
- // Optional here, required at the write: throwing on an older
931
- // record would strand the refund it is still owed.
932
- ...profile.payoutPkScript ? { payoutPkScript: hex3.decode(profile.payoutPkScript) } : {},
933
- ...profile.funding ? { funding: profile.funding } : {},
934
- ...profile.claimTxid ? { claimTxid: profile.claimTxid } : {}
935
- };
936
- },
937
- // The trader claims the L1 HTLC with P, so this leg's preimage material is
938
- // ours.
939
- claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
940
- // Our own L1 claim only. `funding` is the SOLVER's fill into the HTLC —
941
- // not a transaction of ours, so grouping it would claim a row this wallet
942
- // never made.
943
- activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
944
- };
945
- rfqCorridorHandlers.register(LightningSendCorridor);
946
- rfqCorridorHandlers.register(LightningReceiveCorridor);
947
- rfqCorridorHandlers.register(OnchainSendCorridor);
948
-
949
- // src/client/corridors/lightning.ts
950
- import { invoiceTarget } from "@arkade-os/sdk";
951
- var INVOICE_HRPS = [
952
- ["lnbcrt", ["regtest"]],
953
- ["lntbs", ["signet", "mutinynet"]],
954
- ["lnbc", ["bitcoin"]],
955
- ["lntb", ["testnet"]]
956
- ];
957
- var networksOfInvoiceHrp = (raw) => {
958
- const lower = raw.toLowerCase();
959
- return INVOICE_HRPS.find(([hrp]) => lower.startsWith(hrp))?.[1];
960
- };
961
- var PAYMENT_HASH = /^[0-9a-f]{64}$/;
962
- var LIGHTNING_DRIVE = {
963
- give: {
964
- lockups: [{ covenant: "arkade_lockup", owner: "solver", deadline: "refund_locktime" }],
965
- actions: ["claimLockup"],
966
- seams: ["indexer"]
967
- },
968
- take: {
969
- lockups: [{ covenant: "arkade_lockup", owner: "trader", deadline: "refund_locktime" }],
970
- actions: ["refundArkade"],
971
- seams: ["indexer"]
972
- }
973
- };
974
- var lightningCorridor = Object.assign(
975
- (deps) => ({
976
- corridor: "lightning",
977
- deps,
978
- drive: LIGHTNING_DRIVE,
979
- matches(raw) {
980
- const invoice = invoiceTarget(raw);
981
- if (invoice === void 0) return void 0;
982
- const networks = networksOfInvoiceHrp(invoice);
983
- if (networks === void 0) {
984
- return { refused: "this invoice's network prefix names no network this SDK knows" };
985
- }
986
- if (!networks.includes(deps.networkName)) {
987
- return {
988
- refused: `this is a ${networks.join(" or ")} invoice and the wallet is on ${deps.networkName}`
989
- };
990
- }
991
- let facts;
992
- try {
993
- facts = deps.decode(invoice);
994
- if (!PAYMENT_HASH.test(facts.paymentHash)) {
995
- return { refused: "the decoded invoice carries no usable payment hash" };
996
- }
997
- } catch (error) {
998
- return {
999
- refused: `the invoice did not decode: ${error instanceof Error ? error.message : String(error)}`
1000
- };
1001
- }
1002
- if (!Number.isSafeInteger(facts.expiresAt)) {
1003
- return { refused: "the decoded invoice carries no usable expiry" };
1004
- }
1005
- const now = Math.floor(Date.now() / 1e3);
1006
- if (facts.expiresAt <= now) {
1007
- return { refused: `the invoice expired ${now - facts.expiresAt}s ago` };
1008
- }
1009
- if (!Number.isSafeInteger(facts.amountSats) || facts.amountSats < 0) {
1010
- return { refused: "the decoded invoice carries no usable amount" };
1011
- }
1012
- if (facts.amountSats === 0) {
1013
- return { refused: "the invoice names no amount, and a send route needs one" };
1014
- }
1015
- return {
1016
- claimed: {
1017
- kind: "invoice",
1018
- bolt11: invoice,
1019
- paymentHash: facts.paymentHash,
1020
- amount: BigInt(facts.amountSats),
1021
- expiresAt: facts.expiresAt
1022
- }
1023
- };
1024
- }
1025
- }),
1026
- { target: invoiceTarget }
1027
- );
1028
-
1029
- // src/client/corridors/onchain.ts
1030
- import { BIP21, btcTarget } from "@arkade-os/sdk";
1031
- import * as btc from "@scure/btc-signer";
1032
- var ONCHAIN_DRIVE = {
1033
- take: {
1034
- lockups: [
1035
- { covenant: "arkade_lockup", owner: "trader", deadline: "refund_locktime" },
1036
- { covenant: "onchain_htlc", owner: "solver", deadline: "htlc_refund_locktime" }
1037
- ],
1038
- actions: ["claimOnchain", "refundArkade"],
1039
- seams: ["indexer", "chain"]
1040
- }
1041
- };
1042
- var onchainCorridor = Object.assign(
1043
- (deps) => {
1044
- const l1 = l1NetworkFromArk(deps.networkName);
1045
- return {
1046
- corridor: "onchain",
1047
- deps,
1048
- drive: ONCHAIN_DRIVE,
1049
- matches(raw) {
1050
- const target = btcTarget(raw);
1051
- if (target === void 0) return void 0;
1052
- try {
1053
- btc.Address(L1_NETWORKS[l1]).decode(target);
1054
- } catch {
1055
- return { refused: `this is not a ${l1} address` };
1056
- }
1057
- const amount = BIP21.amountSats(raw);
1058
- return {
1059
- claimed: {
1060
- kind: "address",
1061
- address: target,
1062
- ...amount === void 0 ? {} : { amount: BigInt(amount) }
1063
- }
1064
- };
1065
- }
1066
- };
1067
- },
1068
- { target: btcTarget }
1069
- );
1070
-
1071
- // src/client/outcome.ts
1072
- var CORRIDOR_PASS = {
1073
- lightning_send: LIGHTNING_DRIVE.take,
1074
- lightning_receive: LIGHTNING_DRIVE.give,
1075
- onchain_send: ONCHAIN_DRIVE.take
1076
- };
1077
- var LOCKUP_OWNER = {
1078
- lightning_send: CORRIDOR_PASS.lightning_send.lockups[0].owner,
1079
- lightning_receive: CORRIDOR_PASS.lightning_receive.lockups[0].owner,
1080
- onchain_send: CORRIDOR_PASS.onchain_send.lockups[0].owner
1081
- };
1082
- var readsChain = (kind) => CORRIDOR_PASS[kind].seams.includes("chain");
1083
- var at = (outcome) => () => outcome;
1084
- var CORRIDOR_OUTCOME = {
1085
- trader: {
1086
- pending: at("funded"),
1087
- claimable: at("funded"),
1088
- claimed: at("funded"),
1089
- needs_counterparty: at("needs_recovery"),
1090
- settled: (kind) => kind === "onchain_send" ? "claimed" : "paid",
1091
- refunded: at("refunded"),
1092
- failed: at("failed")
1093
- },
1094
- solver: {
1095
- // The solver has funded nothing yet: the invoice is shown and unpaid,
1096
- // which is what makes this `open` where the trader's side is `funded`.
1097
- pending: at("open"),
1098
- claimable: at("funded"),
1099
- claimed: at("funded"),
1100
- needs_counterparty: at("needs_recovery"),
1101
- // The trader's OWN claim, matched by the hash and not by our txid — so
1102
- // a claim that lands without us still counts.
1103
- settled: at("claimed"),
1104
- // The one inversion this whole module exists for: every non-claim leaf
1105
- // of a receive covenant is the solver's, so a lockup spent by one is
1106
- // the trader's incoming payment never arriving.
1107
- refunded: at("lapsed"),
1108
- failed: at("failed")
1109
- }
1110
- };
1111
- var corridorOutcome = (kind, state) => CORRIDOR_OUTCOME[LOCKUP_OWNER[kind]][state](kind);
1112
- var OFFER_OUTCOME = {
1113
- pending: "open",
1114
- cancelling: "cancelling",
1115
- cancelled: "cancelled",
1116
- fulfilled: "filled",
1117
- // A swept deposit: still the trader's money, at a script no offchain spend
1118
- // can reach until it is recovered into a fresh batch.
1119
- recoverable: "needs_recovery",
1120
- awaiting_fill: "needs_recovery",
1121
- claimable: "needs_recovery",
1122
- claimed: "needs_recovery",
1123
- refunded_l1: "needs_recovery"
1124
- };
1125
- var offerOutcome = (status) => OFFER_OUTCOME[status];
1126
- var recordOutcome = (record) => {
1127
- if (record.fundingTxid === void 0) return "accepted";
1128
- if (record.family === "rfq") return "funding";
1129
- return record.status === void 0 ? "funding" : offerOutcome(record.status);
1130
- };
1131
- var ACTIVITY_TOKEN = {
1132
- accepted: "pending",
1133
- funding: "pending",
1134
- funded: "pending",
1135
- open: "pending",
1136
- // The drive's in-flight states have no user-visible phase distinct from
1137
- // "pending"; `needs_recovery` is different in kind — the swap is BLOCKED —
1138
- // and collapsing it here is the same deliberate choice v1 made, which the
1139
- // opaque-token design permits because apps map tokens themselves.
1140
- needs_recovery: "pending",
1141
- refunding: "pending",
1142
- cancelling: "pending",
1143
- cancelled: "cancelled",
1144
- filled: "settled",
1145
- claimed: "settled",
1146
- paid: "settled",
1147
- refunded: "refunded",
1148
- lapsed: "lost",
1149
- failed: "failed"
1150
- };
1151
-
1152
- // src/refund.ts
1153
- import { base64, hex as hex4 } from "@scure/base";
1154
- import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
1155
- import {
1156
- CSVMultisigTapscript,
1157
- ConditionWitness,
1158
- Transaction,
1159
- assertSubmittedArkTxid,
1160
- buildOffchainTx,
1161
- getArkPsbtFields,
1162
- hasTerminalSpend,
1163
- matchServerCheckpoints
1164
- } from "@arkade-os/sdk";
1165
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1166
- var isRfqTerminal = (state) => RFQ_TERMINAL_STATES.includes(state);
1167
- var RFQ_RESOLVED_STATES = ["settled", "refunded"];
1168
- var isResolved = (state) => RFQ_RESOLVED_STATES.includes(state);
1169
- async function awaitRfqResolution(transport, rfqId, options = {}) {
1170
- const pollMs = options.pollMs ?? 5e3;
1171
- for (; ; ) {
1172
- const status = await transport.status(rfqId);
1173
- if (status && isRfqTerminal(status.state)) return status;
1174
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
1175
- const error = new Error(
1176
- `rfq ${rfqId} did not reach a terminal state before the deadline`
1177
- );
1178
- error.reason = "status_timeout";
1179
- throw error;
1180
- }
1181
- await sleep(pollMs);
1182
- }
1183
- }
1184
- var walletOperator = (wallet) => {
1185
- let broadcaster;
1186
- const broadcasting = () => broadcaster ??= wallet.getArkadeBroadcaster();
1187
- return {
1188
- getInfo: () => wallet.getArkadeInfo({ requireLive: true }),
1189
- submitTx: async (...args) => (await broadcasting()).submitTx(...args),
1190
- finalizeTx: async (...args) => (await broadcasting()).finalizeTx(...args)
1191
- };
1192
- };
1193
- var LockupNeedsRecoveryError = class extends Error {
1194
- name = "LockupNeedsRecoveryError";
1195
- reason = "needs_recovery";
1196
- /** `txid:vout` for each output that must be recovered first. */
1197
- outpoints;
1198
- /**
1199
- * The contract's `refundLocktime`. Recovering before this matures is the
1200
- * hazard described above: `recoverVtxos()` sweeps EVERY recoverable output
1201
- * into one settlement with no CLTV awareness, so an early attempt can fail
1202
- * the whole batch — including unrelated outputs that were otherwise fine.
1203
- *
1204
- * Exposed as a value, not only inside the message, so a caller can skip
1205
- * pre-CLTV recoverable outputs without parsing prose. Seconds-based
1206
- * locktimes mature against the chain tip's timestamp rather than wall
1207
- * clock, so treat this as a floor to wait past, not an exact alarm.
1208
- */
1209
- recoverableAfter;
1210
- constructor(outpoints, recoverableAfter) {
1211
- super(
1212
- `refund refused: ${outpoints.length} lockup output(s) have been swept and can no longer be spent offchain (${outpoints.join(", ")}). Recover them into a fresh batch first \u2014 IVtxoManager.recoverVtxos() does this for a wallet whose contract manager has the lockup registered, once refundLocktime (${recoverableAfter}) has matured \u2014 then retry the refund. Recovering before then can fail the entire settlement, not just these outputs.`
1213
- );
1214
- this.outpoints = outpoints;
1215
- this.recoverableAfter = recoverableAfter;
1216
- }
1217
- };
1218
- async function findLockupVtxos(indexer, swapPkScript) {
1219
- const scripts = [hex4.encode(swapPkScript)];
1220
- const [spendable, recoverable] = await Promise.all([
1221
- indexer.getVtxos({ scripts, spendableOnly: true }),
1222
- indexer.getVtxos({ scripts, recoverableOnly: true })
1223
- ]);
1224
- const seen = /* @__PURE__ */ new Set();
1225
- const out = [];
1226
- for (const [vtxos, isRecoverable] of [
1227
- [spendable.vtxos ?? [], false],
1228
- [recoverable.vtxos ?? [], true]
1229
- ]) {
1230
- for (const vtxo of vtxos) {
1231
- if (vtxo.isUnrolled) continue;
1232
- const key = `${vtxo.txid}:${vtxo.vout}`;
1233
- if (seen.has(key)) continue;
1234
- seen.add(key);
1235
- out.push({
1236
- txid: vtxo.txid,
1237
- vout: vtxo.vout,
1238
- value: Number(vtxo.value),
1239
- recoverable: isRecoverable
1240
- });
1241
- }
1242
- }
1243
- return out;
1244
- }
1245
- var hashesTo = (candidate, paymentHash) => hex4.encode(sha2562(candidate)) === paymentHash;
1246
- var candidateWitnessItems = (tx, inputIndex) => [
1247
- ...getArkPsbtFields(tx, inputIndex, ConditionWitness).flat(),
1248
- ...tx.getInput(inputIndex).finalScriptWitness ?? []
1249
- ];
1250
- async function readLockupFate(indexer, input) {
1251
- const { vtxos } = await indexer.getVtxos({ scripts: [hex4.encode(input.swapPkScript)] });
1252
- const all = vtxos ?? [];
1253
- if (all.length === 0) return { fate: "unknown" };
1254
- const exited = all.filter((vtxo) => vtxo.isUnrolled && !hasTerminalSpend(vtxo));
1255
- if (exited.length > 0) {
1256
- return {
1257
- fate: "exited",
1258
- outpoints: exited.map((vtxo) => ({ txid: vtxo.txid, vout: vtxo.vout }))
1259
- };
1260
- }
1261
- const spentBy = /* @__PURE__ */ new Map();
1262
- let everySpendNamed = true;
1263
- for (const vtxo of all) {
1264
- if (!hasTerminalSpend(vtxo)) return { fate: "open" };
1265
- if (vtxo.spentBy)
1266
- spentBy.set(vtxo.spentBy, {
1267
- checkpointTxid: vtxo.spentBy,
1268
- txid: vtxo.arkTxId
1269
- });
1270
- else everySpendNamed = false;
1271
- }
1272
- const spends = [...spentBy.values()];
1273
- const { txs } = await indexer.getVirtualTxs([...spentBy.keys()]);
1274
- const observed = /* @__PURE__ */ new Set();
1275
- for (const raw of txs) {
1276
- let tx;
1277
- try {
1278
- tx = Transaction.fromPSBT(base64.decode(raw));
1279
- } catch {
1280
- continue;
1281
- }
1282
- if (spentBy.has(tx.id)) observed.add(tx.id);
1283
- for (let i = 0; i < tx.inputsLength; i++) {
1284
- const spent = tx.getInput(i);
1285
- if (!spent.txid) continue;
1286
- const txid = hex4.encode(spent.txid);
1287
- if (!all.some((vtxo) => vtxo.txid === txid && vtxo.vout === spent.index)) continue;
1288
- for (const candidate of candidateWitnessItems(tx, i)) {
1289
- if (hashesTo(candidate, input.paymentHash)) {
1290
- return { fate: "claimed", preimage: candidate, spends };
1291
- }
1292
- }
1293
- }
1294
- }
1295
- return everySpendNamed && observed.size === spentBy.size ? { fate: "returned", spends } : { fate: "unknown" };
1296
- }
1297
- async function pushRefundWithoutReceiver(operator, input) {
1298
- if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
1299
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
1300
- if (swept.length > 0) {
1301
- throw new LockupNeedsRecoveryError(
1302
- swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
1303
- input.contract.options.refundLocktime
1304
- );
1305
- }
1306
- const refundPkScript = input.refundPkScript ?? input.contract.options.nonInteractiveParameters?.senderPkScript;
1307
- if (!refundPkScript) {
1308
- throw new Error(
1309
- "no refund destination: the contract carries no emulator covenant suite, so pass refundPkScript explicitly"
1310
- );
1311
- }
1312
- const info = await operator.getInfo();
1313
- let operatorUnrollScript;
1314
- try {
1315
- operatorUnrollScript = CSVMultisigTapscript.decode(hex4.decode(info.checkpointTapscript));
1316
- } catch {
1317
- throw new Error("invalid checkpointTapscript from the operator");
1318
- }
1319
- const leaf = input.contract.refundWithoutReceiver();
1320
- const tapTree = input.contract.encode();
1321
- const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
1322
- const { arkTx: tx, checkpoints } = buildOffchainTx(
1323
- input.vtxos.map((vtxo) => ({
1324
- txid: vtxo.txid,
1325
- vout: vtxo.vout,
1326
- value: vtxo.value,
1327
- tapLeafScript: leaf,
1328
- tapTree
1329
- })),
1330
- [{ script: refundPkScript, amount: BigInt(amount) }],
1331
- operatorUnrollScript
1332
- );
1333
- const signedTx = await input.sender.sign(tx);
1334
- const submitted = await operator.submitTx(
1335
- base64.encode(signedTx.toPSBT()),
1336
- checkpoints.map((c) => base64.encode(c.toPSBT()))
1337
- );
1338
- assertSubmittedArkTxid(submitted, signedTx, "refundWithoutReceiver");
1339
- const matched = matchServerCheckpoints(
1340
- submitted.signedCheckpointTxs,
1341
- checkpoints,
1342
- "refundWithoutReceiver"
1343
- );
1344
- const finalCheckpoints = await Promise.all(
1345
- matched.map(
1346
- async ({ server }) => base64.encode((await input.sender.sign(server, [0])).toPSBT())
1347
- )
1348
- );
1349
- await operator.finalizeTx(submitted.arkTxid, finalCheckpoints);
1350
- return { txid: submitted.arkTxid, amount };
1351
- }
1352
- var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
1353
- async function refundIfUnresolved(transport, operator, indexer, input) {
1354
- const pollMs = input.pollMs ?? 5e3;
1355
- const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
1356
- const attemptDeadline = input.attemptDeadline ?? input.refundLocktime + REFUND_MTP_LAG_SECONDS;
1357
- for (; ; ) {
1358
- const status = await transport.status(input.rfqId);
1359
- if (status && isResolved(status.state)) return { outcome: "resolved", status };
1360
- if (now() >= input.refundLocktime) {
1361
- let fate = { fate: "unknown" };
1362
- try {
1363
- fate = await readLockupFate(indexer, {
1364
- swapPkScript: input.contract.pkScript,
1365
- paymentHash: input.paymentHash
1366
- });
1367
- } catch {
1368
- }
1369
- if (fate.fate === "exited") {
1370
- return {
1371
- outcome: "exited",
1372
- outpoints: fate.outpoints.map((o) => `${o.txid}:${o.vout}`),
1373
- status
1374
- };
1375
- }
1376
- const vtxos = await findLockupVtxos(indexer, input.contract.pkScript);
1377
- if (vtxos.length === 0) return { outcome: "nothing_to_refund", status };
1378
- try {
1379
- const pushed = await pushRefundWithoutReceiver(operator, {
1380
- contract: input.contract,
1381
- sender: input.sender,
1382
- vtxos,
1383
- refundPkScript: input.refundPkScript
1384
- });
1385
- return { outcome: "refunded", status, ...pushed };
1386
- } catch (error) {
1387
- if (error instanceof LockupNeedsRecoveryError) {
1388
- return {
1389
- outcome: "needs_recovery",
1390
- outpoints: error.outpoints,
1391
- vtxos,
1392
- status
1393
- };
1394
- }
1395
- if (now() >= attemptDeadline) throw error;
1396
- }
1397
- }
1398
- await sleep(pollMs);
1399
- }
1400
- }
1401
-
1402
- // src/markets.ts
1403
- import {
1404
- bestMarket,
1405
- discover,
1406
- isNetwork,
1407
- sideLimits
1408
- } from "@arkade-os/solver-discovery";
1409
- import { isSubdust } from "@arkade-os/sdk";
1410
-
1411
- // src/marketShape.ts
1412
- var assetOf = (market, side) => side === "base" ? market.base_asset : market.quote_asset;
1413
- var marketAssetId = (market, side) => {
1414
- const asset2 = assetOf(market, side);
1415
- if (typeof asset2?.caip19_id === "string") return asset2.caip19_id;
1416
- return typeof asset2?.id === "string" ? asset2.id : void 0;
1417
- };
1418
-
1419
- // src/markets.ts
1420
- var QUOTE_OPTIONS = { safetyBps: 0 };
1421
- var makeCachedFeedFetch = (ttlMs = 3e4, fetchImpl = fetch) => {
1422
- const cache = /* @__PURE__ */ new Map();
1423
- const inflight = /* @__PURE__ */ new Map();
1424
- return async (input, init) => {
1425
- const url = input instanceof Request ? input.url : String(input);
1426
- const hit = cache.get(url);
1427
- if (hit) {
1428
- if (Date.now() - hit.at < ttlMs) return new Response(hit.body);
1429
- cache.delete(url);
1430
- }
1431
- const pending = inflight.get(url);
1432
- if (pending) {
1433
- const body = await pending;
1434
- if (body !== void 0) return new Response(body);
1435
- }
1436
- let settle = () => {
1437
- };
1438
- inflight.set(
1439
- url,
1440
- new Promise((resolve) => {
1441
- settle = resolve;
1442
- })
1443
- );
1444
- try {
1445
- const response = await fetchImpl(input, init);
1446
- let body;
1447
- if (response.ok) {
1448
- try {
1449
- body = await response.clone().text();
1450
- cache.set(url, { at: Date.now(), body });
1451
- } catch {
1452
- body = void 0;
1453
- }
1454
- }
1455
- settle(body);
1456
- return response;
1457
- } catch (err) {
1458
- settle(void 0);
1459
- throw err;
1460
- } finally {
1461
- inflight.delete(url);
1462
- }
1463
- };
1464
- };
1465
- var MARKETS_CACHE_TTL_MS = 60 * 60 * 1e3;
1466
- var isMarketShaped = (m) => {
1467
- const market = m;
1468
- if (!market) return false;
1469
- return typeof market.base_asset?.id === "string" && typeof market.quote_asset?.id === "string" && typeof market.quote_asset.decimals === "number";
1470
- };
1471
- var readMarketsCache = async (repository, network, registry) => {
1472
- try {
1473
- const entry = await repository.getCachedMarkets(network, registry);
1474
- if (!Array.isArray(entry?.markets) || typeof entry?.fetchedAt !== "number")
1475
- return void 0;
1476
- const markets = entry.markets.filter(isMarketShaped);
1477
- if (entry.markets.length > 0 && markets.length === 0) return void 0;
1478
- return { ...entry, markets };
1479
- } catch {
1480
- return void 0;
1481
- }
1482
- };
1483
- var discoverMarkets = async (options) => {
1484
- const {
1485
- network,
1486
- registryUrl: registry,
1487
- repository,
1488
- localCards = [],
1489
- logger,
1490
- fetchImpl,
1491
- useCache = true
1492
- } = options;
1493
- if (!registry || !isNetwork(network)) return [];
1494
- const cached = repository && await readMarketsCache(repository, network, registry);
1495
- if (useCache && cached && Date.now() - cached.fetchedAt < MARKETS_CACHE_TTL_MS)
1496
- return cached.markets;
1497
- const { markets, sources, warnings } = await discover({
1498
- registries: [registry],
1499
- localCards,
1500
- network,
1501
- fetchImpl
1502
- });
1503
- if (warnings.length) logger?.("solver discovery:", ...warnings);
1504
- const reachable = sources.some((source) => source.ok);
1505
- if (!reachable && cached) return cached.markets;
1506
- if (reachable && repository) {
1507
- try {
1508
- await repository.saveCachedMarkets(network, registry, {
1509
- markets,
1510
- fetchedAt: Date.now()
1511
- });
1512
- } catch {
1513
- }
1514
- }
1515
- return markets;
1516
- };
1517
- var findMarket = (markets, fromId, toId) => {
1518
- if (fromId === toId) return void 0;
1519
- const resolveMarketId = (id) => {
1520
- for (const market of markets) {
1521
- for (const side of ["base", "quote"]) {
1522
- const asset2 = side === "base" ? market.base_asset : market.quote_asset;
1523
- if (asset2.id === id) return id;
1524
- const canonical = marketAssetId(market, side) ?? "";
1525
- const matchesBtc = id === BTC_ASSET_ID && /^arkade:[^/]+\/slip44:(?:0|1)$/.test(canonical);
1526
- const matchesAsset = /^[0-9a-f]{68}$/.test(id) && canonical.endsWith(`/asset:${id}`);
1527
- if ((matchesBtc || matchesAsset) && typeof asset2.id === "string") return asset2.id;
1528
- }
1529
- }
1530
- return id;
1531
- };
1532
- const resolvedFrom = resolveMarketId(fromId);
1533
- const resolvedTo = resolveMarketId(toId);
1534
- const givingBase = bestMarket(markets, {
1535
- baseId: resolvedFrom,
1536
- quoteId: resolvedTo,
1537
- wantSide: "quote"
1538
- });
1539
- if (givingBase) return { market: givingBase, give: "base" };
1540
- return {
1541
- market: bestMarket(markets, {
1542
- baseId: resolvedTo,
1543
- quoteId: resolvedFrom,
1544
- wantSide: "base"
1545
- }),
1546
- give: "quote"
1547
- };
1548
- };
1549
- var validatePlan = (plan, giveBalance, dust) => {
1550
- if (plan.deposit.atomic > giveBalance) return "insufficient-balance";
1551
- const { min, max, withinLimits } = plan.limits;
1552
- if (!min || !max) return "side-disabled";
1553
- const giveLimits = sideLimits(plan.market, plan.give);
1554
- if (!giveLimits) return "side-disabled";
1555
- if (plan.deposit.atomic < giveLimits.min) return "below-min";
1556
- if (plan.deposit.atomic > giveLimits.max) return "above-max";
1557
- if (!withinLimits) return plan.receive.atomic < min.atomic ? "below-min" : "above-max";
1558
- const depositIsBtc = plan.deposit.asset.id === BTC_ASSET_ID;
1559
- const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
1560
- if (depositIsBtc || receiveIsBtc) {
1561
- const btcSide = depositIsBtc ? plan.deposit.atomic : plan.receive.atomic;
1562
- if (isSubdust(btcSide, dust)) return "below-dust";
1563
- }
1564
- return void 0;
1565
- };
1566
-
1567
- // src/restore.ts
1568
- import { base64 as base642, hex as hex5 } from "@scure/base";
1569
- import {
1570
- Extension,
1571
- Transaction as Transaction2,
1572
- scriptFromTapLeafScript
1573
- } from "@arkade-os/sdk";
1574
- var TXS_PER_REQUEST = 50;
1575
- async function fetchParsedTxs(indexer, txids) {
1576
- const parsedByTxid = /* @__PURE__ */ new Map();
1577
- if (txids.length === 0) return parsedByTxid;
1578
- const chunks = [];
1579
- for (let i = 0; i < txids.length; i += TXS_PER_REQUEST) {
1580
- chunks.push(txids.slice(i, i + TXS_PER_REQUEST));
1581
- }
1582
- const chunkResults = await Promise.allSettled(
1583
- chunks.map(async (ids) => (await indexer.getVirtualTxs(ids)).txs)
1584
- );
1585
- for (const result of chunkResults) {
1586
- if (result.status !== "fulfilled") continue;
1587
- for (const psbt of result.value) {
1588
- try {
1589
- const parsed = Transaction2.fromPSBT(base642.decode(psbt));
1590
- parsedByTxid.set(parsed.id, parsed);
1591
- } catch {
1592
- }
1593
- }
1594
- }
1595
- return parsedByTxid;
1596
- }
1597
- var unscannedSwapCandidates = (txs, existingIds, scanned) => txs.filter(
1598
- (tx) => tx.type === "sent" && tx.redeemTxid && !existingIds.has(tx.redeemTxid) && !scanned.has(tx.redeemTxid)
1599
- );
1600
- function classifySpend(offer, operatorPubkey, spendTx, deposit) {
1601
- let leaves;
1602
- try {
1603
- const script = offerContract(offer, operatorPubkey);
1604
- if (hex5.encode(script.pkScript) !== hex5.encode(offer.swapPkScript)) return "indeterminate";
1605
- leaves = {
1606
- // both routes that hand the deposit back; `exit` is absent on an
1607
- // offer that carries no exit closure, and drops out here
1608
- returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
1609
- fulfill: script.functionByName("fulfill")?.leafScript
1610
- };
1611
- } catch {
1612
- return "indeterminate";
1613
- }
1614
- for (let i = 0; i < spendTx.inputsLength; i++) {
1615
- const input = spendTx.getInput(i);
1616
- if (!input.txid || input.index !== deposit.vout) continue;
1617
- if (hex5.encode(input.txid) !== deposit.txid) continue;
1618
- for (const leaf of input.tapLeafScript ?? []) {
1619
- const spent = hex5.encode(scriptFromTapLeafScript(leaf));
1620
- if (leaves.returned.some((back) => spent === hex5.encode(back))) return "cancelled";
1621
- if (leaves.fulfill && spent === hex5.encode(leaves.fulfill)) return "fulfilled";
1622
- }
1623
- }
1624
- return "indeterminate";
1625
- }
1626
- var spendTxidsOf = (vtxo) => [vtxo.spentBy, vtxo.arkTxId].filter((id) => Boolean(id));
1627
- function classifyDepositSpend(offer, operatorPubkey, spendTxs, deposit) {
1628
- for (const tx of spendTxs) {
1629
- const kind = classifySpend(offer, operatorPubkey, tx, deposit);
1630
- if (kind !== "indeterminate") return kind;
1631
- }
1632
- return "indeterminate";
1633
- }
1634
- async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1635
- const { operatorPubkey, scanned = /* @__PURE__ */ new Set(), reopen = [] } = opts;
1636
- const reopened = [];
1637
- for (const swap of reopen) {
1638
- try {
1639
- reopened.push({
1640
- fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
1641
- offer: decodeOffer(hex5.decode(swap.offerHex)),
1642
- offerHex: swap.offerHex,
1643
- existing: swap
1644
- });
1645
- } catch {
1646
- }
1647
- }
1648
- const reopenedTxids = new Set(reopened.map(({ fundingTx }) => fundingTx.redeemTxid));
1649
- const candidates = unscannedSwapCandidates(txs, existingIds, scanned).filter(
1650
- ({ redeemTxid }) => !reopenedTxids.has(redeemTxid)
1651
- );
1652
- if (candidates.length === 0 && reopened.length === 0) {
1653
- return { restored: [], scannedTxids: [] };
1654
- }
1655
- const byTxid = new Map(candidates.map((tx) => [tx.redeemTxid, tx]));
1656
- const parsedByTxid = await fetchParsedTxs(
1657
- indexer,
1658
- candidates.map((tx) => tx.redeemTxid)
1659
- );
1660
- const fetchedTxids = [];
1661
- const found = [...reopened];
1662
- for (const [txid, parsed] of parsedByTxid) {
1663
- const fundingTx = byTxid.get(txid);
1664
- if (!fundingTx) continue;
1665
- fetchedTxids.push(txid);
1666
- try {
1667
- const packet = Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
1668
- if (!packet) continue;
1669
- const payload = packet.serialize();
1670
- found.push({
1671
- fundingTx,
1672
- offer: decodeOffer(payload),
1673
- offerHex: hex5.encode(payload)
1674
- });
1675
- } catch {
1676
- }
1677
- }
1678
- if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
1679
- const scripts = [...new Set(found.map((f) => hex5.encode(f.offer.swapPkScript)))];
1680
- const { vtxos } = await indexer.getVtxos({ scripts });
1681
- const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
1682
- const txByAnyId = /* @__PURE__ */ new Map();
1683
- for (const tx of txs) {
1684
- for (const id of [tx.boardingTxid, tx.redeemTxid, tx.roundTxid]) {
1685
- if (id) txByAnyId.set(id, tx);
1686
- }
1687
- }
1688
- const spendTxids = /* @__PURE__ */ new Set();
1689
- for (const { fundingTx, offer } of found) {
1690
- const vtxo = vtxoByScriptAndTxid.get(
1691
- `${hex5.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
1692
- );
1693
- if (!vtxo?.isSpent) continue;
1694
- for (const txid of spendTxidsOf(vtxo)) spendTxids.add(txid);
1695
- }
1696
- const spendTxByTxid = await fetchParsedTxs(indexer, [...spendTxids]);
1697
- const restored = [];
1698
- const unresolved = /* @__PURE__ */ new Set();
1699
- for (const { fundingTx, offer, offerHex, existing } of found) {
1700
- const swapPkScript = hex5.encode(offer.swapPkScript);
1701
- const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
1702
- if (!vtxo) {
1703
- unresolved.add(fundingTx.redeemTxid);
1704
- continue;
1705
- }
1706
- const depositRider = vtxo.assets?.length === 1 && vtxo.assets[0].amount > BigInt(0) ? vtxo.assets[0] : void 0;
1707
- const fromAsset = offer.offerAsset?.toString() ?? depositRider?.assetId ?? BTC_ASSET_ID;
1708
- const toAsset = offer.wantAsset?.toString() ?? BTC_ASSET_ID;
1709
- const depositAmount = fromAsset === BTC_ASSET_ID ? BigInt(vtxo.value) : vtxo.assets?.find((a) => a.assetId === fromAsset)?.amount;
1710
- if (depositAmount === void 0) {
1711
- unresolved.add(fundingTx.redeemTxid);
1712
- continue;
1713
- }
1714
- const fromAmount = depositAmount.toString();
1715
- const spentTxid = vtxo.isSpent ? vtxo.arkTxId || vtxo.spentBy : void 0;
1716
- let status = "pending";
1717
- if (vtxo.isSwept) status = "recoverable";
1718
- else if (vtxo.isSpent) {
1719
- const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
1720
- const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
1721
- txid: vtxo.txid,
1722
- vout: vtxo.vout
1723
- });
1724
- if (kind === "indeterminate") {
1725
- unresolved.add(fundingTx.redeemTxid);
1726
- continue;
1727
- }
1728
- status = kind;
1729
- }
1730
- const completion = status === "fulfilled" && spentTxid && txByAnyId.get(spentTxid)?.createdAt ? { completedAt: txByAnyId.get(spentTxid).createdAt * 1e3 } : {};
1731
- if (existing) {
1732
- if (status === "pending") continue;
1733
- restored.push({ ...existing, status, spentTxid, ...completion });
1734
- continue;
1735
- }
1736
- restored.push({
1737
- id: fundingTx.redeemTxid,
1738
- fromAsset,
1739
- toAsset,
1740
- fromAmount,
1741
- toAmount: offer.wantAmount.toString(),
1742
- // ponytail(arkade-os/ts-sdk#680): empty address makes cancel fall back
1743
- // to the current operator key; store the funded address if operator-key
1744
- // rotations become real (cancelOffer now at least diagnoses the
1745
- // mismatch instead of reporting a missing VTXO)
1746
- swapAddress: "",
1747
- swapPkScript,
1748
- offerHex,
1749
- fundingTxid: fundingTx.redeemTxid,
1750
- spentTxid,
1751
- status,
1752
- createdAt: fundingTx.createdAt ? fundingTx.createdAt * 1e3 : vtxo.createdAt.getTime(),
1753
- // the completion time is the caller's record of the spend, if it
1754
- // has one — the psbt that classified it carries no timestamp
1755
- ...completion
1756
- });
1757
- }
1758
- return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
1759
- }
1760
-
1761
- // src/claim.ts
1762
- import { hex as hex6 } from "@scure/base";
1763
- import { ripemd160 } from "@noble/hashes/legacy.js";
1764
- import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
1765
- import {
1766
- CSVMultisigTapscript as CSVMultisigTapscript2,
1767
- claimWithPreimageIdentity,
1768
- signAndSubmitOffchainTx
1769
- } from "@arkade-os/sdk";
1770
- var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1771
- var LockupAmountMismatchError = class extends Error {
1772
- name = "LockupAmountMismatchError";
1773
- reason = "amount_mismatch";
1774
- expectedAmount;
1775
- lockedAmount;
1776
- constructor(expectedAmount, lockedAmount) {
1777
- super(
1778
- `lockup holds ${lockedAmount} sats, below the agreed ${expectedAmount} \u2014 refusing to publish the preimage`
1779
- );
1780
- this.expectedAmount = expectedAmount;
1781
- this.lockedAmount = lockedAmount;
1782
- }
1783
- };
1784
- var assertFiniteAmount = (value, reason, label) => {
1785
- if (Number.isFinite(value)) return;
1786
- const error = new Error(`${label} is not a finite number (${String(value)})`);
1787
- error.reason = reason;
1788
- throw error;
1789
- };
1790
- async function pushClaim(operator, input) {
1791
- if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
1792
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
1793
- if (swept.length > 0) {
1794
- throw new LockupNeedsRecoveryError(
1795
- swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
1796
- input.contract.options.refundLocktime
1797
- );
1798
- }
1799
- const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
1800
- assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
1801
- if (!input.partiallyClaimed) {
1802
- assertFiniteAmount(input.expectedAmount, "invalid_gate_input", "expectedAmount");
1803
- if (locked < input.expectedAmount) {
1804
- throw new LockupAmountMismatchError(input.expectedAmount, locked);
1805
- }
1806
- }
1807
- const committed = input.contract.options.preimageHash;
1808
- if (hex6.encode(ripemd160(sha2563(input.preimage))) !== hex6.encode(committed)) {
1809
- throw new Error("preimage does not match the covenant's payment hash");
1810
- }
1811
- const info = await operator.getInfo();
1812
- let operatorUnrollScript;
1813
- try {
1814
- operatorUnrollScript = CSVMultisigTapscript2.decode(hex6.decode(info.checkpointTapscript));
1815
- } catch {
1816
- throw new Error("invalid checkpointTapscript from the operator");
1817
- }
1818
- const leaf = input.contract.claim();
1819
- const tapTree = input.contract.encode();
1820
- const txid = await signAndSubmitOffchainTx({
1821
- identity: claimWithPreimageIdentity(input.receiver, input.preimage),
1822
- provider: operator,
1823
- inputs: input.vtxos.map((vtxo) => ({
1824
- txid: vtxo.txid,
1825
- vout: vtxo.vout,
1826
- value: vtxo.value,
1827
- tapLeafScript: leaf,
1828
- tapTree
1829
- })),
1830
- // One aggregate output: unlike the covenant refund, this leaf inspects
1831
- // nothing about the output set.
1832
- outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
1833
- serverUnrollScript: operatorUnrollScript,
1834
- verifyServerSignatures: { serverPubkey: input.contract.options.server }
1835
- });
1836
- return { txid, amount: locked };
1837
- }
1838
- async function awaitLockupFunding(indexer, swapPkScript, options = {}) {
1839
- const pollMs = options.pollMs ?? 5e3;
1840
- for (; ; ) {
1841
- const vtxos = await findLockupVtxos(indexer, swapPkScript);
1842
- if (vtxos.length > 0) return vtxos;
1843
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
1844
- const error = new Error("the lockup never appeared at the covenant script");
1845
- error.reason = "lockup_timeout";
1846
- throw error;
1847
- }
1848
- await sleep2(pollMs);
1849
- }
1850
- }
1851
- async function claimReceiveLockup(indexer, operator, input) {
1852
- const vtxos = await awaitLockupFunding(indexer, input.swapPkScript, {
1853
- pollMs: input.pollMs,
1854
- deadline: input.deadline
1855
- });
1856
- return pushClaim(operator, {
1857
- contract: input.contract,
1858
- receiver: input.receiver,
1859
- preimage: input.preimage,
1860
- vtxos,
1861
- destinationPkScript: input.destinationPkScript,
1862
- expectedAmount: input.expectedAmount,
1863
- partiallyClaimed: input.partiallyClaimed
1864
- });
1865
- }
1866
-
1867
- // src/refundBlocked.ts
1868
- import {
1869
- ForeignDescriptorError,
1870
- WalletCannotSignError,
1871
- contractSigner
1872
- } from "@arkade-os/sdk";
1873
- var RefundNotLocallyPossibleError = class extends Error {
1874
- constructor(reason, message, options) {
1875
- super(message, options);
1876
- this.reason = reason;
1877
- }
1878
- reason;
1879
- name = "RefundNotLocallyPossibleError";
1880
- };
1881
- async function senderIdentityForSwapRecord(wallet, record) {
1882
- if (!record.signingDescriptor) {
1883
- throw new RefundNotLocallyPossibleError(
1884
- "no-secrets",
1885
- "this swap record carries no signing descriptor"
1886
- );
1887
- }
1888
- try {
1889
- return await contractSigner(wallet, record.signingDescriptor);
1890
- } catch (cause) {
1891
- if (cause instanceof WalletCannotSignError) {
1892
- throw new RefundNotLocallyPossibleError(
1893
- "unsignable-wallet",
1894
- `this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
1895
- { cause }
1896
- );
1897
- }
1898
- if (cause instanceof ForeignDescriptorError) {
1899
- throw new RefundNotLocallyPossibleError(
1900
- "foreign-descriptor",
1901
- `this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
1902
- { cause }
1903
- );
1904
- }
1905
- throw cause;
1906
- }
1907
- }
1908
-
1909
- // src/arkadeRefunder.ts
1910
- function arkadeRefunder(deps) {
1911
- return async (swap) => {
1912
- const contract = swap.lockup?.script;
1913
- if (!contract) {
1914
- throw new Error(
1915
- `swap ${swap.rfqId} carries no lockup covenant, so its refund cannot be built`
1916
- );
1917
- }
1918
- const vtxos = await findLockupVtxos(deps.indexer, swap.lockupPkScript);
1919
- if (vtxos.length === 0) return null;
1920
- const record = await deps.repository.getRfqSwap(swap.rfqId);
1921
- if (!record) {
1922
- throw new RefundNotLocallyPossibleError(
1923
- "no-secrets",
1924
- `no stored record for ${swap.rfqId}; the descriptor that signs its refund lives there`
1925
- );
1926
- }
1927
- const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
1928
- return pushRefundWithoutReceiver(deps.operator, { contract, sender, vtxos });
1929
- };
1930
- }
1931
-
1932
- // src/rfqSwapState.ts
1933
- var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
1934
- var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
1935
-
1936
- // src/rfqRecord.ts
1937
- import { ArkAddress as ArkAddress2, VHTLCV2ContractHandler } from "@arkade-os/sdk";
1938
- import { hex as hex7 } from "@scure/base";
1939
- var RFQ_SWAP_RETENTION_SECONDS = 30 * 24 * 60 * 60;
1940
- function renameLegacyClaimTxid(profile) {
1941
- const { claimArkTxid, ...rest } = profile;
1942
- return { ...rest, claimTxid: rest.claimTxid ?? claimArkTxid };
1943
- }
1944
- function normalizeRfqSwapRecord(record) {
1945
- const { fundingArkTxid, refundArkTxid, lockupSpendArkTxids, ...rest } = record;
1946
- const legacyClaim = record.kind === "lightning_receive" && record.profile.claimArkTxid !== void 0;
1947
- if (!fundingArkTxid && !refundArkTxid && !lockupSpendArkTxids && !legacyClaim) return record;
1948
- const fundingTxid = rest.fundingTxid ?? fundingArkTxid;
1949
- const refundTxid = rest.refundTxid ?? refundArkTxid;
1950
- const lockupSpendTxids = rest.lockupSpendTxids ?? lockupSpendArkTxids;
1951
- return {
1952
- ...rest,
1953
- ...fundingTxid ? { fundingTxid } : {},
1954
- ...refundTxid ? { refundTxid } : {},
1955
- ...lockupSpendTxids?.length ? { lockupSpendTxids } : {},
1956
- ...legacyClaim ? { profile: renameLegacyClaimTxid(record.profile) } : {}
1957
- };
1958
- }
1959
- var managerState = (swap) => ({
1960
- rfqId: swap.rfqId,
1961
- state: swap.state,
1962
- createdAt: swap.createdAt,
1963
- updatedAt: swap.updatedAt,
1964
- ...swap.refundTxid ? { refundTxid: swap.refundTxid } : {},
1965
- ...swap.lockupSpendTxids?.length ? { lockupSpendTxids: [...swap.lockupSpendTxids] } : {},
1966
- ...swap.settlementPreimageHex ? { settlementPreimageHex: swap.settlementPreimageHex } : {},
1967
- ...swap.failure ? { failure: swap.failure } : {},
1968
- ...swap.claimFailure ? { claimFailure: swap.claimFailure } : {},
1969
- ...swap.blockedReason ? { blockedReason: swap.blockedReason } : {}
1970
- });
1971
- function assertSameSwap(origin, swap) {
1972
- if (origin.kind !== swap.kind) {
1973
- throw new Error(
1974
- `rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
1975
- );
1976
- }
1977
- const funded = hex7.encode(ArkAddress2.decode(origin.lockupAddress).pkScript);
1978
- const watched = hex7.encode(swap.lockupPkScript);
1979
- if (funded !== watched) {
1980
- throw new Error(
1981
- `rfq swap record's lockup address holds ${funded}, but the swap watches ${watched} \u2014 these are not the same swap`
1982
- );
1983
- }
1984
- }
1985
- function createRfqSwapRecord(origin, swap) {
1986
- assertSameSwap(origin, swap);
1987
- const handler = rfqCorridorHandlers.getOrThrow(origin.kind);
1988
- return {
1989
- ...origin,
1990
- ...managerState(swap),
1991
- // The caller wrote what only the request result knows; the handler adds
1992
- // what the live swap already carries.
1993
- profile: { ...origin.profile, ...handler.project(swap) }
1994
- };
1995
- }
1996
- function updateRfqSwapRecord(record, swap) {
1997
- assertSameSwap(record, swap);
1998
- const stored = normalizeRfqSwapRecord(record);
1999
- const {
2000
- refundTxid: _refundTxid,
2001
- lockupSpendTxids: _lockupSpendTxids,
2002
- settlementPreimageHex: _settlementPreimageHex,
2003
- failure: _failure,
2004
- claimFailure: _claimFailure,
2005
- blockedReason: _blockedReason,
2006
- ...origin
2007
- } = stored;
2008
- const handler = rfqCorridorHandlers.getOrThrow(stored.kind);
2009
- return {
2010
- ...origin,
2011
- ...managerState(swap),
2012
- profile: { ...stored.profile, ...handler.project(swap) }
2013
- };
2014
- }
2015
- function rfqSwapOriginOf(record) {
2016
- const stored = normalizeRfqSwapRecord(record);
2017
- return {
2018
- kind: stored.kind,
2019
- lockupAddress: stored.lockupAddress,
2020
- profile: { ...stored.profile },
2021
- ...stored.amount !== void 0 ? { amount: stored.amount } : {},
2022
- ...stored.fundingTxid ? { fundingTxid: stored.fundingTxid } : {}
2023
- };
2024
- }
2025
- function lockupScript(params, lockupAddress) {
2026
- const script = VHTLCV2ContractHandler.createScript(params);
2027
- const funded = ArkAddress2.decode(lockupAddress).pkScript;
2028
- if (hex7.encode(funded) !== hex7.encode(script.pkScript)) {
2029
- throw new Error(
2030
- `rfq swap covenant params derive ${hex7.encode(script.pkScript)}, but the record's lockup address holds ${hex7.encode(funded)} \u2014 these params are not this swap's`
2031
- );
2032
- }
2033
- return script;
2034
- }
2035
- function rebuildRfqSwap(record, params) {
2036
- const stored = normalizeRfqSwapRecord(record);
2037
- const script = lockupScript(params, stored.lockupAddress);
2038
- const common = {
2039
- rfqId: stored.rfqId,
2040
- state: stored.state,
2041
- lockupPkScript: script.pkScript,
2042
- lockup: { script, address: stored.lockupAddress },
2043
- // From the covenant, which binds it: the record's own copy would be a
2044
- // second source for the deadline the refund is gated on.
2045
- refundLocktime: Number(script.options.refundLocktime),
2046
- createdAt: stored.createdAt,
2047
- updatedAt: stored.updatedAt,
2048
- ...stored.refundTxid ? { refundTxid: stored.refundTxid } : {},
2049
- ...stored.lockupSpendTxids?.length ? { lockupSpendTxids: [...stored.lockupSpendTxids] } : {},
2050
- ...stored.settlementPreimageHex ? { settlementPreimageHex: stored.settlementPreimageHex } : {},
2051
- ...stored.failure ? { failure: stored.failure } : {},
2052
- ...stored.claimFailure ? { claimFailure: stored.claimFailure } : {},
2053
- ...stored.blockedReason ? { blockedReason: stored.blockedReason } : {}
2054
- };
2055
- const handler = rfqCorridorHandlers.getOrThrow(stored.kind);
2056
- return {
2057
- ...common,
2058
- kind: stored.kind,
2059
- ...handler.hydrate(stored.profile, { lockup: script })
2060
- };
2061
- }
2062
- function shouldRetainRfqSwap(record, now) {
2063
- if (!isRfqSwapTerminal(record.state)) return true;
2064
- return now - record.updatedAt < RFQ_SWAP_RETENTION_SECONDS;
2065
- }
2066
-
2067
- // src/swapManager.ts
2068
- import { hex as hex8 } from "@scure/base";
2069
- import {
2070
- isContractVtxoEvent
2071
- } from "@arkade-os/sdk";
2072
- function nextOnchainAction(input) {
2073
- switch (input.phase.phase) {
2074
- case "unfunded":
2075
- case "awaiting_confirmations":
2076
- return "wait";
2077
- case "claimed":
2078
- return "claimed";
2079
- case "swept":
2080
- return "swept";
2081
- case "refundable":
2082
- return "claim_window_closed";
2083
- case "claimable":
2084
- return input.htlcLocktime - input.now >= ONCHAIN_CLAIM_MARGIN_SECONDS ? "claim" : "claim_window_closed";
2085
- }
2086
- }
2087
- var RFQ_CONFIGURATION_REFUSAL = {
2088
- noClaimLockupCallback: "no claimLockup callback is wired, so this wallet cannot claim the lockup",
2089
- noCallbacksForClaim: "no callbacks are wired, so this wallet cannot claim the lockup",
2090
- noClaimOnchainCallback: "no claimOnchain callback is wired, so this wallet cannot claim the L1 fill",
2091
- autoActionsDisabled: "automatic actions are disabled, so this wallet will not push the refund",
2092
- noCallbacksForRefund: "no callbacks are wired, so this wallet cannot push the refund"
2093
- };
2094
- var RFQ_CONFIGURATION_REFUSALS = Object.values(RFQ_CONFIGURATION_REFUSAL);
2095
- var isRfqConfigurationRefusal = (reason) => reason !== void 0 && RFQ_CONFIGURATION_REFUSALS.includes(reason);
2096
- var RfqSwapOriginRequired = class extends Error {
2097
- /** The swap that could not be admitted. */
2098
- rfqId;
2099
- constructor(rfqId) {
2100
- super(
2101
- `rfq swap ${rfqId} has no stored record and no origin was supplied; pass the request-time origin as addSwap's second argument so its first record can be written`
2102
- );
2103
- this.name = "RfqSwapOriginRequired";
2104
- this.rfqId = rfqId;
2105
- }
2106
- };
2107
- var notify = (listeners, call) => {
2108
- for (const listener of listeners) {
2109
- try {
2110
- call(listener);
2111
- } catch {
2112
- }
2113
- }
2114
- };
2115
- var RfqSwapManager = class {
2116
- deps;
2117
- config;
2118
- callbacks = null;
2119
- swapUpdateListeners = /* @__PURE__ */ new Set();
2120
- swapCompletedListeners = /* @__PURE__ */ new Set();
2121
- swapFailedListeners = /* @__PURE__ */ new Set();
2122
- actionExecutedListeners = /* @__PURE__ */ new Set();
2123
- monitored = /* @__PURE__ */ new Map();
2124
- /** Monitored swaps by lockup script hex, so a contract event — which names
2125
- * a script and nothing else — can find the swap it belongs to. */
2126
- byLockupScript = /* @__PURE__ */ new Map();
2127
- /**
2128
- * Swaps whose lockup registration has been SETTLED one way or another,
2129
- * mapped to whether a contract row actually resulted. Membership is what
2130
- * stops a per-pass retry from becoming a per-pass round trip; the value is
2131
- * what keeps a swap that could never be registered from later trying to
2132
- * retire a row that does not exist, which would report a spurious failure
2133
- * on a swap that in fact succeeded.
2134
- */
2135
- registered = /* @__PURE__ */ new Map();
2136
- /**
2137
- * Swaps whose `refundArkade` answered {@link RefundNotLocallyPossibleError}
2138
- * in this process. Membership stops the push from being re-issued every
2139
- * pass — it cannot start working on its own, and re-issuing it is the
2140
- * grind `needs_counterparty` exists to remove. Only
2141
- * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it, so a caller
2142
- * with no probe learns again on the next start, when the wallet that can
2143
- * sign may well have been restored.
2144
- */
2145
- refundRefused = /* @__PURE__ */ new Set();
2146
- /**
2147
- * The lockup outpoints a receive swap's claim callback has already been
2148
- * handed, by rfqId.
2149
- *
2150
- * What this exists to prevent: a claim SUCCEEDS, and for the next few
2151
- * passes the indexer still lists those outputs as unspent. Without a
2152
- * record of what was already claimed, every one of those passes would
2153
- * re-submit the same spend, fail against the server, and report a swap
2154
- * that in fact worked as failing. With one, a re-claim happens only when
2155
- * an outpoint appears that was never claimed — a lockup funded piecemeal,
2156
- * which is legitimate and which `partiallyClaimed` exists for.
2157
- *
2158
- * Process-local: after a restart a swap with a live claim tries once more.
2159
- * That is the recovery case rather than the spam one — a claim that never
2160
- * landed leaves its outputs unspent, and one that did leaves a single
2161
- * rejection.
2162
- */
2163
- claimedOutpoints = /* @__PURE__ */ new Map();
2164
- /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
2165
- unsubscribeContracts = null;
2166
- /** Terminal records, kept so a late {@link waitForSwapCompletion} still
2167
- * answers instead of throwing "not found". Cleared by {@link removeSwap}. */
2168
- finished = /* @__PURE__ */ new Map();
2169
- waiters = /* @__PURE__ */ new Map();
2170
- /**
2171
- * The request-time origin of each swap the manager may have to CREATE a
2172
- * record for, by rfqId.
2173
- *
2174
- * Needed only for a swap the store has never seen: once a record exists,
2175
- * `updateRfqSwapRecord` carries the origin half through and the map is
2176
- * redundant. It is kept anyway for the swap's whole life, so a record the
2177
- * store loses between passes is rewritten rather than lost — and dropped
2178
- * by {@link removeSwap} and by retention, which are the two places a swap
2179
- * stops being this manager's business.
2180
- */
2181
- origins = /* @__PURE__ */ new Map();
2182
- /** Records changed during the current pass, flushed to the repository and
2183
- * through `saveSwap`. */
2184
- dirty = /* @__PURE__ */ new Set();
2185
- /** Race guard: one action at a time per swap. */
2186
- inProgress = /* @__PURE__ */ new Set();
2187
- timer = null;
2188
- running = false;
2189
- constructor(deps, config = {}) {
2190
- this.deps = deps;
2191
- this.config = {
2192
- enableAutoActions: config.enableAutoActions ?? true,
2193
- pollIntervalMs: config.pollIntervalMs ?? 5e3,
2194
- now: config.now ?? (() => Math.floor(Date.now() / 1e3))
2195
- };
2196
- if (config.events?.onSwapUpdate) this.swapUpdateListeners.add(config.events.onSwapUpdate);
2197
- if (config.events?.onSwapCompleted) {
2198
- this.swapCompletedListeners.add(config.events.onSwapCompleted);
2199
- }
2200
- if (config.events?.onSwapFailed) this.swapFailedListeners.add(config.events.onSwapFailed);
2201
- if (config.events?.onActionExecuted) {
2202
- this.actionExecutedListeners.add(config.events.onActionExecuted);
2203
- }
2204
- }
2205
- /** Wire the money-moving half. Without it the manager only watches. The
2206
- * two claims may be omitted for a consumer that drives no kind reaching
2207
- * them — see {@link AvailableRfqSwapManagerCallbacks}. */
2208
- setCallbacks(callbacks) {
2209
- this.callbacks = callbacks;
2210
- }
2211
- onSwapUpdate(listener) {
2212
- this.swapUpdateListeners.add(listener);
2213
- return () => this.swapUpdateListeners.delete(listener);
2214
- }
2215
- onSwapCompleted(listener) {
2216
- this.swapCompletedListeners.add(listener);
2217
- return () => this.swapCompletedListeners.delete(listener);
2218
- }
2219
- onSwapFailed(listener) {
2220
- this.swapFailedListeners.add(listener);
2221
- return () => this.swapFailedListeners.delete(listener);
2222
- }
2223
- onActionExecuted(listener) {
2224
- this.actionExecutedListeners.add(listener);
2225
- return () => this.actionExecutedListeners.delete(listener);
2226
- }
2227
- /**
2228
- * Rebuild every stored swap and take over monitoring them.
2229
- *
2230
- * The composition a consumer otherwise writes by hand, and the one place
2231
- * all four pieces meet: retention decides what to keep
2232
- * (`shouldRetainRfqSwap`), the lockup's contract row supplies the covenant
2233
- * (`lockupContractParams`), `rebuildRfqSwap` turns a record back into a
2234
- * live swap, and each rebuilt swap arrives with its own origin, so nothing
2235
- * is asked of the caller.
2236
- *
2237
- * **Deliberately not part of {@link start}.** A consumer that wants to
2238
- * look at its records — count them, show them, prune and stop — is not
2239
- * forced to start driving money to do it. Call this first and `start()`
2240
- * after; a manager already running polls the restored swaps at once.
2241
- *
2242
- * Retention runs BEFORE the rebuild, so a record past
2243
- * `RFQ_SWAP_RETENTION_SECONDS` costs no contract lookup on its way to being
2244
- * dropped.
2245
- *
2246
- * **A record that cannot be rebuilt is reported, never swallowed and never
2247
- * fatal.** `rebuildRfqSwap` throws by design when the covenant params do
2248
- * not derive the funded address, and `lockupContractParams` throws
2249
- * `LockupContractMissing` when the wallet has no row for the lockup — both
2250
- * say something true about that one record, and neither is a reason to
2251
- * strand the others. They come back in {@link RfqRestoreResult.failed}.
2252
- */
2253
- async restoreFromRepository(options = {}) {
2254
- const repository = this.requireRepository("restoreFromRepository");
2255
- const params = options.params ?? this.paramsFromContracts();
2256
- const records = await repository.getAllRfqSwaps();
2257
- const pruned = await this.dropRetired(repository, records);
2258
- const retired = new Set(pruned);
2259
- const restored = [];
2260
- const failed = [];
2261
- for (const record of records) {
2262
- if (retired.has(record.rfqId)) continue;
2263
- let swap;
2264
- try {
2265
- swap = rebuildRfqSwap(record, await params(record));
2266
- } catch (error) {
2267
- failed.push({
2268
- rfqId: record.rfqId,
2269
- error: error instanceof Error ? error : new Error(errorMessage(error))
2270
- });
2271
- continue;
2272
- }
2273
- this.origins.set(record.rfqId, rfqSwapOriginOf(record));
2274
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
2275
- else this.track(swap);
2276
- restored.push(swap);
2277
- }
2278
- if (this.running) {
2279
- await Promise.allSettled(
2280
- restored.filter((swap) => this.monitored.has(swap.rfqId)).map((swap) => this.pollSwap(swap))
2281
- );
2282
- }
2283
- return { restored, failed, pruned };
2284
- }
2285
- /**
2286
- * Drop stored records that are terminal and past
2287
- * `RFQ_SWAP_RETENTION_SECONDS`, and return their ids.
2288
- *
2289
- * `needs_counterparty` is never dropped, however old: the money is still at
2290
- * the lockup and the counterparty's move still ends the swap. That rule
2291
- * lives in `shouldRetainRfqSwap`, which this defers to rather than
2292
- * restating.
2293
- *
2294
- * Public because retention is a caller's cadence, not the manager's: a
2295
- * long-lived process wants it on a timer of its own, a mobile app wants it
2296
- * at boot. {@link restoreFromRepository} runs it first, so the boot path
2297
- * needs no separate call.
2298
- */
2299
- async pruneRetiredSwaps() {
2300
- const repository = this.deps.repository;
2301
- if (!repository) return [];
2302
- return this.dropRetired(repository, await repository.getAllRfqSwaps());
2303
- }
2304
- async dropRetired(repository, records) {
2305
- const now = this.config.now();
2306
- const dropped = [];
2307
- for (const record of records) {
2308
- if (shouldRetainRfqSwap(record, now)) continue;
2309
- await repository.removeRfqSwap(record.rfqId);
2310
- this.finished.delete(record.rfqId);
2311
- if (!this.monitored.has(record.rfqId)) this.origins.delete(record.rfqId);
2312
- dropped.push(record.rfqId);
2313
- }
2314
- return dropped;
2315
- }
2316
- requireRepository(method) {
2317
- const repository = this.deps.repository;
2318
- if (!repository) {
2319
- throw new Error(
2320
- `${method} needs a record store; pass one as RfqSwapManagerDeps.repository`
2321
- );
2322
- }
2323
- return repository;
2324
- }
2325
- /** The default covenant source: the wallet's own contract row for each
2326
- * lockup, which is where registration put it before the address could be
2327
- * funded. */
2328
- paramsFromContracts() {
2329
- const contracts = this.deps.contracts;
2330
- if (!contracts) {
2331
- throw new Error(
2332
- "restoreFromRepository needs the covenant parameters: wire RfqSwapManagerDeps.contracts so each lockup's contract row can be read, or pass options.params"
2333
- );
2334
- }
2335
- return (record) => lockupContractParams(contracts, record.lockupAddress);
2336
- }
2337
- /**
2338
- * Load records and begin monitoring. Runs one pass immediately — a caller
2339
- * resuming after a restart may be well past a deadline already — then
2340
- * every `pollIntervalMs`. Records that are already terminal are kept only
2341
- * so {@link waitForSwapCompletion} can answer for them.
2342
- *
2343
- * Calling it again while running loads the records and returns rather than
2344
- * re-arming — dropping them silently would strand a funded swap on a
2345
- * caller's harmless double-start.
2346
- *
2347
- * The signature is unchanged with a {@link RfqSwapManagerDeps.repository}
2348
- * wired; the origins are resolved from the store instead, by the same rule
2349
- * {@link addSwap} applies. A swap the store has never seen throws
2350
- * {@link RfqSwapOriginRequired} — hand that one to `addSwap` with its
2351
- * origin, or restore the whole set with {@link restoreFromRepository},
2352
- * which needs no caller input at all. Every swap is checked before any is
2353
- * tracked, so a bad one in the list does not leave a half-loaded manager.
2354
- */
2355
- async start(swaps = []) {
2356
- for (const swap of swaps) await this.admit(swap);
2357
- for (const swap of swaps) {
2358
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
2359
- else this.track(swap);
2360
- }
2361
- if (this.running) return;
2362
- this.running = true;
2363
- this.subscribe();
2364
- await this.poll();
2365
- this.arm();
2366
- }
2367
- /**
2368
- * Stop monitoring and clear the timer. In-flight actions are not
2369
- * cancellable and run to completion; outstanding
2370
- * {@link waitForSwapCompletion} promises are left pending, since
2371
- * stop/start is a pause rather than a cancellation.
2372
- *
2373
- * The contract subscription is dropped too — an open stream with nothing
2374
- * reacting to it is a leak, and {@link start} puts it back. What is NOT
2375
- * undone is the contract registration: those rows are the wallet's, they
2376
- * outlive this manager's lifecycle, and dropping them would unwatch a
2377
- * lockup that is still funded.
2378
- */
2379
- async stop() {
2380
- this.running = false;
2381
- if (this.timer) {
2382
- clearTimeout(this.timer);
2383
- this.timer = null;
2384
- }
2385
- this.unsubscribeContracts?.();
2386
- this.unsubscribeContracts = null;
2387
- }
2388
- /**
2389
- * Begin monitoring a swap. Polled immediately when the manager is running,
2390
- * so a just-funded swap does not wait out a whole interval.
2391
- *
2392
- * `origin` is the request-time half a live swap cannot carry — the corridor,
2393
- * the funded address, the corridor's profile, the funding txid — and it is
2394
- * what lets the manager write this swap's FIRST record. Supply it whenever
2395
- * a {@link RfqSwapManagerDeps.repository} is wired and the swap is new. It
2396
- * may be omitted for a swap the store already holds a record for, which is
2397
- * then read to confirm it; omitting it for one the store has never seen
2398
- * throws {@link RfqSwapOriginRequired} rather than admitting a swap whose
2399
- * record could never be written. With no repository wired the parameter is
2400
- * inert.
2401
- */
2402
- async addSwap(swap, origin) {
2403
- await this.admit(swap, origin);
2404
- if (isRfqSwapTerminal(swap.state)) {
2405
- this.finished.set(swap.rfqId, swap);
2406
- return;
2407
- }
2408
- this.track(swap);
2409
- if (this.running) await this.pollSwap(swap);
2410
- }
2411
- /**
2412
- * Settle where this swap's record will come from, before it is monitored.
2413
- *
2414
- * Three ways it can be answered, in order: the caller passed an origin, one
2415
- * is already remembered from an earlier `addSwap`, or the store holds a
2416
- * record — which is the origin, already written. Only the last costs a read,
2417
- * and only when the first two are absent.
2418
- */
2419
- async admit(swap, origin) {
2420
- if (origin) {
2421
- assertSameSwap(origin, swap);
2422
- this.origins.set(swap.rfqId, origin);
2423
- if (this.deps.repository && !isRfqSwapTerminal(swap.state)) {
2424
- this.dirty.add(swap.rfqId);
2425
- }
2426
- return;
2427
- }
2428
- const repository = this.deps.repository;
2429
- if (!repository || this.origins.has(swap.rfqId)) return;
2430
- const stored = await repository.getRfqSwap(swap.rfqId);
2431
- if (!stored) throw new RfqSwapOriginRequired(swap.rfqId);
2432
- this.origins.set(swap.rfqId, rfqSwapOriginOf(stored));
2433
- }
2434
- /** Forget a swap entirely, monitored or finished.
2435
- *
2436
- * Its contract row is left alone: registration is a wallet-level fact about
2437
- * a script that may still hold money, and this call says only that THIS
2438
- * manager stops driving the swap. Retiring the row is reserved for a swap
2439
- * that reached a terminal state, where the lockup is provably done. */
2440
- async removeSwap(rfqId) {
2441
- this.untrack(rfqId);
2442
- this.finished.delete(rfqId);
2443
- this.registered.delete(rfqId);
2444
- const waiting = this.waiters.get(rfqId);
2445
- if (waiting) {
2446
- const error = new Error(`swap ${rfqId} was removed from monitoring`);
2447
- for (const waiter of waiting) waiter.reject(error);
2448
- }
2449
- this.waiters.delete(rfqId);
2450
- this.dirty.delete(rfqId);
2451
- this.origins.delete(rfqId);
2452
- }
2453
- /** Every swap still being monitored. */
2454
- async getPendingSwaps() {
2455
- return [...this.monitored.values()];
2456
- }
2457
- /**
2458
- * Every swap this manager holds — {@link getPendingSwaps} plus the ones
2459
- * that already ended. The two sets are disjoint: a swap leaves `monitored`
2460
- * as it enters `finished`.
2461
- *
2462
- * The finished half is what this process has seen, which after
2463
- * {@link restoreFromRepository} is the stored history minus what retention
2464
- * pruned. A manager that has restored nothing answers with the live swaps
2465
- * alone.
2466
- */
2467
- async getAllSwaps() {
2468
- return [...this.monitored.values(), ...this.finished.values()];
2469
- }
2470
- async hasSwap(rfqId) {
2471
- return this.monitored.has(rfqId);
2472
- }
2473
- /** True while an action for this swap holds the per-swap lock. */
2474
- async isProcessing(rfqId) {
2475
- return this.inProgress.has(rfqId);
2476
- }
2477
- async getStats() {
2478
- return {
2479
- isRunning: this.running,
2480
- monitoredSwaps: this.monitored.size,
2481
- finishedSwaps: this.finished.size,
2482
- inProgress: this.inProgress.size,
2483
- pollIntervalMs: this.config.pollIntervalMs
2484
- };
2485
- }
2486
- /**
2487
- * Run one monitoring pass over every swap now.
2488
- *
2489
- * {@link start} calls this on an interval, but it is public on purpose: a
2490
- * caller that sleeps its process (a mobile app resuming, a service worker
2491
- * waking) wants a pass on that event rather than at the next tick. Passes
2492
- * do not overlap per swap — the in-progress lock makes a concurrent call a
2493
- * no-op for any swap already being worked on.
2494
- */
2495
- async poll() {
2496
- await Promise.allSettled([...this.monitored.values()].map((swap) => this.pollSwap(swap)));
2497
- }
2498
- /**
2499
- * Resolve once this swap's PAYOUT is decided — which for onchain-send is
2500
- * the L1 claim, not the end of the record's life: once `claimTxid` is set
2501
- * the trader has the coins it swapped for, and what remains is the manager
2502
- * watching the Arkade lockup close. That holds however the record is
2503
- * labelled afterwards, `needs_counterparty` included. Lightning-send has no
2504
- * such split and resolves at `settled`/`refunded`, and so does lightning
2505
- * receive — see {@link isPayoutDecided} for why its own claim txid does not
2506
- * decide it.
2507
- *
2508
- * Rejects only on `failed`. `refunded` resolves: on a send leg a refund is
2509
- * an outcome the caller asked this manager to drive, not an exception. On a
2510
- * receive leg it is the swap being lost, which is still an answer and not
2511
- * an error — read `state`, do not infer success from resolution.
2512
- */
2513
- async waitForSwapCompletion(rfqId) {
2514
- const swap = this.monitored.get(rfqId) ?? this.finished.get(rfqId);
2515
- if (!swap) throw new Error(`swap ${rfqId} is not monitored`);
2516
- if (swap.state === "failed") throw new Error(swap.failure ?? `swap ${rfqId} failed`);
2517
- if (isPayoutDecided(swap)) return outcomeOf(swap);
2518
- return new Promise((resolve, reject) => {
2519
- const set = this.waiters.get(rfqId) ?? /* @__PURE__ */ new Set();
2520
- set.add({ resolve, reject });
2521
- this.waiters.set(rfqId, set);
2522
- });
2523
- }
2524
- // ── internals ────────────────────────────────────────────────────────────
2525
- track(swap) {
2526
- this.monitored.set(swap.rfqId, swap);
2527
- this.byLockupScript.set(hex8.encode(swap.lockupPkScript), swap);
2528
- }
2529
- /** Drops the swap from BOTH indexes. The event index is the one that stops
2530
- * a late event finding a swap that is gone; `pollSwap`'s own
2531
- * `monitored` check would also catch it, and deliberately still does —
2532
- * either alone is sufficient, which is what keeps a future change to one of
2533
- * them from silently re-driving a cancelled swap. */
2534
- untrack(rfqId) {
2535
- const swap = this.monitored.get(rfqId);
2536
- if (swap) this.byLockupScript.delete(hex8.encode(swap.lockupPkScript));
2537
- this.monitored.delete(rfqId);
2538
- this.refundRefused.delete(rfqId);
2539
- this.claimedOutpoints.delete(rfqId);
2540
- }
2541
- /**
2542
- * Turn the indexer's push into an extra reason to run a pass — and nothing
2543
- * more.
2544
- *
2545
- * **This is deliberately not a source of truth.** An event names a script;
2546
- * the reaction is to run the ordinary pass for the swap at that script, and
2547
- * that pass re-reads the lockup through {@link readLockupFate} exactly as
2548
- * the timer's pass does. So an event that is missed, duplicated, reordered
2549
- * or outright FORGED can only cost or save latency — it can never change
2550
- * what this manager believes about a swap, and it can never on its own
2551
- * cause a claim or a refund. That property is what makes it safe to bolt a
2552
- * best-effort stream onto a money path, and it must survive any future
2553
- * change here: the moment an event is BELIEVED rather than merely acted on,
2554
- * a relay outage becomes a correctness problem instead of a latency one.
2555
- *
2556
- * The timer stays armed regardless, and is the failsafe. Every deadline
2557
- * that moves money — `refundLocktime`, the L1 claim window — is an absolute
2558
- * timelock that passes whether or not a single event ever arrives.
2559
- */
2560
- subscribe() {
2561
- if (!this.deps.contracts || this.unsubscribeContracts) return;
2562
- this.unsubscribeContracts = this.deps.contracts.onContractEvent((event) => {
2563
- if (event.type === "connection_reset") {
2564
- void this.poll().catch(() => {
2565
- });
2566
- return;
2567
- }
2568
- if (!isContractVtxoEvent(event)) return;
2569
- const swap = this.byLockupScript.get(event.contractScript);
2570
- if (!swap) return;
2571
- void this.pollSwap(swap).catch(() => {
2572
- });
2573
- });
2574
- }
2575
- /**
2576
- * Register this swap's lockup with the wallet's contract manager, once.
2577
- *
2578
- * The backstop, not the primary site: `requestLightningSend` /
2579
- * `requestOnchainSend` register before the caller can fund, so this covers
2580
- * swaps whose records predate that — and costs nothing when it does not,
2581
- * since `createContract` is first-writer-wins.
2582
- *
2583
- * Best-effort by design: a failure here is reported and retried on the next
2584
- * pass, and never aborts the pass it is part of. Registration buys latency
2585
- * and puts the lockup in the wallet's contract set; it decides nothing. The
2586
- * money path below it reads the indexer directly and is gated on timelocks
2587
- * that a missing contract row has no bearing on, so failing the pass over
2588
- * this would trade a real deadline for a bookkeeping one.
2589
- */
2590
- async ensureRegistered(swap) {
2591
- const contracts = this.deps.contracts;
2592
- if (!contracts) return;
2593
- if (this.registered.has(swap.rfqId)) return;
2594
- const lockup = swap.lockup;
2595
- if (!lockup) {
2596
- try {
2597
- const [existing] = await contracts.getContracts({
2598
- script: hex8.encode(swap.lockupPkScript)
2599
- });
2600
- if (existing) {
2601
- this.registered.set(swap.rfqId, true);
2602
- return;
2603
- }
2604
- } catch (error) {
2605
- this.emitFailed(swap, error);
2606
- return;
2607
- }
2608
- this.registered.set(swap.rfqId, false);
2609
- this.emitFailed(
2610
- swap,
2611
- new Error(
2612
- `swap ${swap.rfqId} carries no lockup script and has no contract row, so it cannot be registered \u2014 pass \`lockup\` to subscribe instead of polling`
2613
- )
2614
- );
2615
- return;
2616
- }
2617
- const script = hex8.encode(lockup.script.pkScript);
2618
- if (script !== hex8.encode(swap.lockupPkScript)) {
2619
- this.registered.set(swap.rfqId, false);
2620
- this.emitFailed(
2621
- swap,
2622
- new Error(
2623
- `swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${hex8.encode(swap.lockupPkScript)}`
2624
- )
2625
- );
2626
- return;
2627
- }
2628
- try {
2629
- await registerLockupContract(contracts, lockup.script, lockup.address);
2630
- this.registered.set(swap.rfqId, true);
2631
- } catch (error) {
2632
- this.emitFailed(swap, error);
2633
- }
2634
- }
2635
- /** Stop watching a finished swap's lockup. Retained, not deleted: the row
2636
- * is what keeps the lockup's own VTXOs annotatable and its history
2637
- * readable, while `retained` is what drops it from the subscription and
2638
- * the poll — a settled swap that stayed watched would cost the wallet a
2639
- * script for its whole life. Best-effort — the swap is over either way. */
2640
- retireContract(swap) {
2641
- if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
2642
- if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
2643
- void this.deps.contracts.setContractWatchState(hex8.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
2644
- }
2645
- arm() {
2646
- if (!this.running) return;
2647
- if (this.timer) clearTimeout(this.timer);
2648
- this.timer = setTimeout(() => {
2649
- this.timer = null;
2650
- void this.poll().then(() => this.arm());
2651
- }, this.config.pollIntervalMs);
2652
- }
2653
- async pollSwap(swap) {
2654
- if (this.inProgress.has(swap.rfqId)) return;
2655
- if (!this.monitored.has(swap.rfqId)) return;
2656
- this.inProgress.add(swap.rfqId);
2657
- try {
2658
- await this.runPass(swap);
2659
- } finally {
2660
- const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
2661
- if (persisted) {
2662
- this.dirty.delete(swap.rfqId);
2663
- this.settleWaiters(swap);
2664
- if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
2665
- }
2666
- this.inProgress.delete(swap.rfqId);
2667
- }
2668
- }
2669
- async runPass(swap) {
2670
- await this.ensureRegistered(swap);
2671
- let fate;
2672
- try {
2673
- fate = await readLockupFate(this.deps.indexer, {
2674
- swapPkScript: swap.lockupPkScript,
2675
- paymentHash: swap.paymentHash
2676
- });
2677
- } catch {
2678
- fate = { fate: "unknown" };
2679
- }
2680
- if (fate.fate === "claimed" || fate.fate === "returned") {
2681
- this.stampLockupSpends(swap, fate.spends);
2682
- if (fate.fate === "claimed") this.stampSettlementPreimage(swap, fate.preimage);
2683
- this.setState(swap, fate.fate === "claimed" ? "settled" : "refunded");
2684
- return;
2685
- }
2686
- if (swap.kind === "lightning_receive") {
2687
- return fate.fate === "exited" ? this.blockExitedLockup(swap, fate) : this.driveReceiveClaim(swap);
2688
- }
2689
- if (swap.kind === "onchain_send" && swap.state !== "claimed") {
2690
- if (await this.driveOnchain(swap) === "handled") return;
2691
- }
2692
- if (fate.fate === "exited") {
2693
- const claiming = swap.state === "claimable" || swap.state === "claimed";
2694
- if (this.config.now() < swap.refundLocktime && claiming) return;
2695
- return this.blockExitedLockup(swap, fate);
2696
- }
2697
- await this.driveArkadeRefund(swap);
2698
- }
2699
- /**
2700
- * The lockup was unilaterally exited: its outputs sit onchain under the
2701
- * VHTLC script, where no offchain claim or refund can reach them.
2702
- *
2703
- * `needs_counterparty` rather than a terminal state, because the money still
2704
- * needs action and the swap can still end either way — an onchain claim can
2705
- * reveal the preimage, an onchain refund can return it — and that state is
2706
- * documented as re-checked every pass. It must be set from HERE and not from
2707
- * inside `driveArkadeRefund`, whose two `unblock` calls would lift it again
2708
- * on the very next pass.
2709
- */
2710
- blockExitedLockup(swap, fate) {
2711
- this.block(
2712
- swap,
2713
- `the lockup was unilaterally exited (${fate.outpoints.length} output(s) onchain), so no offchain spend can move it \u2014 complete the unroll and spend it onchain`
2714
- );
2715
- }
2716
- /**
2717
- * The receive leg's whole state machine: claim the solver-funded lockup
2718
- * while the window is open, and recognise the shapes in which it can be
2719
- * lost.
2720
- *
2721
- * **The window closes at `refundLocktime`, on wall clock, with no margin.**
2722
- * Both halves of that are deliberate. It closes there because publishing
2723
- * `P` into the solver's live refund window risks losing the race and
2724
- * handing over the preimage anyway — the hazard `ONCHAIN_CLAIM_MARGIN_SECONDS`
2725
- * guards on the L1 side. It takes no margin because the two situations are
2726
- * not alike: that one budgets for confirmation depth, while this claim is an
2727
- * offchain spend that lands in seconds. Wall clock is already the
2728
- * conservative reading — the solver's leaf is a CLTV, which matures against
2729
- * median-time-past, and MTP trails wall clock — so the real window extends
2730
- * PAST this deadline rather than ending before it. Every second of margin
2731
- * subtracted here is a second of live claim window given away for nothing.
2732
- *
2733
- * **The trader has no move after it.** Nothing here can take the lockup
2734
- * back, so once the window shuts the swap is the solver's to resolve and
2735
- * this manager's job is to watch it happen and then stop.
2736
- */
2737
- async driveReceiveClaim(swap) {
2738
- const now = this.config.now();
2739
- if (now < swap.refundLocktime) {
2740
- let vtxos;
2741
- try {
2742
- vtxos = await findLockupVtxos(this.deps.indexer, swap.lockupPkScript);
2743
- } catch (error) {
2744
- this.emitFailed(swap, error);
2745
- return;
2746
- }
2747
- return this.claimIfFunded(swap, vtxos);
2748
- }
2749
- if (now < swap.refundLocktime + REFUND_MTP_LAG_SECONDS) {
2750
- if (swap.claimTxid) return;
2751
- return this.block(
2752
- swap,
2753
- "the claim window closed with the lockup unclaimed \u2014 only the solver can act now"
2754
- );
2755
- }
2756
- const failure = swap.claimFailure;
2757
- if (failure && !swap.claimTxid) {
2758
- return this.fail(swap, new Error(failure));
2759
- }
2760
- this.setState(swap, "refunded");
2761
- }
2762
- /**
2763
- * Claim what the solver funded, once it is enough.
2764
- *
2765
- * The value gate here decides WHEN to act. `pushClaim`'s decides whether
2766
- * `P` is published, and runs with nothing between it and the signature —
2767
- * the check that matters is the inner one, and this is not a reason to
2768
- * relax it.
2769
- */
2770
- async claimIfFunded(swap, vtxos) {
2771
- if (vtxos.length === 0) return this.unblock(swap);
2772
- const partiallyClaimed = swap.claimTxid !== void 0;
2773
- if (partiallyClaimed && !this.hasUnclaimedOutpoint(swap.rfqId, vtxos)) {
2774
- return;
2775
- }
2776
- if (!partiallyClaimed) {
2777
- if (!Number.isFinite(swap.expectedAmount)) {
2778
- return this.block(
2779
- swap,
2780
- `expectedAmount is not a finite number (${String(swap.expectedAmount)}), so the funded value cannot be checked \u2014 refusing to publish the preimage`
2781
- );
2782
- }
2783
- const locked = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
2784
- if (!Number.isFinite(locked) || locked < swap.expectedAmount) {
2785
- return this.block(
2786
- swap,
2787
- `lockup holds ${locked} sats, below the agreed ${swap.expectedAmount} \u2014 refusing to publish the preimage`
2788
- );
2789
- }
2790
- }
2791
- if (!this.callbacks || !this.callbacks.claimLockup) {
2792
- return this.block(
2793
- swap,
2794
- this.callbacks ? RFQ_CONFIGURATION_REFUSAL.noClaimLockupCallback : RFQ_CONFIGURATION_REFUSAL.noCallbacksForClaim
2795
- );
2796
- }
2797
- this.setState(swap, "claimable");
2798
- if (!this.config.enableAutoActions) return;
2799
- try {
2800
- const { txid } = await this.callbacks.claimLockup(swap, vtxos, { partiallyClaimed });
2801
- delete swap.claimFailure;
2802
- this.rememberClaimed(swap.rfqId, vtxos);
2803
- swap.claimTxid = txid;
2804
- this.touch(swap);
2805
- this.setState(swap, "claimed");
2806
- this.emitAction(swap, "claimLockup");
2807
- } catch (error) {
2808
- swap.claimFailure = errorMessage(error);
2809
- this.touch(swap);
2810
- this.emitFailed(swap, error);
2811
- }
2812
- }
2813
- /** `handled` ends the pass; `continue` falls through to the refund gate. */
2814
- async driveOnchain(swap) {
2815
- if (!this.deps.chain) {
2816
- this.fail(
2817
- swap,
2818
- new Error(
2819
- "onchain-send swap monitored without a ChainSource \u2014 the L1 fill cannot be seen or claimed"
2820
- )
2821
- );
2822
- return "handled";
2823
- }
2824
- let phase;
2825
- try {
2826
- phase = await classifyOnchainHtlc(this.deps.chain, {
2827
- htlc: swap.htlc,
2828
- minConfirmations: swap.minConfirmations,
2829
- funding: swap.funding
2830
- });
2831
- } catch {
2832
- return "continue";
2833
- }
2834
- if ("utxo" in phase && !swap.funding) {
2835
- swap.funding = { txid: phase.utxo.txid, vout: phase.utxo.vout };
2836
- this.touch(swap);
2837
- }
2838
- const action = nextOnchainAction({
2839
- phase,
2840
- htlcLocktime: swap.htlc.refundLocktime,
2841
- now: this.config.now()
2842
- });
2843
- if (action === "claim" && phase.phase === "claimable") {
2844
- if (swap.claimTxid) return "continue";
2845
- if (this.callbacks && !this.callbacks.claimOnchain) {
2846
- this.block(swap, RFQ_CONFIGURATION_REFUSAL.noClaimOnchainCallback);
2847
- return "handled";
2848
- }
2849
- this.setOnchainState(swap, "claimable");
2850
- if (!this.config.enableAutoActions || !this.callbacks?.claimOnchain) return "handled";
2851
- try {
2852
- const { txid } = await this.callbacks.claimOnchain(swap, phase.utxo);
2853
- swap.claimTxid = txid;
2854
- this.setOnchainState(swap, "claimed");
2855
- this.emitAction(swap, "claimOnchain");
2856
- } catch (error) {
2857
- this.emitFailed(swap, error);
2858
- }
2859
- return "handled";
2860
- }
2861
- if (action === "claimed" && phase.phase === "claimed") {
2862
- if (!swap.claimTxid) {
2863
- swap.claimTxid = phase.txid;
2864
- this.touch(swap);
2865
- }
2866
- this.setOnchainState(swap, "claimed");
2867
- }
2868
- return "continue";
2869
- }
2870
- async driveArkadeRefund(swap) {
2871
- const now = this.config.now();
2872
- const refusal = await this.probeRefusal(swap);
2873
- if (refusal) {
2874
- const claiming = swap.state === "claimable" || swap.state === "claimed";
2875
- if (now < swap.refundLocktime && claiming) return;
2876
- return this.block(swap, refusal);
2877
- }
2878
- if (this.refundRefused.has(swap.rfqId)) {
2879
- if (!this.callbacks?.canRefundArkade) return;
2880
- this.refundRefused.delete(swap.rfqId);
2881
- }
2882
- if (now < swap.refundLocktime) return this.unblock(swap);
2883
- if (!this.config.enableAutoActions || !this.callbacks) {
2884
- return this.block(
2885
- swap,
2886
- this.callbacks ? RFQ_CONFIGURATION_REFUSAL.autoActionsDisabled : RFQ_CONFIGURATION_REFUSAL.noCallbacksForRefund
2887
- );
2888
- }
2889
- this.unblock(swap);
2890
- try {
2891
- const pushed = await this.callbacks.refundArkade(swap);
2892
- if (pushed) {
2893
- swap.refundTxid = pushed.txid;
2894
- this.touch(swap);
2895
- }
2896
- this.setState(swap, "refunded");
2897
- this.emitAction(swap, "refundArkade");
2898
- } catch (error) {
2899
- if (error instanceof RefundNotLocallyPossibleError) {
2900
- this.refundRefused.add(swap.rfqId);
2901
- return this.block(swap, error.message);
2902
- }
2903
- this.emitFailed(swap, error);
2904
- if (now >= swap.refundLocktime + REFUND_MTP_LAG_SECONDS) {
2905
- swap.failure = errorMessage(error);
2906
- this.setState(swap, "failed");
2907
- }
2908
- }
2909
- }
2910
- /** Whether any of these outputs has never been handed to the claim
2911
- * callback — the only reason to claim a lockup a second time. */
2912
- hasUnclaimedOutpoint(rfqId, vtxos) {
2913
- const claimed = this.claimedOutpoints.get(rfqId);
2914
- if (!claimed) return true;
2915
- return vtxos.some((vtxo) => !claimed.has(outpointKey(vtxo)));
2916
- }
2917
- rememberClaimed(rfqId, vtxos) {
2918
- const claimed = this.claimedOutpoints.get(rfqId) ?? /* @__PURE__ */ new Set();
2919
- for (const vtxo of vtxos) claimed.add(outpointKey(vtxo));
2920
- this.claimedOutpoints.set(rfqId, claimed);
2921
- }
2922
- /**
2923
- * L1 progress, which past the refund window must not overwrite a refusal.
2924
- * The two halves are independent — a claimed fill says nothing about
2925
- * whether this wallet can take the Arkade lockup back — and `claimed` is
2926
- * re-asserted from chain on every pass, so without this a blocked swap
2927
- * would flip between the two states forever. The claim itself always runs;
2928
- * only the label defers, and only once the refund is the live half.
2929
- */
2930
- setOnchainState(swap, state) {
2931
- if (swap.state === "needs_counterparty" && this.config.now() >= swap.refundLocktime) return;
2932
- this.setState(swap, state);
2933
- }
2934
- /** The probe's refusal reason, or `undefined` when a local refund is
2935
- * possible as far as anyone here can tell. A probe that throws is treated
2936
- * as a refusal: a capability check that cannot answer is not a yes. */
2937
- async probeRefusal(swap) {
2938
- const probe = this.callbacks?.canRefundArkade;
2939
- if (!probe) return void 0;
2940
- try {
2941
- const answer = await probe(swap);
2942
- return answer.ok ? void 0 : answer.reason;
2943
- } catch (error) {
2944
- return errorMessage(error);
2945
- }
2946
- }
2947
- /** Report that no local refund will happen, without ending the swap. */
2948
- block(swap, reason) {
2949
- if (swap.blockedReason !== reason) {
2950
- swap.blockedReason = reason;
2951
- this.touch(swap);
2952
- }
2953
- this.setState(swap, "needs_counterparty");
2954
- }
2955
- /** The way back out, taken as soon as the swap becomes actionable again.
2956
- * Back to what the record can prove, not to `pending` unconditionally: a
2957
- * swap that already made its claim has a txid for it, and reporting that
2958
- * swap as `pending` would un-say something true. */
2959
- unblock(swap) {
2960
- if (swap.state !== "needs_counterparty") return;
2961
- this.setState(swap, traderClaimTxid(swap) ? "claimed" : "pending");
2962
- }
2963
- /**
2964
- * Record which ark transactions ended the lockup.
2965
- *
2966
- * Only the ones the indexer actually named: `LockupSpend.txid` is
2967
- * optional, and a checkpoint txid is not what history correlates on — a
2968
- * record carrying one would name a transaction the wallet's own activity
2969
- * never shows. Fewer txids is the right failure here.
2970
- *
2971
- * Assigned rather than merged: the fate is one read of the whole lockup,
2972
- * so it is the complete answer for this swap, and a swap only reaches a
2973
- * verdict once.
2974
- */
2975
- stampLockupSpends(swap, spends) {
2976
- const txids = spends.map((spend) => spend.txid).filter((txid) => txid !== void 0);
2977
- if (txids.length === 0) return;
2978
- swap.lockupSpendTxids = txids;
2979
- this.touch(swap);
2980
- }
2981
- /**
2982
- * Keep the preimage that settled a Lightning send.
2983
- *
2984
- * Only that leg. A receive's `claimed` verdict reveals the wallet's own
2985
- * claim secret and an onchain send's reveals the one it minted — both
2986
- * already recoverable from `profile`, so stamping either would be a second
2987
- * home for a secret that has one.
2988
- */
2989
- stampSettlementPreimage(swap, preimage) {
2990
- if (swap.kind !== "lightning_send") return;
2991
- swap.settlementPreimageHex = hex8.encode(preimage);
2992
- this.touch(swap);
2993
- }
2994
- touch(swap) {
2995
- swap.updatedAt = this.config.now();
2996
- this.dirty.add(swap.rfqId);
2997
- }
2998
- setState(swap, state) {
2999
- if (swap.state === state) return;
3000
- const previous = swap.state;
3001
- if (previous === "needs_counterparty") delete swap.blockedReason;
3002
- if (isRfqSwapTerminal(state)) delete swap.claimFailure;
3003
- swap.state = state;
3004
- this.touch(swap);
3005
- notify(this.swapUpdateListeners, (listener) => listener(swap, previous));
3006
- }
3007
- /** Terminal failure. The `onSwapFailed` emission is left to
3008
- * {@link finalize}, so this does not double-report. */
3009
- fail(swap, error) {
3010
- swap.failure = error.message;
3011
- this.setState(swap, "failed");
3012
- }
3013
- emitFailed(swap, error) {
3014
- const wrapped = error instanceof Error ? error : new Error(errorMessage(error));
3015
- notify(this.swapFailedListeners, (listener) => listener(swap, wrapped));
3016
- }
3017
- emitAction(swap, action) {
3018
- notify(this.actionExecutedListeners, (listener) => listener(swap, action));
3019
- }
3020
- /**
3021
- * Flush a changed record to every sink that is wired, and say whether all
3022
- * of them took it.
3023
- *
3024
- * Up to two writes, in this order: the canonical `RfqSwapRecord` to
3025
- * {@link RfqSwapManagerDeps.repository}, then
3026
- * {@link RfqSwapManagerCallbacks.saveSwap}. Both gate — a rejection from
3027
- * either leaves the record dirty and monitored, so waiters stay unsettled
3028
- * and a terminal swap is not finalized until the write it claims lands.
3029
- * That is exactly today's rule for `saveSwap`, applied to whichever sinks
3030
- * exist; wiring the repository does not weaken it.
3031
- *
3032
- * The canonical write goes FIRST and a failure there skips the second.
3033
- * `saveSwap` is a projection of the record, and projecting a state the
3034
- * record of record has just refused would leave the secondary sink ahead
3035
- * of the primary — the one ordering that survives no restart.
3036
- *
3037
- * With neither wired the state is process-local, which is what a manager
3038
- * with no callbacks has always done.
3039
- */
3040
- async save(swap) {
3041
- if (!await this.saveRecord(swap)) return false;
3042
- if (!this.callbacks?.saveSwap) return true;
3043
- try {
3044
- await this.callbacks.saveSwap(swap);
3045
- return true;
3046
- } catch (error) {
3047
- this.emitFailed(swap, error);
3048
- return false;
3049
- }
3050
- }
3051
- /** The canonical write. True when there is no repository to write to. */
3052
- async saveRecord(swap) {
3053
- const repository = this.deps.repository;
3054
- if (!repository) return true;
3055
- try {
3056
- const stored = await repository.getRfqSwap(swap.rfqId);
3057
- const record = stored ? updateRfqSwapRecord(stored, swap) : createRfqSwapRecord(this.originOrThrow(swap), swap);
3058
- await repository.saveRfqSwap(record);
3059
- return true;
3060
- } catch (error) {
3061
- this.emitFailed(swap, error);
3062
- return false;
3063
- }
3064
- }
3065
- originOrThrow(swap) {
3066
- const origin = this.origins.get(swap.rfqId);
3067
- if (!origin) throw new RfqSwapOriginRequired(swap.rfqId);
3068
- return origin;
3069
- }
3070
- /**
3071
- * Drop a terminal swap from monitoring and report it exactly once.
3072
- *
3073
- * `onSwapCompleted` and `onSwapFailed` are mutually exclusive here: a
3074
- * listener named "completed" that also fires on failure is a trap, so a
3075
- * swap that leaves monitoring reports through exactly one of them.
3076
- */
3077
- finalize(swap) {
3078
- if (!this.monitored.has(swap.rfqId)) return;
3079
- this.untrack(swap.rfqId);
3080
- this.finished.set(swap.rfqId, swap);
3081
- this.retireContract(swap);
3082
- if (swap.state === "failed") {
3083
- notify(
3084
- this.swapFailedListeners,
3085
- (listener) => listener(swap, new Error(swap.failure ?? `swap ${swap.rfqId} failed`))
3086
- );
3087
- return;
3088
- }
3089
- notify(this.swapCompletedListeners, (listener) => listener(swap));
3090
- }
3091
- settleWaiters(swap) {
3092
- const waiting = this.waiters.get(swap.rfqId);
3093
- if (!waiting) return;
3094
- if (swap.state === "failed") {
3095
- const error = new Error(swap.failure ?? `swap ${swap.rfqId} failed`);
3096
- for (const waiter of waiting) waiter.reject(error);
3097
- } else if (isPayoutDecided(swap)) {
3098
- const outcome = outcomeOf(swap);
3099
- for (const waiter of waiting) waiter.resolve(outcome);
3100
- } else {
3101
- return;
3102
- }
3103
- this.waiters.delete(swap.rfqId);
3104
- }
3105
- };
3106
- var traderClaimTxid = (swap) => {
3107
- switch (swap.kind) {
3108
- case "onchain_send":
3109
- return swap.claimTxid;
3110
- case "lightning_receive":
3111
- return swap.claimTxid;
3112
- default:
3113
- return void 0;
3114
- }
3115
- };
3116
- var isPayoutDecided = (swap) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0;
3117
- var outcomeOf = (swap) => {
3118
- const lostReceive = swap.kind === "lightning_receive" && swap.state === "refunded";
3119
- return {
3120
- state: swap.state,
3121
- txid: lostReceive ? swap.refundTxid : traderClaimTxid(swap) ?? swap.refundTxid
3122
- };
3123
- };
3124
- var errorMessage = (error) => error instanceof Error ? error.message : String(error);
3125
- var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
3126
-
3127
- // src/watch.ts
3128
- import { base64 as base643, hex as hex9 } from "@scure/base";
3129
- import {
3130
- ArkAddress as ArkAddress3,
3131
- isContractVtxoEvent as isContractVtxoEvent2,
3132
- Transaction as Transaction3
3133
- } from "@arkade-os/sdk";
3134
- var TERMINAL = ["fulfilled", "cancelled", "recoverable"];
3135
- var assetSwapSource = (repository) => ({
3136
- list: () => getAssetSwaps(repository),
3137
- apply: async (swap, changes) => updateAssetSwapBestEffort(repository, swap.id, changes)
3138
- });
3139
- function spendUpdate(swap, spend) {
3140
- if (TERMINAL.includes(swap.status)) return void 0;
3141
- if (spend.kind === "indeterminate") return void 0;
3142
- const status = spend.kind === "cancelled" ? "cancelled" : "fulfilled";
3143
- return {
3144
- status,
3145
- spentTxid: spend.txid,
3146
- // mirrors restore.ts: a completion time is a fill's, not a cancel's
3147
- ...status === "fulfilled" && spend.at ? { completedAt: spend.at } : {}
3148
- };
3149
- }
3150
- async function watchOfferSwaps({
3151
- wallet,
3152
- repository,
3153
- source,
3154
- onUpdate
3155
- }) {
3156
- if (!source && !repository) {
3157
- throw new Error("watchOfferSwaps needs either a record source or a repository");
3158
- }
3159
- const records = source ?? assetSwapSource(repository);
3160
- const [manager, address, indexer] = await Promise.all([
3161
- wallet.getContractManager(),
3162
- wallet.getAddress(),
3163
- wallet.getArkadeReader()
3164
- ]);
3165
- const operatorPubkey = ArkAddress3.decode(address).serverPubKey;
3166
- let queue = Promise.resolve();
3167
- const enqueue = (task) => {
3168
- queue = queue.then(task).catch(() => {
3169
- });
3170
- };
3171
- const classify = async (swap, vtxo, spentTxid) => {
3172
- if (swap.spentTxid === spentTxid && swap.status === "cancelling") return "cancelled";
3173
- try {
3174
- const candidates = spendTxidsOf(vtxo);
3175
- if (candidates.length === 0) return "indeterminate";
3176
- const { txs } = await indexer.getVirtualTxs(candidates);
3177
- return classifyDepositSpend(
3178
- decodeOffer(hex9.decode(swap.offerHex)),
3179
- operatorPubkey,
3180
- txs.map((psbt) => Transaction3.fromPSBT(base643.decode(psbt))),
3181
- { txid: vtxo.txid, vout: vtxo.vout }
3182
- );
3183
- } catch {
3184
- return "indeterminate";
3185
- }
3186
- };
3187
- const handleSpend = async (event) => {
3188
- if (event.contract.metadata?.kind !== OFFER_CONTRACT_KIND) return;
3189
- for (const vtxo of event.vtxos) {
3190
- const spentTxid = vtxo.arkTxId || vtxo.spentBy;
3191
- if (!spentTxid) continue;
3192
- const swap = (await records.list()).find(
3193
- (s) => s.fundingTxid === vtxo.txid && s.swapPkScript === event.contractScript
3194
- );
3195
- if (!swap) continue;
3196
- const kind = await classify(swap, vtxo, spentTxid);
3197
- const changes = spendUpdate(swap, { txid: spentTxid, kind, at: event.timestamp });
3198
- if (!changes) continue;
3199
- const { persisted, swaps } = await records.apply(swap, changes);
3200
- if (!persisted) continue;
3201
- onUpdate?.(swaps.find((s) => s.id === swap.id) ?? swap);
3202
- if (changes.status && RETIRABLE.includes(changes.status)) {
3203
- await retireOfferContract(manager, swaps, event.contractScript);
3204
- }
3205
- }
3206
- };
3207
- const unsubscribe = manager.onContractEvent((event) => {
3208
- if (!isContractVtxoEvent2(event) || event.type !== "vtxo_spent") return;
3209
- enqueue(() => handleSpend(event));
3210
- });
3211
- return {
3212
- stop: unsubscribe,
3213
- idle: () => queue
3214
- };
3215
- }
3216
-
3217
- export {
3218
- RETIRABLE,
3219
- retireOfferContract,
3220
- retireSettledOfferContracts,
3221
- BTC_ASSET_ID,
3222
- getAssetSwapsOrThrow,
3223
- getAssetSwaps,
3224
- addAssetSwap,
3225
- updateAssetSwap,
3226
- swapSecretsToRecord,
3227
- PreimageNotRecoverableError,
3228
- preimageForSwapRecord,
3229
- swapPrograms,
3230
- offerContract,
3231
- OFFER_PACKET_TYPE,
3232
- encodeOffer,
3233
- decodeOffer,
3234
- restoreOfferCoverage,
3235
- createOffer,
3236
- cancelOffer,
3237
- NoSpendableDepositError,
3238
- OfferCovenantMismatchError,
3239
- prepareOfferCancel,
3240
- rfqCorridorHandlers,
3241
- rfqSecretsProfile,
3242
- rfqSignerOf,
3243
- rfqClaimSecretOf,
3244
- rfqClaimDestinationOf,
3245
- onchainSendProfile,
3246
- INVOICE_HRPS,
3247
- networksOfInvoiceHrp,
3248
- LIGHTNING_DRIVE,
3249
- lightningCorridor,
3250
- ONCHAIN_DRIVE,
3251
- onchainCorridor,
3252
- CORRIDOR_PASS,
3253
- LOCKUP_OWNER,
3254
- readsChain,
3255
- corridorOutcome,
3256
- offerOutcome,
3257
- recordOutcome,
3258
- ACTIVITY_TOKEN,
3259
- isRfqTerminal,
3260
- awaitRfqResolution,
3261
- walletOperator,
3262
- LockupNeedsRecoveryError,
3263
- findLockupVtxos,
3264
- readLockupFate,
3265
- pushRefundWithoutReceiver,
3266
- refundIfUnresolved,
3267
- QUOTE_OPTIONS,
3268
- makeCachedFeedFetch,
3269
- MARKETS_CACHE_TTL_MS,
3270
- discoverMarkets,
3271
- findMarket,
3272
- validatePlan,
3273
- classifySpend,
3274
- spendTxidsOf,
3275
- classifyDepositSpend,
3276
- restoreAssetSwaps,
3277
- LockupAmountMismatchError,
3278
- pushClaim,
3279
- awaitLockupFunding,
3280
- claimReceiveLockup,
3281
- RefundNotLocallyPossibleError,
3282
- senderIdentityForSwapRecord,
3283
- arkadeRefunder,
3284
- isRfqSwapTerminal,
3285
- RFQ_SWAP_RETENTION_SECONDS,
3286
- normalizeRfqSwapRecord,
3287
- createRfqSwapRecord,
3288
- updateRfqSwapRecord,
3289
- rfqSwapOriginOf,
3290
- rebuildRfqSwap,
3291
- shouldRetainRfqSwap,
3292
- nextOnchainAction,
3293
- isRfqConfigurationRefusal,
3294
- RfqSwapOriginRequired,
3295
- RfqSwapManager,
3296
- watchOfferSwaps
3297
- };