@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/advanced.cjs CHANGED
@@ -35,135 +35,11 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
35
35
  ));
36
36
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
37
37
 
38
- // src/contracts/asset-swap.json
39
- var asset_swap_default;
40
- var init_asset_swap = __esm({
41
- "src/contracts/asset-swap.json"() {
42
- asset_swap_default = {
43
- formatVersion: 1,
44
- contractName: "AssetSwap",
45
- constructorInputs: [
46
- {
47
- name: "receiver",
48
- type: "pubkey"
49
- },
50
- {
51
- name: "amount",
52
- type: "int"
53
- },
54
- {
55
- name: "assetTxid",
56
- type: "bytes32"
57
- },
58
- {
59
- name: "assetGroupIndex",
60
- type: "int"
61
- },
62
- {
63
- name: "user",
64
- type: "pubkey"
65
- }
66
- ],
67
- functions: [
68
- {
69
- name: "fulfill",
70
- arkade: {
71
- inputs: [],
72
- asm: [
73
- "OP_PUSHCURRENTINPUTINDEX",
74
- "OP_DUP",
75
- "<assetTxid>",
76
- "<assetGroupIndex>",
77
- "OP_INSPECTOUTASSETLOOKUP",
78
- "OP_VERIFY",
79
- "<amount>",
80
- "OP_GREATERTHANOREQUAL",
81
- "OP_VERIFY",
82
- "OP_INSPECTOUTPUTSCRIPTPUBKEY",
83
- "1",
84
- "OP_NUMEQUALVERIFY",
85
- "<receiver>",
86
- "OP_EQUAL"
87
- ]
88
- },
89
- leaves: [
90
- {
91
- name: "fulfill",
92
- witness: [
93
- {
94
- name: "serverSig",
95
- type: "signature",
96
- encoding: "schnorr-64",
97
- injected: true
98
- },
99
- {
100
- name: "emulatorSig",
101
- type: "signature",
102
- encoding: "schnorr-64",
103
- injected: true
104
- }
105
- ],
106
- asm: [
107
- "<SERVER_KEY>",
108
- "OP_CHECKSIGVERIFY",
109
- "<EMULATOR_KEY:fulfill>",
110
- "OP_CHECKSIG"
111
- ]
112
- }
113
- ]
114
- },
115
- {
116
- name: "cancel",
117
- leaves: [
118
- {
119
- name: "cancel",
120
- witness: [
121
- {
122
- name: "userSig",
123
- type: "signature",
124
- encoding: "schnorr-64"
125
- },
126
- {
127
- name: "serverSig",
128
- type: "signature",
129
- encoding: "schnorr-64",
130
- injected: true
131
- }
132
- ],
133
- asm: [
134
- "<user>",
135
- "OP_CHECKSIGVERIFY",
136
- "<SERVER_KEY>",
137
- "OP_CHECKSIG"
138
- ]
139
- }
140
- ]
141
- }
142
- ],
143
- source: {
144
- entry: "asset-swap.ark",
145
- files: {
146
- "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"
147
- }
148
- },
149
- compiler: {
150
- name: "arkadec",
151
- version: "0.1.0-rc.1",
152
- options: {
153
- optimize: true
154
- }
155
- },
156
- updatedAt: "2026-11-02T17:43:42.615113722+00:00",
157
- fingerprint: "sha256:e2b80add6237f6c7e2c69a96ae46d55abe6de5f71c3718106f4d5b22ac9e6d0a"
158
- };
159
- }
160
- });
161
-
162
- // src/contracts/asset-swap-v4.json
163
- var asset_swap_v4_default;
164
- var init_asset_swap_v4 = __esm({
165
- "src/contracts/asset-swap-v4.json"() {
166
- asset_swap_v4_default = {
38
+ // src/contracts/asset-swap-directed.json
39
+ var asset_swap_directed_default;
40
+ var init_asset_swap_directed = __esm({
41
+ "src/contracts/asset-swap-directed.json"() {
42
+ asset_swap_directed_default = {
167
43
  formatVersion: 1,
168
44
  contractName: "AssetSwap",
169
45
  constructorInputs: [
@@ -276,9 +152,9 @@ var init_asset_swap_v4 = __esm({
276
152
  }
277
153
  ],
278
154
  source: {
279
- entry: "asset-swap-v4.ark",
155
+ entry: "asset-swap-directed.ark",
280
156
  files: {
281
- "asset-swap-v4.ark": "pragma arkade ^0.1.0;\n\n// The output at this input's index pays `receiver` at least `amount` of the asset,\n// and only `taker` can make that spend.\ncontract AssetSwap(\n pubkey receiver,\n int amount,\n bytes32 assetTxid,\n int assetGroupIndex,\n pubkey user,\n pubkey taker\n) {\n function fulfill() {\n int i = this.activeInputIndex;\n require(tx.outputs[i].assets.lookup(assetTxid, assetGroupIndex) >= amount);\n let paid = tx.outputs[i].script;\n require(paid.version == 1);\n require(paid.program == receiver);\n }\n\n // Replaces the synthesized collaborative leaf: the quoting solver is a third\n // conjunct, so an observer who reads the deposit cannot complete it.\n function fulfill(signature takerSig, signature serverSig, signature emulatorSig) tapscript {\n require(checkMultisig([taker, server, emulator], [takerSig, serverSig, emulatorSig], 3));\n }\n\n function cancel(signature userSig, signature serverSig) tapscript {\n require(checkMultisig([user, server], [userSig, serverSig], 2));\n }\n}\n"
157
+ "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"
282
158
  }
283
159
  },
284
160
  compiler: {
@@ -294,124 +170,11 @@ var init_asset_swap_v4 = __esm({
294
170
  }
295
171
  });
296
172
 
297
- // src/contracts/sats-swap.json
298
- var sats_swap_default;
299
- var init_sats_swap = __esm({
300
- "src/contracts/sats-swap.json"() {
301
- sats_swap_default = {
302
- formatVersion: 1,
303
- contractName: "SatsSwap",
304
- constructorInputs: [
305
- {
306
- name: "receiver",
307
- type: "pubkey"
308
- },
309
- {
310
- name: "amount",
311
- type: "int"
312
- },
313
- {
314
- name: "user",
315
- type: "pubkey"
316
- }
317
- ],
318
- functions: [
319
- {
320
- name: "fulfill",
321
- arkade: {
322
- inputs: [],
323
- asm: [
324
- "OP_PUSHCURRENTINPUTINDEX",
325
- "OP_DUP",
326
- "OP_INSPECTOUTPUTVALUE",
327
- "<amount>",
328
- "OP_GREATERTHANOREQUAL",
329
- "OP_VERIFY",
330
- "OP_INSPECTOUTPUTSCRIPTPUBKEY",
331
- "1",
332
- "OP_NUMEQUALVERIFY",
333
- "<receiver>",
334
- "OP_EQUAL"
335
- ]
336
- },
337
- leaves: [
338
- {
339
- name: "fulfill",
340
- witness: [
341
- {
342
- name: "serverSig",
343
- type: "signature",
344
- encoding: "schnorr-64",
345
- injected: true
346
- },
347
- {
348
- name: "emulatorSig",
349
- type: "signature",
350
- encoding: "schnorr-64",
351
- injected: true
352
- }
353
- ],
354
- asm: [
355
- "<SERVER_KEY>",
356
- "OP_CHECKSIGVERIFY",
357
- "<EMULATOR_KEY:fulfill>",
358
- "OP_CHECKSIG"
359
- ]
360
- }
361
- ]
362
- },
363
- {
364
- name: "cancel",
365
- leaves: [
366
- {
367
- name: "cancel",
368
- witness: [
369
- {
370
- name: "userSig",
371
- type: "signature",
372
- encoding: "schnorr-64"
373
- },
374
- {
375
- name: "serverSig",
376
- type: "signature",
377
- encoding: "schnorr-64",
378
- injected: true
379
- }
380
- ],
381
- asm: [
382
- "<user>",
383
- "OP_CHECKSIGVERIFY",
384
- "<SERVER_KEY>",
385
- "OP_CHECKSIG"
386
- ]
387
- }
388
- ]
389
- }
390
- ],
391
- source: {
392
- entry: "sats-swap.ark",
393
- files: {
394
- "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"
395
- }
396
- },
397
- compiler: {
398
- name: "arkadec",
399
- version: "0.1.0-rc.1",
400
- options: {
401
- optimize: true
402
- }
403
- },
404
- updatedAt: "2026-11-02T17:43:42.616824535+00:00",
405
- fingerprint: "sha256:d7a60ab2178ede40a2e4867816689ea022641531cc662b562bebd7caa1ef96c4"
406
- };
407
- }
408
- });
409
-
410
- // src/contracts/sats-swap-v4.json
411
- var sats_swap_v4_default;
412
- var init_sats_swap_v4 = __esm({
413
- "src/contracts/sats-swap-v4.json"() {
414
- sats_swap_v4_default = {
173
+ // src/contracts/sats-swap-directed.json
174
+ var sats_swap_directed_default;
175
+ var init_sats_swap_directed = __esm({
176
+ "src/contracts/sats-swap-directed.json"() {
177
+ sats_swap_directed_default = {
415
178
  formatVersion: 1,
416
179
  contractName: "SatsSwap",
417
180
  constructorInputs: [
@@ -513,9 +276,9 @@ var init_sats_swap_v4 = __esm({
513
276
  }
514
277
  ],
515
278
  source: {
516
- entry: "sats-swap-v4.ark",
279
+ entry: "sats-swap-directed.ark",
517
280
  files: {
518
- "sats-swap-v4.ark": "pragma arkade ^0.1.0;\n\n// The output at this input's index pays `receiver` at least `amount` sats,\n// and only `taker` can make that spend.\ncontract SatsSwap(\n pubkey receiver,\n int amount,\n pubkey user,\n pubkey taker\n) {\n function fulfill() {\n int i = this.activeInputIndex;\n require(tx.outputs[i].value >= amount);\n let paid = tx.outputs[i].script;\n require(paid.version == 1);\n require(paid.program == receiver);\n }\n\n function fulfill(signature takerSig, signature serverSig, signature emulatorSig) tapscript {\n require(checkMultisig([taker, server, emulator], [takerSig, serverSig, emulatorSig], 3));\n }\n\n function cancel(signature userSig, signature serverSig) tapscript {\n require(checkMultisig([user, server], [userSig, serverSig], 2));\n }\n}\n"
281
+ "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"
519
282
  }
520
283
  },
521
284
  compiler: {
@@ -617,7 +380,7 @@ var init_swap_want_btc_program_v1 = __esm({
617
380
  });
618
381
 
619
382
  // src/rfq-contract.ts
620
- var RFQ_CONTRACT_VERSIONS_KEY, RFQ_CONTRACT_VERSION_KEY, RFQ_CONTRACT_VERSION_UNSUPPORTED, ASSET_SWAP_V2, ASSET_SWAP_V3, ASSET_SWAP_V4, ASSET_SWAP_BASELINE;
383
+ var RFQ_CONTRACT_VERSIONS_KEY, RFQ_CONTRACT_VERSION_KEY, RFQ_CONTRACT_VERSION_UNSUPPORTED, ASSET_SWAP_V2, ASSET_SWAP_DIRECTED, ASSET_SWAP_BASELINE;
621
384
  var init_rfq_contract = __esm({
622
385
  "src/rfq-contract.ts"() {
623
386
  "use strict";
@@ -625,60 +388,41 @@ var init_rfq_contract = __esm({
625
388
  RFQ_CONTRACT_VERSION_KEY = "contract_version";
626
389
  RFQ_CONTRACT_VERSION_UNSUPPORTED = "contract_version_unsupported";
627
390
  ASSET_SWAP_V2 = "asset-swap-v2";
628
- ASSET_SWAP_V3 = "asset-swap-v3";
629
- ASSET_SWAP_V4 = "asset-swap-v4";
391
+ ASSET_SWAP_DIRECTED = "asset-swap-directed";
630
392
  ASSET_SWAP_BASELINE = ASSET_SWAP_V2;
631
393
  }
632
394
  });
633
395
 
634
396
  // src/program.ts
635
- var import_sdk, swapPrograms, legacySwapPrograms, directedSwapPrograms, sharedArgs, refuseTaker, v3Args, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
397
+ var import_sdk, swapPrograms, directedSwapPrograms, sharedArgs, ASSET_SWAP_CONTRACTS, ASSET_SWAP_CONTRACT_VERSIONS, assetSwapContractVersion;
636
398
  var init_program = __esm({
637
399
  "src/program.ts"() {
638
400
  "use strict";
639
401
  import_sdk = require("@arkade-os/sdk");
640
- init_asset_swap();
641
- init_asset_swap_v4();
642
- init_sats_swap();
643
- init_sats_swap_v4();
402
+ init_asset_swap_directed();
403
+ init_sats_swap_directed();
644
404
  init_swap_want_asset_program_v1();
645
405
  init_swap_want_btc_program_v1();
646
406
  init_rfq_contract();
647
407
  init_rfq_contract();
648
408
  swapPrograms = {
649
- wantAsset: import_sdk.arkade.programFromArtifact(asset_swap_default),
650
- wantBtc: import_sdk.arkade.programFromArtifact(sats_swap_default)
651
- };
652
- legacySwapPrograms = {
653
409
  wantAsset: import_sdk.arkade.parseArtifact(swap_want_asset_program_v1_default),
654
410
  wantBtc: import_sdk.arkade.parseArtifact(swap_want_btc_program_v1_default)
655
411
  };
656
412
  directedSwapPrograms = {
657
- wantAsset: import_sdk.arkade.programFromArtifact(asset_swap_v4_default),
658
- wantBtc: import_sdk.arkade.programFromArtifact(sats_swap_v4_default)
413
+ wantAsset: import_sdk.arkade.programFromArtifact(asset_swap_directed_default),
414
+ wantBtc: import_sdk.arkade.programFromArtifact(sats_swap_directed_default)
659
415
  };
660
416
  sharedArgs = ({ user, server, exitDelay }) => ({
661
417
  user,
662
418
  server,
663
419
  ...exitDelay && { exitDelay }
664
420
  });
665
- refuseTaker = (version, { taker }) => {
666
- if (taker !== void 0) throw new Error(`${version} binds no taker key`);
667
- };
668
- v3Args = (inputs) => ({
669
- receiver: inputs.receiver,
670
- amount: inputs.amount,
671
- ...inputs.asset && {
672
- assetTxid: inputs.asset.txid,
673
- assetGroupIndex: inputs.asset.groupIndex
674
- },
675
- ...sharedArgs(inputs)
676
- });
677
421
  ASSET_SWAP_CONTRACTS = {
678
422
  [ASSET_SWAP_V2]: {
679
- programs: legacySwapPrograms,
423
+ programs: swapPrograms,
680
424
  args: (inputs) => {
681
- refuseTaker(ASSET_SWAP_V2, inputs);
425
+ if (inputs.taker !== void 0) throw new Error(`${ASSET_SWAP_V2} binds no taker key`);
682
426
  return {
683
427
  makerWP: inputs.receiver,
684
428
  wantAmount: inputs.amount,
@@ -690,22 +434,25 @@ var init_program = __esm({
690
434
  };
691
435
  }
692
436
  },
693
- [ASSET_SWAP_V3]: {
694
- programs: swapPrograms,
695
- args: (inputs) => {
696
- refuseTaker(ASSET_SWAP_V3, inputs);
697
- return v3Args(inputs);
698
- }
699
- },
700
- [ASSET_SWAP_V4]: {
437
+ [ASSET_SWAP_DIRECTED]: {
701
438
  programs: directedSwapPrograms,
702
439
  args: (inputs) => {
703
- if (inputs.taker === void 0) throw new Error(`${ASSET_SWAP_V4} needs a taker key`);
704
- return { ...v3Args(inputs), taker: inputs.taker };
440
+ if (inputs.taker === void 0)
441
+ throw new Error(`${ASSET_SWAP_DIRECTED} needs a taker key`);
442
+ return {
443
+ receiver: inputs.receiver,
444
+ amount: inputs.amount,
445
+ ...inputs.asset && {
446
+ assetTxid: inputs.asset.txid,
447
+ assetGroupIndex: inputs.asset.groupIndex
448
+ },
449
+ ...sharedArgs(inputs),
450
+ taker: inputs.taker
451
+ };
705
452
  }
706
453
  }
707
454
  };
708
- ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_V4];
455
+ ASSET_SWAP_CONTRACT_VERSIONS = [ASSET_SWAP_DIRECTED];
709
456
  assetSwapContractVersion = (id) => {
710
457
  if (id === void 0) return ASSET_SWAP_BASELINE;
711
458
  if (Object.hasOwn(ASSET_SWAP_CONTRACTS, id)) return id;
@@ -1083,19 +830,16 @@ function swapProgramBinding(offer, operatorPubkey, contractVersion) {
1083
830
  throw new Error("makerPkScript is not a 34-byte taproot scriptPubKey");
1084
831
  }
1085
832
  const directed = offer.taker !== void 0;
1086
- const version = contractVersion ?? (directed ? ASSET_SWAP_V4 : ASSET_SWAP_BASELINE);
833
+ const version = contractVersion ?? (directed ? ASSET_SWAP_DIRECTED : ASSET_SWAP_BASELINE);
1087
834
  const expected = offer.swapPkScript;
1088
835
  if (!expected?.length) return bindSwapProgram(offer, operatorPubkey, version);
1089
- const funded = import_base2.hex.encode(expected);
1090
- const order = directed ? [ASSET_SWAP_V4] : [ASSET_SWAP_BASELINE, ASSET_SWAP_V3];
1091
- for (const candidate of order) {
1092
- const binding = bindSwapProgram(offer, operatorPubkey, candidate);
1093
- if (pkOf(binding) === funded) return binding;
1094
- }
1095
- return bindSwapProgram(offer, operatorPubkey, directed ? ASSET_SWAP_V4 : version);
836
+ const candidate = directed ? ASSET_SWAP_DIRECTED : ASSET_SWAP_BASELINE;
837
+ const binding = bindSwapProgram(offer, operatorPubkey, candidate);
838
+ if (pkOf(binding) === import_base2.hex.encode(expected)) return binding;
839
+ return bindSwapProgram(offer, operatorPubkey, directed ? ASSET_SWAP_DIRECTED : version);
1096
840
  }
1097
841
  function bindSwapProgram(offer, operatorPubkey, contractVersion) {
1098
- const { programs, args } = ASSET_SWAP_CONTRACTS[contractVersion];
842
+ const { programs, args } = ASSET_SWAP_CONTRACTS[assetSwapContractVersion(contractVersion)];
1099
843
  const user = offer.makerPublicKey;
1100
844
  const assetId = offer.wantAsset;
1101
845
  return {
@@ -2291,6 +2035,26 @@ var init_onchainHtlc = __esm({
2291
2035
  }
2292
2036
  });
2293
2037
 
2038
+ // src/transportErrors.ts
2039
+ var SolverUnavailable, SolverResponseInvalid;
2040
+ var init_transportErrors = __esm({
2041
+ "src/transportErrors.ts"() {
2042
+ "use strict";
2043
+ SolverUnavailable = class extends Error {
2044
+ constructor(message, options) {
2045
+ super(message, options);
2046
+ this.name = "SolverUnavailable";
2047
+ }
2048
+ };
2049
+ SolverResponseInvalid = class extends SolverUnavailable {
2050
+ constructor(message, options) {
2051
+ super(message, options);
2052
+ this.name = "SolverResponseInvalid";
2053
+ }
2054
+ };
2055
+ }
2056
+ });
2057
+
2294
2058
  // src/claimAmountGate.ts
2295
2059
  var bindsClaimAmount;
2296
2060
  var init_claimAmountGate = __esm({
@@ -2546,6 +2310,7 @@ var init_rfq = __esm({
2546
2310
  "src/rfq.ts"() {
2547
2311
  "use strict";
2548
2312
  import_base7 = require("@scure/base");
2313
+ init_transportErrors();
2549
2314
  import_solver_discovery = require("@arkade-os/solver-discovery");
2550
2315
  import_legacy2 = require("@noble/hashes/legacy.js");
2551
2316
  import_sdk8 = require("@arkade-os/sdk");
@@ -2889,10 +2654,10 @@ var init_rfq = __esm({
2889
2654
  });
2890
2655
  }
2891
2656
  if (p?.type !== "rfq_quote" || p.rfq_id !== rfqId) {
2892
- throw new Error(`unexpected reply: ${p?.type ?? "no payload"}`);
2657
+ throw new SolverResponseInvalid(`unexpected reply: ${p?.type ?? "no payload"}`);
2893
2658
  }
2894
2659
  if (requestedPair !== void 0 && p.pair !== requestedPair) {
2895
- throw new Error(
2660
+ throw new SolverResponseInvalid(
2896
2661
  `solver quoted ${JSON.stringify(p.pair)}, not the requested ${requestedPair}`
2897
2662
  );
2898
2663
  }
@@ -2916,11 +2681,13 @@ var init_rfq = __esm({
2916
2681
  }
2917
2682
  const selected = quote[RFQ_CONTRACT_VERSION_KEY];
2918
2683
  if (sent !== request && selected !== void 0) {
2919
- throw new Error(`solver chose contract version ${selected}, but none was advertised`);
2684
+ throw new SolverResponseInvalid(
2685
+ `solver chose contract version ${selected}, but none was advertised`
2686
+ );
2920
2687
  }
2921
2688
  const version = selected ?? ASSET_SWAP_BASELINE;
2922
2689
  if (!advertised.includes(version)) {
2923
- throw new Error(
2690
+ throw new SolverResponseInvalid(
2924
2691
  selected === void 0 ? `solver negotiated no contract version; advertised ${advertised.join(", ")}` : `solver chose contract version ${version}, not one of ${advertised.join(", ")}`
2925
2692
  );
2926
2693
  }
@@ -3423,33 +3190,250 @@ var init_nostrPool = __esm({
3423
3190
  }
3424
3191
  });
3425
3192
 
3193
+ // src/openRfq.ts
3194
+ var RFQ_BROADCAST_KIND, idPattern, pairPattern, hexKey, positiveAtomic, positiveSeconds, openRfqPayload, parseOpenRfqBid, rankOpenRfqBids;
3195
+ var init_openRfq = __esm({
3196
+ "src/openRfq.ts"() {
3197
+ "use strict";
3198
+ RFQ_BROADCAST_KIND = 24860;
3199
+ idPattern = /^[a-f0-9]{64}$/;
3200
+ pairPattern = /^[a-zA-Z0-9:/._%-]{1,256}->[a-zA-Z0-9:/._%-]{1,256}$/;
3201
+ hexKey = /^[a-f0-9]{64}$/;
3202
+ positiveAtomic = (value) => typeof value === "string" && /^[1-9][0-9]{0,127}$/.test(value) ? BigInt(value) : void 0;
3203
+ positiveSeconds = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
3204
+ openRfqPayload = (request) => {
3205
+ 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))
3206
+ throw new Error("invalid open RFQ request");
3207
+ return {
3208
+ v: 1,
3209
+ type: "rfq_open",
3210
+ open_id: request.openId,
3211
+ pair: request.pair,
3212
+ amount_side: request.amountSide,
3213
+ amount: request.amount.toString(),
3214
+ bids_until: request.bidsUntil
3215
+ };
3216
+ };
3217
+ parseOpenRfqBid = (payload, solverPubkey, eventId) => {
3218
+ if (!payload || typeof payload !== "object" || !hexKey.test(solverPubkey) || !hexKey.test(eventId))
3219
+ return null;
3220
+ const value = payload;
3221
+ const fromAmount = positiveAtomic(value.from_amount);
3222
+ const toAmount2 = positiveAtomic(value.to_amount);
3223
+ 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))
3224
+ return null;
3225
+ return {
3226
+ id: eventId,
3227
+ solverPubkey,
3228
+ openId: value.open_id,
3229
+ pair: value.pair,
3230
+ amountSide: value.amount_side,
3231
+ fromAmount,
3232
+ toAmount: toAmount2,
3233
+ validUntil: value.valid_until,
3234
+ card: value.card
3235
+ };
3236
+ };
3237
+ rankOpenRfqBids = (bids, amountSide) => [...bids].sort((left, right) => {
3238
+ const difference = amountSide === "from" ? right.toAmount - left.toAmount : left.fromAmount - right.fromAmount;
3239
+ return difference < 0n ? -1 : difference > 0n ? 1 : left.solverPubkey.localeCompare(right.solverPubkey) || left.id.localeCompare(right.id);
3240
+ });
3241
+ }
3242
+ });
3243
+
3244
+ // src/openRfqTransport.ts
3245
+ var openRfqTransport_exports = {};
3246
+ __export(openRfqTransport_exports, {
3247
+ collectOpenRfqBids: () => collectOpenRfqBids
3248
+ });
3249
+ var import_nostr_tools2, MAX_BIDS, MAX_AUTHENTICATED_REPLY_DECRYPTIONS, MAX_EVENT_CONTENT, MAX_WINDOW_MS, CLOCK_SKEW_SECONDS, collectOpenRfqBids;
3250
+ var init_openRfqTransport = __esm({
3251
+ "src/openRfqTransport.ts"() {
3252
+ "use strict";
3253
+ import_nostr_tools2 = require("nostr-tools");
3254
+ init_nostr();
3255
+ init_nostrPool();
3256
+ init_openRfq();
3257
+ init_transportErrors();
3258
+ MAX_BIDS = 64;
3259
+ MAX_AUTHENTICATED_REPLY_DECRYPTIONS = 256;
3260
+ MAX_EVENT_CONTENT = 1e5;
3261
+ MAX_WINDOW_MS = 3e4;
3262
+ CLOCK_SKEW_SECONDS = 30;
3263
+ collectOpenRfqBids = (request, options) => {
3264
+ const payload = openRfqPayload(request);
3265
+ const windowMs = options.windowMs ?? 3e3;
3266
+ if (!Number.isSafeInteger(windowMs) || windowMs < 0 || windowMs > MAX_WINDOW_MS)
3267
+ throw new Error("windowMs must be an integer between 0 and 30000");
3268
+ const started = Date.now();
3269
+ const now = Math.floor(started / 1e3);
3270
+ const duration = Math.min(windowMs, request.bidsUntil * 1e3 - started);
3271
+ if (duration < 0 || request.bidsUntil > now + 31) throw new Error("invalid open RFQ deadline");
3272
+ const relays = [...new Set(options.relays)];
3273
+ if (!relays.length || relays.length > 16)
3274
+ throw new Error("open RFQ requires between 1 and 16 relays");
3275
+ for (const relay of relays) {
3276
+ const url = new URL(relay);
3277
+ if (!/^wss?:$/.test(url.protocol) || url.username || url.password || url.hash)
3278
+ throw new Error("invalid open RFQ relay");
3279
+ }
3280
+ options.signal?.throwIfAborted();
3281
+ const secretKey = new Uint8Array(options.secretKey);
3282
+ const clientPubkey = (0, import_nostr_tools2.getPublicKey)(secretKey);
3283
+ const event = (0, import_nostr_tools2.finalizeEvent)(
3284
+ {
3285
+ kind: RFQ_BROADCAST_KIND,
3286
+ created_at: now,
3287
+ tags: [["t", request.pair]],
3288
+ content: JSON.stringify(payload)
3289
+ },
3290
+ secretKey
3291
+ );
3292
+ const pool = options.pool ?? sharedNostrPool();
3293
+ return new Promise((resolve, reject) => {
3294
+ const bids = /* @__PURE__ */ new Map();
3295
+ const seen = /* @__PURE__ */ new Set();
3296
+ let closed = false;
3297
+ let accepted = false;
3298
+ let subscription;
3299
+ const noRelay = () => new SolverUnavailable("no relay accepted the open RFQ");
3300
+ const finish = (error) => {
3301
+ if (closed) return;
3302
+ closed = true;
3303
+ clearTimeout(timer);
3304
+ options.signal?.removeEventListener("abort", abort);
3305
+ try {
3306
+ subscription?.close();
3307
+ } catch {
3308
+ }
3309
+ secretKey.fill(0);
3310
+ if (error !== void 0) reject(error);
3311
+ else resolve(rankOpenRfqBids([...bids.values()], request.amountSide));
3312
+ };
3313
+ const abort = () => finish(options.signal?.reason ?? new Error("open RFQ aborted"));
3314
+ const timer = setTimeout(() => finish(accepted ? void 0 : noRelay()), duration);
3315
+ options.signal?.addEventListener("abort", abort, { once: true });
3316
+ try {
3317
+ subscription = pool.subscribeMany(
3318
+ relays,
3319
+ {
3320
+ kinds: [RFQ_DIRECTED_KIND],
3321
+ "#p": [clientPubkey],
3322
+ "#e": [event.id],
3323
+ since: now - CLOCK_SKEW_SECONDS
3324
+ },
3325
+ {
3326
+ onevent(reply) {
3327
+ const current = Math.floor(Date.now() / 1e3);
3328
+ 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(
3329
+ (tag) => Array.isArray(tag) && tag.length <= 8 && tag.every(
3330
+ (value) => typeof value === "string" && value.length <= 1024
3331
+ )
3332
+ ) || 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)
3333
+ return;
3334
+ const recipients = reply.tags.filter((tag) => tag[0] === "p");
3335
+ const references = reply.tags.filter((tag) => tag[0] === "e");
3336
+ if (recipients.length !== 1 || recipients[0]?.[1] !== clientPubkey || references.length !== 1 || references[0]?.[1] !== event.id)
3337
+ return;
3338
+ try {
3339
+ if (!(0, import_nostr_tools2.verifyEvent)(reply)) return;
3340
+ seen.add(reply.id);
3341
+ const key = import_nostr_tools2.nip44.v2.utils.getConversationKey(secretKey, reply.pubkey);
3342
+ const bid = parseOpenRfqBid(
3343
+ JSON.parse(import_nostr_tools2.nip44.v2.decrypt(reply.content, key)),
3344
+ reply.pubkey,
3345
+ reply.id
3346
+ );
3347
+ 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)
3348
+ return;
3349
+ const previous = bids.get(bid.solverPubkey);
3350
+ if (previous) {
3351
+ const improved = request.amountSide === "from" ? bid.toAmount > previous.toAmount : bid.fromAmount < previous.fromAmount;
3352
+ if (!improved) return;
3353
+ } else if (bids.size >= MAX_BIDS) {
3354
+ const worst = rankOpenRfqBids(
3355
+ [...bids.values()],
3356
+ request.amountSide
3357
+ ).at(-1);
3358
+ if (rankOpenRfqBids([worst, bid], request.amountSide)[0] !== bid)
3359
+ return;
3360
+ bids.delete(worst.solverPubkey);
3361
+ }
3362
+ bids.set(bid.solverPubkey, bid);
3363
+ accepted = true;
3364
+ options.onBids?.(
3365
+ rankOpenRfqBids([...bids.values()], request.amountSide)
3366
+ );
3367
+ } catch {
3368
+ }
3369
+ },
3370
+ onclose(reasons) {
3371
+ finish(new RelayUnavailable(reasons.map(String)));
3372
+ }
3373
+ }
3374
+ );
3375
+ if (closed) subscription.close();
3376
+ else {
3377
+ const publications = pool.publish(relays, event);
3378
+ if (!publications.length) finish(noRelay());
3379
+ void Promise.allSettled(publications).then((results) => {
3380
+ accepted ||= results.some(
3381
+ (result) => result.status === "fulfilled" && !String(result.value).startsWith("connection failure")
3382
+ );
3383
+ if (!accepted) finish(noRelay());
3384
+ });
3385
+ for (const publication of publications)
3386
+ void publication.then(
3387
+ (result) => {
3388
+ if (!String(result).startsWith("connection failure")) accepted = true;
3389
+ },
3390
+ () => {
3391
+ }
3392
+ );
3393
+ }
3394
+ } catch (error) {
3395
+ finish(error);
3396
+ }
3397
+ });
3398
+ };
3399
+ }
3400
+ });
3401
+
3426
3402
  // src/nostr.ts
3427
3403
  var nostr_exports = {};
3428
3404
  __export(nostr_exports, {
3405
+ RFQ_BROADCAST_KIND: () => RFQ_BROADCAST_KIND,
3429
3406
  RFQ_DIRECTED_KIND: () => RFQ_DIRECTED_KIND,
3430
3407
  RelayUnavailable: () => RelayUnavailable,
3431
3408
  TransportClosed: () => TransportClosed,
3432
3409
  closeSharedNostrPool: () => closeSharedNostrPool,
3410
+ collectOpenRfqBids: () => collectOpenRfqBids,
3433
3411
  createNostrPool: () => createNostrPool,
3434
3412
  nostrCardFetcher: () => nostrCardFetcher,
3435
3413
  nostrRfqTransport: () => nostrRfqTransport,
3414
+ openRfqPayload: () => openRfqPayload,
3415
+ parseOpenRfqBid: () => parseOpenRfqBid,
3416
+ rankOpenRfqBids: () => rankOpenRfqBids,
3436
3417
  sharedNostrPool: () => sharedNostrPool
3437
3418
  });
3438
- var import_solver_discovery7, import_sdk20, import_nostr_tools2, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CONNECTION_FAILURE, CARD_FETCH_TIMEOUT_MS, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
3419
+ var import_solver_discovery7, import_sdk20, import_nostr_tools3, RFQ_DIRECTED_KIND, DEFAULT_TIMEOUT_MS, CONNECTION_FAILURE, CARD_FETCH_TIMEOUT_MS, RelayUnavailable, TransportClosed, closeReasons, nostrRfqTransport, isNewer, nostrCardFetcher;
3439
3420
  var init_nostr = __esm({
3440
3421
  "src/nostr.ts"() {
3441
3422
  "use strict";
3442
3423
  import_solver_discovery7 = require("@arkade-os/solver-discovery");
3443
3424
  init_rfq();
3444
3425
  init_nostrPool();
3426
+ init_transportErrors();
3445
3427
  import_sdk20 = require("@arkade-os/sdk");
3446
- import_nostr_tools2 = require("nostr-tools");
3428
+ import_nostr_tools3 = require("nostr-tools");
3447
3429
  init_nostrPool();
3430
+ init_openRfqTransport();
3431
+ init_openRfq();
3448
3432
  RFQ_DIRECTED_KIND = 24859;
3449
3433
  DEFAULT_TIMEOUT_MS = 3e4;
3450
3434
  CONNECTION_FAILURE = "connection failure";
3451
3435
  CARD_FETCH_TIMEOUT_MS = 5e3;
3452
- RelayUnavailable = class extends Error {
3436
+ RelayUnavailable = class extends SolverUnavailable {
3453
3437
  reasons;
3454
3438
  constructor(reasons) {
3455
3439
  super(`lost every relay connection: ${reasons.join("; ") || "connection closed"}`);
@@ -3472,11 +3456,11 @@ var init_nostr = __esm({
3472
3456
  (0, import_sdk20.assertTimerMs)("timeoutMs", options.timeoutMs);
3473
3457
  const relays = options.relays;
3474
3458
  const solverPubkey = options.solverPubkey;
3475
- const secretKey = options.secretKey ?? (0, import_nostr_tools2.generateSecretKey)();
3476
- const pubkey = (0, import_nostr_tools2.getPublicKey)(secretKey);
3459
+ const secretKey = options.secretKey ?? (0, import_nostr_tools3.generateSecretKey)();
3460
+ const pubkey = (0, import_nostr_tools3.getPublicKey)(secretKey);
3477
3461
  const pool = options.pool ?? sharedNostrPool();
3478
3462
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS;
3479
- const conversationKey = import_nostr_tools2.nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
3463
+ const conversationKey = import_nostr_tools3.nip44.v2.utils.getConversationKey(secretKey, solverPubkey);
3480
3464
  let closed = false;
3481
3465
  let lost;
3482
3466
  const waiters = /* @__PURE__ */ new Map();
@@ -3485,10 +3469,10 @@ var init_nostr = __esm({
3485
3469
  { kinds: [RFQ_DIRECTED_KIND], "#p": [pubkey], authors: [solverPubkey] },
3486
3470
  {
3487
3471
  onevent(event) {
3488
- if (event.pubkey !== solverPubkey || !(0, import_nostr_tools2.verifyEvent)(event)) return;
3472
+ if (event.pubkey !== solverPubkey || !(0, import_nostr_tools3.verifyEvent)(event)) return;
3489
3473
  let payload;
3490
3474
  try {
3491
- payload = JSON.parse(import_nostr_tools2.nip44.v2.decrypt(event.content, conversationKey));
3475
+ payload = JSON.parse(import_nostr_tools3.nip44.v2.decrypt(event.content, conversationKey));
3492
3476
  } catch {
3493
3477
  return;
3494
3478
  }
@@ -3507,12 +3491,12 @@ var init_nostr = __esm({
3507
3491
  }
3508
3492
  );
3509
3493
  const send = async (payload) => {
3510
- const event = (0, import_nostr_tools2.finalizeEvent)(
3494
+ const event = (0, import_nostr_tools3.finalizeEvent)(
3511
3495
  {
3512
3496
  kind: RFQ_DIRECTED_KIND,
3513
3497
  created_at: Math.floor(Date.now() / 1e3),
3514
3498
  tags: [["p", solverPubkey]],
3515
- content: import_nostr_tools2.nip44.v2.encrypt(JSON.stringify(payload), conversationKey)
3499
+ content: import_nostr_tools3.nip44.v2.encrypt(JSON.stringify(payload), conversationKey)
3516
3500
  },
3517
3501
  secretKey
3518
3502
  );
@@ -3523,13 +3507,14 @@ var init_nostr = __esm({
3523
3507
  const accepted = results.some(
3524
3508
  (r) => r.status === "fulfilled" && !String(r.value).startsWith(CONNECTION_FAILURE)
3525
3509
  );
3526
- if (!accepted) throw new Error(`no relay accepted the RFQ message: ${reasons.join("; ")}`);
3510
+ if (!accepted)
3511
+ throw new SolverUnavailable(`no relay accepted the RFQ message: ${reasons.join("; ")}`);
3527
3512
  };
3528
3513
  const awaitReply = (rfqId) => {
3529
3514
  const reply = new Promise((resolve, reject) => {
3530
3515
  const timer = setTimeout(() => {
3531
3516
  waiters.delete(rfqId);
3532
- reject(new Error(`no solver reply within ${timeoutMs}ms`));
3517
+ reject(new SolverUnavailable(`no solver reply within ${timeoutMs}ms`));
3533
3518
  }, timeoutMs);
3534
3519
  waiters.set(rfqId, {
3535
3520
  resolve: (payload) => {
@@ -3615,7 +3600,7 @@ var init_nostr = __esm({
3615
3600
  onevent(event) {
3616
3601
  if (event.kind !== import_solver_discovery7.SOLVER_CARD_KIND || !asked.has(event.pubkey))
3617
3602
  return;
3618
- if (!(0, import_nostr_tools2.verifyEvent)(event)) return;
3603
+ if (!(0, import_nostr_tools3.verifyEvent)(event)) return;
3619
3604
  if (event.tags.find((tag) => tag[0] === "d")?.[1] !== network)
3620
3605
  return;
3621
3606
  if (isNewer(event, latest.get(event.pubkey)))
@@ -3919,6 +3904,7 @@ __export(advanced_exports, {
3919
3904
  CovclaimdRevealError: () => CovclaimdRevealError,
3920
3905
  DEFAULT_INVOICE_EXPIRY_SECONDS: () => DEFAULT_INVOICE_EXPIRY_SECONDS,
3921
3906
  DEFAULT_MAX_REFUND_WINDOW_SECONDS: () => DEFAULT_MAX_REFUND_WINDOW_SECONDS,
3907
+ DEFAULT_OPEN_RFQ_RELAYS: () => DEFAULT_OPEN_RFQ_RELAYS,
3922
3908
  DiscoverySnapshotUnavailable: () => DiscoverySnapshotUnavailable,
3923
3909
  EVM_CHAIN: () => EVM_CHAIN,
3924
3910
  FEED_TTL_MS: () => FEED_TTL_MS,
@@ -3943,6 +3929,7 @@ __export(advanced_exports, {
3943
3929
  REGISTRY_URL: () => REGISTRY_URL,
3944
3930
  RFQ_SWAP_ID_PREFIX: () => RFQ_SWAP_ID_PREFIX,
3945
3931
  SWAP_ERROR_NAMES: () => SWAP_ERROR_NAMES,
3932
+ SolverRoutesUnavailable: () => SolverRoutesUnavailable,
3946
3933
  SwapDriveRefusedError: () => SwapDriveRefusedError,
3947
3934
  SwapRefusal: () => SwapRefusal,
3948
3935
  UnsupportedRoute: () => UnsupportedRoute,
@@ -3960,12 +3947,14 @@ __export(advanced_exports, {
3960
3947
  btcAssetPart: () => btcAssetPart,
3961
3948
  btcOn: () => btcOn,
3962
3949
  buildOfferFillPlan: () => buildOfferFillPlan,
3950
+ canFailoverQuote: () => canFailoverQuote,
3963
3951
  cancelSwap: () => cancelSwap,
3964
3952
  canonicalAssetId: () => canonicalAssetId,
3965
3953
  cardLegAssetId: () => cardLegAssetId,
3966
3954
  cardMarketOf: () => cardMarketOf,
3967
3955
  chainSourceOver: () => chainSourceOver,
3968
3956
  chooseMarket: () => chooseMarket,
3957
+ completedSolverUsage: () => completedSolverUsage,
3969
3958
  conflictingFields: () => conflictingFields,
3970
3959
  corridorOfRail: () => corridorOfRail,
3971
3960
  corridorOutcome: () => corridorOutcome,
@@ -3973,6 +3962,7 @@ __export(advanced_exports, {
3973
3962
  corridorSet: () => corridorSet,
3974
3963
  covclaimdClient: () => covclaimdClient,
3975
3964
  createNostrTransportFactory: () => createNostrTransportFactory,
3965
+ createSolverHealth: () => createSolverHealth,
3976
3966
  createSwapClient: () => createSwapClient,
3977
3967
  createSwapDrive: () => createSwapDrive,
3978
3968
  decodeBolt11: () => decodeBolt11,
@@ -4002,10 +3992,12 @@ __export(advanced_exports, {
4002
3992
  feedFetch: () => feedFetch,
4003
3993
  feedSpread: () => feedSpread,
4004
3994
  formatAssetId: () => formatAssetId,
3995
+ freezeOpenRfqValue: () => freezeOpenRfqValue,
4005
3996
  fromAtomicDecimal: () => fromAtomicDecimal,
4006
3997
  fromRfqAmountSide: () => fromRfqAmountSide,
4007
3998
  fundingWasNotSubmitted: () => fundingWasNotSubmitted,
4008
3999
  fundsFromWallet: () => fundsFromWallet,
4000
+ hasPausedKnownBidder: () => hasPausedKnownBidder,
4009
4001
  instrumentOf: () => instrumentOf,
4010
4002
  isAddressable: () => isAddressable,
4011
4003
  isAssetId: () => isAssetId,
@@ -4015,6 +4007,7 @@ __export(advanced_exports, {
4015
4007
  isCardMarket: () => isCardMarket,
4016
4008
  isIndexedNetwork: () => isIndexedNetwork,
4017
4009
  isNetworkRef: () => isNetworkRef,
4010
+ isSolverReliabilityFailure: () => isSolverReliabilityFailure,
4018
4011
  isSwapError: () => isSwapError,
4019
4012
  isUsableCard: () => isUsableCard,
4020
4013
  issuanceOf: () => issuanceOf,
@@ -4032,11 +4025,14 @@ __export(advanced_exports, {
4032
4025
  offerOutcome: () => offerOutcome,
4033
4026
  offerRecordSource: () => offerRecordSource,
4034
4027
  onchainCorridor: () => onchainCorridor,
4028
+ openBidCandidates: () => openBidCandidates,
4029
+ orderedSolverCandidates: () => orderedSolverCandidates,
4035
4030
  pageRfqRecords: () => pageRfqRecords,
4036
4031
  parseAssetId: () => parseAssetId,
4037
4032
  parseRfqQuote: () => parseRfqQuote,
4038
4033
  pay: () => pay,
4039
4034
  publicAssetId: () => publicAssetId,
4035
+ quoteAdvertisedPlan: () => quoteAdvertisedPlan,
4040
4036
  quoteFromFeed: () => quoteFromFeed,
4041
4037
  quoteIdOfSwapId: () => quoteIdOfSwapId,
4042
4038
  quoteViaRfq: () => quoteViaRfq,
@@ -4066,6 +4062,7 @@ __export(advanced_exports, {
4066
4062
  sameAsset: () => sameAsset,
4067
4063
  satsOf: () => satsOf,
4068
4064
  scopedToRail: () => scopedToRail,
4065
+ solverFacingAmount: () => solverFacingAmount,
4069
4066
  splitRecords: () => splitRecords,
4070
4067
  swapOf: () => swapOf,
4071
4068
  swapRecordOf: () => swapRecordOf,
@@ -5398,6 +5395,7 @@ var commonOf = (quote, now) => ({
5398
5395
  market: quote.market,
5399
5396
  ...quote.solver === void 0 ? {} : { solver: quote.solver },
5400
5397
  expiresAt: quote.expiresAt,
5398
+ ...quote.auction === void 0 ? {} : { fundingDeadline: quote.expiresAt },
5401
5399
  ...quote.artifact === void 0 ? {} : { artifact: recordArtifact(quote.artifact) },
5402
5400
  createdAt: now,
5403
5401
  updatedAt: now
@@ -5584,8 +5582,14 @@ var registeredCorridorRecord = async (input, preparation) => {
5584
5582
  return corridorRecord(input.quote, preparation, input.now);
5585
5583
  };
5586
5584
  var fundAndStamp = async (input, record, repository) => {
5585
+ if (record.fundingDeadline !== void 0 && (!Number.isSafeInteger(record.fundingDeadline) || record.fundingDeadline <= 0 || record.fundingDeadline > record.expiresAt))
5586
+ throw new Error("invalid stored funding deadline");
5587
5587
  const bounds = storedFundingBounds(record.assetPayment, record.expiresAt);
5588
- const cap = input.validUntil === void 0 ? bounds.validUntil : Math.min(input.validUntil, bounds.validUntil ?? record.expiresAt);
5588
+ const cap = input.validUntil === void 0 ? record.fundingDeadline === void 0 ? bounds.validUntil : Math.min(record.fundingDeadline, bounds.validUntil ?? record.expiresAt) : Math.min(
5589
+ input.validUntil,
5590
+ bounds.validUntil ?? record.expiresAt,
5591
+ record.fundingDeadline ?? record.expiresAt
5592
+ );
5589
5593
  const validUntil = cap === void 0 ? void 0 : Math.min(cap, record.expiresAt);
5590
5594
  if (input.firstFundingAttempt && record.assetPayment !== void 0 && validUntil !== void 0 && validUntil < record.assetPayment.validUntil) {
5591
5595
  record = { ...record, assetPayment: { ...record.assetPayment, validUntil } };
@@ -7175,6 +7179,11 @@ var covenantOf = (swap) => ({
7175
7179
  ...swap.offerHex === void 0 ? {} : { offerHex: swap.offerHex },
7176
7180
  ...swap.binding === void 0 ? {} : { binding: swap.binding }
7177
7181
  });
7182
+ var restoredCovenant = (swap) => {
7183
+ if (swap.binding !== void 0) return { ...covenantOf(swap), binding: swap.binding };
7184
+ if (swap.offerHex !== void 0) return { offerHex: swap.offerHex };
7185
+ throw new Error("this offer swap carries neither a binding nor an offerHex to rebuild from");
7186
+ };
7178
7187
  var offerFactsOf = (record) => ({
7179
7188
  id: record.id,
7180
7189
  coverageId: record.id,
@@ -7251,7 +7260,7 @@ var restoredOfferRecord = (swap, network, now) => {
7251
7260
  market: { kind: "restored", backend: "feed" },
7252
7261
  expiresAt: createdAt,
7253
7262
  status: swap.status,
7254
- ...covenantOf(swap),
7263
+ ...restoredCovenant(swap),
7255
7264
  swapAddress: swap.swapAddress,
7256
7265
  swapPkScript: swap.swapPkScript,
7257
7266
  fundingTxid: swap.fundingTxid,
@@ -7695,8 +7704,8 @@ function withExitV0(program, exit) {
7695
7704
  }
7696
7705
  var V0_TO_V1 = /* @__PURE__ */ new Map();
7697
7706
  for (const [v0, v1] of [
7698
- [swap_want_btc_program_v0_default, legacySwapPrograms.wantBtc],
7699
- [swap_want_asset_program_v0_default, legacySwapPrograms.wantAsset]
7707
+ [swap_want_btc_program_v0_default, swapPrograms.wantBtc],
7708
+ [swap_want_asset_program_v0_default, swapPrograms.wantAsset]
7700
7709
  ]) {
7701
7710
  for (const exit of [void 0, "blocks", "seconds"]) {
7702
7711
  const timelock = exit && { type: exit, value: BigInt(0) };
@@ -10328,6 +10337,8 @@ var pinAmount = (input, takeInstrument) => {
10328
10337
 
10329
10338
  // src/client/quoteOffer.ts
10330
10339
  init_verify();
10340
+ init_transportErrors();
10341
+ init_rfq();
10331
10342
  var FEED_TTL_MS = 3e4;
10332
10343
  var feedFetch = (base = fetch) => {
10333
10344
  const at2 = /* @__PURE__ */ new Map();
@@ -10337,20 +10348,32 @@ var feedFetch = (base = fetch) => {
10337
10348
  };
10338
10349
  return { fetch: makeCachedFeedFetch(FEED_TTL_MS, probe), fetchedAt: (url) => at2.get(url) };
10339
10350
  };
10351
+ var quoteAdvertisedPlan = (card, options, policy) => (0, import_solver_discovery11.quoteOffer)(card, options).catch((cause) => {
10352
+ const cancelled = options.signal?.aborted || cause !== null && typeof cause === "object" && "name" in cause && cause.name === "AbortError";
10353
+ if (policy?.solverRouting === void 0 || cancelled) throw cause;
10354
+ throw new SolverUnavailable("The solver's advertised price is unavailable", { cause });
10355
+ });
10340
10356
  var quoteFromFeed = async (input) => {
10341
10357
  const { candidate, amount } = input;
10342
10358
  if (amount === void 0) {
10343
10359
  throw new Error("an asset swap needs an amount and the side it pins");
10344
10360
  }
10345
- const plan = await (0, import_solver_discovery11.quoteOffer)(candidate.card, {
10346
- give: candidate.give,
10347
- ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
10348
- // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
10349
- // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
10350
- carrierSats: ASSET_CARRIER_SATS,
10351
- ...QUOTE_OPTIONS,
10352
- fetchImpl: input.feed.fetch
10353
- });
10361
+ const plan = await quoteAdvertisedPlan(
10362
+ candidate.card,
10363
+ {
10364
+ give: candidate.give,
10365
+ ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
10366
+ // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
10367
+ // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
10368
+ carrierSats: ASSET_CARRIER_SATS,
10369
+ ...QUOTE_OPTIONS,
10370
+ fetchImpl: input.feed.fetch
10371
+ },
10372
+ input.policy
10373
+ );
10374
+ if (input.policy?.solverRouting !== void 0 && !plan.limits.withinLimits) {
10375
+ throw new SwapRefusal("amount_out_of_range");
10376
+ }
10354
10377
  verifyPlanLegs(plan, input.legs, candidate.give);
10355
10378
  const expiresAt = feedExpiry(candidate.card, input.feed, input.now);
10356
10379
  verifyQuoteTtl({
@@ -10418,7 +10441,6 @@ var verifyPlanLegs = (plan, legs, give) => {
10418
10441
  // src/client/quoteRfq.ts
10419
10442
  var import_base23 = require("@scure/base");
10420
10443
  var import_sdk36 = require("@arkade-os/sdk");
10421
- var import_solver_discovery12 = require("@arkade-os/solver-discovery");
10422
10444
 
10423
10445
  // src/jointGraph.ts
10424
10446
  var import_base22 = require("@scure/base");
@@ -10539,6 +10561,7 @@ var claimFeeSats = (deps) => BigInt(Math.ceil((deps.claimVsize ?? ONCHAIN_CLAIM_
10539
10561
  init_rfq_contract();
10540
10562
  init_rfq();
10541
10563
  init_errors();
10564
+ init_transportErrors();
10542
10565
 
10543
10566
  // src/client/rfqWire.ts
10544
10567
  init_rfq();
@@ -10589,6 +10612,16 @@ var covenantInputs = (input) => {
10589
10612
  hrp: network.hrp
10590
10613
  };
10591
10614
  };
10615
+ var parseRfqQuote2 = (wire, policy) => {
10616
+ try {
10617
+ return parseRfqQuote(wire);
10618
+ } catch (cause) {
10619
+ if (policy?.solverRouting !== void 0 && cause instanceof AmountEncodingUnsupported) {
10620
+ throw new SolverResponseInvalid(cause.message, { cause });
10621
+ }
10622
+ throw cause;
10623
+ }
10624
+ };
10592
10625
  var sealingKey = (deps) => {
10593
10626
  const configured = deps.covclaimd?.pubkey;
10594
10627
  if (configured === void 0) return void 0;
@@ -10690,8 +10723,8 @@ var quoteArkadeAsset = async (input) => {
10690
10723
  ASSET_SWAP_CONTRACT_VERSIONS
10691
10724
  );
10692
10725
  verifyPair(wire.pair, pair);
10693
- const parsed = parseRfqQuote(wire);
10694
- const taker = contractVersion === ASSET_SWAP_V4 ? verifyTaker({
10726
+ const parsed = parseRfqQuote2(wire, input.policy);
10727
+ const taker = contractVersion === ASSET_SWAP_DIRECTED ? verifyTaker({
10695
10728
  attested: input.transport.attestedResponder,
10696
10729
  solverPubkey: parsed.solver
10697
10730
  }) : void 0;
@@ -10737,15 +10770,19 @@ var quoteArkadeAsset = async (input) => {
10737
10770
  }
10738
10771
  if (assetPayment !== void 0) deepFreeze(assetPayment);
10739
10772
  const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
10740
- const reference = await (0, import_solver_discovery12.quoteOffer)(input.candidate.card, {
10741
- give: input.candidate.give,
10742
- giveAmount: parsed.give,
10743
- // Unconditional: a card charging for the delivered carrier refuses to price without
10744
- // it whichever leg gives, and a BTC deposit funds none of its own to publish.
10745
- carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
10746
- ...QUOTE_OPTIONS,
10747
- fetchImpl: input.feed.fetch
10748
- });
10773
+ const reference = await quoteAdvertisedPlan(
10774
+ input.candidate.card,
10775
+ {
10776
+ give: input.candidate.give,
10777
+ giveAmount: parsed.give,
10778
+ // Unconditional: a card charging for the delivered carrier refuses to price without
10779
+ // it whichever leg gives, and a BTC deposit funds none of its own to publish.
10780
+ carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
10781
+ ...QUOTE_OPTIONS,
10782
+ fetchImpl: input.feed.fetch
10783
+ },
10784
+ input.policy
10785
+ );
10749
10786
  verifyPlanLegs(reference, input.legs, input.candidate.give);
10750
10787
  const terms = offerTermsFromQuote(wire, sides);
10751
10788
  const offer = await deriveOffer(input.wallet, {
@@ -10838,7 +10875,7 @@ var quoteLightningSend = async (input) => {
10838
10875
  })
10839
10876
  );
10840
10877
  verifyPair(wire.pair, pair);
10841
- const parsed = parseRfqQuote(wire);
10878
+ const parsed = parseRfqQuote2(wire, input.policy);
10842
10879
  verifySendInvoice({ invoiced: invoice.amount, give: parsed.give, take: parsed.take });
10843
10880
  const covenant = covenantInputs(input);
10844
10881
  const derived = verifyingDerivation(
@@ -10933,7 +10970,7 @@ var quoteLightningReceive = async (input) => {
10933
10970
  )
10934
10971
  );
10935
10972
  verifyPair(wire.pair, pair);
10936
- const parsed = parseRfqQuote(wire);
10973
+ const parsed = parseRfqQuote2(wire, input.policy);
10937
10974
  verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
10938
10975
  const covenant = covenantInputs(input);
10939
10976
  const derived = verifyingDerivation(
@@ -11007,6 +11044,16 @@ var quoteLightningReceive = async (input) => {
11007
11044
  }
11008
11045
  };
11009
11046
  };
11047
+ var solverFacingAmount = (route, pinned, corridors) => {
11048
+ if (route !== "arkade->onchain" || pinned.on !== "take") return { quoted: pinned };
11049
+ const onchain = corridors.get("onchain").deps;
11050
+ if (onchain.claimFeeRateSatVb === void 0) return { quoted: pinned };
11051
+ const claimFee = claimFeeSats({
11052
+ claimFeeRateSatVb: onchain.claimFeeRateSatVb,
11053
+ claimVsize: onchain.claimVsize
11054
+ });
11055
+ return { quoted: { ...pinned, value: pinned.value + claimFee }, claimFee };
11056
+ };
11010
11057
  var quoteOnchainSend = async (input) => {
11011
11058
  const pinned = pinnedFor(input);
11012
11059
  const destination = input.endpoints.take.instrument;
@@ -11017,12 +11064,7 @@ var quoteOnchainSend = async (input) => {
11017
11064
  const payoutPkScript = l1ScriptForAddress(destination.address, l1Network);
11018
11065
  const pair = rfqPairFor(input.legs.give, input.legs.take);
11019
11066
  const rfqId = newRfqId();
11020
- const onchain = input.corridors.get("onchain").deps;
11021
- const claimFee = pinned.on === "take" && onchain.claimFeeRateSatVb !== void 0 ? claimFeeSats({
11022
- claimFeeRateSatVb: onchain.claimFeeRateSatVb,
11023
- claimVsize: onchain.claimVsize
11024
- }) : void 0;
11025
- const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
11067
+ const { quoted, claimFee } = solverFacingAmount(input.route, pinned, input.corridors);
11026
11068
  const [secrets, payoutKey] = await Promise.all([
11027
11069
  (0, import_sdk36.provisionClaimSecret)(input.wallet),
11028
11070
  (0, import_sdk36.provisionRefundKey)(input.wallet)
@@ -11043,7 +11085,7 @@ var quoteOnchainSend = async (input) => {
11043
11085
  )
11044
11086
  );
11045
11087
  verifyPair(wire.pair, pair);
11046
- const parsed = parseRfqQuote(wire);
11088
+ const parsed = parseRfqQuote2(wire, input.policy);
11047
11089
  verifyQuotedAmount({ pair, pinned: quoted, give: parsed.give, take: parsed.take });
11048
11090
  if (claimFee !== void 0) {
11049
11091
  const payout = parsed.take - claimFee;
@@ -11156,7 +11198,7 @@ var quoteOnchainReceive = async (input) => {
11156
11198
  )
11157
11199
  );
11158
11200
  verifyPair(wire.pair, pair);
11159
- const parsed = parseRfqQuote(wire);
11201
+ const parsed = parseRfqQuote2(wire, input.policy);
11160
11202
  verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
11161
11203
  const covenant = covenantInputs(input);
11162
11204
  const derived = verifyingDerivation(
@@ -11243,6 +11285,9 @@ var quoteOnchainReceive = async (input) => {
11243
11285
  };
11244
11286
  };
11245
11287
 
11288
+ // src/client/client.ts
11289
+ init_verify();
11290
+
11246
11291
  // src/client/verbs.ts
11247
11292
  var import_sdk37 = require("@arkade-os/sdk");
11248
11293
  init_errors();
@@ -11337,6 +11382,225 @@ var createNostrTransportFactory = (pool) => {
11337
11382
  };
11338
11383
  var nostrTransportFactory = createNostrTransportFactory();
11339
11384
 
11385
+ // src/client/solverHealth.ts
11386
+ var QUIET_MS = 30 * 6e4;
11387
+ var cooldown = (failures) => failures < 2 ? 0 : Math.min(6e4 * 2 ** Math.min(failures - 2, 4), 15 * 6e4);
11388
+ function createSolverHealth(options = {}) {
11389
+ const now = options.now ?? (() => Date.now());
11390
+ const memory = /* @__PURE__ */ new Map();
11391
+ const keyOf = (scope) => JSON.stringify([scope.network, scope.direction]);
11392
+ const storage = options.storage ?? {
11393
+ load: (scope) => memory.get(keyOf(scope)),
11394
+ save: (scope, records) => {
11395
+ memory.set(keyOf(scope), records);
11396
+ }
11397
+ };
11398
+ const pending = /* @__PURE__ */ new Map();
11399
+ const active = (records, timestamp) => Object.keys(records).filter(
11400
+ (id) => timestamp < records[id].lastFailureAt + cooldown(records[id].failures)
11401
+ );
11402
+ const read = async (scope) => {
11403
+ try {
11404
+ const value = await storage.load(scope);
11405
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
11406
+ const timestamp = now();
11407
+ return Object.fromEntries(
11408
+ Object.entries(value).flatMap(([id, entry]) => {
11409
+ if (!entry || typeof entry !== "object") return [];
11410
+ const { failures, lastFailureAt } = entry;
11411
+ 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 }]] : [];
11412
+ })
11413
+ );
11414
+ } catch {
11415
+ return {};
11416
+ }
11417
+ };
11418
+ return {
11419
+ deprioritized: async (scope) => {
11420
+ await pending.get(keyOf(scope));
11421
+ const records = await read(scope);
11422
+ const timestamp = now();
11423
+ return active(records, timestamp);
11424
+ },
11425
+ record: (scope, solverId3, outcome) => {
11426
+ const key = keyOf(scope);
11427
+ const update = (pending.get(key) ?? Promise.resolve()).then(async () => {
11428
+ let records = await read(scope);
11429
+ const before = JSON.stringify(active(records, now()).sort());
11430
+ if (outcome === "success") delete records[solverId3];
11431
+ else
11432
+ records = {
11433
+ ...records,
11434
+ [solverId3]: {
11435
+ failures: Math.min((records[solverId3]?.failures ?? 0) + 1, 32),
11436
+ lastFailureAt: now()
11437
+ }
11438
+ };
11439
+ try {
11440
+ await storage.save(scope, records);
11441
+ if (before !== JSON.stringify(active(records, now()).sort()))
11442
+ options.onChange?.();
11443
+ } catch {
11444
+ }
11445
+ });
11446
+ pending.set(key, update);
11447
+ return update.finally(() => {
11448
+ if (pending.get(key) === update) pending.delete(key);
11449
+ });
11450
+ }
11451
+ };
11452
+ }
11453
+
11454
+ // src/client/solverRouting.ts
11455
+ var import_solver_discovery12 = require("@arkade-os/solver-discovery");
11456
+ init_offer();
11457
+ init_rfq();
11458
+ init_rfq_contract();
11459
+ init_transportErrors();
11460
+ init_errors();
11461
+ var orderedSolverCandidates = async (route, network, policy, fetchImpl, estimate = true, health) => {
11462
+ const candidates = (policy?.selectMarket ? route.market === void 0 ? [] : [route.market] : route.candidates).map((candidate) => ({
11463
+ ...candidate,
11464
+ solverId: (0, import_solver_discovery12.solverId)(candidate.card, network),
11465
+ direction: (0, import_solver_discovery12.solverDirectionKey)(candidate.card, candidate.give, network)
11466
+ }));
11467
+ if (candidates.length === 0) return [];
11468
+ const preferences = await policy?.solverRouting?.preferences?.({
11469
+ network,
11470
+ direction: candidates[0].direction,
11471
+ candidates
11472
+ });
11473
+ let cooling = [];
11474
+ try {
11475
+ cooling = await health?.deprioritized({ network, direction: candidates[0].direction }) ?? [];
11476
+ } catch {
11477
+ }
11478
+ const options = {
11479
+ network,
11480
+ preferences: {
11481
+ ...preferences,
11482
+ deprioritized: [.../* @__PURE__ */ new Set([...preferences?.deprioritized ?? [], ...cooling])]
11483
+ }
11484
+ };
11485
+ return estimate ? (0, import_solver_discovery12.rankSolverMarkets)(candidates, {
11486
+ ...options,
11487
+ amount: route.amount === void 0 ? void 0 : { on: route.amount.on, value: route.amount.value },
11488
+ carrierSats: ASSET_CARRIER_SATS,
11489
+ fetchImpl
11490
+ }) : (0, import_solver_discovery12.orderSolverMarkets)(candidates, options);
11491
+ };
11492
+ var canFailoverQuote = (error) => {
11493
+ if (error instanceof SolverUnavailable || error instanceof QuoteExpired || error instanceof QuoteVerificationFailed) {
11494
+ return true;
11495
+ }
11496
+ if (!(error instanceof SwapRefusal)) return false;
11497
+ if (error.errorCode !== void 0) {
11498
+ return error.errorCode === "amount_side_unsupported" || error.errorCode === "exact_out_unsupported" || error.errorCode === RFQ_CONTRACT_VERSION_UNSUPPORTED;
11499
+ }
11500
+ return [
11501
+ "unsupported_pair",
11502
+ "amount_out_of_range",
11503
+ "exposure_cap",
11504
+ "pricing_unavailable",
11505
+ "rate_limited"
11506
+ ].includes(error.reason);
11507
+ };
11508
+ 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);
11509
+ var SolverRoutesUnavailable = class extends AggregateError {
11510
+ constructor(attempts) {
11511
+ super(
11512
+ attempts.map(({ error }) => error),
11513
+ "No available solver could quote this swap"
11514
+ );
11515
+ this.attempts = attempts;
11516
+ }
11517
+ attempts;
11518
+ name = "SolverRoutesUnavailable";
11519
+ };
11520
+ var completedSolverUsage = (swaps, network, direction) => {
11521
+ const usage = {};
11522
+ const seen = /* @__PURE__ */ new Set();
11523
+ for (const swap of swaps) {
11524
+ if (seen.has(swap.id) || !["filled", "paid", "claimed"].includes(swap.outcome) || swap.market.kind !== "card")
11525
+ continue;
11526
+ if (JSON.stringify([network, swap.route.give.asset, swap.route.take.asset]) !== direction)
11527
+ continue;
11528
+ seen.add(swap.id);
11529
+ const id = (0, import_solver_discovery12.solverId)(
11530
+ {
11531
+ solver: swap.market.solver,
11532
+ source: swap.market.source,
11533
+ sourceType: swap.market.sourceType,
11534
+ discovery_pubkey: swap.market.discoveryPubkey
11535
+ },
11536
+ network
11537
+ );
11538
+ usage[id] = (usage[id] ?? 0) + 1;
11539
+ }
11540
+ return usage;
11541
+ };
11542
+
11543
+ // src/client/openRfq.ts
11544
+ var import_solver_discovery13 = require("@arkade-os/solver-discovery");
11545
+ var DEFAULT_OPEN_RFQ_RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
11546
+ var freezeOpenRfqValue = (value) => {
11547
+ if (value !== null && typeof value === "object") {
11548
+ for (const nested of Object.values(value)) freezeOpenRfqValue(nested);
11549
+ Object.freeze(value);
11550
+ }
11551
+ return value;
11552
+ };
11553
+ var openBidCandidates = (bid, route, network, policy) => {
11554
+ const checked = (0, import_solver_discovery13.validateCard)(bid.card);
11555
+ 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)
11556
+ return void 0;
11557
+ const signedCard = freezeOpenRfqValue(JSON.parse(JSON.stringify(checked.value)));
11558
+ const markets = (signedCard.markets ?? []).flatMap((market) => {
11559
+ const projected = (0, import_solver_discovery13.indexMarketFromCard)(signedCard, market);
11560
+ if (!projected.ok) return [];
11561
+ const matches = route.snapshot.ref.live ? route.snapshot.markets.filter((entry) => {
11562
+ const { source: _source, sourceType: _sourceType, ...content } = entry;
11563
+ return (0, import_solver_discovery13.stableStringify)(content) === (0, import_solver_discovery13.stableStringify)(projected.market);
11564
+ }) : [];
11565
+ const known = policy?.allowedRegistries === void 0 ? matches[0] : matches.find((entry) => policy.allowedRegistries.includes(entry.source));
11566
+ return [
11567
+ freezeOpenRfqValue({
11568
+ ...projected.market,
11569
+ source: known?.source ?? `nostr:${bid.solverPubkey}`,
11570
+ sourceType: known?.sourceType ?? "local"
11571
+ })
11572
+ ];
11573
+ });
11574
+ const candidates = eligibleMarkets(
11575
+ { markets, ref: { ...route.snapshot.ref, live: true } },
11576
+ route.legs,
11577
+ policy
11578
+ ).filter((candidate) => {
11579
+ if (candidate.backend !== "rfq") return false;
11580
+ const takeSide = candidate.give === "base" ? "quote" : "base";
11581
+ const to = (0, import_solver_discovery13.sideLimits)(candidate.card, takeSide);
11582
+ return to !== null && bid.toAmount >= to.min && bid.toAmount <= to.max;
11583
+ });
11584
+ return { signedCard, candidates };
11585
+ };
11586
+ var hasPausedKnownBidder = async (signer, name, route, network, policy) => {
11587
+ if (!route.snapshot.ref.live || policy?.solverRouting?.preferences === void 0) return false;
11588
+ const candidates = eligibleMarkets(route.snapshot, route.legs).filter(
11589
+ (candidate) => candidate.card.discovery_pubkey === signer && candidate.card.solver === name
11590
+ ).map((candidate) => ({
11591
+ ...candidate,
11592
+ solverId: (0, import_solver_discovery13.solverId)(candidate.card, network),
11593
+ direction: (0, import_solver_discovery13.solverDirectionKey)(candidate.card, candidate.give, network)
11594
+ }));
11595
+ if (candidates.length === 0) return false;
11596
+ const preferences = await policy.solverRouting.preferences({
11597
+ network,
11598
+ direction: candidates[0].direction,
11599
+ candidates
11600
+ });
11601
+ return candidates.some((candidate) => preferences.disabled?.includes(candidate.solverId));
11602
+ };
11603
+
11340
11604
  // src/client/client.ts
11341
11605
  var PREPARATIONS_HELD = 64;
11342
11606
  var mintQuoteId = () => import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(16)));
@@ -11345,6 +11609,18 @@ var createSwapClient = (config) => {
11345
11609
  const operator = config.operator ?? walletOperator(wallet);
11346
11610
  const feed = feedFetch(config.fetchImpl ?? fetch);
11347
11611
  const preparations = /* @__PURE__ */ new Map();
11612
+ const activeQuotes = /* @__PURE__ */ new Set();
11613
+ const activeAuctions = /* @__PURE__ */ new Set();
11614
+ const auctionQuotes = /* @__PURE__ */ new Map();
11615
+ const auctions = /* @__PURE__ */ new Map();
11616
+ const health = config.policy?.solverRouting === void 0 ? void 0 : config.policy.solverRouting.health ?? createSolverHealth();
11617
+ const recordHealth = (candidate, outcome, network) => {
11618
+ try {
11619
+ void health?.record({ network, direction: candidate.direction }, candidate.solverId, outcome).catch(() => {
11620
+ });
11621
+ } catch {
11622
+ }
11623
+ };
11348
11624
  const indexer = walletLockupIndexer(wallet);
11349
11625
  let disposed = false;
11350
11626
  const ensureLive = (method) => {
@@ -11395,25 +11671,409 @@ var createSwapClient = (config) => {
11395
11671
  const remember = (id, preparation) => {
11396
11672
  preparations.set(id, preparation);
11397
11673
  if (preparations.size > PREPARATIONS_HELD) {
11398
- preparations.delete(preparations.keys().next().value);
11674
+ const oldest = preparations.keys().next().value;
11675
+ preparations.delete(oldest);
11676
+ auctionQuotes.delete(oldest);
11677
+ }
11678
+ };
11679
+ const prepare = async (resolvedRoute, market, assetPayment, auction) => {
11680
+ const { corridors } = await resolved();
11681
+ corridors.get(resolvedRoute.legs.give.corridor);
11682
+ corridors.get(resolvedRoute.legs.take.corridor);
11683
+ ensureLive("quote");
11684
+ const quoteId = mintQuoteId();
11685
+ const now = Math.floor(Date.now() / 1e3);
11686
+ const marketRef = marketRefOf(market, resolvedRoute.snapshot.ref);
11687
+ const checkAuctionTtl = () => {
11688
+ if (auction !== void 0)
11689
+ verifyQuoteTtl({
11690
+ quoteId,
11691
+ expiresAt: auction.winner.expiresAt,
11692
+ now: Math.floor(Date.now() / 1e3),
11693
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
11694
+ });
11695
+ };
11696
+ if (market.backend === "feed") {
11697
+ if (assetPayment !== void 0)
11698
+ throw new Error("assetPayment needs a negotiated BTC-to-asset market");
11699
+ const { quote, preparation } = await quoteFromFeed({
11700
+ quoteId,
11701
+ candidate: market,
11702
+ market: marketRef,
11703
+ legs: resolvedRoute.legs,
11704
+ endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11705
+ ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11706
+ feed,
11707
+ ...config.policy === void 0 ? {} : { policy: config.policy },
11708
+ now
11709
+ });
11710
+ ensureLive("quote");
11711
+ const issued = auction === void 0 ? quote : { ...quote, auction };
11712
+ remember(quoteId, preparation);
11713
+ return issued;
11714
+ }
11715
+ const info = await liveOperatorInfo(wallet, { requireLive: true });
11716
+ const rendezvous = market.card.discovery_pubkey;
11717
+ if (rendezvous === void 0) {
11718
+ throw new Error(`card ${market.card.solver} names no discovery key to address`);
11719
+ }
11720
+ checkAuctionTtl();
11721
+ const transport = await (config.transportFor ?? nostrTransportFactory)({
11722
+ card: market.card,
11723
+ solverPubkey: rendezvous,
11724
+ relays: market.card.transports?.nostr?.relays ?? []
11725
+ });
11726
+ let closing;
11727
+ const close = () => closing ??= (async () => {
11728
+ activeQuotes.delete(close);
11729
+ await transport.close().catch(() => {
11730
+ });
11731
+ })();
11732
+ activeQuotes.add(close);
11733
+ try {
11734
+ ensureLive("quote");
11735
+ checkAuctionTtl();
11736
+ const { quote, preparation } = await quoteViaRfq({
11737
+ quoteId,
11738
+ route: resolvedRoute.pair,
11739
+ ...assetPayment === void 0 ? {} : { assetPayment },
11740
+ candidate: market,
11741
+ market: marketRef,
11742
+ legs: resolvedRoute.legs,
11743
+ endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11744
+ ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11745
+ wallet,
11746
+ info,
11747
+ corridors,
11748
+ transport,
11749
+ feed,
11750
+ ...config.policy === void 0 ? {} : { policy: config.policy },
11751
+ now
11752
+ });
11753
+ ensureLive("quote");
11754
+ const issued = auction === void 0 ? quote : { ...quote, auction };
11755
+ remember(quoteId, preparation);
11756
+ return issued;
11757
+ } finally {
11758
+ await close();
11399
11759
  }
11400
11760
  };
11761
+ const withSnapshot = async (input, snapshot) => {
11762
+ const { base, corridors } = await resolved();
11763
+ const fixed = { peek: async () => snapshot, load: async () => snapshot };
11764
+ return resolveRoute(input, {
11765
+ corridors,
11766
+ network: base.networkName,
11767
+ discovery: fixed,
11768
+ ...config.policy === void 0 ? {} : { policy: config.policy },
11769
+ mode: "quote"
11770
+ });
11771
+ };
11401
11772
  const client = {
11773
+ openRfq: async (input, options) => {
11774
+ ensureLive("openRfq");
11775
+ options.signal?.throwIfAborted();
11776
+ if (input.assetPayment !== void 0)
11777
+ throw new UnsupportedRoute("open RFQ does not publish asset-payment terms");
11778
+ const captured = Object.freeze({ ...input });
11779
+ const { base, corridors, discovery } = await resolved();
11780
+ let snapshot;
11781
+ try {
11782
+ snapshot = await discovery.load();
11783
+ } catch (error) {
11784
+ if (!(error instanceof DiscoverySnapshotUnavailable)) throw error;
11785
+ snapshot = {
11786
+ markets: [],
11787
+ ref: { fetchedAt: Date.now(), live: false, source: "local" }
11788
+ };
11789
+ }
11790
+ const routed = await withSnapshot(captured, snapshot);
11791
+ if (routed.pair !== "arkade->arkade" && (!isBtcAsset(routed.give.asset) || !isBtcAsset(routed.take.asset)))
11792
+ throw new UnsupportedRoute("Cross-chain swaps currently support Bitcoin only", {
11793
+ give: routed.legs.give.corridor,
11794
+ take: routed.legs.take.corridor
11795
+ });
11796
+ const canonicalInput = Object.freeze({
11797
+ ...captured,
11798
+ give: routed.give.asset,
11799
+ take: routed.take.asset
11800
+ });
11801
+ if (routed.amount === void 0) throw new Error("open RFQ needs a positive amount");
11802
+ const { quoted, claimFee = 0n } = solverFacingAmount(
11803
+ routed.pair,
11804
+ routed.amount,
11805
+ corridors
11806
+ );
11807
+ const windowMs = options.windowMs ?? config.policy?.rfq?.windowMs ?? 3e3;
11808
+ if (!Number.isSafeInteger(windowMs) || windowMs < 1 || windowMs > 3e4)
11809
+ throw new RangeError("open RFQ windowMs must be between 1 and 30000");
11810
+ const configuredRelays = options.relays ?? config.policy?.rfq?.relays;
11811
+ const discoveredRelays = [
11812
+ ...new Set(
11813
+ snapshot.markets.flatMap((market) => market.transports?.nostr?.relays ?? [])
11814
+ )
11815
+ ];
11816
+ const relays = configuredRelays ?? (discoveredRelays.length === 0 ? DEFAULT_OPEN_RFQ_RELAYS : discoveredRelays.slice(0, 16));
11817
+ const request = {
11818
+ openId: import_base24.hex.encode(crypto.getRandomValues(new Uint8Array(32))),
11819
+ pair: `${routed.give.asset}->${routed.take.asset}`,
11820
+ amountSide: routed.amount.on === "give" ? "from" : "to",
11821
+ amount: quoted.value
11822
+ };
11823
+ const controller = new AbortController();
11824
+ const abort = () => controller.abort(options.signal?.reason);
11825
+ if (options.signal?.aborted) abort();
11826
+ else options.signal?.addEventListener("abort", abort, { once: true });
11827
+ activeAuctions.add(controller);
11828
+ const owned = /* @__PURE__ */ new Map();
11829
+ const filter = async (bids) => {
11830
+ const offers = [];
11831
+ for (const bid of bids) {
11832
+ if (controller.signal.aborted || disposed) return [];
11833
+ const now2 = Math.floor(Date.now() / 1e3);
11834
+ 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)
11835
+ continue;
11836
+ let checked;
11837
+ try {
11838
+ checked = openBidCandidates(bid, routed, base.networkName, config.policy);
11839
+ } catch {
11840
+ continue;
11841
+ }
11842
+ if (checked === void 0 || checked.candidates[0] === void 0) continue;
11843
+ if (await hasPausedKnownBidder(
11844
+ bid.solverPubkey,
11845
+ checked.signedCard.name,
11846
+ routed,
11847
+ base.networkName,
11848
+ config.policy
11849
+ ))
11850
+ continue;
11851
+ const candidateRoute = {
11852
+ ...routed,
11853
+ candidates: checked.candidates,
11854
+ market: chooseMarket(checked.candidates, config.policy)
11855
+ };
11856
+ const eligible = await orderedSolverCandidates(
11857
+ candidateRoute,
11858
+ base.networkName,
11859
+ config.policy,
11860
+ feed.fetch,
11861
+ false,
11862
+ health
11863
+ );
11864
+ const candidate = eligible[0];
11865
+ if (candidate === void 0) continue;
11866
+ const cached = owned.get(bid.id);
11867
+ const offer = cached?.offer ?? Object.freeze({
11868
+ id: bid.id,
11869
+ solverPubkey: bid.solverPubkey,
11870
+ solverName: checked.signedCard.name,
11871
+ market: candidate.card,
11872
+ signedCard: checked.signedCard,
11873
+ fromAmount: bid.fromAmount,
11874
+ toAmount: bid.toAmount - claimFee,
11875
+ expiresAt: bid.validUntil
11876
+ });
11877
+ if (cached === void 0) owned.set(bid.id, { offer, candidate });
11878
+ offers.push(offer);
11879
+ }
11880
+ const now = Math.floor(Date.now() / 1e3);
11881
+ return Object.freeze(offers.filter((offer) => offer.expiresAt > now));
11882
+ };
11883
+ let updates = Promise.resolve();
11884
+ let progressRevision = 0;
11885
+ try {
11886
+ ensureLive("openRfq");
11887
+ const { collectOpenRfqBids: collectOpenRfqBids2 } = await Promise.resolve().then(() => (init_openRfqTransport(), openRfqTransport_exports));
11888
+ ensureLive("openRfq");
11889
+ const bids = await collectOpenRfqBids2(
11890
+ { ...request, bidsUntil: Math.ceil((Date.now() + windowMs) / 1e3) },
11891
+ {
11892
+ secretKey: options.secretKey,
11893
+ relays: [...relays],
11894
+ windowMs,
11895
+ signal: controller.signal,
11896
+ onBids: options.onBids === void 0 ? void 0 : (bids2) => {
11897
+ const revision = ++progressRevision;
11898
+ updates = updates.then(async () => {
11899
+ if (revision !== progressRevision) return;
11900
+ const offers2 = await filter(bids2);
11901
+ if (revision === progressRevision && !controller.signal.aborted && !disposed) {
11902
+ try {
11903
+ options.onBids?.(offers2);
11904
+ } catch {
11905
+ }
11906
+ }
11907
+ });
11908
+ void updates.catch(() => {
11909
+ });
11910
+ }
11911
+ }
11912
+ );
11913
+ await updates;
11914
+ ensureLive("openRfq");
11915
+ if (controller.signal.aborted) throw controller.signal.reason;
11916
+ const offers = await filter(bids);
11917
+ ensureLive("openRfq");
11918
+ if (controller.signal.aborted) throw controller.signal.reason;
11919
+ const auction = Object.freeze({
11920
+ id: request.openId,
11921
+ input: canonicalInput,
11922
+ pair: request.pair,
11923
+ bids: offers,
11924
+ closedAt: Math.floor(Date.now() / 1e3)
11925
+ });
11926
+ for (const session of auctions.keys()) {
11927
+ if (session.bids.every((bid) => bid.expiresAt <= auction.closedAt))
11928
+ auctions.delete(session);
11929
+ }
11930
+ auctions.set(auction, {
11931
+ input: canonicalInput,
11932
+ route: routed,
11933
+ offers: new Map(offers.map((offer) => [offer, owned.get(offer.id).candidate]))
11934
+ });
11935
+ if (auctions.size > 16) auctions.delete(auctions.keys().next().value);
11936
+ return auction;
11937
+ } finally {
11938
+ activeAuctions.delete(controller);
11939
+ options.signal?.removeEventListener("abort", abort);
11940
+ }
11941
+ },
11942
+ quoteBid: async (auction, bid) => {
11943
+ ensureLive("quoteBid");
11944
+ const session = auctions.get(auction);
11945
+ const selected = session?.offers.get(bid);
11946
+ if (session === void 0 || selected === void 0)
11947
+ throw new Error("bid was not issued by this client's auction");
11948
+ const checkExpiry = () => {
11949
+ verifyQuoteTtl({
11950
+ quoteId: bid.id,
11951
+ expiresAt: bid.expiresAt,
11952
+ now: Math.floor(Date.now() / 1e3),
11953
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
11954
+ });
11955
+ };
11956
+ checkExpiry();
11957
+ const snapshot = {
11958
+ markets: [selected.card],
11959
+ ref: { fetchedAt: Date.now(), live: true, source: "injected" }
11960
+ };
11961
+ const routed = await withSnapshot(session.input, snapshot);
11962
+ const { base } = await resolved();
11963
+ if (await hasPausedKnownBidder(
11964
+ bid.solverPubkey,
11965
+ bid.solverName,
11966
+ session.route,
11967
+ base.networkName,
11968
+ config.policy
11969
+ ))
11970
+ throw new UnsupportedRoute("selected bidder is paused");
11971
+ const eligible = await orderedSolverCandidates(
11972
+ routed,
11973
+ base.networkName,
11974
+ config.policy,
11975
+ feed.fetch,
11976
+ false,
11977
+ health
11978
+ );
11979
+ const candidate = eligible[0];
11980
+ if (candidate === void 0 || candidate.card.discovery_pubkey !== bid.solverPubkey)
11981
+ throw new UnsupportedRoute("selected bidder is no longer enabled");
11982
+ const ranked = (offer) => ({
11983
+ bidder: offer.solverPubkey,
11984
+ amount: routed.amount?.on === "give" ? offer.toAmount : offer.fromAmount,
11985
+ amountOn: routed.amount?.on === "give" ? "take" : "give",
11986
+ expiresAt: offer.expiresAt
11987
+ });
11988
+ checkExpiry();
11989
+ let quote;
11990
+ try {
11991
+ quote = await prepare(routed, candidate, void 0, {
11992
+ marketKey: auction.pair,
11993
+ winner: ranked(bid),
11994
+ losers: auction.bids.filter((other) => other !== bid).map(ranked),
11995
+ closedAt: auction.closedAt
11996
+ });
11997
+ ensureLive("quoteBid");
11998
+ checkExpiry();
11999
+ if (quote.give.amount > bid.fromAmount || quote.take.amount < bid.toAmount)
12000
+ throw new QuoteVerificationFailed(
12001
+ "amount",
12002
+ `${bid.fromAmount}/${bid.toAmount}`,
12003
+ `${quote.give.amount}/${quote.take.amount}`
12004
+ );
12005
+ const expiresAt = Math.min(quote.expiresAt, bid.expiresAt);
12006
+ verifyQuoteTtl({
12007
+ quoteId: quote.id,
12008
+ expiresAt,
12009
+ now: Math.floor(Date.now() / 1e3),
12010
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
12011
+ });
12012
+ const bound = freezeOpenRfqValue({
12013
+ ...quote,
12014
+ expiresAt
12015
+ });
12016
+ auctionQuotes.set(bound.id, bound);
12017
+ recordHealth(candidate, "success", base.networkName);
12018
+ return bound;
12019
+ } catch (error) {
12020
+ if (quote !== void 0) preparations.delete(quote.id);
12021
+ if (isSolverReliabilityFailure(error) && bid.expiresAt - Math.floor(Date.now() / 1e3) > (config.policy?.quoteTtlFloorSeconds ?? 0))
12022
+ recordHealth(candidate, "failure", base.networkName);
12023
+ throw error;
12024
+ }
12025
+ },
11402
12026
  resolve: async (input) => {
11403
12027
  ensureLive("resolve");
11404
- return (await route(input, "resolve")).resolution;
12028
+ const routed = await route(input, "resolve");
12029
+ if (config.policy?.solverRouting === void 0) return routed.resolution;
12030
+ const { base } = await resolved();
12031
+ const candidates = await orderedSolverCandidates(
12032
+ routed,
12033
+ base.networkName,
12034
+ config.policy,
12035
+ feed.fetch,
12036
+ false,
12037
+ health
12038
+ );
12039
+ const { market: _market, ...resolution } = routed.resolution;
12040
+ return {
12041
+ ...resolution,
12042
+ eligible: candidates.length,
12043
+ ...candidates[0] === void 0 ? {} : { market: marketRefOf(candidates[0], routed.snapshot.ref) }
12044
+ };
12045
+ },
12046
+ candidates: async (input) => {
12047
+ ensureLive("candidates");
12048
+ const routed = await route(input, "quote");
12049
+ const { base } = await resolved();
12050
+ return orderedSolverCandidates(
12051
+ routed,
12052
+ base.networkName,
12053
+ config.policy,
12054
+ feed.fetch,
12055
+ true,
12056
+ health
12057
+ );
11405
12058
  },
11406
12059
  quote: async (input) => {
11407
12060
  const assetPayment = captureAssetPayment(input.assetPayment);
11408
12061
  ensureLive("quote");
11409
- const { corridors, discovery } = await resolved();
12062
+ const { base, corridors, discovery } = await resolved();
11410
12063
  let resolvedRoute = await route(input, "quote");
11411
- if (resolvedRoute.market?.backend === "rfq" && !resolvedRoute.snapshot.ref.live) {
12064
+ if ((config.policy?.solverRouting === void 0 ? resolvedRoute.market?.backend === "rfq" : resolvedRoute.candidates.some((candidate) => candidate.backend === "rfq")) && !resolvedRoute.snapshot.ref.live) {
11412
12065
  await discovery.load({ refresh: true });
11413
12066
  resolvedRoute = await route(input, "quote");
11414
12067
  }
11415
- const { market } = resolvedRoute;
11416
- if (market === void 0) {
12068
+ const candidates = await orderedSolverCandidates(
12069
+ resolvedRoute,
12070
+ base.networkName,
12071
+ config.policy,
12072
+ feed.fetch,
12073
+ true,
12074
+ health
12075
+ );
12076
+ if (candidates.length === 0) {
11417
12077
  throw new UnsupportedRoute(
11418
12078
  `no market serves ${resolvedRoute.legs.give.corridor}:${resolvedRoute.legs.give.assetId} -> ${resolvedRoute.legs.take.corridor}:${resolvedRoute.legs.take.assetId} on the active discovery snapshot`,
11419
12079
  {
@@ -11422,68 +12082,35 @@ var createSwapClient = (config) => {
11422
12082
  }
11423
12083
  );
11424
12084
  }
11425
- const marketRef = resolvedRoute.resolution.market;
11426
- if (marketRef === void 0 || marketRef.kind !== "card") {
11427
- throw new Error("a resolved market must carry its card's provenance");
11428
- }
11429
12085
  corridors.get(resolvedRoute.legs.give.corridor);
11430
12086
  corridors.get(resolvedRoute.legs.take.corridor);
11431
- const quoteId = mintQuoteId();
11432
- const now = Math.floor(Date.now() / 1e3);
11433
- if (market.backend === "feed") {
11434
- if (assetPayment !== void 0)
11435
- throw new Error("assetPayment needs a negotiated BTC-to-asset market");
11436
- const { quote, preparation } = await quoteFromFeed({
11437
- quoteId,
11438
- candidate: market,
11439
- market: marketRef,
11440
- legs: resolvedRoute.legs,
11441
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11442
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11443
- feed,
11444
- ...config.policy === void 0 ? {} : { policy: config.policy },
11445
- now
11446
- });
11447
- remember(quoteId, preparation);
11448
- return quote;
11449
- }
11450
- const info = await liveOperatorInfo(wallet, { requireLive: true });
11451
- const rendezvous = market.card.discovery_pubkey;
11452
- if (rendezvous === void 0) {
11453
- throw new Error(`card ${market.card.solver} names no discovery key to address`);
11454
- }
11455
- const transport = await (config.transportFor ?? nostrTransportFactory)({
11456
- card: market.card,
11457
- solverPubkey: rendezvous,
11458
- relays: market.card.transports?.nostr?.relays ?? []
11459
- });
11460
- try {
11461
- const { quote, preparation } = await quoteViaRfq({
11462
- quoteId,
11463
- route: resolvedRoute.pair,
11464
- ...assetPayment === void 0 ? {} : { assetPayment },
11465
- candidate: market,
11466
- market: marketRef,
11467
- legs: resolvedRoute.legs,
11468
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
11469
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
11470
- wallet,
11471
- info,
11472
- corridors,
11473
- transport,
11474
- feed,
11475
- ...config.policy === void 0 ? {} : { policy: config.policy },
11476
- now
11477
- });
11478
- remember(quoteId, preparation);
11479
- return quote;
11480
- } finally {
11481
- await transport.close().catch(() => {
11482
- });
12087
+ const failover = config.policy?.solverRouting !== void 0 && config.policy.solverRouting.failover !== false && config.policy.selectMarket === void 0;
12088
+ const attempts = [];
12089
+ const attempted = /* @__PURE__ */ new Set();
12090
+ for (const candidate of failover ? candidates : candidates.slice(0, 1)) {
12091
+ if (attempted.has(candidate.solverId)) continue;
12092
+ attempted.add(candidate.solverId);
12093
+ try {
12094
+ const quote = await prepare(resolvedRoute, candidate, assetPayment);
12095
+ recordHealth(candidate, "success", base.networkName);
12096
+ return quote;
12097
+ } catch (error) {
12098
+ ensureLive("quote");
12099
+ if (isSolverReliabilityFailure(error))
12100
+ recordHealth(candidate, "failure", base.networkName);
12101
+ if (!failover || !canFailoverQuote(error)) throw error;
12102
+ attempts.push({ solverId: candidate.solverId, error });
12103
+ }
11483
12104
  }
12105
+ if (attempts.length === 1) throw attempts[0].error;
12106
+ throw new SolverRoutesUnavailable(attempts);
11484
12107
  },
11485
12108
  accept: async (quote, options) => {
11486
- const validUntil = (0, import_sdk38.captureSendDeadline)(options?.validUntil);
12109
+ const issued = auctionQuotes.get(quote.id);
12110
+ if (issued !== void 0 && issued !== quote)
12111
+ throw new Error("auction quote must be the original issued quote");
12112
+ const requestedDeadline = (0, import_sdk38.captureSendDeadline)(options?.validUntil);
12113
+ const validUntil = issued === void 0 ? requestedDeadline : Math.min(issued.expiresAt, requestedDeadline ?? issued.expiresAt);
11487
12114
  ensureLive("accept");
11488
12115
  const { corridors } = await resolved();
11489
12116
  const drive2 = driving();
@@ -11574,6 +12201,11 @@ var createSwapClient = (config) => {
11574
12201
  [Symbol.asyncDispose]: async () => {
11575
12202
  if (disposed) return;
11576
12203
  disposed = true;
12204
+ for (const controller of activeAuctions)
12205
+ controller.abort(new ClientDisposed("openRfq"));
12206
+ auctions.clear();
12207
+ auctionQuotes.clear();
12208
+ await Promise.allSettled([...activeQuotes].map((close) => close()));
11577
12209
  await drive?.dispose();
11578
12210
  },
11579
12211
  onUpdate: (fn) => {
@@ -12132,6 +12764,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12132
12764
  CovclaimdRevealError,
12133
12765
  DEFAULT_INVOICE_EXPIRY_SECONDS,
12134
12766
  DEFAULT_MAX_REFUND_WINDOW_SECONDS,
12767
+ DEFAULT_OPEN_RFQ_RELAYS,
12135
12768
  DiscoverySnapshotUnavailable,
12136
12769
  EVM_CHAIN,
12137
12770
  FEED_TTL_MS,
@@ -12156,6 +12789,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12156
12789
  REGISTRY_URL,
12157
12790
  RFQ_SWAP_ID_PREFIX,
12158
12791
  SWAP_ERROR_NAMES,
12792
+ SolverRoutesUnavailable,
12159
12793
  SwapDriveRefusedError,
12160
12794
  SwapRefusal,
12161
12795
  UnsupportedRoute,
@@ -12173,12 +12807,14 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12173
12807
  btcAssetPart,
12174
12808
  btcOn,
12175
12809
  buildOfferFillPlan,
12810
+ canFailoverQuote,
12176
12811
  cancelSwap,
12177
12812
  canonicalAssetId,
12178
12813
  cardLegAssetId,
12179
12814
  cardMarketOf,
12180
12815
  chainSourceOver,
12181
12816
  chooseMarket,
12817
+ completedSolverUsage,
12182
12818
  conflictingFields,
12183
12819
  corridorOfRail,
12184
12820
  corridorOutcome,
@@ -12186,6 +12822,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12186
12822
  corridorSet,
12187
12823
  covclaimdClient,
12188
12824
  createNostrTransportFactory,
12825
+ createSolverHealth,
12189
12826
  createSwapClient,
12190
12827
  createSwapDrive,
12191
12828
  decodeBolt11,
@@ -12215,10 +12852,12 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12215
12852
  feedFetch,
12216
12853
  feedSpread,
12217
12854
  formatAssetId,
12855
+ freezeOpenRfqValue,
12218
12856
  fromAtomicDecimal,
12219
12857
  fromRfqAmountSide,
12220
12858
  fundingWasNotSubmitted,
12221
12859
  fundsFromWallet,
12860
+ hasPausedKnownBidder,
12222
12861
  instrumentOf,
12223
12862
  isAddressable,
12224
12863
  isAssetId,
@@ -12228,6 +12867,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12228
12867
  isCardMarket,
12229
12868
  isIndexedNetwork,
12230
12869
  isNetworkRef,
12870
+ isSolverReliabilityFailure,
12231
12871
  isSwapError,
12232
12872
  isUsableCard,
12233
12873
  issuanceOf,
@@ -12245,11 +12885,14 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12245
12885
  offerOutcome,
12246
12886
  offerRecordSource,
12247
12887
  onchainCorridor,
12888
+ openBidCandidates,
12889
+ orderedSolverCandidates,
12248
12890
  pageRfqRecords,
12249
12891
  parseAssetId,
12250
12892
  parseRfqQuote,
12251
12893
  pay,
12252
12894
  publicAssetId,
12895
+ quoteAdvertisedPlan,
12253
12896
  quoteFromFeed,
12254
12897
  quoteIdOfSwapId,
12255
12898
  quoteViaRfq,
@@ -12279,6 +12922,7 @@ var readCommonProfile = (profile, paymentHash, chainId) => {
12279
12922
  sameAsset,
12280
12923
  satsOf,
12281
12924
  scopedToRail,
12925
+ solverFacingAmount,
12282
12926
  splitRecords,
12283
12927
  swapOf,
12284
12928
  swapRecordOf,