@arkade-os/swap 0.1.9 → 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 +1097 -541
  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-FQNG4XMF.js → chunk-2HQZLIVX.js} +98 -37
  6. package/dist/{chunk-5QPJWOCN.js → chunk-6RJVT65W.js} +2 -0
  7. package/dist/chunk-AUJDREZN.js +445 -0
  8. package/dist/{chunk-I7WEXXZX.js → chunk-FWRDAL73.js} +157 -477
  9. package/dist/{chunk-552GDPBU.js → chunk-LCO6AJOS.js} +433 -59
  10. package/dist/index.cjs +1083 -530
  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 +1054 -175
  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 },
@@ -2547,7 +2921,7 @@ var init_rfq = __esm({
2547
2921
  const version = selected ?? ASSET_SWAP_BASELINE;
2548
2922
  if (!advertised.includes(version)) {
2549
2923
  throw new Error(
2550
- `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(", ")}`
2551
2925
  );
2552
2926
  }
2553
2927
  return { quote, rfqId: sent.rfq_id, contractVersion: assetSwapContractVersion(version) };
@@ -2727,6 +3101,191 @@ var init_rfq = __esm({
2727
3101
  }
2728
3102
  });
2729
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
+
2730
3289
  // src/closeOnceWebSocket.ts
2731
3290
  var CloseOnceWebSocket;
2732
3291
  var init_closeOnceWebSocket = __esm({
@@ -2926,6 +3485,7 @@ var init_nostr = __esm({
2926
3485
  { kinds: [RFQ_DIRECTED_KIND], "#p": [pubkey], authors: [solverPubkey] },
2927
3486
  {
2928
3487
  onevent(event) {
3488
+ if (event.pubkey !== solverPubkey || !(0, import_nostr_tools2.verifyEvent)(event)) return;
2929
3489
  let payload;
2930
3490
  try {
2931
3491
  payload = JSON.parse(import_nostr_tools2.nip44.v2.decrypt(event.content, conversationKey));
@@ -3099,6 +3659,245 @@ var init_nostr = __esm({
3099
3659
  }
3100
3660
  });
3101
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
+
3102
3901
  // src/advanced.ts
3103
3902
  var advanced_exports = {};
3104
3903
  __export(advanced_exports, {
@@ -3253,6 +4052,7 @@ __export(advanced_exports, {
3253
4052
  recordInstrument: () => recordInstrument,
3254
4053
  recordLeg: () => recordLeg,
3255
4054
  recordOutcome: () => recordOutcome,
4055
+ reopenedDeposit: () => reopenedDeposit,
3256
4056
  resolveCorridorBase: () => resolveCorridorBase,
3257
4057
  resolveCorridorDeps: () => resolveCorridorDeps,
3258
4058
  resolveRoute: () => resolveRoute,
@@ -3289,6 +4089,7 @@ __export(advanced_exports, {
3289
4089
  verifyResponder: () => verifyResponder,
3290
4090
  verifySendInvoice: () => verifySendInvoice,
3291
4091
  verifySendWindow: () => verifySendWindow,
4092
+ verifyTaker: () => verifyTaker,
3292
4093
  verifyingDerivation: () => verifyingDerivation,
3293
4094
  walletLockupIndexer: () => walletLockupIndexer,
3294
4095
  withCanonicalAmount: () => withCanonicalAmount,
@@ -3657,187 +4458,7 @@ var issuanceOf = (id) => {
3657
4458
  // src/client/aliases.ts
3658
4459
  var import_solver_discovery2 = require("@arkade-os/solver-discovery");
3659
4460
  init_store();
3660
-
3661
- // src/client/errors.ts
3662
- init_rfq();
3663
- var AmbiguousDestination = class extends Error {
3664
- constructor(destination, detail) {
3665
- super(`cannot route ${JSON.stringify(destination)}: ${detail}`);
3666
- this.destination = destination;
3667
- }
3668
- destination;
3669
- name = "AmbiguousDestination";
3670
- };
3671
- var UnsupportedRoute = class extends Error {
3672
- name = "UnsupportedRoute";
3673
- give;
3674
- take;
3675
- constructor(detail, corridors = {}) {
3676
- super(`unsupported route: ${detail}`);
3677
- this.give = corridors.give;
3678
- this.take = corridors.take;
3679
- }
3680
- };
3681
- var DiscoverySnapshotUnavailable = class extends Error {
3682
- constructor(network, detail) {
3683
- super(`cannot resolve on ${network} offline: ${detail}`);
3684
- this.network = network;
3685
- }
3686
- network;
3687
- name = "DiscoverySnapshotUnavailable";
3688
- };
3689
- var AmountMismatch = class extends Error {
3690
- constructor(sources) {
3691
- super(`exactly one amount may be pinned; got ${sources[0]} and ${sources[1]}`);
3692
- this.sources = sources;
3693
- }
3694
- sources;
3695
- name = "AmountMismatch";
3696
- };
3697
- var AmountEncodingUnsupported = class extends Error {
3698
- constructor(field, value, detail, options) {
3699
- super(`${field}: ${detail}`, options);
3700
- this.field = field;
3701
- this.value = value;
3702
- }
3703
- field;
3704
- value;
3705
- name = "AmountEncodingUnsupported";
3706
- };
3707
- var QuoteVerificationFailed = class extends Error {
3708
- constructor(check, expected, actual, options) {
3709
- super(`quote failed the ${check} check \u2014 refusing to fund`, options);
3710
- this.check = check;
3711
- this.expected = expected;
3712
- this.actual = actual;
3713
- }
3714
- check;
3715
- name = "QuoteVerificationFailed";
3716
- expected;
3717
- actual;
3718
- };
3719
- var QuoteExpired = class extends Error {
3720
- constructor(quoteId, expiresAt, now) {
3721
- super(`quote ${quoteId} expired at ${expiresAt}, ${now - expiresAt} ago`);
3722
- this.quoteId = quoteId;
3723
- this.expiresAt = expiresAt;
3724
- this.now = now;
3725
- }
3726
- quoteId;
3727
- expiresAt;
3728
- now;
3729
- name = "QuoteExpired";
3730
- };
3731
- var MaxFeeExceeded = class extends Error {
3732
- constructor(quoteId, asset8, fee, maxFee) {
3733
- super(`fee ${fee} of ${asset8} exceeds the ${maxFee} ceiling`);
3734
- this.quoteId = quoteId;
3735
- this.asset = asset8;
3736
- this.fee = fee;
3737
- this.maxFee = maxFee;
3738
- }
3739
- quoteId;
3740
- asset;
3741
- fee;
3742
- maxFee;
3743
- name = "MaxFeeExceeded";
3744
- };
3745
- var InsufficientFunds = class extends Error {
3746
- constructor(asset8, required, available) {
3747
- super(
3748
- `funding needs ${required} of ${asset8}` + (available === void 0 ? "" : `, wallet holds ${available}`)
3749
- );
3750
- this.asset = asset8;
3751
- this.required = required;
3752
- this.available = available;
3753
- }
3754
- asset;
3755
- required;
3756
- name = "InsufficientFunds";
3757
- available;
3758
- };
3759
- var AcceptConflict = class extends Error {
3760
- constructor(quoteId, swapId, fields) {
3761
- super(`accept ${quoteId} conflicts with swap ${swapId} on ${fields.join(", ")}`);
3762
- this.quoteId = quoteId;
3763
- this.swapId = swapId;
3764
- this.fields = fields;
3765
- }
3766
- quoteId;
3767
- swapId;
3768
- fields;
3769
- name = "AcceptConflict";
3770
- };
3771
- var ClientDisposed = class extends Error {
3772
- constructor(method) {
3773
- super(`${method}() called after the client was disposed`);
3774
- this.method = method;
3775
- }
3776
- method;
3777
- name = "ClientDisposed";
3778
- };
3779
- var NotCancellable = class extends Error {
3780
- constructor(swapId) {
3781
- super(`swap ${swapId} is not a cancellable asset swap`);
3782
- this.swapId = swapId;
3783
- }
3784
- swapId;
3785
- name = "NotCancellable";
3786
- };
3787
- var InconsistentRoute = class extends Error {
3788
- constructor(asset8, destination) {
3789
- super(`destination ${JSON.stringify(destination)} is not on ${asset8}'s chain`);
3790
- this.asset = asset8;
3791
- this.destination = destination;
3792
- }
3793
- asset;
3794
- destination;
3795
- name = "InconsistentRoute";
3796
- };
3797
- var OperatorUnreachable = class extends Error {
3798
- name = "OperatorUnreachable";
3799
- constructor(detail, options) {
3800
- super(`cannot derive a covenant: ${detail}`, options);
3801
- }
3802
- };
3803
- var MissingCorridorDep = class extends Error {
3804
- constructor(corridor, dep) {
3805
- super(`the ${corridor} corridor has no ${dep}`);
3806
- this.corridor = corridor;
3807
- this.dep = dep;
3808
- }
3809
- corridor;
3810
- dep;
3811
- name = "MissingCorridorDep";
3812
- };
3813
- var SWAP_ERRORS = {
3814
- AmbiguousDestination,
3815
- UnsupportedRoute,
3816
- DiscoverySnapshotUnavailable,
3817
- AmountMismatch,
3818
- AmountEncodingUnsupported,
3819
- QuoteVerificationFailed,
3820
- SwapRefusal,
3821
- QuoteExpired,
3822
- MaxFeeExceeded,
3823
- InsufficientFunds,
3824
- AcceptConflict,
3825
- ClientDisposed,
3826
- NotCancellable,
3827
- InconsistentRoute,
3828
- OperatorUnreachable,
3829
- MissingCorridorDep
3830
- };
3831
- var SWAP_ERROR_NAMES = Object.keys(SWAP_ERRORS);
3832
- function isSwapError(e, name) {
3833
- if (!(e instanceof Error)) return false;
3834
- const table = SWAP_ERRORS;
3835
- const ctor = table[e.name];
3836
- if (ctor === void 0 || !(e instanceof ctor)) return false;
3837
- return name === void 0 || e.name === name;
3838
- }
3839
-
3840
- // src/client/aliases.ts
4461
+ init_errors();
3841
4462
  var toDiscoveryLeg = (id) => {
3842
4463
  const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
3843
4464
  const asset8 = `${assetNamespace}:${assetReference}`;
@@ -4624,8 +5245,12 @@ var ACTIVITY_TOKEN = {
4624
5245
  failed: "failed"
4625
5246
  };
4626
5247
 
5248
+ // src/client/accept.ts
5249
+ init_errors();
5250
+
4627
5251
  // src/client/rfqAmount.ts
4628
5252
  var import_solver_discovery5 = require("@arkade-os/solver-discovery");
5253
+ init_errors();
4629
5254
  var toRfqAmountSide = (on) => on === "give" ? "from" : "to";
4630
5255
  var fromRfqAmountSide = (side) => side === "from" ? "give" : "take";
4631
5256
  var encodeRfqAmount = (value, field) => {
@@ -4876,7 +5501,8 @@ var acceptQuoteBody = async (input) => {
4876
5501
  }
4877
5502
  const funds = fundsFromWallet(quote.route);
4878
5503
  if (funds) await assertFundable2(wallet, quote);
4879
- 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;
4880
5506
  await repository.saveSwapRecord(record);
4881
5507
  if (!funds) return answer(record);
4882
5508
  return answer(
@@ -4896,7 +5522,7 @@ var acceptQuoteBody = async (input) => {
4896
5522
  var registeredOfferRecord = async (input, preparation) => {
4897
5523
  const { quote, wallet, corridors, now } = input;
4898
5524
  const { plan } = preparation;
4899
- const arkade4 = corridors.get("arkade").deps;
5525
+ const arkade5 = corridors.get("arkade").deps;
4900
5526
  const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
4901
5527
  const offer = await createOffer(
4902
5528
  wallet,
@@ -4904,7 +5530,7 @@ var registeredOfferRecord = async (input, preparation) => {
4904
5530
  // Keyed on the receive side: the covenant binds what the fill delivers.
4905
5531
  wantAmount: plan.receive.atomic,
4906
5532
  ...receiveIsBtc ? { offerAsset: import_sdk14.asset.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: import_sdk14.asset.AssetId.fromString(plan.receive.asset.id) },
4907
- emulatorPubkey: arkade4.emulatorPubkey
5533
+ emulatorPubkey: arkade5.emulatorPubkey
4908
5534
  },
4909
5535
  { coverageId: quote.id }
4910
5536
  );
@@ -4932,7 +5558,9 @@ var registeredAssetRecord = async (input, preparation) => {
4932
5558
  ...preparation.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(preparation.assetPayment) },
4933
5559
  family: "offer",
4934
5560
  status: "pending",
4935
- 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) },
4936
5564
  swapAddress: preparation.offer.address,
4937
5565
  swapPkScript: import_base9.hex.encode(preparation.offer.swapPkScript),
4938
5566
  ...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
@@ -5017,7 +5645,7 @@ var fund = async (input, record) => {
5017
5645
  { assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
5018
5646
  ]
5019
5647
  },
5020
- extensions: [offerExtensionOf(record)]
5648
+ ...record.attachOfferPacket === false ? {} : { extensions: [offerExtensionOf(record)] }
5021
5649
  });
5022
5650
  }
5023
5651
  if (record.kind === "lightning_receive" || record.kind === "onchain_receive") {
@@ -5028,10 +5656,13 @@ var fund = async (input, record) => {
5028
5656
  amount: toSafeNumber(fromAtomicDecimal(record.give.amount), "give.amount")
5029
5657
  });
5030
5658
  };
5031
- var offerExtensionOf = (record) => ({
5032
- type: OFFER_PACKET_TYPE,
5033
- payload: import_base9.hex.decode(record.offerHex)
5034
- });
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
+ };
5035
5666
  var reconcileFunding = async (input, record) => {
5036
5667
  const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
5037
5668
  const expected = BigInt(record.give.amount);
@@ -5145,7 +5776,7 @@ var scopedToRail = (table, rail) => ({
5145
5776
  });
5146
5777
 
5147
5778
  // src/client/client.ts
5148
- var import_base23 = require("@scure/base");
5779
+ var import_base24 = require("@scure/base");
5149
5780
  var import_sdk38 = require("@arkade-os/sdk");
5150
5781
  init_repository();
5151
5782
 
@@ -5382,6 +6013,7 @@ var REFUND_MTP_LAG_SECONDS = 2 * 60 * 60;
5382
6013
 
5383
6014
  // src/client/corridors/registry.ts
5384
6015
  var import_sdk19 = require("@arkade-os/sdk");
6016
+ init_errors();
5385
6017
 
5386
6018
  // src/client/corridors/arkade.ts
5387
6019
  var import_sdk16 = require("@arkade-os/sdk");
@@ -5465,6 +6097,7 @@ var chainSourceFrom = (provider, network) => {
5465
6097
  // src/client/corridors/deps.ts
5466
6098
  init_onchainHtlc();
5467
6099
  init_rfq();
6100
+ init_errors();
5468
6101
 
5469
6102
  // src/client/corridors/bolt11.ts
5470
6103
  var import_light_bolt11_decoder = __toESM(require("light-bolt11-decoder"), 1);
@@ -5843,6 +6476,7 @@ var undeliveredCarry = (fresh, undelivered, cached) => {
5843
6476
  };
5844
6477
 
5845
6478
  // src/client/discovery.ts
6479
+ init_errors();
5846
6480
  var REGISTRY_URL = {
5847
6481
  bitcoin: "https://arkade-os.github.io/solver-registry/bitcoin.json",
5848
6482
  signet: "https://arkade-os.github.io/solver-registry/signet.json",
@@ -5999,6 +6633,9 @@ var discoveryIndex = (input) => {
5999
6633
  return { peek, load };
6000
6634
  };
6001
6635
 
6636
+ // src/client/client.ts
6637
+ init_errors();
6638
+
6002
6639
  // src/client/cancel.ts
6003
6640
  var import_base16 = require("@scure/base");
6004
6641
  var import_sdk25 = require("@arkade-os/sdk");
@@ -6046,8 +6683,16 @@ var unscannedSwapCandidates = (txs, existingIds, scanned) => txs.filter(
6046
6683
  function classifySpend(offer, operatorPubkey, spendTx, deposit) {
6047
6684
  let leaves;
6048
6685
  try {
6049
- const script = offerContract(offer, operatorPubkey);
6050
- 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
+ }
6051
6696
  leaves = {
6052
6697
  // `exit` is absent on an offer with no exit closure, and drops out here
6053
6698
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
@@ -6076,21 +6721,56 @@ function classifyDepositSpend(offer, operatorPubkey, spendTxs, deposit) {
6076
6721
  }
6077
6722
  return "indeterminate";
6078
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
+ });
6079
6757
  async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6080
6758
  const {
6081
6759
  operatorPubkey,
6082
6760
  scanned = /* @__PURE__ */ new Set(),
6083
6761
  reopen = [],
6084
6762
  hrp,
6085
- recoveredIn = /* @__PURE__ */ new Set()
6763
+ recoveredIn = /* @__PURE__ */ new Set(),
6764
+ sources = [packetRecoverySource(indexer)]
6086
6765
  } = opts;
6087
6766
  const reopened = [];
6088
6767
  for (const swap of reopen) {
6089
6768
  try {
6769
+ const source = storedOffer(swap);
6090
6770
  reopened.push({
6091
6771
  fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
6092
- offer: decodeOffer(import_base13.hex.decode(swap.offerHex)),
6093
- offerHex: swap.offerHex,
6772
+ offer: "version" in source ? offerFromBinding(source) : source,
6773
+ source,
6094
6774
  existing: swap
6095
6775
  });
6096
6776
  } catch {
@@ -6104,29 +6784,40 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6104
6784
  return { restored: [], scannedTxids: [] };
6105
6785
  }
6106
6786
  const byTxid = new Map(candidates.map((tx) => [tx.redeemTxid, tx]));
6107
- const parsedByTxid = await fetchParsedTxs(
6108
- indexer,
6109
- candidates.map((tx) => tx.redeemTxid)
6110
- );
6111
- const fetchedTxids = [];
6787
+ const candidateTxids = candidates.map((tx) => tx.redeemTxid);
6112
6788
  const found = [...reopened];
6113
- for (const [txid, parsed] of parsedByTxid) {
6114
- const fundingTx = byTxid.get(txid);
6115
- if (!fundingTx) continue;
6116
- 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;
6117
6793
  try {
6118
- const packet = import_sdk22.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
6119
- if (!packet) continue;
6120
- const payload = packet.serialize();
6121
- found.push({
6122
- fundingTx,
6123
- offer: decodeOffer(payload),
6124
- offerHex: import_base13.hex.encode(payload)
6125
- });
6126
- } 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 });
6127
6817
  }
6128
6818
  }
6129
- 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 };
6130
6821
  const scripts = [...new Set(found.map((f) => import_base13.hex.encode(f.offer.swapPkScript)))];
6131
6822
  const { vtxos } = await indexer.getVtxos({ scripts });
6132
6823
  const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
@@ -6147,7 +6838,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6147
6838
  const spendTxByTxid = await fetchParsedTxs(indexer, [...spendTxids]);
6148
6839
  const restored = [];
6149
6840
  const unresolved = /* @__PURE__ */ new Set();
6150
- for (const { fundingTx, offer, offerHex, existing } of found) {
6841
+ for (const { fundingTx, offer, source, offerHex, existing } of found) {
6151
6842
  const swapPkScript = import_base13.hex.encode(offer.swapPkScript);
6152
6843
  const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
6153
6844
  if (!vtxo) {
@@ -6176,7 +6867,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6176
6867
  } else if (vtxo.isSwept && !vtxo.isSpent) status = "recoverable";
6177
6868
  else if (vtxo.isSpent) {
6178
6869
  const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
6179
- const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
6870
+ const kind = classifyDepositSpend(source, operatorPubkey, spendTxs, {
6180
6871
  txid: vtxo.txid,
6181
6872
  vout: vtxo.vout
6182
6873
  });
@@ -6192,20 +6883,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6192
6883
  restored.push({ ...existing, status, spentTxid, ...completion });
6193
6884
  continue;
6194
6885
  }
6886
+ if (!("version" in source)) continue;
6195
6887
  let swapAddress = "";
6196
6888
  try {
6197
- const compiled = offerContract(offer, operatorPubkey);
6198
- if (import_base13.hex.encode(compiled.pkScript) !== swapPkScript) {
6199
- unresolved.add(fundingTx.redeemTxid);
6200
- continue;
6201
- }
6202
6889
  if (hrp !== void 0) {
6203
- 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();
6204
6893
  }
6205
6894
  } catch {
6206
6895
  unresolved.add(fundingTx.redeemTxid);
6207
6896
  continue;
6208
6897
  }
6898
+ const covenant = source.taker === void 0 ? { offerHex: offerHex ?? import_base13.hex.encode(encodeOffer(offer)) } : { binding: recordOfferBinding(source) };
6209
6899
  restored.push({
6210
6900
  id: fundingTx.redeemTxid,
6211
6901
  fromAsset,
@@ -6214,7 +6904,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6214
6904
  toAmount: offer.wantAmount.toString(),
6215
6905
  swapAddress,
6216
6906
  swapPkScript,
6217
- offerHex,
6907
+ ...covenant,
6218
6908
  fundingTxid: fundingTx.redeemTxid,
6219
6909
  spentTxid,
6220
6910
  status,
@@ -6222,7 +6912,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6222
6912
  ...completion
6223
6913
  });
6224
6914
  }
6225
- return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
6915
+ return { restored, scannedTxids: answered.filter((id) => !unresolved.has(id)) };
6226
6916
  }
6227
6917
 
6228
6918
  // src/client/cancel.ts
@@ -6481,11 +7171,15 @@ var corridorRecordStore = (repository, onRecord = () => {
6481
7171
  }
6482
7172
  };
6483
7173
  };
7174
+ var covenantOf = (swap) => ({
7175
+ ...swap.offerHex === void 0 ? {} : { offerHex: swap.offerHex },
7176
+ ...swap.binding === void 0 ? {} : { binding: swap.binding }
7177
+ });
6484
7178
  var offerFactsOf = (record) => ({
6485
7179
  id: record.id,
6486
7180
  coverageId: record.id,
6487
7181
  status: record.status,
6488
- offerHex: record.offerHex,
7182
+ ...covenantOf(record),
6489
7183
  swapPkScript: record.swapPkScript,
6490
7184
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
6491
7185
  ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
@@ -6557,7 +7251,7 @@ var restoredOfferRecord = (swap, network, now) => {
6557
7251
  market: { kind: "restored", backend: "feed" },
6558
7252
  expiresAt: createdAt,
6559
7253
  status: swap.status,
6560
- offerHex: swap.offerHex,
7254
+ ...covenantOf(swap),
6561
7255
  swapAddress: swap.swapAddress,
6562
7256
  swapPkScript: swap.swapPkScript,
6563
7257
  fundingTxid: swap.fundingTxid,
@@ -6568,6 +7262,20 @@ var restoredOfferRecord = (swap, network, now) => {
6568
7262
  now
6569
7263
  );
6570
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
+ });
6571
7279
  var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, import_sdk24.asset.AssetId.fromString(id));
6572
7280
  var RESTORED_CORRIDORS = {
6573
7281
  lightning_send: ["arkade", "lightning"],
@@ -6632,12 +7340,13 @@ var cancelSwap = async (input) => {
6632
7340
  if (outcome === "cancelled" || outcome === "filled" || outcome === "needs_recovery") {
6633
7341
  return { outcome };
6634
7342
  }
7343
+ const offer = storedOffer(record);
6635
7344
  const gated2 = withStatus(record, "cancelling", now());
6636
7345
  await repository.saveSwapRecord(gated2);
6637
7346
  drive.ingest(gated2);
6638
7347
  let prepared;
6639
7348
  try {
6640
- prepared = await prepareOfferCancel(wallet, record.offerHex, {
7349
+ prepared = await prepareOfferCancel(wallet, offer, {
6641
7350
  swapAddress: record.swapAddress,
6642
7351
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid }
6643
7352
  });
@@ -6684,7 +7393,7 @@ var cancelSwap = async (input) => {
6684
7393
  return { outcome: "cancelled" };
6685
7394
  };
6686
7395
  var reconcileDepositSpend = async (record, indexer) => {
6687
- const offer = decodeOffer(import_base16.hex.decode(record.offerHex));
7396
+ const offer = storedOffer(record);
6688
7397
  const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
6689
7398
  const all = vtxos ?? [];
6690
7399
  const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
@@ -8437,7 +9146,7 @@ async function watchOfferSwaps({
8437
9146
  if (candidates.length === 0) return "indeterminate";
8438
9147
  const { txs } = await indexer.getVirtualTxs(candidates);
8439
9148
  return classifyDepositSpend(
8440
- decodeOffer(import_base19.hex.decode(swap.offerHex)),
9149
+ storedOffer(swap),
8441
9150
  operatorPubkey,
8442
9151
  txs.map((psbt) => import_sdk30.Transaction.fromPSBT(import_base19.base64.decode(psbt))),
8443
9152
  { txid: vtxo.txid, vout: vtxo.vout }
@@ -8476,6 +9185,9 @@ async function watchOfferSwaps({
8476
9185
  };
8477
9186
  }
8478
9187
 
9188
+ // src/client/drive.ts
9189
+ init_errors();
9190
+
8479
9191
  // src/client/legacyRecords.ts
8480
9192
  var import_sdk31 = require("@arkade-os/sdk");
8481
9193
  init_repository();
@@ -8547,7 +9259,7 @@ var readLegacyAssetSwaps = async (repository) => {
8547
9259
  };
8548
9260
  var legacyOfferDepositsToAdopt = async (repository) => {
8549
9261
  const unadopted = (await readLegacyAssetSwaps(repository)).filter(
8550
- (swap) => !!swap.offerHex && !!swap.fundingTxid
9262
+ (swap) => (!!swap.offerHex || !!swap.binding) && !!swap.fundingTxid
8551
9263
  );
8552
9264
  if (unadopted.length === 0) return /* @__PURE__ */ new Set();
8553
9265
  const { offer } = splitRecords(await collectSwapRecords(repository));
@@ -8567,6 +9279,7 @@ var SwapDriveRefusedError = class extends Error {
8567
9279
  name = "SwapDriveRefusedError";
8568
9280
  };
8569
9281
  var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
9282
+ var DIRECTED_CANCEL_GRACE_SECONDS = 60;
8570
9283
  var traderClaimTxid2 = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
8571
9284
  var readableRecord = (record) => {
8572
9285
  if (typeof record?.id !== "string" || record.route?.give === void 0) return false;
@@ -8580,7 +9293,7 @@ var readableRecord = (record) => {
8580
9293
  if (record.family === "rfq") {
8581
9294
  return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
8582
9295
  }
8583
- return record.family === "offer" && typeof record.offerHex === "string";
9296
+ return record.family === "offer" && (typeof record.offerHex === "string" || record.binding !== void 0);
8584
9297
  };
8585
9298
  var createSwapDrive = (config) => {
8586
9299
  const { wallet, operator, repository, corridors, indexer } = config;
@@ -8953,11 +9666,15 @@ var createSwapDrive = (config) => {
8953
9666
  const reopened = await legacyOfferDepositsToAdopt(store);
8954
9667
  for (const txid of reopen) reopened.add(txid);
8955
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
+ );
8956
9672
  const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
8957
9673
  operatorPubkey,
8958
9674
  scanned: cursor,
8959
9675
  hrp,
8960
- recoveredIn
9676
+ recoveredIn,
9677
+ reopen: bound
8961
9678
  });
8962
9679
  const { offer } = splitRecords(await collectSwapRecords(store));
8963
9680
  const current = new Map(offer.map((record) => [record.id, record]));
@@ -9049,6 +9766,33 @@ var createSwapDrive = (config) => {
9049
9766
  onUpdate: (swap) => emit(swap.id)
9050
9767
  });
9051
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
+ }
9052
9796
  };
9053
9797
  const registerRestoredOffers = async (offers2) => {
9054
9798
  if (mode === "readonly") return;
@@ -9187,6 +9931,8 @@ var createSwapDrive = (config) => {
9187
9931
  const stop = async () => {
9188
9932
  await queue;
9189
9933
  await manager.stop();
9934
+ clearInterval(lapseTimer);
9935
+ lapseTimer = void 0;
9190
9936
  watcher?.stop();
9191
9937
  await watcher?.idle();
9192
9938
  watcher = void 0;
@@ -9354,6 +10100,10 @@ var createSwapDrive = (config) => {
9354
10100
  // src/client/quoteOffer.ts
9355
10101
  var import_solver_discovery11 = require("@arkade-os/solver-discovery");
9356
10102
  init_offer();
10103
+ init_errors();
10104
+
10105
+ // src/client/resolve.ts
10106
+ init_errors();
9357
10107
 
9358
10108
  // src/client/market.ts
9359
10109
  var import_solver_discovery10 = require("@arkade-os/solver-discovery");
@@ -9576,224 +10326,8 @@ var pinAmount = (input, takeInstrument) => {
9576
10326
  return void 0;
9577
10327
  };
9578
10328
 
9579
- // src/client/verify.ts
9580
- init_rfq();
9581
-
9582
- // src/client/policy.ts
9583
- var DEFAULT_MAX_REFUND_WINDOW_SECONDS = 30 * 24 * 3600;
9584
-
9585
- // src/client/verify.ts
9586
- var reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
9587
- var CHECK_BY_REASON = {
9588
- invoice_expired: "invoice",
9589
- invoice_undecodable: "invoice",
9590
- invoice_hash_mismatch: "invoice",
9591
- invoice_amount_mismatch: "invoice",
9592
- insufficient_headroom: "refund_window",
9593
- missing_refund_locktime: "refund_window",
9594
- claim_window_too_short: "refund_window",
9595
- confirmations_out_of_range: "refund_window",
9596
- timelock_order: "refund_window",
9597
- quote_malformed: "refund_window"
9598
- };
9599
- var gated = (run, quote) => {
9600
- try {
9601
- run();
9602
- } catch (error) {
9603
- const reason = reasonOf(error);
9604
- if (reason === "quote_expired") {
9605
- throw new QuoteExpired(quote.id, quote.expiresAt, quote.now);
9606
- }
9607
- const check = reason === void 0 ? void 0 : CHECK_BY_REASON[reason];
9608
- if (check === void 0) throw error;
9609
- throw new QuoteVerificationFailed(
9610
- check,
9611
- void 0,
9612
- error instanceof Error ? error.message : String(error),
9613
- { cause: error }
9614
- );
9615
- }
9616
- };
9617
- var verifyResponder = (input) => {
9618
- if (!input.pinnable || input.expected === void 0) {
9619
- throw new QuoteVerificationFailed(
9620
- "responder",
9621
- "a registry-served card naming the solver's discovery key",
9622
- input.expected === void 0 ? "the card names no discovery key" : "the card came out of the local cache, which does not authenticate it"
9623
- );
9624
- }
9625
- if (input.attested === void 0) {
9626
- throw new QuoteVerificationFailed(
9627
- "responder",
9628
- input.expected,
9629
- "the transport attests nobody"
9630
- );
9631
- }
9632
- if (input.attested !== input.expected) {
9633
- throw new QuoteVerificationFailed("responder", input.expected, input.attested);
9634
- }
9635
- };
9636
- var verifyPair = (quoted, requested) => {
9637
- if (quoted !== requested) {
9638
- throw new QuoteVerificationFailed("pair", requested, String(quoted));
9639
- }
9640
- };
9641
- var verifyingDerivation = (derive) => {
9642
- try {
9643
- return derive();
9644
- } catch (error) {
9645
- if (error instanceof AddressMismatch) {
9646
- const derived = Array.isArray(error.derived) ? error.derived.join(", ") : error.derived;
9647
- throw new QuoteVerificationFailed("lockup_address", derived, error.quoted, {
9648
- cause: error
9649
- });
9650
- }
9651
- if (error instanceof Error) {
9652
- throw new QuoteVerificationFailed("lockup_address", void 0, error.message, {
9653
- cause: error
9654
- });
9655
- }
9656
- throw error;
9657
- }
9658
- };
9659
- var verifySendWindow = (input) => {
9660
- gated(
9661
- () => assertFundable({
9662
- quote: input.quote,
9663
- now: input.now,
9664
- ...input.invoiceExpiresAt === void 0 ? {} : { invoiceExpiresAt: input.invoiceExpiresAt },
9665
- ...input.onchain === void 0 ? {} : { onchain: input.onchain }
9666
- }),
9667
- { id: input.quoteId, expiresAt: input.quote.valid_until, now: input.now }
9668
- );
9669
- };
9670
- var verifyReceiveWindow = (input) => {
9671
- gated(
9672
- () => assertReceivable({
9673
- quote: input.quote,
9674
- payDeadline: input.payDeadline,
9675
- now: input.now
9676
- }),
9677
- { id: input.quoteId, expiresAt: input.payDeadline, now: input.now }
9678
- );
9679
- };
9680
- var verifySendInvoice = (input) => {
9681
- const invoiced = input.invoiced;
9682
- if (input.take !== invoiced) {
9683
- throw new QuoteVerificationFailed("invoice", `${invoiced}`, `${input.take}`);
9684
- }
9685
- if (input.give < input.take) {
9686
- throw new QuoteVerificationFailed(
9687
- "invoice",
9688
- `at least the invoice's ${invoiced}`,
9689
- `${input.give}, a negative spread`
9690
- );
9691
- }
9692
- };
9693
- var verifyReceiveInvoiceFacts = (input) => {
9694
- let decoded;
9695
- try {
9696
- decoded = input.decode(input.invoice);
9697
- } catch (cause) {
9698
- throw new QuoteVerificationFailed(
9699
- "invoice",
9700
- "a decodable BOLT11",
9701
- cause instanceof Error ? cause.message : String(cause),
9702
- { cause }
9703
- );
9704
- }
9705
- if (!Number.isFinite(decoded.expiresAt)) {
9706
- throw new QuoteVerificationFailed("invoice", "a finite expiry", `${decoded.expiresAt}`);
9707
- }
9708
- if (!Number.isFinite(input.validUntil)) {
9709
- throw new QuoteVerificationFailed(
9710
- "refund_window",
9711
- "a finite valid_until",
9712
- `${input.validUntil}`
9713
- );
9714
- }
9715
- if (decoded.paymentHash !== input.paymentHash) {
9716
- throw new QuoteVerificationFailed("invoice", input.paymentHash, decoded.paymentHash);
9717
- }
9718
- if (!Number.isSafeInteger(decoded.amountSats) || decoded.amountSats <= 0) {
9719
- throw new QuoteVerificationFailed(
9720
- "invoice",
9721
- `${input.payAmount}`,
9722
- "the invoice names no amount"
9723
- );
9724
- }
9725
- if (BigInt(decoded.amountSats) !== input.payAmount) {
9726
- throw new QuoteVerificationFailed("invoice", `${input.payAmount}`, `${decoded.amountSats}`);
9727
- }
9728
- return { payDeadline: Math.min(decoded.expiresAt, input.validUntil) };
9729
- };
9730
- var verifyQuoteTtl = (input) => {
9731
- const floor = input.floorSeconds ?? 0;
9732
- if (input.expiresAt - input.now <= floor) {
9733
- throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
9734
- }
9735
- };
9736
- var CSV_GRANULARITY_SECONDS = 512;
9737
- var verifyRefundWindow = (input) => {
9738
- const max = input.maxSeconds ?? DEFAULT_MAX_REFUND_WINDOW_SECONDS;
9739
- const window = input.refundLocktime - input.now;
9740
- if (!(window <= max)) {
9741
- throw new QuoteVerificationFailed("refund_window", `at most ${max}s`, `${window}s`);
9742
- }
9743
- const delay = input.refundWithoutReceiverDelay;
9744
- if (delay !== void 0 && !(delay < max + CSV_GRANULARITY_SECONDS)) {
9745
- throw new QuoteVerificationFailed(
9746
- "refund_window",
9747
- `a solo-refund delay of at most ${max}s`,
9748
- `${delay}s`
9749
- );
9750
- }
9751
- };
9752
- var verifyQuotedAmount = (input) => {
9753
- verifyPinnedAmount(input);
9754
- if (input.take > input.give) {
9755
- throw new QuoteVerificationFailed(
9756
- "pair",
9757
- `${input.pair} give >= take`,
9758
- `give=${input.give} take=${input.take}`
9759
- );
9760
- }
9761
- };
9762
- var verifyCrossAssetAmount = (input) => {
9763
- verifyPinnedAmount(input);
9764
- if (input.give <= 0n || input.take <= 0n) {
9765
- throw new QuoteVerificationFailed(
9766
- "pair",
9767
- `${input.pair} give > 0 take > 0`,
9768
- `give=${input.give} take=${input.take}`
9769
- );
9770
- }
9771
- };
9772
- var verifiedCarrierSats = (quote) => {
9773
- try {
9774
- return quoteCarrierSats(quote);
9775
- } catch (error) {
9776
- if (reasonOf(error) !== "carrier_malformed") throw error;
9777
- throw new QuoteVerificationFailed(
9778
- "pair",
9779
- "carrier_sats a non-negative integer",
9780
- String(quote.carrier_sats),
9781
- { cause: error }
9782
- );
9783
- }
9784
- };
9785
- var verifyPinnedAmount = (input) => {
9786
- const quoted = input.pinned.on === "give" ? input.give : input.take;
9787
- if (quoted !== input.pinned.value) {
9788
- throw new QuoteVerificationFailed(
9789
- "pair",
9790
- `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
9791
- `${input.pair} ${input.pinned.on}=${quoted}`
9792
- );
9793
- }
9794
- };
9795
-
9796
10329
  // src/client/quoteOffer.ts
10330
+ init_verify();
9797
10331
  var FEED_TTL_MS = 3e4;
9798
10332
  var feedFetch = (base = fetch) => {
9799
10333
  const at2 = /* @__PURE__ */ new Map();
@@ -9882,12 +10416,12 @@ var verifyPlanLegs = (plan, legs, give) => {
9882
10416
  };
9883
10417
 
9884
10418
  // src/client/quoteRfq.ts
9885
- var import_base22 = require("@scure/base");
10419
+ var import_base23 = require("@scure/base");
9886
10420
  var import_sdk36 = require("@arkade-os/sdk");
9887
10421
  var import_solver_discovery12 = require("@arkade-os/solver-discovery");
9888
10422
 
9889
10423
  // src/jointGraph.ts
9890
- var import_base21 = require("@scure/base");
10424
+ var import_base22 = require("@scure/base");
9891
10425
  var import_sha26 = require("@noble/hashes/sha2.js");
9892
10426
  var import_sdk33 = require("@arkade-os/sdk");
9893
10427
  function digestJointGraph(plan, template) {
@@ -9923,7 +10457,7 @@ function digestJointGraph(plan, template) {
9923
10457
  preimage.set(part, at2);
9924
10458
  at2 += part.length;
9925
10459
  }
9926
- return import_base21.hex.encode((0, import_sha26.sha256)(preimage));
10460
+ return import_base22.hex.encode((0, import_sha26.sha256)(preimage));
9927
10461
  }
9928
10462
  function verifyJointGraph(plan, template) {
9929
10463
  try {
@@ -9951,7 +10485,7 @@ function verifyJointGraph(plan, template) {
9951
10485
  }
9952
10486
  }
9953
10487
  function parseGraphTx(psbt) {
9954
- return import_sdk33.Transaction.fromPSBT(import_base21.base64.decode(psbt));
10488
+ return import_sdk33.Transaction.fromPSBT(import_base22.base64.decode(psbt));
9955
10489
  }
9956
10490
  function deepFreeze(value) {
9957
10491
  if (value !== null && typeof value === "object") {
@@ -9983,8 +10517,10 @@ init_onchainHtlc();
9983
10517
 
9984
10518
  // src/payment/swapRail.ts
9985
10519
  var import_sdk34 = require("@arkade-os/sdk");
10520
+ init_errors();
9986
10521
 
9987
10522
  // src/client/sats.ts
10523
+ init_errors();
9988
10524
  var satsOf = (value, field) => {
9989
10525
  if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
9990
10526
  throw new AmountEncodingUnsupported(
@@ -10000,7 +10536,9 @@ var satsOf = (value, field) => {
10000
10536
  var claimFeeSats = (deps) => BigInt(Math.ceil((deps.claimVsize ?? ONCHAIN_CLAIM_VSIZE) * deps.claimFeeRateSatVb));
10001
10537
 
10002
10538
  // src/client/quoteRfq.ts
10539
+ init_rfq_contract();
10003
10540
  init_rfq();
10541
+ init_errors();
10004
10542
 
10005
10543
  // src/client/rfqWire.ts
10006
10544
  init_rfq();
@@ -10033,6 +10571,7 @@ var parseRfqQuote = (quote) => ({
10033
10571
  });
10034
10572
 
10035
10573
  // src/client/quoteRfq.ts
10574
+ init_verify();
10036
10575
  var lockupOf = (derived) => ({
10037
10576
  address: derived.address,
10038
10577
  script: derived.script,
@@ -10040,12 +10579,12 @@ var lockupOf = (derived) => ({
10040
10579
  });
10041
10580
  var covenantInputs = (input) => {
10042
10581
  const network = (0, import_sdk36.networkFromOperatorInfo)(input.info);
10043
- const arkade4 = input.corridors.get("arkade").deps;
10582
+ const arkade5 = input.corridors.get("arkade").deps;
10044
10583
  return {
10045
- 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"),
10046
10585
  // The resolved per-network pin, never operator-reported: it lands in a covenant leaf
10047
10586
  // that decides who can move the funds.
10048
- 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"),
10049
10588
  claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
10050
10589
  hrp: network.hrp
10051
10590
  };
@@ -10053,7 +10592,7 @@ var covenantInputs = (input) => {
10053
10592
  var sealingKey = (deps) => {
10054
10593
  const configured = deps.covclaimd?.pubkey;
10055
10594
  if (configured === void 0) return void 0;
10056
- const key = import_base22.hex.decode(configured);
10595
+ const key = import_base23.hex.decode(configured);
10057
10596
  if (key.length !== 33) {
10058
10597
  throw new Error(
10059
10598
  `the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
@@ -10109,7 +10648,7 @@ var quoteArkadeAsset = async (input) => {
10109
10648
  receiveAddress,
10110
10649
  maker.pkScript,
10111
10650
  (0, import_sdk36.networkFromOperatorInfo)(input.info).hrp,
10112
- (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")
10113
10652
  );
10114
10653
  const choice = payment?.carrier;
10115
10654
  const carrierRequest = choice === void 0 ? void 0 : choice.mode === "purchase" ? { mode: "purchase" } : {
@@ -10121,7 +10660,7 @@ var quoteArkadeAsset = async (input) => {
10121
10660
  if (choice?.mode === "recycleReceiver") {
10122
10661
  if (choice.quote.assetId !== sides.wantAsset?.toString())
10123
10662
  throw new Error("carrier quote assetId differs from requested asset");
10124
- if (choice.quote.senderKey !== import_base22.hex.encode(maker.publicKey))
10663
+ if (choice.quote.senderKey !== import_base23.hex.encode(maker.publicKey))
10125
10664
  throw new Error("carrier quote senderKey differs from wallet identity");
10126
10665
  if (input.now >= choice.quote.expiresAt - 30)
10127
10666
  throw new Error("carrier quote expired before RFQ");
@@ -10152,6 +10691,10 @@ var quoteArkadeAsset = async (input) => {
10152
10691
  );
10153
10692
  verifyPair(wire.pair, pair);
10154
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;
10155
10698
  verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
10156
10699
  verifyQuoteTtl({
10157
10700
  quoteId: input.quoteId,
@@ -10183,7 +10726,7 @@ var quoteArkadeAsset = async (input) => {
10183
10726
  if (input.now >= validUntil) throw new Error("asset payment terms lapsed before funding");
10184
10727
  assetPayment = {
10185
10728
  receiveAddress: receiveAddress ?? new import_sdk36.ArkAddress(
10186
- (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"),
10187
10730
  maker.pkScript.slice(2),
10188
10731
  (0, import_sdk36.networkFromOperatorInfo)(input.info).hrp
10189
10732
  ).encode(),
@@ -10197,7 +10740,9 @@ var quoteArkadeAsset = async (input) => {
10197
10740
  const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
10198
10741
  give: input.candidate.give,
10199
10742
  giveAmount: parsed.give,
10200
- ...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,
10201
10746
  ...QUOTE_OPTIONS,
10202
10747
  fetchImpl: input.feed.fetch
10203
10748
  });
@@ -10211,7 +10756,8 @@ var quoteArkadeAsset = async (input) => {
10211
10756
  maker,
10212
10757
  ...receiveAddress === void 0 ? {} : { receiveAddress },
10213
10758
  info: input.info,
10214
- contractVersion
10759
+ contractVersion,
10760
+ ...taker === void 0 ? {} : { taker }
10215
10761
  });
10216
10762
  verifyingDerivation(() => verifyOfferAddress(wire, offer));
10217
10763
  return {
@@ -10361,7 +10907,7 @@ var quoteLightningReceive = async (input) => {
10361
10907
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
10362
10908
  input.wallet.getAddress()
10363
10909
  ]);
10364
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
10910
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10365
10911
  const lightning = input.corridors.get("lightning").deps;
10366
10912
  const sealTo = sealingKey(lightning);
10367
10913
  const sealsAmount = pinned.on === "take" && input.legs.take.assetId === BTC_ASSET_ID;
@@ -10481,7 +11027,7 @@ var quoteOnchainSend = async (input) => {
10481
11027
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
10482
11028
  (0, import_sdk36.provisionRefundKey)(input.wallet)
10483
11029
  ]);
10484
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11030
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10485
11031
  const wire = await input.transport.requestQuote(
10486
11032
  withCanonicalAmount(
10487
11033
  onchainSendRequest({
@@ -10592,7 +11138,7 @@ var quoteOnchainReceive = async (input) => {
10592
11138
  input.wallet.getAddress(),
10593
11139
  input.wallet.getBoardingAddress()
10594
11140
  ]);
10595
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11141
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10596
11142
  const refundPkScript = l1ScriptForAddress(boardingAddress, l1Network);
10597
11143
  const wire = await input.transport.requestQuote(
10598
11144
  withCanonicalAmount(
@@ -10699,6 +11245,7 @@ var quoteOnchainReceive = async (input) => {
10699
11245
 
10700
11246
  // src/client/verbs.ts
10701
11247
  var import_sdk37 = require("@arkade-os/sdk");
11248
+ init_errors();
10702
11249
  var enforceFeeCeiling = (quote, call, policy) => {
10703
11250
  let ceiling;
10704
11251
  for (const [source, limit] of [
@@ -10723,14 +11270,14 @@ var settle = async (deps, input, maxFee) => {
10723
11270
  return deps.accept(quote);
10724
11271
  };
10725
11272
  var pay = async (deps, destination, options = {}) => {
10726
- const arkade4 = (0, import_sdk37.arkTarget)(destination);
10727
- if (arkade4 !== void 0) {
11273
+ const arkade5 = (0, import_sdk37.arkTarget)(destination);
11274
+ if (arkade5 !== void 0) {
10728
11275
  const amount = (0, import_sdk37.resolveSendAmount)(
10729
11276
  "ark",
10730
11277
  destination,
10731
11278
  options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
10732
11279
  );
10733
- return { kind: "payment", txid: await deps.wallet.send({ address: arkade4, amount }) };
11280
+ return { kind: "payment", txid: await deps.wallet.send({ address: arkade5, amount }) };
10734
11281
  }
10735
11282
  const swap = await settle(
10736
11283
  deps,
@@ -10792,7 +11339,7 @@ var nostrTransportFactory = createNostrTransportFactory();
10792
11339
 
10793
11340
  // src/client/client.ts
10794
11341
  var PREPARATIONS_HELD = 64;
10795
- var mintQuoteId = () => import_base23.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
11342
+ var mintQuoteId = () => import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
10796
11343
  var createSwapClient = (config) => {
10797
11344
  const { wallet } = config;
10798
11345
  const operator = config.operator ?? walletOperator(wallet);
@@ -10945,6 +11492,7 @@ var createSwapClient = (config) => {
10945
11492
  return acceptQuote({
10946
11493
  quote,
10947
11494
  ...validUntil === void 0 ? {} : { validUntil },
11495
+ ...options?.attachOfferPacket === false ? { attachOfferPacket: false } : {},
10948
11496
  ...preparation === void 0 ? {} : { preparation },
10949
11497
  wallet,
10950
11498
  repository: config.repository,
@@ -11046,8 +11594,13 @@ var createSwapClient = (config) => {
11046
11594
  return client;
11047
11595
  };
11048
11596
 
11597
+ // src/client/index.ts
11598
+ init_errors();
11599
+ init_policy();
11600
+ init_verify();
11601
+
11049
11602
  // src/reveal.ts
11050
- var import_base24 = require("@scure/base");
11603
+ var import_base25 = require("@scure/base");
11051
11604
  var import_sdk39 = require("@arkade-os/sdk");
11052
11605
  init_claimAmountGate();
11053
11606
  init_claimPacket();
@@ -11075,7 +11628,7 @@ var decodeKey = (value, field) => {
11075
11628
  if (typeof value !== "string") throw new Error(`covclaimd info: ${field} is not a string`);
11076
11629
  let bytes;
11077
11630
  try {
11078
- bytes = import_base24.hex.decode(value);
11631
+ bytes = import_base25.hex.decode(value);
11079
11632
  } catch {
11080
11633
  throw new Error(`covclaimd info: ${field} is not hex`);
11081
11634
  }
@@ -11136,7 +11689,7 @@ var covclaimdClient = (baseUrl, options = {}) => {
11136
11689
  const body = await readJson("info", response);
11137
11690
  return {
11138
11691
  covclaimdPubkey: decodeKey(body?.covclaimd_pub_key, "covclaimd_pub_key"),
11139
- 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"))
11140
11693
  };
11141
11694
  },
11142
11695
  async reveal(params) {
@@ -11164,13 +11717,13 @@ function revealFieldsFromScript(script) {
11164
11717
  throw new Error("this covenant has no non-interactive claim leaf to reveal against");
11165
11718
  }
11166
11719
  return {
11167
- arkadeScript: import_base24.base64.encode(script.nonInteractiveClaimArkadeScript),
11168
- taptree: import_base24.hex.encode(script.encode())
11720
+ arkadeScript: import_base25.base64.encode(script.nonInteractiveClaimArkadeScript),
11721
+ taptree: import_base25.hex.encode(script.encode())
11169
11722
  };
11170
11723
  }
11171
11724
  async function revealClaimPacket(client, input) {
11172
11725
  const fields = revealFieldsFromScript(input.script);
11173
- 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)) {
11174
11727
  throw new Error("address does not belong to this covenant");
11175
11728
  }
11176
11729
  assertPreimageMatches(input.preimage, input.script.options.preimageHash);
@@ -11186,7 +11739,7 @@ async function revealClaimPacket(client, input) {
11186
11739
  }
11187
11740
 
11188
11741
  // src/offerFillPlan.ts
11189
- var import_base25 = require("@scure/base");
11742
+ var import_base26 = require("@scure/base");
11190
11743
  var import_sdk40 = require("@arkade-os/sdk");
11191
11744
  init_offer();
11192
11745
  var OFFER_FILL_TEMPLATE = "offer-fill/1";
@@ -11201,8 +11754,9 @@ async function buildOfferFillPlan(wallet, arkServerUrl, offerHex, opts) {
11201
11754
  assetCarrierSats = ASSET_CARRIER_SATS,
11202
11755
  sponsor
11203
11756
  } = opts;
11204
- const offer = decodeOffer(import_base25.hex.decode(offerHex));
11205
- 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);
11206
11760
  const vtxos = await contract.getUtxos();
11207
11761
  const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
11208
11762
  const solverPayout = payoutScript ?? import_sdk40.ArkAddress.decode(await wallet.getAddress()).pkScript;
@@ -11250,7 +11804,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11250
11804
  }
11251
11805
  layout.inputs.forEach((input, i) => {
11252
11806
  const spent = checkpoints[i].getInput(0);
11253
- 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) {
11254
11808
  throw new Error(`fill plan checkpoint ${i} does not spend ${input.txid}:${input.vout}`);
11255
11809
  }
11256
11810
  });
@@ -11262,7 +11816,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11262
11816
  }
11263
11817
  layout.outputs.forEach((expected, i) => {
11264
11818
  const out = arkTx.getOutput(i);
11265
- 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)) {
11266
11820
  throw new Error(`fill plan output ${i} is not the ${expected.role} script`);
11267
11821
  }
11268
11822
  if (out.amount !== expected.sats) {
@@ -11276,7 +11830,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11276
11830
  throw new Error(`fill plan output ${payments} is not the extension packet`);
11277
11831
  }
11278
11832
  const anchor = arkTx.getOutput(payments + 1);
11279
- 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) {
11280
11834
  throw new Error(`fill plan output ${payments + 1} is not the anchor`);
11281
11835
  }
11282
11836
  const packet = import_sdk40.Extension.fromTx(arkTx).getAssetPacket();
@@ -11308,8 +11862,8 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11308
11862
  );
11309
11863
  }
11310
11864
  }
11311
- const arkTxPsbt = import_base25.base64.encode(arkTx.toPSBT());
11312
- 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()));
11313
11867
  const inputOwners = layout.inputs.map((input) => input.owner);
11314
11868
  const graph = {
11315
11869
  arkTx: arkTxPsbt,
@@ -11330,7 +11884,7 @@ function verifyOfferFillPlan(plan) {
11330
11884
  }
11331
11885
 
11332
11886
  // src/evmRfq.ts
11333
- var import_base26 = require("@scure/base");
11887
+ var import_base27 = require("@scure/base");
11334
11888
  init_rfq();
11335
11889
  var EVM_CHAIN = "ethereum";
11336
11890
  var EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
@@ -11395,7 +11949,7 @@ var evmSendRequest = (input) => {
11395
11949
  payment_hash: input.paymentHash,
11396
11950
  evm_claim_address: assertEvmAddress(input.evmClaimAddress, "evmClaimAddress"),
11397
11951
  refund_address: input.refundAddress,
11398
- client_refund_pubkey: import_base26.hex.encode(input.senderPubkey)
11952
+ client_refund_pubkey: import_base27.hex.encode(input.senderPubkey)
11399
11953
  }
11400
11954
  };
11401
11955
  };
@@ -11419,7 +11973,7 @@ var evmReceiveRequest = (input) => {
11419
11973
  evm_timeout_block: input.evmTimeoutBlock,
11420
11974
  evm_refund_address: assertEvmAddress(input.evmRefundAddress, "evmRefundAddress"),
11421
11975
  payout_address: input.payoutAddress,
11422
- payout_pubkey: import_base26.hex.encode(input.payoutPubkey)
11976
+ payout_pubkey: import_base27.hex.encode(input.payoutPubkey)
11423
11977
  }
11424
11978
  };
11425
11979
  };
@@ -11711,6 +12265,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
11711
12265
  recordInstrument,
11712
12266
  recordLeg,
11713
12267
  recordOutcome,
12268
+ reopenedDeposit,
11714
12269
  resolveCorridorBase,
11715
12270
  resolveCorridorDeps,
11716
12271
  resolveRoute,
@@ -11747,6 +12302,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
11747
12302
  verifyResponder,
11748
12303
  verifySendInvoice,
11749
12304
  verifySendWindow,
12305
+ verifyTaker,
11750
12306
  verifyingDerivation,
11751
12307
  walletLockupIndexer,
11752
12308
  withCanonicalAmount,