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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +52 -2
  2. package/dist/advanced.cjs +8376 -0
  3. package/dist/advanced.d.cts +550 -0
  4. package/dist/advanced.d.ts +550 -0
  5. package/dist/advanced.js +451 -0
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-HUQQVBC4.js +4262 -0
  8. package/dist/{chunk-EOYGUCDM.js → chunk-ITFCQWPG.js} +755 -1382
  9. package/dist/chunk-PVB7EBAM.js +2517 -0
  10. package/dist/errors-C3h8ANmE.d.ts +1560 -0
  11. package/dist/errors-hm7aqnRM.d.cts +1560 -0
  12. package/dist/index.cjs +4861 -3988
  13. package/dist/index.d.cts +69 -2812
  14. package/dist/index.d.ts +69 -2812
  15. package/dist/index.js +179 -3719
  16. package/dist/lockupContract-5r5RlgOJ.d.cts +137 -0
  17. package/dist/lockupContract-5r5RlgOJ.d.ts +137 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +249 -591
  20. package/dist/node/index.d.ts +249 -591
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +191 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer-Bd9Yvd8Z.d.ts +261 -0
  27. package/dist/offer-F88rtL_I.d.cts +261 -0
  28. package/dist/protocol.cjs +4086 -3706
  29. package/dist/protocol.d.cts +163 -768
  30. package/dist/protocol.d.ts +163 -768
  31. package/dist/protocol.js +190 -173
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BuYWGAKz.d.cts +2261 -0
  41. package/dist/repository-DYnRLPt-.d.ts +2261 -0
  42. package/dist/rfq-60PGpQ_x.d.cts +950 -0
  43. package/dist/rfq-60PGpQ_x.d.ts +950 -0
  44. package/dist/watch-BTyiBLSd.d.ts +74 -0
  45. package/dist/watch-M_KY-5ho.d.cts +74 -0
  46. package/package.json +20 -10
  47. package/dist/chunk-LYCMM3VB.js +0 -1357
  48. package/dist/chunk-U7VWWTL6.js +0 -66
  49. package/dist/repository-_zU9_pM3.d.cts +0 -3426
  50. package/dist/repository-kO95noyv.d.ts +0 -3426
  51. package/dist/rfq-DdBV4JO5.d.cts +0 -1097
  52. package/dist/rfq-DdBV4JO5.d.ts +0 -1097
  53. package/dist/watch-CQqvwgwY.d.cts +0 -96
  54. package/dist/watch-wMbmfN4p.d.ts +0 -96
