@arkade-os/swap 0.1.8 → 0.1.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/advanced.cjs +1125 -554
  2. package/dist/advanced.d.cts +19 -21
  3. package/dist/advanced.d.ts +19 -21
  4. package/dist/advanced.js +40 -34
  5. package/dist/{chunk-ISWLKKSS.js → chunk-2HQZLIVX.js} +106 -39
  6. package/dist/{chunk-5QPJWOCN.js → chunk-6RJVT65W.js} +2 -0
  7. package/dist/chunk-AUJDREZN.js +445 -0
  8. package/dist/{chunk-ZBJGLLYV.js → chunk-FWRDAL73.js} +157 -477
  9. package/dist/{chunk-PDNVKH5L.js → chunk-LCO6AJOS.js} +453 -70
  10. package/dist/index.cjs +1110 -542
  11. package/dist/index.d.cts +5 -6
  12. package/dist/index.d.ts +5 -6
  13. package/dist/index.js +24 -22
  14. package/dist/{lockupContract-DguuT7NK.d.cts → lockupContract-BTTRVwOt.d.cts} +1 -1
  15. package/dist/{lockupContract-BUOsghl1.d.ts → lockupContract-aFarhlxj.d.ts} +1 -1
  16. package/dist/node/index.d.cts +97 -67
  17. package/dist/node/index.d.ts +97 -67
  18. package/dist/nostr.cjs +925 -516
  19. package/dist/nostr.d.cts +1 -1
  20. package/dist/nostr.d.ts +1 -1
  21. package/dist/nostr.js +3 -2
  22. package/dist/{offerFillPlan-_AOLo6kh.d.ts → offerFillPlan-CJC5tnEd.d.ts} +10 -42
  23. package/dist/{offerFillPlan-Bp6-z6dS.d.cts → offerFillPlan-FmyaQoYT.d.cts} +10 -42
  24. package/dist/protocol.cjs +1082 -188
  25. package/dist/protocol.d.cts +42 -23
  26. package/dist/protocol.d.ts +42 -23
  27. package/dist/protocol.js +20 -7
  28. package/dist/repositories/realm/index.d.cts +3 -2
  29. package/dist/repositories/realm/index.d.ts +3 -2
  30. package/dist/repositories/sqlite/index.d.cts +3 -2
  31. package/dist/repositories/sqlite/index.d.ts +3 -2
  32. package/dist/{repository-CkKK0dGO.d.ts → repository-CwwhIAEd.d.cts} +406 -74
  33. package/dist/{repository--pfikw2R.d.cts → repository-DO6QKxBx.d.ts} +406 -74
  34. package/dist/{rfq-IzhOCG02.d.ts → rfq-CYxOyniL.d.ts} +52 -11
  35. package/dist/rfq-contract.cjs +3 -0
  36. package/dist/rfq-contract.d.cts +3 -1
  37. package/dist/rfq-contract.d.ts +3 -1
  38. package/dist/rfq-contract.js +3 -1
  39. package/dist/{rfq-BRpo5uWU.d.cts → rfq-nMGywkqI.d.cts} +52 -11
  40. package/dist/verify-ENO36VPK.js +33 -0
  41. package/dist/{watch-pvTVFp6-.d.cts → watch-DpDSP2tu.d.cts} +4 -3
  42. package/dist/{watch-DDNycuUa.d.ts → watch-_fZSgx_l.d.ts} +4 -3
  43. package/package.json +2 -2
  44. package/dist/offer-BhonWuKR.d.ts +0 -274
  45. package/dist/offer-D_qHpWo2.d.cts +0 -274
