@arkade-os/swap 0.1.0-rc.2 → 0.1.0-rc.21

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 (54) hide show
  1. package/README.md +52 -2
  2. package/dist/advanced.cjs +8376 -0
  3. package/dist/advanced.d.cts +550 -0
  4. package/dist/advanced.d.ts +550 -0
  5. package/dist/advanced.js +451 -0
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-HUQQVBC4.js +4262 -0
  8. package/dist/{chunk-EOYGUCDM.js → chunk-ITFCQWPG.js} +755 -1382
  9. package/dist/chunk-PVB7EBAM.js +2517 -0
  10. package/dist/errors-C3h8ANmE.d.ts +1560 -0
  11. package/dist/errors-hm7aqnRM.d.cts +1560 -0
  12. package/dist/index.cjs +4861 -3988
  13. package/dist/index.d.cts +69 -2812
  14. package/dist/index.d.ts +69 -2812
  15. package/dist/index.js +179 -3719
  16. package/dist/lockupContract-5r5RlgOJ.d.cts +137 -0
  17. package/dist/lockupContract-5r5RlgOJ.d.ts +137 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +249 -591
  20. package/dist/node/index.d.ts +249 -591
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +191 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer-Bd9Yvd8Z.d.ts +261 -0
  27. package/dist/offer-F88rtL_I.d.cts +261 -0
  28. package/dist/protocol.cjs +4086 -3706
  29. package/dist/protocol.d.cts +163 -768
  30. package/dist/protocol.d.ts +163 -768
  31. package/dist/protocol.js +190 -173
  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-BuYWGAKz.d.cts +2261 -0
  41. package/dist/repository-DYnRLPt-.d.ts +2261 -0
  42. package/dist/rfq-60PGpQ_x.d.cts +950 -0
  43. package/dist/rfq-60PGpQ_x.d.ts +950 -0
  44. package/dist/watch-BTyiBLSd.d.ts +74 -0
  45. package/dist/watch-M_KY-5ho.d.cts +74 -0
  46. package/package.json +20 -10
  47. package/dist/chunk-LYCMM3VB.js +0 -1357
  48. package/dist/chunk-U7VWWTL6.js +0 -66
  49. package/dist/repository-_zU9_pM3.d.cts +0 -3426
  50. package/dist/repository-kO95noyv.d.ts +0 -3426
  51. package/dist/rfq-DdBV4JO5.d.cts +0 -1097
  52. package/dist/rfq-DdBV4JO5.d.ts +0 -1097
  53. package/dist/watch-CQqvwgwY.d.cts +0 -96
  54. package/dist/watch-wMbmfN4p.d.ts +0 -96
@@ -1,653 +1,32 @@
1
1
  import {
2
+ BTC_ASSET_ID,
2
3
  L1_NETWORKS,
4
+ LOCKUP_RETIRABLE,
5
+ OFFER_CONTRACT_KIND,
6
+ OFFER_PACKET_TYPE,
3
7
  ONCHAIN_CLAIM_MARGIN_SECONDS,
8
+ PreimageNotRecoverableError,
9
+ RETIRABLE,
4
10
  RFQ_TERMINAL_STATES,
11
+ assertPreimageMatches,
5
12
  classifyOnchainHtlc,
13
+ decodeOffer,
14
+ gateError,
15
+ getAssetSwaps,
6
16
  l1NetworkFromArk,
7
17
  lockupContractParams,
18
+ offerContract,
8
19
  onchainHtlcScript,
9
- registerLockupContract
10
- } from "./chunk-LYCMM3VB.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";
20
+ pollUntil,
21
+ registerLockupContract,
22
+ retireOfferContract,
23
+ sleep,
24
+ swapSecretsToRecord,
25
+ updateAssetSwapBestEffort
26
+ } from "./chunk-PVB7EBAM.js";
129
27
  import {
130
- ArkAddress,
131
- arkade,
132
- asset,
133
- networkFromArkadeInfo,
134
- resolveEmulatorPubkey,
135
- toXOnlySignerHex
136
- } from "@arkade-os/sdk";
137
-
138
- // src/swap-want-asset.program.json
139
- var swap_want_asset_program_default = {
140
- version: 0,
141
- name: "banco-btc-to-asset",
142
- params: [
143
- { name: "makerWP", type: "pubkey" },
144
- { name: "wantAmount", type: "int" },
145
- { name: "wantAssetTxid", type: "hash" },
146
- { name: "wantAssetGroupIndex", type: "int" },
147
- { name: "server", type: "pubkey" },
148
- { name: "user", type: "pubkey" }
149
- ],
150
- functions: {
151
- fulfill: {
152
- tapscript: { signers: ["$server"] },
153
- arkadeScript: {
154
- asm: [
155
- 0,
156
- "$wantAssetTxid",
157
- "$wantAssetGroupIndex",
158
- "INSPECTOUTASSETLOOKUP",
159
- "VERIFY",
160
- "$wantAmount",
161
- "GREATERTHANOREQUAL",
162
- "VERIFY",
163
- 0,
164
- "INSPECTOUTPUTSCRIPTPUBKEY",
165
- 1,
166
- "EQUALVERIFY",
167
- "$makerWP",
168
- "EQUAL"
169
- ]
170
- }
171
- },
172
- cancel: {
173
- tapscript: { signers: ["$user", "$server"] }
174
- }
175
- }
176
- };
177
-
178
- // src/swap-want-btc.program.json
179
- var swap_want_btc_program_default = {
180
- version: 0,
181
- name: "banco-asset-to-btc",
182
- params: [
183
- { name: "makerWP", type: "pubkey" },
184
- { name: "wantAmount", type: "int" },
185
- { name: "server", type: "pubkey" },
186
- { name: "user", type: "pubkey" }
187
- ],
188
- functions: {
189
- fulfill: {
190
- tapscript: { signers: ["$server"] },
191
- arkadeScript: {
192
- asm: [
193
- 0,
194
- "INSPECTOUTPUTVALUE",
195
- "$wantAmount",
196
- "GREATERTHANOREQUAL",
197
- "VERIFY",
198
- 0,
199
- "INSPECTOUTPUTSCRIPTPUBKEY",
200
- 1,
201
- "EQUALVERIFY",
202
- "$makerWP",
203
- "EQUAL"
204
- ]
205
- }
206
- },
207
- cancel: {
208
- tapscript: { signers: ["$user", "$server"] }
209
- }
210
- }
211
- };
212
-
213
- // src/coverage.ts
214
- var RETIRABLE = ["fulfilled", "cancelled"];
215
- var issuedAt = /* @__PURE__ */ new Map();
216
- var inFlight = /* @__PURE__ */ new Map();
217
- async function serialize(script, task) {
218
- const previous = inFlight.get(script) ?? Promise.resolve();
219
- const result = previous.then(task, task);
220
- const settled = result.then(
221
- () => {
222
- },
223
- () => {
224
- }
225
- );
226
- inFlight.set(script, settled);
227
- void settled.then(() => {
228
- if (inFlight.get(script) === settled) inFlight.delete(script);
229
- });
230
- return result;
231
- }
232
- function addressOutstanding(swaps, script) {
233
- const issued = issuedAt.get(script);
234
- if (issued === void 0) return false;
235
- if (swaps.some((s) => s.swapPkScript === script && s.createdAt >= issued)) {
236
- issuedAt.delete(script);
237
- return false;
238
- }
239
- return true;
240
- }
241
- async function promoteOfferContract(manager, script) {
242
- await serialize(script, async () => {
243
- await manager.setContractWatchState(script, "watched");
244
- issuedAt.set(script, Date.now());
245
- });
246
- }
247
- async function retireOfferContract(manager, swaps, script) {
248
- await serialize(script, async () => {
249
- if (swaps.some((s) => s.swapPkScript === script && !RETIRABLE.includes(s.status))) return;
250
- if (addressOutstanding(swaps, script)) return;
251
- try {
252
- await manager.setContractWatchState(script, "retained");
253
- } catch (err) {
254
- console.warn(`[swap] could not retire offer contract ${script}`, err);
255
- }
256
- });
257
- }
258
- async function retireSettledOfferContracts(manager, swaps) {
259
- const settled = new Set(
260
- swaps.filter((s) => RETIRABLE.includes(s.status)).map((s) => s.swapPkScript)
261
- );
262
- for (const script of settled) await retireOfferContract(manager, swaps, script);
263
- }
264
-
265
- // src/offer.ts
266
- var swapPrograms = {
267
- wantAsset: arkade.parseArtifact(swap_want_asset_program_default),
268
- wantBtc: arkade.parseArtifact(swap_want_btc_program_default)
269
- };
270
- function withExitClosure(program, exit) {
271
- if (!exit) return program;
272
- return {
273
- ...program,
274
- // typed params are authoritative: an undeclared `$exitDelay` fails
275
- // validateProgram instead of compiling against an unbound value
276
- params: [...program.params ?? [], { name: "exitDelay", type: "int" }],
277
- functions: {
278
- ...program.functions,
279
- exit: {
280
- tapscript: { signers: ["$user"], csv: { type: exit.type, value: "$exitDelay" } }
281
- }
282
- }
283
- };
284
- }
285
- function swapProgramBinding(offer, operatorPubkey) {
286
- if (offer.makerPkScript.length !== FIELDS.makerPkScript.width) {
287
- throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
288
- }
289
- return {
290
- program: withExitClosure(
291
- offer.wantAsset ? swapPrograms.wantAsset : swapPrograms.wantBtc,
292
- offer.exitDelay
293
- ),
294
- args: {
295
- makerWP: offer.makerPkScript.subarray(2),
296
- wantAmount: offer.wantAmount,
297
- server: operatorPubkey,
298
- user: offer.makerPublicKey,
299
- // internal byte order
300
- ...offer.wantAsset && {
301
- wantAssetTxid: offer.wantAsset.txid.slice().reverse(),
302
- wantAssetGroupIndex: offer.wantAsset.groupIndex
303
- },
304
- ...offer.exitDelay && { exitDelay: offer.exitDelay.value }
305
- },
306
- keys: {
307
- serverKey: operatorPubkey,
308
- userKey: offer.makerPublicKey,
309
- emulatorKey: offer.emulatorPubkey
310
- }
311
- };
312
- }
313
- function offerContract(offer, operatorPubkey) {
314
- const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
315
- return new arkade.ArkadeProgramScript(program, args, keys);
316
- }
317
- var OFFER_PACKET_TYPE = 3;
318
- var FIELDS = {
319
- swapPkScript: { tag: 1, width: 34 },
320
- wantAmount: { tag: 2, width: 8 },
321
- wantAsset: { tag: 3, width: void 0 },
322
- makerPkScript: { tag: 5, width: 34 },
323
- makerPublicKey: { tag: 7, width: 32 },
324
- emulatorPubkey: { tag: 8, width: 32 },
325
- ratioNum: { tag: 9, width: 8 },
326
- ratioDen: { tag: 10, width: 8 },
327
- offerAsset: { tag: 11, width: void 0 },
328
- exitTimelock: { tag: 12, width: 9 }
329
- };
330
- var EXIT_TYPES = ["blocks", "seconds"];
331
- var NAMES = Object.fromEntries(Object.entries(FIELDS).map(([k, f]) => [f.tag, k]));
332
- function u64(name, value) {
333
- if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
334
- throw new Error(`${name} does not fit the offer wire format (u64)`);
335
- }
336
- const out = new Uint8Array(FIELDS.wantAmount.width);
337
- new DataView(out.buffer).setBigUint64(0, value, false);
338
- return out;
339
- }
340
- var readU64 = (value) => new DataView(value.buffer, value.byteOffset).getBigUint64(0, false);
341
- var setRatio = (name, value) => {
342
- if (value === void 0 || value === BigInt(0)) return void 0;
343
- if (value < BigInt(0)) throw new Error(`${name} does not fit the offer wire format (u64)`);
344
- return value;
345
- };
346
- function tlv(type, value) {
347
- if (value.length > 65535) throw new Error("TLV value exceeds the u16 length field");
348
- return concatBytes(Uint8Array.of(type, value.length >> 8 & 255, value.length & 255), value);
349
- }
350
- function encodeOffer(offer) {
351
- if (Boolean(offer.wantAsset) === Boolean(offer.offerAsset)) {
352
- throw new Error("offer must carry exactly one of wantAsset or offerAsset");
353
- }
354
- for (const name of [
355
- "swapPkScript",
356
- "makerPkScript",
357
- "makerPublicKey",
358
- "emulatorPubkey"
359
- ]) {
360
- if (offer[name].length !== FIELDS[name].width) {
361
- throw new Error(`${name} must be ${FIELDS[name].width} bytes`);
362
- }
363
- }
364
- const ratioNum = setRatio("ratioNum", offer.ratioNum);
365
- const ratioDen = setRatio("ratioDen", offer.ratioDen);
366
- if (ratioNum === void 0 !== (ratioDen === void 0)) {
367
- throw new Error("offer must carry both ratioNum and ratioDen, or neither");
368
- }
369
- const recs = [
370
- tlv(FIELDS.swapPkScript.tag, offer.swapPkScript),
371
- tlv(FIELDS.wantAmount.tag, u64("wantAmount", offer.wantAmount))
372
- ];
373
- if (offer.wantAsset) recs.push(tlv(FIELDS.wantAsset.tag, offer.wantAsset.serialize()));
374
- if (ratioNum !== void 0) recs.push(tlv(FIELDS.ratioNum.tag, u64("ratioNum", ratioNum)));
375
- if (ratioDen !== void 0) recs.push(tlv(FIELDS.ratioDen.tag, u64("ratioDen", ratioDen)));
376
- if (offer.offerAsset) recs.push(tlv(FIELDS.offerAsset.tag, offer.offerAsset.serialize()));
377
- recs.push(
378
- tlv(FIELDS.makerPkScript.tag, offer.makerPkScript),
379
- tlv(FIELDS.makerPublicKey.tag, offer.makerPublicKey),
380
- tlv(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey)
381
- );
382
- if (offer.exitDelay) recs.push(tlv(FIELDS.exitTimelock.tag, encodeExitDelay(offer.exitDelay)));
383
- return concatBytes(...recs);
384
- }
385
- function encodeExitDelay(exit) {
386
- return concatBytes(
387
- Uint8Array.of(EXIT_TYPES.indexOf(assertExitDelay(exit).type)),
388
- u64("exitDelay", exit.value)
389
- );
390
- }
391
- function assertExitDelay(exit) {
392
- if (EXIT_TYPES.indexOf(exit.type) < 0) {
393
- throw new Error(`unknown exitDelay locktime type: ${exit.type}`);
394
- }
395
- if (exit.value <= BigInt(0)) {
396
- throw new Error("exitDelay must be a positive relative locktime");
397
- }
398
- if (exit.value >> BigInt(32) > BigInt(0)) {
399
- throw new Error("exitDelay does not fit the locktime field (u32)");
400
- }
401
- return exit;
402
- }
403
- function decodeOffer(data) {
404
- const fields = {};
405
- let off = 0;
406
- while (off < data.length) {
407
- if (off + 3 > data.length) throw new Error("truncated TLV header");
408
- const type = data[off];
409
- const length = data[off + 1] << 8 | data[off + 2];
410
- off += 3;
411
- if (off + length > data.length)
412
- throw new Error(`truncated TLV value for type 0x${type.toString(16)}`);
413
- const name = NAMES[type];
414
- if (!name) throw new Error(`unknown TLV type: 0x${type.toString(16)}`);
415
- if (fields[name] !== void 0) throw new Error(`duplicate TLV record: ${name}`);
416
- fields[name] = data.slice(off, off + length);
417
- off += length;
418
- }
419
- for (const name of ["wantAsset", "offerAsset"]) {
420
- if (fields[name]?.length === 0) throw new Error(`missing/invalid ${name}`);
421
- }
422
- for (const [name, value] of Object.entries(fields)) {
423
- const width = FIELDS[name].width;
424
- if (width !== void 0 && value.length !== width) {
425
- throw new Error(`missing/invalid ${name}`);
426
- }
427
- }
428
- const need = (name) => {
429
- const v = fields[name];
430
- const len = FIELDS[name].width;
431
- if (!v || len !== void 0 && v.length !== len)
432
- throw new Error(`missing/invalid ${name}`);
433
- return v;
434
- };
435
- const amount = need("wantAmount");
436
- if (Boolean(fields.wantAsset) === Boolean(fields.offerAsset)) {
437
- throw new Error("offer must carry exactly one of wantAsset or offerAsset");
438
- }
439
- const readRatio = (name) => {
440
- const raw = fields[name];
441
- if (!raw) return void 0;
442
- const value = readU64(raw);
443
- if (value === BigInt(0)) throw new Error(`missing/invalid ${name}`);
444
- return value;
445
- };
446
- const ratioNum = readRatio("ratioNum");
447
- const ratioDen = readRatio("ratioDen");
448
- if (ratioNum === void 0 !== (ratioDen === void 0)) {
449
- throw new Error("offer must carry both ratioNum and ratioDen, or neither");
450
- }
451
- return {
452
- swapPkScript: need("swapPkScript"),
453
- wantAmount: readU64(amount),
454
- ...fields.wantAsset && { wantAsset: asset.AssetId.fromBytes(fields.wantAsset) },
455
- ...fields.offerAsset && { offerAsset: asset.AssetId.fromBytes(fields.offerAsset) },
456
- makerPkScript: need("makerPkScript"),
457
- makerPublicKey: need("makerPublicKey"),
458
- emulatorPubkey: need("emulatorPubkey"),
459
- ...ratioNum !== void 0 && { ratioNum },
460
- ...ratioDen !== void 0 && { ratioDen },
461
- ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) }
462
- };
463
- }
464
- function decodeExitDelay(value) {
465
- const type = EXIT_TYPES[value[0]];
466
- if (!type) throw new Error(`unknown exitDelay locktime type: 0x${value[0].toString(16)}`);
467
- return { type, value: readU64(value.subarray(1)) };
468
- }
469
- var OFFER_CONTRACT_LABEL = "Arkade swap offer";
470
- var OFFER_CONTRACT_KIND = "asset-swap-offer";
471
- async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
472
- const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
473
- const contractManager = await wallet.getContractManager();
474
- const client = await arkade.Arkade.connect({
475
- // Registration derives and persists; it never broadcasts and never
476
- // reads UTXOs, so the only thing the client needs off the server is the
477
- // info the caller already resolved. Handing that back — rather than a
478
- // provider built from a URL — is what lets `createOffer` take just a
479
- // wallet, and spares a second `/v1/info` round-trip.
480
- arkade: { getInfo: async () => info },
481
- identity: wallet.identity,
482
- // without this the row's `address` would be derived against the SDK's
483
- // default network while its script is right — a row that disagrees with
484
- // the address the user is about to fund
485
- network: networkFromArkadeInfo(info),
486
- contractManager
487
- });
488
- const contract = new arkade.ArkadeContract(client, program, args, keys);
489
- if (hex2.encode(contract.pkScript) !== hex2.encode(expectedPkScript)) {
490
- throw new Error("derived covenant does not match the offer's swapPkScript");
491
- }
492
- await contract.register({
493
- label: OFFER_CONTRACT_LABEL,
494
- metadata: { genericallySpendable: false, kind: OFFER_CONTRACT_KIND }
495
- });
496
- await promoteOfferContract(contractManager, hex2.encode(expectedPkScript));
497
- }
498
- function serverExitDelay(delay) {
499
- if (typeof delay !== "bigint" || delay <= BigInt(0)) {
500
- throw new Error(
501
- "the server reports no usable unilateralExitDelay; pass `exitDelay` to set the offer's exit closure explicitly, or `noExit: true` to publish without one"
502
- );
503
- }
504
- return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
505
- }
506
- async function createOffer(wallet, params) {
507
- if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
508
- throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
509
- }
510
- const [info, makerAddress, makerPublicKey] = await Promise.all([
511
- // requireLive: this info binds signerPubkey into the covenant — a
512
- // snapshot could derive an address the operator no longer co-signs
513
- // for, so an unreachable operator fails the call instead (fail closed,
514
- // the same behaviour the pre-#734 caller-held provider had)
515
- wallet.getArkadeInfo({ requireLive: true }),
516
- wallet.getAddress(),
517
- wallet.identity.xOnlyPublicKey()
518
- ]);
519
- const operatorPubKey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
520
- const network = networkFromArkadeInfo(info);
521
- const emuKey = hex2.decode(
522
- toXOnlySignerHex(resolveEmulatorPubkey(network, params.emulatorPubkey))
523
- );
524
- const binding = {
525
- wantAmount: params.wantAmount,
526
- wantAsset: params.wantAsset,
527
- offerAsset: params.offerAsset,
528
- makerPkScript: ArkAddress.decode(makerAddress).pkScript,
529
- makerPublicKey,
530
- emulatorPubkey: emuKey,
531
- // checked HERE, before the covenant is derived and registered below:
532
- // deferring it to `encodeOffer` leaves a registered contract behind for
533
- // an offer that then fails to encode. @see assertExitDelay
534
- exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
535
- };
536
- const script = offerContract(binding, operatorPubKey);
537
- const offer = { ...binding, swapPkScript: script.pkScript };
538
- await registerOfferContract(wallet, info, binding, operatorPubKey, script.pkScript);
539
- const payload = encodeOffer(offer);
540
- return {
541
- offerHex: hex2.encode(payload),
542
- extension: { type: OFFER_PACKET_TYPE, payload },
543
- // the contract's .address() builds the address; assembling an ArkAddress
544
- // from tweakedPublicKey here would silently miss any future step it gains
545
- address: script.address(network.hrp, operatorPubKey).encode(),
546
- swapPkScript: script.pkScript
547
- };
548
- }
549
- async function cancelOffer(wallet, offerHex, opts) {
550
- const { repository, fundingTxid, swapAddress } = opts;
551
- const prepared = await prepareOfferCancel(wallet, offerHex, {
552
- ...fundingTxid === void 0 ? {} : { fundingTxid },
553
- ...swapAddress === void 0 ? {} : { swapAddress }
554
- });
555
- const swapId = fundingTxid ?? prepared.vtxo.txid;
556
- const hasLocalRecord = (await getAssetSwapsOrThrow(repository)).some((s) => s.id === swapId);
557
- if (hasLocalRecord) await updateAssetSwap(repository, swapId, { status: "cancelling" });
558
- const txid = await prepared.send();
559
- if (hasLocalRecord) {
560
- const { persisted, swaps } = await updateAssetSwapBestEffort(repository, swapId, {
561
- status: "cancelled",
562
- spentTxid: txid
563
- });
564
- if (persisted) {
565
- const contractManager = await wallet.getContractManager();
566
- await retireOfferContract(
567
- contractManager,
568
- swaps,
569
- hex2.encode(prepared.offer.swapPkScript)
570
- );
571
- }
572
- }
573
- return txid;
574
- }
575
- var OFFER_COVENANT_MISMATCH = "rebuilt covenant does not match the offer's swapPkScript";
576
- var NoSpendableDepositError = class extends Error {
577
- name = "NoSpendableDepositError";
578
- constructor(options) {
579
- super("no spendable VTXO at the swap address", options);
580
- }
581
- };
582
- var OfferCovenantMismatchError = class extends Error {
583
- constructor(swapPkScript, options) {
584
- super(
585
- `${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`,
586
- options
587
- );
588
- this.swapPkScript = swapPkScript;
589
- }
590
- swapPkScript;
591
- name = "OfferCovenantMismatchError";
592
- };
593
- async function prepareOfferCancel(wallet, offerHex, opts) {
594
- const { fundingTxid, swapAddress } = opts;
595
- const offer = decodeOffer(hex2.decode(offerHex));
596
- const [contractManager, info, reader, broadcaster] = await Promise.all([
597
- wallet.getContractManager(),
598
- wallet.getArkadeInfo({ requireLive: true }),
599
- wallet.getArkadeReader(),
600
- wallet.getArkadeBroadcaster()
601
- ]);
602
- const client = await arkade.Arkade.connect({
603
- // info the wallet already holds, plus its broadcast pair — the shape
604
- // `ArkadeServerProvider` describes, without a second `/v1/info`
605
- arkade: { getInfo: async () => info, ...broadcaster },
606
- indexer: reader,
607
- identity: wallet.identity,
608
- // registered offers resolve their VTXOs from the contract repository
609
- // instead of a direct indexer query; the indexer above stays as the
610
- // fallback for offers created before registration existed
611
- contractManager
612
- // no `network`, unlike registerOfferContract: the row lookup is by
613
- // script and the payout script comes from wallet.getAddress(), so the
614
- // client's network (which only shapes address derivation) is unused here
615
- });
616
- const operatorPubkey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
617
- const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
618
- let rebuilt;
619
- try {
620
- rebuilt = new arkade.ArkadeProgramScript(program, args, keys);
621
- } catch (cause) {
622
- throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript), { cause });
623
- }
624
- if (hex2.encode(rebuilt.pkScript) !== hex2.encode(offer.swapPkScript)) {
625
- throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript));
626
- }
627
- const contract = new arkade.ArkadeContract(client, program, args, keys);
628
- const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
629
- if (!fundingTxid && vtxos.length > 1) {
630
- throw new Error(
631
- "multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
632
- );
633
- }
634
- const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
635
- if (!vtxo) throw new NoSpendableDepositError();
636
- const makerPkScript = ArkAddress.decode(makerAddress).pkScript;
637
- const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
638
- for (const a of vtxo.assets ?? []) {
639
- cancel.withAsset({
640
- assetId: a.assetId,
641
- inputs: [{ vin: 0, amount: BigInt(a.amount) }],
642
- outputs: [{ vout: 0, amount: BigInt(a.amount) }]
643
- });
644
- }
645
- return {
646
- offer,
647
- vtxo: { txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value },
648
- send: async () => (await cancel.send()).txid
649
- };
650
- }
28
+ collectRfqSwaps
29
+ } from "./chunk-A3SHHRX4.js";
651
30
 
