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

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