@arkade-os/swap 0.1.10 → 0.1.12

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 (48) hide show
  1. package/README.md +58 -0
  2. package/dist/advanced.cjs +1058 -414
  3. package/dist/advanced.d.cts +7 -64
  4. package/dist/advanced.d.ts +7 -64
  5. package/dist/advanced.js +29 -5
  6. package/dist/{chunk-AUJDREZN.js → chunk-CIDVLDDM.js} +1 -1
  7. package/dist/{chunk-FWRDAL73.js → chunk-F3BGKWIB.js} +758 -104
  8. package/dist/{chunk-LCO6AJOS.js → chunk-ISKJIONJ.js} +58 -285
  9. package/dist/{chunk-2HQZLIVX.js → chunk-JBTU7Y6M.js} +1 -1
  10. package/dist/chunk-UXK7YDA4.js +568 -0
  11. package/dist/{chunk-6RJVT65W.js → chunk-VPVSSBY2.js} +2 -4
  12. package/dist/index.cjs +1045 -414
  13. package/dist/index.d.cts +6 -4
  14. package/dist/index.d.ts +6 -4
  15. package/dist/index.js +15 -5
  16. package/dist/{lockupContract-BTTRVwOt.d.cts → lockupContract-B1mr672c.d.cts} +1 -1
  17. package/dist/{lockupContract-aFarhlxj.d.ts → lockupContract-BRpk0NxT.d.ts} +1 -1
  18. package/dist/node/index.d.cts +18 -18
  19. package/dist/node/index.d.ts +18 -18
  20. package/dist/nostr.cjs +276 -302
  21. package/dist/nostr.d.cts +20 -2
  22. package/dist/nostr.d.ts +20 -2
  23. package/dist/nostr.js +21 -357
  24. package/dist/{offerFillPlan-CJC5tnEd.d.ts → offerFillPlan-BMZXiVMB.d.ts} +213 -28
  25. package/dist/{offerFillPlan-FmyaQoYT.d.cts → offerFillPlan-CqJerwXd.d.cts} +213 -28
  26. package/dist/openRfq-Dx-vxOzl.d.cts +32 -0
  27. package/dist/openRfq-Dx-vxOzl.d.ts +32 -0
  28. package/dist/openRfqTransport-MQZ7JWYN.js +9 -0
  29. package/dist/protocol.cjs +301 -322
  30. package/dist/protocol.d.cts +5 -5
  31. package/dist/protocol.d.ts +5 -5
  32. package/dist/protocol.js +6 -8
  33. package/dist/repositories/realm/index.d.cts +1 -1
  34. package/dist/repositories/realm/index.d.ts +1 -1
  35. package/dist/repositories/sqlite/index.d.cts +1 -1
  36. package/dist/repositories/sqlite/index.d.ts +1 -1
  37. package/dist/{repository-CwwhIAEd.d.cts → repository-CFC0fHAy.d.cts} +26 -26
  38. package/dist/{repository-DO6QKxBx.d.ts → repository-suGldzOK.d.ts} +26 -26
  39. package/dist/rfq-contract.cjs +3 -6
  40. package/dist/rfq-contract.d.cts +3 -4
  41. package/dist/rfq-contract.d.ts +3 -4
  42. package/dist/rfq-contract.js +3 -5
  43. package/dist/transportErrors-DZuZqnF4.d.cts +8 -0
  44. package/dist/transportErrors-DZuZqnF4.d.ts +8 -0
  45. package/dist/{verify-ENO36VPK.js → verify-HU5COTNO.js} +3 -3
  46. package/dist/{watch-_fZSgx_l.d.ts → watch-C2z6Onak.d.ts} +1 -1
  47. package/dist/{watch-DpDSP2tu.d.cts → watch-CpYjItYX.d.cts} +1 -1
  48. package/package.json +3 -3
package/dist/index.cjs CHANGED
@@ -370,6 +370,26 @@ var init_onchainHtlc = __esm({
370
370
  }
371
371
  });
372
372
 
373
+ // src/transportErrors.ts
374
+ var SolverUnavailable, SolverResponseInvalid;
375
+ var init_transportErrors = __esm({
376
+ "src/transportErrors.ts"() {
377
+ "use strict";
378
+ SolverUnavailable = class extends Error {
379
+ constructor(message, options) {
380
+ super(message, options);
381
+ this.name = "SolverUnavailable";
382
+ }
383
+ };
384
+ SolverResponseInvalid = class extends SolverUnavailable {
385
+ constructor(message, options) {
386
+ super(message, options);
387
+ this.name = "SolverResponseInvalid";
388
+ }
389
+ };
390
+ }
391
+ });
392
+
373
393
  // src/claimAmountGate.ts
374
394
  var bindsClaimAmount;
