@arkade-os/swap 0.1.8 → 0.1.10

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 (45) hide show
  1. package/dist/advanced.cjs +1125 -554
  2. package/dist/advanced.d.cts +19 -21
  3. package/dist/advanced.d.ts +19 -21
  4. package/dist/advanced.js +40 -34
  5. package/dist/{chunk-ISWLKKSS.js → chunk-2HQZLIVX.js} +106 -39
  6. package/dist/{chunk-5QPJWOCN.js → chunk-6RJVT65W.js} +2 -0
  7. package/dist/chunk-AUJDREZN.js +445 -0
  8. package/dist/{chunk-ZBJGLLYV.js → chunk-FWRDAL73.js} +157 -477
  9. package/dist/{chunk-PDNVKH5L.js → chunk-LCO6AJOS.js} +453 -70
  10. package/dist/index.cjs +1110 -542
  11. package/dist/index.d.cts +5 -6
  12. package/dist/index.d.ts +5 -6
  13. package/dist/index.js +24 -22
  14. package/dist/{lockupContract-DguuT7NK.d.cts → lockupContract-BTTRVwOt.d.cts} +1 -1
  15. package/dist/{lockupContract-BUOsghl1.d.ts → lockupContract-aFarhlxj.d.ts} +1 -1
  16. package/dist/node/index.d.cts +97 -67
  17. package/dist/node/index.d.ts +97 -67
  18. package/dist/nostr.cjs +925 -516
  19. package/dist/nostr.d.cts +1 -1
  20. package/dist/nostr.d.ts +1 -1
  21. package/dist/nostr.js +3 -2
  22. package/dist/{offerFillPlan-_AOLo6kh.d.ts → offerFillPlan-CJC5tnEd.d.ts} +10 -42
  23. package/dist/{offerFillPlan-Bp6-z6dS.d.cts → offerFillPlan-FmyaQoYT.d.cts} +10 -42
  24. package/dist/protocol.cjs +1082 -188
  25. package/dist/protocol.d.cts +42 -23
  26. package/dist/protocol.d.ts +42 -23
  27. package/dist/protocol.js +20 -7
  28. package/dist/repositories/realm/index.d.cts +3 -2
  29. package/dist/repositories/realm/index.d.ts +3 -2
  30. package/dist/repositories/sqlite/index.d.cts +3 -2
  31. package/dist/repositories/sqlite/index.d.ts +3 -2
  32. package/dist/{repository-CkKK0dGO.d.ts → repository-CwwhIAEd.d.cts} +406 -74
  33. package/dist/{repository--pfikw2R.d.cts → repository-DO6QKxBx.d.ts} +406 -74
  34. package/dist/{rfq-IzhOCG02.d.ts → rfq-CYxOyniL.d.ts} +52 -11
  35. package/dist/rfq-contract.cjs +3 -0
  36. package/dist/rfq-contract.d.cts +3 -1
  37. package/dist/rfq-contract.d.ts +3 -1
  38. package/dist/rfq-contract.js +3 -1
  39. package/dist/{rfq-BRpo5uWU.d.cts → rfq-nMGywkqI.d.cts} +52 -11
  40. package/dist/verify-ENO36VPK.js +33 -0
  41. package/dist/{watch-pvTVFp6-.d.cts → watch-DpDSP2tu.d.cts} +4 -3
  42. package/dist/{watch-DDNycuUa.d.ts → watch-_fZSgx_l.d.ts} +4 -3
  43. package/package.json +2 -2
  44. package/dist/offer-BhonWuKR.d.ts +0 -274
  45. package/dist/offer-D_qHpWo2.d.cts +0 -274
package/dist/advanced.cjs CHANGED
@@ -159,6 +159,141 @@ var init_asset_swap = __esm({
159
159
  }
160
160
  });
161
161
 
162
+ // src/contracts/asset-swap-v4.json
163
+ var asset_swap_v4_default;
164
+ var init_asset_swap_v4 = __esm({
165
+ "src/contracts/asset-swap-v4.json"() {
166
+ asset_swap_v4_default = {
167
+ formatVersion: 1,
168
+ contractName: "AssetSwap",
169
+ constructorInputs: [
170
+ {
171
+ name: "receiver",
172
+ type: "pubkey"
173
+ },
174
+ {
175
+ name: "amount",
176
+ type: "int"
177
+ },
178
+ {
179
+ name: "assetTxid",
180
+ type: "bytes32"
181
+ },
182
+ {
183
+ name: "assetGroupIndex",
184
+ type: "int"
185
+ },
186
+ {
187
+ name: "user",
188
+ type: "pubkey"
189
+ },
190
+ {
191
+ name: "taker",
192
+ type: "pubkey"
193
+ }
194
+ ],
195
+ functions: [
196
+ {
197
+ name: "fulfill",
198
+ arkade: {
199
+ inputs: [],
200
+ asm: [
201
+ "OP_PUSHCURRENTINPUTINDEX",
202
+ "OP_DUP",
203
+ "<assetTxid>",
204
+ "<assetGroupIndex>",
205
+ "OP_INSPECTOUTASSETLOOKUP",
206
+ "OP_VERIFY",
207
+ "<amount>",
208
+ "OP_GREATERTHANOREQUAL",
209
+ "OP_VERIFY",
210
+ "OP_INSPECTOUTPUTSCRIPTPUBKEY",
211
+ "1",
212
+ "OP_NUMEQUALVERIFY",
213
+ "<receiver>",
214
+ "OP_EQUAL"
215
+ ]
216
+ },
217
+ leaves: [
218
+ {
219
+ name: "fulfill",
220
+ witness: [
221
+ {
222
+ name: "takerSig",
223
+ type: "signature",
224
+ encoding: "schnorr-64"
225
+ },
226
+ {
227
+ name: "serverSig",
228
+ type: "signature",
229
+ encoding: "schnorr-64",
230
+ injected: true
231
+ },
232
+ {
233
+ name: "emulatorSig",
234
+ type: "signature",
235
+ encoding: "schnorr-64",
236
+ injected: true
237
+ }
238
+ ],
239
+ asm: [
240
+ "<taker>",
241
+ "OP_CHECKSIGVERIFY",
242
+ "<SERVER_KEY>",
243
+ "OP_CHECKSIGVERIFY",
244
+ "<EMULATOR_KEY:fulfill>",
245
+ "OP_CHECKSIG"
246
+ ]
247
+ }
248
+ ]
249
+ },
250
+ {
251
+ name: "cancel",
252
+ leaves: [
253
+ {
254
+ name: "cancel",
255
+ witness: [
256
+ {
257
+ name: "userSig",
258
+ type: "signature",
259
+ encoding: "schnorr-64"
260
+ },
261
+ {
262
+ name: "serverSig",
263
+ type: "signature",
264
+ encoding: "schnorr-64",
265
+ injected: true
266
+ }
267
+ ],
268
+ asm: [
269
+ "<user>",
270
+ "OP_CHECKSIGVERIFY",
271
+ "<SERVER_KEY>",
272
+ "OP_CHECKSIG"
273
+ ]
274
+ }
275
+ ]
276
+ }
277
+ ],
278
+ source: {
279
+ entry: "asset-swap-v4.ark",
280
+ files: {
281
+ "asset-swap-v4.ark": "pragma arkade ^0.1.0;\n\n// The output at this input's index pays `receiver` at least `amount` of the asset,\n// and only `taker` can make that spend.\ncontract AssetSwap(\n pubkey receiver,\n int amount,\n bytes32 assetTxid,\n int assetGroupIndex,\n pubkey user,\n pubkey taker\n) {\n function fulfill() {\n int i = this.activeInputIndex;\n require(tx.outputs[i].assets.lookup(assetTxid, assetGroupIndex) >= amount);\n let paid = tx.outputs[i].script;\n require(paid.version == 1);\n require(paid.program == receiver);\n }\n\n // Replaces the synthesized collaborative leaf: the quoting solver is a third\n // conjunct, so an observer who reads the deposit cannot complete it.\n function fulfill(signature takerSig, signature serverSig, signature emulatorSig) tapscript {\n require(checkMultisig([taker, server, emulator], [takerSig, serverSig, emulatorSig], 3));\n }\n\n function cancel(signature userSig, signature serverSig) tapscript {\n require(checkMultisig([user, server], [userSig, serverSig], 2));\n }\n}\n"
282
+ }
283
+ },
284
+ compiler: {
285
+ name: "arkadec",
286
+ version: "0.1.0-rc.1",
287
+ options: {
288
+ optimize: true
289
+ }
290
+ },
291
+ updatedAt: "2026-11-19T20:57:50.605738400+00:00",
292
+ fingerprint: "sha256:d830de32cd1d286a0a1fac698ff114a6c8ef5338a69f9f813717d1038ab2fb4a"
293
+ };
294
+ }
295
+ });
296
+
162
297
  // src/contracts/sats-swap.json
163
298
  var sats_swap_default;
