@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
@@ -62,7 +62,7 @@ import {
62
62
  undeliveredCarry,
63
63
  walletOperator,
64
64
  watchOfferSwaps
65
- } from "./chunk-2HQZLIVX.js";
65
+ } from "./chunk-JBTU7Y6M.js";
66
66
  import {
67
67
  AcceptConflict,
68
68
  AmbiguousDestination,
@@ -92,7 +92,7 @@ import {
92
92
  verifySendWindow,
93
93
  verifyTaker,
94
94
  verifyingDerivation
95
- } from "./chunk-AUJDREZN.js";
95
+ } from "./chunk-CIDVLDDM.js";
96
96
  import {
97
97
  ARKADE_BTC,
98
98
  ASSET_CARRIER_SATS,
@@ -109,6 +109,9 @@ import {
109
109
  ONCHAIN_DUST_SATS,
110
110
  OfferCovenantMismatchError,
111
111
  RETIRABLE,
112
+ SolverResponseInvalid,
113
+ SolverUnavailable,
114
+ SwapRefusal,
112
115
  arkadeSwapRequest,
113
116
  assembleOfferFill,
114
117
  assertPairLength,
@@ -126,7 +129,6 @@ import {
126
129
  encodeOffer,
127
130
  l1NetworkFromArk,
128
131
  l1ScriptForAddress,
129
- legacySwapPrograms,
130
132
  lightningReceiveRequest,
131
133
  lightningSendRequest,
132
134
  lockupContractParams,
@@ -156,13 +158,15 @@ import {
156
158
  rfqSignerOf,
157
159
  sealClaimPacket,
158
160
  storedOffer,
161
+ swapPrograms,
159
162
  unilateralClaimDelay,
160
163
  verifyOfferAddress,
161
164
  withExitClosure
162
- } from "./chunk-LCO6AJOS.js";
165
+ } from "./chunk-ISKJIONJ.js";
163
166
  import {
164
- ASSET_SWAP_V4
165
- } from "./chunk-6RJVT65W.js";
167
+ ASSET_SWAP_DIRECTED,
168
+ RFQ_CONTRACT_VERSION_UNSUPPORTED
169
+ } from "./chunk-VPVSSBY2.js";
166
170
  import {
167
171
  assertRfqSwapPageFilter,
168
172
  collectAssetSwaps,
@@ -568,6 +572,7 @@ var commonOf = (quote, now) => ({
568
572
  market: quote.market,
569
573
  ...quote.solver === void 0 ? {} : { solver: quote.solver },
570
574
  expiresAt: quote.expiresAt,
575
+ ...quote.auction === void 0 ? {} : { fundingDeadline: quote.expiresAt },
571
576
  ...quote.artifact === void 0 ? {} : { artifact: recordArtifact(quote.artifact) },
572
577
  createdAt: now,
573
578
  updatedAt: now
@@ -754,8 +759,14 @@ var registeredCorridorRecord = async (input, preparation) => {
754
759
  return corridorRecord(input.quote, preparation, input.now);
755
760
  };
756
761
  var fundAndStamp = async (input, record, repository) => {
762
+ if (record.fundingDeadline !== void 0 && (!Number.isSafeInteger(record.fundingDeadline) || record.fundingDeadline <= 0 || record.fundingDeadline > record.expiresAt))
763
+ throw new Error("invalid stored funding deadline");
757
764
  const bounds = storedFundingBounds(record.assetPayment, record.expiresAt);
758
- const cap = input.validUntil === void 0 ? bounds.validUntil : Math.min(input.validUntil, bounds.validUntil ?? record.expiresAt);
765
+ const cap = input.validUntil === void 0 ? record.fundingDeadline === void 0 ? bounds.validUntil : Math.min(record.fundingDeadline, bounds.validUntil ?? record.expiresAt) : Math.min(
766
+ input.validUntil,
767
+ bounds.validUntil ?? record.expiresAt,
768
+ record.fundingDeadline ?? record.expiresAt
769
+ );
759
770
  const validUntil = cap === void 0 ? void 0 : Math.min(cap, record.expiresAt);
760
771
  if (input.firstFundingAttempt && record.assetPayment !== void 0 && validUntil !== void 0 && validUntil < record.assetPayment.validUntil) {
761
772
  record = { ...record, assetPayment: { ...record.assetPayment, validUntil } };
@@ -1480,6 +1491,11 @@ var covenantOf = (swap) => ({
1480
1491
  ...swap.offerHex === void 0 ? {} : { offerHex: swap.offerHex },
1481
1492
  ...swap.binding === void 0 ? {} : { binding: swap.binding }
1482
1493
  });
1494
+ var restoredCovenant = (swap) => {
1495
+ if (swap.binding !== void 0) return { ...covenantOf(swap), binding: swap.binding };
1496
+ if (swap.offerHex !== void 0) return { offerHex: swap.offerHex };
1497
+ throw new Error("this offer swap carries neither a binding nor an offerHex to rebuild from");
1498
+ };
1483
1499
  var offerFactsOf = (record) => ({
1484
1500
  id: record.id,
1485
1501
  coverageId: record.id,
@@ -1556,7 +1572,7 @@ var restoredOfferRecord = (swap, network, now) => {
1556
1572
  market: { kind: "restored", backend: "feed" },
1557
1573
  expiresAt: createdAt,
1558
1574
  status: swap.status,
1559
- ...covenantOf(swap),
1575
+ ...restoredCovenant(swap),
1560
1576
  swapAddress: swap.swapAddress,
1561
1577
  swapPkScript: swap.swapPkScript,
1562
1578
  fundingTxid: swap.fundingTxid,
@@ -1856,8 +1872,8 @@ function withExitV0(program, exit) {
1856
1872
  }
1857
1873
  var V0_TO_V1 = /* @__PURE__ */ new Map();
1858
1874
  for (const [v0, v1] of [
1859
- [swap_want_btc_program_v0_default, legacySwapPrograms.wantBtc],
1860
- [swap_want_asset_program_v0_default, legacySwapPrograms.wantAsset]
1875
+ [swap_want_btc_program_v0_default, swapPrograms.wantBtc],
1876
+ [swap_want_asset_program_v0_default, swapPrograms.wantAsset]
1861
1877
  ]) {
1862
1878
  for (const exit of [void 0, "blocks", "seconds"]) {
1863
1879
  const timelock = exit && { type: exit, value: BigInt(0) };
@@ -3047,20 +3063,32 @@ var feedFetch = (base = fetch) => {
3047
3063
  };
3048
3064
  return { fetch: makeCachedFeedFetch(FEED_TTL_MS, probe), fetchedAt: (url) => at.get(url) };
3049
3065
  };
3066
+ var quoteAdvertisedPlan = (card, options, policy) => quoteOffer(card, options).catch((cause) => {
3067
+ const cancelled = options.signal?.aborted || cause !== null && typeof cause === "object" && "name" in cause && cause.name === "AbortError";
3068
+ if (policy?.solverRouting === void 0 || cancelled) throw cause;
3069
+ throw new SolverUnavailable("The solver's advertised price is unavailable", { cause });
3070
+ });
3050
3071
  var quoteFromFeed = async (input) => {
3051
3072
  const { candidate, amount } = input;
3052
3073
  if (amount === void 0) {
3053
3074
  throw new Error("an asset swap needs an amount and the side it pins");
3054
3075
  }
3055
- const plan = await quoteOffer(candidate.card, {
3056
- give: candidate.give,
3057
- ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
3058
- // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
3059
- // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
3060
- carrierSats: ASSET_CARRIER_SATS,
3061
- ...QUOTE_OPTIONS,
3062
- fetchImpl: input.feed.fetch
3063
- });
3076
+ const plan = await quoteAdvertisedPlan(
3077
+ candidate.card,
3078
+ {
3079
+ give: candidate.give,
3080
+ ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
3081
+ // What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
3082
+ // for it back in a BTC payout, and charges it where the card declares a delivered carrier.
3083
+ carrierSats: ASSET_CARRIER_SATS,
3084
+ ...QUOTE_OPTIONS,
3085
+ fetchImpl: input.feed.fetch
3086
+ },
3087
+ input.policy
3088
+ );
3089
+ if (input.policy?.solverRouting !== void 0 && !plan.limits.withinLimits) {
3090
+ throw new SwapRefusal("amount_out_of_range");
3091
+ }
3064
3092
  verifyPlanLegs(plan, input.legs, candidate.give);
3065
3093
  const expiresAt = feedExpiry(candidate.card, input.feed, input.now);
3066
3094
  verifyQuoteTtl({
@@ -3437,7 +3465,6 @@ import {
3437
3465
  provisionRefundKey,
3438
3466
  toXOnly
3439
3467
  } from "@arkade-os/sdk";
3440
- import { quoteOffer as quoteOffer2 } from "@arkade-os/solver-discovery";
3441
3468
  var lockupOf = (derived) => ({
3442
3469
  address: derived.address,
3443
3470
  script: derived.script,
@@ -3455,6 +3482,16 @@ var covenantInputs = (input) => {
3455
3482
  hrp: network.hrp
3456
3483
  };
3457
3484
  };
3485
+ var parseRfqQuote2 = (wire, policy) => {
3486
+ try {
3487
+ return parseRfqQuote(wire);
3488
+ } catch (cause) {
3489
+ if (policy?.solverRouting !== void 0 && cause instanceof AmountEncodingUnsupported) {
3490
+ throw new SolverResponseInvalid(cause.message, { cause });
3491
+ }
3492
+ throw cause;
3493
+ }
3494
+ };
3458
3495
  var sealingKey = (deps) => {
3459
3496
  const configured = deps.covclaimd?.pubkey;
3460
3497
  if (configured === void 0) return void 0;
@@ -3556,8 +3593,8 @@ var quoteArkadeAsset = async (input) => {
3556
3593
  ASSET_SWAP_CONTRACT_VERSIONS
3557
3594
  );
3558
3595
  verifyPair(wire.pair, pair);
3559
- const parsed = parseRfqQuote(wire);
3560
- const taker = contractVersion === ASSET_SWAP_V4 ? verifyTaker({
3596
+ const parsed = parseRfqQuote2(wire, input.policy);
3597
+ const taker = contractVersion === ASSET_SWAP_DIRECTED ? verifyTaker({
3561
3598
  attested: input.transport.attestedResponder,
3562
3599
  solverPubkey: parsed.solver
3563
3600
  }) : void 0;
@@ -3603,15 +3640,19 @@ var quoteArkadeAsset = async (input) => {
3603
3640
  }
3604
3641
  if (assetPayment !== void 0) deepFreeze(assetPayment);
3605
3642
  const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
3606
- const reference = await quoteOffer2(input.candidate.card, {
3607
- give: input.candidate.give,
3608
- giveAmount: parsed.give,
3609
- // Unconditional: a card charging for the delivered carrier refuses to price without
3610
- // it whichever leg gives, and a BTC deposit funds none of its own to publish.
3611
- carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
3612
- ...QUOTE_OPTIONS,
3613
- fetchImpl: input.feed.fetch
3614
- });
3643
+ const reference = await quoteAdvertisedPlan(
3644
+ input.candidate.card,
3645
+ {
3646
+ give: input.candidate.give,
3647
+ giveAmount: parsed.give,
3648
+ // Unconditional: a card charging for the delivered carrier refuses to price without
3649
+ // it whichever leg gives, and a BTC deposit funds none of its own to publish.
3650
+ carrierSats: carrierSats ?? ASSET_CARRIER_SATS,
3651
+ ...QUOTE_OPTIONS,
3652
+ fetchImpl: input.feed.fetch
3653
+ },
3654
+ input.policy
3655
+ );
3615
3656
  verifyPlanLegs(reference, input.legs, input.candidate.give);
3616
3657
  const terms = offerTermsFromQuote(wire, sides);
3617
3658
  const offer = await deriveOffer(input.wallet, {
@@ -3704,7 +3745,7 @@ var quoteLightningSend = async (input) => {
3704
3745
  })
3705
3746
  );
3706
3747
  verifyPair(wire.pair, pair);
3707
- const parsed = parseRfqQuote(wire);
3748
+ const parsed = parseRfqQuote2(wire, input.policy);
3708
3749
  verifySendInvoice({ invoiced: invoice.amount, give: parsed.give, take: parsed.take });
3709
3750
  const covenant = covenantInputs(input);
3710
3751
  const derived = verifyingDerivation(
@@ -3799,7 +3840,7 @@ var quoteLightningReceive = async (input) => {
3799
3840
  )
3800
3841
  );
3801
3842
  verifyPair(wire.pair, pair);
3802
- const parsed = parseRfqQuote(wire);
3843
+ const parsed = parseRfqQuote2(wire, input.policy);
3803
3844
  verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
3804
3845
  const covenant = covenantInputs(input);
3805
3846
  const derived = verifyingDerivation(
@@ -3873,6 +3914,16 @@ var quoteLightningReceive = async (input) => {
3873
3914
  }
3874
3915
  };
3875
3916
  };
3917
+ var solverFacingAmount = (route, pinned, corridors) => {
3918
+ if (route !== "arkade->onchain" || pinned.on !== "take") return { quoted: pinned };
3919
+ const onchain = corridors.get("onchain").deps;
3920
+ if (onchain.claimFeeRateSatVb === void 0) return { quoted: pinned };
3921
+ const claimFee = claimFeeSats({
3922
+ claimFeeRateSatVb: onchain.claimFeeRateSatVb,
3923
+ claimVsize: onchain.claimVsize
3924
+ });
3925
+ return { quoted: { ...pinned, value: pinned.value + claimFee }, claimFee };
3926
+ };
3876
3927
  var quoteOnchainSend = async (input) => {
3877
3928
  const pinned = pinnedFor(input);
3878
3929
  const destination = input.endpoints.take.instrument;
@@ -3883,12 +3934,7 @@ var quoteOnchainSend = async (input) => {
3883
3934
  const payoutPkScript = l1ScriptForAddress(destination.address, l1Network);
3884
3935
  const pair = rfqPairFor(input.legs.give, input.legs.take);
3885
3936
  const rfqId = newRfqId();
3886
- const onchain = input.corridors.get("onchain").deps;
3887
- const claimFee = pinned.on === "take" && onchain.claimFeeRateSatVb !== void 0 ? claimFeeSats({
3888
- claimFeeRateSatVb: onchain.claimFeeRateSatVb,
3889
- claimVsize: onchain.claimVsize
3890
- }) : void 0;
3891
- const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
3937
+ const { quoted, claimFee } = solverFacingAmount(input.route, pinned, input.corridors);
3892
3938
  const [secrets, payoutKey] = await Promise.all([
3893
3939
  provisionClaimSecret(input.wallet),
3894
3940
  provisionRefundKey(input.wallet)
@@ -3909,7 +3955,7 @@ var quoteOnchainSend = async (input) => {
3909
3955
  )
3910
3956
  );
3911
3957
  verifyPair(wire.pair, pair);
3912
- const parsed = parseRfqQuote(wire);
3958
+ const parsed = parseRfqQuote2(wire, input.policy);
3913
3959
  verifyQuotedAmount({ pair, pinned: quoted, give: parsed.give, take: parsed.take });
3914
3960
  if (claimFee !== void 0) {
3915
3961
  const payout = parsed.take - claimFee;
@@ -4022,7 +4068,7 @@ var quoteOnchainReceive = async (input) => {
4022
4068
  )
4023
4069
  );
4024
4070
  verifyPair(wire.pair, pair);
4025
- const parsed = parseRfqQuote(wire);
4071
+ const parsed = parseRfqQuote2(wire, input.policy);
4026
4072
  verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
4027
4073
  const covenant = covenantInputs(input);
4028
4074
  const derived = verifyingDerivation(
@@ -4202,6 +4248,234 @@ var createNostrTransportFactory = (pool) => {
4202
4248
  };
4203
4249
  var nostrTransportFactory = createNostrTransportFactory();
4204
4250
 
4251
+ // src/client/solverHealth.ts
4252
+ var QUIET_MS = 30 * 6e4;
4253
+ var cooldown = (failures) => failures < 2 ? 0 : Math.min(6e4 * 2 ** Math.min(failures - 2, 4), 15 * 6e4);
4254
+ function createSolverHealth(options = {}) {
4255
+ const now = options.now ?? (() => Date.now());
4256
+ const memory = /* @__PURE__ */ new Map();
4257
+ const keyOf = (scope) => JSON.stringify([scope.network, scope.direction]);
4258
+ const storage = options.storage ?? {
4259
+ load: (scope) => memory.get(keyOf(scope)),
4260
+ save: (scope, records) => {
4261
+ memory.set(keyOf(scope), records);
4262
+ }
4263
+ };
4264
+ const pending = /* @__PURE__ */ new Map();
4265
+ const active = (records, timestamp) => Object.keys(records).filter(
4266
+ (id) => timestamp < records[id].lastFailureAt + cooldown(records[id].failures)
4267
+ );
4268
+ const read = async (scope) => {
4269
+ try {
4270
+ const value = await storage.load(scope);
4271
+ if (!value || typeof value !== "object" || Array.isArray(value)) return {};
4272
+ const timestamp = now();
4273
+ return Object.fromEntries(
4274
+ Object.entries(value).flatMap(([id, entry]) => {
4275
+ if (!entry || typeof entry !== "object") return [];
4276
+ const { failures, lastFailureAt } = entry;
4277
+ 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 }]] : [];
4278
+ })
4279
+ );
4280
+ } catch {
4281
+ return {};
4282
+ }
4283
+ };
4284
+ return {
4285
+ deprioritized: async (scope) => {
4286
+ await pending.get(keyOf(scope));
4287
+ const records = await read(scope);
4288
+ const timestamp = now();
4289
+ return active(records, timestamp);
4290
+ },
4291
+ record: (scope, solverId3, outcome) => {
4292
+ const key = keyOf(scope);
4293
+ const update = (pending.get(key) ?? Promise.resolve()).then(async () => {
4294
+ let records = await read(scope);
4295
+ const before = JSON.stringify(active(records, now()).sort());
4296
+ if (outcome === "success") delete records[solverId3];
4297
+ else
4298
+ records = {
4299
+ ...records,
4300
+ [solverId3]: {
4301
+ failures: Math.min((records[solverId3]?.failures ?? 0) + 1, 32),
4302
+ lastFailureAt: now()
4303
+ }
4304
+ };
4305
+ try {
4306
+ await storage.save(scope, records);
4307
+ if (before !== JSON.stringify(active(records, now()).sort()))
4308
+ options.onChange?.();
4309
+ } catch {
4310
+ }
4311
+ });
4312
+ pending.set(key, update);
4313
+ return update.finally(() => {
4314
+ if (pending.get(key) === update) pending.delete(key);
4315
+ });
4316
+ }
4317
+ };
4318
+ }
4319
+
4320
+ // src/client/solverRouting.ts
4321
+ import {
4322
+ orderSolverMarkets,
4323
+ rankSolverMarkets,
4324
+ solverDirectionKey,
4325
+ solverId
4326
+ } from "@arkade-os/solver-discovery";
4327
+ var orderedSolverCandidates = async (route, network, policy, fetchImpl, estimate = true, health) => {
4328
+ const candidates = (policy?.selectMarket ? route.market === void 0 ? [] : [route.market] : route.candidates).map((candidate) => ({
4329
+ ...candidate,
4330
+ solverId: solverId(candidate.card, network),
4331
+ direction: solverDirectionKey(candidate.card, candidate.give, network)
4332
+ }));
4333
+ if (candidates.length === 0) return [];
4334
+ const preferences = await policy?.solverRouting?.preferences?.({
4335
+ network,
4336
+ direction: candidates[0].direction,
4337
+ candidates
4338
+ });
4339
+ let cooling = [];
4340
+ try {
4341
+ cooling = await health?.deprioritized({ network, direction: candidates[0].direction }) ?? [];
4342
+ } catch {
4343
+ }
4344
+ const options = {
4345
+ network,
4346
+ preferences: {
4347
+ ...preferences,
4348
+ deprioritized: [.../* @__PURE__ */ new Set([...preferences?.deprioritized ?? [], ...cooling])]
4349
+ }
4350
+ };
4351
+ return estimate ? rankSolverMarkets(candidates, {
4352
+ ...options,
4353
+ amount: route.amount === void 0 ? void 0 : { on: route.amount.on, value: route.amount.value },
4354
+ carrierSats: ASSET_CARRIER_SATS,
4355
+ fetchImpl
4356
+ }) : orderSolverMarkets(candidates, options);
4357
+ };
4358
+ var canFailoverQuote = (error) => {
4359
+ if (error instanceof SolverUnavailable || error instanceof QuoteExpired || error instanceof QuoteVerificationFailed) {
4360
+ return true;
4361
+ }
4362
+ if (!(error instanceof SwapRefusal)) return false;
4363
+ if (error.errorCode !== void 0) {
4364
+ return error.errorCode === "amount_side_unsupported" || error.errorCode === "exact_out_unsupported" || error.errorCode === RFQ_CONTRACT_VERSION_UNSUPPORTED;
4365
+ }
4366
+ return [
4367
+ "unsupported_pair",
4368
+ "amount_out_of_range",
4369
+ "exposure_cap",
4370
+ "pricing_unavailable",
4371
+ "rate_limited"
4372
+ ].includes(error.reason);
4373
+ };
4374
+ 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);
4375
+ var SolverRoutesUnavailable = class extends AggregateError {
4376
+ constructor(attempts) {
4377
+ super(
4378
+ attempts.map(({ error }) => error),
4379
+ "No available solver could quote this swap"
4380
+ );
4381
+ this.attempts = attempts;
4382
+ }
4383
+ attempts;
4384
+ name = "SolverRoutesUnavailable";
4385
+ };
4386
+ var completedSolverUsage = (swaps, network, direction) => {
4387
+ const usage = {};
4388
+ const seen = /* @__PURE__ */ new Set();
4389
+ for (const swap of swaps) {
4390
+ if (seen.has(swap.id) || !["filled", "paid", "claimed"].includes(swap.outcome) || swap.market.kind !== "card")
4391
+ continue;
4392
+ if (JSON.stringify([network, swap.route.give.asset, swap.route.take.asset]) !== direction)
4393
+ continue;
4394
+ seen.add(swap.id);
4395
+ const id = solverId(
4396
+ {
4397
+ solver: swap.market.solver,
4398
+ source: swap.market.source,
4399
+ sourceType: swap.market.sourceType,
4400
+ discovery_pubkey: swap.market.discoveryPubkey
4401
+ },
4402
+ network
4403
+ );
4404
+ usage[id] = (usage[id] ?? 0) + 1;
4405
+ }
4406
+ return usage;
4407
+ };
4408
+
4409
+ // src/client/openRfq.ts
4410
+ import {
4411
+ cardErrors,
4412
+ indexMarketFromCard,
4413
+ sideLimits as sideLimits2,
4414
+ stableStringify as stableStringify2,
4415
+ solverDirectionKey as solverDirectionKey2,
4416
+ solverId as solverId2,
4417
+ validateCard,
4418
+ verifyCardSig
4419
+ } from "@arkade-os/solver-discovery";
4420
+ var DEFAULT_OPEN_RFQ_RELAYS = ["wss://relay.damus.io", "wss://nos.lol"];
4421
+ var freezeOpenRfqValue = (value) => {
4422
+ if (value !== null && typeof value === "object") {
4423
+ for (const nested of Object.values(value)) freezeOpenRfqValue(nested);
4424
+ Object.freeze(value);
4425
+ }
4426
+ return value;
4427
+ };
4428
+ var openBidCandidates = (bid, route, network, policy) => {
4429
+ const checked = validateCard(bid.card);
4430
+ if (!checked.ok || checked.value === void 0 || checked.value.discovery_pubkey !== bid.solverPubkey || !verifyCardSig(checked.value) || cardErrors(checked.value, network).length !== 0)
4431
+ return void 0;
4432
+ const signedCard = freezeOpenRfqValue(JSON.parse(JSON.stringify(checked.value)));
4433
+ const markets = (signedCard.markets ?? []).flatMap((market) => {
4434
+ const projected = indexMarketFromCard(signedCard, market);
4435
+ if (!projected.ok) return [];
4436
+ const matches = route.snapshot.ref.live ? route.snapshot.markets.filter((entry) => {
4437
+ const { source: _source, sourceType: _sourceType, ...content } = entry;
4438
+ return stableStringify2(content) === stableStringify2(projected.market);
4439
+ }) : [];
4440
+ const known = policy?.allowedRegistries === void 0 ? matches[0] : matches.find((entry) => policy.allowedRegistries.includes(entry.source));
4441
+ return [
4442
+ freezeOpenRfqValue({
4443
+ ...projected.market,
4444
+ source: known?.source ?? `nostr:${bid.solverPubkey}`,
4445
+ sourceType: known?.sourceType ?? "local"
4446
+ })
4447
+ ];
4448
+ });
4449
+ const candidates = eligibleMarkets(
4450
+ { markets, ref: { ...route.snapshot.ref, live: true } },
4451
+ route.legs,
4452
+ policy
4453
+ ).filter((candidate) => {
4454
+ if (candidate.backend !== "rfq") return false;
4455
+ const takeSide = candidate.give === "base" ? "quote" : "base";
4456
+ const to = sideLimits2(candidate.card, takeSide);
4457
+ return to !== null && bid.toAmount >= to.min && bid.toAmount <= to.max;
4458
+ });
4459
+ return { signedCard, candidates };
4460
+ };
4461
+ var hasPausedKnownBidder = async (signer, name, route, network, policy) => {
4462
+ if (!route.snapshot.ref.live || policy?.solverRouting?.preferences === void 0) return false;
4463
+ const candidates = eligibleMarkets(route.snapshot, route.legs).filter(
4464
+ (candidate) => candidate.card.discovery_pubkey === signer && candidate.card.solver === name
4465
+ ).map((candidate) => ({
4466
+ ...candidate,
4467
+ solverId: solverId2(candidate.card, network),
4468
+ direction: solverDirectionKey2(candidate.card, candidate.give, network)
4469
+ }));
4470
+ if (candidates.length === 0) return false;
4471
+ const preferences = await policy.solverRouting.preferences({
4472
+ network,
4473
+ direction: candidates[0].direction,
4474
+ candidates
4475
+ });
4476
+ return candidates.some((candidate) => preferences.disabled?.includes(candidate.solverId));
4477
+ };
4478
+
4205
4479
  // src/client/client.ts
4206
4480
  import { hex as hex8 } from "@scure/base";
4207
4481
  import { captureSendDeadline } from "@arkade-os/sdk";
@@ -4212,6 +4486,18 @@ var createSwapClient = (config) => {
4212
4486
  const operator = config.operator ?? walletOperator(wallet);
4213
4487
  const feed = feedFetch(config.fetchImpl ?? fetch);
4214
4488
  const preparations = /* @__PURE__ */ new Map();
4489
+ const activeQuotes = /* @__PURE__ */ new Set();
4490
+ const activeAuctions = /* @__PURE__ */ new Set();
4491
+ const auctionQuotes = /* @__PURE__ */ new Map();
4492
+ const auctions = /* @__PURE__ */ new Map();
4493
+ const health = config.policy?.solverRouting === void 0 ? void 0 : config.policy.solverRouting.health ?? createSolverHealth();
4494
+ const recordHealth = (candidate, outcome, network) => {
4495
+ try {
4496
+ void health?.record({ network, direction: candidate.direction }, candidate.solverId, outcome).catch(() => {
4497
+ });
4498
+ } catch {
4499
+ }
4500
+ };
4215
4501
  const indexer = walletLockupIndexer(wallet);
4216
4502
  let disposed = false;
4217
4503
  const ensureLive = (method) => {
@@ -4262,25 +4548,409 @@ var createSwapClient = (config) => {
4262
4548
  const remember = (id, preparation) => {
4263
4549
  preparations.set(id, preparation);
4264
4550
  if (preparations.size > PREPARATIONS_HELD) {
4265
- preparations.delete(preparations.keys().next().value);
4551
+ const oldest = preparations.keys().next().value;
4552
+ preparations.delete(oldest);
4553
+ auctionQuotes.delete(oldest);
4554
+ }
4555
+ };
4556
+ const prepare = async (resolvedRoute, market, assetPayment, auction) => {
4557
+ const { corridors } = await resolved();
4558
+ corridors.get(resolvedRoute.legs.give.corridor);
4559
+ corridors.get(resolvedRoute.legs.take.corridor);
4560
+ ensureLive("quote");
4561
+ const quoteId = mintQuoteId();
4562
+ const now = Math.floor(Date.now() / 1e3);
4563
+ const marketRef = marketRefOf(market, resolvedRoute.snapshot.ref);
4564
+ const checkAuctionTtl = () => {
4565
+ if (auction !== void 0)
4566
+ verifyQuoteTtl({
4567
+ quoteId,
4568
+ expiresAt: auction.winner.expiresAt,
4569
+ now: Math.floor(Date.now() / 1e3),
4570
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
4571
+ });
4572
+ };
4573
+ if (market.backend === "feed") {
4574
+ if (assetPayment !== void 0)
4575
+ throw new Error("assetPayment needs a negotiated BTC-to-asset market");
4576
+ const { quote, preparation } = await quoteFromFeed({
4577
+ quoteId,
4578
+ candidate: market,
4579
+ market: marketRef,
4580
+ legs: resolvedRoute.legs,
4581
+ endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
4582
+ ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
4583
+ feed,
4584
+ ...config.policy === void 0 ? {} : { policy: config.policy },
4585
+ now
4586
+ });
4587
+ ensureLive("quote");
4588
+ const issued = auction === void 0 ? quote : { ...quote, auction };
4589
+ remember(quoteId, preparation);
4590
+ return issued;
4591
+ }
4592
+ const info = await liveOperatorInfo(wallet, { requireLive: true });
4593
+ const rendezvous = market.card.discovery_pubkey;
4594
+ if (rendezvous === void 0) {
4595
+ throw new Error(`card ${market.card.solver} names no discovery key to address`);
4596
+ }
4597
+ checkAuctionTtl();
4598
+ const transport = await (config.transportFor ?? nostrTransportFactory)({
4599
+ card: market.card,
4600
+ solverPubkey: rendezvous,
4601
+ relays: market.card.transports?.nostr?.relays ?? []
4602
+ });
4603
+ let closing;
4604
+ const close = () => closing ??= (async () => {
4605
+ activeQuotes.delete(close);
4606
+ await transport.close().catch(() => {
4607
+ });
4608
+ })();
4609
+ activeQuotes.add(close);
4610
+ try {
4611
+ ensureLive("quote");
4612
+ checkAuctionTtl();
4613
+ const { quote, preparation } = await quoteViaRfq({
4614
+ quoteId,
4615
+ route: resolvedRoute.pair,
4616
+ ...assetPayment === void 0 ? {} : { assetPayment },
4617
+ candidate: market,
4618
+ market: marketRef,
4619
+ legs: resolvedRoute.legs,
4620
+ endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
4621
+ ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
4622
+ wallet,
4623
+ info,
4624
+ corridors,
4625
+ transport,
4626
+ feed,
4627
+ ...config.policy === void 0 ? {} : { policy: config.policy },
4628
+ now
4629
+ });
4630
+ ensureLive("quote");
4631
+ const issued = auction === void 0 ? quote : { ...quote, auction };
4632
+ remember(quoteId, preparation);
4633
+ return issued;
4634
+ } finally {
4635
+ await close();
4266
4636
  }
4267
4637
  };
4638
+ const withSnapshot = async (input, snapshot) => {
4639
+ const { base, corridors } = await resolved();
4640
+ const fixed = { peek: async () => snapshot, load: async () => snapshot };
4641
+ return resolveRoute(input, {
4642
+ corridors,
4643
+ network: base.networkName,
4644
+ discovery: fixed,
4645
+ ...config.policy === void 0 ? {} : { policy: config.policy },
4646
+ mode: "quote"
4647
+ });
4648
+ };
4268
4649
  const client = {
4650
+ openRfq: async (input, options) => {
4651
+ ensureLive("openRfq");
4652
+ options.signal?.throwIfAborted();
4653
+ if (input.assetPayment !== void 0)
4654
+ throw new UnsupportedRoute("open RFQ does not publish asset-payment terms");
4655
+ const captured = Object.freeze({ ...input });
4656
+ const { base, corridors, discovery } = await resolved();
4657
+ let snapshot;
4658
+ try {
4659
+ snapshot = await discovery.load();
4660
+ } catch (error) {
4661
+ if (!(error instanceof DiscoverySnapshotUnavailable)) throw error;
4662
+ snapshot = {
4663
+ markets: [],
4664
+ ref: { fetchedAt: Date.now(), live: false, source: "local" }
4665
+ };
4666
+ }
4667
+ const routed = await withSnapshot(captured, snapshot);
4668
+ if (routed.pair !== "arkade->arkade" && (!isBtcAsset(routed.give.asset) || !isBtcAsset(routed.take.asset)))
4669
+ throw new UnsupportedRoute("Cross-chain swaps currently support Bitcoin only", {
4670
+ give: routed.legs.give.corridor,
4671
+ take: routed.legs.take.corridor
4672
+ });
4673
+ const canonicalInput = Object.freeze({
4674
+ ...captured,
4675
+ give: routed.give.asset,
4676
+ take: routed.take.asset
4677
+ });
4678
+ if (routed.amount === void 0) throw new Error("open RFQ needs a positive amount");
4679
+ const { quoted, claimFee = 0n } = solverFacingAmount(
4680
+ routed.pair,
4681
+ routed.amount,
4682
+ corridors
4683
+ );
4684
+ const windowMs = options.windowMs ?? config.policy?.rfq?.windowMs ?? 3e3;
4685
+ if (!Number.isSafeInteger(windowMs) || windowMs < 1 || windowMs > 3e4)
4686
+ throw new RangeError("open RFQ windowMs must be between 1 and 30000");
4687
+ const configuredRelays = options.relays ?? config.policy?.rfq?.relays;
4688
+ const discoveredRelays = [
4689
+ ...new Set(
4690
+ snapshot.markets.flatMap((market) => market.transports?.nostr?.relays ?? [])
4691
+ )
4692
+ ];
4693
+ const relays = configuredRelays ?? (discoveredRelays.length === 0 ? DEFAULT_OPEN_RFQ_RELAYS : discoveredRelays.slice(0, 16));
4694
+ const request = {
4695
+ openId: hex8.encode(crypto.getRandomValues(new Uint8Array(32))),
4696
+ pair: `${routed.give.asset}->${routed.take.asset}`,
4697
+ amountSide: routed.amount.on === "give" ? "from" : "to",
4698
+ amount: quoted.value
4699
+ };
4700
+ const controller = new AbortController();
4701
+ const abort = () => controller.abort(options.signal?.reason);
4702
+ if (options.signal?.aborted) abort();
4703
+ else options.signal?.addEventListener("abort", abort, { once: true });
4704
+ activeAuctions.add(controller);
4705
+ const owned = /* @__PURE__ */ new Map();
4706
+ const filter = async (bids) => {
4707
+ const offers = [];
4708
+ for (const bid of bids) {
4709
+ if (controller.signal.aborted || disposed) return [];
4710
+ const now2 = Math.floor(Date.now() / 1e3);
4711
+ 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)
4712
+ continue;
4713
+ let checked;
4714
+ try {
4715
+ checked = openBidCandidates(bid, routed, base.networkName, config.policy);
4716
+ } catch {
4717
+ continue;
4718
+ }
4719
+ if (checked === void 0 || checked.candidates[0] === void 0) continue;
4720
+ if (await hasPausedKnownBidder(
4721
+ bid.solverPubkey,
4722
+ checked.signedCard.name,
4723
+ routed,
4724
+ base.networkName,
4725
+ config.policy
4726
+ ))
4727
+ continue;
4728
+ const candidateRoute = {
4729
+ ...routed,
4730
+ candidates: checked.candidates,
4731
+ market: chooseMarket(checked.candidates, config.policy)
4732
+ };
4733
+ const eligible = await orderedSolverCandidates(
4734
+ candidateRoute,
4735
+ base.networkName,
4736
+ config.policy,
4737
+ feed.fetch,
4738
+ false,
4739
+ health
4740
+ );
4741
+ const candidate = eligible[0];
4742
+ if (candidate === void 0) continue;
4743
+ const cached = owned.get(bid.id);
4744
+ const offer = cached?.offer ?? Object.freeze({
4745
+ id: bid.id,
4746
+ solverPubkey: bid.solverPubkey,
4747
+ solverName: checked.signedCard.name,
4748
+ market: candidate.card,
4749
+ signedCard: checked.signedCard,
4750
+ fromAmount: bid.fromAmount,
4751
+ toAmount: bid.toAmount - claimFee,
4752
+ expiresAt: bid.validUntil
4753
+ });
4754
+ if (cached === void 0) owned.set(bid.id, { offer, candidate });
4755
+ offers.push(offer);
4756
+ }
4757
+ const now = Math.floor(Date.now() / 1e3);
4758
+ return Object.freeze(offers.filter((offer) => offer.expiresAt > now));
4759
+ };
4760
+ let updates = Promise.resolve();
4761
+ let progressRevision = 0;
4762
+ try {
4763
+ ensureLive("openRfq");
4764
+ const { collectOpenRfqBids } = await import("./openRfqTransport-MQZ7JWYN.js");
4765
+ ensureLive("openRfq");
4766
+ const bids = await collectOpenRfqBids(
4767
+ { ...request, bidsUntil: Math.ceil((Date.now() + windowMs) / 1e3) },
4768
+ {
4769
+ secretKey: options.secretKey,
4770
+ relays: [...relays],
4771
+ windowMs,
4772
+ signal: controller.signal,
4773
+ onBids: options.onBids === void 0 ? void 0 : (bids2) => {
4774
+ const revision = ++progressRevision;
4775
+ updates = updates.then(async () => {
4776
+ if (revision !== progressRevision) return;
4777
+ const offers2 = await filter(bids2);
4778
+ if (revision === progressRevision && !controller.signal.aborted && !disposed) {
4779
+ try {
4780
+ options.onBids?.(offers2);
4781
+ } catch {
4782
+ }
4783
+ }
4784
+ });
4785
+ void updates.catch(() => {
4786
+ });
4787
+ }
4788
+ }
4789
+ );
4790
+ await updates;
4791
+ ensureLive("openRfq");
4792
+ if (controller.signal.aborted) throw controller.signal.reason;
4793
+ const offers = await filter(bids);
4794
+ ensureLive("openRfq");
4795
+ if (controller.signal.aborted) throw controller.signal.reason;
4796
+ const auction = Object.freeze({
4797
+ id: request.openId,
4798
+ input: canonicalInput,
4799
+ pair: request.pair,
4800
+ bids: offers,
4801
+ closedAt: Math.floor(Date.now() / 1e3)
4802
+ });
4803
+ for (const session of auctions.keys()) {
4804
+ if (session.bids.every((bid) => bid.expiresAt <= auction.closedAt))
4805
+ auctions.delete(session);
4806
+ }
4807
+ auctions.set(auction, {
4808
+ input: canonicalInput,
4809
+ route: routed,
4810
+ offers: new Map(offers.map((offer) => [offer, owned.get(offer.id).candidate]))
4811
+ });
4812
+ if (auctions.size > 16) auctions.delete(auctions.keys().next().value);
4813
+ return auction;
4814
+ } finally {
4815
+ activeAuctions.delete(controller);
4816
+ options.signal?.removeEventListener("abort", abort);
4817
+ }
4818
+ },
4819
+ quoteBid: async (auction, bid) => {
4820
+ ensureLive("quoteBid");
4821
+ const session = auctions.get(auction);
4822
+ const selected = session?.offers.get(bid);
4823
+ if (session === void 0 || selected === void 0)
4824
+ throw new Error("bid was not issued by this client's auction");
4825
+ const checkExpiry = () => {
4826
+ verifyQuoteTtl({
4827
+ quoteId: bid.id,
4828
+ expiresAt: bid.expiresAt,
4829
+ now: Math.floor(Date.now() / 1e3),
4830
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
4831
+ });
4832
+ };
4833
+ checkExpiry();
4834
+ const snapshot = {
4835
+ markets: [selected.card],
4836
+ ref: { fetchedAt: Date.now(), live: true, source: "injected" }
4837
+ };
4838
+ const routed = await withSnapshot(session.input, snapshot);
4839
+ const { base } = await resolved();
4840
+ if (await hasPausedKnownBidder(
4841
+ bid.solverPubkey,
4842
+ bid.solverName,
4843
+ session.route,
4844
+ base.networkName,
4845
+ config.policy
4846
+ ))
4847
+ throw new UnsupportedRoute("selected bidder is paused");
4848
+ const eligible = await orderedSolverCandidates(
4849
+ routed,
4850
+ base.networkName,
4851
+ config.policy,
4852
+ feed.fetch,
4853
+ false,
4854
+ health
4855
+ );
4856
+ const candidate = eligible[0];
4857
+ if (candidate === void 0 || candidate.card.discovery_pubkey !== bid.solverPubkey)
4858
+ throw new UnsupportedRoute("selected bidder is no longer enabled");
4859
+ const ranked = (offer) => ({
4860
+ bidder: offer.solverPubkey,
4861
+ amount: routed.amount?.on === "give" ? offer.toAmount : offer.fromAmount,
4862
+ amountOn: routed.amount?.on === "give" ? "take" : "give",
4863
+ expiresAt: offer.expiresAt
4864
+ });
4865
+ checkExpiry();
4866
+ let quote;
4867
+ try {
4868
+ quote = await prepare(routed, candidate, void 0, {
4869
+ marketKey: auction.pair,
4870
+ winner: ranked(bid),
4871
+ losers: auction.bids.filter((other) => other !== bid).map(ranked),
4872
+ closedAt: auction.closedAt
4873
+ });
4874
+ ensureLive("quoteBid");
4875
+ checkExpiry();
4876
+ if (quote.give.amount > bid.fromAmount || quote.take.amount < bid.toAmount)
4877
+ throw new QuoteVerificationFailed(
4878
+ "amount",
4879
+ `${bid.fromAmount}/${bid.toAmount}`,
4880
+ `${quote.give.amount}/${quote.take.amount}`
4881
+ );
4882
+ const expiresAt = Math.min(quote.expiresAt, bid.expiresAt);
4883
+ verifyQuoteTtl({
4884
+ quoteId: quote.id,
4885
+ expiresAt,
4886
+ now: Math.floor(Date.now() / 1e3),
4887
+ floorSeconds: config.policy?.quoteTtlFloorSeconds
4888
+ });
4889
+ const bound = freezeOpenRfqValue({
4890
+ ...quote,
4891
+ expiresAt
4892
+ });
4893
+ auctionQuotes.set(bound.id, bound);
4894
+ recordHealth(candidate, "success", base.networkName);
4895
+ return bound;
4896
+ } catch (error) {
4897
+ if (quote !== void 0) preparations.delete(quote.id);
4898
+ if (isSolverReliabilityFailure(error) && bid.expiresAt - Math.floor(Date.now() / 1e3) > (config.policy?.quoteTtlFloorSeconds ?? 0))
4899
+ recordHealth(candidate, "failure", base.networkName);
4900
+ throw error;
4901
+ }
4902
+ },
4269
4903
  resolve: async (input) => {
4270
4904
  ensureLive("resolve");
4271
- return (await route(input, "resolve")).resolution;
4905
+ const routed = await route(input, "resolve");
4906
+ if (config.policy?.solverRouting === void 0) return routed.resolution;
4907
+ const { base } = await resolved();
4908
+ const candidates = await orderedSolverCandidates(
4909
+ routed,
4910
+ base.networkName,
4911
+ config.policy,
4912
+ feed.fetch,
4913
+ false,
4914
+ health
4915
+ );
4916
+ const { market: _market, ...resolution } = routed.resolution;
4917
+ return {
4918
+ ...resolution,
4919
+ eligible: candidates.length,
4920
+ ...candidates[0] === void 0 ? {} : { market: marketRefOf(candidates[0], routed.snapshot.ref) }
4921
+ };
4922
+ },
4923
+ candidates: async (input) => {
4924
+ ensureLive("candidates");
4925
+ const routed = await route(input, "quote");
4926
+ const { base } = await resolved();
4927
+ return orderedSolverCandidates(
4928
+ routed,
4929
+ base.networkName,
4930
+ config.policy,
4931
+ feed.fetch,
4932
+ true,
4933
+ health
4934
+ );
4272
4935
  },
4273
4936
  quote: async (input) => {
4274
4937
  const assetPayment = captureAssetPayment(input.assetPayment);
4275
4938
  ensureLive("quote");
4276
- const { corridors, discovery } = await resolved();
4939
+ const { base, corridors, discovery } = await resolved();
4277
4940
  let resolvedRoute = await route(input, "quote");
4278
- if (resolvedRoute.market?.backend === "rfq" && !resolvedRoute.snapshot.ref.live) {
4941
+ if ((config.policy?.solverRouting === void 0 ? resolvedRoute.market?.backend === "rfq" : resolvedRoute.candidates.some((candidate) => candidate.backend === "rfq")) && !resolvedRoute.snapshot.ref.live) {
4279
4942
  await discovery.load({ refresh: true });
4280
4943
  resolvedRoute = await route(input, "quote");
4281
4944
  }
4282
- const { market } = resolvedRoute;
4283
- if (market === void 0) {
4945
+ const candidates = await orderedSolverCandidates(
4946
+ resolvedRoute,
4947
+ base.networkName,
4948
+ config.policy,
4949
+ feed.fetch,
4950
+ true,
4951
+ health
4952
+ );
4953
+ if (candidates.length === 0) {
4284
4954
  throw new UnsupportedRoute(
4285
4955
  `no market serves ${resolvedRoute.legs.give.corridor}:${resolvedRoute.legs.give.assetId} -> ${resolvedRoute.legs.take.corridor}:${resolvedRoute.legs.take.assetId} on the active discovery snapshot`,
4286
4956
  {
@@ -4289,68 +4959,35 @@ var createSwapClient = (config) => {
4289
4959
  }
4290
4960
  );
4291
4961
  }
4292
- const marketRef = resolvedRoute.resolution.market;
4293
- if (marketRef === void 0 || marketRef.kind !== "card") {
4294
- throw new Error("a resolved market must carry its card's provenance");
4295
- }
4296
4962
  corridors.get(resolvedRoute.legs.give.corridor);
4297
4963
  corridors.get(resolvedRoute.legs.take.corridor);
4298
- const quoteId = mintQuoteId();
4299
- const now = Math.floor(Date.now() / 1e3);
4300
- if (market.backend === "feed") {
4301
- if (assetPayment !== void 0)
4302
- throw new Error("assetPayment needs a negotiated BTC-to-asset market");
4303
- const { quote, preparation } = await quoteFromFeed({
4304
- quoteId,
4305
- candidate: market,
4306
- market: marketRef,
4307
- legs: resolvedRoute.legs,
4308
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
4309
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
4310
- feed,
4311
- ...config.policy === void 0 ? {} : { policy: config.policy },
4312
- now
4313
- });
4314
- remember(quoteId, preparation);
4315
- return quote;
4316
- }
4317
- const info = await liveOperatorInfo(wallet, { requireLive: true });
4318
- const rendezvous = market.card.discovery_pubkey;
4319
- if (rendezvous === void 0) {
4320
- throw new Error(`card ${market.card.solver} names no discovery key to address`);
4321
- }
4322
- const transport = await (config.transportFor ?? nostrTransportFactory)({
4323
- card: market.card,
4324
- solverPubkey: rendezvous,
4325
- relays: market.card.transports?.nostr?.relays ?? []
4326
- });
4327
- try {
4328
- const { quote, preparation } = await quoteViaRfq({
4329
- quoteId,
4330
- route: resolvedRoute.pair,
4331
- ...assetPayment === void 0 ? {} : { assetPayment },
4332
- candidate: market,
4333
- market: marketRef,
4334
- legs: resolvedRoute.legs,
4335
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
4336
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
4337
- wallet,
4338
- info,
4339
- corridors,
4340
- transport,
4341
- feed,
4342
- ...config.policy === void 0 ? {} : { policy: config.policy },
4343
- now
4344
- });
4345
- remember(quoteId, preparation);
4346
- return quote;
4347
- } finally {
4348
- await transport.close().catch(() => {
4349
- });
4964
+ const failover = config.policy?.solverRouting !== void 0 && config.policy.solverRouting.failover !== false && config.policy.selectMarket === void 0;
4965
+ const attempts = [];
4966
+ const attempted = /* @__PURE__ */ new Set();
4967
+ for (const candidate of failover ? candidates : candidates.slice(0, 1)) {
4968
+ if (attempted.has(candidate.solverId)) continue;
4969
+ attempted.add(candidate.solverId);
4970
+ try {
4971
+ const quote = await prepare(resolvedRoute, candidate, assetPayment);
4972
+ recordHealth(candidate, "success", base.networkName);
4973
+ return quote;
4974
+ } catch (error) {
4975
+ ensureLive("quote");
4976
+ if (isSolverReliabilityFailure(error))
4977
+ recordHealth(candidate, "failure", base.networkName);
4978
+ if (!failover || !canFailoverQuote(error)) throw error;
4979
+ attempts.push({ solverId: candidate.solverId, error });
4980
+ }
4350
4981
  }
4982
+ if (attempts.length === 1) throw attempts[0].error;
4983
+ throw new SolverRoutesUnavailable(attempts);
4351
4984
  },
4352
4985
  accept: async (quote, options) => {
4353
- const validUntil = captureSendDeadline(options?.validUntil);
4986
+ const issued = auctionQuotes.get(quote.id);
4987
+ if (issued !== void 0 && issued !== quote)
4988
+ throw new Error("auction quote must be the original issued quote");
4989
+ const requestedDeadline = captureSendDeadline(options?.validUntil);
4990
+ const validUntil = issued === void 0 ? requestedDeadline : Math.min(issued.expiresAt, requestedDeadline ?? issued.expiresAt);
4354
4991
  ensureLive("accept");
4355
4992
  const { corridors } = await resolved();
4356
4993
  const drive2 = driving();
@@ -4441,6 +5078,11 @@ var createSwapClient = (config) => {
4441
5078
  [Symbol.asyncDispose]: async () => {
4442
5079
  if (disposed) return;
4443
5080
  disposed = true;
5081
+ for (const controller of activeAuctions)
5082
+ controller.abort(new ClientDisposed("openRfq"));
5083
+ auctions.clear();
5084
+ auctionQuotes.clear();
5085
+ await Promise.allSettled([...activeQuotes].map((close) => close()));
4444
5086
  await drive?.dispose();
4445
5087
  },
4446
5088
  onUpdate: (fn) => {
@@ -4692,6 +5334,7 @@ export {
4692
5334
  resolveRoute,
4693
5335
  FEED_TTL_MS,
4694
5336
  feedFetch,
5337
+ quoteAdvertisedPlan,
4695
5338
  quoteFromFeed,
4696
5339
  feedSpread,
4697
5340
  verifyPlanLegs,
@@ -4716,6 +5359,7 @@ export {
4716
5359
  withCanonicalAmount,
4717
5360
  parseRfqQuote,
4718
5361
  quoteViaRfq,
5362
+ solverFacingAmount,
4719
5363
  enforceFeeCeiling,
4720
5364
  pay,
4721
5365
  receive,
@@ -4723,6 +5367,16 @@ export {
4723
5367
  attesting,
4724
5368
  createNostrTransportFactory,
4725
5369
  nostrTransportFactory,
5370
+ createSolverHealth,
5371
+ orderedSolverCandidates,
5372
+ canFailoverQuote,
5373
+ isSolverReliabilityFailure,
5374
+ SolverRoutesUnavailable,
5375
+ completedSolverUsage,
5376
+ DEFAULT_OPEN_RFQ_RELAYS,
5377
+ freezeOpenRfqValue,
5378
+ openBidCandidates,
5379
+ hasPausedKnownBidder,
4726
5380
  createSwapClient,
4727
5381
  OFFER_FILL_TEMPLATE,
4728
5382
  OFFER_FILL_OWNERS,