375
395
  var init_claimAmountGate = __esm({
@@ -636,135 +656,11 @@ var init_lockupContract = __esm({
636
656
  }
637
657
  });
638
658
 
639
- // src/contracts/asset-swap.json
640
- var asset_swap_default;
641
- var init_asset_swap = __esm({
642
- "src/contracts/asset-swap.json"() {
643
- asset_swap_default = {
644
- formatVersion: 1,
645
- contractName: "AssetSwap",
646
- constructorInputs: [
647
- {
648
- name: "receiver",
649
- type: "pubkey"
650
- },
651
- {
652
- name: "amount",
653
- type: "int"
654
- },
655
- {
656
- name: "assetTxid",
657
- type: "bytes32"
658
- },
659
- {
660
- name: "assetGroupIndex",
661
- type: "int"
662
- },
663
- {
664
- name: "user",
665
- type: "pubkey"
666
- }
667
- ],
668
- functions: [
669
- {
670
- name: "fulfill",
671
- arkade: {
672
- inputs: [],
673
- asm: [
674
- "OP_PUSHCURRENTINPUTINDEX",
675
- "OP_DUP",
676
- "<assetTxid>",
677
- "<assetGroupIndex>",
678
- "OP_INSPECTOUTASSETLOOKUP",
679
- "OP_VERIFY",
680
- "<amount>",
681
- "OP_GREATERTHANOREQUAL",
682
- "OP_VERIFY",
683
- "OP_INSPECTOUTPUTSCRIPTPUBKEY",
684
- "1",
685
- "OP_NUMEQUALVERIFY",
686
- "<receiver>",
687
- "OP_EQUAL"
688
- ]
689
- },
690
- leaves: [
691
- {
692
- name: "fulfill",
693
- witness: [
694
- {
695
- name: "serverSig",
696
- type: "signature",
697
- encoding: "schnorr-64",
698
- injected: true
699
- },
700
- {
701
- name: "emulatorSig",
702
- type: "signature",
703
- encoding: "schnorr-64",
704
- injected: true
705
- }
706
- ],
707
- asm: [
708
- "<SERVER_KEY>",
709
- "OP_CHECKSIGVERIFY",
710
- "<EMULATOR_KEY:fulfill>",
711
- "OP_CHECKSIG"
712
- ]
713
- }
714
- ]
715
- },
716
- {
717
- name: "cancel",
718
- leaves: [
719
- {
720
- name: "cancel",
721
- witness: [
722
- {
723
- name: "userSig",
724
- type: "signature",
725
- encoding: "schnorr-64"
726
- },
727
- {
728
- name: "serverSig",
729
- type: "signature",
730
- encoding: "schnorr-64",
731
- injected: true
732
- }
733
- ],
734
- asm: [
735
- "<user>",
736
- "OP_CHECKSIGVERIFY",
737
- "<SERVER_KEY>",
738
- "OP_CHECKSIG"
739
- ]
740
- }
741
- ]
742
- }
743
- ],
744
- source: {
745
- entry: "asset-swap.ark",
746
- files: {
747
- "asset-swap.ark": "pragma arkade ^0.1.0;\n\n// The output at this input's index pays `receiver` at least `amount` of the asset.\n// Coordination of who funds it lives outside the contract.\ncontract AssetSwap(\n pubkey receiver,\n int amount,\n bytes32 assetTxid,\n int assetGroupIndex,\n pubkey user\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 function cancel(signature userSig, signature serverSig) tapscript {\n require(checkMultisig([user, server], [userSig, serverSig], 2));\n }\n}\n"
748
- }
749
- },
750
- compiler: {
751
- name: "arkadec",
752
- version: "0.1.0-rc.1",
753
- options: {
754
- optimize: true
755
- }
756
- },
757
- updatedAt: "2026-11-02T17:43:42.615113722+00:00",
758
- fingerprint: "sha256:e2b80add6237f6c7e2c69a96ae46d55abe6de5f71c3718106f4d5b22ac9e6d0a"
759
- };
760
- }
761
- });
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 = {
659
+ // src/contracts/asset-swap-directed.json
660
+ var asset_swap_directed_default;
661
+ var init_asset_swap_directed = __esm({
662
+ "src/contracts/asset-swap-directed.json"() {
663
+ asset_swap_directed_default = {
768
664
  formatVersion: 1,
769
665
  contractName: "AssetSwap",
770
666
  constructorInputs: [
@@ -877,9 +773,9 @@ var init_asset_swap_v4 = __esm({
877
773
  }
878
774
  ],
879
775
  source: {
880
- entry: "asset-swap-v4.ark",
776
+ entry: "asset-swap-directed.ark",
881
777
  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"
778
+ "asset-swap-directed.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
779
  }
884
780
  },
885
781
  compiler: {
@@ -895,124 +791,11 @@ var init_asset_swap_v4 = __esm({
895
791
  }
896
792
  });
897
793
 
898
- // src/contracts/sats-swap.json
899
- var sats_swap_default;
900
- var init_sats_swap = __esm({
901
- "src/contracts/sats-swap.json"() {
902
- sats_swap_default = {
903
- formatVersion: 1,
904
- contractName: "SatsSwap",
905
- constructorInputs: [
906
- {
907
- name: "receiver",
908
- type: "pubkey"
909
- },
910
- {
911
- name: "amount",
912
- type: "int"
913
- },
914
- {
915
- name: "user",
916
- type: "pubkey"
917
- }
918
- ],
919
- functions: [
920
- {
921
- name: "fulfill",
922
- arkade: {
923
- inputs: [],
924
- asm: [
925
- "OP_PUSHCURRENTINPUTINDEX",
926
- "OP_DUP",
927
- "OP_INSPECTOUTPUTVALUE",
928
- "<amount>",
929
- "OP_GREATERTHANOREQUAL",
930
- "OP_VERIFY",
931
- "OP_INSPECTOUTPUTSCRIPTPUBKEY",
932
- "1",
933
- "OP_NUMEQUALVERIFY",
934
- "<receiver>",
935
- "OP_EQUAL"
936
- ]
937
- },
938
- leaves: [
939
- {
940
- name: "fulfill",
941
- witness: [
942
- {
943
- name: "serverSig",
944
- type: "signature",
945
- encoding: "schnorr-64",
946
- injected: true
947
- },
948
- {
949
- name: "emulatorSig",
950
- type: "signature",
951
- encoding: "schnorr-64",
952
- injected: true
953
- }
954
- ],
955
- asm: [
956
- "<SERVER_KEY>",
957
- "OP_CHECKSIGVERIFY",
958
- "<EMULATOR_KEY:fulfill>",
959
- "OP_CHECKSIG"
960
- ]
961
- }
962
- ]
963
- },
964
- {
965
- name: "cancel",
966
- leaves: [
967
- {
968
- name: "cancel",
969
- witness: [
970
- {
971
- name: "userSig",
972
- type: "signature",
973
- encoding: "schnorr-64"
974
- },
975
- {
976
- name: "serverSig",
977
- type: "signature",
978
- encoding: "schnorr-64",
979
- injected: true
980
- }
981
- ],
982
- asm: [
983
- "<user>",
984
- "OP_CHECKSIGVERIFY",
985
- "<SERVER_KEY>",
986
- "OP_CHECKSIG"
987
- ]
988
- }
989
- ]
990
- }
991
- ],
992
- source: {
993
- entry: "sats-swap.ark",
994
- files: {
995
- "sats-swap.ark": "pragma arkade ^0.1.0;\n\n// The output at this input's index pays `receiver` at least `amount` sats.\n// Coordination of who funds it lives outside the contract.\ncontract SatsSwap(\n pubkey receiver,\n int amount,\n pubkey user\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 cancel(signature userSig, signature serverSig) tapscript {\n require(checkMultisig([user, server], [userSig, serverSig], 2));\n }\n}\n"
996
- }
997
- },
998
- compiler: {
999
- name: "arkadec",
1000
- version: "0.1.0-rc.1",
1001
- options: {
1002
- optimize: true
1003
- }
1004
- },
1005
- updatedAt: "2026-11-02T17:43:42.616824535+00:00",
1006
- fingerprint: "sha256:d7a60ab2178ede40a2e4867816689ea022641531cc662b562bebd7caa1ef96c4"
1007
- };
1008
- }
1009
- });
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 = {
794
+ // src/contracts/sats-swap-directed.json
795
+ var sats_swap_directed_default;
796
+ var init_sats_swap_directed = __esm({
797
+ "src/contracts/sats-swap-directed.json"() {
798
+ sats_swap_directed_default = {
1016
799
  formatVersion: 1,
1017
800
  contractName: "SatsSwap",
1018
801
  constructorInputs: [
@@ -1114,9 +897,9 @@ var init_sats_swap_v4 = __esm({
1114
897
  }
1115
898
  ],
1116
899
  source: {
1117
- entry: "sats-swap-v4.ark",
900
+ entry: "sats-swap-directed.ark",
1118
901
  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"
902
+ "sats-swap-directed.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
903
  }
1121
904
  },
1122
905
  compiler: {
@@ -1218,7 +1001,7 @@ var init_swap_want_btc_program_v1 = __esm({
1218
1001
  });
1219
1002
 
1220
1003
  // src/rfq-contract.ts
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;
1004
+ var RFQ_CONTRACT_VERSIONS_KEY, RFQ_CONTRACT_VERSION_KEY, RFQ_CONTRACT_VERSION_UNSUPPORTED, ASSET_SWAP_V2, ASSET_SWAP_DIRECTED, ASSET_SWAP_BASELINE;
1222
1005
  var init_rfq_contract = __esm({
1223
1006
  "src/rfq-contract.ts"() {
1224
1007
  "use strict";
@@ -1226,60 +1009,41 @@ var init_rfq_contract = __esm({
1226
1009
  RFQ_CONTRACT_VERSION_KEY = "contract_version";
1227
1010
  RFQ_CONTRACT_VERSION_UNSUPPORTED = "contract_version_unsupported";
1228
1011
  ASSET_SWAP_V2 = "asset-swap-v2";
1229
- ASSET_SWAP_V3 = "asset-swap-v3";
1230
- ASSET_SWAP_V4 = "asset-swap-v4";
1012
+ ASSET_SWAP_DIRECTED = "asset-swap-directed";
1231
1013
  ASSET_SWAP_BASELINE = ASSET_SWAP_V2;
1232
1014
  }
1233
1015
  });
1234
1016
 
1235
1017
  // src/program.ts
1236
- var import_sdk4, swapPrograms, legacySwapPrograms, directedSwapPrograms, sharedArgs, refuseTaker, v3Args, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
1018
+ var import_sdk4, swapPrograms, directedSwapPrograms, sharedArgs, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
1237
1019
  var init_program = __esm({
1238
1020
  "src/program.ts"() {
1239
1021
  "use strict";
1240
1022
  import_sdk4 = require("@arkade-os/sdk");
1241
- init_asset_swap();
1242
- init_asset_swap_v4();
1243
- init_sats_swap();
1244
- init_sats_swap_v4();
1023
+ init_asset_swap_directed();
1024
+ init_sats_swap_directed();
1245
1025
  init_swap_want_asset_program_v1();
1246
1026
  init_swap_want_btc_program_v1();
1247
1027
  init_rfq_contract();
1248
1028
  init_rfq_contract();
1249
1029
  swapPrograms = {
1250
- wantAsset: import_sdk4.arkade.programFromArtifact(asset_swap_default),
1251
- wantBtc: import_sdk4.arkade.programFromArtifact(sats_swap_default)
1252
- };
1253
- legacySwapPrograms = {
1254
1030
  wantAsset: import_sdk4.arkade.parseArtifact(swap_want_asset_program_v1_default),
1255
1031
  wantBtc: import_sdk4.arkade.parseArtifact(swap_want_btc_program_v1_default)
1256
1032
  };
1257
1033
  directedSwapPrograms = {
1258
- wantAsset: import_sdk4.arkade.programFromArtifact(asset_swap_v4_default),
1259
- wantBtc: import_sdk4.arkade.programFromArtifact(sats_swap_v4_default)
1034
+ wantAsset: import_sdk4.arkade.programFromArtifact(asset_swap_directed_default),
1035
+ wantBtc: import_sdk4.arkade.programFromArtifact(sats_swap_directed_default)
1260
1036
  };
1261
1037
  sharedArgs = ({ user, server, exitDelay }) => ({
1262
1038
  user,
1263
1039
  server,
1264
1040
  ...exitDelay && { exitDelay }
1265
1041
  });
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
- });
1278
1042
  ASSET_SWAP_CONTRACTS = {
1279
1043
  [ASSET_SWAP_V2]: {
1280
- programs: legacySwapPrograms,
1044
+ programs: swapPrograms,
1281
1045
  args: (inputs) => {
1282
- refuseTaker(ASSET_SWAP_V2, inputs);
1046
+ if (inputs.taker !== void 0) throw new Error(`${ASSET_SWAP_V2} binds no taker key`);
1283
1047
  return {
1284
1048
  makerWP: inputs.receiver,
1285
1049
  wantAmount: inputs.amount,
@@ -1291,22 +1055,25 @@ var init_program = __esm({
1291
1055
  };
1292
1056
  }
1293
1057
  },
1294
- [ASSET_SWAP_V3]: {
1295
- programs: swapPrograms,
1296
- args: (inputs) => {
1297
- refuseTaker(ASSET_SWAP_V3, inputs);
1298
- return v3Args(inputs);
1299
- }
1300
- },
1301
- [ASSET_SWAP_V4]: {
1058
+ [ASSET_SWAP_DIRECTED]: {
1302
1059
  programs: directedSwapPrograms,
1303
1060
  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 };
1061
+ if (inputs.taker === void 0)
1062
+ throw new Error(`${ASSET_SWAP_DIRECTED} needs a taker key`);
1063
+ return {
1064
+ receiver: inputs.receiver,
1065
+ amount: inputs.amount,
1066
+ ...inputs.asset && {
1067
+ assetTxid: inputs.asset.txid,
1068
+ assetGroupIndex: inputs.asset.groupIndex
1069
+ },
1070
+ ...sharedArgs(inputs),
1071
+ taker: inputs.taker
1072
+ };
1306
1073
  }
1307
1074
  }
1308
1075
  };
1309
- ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_V4];
1076
+ ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_DIRECTED];
1310
1077
  assetSwapContractVersion = (id) => {
1311
1078
  if (id === void 0) return ASSET_SWAP_BASELINE;
1312
1079
  if (Object.hasOwn(ASSET_SWAP_CONTRACTS, id)) return id;
@@ -1580,19 +1347,16 @@ function swapProgramBinding(offer, operatorPubkey, contractVersion) {
1580
1347
  throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
1581
1348
  }
1582
1349
  const directed = offer.taker !== void 0;
1583
- const version = contractVersion ?? (directed ? ASSET_SWAP_V4 : ASSET_SWAP_BASELINE);
1350
+ const version = contractVersion ?? (directed ? ASSET_SWAP_DIRECTED : ASSET_SWAP_BASELINE);
1584
1351
  const expected = offer.swapPkScript;
1585
1352
  if (!expected?.length) return bindSwapProgram(offer, operatorPubkey, version);
1586
- const funded = import_base5.hex.encode(expected);
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);
1590
- if (pkOf(binding) === funded) return binding;
1591
- }
1592
- return bindSwapProgram(offer, operatorPubkey, directed ? ASSET_SWAP_V4 : version);
1353
+ const candidate = directed ? ASSET_SWAP_DIRECTED : ASSET_SWAP_BASELINE;
1354
+ const binding = bindSwapProgram(offer, operatorPubkey, candidate);
1355
+ if (pkOf(binding) === import_base5.hex.encode(expected)) return binding;
1356
+ return bindSwapProgram(offer, operatorPubkey, directed ? ASSET_SWAP_DIRECTED : version);
1593
1357
  }
1594
1358
  function bindSwapProgram(offer, operatorPubkey, contractVersion) {
1595
- const { programs, args } = ASSET_SWAP_CONTRACTS[contractVersion];
1359
+ const { programs, args } = ASSET_SWAP_CONTRACTS[assetSwapContractVersion(contractVersion)];
1596
1360
  const user = offer.makerPublicKey;
1597
1361
  const assetId = offer.wantAsset;
1598
1362
  return {
@@ -2676,6 +2440,7 @@ var init_rfq = __esm({
2676
2440
  "src/rfq.ts"() {
2677
2441
  "use strict";
2678
2442
  import_base6 = require("@scure/base");
2443
+ init_transportErrors();
2679
2444
  import_solver_discovery = require("@arkade-os/solver-discovery");
2680
2445
  import_legacy2 = require("@noble/hashes/legacy.js");
2681
2446
  import_sdk7 = require("@arkade-os/sdk");
@@ -3019,10 +2784,10 @@ var init_rfq = __esm({
3019
2784
  });
3020
2785
  }
3021
2786
  if (p?.type !== "rfq_quote" || p.rfq_id !== rfqId) {
3022
- throw new Error(`unexpected reply: ${p?.type ?? "no payload"}`);
2787
+ throw new SolverResponseInvalid(`unexpected reply: ${p?.type ?? "no payload"}`);
3023
2788
  }
3024
2789
  if (requestedPair !== void 0 && p.pair !== requestedPair) {
3025
- throw new Error(
2790
+ throw new SolverResponseInvalid(
3026
2791
  `solver quoted ${JSON.stringify(p.pair)}, not the requested ${requestedPair}`
3027
2792
  );
3028
2793
  }
@@ -3046,11 +2811,13 @@ var init_rfq = __esm({
3046
2811
  }
3047
2812
  const selected = quote[RFQ_CONTRACT_VERSION_KEY];
3048
2813
  if (sent !== request && selected !== void 0) {
3049
- throw new Error(`solver chose contract version ${selected}, but none was advertised`);
2814
+ throw new SolverResponseInvalid(
2815
+ `solver chose contract version ${selected}, but none was advertised`
2816
+ );
3050
2817
  }
3051
2818
  const version = selected ?? ASSET_SWAP_BASELINE;
3052
2819
  if (!advertised.includes(version)) {
3053
- throw new Error(
2820
+ throw new SolverResponseInvalid(
3054
2821
  selected === void 0 ? `solver negotiated no contract version; advertised ${advertised.join(", ")}` : `solver chose contract version ${version}, not one of ${advertised.join(", ")}`
3055
2822
  );
3056
2823
  }
@@ -3553,33 +3320,250 @@ var init_nostrPool = __esm({
3553
3320
  }
3554
3321
  });
3555
3322
 
3323
+ // src/openRfq.ts
3324
+ var RFQ_BROADCAST_KIND, idPattern, pairPattern, hexKey, positiveAtomic, positiveSeconds, openRfqPayload, parseOpenRfqBid, rankOpenRfqBids;
3325
+ var init_openRfq = __esm({
3326
+ "src/openRfq.ts"() {
3327
+ "use strict";
3328
+ RFQ_BROADCAST_KIND = 24860;
3329
+ idPattern = /^[a-f0-9]{64}$/;
3330
+ pairPattern = /^[a-zA-Z0-9:/._%-]{1,256}->[a-zA-Z0-9:/._%-]{1,256}$/;
3331
+ hexKey = /^[a-f0-9]{64}$/;
3332
+ positiveAtomic = (value) => typeof value === "string" && /^[1-9][0-9]{0,127}$/.test(value) ? BigInt(value) : void 0;
3333
+ positiveSeconds = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
3334
+ openRfqPayload = (request) => {
3335
+ if (!idPattern.test(request.openId) || !pairPattern.test(request.pair) || request.amountSide !== "from" && request.amountSide !== "to" || typeof request.amount !== "bigint" || positiveAtomic(request.amount.toString()) === void 0 || !positiveSeconds(request.bidsUntil))
3336
+ throw new Error("invalid open RFQ request");
3337
+ return {
3338
+ v: 1,
3339
+ type: "rfq_open",
3340
+ open_id: request.openId,
3341
+ pair: request.pair,
3342
+ amount_side: request.amountSide,
3343
+ amount: request.amount.toString(),
3344
+ bids_until: request.bidsUntil
3345
+ };
3346
+ };
3347
+ parseOpenRfqBid = (payload, solverPubkey, eventId) => {
3348
+ if (!payload || typeof payload !== "object" || !hexKey.test(solverPubkey) || !hexKey.test(eventId))
3349
+ return null;
3350
+ const value = payload;
3351
+ const fromAmount = positiveAtomic(value.from_amount);
3352
+ const toAmount2 = positiveAtomic(value.to_amount);
3353
+ if (value.v !== 1 || value.type !== "rfq_bid" || typeof value.open_id !== "string" || !idPattern.test(value.open_id) || typeof value.pair !== "string" || !pairPattern.test(value.pair) || value.amount_side !== "from" && value.amount_side !== "to" || fromAmount === void 0 || toAmount2 === void 0 || !positiveSeconds(value.valid_until) || !value.card || typeof value.card !== "object" || Array.isArray(value.card))
3354
+ return null;
3355
+ return {
3356
+ id: eventId,
3357
+ solverPubkey,
3358
+ openId: value.open_id,
3359
+ pair: value.pair,
3360
+ amountSide: value.amount_side,
3361
+ fromAmount,
3362
+ toAmount: toAmount2,
3363
+ validUntil: value.valid_until,
3364
+ card: value.card
3365
+ };
3366
+ };
3367
+ rankOpenRfqBids = (bids, amountSide) => [...bids].sort((left, right) => {
3368
+ const difference = amountSide === "from" ? right.toAmount - left.toAmount : left.fromAmount - right.fromAmount;
3369
+ return difference < 0n ? -1 : difference > 0n ? 1 : left.solverPubkey.localeCompare(right.solverPubkey) || left.id.localeCompare(right.id);
3370
+ });
3371
+ }
3372
+ });
3373
+
3374
+ // src/openRfqTransport.ts
3375
+ var openRfqTransport_exports = {};
3376
+ __export(openRfqTransport_exports, {
3377
+ collectOpenRfqBids: () => collectOpenRfqBids
3378
+ });
3379
+ var import_nostr_tools2, MAX_BIDS, MAX_AUTHENTICATED_REPLY_DECRYPTIONS, MAX_EVENT_CONTENT, MAX_WINDOW_MS, CLOCK_SKEW_SECONDS, collectOpenRfqBids;
3380
+ var init_openRfqTransport = __esm({
3381
+ "src/openRfqTransport.ts"() {
3382
+ "use strict";
3383
+ import_nostr_tools2 = require("nostr-tools");
3384
+ init_nostr();
3385
+ init_nostrPool();
3386
+ init_openRfq();
3387
+ init_transportErrors();
3388
+ MAX_BIDS = 64;
3389
+ MAX_AUTHENTICATED_REPLY_DECRYPTIONS = 256;
3390
+ MAX_EVENT_CONTENT = 1e5;
3391
+ MAX_WINDOW_MS = 3e4;
3392
+ CLOCK_SKEW_SECONDS = 30;
3393
+ collectOpenRfqBids = (request, options) => {
3394
+ const payload = openRfqPayload(request);
3395
+ const windowMs = options.windowMs ?? 3e3;
3396
+ if (!Number.isSafeInteger(windowMs) || windowMs < 0 || windowMs > MAX_WINDOW_MS)
3397
+ throw new Error("windowMs must be an integer between 0 and 30000");
3398
+ const started = Date.now();
3399
+ const now = Math.floor(started / 1e3);
3400
+ const duration = Math.min(windowMs, request.bidsUntil * 1e3 - started);
3401
+ if (duration < 0 || request.bidsUntil > now + 31) throw new Error("invalid open RFQ deadline");
3402
+ const relays = [...new Set(options.relays)];
3403
+ if (!relays.length || relays.length > 16)
3404
+ throw new Error("open RFQ requires between 1 and 16 relays");
3405
+ for (const relay of relays) {
3406
+ const url = new URL(relay);
3407
+ if (!/^wss?:$/.test(url.protocol) || url.username || url.password || url.hash)
3408
+ throw new Error("invalid open RFQ relay");
3409
+ }
3410
+ options.signal?.throwIfAborted();
3411
+ const secretKey = new Uint8Array(options.secretKey);
3412
+ const clientPubkey = (0, import_nostr_tools2.getPublicKey)(secretKey);
3413
+ const event = (0, import_nostr_tools2.finalizeEvent)(
3414
+ {
3415
+ kind: RFQ_BROADCAST_KIND,
3416
+ created_at: now,
3417
+ tags: [["t", request.pair]],
3418
+ content: JSON.stringify(payload)
3419
+ },
3420
+ secretKey
3421
+ );
3422
+ const pool = options.pool ?? sharedNostrPool();
3423
+ return new Promise((resolve, reject) => {
3424
+ const bids = /* @__PURE__ */ new Map();
3425
+ const seen = /* @__PURE__ */ new Set();
3426
+ let closed = false;
3427
+ let accepted = false;
3428
+ let subscription;
3429
+ const noRelay = () => new SolverUnavailable("no relay accepted the open RFQ");
3430
+ const finish = (error) => {
3431
+ if (closed) return;
3432
+ closed = true;
3433
+ clearTimeout(timer);
3434
+ options.signal?.removeEventListener("abort", abort);
3435
+ try {
3436
+ subscription?.close();
3437
+ } catch {
3438
+ }
3439
+ secretKey.fill(0);
3440
+ if (error !== void 0) reject(error);
3441
+ else resolve(rankOpenRfqBids([...bids.values()], request.amountSide));
3442
+ };
3443
+ const abort = () => finish(options.signal?.reason ?? new Error("open RFQ aborted"));
3444
+ const timer = setTimeout(() => finish(accepted ? void 0 : noRelay()), duration);
3445
+ options.signal?.addEventListener("abort", abort, { once: true });
3446
+ try {
3447
+ subscription = pool.subscribeMany(
3448
+ relays,
3449
+ {
3450
+ kinds: [RFQ_DIRECTED_KIND],
3451
+ "#p": [clientPubkey],
3452
+ "#e": [event.id],
3453
+ since: now - CLOCK_SKEW_SECONDS
3454
+ },
3455
+ {
3456
+ onevent(reply) {
3457
+ const current = Math.floor(Date.now() / 1e3);
3458
+ if (closed || !reply || typeof reply.content !== "string" || typeof reply.id !== "string" || !/^[a-f0-9]{64}$/.test(reply.id) || typeof reply.pubkey !== "string" || !/^[a-f0-9]{64}$/.test(reply.pubkey) || typeof reply.sig !== "string" || !/^[a-f0-9]{128}$/.test(reply.sig) || !Array.isArray(reply.tags) || reply.tags.length > 32 || !reply.tags.every(
3459
+ (tag) => Array.isArray(tag) && tag.length <= 8 && tag.every(
3460
+ (value) => typeof value === "string" && value.length <= 1024
3461
+ )
3462
+ ) || Date.now() >= started + duration || reply.kind !== RFQ_DIRECTED_KIND || reply.content.length > MAX_EVENT_CONTENT || !Number.isSafeInteger(reply.created_at) || reply.created_at < event.created_at - CLOCK_SKEW_SECONDS || reply.created_at > current + CLOCK_SKEW_SECONDS || reply.created_at >= request.bidsUntil || seen.has(reply.id) || seen.size >= MAX_AUTHENTICATED_REPLY_DECRYPTIONS)
3463
+ return;
3464
+ const recipients = reply.tags.filter((tag) => tag[0] === "p");
3465
+ const references = reply.tags.filter((tag) => tag[0] === "e");
3466
+ if (recipients.length !== 1 || recipients[0]?.[1] !== clientPubkey || references.length !== 1 || references[0]?.[1] !== event.id)
3467
+ return;
3468
+ try {
3469
+ if (!(0, import_nostr_tools2.verifyEvent)(reply)) return;
3470
+ seen.add(reply.id);
3471
+ const key = import_nostr_tools2.nip44.v2.utils.getConversationKey(secretKey, reply.pubkey);
3472
+ const bid = parseOpenRfqBid(
3473
+ JSON.parse(import_nostr_tools2.nip44.v2.decrypt(reply.content, key)),
3474
+ reply.pubkey,
3475
+ reply.id
3476
+ );
3477
+ if (!bid || bid.openId !== request.openId || bid.pair !== request.pair || bid.amountSide !== request.amountSide || bid.validUntil <= current || bid.validUntil <= request.bidsUntil || (request.amountSide === "from" ? bid.fromAmount : bid.toAmount) !== request.amount)
3478
+ return;
3479
+ const previous = bids.get(bid.solverPubkey);
3480
+ if (previous) {
3481
+ const improved = request.amountSide === "from" ? bid.toAmount > previous.toAmount : bid.fromAmount < previous.fromAmount;
3482
+ if (!improved) return;
3483
+ } else if (bids.size >= MAX_BIDS) {
3484
+ const worst = rankOpenRfqBids(
3485
+ [...bids.values()],
3486
+ request.amountSide
3487
+ ).at(-1);
3488
+ if (rankOpenRfqBids([worst, bid], request.amountSide)[0] !== bid)
3489
+ return;
3490
+ bids.delete(worst.solverPubkey);
3491
+ }
3492
+ bids.set(bid.solverPubkey, bid);
3493
+ accepted = true;
3494
+ options.onBids?.(
3495
+ rankOpenRfqBids([...bids.values()], request.amountSide)
3496
+ );
3497
+ } catch {
3498
+ }
3499
+ },
3500
+ onclose(reasons) {
3501
+ finish(new RelayUnavailable(reasons.map(String)));
3502
+ }
3503
+ }
3504
+ );
3505
+ if (closed) subscription.close();
3506
+ else {
3507
+ const publications = pool.publish(relays, event);
3508
+ if (!publications.length) finish(noRelay());
3509
+ void Promise.allSettled(publications).then((results) => {
3510
+ accepted ||= results.some(
3511
+ (result) => result.status === "fulfilled" && !String(result.value).startsWith("connection failure")
3512
+ );
3513
+ if (!accepted) finish(noRelay());
3514
+ });
3515
+ for (const publication of publications)
3516
+ void publication.then(
3517
+ (result) => {
3518
+ if (!String(result).startsWith("connection failure")) accepted = true;
3519
+ },
3520
+ () => {
3521
+ }
3522
+ );
3523
+ }
3524
+ } catch (error) {
3525
+ finish(error);
3526
+ }
3527
+ });
3528
+ };
3529
+ }
3530
+ });
3531
+
3556
3532
  // src/nostr.ts
3557
3533
  var nostr_exports = {};
3558
3534
  __export(nostr_exports, {
3535
+ RFQ_BROADCAST_KIND: () => RFQ_BROADCAST_KIND,
3559
3536
  RFQ_DIRECTED_KIND: () => RFQ_DIRECTED_KIND,
3560
3537
  RelayUnavailable: () => RelayUnavailable,
3561
3538
  TransportClosed: () => TransportClosed,
3562
3539
  closeSharedNostrPool: () => closeSharedNostrPool,
3540
+ collectOpenRfqBids: () => collectOpenRfqBids,
3563
3541
  createNostrPool: () => createNostrPool,
3564
3542
  nostrCardFetcher: () => nostrCardFetcher,
3565
3543
  nostrRfqTransport: () => nostrRfqTransport,
3544
+ openRfqPayload: () => openRfqPayload,
3545
+ parseOpenRfqBid: () => parseOpenRfqBid,
3546
+ rankOpenRfqBids: () => rankOpenRfqBids,
3566
3547
  sharedNostrPool: () => sharedNostrPool
3567
3548
  });
3568
- var import_solver_discovery2, import_sdk16, import_nostr_tools2, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CONNECTION_FAILURE, CARD_FETCH_TIMEOUT_MS, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
3549
+ var import_solver_discovery2, import_sdk16, import_nostr_tools3, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CONNECTION_FAILURE, CARD_FETCH_TIMEOUT_MS, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
3569
3550
  var init_nostr = __esm({
3570
3551
  "src/nostr.ts"() {
3571
3552
  "use strict";
3572
3553
  import_solver_discovery2 = require("@arkade-os/solver-discovery");
3573
3554
  init_rfq();
3574
3555
  init_nostrPool();
3556
+ init_transportErrors();
3575
3557
  import_sdk16 = require("@arkade-os/sdk");
3576
- import_nostr_tools2 = require("nostr-tools");
3558
+ import_nostr_tools3 = require("nostr-tools");
3577
3559
  init_nostrPool();
3560
+ init_openRfqTransport();
3561
+ init_openRfq();
3578
3562
  RFQ_DIRECTED_KIND = 24859;
3579
3563
  DEFAULT_TIMEOUT_MS = 3e4;
3580
3564
  CONNECTION_FAILURE = "connection failure";
3581
3565
  CARD_FETCH_TIMEOUT_MS = 5e3;
3582
- RelayUnavailable = class extends Error {
3566
+ RelayUnavailable = class extends SolverUnavailable {
3583
3567
  reasons;
3584
3568
  constructor(reasons) {
3585
3569
  super(`lost every relay connection: ${reasons.join("; ") || "connection closed"}`);
@@ -3602,11 +3586,11 @@ var init_nostr = __esm({
3602
3586
  (0, import_sdk16.assertTimerMs)("timeoutMs", options.timeoutMs);
3603
3587
  const relays = options.relays;
3604
3588
  const solverPubkey = options.solverPubkey;
3605
- const secretKey = options.secretKey ?? (0, import_nostr_tools2.generateSecretKey)();
3606
- const pubkey = (0, import_nostr_tools2.getPublicKey)(secretKey);
3589
+ const secretKey = options.secretKey ?? (0, import_nostr_tools3.generateSecretKey)();
3590
+ const pubkey = (0, import_nostr_tools3.getPublicKey)(secretKey);
3607
3591
  const pool = options.pool ?? sharedNostrPool();
3608
3592
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3609
- const conversationKey = import_nostr_tools2.nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
3593
+ const conversationKey = import_nostr_tools3.nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
3610
3594
  let closed = false;
3611
3595
  let lost;
3612
3596
  const waiters = /* @__PURE__ */ new Map();
@@ -3615,10 +3599,10 @@ var init_nostr = __esm({
3615
3599
  { kinds: [RFQ_DIRECTED_KIND], "#p": [pubkey], authors: [solverPubkey] },
3616
3600
  {
3617
3601
  onevent(event) {
3618
- if (event.pubkey !== solverPubkey || !(0, import_nostr_tools2.verifyEvent)(event)) return;
3602
+ if (event.pubkey !== solverPubkey || !(0, import_nostr_tools3.verifyEvent)(event)) return;
3619
3603
  let payload;
3620
3604
  try {
3621
- payload = JSON.parse(import_nostr_tools2.nip44.v2.decrypt(event.content, conversationKey));
3605
+ payload = JSON.parse(import_nostr_tools3.nip44.v2.decrypt(event.content, conversationKey));
3622
3606
  } catch {
3623
3607
  return;
3624
3608
  }
@@ -3637,12 +3621,12 @@ var init_nostr = __esm({
3637
3621
  }
3638
3622
  );
3639
3623
  const send = async (payload) => {
3640
- const event = (0, import_nostr_tools2.finalizeEvent)(
3624
+ const event = (0, import_nostr_tools3.finalizeEvent)(
3641
3625
  {
3642
3626
  kind: RFQ_DIRECTED_KIND,
3643
3627
  created_at: Math.floor(Date.now() / 1e3),
3644
3628
  tags: [["p", solverPubkey]],
3645
- content: import_nostr_tools2.nip44.v2.encrypt(JSON.stringify(payload), conversationKey)
3629
+ content: import_nostr_tools3.nip44.v2.encrypt(JSON.stringify(payload), conversationKey)
3646
3630
  },
3647
3631
  secretKey
3648
3632
  );
@@ -3653,13 +3637,14 @@ var init_nostr = __esm({
3653
3637
  const accepted = results.some(
3654
3638
  (r) => r.status === "fulfilled" && !String(r.value).startsWith(CONNECTION_FAILURE)
3655
3639
  );
3656
- if (!accepted) throw new Error(`no relay accepted the RFQ message: ${reasons.join("; ")}`);
3640
+ if (!accepted)
3641
+ throw new SolverUnavailable(`no relay accepted the RFQ message: ${reasons.join("; ")}`);
3657
3642
  };
3658
3643
  const awaitReply = (rfqId) => {
3659
3644
  const reply = new Promise((resolve, reject) => {
3660
3645
  const timer = setTimeout(() => {
3661
3646
  waiters.delete(rfqId);
3662
- reject(new Error(`no solver reply within ${timeoutMs}ms`));
3647
+ reject(new SolverUnavailable(`no solver reply within ${timeoutMs}ms`));
3663
3648
  }, timeoutMs);
3664
3649
  waiters.set(rfqId, {
3665
3650
  resolve: (payload) => {
@@ -3745,7 +3730,7 @@ var init_nostr = __esm({
3745
3730
  onevent(event) {
3746
3731
  if (event.kind !== import_solver_discovery2.SOLVER_CARD_KIND || !asked.has(event.pubkey))
3747
3732
  return;
3748
- if (!(0, import_nostr_tools2.verifyEvent)(event)) return;
3733
+ if (!(0, import_nostr_tools3.verifyEvent)(event)) return;
3749
3734
  if (event.tags.find((tag) => tag[0] === "d")?.[1] !== network)
3750
3735
  return;
3751
3736
  if (isNewer(event, latest.get(event.pubkey)))
@@ -4067,6 +4052,9 @@ __export(index_exports, {
4067
4052
  SEALED_CIPHERTEXT_LENGTH: () => SEALED_CIPHERTEXT_LENGTH,
4068
4053
  SWAP_ERROR_NAMES: () => SWAP_ERROR_NAMES,
4069
4054
  SWAP_ROUTER_PRIORITY: () => SWAP_ROUTER_PRIORITY,
4055
+ SolverResponseInvalid: () => SolverResponseInvalid,
4056
+ SolverRoutesUnavailable: () => SolverRoutesUnavailable,
4057
+ SolverUnavailable: () => SolverUnavailable,
4070
4058
  SwapDriveRefusedError: () => SwapDriveRefusedError,
4071
4059
  SwapPaymentFailedError: () => SwapPaymentFailedError,
4072
4060
  SwapRefusal: () => SwapRefusal,
@@ -4082,6 +4070,8 @@ __export(index_exports, {
4082
4070
  canonicalAssetId: () => canonicalAssetId,
4083
4071
  claimFeeSats: () => claimFeeSats,
4084
4072
  claimPacketShape: () => claimPacketShape,
4073
+ completedSolverUsage: () => completedSolverUsage,
4074
+ createSolverHealth: () => createSolverHealth,
4085
4075
  createSwapClient: () => createSwapClient,
4086
4076
  createSwapPaymentRouter: () => createSwapPaymentRouter,
4087
4077
  deepFreeze: () => deepFreeze,
@@ -6318,6 +6308,7 @@ var commonOf = (quote, now) => ({
6318
6308
  market: quote.market,
6319
6309
  ...quote.solver === void 0 ? {} : { solver: quote.solver },
6320
6310
  expiresAt: quote.expiresAt,
6311
+ ...quote.auction === void 0 ? {} : { fundingDeadline: quote.expiresAt },
6321
6312
  ...quote.artifact === void 0 ? {} : { artifact: recordArtifact(quote.artifact) },
6322
6313
  createdAt: now,
6323
6314
  updatedAt: now
@@ -6504,8 +6495,14 @@ var registeredCorridorRecord = async (input, preparation) => {
6504
6495
  return corridorRecord(input.quote, preparation, input.now);
6505
6496
  };
6506
6497
  var fundAndStamp = async (input, record, repository) => {
6498
+ if (record.fundingDeadline !== void 0 && (!Number.isSafeInteger(record.fundingDeadline) || record.fundingDeadline <= 0 || record.fundingDeadline > record.expiresAt))
6499
+ throw new Error("invalid stored funding deadline");
6507
6500
  const bounds = storedFundingBounds(record.assetPayment, record.expiresAt);
6508
- const cap = input.validUntil === void 0 ? bounds.validUntil : Math.min(input.validUntil, bounds.validUntil ?? record.expiresAt);
6501
+ const cap = input.validUntil === void 0 ? record.fundingDeadline === void 0 ? bounds.validUntil : Math.min(record.fundingDeadline, bounds.validUntil ?? record.expiresAt) : Math.min(
6502
+ input.validUntil,
6503
+ bounds.validUntil ?? record.expiresAt,
6504
+ record.fundingDeadline ?? record.expiresAt
6505
+ );
6509
6506
  const validUntil = cap === void 0 ? void 0 : Math.min(cap, record.expiresAt);
6510
6507
  if (input.firstFundingAttempt && record.assetPayment !== void 0 && validUntil !== void 0 && validUntil < record.assetPayment.validUntil) {
6511
6508
  record = { ...record, assetPayment: { ...record.assetPayment, validUntil } };
@@ -7140,6 +7137,11 @@ var covenantOf = (swap) => ({
7140
7137
  ...swap.offerHex === void 0 ? {} : { offerHex: swap.offerHex },
7141
7138
  ...swap.binding === void 0 ? {} : { binding: swap.binding }
7142
7139
  });
7140
+ var restoredCovenant = (swap) => {
7141
+ if (swap.binding !== void 0) return { ...covenantOf(swap), binding: swap.binding };
7142
+ if (swap.offerHex !== void 0) return { offerHex: swap.offerHex };
7143
+ throw new Error("this offer swap carries neither a binding nor an offerHex to rebuild from");
7144
+ };
7143
7145
  var offerFactsOf = (record) => ({
7144
7146
  id: record.id,
7145
7147
  coverageId: record.id,
@@ -7216,7 +7218,7 @@ var restoredOfferRecord = (swap, network, now) => {
7216
7218
  market: { kind: "restored", backend: "feed" },
7217
7219
  expiresAt: createdAt,
7218
7220
  status: swap.status,
7219
- ...covenantOf(swap),
7221
+ ...restoredCovenant(swap),
7220
7222
  swapAddress: swap.swapAddress,
7221
7223
  swapPkScript: swap.swapPkScript,
7222
7224
  fundingTxid: swap.fundingTxid,
@@ -7660,8 +7662,8 @@ function withExitV0(program, exit) {
7660
7662
  }
7661
7663
  var V0_TO_V1 = /* @__PURE__ */ new Map();
7662
7664
  for (const [v0, v1] of [
7663
- [swap_want_btc_program_v0_default, legacySwapPrograms.wantBtc],
7664
- [swap_want_asset_program_v0_default, legacySwapPrograms.wantAsset]
7665
+ [swap_want_btc_program_v0_default, swapPrograms.wantBtc],
7666
+ [swap_want_asset_program_v0_default, swapPrograms.wantAsset]
7665
7667
  ]) {
7666
7668
  for (const exit of [void 0, "blocks", "seconds"]) {
7667
7669
  const timelock = exit && { type: exit, value: BigInt(0) };
@@ -10332,6 +10334,8 @@ var pinAmount = (input, takeInstrument) => {
10332
10334
 
10333
10335
  // src/client/quoteOffer.ts
10334
10336
  init_verify();
10337
+ init_transportErrors();
10338
+ init_rfq();
10335
10339
  var FEED_TTL_MS = 3e4;
10336
10340
  var feedFetch = (base = fetch) => {
10337
10341
  const at2 = /* @__PURE__ */ new Map();
@@ -10341,20 +10345,32 @@ var feedFetch = (base = fetch) => {
10341
10345
  };
10342
10346
  return { fetch: makeCachedFeedFetch(FEED_TTL_MS, probe), fetchedAt: (url) => at2.get(url) };
10343
10347
  };
10348
+ var quoteAdvertisedPlan = (card, options, policy) => (0, import_solver_discovery11.quoteOffer)(card, options).catch((cause) => {
10349
+ const cancelled = options.signal?.aborted || cause !== null && typeof cause === "object" && "name" in cause && cause.name === "AbortError";
10350
+ if (policy?.solverRouting === void 0 || cancelled) throw cause;
10351
+ throw new SolverUnavailable("The solver's advertised price is unavailable", { cause });
10352
+ });
10344
10353
  var quoteFromFeed = async (input) => {
10345
10354
  const { candidate, amount } = input;
10346
10355
  if (amount === void 0) {
10347
10356
  throw new Error("an asset swap needs an amount and the side it pins");
10348
10357
  }
10349
- const plan = await (0, import_solver_discovery11.quoteOffer)(candidate.card, {
10350
- give: candidate.give,
10351
- ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
10352
- // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
10353
- // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
10354
- carrierSats: ASSET_CARRIER_SATS,
10355
- ...QUOTE_OPTIONS,
10356
- fetchImpl: input.feed.fetch
10357
- });
10358
+ const plan = await quoteAdvertisedPlan(
10359
+ candidate.card,
10360
+ {
10361
+ give: candidate.give,
10362
+ ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
10363
+ // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
10364
+ // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
10365
+ carrierSats: ASSET_CARRIER_SATS,
10366
+ ...QUOTE_OPTIONS,
10367
+ fetchImpl: input.feed.fetch
10368
+ },
10369
+ input.policy
10370
+ );
10371
+ if (input.policy?.solverRouting !== void 0 && !plan.limits.withinLimits) {
10372
+ throw new SwapRefusal("amount_out_of_range");
10373
+ }
10358
10374
  verifyPlanLegs(plan, input.legs, candidate.give);
10359
10375
  const expiresAt = feedExpiry(candidate.card, input.feed, input.now);
10360
10376
  verifyQuoteTtl({
@@ -10422,7 +10438,6 @@ var verifyPlanLegs = (plan, legs, give) => {
10422
10438
  // src/client/quoteRfq.ts
10423
10439
  var import_base23 = require("@scure/base");
10424
10440
  var import_sdk36 = require("@arkade-os/sdk");
10425
- var import_solver_discovery12 = require("@arkade-os/solver-discovery");
10426
10441
 
10427
10442
  // src/jointGraph.ts
10428
10443
  var import_base22 = require("@scure/base");
@@ -10712,6 +10727,7 @@ function onchainSwapRail(client, deps) {
10712
10727
  init_rfq_contract();
10713
10728
  init_rfq();
10714
10729
  init_errors();
10730
+ init_transportErrors();
10715
10731
 
10716
10732
  // src/client/rfqWire.ts
10717
10733
  init_rfq();
@@ -10762,6 +10778,16 @@ var covenantInputs = (input) => {
10762
10778
  hrp: network.hrp
10763
10779
  };
10764
10780
  };
10781
+ var parseRfqQuote2 = (wire, policy) => {
10782
+ try {
10783
+ return parseRfqQuote(wire);
10784
+ } catch (cause) {
10785
+ if (policy?.solverRouting !== void 0 && cause instanceof AmountEncodingUnsupported) {
10786
+ throw new SolverResponseInvalid(cause.message, { cause });
10787
+ }
10788
+ throw cause;
10789
+ }
10790
+ };
10765
10791
  var sealingKey = (deps) => {
10766
10792
  const configured = deps.covclaimd?.pubkey;
10767
10793
  if (configured === void 0) return void 0;
@@ -10863,8 +10889,8 @@ var quoteArkadeAsset = async (input) => {
10863
10889
  ASSET_SWAP_CONTRACT_VERSIONS
10864
10890
  );
10865
10891
  verifyPair(wire.pair, pair);
10866
- const parsed = parseRfqQuote(wire);
10867
- const taker = contractVersion === ASSET_SWAP_V4 ? verifyTaker({
10892
+ const parsed = parseRfqQuote2(wire, input.policy);
10893
+ const taker = contractVersion === ASSET_SWAP_DIRECTED ? verifyTaker({
10868
10894
  attested: input.transport.attestedResponder,
10869
10895
  solverPubkey: parsed.solver
10870
10896
  }) : void 0;
@@ -10910,15 +10936,19 @@ var quoteArkadeAsset = async (input) => {
10910
10936
  }
10911
10937
  if (assetPayment !== void 0) deepFreeze(assetPayment);
10912
10938
  const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
10913
- const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
10914
- give: input.candidate.give,
10915
- giveAmount: parsed.give,
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,
10919
- ...QUOTE_OPTIONS,
10920
- fetchImpl: input.feed.fetch
10921
- });
10939
+ const reference = await quoteAdvertisedPlan(
10940
+ input.candidate.card,
10941
+ {
10942
+ give: input.candidate.give,
10943
+ giveAmount: parsed.give,
10944
+ // Unconditional: a card charging for the delivered carrier refuses to price without
10945
+ // it whichever leg gives, and a BTC deposit funds none of its own to publish.
10946
+ carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
10947
+ ...QUOTE_OPTIONS,
10948
+ fetchImpl: input.feed.fetch
10949
+ },
10950
+ input.policy
10951
+ );
10922
10952
  verifyPlanLegs(reference, input.legs, input.candidate.give);
10923
10953
  const terms = offerTermsFromQuote(wire, sides);
10924
10954
  const offer = await deriveOffer(input.wallet, {
@@ -11011,7 +11041,7 @@ var quoteLightningSend = async (input) => {
11011
11041
  })
11012
11042
  );
11013
11043
  verifyPair(wire.pair, pair);
11014
- const parsed = parseRfqQuote(wire);
11044
+ const parsed = parseRfqQuote2(wire, input.policy);
11015
11045
  verifySendInvoice({ invoiced: invoice.amount, give: parsed.give, take: parsed.take });
11016
11046
  const covenant = covenantInputs(input);
11017
11047
  const derived = verifyingDerivation(
@@ -11106,7 +11136,7 @@ var quoteLightningReceive = async (input) => {
11106
11136
  )
11107
11137
  );
11108
11138
  verifyPair(wire.pair, pair);
11109
- const parsed = parseRfqQuote(wire);
11139
+ const parsed = parseRfqQuote2(wire, input.policy);
11110
11140
  verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
11111
11141
  const covenant = covenantInputs(input);
11112
11142
  const derived = verifyingDerivation(
@@ -11180,6 +11210,16 @@ var quoteLightningReceive = async (input) => {
11180
11210
  }
11181
11211
  };
11182
11212
  };
11213
+ var solverFacingAmount = (route, pinned, corridors) => {
11214
+ if (route !== "arkade->onchain" || pinned.on !== "take") return { quoted: pinned };
11215
+ const onchain = corridors.get("onchain").deps;
11216
+ if (onchain.claimFeeRateSatVb === void 0) return { quoted: pinned };
11217
+ const claimFee = claimFeeSats({
11218
+ claimFeeRateSatVb: onchain.claimFeeRateSatVb,
11219
+ claimVsize: onchain.claimVsize
11220
+ });
11221
+ return { quoted: { ...pinned, value: pinned.value + claimFee }, claimFee };
11222
+ };
11183
11223
  var quoteOnchainSend = async (input) => {
11184
11224
  const pinned = pinnedFor(input);
11185
11225
  const destination = input.endpoints.take.instrument;
@@ -11190,12 +11230,7 @@ var quoteOnchainSend = async (input) => {
11190
11230
  const payoutPkScript = l1ScriptForAddress(destination.address, l1Network);
11191
11231
  const pair = rfqPairFor(input.legs.give, input.legs.take);
11192
11232
  const rfqId = newRfqId();
11193
- const onchain = input.corridors.get("onchain").deps;
11194
- const claimFee = pinned.on === "take" && onchain.claimFeeRateSatVb !== void 0 ? claimFeeSats({
11195
- claimFeeRateSatVb: onchain.claimFeeRateSatVb,
11196
- claimVsize: onchain.claimVsize
11197
- }) : void 0;
11198
- const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
11233
+ const { quoted, claimFee } = solverFacingAmount(input.route, pinned, input.corridors);
11199
11234
  const [secrets, payoutKey] = await Promise.all([
11200
11235
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
11201
11236
  (0, import_sdk36.provisionRefundKey)(input.wallet)
@@ -11216,7 +11251,7 @@ var quoteOnchainSend = async (input) => {
11216
11251
  )
11217
11252
  );
11218
11253
  verifyPair(wire.pair, pair);
11219
- const parsed = parseRfqQuote(wire);
11254
+ const parsed = parseRfqQuote2(wire, input.policy);
11220
11255
  verifyQuotedAmount({ pair, pinned: quoted, give: parsed.give, take: parsed.take });
11221
11256
  if (claimFee !== void 0) {
11222
11257
  const payout = parsed.take - claimFee;
@@ -11329,7 +11364,7 @@ var quoteOnchainReceive = async (input) => {
11329
11364
  )
11330
11365
  );
11331
11366
  verifyPair(wire.pair, pair);
11332
- const parsed = parseRfqQuote(wire);
11367
+ const parsed = parseRfqQuote2(wire, input.policy);
11333
11368
  verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
11334
11369
  const covenant = covenantInputs(input);
11335
11370
  const derived = verifyingDerivation(
@@ -11416,6 +11451,9 @@ var quoteOnchainReceive = async (input) => {
11416
11451
  };
11417
11452
  };
11418
11453
 
11454
+ // src/client/client.ts
11455
+ init_verify();
11456
+
11419
11457
  // src/client/verbs.ts
11420
11458
  var import_sdk37 = require("@arkade-os/sdk");
11421
11459
  init_errors();
@@ -11510,6 +11548,225 @@ var createNostrTransportFactory = (pool) => {
11510
11548
  };
11511
11549
  var nostrTransportFactory = createNostrTransportFactory();
11512
11550
 
11551
+ // src/client/solverHealth.ts
11552
+ var QUIET_MS = 30 * 6e4;
11553
+ var cooldown = (failures) => failures < 2 ? 0 : Math.min(6e4 * 2 ** Math.min(failures - 2, 4), 15 * 6e4);
11554
+ function createSolverHealth(options = {}) {
11555
+ const now = options.now ?? (() => Date.now());
11556
+ const memory = /* @__PURE__ */ new Map();
11557
+ const keyOf = (scope) => JSON.stringify([scope.network, scope.direction]);
11558
+ const storage = options.storage ?? {
11559
+ load: (scope) => memory.get(keyOf(scope)),
11560
+ save: (scope, records) => {
11561
+ memory.set(keyOf(scope), records);
11562
+ }
11563
+ };
11564
+ const pending = /* @__PURE__ */ new Map();
11565
+ const active = (records, timestamp) => Object.keys(records).filter(
11566
+ (id) => timestamp < records[id].lastFailureAt + cooldown(records[id].failures)
11567
+ );
11568
+ const read = async (scope) => {
11569
+ try {
11570
+ const value = await storage.load(scope);
11571
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
11572
+ const timestamp = now();
11573
+ return Object.fromEntries(
11574
+ Object.entries(value).flatMap(([id, entry]) => {
11575
+ if (!entry || typeof entry !== "object") return [];
11576
+ const { failures, lastFailureAt } = entry;
11577
+ return typeof failures === "number" && Number.isSafeInteger(failures) && failures > 0 && failures <= 32 && typeof lastFailureAt === "number" && Number.isFinite(lastFailureAt) && lastFailureAt >= 0 && lastFailureAt <= timestamp && timestamp - lastFailureAt < QUIET_MS ? [[id, { failures, lastFailureAt }]] : [];
11578
+ })
11579
+ );
11580
+ } catch {
11581
+ return {};
11582
+ }
11583
+ };
11584
+ return {
11585
+ deprioritized: async (scope) => {
11586
+ await pending.get(keyOf(scope));
11587
+ const records = await read(scope);
11588
+ const timestamp = now();
11589
+ return active(records, timestamp);
11590
+ },
11591
+ record: (scope, solverId3, outcome) => {
11592
+ const key = keyOf(scope);
11593
+ const update = (pending.get(key) ?? Promise.resolve()).then(async () => {
11594
+ let records = await read(scope);
11595
+ const before = JSON.stringify(active(records, now()).sort());
11596
+ if (outcome === "success") delete records[solverId3];
11597
+ else
11598
+ records = {
11599
+ ...records,
11600
+ [solverId3]: {
11601
+ failures: Math.min((records[solverId3]?.failures ?? 0) + 1, 32),
11602
+ lastFailureAt: now()
11603
+ }
11604
+ };
11605
+ try {
11606
+ await storage.save(scope, records);
11607
+ if (before !== JSON.stringify(active(records, now()).sort()))
11608
+ options.onChange?.();
11609
+ } catch {
11610
+ }
11611
+ });
11612
+ pending.set(key, update);
11613
+ return update.finally(() => {
11614
+ if (pending.get(key) === update) pending.delete(key);
11615
+ });
11616
+ }
11617
+ };
11618
+ }
11619
+
11620
+ // src/client/solverRouting.ts
11621
+ var import_solver_discovery12 = require("@arkade-os/solver-discovery");
11622
+ init_offer();
11623
+ init_rfq();
11624
+ init_rfq_contract();
11625
+ init_transportErrors();
11626
+ init_errors();
11627
+ var orderedSolverCandidates = async (route, network, policy, fetchImpl, estimate = true, health) => {
11628
+ const candidates = (policy?.selectMarket ? route.market === void 0 ? [] : [route.market] : route.candidates).map((candidate) => ({
11629
+ ...candidate,
11630
+ solverId: (0, import_solver_discovery12.solverId)(candidate.card, network),
11631
+ direction: (0, import_solver_discovery12.solverDirectionKey)(candidate.card, candidate.give, network)
11632
+ }));
11633
+ if (candidates.length === 0) return [];
11634
+ const preferences = await policy?.solverRouting?.preferences?.({
11635
+ network,
11636
+ direction: candidates[0].direction,
11637
+ candidates
11638
+ });
11639
+ let cooling = [];
11640
+ try {
11641
+ cooling = await health?.deprioritized({ network, direction: candidates[0].direction }) ?? [];
11642
+ } catch {
11643
+ }
11644
+ const options = {
11645
+ network,
11646
+ preferences: {
11647
+ ...preferences,
11648
+ deprioritized: [.../* @__PURE__ */ new Set([...preferences?.deprioritized ?? [], ...cooling])]
11649
+ }
11650
+ };
11651
+ return estimate ? (0, import_solver_discovery12.rankSolverMarkets)(candidates, {
11652
+ ...options,
11653
+ amount: route.amount === void 0 ? void 0 : { on: route.amount.on, value: route.amount.value },
11654
+ carrierSats: ASSET_CARRIER_SATS,
11655
+ fetchImpl
11656
+ }) : (0, import_solver_discovery12.orderSolverMarkets)(candidates, options);
11657
+ };
11658
+ var canFailoverQuote = (error) => {
11659
+ if (error instanceof SolverUnavailable || error instanceof QuoteExpired || error instanceof QuoteVerificationFailed) {
11660
+ return true;
11661
+ }
11662
+ if (!(error instanceof SwapRefusal)) return false;
11663
+ if (error.errorCode !== void 0) {
11664
+ return error.errorCode === "amount_side_unsupported" || error.errorCode === "exact_out_unsupported" || error.errorCode === RFQ_CONTRACT_VERSION_UNSUPPORTED;
11665
+ }
11666
+ return [
11667
+ "unsupported_pair",
11668
+ "amount_out_of_range",
11669
+ "exposure_cap",
11670
+ "pricing_unavailable",
11671
+ "rate_limited"
11672
+ ].includes(error.reason);
11673
+ };
11674
+ var isSolverReliabilityFailure = (error) => error instanceof SolverUnavailable || error instanceof QuoteExpired || error instanceof QuoteVerificationFailed || error instanceof SwapRefusal && error.errorCode === void 0 && ["pricing_unavailable", "rate_limited"].includes(error.reason);
11675
+ var SolverRoutesUnavailable = class extends AggregateError {
11676
+ constructor(attempts) {
11677
+ super(
11678
+ attempts.map(({ error }) => error),
11679
+ "No available solver could quote this swap"
11680
+ );
11681
+ this.attempts = attempts;
11682
+ }
11683
+ attempts;
11684
+ name = "SolverRoutesUnavailable";
11685
+ };
11686
+ var completedSolverUsage = (swaps, network, direction) => {
11687
+ const usage = {};
11688
+ const seen = /* @__PURE__ */ new Set();
11689
+ for (const swap of swaps) {
11690
+ if (seen.has(swap.id) || !["filled", "paid", "claimed"].includes(swap.outcome) || swap.market.kind !== "card")
11691
+ continue;
11692
+ if (JSON.stringify([network, swap.route.give.asset, swap.route.take.asset]) !== direction)
11693
+ continue;
11694
+ seen.add(swap.id);
11695
+ const id = (0, import_solver_discovery12.solverId)(
11696
+ {
11697
+ solver: swap.market.solver,
11698
+ source: swap.market.source,
11699
+ sourceType: swap.market.sourceType,
11700
+ discovery_pubkey: swap.market.discoveryPubkey
11701
+ },
11702
+ network
11703
+ );
11704
+ usage[id] = (usage[id] ?? 0) + 1;
11705
+ }
11706
+ return usage;
11707
+ };
11708
+
11709
+ // src/client/openRfq.ts
11710
+ var import_solver_discovery13 = require("@arkade-os/solver-discovery");
11711
+ var DEFAULT_OPEN_RFQ_RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
11712
+ var freezeOpenRfqValue = (value) => {
11713
+ if (value !== null && typeof value === "object") {
11714
+ for (const nested of Object.values(value)) freezeOpenRfqValue(nested);
11715
+ Object.freeze(value);
11716
+ }
11717
+ return value;
11718
+ };
11719
+ var openBidCandidates = (bid, route, network, policy) => {
11720
+ const checked = (0, import_solver_discovery13.validateCard)(bid.card);
11721
+ if (!checked.ok || checked.value === void 0 || checked.value.discovery_pubkey !== bid.solverPubkey || !(0, import_solver_discovery13.verifyCardSig)(checked.value) || (0, import_solver_discovery13.cardErrors)(checked.value, network).length !== 0)
11722
+ return void 0;
11723
+ const signedCard = freezeOpenRfqValue(JSON.parse(JSON.stringify(checked.value)));
11724
+ const markets = (signedCard.markets ?? []).flatMap((market) => {
11725
+ const projected = (0, import_solver_discovery13.indexMarketFromCard)(signedCard, market);
11726
+ if (!projected.ok) return [];
11727
+ const matches = route.snapshot.ref.live ? route.snapshot.markets.filter((entry) => {
11728
+ const { source: _source, sourceType: _sourceType, ...content } = entry;
11729
+ return (0, import_solver_discovery13.stableStringify)(content) === (0, import_solver_discovery13.stableStringify)(projected.market);
11730
+ }) : [];
11731
+ const known = policy?.allowedRegistries === void 0 ? matches[0] : matches.find((entry) => policy.allowedRegistries.includes(entry.source));
11732
+ return [
11733
+ freezeOpenRfqValue({
11734
+ ...projected.market,
11735
+ source: known?.source ?? `nostr:${bid.solverPubkey}`,
11736
+ sourceType: known?.sourceType ?? "local"
11737
+ })
11738
+ ];
11739
+ });
11740
+ const candidates = eligibleMarkets(
11741
+ { markets, ref: { ...route.snapshot.ref, live: true } },
11742
+ route.legs,
11743
+ policy
11744
+ ).filter((candidate) => {
11745
+ if (candidate.backend !== "rfq") return false;
11746
+ const takeSide = candidate.give === "base" ? "quote" : "base";
11747
+ const to = (0, import_solver_discovery13.sideLimits)(candidate.card, takeSide);
11748
+ return to !== null && bid.toAmount >= to.min && bid.toAmount <= to.max;
11749
+ });
11750
+ return { signedCard, candidates };
11751
+ };
11752
+ var hasPausedKnownBidder = async (signer, name, route, network, policy) => {
11753
+ if (!route.snapshot.ref.live || policy?.solverRouting?.preferences === void 0) return false;
11754
+ const candidates = eligibleMarkets(route.snapshot, route.legs).filter(
11755
+ (candidate) => candidate.card.discovery_pubkey === signer && candidate.card.solver === name
11756
+ ).map((candidate) => ({
11757
+ ...candidate,
11758
+ solverId: (0, import_solver_discovery13.solverId)(candidate.card, network),
11759
+ direction: (0, import_solver_discovery13.solverDirectionKey)(candidate.card, candidate.give, network)
11760
+ }));
11761
+ if (candidates.length === 0) return false;
11762
+ const preferences = await policy.solverRouting.preferences({
11763
+ network,
11764
+ direction: candidates[0].direction,
11765
+ candidates
11766
+ });
11767
+ return candidates.some((candidate) => preferences.disabled?.includes(candidate.solverId));
11768
+ };
11769
+
11513
11770
  // src/client/client.ts
11514
11771
  var PREPARATIONS_HELD = 64;
11515
11772
  var mintQuoteId = () => import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
@@ -11518,6 +11775,18 @@ var createSwapClient = (config) => {
11518
11775
  const operator = config.operator ?? walletOperator(wallet);
11519
11776
  const feed = feedFetch(config.fetchImpl ?? fetch);
11520
11777
  const preparations = /* @__PURE__ */ new Map();
11778
+ const activeQuotes = /* @__PURE__ */ new Set();
11779
+ const activeAuctions = /* @__PURE__ */ new Set();
11780
+ const auctionQuotes = /* @__PURE__ */ new Map();
11781
+ const auctions = /* @__PURE__ */ new Map();
11782
+ const health = config.policy?.solverRouting === void 0 ? void 0 : config.policy.solverRouting.health ?? createSolverHealth();
11783
+ const recordHealth = (candidate, outcome, network) => {
11784
+ try {
11785
+ void health?.record({ network, direction: candidate.direction }, candidate.solverId, outcome).catch(() => {
11786
+ });
11787
+ } catch {
11788
+ }
11789
+ };
11521
11790
  const indexer = walletLockupIndexer(wallet);
11522
11791
  let disposed = false;
11523
11792
  const ensureLive = (method) => {
@@ -11568,25 +11837,409 @@ var createSwapClient = (config) => {
11568
11837
  const remember = (id, preparation) => {
11569
11838
  preparations.set(id, preparation);
11570
11839
  if (preparations.size > PREPARATIONS_HELD) {
11571
- preparations.delete(preparations.keys().next().value);
11840
+ const oldest = preparations.keys().next().value;
11841
+ preparations.delete(oldest);
11842
+ auctionQuotes.delete(oldest);
11843
+ }
11844
+ };
11845
+ const prepare = async (resolvedRoute, market, assetPayment, auction) => {
11846
+ const { corridors } = await resolved();
11847
+ corridors.get(resolvedRoute.legs.give.corridor);
11848
+ corridors.get(resolvedRoute.legs.take.corridor);
11849
+ ensureLive("quote");
11850
+ const quoteId = mintQuoteId();
11851
+ const now = Math.floor(Date.now() / 1e3);
11852
+ const marketRef = marketRefOf(market, resolvedRoute.snapshot.ref);
11853
+ const checkAuctionTtl = () => {
11854
+ if (auction !== void 0)
11855
+ verifyQuoteTtl({
11856
+ quoteId,
11857
+ expiresAt: auction.winner.expiresAt,
11858
+ now: Math.floor(Date.now() / 1e3),
11859
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
11860
+ });
11861
+ };
11862
+ if (market.backend === "feed") {
11863
+ if (assetPayment !== void 0)
11864
+ throw new Error("assetPayment needs a negotiated BTC-to-asset market");
11865
+ const { quote, preparation } = await quoteFromFeed({
11866
+ quoteId,
11867
+ candidate: market,
11868
+ market: marketRef,
11869
+ legs: resolvedRoute.legs,
11870
+ endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11871
+ ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11872
+ feed,
11873
+ ...config.policy === void 0 ? {} : { policy: config.policy },
11874
+ now
11875
+ });
11876
+ ensureLive("quote");
11877
+ const issued = auction === void 0 ? quote : { ...quote, auction };
11878
+ remember(quoteId, preparation);
11879
+ return issued;
11880
+ }
11881
+ const info = await liveOperatorInfo(wallet, { requireLive: true });
11882
+ const rendezvous = market.card.discovery_pubkey;
11883
+ if (rendezvous === void 0) {
11884
+ throw new Error(`card ${market.card.solver} names no discovery key to address`);
11885
+ }
11886
+ checkAuctionTtl();
11887
+ const transport = await (config.transportFor ?? nostrTransportFactory)({
11888
+ card: market.card,
11889
+ solverPubkey: rendezvous,
11890
+ relays: market.card.transports?.nostr?.relays ?? []
11891
+ });
11892
+ let closing;
11893
+ const close = () => closing ??= (async () => {
11894
+ activeQuotes.delete(close);
11895
+ await transport.close().catch(() => {
11896
+ });
11897
+ })();
11898
+ activeQuotes.add(close);
11899
+ try {
11900
+ ensureLive("quote");
11901
+ checkAuctionTtl();
11902
+ const { quote, preparation } = await quoteViaRfq({
11903
+ quoteId,
11904
+ route: resolvedRoute.pair,
11905
+ ...assetPayment === void 0 ? {} : { assetPayment },
11906
+ candidate: market,
11907
+ market: marketRef,
11908
+ legs: resolvedRoute.legs,
11909
+ endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11910
+ ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11911
+ wallet,
11912
+ info,
11913
+ corridors,
11914
+ transport,
11915
+ feed,
11916
+ ...config.policy === void 0 ? {} : { policy: config.policy },
11917
+ now
11918
+ });
11919
+ ensureLive("quote");
11920
+ const issued = auction === void 0 ? quote : { ...quote, auction };
11921
+ remember(quoteId, preparation);
11922
+ return issued;
11923
+ } finally {
11924
+ await close();
11572
11925
  }
11573
11926
  };
11927
+ const withSnapshot = async (input, snapshot) => {
11928
+ const { base, corridors } = await resolved();
11929
+ const fixed = { peek: async () => snapshot, load: async () => snapshot };
11930
+ return resolveRoute(input, {
11931
+ corridors,
11932
+ network: base.networkName,
11933
+ discovery: fixed,
11934
+ ...config.policy === void 0 ? {} : { policy: config.policy },
11935
+ mode: "quote"
11936
+ });
11937
+ };
11574
11938
  const client = {
11939
+ openRfq: async (input, options) => {
11940
+ ensureLive("openRfq");
11941
+ options.signal?.throwIfAborted();
11942
+ if (input.assetPayment !== void 0)
11943
+ throw new UnsupportedRoute("open RFQ does not publish asset-payment terms");
11944
+ const captured = Object.freeze({ ...input });
11945
+ const { base, corridors, discovery } = await resolved();
11946
+ let snapshot;
11947
+ try {
11948
+ snapshot = await discovery.load();
11949
+ } catch (error) {
11950
+ if (!(error instanceof DiscoverySnapshotUnavailable)) throw error;
11951
+ snapshot = {
11952
+ markets: [],
11953
+ ref: { fetchedAt: Date.now(), live: false, source: "local" }
11954
+ };
11955
+ }
11956
+ const routed = await withSnapshot(captured, snapshot);
11957
+ if (routed.pair !== "arkade->arkade" && (!isBtcAsset(routed.give.asset) || !isBtcAsset(routed.take.asset)))
11958
+ throw new UnsupportedRoute("Cross-chain swaps currently support Bitcoin only", {
11959
+ give: routed.legs.give.corridor,
11960
+ take: routed.legs.take.corridor
11961
+ });
11962
+ const canonicalInput = Object.freeze({
11963
+ ...captured,
11964
+ give: routed.give.asset,
11965
+ take: routed.take.asset
11966
+ });
11967
+ if (routed.amount === void 0) throw new Error("open RFQ needs a positive amount");
11968
+ const { quoted, claimFee = 0n } = solverFacingAmount(
11969
+ routed.pair,
11970
+ routed.amount,
11971
+ corridors
11972
+ );
11973
+ const windowMs = options.windowMs ?? config.policy?.rfq?.windowMs ?? 3e3;
11974
+ if (!Number.isSafeInteger(windowMs) || windowMs < 1 || windowMs > 3e4)
11975
+ throw new RangeError("open RFQ windowMs must be between 1 and 30000");
11976
+ const configuredRelays = options.relays ?? config.policy?.rfq?.relays;
11977
+ const discoveredRelays = [
11978
+ ...new Set(
11979
+ snapshot.markets.flatMap((market) => market.transports?.nostr?.relays ?? [])
11980
+ )
11981
+ ];
11982
+ const relays = configuredRelays ?? (discoveredRelays.length === 0 ? DEFAULT_OPEN_RFQ_RELAYS : discoveredRelays.slice(0, 16));
11983
+ const request = {
11984
+ openId: import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(32))),
11985
+ pair: `${routed.give.asset}->${routed.take.asset}`,
11986
+ amountSide: routed.amount.on === "give" ? "from" : "to",
11987
+ amount: quoted.value
11988
+ };
11989
+ const controller = new AbortController();
11990
+ const abort = () => controller.abort(options.signal?.reason);
11991
+ if (options.signal?.aborted) abort();
11992
+ else options.signal?.addEventListener("abort", abort, { once: true });
11993
+ activeAuctions.add(controller);
11994
+ const owned = /* @__PURE__ */ new Map();
11995
+ const filter = async (bids) => {
11996
+ const offers = [];
11997
+ for (const bid of bids) {
11998
+ if (controller.signal.aborted || disposed) return [];
11999
+ const now2 = Math.floor(Date.now() / 1e3);
12000
+ if (bid.openId !== request.openId || bid.pair !== request.pair || bid.amountSide !== request.amountSide || bid.validUntil <= now2 || (request.amountSide === "from" ? bid.fromAmount : bid.toAmount) !== request.amount)
12001
+ continue;
12002
+ let checked;
12003
+ try {
12004
+ checked = openBidCandidates(bid, routed, base.networkName, config.policy);
12005
+ } catch {
12006
+ continue;
12007
+ }
12008
+ if (checked === void 0 || checked.candidates[0] === void 0) continue;
12009
+ if (await hasPausedKnownBidder(
12010
+ bid.solverPubkey,
12011
+ checked.signedCard.name,
12012
+ routed,
12013
+ base.networkName,
12014
+ config.policy
12015
+ ))
12016
+ continue;
12017
+ const candidateRoute = {
12018
+ ...routed,
12019
+ candidates: checked.candidates,
12020
+ market: chooseMarket(checked.candidates, config.policy)
12021
+ };
12022
+ const eligible = await orderedSolverCandidates(
12023
+ candidateRoute,
12024
+ base.networkName,
12025
+ config.policy,
12026
+ feed.fetch,
12027
+ false,
12028
+ health
12029
+ );
12030
+ const candidate = eligible[0];
12031
+ if (candidate === void 0) continue;
12032
+ const cached = owned.get(bid.id);
12033
+ const offer = cached?.offer ?? Object.freeze({
12034
+ id: bid.id,
12035
+ solverPubkey: bid.solverPubkey,
12036
+ solverName: checked.signedCard.name,
12037
+ market: candidate.card,
12038
+ signedCard: checked.signedCard,
12039
+ fromAmount: bid.fromAmount,
12040
+ toAmount: bid.toAmount - claimFee,
12041
+ expiresAt: bid.validUntil
12042
+ });
12043
+ if (cached === void 0) owned.set(bid.id, { offer, candidate });
12044
+ offers.push(offer);
12045
+ }
12046
+ const now = Math.floor(Date.now() / 1e3);
12047
+ return Object.freeze(offers.filter((offer) => offer.expiresAt > now));
12048
+ };
12049
+ let updates = Promise.resolve();
12050
+ let progressRevision = 0;
12051
+ try {
12052
+ ensureLive("openRfq");
12053
+ const { collectOpenRfqBids: collectOpenRfqBids2 } = await Promise.resolve().then(() => (init_openRfqTransport(), openRfqTransport_exports));
12054
+ ensureLive("openRfq");
12055
+ const bids = await collectOpenRfqBids2(
12056
+ { ...request, bidsUntil: Math.ceil((Date.now() + windowMs) / 1e3) },
12057
+ {
12058
+ secretKey: options.secretKey,
12059
+ relays: [...relays],
12060
+ windowMs,
12061
+ signal: controller.signal,
12062
+ onBids: options.onBids === void 0 ? void 0 : (bids2) => {
12063
+ const revision = ++progressRevision;
12064
+ updates = updates.then(async () => {
12065
+ if (revision !== progressRevision) return;
12066
+ const offers2 = await filter(bids2);
12067
+ if (revision === progressRevision && !controller.signal.aborted && !disposed) {
12068
+ try {
12069
+ options.onBids?.(offers2);
12070
+ } catch {
12071
+ }
12072
+ }
12073
+ });
12074
+ void updates.catch(() => {
12075
+ });
12076
+ }
12077
+ }
12078
+ );
12079
+ await updates;
12080
+ ensureLive("openRfq");
12081
+ if (controller.signal.aborted) throw controller.signal.reason;
12082
+ const offers = await filter(bids);
12083
+ ensureLive("openRfq");
12084
+ if (controller.signal.aborted) throw controller.signal.reason;
12085
+ const auction = Object.freeze({
12086
+ id: request.openId,
12087
+ input: canonicalInput,
12088
+ pair: request.pair,
12089
+ bids: offers,
12090
+ closedAt: Math.floor(Date.now() / 1e3)
12091
+ });
12092
+ for (const session of auctions.keys()) {
12093
+ if (session.bids.every((bid) => bid.expiresAt <= auction.closedAt))
12094
+ auctions.delete(session);
12095
+ }
12096
+ auctions.set(auction, {
12097
+ input: canonicalInput,
12098
+ route: routed,
12099
+ offers: new Map(offers.map((offer) => [offer, owned.get(offer.id).candidate]))
12100
+ });
12101
+ if (auctions.size > 16) auctions.delete(auctions.keys().next().value);
12102
+ return auction;
12103
+ } finally {
12104
+ activeAuctions.delete(controller);
12105
+ options.signal?.removeEventListener("abort", abort);
12106
+ }
12107
+ },
12108
+ quoteBid: async (auction, bid) => {
12109
+ ensureLive("quoteBid");
12110
+ const session = auctions.get(auction);
12111
+ const selected = session?.offers.get(bid);
12112
+ if (session === void 0 || selected === void 0)
12113
+ throw new Error("bid was not issued by this client's auction");
12114
+ const checkExpiry = () => {
12115
+ verifyQuoteTtl({
12116
+ quoteId: bid.id,
12117
+ expiresAt: bid.expiresAt,
12118
+ now: Math.floor(Date.now() / 1e3),
12119
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
12120
+ });
12121
+ };
12122
+ checkExpiry();
12123
+ const snapshot = {
12124
+ markets: [selected.card],
12125
+ ref: { fetchedAt: Date.now(), live: true, source: "injected" }
12126
+ };
12127
+ const routed = await withSnapshot(session.input, snapshot);
12128
+ const { base } = await resolved();
12129
+ if (await hasPausedKnownBidder(
12130
+ bid.solverPubkey,
12131
+ bid.solverName,
12132
+ session.route,
12133
+ base.networkName,
12134
+ config.policy
12135
+ ))
12136
+ throw new UnsupportedRoute("selected bidder is paused");
12137
+ const eligible = await orderedSolverCandidates(
12138
+ routed,
12139
+ base.networkName,
12140
+ config.policy,
12141
+ feed.fetch,
12142
+ false,
12143
+ health
12144
+ );
12145
+ const candidate = eligible[0];
12146
+ if (candidate === void 0 || candidate.card.discovery_pubkey !== bid.solverPubkey)
12147
+ throw new UnsupportedRoute("selected bidder is no longer enabled");
12148
+ const ranked = (offer) => ({
12149
+ bidder: offer.solverPubkey,
12150
+ amount: routed.amount?.on === "give" ? offer.toAmount : offer.fromAmount,
12151
+ amountOn: routed.amount?.on === "give" ? "take" : "give",
12152
+ expiresAt: offer.expiresAt
12153
+ });
12154
+ checkExpiry();
12155
+ let quote;
12156
+ try {
12157
+ quote = await prepare(routed, candidate, void 0, {
12158
+ marketKey: auction.pair,
12159
+ winner: ranked(bid),
12160
+ losers: auction.bids.filter((other) => other !== bid).map(ranked),
12161
+ closedAt: auction.closedAt
12162
+ });
12163
+ ensureLive("quoteBid");
12164
+ checkExpiry();
12165
+ if (quote.give.amount > bid.fromAmount || quote.take.amount < bid.toAmount)
12166
+ throw new QuoteVerificationFailed(
12167
+ "amount",
12168
+ `${bid.fromAmount}/${bid.toAmount}`,
12169
+ `${quote.give.amount}/${quote.take.amount}`
12170
+ );
12171
+ const expiresAt = Math.min(quote.expiresAt, bid.expiresAt);
12172
+ verifyQuoteTtl({
12173
+ quoteId: quote.id,
12174
+ expiresAt,
12175
+ now: Math.floor(Date.now() / 1e3),
12176
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
12177
+ });
12178
+ const bound = freezeOpenRfqValue({
12179
+ ...quote,
12180
+ expiresAt
12181
+ });
12182
+ auctionQuotes.set(bound.id, bound);
12183
+ recordHealth(candidate, "success", base.networkName);
12184
+ return bound;
12185
+ } catch (error) {
12186
+ if (quote !== void 0) preparations.delete(quote.id);
12187
+ if (isSolverReliabilityFailure(error) && bid.expiresAt - Math.floor(Date.now() / 1e3) > (config.policy?.quoteTtlFloorSeconds ?? 0))
12188
+ recordHealth(candidate, "failure", base.networkName);
12189
+ throw error;
12190
+ }
12191
+ },
11575
12192
  resolve: async (input) => {
11576
12193
  ensureLive("resolve");
11577
- return (await route(input, "resolve")).resolution;
12194
+ const routed = await route(input, "resolve");
12195
+ if (config.policy?.solverRouting === void 0) return routed.resolution;
12196
+ const { base } = await resolved();
12197
+ const candidates = await orderedSolverCandidates(
12198
+ routed,
12199
+ base.networkName,
12200
+ config.policy,
12201
+ feed.fetch,
12202
+ false,
12203
+ health
12204
+ );
12205
+ const { market: _market, ...resolution } = routed.resolution;
12206
+ return {
12207
+ ...resolution,
12208
+ eligible: candidates.length,
12209
+ ...candidates[0] === void 0 ? {} : { market: marketRefOf(candidates[0], routed.snapshot.ref) }
12210
+ };
12211
+ },
12212
+ candidates: async (input) => {
12213
+ ensureLive("candidates");
12214
+ const routed = await route(input, "quote");
12215
+ const { base } = await resolved();
12216
+ return orderedSolverCandidates(
12217
+ routed,
12218
+ base.networkName,
12219
+ config.policy,
12220
+ feed.fetch,
12221
+ true,
12222
+ health
12223
+ );
11578
12224
  },
11579
12225
  quote: async (input) => {
11580
12226
  const assetPayment = captureAssetPayment(input.assetPayment);
11581
12227
  ensureLive("quote");
11582
- const { corridors, discovery } = await resolved();
12228
+ const { base, corridors, discovery } = await resolved();
11583
12229
  let resolvedRoute = await route(input, "quote");
11584
- if (resolvedRoute.market?.backend === "rfq" && !resolvedRoute.snapshot.ref.live) {
12230
+ if ((config.policy?.solverRouting === void 0 ? resolvedRoute.market?.backend === "rfq" : resolvedRoute.candidates.some((candidate) => candidate.backend === "rfq")) && !resolvedRoute.snapshot.ref.live) {
11585
12231
  await discovery.load({ refresh: true });
11586
12232
  resolvedRoute = await route(input, "quote");
11587
12233
  }
11588
- const { market } = resolvedRoute;
11589
- if (market === void 0) {
12234
+ const candidates = await orderedSolverCandidates(
12235
+ resolvedRoute,
12236
+ base.networkName,
12237
+ config.policy,
12238
+ feed.fetch,
12239
+ true,
12240
+ health
12241
+ );
12242
+ if (candidates.length === 0) {
11590
12243
  throw new UnsupportedRoute(
11591
12244
  `no market serves ${resolvedRoute.legs.give.corridor}:${resolvedRoute.legs.give.assetId} -> ${resolvedRoute.legs.take.corridor}:${resolvedRoute.legs.take.assetId} on the active discovery snapshot`,
11592
12245
  {
@@ -11595,68 +12248,35 @@ var createSwapClient = (config) => {
11595
12248
  }
11596
12249
  );
11597
12250
  }
11598
- const marketRef = resolvedRoute.resolution.market;
11599
- if (marketRef === void 0 || marketRef.kind !== "card") {
11600
- throw new Error("a resolved market must carry its card's provenance");
11601
- }
11602
12251
  corridors.get(resolvedRoute.legs.give.corridor);
11603
12252
  corridors.get(resolvedRoute.legs.take.corridor);
11604
- const quoteId = mintQuoteId();
11605
- const now = Math.floor(Date.now() / 1e3);
11606
- if (market.backend === "feed") {
11607
- if (assetPayment !== void 0)
11608
- throw new Error("assetPayment needs a negotiated BTC-to-asset market");
11609
- const { quote, preparation } = await quoteFromFeed({
11610
- quoteId,
11611
- candidate: market,
11612
- market: marketRef,
11613
- legs: resolvedRoute.legs,
11614
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11615
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11616
- feed,
11617
- ...config.policy === void 0 ? {} : { policy: config.policy },
11618
- now
11619
- });
11620
- remember(quoteId, preparation);
11621
- return quote;
11622
- }
11623
- const info = await liveOperatorInfo(wallet, { requireLive: true });
11624
- const rendezvous = market.card.discovery_pubkey;
11625
- if (rendezvous === void 0) {
11626
- throw new Error(`card ${market.card.solver} names no discovery key to address`);
11627
- }
11628
- const transport = await (config.transportFor ?? nostrTransportFactory)({
11629
- card: market.card,
11630
- solverPubkey: rendezvous,
11631
- relays: market.card.transports?.nostr?.relays ?? []
11632
- });
11633
- try {
11634
- const { quote, preparation } = await quoteViaRfq({
11635
- quoteId,
11636
- route: resolvedRoute.pair,
11637
- ...assetPayment === void 0 ? {} : { assetPayment },
11638
- candidate: market,
11639
- market: marketRef,
11640
- legs: resolvedRoute.legs,
11641
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11642
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11643
- wallet,
11644
- info,
11645
- corridors,
11646
- transport,
11647
- feed,
11648
- ...config.policy === void 0 ? {} : { policy: config.policy },
11649
- now
11650
- });
11651
- remember(quoteId, preparation);
11652
- return quote;
11653
- } finally {
11654
- await transport.close().catch(() => {
11655
- });
12253
+ const failover = config.policy?.solverRouting !== void 0 && config.policy.solverRouting.failover !== false && config.policy.selectMarket === void 0;
12254
+ const attempts = [];
12255
+ const attempted = /* @__PURE__ */ new Set();
12256
+ for (const candidate of failover ? candidates : candidates.slice(0, 1)) {
12257
+ if (attempted.has(candidate.solverId)) continue;
12258
+ attempted.add(candidate.solverId);
12259
+ try {
12260
+ const quote = await prepare(resolvedRoute, candidate, assetPayment);
12261
+ recordHealth(candidate, "success", base.networkName);
12262
+ return quote;
12263
+ } catch (error) {
12264
+ ensureLive("quote");
12265
+ if (isSolverReliabilityFailure(error))
12266
+ recordHealth(candidate, "failure", base.networkName);
12267
+ if (!failover || !canFailoverQuote(error)) throw error;
12268
+ attempts.push({ solverId: candidate.solverId, error });
12269
+ }
11656
12270
  }
12271
+ if (attempts.length === 1) throw attempts[0].error;
12272
+ throw new SolverRoutesUnavailable(attempts);
11657
12273
  },
11658
12274
  accept: async (quote, options) => {
11659
- const validUntil = (0, import_sdk38.captureSendDeadline)(options?.validUntil);
12275
+ const issued = auctionQuotes.get(quote.id);
12276
+ if (issued !== void 0 && issued !== quote)
12277
+ throw new Error("auction quote must be the original issued quote");
12278
+ const requestedDeadline = (0, import_sdk38.captureSendDeadline)(options?.validUntil);
12279
+ const validUntil = issued === void 0 ? requestedDeadline : Math.min(issued.expiresAt, requestedDeadline ?? issued.expiresAt);
11660
12280
  ensureLive("accept");
11661
12281
  const { corridors } = await resolved();
11662
12282
  const drive2 = driving();
@@ -11747,6 +12367,11 @@ var createSwapClient = (config) => {
11747
12367
  [Symbol.asyncDispose]: async () => {
11748
12368
  if (disposed) return;
11749
12369
  disposed = true;
12370
+ for (const controller of activeAuctions)
12371
+ controller.abort(new ClientDisposed("openRfq"));
12372
+ auctions.clear();
12373
+ auctionQuotes.clear();
12374
+ await Promise.allSettled([...activeQuotes].map((close) => close()));
11750
12375
  await drive?.dispose();
11751
12376
  },
11752
12377
  onUpdate: (fn) => {
@@ -11769,6 +12394,7 @@ var createSwapClient = (config) => {
11769
12394
 
11770
12395
  // src/index.ts
11771
12396
  init_policy();
12397
+ init_transportErrors();
11772
12398
  init_errors();
11773
12399
  init_rfq();
11774
12400
  init_repository();
@@ -12214,6 +12840,9 @@ function verifyOfferFillPlan(plan) {
12214
12840
  SEALED_CIPHERTEXT_LENGTH,
12215
12841
  SWAP_ERROR_NAMES,
12216
12842
  SWAP_ROUTER_PRIORITY,
12843
+ SolverResponseInvalid,
12844
+ SolverRoutesUnavailable,
12845
+ SolverUnavailable,
12217
12846
  SwapDriveRefusedError,
12218
12847
  SwapPaymentFailedError,
12219
12848
  SwapRefusal,
@@ -12229,6 +12858,8 @@ function verifyOfferFillPlan(plan) {
12229
12858
  canonicalAssetId,
12230
12859
  claimFeeSats,
12231
12860
  claimPacketShape,
12861
+ completedSolverUsage,
12862
+ createSolverHealth,
12232
12863
  createSwapClient,
12233
12864
  createSwapPaymentRouter,
12234
12865
  deepFreeze,