164
299
  var init_sats_swap = __esm({
@@ -272,6 +407,130 @@ var init_sats_swap = __esm({
272
407
  }
273
408
  });
274
409
 
410
+ // src/contracts/sats-swap-v4.json
411
+ var sats_swap_v4_default;
412
+ var init_sats_swap_v4 = __esm({
413
+ "src/contracts/sats-swap-v4.json"() {
414
+ sats_swap_v4_default = {
415
+ formatVersion: 1,
416
+ contractName: "SatsSwap",
417
+ constructorInputs: [
418
+ {
419
+ name: "receiver",
420
+ type: "pubkey"
421
+ },
422
+ {
423
+ name: "amount",
424
+ type: "int"
425
+ },
426
+ {
427
+ name: "user",
428
+ type: "pubkey"
429
+ },
430
+ {
431
+ name: "taker",
432
+ type: "pubkey"
433
+ }
434
+ ],
435
+ functions: [
436
+ {
437
+ name: "fulfill",
438
+ arkade: {
439
+ inputs: [],
440
+ asm: [
441
+ "OP_PUSHCURRENTINPUTINDEX",
442
+ "OP_DUP",
443
+ "OP_INSPECTOUTPUTVALUE",
444
+ "<amount>",
445
+ "OP_GREATERTHANOREQUAL",
446
+ "OP_VERIFY",
447
+ "OP_INSPECTOUTPUTSCRIPTPUBKEY",
448
+ "1",
449
+ "OP_NUMEQUALVERIFY",
450
+ "<receiver>",
451
+ "OP_EQUAL"
452
+ ]
453
+ },
454
+ leaves: [
455
+ {
456
+ name: "fulfill",
457
+ witness: [
458
+ {
459
+ name: "takerSig",
460
+ type: "signature",
461
+ encoding: "schnorr-64"
462
+ },
463
+ {
464
+ name: "serverSig",
465
+ type: "signature",
466
+ encoding: "schnorr-64",
467
+ injected: true
468
+ },
469
+ {
470
+ name: "emulatorSig",
471
+ type: "signature",
472
+ encoding: "schnorr-64",
473
+ injected: true
474
+ }
475
+ ],
476
+ asm: [
477
+ "<taker>",
478
+ "OP_CHECKSIGVERIFY",
479
+ "<SERVER_KEY>",
480
+ "OP_CHECKSIGVERIFY",
481
+ "<EMULATOR_KEY:fulfill>",
482
+ "OP_CHECKSIG"
483
+ ]
484
+ }
485
+ ]
486
+ },
487
+ {
488
+ name: "cancel",
489
+ leaves: [
490
+ {
491
+ name: "cancel",
492
+ witness: [
493
+ {
494
+ name: "userSig",
495
+ type: "signature",
496
+ encoding: "schnorr-64"
497
+ },
498
+ {
499
+ name: "serverSig",
500
+ type: "signature",
501
+ encoding: "schnorr-64",
502
+ injected: true
503
+ }
504
+ ],
505
+ asm: [
506
+ "<user>",
507
+ "OP_CHECKSIGVERIFY",
508
+ "<SERVER_KEY>",
509
+ "OP_CHECKSIG"
510
+ ]
511
+ }
512
+ ]
513
+ }
514
+ ],
515
+ source: {
516
+ entry: "sats-swap-v4.ark",
517
+ files: {
518
+ "sats-swap-v4.ark": "pragma arkade ^0.1.0;\n\n// The output at this input's index pays `receiver` at least `amount` sats,\n// and only `taker` can make that spend.\ncontract SatsSwap(\n pubkey receiver,\n int amount,\n pubkey user,\n pubkey taker\n) {\n function fulfill() {\n int i = this.activeInputIndex;\n require(tx.outputs[i].value >= amount);\n let paid = tx.outputs[i].script;\n require(paid.version == 1);\n require(paid.program == receiver);\n }\n\n function fulfill(signature takerSig, signature serverSig, signature emulatorSig) tapscript {\n require(checkMultisig([taker, server, emulator], [takerSig, serverSig, emulatorSig], 3));\n }\n\n function cancel(signature userSig, signature serverSig) tapscript {\n require(checkMultisig([user, server], [userSig, serverSig], 2));\n }\n}\n"
519
+ }
520
+ },
521
+ compiler: {
522
+ name: "arkadec",
523
+ version: "0.1.0-rc.1",
524
+ options: {
525
+ optimize: true
526
+ }
527
+ },
528
+ updatedAt: "2026-11-19T20:57:50.848496600+00:00",
529
+ fingerprint: "sha256:6ca61bf7ed8d8f65af3141da4e95fcc896863650127dd20949a84e72258053f4"
530
+ };
531
+ }
532
+ });
533
+
275
534
  // src/legacy/swap-want-asset.program.v1.json
276
535
  var swap_want_asset_program_v1_default;
277
536
  var init_swap_want_asset_program_v1 = __esm({
@@ -358,7 +617,7 @@ var init_swap_want_btc_program_v1 = __esm({
358
617
  });
359
618
 
360
619
  // src/rfq-contract.ts
361
- var RFQ_CONTRACT_VERSIONS_KEY, RFQ_CONTRACT_VERSION_KEY, RFQ_CONTRACT_VERSION_UNSUPPORTED, ASSET_SWAP_V2, ASSET_SWAP_V3, ASSET_SWAP_BASELINE;
620
+ var RFQ_CONTRACT_VERSIONS_KEY, RFQ_CONTRACT_VERSION_KEY, RFQ_CONTRACT_VERSION_UNSUPPORTED, ASSET_SWAP_V2, ASSET_SWAP_V3, ASSET_SWAP_V4, ASSET_SWAP_BASELINE;
362
621
  var init_rfq_contract = __esm({
363
622
  "src/rfq-contract.ts"() {
364
623
  "use strict";
@@ -367,18 +626,21 @@ var init_rfq_contract = __esm({
367
626
  RFQ_CONTRACT_VERSION_UNSUPPORTED = "contract_version_unsupported";
368
627
  ASSET_SWAP_V2 = "asset-swap-v2";
369
628
  ASSET_SWAP_V3 = "asset-swap-v3";
629
+ ASSET_SWAP_V4 = "asset-swap-v4";
370
630
  ASSET_SWAP_BASELINE = ASSET_SWAP_V2;
371
631
  }
372
632
  });
373
633
 
374
634
  // src/program.ts
375
- var import_sdk, swapPrograms, legacySwapPrograms, sharedArgs, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
635
+ var import_sdk, swapPrograms, legacySwapPrograms, directedSwapPrograms, sharedArgs, refuseTaker, v3Args, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
376
636
  var init_program = __esm({
377
637
  "src/program.ts"() {
378
638
  "use strict";
379
639
  import_sdk = require("@arkade-os/sdk");
380
640
  init_asset_swap();
641
+ init_asset_swap_v4();
381
642
  init_sats_swap();
643
+ init_sats_swap_v4();
382
644
  init_swap_want_asset_program_v1();
383
645
  init_swap_want_btc_program_v1();
384
646
  init_rfq_contract();
@@ -391,38 +653,59 @@ var init_program = __esm({
391
653
  wantAsset: import_sdk.arkade.parseArtifact(swap_want_asset_program_v1_default),
392
654
  wantBtc: import_sdk.arkade.parseArtifact(swap_want_btc_program_v1_default)
393
655
  };
656
+ directedSwapPrograms = {
657
+ wantAsset: import_sdk.arkade.programFromArtifact(asset_swap_v4_default),
658
+ wantBtc: import_sdk.arkade.programFromArtifact(sats_swap_v4_default)
659
+ };
394
660
  sharedArgs = ({ user, server, exitDelay }) => ({
395
661
  user,
396
662
  server,
397
663
  ...exitDelay && { exitDelay }
398
664
  });
665
+ refuseTaker = (version, { taker }) => {
666
+ if (taker !== void 0) throw new Error(`${version} binds no taker key`);
667
+ };
668
+ v3Args = (inputs) => ({
669
+ receiver: inputs.receiver,
670
+ amount: inputs.amount,
671
+ ...inputs.asset && {
672
+ assetTxid: inputs.asset.txid,
673
+ assetGroupIndex: inputs.asset.groupIndex
674
+ },
675
+ ...sharedArgs(inputs)
676
+ });
399
677
  ASSET_SWAP_CONTRACTS = {
400
678
  [ASSET_SWAP_V2]: {
401
679
  programs: legacySwapPrograms,
402
- args: (inputs) => ({
403
- makerWP: inputs.receiver,
404
- wantAmount: inputs.amount,
405
- ...inputs.asset && {
406
- wantAssetTxid: inputs.asset.txid,
407
- wantAssetGroupIndex: inputs.asset.groupIndex
408
- },
409
- ...sharedArgs(inputs)
410
- })
680
+ args: (inputs) => {
681
+ refuseTaker(ASSET_SWAP_V2, inputs);
682
+ return {
683
+ makerWP: inputs.receiver,
684
+ wantAmount: inputs.amount,
685
+ ...inputs.asset && {
686
+ wantAssetTxid: inputs.asset.txid,
687
+ wantAssetGroupIndex: inputs.asset.groupIndex
688
+ },
689
+ ...sharedArgs(inputs)
690
+ };
691
+ }
411
692
  },
412
693
  [ASSET_SWAP_V3]: {
413
694
  programs: swapPrograms,
414
- args: (inputs) => ({
415
- receiver: inputs.receiver,
416
- amount: inputs.amount,
417
- ...inputs.asset && {
418
- assetTxid: inputs.asset.txid,
419
- assetGroupIndex: inputs.asset.groupIndex
420
- },
421
- ...sharedArgs(inputs)
422
- })
695
+ args: (inputs) => {
696
+ refuseTaker(ASSET_SWAP_V3, inputs);
697
+ return v3Args(inputs);
698
+ }
699
+ },
700
+ [ASSET_SWAP_V4]: {
701
+ programs: directedSwapPrograms,
702
+ args: (inputs) => {
703
+ if (inputs.taker === void 0) throw new Error(`${ASSET_SWAP_V4} needs a taker key`);
704
+ return { ...v3Args(inputs), taker: inputs.taker };
705
+ }
423
706
  }
424
707
  };
425
- ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_V3, ASSET_SWAP_V2];
708
+ ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_V4];
426
709
  assetSwapContractVersion = (id) => {
427
710
  if (id === void 0) return ASSET_SWAP_BASELINE;
428
711
  if (Object.hasOwn(ASSET_SWAP_CONTRACTS, id)) return id;
@@ -590,9 +873,9 @@ var init_store = __esm({
590
873
  byNewest = (a, b) => b.createdAt - a.createdAt;
591
874
  getAssetSwapsOrThrow = async (repository) => {
592
875
  return (await collectAssetSwaps(repository)).filter(
593
- (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
594
- // the payment hash instead — either marks a valid record
595
- (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
876
+ (s) => s && typeof s.id === "string" && // offer swaps carry the TLV or the binding; onchain-corridor swaps carry
877
+ // the payment hash instead — any of them marks a valid record
878
+ (typeof s.offerHex === "string" || s.binding !== void 0 || typeof s.paymentHash === "string")
596
879
  ).sort(byNewest);
597
880
  };
598
881
  getAssetSwaps = async (repository) => {
@@ -795,28 +1078,28 @@ function withExitClosure(program, exit) {
795
1078
  }
796
1079
  };
797
1080
  }
798
- function swapProgramBinding(offer, operatorPubkey, contractVersion = ASSET_SWAP_BASELINE) {
1081
+ function swapProgramBinding(offer, operatorPubkey, contractVersion) {
799
1082
  if (offer.makerPkScript.length !== FIELDS.makerPkScript.width) {
800
1083
  throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
801
1084
  }
1085
+ const directed = offer.taker !== void 0;
1086
+ const version = contractVersion ?? (directed ? ASSET_SWAP_V4 : ASSET_SWAP_BASELINE);
802
1087
  const expected = offer.swapPkScript;
803
- if (!expected?.length) return bindSwapProgram(offer, operatorPubkey, contractVersion);
1088
+ if (!expected?.length) return bindSwapProgram(offer, operatorPubkey, version);
804
1089
  const funded = import_base2.hex.encode(expected);
805
- const order = [
806
- ASSET_SWAP_BASELINE,
807
- ...ASSET_SWAP_CONTRACT_VERSIONS.filter((v) => v !== ASSET_SWAP_BASELINE)
808
- ];
809
- for (const version of order) {
810
- const binding = bindSwapProgram(offer, operatorPubkey, version);
1090
+ const order = directed ? [ASSET_SWAP_V4] : [ASSET_SWAP_BASELINE, ASSET_SWAP_V3];
1091
+ for (const candidate of order) {
1092
+ const binding = bindSwapProgram(offer, operatorPubkey, candidate);
811
1093
  if (pkOf(binding) === funded) return binding;
812
1094
  }
813
- return bindSwapProgram(offer, operatorPubkey, contractVersion);
1095
+ return bindSwapProgram(offer, operatorPubkey, directed ? ASSET_SWAP_V4 : version);
814
1096
  }
815
1097
  function bindSwapProgram(offer, operatorPubkey, contractVersion) {
816
1098
  const { programs, args } = ASSET_SWAP_CONTRACTS[contractVersion];
817
1099
  const user = offer.makerPublicKey;
818
1100
  const assetId = offer.wantAsset;
819
1101
  return {
1102
+ version: contractVersion,
820
1103
  program: withExitClosure(assetId ? programs.wantAsset : programs.wantBtc, offer.exitDelay),
821
1104
  args: args({
822
1105
  receiver: offer.makerPkScript.subarray(2),
@@ -827,7 +1110,8 @@ function bindSwapProgram(offer, operatorPubkey, contractVersion) {
827
1110
  },
828
1111
  user,
829
1112
  server: operatorPubkey,
830
- ...offer.exitDelay && { exitDelay: offer.exitDelay.value }
1113
+ ...offer.exitDelay && { exitDelay: offer.exitDelay.value },
1114
+ ...offer.taker && { taker: offer.taker }
831
1115
  }),
832
1116
  keys: {
833
1117
  serverKey: operatorPubkey,
@@ -850,6 +1134,33 @@ function pkOf(binding) {
850
1134
  function offerContract(offer, operatorPubkey, contractVersion) {
851
1135
  return compileSwapBinding(swapProgramBinding(offer, operatorPubkey, contractVersion));
852
1136
  }
1137
+ function bindingProgram(binding) {
1138
+ if (Boolean(binding.wantAsset) === Boolean(binding.offerAsset)) {
1139
+ throw new Error("an offer binding names exactly one of wantAsset or offerAsset");
1140
+ }
1141
+ return swapProgramBinding(termsOf(binding), binding.serverPublicKey, binding.version);
1142
+ }
1143
+ function bindingFromOffer(offer, operatorPubkey) {
1144
+ const program = swapProgramBinding(offer, operatorPubkey);
1145
+ if (pkOf(program) !== import_base2.hex.encode(offer.swapPkScript)) {
1146
+ throw new OfferCovenantMismatchError(import_base2.hex.encode(offer.swapPkScript));
1147
+ }
1148
+ return {
1149
+ version: program.version,
1150
+ receiverPkScript: offer.makerPkScript,
1151
+ amount: offer.wantAmount,
1152
+ ...offer.wantAsset && { wantAsset: offer.wantAsset },
1153
+ ...offer.offerAsset && { offerAsset: offer.offerAsset },
1154
+ userPublicKey: offer.makerPublicKey,
1155
+ serverPublicKey: operatorPubkey,
1156
+ emulatorPublicKey: offer.emulatorPubkey,
1157
+ ...offer.exitDelay && { exitDelay: offer.exitDelay },
1158
+ ...offer.taker && { taker: offer.taker }
1159
+ };
1160
+ }
1161
+ function offerFromBinding(binding) {
1162
+ return offerOf(binding, compileSwapBinding(bindingProgram(binding)).pkScript);
1163
+ }
853
1164
  function u64(name, value) {
854
1165
  if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
855
1166
  throw new Error(`${name} does not fit the offer wire format (u64)`);
@@ -876,6 +1187,9 @@ function encodeOffer(offer) {
876
1187
  throw new Error(`${name} must be ${FIELDS[name].width} bytes`);
877
1188
  }
878
1189
  }
1190
+ if (offer.taker !== void 0 && offer.taker.length !== FIELDS.taker.width) {
1191
+ throw new Error(`taker must be ${FIELDS.taker.width} bytes`);
1192
+ }
879
1193
  const ratioNum = setRatio("ratioNum", offer.ratioNum);
880
1194
  const ratioDen = setRatio("ratioDen", offer.ratioDen);
881
1195
  if (ratioNum === void 0 !== (ratioDen === void 0)) {
@@ -891,9 +1205,10 @@ function encodeOffer(offer) {
891
1205
  if (offer.offerAsset) recs.push(tlv(FIELDS.offerAsset.tag, offer.offerAsset.serialize()));
892
1206
  recs.push(
893
1207
  tlv(FIELDS.makerPkScript.tag, offer.makerPkScript),
894
- tlv(FIELDS.makerPublicKey.tag, offer.makerPublicKey),
895
- tlv(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey)
1208
+ tlv(FIELDS.makerPublicKey.tag, offer.makerPublicKey)
896
1209
  );
1210
+ if (offer.taker) recs.push(tlv(FIELDS.taker.tag, offer.taker));
1211
+ recs.push(tlv(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey));
897
1212
  if (offer.exitDelay) recs.push(tlv(FIELDS.exitTimelock.tag, encodeExitDelay(offer.exitDelay)));
898
1213
  return (0, import_utils.concatBytes)(...recs);
899
1214
  }
@@ -971,7 +1286,8 @@ function decodeOffer(data) {
971
1286
  emulatorPubkey: need("emulatorPubkey"),
972
1287
  ...ratioNum !== void 0 && { ratioNum },
973
1288
  ...ratioDen !== void 0 && { ratioDen },
974
- ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) }
1289
+ ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) },
1290
+ ...fields.taker && { taker: fields.taker }
975
1291
  };
976
1292
  }
977
1293
  function decodeExitDelay(value) {
@@ -991,10 +1307,7 @@ async function registerOfferContract(wallet, info, binding, operatorPubkey, expe
991
1307
  });
992
1308
  }
993
1309
  function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
994
- const { program, args, keys } = swapProgramBinding(
995
- { ...binding, swapPkScript: expectedPkScript },
996
- operatorPubkey
997
- );
1310
+ const { program, args, keys } = "version" in binding ? bindingProgram(binding) : swapProgramBinding({ ...binding, swapPkScript: expectedPkScript }, operatorPubkey);
998
1311
  const contract = new import_sdk4.arkade.ArkadeContract(client, program, args, keys);
999
1312
  if (import_base2.hex.encode(contract.pkScript) !== import_base2.hex.encode(expectedPkScript)) {
1000
1313
  throw new Error("derived covenant does not match the offer's swapPkScript");
@@ -1026,7 +1339,7 @@ async function restoreOfferCoverage(wallet, swaps) {
1026
1339
  if (seen.has(swap.swapPkScript)) continue;
1027
1340
  seen.add(swap.swapPkScript);
1028
1341
  try {
1029
- const { swapPkScript: _, ...binding } = decodeOffer(import_base2.hex.decode(swap.offerHex));
1342
+ const binding = storedOffer(swap);
1030
1343
  const stored = fundedKey.get(swap.swapPkScript);
1031
1344
  covenants.push({
1032
1345
  script: swap.swapPkScript,
@@ -1135,7 +1448,8 @@ async function deriveOffer(wallet, params) {
1135
1448
  makerPublicKey: maker.publicKey,
1136
1449
  emulatorPubkey: emuKey,
1137
1450
  // checked before registration below. @see assertExitDelay
1138
- exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
1451
+ exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay),
1452
+ ...params.taker && { taker: params.taker }
1139
1453
  });
1140
1454
  const script = offerContract(binding, operatorPubKey, params.contractVersion);
1141
1455
  const offer = { ...binding, swapPkScript: script.pkScript };
@@ -1148,6 +1462,7 @@ async function deriveOffer(wallet, params) {
1148
1462
  address: script.address(network.hrp, operatorPubKey).encode(),
1149
1463
  swapPkScript: script.pkScript,
1150
1464
  binding,
1465
+ offerBinding: Object.freeze(bindingFromOffer(offer, operatorPubKey)),
1151
1466
  info,
1152
1467
  operatorPubkey: operatorPubKey
1153
1468
  });
@@ -1164,7 +1479,7 @@ async function registerDerivedOffer(wallet, derived, options = {}) {
1164
1479
  }
1165
1480
  async function prepareOfferCancel(wallet, offerHex, opts) {
1166
1481
  const { fundingTxid, fundingOutpoint, swapAddress } = opts;
1167
- const offer = decodeOffer(import_base2.hex.decode(offerHex));
1482
+ const decoded = typeof offerHex === "string" ? decodeOffer(import_base2.hex.decode(offerHex)) : isOfferBinding(offerHex) ? void 0 : offerHex;
1168
1483
  const [contractManager, info, reader, broadcaster] = await Promise.all([
1169
1484
  wallet.getContractManager(),
1170
1485
  wallet.getArkadeInfo({ requireLive: true }),
@@ -1181,18 +1496,20 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
1181
1496
  // no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
1182
1497
  oneShotSubmit: wallet.oneShotSubmit
1183
1498
  });
1184
- const operatorPubkey = swapAddress ? import_sdk4.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1499
+ const pinned = swapAddress ? import_sdk4.ArkAddress.decode(swapAddress) : void 0;
1500
+ const funded = decoded ? decoded.swapPkScript : pinned?.pkScript;
1185
1501
  let binding;
1186
1502
  let rebuilt;
1187
1503
  try {
1188
- binding = swapProgramBinding(offer, operatorPubkey);
1504
+ binding = decoded ? swapProgramBinding(decoded, pinned?.serverPubKey ?? client.serverKey) : bindingProgram(offerHex);
1189
1505
  rebuilt = compileSwapBinding(binding);
1190
1506
  } catch (cause) {
1191
- throw new OfferCovenantMismatchError(import_base2.hex.encode(offer.swapPkScript), { cause });
1507
+ throw new OfferCovenantMismatchError(import_base2.hex.encode(funded ?? new Uint8Array()), { cause });
1192
1508
  }
1193
- if (import_base2.hex.encode(rebuilt.pkScript) !== import_base2.hex.encode(offer.swapPkScript)) {
1194
- throw new OfferCovenantMismatchError(import_base2.hex.encode(offer.swapPkScript));
1509
+ if (funded && import_base2.hex.encode(rebuilt.pkScript) !== import_base2.hex.encode(funded)) {
1510
+ throw new OfferCovenantMismatchError(import_base2.hex.encode(funded));
1195
1511
  }
1512
+ const offer = decoded ?? offerOf(offerHex, rebuilt.pkScript);
1196
1513
  const contract = new import_sdk4.arkade.ArkadeContract(client, binding.program, binding.args, binding.keys);
1197
1514
  const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
1198
1515
  const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
@@ -1224,10 +1541,11 @@ async function connectFillContract(wallet, arkServerUrl, offer, opts = {}) {
1224
1541
  } : {},
1225
1542
  ...emulatorPubkey ? { emulatorPubkey } : {}
1226
1543
  });
1227
- const serverKey = swapAddress ? import_sdk4.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1228
- const binding = swapProgramBinding(offer, serverKey);
1544
+ const pinned = swapAddress ? import_sdk4.ArkAddress.decode(swapAddress) : void 0;
1545
+ const binding = isOfferBinding(offer) ? bindingProgram(offer) : swapProgramBinding(offer, pinned?.serverPubKey ?? client.serverKey);
1546
+ const funded = isOfferBinding(offer) ? pinned?.pkScript : offer.swapPkScript;
1229
1547
  const rebuilt = compileSwapBinding(binding);
1230
- if (import_base2.hex.encode(rebuilt.pkScript) !== import_base2.hex.encode(offer.swapPkScript)) {
1548
+ if (funded && import_base2.hex.encode(rebuilt.pkScript) !== import_base2.hex.encode(funded)) {
1231
1549
  throw new Error(
1232
1550
  "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"
1233
1551
  );
@@ -1543,7 +1861,7 @@ function assertFillCoin(coin, what) {
1543
1861
  toAmount(coin.value, `${what}.value`, "sats", BigInt(1));
1544
1862
  assertAssetEntries(coin.assets, what);
1545
1863
  }
1546
- var import_base2, import_utils, import_sdk4, compiledBindings, OFFER_PACKET_TYPE, FIELDS, EXIT_TYPES, NAMES, readU64, setRatio, OFFER_CONTRACT_LABEL, OFFER_CONTRACT_KIND, derivingClient, NoSpendableDepositError, OfferCovenantMismatchError, ASSET_CARRIER_SATS, amountOfAsset, U64_MAX, MAX_SAFE_SATS;
1864
+ var import_base2, import_utils, import_sdk4, compiledBindings, isOfferBinding, termsOf, offerOf, recordOfferBinding, decimal, offerBindingOf, storedOffer, OFFER_PACKET_TYPE, FIELDS, EXIT_TYPES, NAMES, readU64, setRatio, OFFER_CONTRACT_LABEL, OFFER_CONTRACT_KIND, derivingClient, NoSpendableDepositError, OfferCovenantMismatchError, ASSET_CARRIER_SATS, amountOfAsset, U64_MAX, MAX_SAFE_SATS;
1547
1865
  var init_offer = __esm({
1548
1866
  "src/offer.ts"() {
1549
1867
  "use strict";
@@ -1555,11 +1873,67 @@ var init_offer = __esm({
1555
1873
  init_rfqProfileParts();
1556
1874
  init_store();
1557
1875
  compiledBindings = /* @__PURE__ */ new WeakMap();
1876
+ isOfferBinding = (offer) => "version" in offer;
1877
+ termsOf = (binding) => ({
1878
+ wantAmount: binding.amount,
1879
+ ...binding.wantAsset && { wantAsset: binding.wantAsset },
1880
+ ...binding.offerAsset && { offerAsset: binding.offerAsset },
1881
+ makerPkScript: binding.receiverPkScript,
1882
+ makerPublicKey: binding.userPublicKey,
1883
+ emulatorPubkey: binding.emulatorPublicKey,
1884
+ ...binding.exitDelay && { exitDelay: binding.exitDelay },
1885
+ ...binding.taker && { taker: binding.taker }
1886
+ });
1887
+ offerOf = (offer, swapPkScript) => isOfferBinding(offer) ? { ...termsOf(offer), swapPkScript } : offer;
1888
+ recordOfferBinding = (binding) => ({
1889
+ version: binding.version,
1890
+ receiverPkScript: import_base2.hex.encode(binding.receiverPkScript),
1891
+ amount: binding.amount.toString(),
1892
+ ...binding.wantAsset && { wantAsset: binding.wantAsset.toString() },
1893
+ ...binding.offerAsset && { offerAsset: binding.offerAsset.toString() },
1894
+ userPublicKey: import_base2.hex.encode(binding.userPublicKey),
1895
+ serverPublicKey: import_base2.hex.encode(binding.serverPublicKey),
1896
+ emulatorPublicKey: import_base2.hex.encode(binding.emulatorPublicKey),
1897
+ ...binding.exitDelay && {
1898
+ exitDelay: { type: binding.exitDelay.type, value: binding.exitDelay.value.toString() }
1899
+ },
1900
+ ...binding.taker && { taker: import_base2.hex.encode(binding.taker) }
1901
+ });
1902
+ decimal = (value, name) => {
1903
+ if (!/^\d+$/.test(value)) throw new Error(`recorded binding ${name} is not a decimal amount`);
1904
+ return BigInt(value);
1905
+ };
1906
+ offerBindingOf = (recorded) => {
1907
+ if (typeof recorded.version !== "string" || !Object.hasOwn(ASSET_SWAP_CONTRACTS, recorded.version)) {
1908
+ throw new Error(`recorded binding names no known contract version (${recorded.version})`);
1909
+ }
1910
+ const { exitDelay, wantAsset, offerAsset, taker } = recorded;
1911
+ return {
1912
+ version: recorded.version,
1913
+ receiverPkScript: import_base2.hex.decode(recorded.receiverPkScript),
1914
+ amount: decimal(recorded.amount, "amount"),
1915
+ ...wantAsset !== void 0 && { wantAsset: import_sdk4.asset.AssetId.fromString(wantAsset) },
1916
+ ...offerAsset !== void 0 && { offerAsset: import_sdk4.asset.AssetId.fromString(offerAsset) },
1917
+ userPublicKey: import_base2.hex.decode(recorded.userPublicKey),
1918
+ serverPublicKey: import_base2.hex.decode(recorded.serverPublicKey),
1919
+ emulatorPublicKey: import_base2.hex.decode(recorded.emulatorPublicKey),
1920
+ ...exitDelay && {
1921
+ exitDelay: { type: exitDelay.type, value: decimal(exitDelay.value, "exitDelay") }
1922
+ },
1923
+ ...taker !== void 0 && { taker: import_base2.hex.decode(taker) }
1924
+ };
1925
+ };
1926
+ storedOffer = (swap) => {
1927
+ if (swap.binding !== void 0) return offerBindingOf(swap.binding);
1928
+ if (typeof swap.offerHex === "string") return decodeOffer(import_base2.hex.decode(swap.offerHex));
1929
+ throw new Error("this offer swap carries neither a binding nor an offerHex to rebuild from");
1930
+ };
1558
1931
  OFFER_PACKET_TYPE = 3;
1559
1932
  FIELDS = {
1560
1933
  swapPkScript: { tag: 1, width: 34 },
1561
1934
  wantAmount: { tag: 2, width: 8 },
1562
1935
  wantAsset: { tag: 3, width: void 0 },
1936
+ taker: { tag: 4, width: 32 },
1563
1937
  makerPkScript: { tag: 5, width: 34 },
1564
1938
  makerPublicKey: { tag: 7, width: 32 },
1565
1939
  emulatorPubkey: { tag: 8, width: 32 },
@@ -1685,9 +2059,9 @@ function onchainHtlcScript(params, network) {
1685
2059
  if (params.claimKey.length !== 32 || params.refundKey.length !== 32) {
1686
2060
  throw new Error("claimKey and refundKey must be 32-byte x-only keys");
1687
2061
  }
1688
- if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0) {
2062
+ if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0 || params.refundLocktime > 4294967295) {
1689
2063
  throw new Error(
1690
- `refundLocktime must be a positive unix timestamp, got ${params.refundLocktime}`
2064
+ `refundLocktime must be a positive uint32 unix timestamp, got ${params.refundLocktime}`
1691
2065
  );
1692
2066
  }
1693
2067
  if (params.refundLocktime < LOCKTIME_THRESHOLD) {
@@ -1776,15 +2150,20 @@ async function claimOnchainFill(chain, input) {
1776
2150
  }
1777
2151
  async function classifyOnchainHtlc(chain, input) {
1778
2152
  const utxos = await chain.getScriptUtxos(input.htlc.pkScript);
1779
- const best = utxos.sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
1780
- if (!best) {
1781
- if (!input.funding) return { phase: "unfunded" };
1782
- const spend = await chain.getSpendingTx(
1783
- input.funding.txid,
1784
- input.funding.vout,
1785
- input.htlc.pkScript
1786
- );
1787
- if (!spend) return { phase: "unfunded" };
2153
+ const deep = (u) => u.confirmations >= input.minConfirmations;
2154
+ const best = utxos.sort(
2155
+ (a, b) => deep(a) !== deep(b) ? deep(a) ? -1 : 1 : b.amount > a.amount ? 1 : -1
2156
+ )[0];
2157
+ const { funding } = input;
2158
+ let spend = null;
2159
+ if (funding && !utxos.some((u) => u.txid === funding.txid && u.vout === funding.vout)) {
2160
+ try {
2161
+ spend = await chain.getSpendingTx(funding.txid, funding.vout, input.htlc.pkScript);
2162
+ } catch (error) {
2163
+ if (!best) throw error;
2164
+ }
2165
+ }
2166
+ if (spend) {
1788
2167
  const preimage = extractPreimage(spend.txHex, input.htlc.paymentHash);
1789
2168
  const txid = btc.Transaction.fromRaw(import_base4.hex.decode(spend.txHex), {
1790
2169
  allowUnknownInputs: true,
@@ -1792,6 +2171,7 @@ async function classifyOnchainHtlc(chain, input) {
1792
2171
  }).id;
1793
2172
  return preimage ? { phase: "claimed", txid, preimage } : { phase: "swept", txid };
1794
2173
  }
2174
+ if (!best) return { phase: "unfunded" };
1795
2175
  if (best.confirmations < input.minConfirmations)
1796
2176
  return { phase: "awaiting_confirmations", utxo: best };
1797
2177
  const mtp = await chain.getMtp();
@@ -2541,7 +2921,7 @@ var init_rfq = __esm({
2541
2921
  const version = selected ?? ASSET_SWAP_BASELINE;
2542
2922
  if (!advertised.includes(version)) {
2543
2923
  throw new Error(
2544
- `solver chose contract version ${version}, not one of ${advertised.join(", ")}`
2924
+ selected === void 0 ? `solver negotiated no contract version; advertised ${advertised.join(", ")}` : `solver chose contract version ${version}, not one of ${advertised.join(", ")}`
2545
2925
  );
2546
2926
  }
2547
2927
  return { quote, rfqId: sent.rfq_id, contractVersion: assetSwapContractVersion(version) };
@@ -2678,6 +3058,9 @@ var init_rfq = __esm({
2678
3058
  if (input.now >= input.payDeadline) {
2679
3059
  throw gateError("quote_expired", "quote or invoice already expired \u2014 request a fresh one");
2680
3060
  }
3061
+ if (quoteAmountSats(input.quote.from_amount, "from_amount") <= 0n || quoteAmountSats(input.quote.to_amount, "to_amount") <= 0n) {
3062
+ throw gateError("non_positive_amount", "quote carries a non-positive amount");
3063
+ }
2681
3064
  if (input.quote.refund_locktime === void 0) {
2682
3065
  throw gateError("missing_refund_locktime", "receive quote carries no refund_locktime");
2683
3066
  }
@@ -2718,6 +3101,191 @@ var init_rfq = __esm({
2718
3101
  }
2719
3102
  });
2720
3103
 
3104
+ // src/client/errors.ts
3105
+ function isSwapError(e, name) {
3106
+ if (!(e instanceof Error)) return false;
3107
+ const table = SWAP_ERRORS;
3108
+ const ctor = table[e.name];
3109
+ if (ctor === void 0 || !(e instanceof ctor)) return false;
3110
+ return name === void 0 || e.name === name;
3111
+ }
3112
+ var AmbiguousDestination, UnsupportedRoute, DiscoverySnapshotUnavailable, AmountMismatch, AmountEncodingUnsupported, QuoteVerificationFailed, QuoteExpired, MaxFeeExceeded, InsufficientFunds, AcceptConflict, ClientDisposed, NotCancellable, InconsistentRoute, OperatorUnreachable, MissingCorridorDep, SWAP_ERRORS, SWAP_ERROR_NAMES;
3113
+ var init_errors = __esm({
3114
+ "src/client/errors.ts"() {
3115
+ "use strict";
3116
+ init_rfq();
3117
+ AmbiguousDestination = class extends Error {
3118
+ constructor(destination, detail) {
3119
+ super(`cannot route ${JSON.stringify(destination)}: ${detail}`);
3120
+ this.destination = destination;
3121
+ }
3122
+ destination;
3123
+ name = "AmbiguousDestination";
3124
+ };
3125
+ UnsupportedRoute = class extends Error {
3126
+ name = "UnsupportedRoute";
3127
+ give;
3128
+ take;
3129
+ constructor(detail, corridors = {}) {
3130
+ super(`unsupported route: ${detail}`);
3131
+ this.give = corridors.give;
3132
+ this.take = corridors.take;
3133
+ }
3134
+ };
3135
+ DiscoverySnapshotUnavailable = class extends Error {
3136
+ constructor(network, detail) {
3137
+ super(`cannot resolve on ${network} offline: ${detail}`);
3138
+ this.network = network;
3139
+ }
3140
+ network;
3141
+ name = "DiscoverySnapshotUnavailable";
3142
+ };
3143
+ AmountMismatch = class extends Error {
3144
+ constructor(sources) {
3145
+ super(`exactly one amount may be pinned; got ${sources[0]} and ${sources[1]}`);
3146
+ this.sources = sources;
3147
+ }
3148
+ sources;
3149
+ name = "AmountMismatch";
3150
+ };
3151
+ AmountEncodingUnsupported = class extends Error {
3152
+ constructor(field, value, detail, options) {
3153
+ super(`${field}: ${detail}`, options);
3154
+ this.field = field;
3155
+ this.value = value;
3156
+ }
3157
+ field;
3158
+ value;
3159
+ name = "AmountEncodingUnsupported";
3160
+ };
3161
+ QuoteVerificationFailed = class extends Error {
3162
+ constructor(check, expected, actual, options) {
3163
+ super(`quote failed the ${check} check \u2014 refusing to fund`, options);
3164
+ this.check = check;
3165
+ this.expected = expected;
3166
+ this.actual = actual;
3167
+ }
3168
+ check;
3169
+ name = "QuoteVerificationFailed";
3170
+ expected;
3171
+ actual;
3172
+ };
3173
+ QuoteExpired = class extends Error {
3174
+ constructor(quoteId, expiresAt, now) {
3175
+ super(`quote ${quoteId} expired at ${expiresAt}, ${now - expiresAt} ago`);
3176
+ this.quoteId = quoteId;
3177
+ this.expiresAt = expiresAt;
3178
+ this.now = now;
3179
+ }
3180
+ quoteId;
3181
+ expiresAt;
3182
+ now;
3183
+ name = "QuoteExpired";
3184
+ };
3185
+ MaxFeeExceeded = class extends Error {
3186
+ constructor(quoteId, asset8, fee, maxFee) {
3187
+ super(`fee ${fee} of ${asset8} exceeds the ${maxFee} ceiling`);
3188
+ this.quoteId = quoteId;
3189
+ this.asset = asset8;
3190
+ this.fee = fee;
3191
+ this.maxFee = maxFee;
3192
+ }
3193
+ quoteId;
3194
+ asset;
3195
+ fee;
3196
+ maxFee;
3197
+ name = "MaxFeeExceeded";
3198
+ };
3199
+ InsufficientFunds = class extends Error {
3200
+ constructor(asset8, required, available) {
3201
+ super(
3202
+ `funding needs ${required} of ${asset8}` + (available === void 0 ? "" : `, wallet holds ${available}`)
3203
+ );
3204
+ this.asset = asset8;
3205
+ this.required = required;
3206
+ this.available = available;
3207
+ }
3208
+ asset;
3209
+ required;
3210
+ name = "InsufficientFunds";
3211
+ available;
3212
+ };
3213
+ AcceptConflict = class extends Error {
3214
+ constructor(quoteId, swapId, fields) {
3215
+ super(`accept ${quoteId} conflicts with swap ${swapId} on ${fields.join(", ")}`);
3216
+ this.quoteId = quoteId;
3217
+ this.swapId = swapId;
3218
+ this.fields = fields;
3219
+ }
3220
+ quoteId;
3221
+ swapId;
3222
+ fields;
3223
+ name = "AcceptConflict";
3224
+ };
3225
+ ClientDisposed = class extends Error {
3226
+ constructor(method) {
3227
+ super(`${method}() called after the client was disposed`);
3228
+ this.method = method;
3229
+ }
3230
+ method;
3231
+ name = "ClientDisposed";
3232
+ };
3233
+ NotCancellable = class extends Error {
3234
+ constructor(swapId) {
3235
+ super(`swap ${swapId} is not a cancellable asset swap`);
3236
+ this.swapId = swapId;
3237
+ }
3238
+ swapId;
3239
+ name = "NotCancellable";
3240
+ };
3241
+ InconsistentRoute = class extends Error {
3242
+ constructor(asset8, destination) {
3243
+ super(`destination ${JSON.stringify(destination)} is not on ${asset8}'s chain`);
3244
+ this.asset = asset8;
3245
+ this.destination = destination;
3246
+ }
3247
+ asset;
3248
+ destination;
3249
+ name = "InconsistentRoute";
3250
+ };
3251
+ OperatorUnreachable = class extends Error {
3252
+ name = "OperatorUnreachable";
3253
+ constructor(detail, options) {
3254
+ super(`cannot derive a covenant: ${detail}`, options);
3255
+ }
3256
+ };
3257
+ MissingCorridorDep = class extends Error {
3258
+ constructor(corridor, dep) {
3259
+ super(`the ${corridor} corridor has no ${dep}`);
3260
+ this.corridor = corridor;
3261
+ this.dep = dep;
3262
+ }
3263
+ corridor;
3264
+ dep;
3265
+ name = "MissingCorridorDep";
3266
+ };
3267
+ SWAP_ERRORS = {
3268
+ AmbiguousDestination,
3269
+ UnsupportedRoute,
3270
+ DiscoverySnapshotUnavailable,
3271
+ AmountMismatch,
3272
+ AmountEncodingUnsupported,
3273
+ QuoteVerificationFailed,
3274
+ SwapRefusal,
3275
+ QuoteExpired,
3276
+ MaxFeeExceeded,
3277
+ InsufficientFunds,
3278
+ AcceptConflict,
3279
+ ClientDisposed,
3280
+ NotCancellable,
3281
+ InconsistentRoute,
3282
+ OperatorUnreachable,
3283
+ MissingCorridorDep
3284
+ };
3285
+ SWAP_ERROR_NAMES = Object.keys(SWAP_ERRORS);
3286
+ }
3287
+ });
3288
+
2721
3289
  // src/closeOnceWebSocket.ts
2722
3290
  var CloseOnceWebSocket;
2723
3291
  var init_closeOnceWebSocket = __esm({
@@ -2917,6 +3485,7 @@ var init_nostr = __esm({
2917
3485
  { kinds: [RFQ_DIRECTED_KIND], "#p": [pubkey], authors: [solverPubkey] },
2918
3486
  {
2919
3487
  onevent(event) {
3488
+ if (event.pubkey !== solverPubkey || !(0, import_nostr_tools2.verifyEvent)(event)) return;
2920
3489
  let payload;
2921
3490
  try {
2922
3491
  payload = JSON.parse(import_nostr_tools2.nip44.v2.decrypt(event.content, conversationKey));
@@ -3090,6 +3659,245 @@ var init_nostr = __esm({
3090
3659
  }
3091
3660
  });
3092
3661
 
3662
+ // src/client/policy.ts
3663
+ var DEFAULT_MAX_REFUND_WINDOW_SECONDS;
3664
+ var init_policy = __esm({
3665
+ "src/client/policy.ts"() {
3666
+ "use strict";
3667
+ DEFAULT_MAX_REFUND_WINDOW_SECONDS = 30 * 24 * 3600;
3668
+ }
3669
+ });
3670
+
3671
+ // src/client/verify.ts
3672
+ var import_base21, reasonOf, CHECK_BY_REASON, gated, verifyResponder, verifyTaker, verifyPair, verifyingDerivation, verifySendWindow, verifyReceiveWindow, verifySendInvoice, verifyReceiveInvoiceFacts, verifyQuoteTtl, CSV_GRANULARITY_SECONDS, verifyRefundWindow, verifyQuotedAmount, verifyCrossAssetAmount, verifiedCarrierSats, verifyPinnedAmount;
3673
+ var init_verify = __esm({
3674
+ "src/client/verify.ts"() {
3675
+ "use strict";
3676
+ import_base21 = require("@scure/base");
3677
+ init_rfq();
3678
+ init_errors();
3679
+ init_policy();
3680
+ reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
3681
+ CHECK_BY_REASON = {
3682
+ invoice_expired: "invoice",
3683
+ invoice_undecodable: "invoice",
3684
+ invoice_hash_mismatch: "invoice",
3685
+ invoice_amount_mismatch: "invoice",
3686
+ insufficient_headroom: "refund_window",
3687
+ missing_refund_locktime: "refund_window",
3688
+ claim_window_too_short: "refund_window",
3689
+ confirmations_out_of_range: "refund_window",
3690
+ timelock_order: "refund_window",
3691
+ quote_malformed: "refund_window"
3692
+ };
3693
+ gated = (run, quote) => {
3694
+ try {
3695
+ run();
3696
+ } catch (error) {
3697
+ const reason = reasonOf(error);
3698
+ if (reason === "quote_expired") {
3699
+ throw new QuoteExpired(quote.id, quote.expiresAt, quote.now);
3700
+ }
3701
+ const check = reason === void 0 ? void 0 : CHECK_BY_REASON[reason];
3702
+ if (check === void 0) throw error;
3703
+ throw new QuoteVerificationFailed(
3704
+ check,
3705
+ void 0,
3706
+ error instanceof Error ? error.message : String(error),
3707
+ { cause: error }
3708
+ );
3709
+ }
3710
+ };
3711
+ verifyResponder = (input) => {
3712
+ if (!input.pinnable || input.expected === void 0) {
3713
+ throw new QuoteVerificationFailed(
3714
+ "responder",
3715
+ "a registry-served card naming the solver's discovery key",
3716
+ input.expected === void 0 ? "the card names no discovery key" : "the card came out of the local cache, which does not authenticate it"
3717
+ );
3718
+ }
3719
+ if (input.attested === void 0) {
3720
+ throw new QuoteVerificationFailed(
3721
+ "responder",
3722
+ input.expected,
3723
+ "the transport attests nobody"
3724
+ );
3725
+ }
3726
+ if (input.attested !== input.expected) {
3727
+ throw new QuoteVerificationFailed("responder", input.expected, input.attested);
3728
+ }
3729
+ };
3730
+ verifyTaker = (input) => {
3731
+ const xOnly = (key) => typeof key === "string" && /^[0-9a-f]{64}$/i.test(key) ? import_base21.hex.decode(key.toLowerCase()) : void 0;
3732
+ const taker = xOnly(input.solverPubkey);
3733
+ const attested = xOnly(input.attested);
3734
+ if (taker === void 0 || attested === void 0 || import_base21.hex.encode(taker) !== import_base21.hex.encode(attested)) {
3735
+ throw new QuoteVerificationFailed("responder", input.attested, String(input.solverPubkey));
3736
+ }
3737
+ return taker;
3738
+ };
3739
+ verifyPair = (quoted, requested) => {
3740
+ if (quoted !== requested) {
3741
+ throw new QuoteVerificationFailed("pair", requested, String(quoted));
3742
+ }
3743
+ };
3744
+ verifyingDerivation = (derive) => {
3745
+ try {
3746
+ return derive();
3747
+ } catch (error) {
3748
+ if (error instanceof AddressMismatch) {
3749
+ const derived = Array.isArray(error.derived) ? error.derived.join(", ") : error.derived;
3750
+ throw new QuoteVerificationFailed("lockup_address", derived, error.quoted, {
3751
+ cause: error
3752
+ });
3753
+ }
3754
+ if (error instanceof Error) {
3755
+ throw new QuoteVerificationFailed("lockup_address", void 0, error.message, {
3756
+ cause: error
3757
+ });
3758
+ }
3759
+ throw error;
3760
+ }
3761
+ };
3762
+ verifySendWindow = (input) => {
3763
+ gated(
3764
+ () => assertFundable({
3765
+ quote: input.quote,
3766
+ now: input.now,
3767
+ ...input.invoiceExpiresAt === void 0 ? {} : { invoiceExpiresAt: input.invoiceExpiresAt },
3768
+ ...input.onchain === void 0 ? {} : { onchain: input.onchain }
3769
+ }),
3770
+ { id: input.quoteId, expiresAt: input.quote.valid_until, now: input.now }
3771
+ );
3772
+ };
3773
+ verifyReceiveWindow = (input) => {
3774
+ gated(
3775
+ () => assertReceivable({
3776
+ quote: input.quote,
3777
+ payDeadline: input.payDeadline,
3778
+ now: input.now
3779
+ }),
3780
+ { id: input.quoteId, expiresAt: input.payDeadline, now: input.now }
3781
+ );
3782
+ };
3783
+ verifySendInvoice = (input) => {
3784
+ const invoiced = input.invoiced;
3785
+ if (input.take !== invoiced) {
3786
+ throw new QuoteVerificationFailed("invoice", `${invoiced}`, `${input.take}`);
3787
+ }
3788
+ if (input.give < input.take) {
3789
+ throw new QuoteVerificationFailed(
3790
+ "invoice",
3791
+ `at least the invoice's ${invoiced}`,
3792
+ `${input.give}, a negative spread`
3793
+ );
3794
+ }
3795
+ };
3796
+ verifyReceiveInvoiceFacts = (input) => {
3797
+ let decoded;
3798
+ try {
3799
+ decoded = input.decode(input.invoice);
3800
+ } catch (cause) {
3801
+ throw new QuoteVerificationFailed(
3802
+ "invoice",
3803
+ "a decodable BOLT11",
3804
+ cause instanceof Error ? cause.message : String(cause),
3805
+ { cause }
3806
+ );
3807
+ }
3808
+ if (!Number.isFinite(decoded.expiresAt)) {
3809
+ throw new QuoteVerificationFailed("invoice", "a finite expiry", `${decoded.expiresAt}`);
3810
+ }
3811
+ if (!Number.isFinite(input.validUntil)) {
3812
+ throw new QuoteVerificationFailed(
3813
+ "refund_window",
3814
+ "a finite valid_until",
3815
+ `${input.validUntil}`
3816
+ );
3817
+ }
3818
+ if (decoded.paymentHash !== input.paymentHash) {
3819
+ throw new QuoteVerificationFailed("invoice", input.paymentHash, decoded.paymentHash);
3820
+ }
3821
+ if (!Number.isSafeInteger(decoded.amountSats) || decoded.amountSats <= 0) {
3822
+ throw new QuoteVerificationFailed(
3823
+ "invoice",
3824
+ `${input.payAmount}`,
3825
+ "the invoice names no amount"
3826
+ );
3827
+ }
3828
+ if (BigInt(decoded.amountSats) !== input.payAmount) {
3829
+ throw new QuoteVerificationFailed("invoice", `${input.payAmount}`, `${decoded.amountSats}`);
3830
+ }
3831
+ return { payDeadline: Math.min(decoded.expiresAt, input.validUntil) };
3832
+ };
3833
+ verifyQuoteTtl = (input) => {
3834
+ const floor = input.floorSeconds ?? 0;
3835
+ if (input.expiresAt - input.now <= floor) {
3836
+ throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
3837
+ }
3838
+ };
3839
+ CSV_GRANULARITY_SECONDS = 512;
3840
+ verifyRefundWindow = (input) => {
3841
+ const max = input.maxSeconds ?? DEFAULT_MAX_REFUND_WINDOW_SECONDS;
3842
+ const window = input.refundLocktime - input.now;
3843
+ if (!(window <= max)) {
3844
+ throw new QuoteVerificationFailed("refund_window", `at most ${max}s`, `${window}s`);
3845
+ }
3846
+ const delay = input.refundWithoutReceiverDelay;
3847
+ if (delay !== void 0 && !(delay < max + CSV_GRANULARITY_SECONDS)) {
3848
+ throw new QuoteVerificationFailed(
3849
+ "refund_window",
3850
+ `a solo-refund delay of at most ${max}s`,
3851
+ `${delay}s`
3852
+ );
3853
+ }
3854
+ };
3855
+ verifyQuotedAmount = (input) => {
3856
+ verifyPinnedAmount(input);
3857
+ if (input.take > input.give) {
3858
+ throw new QuoteVerificationFailed(
3859
+ "pair",
3860
+ `${input.pair} give >= take`,
3861
+ `give=${input.give} take=${input.take}`
3862
+ );
3863
+ }
3864
+ };
3865
+ verifyCrossAssetAmount = (input) => {
3866
+ verifyPinnedAmount(input);
3867
+ if (input.give <= 0n || input.take <= 0n) {
3868
+ throw new QuoteVerificationFailed(
3869
+ "pair",
3870
+ `${input.pair} give > 0 take > 0`,
3871
+ `give=${input.give} take=${input.take}`
3872
+ );
3873
+ }
3874
+ };
3875
+ verifiedCarrierSats = (quote) => {
3876
+ try {
3877
+ return quoteCarrierSats(quote);
3878
+ } catch (error) {
3879
+ if (reasonOf(error) !== "carrier_malformed") throw error;
3880
+ throw new QuoteVerificationFailed(
3881
+ "pair",
3882
+ "carrier_sats a non-negative integer",
3883
+ String(quote.carrier_sats),
3884
+ { cause: error }
3885
+ );
3886
+ }
3887
+ };
3888
+ verifyPinnedAmount = (input) => {
3889
+ const quoted = input.pinned.on === "give" ? input.give : input.take;
3890
+ if (quoted !== input.pinned.value) {
3891
+ throw new QuoteVerificationFailed(
3892
+ "pair",
3893
+ `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
3894
+ `${input.pair} ${input.pinned.on}=${quoted}`
3895
+ );
3896
+ }
3897
+ };
3898
+ }
3899
+ });
3900
+
3093
3901
  // src/advanced.ts
3094
3902
  var advanced_exports = {};
3095
3903
  __export(advanced_exports, {
@@ -3244,6 +4052,7 @@ __export(advanced_exports, {
3244
4052
  recordInstrument: () => recordInstrument,
3245
4053
  recordLeg: () => recordLeg,
3246
4054
  recordOutcome: () => recordOutcome,
4055
+ reopenedDeposit: () => reopenedDeposit,
3247
4056
  resolveCorridorBase: () => resolveCorridorBase,
3248
4057
  resolveCorridorDeps: () => resolveCorridorDeps,
3249
4058
  resolveRoute: () => resolveRoute,
@@ -3280,6 +4089,7 @@ __export(advanced_exports, {
3280
4089
  verifyResponder: () => verifyResponder,
3281
4090
  verifySendInvoice: () => verifySendInvoice,
3282
4091
  verifySendWindow: () => verifySendWindow,
4092
+ verifyTaker: () => verifyTaker,
3283
4093
  verifyingDerivation: () => verifyingDerivation,
3284
4094
  walletLockupIndexer: () => walletLockupIndexer,
3285
4095
  withCanonicalAmount: () => withCanonicalAmount,
@@ -3648,187 +4458,7 @@ var issuanceOf = (id) => {
3648
4458
  // src/client/aliases.ts
3649
4459
  var import_solver_discovery2 = require("@arkade-os/solver-discovery");
3650
4460
  init_store();
3651
-
3652
- // src/client/errors.ts
3653
- init_rfq();
3654
- var AmbiguousDestination = class extends Error {
3655
- constructor(destination, detail) {
3656
- super(`cannot route ${JSON.stringify(destination)}: ${detail}`);
3657
- this.destination = destination;
3658
- }
3659
- destination;
3660
- name = "AmbiguousDestination";
3661
- };
3662
- var UnsupportedRoute = class extends Error {
3663
- name = "UnsupportedRoute";
3664
- give;
3665
- take;
3666
- constructor(detail, corridors = {}) {
3667
- super(`unsupported route: ${detail}`);
3668
- this.give = corridors.give;
3669
- this.take = corridors.take;
3670
- }
3671
- };
3672
- var DiscoverySnapshotUnavailable = class extends Error {
3673
- constructor(network, detail) {
3674
- super(`cannot resolve on ${network} offline: ${detail}`);
3675
- this.network = network;
3676
- }
3677
- network;
3678
- name = "DiscoverySnapshotUnavailable";
3679
- };
3680
- var AmountMismatch = class extends Error {
3681
- constructor(sources) {
3682
- super(`exactly one amount may be pinned; got ${sources[0]} and ${sources[1]}`);
3683
- this.sources = sources;
3684
- }
3685
- sources;
3686
- name = "AmountMismatch";
3687
- };
3688
- var AmountEncodingUnsupported = class extends Error {
3689
- constructor(field, value, detail, options) {
3690
- super(`${field}: ${detail}`, options);
3691
- this.field = field;
3692
- this.value = value;
3693
- }
3694
- field;
3695
- value;
3696
- name = "AmountEncodingUnsupported";
3697
- };
3698
- var QuoteVerificationFailed = class extends Error {
3699
- constructor(check, expected, actual, options) {
3700
- super(`quote failed the ${check} check \u2014 refusing to fund`, options);
3701
- this.check = check;
3702
- this.expected = expected;
3703
- this.actual = actual;
3704
- }
3705
- check;
3706
- name = "QuoteVerificationFailed";
3707
- expected;
3708
- actual;
3709
- };
3710
- var QuoteExpired = class extends Error {
3711
- constructor(quoteId, expiresAt, now) {
3712
- super(`quote ${quoteId} expired at ${expiresAt}, ${now - expiresAt} ago`);
3713
- this.quoteId = quoteId;
3714
- this.expiresAt = expiresAt;
3715
- this.now = now;
3716
- }
3717
- quoteId;
3718
- expiresAt;
3719
- now;
3720
- name = "QuoteExpired";
3721
- };
3722
- var MaxFeeExceeded = class extends Error {
3723
- constructor(quoteId, asset8, fee, maxFee) {
3724
- super(`fee ${fee} of ${asset8} exceeds the ${maxFee} ceiling`);
3725
- this.quoteId = quoteId;
3726
- this.asset = asset8;
3727
- this.fee = fee;
3728
- this.maxFee = maxFee;
3729
- }
3730
- quoteId;
3731
- asset;
3732
- fee;
3733
- maxFee;
3734
- name = "MaxFeeExceeded";
3735
- };
3736
- var InsufficientFunds = class extends Error {
3737
- constructor(asset8, required, available) {
3738
- super(
3739
- `funding needs ${required} of ${asset8}` + (available === void 0 ? "" : `, wallet holds ${available}`)
3740
- );
3741
- this.asset = asset8;
3742
- this.required = required;
3743
- this.available = available;
3744
- }
3745
- asset;
3746
- required;
3747
- name = "InsufficientFunds";
3748
- available;
3749
- };
3750
- var AcceptConflict = class extends Error {
3751
- constructor(quoteId, swapId, fields) {
3752
- super(`accept ${quoteId} conflicts with swap ${swapId} on ${fields.join(", ")}`);
3753
- this.quoteId = quoteId;
3754
- this.swapId = swapId;
3755
- this.fields = fields;
3756
- }
3757
- quoteId;
3758
- swapId;
3759
- fields;
3760
- name = "AcceptConflict";
3761
- };
3762
- var ClientDisposed = class extends Error {
3763
- constructor(method) {
3764
- super(`${method}() called after the client was disposed`);
3765
- this.method = method;
3766
- }
3767
- method;
3768
- name = "ClientDisposed";
3769
- };
3770
- var NotCancellable = class extends Error {
3771
- constructor(swapId) {
3772
- super(`swap ${swapId} is not a cancellable asset swap`);
3773
- this.swapId = swapId;
3774
- }
3775
- swapId;
3776
- name = "NotCancellable";
3777
- };
3778
- var InconsistentRoute = class extends Error {
3779
- constructor(asset8, destination) {
3780
- super(`destination ${JSON.stringify(destination)} is not on ${asset8}'s chain`);
3781
- this.asset = asset8;
3782
- this.destination = destination;
3783
- }
3784
- asset;
3785
- destination;
3786
- name = "InconsistentRoute";
3787
- };
3788
- var OperatorUnreachable = class extends Error {
3789
- name = "OperatorUnreachable";
3790
- constructor(detail, options) {
3791
- super(`cannot derive a covenant: ${detail}`, options);
3792
- }
3793
- };
3794
- var MissingCorridorDep = class extends Error {
3795
- constructor(corridor, dep) {
3796
- super(`the ${corridor} corridor has no ${dep}`);
3797
- this.corridor = corridor;
3798
- this.dep = dep;
3799
- }
3800
- corridor;
3801
- dep;
3802
- name = "MissingCorridorDep";
3803
- };
3804
- var SWAP_ERRORS = {
3805
- AmbiguousDestination,
3806
- UnsupportedRoute,
3807
- DiscoverySnapshotUnavailable,
3808
- AmountMismatch,
3809
- AmountEncodingUnsupported,
3810
- QuoteVerificationFailed,
3811
- SwapRefusal,
3812
- QuoteExpired,
3813
- MaxFeeExceeded,
3814
- InsufficientFunds,
3815
- AcceptConflict,
3816
- ClientDisposed,
3817
- NotCancellable,
3818
- InconsistentRoute,
3819
- OperatorUnreachable,
3820
- MissingCorridorDep
3821
- };
3822
- var SWAP_ERROR_NAMES = Object.keys(SWAP_ERRORS);
3823
- function isSwapError(e, name) {
3824
- if (!(e instanceof Error)) return false;
3825
- const table = SWAP_ERRORS;
3826
- const ctor = table[e.name];
3827
- if (ctor === void 0 || !(e instanceof ctor)) return false;
3828
- return name === void 0 || e.name === name;
3829
- }
3830
-
3831
- // src/client/aliases.ts
4461
+ init_errors();
3832
4462
  var toDiscoveryLeg = (id) => {
3833
4463
  const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
3834
4464
  const asset8 = `${assetNamespace}:${assetReference}`;
@@ -4615,8 +5245,12 @@ var ACTIVITY_TOKEN = {
4615
5245
  failed: "failed"
4616
5246
  };
4617
5247
 
5248
+ // src/client/accept.ts
5249
+ init_errors();
5250
+
4618
5251
  // src/client/rfqAmount.ts
4619
5252
  var import_solver_discovery5 = require("@arkade-os/solver-discovery");
5253
+ init_errors();
4620
5254
  var toRfqAmountSide = (on) => on === "give" ? "from" : "to";
4621
5255
  var fromRfqAmountSide = (side) => side === "from" ? "give" : "take";
4622
5256
  var encodeRfqAmount = (value, field) => {
@@ -4867,7 +5501,8 @@ var acceptQuoteBody = async (input) => {
4867
5501
  }
4868
5502
  const funds = fundsFromWallet(quote.route);
4869
5503
  if (funds) await assertFundable2(wallet, quote);
4870
- const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
5504
+ const built = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
5505
+ const record = built.family === "offer" && input.attachOfferPacket === false ? { ...built, attachOfferPacket: false } : built;
4871
5506
  await repository.saveSwapRecord(record);
4872
5507
  if (!funds) return answer(record);
4873
5508
  return answer(
@@ -4887,7 +5522,7 @@ var acceptQuoteBody = async (input) => {
4887
5522
  var registeredOfferRecord = async (input, preparation) => {
4888
5523
  const { quote, wallet, corridors, now } = input;
4889
5524
  const { plan } = preparation;
4890
- const arkade4 = corridors.get("arkade").deps;
5525
+ const arkade5 = corridors.get("arkade").deps;
4891
5526
  const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
4892
5527
  const offer = await createOffer(
4893
5528
  wallet,
@@ -4895,7 +5530,7 @@ var registeredOfferRecord = async (input, preparation) => {
4895
5530
  // Keyed on the receive side: the covenant binds what the fill delivers.
4896
5531
  wantAmount: plan.receive.atomic,
4897
5532
  ...receiveIsBtc ? { offerAsset: import_sdk14.asset.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: import_sdk14.asset.AssetId.fromString(plan.receive.asset.id) },
4898
- emulatorPubkey: arkade4.emulatorPubkey
5533
+ emulatorPubkey: arkade5.emulatorPubkey
4899
5534
  },
4900
5535
  { coverageId: quote.id }
4901
5536
  );
@@ -4923,7 +5558,9 @@ var registeredAssetRecord = async (input, preparation) => {
4923
5558
  ...preparation.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(preparation.assetPayment) },
4924
5559
  family: "offer",
4925
5560
  status: "pending",
4926
- offerHex: preparation.offer.offerHex,
5561
+ // a directed covenant is kept as its binding alone, which an older reader drops whole
5562
+ // rather than half-reads
5563
+ ...preparation.offer.offerBinding.taker === void 0 ? { offerHex: preparation.offer.offerHex } : { binding: recordOfferBinding(preparation.offer.offerBinding) },
4927
5564
  swapAddress: preparation.offer.address,
4928
5565
  swapPkScript: import_base9.hex.encode(preparation.offer.swapPkScript),
4929
5566
  ...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
@@ -5008,7 +5645,7 @@ var fund = async (input, record) => {
5008
5645
  { assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
5009
5646
  ]
5010
5647
  },
5011
- extensions: [offerExtensionOf(record)]
5648
+ ...record.attachOfferPacket === false ? {} : { extensions: [offerExtensionOf(record)] }
5012
5649
  });
5013
5650
  }
5014
5651
  if (record.kind === "lightning_receive" || record.kind === "onchain_receive") {
@@ -5019,10 +5656,13 @@ var fund = async (input, record) => {
5019
5656
  amount: toSafeNumber(fromAtomicDecimal(record.give.amount), "give.amount")
5020
5657
  });
5021
5658
  };
5022
- var offerExtensionOf = (record) => ({
5023
- type: OFFER_PACKET_TYPE,
5024
- payload: import_base9.hex.decode(record.offerHex)
5025
- });
5659
+ var offerExtensionOf = (record) => {
5660
+ const stored = storedOffer(record);
5661
+ return {
5662
+ type: OFFER_PACKET_TYPE,
5663
+ payload: record.offerHex !== void 0 ? import_base9.hex.decode(record.offerHex) : encodeOffer("version" in stored ? offerFromBinding(stored) : stored)
5664
+ };
5665
+ };
5026
5666
  var reconcileFunding = async (input, record) => {
5027
5667
  const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
5028
5668
  const expected = BigInt(record.give.amount);
@@ -5136,7 +5776,7 @@ var scopedToRail = (table, rail) => ({
5136
5776
  });
5137
5777
 
5138
5778
  // src/client/client.ts
5139
- var import_base23 = require("@scure/base");
5779
+ var import_base24 = require("@scure/base");
5140
5780
  var import_sdk38 = require("@arkade-os/sdk");
5141
5781
  init_repository();
5142
5782
 
@@ -5373,6 +6013,7 @@ var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
5373
6013
 
5374
6014
  // src/client/corridors/registry.ts
5375
6015
  var import_sdk19 = require("@arkade-os/sdk");
6016
+ init_errors();
5376
6017
 
5377
6018
  // src/client/corridors/arkade.ts
5378
6019
  var import_sdk16 = require("@arkade-os/sdk");
@@ -5456,6 +6097,7 @@ var chainSourceFrom = (provider, network) => {
5456
6097
  // src/client/corridors/deps.ts
5457
6098
  init_onchainHtlc();
5458
6099
  init_rfq();
6100
+ init_errors();
5459
6101
 
5460
6102
  // src/client/corridors/bolt11.ts
5461
6103
  var import_light_bolt11_decoder = __toESM(require("light-bolt11-decoder"), 1);
@@ -5834,6 +6476,7 @@ var undeliveredCarry = (fresh, undelivered, cached) => {
5834
6476
  };
5835
6477
 
5836
6478
  // src/client/discovery.ts
6479
+ init_errors();
5837
6480
  var REGISTRY_URL = {
5838
6481
  bitcoin: "https://arkade-os.github.io/solver-registry/bitcoin.json",
5839
6482
  signet: "https://arkade-os.github.io/solver-registry/signet.json",
@@ -5990,6 +6633,9 @@ var discoveryIndex = (input) => {
5990
6633
  return { peek, load };
5991
6634
  };
5992
6635
 
6636
+ // src/client/client.ts
6637
+ init_errors();
6638
+
5993
6639
  // src/client/cancel.ts
5994
6640
  var import_base16 = require("@scure/base");
5995
6641
  var import_sdk25 = require("@arkade-os/sdk");
@@ -6037,8 +6683,16 @@ var unscannedSwapCandidates = (txs, existingIds, scanned) => txs.filter(
6037
6683
  function classifySpend(offer, operatorPubkey, spendTx, deposit) {
6038
6684
  let leaves;
6039
6685
  try {
6040
- const script = offerContract(offer, operatorPubkey);
6041
- if (import_base13.hex.encode(script.pkScript) !== import_base13.hex.encode(offer.swapPkScript)) return "indeterminate";
6686
+ let script;
6687
+ if ("version" in offer) {
6688
+ const { program, args, keys } = bindingProgram(offer);
6689
+ script = new import_sdk22.arkade.ArkadeProgramScript(program, args, keys);
6690
+ } else {
6691
+ script = offerContract(offer, operatorPubkey);
6692
+ if (import_base13.hex.encode(script.pkScript) !== import_base13.hex.encode(offer.swapPkScript)) {
6693
+ return "indeterminate";
6694
+ }
6695
+ }
6042
6696
  leaves = {
6043
6697
  // `exit` is absent on an offer with no exit closure, and drops out here
6044
6698
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
@@ -6067,21 +6721,56 @@ function classifyDepositSpend(offer, operatorPubkey, spendTxs, deposit) {
6067
6721
  }
6068
6722
  return "indeterminate";
6069
6723
  }
6724
+ var encodesOffer = (offerHex, offer) => {
6725
+ try {
6726
+ const { ratioNum: _num, ratioDen: _den, ...terms } = decodeOffer(import_base13.hex.decode(offerHex));
6727
+ return import_base13.hex.encode(encodeOffer(terms)) === import_base13.hex.encode(encodeOffer(offer));
6728
+ } catch {
6729
+ return false;
6730
+ }
6731
+ };
6732
+ var packetRecoverySource = (indexer) => ({
6733
+ name: "packet",
6734
+ async discover({ candidateTxids, operatorPubkey }) {
6735
+ const found = [];
6736
+ const declined = [];
6737
+ for (const [txid, parsed] of await fetchParsedTxs(indexer, [...candidateTxids])) {
6738
+ let packet;
6739
+ try {
6740
+ packet = import_sdk22.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
6741
+ } catch {
6742
+ }
6743
+ if (!packet) {
6744
+ declined.push(txid);
6745
+ continue;
6746
+ }
6747
+ const payload = packet.serialize();
6748
+ try {
6749
+ const binding = bindingFromOffer(decodeOffer(payload), operatorPubkey);
6750
+ found.push({ fundingTxid: txid, binding, offerHex: import_base13.hex.encode(payload) });
6751
+ } catch {
6752
+ }
6753
+ }
6754
+ return { found, declined };
6755
+ }
6756
+ });
6070
6757
  async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6071
6758
  const {
6072
6759
  operatorPubkey,
6073
6760
  scanned = /* @__PURE__ */ new Set(),
6074
6761
  reopen = [],
6075
6762
  hrp,
6076
- recoveredIn = /* @__PURE__ */ new Set()
6763
+ recoveredIn = /* @__PURE__ */ new Set(),
6764
+ sources = [packetRecoverySource(indexer)]
6077
6765
  } = opts;
6078
6766
  const reopened = [];
6079
6767
  for (const swap of reopen) {
6080
6768
  try {
6769
+ const source = storedOffer(swap);
6081
6770
  reopened.push({
6082
6771
  fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
6083
- offer: decodeOffer(import_base13.hex.decode(swap.offerHex)),
6084
- offerHex: swap.offerHex,
6772
+ offer: "version" in source ? offerFromBinding(source) : source,
6773
+ source,
6085
6774
  existing: swap
6086
6775
  });
6087
6776
  } catch {
@@ -6095,29 +6784,40 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6095
6784
  return { restored: [], scannedTxids: [] };
6096
6785
  }
6097
6786
  const byTxid = new Map(candidates.map((tx) => [tx.redeemTxid, tx]));
6098
- const parsedByTxid = await fetchParsedTxs(
6099
- indexer,
6100
- candidates.map((tx) => tx.redeemTxid)
6101
- );
6102
- const fetchedTxids = [];
6787
+ const candidateTxids = candidates.map((tx) => tx.redeemTxid);
6103
6788
  const found = [...reopened];
6104
- for (const [txid, parsed] of parsedByTxid) {
6105
- const fundingTx = byTxid.get(txid);
6106
- if (!fundingTx) continue;
6107
- fetchedTxids.push(txid);
6789
+ const claimed = /* @__PURE__ */ new Set();
6790
+ const declined = /* @__PURE__ */ new Set();
6791
+ for (const recovery of candidateTxids.length === 0 ? [] : sources) {
6792
+ let answer;
6108
6793
  try {
6109
- const packet = import_sdk22.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
6110
- if (!packet) continue;
6111
- const payload = packet.serialize();
6112
- found.push({
6113
- fundingTx,
6114
- offer: decodeOffer(payload),
6115
- offerHex: import_base13.hex.encode(payload)
6116
- });
6117
- } catch {
6794
+ answer = await recovery.discover({ candidateTxids, operatorPubkey });
6795
+ } catch (error) {
6796
+ console.warn(`[swap] recovery source ${recovery.name} failed`, error);
6797
+ continue;
6798
+ }
6799
+ for (const txid of answer.declined) declined.add(txid);
6800
+ for (const { fundingTxid, binding, offerHex } of answer.found) {
6801
+ const fundingTx = byTxid.get(fundingTxid);
6802
+ if (!fundingTx || claimed.has(fundingTxid)) continue;
6803
+ let offer;
6804
+ try {
6805
+ offer = offerFromBinding(binding);
6806
+ } catch (error) {
6807
+ console.warn(`[swap] ${recovery.name} sent a binding that does not compile`, error);
6808
+ continue;
6809
+ }
6810
+ if (offerHex !== void 0 && !encodesOffer(offerHex, offer)) {
6811
+ console.warn(`[swap] ${recovery.name} sent a packet its binding does not match`);
6812
+ continue;
6813
+ }
6814
+ claimed.add(fundingTxid);
6815
+ const packet = offerHex ?? import_base13.hex.encode(encodeOffer(offer));
6816
+ found.push({ fundingTx, offer, source: binding, offerHex: packet });
6118
6817
  }
6119
6818
  }
6120
- if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
6819
+ const answered = [...claimed, ...[...declined].filter((txid) => !claimed.has(txid))];
6820
+ if (found.length === 0) return { restored: [], scannedTxids: answered };
6121
6821
  const scripts = [...new Set(found.map((f) => import_base13.hex.encode(f.offer.swapPkScript)))];
6122
6822
  const { vtxos } = await indexer.getVtxos({ scripts });
6123
6823
  const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
@@ -6138,7 +6838,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6138
6838
  const spendTxByTxid = await fetchParsedTxs(indexer, [...spendTxids]);
6139
6839
  const restored = [];
6140
6840
  const unresolved = /* @__PURE__ */ new Set();
6141
- for (const { fundingTx, offer, offerHex, existing } of found) {
6841
+ for (const { fundingTx, offer, source, offerHex, existing } of found) {
6142
6842
  const swapPkScript = import_base13.hex.encode(offer.swapPkScript);
6143
6843
  const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
6144
6844
  if (!vtxo) {
@@ -6167,7 +6867,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6167
6867
  } else if (vtxo.isSwept && !vtxo.isSpent) status = "recoverable";
6168
6868
  else if (vtxo.isSpent) {
6169
6869
  const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
6170
- const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
6870
+ const kind = classifyDepositSpend(source, operatorPubkey, spendTxs, {
6171
6871
  txid: vtxo.txid,
6172
6872
  vout: vtxo.vout
6173
6873
  });
@@ -6183,20 +6883,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6183
6883
  restored.push({ ...existing, status, spentTxid, ...completion });
6184
6884
  continue;
6185
6885
  }
6886
+ if (!("version" in source)) continue;
6186
6887
  let swapAddress = "";
6187
6888
  try {
6188
- const compiled = offerContract(offer, operatorPubkey);
6189
- if (import_base13.hex.encode(compiled.pkScript) !== swapPkScript) {
6190
- unresolved.add(fundingTx.redeemTxid);
6191
- continue;
6192
- }
6193
6889
  if (hrp !== void 0) {
6194
- swapAddress = compiled.address(hrp, operatorPubkey).encode();
6890
+ const { program, args, keys } = bindingProgram(source);
6891
+ const compiled = new import_sdk22.arkade.ArkadeProgramScript(program, args, keys);
6892
+ swapAddress = compiled.address(hrp, source.serverPublicKey).encode();
6195
6893
  }
6196
6894
  } catch {
6197
6895
  unresolved.add(fundingTx.redeemTxid);
6198
6896
  continue;
6199
6897
  }
6898
+ const covenant = source.taker === void 0 ? { offerHex: offerHex ?? import_base13.hex.encode(encodeOffer(offer)) } : { binding: recordOfferBinding(source) };
6200
6899
  restored.push({
6201
6900
  id: fundingTx.redeemTxid,
6202
6901
  fromAsset,
@@ -6205,7 +6904,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6205
6904
  toAmount: offer.wantAmount.toString(),
6206
6905
  swapAddress,
6207
6906
  swapPkScript,
6208
- offerHex,
6907
+ ...covenant,
6209
6908
  fundingTxid: fundingTx.redeemTxid,
6210
6909
  spentTxid,
6211
6910
  status,
@@ -6213,7 +6912,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6213
6912
  ...completion
6214
6913
  });
6215
6914
  }
6216
- return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
6915
+ return { restored, scannedTxids: answered.filter((id) => !unresolved.has(id)) };
6217
6916
  }
6218
6917
 
6219
6918
  // src/client/cancel.ts
@@ -6472,11 +7171,15 @@ var corridorRecordStore = (repository, onRecord = () => {
6472
7171
  }
6473
7172
  };
6474
7173
  };
7174
+ var covenantOf = (swap) => ({
7175
+ ...swap.offerHex === void 0 ? {} : { offerHex: swap.offerHex },
7176
+ ...swap.binding === void 0 ? {} : { binding: swap.binding }
7177
+ });
6475
7178
  var offerFactsOf = (record) => ({
6476
7179
  id: record.id,
6477
7180
  coverageId: record.id,
6478
7181
  status: record.status,
6479
- offerHex: record.offerHex,
7182
+ ...covenantOf(record),
6480
7183
  swapPkScript: record.swapPkScript,
6481
7184
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
6482
7185
  ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
@@ -6548,7 +7251,7 @@ var restoredOfferRecord = (swap, network, now) => {
6548
7251
  market: { kind: "restored", backend: "feed" },
6549
7252
  expiresAt: createdAt,
6550
7253
  status: swap.status,
6551
- offerHex: swap.offerHex,
7254
+ ...covenantOf(swap),
6552
7255
  swapAddress: swap.swapAddress,
6553
7256
  swapPkScript: swap.swapPkScript,
6554
7257
  fundingTxid: swap.fundingTxid,
@@ -6559,6 +7262,20 @@ var restoredOfferRecord = (swap, network, now) => {
6559
7262
  now
6560
7263
  );
6561
7264
  };
7265
+ var reopenedDeposit = (record, fundingTxid) => ({
7266
+ id: fundingTxid,
7267
+ fromAsset: record.give.asset,
7268
+ toAsset: record.take.asset,
7269
+ fromAmount: record.give.amount,
7270
+ toAmount: record.take.amount,
7271
+ swapAddress: record.swapAddress,
7272
+ swapPkScript: record.swapPkScript,
7273
+ ...covenantOf(record),
7274
+ fundingTxid,
7275
+ ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
7276
+ status: record.status,
7277
+ createdAt: record.createdAt * 1e3
7278
+ });
6562
7279
  var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, import_sdk24.asset.AssetId.fromString(id));
6563
7280
  var RESTORED_CORRIDORS = {
6564
7281
  lightning_send: ["arkade", "lightning"],
@@ -6623,12 +7340,13 @@ var cancelSwap = async (input) => {
6623
7340
  if (outcome === "cancelled" || outcome === "filled" || outcome === "needs_recovery") {
6624
7341
  return { outcome };
6625
7342
  }
7343
+ const offer = storedOffer(record);
6626
7344
  const gated2 = withStatus(record, "cancelling", now());
6627
7345
  await repository.saveSwapRecord(gated2);
6628
7346
  drive.ingest(gated2);
6629
7347
  let prepared;
6630
7348
  try {
6631
- prepared = await prepareOfferCancel(wallet, record.offerHex, {
7349
+ prepared = await prepareOfferCancel(wallet, offer, {
6632
7350
  swapAddress: record.swapAddress,
6633
7351
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid }
6634
7352
  });
@@ -6675,7 +7393,7 @@ var cancelSwap = async (input) => {
6675
7393
  return { outcome: "cancelled" };
6676
7394
  };
6677
7395
  var reconcileDepositSpend = async (record, indexer) => {
6678
- const offer = decodeOffer(import_base16.hex.decode(record.offerHex));
7396
+ const offer = storedOffer(record);
6679
7397
  const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
6680
7398
  const all = vtxos ?? [];
6681
7399
  const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
@@ -6763,6 +7481,9 @@ async function pushClaim(operator, input) {
6763
7481
  assertFiniteAmount(funded, "lockup_malformed", "the lockup's summed value");
6764
7482
  if (!input.partiallyClaimed) {
6765
7483
  assertFiniteAmount(input.expectedAmount, "invalid_gate_input", "expectedAmount");
7484
+ if (input.expectedAmount <= 0) {
7485
+ throw gateError("invalid_gate_input", "expectedAmount is not positive");
7486
+ }
6766
7487
  if (funded < input.expectedAmount) {
6767
7488
  throw new LockupAmountMismatchError(input.expectedAmount, funded);
6768
7489
  }
@@ -7855,10 +8576,10 @@ var RfqSwapManager = class _RfqSwapManager {
7855
8576
  return;
7856
8577
  }
7857
8578
  if (!partiallyClaimed) {
7858
- if (!Number.isFinite(swap.expectedAmount)) {
8579
+ if (!Number.isSafeInteger(swap.expectedAmount) || swap.expectedAmount <= 0) {
7859
8580
  return this.block(
7860
8581
  swap,
7861
- `expectedAmount is not a finite number (${String(swap.expectedAmount)}), so the funded value cannot be checked \u2014 refusing to publish the preimage`
8582
+ `expectedAmount is not a positive number of sats (${String(swap.expectedAmount)}), so the funded value cannot be checked \u2014 refusing to publish the preimage`
7862
8583
  );
7863
8584
  }
7864
8585
  const locked = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
@@ -8119,6 +8840,9 @@ var RfqSwapManager = class _RfqSwapManager {
8119
8840
  utxo,
8120
8841
  bump ? { bump } : void 0
8121
8842
  );
8843
+ if (swap.funding?.txid !== utxo.txid || swap.funding.vout !== utxo.vout || swap.funding.amount === void 0) {
8844
+ swap.funding = { txid: utxo.txid, vout: utxo.vout, amount: Number(utxo.amount) };
8845
+ }
8122
8846
  swap.claimTxid = txid;
8123
8847
  swap.claimBroadcastAt = this.config.now();
8124
8848
  delete swap.claimConfirmed;
@@ -8422,7 +9146,7 @@ async function watchOfferSwaps({
8422
9146
  if (candidates.length === 0) return "indeterminate";
8423
9147
  const { txs } = await indexer.getVirtualTxs(candidates);
8424
9148
  return classifyDepositSpend(
8425
- decodeOffer(import_base19.hex.decode(swap.offerHex)),
9149
+ storedOffer(swap),
8426
9150
  operatorPubkey,
8427
9151
  txs.map((psbt) => import_sdk30.Transaction.fromPSBT(import_base19.base64.decode(psbt))),
8428
9152
  { txid: vtxo.txid, vout: vtxo.vout }
@@ -8461,6 +9185,9 @@ async function watchOfferSwaps({
8461
9185
  };
8462
9186
  }
8463
9187
 
9188
+ // src/client/drive.ts
9189
+ init_errors();
9190
+
8464
9191
  // src/client/legacyRecords.ts
8465
9192
  var import_sdk31 = require("@arkade-os/sdk");
8466
9193
  init_repository();
@@ -8532,7 +9259,7 @@ var readLegacyAssetSwaps = async (repository) => {
8532
9259
  };
8533
9260
  var legacyOfferDepositsToAdopt = async (repository) => {
8534
9261
  const unadopted = (await readLegacyAssetSwaps(repository)).filter(
8535
- (swap) => !!swap.offerHex && !!swap.fundingTxid
9262
+ (swap) => (!!swap.offerHex || !!swap.binding) && !!swap.fundingTxid
8536
9263
  );
8537
9264
  if (unadopted.length === 0) return /* @__PURE__ */ new Set();
8538
9265
  const { offer } = splitRecords(await collectSwapRecords(repository));
@@ -8552,6 +9279,7 @@ var SwapDriveRefusedError = class extends Error {
8552
9279
  name = "SwapDriveRefusedError";
8553
9280
  };
8554
9281
  var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
9282
+ var DIRECTED_CANCEL_GRACE_SECONDS = 60;
8555
9283
  var traderClaimTxid2 = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
8556
9284
  var readableRecord = (record) => {
8557
9285
  if (typeof record?.id !== "string" || record.route?.give === void 0) return false;
@@ -8565,7 +9293,7 @@ var readableRecord = (record) => {
8565
9293
  if (record.family === "rfq") {
8566
9294
  return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
8567
9295
  }
8568
- return record.family === "offer" && typeof record.offerHex === "string";
9296
+ return record.family === "offer" && (typeof record.offerHex === "string" || record.binding !== void 0);
8569
9297
  };
8570
9298
  var createSwapDrive = (config) => {
8571
9299
  const { wallet, operator, repository, corridors, indexer } = config;
@@ -8938,11 +9666,15 @@ var createSwapDrive = (config) => {
8938
9666
  const reopened = await legacyOfferDepositsToAdopt(store);
8939
9667
  for (const txid of reopen) reopened.add(txid);
8940
9668
  const cursor = reopened.size === 0 ? scanned : new Set([...scanned].filter((txid) => !reopened.has(txid)));
9669
+ const bound = [...records.values()].flatMap(
9670
+ (record) => record.family === "offer" && record.binding !== void 0 && record.fundingTxid !== void 0 && !RETIRABLE.includes(record.status) ? [reopenedDeposit(record, record.fundingTxid)] : []
9671
+ );
8941
9672
  const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
8942
9673
  operatorPubkey,
8943
9674
  scanned: cursor,
8944
9675
  hrp,
8945
- recoveredIn
9676
+ recoveredIn,
9677
+ reopen: bound
8946
9678
  });
8947
9679
  const { offer } = splitRecords(await collectSwapRecords(store));
8948
9680
  const current = new Map(offer.map((record) => [record.id, record]));
@@ -9034,6 +9766,33 @@ var createSwapDrive = (config) => {
9034
9766
  onUpdate: (swap) => emit(swap.id)
9035
9767
  });
9036
9768
  }
9769
+ if (!lapseTimer) {
9770
+ lapseTimer = setInterval(cancelLapsed, config.pollIntervalMs ?? 5e3);
9771
+ cancelLapsed();
9772
+ }
9773
+ };
9774
+ const lapsing = /* @__PURE__ */ new Set();
9775
+ let lapseTimer;
9776
+ const cancelLapsed = () => {
9777
+ if (disposed || !repository) return;
9778
+ for (const record of records.values()) {
9779
+ if (record.family !== "offer" || record.binding?.taker === void 0 || record.market.kind === "restored" || record.fundingTxid === void 0 || !OFFER_LIVE(record.status) || fundingWasNotSubmitted(record) || now() <= record.expiresAt + DIRECTED_CANCEL_GRACE_SECONDS || lapsing.has(record.id)) {
9780
+ continue;
9781
+ }
9782
+ lapsing.add(record.id);
9783
+ void track(
9784
+ cancelSwap({
9785
+ wallet,
9786
+ repository,
9787
+ record,
9788
+ drive: { ingest: remember },
9789
+ indexer,
9790
+ now
9791
+ }).catch((error) => {
9792
+ console.warn(`[swap] could not cancel lapsed swap ${record.id}`, error);
9793
+ }).finally(() => lapsing.delete(record.id))
9794
+ );
9795
+ }
9037
9796
  };
9038
9797
  const registerRestoredOffers = async (offers2) => {
9039
9798
  if (mode === "readonly") return;
@@ -9172,6 +9931,8 @@ var createSwapDrive = (config) => {
9172
9931
  const stop = async () => {
9173
9932
  await queue;
9174
9933
  await manager.stop();
9934
+ clearInterval(lapseTimer);
9935
+ lapseTimer = void 0;
9175
9936
  watcher?.stop();
9176
9937
  await watcher?.idle();
9177
9938
  watcher = void 0;
@@ -9339,6 +10100,10 @@ var createSwapDrive = (config) => {
9339
10100
  // src/client/quoteOffer.ts
9340
10101
  var import_solver_discovery11 = require("@arkade-os/solver-discovery");
9341
10102
  init_offer();
10103
+ init_errors();
10104
+
10105
+ // src/client/resolve.ts
10106
+ init_errors();
9342
10107
 
9343
10108
  // src/client/market.ts
9344
10109
  var import_solver_discovery10 = require("@arkade-os/solver-discovery");
@@ -9561,224 +10326,8 @@ var pinAmount = (input, takeInstrument) => {
9561
10326
  return void 0;
9562
10327
  };
9563
10328
 
9564
- // src/client/verify.ts
9565
- init_rfq();
9566
-
9567
- // src/client/policy.ts
9568
- var DEFAULT_MAX_REFUND_WINDOW_SECONDS = 30 * 24 * 3600;
9569
-
9570
- // src/client/verify.ts
9571
- var reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
9572
- var CHECK_BY_REASON = {
9573
- invoice_expired: "invoice",
9574
- invoice_undecodable: "invoice",
9575
- invoice_hash_mismatch: "invoice",
9576
- invoice_amount_mismatch: "invoice",
9577
- insufficient_headroom: "refund_window",
9578
- missing_refund_locktime: "refund_window",
9579
- claim_window_too_short: "refund_window",
9580
- confirmations_out_of_range: "refund_window",
9581
- timelock_order: "refund_window",
9582
- quote_malformed: "refund_window"
9583
- };
9584
- var gated = (run, quote) => {
9585
- try {
9586
- run();
9587
- } catch (error) {
9588
- const reason = reasonOf(error);
9589
- if (reason === "quote_expired") {
9590
- throw new QuoteExpired(quote.id, quote.expiresAt, quote.now);
9591
- }
9592
- const check = reason === void 0 ? void 0 : CHECK_BY_REASON[reason];
9593
- if (check === void 0) throw error;
9594
- throw new QuoteVerificationFailed(
9595
- check,
9596
- void 0,
9597
- error instanceof Error ? error.message : String(error),
9598
- { cause: error }
9599
- );
9600
- }
9601
- };
9602
- var verifyResponder = (input) => {
9603
- if (!input.pinnable || input.expected === void 0) {
9604
- throw new QuoteVerificationFailed(
9605
- "responder",
9606
- "a registry-served card naming the solver's discovery key",
9607
- input.expected === void 0 ? "the card names no discovery key" : "the card came out of the local cache, which does not authenticate it"
9608
- );
9609
- }
9610
- if (input.attested === void 0) {
9611
- throw new QuoteVerificationFailed(
9612
- "responder",
9613
- input.expected,
9614
- "the transport attests nobody"
9615
- );
9616
- }
9617
- if (input.attested !== input.expected) {
9618
- throw new QuoteVerificationFailed("responder", input.expected, input.attested);
9619
- }
9620
- };
9621
- var verifyPair = (quoted, requested) => {
9622
- if (quoted !== requested) {
9623
- throw new QuoteVerificationFailed("pair", requested, String(quoted));
9624
- }
9625
- };
9626
- var verifyingDerivation = (derive) => {
9627
- try {
9628
- return derive();
9629
- } catch (error) {
9630
- if (error instanceof AddressMismatch) {
9631
- const derived = Array.isArray(error.derived) ? error.derived.join(", ") : error.derived;
9632
- throw new QuoteVerificationFailed("lockup_address", derived, error.quoted, {
9633
- cause: error
9634
- });
9635
- }
9636
- if (error instanceof Error) {
9637
- throw new QuoteVerificationFailed("lockup_address", void 0, error.message, {
9638
- cause: error
9639
- });
9640
- }
9641
- throw error;
9642
- }
9643
- };
9644
- var verifySendWindow = (input) => {
9645
- gated(
9646
- () => assertFundable({
9647
- quote: input.quote,
9648
- now: input.now,
9649
- ...input.invoiceExpiresAt === void 0 ? {} : { invoiceExpiresAt: input.invoiceExpiresAt },
9650
- ...input.onchain === void 0 ? {} : { onchain: input.onchain }
9651
- }),
9652
- { id: input.quoteId, expiresAt: input.quote.valid_until, now: input.now }
9653
- );
9654
- };
9655
- var verifyReceiveWindow = (input) => {
9656
- gated(
9657
- () => assertReceivable({
9658
- quote: input.quote,
9659
- payDeadline: input.payDeadline,
9660
- now: input.now
9661
- }),
9662
- { id: input.quoteId, expiresAt: input.payDeadline, now: input.now }
9663
- );
9664
- };
9665
- var verifySendInvoice = (input) => {
9666
- const invoiced = input.invoiced;
9667
- if (input.take !== invoiced) {
9668
- throw new QuoteVerificationFailed("invoice", `${invoiced}`, `${input.take}`);
9669
- }
9670
- if (input.give < input.take) {
9671
- throw new QuoteVerificationFailed(
9672
- "invoice",
9673
- `at least the invoice's ${invoiced}`,
9674
- `${input.give}, a negative spread`
9675
- );
9676
- }
9677
- };
9678
- var verifyReceiveInvoiceFacts = (input) => {
9679
- let decoded;
9680
- try {
9681
- decoded = input.decode(input.invoice);
9682
- } catch (cause) {
9683
- throw new QuoteVerificationFailed(
9684
- "invoice",
9685
- "a decodable BOLT11",
9686
- cause instanceof Error ? cause.message : String(cause),
9687
- { cause }
9688
- );
9689
- }
9690
- if (!Number.isFinite(decoded.expiresAt)) {
9691
- throw new QuoteVerificationFailed("invoice", "a finite expiry", `${decoded.expiresAt}`);
9692
- }
9693
- if (!Number.isFinite(input.validUntil)) {
9694
- throw new QuoteVerificationFailed(
9695
- "refund_window",
9696
- "a finite valid_until",
9697
- `${input.validUntil}`
9698
- );
9699
- }
9700
- if (decoded.paymentHash !== input.paymentHash) {
9701
- throw new QuoteVerificationFailed("invoice", input.paymentHash, decoded.paymentHash);
9702
- }
9703
- if (!Number.isSafeInteger(decoded.amountSats) || decoded.amountSats <= 0) {
9704
- throw new QuoteVerificationFailed(
9705
- "invoice",
9706
- `${input.payAmount}`,
9707
- "the invoice names no amount"
9708
- );
9709
- }
9710
- if (BigInt(decoded.amountSats) !== input.payAmount) {
9711
- throw new QuoteVerificationFailed("invoice", `${input.payAmount}`, `${decoded.amountSats}`);
9712
- }
9713
- return { payDeadline: Math.min(decoded.expiresAt, input.validUntil) };
9714
- };
9715
- var verifyQuoteTtl = (input) => {
9716
- const floor = input.floorSeconds ?? 0;
9717
- if (input.expiresAt - input.now <= floor) {
9718
- throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
9719
- }
9720
- };
9721
- var CSV_GRANULARITY_SECONDS = 512;
9722
- var verifyRefundWindow = (input) => {
9723
- const max = input.maxSeconds ?? DEFAULT_MAX_REFUND_WINDOW_SECONDS;
9724
- const window = input.refundLocktime - input.now;
9725
- if (!(window <= max)) {
9726
- throw new QuoteVerificationFailed("refund_window", `at most ${max}s`, `${window}s`);
9727
- }
9728
- const delay = input.refundWithoutReceiverDelay;
9729
- if (delay !== void 0 && !(delay < max + CSV_GRANULARITY_SECONDS)) {
9730
- throw new QuoteVerificationFailed(
9731
- "refund_window",
9732
- `a solo-refund delay of at most ${max}s`,
9733
- `${delay}s`
9734
- );
9735
- }
9736
- };
9737
- var verifyQuotedAmount = (input) => {
9738
- verifyPinnedAmount(input);
9739
- if (input.take > input.give) {
9740
- throw new QuoteVerificationFailed(
9741
- "pair",
9742
- `${input.pair} give >= take`,
9743
- `give=${input.give} take=${input.take}`
9744
- );
9745
- }
9746
- };
9747
- var verifyCrossAssetAmount = (input) => {
9748
- verifyPinnedAmount(input);
9749
- if (input.give <= 0n || input.take <= 0n) {
9750
- throw new QuoteVerificationFailed(
9751
- "pair",
9752
- `${input.pair} give > 0 take > 0`,
9753
- `give=${input.give} take=${input.take}`
9754
- );
9755
- }
9756
- };
9757
- var verifiedCarrierSats = (quote) => {
9758
- try {
9759
- return quoteCarrierSats(quote);
9760
- } catch (error) {
9761
- if (reasonOf(error) !== "carrier_malformed") throw error;
9762
- throw new QuoteVerificationFailed(
9763
- "pair",
9764
- "carrier_sats a non-negative integer",
9765
- String(quote.carrier_sats),
9766
- { cause: error }
9767
- );
9768
- }
9769
- };
9770
- var verifyPinnedAmount = (input) => {
9771
- const quoted = input.pinned.on === "give" ? input.give : input.take;
9772
- if (quoted !== input.pinned.value) {
9773
- throw new QuoteVerificationFailed(
9774
- "pair",
9775
- `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
9776
- `${input.pair} ${input.pinned.on}=${quoted}`
9777
- );
9778
- }
9779
- };
9780
-
9781
10329
  // src/client/quoteOffer.ts
10330
+ init_verify();
9782
10331
  var FEED_TTL_MS = 3e4;
9783
10332
  var feedFetch = (base = fetch) => {
9784
10333
  const at2 = /* @__PURE__ */ new Map();
@@ -9867,12 +10416,12 @@ var verifyPlanLegs = (plan, legs, give) => {
9867
10416
  };
9868
10417
 
9869
10418
  // src/client/quoteRfq.ts
9870
- var import_base22 = require("@scure/base");
10419
+ var import_base23 = require("@scure/base");
9871
10420
  var import_sdk36 = require("@arkade-os/sdk");
9872
10421
  var import_solver_discovery12 = require("@arkade-os/solver-discovery");
9873
10422
 
9874
10423
  // src/jointGraph.ts
9875
- var import_base21 = require("@scure/base");
10424
+ var import_base22 = require("@scure/base");
9876
10425
  var import_sha26 = require("@noble/hashes/sha2.js");
9877
10426
  var import_sdk33 = require("@arkade-os/sdk");
9878
10427
  function digestJointGraph(plan, template) {
@@ -9908,7 +10457,7 @@ function digestJointGraph(plan, template) {
9908
10457
  preimage.set(part, at2);
9909
10458
  at2 += part.length;
9910
10459
  }
9911
- return import_base21.hex.encode((0, import_sha26.sha256)(preimage));
10460
+ return import_base22.hex.encode((0, import_sha26.sha256)(preimage));
9912
10461
  }
9913
10462
  function verifyJointGraph(plan, template) {
9914
10463
  try {
@@ -9936,7 +10485,7 @@ function verifyJointGraph(plan, template) {
9936
10485
  }
9937
10486
  }
9938
10487
  function parseGraphTx(psbt) {
9939
- return import_sdk33.Transaction.fromPSBT(import_base21.base64.decode(psbt));
10488
+ return import_sdk33.Transaction.fromPSBT(import_base22.base64.decode(psbt));
9940
10489
  }
9941
10490
  function deepFreeze(value) {
9942
10491
  if (value !== null && typeof value === "object") {
@@ -9968,8 +10517,10 @@ init_onchainHtlc();
9968
10517
 
9969
10518
  // src/payment/swapRail.ts
9970
10519
  var import_sdk34 = require("@arkade-os/sdk");
10520
+ init_errors();
9971
10521
 
9972
10522
  // src/client/sats.ts
10523
+ init_errors();
9973
10524
  var satsOf = (value, field) => {
9974
10525
  if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
9975
10526
  throw new AmountEncodingUnsupported(
@@ -9985,7 +10536,9 @@ var satsOf = (value, field) => {
9985
10536
  var claimFeeSats = (deps) => BigInt(Math.ceil((deps.claimVsize ?? ONCHAIN_CLAIM_VSIZE) * deps.claimFeeRateSatVb));
9986
10537
 
9987
10538
  // src/client/quoteRfq.ts
10539
+ init_rfq_contract();
9988
10540
  init_rfq();
10541
+ init_errors();
9989
10542
 
9990
10543
  // src/client/rfqWire.ts
9991
10544
  init_rfq();
@@ -10018,6 +10571,7 @@ var parseRfqQuote = (quote) => ({
10018
10571
  });
10019
10572
 
10020
10573
  // src/client/quoteRfq.ts
10574
+ init_verify();
10021
10575
  var lockupOf = (derived) => ({
10022
10576
  address: derived.address,
10023
10577
  script: derived.script,
@@ -10025,12 +10579,12 @@ var lockupOf = (derived) => ({
10025
10579
  });
10026
10580
  var covenantInputs = (input) => {
10027
10581
  const network = (0, import_sdk36.networkFromOperatorInfo)(input.info);
10028
- const arkade4 = input.corridors.get("arkade").deps;
10582
+ const arkade5 = input.corridors.get("arkade").deps;
10029
10583
  return {
10030
- operatorPubkey: (0, import_sdk36.toXOnly)(import_base22.hex.decode(input.info.signerPubkey), "ark signer key"),
10584
+ operatorPubkey: (0, import_sdk36.toXOnly)(import_base23.hex.decode(input.info.signerPubkey), "ark signer key"),
10031
10585
  // The resolved per-network pin, never operator-reported: it lands in a covenant leaf
10032
10586
  // that decides who can move the funds.
10033
- emulatorPubkey: (0, import_sdk36.toXOnly)(import_base22.hex.decode(arkade4.emulatorPubkey), "emulator signer key"),
10587
+ emulatorPubkey: (0, import_sdk36.toXOnly)(import_base23.hex.decode(arkade5.emulatorPubkey), "emulator signer key"),
10034
10588
  claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
10035
10589
  hrp: network.hrp
10036
10590
  };
@@ -10038,7 +10592,7 @@ var covenantInputs = (input) => {
10038
10592
  var sealingKey = (deps) => {
10039
10593
  const configured = deps.covclaimd?.pubkey;
10040
10594
  if (configured === void 0) return void 0;
10041
- const key = import_base22.hex.decode(configured);
10595
+ const key = import_base23.hex.decode(configured);
10042
10596
  if (key.length !== 33) {
10043
10597
  throw new Error(
10044
10598
  `the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
@@ -10094,7 +10648,7 @@ var quoteArkadeAsset = async (input) => {
10094
10648
  receiveAddress,
10095
10649
  maker.pkScript,
10096
10650
  (0, import_sdk36.networkFromOperatorInfo)(input.info).hrp,
10097
- (0, import_sdk36.toXOnly)(import_base22.hex.decode(input.info.signerPubkey), "ark signer key")
10651
+ (0, import_sdk36.toXOnly)(import_base23.hex.decode(input.info.signerPubkey), "ark signer key")
10098
10652
  );
10099
10653
  const choice = payment?.carrier;
10100
10654
  const carrierRequest = choice === void 0 ? void 0 : choice.mode === "purchase" ? { mode: "purchase" } : {
@@ -10106,7 +10660,7 @@ var quoteArkadeAsset = async (input) => {
10106
10660
  if (choice?.mode === "recycleReceiver") {
10107
10661
  if (choice.quote.assetId !== sides.wantAsset?.toString())
10108
10662
  throw new Error("carrier quote assetId differs from requested asset");
10109
- if (choice.quote.senderKey !== import_base22.hex.encode(maker.publicKey))
10663
+ if (choice.quote.senderKey !== import_base23.hex.encode(maker.publicKey))
10110
10664
  throw new Error("carrier quote senderKey differs from wallet identity");
10111
10665
  if (input.now >= choice.quote.expiresAt - 30)
10112
10666
  throw new Error("carrier quote expired before RFQ");
@@ -10137,6 +10691,10 @@ var quoteArkadeAsset = async (input) => {
10137
10691
  );
10138
10692
  verifyPair(wire.pair, pair);
10139
10693
  const parsed = parseRfqQuote(wire);
10694
+ const taker = contractVersion === ASSET_SWAP_V4 ? verifyTaker({
10695
+ attested: input.transport.attestedResponder,
10696
+ solverPubkey: parsed.solver
10697
+ }) : void 0;
10140
10698
  verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
10141
10699
  verifyQuoteTtl({
10142
10700
  quoteId: input.quoteId,
@@ -10168,7 +10726,7 @@ var quoteArkadeAsset = async (input) => {
10168
10726
  if (input.now >= validUntil) throw new Error("asset payment terms lapsed before funding");
10169
10727
  assetPayment = {
10170
10728
  receiveAddress: receiveAddress ?? new import_sdk36.ArkAddress(
10171
- (0, import_sdk36.toXOnly)(import_base22.hex.decode(input.info.signerPubkey), "ark signer key"),
10729
+ (0, import_sdk36.toXOnly)(import_base23.hex.decode(input.info.signerPubkey), "ark signer key"),
10172
10730
  maker.pkScript.slice(2),
10173
10731
  (0, import_sdk36.networkFromOperatorInfo)(input.info).hrp
10174
10732
  ).encode(),
@@ -10182,7 +10740,9 @@ var quoteArkadeAsset = async (input) => {
10182
10740
  const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
10183
10741
  give: input.candidate.give,
10184
10742
  giveAmount: parsed.give,
10185
- ...carrierSats === void 0 ? {} : { carrierSats },
10743
+ // Unconditional: a card charging for the delivered carrier refuses to price without
10744
+ // it whichever leg gives, and a BTC deposit funds none of its own to publish.
10745
+ carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
10186
10746
  ...QUOTE_OPTIONS,
10187
10747
  fetchImpl: input.feed.fetch
10188
10748
  });
@@ -10196,7 +10756,8 @@ var quoteArkadeAsset = async (input) => {
10196
10756
  maker,
10197
10757
  ...receiveAddress === void 0 ? {} : { receiveAddress },
10198
10758
  info: input.info,
10199
- contractVersion
10759
+ contractVersion,
10760
+ ...taker === void 0 ? {} : { taker }
10200
10761
  });
10201
10762
  verifyingDerivation(() => verifyOfferAddress(wire, offer));
10202
10763
  return {
@@ -10346,7 +10907,7 @@ var quoteLightningReceive = async (input) => {
10346
10907
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
10347
10908
  input.wallet.getAddress()
10348
10909
  ]);
10349
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
10910
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10350
10911
  const lightning = input.corridors.get("lightning").deps;
10351
10912
  const sealTo = sealingKey(lightning);
10352
10913
  const sealsAmount = pinned.on === "take" && input.legs.take.assetId === BTC_ASSET_ID;
@@ -10466,7 +11027,7 @@ var quoteOnchainSend = async (input) => {
10466
11027
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
10467
11028
  (0, import_sdk36.provisionRefundKey)(input.wallet)
10468
11029
  ]);
10469
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11030
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10470
11031
  const wire = await input.transport.requestQuote(
10471
11032
  withCanonicalAmount(
10472
11033
  onchainSendRequest({
@@ -10577,7 +11138,7 @@ var quoteOnchainReceive = async (input) => {
10577
11138
  input.wallet.getAddress(),
10578
11139
  input.wallet.getBoardingAddress()
10579
11140
  ]);
10580
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11141
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10581
11142
  const refundPkScript = l1ScriptForAddress(boardingAddress, l1Network);
10582
11143
  const wire = await input.transport.requestQuote(
10583
11144
  withCanonicalAmount(
@@ -10684,6 +11245,7 @@ var quoteOnchainReceive = async (input) => {
10684
11245
 
10685
11246
  // src/client/verbs.ts
10686
11247
  var import_sdk37 = require("@arkade-os/sdk");
11248
+ init_errors();
10687
11249
  var enforceFeeCeiling = (quote, call, policy) => {
10688
11250
  let ceiling;
10689
11251
  for (const [source, limit] of [
@@ -10708,14 +11270,14 @@ var settle = async (deps, input, maxFee) => {
10708
11270
  return deps.accept(quote);
10709
11271
  };
10710
11272
  var pay = async (deps, destination, options = {}) => {
10711
- const arkade4 = (0, import_sdk37.arkTarget)(destination);
10712
- if (arkade4 !== void 0) {
11273
+ const arkade5 = (0, import_sdk37.arkTarget)(destination);
11274
+ if (arkade5 !== void 0) {
10713
11275
  const amount = (0, import_sdk37.resolveSendAmount)(
10714
11276
  "ark",
10715
11277
  destination,
10716
11278
  options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
10717
11279
  );
10718
- return { kind: "payment", txid: await deps.wallet.send({ address: arkade4, amount }) };
11280
+ return { kind: "payment", txid: await deps.wallet.send({ address: arkade5, amount }) };
10719
11281
  }
10720
11282
  const swap = await settle(
10721
11283
  deps,
@@ -10777,7 +11339,7 @@ var nostrTransportFactory = createNostrTransportFactory();
10777
11339
 
10778
11340
  // src/client/client.ts
10779
11341
  var PREPARATIONS_HELD = 64;
10780
- var mintQuoteId = () => import_base23.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
11342
+ var mintQuoteId = () => import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
10781
11343
  var createSwapClient = (config) => {
10782
11344
  const { wallet } = config;
10783
11345
  const operator = config.operator ?? walletOperator(wallet);
@@ -10930,6 +11492,7 @@ var createSwapClient = (config) => {
10930
11492
  return acceptQuote({
10931
11493
  quote,
10932
11494
  ...validUntil === void 0 ? {} : { validUntil },
11495
+ ...options?.attachOfferPacket === false ? { attachOfferPacket: false } : {},
10933
11496
  ...preparation === void 0 ? {} : { preparation },
10934
11497
  wallet,
10935
11498
  repository: config.repository,
@@ -11031,8 +11594,13 @@ var createSwapClient = (config) => {
11031
11594
  return client;
11032
11595
  };
11033
11596
 
11597
+ // src/client/index.ts
11598
+ init_errors();
11599
+ init_policy();
11600
+ init_verify();
11601
+
11034
11602
  // src/reveal.ts
11035
- var import_base24 = require("@scure/base");
11603
+ var import_base25 = require("@scure/base");
11036
11604
  var import_sdk39 = require("@arkade-os/sdk");
11037
11605
  init_claimAmountGate();
11038
11606
  init_claimPacket();
@@ -11060,7 +11628,7 @@ var decodeKey = (value, field) => {
11060
11628
  if (typeof value !== "string") throw new Error(`covclaimd info: ${field} is not a string`);
11061
11629
  let bytes;
11062
11630
  try {
11063
- bytes = import_base24.hex.decode(value);
11631
+ bytes = import_base25.hex.decode(value);
11064
11632
  } catch {
11065
11633
  throw new Error(`covclaimd info: ${field} is not hex`);
11066
11634
  }
@@ -11121,7 +11689,7 @@ var covclaimdClient = (baseUrl, options = {}) => {
11121
11689
  const body = await readJson("info", response);
11122
11690
  return {
11123
11691
  covclaimdPubkey: decodeKey(body?.covclaimd_pub_key, "covclaimd_pub_key"),
11124
- emulatorPubkey: import_base24.hex.encode(decodeKey(body?.emulator_pub_key, "emulator_pub_key"))
11692
+ emulatorPubkey: import_base25.hex.encode(decodeKey(body?.emulator_pub_key, "emulator_pub_key"))
11125
11693
  };
11126
11694
  },
11127
11695
  async reveal(params) {
@@ -11149,13 +11717,13 @@ function revealFieldsFromScript(script) {
11149
11717
  throw new Error("this covenant has no non-interactive claim leaf to reveal against");
11150
11718
  }
11151
11719
  return {
11152
- arkadeScript: import_base24.base64.encode(script.nonInteractiveClaimArkadeScript),
11153
- taptree: import_base24.hex.encode(script.encode())
11720
+ arkadeScript: import_base25.base64.encode(script.nonInteractiveClaimArkadeScript),
11721
+ taptree: import_base25.hex.encode(script.encode())
11154
11722
  };
11155
11723
  }
11156
11724
  async function revealClaimPacket(client, input) {
11157
11725
  const fields = revealFieldsFromScript(input.script);
11158
- if (import_base24.hex.encode(import_sdk39.ArkAddress.decode(input.address).pkScript) !== import_base24.hex.encode(input.script.pkScript)) {
11726
+ if (import_base25.hex.encode(import_sdk39.ArkAddress.decode(input.address).pkScript) !== import_base25.hex.encode(input.script.pkScript)) {
11159
11727
  throw new Error("address does not belong to this covenant");
11160
11728
  }
11161
11729
  assertPreimageMatches(input.preimage, input.script.options.preimageHash);
@@ -11171,7 +11739,7 @@ async function revealClaimPacket(client, input) {
11171
11739
  }
11172
11740
 
11173
11741
  // src/offerFillPlan.ts
11174
- var import_base25 = require("@scure/base");
11742
+ var import_base26 = require("@scure/base");
11175
11743
  var import_sdk40 = require("@arkade-os/sdk");
11176
11744
  init_offer();
11177
11745
  var OFFER_FILL_TEMPLATE = "offer-fill/1";
@@ -11186,8 +11754,9 @@ async function buildOfferFillPlan(wallet, arkServerUrl, offerHex, opts) {
11186
11754
  assetCarrierSats = ASSET_CARRIER_SATS,
11187
11755
  sponsor
11188
11756
  } = opts;
11189
- const offer = decodeOffer(import_base25.hex.decode(offerHex));
11190
- const contract = await connectFillContract(wallet, arkServerUrl, offer, { swapAddress });
11757
+ const target = typeof offerHex === "string" ? decodeOffer(import_base26.hex.decode(offerHex)) : offerHex;
11758
+ const contract = await connectFillContract(wallet, arkServerUrl, target, { swapAddress });
11759
+ const offer = offerOf(target, contract.pkScript);
11191
11760
  const vtxos = await contract.getUtxos();
11192
11761
  const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
11193
11762
  const solverPayout = payoutScript ?? import_sdk40.ArkAddress.decode(await wallet.getAddress()).pkScript;
@@ -11235,7 +11804,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11235
11804
  }
11236
11805
  layout.inputs.forEach((input, i) => {
11237
11806
  const spent = checkpoints[i].getInput(0);
11238
- if (!(spent.txid instanceof Uint8Array) || import_base25.hex.encode(spent.txid) !== input.txid || spent.index !== input.vout) {
11807
+ if (!(spent.txid instanceof Uint8Array) || import_base26.hex.encode(spent.txid) !== input.txid || spent.index !== input.vout) {
11239
11808
  throw new Error(`fill plan checkpoint ${i} does not spend ${input.txid}:${input.vout}`);
11240
11809
  }
11241
11810
  });
@@ -11247,7 +11816,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11247
11816
  }
11248
11817
  layout.outputs.forEach((expected, i) => {
11249
11818
  const out = arkTx.getOutput(i);
11250
- if (!out?.script || import_base25.hex.encode(out.script) !== import_base25.hex.encode(expected.script)) {
11819
+ if (!out?.script || import_base26.hex.encode(out.script) !== import_base26.hex.encode(expected.script)) {
11251
11820
  throw new Error(`fill plan output ${i} is not the ${expected.role} script`);
11252
11821
  }
11253
11822
  if (out.amount !== expected.sats) {
@@ -11261,7 +11830,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11261
11830
  throw new Error(`fill plan output ${payments} is not the extension packet`);
11262
11831
  }
11263
11832
  const anchor = arkTx.getOutput(payments + 1);
11264
- if (!anchor?.script || import_base25.hex.encode(anchor.script) !== import_base25.hex.encode(import_sdk40.P2A.script) || anchor.amount !== import_sdk40.P2A.amount) {
11833
+ if (!anchor?.script || import_base26.hex.encode(anchor.script) !== import_base26.hex.encode(import_sdk40.P2A.script) || anchor.amount !== import_sdk40.P2A.amount) {
11265
11834
  throw new Error(`fill plan output ${payments + 1} is not the anchor`);
11266
11835
  }
11267
11836
  const packet = import_sdk40.Extension.fromTx(arkTx).getAssetPacket();
@@ -11293,8 +11862,8 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11293
11862
  );
11294
11863
  }
11295
11864
  }
11296
- const arkTxPsbt = import_base25.base64.encode(arkTx.toPSBT());
11297
- const checkpointPsbts = checkpoints.map((c) => import_base25.base64.encode(c.toPSBT()));
11865
+ const arkTxPsbt = import_base26.base64.encode(arkTx.toPSBT());
11866
+ const checkpointPsbts = checkpoints.map((c) => import_base26.base64.encode(c.toPSBT()));
11298
11867
  const inputOwners = layout.inputs.map((input) => input.owner);
11299
11868
  const graph = {
11300
11869
  arkTx: arkTxPsbt,
@@ -11315,7 +11884,7 @@ function verifyOfferFillPlan(plan) {
11315
11884
  }
11316
11885
 
11317
11886
  // src/evmRfq.ts
11318
- var import_base26 = require("@scure/base");
11887
+ var import_base27 = require("@scure/base");
11319
11888
  init_rfq();
11320
11889
  var EVM_CHAIN = "ethereum";
11321
11890
  var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
@@ -11380,7 +11949,7 @@ var evmSendRequest = (input) => {
11380
11949
  payment_hash: input.paymentHash,
11381
11950
  evm_claim_address: assertEvmAddress(input.evmClaimAddress, "evmClaimAddress"),
11382
11951
  refund_address: input.refundAddress,
11383
- client_refund_pubkey: import_base26.hex.encode(input.senderPubkey)
11952
+ client_refund_pubkey: import_base27.hex.encode(input.senderPubkey)
11384
11953
  }
11385
11954
  };
11386
11955
  };
@@ -11404,7 +11973,7 @@ var evmReceiveRequest = (input) => {
11404
11973
  evm_timeout_block: input.evmTimeoutBlock,
11405
11974
  evm_refund_address: assertEvmAddress(input.evmRefundAddress, "evmRefundAddress"),
11406
11975
  payout_address: input.payoutAddress,
11407
- payout_pubkey: import_base26.hex.encode(input.payoutPubkey)
11976
+ payout_pubkey: import_base27.hex.encode(input.payoutPubkey)
11408
11977
  }
11409
11978
  };
11410
11979
  };
@@ -11696,6 +12265,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
11696
12265
  recordInstrument,
11697
12266
  recordLeg,
11698
12267
  recordOutcome,
12268
+ reopenedDeposit,
11699
12269
  resolveCorridorBase,
11700
12270
  resolveCorridorDeps,
11701
12271
  resolveRoute,
@@ -11732,6 +12302,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
11732
12302
  verifyResponder,
11733
12303
  verifySendInvoice,
11734
12304
  verifySendWindow,
12305
+ verifyTaker,
11735
12306
  verifyingDerivation,
11736
12307
  walletLockupIndexer,
11737
12308
  withCanonicalAmount,