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