@@ -0,0 +1,2517 @@
1
+ import {
2
+ collectAssetSwaps
3
+ } from "./chunk-A3SHHRX4.js";
4
+
5
+ // src/store.ts
6
+ import { hex } from "@scure/base";
7
+ import { sha256 } from "@noble/hashes/sha2.js";
8
+ import { contractPreimage } from "@arkade-os/sdk";
9
+ var BTC_ASSET_ID = "btc";
10
+ var byNewest = (a, b) => b.createdAt - a.createdAt;
11
+ var getAssetSwapsOrThrow = async (repository) => {
12
+ return (await collectAssetSwaps(repository)).filter(
13
+ (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
14
+ // the payment hash instead — either marks a valid record
15
+ (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
16
+ ).sort(byNewest);
17
+ };
18
+ var getAssetSwaps = async (repository) => {
19
+ try {
20
+ return await getAssetSwapsOrThrow(repository);
21
+ } catch {
22
+ return [];
23
+ }
24
+ };
25
+ var saveSwapOrThrow = async (repository, swap) => {
26
+ try {
27
+ await repository.saveSwap(swap);
28
+ } catch (error) {
29
+ const reason = error instanceof Error ? error.message : String(error);
30
+ throw new Error(`failed to save swap ${swap.id}: ${reason}`);
31
+ }
32
+ };
33
+ var addAssetSwap = async (repository, swap) => {
34
+ const swaps = await getAssetSwapsOrThrow(repository);
35
+ if (swaps.some((s) => s.id === swap.id)) return swaps;
36
+ await saveSwapOrThrow(repository, swap);
37
+ const at = swaps.findIndex((s) => byNewest(swap, s) <= 0);
38
+ const merged = [...swaps];
39
+ merged.splice(at === -1 ? merged.length : at, 0, swap);
40
+ return merged;
41
+ };
42
+ var updateAssetSwap = async (repository, id, changes) => {
43
+ const swaps = (await getAssetSwapsOrThrow(repository)).map(
44
+ (s) => s.id === id ? { ...s, ...changes } : s
45
+ );
46
+ const updated = swaps.find((s) => s.id === id);
47
+ if (updated) await saveSwapOrThrow(repository, updated);
48
+ return swaps;
49
+ };
50
+ var updateAssetSwapBestEffort = async (repository, id, changes) => {
51
+ try {
52
+ return { swaps: await updateAssetSwap(repository, id, changes), persisted: true };
53
+ } catch (error) {
54
+ console.warn(`[swap] failed to persist update for swap ${id}`, error);
55
+ const swaps = (await getAssetSwaps(repository)).map(
56
+ (s) => s.id === id ? { ...s, ...changes } : s
57
+ );
58
+ return { swaps, persisted: false };
59
+ }
60
+ };
61
+ var swapSecretsToRecord = (secrets) => ({
62
+ signingDescriptor: secrets.descriptor,
63
+ ..."mustPersistPreimage" in secrets && secrets.mustPersistPreimage ? { preimageHex: hex.encode(secrets.preimage) } : {},
64
+ ..."preimageSalt" in secrets && secrets.preimageSalt ? { preimageSaltHex: hex.encode(secrets.preimageSalt) } : {}
65
+ });
66
+ var decodeHex32 = (value, field) => {
67
+ const bytes = hex.decode(value);
68
+ if (bytes.length !== 32) {
69
+ throw new Error(`${field} must be 32 bytes, got ${bytes.length}`);
70
+ }
71
+ return bytes;
72
+ };
73
+ var PreimageNotRecoverableError = class extends Error {
74
+ constructor(reason, message, options) {
75
+ super(message, options);
76
+ this.reason = reason;
77
+ }
78
+ reason;
79
+ name = "PreimageNotRecoverableError";
80
+ };
81
+ var preimageForSwapRecord = async (wallet, record) => {
82
+ if (!record.signingDescriptor) {
83
+ throw new PreimageNotRecoverableError(
84
+ "no-secrets",
85
+ "this swap record carries no signing descriptor"
86
+ );
87
+ }
88
+ let stored;
89
+ let salt;
90
+ try {
91
+ stored = record.preimageHex ? decodeHex32(record.preimageHex, "preimageHex") : void 0;
92
+ salt = record.preimageSaltHex ? decodeHex32(record.preimageSaltHex, "preimageSaltHex") : void 0;
93
+ } catch (cause) {
94
+ throw new PreimageNotRecoverableError(
95
+ "malformed-record",
96
+ `this swap record's secrets projection is unreadable: ${String(cause)}`,
97
+ { cause }
98
+ );
99
+ }
100
+ let preimage;
101
+ try {
102
+ preimage = await contractPreimage(wallet, record.signingDescriptor, { stored, salt });
103
+ } catch (cause) {
104
+ throw new PreimageNotRecoverableError(
105
+ "not-derivable",
106
+ `this wallet cannot produce the preimage for ${record.signingDescriptor}`,
107
+ { cause }
108
+ );
109
+ }
110
+ if (record.paymentHash && hex.encode(sha256(preimage)) !== record.paymentHash.toLowerCase()) {
111
+ throw new PreimageNotRecoverableError(
112
+ "hash-mismatch",
113
+ "the derived preimage does not match this swap's payment hash: wrong wallet, or a tampered salt"
114
+ );
115
+ }
116
+ return preimage;
117
+ };
118
+
119
+ // src/offer.ts
120
+ import { hex as hex2 } from "@scure/base";
121
+ import { concatBytes } from "@scure/btc-signer/utils.js";
122
+ import {
123
+ ASSET_CARRIER_SATS as SDK_ASSET_CARRIER_SATS,
124
+ ArkAddress,
125
+ RestArkProvider,
126
+ RestEmulatorProvider,
127
+ RestIndexerProvider,
128
+ arkade,
129
+ asset,
130
+ networkFromArkadeInfo,
131
+ resolveEmulatorPubkey,
132
+ toXOnlySignerHex
133
+ } from "@arkade-os/sdk";
134
+
135
+ // src/swap-want-asset.program.json
136
+ var swap_want_asset_program_default = {
137
+ version: 0,
138
+ name: "banco-btc-to-asset",
139
+ params: [
140
+ { name: "makerWP", type: "pubkey" },
141
+ { name: "wantAmount", type: "int" },
142
+ { name: "wantAssetTxid", type: "hash" },
143
+ { name: "wantAssetGroupIndex", type: "int" },
144
+ { name: "server", type: "pubkey" },
145
+ { name: "user", type: "pubkey" }
146
+ ],
147
+ functions: {
148
+ fulfill: {
149
+ tapscript: { signers: ["$server"] },
150
+ arkadeScript: {
151
+ asm: [
152
+ 0,
153
+ "$wantAssetTxid",
154
+ "$wantAssetGroupIndex",
155
+ "INSPECTOUTASSETLOOKUP",
156
+ "VERIFY",
157
+ "$wantAmount",
158
+ "GREATERTHANOREQUAL",
159
+ "VERIFY",
160
+ 0,
161
+ "INSPECTOUTPUTSCRIPTPUBKEY",
162
+ 1,
163
+ "EQUALVERIFY",
164
+ "$makerWP",
165
+ "EQUAL"
166
+ ]
167
+ }
168
+ },
169
+ cancel: {
170
+ tapscript: { signers: ["$user", "$server"] }
171
+ }
172
+ }
173
+ };
174
+
175
+ // src/swap-want-btc.program.json
176
+ var swap_want_btc_program_default = {
177
+ version: 0,
178
+ name: "banco-asset-to-btc",
179
+ params: [
180
+ { name: "makerWP", type: "pubkey" },
181
+ { name: "wantAmount", type: "int" },
182
+ { name: "server", type: "pubkey" },
183
+ { name: "user", type: "pubkey" }
184
+ ],
185
+ functions: {
186
+ fulfill: {
187
+ tapscript: { signers: ["$server"] },
188
+ arkadeScript: {
189
+ asm: [
190
+ 0,
191
+ "INSPECTOUTPUTVALUE",
192
+ "$wantAmount",
193
+ "GREATERTHANOREQUAL",
194
+ "VERIFY",
195
+ 0,
196
+ "INSPECTOUTPUTSCRIPTPUBKEY",
197
+ 1,
198
+ "EQUALVERIFY",
199
+ "$makerWP",
200
+ "EQUAL"
201
+ ]
202
+ }
203
+ },
204
+ cancel: {
205
+ tapscript: { signers: ["$user", "$server"] }
206
+ }
207
+ }
208
+ };
209
+
210
+ // src/coverage.ts
211
+ var RETIRABLE = ["fulfilled", "cancelled"];
212
+ var LOCKUP_RETIRABLE = ["settled", "refunded"];
213
+ var issuedAt = /* @__PURE__ */ new Map();
214
+ var inFlight = /* @__PURE__ */ new Map();
215
+ async function serialize(script, task) {
216
+ const previous = inFlight.get(script) ?? Promise.resolve();
217
+ const result = previous.then(task, task);
218
+ const settled = result.then(
219
+ () => {
220
+ },
221
+ () => {
222
+ }
223
+ );
224
+ inFlight.set(script, settled);
225
+ void settled.then(() => {
226
+ if (inFlight.get(script) === settled) inFlight.delete(script);
227
+ });
228
+ return result;
229
+ }
230
+ function addressOutstanding(swaps, script) {
231
+ const issued = issuedAt.get(script);
232
+ if (issued === void 0) return false;
233
+ if (swaps.some((s) => s.swapPkScript === script && s.createdAt >= issued)) {
234
+ issuedAt.delete(script);
235
+ return false;
236
+ }
237
+ return true;
238
+ }
239
+ async function promoteOfferContract(manager, script, issued = Date.now()) {
240
+ await serialize(script, async () => {
241
+ await manager.setContractWatchState(script, "watched");
242
+ issuedAt.set(script, issued);
243
+ });
244
+ }
245
+ async function retireOfferContract(manager, swaps, script) {
246
+ await serialize(script, async () => {
247
+ if (swaps.some((s) => s.swapPkScript === script && !RETIRABLE.includes(s.status))) return;
248
+ if (addressOutstanding(swaps, script)) return;
249
+ try {
250
+ await manager.setContractWatchState(script, "retained");
251
+ } catch (err) {
252
+ console.warn(`[swap] could not retire offer contract ${script}`, err);
253
+ }
254
+ });
255
+ }
256
+ async function retireSettledOfferContracts(manager, swaps) {
257
+ const settled = new Set(
258
+ swaps.filter((s) => RETIRABLE.includes(s.status)).map((s) => s.swapPkScript)
259
+ );
260
+ for (const script of settled) await retireOfferContract(manager, swaps, script);
261
+ }
262
+
263
+ // src/offer.ts
264
+ var swapPrograms = {
265
+ wantAsset: arkade.parseArtifact(swap_want_asset_program_default),
266
+ wantBtc: arkade.parseArtifact(swap_want_btc_program_default)
267
+ };
268
+ function withExitClosure(program, exit) {
269
+ if (!exit) return program;
270
+ return {
271
+ ...program,
272
+ // typed params are authoritative: an undeclared `$exitDelay` fails
273
+ // validateProgram instead of compiling against an unbound value
274
+ params: [...program.params ?? [], { name: "exitDelay", type: "int" }],
275
+ functions: {
276
+ ...program.functions,
277
+ exit: {
278
+ tapscript: { signers: ["$user"], csv: { type: exit.type, value: "$exitDelay" } }
279
+ }
280
+ }
281
+ };
282
+ }
283
+ function swapProgramBinding(offer, operatorPubkey) {
284
+ if (offer.makerPkScript.length !== FIELDS.makerPkScript.width) {
285
+ throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
286
+ }
287
+ return {
288
+ program: withExitClosure(
289
+ offer.wantAsset ? swapPrograms.wantAsset : swapPrograms.wantBtc,
290
+ offer.exitDelay
291
+ ),
292
+ args: {
293
+ makerWP: offer.makerPkScript.subarray(2),
294
+ wantAmount: offer.wantAmount,
295
+ server: operatorPubkey,
296
+ user: offer.makerPublicKey,
297
+ // internal byte order
298
+ ...offer.wantAsset && {
299
+ wantAssetTxid: offer.wantAsset.txid.slice().reverse(),
300
+ wantAssetGroupIndex: offer.wantAsset.groupIndex
301
+ },
302
+ ...offer.exitDelay && { exitDelay: offer.exitDelay.value }
303
+ },
304
+ keys: {
305
+ serverKey: operatorPubkey,
306
+ userKey: offer.makerPublicKey,
307
+ emulatorKey: offer.emulatorPubkey
308
+ }
309
+ };
310
+ }
311
+ function offerContract(offer, operatorPubkey) {
312
+ const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
313
+ return new arkade.ArkadeProgramScript(program, args, keys);
314
+ }
315
+ var OFFER_PACKET_TYPE = 3;
316
+ var FIELDS = {
317
+ swapPkScript: { tag: 1, width: 34 },
318
+ wantAmount: { tag: 2, width: 8 },
319
+ wantAsset: { tag: 3, width: void 0 },
320
+ makerPkScript: { tag: 5, width: 34 },
321
+ makerPublicKey: { tag: 7, width: 32 },
322
+ emulatorPubkey: { tag: 8, width: 32 },
323
+ ratioNum: { tag: 9, width: 8 },
324
+ ratioDen: { tag: 10, width: 8 },
325
+ offerAsset: { tag: 11, width: void 0 },
326
+ exitTimelock: { tag: 12, width: 9 }
327
+ };
328
+ var EXIT_TYPES = ["blocks", "seconds"];
329
+ var NAMES = Object.fromEntries(Object.entries(FIELDS).map(([k, f]) => [f.tag, k]));
330
+ function u64(name, value) {
331
+ if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
332
+ throw new Error(`${name} does not fit the offer wire format (u64)`);
333
+ }
334
+ const out = new Uint8Array(FIELDS.wantAmount.width);
335
+ new DataView(out.buffer).setBigUint64(0, value, false);
336
+ return out;
337
+ }
338
+ var readU64 = (value) => new DataView(value.buffer, value.byteOffset).getBigUint64(0, false);
339
+ var setRatio = (name, value) => {
340
+ if (value === void 0 || value === BigInt(0)) return void 0;
341
+ if (value < BigInt(0)) throw new Error(`${name} does not fit the offer wire format (u64)`);
342
+ return value;
343
+ };
344
+ function tlv(type, value) {
345
+ if (value.length > 65535) throw new Error("TLV value exceeds the u16 length field");
346
+ return concatBytes(Uint8Array.of(type, value.length >> 8 & 255, value.length & 255), value);
347
+ }
348
+ function encodeOffer(offer) {
349
+ if (Boolean(offer.wantAsset) === Boolean(offer.offerAsset)) {
350
+ throw new Error("offer must carry exactly one of wantAsset or offerAsset");
351
+ }
352
+ for (const name of [
353
+ "swapPkScript",
354
+ "makerPkScript",
355
+ "makerPublicKey",
356
+ "emulatorPubkey"
357
+ ]) {
358
+ if (offer[name].length !== FIELDS[name].width) {
359
+ throw new Error(`${name} must be ${FIELDS[name].width} bytes`);
360
+ }
361
+ }
362
+ const ratioNum = setRatio("ratioNum", offer.ratioNum);
363
+ const ratioDen = setRatio("ratioDen", offer.ratioDen);
364
+ if (ratioNum === void 0 !== (ratioDen === void 0)) {
365
+ throw new Error("offer must carry both ratioNum and ratioDen, or neither");
366
+ }
367
+ const recs = [
368
+ tlv(FIELDS.swapPkScript.tag, offer.swapPkScript),
369
+ tlv(FIELDS.wantAmount.tag, u64("wantAmount", offer.wantAmount))
370
+ ];
371
+ if (offer.wantAsset) recs.push(tlv(FIELDS.wantAsset.tag, offer.wantAsset.serialize()));
372
+ if (ratioNum !== void 0) recs.push(tlv(FIELDS.ratioNum.tag, u64("ratioNum", ratioNum)));
373
+ if (ratioDen !== void 0) recs.push(tlv(FIELDS.ratioDen.tag, u64("ratioDen", ratioDen)));
374
+ if (offer.offerAsset) recs.push(tlv(FIELDS.offerAsset.tag, offer.offerAsset.serialize()));
375
+ recs.push(
376
+ tlv(FIELDS.makerPkScript.tag, offer.makerPkScript),
377
+ tlv(FIELDS.makerPublicKey.tag, offer.makerPublicKey),
378
+ tlv(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey)
379
+ );
380
+ if (offer.exitDelay) recs.push(tlv(FIELDS.exitTimelock.tag, encodeExitDelay(offer.exitDelay)));
381
+ return concatBytes(...recs);
382
+ }
383
+ function encodeExitDelay(exit) {
384
+ return concatBytes(
385
+ Uint8Array.of(EXIT_TYPES.indexOf(assertExitDelay(exit).type)),
386
+ u64("exitDelay", exit.value)
387
+ );
388
+ }
389
+ function assertExitDelay(exit) {
390
+ if (EXIT_TYPES.indexOf(exit.type) < 0) {
391
+ throw new Error(`unknown exitDelay locktime type: ${exit.type}`);
392
+ }
393
+ if (exit.value <= BigInt(0)) {
394
+ throw new Error("exitDelay must be a positive relative locktime");
395
+ }
396
+ if (exit.value >> BigInt(32) > BigInt(0)) {
397
+ throw new Error("exitDelay does not fit the locktime field (u32)");
398
+ }
399
+ return exit;
400
+ }
401
+ function decodeOffer(data) {
402
+ const fields = {};
403
+ let off = 0;
404
+ while (off < data.length) {
405
+ if (off + 3 > data.length) throw new Error("truncated TLV header");
406
+ const type = data[off];
407
+ const length = data[off + 1] << 8 | data[off + 2];
408
+ off += 3;
409
+ if (off + length > data.length)
410
+ throw new Error(`truncated TLV value for type 0x${type.toString(16)}`);
411
+ const name = NAMES[type];
412
+ if (!name) throw new Error(`unknown TLV type: 0x${type.toString(16)}`);
413
+ if (fields[name] !== void 0) throw new Error(`duplicate TLV record: ${name}`);
414
+ fields[name] = data.slice(off, off + length);
415
+ off += length;
416
+ }
417
+ for (const name of ["wantAsset", "offerAsset"]) {
418
+ if (fields[name]?.length === 0) throw new Error(`missing/invalid ${name}`);
419
+ }
420
+ for (const [name, value] of Object.entries(fields)) {
421
+ const width = FIELDS[name].width;
422
+ if (width !== void 0 && value.length !== width) {
423
+ throw new Error(`missing/invalid ${name}`);
424
+ }
425
+ }
426
+ const need = (name) => {
427
+ const v = fields[name];
428
+ if (!v) throw new Error(`missing/invalid ${name}`);
429
+ return v;
430
+ };
431
+ const amount = need("wantAmount");
432
+ if (Boolean(fields.wantAsset) === Boolean(fields.offerAsset)) {
433
+ throw new Error("offer must carry exactly one of wantAsset or offerAsset");
434
+ }
435
+ const readRatio = (name) => {
436
+ const raw = fields[name];
437
+ if (!raw) return void 0;
438
+ const value = readU64(raw);
439
+ if (value === BigInt(0)) throw new Error(`missing/invalid ${name}`);
440
+ return value;
441
+ };
442
+ const ratioNum = readRatio("ratioNum");
443
+ const ratioDen = readRatio("ratioDen");
444
+ if (ratioNum === void 0 !== (ratioDen === void 0)) {
445
+ throw new Error("offer must carry both ratioNum and ratioDen, or neither");
446
+ }
447
+ return {
448
+ swapPkScript: need("swapPkScript"),
449
+ wantAmount: readU64(amount),
450
+ ...fields.wantAsset && { wantAsset: asset.AssetId.fromBytes(fields.wantAsset) },
451
+ ...fields.offerAsset && { offerAsset: asset.AssetId.fromBytes(fields.offerAsset) },
452
+ makerPkScript: need("makerPkScript"),
453
+ makerPublicKey: need("makerPublicKey"),
454
+ emulatorPubkey: need("emulatorPubkey"),
455
+ ...ratioNum !== void 0 && { ratioNum },
456
+ ...ratioDen !== void 0 && { ratioDen },
457
+ ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) }
458
+ };
459
+ }
460
+ function decodeExitDelay(value) {
461
+ const type = EXIT_TYPES[value[0]];
462
+ if (!type) throw new Error(`unknown exitDelay locktime type: 0x${value[0].toString(16)}`);
463
+ return { type, value: readU64(value.subarray(1)) };
464
+ }
465
+ var OFFER_CONTRACT_LABEL = "Arkade swap offer";
466
+ var OFFER_CONTRACT_KIND = "asset-swap-offer";
467
+ async function registerOfferContract(wallet, info, binding, operatorPubkey, expectedPkScript) {
468
+ const contractManager = await wallet.getContractManager();
469
+ const client = await derivingClient(wallet, info, contractManager);
470
+ await contractManager.createContract(
471
+ offerContractParams(client, binding, operatorPubkey, expectedPkScript)
472
+ );
473
+ await promoteOfferContract(contractManager, hex2.encode(expectedPkScript));
474
+ }
475
+ var derivingClient = (wallet, info, contractManager) => arkade.Arkade.connect({
476
+ arkade: { getInfo: async () => info },
477
+ identity: wallet.identity,
478
+ network: networkFromArkadeInfo(info),
479
+ contractManager
480
+ });
481
+ function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
482
+ const { program, args, keys } = swapProgramBinding(binding, operatorPubkey);
483
+ const contract = new arkade.ArkadeContract(client, program, args, keys);
484
+ if (hex2.encode(contract.pkScript) !== hex2.encode(expectedPkScript)) {
485
+ throw new Error("derived covenant does not match the offer's swapPkScript");
486
+ }
487
+ return {
488
+ ...contract.toContractParams(),
489
+ label: OFFER_CONTRACT_LABEL,
490
+ metadata: { genericallySpendable: false, kind: OFFER_CONTRACT_KIND }
491
+ };
492
+ }
493
+ async function restoreOfferCoverage(wallet, swaps) {
494
+ const live = swaps.filter((swap) => !RETIRABLE.includes(swap.status));
495
+ if (live.length === 0) return;
496
+ const [info, contractManager] = await Promise.all([
497
+ wallet.getArkadeInfo({ requireLive: true }),
498
+ wallet.getContractManager()
499
+ ]);
500
+ const operatorPubkey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
501
+ const client = await derivingClient(wallet, info, contractManager);
502
+ const seen = /* @__PURE__ */ new Set();
503
+ const covenants = [];
504
+ for (const swap of live) {
505
+ if (seen.has(swap.swapPkScript)) continue;
506
+ seen.add(swap.swapPkScript);
507
+ try {
508
+ const { swapPkScript: _, ...binding } = decodeOffer(hex2.decode(swap.offerHex));
509
+ covenants.push({
510
+ script: swap.swapPkScript,
511
+ issued: swap.createdAt,
512
+ params: offerContractParams(
513
+ client,
514
+ binding,
515
+ operatorPubkey,
516
+ hex2.decode(swap.swapPkScript)
517
+ )
518
+ });
519
+ } catch (error) {
520
+ console.warn(`[swap] could not restore coverage for ${swap.swapPkScript}`, error);
521
+ }
522
+ }
523
+ const params = covenants.map((covenant) => covenant.params);
524
+ if (contractManager.createContracts) {
525
+ await contractManager.createContracts(params);
526
+ } else {
527
+ for (const contract of params) await contractManager.createContract(contract);
528
+ }
529
+ for (const covenant of covenants) {
530
+ await promoteOfferContract(contractManager, covenant.script, covenant.issued);
531
+ }
532
+ }
533
+ function serverExitDelay(delay) {
534
+ if (typeof delay !== "bigint" || delay <= BigInt(0)) {
535
+ throw new Error(
536
+ "the server reports no usable unilateralExitDelay; pass `exitDelay` to set the offer's exit closure explicitly, or `noExit: true` to publish without one"
537
+ );
538
+ }
539
+ return assertExitDelay({ value: delay, type: delay < BigInt(512) ? "blocks" : "seconds" });
540
+ }
541
+ async function createOffer(wallet, params) {
542
+ const derived = await deriveOffer(wallet, params);
543
+ await registerDerivedOffer(wallet, derived);
544
+ return {
545
+ offerHex: derived.offerHex,
546
+ extension: derived.extension,
547
+ address: derived.address,
548
+ swapPkScript: derived.swapPkScript
549
+ };
550
+ }
551
+ async function deriveOffer(wallet, params) {
552
+ if (Boolean(params.wantAsset) === Boolean(params.offerAsset)) {
553
+ throw new Error("set exactly one of wantAsset (BTC->asset) or offerAsset (asset->BTC)");
554
+ }
555
+ if (params.wantAmount < BigInt(1)) {
556
+ throw new Error("wantAmount must be positive: a zero want lets anyone take the deposit");
557
+ }
558
+ const [info, maker] = await Promise.all([
559
+ // requireLive: this binds signerPubkey into the covenant, and a snapshot could derive an
560
+ // address the operator no longer co-signs for — fail closed instead
561
+ params.info ?? wallet.getArkadeInfo({ requireLive: true }),
562
+ params.maker ?? (async () => {
563
+ const [address, publicKey] = await Promise.all([
564
+ wallet.getAddress(),
565
+ wallet.identity.xOnlyPublicKey()
566
+ ]);
567
+ return { pkScript: ArkAddress.decode(address).pkScript, publicKey };
568
+ })()
569
+ ]);
570
+ const operatorPubKey = hex2.decode(toXOnlySignerHex(info.signerPubkey));
571
+ const network = networkFromArkadeInfo(info);
572
+ const emuKey = hex2.decode(
573
+ toXOnlySignerHex(resolveEmulatorPubkey(network, params.emulatorPubkey))
574
+ );
575
+ const binding = Object.freeze({
576
+ wantAmount: params.wantAmount,
577
+ wantAsset: params.wantAsset,
578
+ offerAsset: params.offerAsset,
579
+ makerPkScript: maker.pkScript,
580
+ makerPublicKey: maker.publicKey,
581
+ emulatorPubkey: emuKey,
582
+ // checked before registration below. @see assertExitDelay
583
+ exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
584
+ });
585
+ const script = offerContract(binding, operatorPubKey);
586
+ const offer = { ...binding, swapPkScript: script.pkScript };
587
+ const payload = encodeOffer(offer);
588
+ return Object.freeze({
589
+ offerHex: hex2.encode(payload),
590
+ extension: { type: OFFER_PACKET_TYPE, payload },
591
+ // the contract's .address() builds the address; assembling an ArkAddress
592
+ // from tweakedPublicKey here would silently miss any future step it gains
593
+ address: script.address(network.hrp, operatorPubKey).encode(),
594
+ swapPkScript: script.pkScript,
595
+ binding,
596
+ info,
597
+ operatorPubkey: operatorPubKey
598
+ });
599
+ }
600
+ async function registerDerivedOffer(wallet, derived) {
601
+ await registerOfferContract(
602
+ wallet,
603
+ derived.info,
604
+ derived.binding,
605
+ derived.operatorPubkey,
606
+ derived.swapPkScript
607
+ );
608
+ }
609
+ async function cancelOffer(wallet, offerHex, opts) {
610
+ const { repository, fundingTxid, swapAddress } = opts;
611
+ const prepared = await prepareOfferCancel(wallet, offerHex, {
612
+ ...fundingTxid === void 0 ? {} : { fundingTxid },
613
+ ...swapAddress === void 0 ? {} : { swapAddress }
614
+ });
615
+ const swapId = fundingTxid ?? prepared.vtxo.txid;
616
+ const hasLocalRecord = (await getAssetSwapsOrThrow(repository)).some((s) => s.id === swapId);
617
+ if (hasLocalRecord) await updateAssetSwap(repository, swapId, { status: "cancelling" });
618
+ const txid = await prepared.send();
619
+ if (hasLocalRecord) {
620
+ const { persisted, swaps } = await updateAssetSwapBestEffort(repository, swapId, {
621
+ status: "cancelled",
622
+ spentTxid: txid
623
+ });
624
+ if (persisted) {
625
+ const contractManager = await wallet.getContractManager();
626
+ await retireOfferContract(
627
+ contractManager,
628
+ swaps,
629
+ hex2.encode(prepared.offer.swapPkScript)
630
+ );
631
+ }
632
+ }
633
+ return txid;
634
+ }
635
+ var NoSpendableDepositError = class extends Error {
636
+ name = "NoSpendableDepositError";
637
+ constructor(options) {
638
+ super("no spendable VTXO at the swap address", options);
639
+ }
640
+ };
641
+ var OfferCovenantMismatchError = class extends Error {
642
+ constructor(swapPkScript, options) {
643
+ super(
644
+ "rebuilt covenant does not match the offer's swapPkScript \u2014 the operator signing key pinned by the rebuild does not reproduce the funded covenant; the signing key has likely rotated since funding (pass swapAddress, the funded address, to pin the original key), or the record is corrupt",
645
+ options
646
+ );
647
+ this.swapPkScript = swapPkScript;
648
+ }
649
+ swapPkScript;
650
+ name = "OfferCovenantMismatchError";
651
+ };
652
+ async function prepareOfferCancel(wallet, offerHex, opts) {
653
+ const { fundingTxid, swapAddress } = opts;
654
+ const offer = decodeOffer(hex2.decode(offerHex));
655
+ const [contractManager, info, reader, broadcaster] = await Promise.all([
656
+ wallet.getContractManager(),
657
+ wallet.getArkadeInfo({ requireLive: true }),
658
+ wallet.getArkadeReader(),
659
+ wallet.getArkadeBroadcaster()
660
+ ]);
661
+ const client = await arkade.Arkade.connect({
662
+ arkade: { getInfo: async () => info, ...broadcaster },
663
+ indexer: reader,
664
+ identity: wallet.identity,
665
+ // registered offers resolve VTXOs from the contract repository; the indexer is the fallback
666
+ // for offers created before registration existed
667
+ contractManager
668
+ // no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
669
+ });
670
+ const operatorPubkey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
671
+ const { program, args, keys } = swapProgramBinding(offer, operatorPubkey);
672
+ let rebuilt;
673
+ try {
674
+ rebuilt = new arkade.ArkadeProgramScript(program, args, keys);
675
+ } catch (cause) {
676
+ throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript), { cause });
677
+ }
678
+ if (hex2.encode(rebuilt.pkScript) !== hex2.encode(offer.swapPkScript)) {
679
+ throw new OfferCovenantMismatchError(hex2.encode(offer.swapPkScript));
680
+ }
681
+ const contract = new arkade.ArkadeContract(client, program, args, keys);
682
+ const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
683
+ if (!fundingTxid && vtxos.length > 1) {
684
+ throw new Error(
685
+ "multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
686
+ );
687
+ }
688
+ const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
689
+ if (!vtxo) throw new NoSpendableDepositError();
690
+ const makerPkScript = ArkAddress.decode(makerAddress).pkScript;
691
+ const cancel = contract.functions.cancel().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).to(makerPkScript, BigInt(vtxo.value));
692
+ for (const a of vtxo.assets ?? []) {
693
+ cancel.withAsset({
694
+ assetId: a.assetId,
695
+ inputs: [{ vin: 0, amount: BigInt(a.amount) }],
696
+ outputs: [{ vout: 0, amount: BigInt(a.amount) }]
697
+ });
698
+ }
699
+ return {
700
+ offer,
701
+ vtxo: { txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value },
702
+ send: async () => (await cancel.send()).txid
703
+ };
704
+ }
705
+ var ASSET_CARRIER_SATS = BigInt(SDK_ASSET_CARRIER_SATS);
706
+ async function fillOffer(wallet, arkServerUrl, offerHex, opts) {
707
+ const {
708
+ fund,
709
+ payoutScript,
710
+ fundingTxid,
711
+ swapAddress,
712
+ assetCarrierSats = ASSET_CARRIER_SATS,
713
+ emulator,
714
+ emulatorPubkey
715
+ } = opts;
716
+ const offer = decodeOffer(hex2.decode(offerHex));
717
+ const wantedAssetId = offer.wantAsset?.toString();
718
+ if (fund.length === 0) {
719
+ throw new Error("fillOffer needs coins to pay wantAmount with \u2014 `fund` is empty");
720
+ }
721
+ if (wantedAssetId !== void 0) {
722
+ const supplied = fund.reduce(
723
+ (sum, coin) => sum + amountOfAsset(coin.assets, wantedAssetId),
724
+ BigInt(0)
725
+ );
726
+ if (supplied < offer.wantAmount) {
727
+ throw new Error(
728
+ `fillOffer needs ${offer.wantAmount} of ${wantedAssetId} to pay the maker, but \`fund\` declares ${supplied} \u2014 pass coins carrying it, and declare their assets`
729
+ );
730
+ }
731
+ }
732
+ const contractManager = await wallet.getContractManager();
733
+ const client = await arkade.Arkade.connect({
734
+ arkade: new RestArkProvider(arkServerUrl),
735
+ indexer: new RestIndexerProvider(arkServerUrl),
736
+ identity: wallet.identity,
737
+ contractManager,
738
+ emulator: typeof emulator === "string" ? new RestEmulatorProvider(emulator) : emulator,
739
+ // only for the client's own emulatorKey, which this fill never derives against (the offer's
740
+ // key is bound below) — but it must still resolve on a network with no pinned key
741
+ ...emulatorPubkey ? { emulatorPubkey } : {}
742
+ });
743
+ const serverKey = swapAddress ? ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
744
+ const { program, args, keys } = swapProgramBinding(offer, serverKey);
745
+ const rebuilt = new arkade.ArkadeProgramScript(program, args, keys);
746
+ if (hex2.encode(rebuilt.pkScript) !== hex2.encode(offer.swapPkScript)) {
747
+ throw new Error(
748
+ "rebuilt covenant does not match the offer's swapPkScript \u2014 the server signing key has likely rotated since funding; pass swapAddress (the funded address) to pin the original key"
749
+ );
750
+ }
751
+ const contract = new arkade.ArkadeContract(client, program, args, keys);
752
+ const [vtxos, takerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
753
+ if (!fundingTxid && vtxos.length > 1) {
754
+ throw new Error(
755
+ "multiple spendable deposits at the swap address \u2014 pass fundingTxid to select one"
756
+ );
757
+ }
758
+ const vtxo = fundingTxid ? vtxos.find((v) => v.txid === fundingTxid) : vtxos[0];
759
+ if (!vtxo) throw new Error("no spendable VTXO at the swap address");
760
+ if (offer.offerAsset) {
761
+ const offered = offer.offerAsset.toString();
762
+ const deposited = amountOfAsset(vtxo.assets, offered);
763
+ if (deposited <= BigInt(0)) {
764
+ throw new Error(
765
+ `the deposit at the swap address carries no ${offered}, which this offer sells \u2014 filling it would pay wantAmount for nothing. The indexer may be behind, or the offer may not be backed by what it advertises`
766
+ );
767
+ }
768
+ }
769
+ const payout = payoutScript ?? ArkAddress.decode(takerAddress).pkScript;
770
+ const makerSats = wantedAssetId === void 0 ? offer.wantAmount : assetCarrierSats;
771
+ const fill = contract.functions.fulfill().from({ txid: vtxo.txid, vout: vtxo.vout, value: vtxo.value }).fund(fund).to(offer.makerPkScript, makerSats).change(payout);
772
+ const held = /* @__PURE__ */ new Map();
773
+ const hold = (vin, assets) => {
774
+ for (const a of assets ?? []) {
775
+ const amount = BigInt(a.amount);
776
+ if (amount <= BigInt(0)) continue;
777
+ held.set(a.assetId, [...held.get(a.assetId) ?? [], { vin, amount }]);
778
+ }
779
+ };
780
+ hold(0, vtxo.assets);
781
+ fund.forEach((coin, i) => hold(i + 1, coin.assets));
782
+ const outputsSum = makerSats;
783
+ const inputsSum = fund.reduce((s, c) => s + BigInt(c.value), BigInt(vtxo.value));
784
+ const hasPayoutOutput = inputsSum > outputsSum;
785
+ const emitWanted = () => {
786
+ if (wantedAssetId === void 0) return;
787
+ const supplying = held.get(wantedAssetId) ?? [];
788
+ const supplied = supplying.reduce((s, i) => s + i.amount, BigInt(0));
789
+ const outputs = [{ vout: 0, amount: offer.wantAmount }];
790
+ const surplus = supplied - offer.wantAmount;
791
+ if (surplus > BigInt(0)) {
792
+ if (!hasPayoutOutput) {
793
+ throw new Error(
794
+ `fillOffer has ${surplus} of ${wantedAssetId} to return but no payout output \u2014 fund with more sats than the maker's output takes`
795
+ );
796
+ }
797
+ outputs.push({ vout: 1, amount: surplus });
798
+ }
799
+ fill.withAsset({ assetId: wantedAssetId, inputs: supplying, outputs });
800
+ held.delete(wantedAssetId);
801
+ };
802
+ emitWanted();
803
+ for (const [assetId, inputs] of held) {
804
+ const amount = inputs.reduce((s, i) => s + i.amount, BigInt(0));
805
+ if (!hasPayoutOutput) {
806
+ throw new Error(
807
+ `fillOffer has ${amount} of ${assetId} to return but no payout output \u2014 fund with more sats than the maker's output takes`
808
+ );
809
+ }
810
+ fill.withAsset({ assetId, inputs, outputs: [{ vout: 1, amount }] });
811
+ }
812
+ const { txid } = await fill.send();
813
+ return txid;
814
+ }
815
+ var amountOfAsset = (assets, assetId) => (assets ?? []).reduce(
816
+ (total, a) => a.assetId === assetId ? total + BigInt(a.amount) : total,
817
+ BigInt(0)
818
+ );
819
+
820
+ // src/lockupContract.ts
821
+ import { hex as hex3 } from "@scure/base";
822
+ import {
823
+ ArkAddress as ArkAddress2,
824
+ VHTLCV2ContractHandler
825
+ } from "@arkade-os/sdk";
826
+ var SWAP_LOCKUP_CONTRACT_TYPE = "vhtlc-v2";
827
+ var SWAP_LOCKUP_CONTRACT_LABEL = "Arkade RFQ swap lockup";
828
+ var SWAP_LOCKUP_CONTRACT_KIND = "rfq-swap-lockup";
829
+ var LockupContractMissing = class extends Error {
830
+ /** The lockup whose row is absent. */
831
+ address;
832
+ /** Its pkScript hex — the key the row would have been under. */
833
+ script;
834
+ constructor(address, script) {
835
+ super(
836
+ `no contract row for lockup ${address} (script ${script}); its covenant cannot be rebuilt from this wallet's contract store`
837
+ );
838
+ this.name = "LockupContractMissing";
839
+ this.address = address;
840
+ this.script = script;
841
+ }
842
+ };
843
+ var LockupRegistrationFailed = class extends Error {
844
+ /** The lockup address that was never registered — never fund it: nothing
845
+ * is watching it. */
846
+ address;
847
+ /** The covenant the row would have been written from, so the write is retryable without a
848
+ * quote. */
849
+ script;
850
+ constructor(script, address, cause) {
851
+ super(`failed to register the lockup contract for ${address}`, { cause });
852
+ this.name = "LockupRegistrationFailed";
853
+ this.address = address;
854
+ this.script = script;
855
+ }
856
+ };
857
+ async function registerLockupContract(contracts, script, address) {
858
+ try {
859
+ await contracts.createContract({
860
+ type: SWAP_LOCKUP_CONTRACT_TYPE,
861
+ params: VHTLCV2ContractHandler.serializeParams(script.options),
862
+ script: hex3.encode(script.pkScript),
863
+ address,
864
+ label: SWAP_LOCKUP_CONTRACT_LABEL,
865
+ metadata: { genericallySpendable: false, kind: SWAP_LOCKUP_CONTRACT_KIND }
866
+ });
867
+ } catch (error) {
868
+ throw new LockupRegistrationFailed(script, address, error);
869
+ }
870
+ }
871
+ async function lockupContractParams(contracts, lockupAddress) {
872
+ const script = hex3.encode(ArkAddress2.decode(lockupAddress).pkScript);
873
+ const [row] = await contracts.getContracts({ script });
874
+ if (!row) throw new LockupContractMissing(lockupAddress, script);
875
+ return row.params;
876
+ }
877
+
878
+ // src/onchainHtlc.ts
879
+ import { hex as hex4 } from "@scure/base";
880
+ import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
881
+ import { ripemd160 } from "@noble/hashes/legacy.js";
882
+ import * as btc from "@scure/btc-signer";
883
+ var ONCHAIN_ORDER_MARGIN_SECONDS = 2 * 60 * 60;
884
+ var ONCHAIN_CLAIM_MARGIN_SECONDS = 90 * 60;
885
+ var MAX_MIN_CONFIRMATIONS = 6;
886
+ var LOCKTIME_THRESHOLD = 5e8;
887
+ var ONCHAIN_SECONDS_PER_BLOCK = 600;
888
+ var ONCHAIN_DUST_SATS = BigInt(330);
889
+ var ONCHAIN_CLAIM_VSIZE = 152;
890
+ var newPreimage = () => crypto.getRandomValues(new Uint8Array(32));
891
+ var paymentHashOf = (preimage) => hex4.encode(sha2562(preimage));
892
+ var h160FromPaymentHash = (paymentHash) => ripemd160(hex4.decode(paymentHash));
893
+ var assertPreimageMatches = (preimage, preimageHash) => {
894
+ if (hex4.encode(ripemd160(sha2562(preimage))) !== hex4.encode(preimageHash)) {
895
+ throw new Error("preimage does not match the covenant's payment hash");
896
+ }
897
+ };
898
+ var gateError = (reason, message) => {
899
+ const error = new Error(message);
900
+ error.reason = reason;
901
+ return error;
902
+ };
903
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
904
+ async function pollUntil(probe, options, reason, message) {
905
+ const pollMs = options.pollMs ?? 5e3;
906
+ for (; ; ) {
907
+ const value = await probe();
908
+ if (value !== void 0) return value;
909
+ if (options.deadline !== void 0 && Date.now() / 1e3 >= options.deadline) {
910
+ throw gateError(reason, message);
911
+ }
912
+ await sleep(pollMs);
913
+ }
914
+ }
915
+ var L1_NETWORKS = {
916
+ bitcoin: btc.NETWORK,
917
+ testnet: btc.TEST_NETWORK,
918
+ regtest: { ...btc.TEST_NETWORK, bech32: "bcrt" }
919
+ };
920
+ var l1ScriptForAddress = (address, network) => btc.OutScript.encode(btc.Address(L1_NETWORKS[network]).decode(address));
921
+ function onchainHtlcScript(params, network) {
922
+ if (params.claimKey.length !== 32 || params.refundKey.length !== 32) {
923
+ throw new Error("claimKey and refundKey must be 32-byte x-only keys");
924
+ }
925
+ if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0) {
926
+ throw new Error(
927
+ `refundLocktime must be a positive unix timestamp, got ${params.refundLocktime}`
928
+ );
929
+ }
930
+ if (params.refundLocktime < LOCKTIME_THRESHOLD) {
931
+ throw new Error(
932
+ `refundLocktime ${params.refundLocktime} is below LOCKTIME_THRESHOLD (${LOCKTIME_THRESHOLD}) and would be interpreted as a block height`
933
+ );
934
+ }
935
+ if (!Object.hasOwn(L1_NETWORKS, network)) {
936
+ throw new Error(
937
+ `unknown L1 network '${String(network)}' \u2014 expected one of ${Object.keys(L1_NETWORKS).join(", ")}`
938
+ );
939
+ }
940
+ const h160 = h160FromPaymentHash(params.paymentHash);
941
+ const claim = btc.Script.encode([
942
+ "SIZE",
943
+ 32,
944
+ "EQUALVERIFY",
945
+ "HASH160",
946
+ h160,
947
+ "EQUALVERIFY",
948
+ params.claimKey,
949
+ "CHECKSIG"
950
+ ]);
951
+ const refund = btc.Script.encode([
952
+ btc.ScriptNum().encode(BigInt(params.refundLocktime)),
953
+ "CHECKLOCKTIMEVERIFY",
954
+ "DROP",
955
+ params.refundKey,
956
+ "CHECKSIG"
957
+ ]);
958
+ const payment = btc.p2tr(
959
+ btc.taprootNumsKey(),
960
+ btc.taprootListToTree([{ script: claim }, { script: refund }]),
961
+ L1_NETWORKS[network],
962
+ true
963
+ );
964
+ const controlBlockFor = (leaf) => {
965
+ for (const [block, script] of payment.tapLeafScript ?? []) {
966
+ if (script.length - 1 === leaf.length && hex4.encode(script.subarray(0, leaf.length)) === hex4.encode(leaf)) {
967
+ return btc.TaprootControlBlock.encode(block);
968
+ }
969
+ }
970
+ throw new Error("leaf missing from compiled taproot tree");
971
+ };
972
+ return {
973
+ address: payment.address,
974
+ pkScript: payment.script,
975
+ leaves: { claim, refund },
976
+ controlBlocks: { claim: controlBlockFor(claim), refund: controlBlockFor(refund) },
977
+ paymentHash: params.paymentHash,
978
+ refundLocktime: params.refundLocktime
979
+ };
980
+ }
981
+ var buildLeafSpend = async (input) => {
982
+ if (!Number.isFinite(input.feeRateSatVb) || input.feeRateSatVb <= 0) {
983
+ throw new Error(`feeRateSatVb must be positive, got ${input.feeRateSatVb}`);
984
+ }
985
+ const assemble = (payout2) => {
986
+ const tx2 = new btc.Transaction({ lockTime: input.lockTime ?? 0 });
987
+ tx2.addInput({
988
+ txid: input.utxo.txid,
989
+ index: input.utxo.vout,
990
+ witnessUtxo: { script: input.htlc.pkScript, amount: input.utxo.amount },
991
+ sequence: input.sequence
992
+ });
993
+ tx2.addOutput({ script: input.payoutPkScript, amount: payout2 });
994
+ return tx2;
995
+ };
996
+ const witness = (sig2) => [
997
+ sig2,
998
+ ...input.stackAboveSig,
999
+ input.leaf,
1000
+ input.controlBlock
1001
+ ];
1002
+ const sizing = assemble(input.utxo.amount);
1003
+ sizing.updateInput(0, { finalScriptWitness: witness(new Uint8Array(64)) }, true);
1004
+ const fee = BigInt(Math.ceil(sizing.vsize * input.feeRateSatVb));
1005
+ const payout = input.utxo.amount - fee;
1006
+ if (payout < ONCHAIN_DUST_SATS) {
1007
+ throw new Error(
1008
+ `fee ${fee} leaves ${payout} sats from a ${input.utxo.amount} sat HTLC \u2014 below the ${ONCHAIN_DUST_SATS} sat dust limit`
1009
+ );
1010
+ }
1011
+ const tx = assemble(payout);
1012
+ const sighash = tx.preimageWitnessV1(
1013
+ 0,
1014
+ [input.htlc.pkScript],
1015
+ btc.SigHash.DEFAULT,
1016
+ [input.utxo.amount],
1017
+ void 0,
1018
+ input.leaf,
1019
+ 192
1020
+ );
1021
+ const sig = await input.sign(sighash);
1022
+ if (sig.length !== 64)
1023
+ throw new Error(`sign() must return a 64-byte BIP340 signature, got ${sig.length}`);
1024
+ tx.updateInput(0, { finalScriptWitness: witness(sig) }, true);
1025
+ return { txHex: tx.hex, txid: tx.id, payoutAmount: payout };
1026
+ };
1027
+ var buildHtlcClaim = async (input) => {
1028
+ if (paymentHashOf(input.preimage) !== input.htlc.paymentHash) {
1029
+ throw new Error("preimage does not hash to the HTLC's payment hash");
1030
+ }
1031
+ return buildLeafSpend({
1032
+ htlc: input.htlc,
1033
+ utxo: input.utxo,
1034
+ leaf: input.htlc.leaves.claim,
1035
+ controlBlock: input.htlc.controlBlocks.claim,
1036
+ stackAboveSig: [input.preimage],
1037
+ payoutPkScript: input.payoutPkScript,
1038
+ feeRateSatVb: input.feeRateSatVb,
1039
+ sign: input.sign,
1040
+ sequence: 4294967293
1041
+ });
1042
+ };
1043
+ var buildHtlcRefund = (input) => buildLeafSpend({
1044
+ htlc: input.htlc,
1045
+ utxo: input.utxo,
1046
+ leaf: input.htlc.leaves.refund,
1047
+ controlBlock: input.htlc.controlBlocks.refund,
1048
+ stackAboveSig: [],
1049
+ payoutPkScript: input.payoutPkScript,
1050
+ feeRateSatVb: input.feeRateSatVb,
1051
+ sign: input.sign,
1052
+ lockTime: input.htlc.refundLocktime,
1053
+ // any value below 0xffffffff enables nLockTime enforcement
1054
+ sequence: 4294967294
1055
+ });
1056
+ function extractPreimage(txHex, paymentHash) {
1057
+ let raw;
1058
+ try {
1059
+ raw = btc.RawTx.decode(hex4.decode(txHex));
1060
+ } catch {
1061
+ return null;
1062
+ }
1063
+ for (const stack of raw.witnesses ?? []) {
1064
+ for (const item of stack) {
1065
+ if (item.length === 32 && hex4.encode(sha2562(item)) === paymentHash) return item;
1066
+ }
1067
+ }
1068
+ return null;
1069
+ }
1070
+ async function awaitOnchainFill(chain, htlc, minConfirmations, options = {}) {
1071
+ return pollUntil(
1072
+ async () => {
1073
+ const utxos = await chain.getScriptUtxos(htlc.pkScript);
1074
+ return utxos.filter((u) => u.confirmations >= minConfirmations).sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
1075
+ },
1076
+ options,
1077
+ "fill_timeout",
1078
+ "HTLC was not filled before the deadline"
1079
+ );
1080
+ }
1081
+ async function claimOnchainFill(chain, input) {
1082
+ const now = input.now ?? Math.floor(Date.now() / 1e3);
1083
+ if (input.htlc.refundLocktime - now < ONCHAIN_CLAIM_MARGIN_SECONDS) {
1084
+ throw gateError(
1085
+ "claim_window_closed",
1086
+ "refund leaf opens too soon to claim safely \u2014 take the covenant refund instead"
1087
+ );
1088
+ }
1089
+ const spend = await buildHtlcClaim(input);
1090
+ const txid = await chain.broadcast(spend.txHex);
1091
+ return { txid, payoutAmount: spend.payoutAmount };
1092
+ }
1093
+ async function classifyOnchainHtlc(chain, input) {
1094
+ const utxos = await chain.getScriptUtxos(input.htlc.pkScript);
1095
+ const best = utxos.sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
1096
+ if (!best) {
1097
+ if (!input.funding) return { phase: "unfunded" };
1098
+ const spend = await chain.getSpendingTx(
1099
+ input.funding.txid,
1100
+ input.funding.vout,
1101
+ input.htlc.pkScript
1102
+ );
1103
+ if (!spend) return { phase: "unfunded" };
1104
+ const preimage = extractPreimage(spend.txHex, input.htlc.paymentHash);
1105
+ const txid = btc.Transaction.fromRaw(hex4.decode(spend.txHex), {
1106
+ allowUnknownInputs: true,
1107
+ allowUnknownOutputs: true
1108
+ }).id;
1109
+ return preimage ? { phase: "claimed", txid, preimage } : { phase: "swept", txid };
1110
+ }
1111
+ if (best.confirmations < input.minConfirmations)
1112
+ return { phase: "awaiting_confirmations", utxo: best };
1113
+ const mtp = await chain.getMtp();
1114
+ if (mtp >= input.htlc.refundLocktime) return { phase: "refundable", utxo: best };
1115
+ return { phase: "claimable", utxo: best };
1116
+ }
1117
+
1118
+ // src/claimPacket.ts
1119
+ import { base64 } from "@scure/base";
1120
+ import { concatBytes as concatBytes2 } from "@scure/btc-signer/utils.js";
1121
+ import { gcm } from "@noble/ciphers/aes.js";
1122
+ import { secp256k1 } from "@noble/curves/secp256k1.js";
1123
+ import { hkdf } from "@noble/hashes/hkdf.js";
1124
+ import { sha256 as sha2563 } from "@noble/hashes/sha2.js";
1125
+ var HKDF_INFO = new TextEncoder().encode("covclaimd/preimage/v1");
1126
+ async function sealClaimPacket(input) {
1127
+ return sealWithEntropy(
1128
+ input,
1129
+ secp256k1.utils.randomSecretKey(),
1130
+ crypto.getRandomValues(new Uint8Array(12))
1131
+ );
1132
+ }
1133
+ async function sealWithEntropy(input, ephemeralKey, nonce) {
1134
+ if (input.preimage.length !== 32) throw new Error("preimage must be 32 bytes");
1135
+ if (input.covclaimdPubkey.length !== 33) {
1136
+ throw new Error("covclaimd pubkey must be 33-byte compressed");
1137
+ }
1138
+ const ephemeralPub = secp256k1.getPublicKey(ephemeralKey, true);
1139
+ const sharedX = secp256k1.getSharedSecret(ephemeralKey, input.covclaimdPubkey, true).subarray(1);
1140
+ const key = hkdf(sha2563, sharedX, ephemeralPub, HKDF_INFO, 32);
1141
+ if (nonce.length !== 12) throw new Error("nonce must be 12 bytes");
1142
+ const sealed = gcm(key, nonce, ephemeralPub).encrypt(input.preimage);
1143
+ const ciphertext = concatBytes2(ephemeralPub, nonce, sealed);
1144
+ return {
1145
+ ciphertext: base64.encode(ciphertext),
1146
+ packet: base64.encode(
1147
+ concatBytes2(
1148
+ tlv2(TLV_CIPHERTEXT, ciphertext),
1149
+ tlv2(TLV_COVCLAIMD_PUBKEY, input.covclaimdPubkey)
1150
+ )
1151
+ )
1152
+ };
1153
+ }
1154
+ var TLV_CIPHERTEXT = 1;
1155
+ var TLV_ARKADE_SCRIPT = 2;
1156
+ var TLV_COVCLAIMD_PUBKEY = 3;
1157
+ var COMPRESSED_PUBKEY_LENGTH = 33;
1158
+ var SEALED_CIPHERTEXT_LENGTH = 93;
1159
+ var CLAIM_PACKET_TYPE = 4;
1160
+ var tlv2 = (type, value) => Uint8Array.from([type, value.length >> 8 & 255, value.length & 255, ...value]);
1161
+ var appendArkadeScript = (body, arkadeScript) => Uint8Array.from([...body, ...tlv2(TLV_ARKADE_SCRIPT, arkadeScript)]);
1162
+ var parseTlv = (data) => {
1163
+ let ciphertextLength;
1164
+ let hasArkadeScript = false;
1165
+ let pubkey;
1166
+ let offset = 0;
1167
+ while (offset < data.length) {
1168
+ if (offset + 3 > data.length) throw new Error("truncated TLV header");
1169
+ const type = data[offset];
1170
+ const length = data[offset + 1] << 8 | data[offset + 2];
1171
+ offset += 3;
1172
+ if (offset + length > data.length) {
1173
+ throw new Error(`TLV type 0x${type.toString(16)} overruns the buffer`);
1174
+ }
1175
+ const value = data.subarray(offset, offset + length);
1176
+ offset += length;
1177
+ if (type === TLV_CIPHERTEXT) ciphertextLength = value.length;
1178
+ else if (type === TLV_ARKADE_SCRIPT) hasArkadeScript = true;
1179
+ else if (type === TLV_COVCLAIMD_PUBKEY) {
1180
+ if (value.length !== COMPRESSED_PUBKEY_LENGTH) {
1181
+ throw new Error(
1182
+ `covclaimd_pub_key TLV is ${value.length} bytes, want ${COMPRESSED_PUBKEY_LENGTH}`
1183
+ );
1184
+ }
1185
+ pubkey = value;
1186
+ }
1187
+ }
1188
+ return { ciphertextLength, hasArkadeScript, pubkey };
1189
+ };
1190
+ var claimPacketShape = (b64) => {
1191
+ try {
1192
+ const raw = base64.decode(b64);
1193
+ if (raw.length === SEALED_CIPHERTEXT_LENGTH) return { kind: "ciphertext" };
1194
+ const { ciphertextLength, hasArkadeScript, pubkey } = parseTlv(raw);
1195
+ if (ciphertextLength !== SEALED_CIPHERTEXT_LENGTH || pubkey === void 0) {
1196
+ return { kind: "ciphertext" };
1197
+ }
1198
+ return {
1199
+ kind: "packet",
1200
+ body: raw,
1201
+ needsArkadeScript: !hasArkadeScript,
1202
+ covclaimdPubkey: pubkey
1203
+ };
1204
+ } catch {
1205
+ return { kind: "ciphertext" };
1206
+ }
1207
+ };
1208
+
1209
+ // src/rfq.ts
1210
+ import { hex as hex5 } from "@scure/base";
1211
+ import { isAmount } from "@arkade-os/solver-discovery";
1212
+ import { ripemd160 as ripemd1602 } from "@noble/hashes/legacy.js";
1213
+ import {
1214
+ ArkAddress as ArkAddress3,
1215
+ VHTLC,
1216
+ networkFromArkadeInfo as networkFromArkadeInfo2,
1217
+ resolveEmulatorPubkey as resolveEmulatorPubkey2,
1218
+ toXOnly
1219
+ } from "@arkade-os/sdk";
1220
+ import {
1221
+ provisionClaimSecret,
1222
+ provisionRefundKey
1223
+ } from "@arkade-os/sdk";
1224
+ var solverHex = (value, field) => {
1225
+ try {
1226
+ return hex5.decode(value);
1227
+ } catch {
1228
+ throw new Error(`solver sent malformed hex for ${field}`);
1229
+ }
1230
+ };
1231
+ var quoteSats = (value, field) => {
1232
+ if (typeof value !== "number" || !Number.isSafeInteger(value)) {
1233
+ throw new Error(`HTLC quote carries a non-sats ${field}: ${String(value)}`);
1234
+ }
1235
+ return value;
1236
+ };
1237
+ var quoteAmountSats = (value, field) => {
1238
+ if (typeof value === "string" && isAmount(value)) return BigInt(value);
1239
+ if (typeof value === "number" && Number.isSafeInteger(value)) return BigInt(value);
1240
+ throw new Error(`HTLC quote carries an unreadable ${field}: ${String(value)}`);
1241
+ };
1242
+ var quoteExpectedSats = (value, field) => {
1243
+ const sats = quoteAmountSats(value, field);
1244
+ if (sats <= 0n || sats > BigInt(Number.MAX_SAFE_INTEGER)) {
1245
+ throw new Error(`HTLC quote carries an unusable ${field}: ${String(value)}`);
1246
+ }
1247
+ return Number(sats);
1248
+ };
1249
+ var ARKADE_BTC = "arkade:BTC";
1250
+ var LIGHTNING_BTC = "lightning:BTC";
1251
+ var ONCHAIN_BTC = "onchain:BTC";
1252
+ var arkadeAssetLeg = (id) => `arkade:${id.toString()}`;
1253
+ var rfqPair = (from, to) => `${from}->${to}`;
1254
+ var LIGHTNING_SEND_PAIR = rfqPair(ARKADE_BTC, LIGHTNING_BTC);
1255
+ var LIGHTNING_RECEIVE_PAIR = rfqPair(LIGHTNING_BTC, ARKADE_BTC);
1256
+ var ONCHAIN_SEND_PAIR = rfqPair(ARKADE_BTC, ONCHAIN_BTC);
1257
+ var ONCHAIN_RECEIVE_PAIR = rfqPair(ONCHAIN_BTC, ARKADE_BTC);
1258
+ var RFQ_TERMINAL_STATES = ["settled", "refused", "expired", "refunded", "stuck"];
1259
+ var RFQ_REFUSAL_ERROR_CODES = [
1260
+ "amount_side_unsupported",
1261
+ "exact_out_unsupported",
1262
+ "invalid_amount",
1263
+ "invalid_payout_address",
1264
+ "invalid_refund_address",
1265
+ "invoice_amount_mismatch",
1266
+ "invoice_cltv_too_large",
1267
+ "invoice_malformed",
1268
+ "invoice_missing_amount",
1269
+ "invoice_missing_network",
1270
+ "invoice_missing_payment_hash",
1271
+ "invoice_missing_timestamp",
1272
+ "invoice_mixed_case",
1273
+ "invoice_sub_satoshi_amount",
1274
+ "invoice_too_long",
1275
+ "invoice_wrong_network"
1276
+ ];
1277
+ var isRfqRefusalErrorCode = (value) => typeof value === "string" && RFQ_REFUSAL_ERROR_CODES.includes(value);
1278
+ var REFUSAL_FIELDS = /* @__PURE__ */ new Set([
1279
+ "amount",
1280
+ "amount_side",
1281
+ "profile.invoice",
1282
+ "profile.payout_address",
1283
+ "profile.refund_address"
1284
+ ]);
1285
+ var REFUSAL_UNITS = /* @__PURE__ */ new Set(["blocks", "characters", "sats"]);
1286
+ var safeInteger = (value) => typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : void 0;
1287
+ var safeRefusalDetail = (detail) => {
1288
+ if (!isRfqRefusalErrorCode(detail.errorCode)) return {};
1289
+ return {
1290
+ errorCode: detail.errorCode,
1291
+ field: typeof detail.field === "string" && REFUSAL_FIELDS.has(detail.field) ? detail.field : void 0,
1292
+ actual: safeInteger(detail.actual),
1293
+ expected: safeInteger(detail.expected),
1294
+ limit: safeInteger(detail.limit),
1295
+ unit: typeof detail.unit === "string" && REFUSAL_UNITS.has(detail.unit) ? detail.unit : void 0
1296
+ };
1297
+ };
1298
+ var refusalMessage = (reason, detail) => {
1299
+ if (!detail.errorCode) return `solver refused: ${reason}`;
1300
+ const where = detail.field ? ` at ${detail.field}` : "";
1301
+ const unit = detail.unit ? ` ${detail.unit}` : "";
1302
+ if (detail.actual !== void 0 && detail.limit !== void 0) {
1303
+ return `solver refused: ${reason} (${detail.errorCode}${where}: ${detail.actual}${unit}, limit ${detail.limit})`;
1304
+ }
1305
+ if (detail.actual !== void 0 && detail.expected !== void 0) {
1306
+ return `solver refused: ${reason} (${detail.errorCode}${where}: ${detail.actual}${unit}, expected ${detail.expected})`;
1307
+ }
1308
+ return `solver refused: ${reason} (${detail.errorCode}${where})`;
1309
+ };
1310
+ var SwapRefusal = class extends Error {
1311
+ /** Literal-typed so the v2 error taxonomy's union discriminates on `name`
1312
+ * — a `string` here collapses the discriminant for every member. */
1313
+ name = "SwapRefusal";
1314
+ reason;
1315
+ rfqId;
1316
+ errorCode;
1317
+ field;
1318
+ actual;
1319
+ expected;
1320
+ limit;
1321
+ unit;
1322
+ constructor(reason, rfqId, detail = {}) {
1323
+ const safeDetail = safeRefusalDetail(detail);
1324
+ super(refusalMessage(reason, safeDetail));
1325
+ this.reason = reason;
1326
+ this.rfqId = rfqId;
1327
+ this.errorCode = safeDetail.errorCode;
1328
+ this.field = safeDetail.field;
1329
+ this.actual = safeDetail.actual;
1330
+ this.expected = safeDetail.expected;
1331
+ this.limit = safeDetail.limit;
1332
+ this.unit = safeDetail.unit;
1333
+ }
1334
+ };
1335
+ var AddressMismatch = class extends Error {
1336
+ derived;
1337
+ quoted;
1338
+ constructor(derived, quoted) {
1339
+ super("solver lockup address does not match local derivation \u2014 refusing to fund");
1340
+ this.name = "AddressMismatch";
1341
+ this.derived = derived;
1342
+ this.quoted = quoted;
1343
+ }
1344
+ };
1345
+ var newRfqId = () => hex5.encode(crypto.getRandomValues(new Uint8Array(32)));
1346
+ var lightningSendRequest = (input) => ({
1347
+ v: 1,
1348
+ type: "rfq_request",
1349
+ rfq_id: input.rfqId,
1350
+ pair: LIGHTNING_SEND_PAIR,
1351
+ amount_side: "to",
1352
+ profile: {
1353
+ invoice: input.invoice,
1354
+ refund_address: input.refundAddress,
1355
+ client_refund_pubkey: hex5.encode(input.senderPubkey)
1356
+ }
1357
+ });
1358
+ var arkadeSwapRequest = (input) => {
1359
+ if (!input.wantAsset && !input.offerAsset) {
1360
+ throw new Error(
1361
+ "set at least one of wantAsset or offerAsset \u2014 with neither set both legs are BTC, which is not a swap"
1362
+ );
1363
+ }
1364
+ const pair = rfqPair(
1365
+ input.offerAsset ? arkadeAssetLeg(input.offerAsset) : ARKADE_BTC,
1366
+ input.wantAsset ? arkadeAssetLeg(input.wantAsset) : ARKADE_BTC
1367
+ );
1368
+ assertPairLength(pair);
1369
+ return {
1370
+ v: 1,
1371
+ type: "rfq_request",
1372
+ rfq_id: input.rfqId,
1373
+ pair,
1374
+ amount_side: input.amountSide ?? "from",
1375
+ amount: canonicalAssetAmount(input.amount),
1376
+ // The solver's `.strict()` schema refuses any undeclared key as `unsupported_payload`.
1377
+ profile: {
1378
+ maker_pk_script: normalizeMakerPkScript(input.makerPkScript),
1379
+ maker_public_key: normalizeMakerPublicKey(input.makerPublicKey)
1380
+ }
1381
+ };
1382
+ };
1383
+ var canonicalAssetAmount = (amount) => {
1384
+ if (typeof amount === "bigint") {
1385
+ if (amount <= 0n) throw new Error(`amount must be positive, got ${amount}`);
1386
+ return amount.toString();
1387
+ }
1388
+ if (typeof amount === "number") {
1389
+ if (!Number.isSafeInteger(amount) || amount <= 0) {
1390
+ throw new Error(`amount must be a positive safe integer, got ${amount}`);
1391
+ }
1392
+ return String(amount);
1393
+ }
1394
+ if (!/^(0|[1-9][0-9]*)$/.test(amount) || BigInt(amount) <= 0n) {
1395
+ throw new Error(`amount must be a canonical decimal string of atomic units, got ${amount}`);
1396
+ }
1397
+ return amount;
1398
+ };
1399
+ var normalizeHexBytes = (value, expectedBytes, label) => {
1400
+ if (value === void 0 || value === null) {
1401
+ throw new Error(`${label} is required`);
1402
+ }
1403
+ const bytes = typeof value === "string" ? solverHex(value, label) : value;
1404
+ if (!(bytes instanceof Uint8Array) || bytes.length !== expectedBytes) {
1405
+ const got = bytes instanceof Uint8Array ? bytes.length : typeof bytes;
1406
+ throw new Error(`${label} must be ${expectedBytes} bytes, got ${got}`);
1407
+ }
1408
+ return hex5.encode(bytes);
1409
+ };
1410
+ var normalizeMakerPkScript = (value) => {
1411
+ const encoded = normalizeHexBytes(value, 34, "maker_pk_script");
1412
+ if (!encoded.startsWith("5100") && !encoded.startsWith("5120")) {
1413
+ throw new Error("maker_pk_script must be a taproot scriptPubKey (OP_1 <32-byte program>)");
1414
+ }
1415
+ return encoded;
1416
+ };
1417
+ var normalizeMakerPublicKey = (value) => {
1418
+ const raw = typeof value === "string" ? value : hex5.encode(value);
1419
+ const bytes = solverHex(raw, "maker_public_key");
1420
+ if (bytes.length === 33) {
1421
+ throw new Error("maker_public_key must be x-only (32 bytes), not compressed (33 bytes)");
1422
+ }
1423
+ return normalizeHexBytes(bytes, 32, "maker_public_key");
1424
+ };
1425
+ var MIN_HEADROOM_SECONDS = 90 * 60;
1426
+ var assertFinite = (value, reason, label) => {
1427
+ if (value !== void 0 && !Number.isFinite(value)) {
1428
+ throw gateError(reason, `${label} is not a finite number (${String(value)})`);
1429
+ }
1430
+ };
1431
+ var MAX_PAIR_LENGTH = 158;
1432
+ var assertPairLength = (pair) => {
1433
+ if (pair.length > MAX_PAIR_LENGTH) {
1434
+ throw new Error(
1435
+ `pair is ${pair.length} characters, over the wire's ${MAX_PAIR_LENGTH}-character limit`
1436
+ );
1437
+ }
1438
+ };
1439
+ var verifyLockupAddress = (quote, derivedAddress) => {
1440
+ const quoted = quote.profile?.lockup_address;
1441
+ const candidates = Array.isArray(derivedAddress) ? derivedAddress : [derivedAddress];
1442
+ const matched = candidates.find((address) => address === quoted);
1443
+ if (matched === void 0) throw new AddressMismatch(candidates, quoted);
1444
+ return matched;
1445
+ };
1446
+ var LOCKUP_SHAPE_VARIANTS = [void 0, "preTimelockedRefund"];
1447
+ var matchQuotedLockup = (quote, hrp, serverPubkey, build) => {
1448
+ const candidates = LOCKUP_SHAPE_VARIANTS.map((legacy) => {
1449
+ const script = build(legacy);
1450
+ return { script, address: script.address(hrp, serverPubkey).encode(), legacy };
1451
+ });
1452
+ const matchedAddress = verifyLockupAddress(
1453
+ quote,
1454
+ candidates.map((candidate) => candidate.address)
1455
+ );
1456
+ return candidates.find((candidate) => candidate.address === matchedAddress);
1457
+ };
1458
+ var assertFundable = (input) => {
1459
+ const fail = (reason, message) => {
1460
+ throw gateError(reason, message);
1461
+ };
1462
+ if (input.quote.valid_until === void 0) {
1463
+ fail("quote_malformed", "quote carries no valid_until");
1464
+ }
1465
+ assertFinite(input.quote.valid_until, "quote_malformed", "quote valid_until");
1466
+ if (input.invoiceExpiresAt !== void 0 && input.now >= input.invoiceExpiresAt) {
1467
+ fail("invoice_expired", "invoice expired");
1468
+ }
1469
+ if (input.now >= input.quote.valid_until)
1470
+ fail("quote_expired", "quote expired \u2014 request a fresh one");
1471
+ if (quoteAmountSats(input.quote.from_amount, "from_amount") <= 0n || quoteAmountSats(input.quote.to_amount, "to_amount") <= 0n) {
1472
+ fail("non_positive_amount", "quote carries a non-positive amount");
1473
+ }
1474
+ if (input.quote.refund_locktime !== void 0 && input.quote.refund_locktime - input.now < MIN_HEADROOM_SECONDS) {
1475
+ fail("insufficient_headroom", "refund deadline headroom below 90 minutes");
1476
+ }
1477
+ if (input.maxFee) {
1478
+ const { bps, sats, referenceRate } = input.maxFee;
1479
+ if (bps === void 0 && sats === void 0) {
1480
+ fail("max_fee_unbounded", "maxFee names neither bps nor sats");
1481
+ }
1482
+ if (bps !== void 0 && (!Number.isInteger(bps) || bps < 0 || bps > 1e4)) {
1483
+ fail("max_fee_out_of_range", `maxFee.bps must be an integer in 0..10000, got ${bps}`);
1484
+ }
1485
+ if (sats !== void 0 && (!Number.isInteger(sats) || sats < 0)) {
1486
+ fail("max_fee_out_of_range", `maxFee.sats must be a non-negative integer, got ${sats}`);
1487
+ }
1488
+ const legs = input.quote.pair.split("->");
1489
+ const assetOf = (leg) => leg.slice(leg.indexOf(":") + 1);
1490
+ const sameAsset = legs.length === 2 && assetOf(legs[0]) === assetOf(legs[1]);
1491
+ if (!sameAsset && referenceRate === void 0) {
1492
+ fail(
1493
+ "fee_gate_unavailable",
1494
+ `maxFee cannot gate ${input.quote.pair}: its legs name different assets, so from_amount - to_amount is not a fee. Supply maxFee.referenceRate (to-units per from-unit) from a source of your OWN \u2014 reading it off the solver's published feed would check the solver against its own number`
1495
+ );
1496
+ }
1497
+ if (!sameAsset && (!Number.isFinite(referenceRate) || referenceRate <= 0)) {
1498
+ fail(
1499
+ "max_fee_out_of_range",
1500
+ `maxFee.referenceRate must be a positive finite number, got ${referenceRate}`
1501
+ );
1502
+ }
1503
+ const fromSats = quoteSats(input.quote.from_amount, "from_amount");
1504
+ const toSats = quoteSats(input.quote.to_amount, "to_amount");
1505
+ const fee = sameAsset ? fromSats - toSats : Math.ceil(
1506
+ (fromSats * referenceRate - toSats) / referenceRate
1507
+ );
1508
+ const allowed = Math.max(sats ?? 0, Math.floor(fromSats * (bps ?? 0) / 1e4));
1509
+ if (fee > allowed) {
1510
+ fail("fee_too_high", `fee ${fee} exceeds the ${allowed} this client allows`);
1511
+ }
1512
+ }
1513
+ if (input.onchain) {
1514
+ const { htlcLocktime, minConfirmations, direction } = input.onchain;
1515
+ if (!Number.isInteger(minConfirmations) || minConfirmations < 1 || minConfirmations > MAX_MIN_CONFIRMATIONS) {
1516
+ fail(
1517
+ "confirmations_out_of_range",
1518
+ `min_confirmations must be 1..${MAX_MIN_CONFIRMATIONS}, got ${minConfirmations}`
1519
+ );
1520
+ }
1521
+ const needed = minConfirmations * ONCHAIN_SECONDS_PER_BLOCK + ONCHAIN_CLAIM_MARGIN_SECONDS;
1522
+ if (htlcLocktime - input.now <= needed) {
1523
+ fail("claim_window_too_short", "L1 HTLC locktime leaves no safe claim window");
1524
+ }
1525
+ if (direction === "send") {
1526
+ if (input.quote.refund_locktime === void 0 || htlcLocktime + ONCHAIN_ORDER_MARGIN_SECONDS > input.quote.refund_locktime) {
1527
+ fail(
1528
+ "timelock_order",
1529
+ "L1 HTLC locktime + margin must fall before the Arkade refund locktime"
1530
+ );
1531
+ }
1532
+ }
1533
+ }
1534
+ };
1535
+ var expectQuote = (payload, rfqId, requestedPair) => {
1536
+ const p = payload;
1537
+ if (p?.type === "rfq_refusal") {
1538
+ throw new SwapRefusal(p.reason ?? "unknown", p.rfq_id ?? rfqId, {
1539
+ errorCode: p.error_code,
1540
+ field: p.field,
1541
+ actual: p.actual,
1542
+ expected: p.expected,
1543
+ limit: p.limit,
1544
+ unit: p.unit
1545
+ });
1546
+ }
1547
+ if (p?.type !== "rfq_quote" || p.rfq_id !== rfqId) {
1548
+ throw new Error(`unexpected reply: ${p?.type ?? "no payload"}`);
1549
+ }
1550
+ if (requestedPair !== void 0 && p.pair !== requestedPair) {
1551
+ throw new Error(
1552
+ `solver quoted ${JSON.stringify(p.pair)}, not the requested ${requestedPair}`
1553
+ );
1554
+ }
1555
+ return payload;
1556
+ };
1557
+ var pairOf = (payload) => typeof payload.pair === "string" ? payload.pair : void 0;
1558
+ var httpTransport = (baseUrl, options = {}) => {
1559
+ const fetchImpl = options.fetchImpl ?? fetch;
1560
+ const readJson = async (response, what) => {
1561
+ const body = await response.text();
1562
+ try {
1563
+ return JSON.parse(body);
1564
+ } catch {
1565
+ throw new Error(
1566
+ `${what} returned HTTP ${response.status} with a non-JSON body: ${body.slice(0, 200)}`
1567
+ );
1568
+ }
1569
+ };
1570
+ return {
1571
+ async requestQuote(payload) {
1572
+ const response = await fetchImpl(`${baseUrl}/v1/swap`, {
1573
+ method: "POST",
1574
+ headers: { "content-type": "application/json" },
1575
+ body: JSON.stringify(payload)
1576
+ });
1577
+ return expectQuote(
1578
+ await readJson(response, "quote request"),
1579
+ String(payload.rfq_id),
1580
+ pairOf(payload)
1581
+ );
1582
+ },
1583
+ async status(rfqId) {
1584
+ const response = await fetchImpl(`${baseUrl}/v1/rfq/${rfqId}`, { method: "GET" });
1585
+ if (response.status === 404) return null;
1586
+ const payload = await readJson(response, "status request");
1587
+ return payload?.type === "rfq_status" ? payload : null;
1588
+ },
1589
+ async close() {
1590
+ }
1591
+ };
1592
+ };
1593
+ var relayTransport = (relayUrl, options) => {
1594
+ const timeoutMs = options.timeoutMs ?? 3e4;
1595
+ const Ctor = options.WebSocketCtor ?? WebSocket;
1596
+ const pending = /* @__PURE__ */ new Map();
1597
+ let sequence = 0;
1598
+ const socketReady = new Promise((resolve, reject) => {
1599
+ const ws = new Ctor(relayUrl);
1600
+ ws.addEventListener("open", () => {
1601
+ ws.send(
1602
+ JSON.stringify({
1603
+ op: "sub",
1604
+ id: "s1",
1605
+ filter: { recipient: options.clientPubkey }
1606
+ })
1607
+ );
1608
+ resolve(ws);
1609
+ });
1610
+ ws.addEventListener("error", () => reject(new Error("relay connection failed")));
1611
+ ws.addEventListener("message", (event) => {
1612
+ let frame;
1613
+ try {
1614
+ frame = JSON.parse(String(event.data));
1615
+ } catch {
1616
+ return;
1617
+ }
1618
+ if (frame.op !== "event") return;
1619
+ const payload = frame.event?.payload;
1620
+ const rfqId = payload?.rfq_id;
1621
+ const settle = rfqId !== void 0 ? pending.get(rfqId) : void 0;
1622
+ if (settle && rfqId !== void 0) {
1623
+ pending.delete(rfqId);
1624
+ settle(payload);
1625
+ }
1626
+ });
1627
+ });
1628
+ const roundTrip = async (payload, rfqId) => {
1629
+ const ws = await socketReady;
1630
+ const reply = new Promise((resolve, reject) => {
1631
+ const timer = setTimeout(() => {
1632
+ pending.delete(rfqId);
1633
+ reject(new Error(`no reply within ${timeoutMs}ms`));
1634
+ }, timeoutMs);
1635
+ pending.set(rfqId, (p) => {
1636
+ clearTimeout(timer);
1637
+ resolve(p);
1638
+ });
1639
+ });
1640
+ ws.send(
1641
+ JSON.stringify({
1642
+ op: "event",
1643
+ event: {
1644
+ id: `${options.clientPubkey}:${sequence += 1}`,
1645
+ author: options.clientPubkey,
1646
+ recipient: options.solverPubkey,
1647
+ createdAtMs: Date.now(),
1648
+ payload
1649
+ }
1650
+ })
1651
+ );
1652
+ return reply;
1653
+ };
1654
+ return {
1655
+ async requestQuote(payload) {
1656
+ return expectQuote(
1657
+ await roundTrip(payload, String(payload.rfq_id)),
1658
+ String(payload.rfq_id),
1659
+ pairOf(payload)
1660
+ );
1661
+ },
1662
+ async status(rfqId) {
1663
+ const payload = await roundTrip(
1664
+ { v: 1, type: "rfq_status_request", rfq_id: rfqId },
1665
+ rfqId
1666
+ );
1667
+ return payload?.type === "rfq_status" ? payload : null;
1668
+ },
1669
+ async close() {
1670
+ try {
1671
+ (await socketReady).close();
1672
+ } catch {
1673
+ }
1674
+ }
1675
+ };
1676
+ };
1677
+ var SEQUENCE_GRANULARITY_SECONDS = 512;
1678
+ var SOLO_REFUND_HEADROOM_SECONDS = 8 * SEQUENCE_GRANULARITY_SECONDS;
1679
+ var unilateralClaimDelay = (operatorExitDelaySeconds) => {
1680
+ if (!Number.isFinite(operatorExitDelaySeconds) || operatorExitDelaySeconds < SEQUENCE_GRANULARITY_SECONDS) {
1681
+ throw new Error(
1682
+ `operator exit delay must be at least ${SEQUENCE_GRANULARITY_SECONDS}s of seconds, got ${operatorExitDelaySeconds}`
1683
+ );
1684
+ }
1685
+ if (operatorExitDelaySeconds > 65535 * SEQUENCE_GRANULARITY_SECONDS - SOLO_REFUND_HEADROOM_SECONDS) {
1686
+ throw new Error(
1687
+ `operator exit delay ${operatorExitDelaySeconds}s exceeds what BIP68 can encode once the solo refund's headroom is stacked above it`
1688
+ );
1689
+ }
1690
+ return Math.ceil(operatorExitDelaySeconds / SEQUENCE_GRANULARITY_SECONDS) * SEQUENCE_GRANULARITY_SECONDS;
1691
+ };
1692
+ var unilateralRefundDelay = (claimDelay) => claimDelay;
1693
+ var unilateralRefundWithoutReceiverDelay = (claimDelay) => claimDelay + SOLO_REFUND_HEADROOM_SECONDS;
1694
+ var seconds = (value) => ({
1695
+ type: "seconds",
1696
+ value: BigInt(value)
1697
+ });
1698
+ var suiteVhtlc = (params, roles) => new VHTLC.ScriptV2({
1699
+ sender: roles.sender,
1700
+ receiver: roles.receiver,
1701
+ server: params.operatorPubkey,
1702
+ preimageHash: ripemd1602(hex5.decode(params.paymentHash)),
1703
+ refundLocktime: BigInt(params.refundLocktime),
1704
+ unilateralClaimDelay: seconds(params.claimDelay),
1705
+ unilateralRefundDelay: seconds(unilateralRefundDelay(params.claimDelay)),
1706
+ unilateralRefundWithoutReceiverDelay: seconds(
1707
+ roles.refundWithoutReceiverDelay ?? unilateralRefundWithoutReceiverDelay(params.claimDelay)
1708
+ ),
1709
+ nonInteractiveParameters: {
1710
+ receiverPkScript: roles.receiverPkScript,
1711
+ senderPkScript: roles.senderPkScript,
1712
+ emulatorPubkey: params.emulatorPubkey,
1713
+ ...params.legacy !== void 0 && { legacy: params.legacy }
1714
+ }
1715
+ });
1716
+ function lightningSendContract(params) {
1717
+ return suiteVhtlc(params, {
1718
+ sender: params.senderPubkey,
1719
+ receiver: params.solverPubkey,
1720
+ senderPkScript: params.refundPkScript,
1721
+ receiverPkScript: params.receiverPkScript,
1722
+ refundWithoutReceiverDelay: params.refundWithoutReceiverDelay
1723
+ });
1724
+ }
1725
+ function deriveLightningSend(input) {
1726
+ const { quote } = input;
1727
+ if (quote.refund_locktime === void 0) {
1728
+ throw new Error("lightning-send quote is missing refund_locktime");
1729
+ }
1730
+ const refundWithoutReceiverDelay = quote.profile?.refund_without_receiver_delay;
1731
+ if (refundWithoutReceiverDelay === void 0) {
1732
+ throw new Error("lightning-send quote is missing profile.refund_without_receiver_delay");
1733
+ }
1734
+ if (!Number.isSafeInteger(refundWithoutReceiverDelay) || refundWithoutReceiverDelay < input.claimDelay || refundWithoutReceiverDelay % SEQUENCE_GRANULARITY_SECONDS !== 0 || refundWithoutReceiverDelay > 65535 * SEQUENCE_GRANULARITY_SECONDS) {
1735
+ throw new Error("lightning-send quote carries an invalid refund_without_receiver_delay");
1736
+ }
1737
+ if (refundWithoutReceiverDelay < quote.refund_locktime - input.now) {
1738
+ throw new Error("lightning-send quote lets the solo refund open before refund_locktime");
1739
+ }
1740
+ const receiverPkScriptHex = quote.profile?.receiver_pk_script;
1741
+ if (receiverPkScriptHex === void 0) {
1742
+ throw new Error("lightning-send quote is missing profile.receiver_pk_script");
1743
+ }
1744
+ const contractParams = {
1745
+ solverPubkey: toXOnly(hex5.decode(quote.solver_pubkey), "solver key"),
1746
+ refundLocktime: quote.refund_locktime,
1747
+ operatorPubkey: input.operatorPubkey,
1748
+ paymentHash: input.paymentHash,
1749
+ claimDelay: input.claimDelay,
1750
+ refundWithoutReceiverDelay,
1751
+ emulatorPubkey: input.emulatorPubkey,
1752
+ senderPubkey: input.senderPubkey,
1753
+ receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
1754
+ refundPkScript: input.refundPkScript
1755
+ };
1756
+ const matched = matchQuotedLockup(
1757
+ quote,
1758
+ input.hrp,
1759
+ input.operatorPubkey,
1760
+ (legacy) => lightningSendContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
1761
+ );
1762
+ return {
1763
+ address: matched.address,
1764
+ swapPkScript: matched.script.pkScript,
1765
+ script: matched.script,
1766
+ contractParams: {
1767
+ ...contractParams,
1768
+ ...matched.legacy !== void 0 && { legacy: matched.legacy }
1769
+ },
1770
+ refundLocktime: quote.refund_locktime
1771
+ };
1772
+ }
1773
+ async function requestLightningSend(wallet, transport, params) {
1774
+ const rfqId = params.rfqId ?? newRfqId();
1775
+ const secrets = await provisionRefundKey(wallet);
1776
+ const senderPubkey = secrets.pubkey;
1777
+ const refundAddress = secrets.address;
1778
+ const info = await wallet.getArkadeInfo({ requireLive: true });
1779
+ const quote = await transport.requestQuote(
1780
+ lightningSendRequest({ rfqId, invoice: params.invoice.raw, refundAddress, senderPubkey })
1781
+ );
1782
+ const now = Math.floor(Date.now() / 1e3);
1783
+ const claimDelay = unilateralClaimDelay(Number(info.unilateralExitDelay));
1784
+ if (quoteSats(quote.to_amount, "to_amount") !== params.invoice.amountSats) {
1785
+ throw new Error(
1786
+ `quote to_amount ${quote.to_amount} does not match the invoice's ${params.invoice.amountSats}`
1787
+ );
1788
+ }
1789
+ if (quoteSats(quote.from_amount, "from_amount") < quoteSats(quote.to_amount, "to_amount")) {
1790
+ throw new Error(
1791
+ `quote from_amount ${quote.from_amount} is below the invoice amount \u2014 a negative spread is not a quote`
1792
+ );
1793
+ }
1794
+ const operatorPubkey = toXOnly(hex5.decode(info.signerPubkey), "ark signer key");
1795
+ const network = networkFromArkadeInfo2(info);
1796
+ const derived = deriveLightningSend({
1797
+ quote,
1798
+ paymentHash: params.invoice.paymentHash,
1799
+ senderPubkey,
1800
+ refundPkScript: secrets.pkScript,
1801
+ operatorPubkey,
1802
+ emulatorPubkey: toXOnly(
1803
+ hex5.decode(resolveEmulatorPubkey2(network, params.emulatorPubkey)),
1804
+ "emulator signer key"
1805
+ ),
1806
+ claimDelay,
1807
+ hrp: network.hrp,
1808
+ now
1809
+ });
1810
+ const { address, script, contractParams } = derived;
1811
+ assertFundable({
1812
+ quote,
1813
+ invoiceExpiresAt: params.invoice.expiresAt,
1814
+ now
1815
+ });
1816
+ await registerLockupContract(await wallet.getContractManager(), script, address);
1817
+ return {
1818
+ rfqId,
1819
+ quote,
1820
+ address,
1821
+ fundAmount: quoteSats(quote.from_amount, "from_amount"),
1822
+ swapPkScript: derived.swapPkScript,
1823
+ script,
1824
+ refundAddress,
1825
+ senderPubkey,
1826
+ secrets,
1827
+ contractParams
1828
+ };
1829
+ }
1830
+ var offerTermsFromQuote = (quote, assets) => {
1831
+ if (!assets.wantAsset && !assets.offerAsset) {
1832
+ throw new Error("set at least one of wantAsset or offerAsset");
1833
+ }
1834
+ const wantAmount = BigInt(quote.to_amount);
1835
+ if (assets.wantAsset) return { wantAmount, wantAsset: assets.wantAsset };
1836
+ return { wantAmount, offerAsset: assets.offerAsset };
1837
+ };
1838
+ var verifyOfferAddress = (quote, derived) => {
1839
+ const quotedAddress = quote.profile?.offer_address;
1840
+ const quotedScript = quote.profile?.offer_pk_script;
1841
+ const derivedScript = hex5.encode(derived.swapPkScript);
1842
+ if (quotedAddress !== derived.address || quotedScript !== derivedScript) {
1843
+ throw new AddressMismatch([derived.address], quotedAddress);
1844
+ }
1845
+ return derived;
1846
+ };
1847
+ var assertArkadeFundable = (input) => {
1848
+ const now = input.now ?? Math.floor(Date.now() / 1e3);
1849
+ if (!Number.isSafeInteger(input.quote.valid_until)) {
1850
+ throw gateError("quote_expired", "quote carries no valid_until");
1851
+ }
1852
+ if (now >= input.quote.valid_until) {
1853
+ throw gateError("quote_expired", `quote lapsed at ${input.quote.valid_until} (now ${now})`);
1854
+ }
1855
+ if (BigInt(input.quote.from_amount) <= 0n || BigInt(input.quote.to_amount) <= 0n) {
1856
+ throw gateError("quote_expired", "quote carries a non-positive amount");
1857
+ }
1858
+ };
1859
+ var quoteCarrierSats = (quote) => {
1860
+ const raw = quote.carrier_sats;
1861
+ if (raw === void 0) return ASSET_CARRIER_SATS;
1862
+ const canonical = typeof raw === "number" ? Number.isSafeInteger(raw) && raw >= 0 : /^(0|[1-9][0-9]*)$/.test(raw);
1863
+ if (!canonical) {
1864
+ throw gateError(
1865
+ "carrier_malformed",
1866
+ `quote carrier_sats ${String(raw)} is not a non-negative integer`
1867
+ );
1868
+ }
1869
+ const published = BigInt(raw);
1870
+ return published > 0n ? published : ASSET_CARRIER_SATS;
1871
+ };
1872
+ async function requestArkadeSwap(wallet, transport, params) {
1873
+ if (!params.wantAsset && !params.offerAsset) {
1874
+ throw new Error("set at least one of wantAsset or offerAsset; BTC-to-BTC is not a swap");
1875
+ }
1876
+ const rfqId = params.rfqId ?? newRfqId();
1877
+ const amountSide = params.amountSide ?? "from";
1878
+ const [makerAddress, makerPublicKey] = await Promise.all([
1879
+ wallet.getAddress(),
1880
+ wallet.identity.xOnlyPublicKey()
1881
+ ]);
1882
+ const makerPkScript = ArkAddress3.decode(makerAddress).pkScript;
1883
+ const pair = rfqPair(
1884
+ params.offerAsset ? arkadeAssetLeg(params.offerAsset) : ARKADE_BTC,
1885
+ params.wantAsset ? arkadeAssetLeg(params.wantAsset) : ARKADE_BTC
1886
+ );
1887
+ const quote = await transport.requestQuote(
1888
+ arkadeSwapRequest({
1889
+ rfqId,
1890
+ ...params.offerAsset !== void 0 ? { offerAsset: params.offerAsset } : {},
1891
+ ...params.wantAsset !== void 0 ? { wantAsset: params.wantAsset } : {},
1892
+ amount: params.amount,
1893
+ amountSide,
1894
+ makerPkScript,
1895
+ makerPublicKey
1896
+ })
1897
+ );
1898
+ if (quote.pair !== pair) {
1899
+ throw new Error(`solver quoted ${JSON.stringify(quote.pair)}, not the requested ${pair}`);
1900
+ }
1901
+ assertArkadeFundable({ quote, ...params.now !== void 0 ? { now: params.now } : {} });
1902
+ const terms = offerTermsFromQuote(quote, {
1903
+ ...params.offerAsset !== void 0 ? { offerAsset: params.offerAsset } : {},
1904
+ ...params.wantAsset !== void 0 ? { wantAsset: params.wantAsset } : {}
1905
+ });
1906
+ const quoted = amountSide === "from" ? quote.from_amount : quote.to_amount;
1907
+ if (BigInt(quoted).toString() !== canonicalAssetAmount(params.amount)) {
1908
+ throw new Error(
1909
+ `quote ${amountSide}_amount ${quoted} does not match the requested ${canonicalAssetAmount(params.amount)}`
1910
+ );
1911
+ }
1912
+ if (params.maxFromAmount !== void 0) {
1913
+ const cap = BigInt(canonicalAssetAmount(params.maxFromAmount));
1914
+ if (BigInt(quote.from_amount) > cap) {
1915
+ throw gateError(
1916
+ "quote_amount_rejected",
1917
+ `quote from_amount ${quote.from_amount} exceeds maxFromAmount ${cap}`
1918
+ );
1919
+ }
1920
+ }
1921
+ if (params.minToAmount !== void 0) {
1922
+ const floorAmount = BigInt(canonicalAssetAmount(params.minToAmount));
1923
+ if (BigInt(quote.to_amount) < floorAmount) {
1924
+ throw gateError(
1925
+ "quote_amount_rejected",
1926
+ `quote to_amount ${quote.to_amount} is under minToAmount ${floorAmount}`
1927
+ );
1928
+ }
1929
+ }
1930
+ const offer = await createOffer(wallet, {
1931
+ wantAmount: terms.wantAmount,
1932
+ ...terms.wantAsset !== void 0 ? { wantAsset: terms.wantAsset } : {},
1933
+ ...terms.offerAsset !== void 0 ? { offerAsset: terms.offerAsset } : {},
1934
+ ...params.emulatorPubkey !== void 0 ? { emulatorPubkey: params.emulatorPubkey } : {}
1935
+ });
1936
+ verifyOfferAddress(quote, offer);
1937
+ const fundAmount = BigInt(quote.from_amount);
1938
+ return {
1939
+ rfqId,
1940
+ quote,
1941
+ pair,
1942
+ address: offer.address,
1943
+ fundAmount,
1944
+ carrierSats: params.offerAsset !== void 0 ? quoteCarrierSats(quote) : 0n,
1945
+ swapPkScript: offer.swapPkScript,
1946
+ offerHex: offer.offerHex,
1947
+ extension: offer.extension
1948
+ };
1949
+ }
1950
+ var l1NetworkFromArk = (network) => network === "bitcoin" ? "bitcoin" : network === "regtest" ? "regtest" : "testnet";
1951
+ var serverTerms = (info, emulatorPubkey) => {
1952
+ const network = networkFromArkadeInfo2(info);
1953
+ return {
1954
+ operatorPubkey: toXOnly(hex5.decode(info.signerPubkey), "ark signer key"),
1955
+ emulatorPubkey: toXOnly(
1956
+ hex5.decode(resolveEmulatorPubkey2(network, emulatorPubkey)),
1957
+ "emulator signer key"
1958
+ ),
1959
+ claimDelay: unilateralClaimDelay(Number(info.unilateralExitDelay)),
1960
+ hrp: network.hrp
1961
+ };
1962
+ };
1963
+ var onchainSendRequest = (input) => ({
1964
+ v: 1,
1965
+ type: "rfq_request",
1966
+ rfq_id: input.rfqId,
1967
+ pair: ONCHAIN_SEND_PAIR,
1968
+ amount_side: input.amountSide,
1969
+ amount: input.amount,
1970
+ profile: {
1971
+ payment_hash: input.paymentHash,
1972
+ payout_pubkey: hex5.encode(input.payoutPubkey),
1973
+ refund_address: input.refundAddress,
1974
+ client_refund_pubkey: hex5.encode(input.senderPubkey)
1975
+ }
1976
+ });
1977
+ var lightningReceiveRequest = (input) => ({
1978
+ v: 1,
1979
+ type: "rfq_request",
1980
+ rfq_id: input.rfqId,
1981
+ pair: LIGHTNING_RECEIVE_PAIR,
1982
+ amount_side: input.amountSide,
1983
+ amount: input.amount,
1984
+ profile: {
1985
+ payment_hash: input.paymentHash,
1986
+ payout_address: input.payoutAddress,
1987
+ payout_pubkey: hex5.encode(input.payoutPubkey),
1988
+ ...input.claimPacket === void 0 ? {} : { claim_packet: input.claimPacket }
1989
+ }
1990
+ });
1991
+ var onchainReceiveRequest = (input) => ({
1992
+ v: 1,
1993
+ type: "rfq_request",
1994
+ rfq_id: input.rfqId,
1995
+ pair: ONCHAIN_RECEIVE_PAIR,
1996
+ amount_side: input.amountSide,
1997
+ amount: input.amount,
1998
+ profile: {
1999
+ payment_hash: input.paymentHash,
2000
+ ...input.claimPacket === void 0 ? {} : { claim_packet: input.claimPacket },
2001
+ refund_pubkey: hex5.encode(input.refundPubkey),
2002
+ payout_address: input.payoutAddress,
2003
+ payout_pubkey: hex5.encode(input.payoutPubkey)
2004
+ }
2005
+ });
2006
+ function deriveOnchainSend(input) {
2007
+ const { quote } = input;
2008
+ const profile = quote.profile ?? {};
2009
+ const refundLocktime = quote.refund_locktime ?? profile.refund_locktime;
2010
+ const htlcPubkey = profile.htlc_pubkey;
2011
+ const htlcLocktime = profile.htlc_locktime;
2012
+ const htlcAddress = profile.htlc_address;
2013
+ const minConfirmations = profile.min_confirmations;
2014
+ const receiverPkScriptHex = profile.receiver_pk_script;
2015
+ if (refundLocktime === void 0 || htlcPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || receiverPkScriptHex === void 0) {
2016
+ throw new Error("onchain-send quote is missing a binding field");
2017
+ }
2018
+ const contractParams = {
2019
+ solverPubkey: toXOnly(hex5.decode(quote.solver_pubkey), "solver key"),
2020
+ refundLocktime,
2021
+ operatorPubkey: input.operatorPubkey,
2022
+ paymentHash: input.paymentHash,
2023
+ claimDelay: input.claimDelay,
2024
+ emulatorPubkey: input.emulatorPubkey,
2025
+ senderPubkey: input.senderPubkey,
2026
+ receiverPkScript: solverHex(receiverPkScriptHex, "profile.receiver_pk_script"),
2027
+ refundPkScript: ArkAddress3.decode(input.refundAddress).pkScript
2028
+ };
2029
+ const { script, address } = matchQuotedLockup(
2030
+ quote,
2031
+ input.hrp,
2032
+ input.operatorPubkey,
2033
+ (legacy) => lightningSendContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
2034
+ );
2035
+ const htlcParams = {
2036
+ paymentHash: input.paymentHash,
2037
+ claimKey: input.payoutPubkey,
2038
+ refundKey: toXOnly(hex5.decode(htlcPubkey), "solver L1 htlc key"),
2039
+ refundLocktime: htlcLocktime
2040
+ };
2041
+ const htlc = onchainHtlcScript(htlcParams, input.l1Network);
2042
+ if (htlc.address !== htlcAddress) throw new AddressMismatch(htlc.address, htlcAddress);
2043
+ return {
2044
+ address,
2045
+ swapPkScript: script.pkScript,
2046
+ script,
2047
+ htlc,
2048
+ htlcParams,
2049
+ l1Network: input.l1Network,
2050
+ refundLocktime,
2051
+ htlcLocktime,
2052
+ minConfirmations,
2053
+ expectedAmount: quoteExpectedSats(quote.to_amount, "to_amount")
2054
+ };
2055
+ }
2056
+ async function requestOnchainSend(wallet, transport, params) {
2057
+ const rfqId = params.rfqId ?? newRfqId();
2058
+ const secrets = await provisionClaimSecret(wallet, { preimage: params.preimage });
2059
+ if (secrets.mustPersistPreimage) {
2060
+ console.warn(
2061
+ "[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before funding"
2062
+ );
2063
+ }
2064
+ const paymentHash = hex5.encode(secrets.paymentHash);
2065
+ const senderPubkey = secrets.pubkey;
2066
+ const [info, refundAddress] = await Promise.all([
2067
+ wallet.getArkadeInfo({ requireLive: true }),
2068
+ wallet.getAddress()
2069
+ ]);
2070
+ const quote = await transport.requestQuote(
2071
+ onchainSendRequest({
2072
+ rfqId,
2073
+ paymentHash,
2074
+ payoutPubkey: params.payoutPubkey,
2075
+ refundAddress,
2076
+ senderPubkey,
2077
+ amount: params.amount,
2078
+ amountSide: params.amountSide
2079
+ })
2080
+ );
2081
+ assertQuotedAmount(quote, params.amountSide, params.amount);
2082
+ const derived = deriveOnchainSend({
2083
+ quote,
2084
+ paymentHash,
2085
+ payoutPubkey: params.payoutPubkey,
2086
+ ...serverTerms(info, params.emulatorPubkey),
2087
+ l1Network: l1NetworkFromArk(info.network),
2088
+ refundAddress,
2089
+ senderPubkey
2090
+ });
2091
+ assertFundable({
2092
+ quote,
2093
+ now: Math.floor(Date.now() / 1e3),
2094
+ onchain: {
2095
+ htlcLocktime: derived.htlcLocktime,
2096
+ minConfirmations: derived.minConfirmations,
2097
+ direction: "send"
2098
+ }
2099
+ });
2100
+ await registerLockupContract(
2101
+ await wallet.getContractManager(),
2102
+ derived.script,
2103
+ derived.address
2104
+ );
2105
+ return {
2106
+ rfqId,
2107
+ quote,
2108
+ address: derived.address,
2109
+ fundAmount: quoteSats(quote.from_amount, "from_amount"),
2110
+ expectedAmount: quoteSats(quote.to_amount, "to_amount"),
2111
+ swapPkScript: derived.swapPkScript,
2112
+ script: derived.script,
2113
+ refundAddress,
2114
+ htlc: derived.htlc,
2115
+ htlcParams: derived.htlcParams,
2116
+ l1Network: derived.l1Network,
2117
+ minConfirmations: derived.minConfirmations,
2118
+ refundLocktime: derived.refundLocktime,
2119
+ senderPubkey,
2120
+ secrets
2121
+ };
2122
+ }
2123
+ var assertQuotedAmount = (quote, amountSide, amount) => {
2124
+ const quoted = amountSide === "from" ? quoteSats(quote.from_amount, "from_amount") : quoteSats(quote.to_amount, "to_amount");
2125
+ if (quoted !== amount) {
2126
+ throw new Error(
2127
+ `quote ${amountSide === "from" ? "from_amount" : "to_amount"} ${quoted} does not match the requested ${amount} \u2014 not this trade's quote`
2128
+ );
2129
+ }
2130
+ if (quote.to_amount > quote.from_amount) {
2131
+ throw new Error("quote pays out more than it takes in \u2014 not a quote to fund");
2132
+ }
2133
+ };
2134
+ var MIN_CLAIM_WINDOW_SECONDS = 30 * 60;
2135
+ var verifyReceiveInvoice = (input) => {
2136
+ let decoded;
2137
+ try {
2138
+ decoded = input.decode(input.invoice);
2139
+ } catch (error) {
2140
+ throw gateError(
2141
+ "invoice_undecodable",
2142
+ `solver sent an undecodable invoice: ${error instanceof Error ? error.message : String(error)}`
2143
+ );
2144
+ }
2145
+ assertFinite(decoded.expiresAt, "invoice_undecodable", "the decoded invoice expiry");
2146
+ assertFinite(input.quote.valid_until, "quote_malformed", "quote valid_until");
2147
+ if (decoded.paymentHash !== input.paymentHash) {
2148
+ throw gateError(
2149
+ "invoice_hash_mismatch",
2150
+ `solver's invoice pays ${decoded.paymentHash}, not this swap's ${input.paymentHash}`
2151
+ );
2152
+ }
2153
+ if (decoded.amountSats <= 0) {
2154
+ throw gateError("invoice_amount_mismatch", "solver's invoice names no amount");
2155
+ }
2156
+ if (decoded.amountSats !== input.quote.from_amount) {
2157
+ throw gateError(
2158
+ "invoice_amount_mismatch",
2159
+ `solver's invoice asks for ${decoded.amountSats}, not the quoted from_amount ${input.quote.from_amount}`
2160
+ );
2161
+ }
2162
+ return { payDeadline: Math.min(decoded.expiresAt, input.quote.valid_until) };
2163
+ };
2164
+ var assertReceivable = (input) => {
2165
+ assertFinite(input.payDeadline, "quote_malformed", "payDeadline");
2166
+ assertFinite(input.now, "invalid_gate_input", "now");
2167
+ assertFinite(input.minClaimWindowSeconds, "invalid_gate_input", "minClaimWindowSeconds");
2168
+ assertFinite(input.maxPayAmount, "invalid_gate_input", "maxPayAmount");
2169
+ const minClaimWindow = input.minClaimWindowSeconds ?? MIN_CLAIM_WINDOW_SECONDS;
2170
+ if (input.now >= input.payDeadline) {
2171
+ throw gateError("quote_expired", "quote or invoice already expired \u2014 request a fresh one");
2172
+ }
2173
+ if (input.quote.refund_locktime === void 0) {
2174
+ throw gateError("missing_refund_locktime", "receive quote carries no refund_locktime");
2175
+ }
2176
+ assertFinite(input.quote.refund_locktime, "quote_malformed", "quote refund_locktime");
2177
+ if (input.quote.refund_locktime - input.payDeadline < minClaimWindow) {
2178
+ throw gateError(
2179
+ "claim_window_too_short",
2180
+ `a payment at the deadline would leave under ${minClaimWindow}s to claim before the solver's refund opens`
2181
+ );
2182
+ }
2183
+ if (input.maxPayAmount !== void 0 && quoteSats(input.quote.from_amount, "from_amount") > input.maxPayAmount) {
2184
+ throw gateError(
2185
+ "price_too_high",
2186
+ `quote asks ${input.quote.from_amount} sats, above the ${input.maxPayAmount} ceiling`
2187
+ );
2188
+ }
2189
+ };
2190
+ function lightningReceiveContract(params) {
2191
+ return suiteVhtlc(params, {
2192
+ sender: params.solverPubkey,
2193
+ receiver: params.payoutPubkey,
2194
+ senderPkScript: params.solverRefundPkScript,
2195
+ receiverPkScript: params.payoutPkScript
2196
+ });
2197
+ }
2198
+ var matchReceiveLockup = (input, refundLocktime, solverRefundPkScriptHex) => {
2199
+ const contractParams = {
2200
+ solverPubkey: toXOnly(hex5.decode(input.quote.solver_pubkey), "solver key"),
2201
+ refundLocktime,
2202
+ operatorPubkey: input.operatorPubkey,
2203
+ paymentHash: input.paymentHash,
2204
+ claimDelay: input.claimDelay,
2205
+ emulatorPubkey: input.emulatorPubkey,
2206
+ solverRefundPkScript: solverHex(solverRefundPkScriptHex, "profile.solver_refund_pk_script"),
2207
+ payoutPubkey: input.payoutPubkey,
2208
+ payoutPkScript: ArkAddress3.decode(input.payoutAddress).pkScript
2209
+ };
2210
+ const matched = matchQuotedLockup(
2211
+ input.quote,
2212
+ input.hrp,
2213
+ input.operatorPubkey,
2214
+ (legacy) => lightningReceiveContract({ ...contractParams, ...legacy !== void 0 && { legacy } })
2215
+ );
2216
+ return { contractParams, matched };
2217
+ };
2218
+ function deriveLightningReceive(input) {
2219
+ const { quote } = input;
2220
+ const profile = quote.profile ?? {};
2221
+ const refundLocktime = quote.refund_locktime;
2222
+ const invoice = profile.invoice;
2223
+ const solverRefundPkScriptHex = profile.solver_refund_pk_script;
2224
+ if (refundLocktime === void 0 || invoice === void 0 || solverRefundPkScriptHex === void 0) {
2225
+ throw new Error("lightning-receive quote is missing a binding field");
2226
+ }
2227
+ const { contractParams, matched } = matchReceiveLockup(
2228
+ input,
2229
+ refundLocktime,
2230
+ solverRefundPkScriptHex
2231
+ );
2232
+ return {
2233
+ address: matched.address,
2234
+ swapPkScript: matched.script.pkScript,
2235
+ script: matched.script,
2236
+ invoice,
2237
+ refundLocktime,
2238
+ contractParams: {
2239
+ ...contractParams,
2240
+ ...matched.legacy !== void 0 && { legacy: matched.legacy }
2241
+ }
2242
+ };
2243
+ }
2244
+ var provisionReceive = async (wallet, covclaimdPubkey, persistBefore) => {
2245
+ const secrets = await provisionClaimSecret(wallet);
2246
+ if (secrets.mustPersistPreimage) {
2247
+ console.warn(
2248
+ `[swap] this swap's preimage cannot be re-derived from the seed and MUST be persisted with the record before ${persistBefore}`
2249
+ );
2250
+ }
2251
+ const preimage = secrets.preimage;
2252
+ const paymentHash = hex5.encode(secrets.paymentHash);
2253
+ const payoutPubkey = secrets.pubkey;
2254
+ const [info, payoutAddress] = await Promise.all([
2255
+ wallet.getArkadeInfo({ requireLive: true }),
2256
+ wallet.getAddress()
2257
+ ]);
2258
+ const claimPacket = covclaimdPubkey ? await sealClaimPacket({ preimage, covclaimdPubkey }) : void 0;
2259
+ return { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket };
2260
+ };
2261
+ async function requestLightningReceive(wallet, transport, params) {
2262
+ const rfqId = params.rfqId ?? newRfqId();
2263
+ const { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket } = await provisionReceive(wallet, params.covclaimdPubkey, "paying");
2264
+ const quote = await transport.requestQuote(
2265
+ lightningReceiveRequest({
2266
+ rfqId,
2267
+ paymentHash,
2268
+ payoutAddress,
2269
+ payoutPubkey,
2270
+ claimPacket: claimPacket?.packet,
2271
+ amount: params.amount,
2272
+ amountSide: params.amountSide
2273
+ })
2274
+ );
2275
+ assertQuotedAmount(quote, params.amountSide, params.amount);
2276
+ const derived = deriveLightningReceive({
2277
+ quote,
2278
+ paymentHash,
2279
+ payoutPubkey,
2280
+ payoutAddress,
2281
+ ...serverTerms(info, params.emulatorPubkey)
2282
+ });
2283
+ const now = Math.floor(Date.now() / 1e3);
2284
+ const { payDeadline } = verifyReceiveInvoice({
2285
+ invoice: derived.invoice,
2286
+ decode: params.decodeInvoice,
2287
+ paymentHash,
2288
+ quote
2289
+ });
2290
+ assertReceivable({ quote, payDeadline, now, maxPayAmount: params.maxPayAmount });
2291
+ await registerLockupContract(
2292
+ await wallet.getContractManager(),
2293
+ derived.script,
2294
+ derived.address
2295
+ );
2296
+ return {
2297
+ rfqId,
2298
+ quote,
2299
+ invoice: derived.invoice,
2300
+ payAmount: quoteSats(quote.from_amount, "from_amount"),
2301
+ expectedAmount: quoteSats(quote.to_amount, "to_amount"),
2302
+ invoiceExpiresAt: payDeadline,
2303
+ address: derived.address,
2304
+ swapPkScript: derived.swapPkScript,
2305
+ script: derived.script,
2306
+ payoutAddress,
2307
+ payoutPubkey,
2308
+ secrets,
2309
+ contractParams: derived.contractParams
2310
+ };
2311
+ }
2312
+ function deriveOnchainReceive(input) {
2313
+ const { quote } = input;
2314
+ const profile = quote.profile ?? {};
2315
+ const refundLocktime = quote.refund_locktime;
2316
+ const claimPubkey = profile.claim_pubkey;
2317
+ const htlcLocktime = profile.htlc_locktime;
2318
+ const htlcAddress = profile.htlc_address;
2319
+ const minConfirmations = profile.min_confirmations;
2320
+ const solverRefundPkScriptHex = profile.solver_refund_pk_script;
2321
+ if (refundLocktime === void 0 || claimPubkey === void 0 || htlcLocktime === void 0 || minConfirmations === void 0 || solverRefundPkScriptHex === void 0) {
2322
+ throw new Error("onchain-receive quote is missing a binding field");
2323
+ }
2324
+ const { script, address } = matchReceiveLockup(
2325
+ input,
2326
+ refundLocktime,
2327
+ solverRefundPkScriptHex
2328
+ ).matched;
2329
+ const htlc = onchainHtlcScript(
2330
+ {
2331
+ paymentHash: input.paymentHash,
2332
+ claimKey: toXOnly(hex5.decode(claimPubkey), "solver L1 claim key"),
2333
+ refundKey: input.refundPubkey,
2334
+ refundLocktime: htlcLocktime
2335
+ },
2336
+ input.l1Network
2337
+ );
2338
+ if (htlc.address !== htlcAddress) throw new AddressMismatch(htlc.address, htlcAddress);
2339
+ return {
2340
+ address,
2341
+ swapPkScript: script.pkScript,
2342
+ script,
2343
+ htlc,
2344
+ refundLocktime,
2345
+ htlcLocktime,
2346
+ minConfirmations
2347
+ };
2348
+ }
2349
+ async function requestOnchainReceive(wallet, transport, params) {
2350
+ const rfqId = params.rfqId ?? newRfqId();
2351
+ const { secrets, paymentHash, payoutPubkey, info, payoutAddress, claimPacket } = await provisionReceive(wallet, params.covclaimdPubkey, "funding");
2352
+ const quote = await transport.requestQuote(
2353
+ onchainReceiveRequest({
2354
+ rfqId,
2355
+ paymentHash,
2356
+ payoutAddress,
2357
+ payoutPubkey,
2358
+ refundPubkey: params.refundPubkey,
2359
+ claimPacket: claimPacket?.packet,
2360
+ amount: params.amount,
2361
+ amountSide: params.amountSide
2362
+ })
2363
+ );
2364
+ assertQuotedAmount(quote, params.amountSide, params.amount);
2365
+ const derived = deriveOnchainReceive({
2366
+ quote,
2367
+ paymentHash,
2368
+ payoutPubkey,
2369
+ payoutAddress,
2370
+ refundPubkey: params.refundPubkey,
2371
+ ...serverTerms(info, params.emulatorPubkey),
2372
+ l1Network: l1NetworkFromArk(info.network)
2373
+ });
2374
+ assertFundable({
2375
+ quote,
2376
+ now: Math.floor(Date.now() / 1e3),
2377
+ onchain: {
2378
+ htlcLocktime: derived.htlcLocktime,
2379
+ minConfirmations: derived.minConfirmations,
2380
+ direction: "receive"
2381
+ }
2382
+ });
2383
+ await registerLockupContract(
2384
+ await wallet.getContractManager(),
2385
+ derived.script,
2386
+ derived.address
2387
+ );
2388
+ return {
2389
+ rfqId,
2390
+ quote,
2391
+ address: derived.address,
2392
+ fundAmount: quoteSats(quote.from_amount, "from_amount"),
2393
+ expectedAmount: quoteSats(quote.to_amount, "to_amount"),
2394
+ swapPkScript: derived.swapPkScript,
2395
+ script: derived.script,
2396
+ htlc: derived.htlc,
2397
+ payoutAddress,
2398
+ payoutPubkey,
2399
+ secrets
2400
+ };
2401
+ }
2402
+
2403
+ export {
2404
+ RETIRABLE,
2405
+ LOCKUP_RETIRABLE,
2406
+ retireOfferContract,
2407
+ retireSettledOfferContracts,
2408
+ BTC_ASSET_ID,
2409
+ getAssetSwaps,
2410
+ addAssetSwap,
2411
+ updateAssetSwap,
2412
+ updateAssetSwapBestEffort,
2413
+ swapSecretsToRecord,
2414
+ PreimageNotRecoverableError,
2415
+ preimageForSwapRecord,
2416
+ swapPrograms,
2417
+ offerContract,
2418
+ OFFER_PACKET_TYPE,
2419
+ encodeOffer,
2420
+ decodeOffer,
2421
+ OFFER_CONTRACT_KIND,
2422
+ restoreOfferCoverage,
2423
+ createOffer,
2424
+ deriveOffer,
2425
+ registerDerivedOffer,
2426
+ cancelOffer,
2427
+ NoSpendableDepositError,
2428
+ OfferCovenantMismatchError,
2429
+ prepareOfferCancel,
2430
+ ASSET_CARRIER_SATS,
2431
+ fillOffer,
2432
+ SWAP_LOCKUP_CONTRACT_TYPE,
2433
+ SWAP_LOCKUP_CONTRACT_LABEL,
2434
+ SWAP_LOCKUP_CONTRACT_KIND,
2435
+ LockupContractMissing,
2436
+ LockupRegistrationFailed,
2437
+ registerLockupContract,
2438
+ lockupContractParams,
2439
+ ONCHAIN_ORDER_MARGIN_SECONDS,
2440
+ ONCHAIN_CLAIM_MARGIN_SECONDS,
2441
+ MAX_MIN_CONFIRMATIONS,
2442
+ LOCKTIME_THRESHOLD,
2443
+ ONCHAIN_SECONDS_PER_BLOCK,
2444
+ ONCHAIN_DUST_SATS,
2445
+ ONCHAIN_CLAIM_VSIZE,
2446
+ newPreimage,
2447
+ paymentHashOf,
2448
+ assertPreimageMatches,
2449
+ gateError,
2450
+ sleep,
2451
+ pollUntil,
2452
+ L1_NETWORKS,
2453
+ l1ScriptForAddress,
2454
+ onchainHtlcScript,
2455
+ buildHtlcClaim,
2456
+ buildHtlcRefund,
2457
+ extractPreimage,
2458
+ awaitOnchainFill,
2459
+ claimOnchainFill,
2460
+ classifyOnchainHtlc,
2461
+ sealClaimPacket,
2462
+ SEALED_CIPHERTEXT_LENGTH,
2463
+ CLAIM_PACKET_TYPE,
2464
+ appendArkadeScript,
2465
+ claimPacketShape,
2466
+ ARKADE_BTC,
2467
+ LIGHTNING_BTC,
2468
+ ONCHAIN_BTC,
2469
+ arkadeAssetLeg,
2470
+ rfqPair,
2471
+ LIGHTNING_SEND_PAIR,
2472
+ LIGHTNING_RECEIVE_PAIR,
2473
+ ONCHAIN_SEND_PAIR,
2474
+ ONCHAIN_RECEIVE_PAIR,
2475
+ RFQ_TERMINAL_STATES,
2476
+ RFQ_REFUSAL_ERROR_CODES,
2477
+ isRfqRefusalErrorCode,
2478
+ SwapRefusal,
2479
+ AddressMismatch,
2480
+ newRfqId,
2481
+ lightningSendRequest,
2482
+ arkadeSwapRequest,
2483
+ canonicalAssetAmount,
2484
+ normalizeMakerPkScript,
2485
+ normalizeMakerPublicKey,
2486
+ assertPairLength,
2487
+ verifyLockupAddress,
2488
+ assertFundable,
2489
+ expectQuote,
2490
+ pairOf,
2491
+ httpTransport,
2492
+ relayTransport,
2493
+ unilateralClaimDelay,
2494
+ unilateralRefundDelay,
2495
+ unilateralRefundWithoutReceiverDelay,
2496
+ lightningSendContract,
2497
+ deriveLightningSend,
2498
+ requestLightningSend,
2499
+ offerTermsFromQuote,
2500
+ verifyOfferAddress,
2501
+ assertArkadeFundable,
2502
+ quoteCarrierSats,
2503
+ requestArkadeSwap,
2504
+ l1NetworkFromArk,
2505
+ onchainSendRequest,
2506
+ lightningReceiveRequest,
2507
+ onchainReceiveRequest,
2508
+ deriveOnchainSend,
2509
+ requestOnchainSend,
2510
+ verifyReceiveInvoice,
2511
+ assertReceivable,
2512
+ lightningReceiveContract,
2513
+ deriveLightningReceive,
2514
+ requestLightningReceive,
2515
+ deriveOnchainReceive,
2516
+ requestOnchainReceive
2517
+ };