package/dist/index.cjs CHANGED
@@ -138,9 +138,9 @@ function onchainHtlcScript(params, network) {
138
138
  if (params.claimKey.length !== 32 || params.refundKey.length !== 32) {
139
139
  throw new Error("claimKey and refundKey must be 32-byte x-only keys");
140
140
  }
141
- if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0) {
141
+ if (!Number.isInteger(params.refundLocktime) || params.refundLocktime <= 0 || params.refundLocktime > 4294967295) {
142
142
  throw new Error(
143
- `refundLocktime must be a positive unix timestamp, got ${params.refundLocktime}`
143
+ `refundLocktime must be a positive uint32 unix timestamp, got ${params.refundLocktime}`
144
144
  );
145
145
  }
146
146
  if (params.refundLocktime < LOCKTIME_THRESHOLD) {
@@ -229,15 +229,20 @@ async function claimOnchainFill(chain, input) {
229
229
  }
230
230
  async function classifyOnchainHtlc(chain, input) {
231
231
  const utxos = await chain.getScriptUtxos(input.htlc.pkScript);
232
- const best = utxos.sort((a, b) => b.amount > a.amount ? 1 : -1)[0];
233
- if (!best) {
234
- if (!input.funding) return { phase: "unfunded" };
235
- const spend = await chain.getSpendingTx(
236
- input.funding.txid,
237
- input.funding.vout,
238
- input.htlc.pkScript
239
- );
240
- if (!spend) return { phase: "unfunded" };
232
+ const deep = (u) => u.confirmations >= input.minConfirmations;
233
+ const best = utxos.sort(
234
+ (a, b) => deep(a) !== deep(b) ? deep(a) ? -1 : 1 : b.amount > a.amount ? 1 : -1
235
+ )[0];
236
+ const { funding } = input;
237
+ let spend = null;
238
+ if (funding && !utxos.some((u) => u.txid === funding.txid && u.vout === funding.vout)) {
239
+ try {
240
+ spend = await chain.getSpendingTx(funding.txid, funding.vout, input.htlc.pkScript);
241
+ } catch (error) {
242
+ if (!best) throw error;
243
+ }
244
+ }
245
+ if (spend) {
241
246
  const preimage = extractPreimage(spend.txHex, input.htlc.paymentHash);
242
247
  const txid = btc.Transaction.fromRaw(import_base.hex.decode(spend.txHex), {
243
248
  allowUnknownInputs: true,
@@ -245,6 +250,7 @@ async function classifyOnchainHtlc(chain, input) {
245
250
  }).id;
246
251
  return preimage ? { phase: "claimed", txid, preimage } : { phase: "swept", txid };
247
252
  }
253
+ if (!best) return { phase: "unfunded" };
248
254
  if (best.confirmations < input.minConfirmations)
249
255
  return { phase: "awaiting_confirmations", utxo: best };
250
256
  const mtp = await chain.getMtp();
@@ -754,6 +760,141 @@ var init_asset_swap = __esm({
754
760
  }
755
761
  });
756
762
 
763
+ // src/contracts/asset-swap-v4.json
764
+ var asset_swap_v4_default;
765
+ var init_asset_swap_v4 = __esm({
766
+ "src/contracts/asset-swap-v4.json"() {
767
+ asset_swap_v4_default = {
768
+ formatVersion: 1,
769
+ contractName: "AssetSwap",
770
+ constructorInputs: [
771
+ {
772
+ name: "receiver",
773
+ type: "pubkey"
774
+ },
775
+ {
776
+ name: "amount",
777
+ type: "int"
778
+ },
779
+ {
780
+ name: "assetTxid",
781
+ type: "bytes32"
782
+ },
783
+ {
784
+ name: "assetGroupIndex",
785
+ type: "int"
786
+ },
787
+ {
788
+ name: "user",
789
+ type: "pubkey"
790
+ },
791
+ {
792
+ name: "taker",
793
+ type: "pubkey"
794
+ }
795
+ ],
796
+ functions: [
797
+ {
798
+ name: "fulfill",
799
+ arkade: {
800
+ inputs: [],
801
+ asm: [
802
+ "OP_PUSHCURRENTINPUTINDEX",
803
+ "OP_DUP",
804
+ "<assetTxid>",
805
+ "<assetGroupIndex>",
806
+ "OP_INSPECTOUTASSETLOOKUP",
807
+ "OP_VERIFY",
808
+ "<amount>",
809
+ "OP_GREATERTHANOREQUAL",
810
+ "OP_VERIFY",
811
+ "OP_INSPECTOUTPUTSCRIPTPUBKEY",
812
+ "1",
813
+ "OP_NUMEQUALVERIFY",
814
+ "<receiver>",
815
+ "OP_EQUAL"
816
+ ]
817
+ },
818
+ leaves: [
819
+ {
820
+ name: "fulfill",
821
+ witness: [
822
+ {
823
+ name: "takerSig",
824
+ type: "signature",
825
+ encoding: "schnorr-64"
826
+ },
827
+ {
828
+ name: "serverSig",
829
+ type: "signature",
830
+ encoding: "schnorr-64",
831
+ injected: true
832
+ },
833
+ {
834
+ name: "emulatorSig",
835
+ type: "signature",
836
+ encoding: "schnorr-64",
837
+ injected: true
838
+ }
839
+ ],
840
+ asm: [
841
+ "<taker>",
842
+ "OP_CHECKSIGVERIFY",
843
+ "<SERVER_KEY>",
844
+ "OP_CHECKSIGVERIFY",
845
+ "<EMULATOR_KEY:fulfill>",
846
+ "OP_CHECKSIG"
847
+ ]
848
+ }
849
+ ]
850
+ },
851
+ {
852
+ name: "cancel",
853
+ leaves: [
854
+ {
855
+ name: "cancel",
856
+ witness: [
857
+ {
858
+ name: "userSig",
859
+ type: "signature",
860
+ encoding: "schnorr-64"
861
+ },
862
+ {
863
+ name: "serverSig",
864
+ type: "signature",
865
+ encoding: "schnorr-64",
866
+ injected: true
867
+ }
868
+ ],
869
+ asm: [
870
+ "<user>",
871
+ "OP_CHECKSIGVERIFY",
872
+ "<SERVER_KEY>",
873
+ "OP_CHECKSIG"
874
+ ]
875
+ }
876
+ ]
877
+ }
878
+ ],
879
+ source: {
880
+ entry: "asset-swap-v4.ark",
881
+ files: {
882
+ "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"
883
+ }
884
+ },
885
+ compiler: {
886
+ name: "arkadec",
887
+ version: "0.1.0-rc.1",
888
+ options: {
889
+ optimize: true
890
+ }
891
+ },
892
+ updatedAt: "2026-11-19T20:57:50.605738400+00:00",
893
+ fingerprint: "sha256:d830de32cd1d286a0a1fac698ff114a6c8ef5338a69f9f813717d1038ab2fb4a"
894
+ };
895
+ }
896
+ });
897
+
757
898
  // src/contracts/sats-swap.json
758
899
  var sats_swap_default;
759
900
  var init_sats_swap = __esm({
@@ -867,6 +1008,130 @@ var init_sats_swap = __esm({
867
1008
  }
868
1009
  });
869
1010
 
1011
+ // src/contracts/sats-swap-v4.json
1012
+ var sats_swap_v4_default;
1013
+ var init_sats_swap_v4 = __esm({
1014
+ "src/contracts/sats-swap-v4.json"() {
1015
+ sats_swap_v4_default = {
1016
+ formatVersion: 1,
1017
+ contractName: "SatsSwap",
1018
+ constructorInputs: [
1019
+ {
1020
+ name: "receiver",
1021
+ type: "pubkey"
1022
+ },
1023
+ {
1024
+ name: "amount",
1025
+ type: "int"
1026
+ },
1027
+ {
1028
+ name: "user",
1029
+ type: "pubkey"
1030
+ },
1031
+ {
1032
+ name: "taker",
1033
+ type: "pubkey"
1034
+ }
1035
+ ],
1036
+ functions: [
1037
+ {
1038
+ name: "fulfill",
1039
+ arkade: {
1040
+ inputs: [],
1041
+ asm: [
1042
+ "OP_PUSHCURRENTINPUTINDEX",
1043
+ "OP_DUP",
1044
+ "OP_INSPECTOUTPUTVALUE",
1045
+ "<amount>",
1046
+ "OP_GREATERTHANOREQUAL",
1047
+ "OP_VERIFY",
1048
+ "OP_INSPECTOUTPUTSCRIPTPUBKEY",
1049
+ "1",
1050
+ "OP_NUMEQUALVERIFY",
1051
+ "<receiver>",
1052
+ "OP_EQUAL"
1053
+ ]
1054
+ },
1055
+ leaves: [
1056
+ {
1057
+ name: "fulfill",
1058
+ witness: [
1059
+ {
1060
+ name: "takerSig",
1061
+ type: "signature",
1062
+ encoding: "schnorr-64"
1063
+ },
1064
+ {
1065
+ name: "serverSig",
1066
+ type: "signature",
1067
+ encoding: "schnorr-64",
1068
+ injected: true
1069
+ },
1070
+ {
1071
+ name: "emulatorSig",
1072
+ type: "signature",
1073
+ encoding: "schnorr-64",
1074
+ injected: true
1075
+ }
1076
+ ],
1077
+ asm: [
1078
+ "<taker>",
1079
+ "OP_CHECKSIGVERIFY",
1080
+ "<SERVER_KEY>",
1081
+ "OP_CHECKSIGVERIFY",
1082
+ "<EMULATOR_KEY:fulfill>",
1083
+ "OP_CHECKSIG"
1084
+ ]
1085
+ }
1086
+ ]
1087
+ },
1088
+ {
1089
+ name: "cancel",
1090
+ leaves: [
1091
+ {
1092
+ name: "cancel",
1093
+ witness: [
1094
+ {
1095
+ name: "userSig",
1096
+ type: "signature",
1097
+ encoding: "schnorr-64"
1098
+ },
1099
+ {
1100
+ name: "serverSig",
1101
+ type: "signature",
1102
+ encoding: "schnorr-64",
1103
+ injected: true
1104
+ }
1105
+ ],
1106
+ asm: [
1107
+ "<user>",
1108
+ "OP_CHECKSIGVERIFY",
1109
+ "<SERVER_KEY>",
1110
+ "OP_CHECKSIG"
1111
+ ]
1112
+ }
1113
+ ]
1114
+ }
1115
+ ],
1116
+ source: {
1117
+ entry: "sats-swap-v4.ark",
1118
+ files: {
1119
+ "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"
1120
+ }
1121
+ },
1122
+ compiler: {
1123
+ name: "arkadec",
1124
+ version: "0.1.0-rc.1",
1125
+ options: {
1126
+ optimize: true
1127
+ }
1128
+ },
1129
+ updatedAt: "2026-11-19T20:57:50.848496600+00:00",
1130
+ fingerprint: "sha256:6ca61bf7ed8d8f65af3141da4e95fcc896863650127dd20949a84e72258053f4"
1131
+ };
1132
+ }
1133
+ });
1134
+
870
1135
  // src/legacy/swap-want-asset.program.v1.json
871
1136
  var swap_want_asset_program_v1_default;
872
1137
  var init_swap_want_asset_program_v1 = __esm({
@@ -953,7 +1218,7 @@ var init_swap_want_btc_program_v1 = __esm({
953
1218
  });
954
1219
 
955
1220
  // src/rfq-contract.ts
956
- var RFQ_CONTRACT_VERSIONS_KEY, RFQ_CONTRACT_VERSION_KEY, RFQ_CONTRACT_VERSION_UNSUPPORTED, ASSET_SWAP_V2, ASSET_SWAP_V3, ASSET_SWAP_BASELINE;
1221
+ 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;
957
1222
  var init_rfq_contract = __esm({
958
1223
  "src/rfq-contract.ts"() {
959
1224
  "use strict";
@@ -962,18 +1227,21 @@ var init_rfq_contract = __esm({
962
1227
  RFQ_CONTRACT_VERSION_UNSUPPORTED = "contract_version_unsupported";
963
1228
  ASSET_SWAP_V2 = "asset-swap-v2";
964
1229
  ASSET_SWAP_V3 = "asset-swap-v3";
1230
+ ASSET_SWAP_V4 = "asset-swap-v4";
965
1231
  ASSET_SWAP_BASELINE = ASSET_SWAP_V2;
966
1232
  }
967
1233
  });
968
1234
 
969
1235
  // src/program.ts
970
- var import_sdk4, swapPrograms, legacySwapPrograms, sharedArgs, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
1236
+ var import_sdk4, swapPrograms, legacySwapPrograms, directedSwapPrograms, sharedArgs, refuseTaker, v3Args, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
971
1237
  var init_program = __esm({
972
1238
  "src/program.ts"() {
973
1239
  "use strict";
974
1240
  import_sdk4 = require("@arkade-os/sdk");
975
1241
  init_asset_swap();
1242
+ init_asset_swap_v4();
976
1243
  init_sats_swap();
1244
+ init_sats_swap_v4();
977
1245
  init_swap_want_asset_program_v1();
978
1246
  init_swap_want_btc_program_v1();
979
1247
  init_rfq_contract();
@@ -986,38 +1254,59 @@ var init_program = __esm({
986
1254
  wantAsset: import_sdk4.arkade.parseArtifact(swap_want_asset_program_v1_default),
987
1255
  wantBtc: import_sdk4.arkade.parseArtifact(swap_want_btc_program_v1_default)
988
1256
  };
1257
+ directedSwapPrograms = {
1258
+ wantAsset: import_sdk4.arkade.programFromArtifact(asset_swap_v4_default),
1259
+ wantBtc: import_sdk4.arkade.programFromArtifact(sats_swap_v4_default)
1260
+ };
989
1261
  sharedArgs = ({ user, server, exitDelay }) => ({
990
1262
  user,
991
1263
  server,
992
1264
  ...exitDelay && { exitDelay }
993
1265
  });
1266
+ refuseTaker = (version, { taker }) => {
1267
+ if (taker !== void 0) throw new Error(`${version} binds no taker key`);
1268
+ };
1269
+ v3Args = (inputs) => ({
1270
+ receiver: inputs.receiver,
1271
+ amount: inputs.amount,
1272
+ ...inputs.asset && {
1273
+ assetTxid: inputs.asset.txid,
1274
+ assetGroupIndex: inputs.asset.groupIndex
1275
+ },
1276
+ ...sharedArgs(inputs)
1277
+ });
994
1278
  ASSET_SWAP_CONTRACTS = {
995
1279
  [ASSET_SWAP_V2]: {
996
1280
  programs: legacySwapPrograms,
997
- args: (inputs) => ({
998
- makerWP: inputs.receiver,
999
- wantAmount: inputs.amount,
1000
- ...inputs.asset && {
1001
- wantAssetTxid: inputs.asset.txid,
1002
- wantAssetGroupIndex: inputs.asset.groupIndex
1003
- },
1004
- ...sharedArgs(inputs)
1005
- })
1281
+ args: (inputs) => {
1282
+ refuseTaker(ASSET_SWAP_V2, inputs);
1283
+ return {
1284
+ makerWP: inputs.receiver,
1285
+ wantAmount: inputs.amount,
1286
+ ...inputs.asset && {
1287
+ wantAssetTxid: inputs.asset.txid,
1288
+ wantAssetGroupIndex: inputs.asset.groupIndex
1289
+ },
1290
+ ...sharedArgs(inputs)
1291
+ };
1292
+ }
1006
1293
  },
1007
1294
  [ASSET_SWAP_V3]: {
1008
1295
  programs: swapPrograms,
1009
- args: (inputs) => ({
1010
- receiver: inputs.receiver,
1011
- amount: inputs.amount,
1012
- ...inputs.asset && {
1013
- assetTxid: inputs.asset.txid,
1014
- assetGroupIndex: inputs.asset.groupIndex
1015
- },
1016
- ...sharedArgs(inputs)
1017
- })
1296
+ args: (inputs) => {
1297
+ refuseTaker(ASSET_SWAP_V3, inputs);
1298
+ return v3Args(inputs);
1299
+ }
1300
+ },
1301
+ [ASSET_SWAP_V4]: {
1302
+ programs: directedSwapPrograms,
1303
+ args: (inputs) => {
1304
+ if (inputs.taker === void 0) throw new Error(`${ASSET_SWAP_V4} needs a taker key`);
1305
+ return { ...v3Args(inputs), taker: inputs.taker };
1306
+ }
1018
1307
  }
1019
1308
  };
1020
- ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_V3, ASSET_SWAP_V2];
1309
+ ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_V4];
1021
1310
  assetSwapContractVersion = (id) => {
1022
1311
  if (id === void 0) return ASSET_SWAP_BASELINE;
1023
1312
  if (Object.hasOwn(ASSET_SWAP_CONTRACTS, id)) return id;
@@ -1081,9 +1370,9 @@ var init_store = __esm({
1081
1370
  byNewest = (a, b) => b.createdAt - a.createdAt;
1082
1371
  getAssetSwapsOrThrow = async (repository) => {
1083
1372
  return (await collectAssetSwaps(repository)).filter(
1084
- (s) => s && typeof s.id === "string" && // offer swaps carry the TLV; onchain-corridor swaps carry
1085
- // the payment hash instead — either marks a valid record
1086
- (typeof s.offerHex === "string" || typeof s.paymentHash === "string")
1373
+ (s) => s && typeof s.id === "string" && // offer swaps carry the TLV or the binding; onchain-corridor swaps carry
1374
+ // the payment hash instead — any of them marks a valid record
1375
+ (typeof s.offerHex === "string" || s.binding !== void 0 || typeof s.paymentHash === "string")
1087
1376
  ).sort(byNewest);
1088
1377
  };
1089
1378
  getAssetSwaps = async (repository) => {
@@ -1286,28 +1575,28 @@ function withExitClosure(program, exit) {
1286
1575
  }
1287
1576
  };
1288
1577
  }
1289
- function swapProgramBinding(offer, operatorPubkey, contractVersion = ASSET_SWAP_BASELINE) {
1578
+ function swapProgramBinding(offer, operatorPubkey, contractVersion) {
1290
1579
  if (offer.makerPkScript.length !== FIELDS.makerPkScript.width) {
1291
1580
  throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
1292
1581
  }
1582
+ const directed = offer.taker !== void 0;
1583
+ const version = contractVersion ?? (directed ? ASSET_SWAP_V4 : ASSET_SWAP_BASELINE);
1293
1584
  const expected = offer.swapPkScript;
1294
- if (!expected?.length) return bindSwapProgram(offer, operatorPubkey, contractVersion);
1585
+ if (!expected?.length) return bindSwapProgram(offer, operatorPubkey, version);
1295
1586
  const funded = import_base5.hex.encode(expected);
1296
- const order = [
1297
- ASSET_SWAP_BASELINE,
1298
- ...ASSET_SWAP_CONTRACT_VERSIONS.filter((v) => v !== ASSET_SWAP_BASELINE)
1299
- ];
1300
- for (const version of order) {
1301
- const binding = bindSwapProgram(offer, operatorPubkey, version);
1587
+ const order = directed ? [ASSET_SWAP_V4] : [ASSET_SWAP_BASELINE, ASSET_SWAP_V3];
1588
+ for (const candidate of order) {
1589
+ const binding = bindSwapProgram(offer, operatorPubkey, candidate);
1302
1590
  if (pkOf(binding) === funded) return binding;
1303
1591
  }
1304
- return bindSwapProgram(offer, operatorPubkey, contractVersion);
1592
+ return bindSwapProgram(offer, operatorPubkey, directed ? ASSET_SWAP_V4 : version);
1305
1593
  }
1306
1594
  function bindSwapProgram(offer, operatorPubkey, contractVersion) {
1307
1595
  const { programs, args } = ASSET_SWAP_CONTRACTS[contractVersion];
1308
1596
  const user = offer.makerPublicKey;
1309
1597
  const assetId = offer.wantAsset;
1310
1598
  return {
1599
+ version: contractVersion,
1311
1600
  program: withExitClosure(assetId ? programs.wantAsset : programs.wantBtc, offer.exitDelay),
1312
1601
  args: args({
1313
1602
  receiver: offer.makerPkScript.subarray(2),
@@ -1318,7 +1607,8 @@ function bindSwapProgram(offer, operatorPubkey, contractVersion) {
1318
1607
  },
1319
1608
  user,
1320
1609
  server: operatorPubkey,
1321
- ...offer.exitDelay && { exitDelay: offer.exitDelay.value }
1610
+ ...offer.exitDelay && { exitDelay: offer.exitDelay.value },
1611
+ ...offer.taker && { taker: offer.taker }
1322
1612
  }),
1323
1613
  keys: {
1324
1614
  serverKey: operatorPubkey,
@@ -1341,6 +1631,33 @@ function pkOf(binding) {
1341
1631
  function offerContract(offer, operatorPubkey, contractVersion) {
1342
1632
  return compileSwapBinding(swapProgramBinding(offer, operatorPubkey, contractVersion));
1343
1633
  }
1634
+ function bindingProgram(binding) {
1635
+ if (Boolean(binding.wantAsset) === Boolean(binding.offerAsset)) {
1636
+ throw new Error("an offer binding names exactly one of wantAsset or offerAsset");
1637
+ }
1638
+ return swapProgramBinding(termsOf(binding), binding.serverPublicKey, binding.version);
1639
+ }
1640
+ function bindingFromOffer(offer, operatorPubkey) {
1641
+ const program = swapProgramBinding(offer, operatorPubkey);
1642
+ if (pkOf(program) !== import_base5.hex.encode(offer.swapPkScript)) {
1643
+ throw new OfferCovenantMismatchError(import_base5.hex.encode(offer.swapPkScript));
1644
+ }
1645
+ return {
1646
+ version: program.version,
1647
+ receiverPkScript: offer.makerPkScript,
1648
+ amount: offer.wantAmount,
1649
+ ...offer.wantAsset && { wantAsset: offer.wantAsset },
1650
+ ...offer.offerAsset && { offerAsset: offer.offerAsset },
1651
+ userPublicKey: offer.makerPublicKey,
1652
+ serverPublicKey: operatorPubkey,
1653
+ emulatorPublicKey: offer.emulatorPubkey,
1654
+ ...offer.exitDelay && { exitDelay: offer.exitDelay },
1655
+ ...offer.taker && { taker: offer.taker }
1656
+ };
1657
+ }
1658
+ function offerFromBinding(binding) {
1659
+ return offerOf(binding, compileSwapBinding(bindingProgram(binding)).pkScript);
1660
+ }
1344
1661
  function u64(name, value) {
1345
1662
  if (value < BigInt(0) || value >> BigInt(64) > BigInt(0)) {
1346
1663
  throw new Error(`${name} does not fit the offer wire format (u64)`);
@@ -1367,6 +1684,9 @@ function encodeOffer(offer) {
1367
1684
  throw new Error(`${name} must be ${FIELDS[name].width} bytes`);
1368
1685
  }
1369
1686
  }
1687
+ if (offer.taker !== void 0 && offer.taker.length !== FIELDS.taker.width) {
1688
+ throw new Error(`taker must be ${FIELDS.taker.width} bytes`);
1689
+ }
1370
1690
  const ratioNum = setRatio("ratioNum", offer.ratioNum);
1371
1691
  const ratioDen = setRatio("ratioDen", offer.ratioDen);
1372
1692
  if (ratioNum === void 0 !== (ratioDen === void 0)) {
@@ -1382,9 +1702,10 @@ function encodeOffer(offer) {
1382
1702
  if (offer.offerAsset) recs.push(tlv2(FIELDS.offerAsset.tag, offer.offerAsset.serialize()));
1383
1703
  recs.push(
1384
1704
  tlv2(FIELDS.makerPkScript.tag, offer.makerPkScript),
1385
- tlv2(FIELDS.makerPublicKey.tag, offer.makerPublicKey),
1386
- tlv2(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey)
1705
+ tlv2(FIELDS.makerPublicKey.tag, offer.makerPublicKey)
1387
1706
  );
1707
+ if (offer.taker) recs.push(tlv2(FIELDS.taker.tag, offer.taker));
1708
+ recs.push(tlv2(FIELDS.emulatorPubkey.tag, offer.emulatorPubkey));
1388
1709
  if (offer.exitDelay) recs.push(tlv2(FIELDS.exitTimelock.tag, encodeExitDelay(offer.exitDelay)));
1389
1710
  return (0, import_utils2.concatBytes)(...recs);
1390
1711
  }
@@ -1462,7 +1783,8 @@ function decodeOffer(data) {
1462
1783
  emulatorPubkey: need("emulatorPubkey"),
1463
1784
  ...ratioNum !== void 0 && { ratioNum },
1464
1785
  ...ratioDen !== void 0 && { ratioDen },
1465
- ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) }
1786
+ ...fields.exitTimelock && { exitDelay: decodeExitDelay(fields.exitTimelock) },
1787
+ ...fields.taker && { taker: fields.taker }
1466
1788
  };
1467
1789
  }
1468
1790
  function decodeExitDelay(value) {
@@ -1482,10 +1804,7 @@ async function registerOfferContract(wallet, info, binding, operatorPubkey, expe
1482
1804
  });
1483
1805
  }
1484
1806
  function offerContractParams(client, binding, operatorPubkey, expectedPkScript) {
1485
- const { program, args, keys } = swapProgramBinding(
1486
- { ...binding, swapPkScript: expectedPkScript },
1487
- operatorPubkey
1488
- );
1807
+ const { program, args, keys } = "version" in binding ? bindingProgram(binding) : swapProgramBinding({ ...binding, swapPkScript: expectedPkScript }, operatorPubkey);
1489
1808
  const contract = new import_sdk6.arkade.ArkadeContract(client, program, args, keys);
1490
1809
  if (import_base5.hex.encode(contract.pkScript) !== import_base5.hex.encode(expectedPkScript)) {
1491
1810
  throw new Error("derived covenant does not match the offer's swapPkScript");
@@ -1517,7 +1836,7 @@ async function restoreOfferCoverage(wallet, swaps) {
1517
1836
  if (seen.has(swap.swapPkScript)) continue;
1518
1837
  seen.add(swap.swapPkScript);
1519
1838
  try {
1520
- const { swapPkScript: _, ...binding } = decodeOffer(import_base5.hex.decode(swap.offerHex));
1839
+ const binding = storedOffer(swap);
1521
1840
  const stored = fundedKey.get(swap.swapPkScript);
1522
1841
  covenants.push({
1523
1842
  script: swap.swapPkScript,
@@ -1626,7 +1945,8 @@ async function deriveOffer(wallet, params) {
1626
1945
  makerPublicKey: maker.publicKey,
1627
1946
  emulatorPubkey: emuKey,
1628
1947
  // checked before registration below. @see assertExitDelay
1629
- exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay)
1948
+ exitDelay: params.noExit ? void 0 : params.exitDelay ? assertExitDelay(params.exitDelay) : serverExitDelay(info.unilateralExitDelay),
1949
+ ...params.taker && { taker: params.taker }
1630
1950
  });
1631
1951
  const script = offerContract(binding, operatorPubKey, params.contractVersion);
1632
1952
  const offer = { ...binding, swapPkScript: script.pkScript };
@@ -1639,6 +1959,7 @@ async function deriveOffer(wallet, params) {
1639
1959
  address: script.address(network.hrp, operatorPubKey).encode(),
1640
1960
  swapPkScript: script.pkScript,
1641
1961
  binding,
1962
+ offerBinding: Object.freeze(bindingFromOffer(offer, operatorPubKey)),
1642
1963
  info,
1643
1964
  operatorPubkey: operatorPubKey
1644
1965
  });
@@ -1655,7 +1976,7 @@ async function registerDerivedOffer(wallet, derived, options = {}) {
1655
1976
  }
1656
1977
  async function prepareOfferCancel(wallet, offerHex, opts) {
1657
1978
  const { fundingTxid, fundingOutpoint, swapAddress } = opts;
1658
- const offer = decodeOffer(import_base5.hex.decode(offerHex));
1979
+ const decoded = typeof offerHex === "string" ? decodeOffer(import_base5.hex.decode(offerHex)) : isOfferBinding(offerHex) ? void 0 : offerHex;
1659
1980
  const [contractManager, info, reader, broadcaster] = await Promise.all([
1660
1981
  wallet.getContractManager(),
1661
1982
  wallet.getArkadeInfo({ requireLive: true }),
@@ -1672,18 +1993,20 @@ async function prepareOfferCancel(wallet, offerHex, opts) {
1672
1993
  // no `network`: the row lookup is by script and the payout comes from wallet.getAddress()
1673
1994
  oneShotSubmit: wallet.oneShotSubmit
1674
1995
  });
1675
- const operatorPubkey = swapAddress ? import_sdk6.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1996
+ const pinned = swapAddress ? import_sdk6.ArkAddress.decode(swapAddress) : void 0;
1997
+ const funded = decoded ? decoded.swapPkScript : pinned?.pkScript;
1676
1998
  let binding;
1677
1999
  let rebuilt;
1678
2000
  try {
1679
- binding = swapProgramBinding(offer, operatorPubkey);
2001
+ binding = decoded ? swapProgramBinding(decoded, pinned?.serverPubKey ?? client.serverKey) : bindingProgram(offerHex);
1680
2002
  rebuilt = compileSwapBinding(binding);
1681
2003
  } catch (cause) {
1682
- throw new OfferCovenantMismatchError(import_base5.hex.encode(offer.swapPkScript), { cause });
2004
+ throw new OfferCovenantMismatchError(import_base5.hex.encode(funded ?? new Uint8Array()), { cause });
1683
2005
  }
1684
- if (import_base5.hex.encode(rebuilt.pkScript) !== import_base5.hex.encode(offer.swapPkScript)) {
1685
- throw new OfferCovenantMismatchError(import_base5.hex.encode(offer.swapPkScript));
2006
+ if (funded && import_base5.hex.encode(rebuilt.pkScript) !== import_base5.hex.encode(funded)) {
2007
+ throw new OfferCovenantMismatchError(import_base5.hex.encode(funded));
1686
2008
  }
2009
+ const offer = decoded ?? offerOf(offerHex, rebuilt.pkScript);
1687
2010
  const contract = new import_sdk6.arkade.ArkadeContract(client, binding.program, binding.args, binding.keys);
1688
2011
  const [vtxos, makerAddress] = await Promise.all([contract.getUtxos(), wallet.getAddress()]);
1689
2012
  const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
@@ -1715,10 +2038,11 @@ async function connectFillContract(wallet, arkServerUrl, offer, opts = {}) {
1715
2038
  } : {},
1716
2039
  ...emulatorPubkey ? { emulatorPubkey } : {}
1717
2040
  });
1718
- const serverKey = swapAddress ? import_sdk6.ArkAddress.decode(swapAddress).serverPubKey : client.serverKey;
1719
- const binding = swapProgramBinding(offer, serverKey);
2041
+ const pinned = swapAddress ? import_sdk6.ArkAddress.decode(swapAddress) : void 0;
2042
+ const binding = isOfferBinding(offer) ? bindingProgram(offer) : swapProgramBinding(offer, pinned?.serverPubKey ?? client.serverKey);
2043
+ const funded = isOfferBinding(offer) ? pinned?.pkScript : offer.swapPkScript;
1720
2044
  const rebuilt = compileSwapBinding(binding);
1721
- if (import_base5.hex.encode(rebuilt.pkScript) !== import_base5.hex.encode(offer.swapPkScript)) {
2045
+ if (funded && import_base5.hex.encode(rebuilt.pkScript) !== import_base5.hex.encode(funded)) {
1722
2046
  throw new Error(
1723
2047
  "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"
1724
2048
  );
@@ -2034,7 +2358,7 @@ function assertFillCoin(coin, what) {
2034
2358
  toAmount(coin.value, `${what}.value`, "sats", BigInt(1));
2035
2359
  assertAssetEntries(coin.assets, what);
2036
2360
  }
2037
- var import_base5, import_utils2, import_sdk6, 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;
2361
+ var import_base5, import_utils2, import_sdk6, 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;
2038
2362
  var init_offer = __esm({
2039
2363
  "src/offer.ts"() {
2040
2364
  "use strict";
@@ -2046,11 +2370,67 @@ var init_offer = __esm({
2046
2370
  init_rfqProfileParts();
2047
2371
  init_store();
2048
2372
  compiledBindings = /* @__PURE__ */ new WeakMap();
2373
+ isOfferBinding = (offer) => "version" in offer;
2374
+ termsOf = (binding) => ({
2375
+ wantAmount: binding.amount,
2376
+ ...binding.wantAsset && { wantAsset: binding.wantAsset },
2377
+ ...binding.offerAsset && { offerAsset: binding.offerAsset },
2378
+ makerPkScript: binding.receiverPkScript,
2379
+ makerPublicKey: binding.userPublicKey,
2380
+ emulatorPubkey: binding.emulatorPublicKey,
2381
+ ...binding.exitDelay && { exitDelay: binding.exitDelay },
2382
+ ...binding.taker && { taker: binding.taker }
2383
+ });
2384
+ offerOf = (offer, swapPkScript) => isOfferBinding(offer) ? { ...termsOf(offer), swapPkScript } : offer;
2385
+ recordOfferBinding = (binding) => ({
2386
+ version: binding.version,
2387
+ receiverPkScript: import_base5.hex.encode(binding.receiverPkScript),
2388
+ amount: binding.amount.toString(),
2389
+ ...binding.wantAsset && { wantAsset: binding.wantAsset.toString() },
2390
+ ...binding.offerAsset && { offerAsset: binding.offerAsset.toString() },
2391
+ userPublicKey: import_base5.hex.encode(binding.userPublicKey),
2392
+ serverPublicKey: import_base5.hex.encode(binding.serverPublicKey),
2393
+ emulatorPublicKey: import_base5.hex.encode(binding.emulatorPublicKey),
2394
+ ...binding.exitDelay && {
2395
+ exitDelay: { type: binding.exitDelay.type, value: binding.exitDelay.value.toString() }
2396
+ },
2397
+ ...binding.taker && { taker: import_base5.hex.encode(binding.taker) }
2398
+ });
2399
+ decimal = (value, name) => {
2400
+ if (!/^\d+$/.test(value)) throw new Error(`recorded binding ${name} is not a decimal amount`);
2401
+ return BigInt(value);
2402
+ };
2403
+ offerBindingOf = (recorded) => {
2404
+ if (typeof recorded.version !== "string" || !Object.hasOwn(ASSET_SWAP_CONTRACTS, recorded.version)) {
2405
+ throw new Error(`recorded binding names no known contract version (${recorded.version})`);
2406
+ }
2407
+ const { exitDelay, wantAsset, offerAsset, taker } = recorded;
2408
+ return {
2409
+ version: recorded.version,
2410
+ receiverPkScript: import_base5.hex.decode(recorded.receiverPkScript),
2411
+ amount: decimal(recorded.amount, "amount"),
2412
+ ...wantAsset !== void 0 && { wantAsset: import_sdk6.asset.AssetId.fromString(wantAsset) },
2413
+ ...offerAsset !== void 0 && { offerAsset: import_sdk6.asset.AssetId.fromString(offerAsset) },
2414
+ userPublicKey: import_base5.hex.decode(recorded.userPublicKey),
2415
+ serverPublicKey: import_base5.hex.decode(recorded.serverPublicKey),
2416
+ emulatorPublicKey: import_base5.hex.decode(recorded.emulatorPublicKey),
2417
+ ...exitDelay && {
2418
+ exitDelay: { type: exitDelay.type, value: decimal(exitDelay.value, "exitDelay") }
2419
+ },
2420
+ ...taker !== void 0 && { taker: import_base5.hex.decode(taker) }
2421
+ };
2422
+ };
2423
+ storedOffer = (swap) => {
2424
+ if (swap.binding !== void 0) return offerBindingOf(swap.binding);
2425
+ if (typeof swap.offerHex === "string") return decodeOffer(import_base5.hex.decode(swap.offerHex));
2426
+ throw new Error("this offer swap carries neither a binding nor an offerHex to rebuild from");
2427
+ };
2049
2428
  OFFER_PACKET_TYPE = 3;
2050
2429
  FIELDS = {
2051
2430
  swapPkScript: { tag: 1, width: 34 },
2052
2431
  wantAmount: { tag: 2, width: 8 },
2053
2432
  wantAsset: { tag: 3, width: void 0 },
2433
+ taker: { tag: 4, width: 32 },
2054
2434
  makerPkScript: { tag: 5, width: 34 },
2055
2435
  makerPublicKey: { tag: 7, width: 32 },
2056
2436
  emulatorPubkey: { tag: 8, width: 32 },
@@ -2671,7 +3051,7 @@ var init_rfq = __esm({
2671
3051
  const version = selected ?? ASSET_SWAP_BASELINE;
2672
3052
  if (!advertised.includes(version)) {
2673
3053
  throw new Error(
2674
- `solver chose contract version ${version}, not one of ${advertised.join(", ")}`
3054
+ selected === void 0 ? `solver negotiated no contract version; advertised ${advertised.join(", ")}` : `solver chose contract version ${version}, not one of ${advertised.join(", ")}`
2675
3055
  );
2676
3056
  }
2677
3057
  return { quote, rfqId: sent.rfq_id, contractVersion: assetSwapContractVersion(version) };
@@ -2808,6 +3188,9 @@ var init_rfq = __esm({
2808
3188
  if (input.now >= input.payDeadline) {
2809
3189
  throw gateError("quote_expired", "quote or invoice already expired \u2014 request a fresh one");
2810
3190
  }
3191
+ if (quoteAmountSats(input.quote.from_amount, "from_amount") <= 0n || quoteAmountSats(input.quote.to_amount, "to_amount") <= 0n) {
3192
+ throw gateError("non_positive_amount", "quote carries a non-positive amount");
3193
+ }
2811
3194
  if (input.quote.refund_locktime === void 0) {
2812
3195
  throw gateError("missing_refund_locktime", "receive quote carries no refund_locktime");
2813
3196
  }
@@ -2848,6 +3231,191 @@ var init_rfq = __esm({
2848
3231
  }
2849
3232
  });
2850
3233
 
3234
+ // src/client/errors.ts
3235
+ function isSwapError(e, name) {
3236
+ if (!(e instanceof Error)) return false;
3237
+ const table = SWAP_ERRORS;
3238
+ const ctor = table[e.name];
3239
+ if (ctor === void 0 || !(e instanceof ctor)) return false;
3240
+ return name === void 0 || e.name === name;
3241
+ }
3242
+ var AmbiguousDestination, UnsupportedRoute, DiscoverySnapshotUnavailable, AmountMismatch, AmountEncodingUnsupported, QuoteVerificationFailed, QuoteExpired, MaxFeeExceeded, InsufficientFunds, AcceptConflict, ClientDisposed, NotCancellable, InconsistentRoute, OperatorUnreachable, MissingCorridorDep, SWAP_ERRORS, SWAP_ERROR_NAMES;
3243
+ var init_errors = __esm({
3244
+ "src/client/errors.ts"() {
3245
+ "use strict";
3246
+ init_rfq();
3247
+ AmbiguousDestination = class extends Error {
3248
+ constructor(destination, detail) {
3249
+ super(`cannot route ${JSON.stringify(destination)}: ${detail}`);
3250
+ this.destination = destination;
3251
+ }
3252
+ destination;
3253
+ name = "AmbiguousDestination";
3254
+ };
3255
+ UnsupportedRoute = class extends Error {
3256
+ name = "UnsupportedRoute";
3257
+ give;
3258
+ take;
3259
+ constructor(detail, corridors = {}) {
3260
+ super(`unsupported route: ${detail}`);
3261
+ this.give = corridors.give;
3262
+ this.take = corridors.take;
3263
+ }
3264
+ };
3265
+ DiscoverySnapshotUnavailable = class extends Error {
3266
+ constructor(network, detail) {
3267
+ super(`cannot resolve on ${network} offline: ${detail}`);
3268
+ this.network = network;
3269
+ }
3270
+ network;
3271
+ name = "DiscoverySnapshotUnavailable";
3272
+ };
3273
+ AmountMismatch = class extends Error {
3274
+ constructor(sources) {
3275
+ super(`exactly one amount may be pinned; got ${sources[0]} and ${sources[1]}`);
3276
+ this.sources = sources;
3277
+ }
3278
+ sources;
3279
+ name = "AmountMismatch";
3280
+ };
3281
+ AmountEncodingUnsupported = class extends Error {
3282
+ constructor(field, value, detail, options) {
3283
+ super(`${field}: ${detail}`, options);
3284
+ this.field = field;
3285
+ this.value = value;
3286
+ }
3287
+ field;
3288
+ value;
3289
+ name = "AmountEncodingUnsupported";
3290
+ };
3291
+ QuoteVerificationFailed = class extends Error {
3292
+ constructor(check, expected, actual, options) {
3293
+ super(`quote failed the ${check} check \u2014 refusing to fund`, options);
3294
+ this.check = check;
3295
+ this.expected = expected;
3296
+ this.actual = actual;
3297
+ }
3298
+ check;
3299
+ name = "QuoteVerificationFailed";
3300
+ expected;
3301
+ actual;
3302
+ };
3303
+ QuoteExpired = class extends Error {
3304
+ constructor(quoteId, expiresAt, now) {
3305
+ super(`quote ${quoteId} expired at ${expiresAt}, ${now - expiresAt} ago`);
3306
+ this.quoteId = quoteId;
3307
+ this.expiresAt = expiresAt;
3308
+ this.now = now;
3309
+ }
3310
+ quoteId;
3311
+ expiresAt;
3312
+ now;
3313
+ name = "QuoteExpired";
3314
+ };
3315
+ MaxFeeExceeded = class extends Error {
3316
+ constructor(quoteId, asset8, fee, maxFee) {
3317
+ super(`fee ${fee} of ${asset8} exceeds the ${maxFee} ceiling`);
3318
+ this.quoteId = quoteId;
3319
+ this.asset = asset8;
3320
+ this.fee = fee;
3321
+ this.maxFee = maxFee;
3322
+ }
3323
+ quoteId;
3324
+ asset;
3325
+ fee;
3326
+ maxFee;
3327
+ name = "MaxFeeExceeded";
3328
+ };
3329
+ InsufficientFunds = class extends Error {
3330
+ constructor(asset8, required, available) {
3331
+ super(
3332
+ `funding needs ${required} of ${asset8}` + (available === void 0 ? "" : `, wallet holds ${available}`)
3333
+ );
3334
+ this.asset = asset8;
3335
+ this.required = required;
3336
+ this.available = available;
3337
+ }
3338
+ asset;
3339
+ required;
3340
+ name = "InsufficientFunds";
3341
+ available;
3342
+ };
3343
+ AcceptConflict = class extends Error {
3344
+ constructor(quoteId, swapId, fields) {
3345
+ super(`accept ${quoteId} conflicts with swap ${swapId} on ${fields.join(", ")}`);
3346
+ this.quoteId = quoteId;
3347
+ this.swapId = swapId;
3348
+ this.fields = fields;
3349
+ }
3350
+ quoteId;
3351
+ swapId;
3352
+ fields;
3353
+ name = "AcceptConflict";
3354
+ };
3355
+ ClientDisposed = class extends Error {
3356
+ constructor(method) {
3357
+ super(`${method}() called after the client was disposed`);
3358
+ this.method = method;
3359
+ }
3360
+ method;
3361
+ name = "ClientDisposed";
3362
+ };
3363
+ NotCancellable = class extends Error {
3364
+ constructor(swapId) {
3365
+ super(`swap ${swapId} is not a cancellable asset swap`);
3366
+ this.swapId = swapId;
3367
+ }
3368
+ swapId;
3369
+ name = "NotCancellable";
3370
+ };
3371
+ InconsistentRoute = class extends Error {
3372
+ constructor(asset8, destination) {
3373
+ super(`destination ${JSON.stringify(destination)} is not on ${asset8}'s chain`);
3374
+ this.asset = asset8;
3375
+ this.destination = destination;
3376
+ }
3377
+ asset;
3378
+ destination;
3379
+ name = "InconsistentRoute";
3380
+ };
3381
+ OperatorUnreachable = class extends Error {
3382
+ name = "OperatorUnreachable";
3383
+ constructor(detail, options) {
3384
+ super(`cannot derive a covenant: ${detail}`, options);
3385
+ }
3386
+ };
3387
+ MissingCorridorDep = class extends Error {
3388
+ constructor(corridor, dep) {
3389
+ super(`the ${corridor} corridor has no ${dep}`);
3390
+ this.corridor = corridor;
3391
+ this.dep = dep;
3392
+ }
3393
+ corridor;
3394
+ dep;
3395
+ name = "MissingCorridorDep";
3396
+ };
3397
+ SWAP_ERRORS = {
3398
+ AmbiguousDestination,
3399
+ UnsupportedRoute,
3400
+ DiscoverySnapshotUnavailable,
3401
+ AmountMismatch,
3402
+ AmountEncodingUnsupported,
3403
+ QuoteVerificationFailed,
3404
+ SwapRefusal,
3405
+ QuoteExpired,
3406
+ MaxFeeExceeded,
3407
+ InsufficientFunds,
3408
+ AcceptConflict,
3409
+ ClientDisposed,
3410
+ NotCancellable,
3411
+ InconsistentRoute,
3412
+ OperatorUnreachable,
3413
+ MissingCorridorDep
3414
+ };
3415
+ SWAP_ERROR_NAMES = Object.keys(SWAP_ERRORS);
3416
+ }
3417
+ });
3418
+
2851
3419
  // src/closeOnceWebSocket.ts
2852
3420
  var CloseOnceWebSocket;
2853
3421
  var init_closeOnceWebSocket = __esm({
@@ -3047,6 +3615,7 @@ var init_nostr = __esm({
3047
3615
  { kinds: [RFQ_DIRECTED_KIND], "#p": [pubkey], authors: [solverPubkey] },
3048
3616
  {
3049
3617
  onevent(event) {
3618
+ if (event.pubkey !== solverPubkey || !(0, import_nostr_tools2.verifyEvent)(event)) return;
3050
3619
  let payload;
3051
3620
  try {
3052
3621
  payload = JSON.parse(import_nostr_tools2.nip44.v2.decrypt(event.content, conversationKey));
@@ -3220,6 +3789,245 @@ var init_nostr = __esm({
3220
3789
  }
3221
3790
  });
3222
3791
 
3792
+ // src/client/policy.ts
3793
+ var DEFAULT_MAX_REFUND_WINDOW_SECONDS;
3794
+ var init_policy = __esm({
3795
+ "src/client/policy.ts"() {
3796
+ "use strict";
3797
+ DEFAULT_MAX_REFUND_WINDOW_SECONDS = 30 * 24 * 3600;
3798
+ }
3799
+ });
3800
+
3801
+ // src/client/verify.ts
3802
+ 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;
3803
+ var init_verify = __esm({
3804
+ "src/client/verify.ts"() {
3805
+ "use strict";
3806
+ import_base21 = require("@scure/base");
3807
+ init_rfq();
3808
+ init_errors();
3809
+ init_policy();
3810
+ reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
3811
+ CHECK_BY_REASON = {
3812
+ invoice_expired: "invoice",
3813
+ invoice_undecodable: "invoice",
3814
+ invoice_hash_mismatch: "invoice",
3815
+ invoice_amount_mismatch: "invoice",
3816
+ insufficient_headroom: "refund_window",
3817
+ missing_refund_locktime: "refund_window",
3818
+ claim_window_too_short: "refund_window",
3819
+ confirmations_out_of_range: "refund_window",
3820
+ timelock_order: "refund_window",
3821
+ quote_malformed: "refund_window"
3822
+ };
3823
+ gated = (run, quote) => {
3824
+ try {
3825
+ run();
3826
+ } catch (error) {
3827
+ const reason = reasonOf(error);
3828
+ if (reason === "quote_expired") {
3829
+ throw new QuoteExpired(quote.id, quote.expiresAt, quote.now);
3830
+ }
3831
+ const check = reason === void 0 ? void 0 : CHECK_BY_REASON[reason];
3832
+ if (check === void 0) throw error;
3833
+ throw new QuoteVerificationFailed(
3834
+ check,
3835
+ void 0,
3836
+ error instanceof Error ? error.message : String(error),
3837
+ { cause: error }
3838
+ );
3839
+ }
3840
+ };
3841
+ verifyResponder = (input) => {
3842
+ if (!input.pinnable || input.expected === void 0) {
3843
+ throw new QuoteVerificationFailed(
3844
+ "responder",
3845
+ "a registry-served card naming the solver's discovery key",
3846
+ input.expected === void 0 ? "the card names no discovery key" : "the card came out of the local cache, which does not authenticate it"
3847
+ );
3848
+ }
3849
+ if (input.attested === void 0) {
3850
+ throw new QuoteVerificationFailed(
3851
+ "responder",
3852
+ input.expected,
3853
+ "the transport attests nobody"
3854
+ );
3855
+ }
3856
+ if (input.attested !== input.expected) {
3857
+ throw new QuoteVerificationFailed("responder", input.expected, input.attested);
3858
+ }
3859
+ };
3860
+ verifyTaker = (input) => {
3861
+ const xOnly = (key) => typeof key === "string" && /^[0-9a-f]{64}$/i.test(key) ? import_base21.hex.decode(key.toLowerCase()) : void 0;
3862
+ const taker = xOnly(input.solverPubkey);
3863
+ const attested = xOnly(input.attested);
3864
+ if (taker === void 0 || attested === void 0 || import_base21.hex.encode(taker) !== import_base21.hex.encode(attested)) {
3865
+ throw new QuoteVerificationFailed("responder", input.attested, String(input.solverPubkey));
3866
+ }
3867
+ return taker;
3868
+ };
3869
+ verifyPair = (quoted, requested) => {
3870
+ if (quoted !== requested) {
3871
+ throw new QuoteVerificationFailed("pair", requested, String(quoted));
3872
+ }
3873
+ };
3874
+ verifyingDerivation = (derive) => {
3875
+ try {
3876
+ return derive();
3877
+ } catch (error) {
3878
+ if (error instanceof AddressMismatch) {
3879
+ const derived = Array.isArray(error.derived) ? error.derived.join(", ") : error.derived;
3880
+ throw new QuoteVerificationFailed("lockup_address", derived, error.quoted, {
3881
+ cause: error
3882
+ });
3883
+ }
3884
+ if (error instanceof Error) {
3885
+ throw new QuoteVerificationFailed("lockup_address", void 0, error.message, {
3886
+ cause: error
3887
+ });
3888
+ }
3889
+ throw error;
3890
+ }
3891
+ };
3892
+ verifySendWindow = (input) => {
3893
+ gated(
3894
+ () => assertFundable({
3895
+ quote: input.quote,
3896
+ now: input.now,
3897
+ ...input.invoiceExpiresAt === void 0 ? {} : { invoiceExpiresAt: input.invoiceExpiresAt },
3898
+ ...input.onchain === void 0 ? {} : { onchain: input.onchain }
3899
+ }),
3900
+ { id: input.quoteId, expiresAt: input.quote.valid_until, now: input.now }
3901
+ );
3902
+ };
3903
+ verifyReceiveWindow = (input) => {
3904
+ gated(
3905
+ () => assertReceivable({
3906
+ quote: input.quote,
3907
+ payDeadline: input.payDeadline,
3908
+ now: input.now
3909
+ }),
3910
+ { id: input.quoteId, expiresAt: input.payDeadline, now: input.now }
3911
+ );
3912
+ };
3913
+ verifySendInvoice = (input) => {
3914
+ const invoiced = input.invoiced;
3915
+ if (input.take !== invoiced) {
3916
+ throw new QuoteVerificationFailed("invoice", `${invoiced}`, `${input.take}`);
3917
+ }
3918
+ if (input.give < input.take) {
3919
+ throw new QuoteVerificationFailed(
3920
+ "invoice",
3921
+ `at least the invoice's ${invoiced}`,
3922
+ `${input.give}, a negative spread`
3923
+ );
3924
+ }
3925
+ };
3926
+ verifyReceiveInvoiceFacts = (input) => {
3927
+ let decoded;
3928
+ try {
3929
+ decoded = input.decode(input.invoice);
3930
+ } catch (cause) {
3931
+ throw new QuoteVerificationFailed(
3932
+ "invoice",
3933
+ "a decodable BOLT11",
3934
+ cause instanceof Error ? cause.message : String(cause),
3935
+ { cause }
3936
+ );
3937
+ }
3938
+ if (!Number.isFinite(decoded.expiresAt)) {
3939
+ throw new QuoteVerificationFailed("invoice", "a finite expiry", `${decoded.expiresAt}`);
3940
+ }
3941
+ if (!Number.isFinite(input.validUntil)) {
3942
+ throw new QuoteVerificationFailed(
3943
+ "refund_window",
3944
+ "a finite valid_until",
3945
+ `${input.validUntil}`
3946
+ );
3947
+ }
3948
+ if (decoded.paymentHash !== input.paymentHash) {
3949
+ throw new QuoteVerificationFailed("invoice", input.paymentHash, decoded.paymentHash);
3950
+ }
3951
+ if (!Number.isSafeInteger(decoded.amountSats) || decoded.amountSats <= 0) {
3952
+ throw new QuoteVerificationFailed(
3953
+ "invoice",
3954
+ `${input.payAmount}`,
3955
+ "the invoice names no amount"
3956
+ );
3957
+ }
3958
+ if (BigInt(decoded.amountSats) !== input.payAmount) {
3959
+ throw new QuoteVerificationFailed("invoice", `${input.payAmount}`, `${decoded.amountSats}`);
3960
+ }
3961
+ return { payDeadline: Math.min(decoded.expiresAt, input.validUntil) };
3962
+ };
3963
+ verifyQuoteTtl = (input) => {
3964
+ const floor = input.floorSeconds ?? 0;
3965
+ if (input.expiresAt - input.now <= floor) {
3966
+ throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
3967
+ }
3968
+ };
3969
+ CSV_GRANULARITY_SECONDS = 512;
3970
+ verifyRefundWindow = (input) => {
3971
+ const max = input.maxSeconds ?? DEFAULT_MAX_REFUND_WINDOW_SECONDS;
3972
+ const window = input.refundLocktime - input.now;
3973
+ if (!(window <= max)) {
3974
+ throw new QuoteVerificationFailed("refund_window", `at most ${max}s`, `${window}s`);
3975
+ }
3976
+ const delay = input.refundWithoutReceiverDelay;
3977
+ if (delay !== void 0 && !(delay < max + CSV_GRANULARITY_SECONDS)) {
3978
+ throw new QuoteVerificationFailed(
3979
+ "refund_window",
3980
+ `a solo-refund delay of at most ${max}s`,
3981
+ `${delay}s`
3982
+ );
3983
+ }
3984
+ };
3985
+ verifyQuotedAmount = (input) => {
3986
+ verifyPinnedAmount(input);
3987
+ if (input.take > input.give) {
3988
+ throw new QuoteVerificationFailed(
3989
+ "pair",
3990
+ `${input.pair} give >= take`,
3991
+ `give=${input.give} take=${input.take}`
3992
+ );
3993
+ }
3994
+ };
3995
+ verifyCrossAssetAmount = (input) => {
3996
+ verifyPinnedAmount(input);
3997
+ if (input.give <= 0n || input.take <= 0n) {
3998
+ throw new QuoteVerificationFailed(
3999
+ "pair",
4000
+ `${input.pair} give > 0 take > 0`,
4001
+ `give=${input.give} take=${input.take}`
4002
+ );
4003
+ }
4004
+ };
4005
+ verifiedCarrierSats = (quote) => {
4006
+ try {
4007
+ return quoteCarrierSats(quote);
4008
+ } catch (error) {
4009
+ if (reasonOf(error) !== "carrier_malformed") throw error;
4010
+ throw new QuoteVerificationFailed(
4011
+ "pair",
4012
+ "carrier_sats a non-negative integer",
4013
+ String(quote.carrier_sats),
4014
+ { cause: error }
4015
+ );
4016
+ }
4017
+ };
4018
+ verifyPinnedAmount = (input) => {
4019
+ const quoted = input.pinned.on === "give" ? input.give : input.take;
4020
+ if (quoted !== input.pinned.value) {
4021
+ throw new QuoteVerificationFailed(
4022
+ "pair",
4023
+ `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
4024
+ `${input.pair} ${input.pinned.on}=${quoted}`
4025
+ );
4026
+ }
4027
+ };
4028
+ }
4029
+ });
4030
+
3223
4031
  // src/index.ts
3224
4032
  var index_exports = {};
3225
4033
  __export(index_exports, {
@@ -3312,7 +4120,7 @@ __export(index_exports, {
3312
4120
  module.exports = __toCommonJS(index_exports);
3313
4121
 
3314
4122
  // src/client/client.ts
3315
- var import_base23 = require("@scure/base");
4123
+ var import_base24 = require("@scure/base");
3316
4124
  var import_sdk38 = require("@arkade-os/sdk");
3317
4125
  init_repository();
3318
4126
 
@@ -3565,184 +4373,8 @@ var CORRIDOR_BY_RAIL = {
3565
4373
  var railOfCorridor = (corridor) => corridor in RAIL_BY_CORRIDOR ? RAIL_BY_CORRIDOR[corridor] : "eip155";
3566
4374
  var corridorOfRail = (rail) => rail === "eip155" ? void 0 : CORRIDOR_BY_RAIL[rail];
3567
4375
 
3568
- // src/client/errors.ts
3569
- init_rfq();
3570
- var AmbiguousDestination = class extends Error {
3571
- constructor(destination, detail) {
3572
- super(`cannot route ${JSON.stringify(destination)}: ${detail}`);
3573
- this.destination = destination;
3574
- }
3575
- destination;
3576
- name = "AmbiguousDestination";
3577
- };
3578
- var UnsupportedRoute = class extends Error {
3579
- name = "UnsupportedRoute";
3580
- give;
3581
- take;
3582
- constructor(detail, corridors = {}) {
3583
- super(`unsupported route: ${detail}`);
3584
- this.give = corridors.give;
3585
- this.take = corridors.take;
3586
- }
3587
- };
3588
- var DiscoverySnapshotUnavailable = class extends Error {
3589
- constructor(network, detail) {
3590
- super(`cannot resolve on ${network} offline: ${detail}`);
3591
- this.network = network;
3592
- }
3593
- network;
3594
- name = "DiscoverySnapshotUnavailable";
3595
- };
3596
- var AmountMismatch = class extends Error {
3597
- constructor(sources) {
3598
- super(`exactly one amount may be pinned; got ${sources[0]} and ${sources[1]}`);
3599
- this.sources = sources;
3600
- }
3601
- sources;
3602
- name = "AmountMismatch";
3603
- };
3604
- var AmountEncodingUnsupported = class extends Error {
3605
- constructor(field, value, detail, options) {
3606
- super(`${field}: ${detail}`, options);
3607
- this.field = field;
3608
- this.value = value;
3609
- }
3610
- field;
3611
- value;
3612
- name = "AmountEncodingUnsupported";
3613
- };
3614
- var QuoteVerificationFailed = class extends Error {
3615
- constructor(check, expected, actual, options) {
3616
- super(`quote failed the ${check} check \u2014 refusing to fund`, options);
3617
- this.check = check;
3618
- this.expected = expected;
3619
- this.actual = actual;
3620
- }
3621
- check;
3622
- name = "QuoteVerificationFailed";
3623
- expected;
3624
- actual;
3625
- };
3626
- var QuoteExpired = class extends Error {
3627
- constructor(quoteId, expiresAt, now) {
3628
- super(`quote ${quoteId} expired at ${expiresAt}, ${now - expiresAt} ago`);
3629
- this.quoteId = quoteId;
3630
- this.expiresAt = expiresAt;
3631
- this.now = now;
3632
- }
3633
- quoteId;
3634
- expiresAt;
3635
- now;
3636
- name = "QuoteExpired";
3637
- };
3638
- var MaxFeeExceeded = class extends Error {
3639
- constructor(quoteId, asset8, fee, maxFee) {
3640
- super(`fee ${fee} of ${asset8} exceeds the ${maxFee} ceiling`);
3641
- this.quoteId = quoteId;
3642
- this.asset = asset8;
3643
- this.fee = fee;
3644
- this.maxFee = maxFee;
3645
- }
3646
- quoteId;
3647
- asset;
3648
- fee;
3649
- maxFee;
3650
- name = "MaxFeeExceeded";
3651
- };
3652
- var InsufficientFunds = class extends Error {
3653
- constructor(asset8, required, available) {
3654
- super(
3655
- `funding needs ${required} of ${asset8}` + (available === void 0 ? "" : `, wallet holds ${available}`)
3656
- );
3657
- this.asset = asset8;
3658
- this.required = required;
3659
- this.available = available;
3660
- }
3661
- asset;
3662
- required;
3663
- name = "InsufficientFunds";
3664
- available;
3665
- };
3666
- var AcceptConflict = class extends Error {
3667
- constructor(quoteId, swapId, fields) {
3668
- super(`accept ${quoteId} conflicts with swap ${swapId} on ${fields.join(", ")}`);
3669
- this.quoteId = quoteId;
3670
- this.swapId = swapId;
3671
- this.fields = fields;
3672
- }
3673
- quoteId;
3674
- swapId;
3675
- fields;
3676
- name = "AcceptConflict";
3677
- };
3678
- var ClientDisposed = class extends Error {
3679
- constructor(method) {
3680
- super(`${method}() called after the client was disposed`);
3681
- this.method = method;
3682
- }
3683
- method;
3684
- name = "ClientDisposed";
3685
- };
3686
- var NotCancellable = class extends Error {
3687
- constructor(swapId) {
3688
- super(`swap ${swapId} is not a cancellable asset swap`);
3689
- this.swapId = swapId;
3690
- }
3691
- swapId;
3692
- name = "NotCancellable";
3693
- };
3694
- var InconsistentRoute = class extends Error {
3695
- constructor(asset8, destination) {
3696
- super(`destination ${JSON.stringify(destination)} is not on ${asset8}'s chain`);
3697
- this.asset = asset8;
3698
- this.destination = destination;
3699
- }
3700
- asset;
3701
- destination;
3702
- name = "InconsistentRoute";
3703
- };
3704
- var OperatorUnreachable = class extends Error {
3705
- name = "OperatorUnreachable";
3706
- constructor(detail, options) {
3707
- super(`cannot derive a covenant: ${detail}`, options);
3708
- }
3709
- };
3710
- var MissingCorridorDep = class extends Error {
3711
- constructor(corridor, dep) {
3712
- super(`the ${corridor} corridor has no ${dep}`);
3713
- this.corridor = corridor;
3714
- this.dep = dep;
3715
- }
3716
- corridor;
3717
- dep;
3718
- name = "MissingCorridorDep";
3719
- };
3720
- var SWAP_ERRORS = {
3721
- AmbiguousDestination,
3722
- UnsupportedRoute,
3723
- DiscoverySnapshotUnavailable,
3724
- AmountMismatch,
3725
- AmountEncodingUnsupported,
3726
- QuoteVerificationFailed,
3727
- SwapRefusal,
3728
- QuoteExpired,
3729
- MaxFeeExceeded,
3730
- InsufficientFunds,
3731
- AcceptConflict,
3732
- ClientDisposed,
3733
- NotCancellable,
3734
- InconsistentRoute,
3735
- OperatorUnreachable,
3736
- MissingCorridorDep
3737
- };
3738
- var SWAP_ERROR_NAMES = Object.keys(SWAP_ERRORS);
3739
- function isSwapError(e, name) {
3740
- if (!(e instanceof Error)) return false;
3741
- const table = SWAP_ERRORS;
3742
- const ctor = table[e.name];
3743
- if (ctor === void 0 || !(e instanceof ctor)) return false;
3744
- return name === void 0 || e.name === name;
3745
- }
4376
+ // src/client/corridors/registry.ts
4377
+ init_errors();
3746
4378
 
3747
4379
  // src/client/corridors/arkade.ts
3748
4380
  var import_sdk10 = require("@arkade-os/sdk");
@@ -3826,6 +4458,7 @@ var chainSourceFrom = (provider, network) => {
3826
4458
  // src/client/corridors/deps.ts
3827
4459
  init_onchainHtlc();
3828
4460
  init_rfq();
4461
+ init_errors();
3829
4462
 
3830
4463
  // src/client/corridors/bolt11.ts
3831
4464
  var import_light_bolt11_decoder = __toESM(require("light-bolt11-decoder"), 1);
@@ -4533,6 +5166,7 @@ var issuanceOf = (id) => {
4533
5166
  };
4534
5167
 
4535
5168
  // src/client/aliases.ts
5169
+ init_errors();
4536
5170
  var toDiscoveryLeg = (id) => {
4537
5171
  const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
4538
5172
  const asset8 = `${assetNamespace}:${assetReference}`;
@@ -4585,6 +5219,7 @@ var canonicalAssetId = (input, table) => {
4585
5219
  };
4586
5220
 
4587
5221
  // src/client/discovery.ts
5222
+ init_errors();
4588
5223
  var REGISTRY_URL = {
4589
5224
  bitcoin: "https://arkade-os.github.io/solver-registry/bitcoin.json",
4590
5225
  signet: "https://arkade-os.github.io/solver-registry/signet.json",
@@ -4741,6 +5376,9 @@ var discoveryIndex = (input) => {
4741
5376
  return { peek, load };
4742
5377
  };
4743
5378
 
5379
+ // src/client/client.ts
5380
+ init_errors();
5381
+
4744
5382
  // src/client/accept.ts
4745
5383
  var import_base12 = require("@scure/base");
4746
5384
  var import_solver_discovery9 = require("@arkade-os/solver-discovery");
@@ -5528,8 +6166,12 @@ var recordOutcome = (record) => {
5528
6166
  return record.status === void 0 ? "funding" : offerOutcome(record.status);
5529
6167
  };
5530
6168
 
6169
+ // src/client/accept.ts
6170
+ init_errors();
6171
+
5531
6172
  // src/client/rfqAmount.ts
5532
6173
  var import_solver_discovery8 = require("@arkade-os/solver-discovery");
6174
+ init_errors();
5533
6175
  var toRfqAmountSide = (on) => on === "give" ? "from" : "to";
5534
6176
  var encodeRfqAmount = (value, field) => {
5535
6177
  try {
@@ -5779,7 +6421,8 @@ var acceptQuoteBody = async (input) => {
5779
6421
  }
5780
6422
  const funds = fundsFromWallet(quote.route);
5781
6423
  if (funds) await assertFundable2(wallet, quote);
5782
- const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
6424
+ const built = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
6425
+ const record = built.family === "offer" && input.attachOfferPacket === false ? { ...built, attachOfferPacket: false } : built;
5783
6426
  await repository.saveSwapRecord(record);
5784
6427
  if (!funds) return answer(record);
5785
6428
  return answer(
@@ -5799,7 +6442,7 @@ var acceptQuoteBody = async (input) => {
5799
6442
  var registeredOfferRecord = async (input, preparation) => {
5800
6443
  const { quote, wallet, corridors, now } = input;
5801
6444
  const { plan } = preparation;
5802
- const arkade4 = corridors.get("arkade").deps;
6445
+ const arkade5 = corridors.get("arkade").deps;
5803
6446
  const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
5804
6447
  const offer = await createOffer(
5805
6448
  wallet,
@@ -5807,7 +6450,7 @@ var registeredOfferRecord = async (input, preparation) => {
5807
6450
  // Keyed on the receive side: the covenant binds what the fill delivers.
5808
6451
  wantAmount: plan.receive.atomic,
5809
6452
  ...receiveIsBtc ? { offerAsset: import_sdk21.asset.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: import_sdk21.asset.AssetId.fromString(plan.receive.asset.id) },
5810
- emulatorPubkey: arkade4.emulatorPubkey
6453
+ emulatorPubkey: arkade5.emulatorPubkey
5811
6454
  },
5812
6455
  { coverageId: quote.id }
5813
6456
  );
@@ -5835,7 +6478,9 @@ var registeredAssetRecord = async (input, preparation) => {
5835
6478
  ...preparation.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(preparation.assetPayment) },
5836
6479
  family: "offer",
5837
6480
  status: "pending",
5838
- offerHex: preparation.offer.offerHex,
6481
+ // a directed covenant is kept as its binding alone, which an older reader drops whole
6482
+ // rather than half-reads
6483
+ ...preparation.offer.offerBinding.taker === void 0 ? { offerHex: preparation.offer.offerHex } : { binding: recordOfferBinding(preparation.offer.offerBinding) },
5839
6484
  swapAddress: preparation.offer.address,
5840
6485
  swapPkScript: import_base12.hex.encode(preparation.offer.swapPkScript),
5841
6486
  ...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
@@ -5920,7 +6565,7 @@ var fund = async (input, record) => {
5920
6565
  { assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
5921
6566
  ]
5922
6567
  },
5923
- extensions: [offerExtensionOf(record)]
6568
+ ...record.attachOfferPacket === false ? {} : { extensions: [offerExtensionOf(record)] }
5924
6569
  });
5925
6570
  }
5926
6571
  if (record.kind === "lightning_receive" || record.kind === "onchain_receive") {
@@ -5931,10 +6576,13 @@ var fund = async (input, record) => {
5931
6576
  amount: toSafeNumber(fromAtomicDecimal(record.give.amount), "give.amount")
5932
6577
  });
5933
6578
  };
5934
- var offerExtensionOf = (record) => ({
5935
- type: OFFER_PACKET_TYPE,
5936
- payload: import_base12.hex.decode(record.offerHex)
5937
- });
6579
+ var offerExtensionOf = (record) => {
6580
+ const stored = storedOffer(record);
6581
+ return {
6582
+ type: OFFER_PACKET_TYPE,
6583
+ payload: record.offerHex !== void 0 ? import_base12.hex.decode(record.offerHex) : encodeOffer("version" in stored ? offerFromBinding(stored) : stored)
6584
+ };
6585
+ };
5938
6586
  var reconcileFunding = async (input, record) => {
5939
6587
  const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
5940
6588
  const expected = BigInt(record.give.amount);
@@ -6000,8 +6648,16 @@ var unscannedSwapCandidates = (txs, existingIds, scanned) => txs.filter(
6000
6648
  function classifySpend(offer, operatorPubkey, spendTx, deposit) {
6001
6649
  let leaves;
6002
6650
  try {
6003
- const script = offerContract(offer, operatorPubkey);
6004
- if (import_base13.hex.encode(script.pkScript) !== import_base13.hex.encode(offer.swapPkScript)) return "indeterminate";
6651
+ let script;
6652
+ if ("version" in offer) {
6653
+ const { program, args, keys } = bindingProgram(offer);
6654
+ script = new import_sdk22.arkade.ArkadeProgramScript(program, args, keys);
6655
+ } else {
6656
+ script = offerContract(offer, operatorPubkey);
6657
+ if (import_base13.hex.encode(script.pkScript) !== import_base13.hex.encode(offer.swapPkScript)) {
6658
+ return "indeterminate";
6659
+ }
6660
+ }
6005
6661
  leaves = {
6006
6662
  // `exit` is absent on an offer with no exit closure, and drops out here
6007
6663
  returned: ["cancel", "exit"].map((name) => script.functionByName(name)?.leafScript).filter((leaf) => leaf !== void 0),
@@ -6030,21 +6686,56 @@ function classifyDepositSpend(offer, operatorPubkey, spendTxs, deposit) {
6030
6686
  }
6031
6687
  return "indeterminate";
6032
6688
  }
6689
+ var encodesOffer = (offerHex, offer) => {
6690
+ try {
6691
+ const { ratioNum: _num, ratioDen: _den, ...terms } = decodeOffer(import_base13.hex.decode(offerHex));
6692
+ return import_base13.hex.encode(encodeOffer(terms)) === import_base13.hex.encode(encodeOffer(offer));
6693
+ } catch {
6694
+ return false;
6695
+ }
6696
+ };
6697
+ var packetRecoverySource = (indexer) => ({
6698
+ name: "packet",
6699
+ async discover({ candidateTxids, operatorPubkey }) {
6700
+ const found = [];
6701
+ const declined = [];
6702
+ for (const [txid, parsed] of await fetchParsedTxs(indexer, [...candidateTxids])) {
6703
+ let packet;
6704
+ try {
6705
+ packet = import_sdk22.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
6706
+ } catch {
6707
+ }
6708
+ if (!packet) {
6709
+ declined.push(txid);
6710
+ continue;
6711
+ }
6712
+ const payload = packet.serialize();
6713
+ try {
6714
+ const binding = bindingFromOffer(decodeOffer(payload), operatorPubkey);
6715
+ found.push({ fundingTxid: txid, binding, offerHex: import_base13.hex.encode(payload) });
6716
+ } catch {
6717
+ }
6718
+ }
6719
+ return { found, declined };
6720
+ }
6721
+ });
6033
6722
  async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6034
6723
  const {
6035
6724
  operatorPubkey,
6036
6725
  scanned = /* @__PURE__ */ new Set(),
6037
6726
  reopen = [],
6038
6727
  hrp,
6039
- recoveredIn = /* @__PURE__ */ new Set()
6728
+ recoveredIn = /* @__PURE__ */ new Set(),
6729
+ sources = [packetRecoverySource(indexer)]
6040
6730
  } = opts;
6041
6731
  const reopened = [];
6042
6732
  for (const swap of reopen) {
6043
6733
  try {
6734
+ const source = storedOffer(swap);
6044
6735
  reopened.push({
6045
6736
  fundingTx: { type: "sent", redeemTxid: swap.fundingTxid },
6046
- offer: decodeOffer(import_base13.hex.decode(swap.offerHex)),
6047
- offerHex: swap.offerHex,
6737
+ offer: "version" in source ? offerFromBinding(source) : source,
6738
+ source,
6048
6739
  existing: swap
6049
6740
  });
6050
6741
  } catch {
@@ -6058,29 +6749,40 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6058
6749
  return { restored: [], scannedTxids: [] };
6059
6750
  }
6060
6751
  const byTxid = new Map(candidates.map((tx) => [tx.redeemTxid, tx]));
6061
- const parsedByTxid = await fetchParsedTxs(
6062
- indexer,
6063
- candidates.map((tx) => tx.redeemTxid)
6064
- );
6065
- const fetchedTxids = [];
6752
+ const candidateTxids = candidates.map((tx) => tx.redeemTxid);
6066
6753
  const found = [...reopened];
6067
- for (const [txid, parsed] of parsedByTxid) {
6068
- const fundingTx = byTxid.get(txid);
6069
- if (!fundingTx) continue;
6070
- fetchedTxids.push(txid);
6754
+ const claimed = /* @__PURE__ */ new Set();
6755
+ const declined = /* @__PURE__ */ new Set();
6756
+ for (const recovery of candidateTxids.length === 0 ? [] : sources) {
6757
+ let answer;
6071
6758
  try {
6072
- const packet = import_sdk22.Extension.fromTx(parsed).getPacketByType(OFFER_PACKET_TYPE);
6073
- if (!packet) continue;
6074
- const payload = packet.serialize();
6075
- found.push({
6076
- fundingTx,
6077
- offer: decodeOffer(payload),
6078
- offerHex: import_base13.hex.encode(payload)
6079
- });
6080
- } catch {
6759
+ answer = await recovery.discover({ candidateTxids, operatorPubkey });
6760
+ } catch (error) {
6761
+ console.warn(`[swap] recovery source ${recovery.name} failed`, error);
6762
+ continue;
6763
+ }
6764
+ for (const txid of answer.declined) declined.add(txid);
6765
+ for (const { fundingTxid, binding, offerHex } of answer.found) {
6766
+ const fundingTx = byTxid.get(fundingTxid);
6767
+ if (!fundingTx || claimed.has(fundingTxid)) continue;
6768
+ let offer;
6769
+ try {
6770
+ offer = offerFromBinding(binding);
6771
+ } catch (error) {
6772
+ console.warn(`[swap] ${recovery.name} sent a binding that does not compile`, error);
6773
+ continue;
6774
+ }
6775
+ if (offerHex !== void 0 && !encodesOffer(offerHex, offer)) {
6776
+ console.warn(`[swap] ${recovery.name} sent a packet its binding does not match`);
6777
+ continue;
6778
+ }
6779
+ claimed.add(fundingTxid);
6780
+ const packet = offerHex ?? import_base13.hex.encode(encodeOffer(offer));
6781
+ found.push({ fundingTx, offer, source: binding, offerHex: packet });
6081
6782
  }
6082
6783
  }
6083
- if (found.length === 0) return { restored: [], scannedTxids: fetchedTxids };
6784
+ const answered = [...claimed, ...[...declined].filter((txid) => !claimed.has(txid))];
6785
+ if (found.length === 0) return { restored: [], scannedTxids: answered };
6084
6786
  const scripts = [...new Set(found.map((f) => import_base13.hex.encode(f.offer.swapPkScript)))];
6085
6787
  const { vtxos } = await indexer.getVtxos({ scripts });
6086
6788
  const vtxoByScriptAndTxid = new Map(vtxos.map((v) => [`${v.script}:${v.txid}`, v]));
@@ -6101,7 +6803,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6101
6803
  const spendTxByTxid = await fetchParsedTxs(indexer, [...spendTxids]);
6102
6804
  const restored = [];
6103
6805
  const unresolved = /* @__PURE__ */ new Set();
6104
- for (const { fundingTx, offer, offerHex, existing } of found) {
6806
+ for (const { fundingTx, offer, source, offerHex, existing } of found) {
6105
6807
  const swapPkScript = import_base13.hex.encode(offer.swapPkScript);
6106
6808
  const vtxo = vtxoByScriptAndTxid.get(`${swapPkScript}:${fundingTx.redeemTxid}`);
6107
6809
  if (!vtxo) {
@@ -6130,7 +6832,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6130
6832
  } else if (vtxo.isSwept && !vtxo.isSpent) status = "recoverable";
6131
6833
  else if (vtxo.isSpent) {
6132
6834
  const spendTxs = spendTxidsOf(vtxo).map((id) => spendTxByTxid.get(id)).filter((tx) => tx !== void 0);
6133
- const kind = classifyDepositSpend(offer, operatorPubkey, spendTxs, {
6835
+ const kind = classifyDepositSpend(source, operatorPubkey, spendTxs, {
6134
6836
  txid: vtxo.txid,
6135
6837
  vout: vtxo.vout
6136
6838
  });
@@ -6146,20 +6848,19 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6146
6848
  restored.push({ ...existing, status, spentTxid, ...completion });
6147
6849
  continue;
6148
6850
  }
6851
+ if (!("version" in source)) continue;
6149
6852
  let swapAddress = "";
6150
6853
  try {
6151
- const compiled = offerContract(offer, operatorPubkey);
6152
- if (import_base13.hex.encode(compiled.pkScript) !== swapPkScript) {
6153
- unresolved.add(fundingTx.redeemTxid);
6154
- continue;
6155
- }
6156
6854
  if (hrp !== void 0) {
6157
- swapAddress = compiled.address(hrp, operatorPubkey).encode();
6855
+ const { program, args, keys } = bindingProgram(source);
6856
+ const compiled = new import_sdk22.arkade.ArkadeProgramScript(program, args, keys);
6857
+ swapAddress = compiled.address(hrp, source.serverPublicKey).encode();
6158
6858
  }
6159
6859
  } catch {
6160
6860
  unresolved.add(fundingTx.redeemTxid);
6161
6861
  continue;
6162
6862
  }
6863
+ const covenant = source.taker === void 0 ? { offerHex: offerHex ?? import_base13.hex.encode(encodeOffer(offer)) } : { binding: recordOfferBinding(source) };
6163
6864
  restored.push({
6164
6865
  id: fundingTx.redeemTxid,
6165
6866
  fromAsset,
@@ -6168,7 +6869,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6168
6869
  toAmount: offer.wantAmount.toString(),
6169
6870
  swapAddress,
6170
6871
  swapPkScript,
6171
- offerHex,
6872
+ ...covenant,
6172
6873
  fundingTxid: fundingTx.redeemTxid,
6173
6874
  spentTxid,
6174
6875
  status,
@@ -6176,7 +6877,7 @@ async function restoreAssetSwaps(indexer, txs, existingIds, opts) {
6176
6877
  ...completion
6177
6878
  });
6178
6879
  }
6179
- return { restored, scannedTxids: fetchedTxids.filter((id) => !unresolved.has(id)) };
6880
+ return { restored, scannedTxids: answered.filter((id) => !unresolved.has(id)) };
6180
6881
  }
6181
6882
 
6182
6883
  // src/client/cancel.ts
@@ -6435,11 +7136,15 @@ var corridorRecordStore = (repository, onRecord = () => {
6435
7136
  }
6436
7137
  };
6437
7138
  };
7139
+ var covenantOf = (swap) => ({
7140
+ ...swap.offerHex === void 0 ? {} : { offerHex: swap.offerHex },
7141
+ ...swap.binding === void 0 ? {} : { binding: swap.binding }
7142
+ });
6438
7143
  var offerFactsOf = (record) => ({
6439
7144
  id: record.id,
6440
7145
  coverageId: record.id,
6441
7146
  status: record.status,
6442
- offerHex: record.offerHex,
7147
+ ...covenantOf(record),
6443
7148
  swapPkScript: record.swapPkScript,
6444
7149
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
6445
7150
  ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
@@ -6511,7 +7216,7 @@ var restoredOfferRecord = (swap, network, now) => {
6511
7216
  market: { kind: "restored", backend: "feed" },
6512
7217
  expiresAt: createdAt,
6513
7218
  status: swap.status,
6514
- offerHex: swap.offerHex,
7219
+ ...covenantOf(swap),
6515
7220
  swapAddress: swap.swapAddress,
6516
7221
  swapPkScript: swap.swapPkScript,
6517
7222
  fundingTxid: swap.fundingTxid,
@@ -6522,6 +7227,20 @@ var restoredOfferRecord = (swap, network, now) => {
6522
7227
  now
6523
7228
  );
6524
7229
  };
7230
+ var reopenedDeposit = (record, fundingTxid) => ({
7231
+ id: fundingTxid,
7232
+ fromAsset: record.give.asset,
7233
+ toAsset: record.take.asset,
7234
+ fromAmount: record.give.amount,
7235
+ toAmount: record.take.amount,
7236
+ swapAddress: record.swapAddress,
7237
+ swapPkScript: record.swapPkScript,
7238
+ ...covenantOf(record),
7239
+ fundingTxid,
7240
+ ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
7241
+ status: record.status,
7242
+ createdAt: record.createdAt * 1e3
7243
+ });
6525
7244
  var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, import_sdk24.asset.AssetId.fromString(id));
6526
7245
  var RESTORED_CORRIDORS = {
6527
7246
  lightning_send: ["arkade", "lightning"],
@@ -6586,12 +7305,13 @@ var cancelSwap = async (input) => {
6586
7305
  if (outcome === "cancelled" || outcome === "filled" || outcome === "needs_recovery") {
6587
7306
  return { outcome };
6588
7307
  }
7308
+ const offer = storedOffer(record);
6589
7309
  const gated2 = withStatus(record, "cancelling", now());
6590
7310
  await repository.saveSwapRecord(gated2);
6591
7311
  drive.ingest(gated2);
6592
7312
  let prepared;
6593
7313
  try {
6594
- prepared = await prepareOfferCancel(wallet, record.offerHex, {
7314
+ prepared = await prepareOfferCancel(wallet, offer, {
6595
7315
  swapAddress: record.swapAddress,
6596
7316
  ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid }
6597
7317
  });
@@ -6638,7 +7358,7 @@ var cancelSwap = async (input) => {
6638
7358
  return { outcome: "cancelled" };
6639
7359
  };
6640
7360
  var reconcileDepositSpend = async (record, indexer) => {
6641
- const offer = decodeOffer(import_base16.hex.decode(record.offerHex));
7361
+ const offer = storedOffer(record);
6642
7362
  const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
6643
7363
  const all = vtxos ?? [];
6644
7364
  const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
@@ -6726,6 +7446,9 @@ async function pushClaim(operator, input) {
6726
7446
  assertFiniteAmount(funded, "lockup_malformed", "the lockup's summed value");
6727
7447
  if (!input.partiallyClaimed) {
6728
7448
  assertFiniteAmount(input.expectedAmount, "invalid_gate_input", "expectedAmount");
7449
+ if (input.expectedAmount <= 0) {
7450
+ throw gateError("invalid_gate_input", "expectedAmount is not positive");
7451
+ }
6729
7452
  if (funded < input.expectedAmount) {
6730
7453
  throw new LockupAmountMismatchError(input.expectedAmount, funded);
6731
7454
  }
@@ -7818,10 +8541,10 @@ var RfqSwapManager = class _RfqSwapManager {
7818
8541
  return;
7819
8542
  }
7820
8543
  if (!partiallyClaimed) {
7821
- if (!Number.isFinite(swap.expectedAmount)) {
8544
+ if (!Number.isSafeInteger(swap.expectedAmount) || swap.expectedAmount <= 0) {
7822
8545
  return this.block(
7823
8546
  swap,
7824
- `expectedAmount is not a finite number (${String(swap.expectedAmount)}), so the funded value cannot be checked \u2014 refusing to publish the preimage`
8547
+ `expectedAmount is not a positive number of sats (${String(swap.expectedAmount)}), so the funded value cannot be checked \u2014 refusing to publish the preimage`
7825
8548
  );
7826
8549
  }
7827
8550
  const locked = vtxos.reduce((sum, vtxo) => sum + vtxo.value, 0);
@@ -8082,6 +8805,9 @@ var RfqSwapManager = class _RfqSwapManager {
8082
8805
  utxo,
8083
8806
  bump ? { bump } : void 0
8084
8807
  );
8808
+ if (swap.funding?.txid !== utxo.txid || swap.funding.vout !== utxo.vout || swap.funding.amount === void 0) {
8809
+ swap.funding = { txid: utxo.txid, vout: utxo.vout, amount: Number(utxo.amount) };
8810
+ }
8085
8811
  swap.claimTxid = txid;
8086
8812
  swap.claimBroadcastAt = this.config.now();
8087
8813
  delete swap.claimConfirmed;
@@ -8385,7 +9111,7 @@ async function watchOfferSwaps({
8385
9111
  if (candidates.length === 0) return "indeterminate";
8386
9112
  const { txs } = await indexer.getVirtualTxs(candidates);
8387
9113
  return classifyDepositSpend(
8388
- decodeOffer(import_base19.hex.decode(swap.offerHex)),
9114
+ storedOffer(swap),
8389
9115
  operatorPubkey,
8390
9116
  txs.map((psbt) => import_sdk30.Transaction.fromPSBT(import_base19.base64.decode(psbt))),
8391
9117
  { txid: vtxo.txid, vout: vtxo.vout }
@@ -8424,6 +9150,9 @@ async function watchOfferSwaps({
8424
9150
  };
8425
9151
  }
8426
9152
 
9153
+ // src/client/drive.ts
9154
+ init_errors();
9155
+
8427
9156
  // src/client/legacyRecords.ts
8428
9157
  var import_sdk31 = require("@arkade-os/sdk");
8429
9158
  init_repository();
@@ -8495,7 +9224,7 @@ var readLegacyAssetSwaps = async (repository) => {
8495
9224
  };
8496
9225
  var legacyOfferDepositsToAdopt = async (repository) => {
8497
9226
  const unadopted = (await readLegacyAssetSwaps(repository)).filter(
8498
- (swap) => !!swap.offerHex && !!swap.fundingTxid
9227
+ (swap) => (!!swap.offerHex || !!swap.binding) && !!swap.fundingTxid
8499
9228
  );
8500
9229
  if (unadopted.length === 0) return /* @__PURE__ */ new Set();
8501
9230
  const { offer } = splitRecords(await collectSwapRecords(repository));
@@ -8515,6 +9244,7 @@ var SwapDriveRefusedError = class extends Error {
8515
9244
  name = "SwapDriveRefusedError";
8516
9245
  };
8517
9246
  var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
9247
+ var DIRECTED_CANCEL_GRACE_SECONDS = 60;
8518
9248
  var traderClaimTxid2 = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
8519
9249
  var readableRecord = (record) => {
8520
9250
  if (typeof record?.id !== "string" || record.route?.give === void 0) return false;
@@ -8528,7 +9258,7 @@ var readableRecord = (record) => {
8528
9258
  if (record.family === "rfq") {
8529
9259
  return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
8530
9260
  }
8531
- return record.family === "offer" && typeof record.offerHex === "string";
9261
+ return record.family === "offer" && (typeof record.offerHex === "string" || record.binding !== void 0);
8532
9262
  };
8533
9263
  var createSwapDrive = (config) => {
8534
9264
  const { wallet, operator, repository, corridors, indexer } = config;
@@ -8901,11 +9631,15 @@ var createSwapDrive = (config) => {
8901
9631
  const reopened = await legacyOfferDepositsToAdopt(store);
8902
9632
  for (const txid of reopen) reopened.add(txid);
8903
9633
  const cursor = reopened.size === 0 ? scanned : new Set([...scanned].filter((txid) => !reopened.has(txid)));
9634
+ const bound = [...records.values()].flatMap(
9635
+ (record) => record.family === "offer" && record.binding !== void 0 && record.fundingTxid !== void 0 && !RETIRABLE.includes(record.status) ? [reopenedDeposit(record, record.fundingTxid)] : []
9636
+ );
8904
9637
  const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
8905
9638
  operatorPubkey,
8906
9639
  scanned: cursor,
8907
9640
  hrp,
8908
- recoveredIn
9641
+ recoveredIn,
9642
+ reopen: bound
8909
9643
  });
8910
9644
  const { offer } = splitRecords(await collectSwapRecords(store));
8911
9645
  const current = new Map(offer.map((record) => [record.id, record]));
@@ -8997,6 +9731,33 @@ var createSwapDrive = (config) => {
8997
9731
  onUpdate: (swap) => emit(swap.id)
8998
9732
  });
8999
9733
  }
9734
+ if (!lapseTimer) {
9735
+ lapseTimer = setInterval(cancelLapsed, config.pollIntervalMs ?? 5e3);
9736
+ cancelLapsed();
9737
+ }
9738
+ };
9739
+ const lapsing = /* @__PURE__ */ new Set();
9740
+ let lapseTimer;
9741
+ const cancelLapsed = () => {
9742
+ if (disposed || !repository) return;
9743
+ for (const record of records.values()) {
9744
+ 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)) {
9745
+ continue;
9746
+ }
9747
+ lapsing.add(record.id);
9748
+ void track(
9749
+ cancelSwap({
9750
+ wallet,
9751
+ repository,
9752
+ record,
9753
+ drive: { ingest: remember },
9754
+ indexer,
9755
+ now
9756
+ }).catch((error) => {
9757
+ console.warn(`[swap] could not cancel lapsed swap ${record.id}`, error);
9758
+ }).finally(() => lapsing.delete(record.id))
9759
+ );
9760
+ }
9000
9761
  };
9001
9762
  const registerRestoredOffers = async (offers2) => {
9002
9763
  if (mode === "readonly") return;
@@ -9135,6 +9896,8 @@ var createSwapDrive = (config) => {
9135
9896
  const stop = async () => {
9136
9897
  await queue;
9137
9898
  await manager.stop();
9899
+ clearInterval(lapseTimer);
9900
+ lapseTimer = void 0;
9138
9901
  watcher?.stop();
9139
9902
  await watcher?.idle();
9140
9903
  watcher = void 0;
@@ -9302,6 +10065,10 @@ var createSwapDrive = (config) => {
9302
10065
  // src/client/quoteOffer.ts
9303
10066
  var import_solver_discovery11 = require("@arkade-os/solver-discovery");
9304
10067
  init_offer();
10068
+ init_errors();
10069
+
10070
+ // src/client/resolve.ts
10071
+ init_errors();
9305
10072
 
9306
10073
  // src/client/aliasTable.ts
9307
10074
  init_store();
@@ -9563,224 +10330,8 @@ var pinAmount = (input, takeInstrument) => {
9563
10330
  return void 0;
9564
10331
  };
9565
10332
 
9566
- // src/client/verify.ts
9567
- init_rfq();
9568
-
9569
- // src/client/policy.ts
9570
- var DEFAULT_MAX_REFUND_WINDOW_SECONDS = 30 * 24 * 3600;
9571
-
9572
- // src/client/verify.ts
9573
- var reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
9574
- var CHECK_BY_REASON = {
9575
- invoice_expired: "invoice",
9576
- invoice_undecodable: "invoice",
9577
- invoice_hash_mismatch: "invoice",
9578
- invoice_amount_mismatch: "invoice",
9579
- insufficient_headroom: "refund_window",
9580
- missing_refund_locktime: "refund_window",
9581
- claim_window_too_short: "refund_window",
9582
- confirmations_out_of_range: "refund_window",
9583
- timelock_order: "refund_window",
9584
- quote_malformed: "refund_window"
9585
- };
9586
- var gated = (run, quote) => {
9587
- try {
9588
- run();
9589
- } catch (error) {
9590
- const reason = reasonOf(error);
9591
- if (reason === "quote_expired") {
9592
- throw new QuoteExpired(quote.id, quote.expiresAt, quote.now);
9593
- }
9594
- const check = reason === void 0 ? void 0 : CHECK_BY_REASON[reason];
9595
- if (check === void 0) throw error;
9596
- throw new QuoteVerificationFailed(
9597
- check,
9598
- void 0,
9599
- error instanceof Error ? error.message : String(error),
9600
- { cause: error }
9601
- );
9602
- }
9603
- };
9604
- var verifyResponder = (input) => {
9605
- if (!input.pinnable || input.expected === void 0) {
9606
- throw new QuoteVerificationFailed(
9607
- "responder",
9608
- "a registry-served card naming the solver's discovery key",
9609
- input.expected === void 0 ? "the card names no discovery key" : "the card came out of the local cache, which does not authenticate it"
9610
- );
9611
- }
9612
- if (input.attested === void 0) {
9613
- throw new QuoteVerificationFailed(
9614
- "responder",
9615
- input.expected,
9616
- "the transport attests nobody"
9617
- );
9618
- }
9619
- if (input.attested !== input.expected) {
9620
- throw new QuoteVerificationFailed("responder", input.expected, input.attested);
9621
- }
9622
- };
9623
- var verifyPair = (quoted, requested) => {
9624
- if (quoted !== requested) {
9625
- throw new QuoteVerificationFailed("pair", requested, String(quoted));
9626
- }
9627
- };
9628
- var verifyingDerivation = (derive) => {
9629
- try {
9630
- return derive();
9631
- } catch (error) {
9632
- if (error instanceof AddressMismatch) {
9633
- const derived = Array.isArray(error.derived) ? error.derived.join(", ") : error.derived;
9634
- throw new QuoteVerificationFailed("lockup_address", derived, error.quoted, {
9635
- cause: error
9636
- });
9637
- }
9638
- if (error instanceof Error) {
9639
- throw new QuoteVerificationFailed("lockup_address", void 0, error.message, {
9640
- cause: error
9641
- });
9642
- }
9643
- throw error;
9644
- }
9645
- };
9646
- var verifySendWindow = (input) => {
9647
- gated(
9648
- () => assertFundable({
9649
- quote: input.quote,
9650
- now: input.now,
9651
- ...input.invoiceExpiresAt === void 0 ? {} : { invoiceExpiresAt: input.invoiceExpiresAt },
9652
- ...input.onchain === void 0 ? {} : { onchain: input.onchain }
9653
- }),
9654
- { id: input.quoteId, expiresAt: input.quote.valid_until, now: input.now }
9655
- );
9656
- };
9657
- var verifyReceiveWindow = (input) => {
9658
- gated(
9659
- () => assertReceivable({
9660
- quote: input.quote,
9661
- payDeadline: input.payDeadline,
9662
- now: input.now
9663
- }),
9664
- { id: input.quoteId, expiresAt: input.payDeadline, now: input.now }
9665
- );
9666
- };
9667
- var verifySendInvoice = (input) => {
9668
- const invoiced = input.invoiced;
9669
- if (input.take !== invoiced) {
9670
- throw new QuoteVerificationFailed("invoice", `${invoiced}`, `${input.take}`);
9671
- }
9672
- if (input.give < input.take) {
9673
- throw new QuoteVerificationFailed(
9674
- "invoice",
9675
- `at least the invoice's ${invoiced}`,
9676
- `${input.give}, a negative spread`
9677
- );
9678
- }
9679
- };
9680
- var verifyReceiveInvoiceFacts = (input) => {
9681
- let decoded;
9682
- try {
9683
- decoded = input.decode(input.invoice);
9684
- } catch (cause) {
9685
- throw new QuoteVerificationFailed(
9686
- "invoice",
9687
- "a decodable BOLT11",
9688
- cause instanceof Error ? cause.message : String(cause),
9689
- { cause }
9690
- );
9691
- }
9692
- if (!Number.isFinite(decoded.expiresAt)) {
9693
- throw new QuoteVerificationFailed("invoice", "a finite expiry", `${decoded.expiresAt}`);
9694
- }
9695
- if (!Number.isFinite(input.validUntil)) {
9696
- throw new QuoteVerificationFailed(
9697
- "refund_window",
9698
- "a finite valid_until",
9699
- `${input.validUntil}`
9700
- );
9701
- }
9702
- if (decoded.paymentHash !== input.paymentHash) {
9703
- throw new QuoteVerificationFailed("invoice", input.paymentHash, decoded.paymentHash);
9704
- }
9705
- if (!Number.isSafeInteger(decoded.amountSats) || decoded.amountSats <= 0) {
9706
- throw new QuoteVerificationFailed(
9707
- "invoice",
9708
- `${input.payAmount}`,
9709
- "the invoice names no amount"
9710
- );
9711
- }
9712
- if (BigInt(decoded.amountSats) !== input.payAmount) {
9713
- throw new QuoteVerificationFailed("invoice", `${input.payAmount}`, `${decoded.amountSats}`);
9714
- }
9715
- return { payDeadline: Math.min(decoded.expiresAt, input.validUntil) };
9716
- };
9717
- var verifyQuoteTtl = (input) => {
9718
- const floor = input.floorSeconds ?? 0;
9719
- if (input.expiresAt - input.now <= floor) {
9720
- throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
9721
- }
9722
- };
9723
- var CSV_GRANULARITY_SECONDS = 512;
9724
- var verifyRefundWindow = (input) => {
9725
- const max = input.maxSeconds ?? DEFAULT_MAX_REFUND_WINDOW_SECONDS;
9726
- const window = input.refundLocktime - input.now;
9727
- if (!(window <= max)) {
9728
- throw new QuoteVerificationFailed("refund_window", `at most ${max}s`, `${window}s`);
9729
- }
9730
- const delay = input.refundWithoutReceiverDelay;
9731
- if (delay !== void 0 && !(delay < max + CSV_GRANULARITY_SECONDS)) {
9732
- throw new QuoteVerificationFailed(
9733
- "refund_window",
9734
- `a solo-refund delay of at most ${max}s`,
9735
- `${delay}s`
9736
- );
9737
- }
9738
- };
9739
- var verifyQuotedAmount = (input) => {
9740
- verifyPinnedAmount(input);
9741
- if (input.take > input.give) {
9742
- throw new QuoteVerificationFailed(
9743
- "pair",
9744
- `${input.pair} give >= take`,
9745
- `give=${input.give} take=${input.take}`
9746
- );
9747
- }
9748
- };
9749
- var verifyCrossAssetAmount = (input) => {
9750
- verifyPinnedAmount(input);
9751
- if (input.give <= 0n || input.take <= 0n) {
9752
- throw new QuoteVerificationFailed(
9753
- "pair",
9754
- `${input.pair} give > 0 take > 0`,
9755
- `give=${input.give} take=${input.take}`
9756
- );
9757
- }
9758
- };
9759
- var verifiedCarrierSats = (quote) => {
9760
- try {
9761
- return quoteCarrierSats(quote);
9762
- } catch (error) {
9763
- if (reasonOf(error) !== "carrier_malformed") throw error;
9764
- throw new QuoteVerificationFailed(
9765
- "pair",
9766
- "carrier_sats a non-negative integer",
9767
- String(quote.carrier_sats),
9768
- { cause: error }
9769
- );
9770
- }
9771
- };
9772
- var verifyPinnedAmount = (input) => {
9773
- const quoted = input.pinned.on === "give" ? input.give : input.take;
9774
- if (quoted !== input.pinned.value) {
9775
- throw new QuoteVerificationFailed(
9776
- "pair",
9777
- `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
9778
- `${input.pair} ${input.pinned.on}=${quoted}`
9779
- );
9780
- }
9781
- };
9782
-
9783
10333
  // src/client/quoteOffer.ts
10334
+ init_verify();
9784
10335
  var FEED_TTL_MS = 3e4;
9785
10336
  var feedFetch = (base = fetch) => {
9786
10337
  const at2 = /* @__PURE__ */ new Map();
@@ -9869,12 +10420,12 @@ var verifyPlanLegs = (plan, legs, give) => {
9869
10420
  };
9870
10421
 
9871
10422
  // src/client/quoteRfq.ts
9872
- var import_base22 = require("@scure/base");
10423
+ var import_base23 = require("@scure/base");
9873
10424
  var import_sdk36 = require("@arkade-os/sdk");
9874
10425
  var import_solver_discovery12 = require("@arkade-os/solver-discovery");
9875
10426
 
9876
10427
  // src/jointGraph.ts
9877
- var import_base21 = require("@scure/base");
10428
+ var import_base22 = require("@scure/base");
9878
10429
  var import_sha26 = require("@noble/hashes/sha2.js");
9879
10430
  var import_sdk33 = require("@arkade-os/sdk");
9880
10431
  function digestJointGraph(plan, template) {
@@ -9910,7 +10461,7 @@ function digestJointGraph(plan, template) {
9910
10461
  preimage.set(part, at2);
9911
10462
  at2 += part.length;
9912
10463
  }
9913
- return import_base21.hex.encode((0, import_sha26.sha256)(preimage));
10464
+ return import_base22.hex.encode((0, import_sha26.sha256)(preimage));
9914
10465
  }
9915
10466
  function verifyJointGraph(plan, template) {
9916
10467
  try {
@@ -9938,7 +10489,7 @@ function verifyJointGraph(plan, template) {
9938
10489
  }
9939
10490
  }
9940
10491
  function parseGraphTx(psbt) {
9941
- return import_sdk33.Transaction.fromPSBT(import_base21.base64.decode(psbt));
10492
+ return import_sdk33.Transaction.fromPSBT(import_base22.base64.decode(psbt));
9942
10493
  }
9943
10494
  function deepFreeze(value) {
9944
10495
  if (value !== null && typeof value === "object") {
@@ -9970,8 +10521,10 @@ init_onchainHtlc();
9970
10521
 
9971
10522
  // src/payment/swapRail.ts
9972
10523
  var import_sdk34 = require("@arkade-os/sdk");
10524
+ init_errors();
9973
10525
 
9974
10526
  // src/client/sats.ts
10527
+ init_errors();
9975
10528
  var satsOf = (value, field) => {
9976
10529
  if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
9977
10530
  throw new AmountEncodingUnsupported(
@@ -10156,7 +10709,9 @@ function onchainSwapRail(client, deps) {
10156
10709
  }
10157
10710
 
10158
10711
  // src/client/quoteRfq.ts
10712
+ init_rfq_contract();
10159
10713
  init_rfq();
10714
+ init_errors();
10160
10715
 
10161
10716
  // src/client/rfqWire.ts
10162
10717
  init_rfq();
@@ -10189,6 +10744,7 @@ var parseRfqQuote = (quote) => ({
10189
10744
  });
10190
10745
 
10191
10746
  // src/client/quoteRfq.ts
10747
+ init_verify();
10192
10748
  var lockupOf = (derived) => ({
10193
10749
  address: derived.address,
10194
10750
  script: derived.script,
@@ -10196,12 +10752,12 @@ var lockupOf = (derived) => ({
10196
10752
  });
10197
10753
  var covenantInputs = (input) => {
10198
10754
  const network = (0, import_sdk36.networkFromOperatorInfo)(input.info);
10199
- const arkade4 = input.corridors.get("arkade").deps;
10755
+ const arkade5 = input.corridors.get("arkade").deps;
10200
10756
  return {
10201
- operatorPubkey: (0, import_sdk36.toXOnly)(import_base22.hex.decode(input.info.signerPubkey), "ark signer key"),
10757
+ operatorPubkey: (0, import_sdk36.toXOnly)(import_base23.hex.decode(input.info.signerPubkey), "ark signer key"),
10202
10758
  // The resolved per-network pin, never operator-reported: it lands in a covenant leaf
10203
10759
  // that decides who can move the funds.
10204
- emulatorPubkey: (0, import_sdk36.toXOnly)(import_base22.hex.decode(arkade4.emulatorPubkey), "emulator signer key"),
10760
+ emulatorPubkey: (0, import_sdk36.toXOnly)(import_base23.hex.decode(arkade5.emulatorPubkey), "emulator signer key"),
10205
10761
  claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
10206
10762
  hrp: network.hrp
10207
10763
  };
@@ -10209,7 +10765,7 @@ var covenantInputs = (input) => {
10209
10765
  var sealingKey = (deps) => {
10210
10766
  const configured = deps.covclaimd?.pubkey;
10211
10767
  if (configured === void 0) return void 0;
10212
- const key = import_base22.hex.decode(configured);
10768
+ const key = import_base23.hex.decode(configured);
10213
10769
  if (key.length !== 33) {
10214
10770
  throw new Error(
10215
10771
  `the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
@@ -10265,7 +10821,7 @@ var quoteArkadeAsset = async (input) => {
10265
10821
  receiveAddress,
10266
10822
  maker.pkScript,
10267
10823
  (0, import_sdk36.networkFromOperatorInfo)(input.info).hrp,
10268
- (0, import_sdk36.toXOnly)(import_base22.hex.decode(input.info.signerPubkey), "ark signer key")
10824
+ (0, import_sdk36.toXOnly)(import_base23.hex.decode(input.info.signerPubkey), "ark signer key")
10269
10825
  );
10270
10826
  const choice = payment?.carrier;
10271
10827
  const carrierRequest = choice === void 0 ? void 0 : choice.mode === "purchase" ? { mode: "purchase" } : {
@@ -10277,7 +10833,7 @@ var quoteArkadeAsset = async (input) => {
10277
10833
  if (choice?.mode === "recycleReceiver") {
10278
10834
  if (choice.quote.assetId !== sides.wantAsset?.toString())
10279
10835
  throw new Error("carrier quote assetId differs from requested asset");
10280
- if (choice.quote.senderKey !== import_base22.hex.encode(maker.publicKey))
10836
+ if (choice.quote.senderKey !== import_base23.hex.encode(maker.publicKey))
10281
10837
  throw new Error("carrier quote senderKey differs from wallet identity");
10282
10838
  if (input.now >= choice.quote.expiresAt - 30)
10283
10839
  throw new Error("carrier quote expired before RFQ");
@@ -10308,6 +10864,10 @@ var quoteArkadeAsset = async (input) => {
10308
10864
  );
10309
10865
  verifyPair(wire.pair, pair);
10310
10866
  const parsed = parseRfqQuote(wire);
10867
+ const taker = contractVersion === ASSET_SWAP_V4 ? verifyTaker({
10868
+ attested: input.transport.attestedResponder,
10869
+ solverPubkey: parsed.solver
10870
+ }) : void 0;
10311
10871
  verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
10312
10872
  verifyQuoteTtl({
10313
10873
  quoteId: input.quoteId,
@@ -10339,7 +10899,7 @@ var quoteArkadeAsset = async (input) => {
10339
10899
  if (input.now >= validUntil) throw new Error("asset payment terms lapsed before funding");
10340
10900
  assetPayment = {
10341
10901
  receiveAddress: receiveAddress ?? new import_sdk36.ArkAddress(
10342
- (0, import_sdk36.toXOnly)(import_base22.hex.decode(input.info.signerPubkey), "ark signer key"),
10902
+ (0, import_sdk36.toXOnly)(import_base23.hex.decode(input.info.signerPubkey), "ark signer key"),
10343
10903
  maker.pkScript.slice(2),
10344
10904
  (0, import_sdk36.networkFromOperatorInfo)(input.info).hrp
10345
10905
  ).encode(),
@@ -10353,7 +10913,9 @@ var quoteArkadeAsset = async (input) => {
10353
10913
  const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
10354
10914
  give: input.candidate.give,
10355
10915
  giveAmount: parsed.give,
10356
- ...carrierSats === void 0 ? {} : { carrierSats },
10916
+ // Unconditional: a card charging for the delivered carrier refuses to price without
10917
+ // it whichever leg gives, and a BTC deposit funds none of its own to publish.
10918
+ carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
10357
10919
  ...QUOTE_OPTIONS,
10358
10920
  fetchImpl: input.feed.fetch
10359
10921
  });
@@ -10367,7 +10929,8 @@ var quoteArkadeAsset = async (input) => {
10367
10929
  maker,
10368
10930
  ...receiveAddress === void 0 ? {} : { receiveAddress },
10369
10931
  info: input.info,
10370
- contractVersion
10932
+ contractVersion,
10933
+ ...taker === void 0 ? {} : { taker }
10371
10934
  });
10372
10935
  verifyingDerivation(() => verifyOfferAddress(wire, offer));
10373
10936
  return {
@@ -10517,7 +11080,7 @@ var quoteLightningReceive = async (input) => {
10517
11080
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
10518
11081
  input.wallet.getAddress()
10519
11082
  ]);
10520
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11083
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10521
11084
  const lightning = input.corridors.get("lightning").deps;
10522
11085
  const sealTo = sealingKey(lightning);
10523
11086
  const sealsAmount = pinned.on === "take" && input.legs.take.assetId === BTC_ASSET_ID;
@@ -10637,7 +11200,7 @@ var quoteOnchainSend = async (input) => {
10637
11200
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
10638
11201
  (0, import_sdk36.provisionRefundKey)(input.wallet)
10639
11202
  ]);
10640
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11203
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10641
11204
  const wire = await input.transport.requestQuote(
10642
11205
  withCanonicalAmount(
10643
11206
  onchainSendRequest({
@@ -10748,7 +11311,7 @@ var quoteOnchainReceive = async (input) => {
10748
11311
  input.wallet.getAddress(),
10749
11312
  input.wallet.getBoardingAddress()
10750
11313
  ]);
10751
- const paymentHash = import_base22.hex.encode(secrets.paymentHash);
11314
+ const paymentHash = import_base23.hex.encode(secrets.paymentHash);
10752
11315
  const refundPkScript = l1ScriptForAddress(boardingAddress, l1Network);
10753
11316
  const wire = await input.transport.requestQuote(
10754
11317
  withCanonicalAmount(
@@ -10855,6 +11418,7 @@ var quoteOnchainReceive = async (input) => {
10855
11418
 
10856
11419
  // src/client/verbs.ts
10857
11420
  var import_sdk37 = require("@arkade-os/sdk");
11421
+ init_errors();
10858
11422
  var enforceFeeCeiling = (quote, call, policy) => {
10859
11423
  let ceiling;
10860
11424
  for (const [source, limit] of [
@@ -10879,14 +11443,14 @@ var settle = async (deps, input, maxFee) => {
10879
11443
  return deps.accept(quote);
10880
11444
  };
10881
11445
  var pay = async (deps, destination, options = {}) => {
10882
- const arkade4 = (0, import_sdk37.arkTarget)(destination);
10883
- if (arkade4 !== void 0) {
11446
+ const arkade5 = (0, import_sdk37.arkTarget)(destination);
11447
+ if (arkade5 !== void 0) {
10884
11448
  const amount = (0, import_sdk37.resolveSendAmount)(
10885
11449
  "ark",
10886
11450
  destination,
10887
11451
  options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
10888
11452
  );
10889
- return { kind: "payment", txid: await deps.wallet.send({ address: arkade4, amount }) };
11453
+ return { kind: "payment", txid: await deps.wallet.send({ address: arkade5, amount }) };
10890
11454
  }
10891
11455
  const swap = await settle(
10892
11456
  deps,
@@ -10948,7 +11512,7 @@ var nostrTransportFactory = createNostrTransportFactory();
10948
11512
 
10949
11513
  // src/client/client.ts
10950
11514
  var PREPARATIONS_HELD = 64;
10951
- var mintQuoteId = () => import_base23.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
11515
+ var mintQuoteId = () => import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
10952
11516
  var createSwapClient = (config) => {
10953
11517
  const { wallet } = config;
10954
11518
  const operator = config.operator ?? walletOperator(wallet);
@@ -11101,6 +11665,7 @@ var createSwapClient = (config) => {
11101
11665
  return acceptQuote({
11102
11666
  quote,
11103
11667
  ...validUntil === void 0 ? {} : { validUntil },
11668
+ ...options?.attachOfferPacket === false ? { attachOfferPacket: false } : {},
11104
11669
  ...preparation === void 0 ? {} : { preparation },
11105
11670
  wallet,
11106
11671
  repository: config.repository,
@@ -11203,6 +11768,8 @@ var createSwapClient = (config) => {
11203
11768
  };
11204
11769
 
11205
11770
  // src/index.ts
11771
+ init_policy();
11772
+ init_errors();
11206
11773
  init_rfq();
11207
11774
  init_repository();
11208
11775
 
@@ -11466,7 +12033,7 @@ function createSwapPaymentRouter(wallet, client, config) {
11466
12033
  }
11467
12034
 
11468
12035
  // src/offerFillPlan.ts
11469
- var import_base24 = require("@scure/base");
12036
+ var import_base25 = require("@scure/base");
11470
12037
  var import_sdk42 = require("@arkade-os/sdk");
11471
12038
  init_offer();
11472
12039
  var OFFER_FILL_TEMPLATE = "offer-fill/1";
@@ -11481,8 +12048,9 @@ async function buildOfferFillPlan(wallet, arkServerUrl, offerHex, opts) {
11481
12048
  assetCarrierSats = ASSET_CARRIER_SATS,
11482
12049
  sponsor
11483
12050
  } = opts;
11484
- const offer = decodeOffer(import_base24.hex.decode(offerHex));
11485
- const contract = await connectFillContract(wallet, arkServerUrl, offer, { swapAddress });
12051
+ const target = typeof offerHex === "string" ? decodeOffer(import_base25.hex.decode(offerHex)) : offerHex;
12052
+ const contract = await connectFillContract(wallet, arkServerUrl, target, { swapAddress });
12053
+ const offer = offerOf(target, contract.pkScript);
11486
12054
  const vtxos = await contract.getUtxos();
11487
12055
  const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
11488
12056
  const solverPayout = payoutScript ?? import_sdk42.ArkAddress.decode(await wallet.getAddress()).pkScript;
@@ -11530,7 +12098,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11530
12098
  }
11531
12099
  layout.inputs.forEach((input, i) => {
11532
12100
  const spent = checkpoints[i].getInput(0);
11533
- if (!(spent.txid instanceof Uint8Array) || import_base24.hex.encode(spent.txid) !== input.txid || spent.index !== input.vout) {
12101
+ if (!(spent.txid instanceof Uint8Array) || import_base25.hex.encode(spent.txid) !== input.txid || spent.index !== input.vout) {
11534
12102
  throw new Error(`fill plan checkpoint ${i} does not spend ${input.txid}:${input.vout}`);
11535
12103
  }
11536
12104
  });
@@ -11542,7 +12110,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11542
12110
  }
11543
12111
  layout.outputs.forEach((expected, i) => {
11544
12112
  const out = arkTx.getOutput(i);
11545
- if (!out?.script || import_base24.hex.encode(out.script) !== import_base24.hex.encode(expected.script)) {
12113
+ if (!out?.script || import_base25.hex.encode(out.script) !== import_base25.hex.encode(expected.script)) {
11546
12114
  throw new Error(`fill plan output ${i} is not the ${expected.role} script`);
11547
12115
  }
11548
12116
  if (out.amount !== expected.sats) {
@@ -11556,7 +12124,7 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11556
12124
  throw new Error(`fill plan output ${payments} is not the extension packet`);
11557
12125
  }
11558
12126
  const anchor = arkTx.getOutput(payments + 1);
11559
- if (!anchor?.script || import_base24.hex.encode(anchor.script) !== import_base24.hex.encode(import_sdk42.P2A.script) || anchor.amount !== import_sdk42.P2A.amount) {
12127
+ if (!anchor?.script || import_base25.hex.encode(anchor.script) !== import_base25.hex.encode(import_sdk42.P2A.script) || anchor.amount !== import_sdk42.P2A.amount) {
11560
12128
  throw new Error(`fill plan output ${payments + 1} is not the anchor`);
11561
12129
  }
11562
12130
  const packet = import_sdk42.Extension.fromTx(arkTx).getAssetPacket();
@@ -11588,8 +12156,8 @@ function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
11588
12156
  );
11589
12157
  }
11590
12158
  }
11591
- const arkTxPsbt = import_base24.base64.encode(arkTx.toPSBT());
11592
- const checkpointPsbts = checkpoints.map((c) => import_base24.base64.encode(c.toPSBT()));
12159
+ const arkTxPsbt = import_base25.base64.encode(arkTx.toPSBT());
12160
+ const checkpointPsbts = checkpoints.map((c) => import_base25.base64.encode(c.toPSBT()));
11593
12161
  const inputOwners = layout.inputs.map((input) => input.owner);
11594
12162
  const graph = {
11595
12163
  arkTx: arkTxPsbt,