652
31
  // src/rfqCorridor.ts
653
32
  var RfqCorridorRegistry = class {
@@ -660,20 +39,12 @@ var RfqCorridorRegistry = class {
660
39
  }
661
40
  this.handlers.set(handler.kind, handler);
662
41
  }
663
- /** Takes a bare `string`, deliberately, where {@link RfqCorridorHandler.kind}
664
- * is the manager's union: a lookup key comes off a record a backend handed
665
- * back, and that it typechecks as a `kind` is a claim about the type, not
666
- * about what was stored. Narrowing this would read as a check already made. */
42
+ /** A bare `string` on purpose: the key comes off a stored record, and narrowing it to the
43
+ * `kind` union would read as a check already made. */
667
44
  get(kind) {
668
45
  return this.handlers.get(kind);
669
46
  }
670
- /**
671
- * The handler for a kind, or a loud failure.
672
- *
673
- * A record whose corridor is not registered cannot be restored, and
674
- * guessing would monitor a swap with no idea how to drive it. Names the
675
- * registered kinds so a missing `register()` call is obvious.
676
- */
47
+ /** The handler for a kind, or a loud failure naming the registered kinds. */
677
48
  getOrThrow(kind) {
678
49
  const handler = this.get(kind);
679
50
  if (!handler) {
@@ -683,9 +54,6 @@ var RfqCorridorRegistry = class {
683
54
  }
684
55
  return handler;
685
56
  }
686
- has(kind) {
687
- return this.handlers.has(kind);
688
- }
689
57
  registeredKinds() {
690
58
  return [...this.handlers.keys()];
691
59
  }
@@ -779,20 +147,17 @@ var rfqClaimDestinationOf = (record) => {
779
147
  };
780
148
 
781
149
  // src/rfqCorridors.ts
782
- import { hex as hex3 } from "@scure/base";
150
+ import { hex } from "@scure/base";
783
151
  var LightningSendCorridor = {
784
152
  kind: "lightning_send",
785
153
  project: () => ({}),
786
154
  hydrate: (profile) => hydrateHashlock(profile)
787
- // No `claimSecret`, deliberately: `provisionRefundKey` mints no preimage at
788
- // all, and deriving one off the refund descriptor would fail the payment
789
- // hash check — a `hash-mismatch` on a swap that was never broken.
155
+ // No `claimSecret`: no preimage was minted, and one derived off the refund descriptor would
156
+ // fail the payment hash check on a swap that was never broken.
790
157
  };
791
158
  var LightningReceiveCorridor = {
792
159
  kind: "lightning_receive",
793
- // What the manager holds: the amount gate, and its own claim once it lands.
794
- // `payoutAddress` comes from the request result and never changes, so the
795
- // caller writes it once and this leaves it alone.
160
+ // `payoutAddress` is written once by the caller from the request result; left alone here.
796
161
  project: (swap) => {
797
162
  const receive = swap;
798
163
  return {
@@ -813,30 +178,28 @@ var LightningReceiveCorridor = {
813
178
  // We are the claimant here, so the preimage material on the hashlock is
814
179
  // ours to use.
815
180
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
816
- // The other half of claiming: where it pays. Written once at request time
817
- // and left alone by `project` above, so this hands back what was stored.
818
181
  claimDestination: (profile) => profile.payoutAddress,
819
182
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
820
183
  };
821
184
  function onchainSendProfile(result) {
822
185
  return {
823
- claimKey: hex3.encode(result.htlcParams.claimKey),
824
- refundKey: hex3.encode(result.htlcParams.refundKey),
186
+ claimKey: hex.encode(result.htlcParams.claimKey),
187
+ refundKey: hex.encode(result.htlcParams.refundKey),
825
188
  htlcLocktime: result.htlcParams.refundLocktime,
826
189
  network: result.l1Network,
827
190
  htlcAddress: result.htlc.address,
828
191
  minConfirmations: result.minConfirmations,
829
- payoutPkScript: hex3.encode(result.payoutPkScript)
192
+ expectedAmount: result.expectedAmount,
193
+ payoutPkScript: hex.encode(result.payoutPkScript)
830
194
  };
831
195
  }
832
196
  var OnchainSendCorridor = {
833
197
  kind: "onchain_send",
834
- // The L1 keys and the network are only in the request result — nothing on
835
- // `OnchainSendSwap` carries them — so the caller writes them once. What the
836
- // manager learns as it drives the swap is the fill and our own claim.
198
+ // The L1 keys and network are written once by the caller; the manager learns fill and claim.
837
199
  project: (swap) => {
838
200
  const send = swap;
839
201
  return {
202
+ expectedAmount: send.expectedAmount,
840
203
  ...send.funding ? { funding: send.funding } : {},
841
204
  ...send.claimTxid ? { claimTxid: send.claimTxid } : {}
842
205
  };
@@ -853,15 +216,18 @@ var OnchainSendCorridor = {
853
216
  `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`
854
217
  );
855
218
  }
219
+ if (!Number.isSafeInteger(profile.expectedAmount) || profile.expectedAmount <= 0) {
220
+ throw new Error(
221
+ `onchain_send record carries no usable expectedAmount (${String(profile.expectedAmount)}); the funded value cannot be checked \u2014 refusing to restore a swap that would claim an underfunded fill`
222
+ );
223
+ }
856
224
  const htlc = onchainHtlcScript(
857
225
  {
858
- // From the profile, not the covenant: the lockup commits to
859
- // `hash160(P)`, and the HTLC needs `sha256(P)`. One P
860
- // unlocks both legs, but only one of the two hashes of it
861
- // is recoverable here.
226
+ // From the profile, not the covenant: the lockup commits to `hash160(P)`, the
227
+ // HTLC needs `sha256(P)`.
862
228
  paymentHash,
863
- claimKey: hex3.decode(profile.claimKey),
864
- refundKey: hex3.decode(profile.refundKey),
229
+ claimKey: hex.decode(profile.claimKey),
230
+ refundKey: hex.decode(profile.refundKey),
865
231
  refundLocktime: profile.htlcLocktime
866
232
  },
867
233
  profile.network
@@ -875,9 +241,10 @@ var OnchainSendCorridor = {
875
241
  paymentHash,
876
242
  htlc,
877
243
  minConfirmations: profile.minConfirmations,
244
+ expectedAmount: profile.expectedAmount,
878
245
  // Optional here, required at the write: throwing on an older
879
246
  // record would strand the refund it is still owed.
880
- ...profile.payoutPkScript ? { payoutPkScript: hex3.decode(profile.payoutPkScript) } : {},
247
+ ...profile.payoutPkScript ? { payoutPkScript: hex.decode(profile.payoutPkScript) } : {},
881
248
  ...profile.funding ? { funding: profile.funding } : {},
882
249
  ...profile.claimTxid ? { claimTxid: profile.claimTxid } : {}
883
250
  };
@@ -885,9 +252,7 @@ var OnchainSendCorridor = {
885
252
  // The trader claims the L1 HTLC with P, so this leg's preimage material is
886
253
  // ours.
887
254
  claimSecret: (profile) => ({ ...profile.signer, ...profile.hashlock }),
888
- // Our own L1 claim only. `funding` is the SOLVER's fill into the HTLC —
889
- // not a transaction of ours, so grouping it would claim a row this wallet
890
- // never made.
255
+ // Our own L1 claim only: `funding` is the solver's tx, not a row this wallet made.
891
256
  activityTxids: (profile) => profile.claimTxid ? [profile.claimTxid] : []
892
257
  };
893
258
  rfqCorridorHandlers.register(LightningSendCorridor);
@@ -975,7 +340,7 @@ var lightningCorridor = Object.assign(
975
340
  );
976
341
 
977
342
  // src/client/corridors/onchain.ts
978
- import { btcTarget } from "@arkade-os/sdk";
343
+ import { BIP21, btcTarget } from "@arkade-os/sdk";
979
344
  import * as btc from "@scure/btc-signer";
980
345
  var ONCHAIN_DRIVE = {
981
346
  take: {
@@ -1002,7 +367,14 @@ var onchainCorridor = Object.assign(
1002
367
  } catch {
1003
368
  return { refused: `this is not a ${l1} address` };
1004
369
  }
1005
- return { claimed: { kind: "address", address: target } };
370
+ const amount = BIP21.amountSats(raw);
371
+ return {
372
+ claimed: {
373
+ kind: "address",
374
+ address: target,
375
+ ...amount === void 0 ? {} : { amount: BigInt(amount) }
376
+ }
377
+ };
1006
378
  }
1007
379
  };
1008
380
  },
@@ -1033,18 +405,14 @@ var CORRIDOR_OUTCOME = {
1033
405
  failed: at("failed")
1034
406
  },
1035
407
  solver: {
1036
- // The solver has funded nothing yet: the invoice is shown and unpaid,
1037
- // which is what makes this `open` where the trader's side is `funded`.
408
+ // The solver has funded nothing yet: the invoice is shown and unpaid.
1038
409
  pending: at("open"),
1039
410
  claimable: at("funded"),
1040
411
  claimed: at("funded"),
1041
412
  needs_counterparty: at("needs_recovery"),
1042
- // The trader's OWN claim, matched by the hash and not by our txid — so
1043
- // a claim that lands without us still counts.
413
+ // Matched by the hash, not our txid, so a claim that lands without us counts.
1044
414
  settled: at("claimed"),
1045
- // The one inversion this whole module exists for: every non-claim leaf
1046
- // of a receive covenant is the solver's, so a lockup spent by one is
1047
- // the trader's incoming payment never arriving.
415
+ // The inversion: a receive lockup's non-claim leaves are all the solver's.
1048
416
  refunded: at("lapsed"),
1049
417
  failed: at("failed")
1050
418
  }
@@ -1055,8 +423,7 @@ var OFFER_OUTCOME = {
1055
423
  cancelling: "cancelling",
1056
424
  cancelled: "cancelled",
1057
425
  fulfilled: "filled",
1058
- // A swept deposit: still the trader's money, at a script no offchain spend
1059
- // can reach until it is recovered into a fresh batch.
426
+ // A swept deposit: still the trader's money, unreachable until recovered into a batch.
1060
427
  recoverable: "needs_recovery",
1061
428
  awaiting_fill: "needs_recovery",
1062
429
  claimable: "needs_recovery",
@@ -1074,10 +441,8 @@ var ACTIVITY_TOKEN = {
1074
441
  funding: "pending",
1075
442
  funded: "pending",
1076
443
  open: "pending",
1077
- // The drive's in-flight states have no user-visible phase distinct from
1078
- // "pending"; `needs_recovery` is different in kind — the swap is BLOCKED —
1079
- // and collapsing it here is the same deliberate choice v1 made, which the
1080
- // opaque-token design permits because apps map tokens themselves.
444
+ // `needs_recovery` (BLOCKED) collapses to pending deliberately, as in v1; apps map
445
+ // tokens themselves.
1081
446
  needs_recovery: "pending",
1082
447
  refunding: "pending",
1083
448
  cancelling: "pending",
@@ -1091,36 +456,34 @@ var ACTIVITY_TOKEN = {
1091
456
  };
1092
457
 
1093
458
  // src/refund.ts
1094
- import { base64, hex as hex4 } from "@scure/base";
1095
- import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
459
+ import { base64, hex as hex2 } from "@scure/base";
460
+ import { sha256 } from "@noble/hashes/sha2.js";
1096
461
  import {
1097
- CSVMultisigTapscript,
1098
462
  ConditionWitness,
1099
463
  Transaction,
1100
464
  assertSubmittedArkTxid,
465
+ assertValidServerUnrollScript,
1101
466
  buildOffchainTx,
1102
467
  getArkPsbtFields,
1103
- hasTerminalSpend,
1104
- matchServerCheckpoints
468
+ isVtxoSpent,
469
+ matchServerCheckpoints,
470
+ networkFromArkadeInfo,
471
+ resolveCheckpointExitDelayPolicy,
472
+ toXOnly
1105
473
  } from "@arkade-os/sdk";
1106
- var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1107
474
  var isRfqTerminal = (state) => RFQ_TERMINAL_STATES.includes(state);
1108
475
  var RFQ_RESOLVED_STATES = ["settled", "refunded"];
1109
476
  var isResolved = (state) => RFQ_RESOLVED_STATES.includes(state);
1110
477
  async function awaitRfqResolution(transport, rfqId, options = {}) {
1111
- const pollMs = options.pollMs ?? 5e3;
1112
- for (; ; ) {
1113
- const status = await transport.status(rfqId);
1114
- if (status && isRfqTerminal(status.state)) return status;
1115
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
1116
- const error = new Error(
1117
- `rfq ${rfqId} did not reach a terminal state before the deadline`
1118
- );
1119
- error.reason = "status_timeout";
1120
- throw error;
1121
- }
1122
- await sleep(pollMs);
1123
- }
478
+ return pollUntil(
479
+ async () => {
480
+ const status = await transport.status(rfqId);
481
+ return status && isRfqTerminal(status.state) ? status : void 0;
482
+ },
483
+ options,
484
+ "status_timeout",
485
+ `rfq ${rfqId} did not reach a terminal state before the deadline`
486
+ );
1124
487
  }
1125
488
  var walletOperator = (wallet) => {
1126
489
  let broadcaster;
@@ -1137,15 +500,8 @@ var LockupNeedsRecoveryError = class extends Error {
1137
500
  /** `txid:vout` for each output that must be recovered first. */
1138
501
  outpoints;
1139
502
  /**
1140
- * The contract's `refundLocktime`. Recovering before this matures is the
1141
- * hazard described above: `recoverVtxos()` sweeps EVERY recoverable output
1142
- * into one settlement with no CLTV awareness, so an early attempt can fail
1143
- * the whole batch — including unrelated outputs that were otherwise fine.
1144
- *
1145
- * Exposed as a value, not only inside the message, so a caller can skip
1146
- * pre-CLTV recoverable outputs without parsing prose. Seconds-based
1147
- * locktimes mature against the chain tip's timestamp rather than wall
1148
- * clock, so treat this as a floor to wait past, not an exact alarm.
503
+ * The contract's `refundLocktime`; do not recover before it (see above). Seconds-based
504
+ * locktimes mature against chain time, not wall clock, so treat this as a floor.
1149
505
  */
1150
506
  recoverableAfter;
1151
507
  constructor(outpoints, recoverableAfter) {
@@ -1156,43 +512,37 @@ var LockupNeedsRecoveryError = class extends Error {
1156
512
  this.recoverableAfter = recoverableAfter;
1157
513
  }
1158
514
  };
1159
- async function findLockupVtxos(indexer, swapPkScript) {
1160
- const scripts = [hex4.encode(swapPkScript)];
1161
- const [spendable, recoverable] = await Promise.all([
1162
- indexer.getVtxos({ scripts, spendableOnly: true }),
1163
- indexer.getVtxos({ scripts, recoverableOnly: true })
1164
- ]);
515
+ async function findLockupVtxos(contracts, swapPkScript) {
516
+ const [row] = await contracts.getContractsWithVtxos({
517
+ script: hex2.encode(swapPkScript)
518
+ });
1165
519
  const seen = /* @__PURE__ */ new Set();
1166
520
  const out = [];
1167
- for (const [vtxos, isRecoverable] of [
1168
- [spendable.vtxos ?? [], false],
1169
- [recoverable.vtxos ?? [], true]
1170
- ]) {
1171
- for (const vtxo of vtxos) {
1172
- if (vtxo.isUnrolled) continue;
1173
- const key = `${vtxo.txid}:${vtxo.vout}`;
1174
- if (seen.has(key)) continue;
1175
- seen.add(key);
1176
- out.push({
1177
- txid: vtxo.txid,
1178
- vout: vtxo.vout,
1179
- value: Number(vtxo.value),
1180
- recoverable: isRecoverable
1181
- });
1182
- }
521
+ for (const vtxo of row?.vtxos ?? []) {
522
+ if (vtxo.isUnrolled) continue;
523
+ if (isVtxoSpent(vtxo)) continue;
524
+ const key = `${vtxo.txid}:${vtxo.vout}`;
525
+ if (seen.has(key)) continue;
526
+ seen.add(key);
527
+ out.push({
528
+ txid: vtxo.txid,
529
+ vout: vtxo.vout,
530
+ value: Number(vtxo.value),
531
+ recoverable: vtxo.isSwept
532
+ });
1183
533
  }
1184
534
  return out;
1185
535
  }
1186
- var hashesTo = (candidate, paymentHash) => hex4.encode(sha2562(candidate)) === paymentHash;
536
+ var hashesTo = (candidate, paymentHash) => hex2.encode(sha256(candidate)) === paymentHash;
1187
537
  var candidateWitnessItems = (tx, inputIndex) => [
1188
538
  ...getArkPsbtFields(tx, inputIndex, ConditionWitness).flat(),
1189
539
  ...tx.getInput(inputIndex).finalScriptWitness ?? []
1190
540
  ];
1191
541
  async function readLockupFate(indexer, input) {
1192
- const { vtxos } = await indexer.getVtxos({ scripts: [hex4.encode(input.swapPkScript)] });
542
+ const { vtxos } = await indexer.getVtxos({ scripts: [hex2.encode(input.swapPkScript)] });
1193
543
  const all = vtxos ?? [];
1194
544
  if (all.length === 0) return { fate: "unknown" };
1195
- const exited = all.filter((vtxo) => vtxo.isUnrolled && !hasTerminalSpend(vtxo));
545
+ const exited = all.filter((vtxo) => vtxo.isUnrolled && !isVtxoSpent(vtxo));
1196
546
  if (exited.length > 0) {
1197
547
  return {
1198
548
  fate: "exited",
@@ -1202,7 +552,7 @@ async function readLockupFate(indexer, input) {
1202
552
  const spentBy = /* @__PURE__ */ new Map();
1203
553
  let everySpendNamed = true;
1204
554
  for (const vtxo of all) {
1205
- if (!hasTerminalSpend(vtxo)) return { fate: "open" };
555
+ if (!isVtxoSpent(vtxo)) return { fate: "open" };
1206
556
  if (vtxo.spentBy)
1207
557
  spentBy.set(vtxo.spentBy, {
1208
558
  checkpointTxid: vtxo.spentBy,
@@ -1224,7 +574,7 @@ async function readLockupFate(indexer, input) {
1224
574
  for (let i = 0; i < tx.inputsLength; i++) {
1225
575
  const spent = tx.getInput(i);
1226
576
  if (!spent.txid) continue;
1227
- const txid = hex4.encode(spent.txid);
577
+ const txid = hex2.encode(spent.txid);
1228
578
  if (!all.some((vtxo) => vtxo.txid === txid && vtxo.vout === spent.index)) continue;
1229
579
  for (const candidate of candidateWitnessItems(tx, i)) {
1230
580
  if (hashesTo(candidate, input.paymentHash)) {
@@ -1235,41 +585,50 @@ async function readLockupFate(indexer, input) {
1235
585
  }
1236
586
  return everySpendNamed && observed.size === spentBy.size ? { fate: "returned", spends } : { fate: "unknown" };
1237
587
  }
1238
- async function pushRefundWithoutReceiver(operator, input) {
1239
- if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
1240
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
588
+ var assertNoneSwept = (vtxos, contract) => {
589
+ const swept = vtxos.filter((vtxo) => vtxo.recoverable);
1241
590
  if (swept.length > 0) {
1242
591
  throw new LockupNeedsRecoveryError(
1243
592
  swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
1244
- input.contract.options.refundLocktime
593
+ contract.options.refundLocktime
1245
594
  );
1246
595
  }
596
+ };
597
+ var operatorUnrollScript = async (operator, network) => {
598
+ const info = await operator.getInfo();
599
+ return assertValidServerUnrollScript(
600
+ info.checkpointTapscript,
601
+ resolveCheckpointExitDelayPolicy(network ?? networkFromArkadeInfo(info), {
602
+ advertisedForfeitPubkey: toXOnly(hex2.decode(info.forfeitPubkey), "forfeit key")
603
+ })
604
+ );
605
+ };
606
+ var lockupInputs = (vtxos, contract, leaf) => {
607
+ const tapTree = contract.encode();
608
+ return vtxos.map((vtxo) => ({
609
+ txid: vtxo.txid,
610
+ vout: vtxo.vout,
611
+ value: vtxo.value,
612
+ tapLeafScript: leaf,
613
+ tapTree
614
+ }));
615
+ };
616
+ async function pushRefundWithoutReceiver(operator, input) {
617
+ if (input.vtxos.length === 0) throw new Error("nothing to refund: no funded outputs");
618
+ assertNoneSwept(input.vtxos, input.contract);
1247
619
  const refundPkScript = input.refundPkScript ?? input.contract.options.nonInteractiveParameters?.senderPkScript;
1248
620
  if (!refundPkScript) {
1249
621
  throw new Error(
1250
622
  "no refund destination: the contract carries no emulator covenant suite, so pass refundPkScript explicitly"
1251
623
  );
1252
624
  }
1253
- const info = await operator.getInfo();
1254
- let operatorUnrollScript;
1255
- try {
1256
- operatorUnrollScript = CSVMultisigTapscript.decode(hex4.decode(info.checkpointTapscript));
1257
- } catch {
1258
- throw new Error("invalid checkpointTapscript from the operator");
1259
- }
625
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
1260
626
  const leaf = input.contract.refundWithoutReceiver();
1261
- const tapTree = input.contract.encode();
1262
627
  const amount = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
1263
628
  const { arkTx: tx, checkpoints } = buildOffchainTx(
1264
- input.vtxos.map((vtxo) => ({
1265
- txid: vtxo.txid,
1266
- vout: vtxo.vout,
1267
- value: vtxo.value,
1268
- tapLeafScript: leaf,
1269
- tapTree
1270
- })),
629
+ lockupInputs(input.vtxos, input.contract, leaf),
1271
630
  [{ script: refundPkScript, amount: BigInt(amount) }],
1272
- operatorUnrollScript
631
+ serverUnrollScript
1273
632
  );
1274
633
  const signedTx = await input.sender.sign(tx);
1275
634
  const submitted = await operator.submitTx(
@@ -1291,7 +650,7 @@ async function pushRefundWithoutReceiver(operator, input) {
1291
650
  return { txid: submitted.arkTxid, amount };
1292
651
  }
1293
652
  var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
1294
- async function refundIfUnresolved(transport, operator, indexer, input) {
653
+ async function refundIfUnresolved(transport, operator, contracts, indexer, input) {
1295
654
  const pollMs = input.pollMs ?? 5e3;
1296
655
  const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
1297
656
  const attemptDeadline = input.attemptDeadline ?? input.refundLocktime + REFUND_MTP_LAG_SECONDS;
@@ -1314,7 +673,7 @@ async function refundIfUnresolved(transport, operator, indexer, input) {
1314
673
  status
1315
674
  };
1316
675
  }
1317
- const vtxos = await findLockupVtxos(indexer, input.contract.pkScript);
676
+ const vtxos = await findLockupVtxos(contracts, input.contract.pkScript);
1318
677
  if (vtxos.length === 0) return { outcome: "nothing_to_refund", status };
1319
678
  try {
1320
679
  const pushed = await pushRefundWithoutReceiver(operator, {
@@ -1345,9 +704,49 @@ import {
1345
704
  bestMarket,
1346
705
  discover,
1347
706
  isNetwork,
707
+ marketLegKey,
708
+ registryIndexUrl,
1348
709
  sideLimits
1349
710
  } from "@arkade-os/solver-discovery";
1350
711
  import { isSubdust } from "@arkade-os/sdk";
712
+
713
+ // src/marketShape.ts
714
+ var MARKET_CORRIDORS = ["arkade", "bolt11", "bitcoin", "eip155"];
715
+ var LEGACY_CORRIDORS = {
716
+ arkade: "arkade",
717
+ lightning: "bolt11",
718
+ onchain: "bitcoin",
719
+ eip155: "eip155"
720
+ };
721
+ var assetOf = (market, side) => side === "base" ? market.base_asset : market.quote_asset;
722
+ var marketAssetId = (market, side) => {
723
+ const asset = assetOf(market, side);
724
+ if (typeof asset?.caip19_id === "string") return asset.caip19_id;
725
+ return typeof asset?.id === "string" ? asset.id : void 0;
726
+ };
727
+ var chainNamespaceOf = (id) => {
728
+ if (id === void 0) return void 0;
729
+ const slash = id.indexOf("/");
730
+ const colon = id.indexOf(":");
731
+ return slash === -1 || colon === -1 || colon > slash ? void 0 : id.slice(0, colon);
732
+ };
733
+ var marketCorridor = (market, side) => {
734
+ const namespace = chainNamespaceOf(marketAssetId(market, side));
735
+ if (namespace !== void 0) {
736
+ return MARKET_CORRIDORS.includes(namespace) ? namespace : "arkade";
737
+ }
738
+ const legacy = side === "base" ? market.base_corridor : market.quote_corridor;
739
+ return typeof legacy === "string" ? LEGACY_CORRIDORS[legacy] ?? "arkade" : "arkade";
740
+ };
741
+ var sideLabel = (market, side) => {
742
+ const ticker = assetOf(market, side)?.ticker;
743
+ const label = typeof ticker === "string" && ticker.length > 0 ? ticker : "?";
744
+ const corridor = marketCorridor(market, side);
745
+ return corridor === "arkade" ? label : `${corridor}:${label}`;
746
+ };
747
+ var marketPairLabel = (market) => `${sideLabel(market, "base")}/${sideLabel(market, "quote")}`;
748
+
749
+ // src/markets.ts
1351
750
  var QUOTE_OPTIONS = { safetyBps: 0 };
1352
751
  var makeCachedFeedFetch = (ttlMs = 3e4, fetchImpl = fetch) => {
1353
752
  const cache = /* @__PURE__ */ new Map();
@@ -1396,14 +795,17 @@ var makeCachedFeedFetch = (ttlMs = 3e4, fetchImpl = fetch) => {
1396
795
  var MARKETS_CACHE_TTL_MS = 60 * 60 * 1e3;
1397
796
  var isMarketShaped = (m) => {
1398
797
  const market = m;
1399
- return typeof market?.pair === "string" && typeof market.base_asset?.id === "string" && typeof market.quote_asset?.id === "string" && typeof market.quote_asset.decimals === "number";
798
+ if (!market) return false;
799
+ return typeof market.base_asset?.id === "string" && typeof market.quote_asset?.id === "string" && typeof market.quote_asset.decimals === "number";
1400
800
  };
1401
801
  var readMarketsCache = async (repository, network, registry) => {
1402
802
  try {
1403
803
  const entry = await repository.getCachedMarkets(network, registry);
1404
804
  if (!Array.isArray(entry?.markets) || typeof entry?.fetchedAt !== "number")
1405
805
  return void 0;
1406
- return entry.markets.every(isMarketShaped) ? entry : void 0;
806
+ const markets = entry.markets.filter(isMarketShaped);
807
+ if (entry.markets.length > 0 && markets.length === 0) return void 0;
808
+ return { ...entry, markets };
1407
809
  } catch {
1408
810
  return void 0;
1409
811
  }
@@ -1418,12 +820,14 @@ var discoverMarkets = async (options) => {
1418
820
  fetchImpl,
1419
821
  useCache = true
1420
822
  } = options;
1421
- if (!registry || !isNetwork(network)) return [];
1422
- const cached = repository && await readMarketsCache(repository, network, registry);
823
+ if (!isNetwork(network)) return [];
824
+ const registries = registry ? [registry] : void 0;
825
+ const registryKey = registries?.[0] ?? registryIndexUrl(network);
826
+ const cached = repository && await readMarketsCache(repository, network, registryKey);
1423
827
  if (useCache && cached && Date.now() - cached.fetchedAt < MARKETS_CACHE_TTL_MS)
1424
828
  return cached.markets;
1425
829
  const { markets, sources, warnings } = await discover({
1426
- registries: [registry],
830
+ registries,
1427
831
  localCards,
1428
832
  network,
1429
833
  fetchImpl
@@ -1433,7 +837,7 @@ var discoverMarkets = async (options) => {
1433
837
  if (!reachable && cached) return cached.markets;
1434
838
  if (reachable && repository) {
1435
839
  try {
1436
- await repository.saveCachedMarkets(network, registry, {
840
+ await repository.saveCachedMarkets(network, registryKey, {
1437
841
  markets,
1438
842
  fetchedAt: Date.now()
1439
843
  });
@@ -1444,10 +848,33 @@ var discoverMarkets = async (options) => {
1444
848
  };
1445
849
  var findMarket = (markets, fromId, toId) => {
1446
850
  if (fromId === toId) return void 0;
1447
- const givingBase = bestMarket(markets, { baseId: fromId, quoteId: toId, wantSide: "quote" });
851
+ const resolveMarketId = (id) => {
852
+ for (const market of markets) {
853
+ for (const side of ["base", "quote"]) {
854
+ const asset = side === "base" ? market.base_asset : market.quote_asset;
855
+ if (asset.id === id) return marketLegKey(market, side);
856
+ const canonical = marketAssetId(market, side) ?? "";
857
+ const matchesBtc = id === BTC_ASSET_ID && /^arkade:[^/]+\/slip44:(?:0|1)$/.test(canonical);
858
+ const matchesAsset = /^[0-9a-f]{68}$/.test(id) && canonical.endsWith(`/asset:${id}`);
859
+ if (matchesBtc || matchesAsset) return marketLegKey(market, side);
860
+ }
861
+ }
862
+ return id;
863
+ };
864
+ const resolvedFrom = resolveMarketId(fromId);
865
+ const resolvedTo = resolveMarketId(toId);
866
+ const givingBase = bestMarket(markets, {
867
+ baseId: resolvedFrom,
868
+ quoteId: resolvedTo,
869
+ wantSide: "quote"
870
+ });
1448
871
  if (givingBase) return { market: givingBase, give: "base" };
1449
872
  return {
1450
- market: bestMarket(markets, { baseId: toId, quoteId: fromId, wantSide: "base" }),
873
+ market: bestMarket(markets, {
874
+ baseId: resolvedTo,
875
+ quoteId: resolvedFrom,
876
+ wantSide: "base"
877
+ }),
1451
878
  give: "quote"
1452
879
  };
1453
880
  };
@@ -1470,13 +897,20 @@ var validatePlan = (plan, giveBalance, dust) => {
1470
897
  };
1471
898
 
1472
899
  // src/restore.ts
1473
- import { base64 as base642, hex as hex5 } from "@scure/base";
900
+ import { base64 as base642, hex as hex3 } from "@scure/base";
1474
901
  import {
1475
902
  Extension,
1476
903
  Transaction as Transaction2,
1477
904
  scriptFromTapLeafScript
1478
905
  } from "@arkade-os/sdk";
1479
906
  var TXS_PER_REQUEST = 50;
907
+ var toRestoreTx = (tx) => ({
908
+ type: tx.type.toLowerCase(),
909
+ redeemTxid: tx.key.arkTxid,
910
+ boardingTxid: tx.key.boardingTxid,
911
+ roundTxid: tx.key.commitmentTxid,
912
+ createdAt: Math.floor(tx.createdAt / 1e3)
913
+ });
1480
914
  async function fetchParsedTxs(indexer, txids) {
1481
915
  const parsedByTxid = /* @__PURE__ */ new Map();
1482
916
  if (txids.length === 0) return parsedByTxid;
@@ -1506,10 +940,9 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
1506
940
  let leaves;
1507
941
  try {
1508
942
  const script = offerContract(offer, operatorPubkey);
1509
- if (hex5.encode(script.pkScript) !== hex5.encode(offer.swapPkScript)) return "indeterminate";
943
+ if (hex3.encode(script.pkScript) !== hex3.encode(offer.swapPkScript)) return "indeterminate";
1510
944
  leaves = {
1511
- // both routes that hand the deposit back; `exit` is absent on an
1512
- // offer that carries no exit closure, and drops out here
945
+ // `exit` is absent on an offer with no exit closure, and drops out here
1513
946
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
1514
947
  fulfill: script.functionByName("fulfill")?.leafScript
1515
948
  };
@@ -1519,11 +952,11 @@ function classifySpend(offer, operatorPubkey, spendTx, deposit) {
1519
952
  for (let i = 0; i < spendTx.inputsLength; i++) {
1520
953
  const input = spendTx.getInput(i);
1521
954
  if (!input.txid || input.index !== deposit.vout) continue;
1522
- if (hex5.encode(input.txid) !== deposit.txid) continue;
955
+ if (hex3.encode(input.txid) !== deposit.txid) continue;
1523
956
  for (const leaf of input.tapLeafScript ?? []) {
1524
- const spent = hex5.encode(scriptFromTapLeafScript(leaf));
1525
- if (leaves.returned.some((back) => spent === hex5.encode(back))) return "cancelled";
1526
- if (leaves.fulfill && spent === hex5.encode(leaves.fulfill)) return "fulfilled";
957
+ const spent = hex3.encode(scriptFromTapLeafScript(leaf));
958
+ if (leaves.returned.some((back) => spent === hex3.encode(back))) return "cancelled";
959
+ if (leaves.fulfill && spent === hex3.encode(leaves.fulfill)) return "fulfilled";
1527
960
  }
1528
961
  }
1529
962
  return "indeterminate";
@@ -1537,16 +970,39 @@ function classifyDepositSpend(offer, operatorPubkey, spendTxs, deposit) {
1537
970
  return "indeterminate";
1538
971
  }
1539
972
  async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1540
- const { operatorPubkey, scanned = /* @__PURE__ */ new Set() } = opts;
1541
- const candidates = unscannedSwapCandidates(txs, existingIds, scanned);
1542
- if (candidates.length === 0) return { restored: [], scannedTxids: [] };
973
+ const {
974
+ operatorPubkey,
975
+ scanned = /* @__PURE__ */ new Set(),
976
+ reopen = [],
977
+ hrp,
978
+ recoveredIn = /* @__PURE__ */ new Set()
979
+ } = opts;
980
+ const reopened = [];
981
+ for (const swap of reopen) {
982
+ try {
983
+ reopened.push({
984
+ fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
985
+ offer: decodeOffer(hex3.decode(swap.offerHex)),
986
+ offerHex: swap.offerHex,
987
+ existing: swap
988
+ });
989
+ } catch {
990
+ }
991
+ }
992
+ const reopenedTxids = new Set(reopened.map(({ fundingTx }) => fundingTx.redeemTxid));
993
+ const candidates = unscannedSwapCandidates(txs, existingIds, scanned).filter(
994
+ ({ redeemTxid }) => !reopenedTxids.has(redeemTxid)
995
+ );
996
+ if (candidates.length === 0 && reopened.length === 0) {
997
+ return { restored: [], scannedTxids: [] };
998
+ }
1543
999
  const byTxid = new Map(candidates.map((tx) => [tx.redeemTxid, tx]));
1544
1000
  const parsedByTxid = await fetchParsedTxs(
1545
1001
  indexer,
1546
1002
  candidates.map((tx) => tx.redeemTxid)
1547
1003
  );
1548
1004
  const fetchedTxids = [];
1549
- const found = [];
1005
+ const found = [...reopened];
1550
1006
  for (const [txid, parsed] of parsedByTxid) {
1551
1007
  const fundingTx = byTxid.get(txid);
1552
1008
  if (!fundingTx) continue;
@@ -1558,13 +1014,13 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1558
1014
  found.push({
1559
1015
  fundingTx,
1560
1016
  offer: decodeOffer(payload),
1561
- offerHex: hex5.encode(payload)
1017
+ offerHex: hex3.encode(payload)
1562
1018
  });
1563
1019
  } catch {
1564
1020
  }
1565
1021
  }
1566
1022
  if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
1567
- const scripts = [...new Set(found.map((f) => hex5.encode(f.offer.swapPkScript)))];
1023
+ const scripts = [...new Set(found.map((f) => hex3.encode(f.offer.swapPkScript)))];
1568
1024
  const { vtxos } = await indexer.getVtxos({ scripts });
1569
1025
  const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
1570
1026
  const txByAnyId = /* @__PURE__ */ new Map();
@@ -1576,16 +1032,16 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1576
1032
  const spendTxids = /* @__PURE__ */ new Set();
1577
1033
  for (const { fundingTx, offer } of found) {
1578
1034
  const vtxo = vtxoByScriptAndTxid.get(
1579
- `${hex5.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
1035
+ `${hex3.encode(offer.swapPkScript)}:${fundingTx.redeemTxid}`
1580
1036
  );
1581
- if (vtxo?.virtualStatus.state !== "spent") continue;
1037
+ if (!vtxo?.isSpent) continue;
1582
1038
  for (const txid of spendTxidsOf(vtxo)) spendTxids.add(txid);
1583
1039
  }
1584
1040
  const spendTxByTxid = await fetchParsedTxs(indexer, [...spendTxids]);
1585
1041
  const restored = [];
1586
1042
  const unresolved = /* @__PURE__ */ new Set();
1587
- for (const { fundingTx, offer, offerHex } of found) {
1588
- const swapPkScript = hex5.encode(offer.swapPkScript);
1043
+ for (const { fundingTx, offer, offerHex, existing } of found) {
1044
+ const swapPkScript = hex3.encode(offer.swapPkScript);
1589
1045
  const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
1590
1046
  if (!vtxo) {
1591
1047
  unresolved.add(fundingTx.redeemTxid);
@@ -1600,225 +1056,81 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
1600
1056
  continue;
1601
1057
  }
1602
1058
  const fromAmount = depositAmount.toString();
1603
- const state = vtxo.virtualStatus.state;
1604
- const spentTxid = state === "spent" ? vtxo.arkTxId || vtxo.spentBy : void 0;
1059
+ const recovered = vtxo.isSpent && vtxo.isSwept && !!vtxo.settledBy && spendTxidsOf(vtxo).length === 0;
1060
+ const spentTxid = vtxo.isSpent ? vtxo.arkTxId || vtxo.spentBy || (recovered ? vtxo.settledBy : void 0) : void 0;
1605
1061
  let status = "pending";
1606
- if (state === "swept") status = "recoverable";
1607
- else if (state === "spent") {
1608
- const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
1609
- const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
1610
- txid: vtxo.txid,
1611
- vout: vtxo.vout
1612
- });
1613
- if (kind === "indeterminate") {
1062
+ if (recovered) {
1063
+ const ours = recoveredIn.has(vtxo.settledBy) || txByAnyId.has(vtxo.settledBy);
1064
+ if (!ours) {
1614
1065
  unresolved.add(fundingTx.redeemTxid);
1615
1066
  continue;
1616
1067
  }
1617
- status = kind;
1618
- }
1619
- restored.push({
1620
- id: fundingTx.redeemTxid,
1621
- fromAsset,
1622
- toAsset,
1623
- fromAmount,
1624
- toAmount: offer.wantAmount.toString(),
1625
- // ponytail(arkade-os/ts-sdk#680): empty address makes cancel fall back
1626
- // to the current operator key; store the funded address if operator-key
1627
- // rotations become real (cancelOffer now at least diagnoses the
1628
- // mismatch instead of reporting a missing VTXO)
1629
- swapAddress: "",
1630
- swapPkScript,
1631
- offerHex,
1632
- fundingTxid: fundingTx.redeemTxid,
1633
- spentTxid,
1634
- status,
1635
- createdAt: fundingTx.createdAt ? fundingTx.createdAt * 1e3 : vtxo.createdAt.getTime(),
1636
- // the completion time is the caller's record of the spend, if it
1637
- // has one — the psbt that classified it carries no timestamp
1638
- ...status === "fulfilled" && spentTxid && txByAnyId.get(spentTxid)?.createdAt ? { completedAt: txByAnyId.get(spentTxid).createdAt * 1e3 } : {}
1639
- });
1640
- }
1641
- return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
1642
- }
1643
-
1644
- // src/claim.ts
1645
- import { hex as hex6 } from "@scure/base";
1646
- import { ripemd160 } from "@noble/hashes/legacy.js";
1647
- import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
1648
- import {
1649
- CSVMultisigTapscript as CSVMultisigTapscript2,
1650
- claimWithPreimageIdentity,
1651
- signAndSubmitOffchainTx
1652
- } from "@arkade-os/sdk";
1653
- var sleep2 = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1654
- var LockupAmountMismatchError = class extends Error {
1655
- name = "LockupAmountMismatchError";
1656
- reason = "amount_mismatch";
1657
- expectedAmount;
1658
- lockedAmount;
1659
- constructor(expectedAmount, lockedAmount) {
1660
- super(
1661
- `lockup holds ${lockedAmount} sats, below the agreed ${expectedAmount} \u2014 refusing to publish the preimage`
1662
- );
1663
- this.expectedAmount = expectedAmount;
1664
- this.lockedAmount = lockedAmount;
1665
- }
1666
- };
1667
- var assertFiniteAmount = (value, reason, label) => {
1668
- if (Number.isFinite(value)) return;
1669
- const error = new Error(`${label} is not a finite number (${String(value)})`);
1670
- error.reason = reason;
1671
- throw error;
1672
- };
1673
- async function pushClaim(operator, input) {
1674
- if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
1675
- const swept = input.vtxos.filter((vtxo) => vtxo.recoverable);
1676
- if (swept.length > 0) {
1677
- throw new LockupNeedsRecoveryError(
1678
- swept.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`),
1679
- input.contract.options.refundLocktime
1680
- );
1681
- }
1682
- const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
1683
- assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
1684
- if (!input.partiallyClaimed) {
1685
- assertFiniteAmount(input.expectedAmount, "invalid_gate_input", "expectedAmount");
1686
- if (locked < input.expectedAmount) {
1687
- throw new LockupAmountMismatchError(input.expectedAmount, locked);
1688
- }
1689
- }
1690
- const committed = input.contract.options.preimageHash;
1691
- if (hex6.encode(ripemd160(sha2563(input.preimage))) !== hex6.encode(committed)) {
1692
- throw new Error("preimage does not match the covenant's payment hash");
1693
- }
1694
- const info = await operator.getInfo();
1695
- let operatorUnrollScript;
1696
- try {
1697
- operatorUnrollScript = CSVMultisigTapscript2.decode(hex6.decode(info.checkpointTapscript));
1698
- } catch {
1699
- throw new Error("invalid checkpointTapscript from the operator");
1700
- }
1701
- const leaf = input.contract.claim();
1702
- const tapTree = input.contract.encode();
1703
- const txid = await signAndSubmitOffchainTx({
1704
- identity: claimWithPreimageIdentity(input.receiver, input.preimage),
1705
- provider: operator,
1706
- inputs: input.vtxos.map((vtxo) => ({
1707
- txid: vtxo.txid,
1708
- vout: vtxo.vout,
1709
- value: vtxo.value,
1710
- tapLeafScript: leaf,
1711
- tapTree
1712
- })),
1713
- // One aggregate output: unlike the covenant refund, this leaf inspects
1714
- // nothing about the output set.
1715
- outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
1716
- serverUnrollScript: operatorUnrollScript,
1717
- verifyServerSignatures: { serverPubkey: input.contract.options.server }
1718
- });
1719
- return { txid, amount: locked };
1720
- }
1721
- async function awaitLockupFunding(indexer, swapPkScript, options = {}) {
1722
- const pollMs = options.pollMs ?? 5e3;
1723
- for (; ; ) {
1724
- const vtxos = await findLockupVtxos(indexer, swapPkScript);
1725
- if (vtxos.length > 0) return vtxos;
1726
- if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
1727
- const error = new Error("the lockup never appeared at the covenant script");
1728
- error.reason = "lockup_timeout";
1729
- throw error;
1730
- }
1731
- await sleep2(pollMs);
1732
- }
1733
- }
1734
- async function claimReceiveLockup(indexer, operator, input) {
1735
- const vtxos = await awaitLockupFunding(indexer, input.swapPkScript, {
1736
- pollMs: input.pollMs,
1737
- deadline: input.deadline
1738
- });
1739
- return pushClaim(operator, {
1740
- contract: input.contract,
1741
- receiver: input.receiver,
1742
- preimage: input.preimage,
1743
- vtxos,
1744
- destinationPkScript: input.destinationPkScript,
1745
- expectedAmount: input.expectedAmount,
1746
- partiallyClaimed: input.partiallyClaimed
1747
- });
1748
- }
1749
-
1750
- // src/refundBlocked.ts
1751
- import {
1752
- ForeignDescriptorError,
1753
- WalletCannotSignError,
1754
- contractSigner
1755
- } from "@arkade-os/sdk";
1756
- var RefundNotLocallyPossibleError = class extends Error {
1757
- constructor(reason, message, options) {
1758
- super(message, options);
1759
- this.reason = reason;
1760
- }
1761
- reason;
1762
- name = "RefundNotLocallyPossibleError";
1763
- };
1764
- async function senderIdentityForSwapRecord(wallet, record) {
1765
- if (!record.signingDescriptor) {
1766
- throw new RefundNotLocallyPossibleError(
1767
- "no-secrets",
1768
- "this swap record carries no signing descriptor"
1769
- );
1770
- }
1771
- try {
1772
- return await contractSigner(wallet, record.signingDescriptor);
1773
- } catch (cause) {
1774
- if (cause instanceof WalletCannotSignError) {
1775
- throw new RefundNotLocallyPossibleError(
1776
- "unsignable-wallet",
1777
- `this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
1778
- { cause }
1779
- );
1780
- }
1781
- if (cause instanceof ForeignDescriptorError) {
1782
- throw new RefundNotLocallyPossibleError(
1783
- "foreign-descriptor",
1784
- `this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
1785
- { cause }
1786
- );
1787
- }
1788
- throw cause;
1789
- }
1790
- }
1791
-
1792
- // src/arkadeRefunder.ts
1793
- function arkadeRefunder(deps) {
1794
- return async (swap) => {
1795
- const contract = swap.lockup?.script;
1796
- if (!contract) {
1797
- throw new Error(
1798
- `swap ${swap.rfqId} carries no lockup covenant, so its refund cannot be built`
1799
- );
1068
+ status = "cancelled";
1069
+ } else if (vtxo.isSwept && !vtxo.isSpent) status = "recoverable";
1070
+ else if (vtxo.isSpent) {
1071
+ const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
1072
+ const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
1073
+ txid: vtxo.txid,
1074
+ vout: vtxo.vout
1075
+ });
1076
+ if (kind === "indeterminate") {
1077
+ unresolved.add(fundingTx.redeemTxid);
1078
+ continue;
1079
+ }
1080
+ status = kind;
1800
1081
  }
1801
- const vtxos = await findLockupVtxos(deps.indexer, swap.lockupPkScript);
1802
- if (vtxos.length === 0) return null;
1803
- const record = await deps.repository.getRfqSwap(swap.rfqId);
1804
- if (!record) {
1805
- throw new RefundNotLocallyPossibleError(
1806
- "no-secrets",
1807
- `no stored record for ${swap.rfqId}; the descriptor that signs its refund lives there`
1808
- );
1082
+ const completion = status === "fulfilled" && spentTxid && txByAnyId.get(spentTxid)?.createdAt ? { completedAt: txByAnyId.get(spentTxid).createdAt * 1e3 } : {};
1083
+ if (existing) {
1084
+ if (status === "pending") continue;
1085
+ restored.push({ ...existing, status, spentTxid, ...completion });
1086
+ continue;
1809
1087
  }
1810
- const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
1811
- return pushRefundWithoutReceiver(deps.operator, { contract, sender, vtxos });
1812
- };
1088
+ let swapAddress = "";
1089
+ try {
1090
+ const compiled = offerContract(offer, operatorPubkey);
1091
+ if (hex3.encode(compiled.pkScript) !== swapPkScript) {
1092
+ unresolved.add(fundingTx.redeemTxid);
1093
+ continue;
1094
+ }
1095
+ if (hrp !== void 0) {
1096
+ swapAddress = compiled.address(hrp, operatorPubkey).encode();
1097
+ }
1098
+ } catch {
1099
+ unresolved.add(fundingTx.redeemTxid);
1100
+ continue;
1101
+ }
1102
+ restored.push({
1103
+ id: fundingTx.redeemTxid,
1104
+ fromAsset,
1105
+ toAsset,
1106
+ fromAmount,
1107
+ toAmount: offer.wantAmount.toString(),
1108
+ swapAddress,
1109
+ swapPkScript,
1110
+ offerHex,
1111
+ fundingTxid: fundingTx.redeemTxid,
1112
+ spentTxid,
1113
+ status,
1114
+ createdAt: fundingTx.createdAt ? fundingTx.createdAt * 1e3 : vtxo.createdAt.getTime(),
1115
+ ...completion
1116
+ });
1117
+ }
1118
+ return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
1813
1119
  }
1814
1120
 
1815
1121
  // src/rfqSwapState.ts
1816
1122
  var RFQ_SWAP_TERMINAL_STATES = ["settled", "refunded", "failed"];
1123
+ var RFQ_SWAP_ACTIVE_STATES = [
1124
+ "pending",
1125
+ "claimable",
1126
+ "claimed",
1127
+ "needs_counterparty"
1128
+ ];
1817
1129
  var isRfqSwapTerminal = (state) => RFQ_SWAP_TERMINAL_STATES.includes(state);
1818
1130
 
1819
1131
  // src/rfqRecord.ts
1820
- import { ArkAddress as ArkAddress2, VHTLCV2ContractHandler } from "@arkade-os/sdk";
1821
- import { hex as hex7 } from "@scure/base";
1132
+ import { ArkAddress, VHTLCV2ContractHandler } from "@arkade-os/sdk";
1133
+ import { hex as hex4 } from "@scure/base";
1822
1134
  var RFQ_SWAP_RETENTION_SECONDS = 30 * 24 * 60 * 60;
1823
1135
  function renameLegacyClaimTxid(profile) {
1824
1136
  const { claimArkTxid, ...rest } = profile;
@@ -1839,16 +1151,20 @@ function normalizeRfqSwapRecord(record) {
1839
1151
  ...legacyClaim ? { profile: renameLegacyClaimTxid(record.profile) } : {}
1840
1152
  };
1841
1153
  }
1154
+ var mutableFields = (from) => ({
1155
+ ...from.refundTxid ? { refundTxid: from.refundTxid } : {},
1156
+ ...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
1157
+ ...from.settlementPreimageHex ? { settlementPreimageHex: from.settlementPreimageHex } : {},
1158
+ ...from.failure ? { failure: from.failure } : {},
1159
+ ...from.claimFailure ? { claimFailure: from.claimFailure } : {},
1160
+ ...from.blockedReason ? { blockedReason: from.blockedReason } : {}
1161
+ });
1842
1162
  var managerState = (swap) => ({
1843
1163
  rfqId: swap.rfqId,
1844
1164
  state: swap.state,
1845
1165
  createdAt: swap.createdAt,
1846
1166
  updatedAt: swap.updatedAt,
1847
- ...swap.refundTxid ? { refundTxid: swap.refundTxid } : {},
1848
- ...swap.lockupSpendTxids?.length ? { lockupSpendTxids: [...swap.lockupSpendTxids] } : {},
1849
- ...swap.failure ? { failure: swap.failure } : {},
1850
- ...swap.claimFailure ? { claimFailure: swap.claimFailure } : {},
1851
- ...swap.blockedReason ? { blockedReason: swap.blockedReason } : {}
1167
+ ...mutableFields(swap)
1852
1168
  });
1853
1169
  function assertSameSwap(origin, swap) {
1854
1170
  if (origin.kind !== swap.kind) {
@@ -1856,8 +1172,8 @@ function assertSameSwap(origin, swap) {
1856
1172
  `rfq swap record is a ${origin.kind} origin paired with a ${swap.kind} swap`
1857
1173
  );
1858
1174
  }
1859
- const funded = hex7.encode(ArkAddress2.decode(origin.lockupAddress).pkScript);
1860
- const watched = hex7.encode(swap.lockupPkScript);
1175
+ const funded = hex4.encode(ArkAddress.decode(origin.lockupAddress).pkScript);
1176
+ const watched = hex4.encode(swap.lockupPkScript);
1861
1177
  if (funded !== watched) {
1862
1178
  throw new Error(
1863
1179
  `rfq swap record's lockup address holds ${funded}, but the swap watches ${watched} \u2014 these are not the same swap`
@@ -1870,8 +1186,6 @@ function createRfqSwapRecord(origin, swap) {
1870
1186
  return {
1871
1187
  ...origin,
1872
1188
  ...managerState(swap),
1873
- // The caller wrote what only the request result knows; the handler adds
1874
- // what the live swap already carries.
1875
1189
  profile: { ...origin.profile, ...handler.project(swap) }
1876
1190
  };
1877
1191
  }
@@ -1881,6 +1195,7 @@ function updateRfqSwapRecord(record, swap) {
1881
1195
  const {
1882
1196
  refundTxid: _refundTxid,
1883
1197
  lockupSpendTxids: _lockupSpendTxids,
1198
+ settlementPreimageHex: _settlementPreimageHex,
1884
1199
  failure: _failure,
1885
1200
  claimFailure: _claimFailure,
1886
1201
  blockedReason: _blockedReason,
@@ -1905,10 +1220,10 @@ function rfqSwapOriginOf(record) {
1905
1220
  }
1906
1221
  function lockupScript(params, lockupAddress) {
1907
1222
  const script = VHTLCV2ContractHandler.createScript(params);
1908
- const funded = ArkAddress2.decode(lockupAddress).pkScript;
1909
- if (hex7.encode(funded) !== hex7.encode(script.pkScript)) {
1223
+ const funded = ArkAddress.decode(lockupAddress).pkScript;
1224
+ if (hex4.encode(funded) !== hex4.encode(script.pkScript)) {
1910
1225
  throw new Error(
1911
- `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`
1226
+ `rfq swap covenant params derive ${hex4.encode(script.pkScript)}, but the record's lockup address holds ${hex4.encode(funded)} \u2014 these params are not this swap's`
1912
1227
  );
1913
1228
  }
1914
1229
  return script;
@@ -1926,11 +1241,7 @@ function rebuildRfqSwap(record, params) {
1926
1241
  refundLocktime: Number(script.options.refundLocktime),
1927
1242
  createdAt: stored.createdAt,
1928
1243
  updatedAt: stored.updatedAt,
1929
- ...stored.refundTxid ? { refundTxid: stored.refundTxid } : {},
1930
- ...stored.lockupSpendTxids?.length ? { lockupSpendTxids: [...stored.lockupSpendTxids] } : {},
1931
- ...stored.failure ? { failure: stored.failure } : {},
1932
- ...stored.claimFailure ? { claimFailure: stored.claimFailure } : {},
1933
- ...stored.blockedReason ? { blockedReason: stored.blockedReason } : {}
1244
+ ...mutableFields(stored)
1934
1245
  };
1935
1246
  const handler = rfqCorridorHandlers.getOrThrow(stored.kind);
1936
1247
  return {
@@ -1944,8 +1255,148 @@ function shouldRetainRfqSwap(record, now) {
1944
1255
  return now - record.updatedAt < RFQ_SWAP_RETENTION_SECONDS;
1945
1256
  }
1946
1257
 
1258
+ // src/claim.ts
1259
+ import {
1260
+ claimWithPreimageIdentity,
1261
+ signAndSubmitOffchainTx
1262
+ } from "@arkade-os/sdk";
1263
+ var LockupAmountMismatchError = class extends Error {
1264
+ name = "LockupAmountMismatchError";
1265
+ reason = "amount_mismatch";
1266
+ expectedAmount;
1267
+ lockedAmount;
1268
+ constructor(expectedAmount, lockedAmount) {
1269
+ super(
1270
+ `lockup holds ${lockedAmount} sats, below the agreed ${expectedAmount} \u2014 refusing to publish the preimage`
1271
+ );
1272
+ this.expectedAmount = expectedAmount;
1273
+ this.lockedAmount = lockedAmount;
1274
+ }
1275
+ };
1276
+ var assertFiniteAmount = (value, reason, label) => {
1277
+ if (Number.isFinite(value)) return;
1278
+ throw gateError(reason, `${label} is not a finite number (${String(value)})`);
1279
+ };
1280
+ async function pushClaim(operator, input) {
1281
+ if (input.vtxos.length === 0) throw new Error("nothing to claim: no funded outputs");
1282
+ assertNoneSwept(input.vtxos, input.contract);
1283
+ const locked = input.vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
1284
+ assertFiniteAmount(locked, "lockup_malformed", "the lockup's summed value");
1285
+ if (!input.partiallyClaimed) {
1286
+ assertFiniteAmount(input.expectedAmount, "invalid_gate_input", "expectedAmount");
1287
+ if (locked < input.expectedAmount) {
1288
+ throw new LockupAmountMismatchError(input.expectedAmount, locked);
1289
+ }
1290
+ }
1291
+ assertPreimageMatches(input.preimage, input.contract.options.preimageHash);
1292
+ const serverUnrollScript = await operatorUnrollScript(operator, input.network);
1293
+ const leaf = input.contract.claim();
1294
+ const txid = await signAndSubmitOffchainTx({
1295
+ identity: claimWithPreimageIdentity(input.receiver, input.preimage),
1296
+ provider: operator,
1297
+ inputs: lockupInputs(input.vtxos, input.contract, leaf),
1298
+ // One aggregate output: this leaf inspects nothing about the output set.
1299
+ outputs: [{ script: input.destinationPkScript, amount: BigInt(locked) }],
1300
+ serverUnrollScript,
1301
+ verifyServerSignatures: { serverPubkey: input.contract.options.server }
1302
+ });
1303
+ return { txid, amount: locked };
1304
+ }
1305
+ async function awaitLockupFunding(contracts, swapPkScript, options = {}) {
1306
+ return pollUntil(
1307
+ async () => {
1308
+ const vtxos = await findLockupVtxos(contracts, swapPkScript);
1309
+ return vtxos.length > 0 ? vtxos : void 0;
1310
+ },
1311
+ options,
1312
+ "lockup_timeout",
1313
+ "the lockup never appeared at the covenant script"
1314
+ );
1315
+ }
1316
+ async function claimReceiveLockup(contracts, operator, input) {
1317
+ const { swapPkScript, pollMs, deadline, ...claim } = input;
1318
+ const vtxos = await awaitLockupFunding(contracts, swapPkScript, { pollMs, deadline });
1319
+ return pushClaim(operator, { ...claim, vtxos });
1320
+ }
1321
+
1322
+ // src/refundBlocked.ts
1323
+ import {
1324
+ ForeignDescriptorError,
1325
+ WalletCannotSignError,
1326
+ contractSigner
1327
+ } from "@arkade-os/sdk";
1328
+ var RefundNotLocallyPossibleError = class extends Error {
1329
+ constructor(reason, message, options) {
1330
+ super(message, options);
1331
+ this.reason = reason;
1332
+ }
1333
+ reason;
1334
+ name = "RefundNotLocallyPossibleError";
1335
+ };
1336
+ async function senderIdentityForSwapRecord(wallet, record) {
1337
+ if (!record.signingDescriptor) {
1338
+ throw new RefundNotLocallyPossibleError(
1339
+ "no-secrets",
1340
+ "this swap record carries no signing descriptor"
1341
+ );
1342
+ }
1343
+ try {
1344
+ return await contractSigner(wallet, record.signingDescriptor);
1345
+ } catch (cause) {
1346
+ if (cause instanceof WalletCannotSignError) {
1347
+ throw new RefundNotLocallyPossibleError(
1348
+ "unsignable-wallet",
1349
+ `this wallet holds ${record.signingDescriptor} but cannot sign with it; attach its signer`,
1350
+ { cause }
1351
+ );
1352
+ }
1353
+ if (cause instanceof ForeignDescriptorError) {
1354
+ throw new RefundNotLocallyPossibleError(
1355
+ "foreign-descriptor",
1356
+ `this wallet cannot derive ${record.signingDescriptor}; the swap was created on another wallet`,
1357
+ { cause }
1358
+ );
1359
+ }
1360
+ throw cause;
1361
+ }
1362
+ }
1363
+
1364
+ // src/arkadeRefunder.ts
1365
+ function arkadeRefunder(deps) {
1366
+ return async (swap) => {
1367
+ const contract = swap.lockup?.script;
1368
+ if (!contract) {
1369
+ throw new Error(
1370
+ `swap ${swap.rfqId} carries no lockup covenant, so its refund cannot be built`
1371
+ );
1372
+ }
1373
+ const vtxos = await findLockupVtxos(deps.contracts, swap.lockupPkScript);
1374
+ if (vtxos.length === 0) return null;
1375
+ const record = await deps.repository.getRfqSwap(swap.rfqId);
1376
+ if (!record) {
1377
+ throw new RefundNotLocallyPossibleError(
1378
+ "no-secrets",
1379
+ `no stored record for ${swap.rfqId}; the descriptor that signs its refund lives there`
1380
+ );
1381
+ }
1382
+ const sender = await senderIdentityForSwapRecord(deps.wallet, rfqSignerOf(record) ?? {});
1383
+ return pushRefundWithoutReceiver(deps.operator, {
1384
+ contract,
1385
+ sender,
1386
+ vtxos,
1387
+ network: await deps.network?.()
1388
+ });
1389
+ };
1390
+ }
1391
+
1947
1392
  // src/swapManager.ts
1948
- import { hex as hex8 } from "@scure/base";
1393
+ import { hex as hex5 } from "@scure/base";
1394
+ import {
1395
+ ArkErrorName,
1396
+ isArkError,
1397
+ isContractVtxoEvent,
1398
+ maybeArkError
1399
+ } from "@arkade-os/sdk";
1949
1400
  function nextOnchainAction(input) {
1950
1401
  switch (input.phase.phase) {
1951
1402
  case "unfunded":
@@ -1989,7 +1440,8 @@ var notify = (listeners, call) => {
1989
1440
  }
1990
1441
  }
1991
1442
  };
1992
- var RfqSwapManager = class {
1443
+ var RfqSwapManager = class _RfqSwapManager {
1444
+ static POLL_CONCURRENCY = 16;
1993
1445
  deps;
1994
1446
  config;
1995
1447
  callbacks = null;
@@ -1998,62 +1450,40 @@ var RfqSwapManager = class {
1998
1450
  swapFailedListeners = /* @__PURE__ */ new Set();
1999
1451
  actionExecutedListeners = /* @__PURE__ */ new Set();
2000
1452
  monitored = /* @__PURE__ */ new Map();
2001
- /** Monitored swaps by lockup script hex, so a contract event — which names
2002
- * a script and nothing else — can find the swap it belongs to. */
1453
+ /** Monitored swaps by lockup script hex: a contract event names only a script. */
2003
1454
  byLockupScript = /* @__PURE__ */ new Map();
2004
1455
  /**
2005
- * Swaps whose lockup registration has been SETTLED one way or another,
2006
- * mapped to whether a contract row actually resulted. Membership is what
2007
- * stops a per-pass retry from becoming a per-pass round trip; the value is
2008
- * what keeps a swap that could never be registered from later trying to
2009
- * retire a row that does not exist, which would report a spurious failure
2010
- * on a swap that in fact succeeded.
1456
+ * Swaps whose lockup registration has SETTLED, mapped to whether a contract row
1457
+ * resulted. Membership stops per-pass round trips; the value stops a never-registered
1458
+ * swap from retiring a nonexistent row and reporting a spurious failure.
2011
1459
  */
2012
1460
  registered = /* @__PURE__ */ new Map();
2013
1461
  /**
2014
- * Swaps whose `refundArkade` answered {@link RefundNotLocallyPossibleError}
2015
- * in this process. Membership stops the push from being re-issued every
2016
- * pass — it cannot start working on its own, and re-issuing it is the
2017
- * grind `needs_counterparty` exists to remove. Only
2018
- * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it, so a caller
2019
- * with no probe learns again on the next start, when the wallet that can
2020
- * sign may well have been restored.
1462
+ * Swaps whose `refundArkade` threw {@link RefundNotLocallyPossibleError} in this
1463
+ * process, so the push is not re-issued every pass. Only
1464
+ * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it.
2021
1465
  */
2022
1466
  refundRefused = /* @__PURE__ */ new Set();
2023
1467
  /**
2024
- * The lockup outpoints a receive swap's claim callback has already been
2025
- * handed, by rfqId.
2026
- *
2027
- * What this exists to prevent: a claim SUCCEEDS, and for the next few
2028
- * passes the indexer still lists those outputs as unspent. Without a
2029
- * record of what was already claimed, every one of those passes would
2030
- * re-submit the same spend, fail against the server, and report a swap
2031
- * that in fact worked as failing. With one, a re-claim happens only when
2032
- * an outpoint appears that was never claimed — a lockup funded piecemeal,
2033
- * which is legitimate and which `partiallyClaimed` exists for.
2034
- *
2035
- * Process-local: after a restart a swap with a live claim tries once more.
2036
- * That is the recovery case rather than the spam one — a claim that never
2037
- * landed leaves its outputs unspent, and one that did leaves a single
2038
- * rejection.
1468
+ * Lockup outpoints already handed to a receive swap's claim callback, by rfqId. After a
1469
+ * claim SUCCEEDS the indexer may still list its outputs as unspent; without this each
1470
+ * pass would re-submit and report a working swap as failing. Process-local: a restart
1471
+ * costs at most one rejected re-claim.
2039
1472
  */
2040
1473
  claimedOutpoints = /* @__PURE__ */ new Map();
2041
1474
  /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
2042
1475
  unsubscribeContracts = null;
2043
- /** Terminal records, kept so a late {@link waitForSwapCompletion} still
2044
- * answers instead of throwing "not found". Cleared by {@link removeSwap}. */
1476
+ /** Recent terminal swaps; older durable outcomes are read from the record store on demand. */
2045
1477
  finished = /* @__PURE__ */ new Map();
1478
+ /** Explicit removals stay suppressed for this manager lifetime; normal completions never enter this set.
1479
+ * Each maps to its removal sequence, so restore can tell a removal made during its rebuild. */
1480
+ removed = /* @__PURE__ */ new Map();
1481
+ removalSeq = 0;
2046
1482
  waiters = /* @__PURE__ */ new Map();
2047
1483
  /**
2048
- * The request-time origin of each swap the manager may have to CREATE a
2049
- * record for, by rfqId.
2050
- *
2051
- * Needed only for a swap the store has never seen: once a record exists,
2052
- * `updateRfqSwapRecord` carries the origin half through and the map is
2053
- * redundant. It is kept anyway for the swap's whole life, so a record the
2054
- * store loses between passes is rewritten rather than lost — and dropped
2055
- * by {@link removeSwap} and by retention, which are the two places a swap
2056
- * stops being this manager's business.
1484
+ * The request-time origin of each swap, by rfqId, needed to CREATE a record. Kept for
1485
+ * the swap's whole life so a record the store loses is rewritten; dropped by
1486
+ * {@link removeSwap} and by retention.
2057
1487
  */
2058
1488
  origins = /* @__PURE__ */ new Map();
2059
1489
  /** Records changed during the current pass, flushed to the repository and
@@ -2061,6 +1491,8 @@ var RfqSwapManager = class {
2061
1491
  dirty = /* @__PURE__ */ new Set();
2062
1492
  /** Race guard: one action at a time per swap. */
2063
1493
  inProgress = /* @__PURE__ */ new Set();
1494
+ activePolls = 0;
1495
+ pollWaiters = /* @__PURE__ */ new Set();
2064
1496
  timer = null;
2065
1497
  running = false;
2066
1498
  constructor(deps, config = {}) {
@@ -2079,9 +1511,8 @@ var RfqSwapManager = class {
2079
1511
  this.actionExecutedListeners.add(config.events.onActionExecuted);
2080
1512
  }
2081
1513
  }
2082
- /** Wire the money-moving half. Without it the manager only watches. The
2083
- * two claims may be omitted for a consumer that drives no kind reaching
2084
- * them — see {@link AvailableRfqSwapManagerCallbacks}. */
1514
+ /** Wire the money-moving half. Without it the manager only watches. See
1515
+ * {@link AvailableRfqSwapManagerCallbacks}. */
2085
1516
  setCallbacks(callbacks) {
2086
1517
  this.callbacks = callbacks;
2087
1518
  }
@@ -2102,41 +1533,21 @@ var RfqSwapManager = class {
2102
1533
  return () => this.actionExecutedListeners.delete(listener);
2103
1534
  }
2104
1535
  /**
2105
- * Rebuild every stored swap and take over monitoring them.
2106
- *
2107
- * The composition a consumer otherwise writes by hand, and the one place
2108
- * all four pieces meet: retention decides what to keep
2109
- * (`shouldRetainRfqSwap`), the lockup's contract row supplies the covenant
2110
- * (`lockupContractParams`), `rebuildRfqSwap` turns a record back into a
2111
- * live swap, and each rebuilt swap arrives with its own origin, so nothing
2112
- * is asked of the caller.
2113
- *
2114
- * **Deliberately not part of {@link start}.** A consumer that wants to
2115
- * look at its records — count them, show them, prune and stop — is not
2116
- * forced to start driving money to do it. Call this first and `start()`
2117
- * after; a manager already running polls the restored swaps at once.
2118
- *
2119
- * Retention runs BEFORE the rebuild, so a record past
2120
- * `RFQ_SWAP_RETENTION_SECONDS` costs no contract lookup on its way to being
2121
- * dropped.
2122
- *
2123
- * **A record that cannot be rebuilt is reported, never swallowed and never
2124
- * fatal.** `rebuildRfqSwap` throws by design when the covenant params do
2125
- * not derive the funded address, and `lockupContractParams` throws
2126
- * `LockupContractMissing` when the wallet has no row for the lockup — both
2127
- * say something true about that one record, and neither is a reason to
2128
- * strand the others. They come back in {@link RfqRestoreResult.failed}.
1536
+ * Rebuild stored swaps and take over monitoring them. By default only active states
1537
+ * are read; terminal history stays stored and a late completion lookup reads one record
1538
+ * by key (`includeTerminal` loads everything). Deliberately not part of {@link start},
1539
+ * so records can be inspected without driving money. An unrebuildable record lands in
1540
+ * {@link RfqRestoreResult.failed}, never fatal to the others.
2129
1541
  */
2130
1542
  async restoreFromRepository(options = {}) {
2131
1543
  const repository = this.requireRepository("restoreFromRepository");
2132
1544
  const params = options.params ?? this.paramsFromContracts();
2133
- const records = await repository.getAllRfqSwaps();
2134
- const pruned = await this.dropRetired(repository, records);
2135
- const retired = new Set(pruned);
2136
1545
  const restored = [];
2137
1546
  const failed = [];
2138
- for (const record of records) {
2139
- if (retired.has(record.rfqId)) continue;
1547
+ const restore = async (record) => {
1548
+ if (!options.includeTerminal && isRfqSwapTerminal(record.state)) return;
1549
+ if (this.monitored.has(record.rfqId)) return;
1550
+ const removedAt = this.removed.get(record.rfqId);
2140
1551
  let swap;
2141
1552
  try {
2142
1553
  swap = rebuildRfqSwap(record, await params(record));
@@ -2145,38 +1556,37 @@ var RfqSwapManager = class {
2145
1556
  rfqId: record.rfqId,
2146
1557
  error: error instanceof Error ? error : new Error(errorMessage(error))
2147
1558
  });
2148
- continue;
1559
+ return;
1560
+ }
1561
+ if (this.monitored.has(record.rfqId)) return;
1562
+ if (this.removed.get(record.rfqId) !== removedAt) return;
1563
+ this.removed.delete(record.rfqId);
1564
+ if (isRfqSwapTerminal(swap.state)) this.rememberFinished(swap, true);
1565
+ else {
1566
+ this.origins.set(record.rfqId, rfqSwapOriginOf(record));
1567
+ this.track(swap);
2149
1568
  }
2150
- this.origins.set(record.rfqId, rfqSwapOriginOf(record));
2151
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
2152
- else this.track(swap);
2153
1569
  restored.push(swap);
1570
+ };
1571
+ const states = options.includeTerminal ? [void 0] : RFQ_SWAP_ACTIVE_STATES;
1572
+ for (const state of states) {
1573
+ for (const record of await collectRfqSwaps(repository, { state }))
1574
+ await restore(record);
2154
1575
  }
2155
1576
  if (this.running) {
2156
- await Promise.allSettled(
2157
- restored.filter((swap) => this.monitored.has(swap.rfqId)).map((swap) => this.pollSwap(swap))
2158
- );
1577
+ await this.pollMany(restored.filter((swap) => this.monitored.has(swap.rfqId)));
2159
1578
  }
2160
- return { restored, failed, pruned };
1579
+ return { restored, failed, pruned: [] };
2161
1580
  }
2162
1581
  /**
2163
- * Drop stored records that are terminal and past
2164
- * `RFQ_SWAP_RETENTION_SECONDS`, and return their ids.
2165
- *
2166
- * `needs_counterparty` is never dropped, however old: the money is still at
2167
- * the lockup and the counterparty's move still ends the swap. That rule
2168
- * lives in `shouldRetainRfqSwap`, which this defers to rather than
2169
- * restating.
2170
- *
2171
- * Public because retention is a caller's cadence, not the manager's: a
2172
- * long-lived process wants it on a timer of its own, a mobile app wants it
2173
- * at boot. {@link restoreFromRepository} runs it first, so the boot path
2174
- * needs no separate call.
1582
+ * Drop stored records that are terminal and past `RFQ_SWAP_RETENTION_SECONDS` (per
1583
+ * `shouldRetainRfqSwap`), and return their ids. Explicit only: restore keeps history.
1584
+ * Loads every stored record; no backend offers indexed deletion.
2175
1585
  */
2176
1586
  async pruneRetiredSwaps() {
2177
1587
  const repository = this.deps.repository;
2178
1588
  if (!repository) return [];
2179
- return this.dropRetired(repository, await repository.getAllRfqSwaps());
1589
+ return this.dropRetired(repository, await collectRfqSwaps(repository));
2180
1590
  }
2181
1591
  async dropRetired(repository, records) {
2182
1592
  const now = this.config.now();
@@ -2184,12 +1594,15 @@ var RfqSwapManager = class {
2184
1594
  for (const record of records) {
2185
1595
  if (shouldRetainRfqSwap(record, now)) continue;
2186
1596
  await repository.removeRfqSwap(record.rfqId);
2187
- this.finished.delete(record.rfqId);
2188
- if (!this.monitored.has(record.rfqId)) this.origins.delete(record.rfqId);
1597
+ this.forgetRetired(record.rfqId);
2189
1598
  dropped.push(record.rfqId);
2190
1599
  }
2191
1600
  return dropped;
2192
1601
  }
1602
+ forgetRetired(rfqId) {
1603
+ this.finished.delete(rfqId);
1604
+ if (!this.monitored.has(rfqId)) this.origins.delete(rfqId);
1605
+ }
2193
1606
  requireRepository(method) {
2194
1607
  const repository = this.deps.repository;
2195
1608
  if (!repository) {
@@ -2199,9 +1612,7 @@ var RfqSwapManager = class {
2199
1612
  }
2200
1613
  return repository;
2201
1614
  }
2202
- /** The default covenant source: the wallet's own contract row for each
2203
- * lockup, which is where registration put it before the address could be
2204
- * funded. */
1615
+ /** The default covenant source: the wallet's own contract row for each lockup. */
2205
1616
  paramsFromContracts() {
2206
1617
  const contracts = this.deps.contracts;
2207
1618
  if (!contracts) {
@@ -2212,28 +1623,23 @@ var RfqSwapManager = class {
2212
1623
  return (record) => lockupContractParams(contracts, record.lockupAddress);
2213
1624
  }
2214
1625
  /**
2215
- * Load records and begin monitoring. Runs one pass immediately — a caller
2216
- * resuming after a restart may be well past a deadline already — then
2217
- * every `pollIntervalMs`. Records that are already terminal are kept only
2218
- * so {@link waitForSwapCompletion} can answer for them.
2219
- *
2220
- * Calling it again while running loads the records and returns rather than
2221
- * re-arming — dropping them silently would strand a funded swap on a
2222
- * caller's harmless double-start.
1626
+ * Load records and begin monitoring: one pass immediately (a restart may already be
1627
+ * past a deadline), then every `pollIntervalMs`. Terminal outcomes in a repository are
1628
+ * read on demand. Calling it again while running loads the records without re-arming,
1629
+ * so a double-start never strands a funded swap.
2223
1630
  *
2224
- * The signature is unchanged with a {@link RfqSwapManagerDeps.repository}
2225
- * wired; the origins are resolved from the store instead, by the same rule
2226
- * {@link addSwap} applies. A swap the store has never seen throws
2227
- * {@link RfqSwapOriginRequired} — hand that one to `addSwap` with its
2228
- * origin, or restore the whole set with {@link restoreFromRepository},
2229
- * which needs no caller input at all. Every swap is checked before any is
2230
- * tracked, so a bad one in the list does not leave a half-loaded manager.
1631
+ * With a repository wired, a swap the store has never seen throws
1632
+ * {@link RfqSwapOriginRequired} (use {@link addSwap} with its origin, or
1633
+ * {@link restoreFromRepository}). Every swap is checked before any is tracked.
2231
1634
  */
2232
1635
  async start(swaps = []) {
2233
1636
  for (const swap of swaps) await this.admit(swap);
2234
1637
  for (const swap of swaps) {
2235
- if (isRfqSwapTerminal(swap.state)) this.finished.set(swap.rfqId, swap);
2236
- else this.track(swap);
1638
+ this.removed.delete(swap.rfqId);
1639
+ if (isRfqSwapTerminal(swap.state)) {
1640
+ this.rememberFinished(swap);
1641
+ this.origins.delete(swap.rfqId);
1642
+ } else this.track(swap);
2237
1643
  }
2238
1644
  if (this.running) return;
2239
1645
  this.running = true;
@@ -2242,16 +1648,10 @@ var RfqSwapManager = class {
2242
1648
  this.arm();
2243
1649
  }
2244
1650
  /**
2245
- * Stop monitoring and clear the timer. In-flight actions are not
2246
- * cancellable and run to completion; outstanding
2247
- * {@link waitForSwapCompletion} promises are left pending, since
2248
- * stop/start is a pause rather than a cancellation.
2249
- *
2250
- * The contract subscription is dropped too — an open stream with nothing
2251
- * reacting to it is a leak, and {@link start} puts it back. What is NOT
2252
- * undone is the contract registration: those rows are the wallet's, they
2253
- * outlive this manager's lifecycle, and dropping them would unwatch a
2254
- * lockup that is still funded.
1651
+ * Stop monitoring: clear the timer and drop the contract subscription. In-flight
1652
+ * actions run to completion and {@link waitForSwapCompletion} promises stay pending
1653
+ * (stop/start is a pause). Contract registrations are NOT undone: they are the
1654
+ * wallet's, and dropping them would unwatch a still-funded lockup.
2255
1655
  */
2256
1656
  async stop() {
2257
1657
  this.running = false;
@@ -2263,35 +1663,26 @@ var RfqSwapManager = class {
2263
1663
  this.unsubscribeContracts = null;
2264
1664
  }
2265
1665
  /**
2266
- * Begin monitoring a swap. Polled immediately when the manager is running,
2267
- * so a just-funded swap does not wait out a whole interval.
1666
+ * Begin monitoring a swap; polled immediately when the manager is running.
2268
1667
  *
2269
- * `origin` is the request-time half a live swap cannot carry — the corridor,
2270
- * the funded address, the corridor's profile, the funding txid — and it is
2271
- * what lets the manager write this swap's FIRST record. Supply it whenever
2272
- * a {@link RfqSwapManagerDeps.repository} is wired and the swap is new. It
2273
- * may be omitted for a swap the store already holds a record for, which is
2274
- * then read to confirm it; omitting it for one the store has never seen
2275
- * throws {@link RfqSwapOriginRequired} rather than admitting a swap whose
2276
- * record could never be written. With no repository wired the parameter is
2277
- * inert.
1668
+ * @param origin - The request-time half a live swap cannot carry, needed to write its
1669
+ * FIRST record. Required with a repository wired unless the store already holds the
1670
+ * record (else {@link RfqSwapOriginRequired}). Inert without a repository.
2278
1671
  */
2279
1672
  async addSwap(swap, origin) {
2280
1673
  await this.admit(swap, origin);
1674
+ this.removed.delete(swap.rfqId);
2281
1675
  if (isRfqSwapTerminal(swap.state)) {
2282
- this.finished.set(swap.rfqId, swap);
1676
+ this.rememberFinished(swap);
1677
+ this.origins.delete(swap.rfqId);
2283
1678
  return;
2284
1679
  }
2285
1680
  this.track(swap);
2286
1681
  if (this.running) await this.pollSwap(swap);
2287
1682
  }
2288
1683
  /**
2289
- * Settle where this swap's record will come from, before it is monitored.
2290
- *
2291
- * Three ways it can be answered, in order: the caller passed an origin, one
2292
- * is already remembered from an earlier `addSwap`, or the store holds a
2293
- * record — which is the origin, already written. Only the last costs a read,
2294
- * and only when the first two are absent.
1684
+ * Settle where this swap's record will come from, before it is monitored: a passed
1685
+ * origin, one remembered from an earlier `addSwap`, or the stored record (one read).
2295
1686
  */
2296
1687
  async admit(swap, origin) {
2297
1688
  if (origin) {
@@ -2308,13 +1699,10 @@ var RfqSwapManager = class {
2308
1699
  if (!stored) throw new RfqSwapOriginRequired(swap.rfqId);
2309
1700
  this.origins.set(swap.rfqId, rfqSwapOriginOf(stored));
2310
1701
  }
2311
- /** Forget a swap entirely, monitored or finished.
2312
- *
2313
- * Its contract row is left alone: registration is a wallet-level fact about
2314
- * a script that may still hold money, and this call says only that THIS
2315
- * manager stops driving the swap. Retiring the row is reserved for a swap
2316
- * that reached a terminal state, where the lockup is provably done. */
1702
+ /** Forget a swap entirely, monitored or finished. Its contract row is left alone: the
1703
+ * script may still hold money, and only a terminal swap's row is retired. */
2317
1704
  async removeSwap(rfqId) {
1705
+ this.removed.set(rfqId, ++this.removalSeq);
2318
1706
  this.untrack(rfqId);
2319
1707
  this.finished.delete(rfqId);
2320
1708
  this.registered.delete(rfqId);
@@ -2332,14 +1720,8 @@ var RfqSwapManager = class {
2332
1720
  return [...this.monitored.values()];
2333
1721
  }
2334
1722
  /**
2335
- * Every swap this manager holds — {@link getPendingSwaps} plus the ones
2336
- * that already ended. The two sets are disjoint: a swap leaves `monitored`
2337
- * as it enters `finished`.
2338
- *
2339
- * The finished half is what this process has seen, which after
2340
- * {@link restoreFromRepository} is the stored history minus what retention
2341
- * pruned. A manager that has restored nothing answers with the live swaps
2342
- * alone.
1723
+ * Every swap this manager holds: {@link getPendingSwaps} plus the finished ones this
1724
+ * process has seen (after {@link restoreFromRepository}, the retained history).
2343
1725
  */
2344
1726
  async getAllSwaps() {
2345
1727
  return [...this.monitored.values(), ...this.finished.values()];
@@ -2351,6 +1733,7 @@ var RfqSwapManager = class {
2351
1733
  async isProcessing(rfqId) {
2352
1734
  return this.inProgress.has(rfqId);
2353
1735
  }
1736
+ /** `finishedSwaps` counts terminal swaps cached in memory, not those only in the repository. */
2354
1737
  async getStats() {
2355
1738
  return {
2356
1739
  isRunning: this.running,
@@ -2361,34 +1744,54 @@ var RfqSwapManager = class {
2361
1744
  };
2362
1745
  }
2363
1746
  /**
2364
- * Run one monitoring pass over every swap now.
2365
- *
2366
- * {@link start} calls this on an interval, but it is public on purpose: a
2367
- * caller that sleeps its process (a mobile app resuming, a service worker
2368
- * waking) wants a pass on that event rather than at the next tick. Passes
2369
- * do not overlap per swap — the in-progress lock makes a concurrent call a
2370
- * no-op for any swap already being worked on.
1747
+ * Run one monitoring pass over every swap now, e.g. when a mobile app resumes. Passes
1748
+ * do not overlap per swap: a concurrent call is a no-op for a swap already in progress.
2371
1749
  */
2372
1750
  async poll() {
2373
- await Promise.allSettled([...this.monitored.values()].map((swap) => this.pollSwap(swap)));
1751
+ await this.pollMany([...this.monitored.values()]);
1752
+ }
1753
+ async pollMany(swaps) {
1754
+ for (let i = 0; i < swaps.length; i += _RfqSwapManager.POLL_CONCURRENCY) {
1755
+ await Promise.allSettled(
1756
+ swaps.slice(i, i + _RfqSwapManager.POLL_CONCURRENCY).map((swap) => this.pollSwap(swap))
1757
+ );
1758
+ }
1759
+ }
1760
+ async acquirePollSlot() {
1761
+ if (this.activePolls < _RfqSwapManager.POLL_CONCURRENCY) {
1762
+ this.activePolls++;
1763
+ } else {
1764
+ await new Promise((resolve) => this.pollWaiters.add(resolve));
1765
+ }
1766
+ return () => {
1767
+ const next = this.pollWaiters.values().next().value;
1768
+ if (next) {
1769
+ this.pollWaiters.delete(next);
1770
+ next();
1771
+ } else {
1772
+ this.activePolls--;
1773
+ }
1774
+ };
2374
1775
  }
2375
1776
  /**
2376
- * Resolve once this swap's PAYOUT is decided — which for onchain-send is
2377
- * the L1 claim, not the end of the record's life: once `claimTxid` is set
2378
- * the trader has the coins it swapped for, and what remains is the manager
2379
- * watching the Arkade lockup close. That holds however the record is
2380
- * labelled afterwards, `needs_counterparty` included. Lightning-send has no
2381
- * such split and resolves at `settled`/`refunded`, and so does lightning
2382
- * receive — see {@link isPayoutDecided} for why its own claim txid does not
2383
- * decide it.
1777
+ * Resolve once this swap's PAYOUT is decided: for onchain-send that is the L1 claim
1778
+ * (`claimTxid` set), whatever the record's later label; otherwise `settled`/`refunded`
1779
+ * (see {@link isPayoutDecided}).
2384
1780
  *
2385
- * Rejects only on `failed`. `refunded` resolves: on a send leg a refund is
2386
- * an outcome the caller asked this manager to drive, not an exception. On a
2387
- * receive leg it is the swap being lost, which is still an answer and not
2388
- * an error — read `state`, do not infer success from resolution.
1781
+ * Rejects only on `failed`. `refunded` resolves, and on a receive leg it means the swap
1782
+ * was lost — read `state`, do not infer success from resolution.
2389
1783
  */
2390
1784
  async waitForSwapCompletion(rfqId) {
2391
1785
  const swap = this.monitored.get(rfqId) ?? this.finished.get(rfqId);
1786
+ if (!swap && !this.removed.has(rfqId) && this.deps.repository) {
1787
+ const record = await this.deps.repository.getRfqSwap(rfqId);
1788
+ if (record && !this.removed.has(rfqId) && isRfqSwapTerminal(record.state)) {
1789
+ if (record.state === "failed") {
1790
+ throw new Error(record.failure ?? `swap ${rfqId} failed`);
1791
+ }
1792
+ return outcomeOfRecord(record);
1793
+ }
1794
+ }
2392
1795
  if (!swap) throw new Error(`swap ${rfqId} is not monitored`);
2393
1796
  if (swap.state === "failed") throw new Error(swap.failure ?? `swap ${rfqId} failed`);
2394
1797
  if (isPayoutDecided(swap)) return outcomeOf(swap);
@@ -2401,38 +1804,26 @@ var RfqSwapManager = class {
2401
1804
  // ── internals ────────────────────────────────────────────────────────────
2402
1805
  track(swap) {
2403
1806
  this.monitored.set(swap.rfqId, swap);
2404
- this.byLockupScript.set(hex8.encode(swap.lockupPkScript), swap);
1807
+ this.byLockupScript.set(hex5.encode(swap.lockupPkScript), swap);
2405
1808
  }
2406
- /** Drops the swap from BOTH indexes. The event index is the one that stops
2407
- * a late event finding a swap that is gone; `pollSwap`'s own
2408
- * `monitored` check would also catch it, and deliberately still does —
2409
- * either alone is sufficient, which is what keeps a future change to one of
2410
- * them from silently re-driving a cancelled swap. */
1809
+ /** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
1810
+ * event, deliberately redundant so neither change alone re-drives a removed swap. */
2411
1811
  untrack(rfqId) {
2412
1812
  const swap = this.monitored.get(rfqId);
2413
- if (swap) this.byLockupScript.delete(hex8.encode(swap.lockupPkScript));
1813
+ if (swap) this.byLockupScript.delete(hex5.encode(swap.lockupPkScript));
2414
1814
  this.monitored.delete(rfqId);
2415
1815
  this.refundRefused.delete(rfqId);
2416
1816
  this.claimedOutpoints.delete(rfqId);
2417
1817
  }
2418
1818
  /**
2419
- * Turn the indexer's push into an extra reason to run a pass — and nothing
2420
- * more.
1819
+ * Turn the indexer's push into an extra reason to run a pass — and nothing more.
2421
1820
  *
2422
- * **This is deliberately not a source of truth.** An event names a script;
2423
- * the reaction is to run the ordinary pass for the swap at that script, and
2424
- * that pass re-reads the lockup through {@link readLockupFate} exactly as
2425
- * the timer's pass does. So an event that is missed, duplicated, reordered
2426
- * or outright FORGED can only cost or save latency — it can never change
2427
- * what this manager believes about a swap, and it can never on its own
2428
- * cause a claim or a refund. That property is what makes it safe to bolt a
2429
- * best-effort stream onto a money path, and it must survive any future
2430
- * change here: the moment an event is BELIEVED rather than merely acted on,
2431
- * a relay outage becomes a correctness problem instead of a latency one.
2432
- *
2433
- * The timer stays armed regardless, and is the failsafe. Every deadline
2434
- * that moves money — `refundLocktime`, the L1 claim window — is an absolute
2435
- * timelock that passes whether or not a single event ever arrives.
1821
+ * **Deliberately not a source of truth.** The pass re-reads the lockup via
1822
+ * {@link readLockupFate}, so a missed, duplicated, reordered or FORGED event only
1823
+ * changes latency, never beliefs, and never causes a claim or refund on its own. This
1824
+ * must survive future changes: a BELIEVED event turns a relay outage into a correctness
1825
+ * bug. The timer stays armed as the failsafe; every money deadline is an absolute
1826
+ * timelock.
2436
1827
  */
2437
1828
  subscribe() {
2438
1829
  if (!this.deps.contracts || this.unsubscribeContracts) return;
@@ -2442,6 +1833,7 @@ var RfqSwapManager = class {
2442
1833
  });
2443
1834
  return;
2444
1835
  }
1836
+ if (!isContractVtxoEvent(event)) return;
2445
1837
  const swap = this.byLockupScript.get(event.contractScript);
2446
1838
  if (!swap) return;
2447
1839
  void this.pollSwap(swap).catch(() => {
@@ -2449,19 +1841,12 @@ var RfqSwapManager = class {
2449
1841
  });
2450
1842
  }
2451
1843
  /**
2452
- * Register this swap's lockup with the wallet's contract manager, once.
2453
- *
2454
- * The backstop, not the primary site: `requestLightningSend` /
2455
- * `requestOnchainSend` register before the caller can fund, so this covers
2456
- * swaps whose records predate that — and costs nothing when it does not,
2457
- * since `createContract` is first-writer-wins.
1844
+ * Register this swap's lockup with the wallet's contract manager, once. A backstop:
1845
+ * the request entrypoints register before funding, and `createContract` is
1846
+ * first-writer-wins.
2458
1847
  *
2459
- * Best-effort by design: a failure here is reported and retried on the next
2460
- * pass, and never aborts the pass it is part of. Registration buys latency
2461
- * and puts the lockup in the wallet's contract set; it decides nothing. The
2462
- * money path below it reads the indexer directly and is gated on timelocks
2463
- * that a missing contract row has no bearing on, so failing the pass over
2464
- * this would trade a real deadline for a bookkeeping one.
1848
+ * Best-effort: a failure is reported and retried next pass, never aborting this one.
1849
+ * Failing the pass over bookkeeping would trade a real timelock deadline for it.
2465
1850
  */
2466
1851
  async ensureRegistered(swap) {
2467
1852
  const contracts = this.deps.contracts;
@@ -2471,7 +1856,7 @@ var RfqSwapManager = class {
2471
1856
  if (!lockup) {
2472
1857
  try {
2473
1858
  const [existing] = await contracts.getContracts({
2474
- script: hex8.encode(swap.lockupPkScript)
1859
+ script: hex5.encode(swap.lockupPkScript)
2475
1860
  });
2476
1861
  if (existing) {
2477
1862
  this.registered.set(swap.rfqId, true);
@@ -2490,13 +1875,13 @@ var RfqSwapManager = class {
2490
1875
  );
2491
1876
  return;
2492
1877
  }
2493
- const script = hex8.encode(lockup.script.pkScript);
2494
- if (script !== hex8.encode(swap.lockupPkScript)) {
1878
+ const script = hex5.encode(lockup.script.pkScript);
1879
+ if (script !== hex5.encode(swap.lockupPkScript)) {
2495
1880
  this.registered.set(swap.rfqId, false);
2496
1881
  this.emitFailed(
2497
1882
  swap,
2498
1883
  new Error(
2499
- `swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${hex8.encode(swap.lockupPkScript)}`
1884
+ `swap ${swap.rfqId} lockup script ${script} does not match its lockupPkScript ${hex5.encode(swap.lockupPkScript)}`
2500
1885
  )
2501
1886
  );
2502
1887
  return;
@@ -2508,14 +1893,12 @@ var RfqSwapManager = class {
2508
1893
  this.emitFailed(swap, error);
2509
1894
  }
2510
1895
  }
2511
- /** Stop watching a finished swap's lockup. Retained, not deleted: the row
2512
- * is what keeps the lockup's own VTXOs annotatable and its history
2513
- * readable, while `retained` is what drops it from the subscription and
2514
- * the poll — a settled swap that stayed watched would cost the wallet a
2515
- * script for its whole life. Best-effort — the swap is over either way. */
1896
+ /** Stop watching a finished swap's lockup. `retained`, not deleted: the row keeps the
1897
+ * lockup's history readable while leaving the subscription and poll. Best-effort. */
2516
1898
  retireContract(swap) {
2517
1899
  if (!this.deps.contracts || !this.registered.get(swap.rfqId)) return;
2518
- void this.deps.contracts.setContractWatchState(hex8.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
1900
+ if (!LOCKUP_RETIRABLE.includes(swap.state)) return;
1901
+ void this.deps.contracts.setContractWatchState(hex5.encode(swap.lockupPkScript), "retained").catch((error) => this.emitFailed(swap, error));
2519
1902
  }
2520
1903
  arm() {
2521
1904
  if (!this.running) return;
@@ -2525,22 +1908,38 @@ var RfqSwapManager = class {
2525
1908
  void this.poll().then(() => this.arm());
2526
1909
  }, this.config.pollIntervalMs);
2527
1910
  }
1911
+ /*
1912
+ * One serialized monitoring pass for a single swap. The per-swap lock is released only
1913
+ * after all async work, so overlapping polls cannot submit duplicate claims or refunds.
1914
+ *
1915
+ * Safety property: terminal state is not finalized until its record is persisted to
1916
+ * every configured sink. A failed save leaves the swap dirty and monitored for retry.
1917
+ */
2528
1918
  async pollSwap(swap) {
2529
1919
  if (this.inProgress.has(swap.rfqId)) return;
2530
1920
  if (!this.monitored.has(swap.rfqId)) return;
2531
1921
  this.inProgress.add(swap.rfqId);
1922
+ const release = await this.acquirePollSlot();
2532
1923
  try {
2533
- await this.runPass(swap);
1924
+ if (this.monitored.has(swap.rfqId)) await this.runPass(swap);
2534
1925
  } finally {
2535
- const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
2536
- if (persisted) {
2537
- this.dirty.delete(swap.rfqId);
2538
- this.settleWaiters(swap);
2539
- if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
1926
+ try {
1927
+ const persisted = this.dirty.has(swap.rfqId) ? await this.save(swap) : true;
1928
+ if (persisted) {
1929
+ this.dirty.delete(swap.rfqId);
1930
+ this.settleWaiters(swap);
1931
+ if (isRfqSwapTerminal(swap.state)) this.finalize(swap);
1932
+ }
1933
+ } finally {
1934
+ this.inProgress.delete(swap.rfqId);
1935
+ release();
2540
1936
  }
2541
- this.inProgress.delete(swap.rfqId);
2542
1937
  }
2543
1938
  }
1939
+ /*
1940
+ * One state-machine pass (steps as in the class doc). Persistence, waiters,
1941
+ * finalization and the per-swap lock belong to `pollSwap`.
1942
+ */
2544
1943
  async runPass(swap) {
2545
1944
  await this.ensureRegistered(swap);
2546
1945
  let fate;
@@ -2554,11 +1953,15 @@ var RfqSwapManager = class {
2554
1953
  }
2555
1954
  if (fate.fate === "claimed" || fate.fate === "returned") {
2556
1955
  this.stampLockupSpends(swap, fate.spends);
1956
+ if (fate.fate === "claimed") this.stampSettlementPreimage(swap, fate.preimage);
2557
1957
  this.setState(swap, fate.fate === "claimed" ? "settled" : "refunded");
2558
1958
  return;
2559
1959
  }
2560
1960
  if (swap.kind === "lightning_receive") {
2561
- return fate.fate === "exited" ? this.blockExitedLockup(swap, fate) : this.driveReceiveClaim(swap);
1961
+ if (fate.fate === "exited") return this.blockExitedLockup(swap, fate);
1962
+ if (fate.fate === "open") return this.driveReceiveClaim(swap);
1963
+ if (this.config.now() >= swap.refundLocktime) return this.driveReceiveClaim(swap);
1964
+ return;
2562
1965
  }
2563
1966
  if (swap.kind === "onchain_send" && swap.state !== "claimed") {
2564
1967
  if (await this.driveOnchain(swap) === "handled") return;
@@ -2571,15 +1974,9 @@ var RfqSwapManager = class {
2571
1974
  await this.driveArkadeRefund(swap);
2572
1975
  }
2573
1976
  /**
2574
- * The lockup was unilaterally exited: its outputs sit onchain under the
2575
- * VHTLC script, where no offchain claim or refund can reach them.
2576
- *
2577
- * `needs_counterparty` rather than a terminal state, because the money still
2578
- * needs action and the swap can still end either way — an onchain claim can
2579
- * reveal the preimage, an onchain refund can return it — and that state is
2580
- * documented as re-checked every pass. It must be set from HERE and not from
2581
- * inside `driveArkadeRefund`, whose two `unblock` calls would lift it again
2582
- * on the very next pass.
1977
+ * The lockup was unilaterally exited: its outputs sit onchain, beyond any offchain
1978
+ * spend. `needs_counterparty`, not terminal: it can still end either way onchain. Set
1979
+ * here, not in `driveArkadeRefund`, whose `unblock` calls would lift it next pass.
2583
1980
  */
2584
1981
  blockExitedLockup(swap, fate) {
2585
1982
  this.block(
@@ -2588,32 +1985,22 @@ var RfqSwapManager = class {
2588
1985
  );
2589
1986
  }
2590
1987
  /**
2591
- * The receive leg's whole state machine: claim the solver-funded lockup
2592
- * while the window is open, and recognise the shapes in which it can be
2593
- * lost.
1988
+ * The receive leg's whole state machine: claim the solver-funded lockup while the
1989
+ * window is open, and recognise the shapes in which it can be lost.
2594
1990
  *
2595
- * **The window closes at `refundLocktime`, on wall clock, with no margin.**
2596
- * Both halves of that are deliberate. It closes there because publishing
2597
- * `P` into the solver's live refund window risks losing the race and
2598
- * handing over the preimage anyway — the hazard `ONCHAIN_CLAIM_MARGIN_SECONDS`
2599
- * guards on the L1 side. It takes no margin because the two situations are
2600
- * not alike: that one budgets for confirmation depth, while this claim is an
2601
- * offchain spend that lands in seconds. Wall clock is already the
2602
- * conservative reading — the solver's leaf is a CLTV, which matures against
2603
- * median-time-past, and MTP trails wall clock — so the real window extends
2604
- * PAST this deadline rather than ending before it. Every second of margin
2605
- * subtracted here is a second of live claim window given away for nothing.
1991
+ * **The window closes at `refundLocktime`, on wall clock, with no margin.** Publishing
1992
+ * `P` into the solver's live refund window risks losing the race. No margin (unlike
1993
+ * `ONCHAIN_CLAIM_MARGIN_SECONDS`, which budgets for confirmations): this offchain claim
1994
+ * lands in seconds, and the solver's CLTV matures on MTP, which trails wall clock.
2606
1995
  *
2607
- * **The trader has no move after it.** Nothing here can take the lockup
2608
- * back, so once the window shuts the swap is the solver's to resolve and
2609
- * this manager's job is to watch it happen and then stop.
1996
+ * After the window the trader has no move; the manager only watches.
2610
1997
  */
2611
1998
  async driveReceiveClaim(swap) {
2612
1999
  const now = this.config.now();
2613
2000
  if (now < swap.refundLocktime) {
2614
2001
  let vtxos;
2615
2002
  try {
2616
- vtxos = await findLockupVtxos(this.deps.indexer, swap.lockupPkScript);
2003
+ vtxos = await findLockupVtxos(this.deps.contracts, swap.lockupPkScript);
2617
2004
  } catch (error) {
2618
2005
  this.emitFailed(swap, error);
2619
2006
  return;
@@ -2633,14 +2020,8 @@ var RfqSwapManager = class {
2633
2020
  }
2634
2021
  this.setState(swap, "refunded");
2635
2022
  }
2636
- /**
2637
- * Claim what the solver funded, once it is enough.
2638
- *
2639
- * The value gate here decides WHEN to act. `pushClaim`'s decides whether
2640
- * `P` is published, and runs with nothing between it and the signature —
2641
- * the check that matters is the inner one, and this is not a reason to
2642
- * relax it.
2643
- */
2023
+ /** Claim what the solver funded, once it is enough (the inner gate that matters is
2024
+ * `pushClaim`'s; see {@link RfqSwapManagerCallbacks.claimLockup}). */
2644
2025
  async claimIfFunded(swap, vtxos) {
2645
2026
  if (vtxos.length === 0) return this.unblock(swap);
2646
2027
  const partiallyClaimed = swap.claimTxid !== void 0;
@@ -2679,6 +2060,14 @@ var RfqSwapManager = class {
2679
2060
  this.setState(swap, "claimed");
2680
2061
  this.emitAction(swap, "claimLockup");
2681
2062
  } catch (error) {
2063
+ const ark = isArkError(error) ? error : maybeArkError(error);
2064
+ if (isArkError(ark, ArkErrorName.VTXO_ALREADY_SPENT)) {
2065
+ if (swap.claimFailure !== void 0) {
2066
+ delete swap.claimFailure;
2067
+ this.touch(swap);
2068
+ }
2069
+ return;
2070
+ }
2682
2071
  swap.claimFailure = errorMessage(error);
2683
2072
  this.touch(swap);
2684
2073
  this.emitFailed(swap, error);
@@ -2716,6 +2105,21 @@ var RfqSwapManager = class {
2716
2105
  });
2717
2106
  if (action === "claim" && phase.phase === "claimable") {
2718
2107
  if (swap.claimTxid) return "continue";
2108
+ if (!Number.isSafeInteger(swap.expectedAmount) || swap.expectedAmount <= 0) {
2109
+ this.block(
2110
+ swap,
2111
+ `expectedAmount is not a positive number of sats (${String(swap.expectedAmount)}), so the funded value cannot be checked \u2014 refusing to publish the preimage`
2112
+ );
2113
+ return "handled";
2114
+ }
2115
+ const filled = Number(phase.utxo.amount);
2116
+ if (!Number.isFinite(filled) || filled < swap.expectedAmount) {
2117
+ this.block(
2118
+ swap,
2119
+ `fill holds ${filled} sats, below the agreed ${swap.expectedAmount} \u2014 refusing to publish the preimage`
2120
+ );
2121
+ return "handled";
2122
+ }
2719
2123
  if (this.callbacks && !this.callbacks.claimOnchain) {
2720
2124
  this.block(swap, RFQ_CONFIGURATION_REFUSAL.noClaimOnchainCallback);
2721
2125
  return "handled";
@@ -2766,6 +2170,8 @@ var RfqSwapManager = class {
2766
2170
  if (pushed) {
2767
2171
  swap.refundTxid = pushed.txid;
2768
2172
  this.touch(swap);
2173
+ } else if (now < swap.refundLocktime + REFUND_MTP_LAG_SECONDS) {
2174
+ return;
2769
2175
  }
2770
2176
  this.setState(swap, "refunded");
2771
2177
  this.emitAction(swap, "refundArkade");
@@ -2781,8 +2187,8 @@ var RfqSwapManager = class {
2781
2187
  }
2782
2188
  }
2783
2189
  }
2784
- /** Whether any of these outputs has never been handed to the claim
2785
- * callback — the only reason to claim a lockup a second time. */
2190
+ /** Whether any output was never handed to the claim callback (the only reason to
2191
+ * claim twice). */
2786
2192
  hasUnclaimedOutpoint(rfqId, vtxos) {
2787
2193
  const claimed = this.claimedOutpoints.get(rfqId);
2788
2194
  if (!claimed) return true;
@@ -2794,20 +2200,15 @@ var RfqSwapManager = class {
2794
2200
  this.claimedOutpoints.set(rfqId, claimed);
2795
2201
  }
2796
2202
  /**
2797
- * L1 progress, which past the refund window must not overwrite a refusal.
2798
- * The two halves are independent — a claimed fill says nothing about
2799
- * whether this wallet can take the Arkade lockup back — and `claimed` is
2800
- * re-asserted from chain on every pass, so without this a blocked swap
2801
- * would flip between the two states forever. The claim itself always runs;
2802
- * only the label defers, and only once the refund is the live half.
2203
+ * L1 progress, which past the refund window must not overwrite a refusal: `claimed` is
2204
+ * re-asserted from chain every pass, so a blocked swap would flip forever. Only the
2205
+ * label defers; the claim itself always runs.
2803
2206
  */
2804
2207
  setOnchainState(swap, state) {
2805
2208
  if (swap.state === "needs_counterparty" && this.config.now() >= swap.refundLocktime) return;
2806
2209
  this.setState(swap, state);
2807
2210
  }
2808
- /** The probe's refusal reason, or `undefined` when a local refund is
2809
- * possible as far as anyone here can tell. A probe that throws is treated
2810
- * as a refusal: a capability check that cannot answer is not a yes. */
2211
+ /** The probe's refusal reason, or `undefined`. A throwing probe is a refusal. */
2811
2212
  async probeRefusal(swap) {
2812
2213
  const probe = this.callbacks?.canRefundArkade;
2813
2214
  if (!probe) return void 0;
@@ -2826,25 +2227,16 @@ var RfqSwapManager = class {
2826
2227
  }
2827
2228
  this.setState(swap, "needs_counterparty");
2828
2229
  }
2829
- /** The way back out, taken as soon as the swap becomes actionable again.
2830
- * Back to what the record can prove, not to `pending` unconditionally: a
2831
- * swap that already made its claim has a txid for it, and reporting that
2832
- * swap as `pending` would un-say something true. */
2230
+ /** The way back out once actionable: to `claimed` if a claim txid exists, else
2231
+ * `pending`. */
2833
2232
  unblock(swap) {
2834
2233
  if (swap.state !== "needs_counterparty") return;
2835
2234
  this.setState(swap, traderClaimTxid(swap) ? "claimed" : "pending");
2836
2235
  }
2837
2236
  /**
2838
- * Record which ark transactions ended the lockup.
2839
- *
2840
- * Only the ones the indexer actually named: `LockupSpend.txid` is
2841
- * optional, and a checkpoint txid is not what history correlates on — a
2842
- * record carrying one would name a transaction the wallet's own activity
2843
- * never shows. Fewer txids is the right failure here.
2844
- *
2845
- * Assigned rather than merged: the fate is one read of the whole lockup,
2846
- * so it is the complete answer for this swap, and a swap only reaches a
2847
- * verdict once.
2237
+ * Record which ark transactions ended the lockup. Only named ark txids: a checkpoint
2238
+ * txid would name a transaction the wallet's activity never shows. Assigned, not
2239
+ * merged: the fate is one complete read, reached once.
2848
2240
  */
2849
2241
  stampLockupSpends(swap, spends) {
2850
2242
  const txids = spends.map((spend) => spend.txid).filter((txid) => txid !== void 0);
@@ -2852,6 +2244,15 @@ var RfqSwapManager = class {
2852
2244
  swap.lockupSpendTxids = txids;
2853
2245
  this.touch(swap);
2854
2246
  }
2247
+ /**
2248
+ * Keep the preimage that settled a Lightning send. Only that leg: the others' preimages
2249
+ * are the wallet's own secrets, already recoverable from `profile`.
2250
+ */
2251
+ stampSettlementPreimage(swap, preimage) {
2252
+ if (swap.kind !== "lightning_send") return;
2253
+ swap.settlementPreimageHex = hex5.encode(preimage);
2254
+ this.touch(swap);
2255
+ }
2855
2256
  touch(swap) {
2856
2257
  swap.updatedAt = this.config.now();
2857
2258
  this.dirty.add(swap.rfqId);
@@ -2879,24 +2280,9 @@ var RfqSwapManager = class {
2879
2280
  notify(this.actionExecutedListeners, (listener) => listener(swap, action));
2880
2281
  }
2881
2282
  /**
2882
- * Flush a changed record to every sink that is wired, and say whether all
2883
- * of them took it.
2884
- *
2885
- * Up to two writes, in this order: the canonical `RfqSwapRecord` to
2886
- * {@link RfqSwapManagerDeps.repository}, then
2887
- * {@link RfqSwapManagerCallbacks.saveSwap}. Both gate — a rejection from
2888
- * either leaves the record dirty and monitored, so waiters stay unsettled
2889
- * and a terminal swap is not finalized until the write it claims lands.
2890
- * That is exactly today's rule for `saveSwap`, applied to whichever sinks
2891
- * exist; wiring the repository does not weaken it.
2892
- *
2893
- * The canonical write goes FIRST and a failure there skips the second.
2894
- * `saveSwap` is a projection of the record, and projecting a state the
2895
- * record of record has just refused would leave the secondary sink ahead
2896
- * of the primary — the one ordering that survives no restart.
2897
- *
2898
- * With neither wired the state is process-local, which is what a manager
2899
- * with no callbacks has always done.
2283
+ * Flush a changed record to every wired sink; true only if all took it (else it stays
2284
+ * dirty and unfinalized). The canonical repository write goes FIRST and a failure skips
2285
+ * `saveSwap`, so the secondary sink never gets ahead of the primary.
2900
2286
  */
2901
2287
  async save(swap) {
2902
2288
  if (!await this.saveRecord(swap)) return false;
@@ -2928,18 +2314,15 @@ var RfqSwapManager = class {
2928
2314
  if (!origin) throw new RfqSwapOriginRequired(swap.rfqId);
2929
2315
  return origin;
2930
2316
  }
2931
- /**
2932
- * Drop a terminal swap from monitoring and report it exactly once.
2933
- *
2934
- * `onSwapCompleted` and `onSwapFailed` are mutually exclusive here: a
2935
- * listener named "completed" that also fires on failure is a trap, so a
2936
- * swap that leaves monitoring reports through exactly one of them.
2937
- */
2317
+ /** Drop a terminal swap from monitoring and report it exactly once, through either
2318
+ * `onSwapCompleted` or `onSwapFailed`. */
2938
2319
  finalize(swap) {
2939
2320
  if (!this.monitored.has(swap.rfqId)) return;
2940
2321
  this.untrack(swap.rfqId);
2941
- this.finished.set(swap.rfqId, swap);
2322
+ this.rememberFinished(swap, true);
2942
2323
  this.retireContract(swap);
2324
+ this.registered.delete(swap.rfqId);
2325
+ this.origins.delete(swap.rfqId);
2943
2326
  if (swap.state === "failed") {
2944
2327
  notify(
2945
2328
  this.swapFailedListeners,
@@ -2949,6 +2332,10 @@ var RfqSwapManager = class {
2949
2332
  }
2950
2333
  notify(this.swapCompletedListeners, (listener) => listener(swap));
2951
2334
  }
2335
+ rememberFinished(swap, durable = false) {
2336
+ if (durable && this.deps.repository) this.finished.delete(swap.rfqId);
2337
+ else this.finished.set(swap.rfqId, swap);
2338
+ }
2952
2339
  settleWaiters(swap) {
2953
2340
  const waiting = this.waiters.get(swap.rfqId);
2954
2341
  if (!waiting) return;
@@ -2964,16 +2351,7 @@ var RfqSwapManager = class {
2964
2351
  this.waiters.delete(swap.rfqId);
2965
2352
  }
2966
2353
  };
2967
- var traderClaimTxid = (swap) => {
2968
- switch (swap.kind) {
2969
- case "onchain_send":
2970
- return swap.claimTxid;
2971
- case "lightning_receive":
2972
- return swap.claimTxid;
2973
- default:
2974
- return void 0;
2975
- }
2976
- };
2354
+ var traderClaimTxid = (swap) => swap.kind === "onchain_send" || swap.kind === "lightning_receive" ? swap.claimTxid : void 0;
2977
2355
  var isPayoutDecided = (swap) => swap.state === "settled" || swap.state === "refunded" || swap.kind === "onchain_send" && swap.claimTxid !== void 0;
2978
2356
  var outcomeOf = (swap) => {
2979
2357
  const lostReceive = swap.kind === "lightning_receive" && swap.state === "refunded";
@@ -2982,13 +2360,23 @@ var outcomeOf = (swap) => {
2982
2360
  txid: lostReceive ? swap.refundTxid : traderClaimTxid(swap) ?? swap.refundTxid
2983
2361
  };
2984
2362
  };
2363
+ var outcomeOfRecord = (stored) => {
2364
+ const record = normalizeRfqSwapRecord(stored);
2365
+ const profileClaim = record.kind === "onchain_send" || record.kind === "lightning_receive" ? record.profile.claimTxid : void 0;
2366
+ const claimTxid = typeof profileClaim === "string" ? profileClaim : void 0;
2367
+ return {
2368
+ state: record.state,
2369
+ txid: record.kind === "lightning_receive" && record.state === "refunded" ? record.refundTxid : claimTxid ?? record.refundTxid
2370
+ };
2371
+ };
2985
2372
  var errorMessage = (error) => error instanceof Error ? error.message : String(error);
2986
2373
  var outpointKey = (vtxo) => `${vtxo.txid}:${vtxo.vout}`;
2987
2374
 
2988
2375
  // src/watch.ts
2989
- import { base64 as base643, hex as hex9 } from "@scure/base";
2376
+ import { base64 as base643, hex as hex6 } from "@scure/base";
2990
2377
  import {
2991
- ArkAddress as ArkAddress3,
2378
+ ArkAddress as ArkAddress2,
2379
+ isContractVtxoEvent as isContractVtxoEvent2,
2992
2380
  Transaction as Transaction3
2993
2381
  } from "@arkade-os/sdk";
2994
2382
  var TERMINAL = ["fulfilled", "cancelled", "recoverable"];
@@ -3022,7 +2410,7 @@ async function watchOfferSwaps({
3022
2410
  wallet.getAddress(),
3023
2411
  wallet.getArkadeReader()
3024
2412
  ]);
3025
- const operatorPubkey = ArkAddress3.decode(address).serverPubKey;
2413
+ const operatorPubkey = ArkAddress2.decode(address).serverPubKey;
3026
2414
  let queue = Promise.resolve();
3027
2415
  const enqueue = (task) => {
3028
2416
  queue = queue.then(task).catch(() => {
@@ -3035,7 +2423,7 @@ async function watchOfferSwaps({
3035
2423
  if (candidates.length === 0) return "indeterminate";
3036
2424
  const { txs } = await indexer.getVirtualTxs(candidates);
3037
2425
  return classifyDepositSpend(
3038
- decodeOffer(hex9.decode(swap.offerHex)),
2426
+ decodeOffer(hex6.decode(swap.offerHex)),
3039
2427
  operatorPubkey,
3040
2428
  txs.map((psbt) => Transaction3.fromPSBT(base643.decode(psbt))),
3041
2429
  { txid: vtxo.txid, vout: vtxo.vout }
@@ -3065,7 +2453,7 @@ async function watchOfferSwaps({
3065
2453
  }
3066
2454
  };
3067
2455
  const unsubscribe = manager.onContractEvent((event) => {
3068
- if (event.type !== "vtxo_spent") return;
2456
+ if (!isContractVtxoEvent2(event) || event.type !== "vtxo_spent") return;
3069
2457
  enqueue(() => handleSpend(event));
3070
2458
  });
3071
2459
  return {
@@ -3075,26 +2463,6 @@ async function watchOfferSwaps({
3075
2463
  }
3076
2464
 
3077
2465
  export {
3078
- RETIRABLE,
3079
- retireOfferContract,
3080
- retireSettledOfferContracts,
3081
- BTC_ASSET_ID,
3082
- getAssetSwaps,
3083
- addAssetSwap,
3084
- updateAssetSwap,
3085
- swapSecretsToRecord,
3086
- PreimageNotRecoverableError,
3087
- preimageForSwapRecord,
3088
- swapPrograms,
3089
- offerContract,
3090
- OFFER_PACKET_TYPE,
3091
- encodeOffer,
3092
- decodeOffer,
3093
- createOffer,
3094
- cancelOffer,
3095
- NoSpendableDepositError,
3096
- OfferCovenantMismatchError,
3097
- prepareOfferCancel,
3098
2466
  rfqCorridorHandlers,
3099
2467
  rfqSecretsProfile,
3100
2468
  rfqSignerOf,
@@ -3103,6 +2471,7 @@ export {
3103
2471
  onchainSendProfile,
3104
2472
  INVOICE_HRPS,
3105
2473
  networksOfInvoiceHrp,
2474
+ PAYMENT_HASH,
3106
2475
  LIGHTNING_DRIVE,
3107
2476
  lightningCorridor,
3108
2477
  ONCHAIN_DRIVE,
@@ -3114,6 +2483,9 @@ export {
3114
2483
  offerOutcome,
3115
2484
  recordOutcome,
3116
2485
  ACTIVITY_TOKEN,
2486
+ marketAssetId,
2487
+ marketCorridor,
2488
+ marketPairLabel,
3117
2489
  isRfqTerminal,
3118
2490
  awaitRfqResolution,
3119
2491
  walletOperator,
@@ -3128,17 +2500,11 @@ export {
3128
2500
  discoverMarkets,
3129
2501
  findMarket,
3130
2502
  validatePlan,
2503
+ toRestoreTx,
3131
2504
  classifySpend,
3132
2505
  spendTxidsOf,
3133
2506
  classifyDepositSpend,
3134
2507
  restoreAssetSwaps,
3135
- LockupAmountMismatchError,
3136
- pushClaim,
3137
- awaitLockupFunding,
3138
- claimReceiveLockup,
3139
- RefundNotLocallyPossibleError,
3140
- senderIdentityForSwapRecord,
3141
- arkadeRefunder,
3142
2508
  isRfqSwapTerminal,
3143
2509
  RFQ_SWAP_RETENTION_SECONDS,
3144
2510
  normalizeRfqSwapRecord,
@@ -3147,6 +2513,13 @@ export {
3147
2513
  rfqSwapOriginOf,
3148
2514
  rebuildRfqSwap,
3149
2515
  shouldRetainRfqSwap,
2516
+ LockupAmountMismatchError,
2517
+ pushClaim,
2518
+ awaitLockupFunding,
2519
+ claimReceiveLockup,
2520
+ RefundNotLocallyPossibleError,
2521
+ senderIdentityForSwapRecord,
2522
+ arkadeRefunder,
3150
2523
  nextOnchainAction,
3151
2524
  isRfqConfigurationRefusal,
3152
2525
  RfqSwapOriginRequired,