@arkade-os/swap 0.1.0-rc.2 → 0.1.0-rc.21

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 (54) hide show
  1. package/README.md +52 -2
  2. package/dist/advanced.cjs +8376 -0
  3. package/dist/advanced.d.cts +550 -0
  4. package/dist/advanced.d.ts +550 -0
  5. package/dist/advanced.js +451 -0
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-HUQQVBC4.js +4262 -0
  8. package/dist/{chunk-EOYGUCDM.js → chunk-ITFCQWPG.js} +755 -1382
  9. package/dist/chunk-PVB7EBAM.js +2517 -0
  10. package/dist/errors-C3h8ANmE.d.ts +1560 -0
  11. package/dist/errors-hm7aqnRM.d.cts +1560 -0
  12. package/dist/index.cjs +4861 -3988
  13. package/dist/index.d.cts +69 -2812
  14. package/dist/index.d.ts +69 -2812
  15. package/dist/index.js +179 -3719
  16. package/dist/lockupContract-5r5RlgOJ.d.cts +137 -0
  17. package/dist/lockupContract-5r5RlgOJ.d.ts +137 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +249 -591
  20. package/dist/node/index.d.ts +249 -591
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +191 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer-Bd9Yvd8Z.d.ts +261 -0
  27. package/dist/offer-F88rtL_I.d.cts +261 -0
  28. package/dist/protocol.cjs +4086 -3706
  29. package/dist/protocol.d.cts +163 -768
  30. package/dist/protocol.d.ts +163 -768
  31. package/dist/protocol.js +190 -173
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BuYWGAKz.d.cts +2261 -0
  41. package/dist/repository-DYnRLPt-.d.ts +2261 -0
  42. package/dist/rfq-60PGpQ_x.d.cts +950 -0
  43. package/dist/rfq-60PGpQ_x.d.ts +950 -0
  44. package/dist/watch-BTyiBLSd.d.ts +74 -0
  45. package/dist/watch-M_KY-5ho.d.cts +74 -0
  46. package/package.json +20 -10
  47. package/dist/chunk-LYCMM3VB.js +0 -1357
  48. package/dist/chunk-U7VWWTL6.js +0 -66
  49. package/dist/repository-_zU9_pM3.d.cts +0 -3426
  50. package/dist/repository-kO95noyv.d.ts +0 -3426
  51. package/dist/rfq-DdBV4JO5.d.cts +0 -1097
  52. package/dist/rfq-DdBV4JO5.d.ts +0 -1097
  53. package/dist/watch-CQqvwgwY.d.cts +0 -96
  54. package/dist/watch-wMbmfN4p.d.ts +0 -96
package/dist/index.d.cts CHANGED
@@ -1,2638 +1,11 @@
1
- import { IWallet, NetworkName, Network, SignerSet, ArkadeInfo, VHTLC, ProvisionedKey, ProvisionedClaimSecret, OnchainProvider, PaymentHandle, PaymentRail, RouterPreferences, Wallet, PaymentRouter, PaymentStatus } from '@arkade-os/sdk';
2
- import { S as SwapOperator, A as AssetSwapRepository, P as Pubkey, R as RfqSwapManagerCallbacks, C as Corridor, I as Instrument, a as RfqSwapActionName, N as NetworkRef, b as AssetId, c as SnapshotRef, M as MarketBackend, d as CardMarketRef, e as MarketRef, f as AssetRef, g as AmountOn, h as Swap, i as CorridorId, j as Artifact, Q as QuoteInput, k as Quote, l as RankedBid, m as SwapUpdate, U as Unsubscribe, n as SwapRecord, o as QuoteId, O as Outcome, L as LockupSpendIndexer, p as SwapContractRegistry, q as ResolvedEndpoint, r as PinnedAmount, s as Rail, t as AssetSwapId, u as SwapFamily, v as RouteResolution, w as RfqSwapRecordStore, x as CorridorSwapRecord, y as OfferSwapRecord, z as RfqSwapRecord, B as AssetSwapStatus, D as Route, E as AssetSwap, F as MarketsCacheEntry } from './repository-_zU9_pM3.cjs';
3
- export { G as ACTIVITY_TOKEN, H as ARKADE_ASSET_NAMESPACE, J as Amount, K as AmountFormatError, T as AmountRefusal, V as AssetIdError, W as AssetIdRefusal, X as AssetNamespace, Y as AssetOn, Z as AssetPart, _ as AssetScale, $ as AtomicDecimal, a0 as AuctionMarketRef, a1 as AuctionProvenance, a2 as BITCOIN_RAILS, a3 as BTC_ASSET_PART, a4 as BitcoinRail, a5 as CORRIDORS, a6 as CORRIDOR_PASS, a7 as CorridorKind, a8 as DepositArtifact, a9 as DisplayDecimal, aa as Endpoint, ab as Ep, ac as Hex, ad as InMemoryAssetSwapRepository, ae as LOCKUP_OWNER, af as OFFER_SWAP_ID_PREFIX, ag as ParsedAssetId, ah as QuoteLeg, ai as RAILS, aj as RFQ_SWAP_ID_PREFIX, ak as RailOf, al as RawState, am as RecordedArtifact, an as RecordedEndpoint, ao as RecordedInstrument, ap as RecordedLeg, aq as RfqAmountSide, ar as SwapRecordCommon, as as arkadeAsset, at as artifactOf, au as assetPartOf, av as assetSwapIdOf, aw as bitcoinNetworkOf, ax as btcOn, ay as corridorOfRail, az as corridorOutcome, aA as decodeRfqAmount, aB as encodeRfqAmount, aC as familyOfSwapId, aD as formatAssetId, aE as fromAtomicDecimal, aF as fromRfqAmountSide, aG as fundsFromWallet, aH as instrumentOf, aI as isAssetId, aJ as isAtomicDecimal, aK as isNetworkRef, aL as issuanceOf, aM as legOf, aN as offerOutcome, aO as parseAssetId, aP as quoteIdOfSwapId, aQ as railOf, aR as railOfCorridor, aS as readsChain, aT as recordArtifact, aU as recordEndpoint, aV as recordInstrument, aW as recordLeg, aX as recordOutcome, aY as sameAsset, aZ as swapOf, a_ as toAtomicDecimal, a$ as toRfqAmountSide, b0 as toSafeNumber } from './repository-_zU9_pM3.cjs';
4
- import { I as InvoiceFacts, C as ChainSource, R as RfqQuote, a as RfqTransport, L as LightningSendContractParams, b as LightningReceiveContractParams, O as OnchainHtlc, c as OnchainHtlcParams, d as OnchainNetwork, S as SwapRefusal } from './rfq-DdBV4JO5.cjs';
5
- import { Network as Network$1, LocalCardInput, DiscoveredMarket, Side, OfferPlan } from '@arkade-os/solver-discovery';
6
- import * as btc from '@scure/btc-signer';
7
- import { O as OfferSpendChanges, a as OfferSwapFacts, b as OfferSwapSource } from './watch-CQqvwgwY.cjs';
8
-
9
- /**
10
- * What a corridor is given, what a caller may replace, and where "overridden to
11
- * nothing" is refused.
12
- *
13
- * §6's rules stand as written; what is added here is a shape, because
14
- * `chain?: ChainSource` cannot tell "absent, use the default" from "disabled,
15
- * deliberately". Every override field is `T | null`: `undefined` takes the
16
- * default, `null` is the refusal, and {@link resolveCorridorDeps} throws
17
- * {@link MissingCorridorDep} naming the dep. It cannot reuse the facade's
18
- * `need()` guard, which tests `value === undefined` and passes a deliberate
19
- * `null` straight through.
20
- *
21
- * Resolution runs when a route first touches a corridor and never at
22
- * construction — a missing dep for a corridor nobody uses is not an error, which
23
- * is `MissingCorridorDep`'s own boundary note and what §6 means by "at quote
24
- * time". The registry beside this file is what memoizes that.
25
- *
26
- * Four keys, not three: §6 gives lightning two overridable deps and the
27
- * covclaimd deployment key is the second. The operator seam and the co-signer
28
- * key are deliberately NOT among them — an override there is a trust anchor §6
29
- * never granted — so the co-signer arrives on {@link CorridorBase} instead, the
30
- * way the facade already threads it.
31
- */
32
-
33
- /**
34
- * The facts every module reads and no caller replaces.
35
- *
36
- * Both wallet and operator seam, and the split is what each is for: the wallet
37
- * answers *who and where* — it is the only thing that can make the live,
38
- * fail-closed info read, since `SwapOperator.getInfo()` takes no options — and
39
- * the operator seam answers *submit and finalize*. Collapsing either into the
40
- * other would delete a seam the unit tests already double.
41
- */
42
- interface CorridorBase {
43
- readonly wallet: IWallet;
44
- readonly operator: SwapOperator;
45
- /** The network the live operator info named. */
46
- readonly networkName: NetworkName;
47
- /** Address parameters for {@link networkName}. */
48
- readonly network: Network;
49
- /** The operator's signer set, for the rotation-aware recipient check. */
50
- readonly signerSet: SignerSet;
51
- /**
52
- * Covenant co-signer override, 33-byte compressed hex.
53
- *
54
- * A dep of the arkade module and not a `CorridorOverrides` key, by the same
55
- * rule that keeps the operator seam out of them. Required on `testnet` and
56
- * `signet`, which `EMULATOR_PUBKEYS` does not pin.
57
- */
58
- readonly emulatorPubkey?: string;
59
- /** For hosts without a global `fetch`, and for tests. */
60
- readonly fetchImpl?: typeof fetch;
61
- /**
62
- * The client's storage, if it was given one.
63
- *
64
- * Here rather than only in the override matrix so the two seams cannot be
65
- * two different objects: a client that takes a repository and an arkade
66
- * override that names one would otherwise write records to one and read the
67
- * markets cache from the other. The override still wins where it is set,
68
- * and a deliberate `null` there still refuses.
69
- */
70
- readonly repository?: AssetSwapRepository;
71
- }
72
- /**
73
- * §6's override matrix, with each field widened to admit the refusal.
74
- *
75
- * An override replaces a dependency inside an implemented corridor. It never
76
- * enables a route, never selects a solver or transport, and never alters
77
- * settlement behaviour — and each one is a named trust anchor: the chain source
78
- * is whose L1 view evidence is reconciled against, the decoder is who validates
79
- * an invoice before display, the covclaimd key is who may open the sealed claim
80
- * packet, the repository is where persist-first lands.
81
- */
82
- interface CorridorOverrides {
83
- arkade?: {
84
- /** Where persist-first lands. Defaults to the client's own
85
- * `repository`, so the two seams are one object; `null` refuses. */
86
- repository?: AssetSwapRepository | null;
87
- };
88
- lightning?: {
89
- /** Default: the package's own {@link decodeBolt11}. */
90
- decode?: ((bolt11: string) => InvoiceFacts) | null;
91
- /** Default: an internal ephemeral self-claim seal, which is what
92
- * `undefined` here means — a deployment key is optional config. */
93
- covclaimd?: {
94
- pubkey: Pubkey;
95
- } | null;
96
- };
97
- onchain?: {
98
- /** Default: `ESPLORA_URL[network]`. The override is the URL, not a
99
- * `ChainSource`: there is no wallet-held provider to substitute. */
100
- chain?: {
101
- esploraUrl: string;
102
- } | null;
103
- /**
104
- * How the trader's L1 claim is built and broadcast. No default: see
105
- * {@link OnchainCorridorDeps.claim}.
106
- */
107
- claim?: OnchainClaim | null;
108
- };
109
- }
110
- /**
111
- * Build and broadcast the L1 claim of an `arkade -> onchain` fill.
112
- *
113
- * The manager's own callback type, so a caller wires `claimOnchainFill` to it
114
- * without a second shape to translate through.
115
- */
116
- type OnchainClaim = RfqSwapManagerCallbacks["claimOnchain"];
117
- /** The arkade corridor's deps. Only the repository is overridable. */
118
- interface ArkadeCorridorDeps {
119
- readonly wallet: IWallet;
120
- readonly operator: SwapOperator;
121
- readonly networkName: NetworkName;
122
- readonly network: Network;
123
- readonly signerSet: SignerSet;
124
- /**
125
- * The pinned per-network co-signer, or the caller's override.
126
- *
127
- * Resolved from the network NAME the wallet reports, never from a key the
128
- * operator reports about itself — `defaultEmulatorPubkey` refuses that
129
- * self-report by name, because the value ends up in a covenant leaf that
130
- * decides who can move the funds.
131
- */
132
- readonly emulatorPubkey: string;
133
- readonly repository: AssetSwapRepository | undefined;
134
- }
135
- /** The lightning corridor's deps. */
136
- interface LightningCorridorDeps {
137
- readonly networkName: NetworkName;
138
- readonly decode: (bolt11: string) => InvoiceFacts;
139
- /** `undefined` is the default seal — an internal ephemeral self-claim key —
140
- * and not a missing dep. */
141
- readonly covclaimd: {
142
- pubkey: Pubkey;
143
- } | undefined;
144
- }
145
- /** The onchain corridor's deps. */
146
- interface OnchainCorridorDeps {
147
- readonly networkName: NetworkName;
148
- readonly chain: ChainSource;
149
- /**
150
- * How the trader's L1 claim is built and broadcast, when a caller supplies
151
- * one.
152
- *
153
- * **Absent by default, and deliberately not defaulted.** `claimOnchainFill`
154
- * needs a fee rate and a signer, both of which are environment-specific and
155
- * neither of which the wallet answers for an L1 key — so there is nothing
156
- * honest to construct here. Without it the drive reports an
157
- * `arkade -> onchain` swap's L1 half blocked, with the reason naming the
158
- * missing callback rather than a counterparty who has done nothing wrong;
159
- * the Arkade lockup keeps being driven and refunded either way.
160
- *
161
- * A dep of the onchain corridor rather than a `SwapClientConfig` field,
162
- * because that is what it is: a route that never touches this corridor
163
- * never resolves it, and a deliberate `null` refuses at the same boundary
164
- * as the chain source.
165
- */
166
- readonly claim?: OnchainClaim;
167
- }
168
- /** Which corridor gets which dep record. */
169
- interface CorridorDepsByCorridor {
170
- arkade: ArkadeCorridorDeps;
171
- lightning: LightningCorridorDeps;
172
- onchain: OnchainCorridorDeps;
173
- }
174
- /** Any corridor's deps. */
175
- type CorridorDeps = CorridorDepsByCorridor[Corridor];
176
- /**
177
- * A corridor's deps, with `undefined` taking the default and `null` refused.
178
- *
179
- * Per corridor, and never for all three at once: resolving a corridor a route
180
- * does not touch is what would turn a deliberate `null` on an unused corridor
181
- * into an error.
182
- */
183
- declare function resolveCorridorDeps<C extends Corridor>(corridor: C, overrides: CorridorOverrides | undefined, base: CorridorBase): CorridorDepsByCorridor[C];
184
- /**
185
- * The operator info read, wrapped so every way it can fail arrives as one
186
- * typed error.
187
- *
188
- * The whole read is wrapped rather than a matched subset of its failures:
189
- * `requireLive` re-throws the provider's raw error unwrapped, which is a
190
- * `FetchError`, a `ProviderUnavailableError`, an `ArkError`, a bare `Error` or a
191
- * `TimeoutError` depending on how the read failed — and across a service-worker
192
- * boundary it is a fresh `Error` whose only branchable identity is `cause.name`.
193
- * A `catch` on a matched set would let exactly those through untyped.
194
- *
195
- * `requireLive` is the caller's, and the two callers want opposite things.
196
- * Every covenant derivation reads live (§6), because a snapshot binds a covenant
197
- * to a signer key the operator may no longer co-sign for. A destination *parse*
198
- * does not derive anything, and the client's `resolve()` promises to answer
199
- * without new disclosure and offline — so it takes the wallet's own fallback
200
- * read, which is live when the operator is reachable and the persisted snapshot
201
- * when it is not.
202
- */
203
- declare const liveArkadeInfo: (wallet: IWallet, opts?: {
204
- requireLive?: boolean;
205
- }) => Promise<ArkadeInfo>;
206
- /**
207
- * The one operator read, made once for all three corridors.
208
- *
209
- * The network narrowing after it is core's own fail-closed one and stays that
210
- * way: an operator that answers with a network name this SDK does not know is
211
- * not unreachable, and resolving it to mainnet parameters is the failure mode
212
- * `getNetwork` exists to prevent.
213
- */
214
- declare const resolveCorridorBase: (input: {
215
- wallet: IWallet;
216
- operator: SwapOperator;
217
- emulatorPubkey?: string;
218
- fetchImpl?: typeof fetch;
219
- /** The client's storage, threaded so the arkade dep can default to it. */
220
- repository?: AssetSwapRepository;
221
- /** Defaults to `true` — see {@link liveArkadeInfo}. */
222
- requireLive?: boolean;
223
- }) => Promise<CorridorBase>;
224
-
225
- /**
226
- * One contract, three implementations.
227
- *
228
- * A corridor module owns four things: its parse claim over destination strings
229
- * and the {@link Instrument} that claim produces, the deps it closes over, the
230
- * observation seams a drive pass reads, and the lockup-owner axis the outcome
231
- * table keys on. Not the table itself — the module declares the axis, and the
232
- * drive layer writes the table against it.
233
- *
234
- * The key is the **corridor**, not v1's `RfqSwap["kind"]`. That union —
235
- * `lightning_send | onchain_send | lightning_receive` — is a route pair, and two
236
- * of its three members are the lightning corridor seen from opposite ends. The
237
- * kind-keyed `RfqCorridorHandler` in `../../rfqCorridor.ts` is untouched and
238
- * stays: `project`/`hydrate` are per-route facts about a *stored record*, and
239
- * folding them in here would make this module own a persistence schema it does
240
- * not decide.
241
- *
242
- * Registration is internal, exactly as `rfqCorridor.ts` argues for its own
243
- * registry: a corridor registered from outside would parse and quote and then
244
- * sit undriven, which is worse than not being registrable at all.
245
- */
246
-
247
- /**
248
- * A module's answer about one destination string. Three outcomes, not two.
249
- *
250
- * "An {@link Instrument} or nothing" cannot say *mine, and wrong* — a `tb1…` on
251
- * a mainnet wallet, another operator's Arkade address, a bolt11 the shape-only
252
- * classifier admits and the decoder then refuses. Collapsing those into *not
253
- * mine* hands a well-formed destination to `UnsupportedRoute`, which names the
254
- * wrong fault, so the refusal is its own arm and the registry turns it into
255
- * `AmbiguousDestination` with the reason attached.
256
- *
257
- * The two object arms are mutually exclusive by construction (`refused?: never`
258
- * / `claimed?: never`), so the registry's count over them is total.
259
- */
260
- type CorridorClaim = {
261
- claimed: Instrument;
262
- refused?: never;
263
- } | {
264
- refused: string;
265
- claimed?: never;
266
- } | undefined;
267
- /** What a drive pass reads. Two, and a solver status read is not one of them. */
268
- type ObservationSeam =
269
- /** Arkade access — `RfqSwapManagerDeps.indexer`. */
270
- "indexer"
271
- /** L1 access — `RfqSwapManagerDeps.chain`. */
272
- | "chain";
273
- /** A covenant a pass reads. */
274
- type CorridorCovenant =
275
- /** The Arkade-side VHTLC every corridor route has exactly one of. */
276
- "arkade_lockup"
277
- /** The L1 HTLC, which only `arkade -> onchain` adds. */
278
- | "onchain_htlc";
279
- /**
280
- * Whose covenant it is — the axis the outcome table keys on.
281
- *
282
- * *Which* lockup a pass reads does not discriminate: every route reads the same
283
- * Arkade lockup and only `arkade -> onchain` reads a second. What inverts is
284
- * ownership, and with it what to do about the deadline: on a give-side leg the
285
- * lockup is the TRADER's and the deadline is a moment to act after, on a
286
- * take-side leg it is the SOLVER's and the deadline is a moment to have acted
287
- * before.
288
- */
289
- type LockupOwner = "trader" | "solver";
290
- /** The deadlines the code already fixes. Margins belong to the drive layer. */
291
- type CorridorDeadline =
292
- /** `RfqSwapCommon.refundLocktime`, on every kind. */
293
- "refund_locktime"
294
- /** `OnchainSendSwap.htlc.refundLocktime`, on `arkade -> onchain` alone. */
295
- | "htlc_refund_locktime";
296
- /** One covenant a pass reads, with its owner and the deadline it runs against. */
297
- interface CorridorLockup {
298
- readonly covenant: CorridorCovenant;
299
- readonly owner: LockupOwner;
300
- readonly deadline: CorridorDeadline;
301
- }
302
- /**
303
- * Which side of a route this corridor is on: the trader gives on it, or takes
304
- * on it. The direction is what inverts every ownership answer below.
305
- */
306
- type RouteSide = "give" | "take";
307
- /** What a drive pass does about a route whose non-arkade leg is this corridor. */
308
- interface CorridorPass {
309
- /** Every covenant the pass reads, in the order it reads them. */
310
- readonly lockups: readonly CorridorLockup[];
311
- /** The actions the manager may execute; a subset of v1's own union. */
312
- readonly actions: readonly RfqSwapActionName[];
313
- /** The seams the pass reads. */
314
- readonly seams: readonly ObservationSeam[];
315
- }
316
- /**
317
- * A corridor's drive facts, per side of the route it serves.
318
- *
319
- * Partial on purpose, and each absence is a decision: `onchain` has no `give`
320
- * entry because `onchain -> arkade` is outside the `Route` union — covering its
321
- * Arkade half alone would produce a manager that silently lets the trader's L1
322
- * refund window pass — and `arkade` has neither, because `arkade -> arkade` is
323
- * an offer covenant with no lockup, no RFQ deadline and no manager action. On
324
- * every corridor route the arkade leg's lockup IS the route's lockup, and it is
325
- * declared once, by the counter-corridor's entry.
326
- */
327
- type CorridorDrive = Partial<Record<RouteSide, CorridorPass>>;
328
- /**
329
- * One corridor.
330
- *
331
- * `deps` are closed over at construction rather than passed per call: the
332
- * network, the operator's signer set and the decoder are all needed at the
333
- * parse, and none of them is in the destination string.
334
- */
335
- interface CorridorModule<D = unknown> {
336
- readonly corridor: Corridor;
337
- /**
338
- * This corridor's claim over `raw` — a bare destination or a BIP21 URI.
339
- *
340
- * **Sync, non-throwing and amount-blind**, and none of the three is this
341
- * module's to reopen: core's rail contract is `match(req, ctx): boolean`,
342
- * "classification only — amount-blind", and core's router calls it bare
343
- * inside `options()`. A plain Arkade destination stays core's own `ark` rail
344
- * and is wrapped by nothing, but one shape across all three beats a second
345
- * one for the corridor that happens not to be wrapped.
346
- */
347
- matches(raw: string): CorridorClaim;
348
- readonly deps: D;
349
- readonly drive: CorridorDrive;
350
- }
351
- /**
352
- * A module's factory, plus the one question that can be asked without deps.
353
- *
354
- * `target` is core's classifier for this corridor's destination class — the
355
- * same one `matches` extracts with, named once so there is no second spelling
356
- * to drift. The registry asks it FIRST, and that is what keeps
357
- * `MissingCorridorDep`'s contract: a bolt11 arriving while the onchain chain
358
- * source is overridden to `null` must not resolve the onchain corridor's deps,
359
- * because a missing dep for a corridor nobody uses is not an error.
360
- */
361
- interface CorridorFactory<D> {
362
- (deps: D): CorridorModule<D>;
363
- /** The destination class this corridor speaks for. Dep-free by
364
- * construction: core's classifiers read the string and nothing else. */
365
- readonly target: (raw: string) => string | undefined;
366
- }
367
-
368
- /** The shipped corridors. Total over `Corridor`, checked at compile time. */
369
- declare const CORRIDOR_FACTORIES: {
370
- readonly arkade: CorridorFactory<ArkadeCorridorDeps>;
371
- readonly lightning: CorridorFactory<LightningCorridorDeps>;
372
- readonly onchain: CorridorFactory<OnchainCorridorDeps>;
373
- };
374
- /** What a destination resolves to: the corridor that claimed it, and how it
375
- * settles. No asset — no destination class carries one, since every Arkade
376
- * asset shares a single address form. */
377
- interface ClaimedDestination {
378
- corridor: Corridor;
379
- instrument: Instrument;
380
- }
381
- /**
382
- * The corridors of one client, with deps resolved on first use.
383
- *
384
- * The laziness is the contract: `resolveCorridorDeps` throws
385
- * `MissingCorridorDep` for a dep overridden to `null`, and a missing dep for a
386
- * corridor nobody uses is not an error.
387
- */
388
- interface CorridorSet {
389
- /** The module for `corridor`, resolving and memoizing its deps on the first
390
- * call. Throws `MissingCorridorDep` when a dep of THIS corridor was
391
- * overridden to nothing. */
392
- get<C extends Corridor>(corridor: C): CorridorModule<CorridorDepsByCorridor[C]>;
393
- /**
394
- * Which corridor claims `raw`, if any.
395
- *
396
- * @throws {AmbiguousDestination} when more than one corridor claims it,
397
- * when the corridor that owns its class refuses it, or when nothing
398
- * classifies it at all.
399
- * @throws {MissingCorridorDep} when the corridor that owns this destination
400
- * has a dep disabled via overrides.
401
- * @returns `undefined` when core classifies the string but no corridor
402
- * serves it — an LNURL today — which becomes `UnsupportedRoute` at route
403
- * resolution rather than a parse failure here.
404
- */
405
- claim(raw: string): ClaimedDestination | undefined;
406
- }
407
- declare const corridorSet: (base: CorridorBase, overrides?: CorridorOverrides) => CorridorSet;
408
-
409
- /**
410
- * The alias layer: public ids down to the vocabulary discovery and RFQ speak.
411
- *
412
- * One way only. A public id is CAIP-19 and carries its rail; discovery keeps
413
- * chain-relative leg keys (a `Corridor` plus an `AssetInfo.id` of `"btc"` or
414
- * the 68-hex identity), and the two are not in bijection — several public ids
415
- * can share one discovery asset. Promising a round trip through it was the
416
- * mistake the earlier Q5 shape made; what does round-trip byte-for-byte is the
417
- * covenant identity itself, which this layer carries verbatim.
418
- *
419
- * Registry ratification of the CAIP form (Q11) does not block any of this: if
420
- * solver-registry adopts it, the table below shortens.
421
- *
422
- * The RFQ wire's `pair` string is not built here. It is `<from-leg>-><to-leg>`,
423
- * byte-compared by the solver and length-capped, and the quote path's request
424
- * builder owns it — a CAIP-19 id would both break the comparison and overrun
425
- * the cap.
426
- */
427
-
428
- /** What discovery names a leg by: its corridor, and the asset id on it. */
429
- interface DiscoveryLeg {
430
- corridor: Corridor;
431
- /** `"btc"`, or the 68-hex Arkade asset identity. */
432
- assetId: string;
433
- }
434
- /**
435
- * A public id down to its discovery leg.
436
- *
437
- * Total over the ids v2 can route and refusing everything else: an `eip155:` id
438
- * is grammar-valid and unserved (§9 is deferred), and a non-BTC asset on
439
- * lightning or L1 names a corridor that carries only BTC.
440
- */
441
- declare const toDiscoveryLeg: (id: AssetId) => DiscoveryLeg;
442
- /** One registry row: what a ticker canonicalizes to. */
443
- interface RegisteredAsset {
444
- id: AssetId;
445
- /** The display ticker. Matched case-insensitively; never an identity. */
446
- ticker: string;
447
- }
448
- /**
449
- * The table caller input is canonicalized against.
450
- *
451
- * Injected rather than fetched: M1 owns no network layer, and the quote path
452
- * fills this from discovery when it has one.
453
- */
454
- interface AssetAliasTable {
455
- /** The wallet's network. An id on any other network is not a candidate. */
456
- network: NetworkRef;
457
- assets: readonly RegisteredAsset[];
458
- }
459
- /**
460
- * The networks discovery publishes a market index for, restated as network
461
- * references.
462
- *
463
- * The two vocabularies are spelled identically and differ only in that core
464
- * carries `testnet` and discovery does not, so the narrowing is set membership
465
- * and nothing more. The `satisfies` is the pin: a rename on either side fails
466
- * to compile here instead of degrading into a silent "no index for this
467
- * network".
468
- */
469
- declare const INDEXED_NETWORKS: readonly ["bitcoin", "signet", "mutinynet", "regtest"];
470
- /**
471
- * Whether a market index can be fetched for `network`.
472
- *
473
- * Partial by construction, and `testnet` is the member outside it: an asset on
474
- * testnet is nameable — `arkade:testnet/slip44:0` is a valid id — there is
475
- * simply no published index to price it against. Which error that becomes is
476
- * the quote path's call, not this layer's.
477
- */
478
- declare const isIndexedNetwork: (network: NetworkRef) => network is Network$1;
479
- /**
480
- * Caller input to a public id: an id passes through validated, a ticker is
481
- * resolved against the table.
482
- *
483
- * Ticker matching is case-insensitive and scoped to the wallet's network, and a
484
- * ticker that matches more than one asset on that network is refused rather
485
- * than guessed — two assets called `USDT` are exactly the case where guessing
486
- * sends the money to the wrong one.
487
- */
488
- declare const canonicalAssetId: (input: string, table: AssetAliasTable) => AssetId;
489
-
490
- /**
491
- * Discovery, and the three states one `DiscoveredMarket[]` used to collapse.
492
- *
493
- * `discoverMarkets` answers one array for three different situations: no
494
- * registry configured (or a network with no published index), a stale cache
495
- * served because every source failed, and a reachable registry that lists
496
- * nothing. They are not the same answer and they do not deserve the same
497
- * behaviour, so this module separates them and carries the difference on the
498
- * snapshot rather than in a comment:
499
- *
500
- * - **No data at all** — no registry, an unindexed network, or an unreachable
501
- * one with nothing cached — is {@link DiscoverySnapshotUnavailable}. There is
502
- * no route state for "resolved against nothing".
503
- * - **A stale cache** resolves and prices, and is marked stale. It is still a
504
- * snapshot; what it cannot do is supply the key an addressed RFQ's responder
505
- * is checked against (see `live` below).
506
- * - **Reachable and empty** is a snapshot like any other, with no markets in it.
507
- * The route resolves; `quote()` is where an empty eligible set becomes
508
- * `UnsupportedRoute`.
509
- *
510
- * It wraps discovery rather than `discoverMarkets`, and the reason is the same
511
- * separation: `discover()` reports per-source outcomes and `discoverMarkets`
512
- * spends them on the way out. `discoverMarkets` itself is untouched — the
513
- * wallet's own wrapper around it keeps working — and the cache is the same
514
- * entry under the same key, so a v1 read warms a v2 quote and back.
515
- *
516
- * The cache is also a trust boundary. `isMarketShaped` revalidates four fields
517
- * on read and trusts the rest, `discovery_pubkey` and `transports` included, and
518
- * those two are precisely what an addressed RFQ addresses itself to. So a cached
519
- * card is revalidated here against every field this client depends on, and a
520
- * snapshot that came out of the cache is marked `live: false` — the responder
521
- * check refuses to pin against cache content whatever its shape.
522
- */
523
-
524
- /** Where the client's market data comes from. Every field is optional: a
525
- * client with none of it resolves against nothing and says so. */
526
- interface DiscoveryConfig {
527
- /**
528
- * The network's solver registry index URL.
529
- *
530
- * Config rather than an inference: nothing in the wallet, the operator info
531
- * or this package names a registry, so "inferred from the wallet" reaches
532
- * only as far as the network. Absent means no source at all, which is the
533
- * unavailable case and not an empty market set.
534
- */
535
- readonly registryUrl?: string;
536
- /** Locally pinned solver cards, merged with the registry's. */
537
- readonly localCards?: readonly LocalCardInput[];
538
- /**
539
- * Markets to resolve against without touching the network.
540
- *
541
- * Caller-supplied and therefore trusted the way config is: an injected
542
- * snapshot can pin an RFQ responder, where a cached one cannot.
543
- */
544
- readonly snapshot?: readonly DiscoveredMarket[];
545
- /** Overrides the network the wallet reports. For tests and multi-network hosts. */
546
- readonly network?: Network$1;
547
- readonly fetchImpl?: typeof fetch;
548
- /** Receives discovery warnings (stale index, skipped cards, …). */
549
- readonly logger?: (...args: unknown[]) => void;
550
- }
551
- /** A market set, and where it came from. */
552
- interface DiscoverySnapshot {
553
- readonly markets: readonly DiscoveredMarket[];
554
- readonly ref: SnapshotRef;
555
- }
556
- interface DiscoveryIndex {
557
- /**
558
- * The snapshot in hand, without touching the network — an injected one, one
559
- * this client already loaded, or the repository's cache.
560
- *
561
- * @throws {DiscoverySnapshotUnavailable} when there is none.
562
- */
563
- peek(): Promise<DiscoverySnapshot>;
564
- /**
565
- * A snapshot, fetching when there is none in hand or when asked to refresh.
566
- *
567
- * @throws {DiscoverySnapshotUnavailable} when the fetch leaves it with
568
- * nothing either.
569
- */
570
- load(opts?: {
571
- refresh?: boolean;
572
- }): Promise<DiscoverySnapshot>;
573
- }
574
- /**
575
- * Whether a card read back out of the cache is one this client may act on.
576
- *
577
- * Wider than `isMarketShaped`, and deliberately so: that predicate guards the
578
- * v1 pricing path, which reads asset ids and decimals, where this one guards a
579
- * path that also addresses a solver over a rendezvous the card names. A stored
580
- * entry outlives the schema that wrote it AND the storage it sits in, so every
581
- * field the client depends on is re-checked rather than four of them.
582
- */
583
- declare const isUsableCard: (value: unknown) => value is DiscoveredMarket;
584
- interface DiscoveryIndexInput {
585
- /** The network the wallet reported. */
586
- readonly network: NetworkName;
587
- readonly config?: DiscoveryConfig;
588
- /** Backs the shared markets cache. Without one, every load hits the registry. */
589
- readonly repository?: AssetSwapRepository;
590
- }
591
- /**
592
- * One client's view of the market index.
593
- *
594
- * Holds at most one snapshot and hands the same one back until it ages out or a
595
- * caller asks for a refresh, so a `resolve()` and the `quote()` after it agree
596
- * on what the market was — two loads a second apart returning different cards
597
- * would make the resolution the caller vetoed a different one from the quote
598
- * they got.
599
- */
600
- declare const discoveryIndex: (input: DiscoveryIndexInput) => DiscoveryIndex;
601
-
602
- /**
603
- * Market resolution: `(give.asset, take.asset, corridors)` to the card that
604
- * prices the swap, and the provenance that card leaves on the quote.
605
- *
606
- * The lookup itself is discovery's — `selectMarkets` matches a leg pair with
607
- * both corridors, arkade defaulted on either side — and this module supplies
608
- * the three things around it that the client cannot borrow: the policy filters
609
- * that run before disclosure, the canonical market key derived under the
610
- * protocol's own leg order rather than the card's, and the addressability check
611
- * that keeps an unreachable corridor card out of the candidate set instead of
612
- * failing at the transport.
613
- *
614
- * `findMarket` is not what this calls, and the reason is the candidate set:
615
- * that helper answers with the single best market of one orientation, and
616
- * `policy.selectMarket` is defined over every eligible card. Both orientations
617
- * are tried here for the same reason it tries them — a registry may publish
618
- * either leg as base.
619
- */
620
-
621
- /** One card that can price this route, with what the route needs read off it. */
622
- interface MarketCandidate {
623
- readonly card: DiscoveredMarket;
624
- /** Which side of the card the trader gives; the other side is received. */
625
- readonly give: Side;
626
- /** Which backend the card selects. The card decides, never the client. */
627
- readonly backend: MarketBackend;
628
- /** The canonical market key — see {@link marketKeyOf}. */
629
- readonly key: string;
630
- }
631
- /**
632
- * The market's canonical key, `<corridor>:<id>/<corridor>:<id>`, under
633
- * rfq-protocol.md §2's leg order: when exactly one leg is arkade it comes
634
- * first; when both or neither are, the legs sort lexicographically.
635
- *
636
- * Derived here, from the card in hand, rather than taken from `marketPairKey`,
637
- * which emits the card's own base/quote order. The two agree for every card the
638
- * registry's reducer validated — it enforces the arkade-as-base half — and
639
- * disagree for a card published outside it, which is where the miss would be
640
- * silent: both sides of a published negotiation derive this key independently
641
- * and subscribe by it, so a key one character apart is not an error either side
642
- * can report, it is a request nobody answers.
643
- */
644
- declare const marketKeyOf: (card: DiscoveredMarket) => string;
645
- /**
646
- * Whether a corridor card can actually be addressed.
647
- *
648
- * A corridor market is negotiated per trade over the rendezvous the card names,
649
- * so a card missing its key or its relays prices nothing, whatever its feed
650
- * says. Dropping it here rather than at the transport is what keeps "no market
651
- * serves this pair" one answer instead of two: an unaddressable card in the
652
- * candidate set would be selected, disclose nothing, and fail as a transport
653
- * error that reads like an outage.
654
- */
655
- declare const isAddressable: (card: DiscoveredMarket) => boolean;
656
- /** Which backend a card selects — the card decides it, never the client. */
657
- declare const marketBackendOf: (card: DiscoveredMarket) => MarketBackend;
658
- /**
659
- * The cards on a snapshot this client may act on at all, before any pair is
660
- * named: the policy's registry allowlist, then addressability.
661
- *
662
- * Shared by the routing read and `markets()`, so the escape hatch cannot offer
663
- * a card the quote path would then refuse.
664
- */
665
- declare const usableMarkets: (snapshot: DiscoverySnapshot, policy?: SwapPolicy) => DiscoveredMarket[];
666
- /**
667
- * Every card on the snapshot that serves this leg pair, best-ranked first,
668
- * after policy.
669
- *
670
- * The allowed-registry filter runs first and matches `source` exactly. It is
671
- * `source` and not `discovery_pubkey` because the latter is the field a cached
672
- * card carries unvalidated: filtering trust on untrusted content would give the
673
- * allowlist the shape of a check and none of the effect.
674
- */
675
- declare const eligibleMarkets: (snapshot: DiscoverySnapshot, legs: {
676
- give: DiscoveryLeg;
677
- take: DiscoveryLeg;
678
- }, policy?: SwapPolicy) => MarketCandidate[];
679
- /**
680
- * The card that prices this swap: the best-ranked candidate, or the one the
681
- * application's policy chose instead.
682
- *
683
- * A veto — `undefined` from `selectMarket` — is not an error here. It empties
684
- * the eligible set, and an empty set is a route no market serves on this
685
- * snapshot, which is one condition with one answer whether it was emptied by
686
- * the registry, by the allowlist or by the application.
687
- */
688
- declare const chooseMarket: (candidates: readonly MarketCandidate[], policy?: SwapPolicy) => MarketCandidate | undefined;
689
- /** The provenance a candidate leaves on every quote it prices. */
690
- declare const marketRefOf: (candidate: MarketCandidate, snapshot: SnapshotRef) => CardMarketRef;
691
- /** A card's own provenance — the same fields {@link marketRefOf} writes, read
692
- * off the card rather than off a routed candidate. */
693
- declare const cardMarketOf: (card: DiscoveredMarket, snapshot: SnapshotRef, key: string, backend: MarketBackend) => CardMarketRef;
694
- /** Narrow a `MarketRef` to the card arm — the only one minted today. */
695
- declare const isCardMarket: (market: MarketRef) => market is CardMarketRef;
696
- /**
697
- * A market as the v2 client publishes it — one shape with {@link CardMarketRef},
698
- * the type `Quote.market` already points at.
699
- *
700
- * `markets()` is the escape hatch, and its return is deliberately the same card
701
- * a quote cites: a caller picking a market for a custom `quote()` reads the same
702
- * provenance the quote will carry, key for key and snapshot for snapshot.
703
- * Discovery's own `DiscoveredMarket` never crosses the v2 root — its asset ids
704
- * (`"btc"` or a 68-hex string) and its display `pair` are exactly the vocabulary
705
- * the alias layer exists to keep off it. The honest limit of the escape hatch
706
- * is that it carries no discovery asset id; an integrator needing the native
707
- * cards keeps the package's own discovery reader below the public surface.
708
- */
709
- type Market = CardMarketRef;
710
-
711
- /**
712
- * The three product-facing verbs, and the one thing they add.
713
- *
714
- * `pay`, `receive` and `exchange` compile a {@link QuoteInput}, call `quote`,
715
- * check `quote.fee` against a ceiling and call `accept`. Everything they call
716
- * was built in M3–M6; what they add is the ceiling — and what they subtract is
717
- * vocabulary. A product integrating payments never sees the words route,
718
- * corridor, market or quote.
719
- *
720
- * The verbs are deliberately thin, and one asymmetry is the reason they exist
721
- * at all: `receive` is what makes the artifact's exposure order unlosable. It
722
- * returns only after `accept()` has persisted, so a caller cannot show a payer
723
- * an invoice whose claim secret is still in memory — the ordering M4 bought,
724
- * stated in a signature.
725
- *
726
- * §5's fourth row — `pay` to a plain Arkade address — is not a swap and must
727
- * not become one. It delegates: same asset, same rail, rate 1, nothing swapped.
728
- * See {@link PayResult}.
729
- */
730
-
731
- /**
732
- * A fee ceiling: an amount, and the asset it is denominated in.
733
- *
734
- * The asset is not ceremony. M3/D denominates the fee on the give leg on
735
- * corridor routes and on the take leg on asset swaps, so a bare `bigint` names
736
- * no asset — and on `exchange` the caller cannot know which leg carries it
737
- * before quoting. A ceiling whose asset is not the fee's is a refusal rather
738
- * than a conversion: the SDK holds no rate, and inventing one to compare two
739
- * numbers is how a ceiling silently stops being one.
740
- *
741
- * The same shape on every verb and on {@link SwapPolicy.maxFee}, so the call
742
- * ceiling and the policy ceiling it is taken against are comparable without a
743
- * translation.
744
- */
745
- interface FeeCeiling {
746
- readonly amount: bigint;
747
- readonly asset: AssetId;
748
- }
749
- /**
750
- * What `pay` takes beside the destination.
751
- *
752
- * `amount` is what the *recipient* gets, and it is omitted exactly when the
753
- * destination pins it — an amount-bearing bolt11 does, and passing one beside
754
- * it is `AmountMismatch`. §9.5's EVM destinations grow a required `take` here;
755
- * they are deferred, so it is not declared yet.
756
- */
757
- interface PayOptions {
758
- /** Atomic units delivered to the recipient. Omitted when an invoice pins it. */
759
- readonly amount?: bigint;
760
- readonly maxFee?: FeeCeiling;
761
- }
762
- /**
763
- * What `receive` takes.
764
- *
765
- * `via` names the corridor because a receive has no instrument to parse — the
766
- * instrument *is* the artifact the solver mints, and it does not exist until
767
- * the quote comes back. `asset` is reserved for §9.5's EVM form: on the
768
- * implemented corridors the corridor carries BTC and nothing else, so naming
769
- * one would be a fact with nothing to disagree with.
770
- */
771
- interface ReceiveOptions {
772
- /** Atomic units the trader receives. */
773
- readonly amount: bigint;
774
- readonly via: CorridorId;
775
- /** §9.5, reserved: the asset arriving, where a corridor carries more than one. */
776
- readonly asset?: AssetRef;
777
- readonly maxFee?: FeeCeiling;
778
- }
779
- /**
780
- * What `exchange` takes: {@link QuoteInput} minus `to` and `via`, plus the
781
- * ceiling.
782
- *
783
- * Thin because `exchange` hides the two-step, not the vocabulary — an asset
784
- * swap names both assets by construction, and there is nothing left to infer.
785
- */
786
- interface ExchangeOptions {
787
- readonly give?: AssetRef;
788
- readonly take?: AssetRef;
789
- readonly amount?: bigint;
790
- readonly amountOn?: AmountOn;
791
- readonly maxFee?: FeeCeiling;
792
- }
793
- /**
794
- * What `receive` answers with: a {@link Swap} whose artifact is a guarantee
795
- * rather than a maybe.
796
- *
797
- * An intersection rather than a parallel record, because that is where the
798
- * guarantee gets *stated*: `Quote.artifact` and `Swap.artifact` are optional —
799
- * three of the four routes have nothing a counterparty must see — and a receive
800
- * always has one. Narrowing the field on the base type is not open to an
801
- * intersection, so this is the shape that says it.
802
- */
803
- type ReceiveRequest = Swap & {
804
- readonly artifact: Artifact;
805
- };
806
- /**
807
- * What `pay` answers with.
808
- *
809
- * Two arms, because §5's four destination rows are not four swaps. A bolt11 and
810
- * a `bc1…` cross a corridor and produce a {@link Swap}; a plain Arkade address
811
- * is a plain Arkade payment and produces a txid and no swap id. Manufacturing a
812
- * `Swap` for the second would be a swap record for something nothing swapped —
813
- * same asset, same rail, rate 1 — and rejecting it instead would put a branch in
814
- * every product's one pay box rather than once here.
815
- */
816
- type PayResult = {
817
- readonly kind: "swap";
818
- readonly swap: Swap;
819
- } | {
820
- readonly kind: "payment";
821
- readonly txid: string;
822
- };
823
- /** What a verb needs from the client it hangs off. */
824
- interface VerbDeps {
825
- readonly wallet: IWallet;
826
- quote(input: QuoteInput): Promise<Quote>;
827
- accept(quote: Quote): Promise<Swap>;
828
- /** {@link SwapPolicy.maxFee}, when the client was configured with one. */
829
- readonly policyMaxFee?: FeeCeiling;
830
- }
831
- /**
832
- * The effective ceiling, and the refusal when the quote is over it.
833
- *
834
- * The effective ceiling is the **minimum** of the call's and the policy's: a
835
- * policy ceiling a call could raise would be decorative, and a call ceiling a
836
- * policy could raise would make the tighter of two explicit instructions lose.
837
- * Either may be absent; both absent means no ceiling, which is the documented
838
- * default and not a zero.
839
- *
840
- * A ceiling denominated in another asset is refused as caller input rather than
841
- * as a member of §7's taxonomy: the taxonomy's members are conditions of the
842
- * swap, and this is a field naming the wrong unit — the same rule that keeps
843
- * "amount needs amountOn" a plain `Error`.
844
- *
845
- * @throws {MaxFeeExceeded} when `quote.fee` is over the effective ceiling —
846
- * between `quote` and `accept`, so nothing was funded.
847
- */
848
- declare const enforceFeeCeiling: (quote: Quote, call: FeeCeiling | undefined, policy: FeeCeiling | undefined) => void;
849
- /**
850
- * Pay a destination: a bolt11, a `bc1…`, or a plain Arkade address.
851
- *
852
- * The Arkade arm is checked first and against core's own parse, so a bare
853
- * address and a BIP21 `ark=` param behave identically here and in the `ark`
854
- * rail — one classification, not two that can drift. It settles through
855
- * `wallet.send`, which is what the `ark` rail settles through: fee 0 and
856
- * receiver-exact for free, with nothing to quote and nothing to persist.
857
- */
858
- declare const pay: (deps: VerbDeps, destination: string, options?: PayOptions) => Promise<PayResult>;
859
- /**
860
- * Ask for an incoming payment over `via`, and get back the artifact to show.
861
- *
862
- * The artifact is non-optional on the return type and the assertion behind it
863
- * is real: a receive route has one by construction, and a client that answered
864
- * without one has failed rather than answered.
865
- */
866
- declare const receive: (deps: VerbDeps, options: ReceiveOptions) => Promise<ReceiveRequest>;
867
- /** Swap one Arkade asset for another. */
868
- declare const exchange: (deps: VerbDeps, options: ExchangeOptions) => Promise<Swap>;
869
-
870
- /**
871
- * Application policy: the vetoes and floors a client applies before it
872
- * discloses anything, plus the two names §10 reserved.
873
- *
874
- * Six members touch the quote path — four active here, two inert — and
875
- * {@link SwapPolicy.drive} is the lifecycle's. `maxFee` landed with M7, the
876
- * milestone that can enforce it: a ceiling declared before a layer applies it
877
- * is a field, not a policy.
878
- *
879
- * Every active member has the same shape of purpose: it runs BEFORE the RFQ
880
- * round trip that discloses an invoice or an amount. A policy that could only
881
- * reject a quote after it arrived would be a preference, not a policy.
882
- */
883
-
884
- /**
885
- * A published-RFQ auction's parameters (§10, Q9).
886
- *
887
- * Reserved and inert: nothing reads it, and its shape is sized against ts-sdk
888
- * #777's draft so the name cannot be occupied by something narrower in the
889
- * meantime — a bid window, the relay set unioned across the pair's cards, and
890
- * the fresh per-open transport key rfq-protocol.md §4.6 recommends for
891
- * unlinkability.
892
- */
893
- interface RfqAuctionPolicy {
894
- /** How long to hold the bid window open, in ms. */
895
- readonly windowMs: number;
896
- /** Relays to publish the open request on. Unioned across the pair's cards. */
897
- readonly relays?: readonly string[];
898
- /** §4.6's SHOULD: a fresh transport key per open, so bids are unlinkable. */
899
- readonly freshTransportKey?: boolean;
900
- }
901
- /**
902
- * How much the client drives on its own.
903
- *
904
- * The split is the one `RfqSwapManager` already draws between reading its
905
- * records and driving them: `restoreFromRepository` is documented as NOT part
906
- * of `start()`, precisely so a consumer can look at its swaps without being
907
- * made to move money to do it. This promotes that to configuration.
908
- */
909
- type DriveMode =
910
- /**
911
- * Default. Construction's restore-read arms the drive when it finds live
912
- * work, and the first `accept()` arms it when it does not.
913
- */
914
- "auto"
915
- /** Restores, then waits: no timer and no stream until `start()`. */
916
- | "manual"
917
- /**
918
- * Restores and reports, and never actuates. It discovers nothing new — no
919
- * pass runs, so no claim, no refund and no recovery round — which is what
920
- * keeps `swaps()` and `onUpdate` honest for an inspection-only consumer.
921
- */
922
- | "readonly";
923
- interface SwapPolicy {
924
- /**
925
- * How much the client drives on its own. Default `"auto"`.
926
- *
927
- * Policy rather than a `SwapClientConfig` field for the same reason the
928
- * other five members are: it is a caller's decision about behaviour, not a
929
- * dependency the client needs to work.
930
- */
931
- readonly drive?: DriveMode;
932
- /**
933
- * The most a swap may cost, as a standing instruction.
934
- *
935
- * The verbs take the **minimum** of this and their own `maxFee`, so a call
936
- * can only tighten it: a policy ceiling a call could raise would be
937
- * decorative. Enforced between `quote` and `accept` and nowhere else —
938
- * before funding, which is the only place a ceiling is worth anything.
939
- *
940
- * Denominated, like every ceiling on this surface: the fee sits on the give
941
- * leg on corridor routes and the take leg on asset swaps, so a bare number
942
- * would name no asset. A ceiling whose asset is not the quoted fee's is
943
- * refused rather than converted.
944
- */
945
- readonly maxFee?: FeeCeiling;
946
- /**
947
- * The last word on which market prices a swap.
948
- *
949
- * Called with every eligible candidate, best-ranked first, and answering
950
- * `undefined` vetoes them all — which lands where an empty candidate set
951
- * lands, as `UnsupportedRoute`, and not as a seventeenth error member. The
952
- * answer must be one of the candidates: a card from somewhere else has not
953
- * been through the pair, corridor and addressability checks that produced
954
- * this list.
955
- */
956
- readonly selectMarket?: (candidates: readonly MarketCandidate[]) => MarketCandidate | undefined;
957
- /**
958
- * The registries whose cards may price a swap, matched exactly against
959
- * `DiscoveredMarket.source`.
960
- *
961
- * On `source` and never on `discovery_pubkey`, which is the field the cache
962
- * does not revalidate on read: filtering an allowlist on unvalidated cache
963
- * content would reintroduce the hole the allowlist exists to close. Exact
964
- * URLs, not hostnames or origins — and a locally pinned card follows
965
- * whatever label discovery recorded for it, which is a path, not a URL.
966
- *
967
- * Absent means every source. An allowlist that empties the candidate set is
968
- * the empty-eligible-set case, not a refusal of its own.
969
- */
970
- readonly allowedRegistries?: readonly string[];
971
- /**
972
- * The least validity a quote may arrive with, in seconds.
973
- *
974
- * One layer above the wire's own refusal of a quote already past
975
- * `valid_until`: a quote with four seconds left is not expired and is not
976
- * usable either, and the caller is the only one who knows how long their
977
- * flow takes between seeing terms and accepting them. Under the floor is
978
- * `QuoteExpired`, thrown from `quote()` rather than handed back to fail at
979
- * `accept()`.
980
- */
981
- readonly quoteTtlFloorSeconds?: number;
982
- /**
983
- * §10, reserved and inert: the published-RFQ auction's parameters.
984
- */
985
- readonly rfq?: RfqAuctionPolicy;
986
- /**
987
- * §10, reserved and inert: which bid to close a published auction with.
988
- */
989
- readonly selectBid?: (bids: readonly RankedBid[]) => RankedBid | undefined;
990
- }
991
-
992
- /**
993
- * The drive: what makes the v2 client self-driving, and the one place the two
994
- * families' state becomes one {@link Outcome}.
995
- *
996
- * Two drivers sit behind one lifecycle — `RfqSwapManager` for the corridor
997
- * swaps and `watchOfferSwaps` for the offers — and they stay separate here, as
998
- * they are in v1: liveness is their union, arming is one idempotent call over
999
- * both, and `stop()` pays the asymmetry the facade already pays (the manager
1000
- * stays reusable, the watcher is a one-shot unsubscribe rebuilt on the next
1001
- * start).
1002
- *
1003
- * **The poll loop is the correctness mechanism.** The contract-event
1004
- * subscription only makes a pass run early, and that pass re-reads the lockup
1005
- * exactly as the timer's does, so a missed, duplicated, reordered or forged
1006
- * event costs or saves latency and nothing else. Stated as an invariant here
1007
- * because it is what makes dropping the stream on `stop()` safe: NO OUTCOME IS
1008
- * EVER WRITTEN FROM AN EVENT PAYLOAD.
1009
- *
1010
- * **No backoff, deliberately.** The poll interval is already the retry cadence
1011
- * and `REFUND_MTP_LAG_SECONDS` already the deadline, so a backoff on a money
1012
- * push could only push a retry past the deadline it exists to beat.
1013
- *
1014
- * What this module does NOT do is decide anything about a swap from the
1015
- * solver's word: there is no `RfqTransport` here, exactly as there is none in
1016
- * the manager.
1017
- */
1018
-
1019
- /** Why the drive refused. */
1020
- type DriveRefusal =
1021
- /** `drive: "readonly"` actuates nothing, and this asked it to. */
1022
- "readonly"
1023
- /** No record with this id, here or in the repository. */
1024
- | "unknown-swap"
1025
- /** The lockup's `refundLocktime` has not matured, so a recovery round
1026
- * including it would be rejected — and `recoverVtxos` settles EVERY
1027
- * recoverable output in one batch, so an early attempt can fail unrelated
1028
- * outputs with it. */
1029
- | "refund-window-open"
1030
- /** Nothing at this swap has been swept, so there is nothing to recover.
1031
- * The two `needs_counterparty` sources of `needs_recovery` land here. */
1032
- | "nothing-swept"
1033
- /** This wallet exposes no VTXO manager, so no recovery round can be run. */
1034
- | "no-recovery-support";
1035
- /**
1036
- * The drive declined, with the reason as a value.
1037
- *
1038
- * Not a member of §7's sixteen, and it keeps the `Error` suffix to say so —
1039
- * `errors.ts`'s own naming rule. What it replaces is `recoverVtxos`'s bare
1040
- * `Error("No recoverable VTXOs found")`, which is outside the taxonomy and
1041
- * carries nothing a caller can branch on.
1042
- *
1043
- * M6's error-coverage pass ruled it a documented NON-member: no §7 member names
1044
- * a drive-refusal condition, so none absorbs these four, and the suffix rule is
1045
- * working as intended rather than marking a loose end.
1046
- */
1047
- declare class SwapDriveRefusedError extends Error {
1048
- readonly reason: DriveRefusal;
1049
- readonly swapId?: QuoteId | undefined;
1050
- readonly name = "SwapDriveRefusedError";
1051
- constructor(reason: DriveRefusal, detail: string, swapId?: QuoteId | undefined);
1052
- }
1053
- /** What {@link SwapDrive.recover} did. */
1054
- interface RecoveryResult {
1055
- /**
1056
- * Whether THIS swap's outpoints were included in the round.
1057
- *
1058
- * A settlement txid is not success: `recoverVtxos` takes no outpoints — it
1059
- * reads the whole wallet, drops what `unspendableNow` refuses, then prices
1060
- * and caps the rest highest-value-first with the overflow deferred to the
1061
- * next cycle. So the named lockup is re-read afterwards and this is that
1062
- * read's answer.
1063
- */
1064
- readonly recovered: boolean;
1065
- /** The settlement the round produced, when one ran. */
1066
- readonly txid?: string;
1067
- /** The swap, after the immediate pass that followed. */
1068
- readonly swap: Swap;
1069
- }
1070
- interface SwapDriveConfig {
1071
- readonly wallet: IWallet;
1072
- readonly operator: SwapOperator;
1073
- /** No repository is legal and shipped: `ready` resolves, nothing arms, and
1074
- * `accept()` keeps its own refusal. */
1075
- readonly repository?: AssetSwapRepository;
1076
- /**
1077
- * The client's corridors, for the two deps a drive pass needs and the quote
1078
- * path does not: the L1 chain source and the L1 claim callback. Read
1079
- * through the set so resolution stays lazy — a client whose `onchain` deps
1080
- * are deliberately `null` and which never drives an `arkade -> onchain`
1081
- * swap never resolves them, which is what `MissingCorridorDep`'s boundary
1082
- * note requires.
1083
- */
1084
- readonly corridors: () => Promise<CorridorSet>;
1085
- readonly mode?: DriveMode;
1086
- readonly pollIntervalMs?: number;
1087
- /** Unix seconds. Injected for tests. */
1088
- readonly now?: () => number;
1089
- /** The Arkade observation seam. Defaults to the wallet's own reader; taken
1090
- * as an input so a drive test can double one without a wallet behind it. */
1091
- readonly indexer: LockupSpendIndexer;
1092
- /** Defaults to `wallet.getContractManager()`, resolved on first arm. */
1093
- readonly contracts?: SwapContractRegistry;
1094
- }
1095
- interface SwapDrive {
1096
- /**
1097
- * The restore-read, and — when it armed — the first pass after it.
1098
- *
1099
- * Lazy: construction stays inert and the first await is what drives it.
1100
- * Rejects only when the repository itself is unreadable, per Q3; a corrupt
1101
- * record is filtered and every per-swap problem is an outcome.
1102
- */
1103
- readonly ready: Promise<void>;
1104
- start(): Promise<void>;
1105
- stop(): Promise<void>;
1106
- dispose(): Promise<void>;
1107
- onUpdate(fn: (update: SwapUpdate) => void): Unsubscribe;
1108
- /**
1109
- * Take a freshly persisted record into the drive and answer with its public
1110
- * form.
1111
- *
1112
- * Synchronous by design: `accept()` returns once the record is durable and
1113
- * does NOT await the first pass, so the registration this schedules runs
1114
- * behind the return.
1115
- */
1116
- adopt(record: SwapRecord): Swap;
1117
- /** The public form of a record this drive holds. */
1118
- swap(id: QuoteId): Swap | undefined;
1119
- /** The outcome a record would report with no live state behind it. */
1120
- outcomeOf(record: SwapRecord): Outcome;
1121
- /**
1122
- * Take a record written OUTSIDE the drive's own loops — today, the
1123
- * awaited cancel call — into the registry, and emit through `onUpdate`.
1124
- *
1125
- * Cancel writes at two edges, the gate and the settlement, and the
1126
- * delivery channel for both is this registry: replay plus the
1127
- * `(swapId, outcome)` key absorb a later pass over the same record, whether
1128
- * or not the drive armed.
1129
- */
1130
- ingest(record: SwapRecord): void;
1131
- recover(id: QuoteId): Promise<RecoveryResult>;
1132
- /** Everything this drive has in flight — registrations and money pushes.
1133
- * Exposed so a test can be deterministic and so dispose can drain. */
1134
- idle(): Promise<void>;
1135
- }
1136
- /**
1137
- * Whether a stored blob is a record this drive can read at all.
1138
- *
1139
- * The v1 store's rule, applied to the v2 keyspace: a corrupt row is filtered
1140
- * rather than fatal, because one unreadable record must not stop a client from
1141
- * driving every other swap it holds. Everything checked here is something the
1142
- * drive dereferences unconditionally.
1143
- */
1144
- declare const readableRecord: (record: SwapRecord) => boolean;
1145
- declare const createSwapDrive: (config: SwapDriveConfig) => SwapDrive;
1146
-
1147
- /**
1148
- * The feed-priced backend: an arkade-to-arkade asset swap, priced from the
1149
- * card's own feed with no round trip to anybody.
1150
- *
1151
- * The market picks the backend — a card with both legs on arkade prices from
1152
- * its feed, and one with a leg off it is negotiated over RFQ — so nothing here
1153
- * is a client switch. What this module owns are the two things the offer path
1154
- * has never had an answer for.
1155
- *
1156
- * **The margin.** `quoteOffer` defaults `safetyBps` to 50, the package exports
1157
- * `QUOTE_OPTIONS = { safetyBps: 0 }` and the wallet passes it, and the v1 facade
1158
- * passes neither — so one card priced two different offers depending on which
1159
- * path built it. `Quote.fee` is one number with one definition, so this picks:
1160
- * the package constant, no cushion. A safety margin is a pre-payment against
1161
- * price drift between quote and fill, and that drift is the solver's risk to
1162
- * manage rather than the trader's to prepay; charging it would also inflate the
1163
- * fee a verb's `maxFee` ceiling is compared against, which is a ceiling on what
1164
- * the trader pays, not on what the client padded.
1165
- *
1166
- * **The expiry.** §3.1 makes `expiresAt` non-optional and a feed-priced quote
1167
- * has no `valid_until` to inherit — `OfferPlan` carries no expiry at all. The
1168
- * only staleness bound in the whole path is the feed cache's TTL, so that is
1169
- * what the quote's life is minted from: the moment the feed value was actually
1170
- * read from upstream, plus the TTL. A quote whose price is thirty seconds old
1171
- * expires when the price does, which is the honest bound; the policy floor then
1172
- * applies to a number the client chose rather than one a solver asserted.
1173
- */
1174
-
1175
- /**
1176
- * How long a feed value is reused, and therefore how long a quote priced from
1177
- * one lives.
1178
- *
1179
- * The same number in both roles on purpose: a quote is only as fresh as the
1180
- * price behind it, and two TTLs would let a quote outlive the value it quoted.
1181
- */
1182
- declare const FEED_TTL_MS = 30000;
1183
- /** A fetch that caches feed values, and remembers when each was really read. */
1184
- interface FeedFetch {
1185
- readonly fetch: typeof fetch;
1186
- /** Unix ms the value behind `url` was last read from upstream. */
1187
- fetchedAt(url: string): number | undefined;
1188
- }
1189
- /**
1190
- * The client's feed fetcher.
1191
- *
1192
- * The upstream probe sits INSIDE the cache rather than around it, which is what
1193
- * makes `fetchedAt` mean what it says: the cache calls through only on a miss,
1194
- * so the recorded time is the age of the value that was served, not the time it
1195
- * was served. Wrapping the other way would restamp every cache hit as fresh and
1196
- * hand back a quote whose expiry outlived its price.
1197
- */
1198
- declare const feedFetch: (base?: typeof fetch) => FeedFetch;
1199
- /** What `accept()` (M4) needs back from a feed-priced quote. */
1200
- interface OfferPreparation {
1201
- readonly backend: "feed";
1202
- readonly card: DiscoveredMarket;
1203
- /** The plan the offer covenant is built from: both amounts and both assets. */
1204
- readonly plan: OfferPlan;
1205
- readonly give: Side;
1206
- }
1207
- interface FeedQuoteInput {
1208
- readonly quoteId: QuoteId;
1209
- readonly candidate: MarketCandidate;
1210
- readonly market: CardMarketRef;
1211
- readonly legs: {
1212
- readonly give: DiscoveryLeg;
1213
- readonly take: DiscoveryLeg;
1214
- };
1215
- readonly endpoints: {
1216
- readonly give: ResolvedEndpoint;
1217
- readonly take: ResolvedEndpoint;
1218
- };
1219
- readonly amount?: PinnedAmount;
1220
- readonly feed: FeedFetch;
1221
- readonly policy?: SwapPolicy;
1222
- /** Unix seconds. */
1223
- readonly now: number;
1224
- }
1225
- declare const quoteFromFeed: (input: FeedQuoteInput) => Promise<{
1226
- quote: Quote;
1227
- preparation: OfferPreparation;
1228
- }>;
1229
-
1230
- /**
1231
- * The RFQ wire adapter: the pair string, the amount encoding, and the parse
1232
- * that turns a solver's reply into values the rest of the client can compare.
1233
- *
1234
- * **The pair string is wire, and it is owned here.** Two different fields are
1235
- * called `pair`. The registry's is a display label (`BTC/lightning:BTC`); the
1236
- * wire's is `<from-leg>-><to-leg>` over legs of `<corridor>:<asset>`, where the
1237
- * asset is a registered ticker or, on arkade only, the 68-hex asset id. Solvers
1238
- * compare it byte for byte and cap it at 158 characters, so a CAIP-19 id cannot
1239
- * go on it — it would fail the comparison and overrun the cap. The public alias
1240
- * layer therefore stops one level above this, at a corridor and a discovery
1241
- * asset id, and the string is built here, one layer below anything public.
1242
- *
1243
- * **Amounts go out as canonical decimal strings, unconditionally.** The solver
1244
- * accepts them on all four corridor request schemas today, and emitting a string
1245
- * is never a narrowing — where a JSON number past 2^53 has already lost the
1246
- * amount before anyone can check it. The receipt side takes either form through
1247
- * M1's adapter, a number only while it is a non-negative safe integer, which is
1248
- * why `AmountEncodingUnsupported` is a receipt-side error here: it fires on the
1249
- * way in, before verification, never on the way out.
1250
- */
1251
-
1252
- /**
1253
- * One leg, as the wire spells it.
1254
- *
1255
- * The BTC legs come from `rfq.ts`'s own constants rather than being rebuilt out
1256
- * of the corridor name and a ticker: the solver compares these byte for byte,
1257
- * and a second construction of `arkade:BTC` is a second thing that can drift.
1258
- * An arkade-issued asset is the id verbatim, lowercase — which is what makes the
1259
- * discovery leg the right input, since the alias layer already lowercased it.
1260
- */
1261
- declare const rfqLeg: (leg: DiscoveryLeg) => string;
1262
- /**
1263
- * The directional pair for a route, checked against the wire's length cap.
1264
- *
1265
- * Direction is give-to-take and never the card's base/quote order: the card
1266
- * describes a market, the pair describes this trade.
1267
- */
1268
- declare const rfqPairFor: (give: DiscoveryLeg, take: DiscoveryLeg) => string;
1269
- /**
1270
- * A request payload with its amount in the wire's canonical string encoding.
1271
- *
1272
- * The payload itself is built by `rfq.ts`'s own request builders — they are the
1273
- * schema, and a second copy of the profile field names is a second thing to keep
1274
- * in step with a `.strict()` remote schema. What this adds is the one field
1275
- * whose encoding M3 decided: `amount`, out as a decimal string on every corridor
1276
- * that carries one.
1277
- */
1278
- declare const withCanonicalAmount: (payload: Record<string, unknown>, amount: bigint) => Record<string, unknown>;
1279
- /**
1280
- * A solver's quote, with the fields the client compares against pulled out and
1281
- * decoded once.
1282
- *
1283
- * The amounts are the point: `RfqQuote` declares them `number`, the migration
1284
- * has them arriving as either, and every check downstream is a comparison. One
1285
- * decode at the boundary is what keeps a string amount from failing a `!==`
1286
- * against a bigint three layers down and reading as a solver mismatch.
1287
- */
1288
- interface ParsedRfqQuote {
1289
- /** The reply verbatim, for the record and for anything not decoded here. */
1290
- readonly raw: RfqQuote;
1291
- readonly rfqId: string;
1292
- readonly pair: string;
1293
- /** `from_amount`: what the trader gives, atomic units of the give leg. */
1294
- readonly give: bigint;
1295
- /** `to_amount`: what the trader takes. */
1296
- readonly take: bigint;
1297
- /** The covenant role key the quote commits to. */
1298
- readonly solver: Pubkey;
1299
- readonly validUntil: number;
1300
- /** Optional on the wire; every corridor route refuses a quote without it. */
1301
- readonly refundLocktime?: number;
1302
- readonly profile: Record<string, unknown>;
1303
- }
1304
- /** Read a solver's quote, decoding both amounts. */
1305
- declare const parseRfqQuote: (quote: RfqQuote) => ParsedRfqQuote;
1306
-
1307
- /**
1308
- * The transport seam, and the attestation the responder check runs on.
1309
- *
1310
- * §4 makes the transport an inference: the card names the rendezvous — its
1311
- * relays and its discovery key — and the client opens it, where v1 had the
1312
- * caller hand-build `nostrRfqTransport({relays, solverPubkey})`. What the card
1313
- * cannot say is whether the transport that gets built authenticates anybody, and
1314
- * that is the whole of G2: the production Nostr transport does, through its
1315
- * `authors` filter and the per-solver conversation key, while `httpTransport`
1316
- * and `relayTransport` attest nobody and route on `rfq_id` alone.
1317
- *
1318
- * So the attestation is a property of the transport and is declared by whoever
1319
- * built it. A transport that filters replies to one author sets
1320
- * {@link AttestingRfqTransport.attestedResponder} to that author; anything else
1321
- * leaves it absent and fails the `responder` check. That is deliberately the
1322
- * fail-closed default: the two dev transports do not authenticate, and a client
1323
- * that quoted over them as though they did would be verifying nothing while
1324
- * reporting that it verified four things.
1325
- *
1326
- * The default factory reaches `./nostr` through a dynamic import, which is what
1327
- * keeps `nostr-tools` an optional peer dependency: a consumer doing HTTP-only
1328
- * swaps against its own transport never loads the subpath, exactly as importing
1329
- * it directly never loaded it for them.
1330
- */
1331
-
1332
- /**
1333
- * An {@link RfqTransport} that can prove who answered.
1334
- *
1335
- * Optional rather than required, because the interface has three
1336
- * implementations today and only one of them can fill it. Absent means "attests
1337
- * nobody", which the responder check refuses — a transport is never trusted for
1338
- * a claim it did not make.
1339
- */
1340
- interface AttestingRfqTransport extends RfqTransport {
1341
- /**
1342
- * The key every reply on this transport is proven to come from.
1343
- *
1344
- * x-only hex, and it must be a claim the transport ENFORCES — a filter that
1345
- * only this author's events satisfy, plus a conversation key only this
1346
- * author can decrypt to. Setting it without that is worse than leaving it
1347
- * absent: it turns a check into a decoration.
1348
- */
1349
- readonly attestedResponder?: Pubkey;
1350
- }
1351
- /** What a factory is told about the card it is opening a rendezvous to. */
1352
- interface RfqRendezvous {
1353
- readonly card: DiscoveredMarket;
1354
- /** The card's `discovery_pubkey` — who the request is addressed to. */
1355
- readonly solverPubkey: Pubkey;
1356
- /** The card's relays. */
1357
- readonly relays: readonly string[];
1358
- }
1359
- type RfqTransportFactory = (rendezvous: RfqRendezvous) => AttestingRfqTransport | Promise<AttestingRfqTransport>;
1360
- /** Declare that `transport` proves every reply came from `responder`. */
1361
- declare const attesting: <T extends RfqTransport>(transport: T, responder: Pubkey) => AttestingRfqTransport;
1362
- /**
1363
- * The default: the card's own Nostr rendezvous.
1364
- *
1365
- * It attests the card's discovery key because `nostrRfqTransport` subscribes
1366
- * with `authors: [solverPubkey]` and decrypts with the conversation key derived
1367
- * against that same key — a reply from anyone else is either filtered out by the
1368
- * relay or fails to decrypt into anything with an `rfq_id`.
1369
- */
1370
- declare const nostrTransportFactory: RfqTransportFactory;
1371
-
1372
- /** The covenant and the keys behind one quoted corridor swap. */
1373
- interface CommonPreparation {
1374
- readonly backend: "rfq";
1375
- readonly card: DiscoveredMarket;
1376
- readonly rfqId: string;
1377
- /** The solver's reply, decoded once. */
1378
- readonly wire: ParsedRfqQuote;
1379
- /** The trader's OWN derivation of the Arkade lockup. */
1380
- readonly lockup: {
1381
- readonly address: string;
1382
- readonly script: InstanceType<typeof VHTLC.ScriptV2>;
1383
- readonly pkScript: Uint8Array;
1384
- };
1385
- }
1386
- /**
1387
- * What `accept()` inherits from a quote.
1388
- *
1389
- * Held in memory by the client, keyed by quote id, and written nowhere: M3's
1390
- * boundary is that `quote()` persists nothing. It exists so the covenant a
1391
- * quote was verified against is the covenant that gets funded — re-deriving it
1392
- * at accept from the stored quote would be a second derivation of the same tree,
1393
- * and two derivations that can disagree is the failure this package guards
1394
- * against everywhere else.
1395
- */
1396
- type RfqPreparation = (CommonPreparation & {
1397
- readonly route: "arkade->lightning";
1398
- readonly contractParams: LightningSendContractParams;
1399
- /** The refund key, and the address the quote named. */
1400
- readonly secrets: ProvisionedKey;
1401
- readonly refundAddress: string;
1402
- /** What the lockup must carry: the quote's give amount. */
1403
- readonly fundAmount: bigint;
1404
- }) | (CommonPreparation & {
1405
- readonly route: "lightning->arkade";
1406
- readonly contractParams: LightningReceiveContractParams;
1407
- readonly secrets: ProvisionedClaimSecret;
1408
- readonly payoutAddress: string;
1409
- /** What the solver's lockup must carry — the claim refuses less. */
1410
- readonly expectedAmount: bigint;
1411
- /** Last moment the hold invoice can be paid, unix seconds. */
1412
- readonly payDeadline: number;
1413
- }) | (CommonPreparation & {
1414
- readonly route: "arkade->onchain";
1415
- readonly secrets: ProvisionedClaimSecret;
1416
- readonly refundAddress: string;
1417
- readonly fundAmount: bigint;
1418
- /** The L1 claim key, provisioned by the wallet like every other key. */
1419
- readonly payoutKey: ProvisionedKey;
1420
- /** Where the claim PAYS — the take endpoint's own address, encoded.
1421
- * Distinct from {@link payoutKey}, which only AUTHORISES the claim:
1422
- * the claim's output is the spender's choice and the resolved
1423
- * destination is the only thing that names it. */
1424
- readonly payoutPkScript: Uint8Array;
1425
- readonly htlc: OnchainHtlc;
1426
- readonly htlcParams: OnchainHtlcParams;
1427
- readonly l1Network: OnchainNetwork;
1428
- readonly minConfirmations: number;
1429
- });
1430
- interface RfqQuoteInput {
1431
- readonly quoteId: QuoteId;
1432
- readonly route: "arkade->lightning" | "lightning->arkade" | "arkade->onchain";
1433
- readonly candidate: MarketCandidate;
1434
- readonly market: CardMarketRef;
1435
- readonly legs: {
1436
- readonly give: DiscoveryLeg;
1437
- readonly take: DiscoveryLeg;
1438
- };
1439
- readonly endpoints: {
1440
- readonly give: ResolvedEndpoint;
1441
- readonly take: ResolvedEndpoint;
1442
- };
1443
- readonly amount?: PinnedAmount;
1444
- readonly wallet: IWallet;
1445
- /** Live, per section 6: a snapshot binds a covenant to a key that may have rotated. */
1446
- readonly info: ArkadeInfo;
1447
- /**
1448
- * The corridor modules, unresolved.
1449
- *
1450
- * The set rather than two dep records, because resolution is what refuses a
1451
- * dep overridden to nothing — and a route that never touches lightning must
1452
- * not resolve its decoder to find that out. Each arm below asks for exactly
1453
- * the corridors it uses.
1454
- */
1455
- readonly corridors: CorridorSet;
1456
- readonly transport: AttestingRfqTransport;
1457
- readonly policy?: SwapPolicy;
1458
- /** Unix seconds. */
1459
- readonly now: number;
1460
- }
1461
- declare const quoteViaRfq: (input: RfqQuoteInput) => Promise<{
1462
- quote: Quote;
1463
- preparation: RfqPreparation;
1464
- }>;
1465
-
1466
- /** What a quote derived, kept in memory for the accept that may follow. */
1467
- type QuotePreparation = RfqPreparation | OfferPreparation;
1468
- interface AcceptInput {
1469
- readonly quote: Quote;
1470
- readonly preparation?: QuotePreparation;
1471
- readonly wallet: IWallet;
1472
- readonly repository: AssetSwapRepository | undefined;
1473
- readonly corridors: CorridorSet;
1474
- /**
1475
- * The drive, when the caller has one.
1476
- *
1477
- * Two jobs, and the second is M5's edit to this file's shipped behaviour.
1478
- * It turns a record into the public {@link Swap} — which now carries an
1479
- * `outcome`, and only the drive knows whether it holds live state for this
1480
- * swap — and it ARMS: the accepted swap is registered with the manager
1481
- * rather than persisted and left, which is what M4 deliberately did not do.
1482
- * The registration runs behind the return, so this call still does not wait
1483
- * on a first pass.
1484
- *
1485
- * Optional so the accept pipeline stays testable on its own; without one
1486
- * the answer is the record's projection and nothing is driven.
1487
- */
1488
- readonly drive?: SwapDrive;
1489
- /** Unix seconds. */
1490
- readonly now: number;
1491
- }
1492
- declare const conflictingFields: (record: SwapRecord, quote: Quote) => string[];
1493
- /**
1494
- * Accept a quote: make it durable, then move the value.
1495
- *
1496
- * Idempotent by quote id and only by quote id. A second call with the same
1497
- * quote returns the stored swap when the funding txid is already known, resumes
1498
- * the record when it is not, and refuses as `AcceptConflict` only when the
1499
- * durable evidence contradicts the quote on a material field.
1500
- */
1501
- declare const acceptQuote: (input: AcceptInput) => Promise<Swap>;
1502
- /** The stored record for a quote id, for a caller that holds only the id. */
1503
- declare const swapRecordOf: (repository: AssetSwapRepository | undefined, id: QuoteId) => Promise<SwapRecord | undefined>;
1504
-
1505
- /**
1506
- * The alias table, filled from discovery.
1507
- *
1508
- * M1 declared {@link AssetAliasTable} and left it injected: the alias layer owns
1509
- * no network, and the table's only real source is the market index, which is
1510
- * this milestone's. So this is the inverse of `toDiscoveryLeg` -- a card's
1511
- * corridor and `AssetInfo` back up to the public id a caller may write, plus the
1512
- * ticker that id answers to.
1513
- *
1514
- * Tickers are display metadata on a card and identity nowhere, which is why the
1515
- * table carries both and `canonicalAssetId` refuses a ticker that names two
1516
- * assets rather than picking one. Rows are deduplicated by id and ticker, so a
1517
- * ticker listed by nine solvers for the same asset is one row and not an
1518
- * ambiguity.
1519
- */
1520
-
1521
- /**
1522
- * The public id for one side of a card.
1523
- *
1524
- * `undefined` where the pair is not expressible as a public id: an
1525
- * arkade-issued asset on lightning or L1, which no corridor carries, and an id
1526
- * that is neither BTC nor the identity form.
1527
- */
1528
- declare const publicAssetId: (corridor: Corridor, assetId: string, network: NetworkRef) => AssetId | undefined;
1529
- /** Every asset the snapshot names, as caller-writable ids and their tickers. */
1530
- declare const aliasTableFrom: (markets: readonly DiscoveredMarket[], network: NetworkRef) => AssetAliasTable;
1531
- /**
1532
- * The table narrowed to one rail.
1533
- *
1534
- * Q12 gives BTC one id per rail, so `"BTC"` names three assets the moment a
1535
- * snapshot carries a corridor market — and the alias layer refuses a colliding
1536
- * ticker rather than guessing, which is the right rule and would make the
1537
- * spec's own `exchange({ give: "BTC", ... })` unresolvable if the table were
1538
- * consulted whole. A ticker is therefore resolved on the leg's own rail: the
1539
- * leg's corridor is already fixed by the destination, by `via`, or by being the
1540
- * wallet's side, so the scope is a fact rather than a preference. Collisions
1541
- * WITHIN a rail — two arkade assets both called `USDT` — still refuse, which is
1542
- * the case the rule exists for.
1543
- */
1544
- declare const scopedToRail: (table: AssetAliasTable, rail: Rail) => AssetAliasTable;
1545
-
1546
- /** What `cancel()` did to the deposit. §3.3's widened return: the
1547
- * `indeterminate` spend is `needs_recovery`, because value moved and the local
1548
- * rebuild cannot name how. */
1549
- type CancelOutcome = "cancelled" | "filled" | "needs_recovery";
1550
-
1551
- interface SwapClientConfig {
1552
- /**
1553
- * The wallet, and through it the operator: server info, chain reads and
1554
- * broadcast all come from it, and no server URL is accepted anywhere.
1555
- */
1556
- readonly wallet: IWallet;
1557
- /**
1558
- * Storage: the accept records, the markets cache, the restore-scan cursor.
1559
- *
1560
- * One seam for all three — the arkade corridor's `repository` override
1561
- * defaults to this object, so a client cannot write records to one store
1562
- * and read its cache from another.
1563
- *
1564
- * No implicit default, and never an in-memory fallback: silently losing
1565
- * active swaps is the thing a storage default exists to prevent. A browser
1566
- * consumer passes `IndexedDbAssetSwapRepository`, a Node consumer imports
1567
- * `@arkade-os/swap/node` for the file-backed SQLite default, and a test
1568
- * passes `InMemoryAssetSwapRepository` — explicitly, which is the only way
1569
- * ephemeral storage is available. `accept()` without one is
1570
- * `MissingCorridorDep("arkade", "repository")`; `quote()` and `resolve()`
1571
- * work without one, since neither persists anything.
1572
- */
1573
- readonly repository?: AssetSwapRepository;
1574
- readonly discovery?: DiscoveryConfig;
1575
- /** Dependency overrides only: they never enable a route or pick a solver. */
1576
- readonly corridors?: CorridorOverrides;
1577
- readonly policy?: SwapPolicy;
1578
- /** Covenant co-signer override, 33-byte compressed hex. */
1579
- readonly emulatorPubkey?: string;
1580
- /** Overrides the wallet's own connection; for tests and a second operator. */
1581
- readonly operator?: SwapOperator;
1582
- readonly fetchImpl?: typeof fetch;
1583
- /**
1584
- * How a card's rendezvous is opened. Defaults to the card's Nostr transport,
1585
- * which is the only shipped one that can attest who answered — an injected
1586
- * transport that attests nobody fails the responder check rather than
1587
- * quietly quoting against an unauthenticated wire.
1588
- */
1589
- readonly transportFor?: RfqTransportFactory;
1590
- }
1591
- interface SwapClient {
1592
- /**
1593
- * The restore-read, and — when it armed — the first pass after it.
1594
- *
1595
- * There is no required `start()`. Construction stays inert and this is what
1596
- * drives the one read of the repository; under `drive: "auto"` the read arms
1597
- * the loop when it finds live work, and the first `accept()` arms it when it
1598
- * does not. A resumed swap may already be past a deadline, which is why
1599
- * arming runs one pass immediately rather than waiting out an interval.
1600
- *
1601
- * **Rejects only when the repository itself is unreadable.** A client that
1602
- * cannot read its own records cannot drive them safely. Everything
1603
- * per-record resolves this and surfaces through the normal channels instead:
1604
- * a corrupt record is filtered, a swap that will not rebuild reports off its
1605
- * record, and a first pass that finds a swept lockup reports
1606
- * `needs_recovery` through {@link onUpdate}.
1607
- */
1608
- readonly ready: Promise<void>;
1609
- /**
1610
- * Arm the drive. Idempotent, and required only by `drive: "manual"`.
1611
- *
1612
- * Double arming is a no-op, so a React double-mount and two concurrent
1613
- * callers are both safe.
1614
- *
1615
- * @throws {SwapDriveRefusedError} under `drive: "readonly"`, which actuates
1616
- * nothing — silence would leave two contradictory instructions standing.
1617
- */
1618
- start(): Promise<void>;
1619
- /**
1620
- * Release the live resources this instance owns, and stay reusable.
1621
- *
1622
- * Timers cleared, the contract subscription dropped, in-flight actions left
1623
- * to run to completion, and outstanding work left where it is: stop/start is
1624
- * a pause, not a cancellation. What is NOT undone is durable — the records
1625
- * stay, and so do the wallet's contract registrations, because dropping one
1626
- * unwatches a funded lockup.
1627
- */
1628
- stop(): Promise<void>;
1629
- /**
1630
- * Terminal cleanup: {@link stop} plus draining what is in flight, dropping
1631
- * every listener, and making the instance terminal.
1632
- *
1633
- * It drains rather than returning while a refund push is mid-flight —
1634
- * nothing in this package takes an `AbortSignal`, so the alternative is
1635
- * calling an instance terminal while it is still moving money. Durable swap
1636
- * records, contract registrations and recovery metadata all survive it: a
1637
- * new client restores and resumes from them, and an injected repository is
1638
- * never closed — the client closes only a connection it opened itself.
1639
- *
1640
- * From M6 every other member refuses with {@link ClientDisposed} afterwards.
1641
- * The two exceptions are teardown, and for one reason: refusing a cleanup
1642
- * call turns correct teardown into a throw. A second dispose is a no-op, and
1643
- * so is an {@link Unsubscribe} this client already handed out.
1644
- */
1645
- [Symbol.asyncDispose](): Promise<void>;
1646
- /**
1647
- * Every outcome transition, in one vocabulary for both families.
1648
- *
1649
- * Subscribing replays the current outcome of every swap this client knows,
1650
- * then streams transitions. Delivery is idempotent per `(swapId, outcome)`,
1651
- * and because the outcome is DERIVED rather than stored the key is the
1652
- * derived one — so the legal `claimed -> claimable` backslide, which
1653
- * produces `funded` twice, is delivered once.
1654
- */
1655
- onUpdate(fn: (update: SwapUpdate) => void): Unsubscribe;
1656
- /**
1657
- * Recover a swap whose value was swept, then run one immediate pass.
1658
- *
1659
- * The recovery round itself is the wallet's — this package deliberately
1660
- * builds none — and it takes no outpoints: it reads the whole wallet, drops
1661
- * what it cannot settle, and caps the batch, deferring the overflow. So a
1662
- * settlement txid is not success, and this re-reads the named lockup to
1663
- * answer whether THIS swap's outputs were included.
1664
- *
1665
- * @throws {SwapDriveRefusedError} under `drive: "readonly"`; for a lockup
1666
- * still inside its refund window, where a round including it can fail the
1667
- * whole batch; and for a swap with nothing swept — which is what a
1668
- * `needs_recovery` that came from `needs_counterparty` is.
1669
- */
1670
- recover(swapId: AssetSwapId): Promise<RecoveryResult>;
1671
- /**
1672
- * Cancel an asset swap: take back an unfilled offer's deposit.
1673
- *
1674
- * Defined only for asset swaps and typed that way — an HTLC corridor swap
1675
- * has phases instead, and its exits are a claim or a refund. The id arrives
1676
- * tagged (`offer:<quoteId>` / `rfq:<quoteId>`), so a corridor id refuses on
1677
- * the parse with no repository read, and an offer id no record backs refuses
1678
- * after the one read this call needed anyway.
1679
- *
1680
- * Cancel races a fill. When the deposit is already spent, the spending
1681
- * transaction is reconciled against the covenant's leaves and the outcome
1682
- * is `filled` rather than a throw — v1's documented throw-means-completed
1683
- * behaviour was a trap. A spend the local rebuild cannot classify is
1684
- * `needs_recovery`: value moved and the client cannot name how, which is
1685
- * what {@link recover} drives.
1686
- *
1687
- * @throws {NotCancellable} for a corridor-tagged id, or an id no record backs.
1688
- * @throws {MissingCorridorDep} when the client was given no repository.
1689
- * @throws {ClientDisposed} after disposal.
1690
- */
1691
- cancel(swapId: AssetSwapId): Promise<{
1692
- outcome: CancelOutcome;
1693
- }>;
1694
- /**
1695
- * Every swap this client wrote — both families, live and ended.
1696
- *
1697
- * One read over the uniform v2 keyspace, projected through the same
1698
- * derivation the drive publishes: the drive's live answer where it holds the
1699
- * record, the no-live-state projection otherwise. Membership is therefore
1700
- * independent of `start()` and of drive mode. A record that will not decode
1701
- * is skipped rather than fatal. **The v2 keyspace is never pruned** — the
1702
- * store grows for the life of the wallet, which this method documents
1703
- * rather than hides.
1704
- *
1705
- * The filter is in-memory; the scope is the v2 client's own history. v1-era
1706
- * rows in the `swaps` and `rfqSwaps` keyspaces are not part of the answer —
1707
- * they belong to `/protocol`'s re-exported readers.
1708
- */
1709
- swaps(filter?: SwapFilter): Promise<Swap[]>;
1710
- /**
1711
- * The markets a `quote()` could be priced against, as {@link Market} — one
1712
- * shape with what `Quote.market` references. The escape hatch for a caller
1713
- * picking a market for a custom `quote()`: it reads the same card the quote
1714
- * will cite, and the same filters the routing read applies, so it cannot
1715
- * offer one `quote()` would then refuse. Never required.
1716
- *
1717
- * Reads the snapshot the way `quote()` does and not the way `resolve()`
1718
- * does — fetching when there is none in hand — because this is what a
1719
- * caller reaches for BEFORE quoting.
1720
- *
1721
- * @throws {DiscoverySnapshotUnavailable} when the fetch leaves it with
1722
- * nothing either.
1723
- */
1724
- markets(): Promise<Market[]>;
1725
- /**
1726
- * The route, the market that would price it, and what the active snapshot
1727
- * serves — without disclosing anything to anybody.
1728
- *
1729
- * Network-free against injected or cached discovery data, which is the point
1730
- * of having it: application policy gets to veto before an RFQ round trip
1731
- * discloses an invoice or an amount.
1732
- */
1733
- resolve(input: QuoteInput): Promise<RouteResolution>;
1734
- /** Verified, binding terms. Nothing is persisted, funded or watched. */
1735
- quote(input: QuoteInput): Promise<Quote>;
1736
- /**
1737
- * Make the quote durable, then move the value.
1738
- *
1739
- * One ordering, on every route: the record and its secrets are at rest
1740
- * before anything irreversible, and the funding txid is a later best-effort
1741
- * write. Idempotent by quote id and only by quote id — a second call with
1742
- * the same quote returns or resumes the stored swap and never mints a
1743
- * second invoice or funds a second time.
1744
- *
1745
- * Does not arm a drive loop or a watcher: this returns once the record is
1746
- * durable. On `lightning -> arkade` that means a durable invoice the payer
1747
- * can be shown — which is the point of the ordering, since showing one
1748
- * whose claim secret is still in memory is what buys a lockup nobody can
1749
- * claim.
1750
- *
1751
- * @throws {QuoteExpired} past `quote.expiresAt`; the client never re-quotes.
1752
- * @throws {InsufficientFunds} before the persist, on funding routes only.
1753
- * @throws {AcceptConflict} when a record for this quote id contradicts it.
1754
- * @throws {MissingCorridorDep} when the client was given no repository.
1755
- */
1756
- accept(quote: Quote): Promise<Swap>;
1757
- /**
1758
- * Pay a destination: a bolt11, a `bc1…`, or a plain Arkade address.
1759
- *
1760
- * One call for §5's whole pay box. `quote` → fee ceiling → `accept`, with
1761
- * the amount taken as what the recipient gets; an amount-bearing invoice
1762
- * pins it already, so passing one beside it is `AmountMismatch`.
1763
- *
1764
- * A plain Arkade address is **not** a swap and does not become one: it
1765
- * settles through `wallet.send` and answers `{ kind: "payment", txid }`,
1766
- * which is why the return is a union. Rejecting it would put the same
1767
- * branch in every product that has one pay box.
1768
- *
1769
- * @throws {MaxFeeExceeded} when the quoted fee is over `maxFee` or
1770
- * `policy.maxFee`, whichever is tighter — before anything is funded.
1771
- */
1772
- pay(destination: string, options?: PayOptions): Promise<PayResult>;
1773
- /**
1774
- * Ask for an incoming payment, and get back the artifact to show its payer.
1775
- *
1776
- * Returns only after `accept()` has persisted, which is the point: an
1777
- * invoice shown to a payer while its claim secret is still in memory buys a
1778
- * lockup nobody can claim. The artifact is non-optional on the return type
1779
- * for the same reason — a receive has one by construction.
1780
- *
1781
- * @throws {MaxFeeExceeded} as {@link pay} does.
1782
- */
1783
- receive(options: ReceiveOptions): Promise<ReceiveRequest>;
1784
- /**
1785
- * Swap one Arkade asset for another.
1786
- *
1787
- * @throws {MaxFeeExceeded} as {@link pay} does.
1788
- */
1789
- exchange(options: ExchangeOptions): Promise<Swap>;
1790
- /**
1791
- * What the quote with this id derived — the covenant, the keys, the wire
1792
- * reply.
1793
- *
1794
- * Process-local and deliberately not durable: M3 persists nothing, and M4's
1795
- * `accept()` is what turns this into a record. It exists so the covenant a
1796
- * quote was verified against is the one that gets funded, rather than a
1797
- * second derivation of the same tree.
1798
- */
1799
- preparationOf(id: QuoteId): QuotePreparation | undefined;
1800
- }
1801
- /** The in-memory filter {@link SwapClient.swaps} applies. */
1802
- interface SwapFilter {
1803
- readonly family?: SwapFamily;
1804
- readonly outcome?: Outcome;
1805
- }
1806
- declare const createSwapClient: (config: SwapClientConfig) => SwapClient;
1807
-
1808
- /** BOLT11's default expiry when an invoice carries no `x` tag. */
1809
- declare const DEFAULT_INVOICE_EXPIRY_SECONDS = 3600;
1810
- /**
1811
- * Decode a BOLT11 invoice into the facts the corridor needs.
1812
- *
1813
- * Signature-blind, like the library: nothing here proves the invoice was issued
1814
- * by whoever offered it. What it does prove is that the payment hash the
1815
- * corridor will compare against is the one the payer would pay to.
1816
- *
1817
- * @throws when the string is not a decodable BOLT11 invoice, or decodes without
1818
- * the timestamp or payment hash BOLT11 requires.
1819
- */
1820
- declare const decodeBolt11: (invoice: string) => InvoiceFacts;
1821
-
1822
- /** The chain tip, as the two reads that need it want it. */
1823
- interface L1Tip {
1824
- height: number;
1825
- /** Median-time-past, unix seconds. */
1826
- mtp: number;
1827
- }
1828
- /** What the adapter reads L1 through: core's provider, plus the one fact its
1829
- * interface does not promise. */
1830
- interface ChainSourceBackend {
1831
- provider: OnchainProvider;
1832
- tip(): Promise<L1Tip>;
1833
- }
1834
- /** The address parameters an output script is encoded under. Structural, so
1835
- * core's `Network` and `L1_NETWORKS`' entries both satisfy it directly. */
1836
- type AddressParams = typeof btc.NETWORK;
1837
- /**
1838
- * A {@link ChainSource} over an arbitrary L1 backend.
1839
- *
1840
- * Separate from {@link esploraChainSource} so the adapter's logic — the
1841
- * confirmations arithmetic, the script-to-address encode, the missing-spender
1842
- * fallback — is exercisable without a server, and so a caller with its own
1843
- * `OnchainProvider` can reuse it.
1844
- */
1845
- declare const chainSourceOver: (backend: ChainSourceBackend, network: AddressParams) => ChainSource;
1846
- /**
1847
- * Tip height and median-time-past off Esplora's `/blocks`.
1848
- *
1849
- * `/blocks` rather than `/blocks/tip`, for the reason core already records:
1850
- * the latter is not part of the Esplora spec — electrs serves it as an alias,
1851
- * a strict backend like mempool answers an empty array.
1852
- */
1853
- declare const esploraTip: (esploraUrl: string, fetchImpl?: typeof fetch) => Promise<L1Tip>;
1854
- /** The default: core's Esplora provider at `esploraUrl`, with the tip read off
1855
- * `/blocks` beside it. */
1856
- declare const esploraChainSource: (input: {
1857
- /** Esplora REST base — the corridor's override, or `ESPLORA_URL[network]`. */
1858
- esploraUrl: string;
1859
- /** Address parameters for the script-to-address encode. */
1860
- network: AddressParams;
1861
- /** For hosts without a global `fetch`, and for tests. Only the `/blocks`
1862
- * read takes it: core's provider carries its own fetch wrapper. */
1863
- fetchImpl?: typeof fetch;
1864
- }) => ChainSource;
1865
-
1866
- declare const arkadeCorridor: CorridorFactory<ArkadeCorridorDeps>;
1867
-
1868
- /**
1869
- * The lightning corridor: a BOLT11 invoice, on this wallet's network.
1870
- *
1871
- * Core settles the shape and stops there — `isLightningInvoice` matches the HRP
1872
- * and a bech32 tail, strips a `lightning:` prefix, and by its own comment
1873
- * carries no bolt11 dependency and so no checksum and no decode. The two gaps
1874
- * are this module's, and §6 puts both at the parse boundary.
1875
- *
1876
- * The HRP-to-network table exists in neither package, so it is authored here.
1877
- * Two of its facts are worth stating because a test could otherwise claim more
1878
- * than the vocabulary can express: `lntbs` is signet AND mutinynet, which share
1879
- * an HRP exactly as they share `tark`, so a signet-versus-mutinynet rejection is
1880
- * not expressible; and `lnsb` (simnet) is admitted by core's regex — five
1881
- * prefixes, where §6 names four — and named by no `NetworkName`, so it is
1882
- * refused rather than mapped to a neighbour.
1883
- *
1884
- * Of §6's parse-boundary gates, this module owns three: the HRP check, the
1885
- * invoice expiry, and the amountless refusal. The rest read the quote — the
1886
- * headroom check needs `quote.refund_locktime` and no parse has a quote — and
1887
- * belong to the quote path.
1888
- */
1889
-
1890
- /**
1891
- * Which networks an invoice HRP can belong to.
1892
- *
1893
- * An ordered list rather than a record, because the order is load-bearing:
1894
- * `lnbcrt` has to be tested before `lnbc` and `lntbs` before `lntb`, and a
1895
- * record would leave that to key-iteration order.
1896
- */
1897
- declare const INVOICE_HRPS: readonly [readonly ["lnbcrt", readonly ["regtest"]], readonly ["lntbs", readonly ["signet", "mutinynet"]], readonly ["lnbc", readonly ["bitcoin"]], readonly ["lntb", readonly ["testnet"]]];
1898
- /** The networks `raw`'s HRP names, or `undefined` for one no network claims. */
1899
- declare const networksOfInvoiceHrp: (raw: string) => readonly NetworkName[] | undefined;
1900
- /**
1901
- * Both directions, and the ownership inverts between them.
1902
- *
1903
- * On `arkade -> lightning` the trader funds the lockup, so `refundLocktime` is
1904
- * the trader's and is a moment to act AFTER — the only action is the Arkade
1905
- * refund, since the solver claims the lockup with the preimage it learns by
1906
- * paying. On `lightning -> arkade` the solver funds it: every non-claim leaf is
1907
- * the solver's, the trader has no refund at all, and the deadline is a moment to
1908
- * have claimed BEFORE.
1909
- */
1910
- declare const LIGHTNING_DRIVE: {
1911
- readonly give: {
1912
- readonly lockups: readonly [{
1913
- readonly covenant: "arkade_lockup";
1914
- readonly owner: "solver";
1915
- readonly deadline: "refund_locktime";
1916
- }];
1917
- readonly actions: readonly ["claimLockup"];
1918
- readonly seams: readonly ["indexer"];
1919
- };
1920
- readonly take: {
1921
- readonly lockups: readonly [{
1922
- readonly covenant: "arkade_lockup";
1923
- readonly owner: "trader";
1924
- readonly deadline: "refund_locktime";
1925
- }];
1926
- readonly actions: readonly ["refundArkade"];
1927
- readonly seams: readonly ["indexer"];
1928
- };
1929
- };
1930
- declare const lightningCorridor: CorridorFactory<LightningCorridorDeps>;
1931
-
1932
- /**
1933
- * One direction only, and the absence is the decision.
1934
- *
1935
- * `onchain -> arkade` gets no entry because it is outside the `Route` union:
1936
- * its Arkade half is the same solver-funded lockup a lightning receive has, but
1937
- * it adds an L1 half the trader funds and must take back itself — a second
1938
- * deadline, a second observation seam AND a second action callback. Declaring
1939
- * the lockup half alone is what would produce a manager that silently lets the
1940
- * trader's L1 refund window pass.
1941
- *
1942
- * On `arkade -> onchain` the pass reads two covenants and they have different
1943
- * owners. The Arkade lockup is the trader's, and `refundLocktime` is the moment
1944
- * the money comes back. The L1 HTLC is the solver's on its refund leaf — the
1945
- * trader holds only the claim key — so reaching `htlc.refundLocktime` does not
1946
- * mean "refund the HTLC", it means the claim was missed.
1947
- */
1948
- declare const ONCHAIN_DRIVE: {
1949
- readonly take: {
1950
- readonly lockups: readonly [{
1951
- readonly covenant: "arkade_lockup";
1952
- readonly owner: "trader";
1953
- readonly deadline: "refund_locktime";
1954
- }, {
1955
- readonly covenant: "onchain_htlc";
1956
- readonly owner: "solver";
1957
- readonly deadline: "htlc_refund_locktime";
1958
- }];
1959
- readonly actions: readonly ["claimOnchain", "refundArkade"];
1960
- readonly seams: readonly ["indexer", "chain"];
1961
- };
1962
- };
1963
- declare const onchainCorridor: CorridorFactory<OnchainCorridorDeps>;
1964
-
1965
- /**
1966
- * The three seams between the v2 record store and v1's drive machinery.
1967
- *
1968
- * **The record bridge is the load-bearing one.** `RfqSwapManager` restores from
1969
- * `getAllRfqSwaps()`, while `accept()` writes `saveSwapRecord` into a keyspace
1970
- * `repository.ts` rules disjoint from it by design. So without this file the
1971
- * manager's restore-read returns nothing for every v2-accepted swap, and the
1972
- * whole drive — `ready`, arm-on-live-work, the outcome projections, recovery —
1973
- * rests on an empty set.
1974
- *
1975
- * The bridge is cheap because M4 designed the record to admit it:
1976
- * {@link CorridorSwapRecord} carries every {@link RfqSwapRecord} field but the
1977
- * optional display `amount` the rebuild ignores, and `RfqSwapRecordStore` is a
1978
- * four-method structural seam. Three rulings come with it.
1979
- *
1980
- * - **The store is wired as the manager's `repository` dep**, not left unwired.
1981
- * `restoreFromRepository` opens with `requireRepository`, so the unwired
1982
- * branch costs a hand-rolled restore rather than a storage-shape choice.
1983
- * - **It carries an `rfqId -> QuoteId` index**, because the manager keys every
1984
- * callback on `rfqId` while the v2 store keys on `QuoteId`. Without it
1985
- * `arkadeRefunder` misses its record and throws
1986
- * `RefundNotLocallyPossibleError` — the one refusal the manager reads as
1987
- * PERMANENT — leaving every v2 send leg blocked for its whole refund window
1988
- * with the lockup funded.
1989
- * - **`removeRfqSwap` is inert.** `restoreFromRepository` runs `dropRetired`
1990
- * before the rebuild, which would hard-delete v2 records under v1's
1991
- * thirty-day retention before `client.ready` resolves. v2 retention is M6's
1992
- * open question, and settling it here by side effect is not M5's to do. The
1993
- * manager still drops its in-memory copies, so an aged terminal record is not
1994
- * rebuilt; the record itself survives.
1995
- */
1996
-
1997
- /** Every stored corridor record, and every offer record, in one read. */
1998
- declare const splitRecords: (records: readonly SwapRecord[]) => {
1999
- corridor: CorridorSwapRecord[];
2000
- offer: OfferSwapRecord[];
2001
- };
2002
- /**
2003
- * A v2 corridor record as the manager's own record type.
2004
- *
2005
- * Field for field, minus the display `amount` — `rebuildRfqSwap` reads none of
2006
- * it, and inventing one would put a number on the record that no request result
2007
- * produced.
2008
- */
2009
- declare const rfqRecordOf: (record: CorridorSwapRecord) => RfqSwapRecord;
2010
- /**
2011
- * The manager's mutable half, written back onto the v2 record.
2012
- *
2013
- * REPLACED, not merged, exactly as `updateRfqSwapRecord` replaces it: the
2014
- * manager clears `blockedReason` when a swap leaves `needs_counterparty` and
2015
- * `claimFailure` when it becomes terminal, and a spread would only ever set
2016
- * these fields, never clear them — leaving a stale refusal reading as a live
2017
- * one. The origin half is carried through untouched, `fundingTxid` included:
2018
- * the manager never learns it, so it can only be the accept path's.
2019
- */
2020
- declare const withRfqState: (record: CorridorSwapRecord, state: RfqSwapRecord) => CorridorSwapRecord;
2021
- /** What a bridge or source hands back to the drive after a write. */
2022
- type RecordSink = (record: SwapRecord) => void;
2023
- interface CorridorRecordStore extends RfqSwapRecordStore {
2024
- /** Remember which quote id an `rfqId` belongs to, so a callback keyed on
2025
- * the manager's id can find the v2 record. Called at restore and at admit. */
2026
- index(record: CorridorSwapRecord): void;
2027
- /** The quote id for a manager-side `rfqId`, if this store has seen it. */
2028
- quoteIdOf(rfqId: string): QuoteId | undefined;
2029
- }
2030
- /**
2031
- * The v2 record store, as the manager's `repository` dep.
2032
- *
2033
- * Every read goes to the repository rather than to a cache: the store is the
2034
- * system of record, and the manager's own read-then-write per pass exists so a
2035
- * consumer's edit is not overwritten by a copy taken at boot. The index is the
2036
- * only thing held in memory, and it is a pure lookup — a miss costs one full
2037
- * scan and never a wrong answer.
2038
- */
2039
- declare const corridorRecordStore: (repository: AssetSwapRepository, onRecord?: RecordSink,
2040
- /**
2041
- * Which stored records the restore may hand to the manager.
2042
- *
2043
- * The filter exists for two cases. An `arkade -> onchain` record on a client
2044
- * whose chain source was refused: `restoreFromRepository` restores
2045
- * everything it reads, and the manager fails an onchain-send swap
2046
- * TERMINALLY on its first pass without a `ChainSource` — a deliberate
2047
- * refusal to watch that corridor blind. Excluding the record here leaves it
2048
- * durable, undriven and reporting off itself, which is the honest answer to
2049
- * "this client cannot drive this swap".
2050
- *
2051
- * And a record in a terminal state, which the drive excludes: the manager
2052
- * would rebuild it only to file it in `finished`, so handing it over pays
2053
- * a covenant derivation and a contract row lookup per record for nothing.
2054
- * The record itself stays readable — it is still in the drive's registry
2055
- * and still answers off its own stored state.
2056
- */
2057
- admits?: (record: CorridorSwapRecord) => boolean) => CorridorRecordStore;
2058
- /** A v2 offer record as the watcher and coverage read one. */
2059
- declare const offerFactsOf: (record: OfferSwapRecord) => OfferSwapFacts & {
2060
- id: QuoteId;
2061
- };
2062
- /** The v2 offer half of the record store, as the watcher's source. */
2063
- declare const offerRecordSource: (repository: AssetSwapRepository, onRecord?: RecordSink, now?: () => number) => OfferSwapSource<OfferSwapFacts & {
2064
- id: QuoteId;
2065
- }>;
2066
- /** One classified spend, written onto a v2 offer record. */
2067
- declare const applyOfferSpend: (record: OfferSwapRecord, changes: OfferSpendChanges, now: number) => OfferSwapRecord;
2068
- /** A restored deposit's status, written onto a v2 offer record. */
2069
- declare const withOfferStatus: (record: OfferSwapRecord, status: AssetSwapStatus, now: number) => OfferSwapRecord;
2070
- /**
2071
- * The wallet's own reader, as the manager's one required observation seam.
2072
- *
2073
- * Lifted from the v1 facade unchanged, guard included: the reader reads for
2074
- * NAMED foreign scripts and has no "the wallet's own" default, so a call with
2075
- * neither scripts nor outpoints is a caller bug rather than a query. Built from
2076
- * the wallet rather than injected on `SwapClientConfig`, because the wallet is
2077
- * where every other connection in this client comes from — a client takes no
2078
- * server URL and no provider. The drive layer still takes it as an input, which
2079
- * is what lets a unit test double one without a wallet behind it.
2080
- */
2081
- declare const walletLockupIndexer: (wallet: IWallet) => LockupSpendIndexer;
2082
-
2083
- /**
2084
- * The §7 taxonomy, as typed errors.
2085
- *
2086
- * The contract every member shares: it is thrown before value moves, or not at
2087
- * all. Anything that can go wrong after funding is an outcome, not an exception,
2088
- * and belongs to the drive loop instead. Each class names the boundary it fires
2089
- * at, because that is the part a caller cannot infer from the name.
2090
- *
2091
- * Naming rule, and it cuts both ways. A member of this taxonomy is a bare
2092
- * condition noun — `QuoteExpired`, `NotCancellable` — because `SwapRefusal` is
2093
- * one and §8 keeps it unchanged, so a module holding all sixteen is bare or it
2094
- * is the first mixed-convention module in the package. An error class that is
2095
- * *not* a member keeps the `Error` suffix: `AssetIdError` and
2096
- * `AmountFormatError` are codec faults on caller input, and the suffix is what
2097
- * says so at the catch site.
2098
- *
2099
- * v1's `AddressMismatch` (`rfq.ts:163`) is deliberately not a seventeenth
2100
- * member: M3 folds it into {@link QuoteVerificationFailed}'s `lockup_address`
2101
- * check, and M8 gives it the `/protocol` re-export and the `@deprecated`
2102
- * pointer. Tagging it here would deprecate a live behaviour against a
2103
- * replacement that does not exist yet.
2104
- */
2105
-
2106
- /**
2107
- * The checks §3.1 runs on every quote, before it is returned.
2108
- *
2109
- * Four of them are the spec's, and the fifth is M3's answer to G2. §3.1 states
2110
- * that "who answered is a transport property, not one of those four checks",
2111
- * and the two dev transports authenticate nobody — so leaving attestation at
2112
- * the transport makes verification skippable by configuration, which is the one
2113
- * thing verification may not be. `responder` is therefore *delivered* as a
2114
- * transport property and *run* as a check, and §3.1's sentence narrows to
2115
- * addressed mode with it: published RFQ (§10) attributes each bid by its own
2116
- * signature and inherits no transport attestation at all.
2117
- */
2118
- type QuoteCheck = "pair" | "lockup_address" | "invoice" | "refund_window" | "responder";
2119
- /**
2120
- * `to` is underdetermined — it parses as nothing, as more than one thing, or as
2121
- * one thing the corridor that owns it refuses.
2122
- *
2123
- * The third arm is the one a name reading only "ambiguous" would hide. A
2124
- * corridor module answers *mine, and wrong* for a `tb1…` on a mainnet wallet,
2125
- * another operator's Arkade address, or a bolt11 the shape-only classifier
2126
- * admits and the decoder then rejects; collapsing that into *not mine* would
2127
- * hand a well-formed destination to {@link UnsupportedRoute}, which names the
2128
- * wrong fault. The refusal rides on `detail`, so the taxonomy stays at sixteen.
2129
- *
2130
- * A destination core classifies but no module claims — an LNURL today — is NOT
2131
- * this: it is left unclaimed at the parse and becomes {@link UnsupportedRoute}
2132
- * at route resolution.
2133
- *
2134
- * Boundary: `resolve()`/`quote()`, the single place `to` is parsed.
2135
- */
2136
- declare class AmbiguousDestination extends Error {
2137
- readonly destination: string;
2138
- readonly name = "AmbiguousDestination";
2139
- constructor(destination: string, detail: string);
2140
- }
2141
- /**
2142
- * The corridor pair is not in the implemented route union — `onchain -> arkade`
2143
- * included, until the manager owns the trader's L1 refund path end to end.
2144
- *
2145
- * Boundary: route resolution, before RFQ disclosure, artifact creation,
2146
- * persistence or funding. Also the alias layer, for a rail no corridor serves,
2147
- * and `quote()` for a pair no discovered market serves on the active snapshot —
2148
- * a resolved route with an empty eligible set, which is an absence of a
2149
- * market-shaped thing rather than a wrong pairing, and so this member rather
2150
- * than a seventeenth.
2151
- */
2152
- declare class UnsupportedRoute extends Error {
2153
- readonly name = "UnsupportedRoute";
2154
- readonly give: CorridorId | undefined;
2155
- readonly take: CorridorId | undefined;
2156
- constructor(detail: string, corridors?: {
2157
- give?: CorridorId;
2158
- take?: CorridorId;
2159
- });
2160
- }
2161
- /**
2162
- * `resolve()` needs market data and has neither an injected nor a cached
2163
- * snapshot. Deliberately not a third, half-resolved route state: the type system
2164
- * excludes one, and a caller that needs offline resolution warms or injects a
2165
- * snapshot.
2166
- *
2167
- * Boundary: `resolve()`, and `quote()` when the fetch it is allowed to make
2168
- * leaves it with nothing either — no registry configured, an unindexed network,
2169
- * or an unreachable registry with no cache behind it. Fetching is what `quote()`
2170
- * may do that `resolve()` may not; having no market data at all is the same
2171
- * condition on both.
2172
- */
2173
- declare class DiscoverySnapshotUnavailable extends Error {
2174
- readonly network: NetworkName;
2175
- readonly name = "DiscoverySnapshotUnavailable";
2176
- constructor(network: NetworkName, detail: string);
2177
- }
2178
- /**
2179
- * Two amounts are pinned. Exactly one may be: the caller's `amount` +
2180
- * `amountOn`, or the invoice's.
2181
- *
2182
- * Boundary: `quote()`, before any network round trip.
2183
- */
2184
- declare class AmountMismatch extends Error {
2185
- readonly sources: readonly [string, string];
2186
- readonly name = "AmountMismatch";
2187
- constructor(sources: readonly [string, string]);
2188
- }
2189
- /**
2190
- * The amount cannot cross this encoding without an unsafe narrowing — a quote
2191
- * field arriving as a JSON number past 2^53, a non-canonical decimal string, or
2192
- * a `bigint` too large for a foreign `number` amount.
2193
- *
2194
- * Boundary: the RFQ adapter, both directions; from M7, core's payment rails.
2195
- */
2196
- declare class AmountEncodingUnsupported extends Error {
2197
- readonly field: string;
2198
- readonly value: string;
2199
- readonly name = "AmountEncodingUnsupported";
2200
- constructor(field: string, value: string, detail: string, options?: ErrorOptions);
2201
- }
2202
- /**
2203
- * A solver response failed a local check. v1 documented the pair check as the
2204
- * caller's job, in bold; here it is an invariant. v1's `AddressMismatch` is the
2205
- * `lockup_address` case of this and folds into it at M3.
2206
- *
2207
- * Boundary: `quote()`, before the quote is returned and so before funding.
2208
- */
2209
- declare class QuoteVerificationFailed extends Error {
2210
- readonly check: QuoteCheck;
2211
- readonly name = "QuoteVerificationFailed";
2212
- readonly expected: string | undefined;
2213
- readonly actual: string | undefined;
2214
- constructor(check: QuoteCheck, expected?: string, actual?: string,
2215
- /** The gate or derivation this folds in, kept as the `cause` chain:
2216
- * `expected`/`actual` say what disagreed, and the cause says which
2217
- * check said so. */
2218
- options?: ErrorOptions);
2219
- }
2220
- /**
2221
- * A quote past its TTL, or so close to it that acting on it is the same thing.
2222
- *
2223
- * Two boundaries, one condition. At `accept()` it is the spec's: the client
2224
- * never silently re-quotes, because the price the caller saw is not the price
2225
- * they would get. At `quote()` it is `policy.quoteTtlFloorSeconds` — a quote arriving
2226
- * with less validity left than the caller can use is expired on arrival, and
2227
- * saying so beats handing back terms that die between the return and the accept.
2228
- *
2229
- * Boundary: `quote()`, against the policy floor; `accept()`, before persistence.
2230
- */
2231
- declare class QuoteExpired extends Error {
2232
- readonly quoteId: string;
2233
- readonly expiresAt: number;
2234
- readonly now: number;
2235
- readonly name = "QuoteExpired";
2236
- constructor(quoteId: string, expiresAt: number, now: number);
2237
- }
2238
- /**
2239
- * The quote's fee is over the verb's ceiling.
2240
- *
2241
- * Carries the terms rather than the quote: a `Quote` field would make this
2242
- * module depend on M3, and an app re-presenting the terms calls `quote()` again
2243
- * anyway.
2244
- *
2245
- * Boundary: the verbs layer, between `quote` and `accept` — before funding.
2246
- */
2247
- declare class MaxFeeExceeded extends Error {
2248
- readonly quoteId: string;
2249
- readonly asset: AssetId;
2250
- readonly fee: bigint;
2251
- readonly maxFee: bigint;
2252
- readonly name = "MaxFeeExceeded";
2253
- constructor(quoteId: string, asset: AssetId, fee: bigint, maxFee: bigint);
2254
- }
2255
- /**
2256
- * The wallet cannot fund the give leg. v1 left this to `validatePlan` and the
2257
- * caller, and `validatePlan` returned rather than threw.
2258
- *
2259
- * Boundary: `accept()`, before persistence and funding.
2260
- */
2261
- declare class InsufficientFunds extends Error {
2262
- readonly asset: AssetId;
2263
- readonly required: bigint;
2264
- readonly name = "InsufficientFunds";
2265
- readonly available: bigint | undefined;
2266
- constructor(asset: AssetId, required: bigint, available?: bigint);
2267
- }
2268
- /**
2269
- * A quote id maps to a persisted accept record that contradicts it. Only
2270
- * incompatible *durable evidence* qualifies — an ordinary duplicate `accept()`
2271
- * returns or resumes the original swap, and a funding txid appearing where there
2272
- * was none is a benign resume.
2273
- *
2274
- * Boundary: `accept()`, on the persisted record, before any second funding.
2275
- */
2276
- declare class AcceptConflict extends Error {
2277
- readonly quoteId: string;
2278
- readonly swapId: string;
2279
- readonly fields: readonly string[];
2280
- readonly name = "AcceptConflict";
2281
- constructor(quoteId: string, swapId: string, fields: readonly string[]);
2282
- }
2283
- /**
2284
- * A method called after async disposal. Disposal is terminal for the instance;
2285
- * the durable records survive it and a new client resumes them.
2286
- *
2287
- * Boundary: every client method, before it does anything.
2288
- */
2289
- declare class ClientDisposed extends Error {
2290
- readonly method: string;
2291
- readonly name = "ClientDisposed";
2292
- constructor(method: string);
2293
- }
2294
- /**
2295
- * `cancel()` on a swap this client cannot cancel. The asymmetry is structural:
2296
- * an offer covenant has no expiry, so cancellation is an unfilled offer's only
2297
- * exit, where an HTLC has phases and its exits are a claim or a refund.
2298
- *
2299
- * Three ways of refusing, one condition. A corridor-tagged id is refused on the
2300
- * parse of its prefix, with no repository read; an `offer:` id no record backs
2301
- * is refused after the one read cancel needed anyway; and an untagged id from
2302
- * `/protocol`'s readers takes that same read. The taxonomy stays at sixteen —
2303
- * a "no such swap" member would split one condition across two classes by
2304
- * which call noticed it.
2305
- *
2306
- * Boundary: `cancel()`.
2307
- */
2308
- declare class NotCancellable extends Error {
2309
- readonly swapId: string;
2310
- readonly name = "NotCancellable";
2311
- constructor(swapId: string);
2312
- }
2313
- /**
2314
- * A destination disagrees with its asset's chain.
2315
- *
2316
- * Inert by ruling. §9's EVM corridor is the only place two chain identities can
2317
- * disagree, and it is deferred, so nothing throws this yet. Declared anyway so
2318
- * the taxonomy has no unowned member, and so M6's coverage pass can assert that
2319
- * exactly one declared error has no throwing site — this one. Its fields are
2320
- * pinned now for the same reason: nothing throws it, so this is the moment to
2321
- * say what the evidence is.
2322
- */
2323
- declare class InconsistentRoute extends Error {
2324
- readonly asset: AssetId;
2325
- readonly destination: string;
2326
- readonly name = "InconsistentRoute";
2327
- constructor(asset: AssetId, destination: string);
2328
- }
2329
- /**
2330
- * `getArkadeInfo({ requireLive: true })` failed while deriving a covenant. A
2331
- * snapshot would bind the covenant to a signer key the operator may no longer
2332
- * co-sign for, so this fails closed rather than falling back.
2333
- *
2334
- * Boundary: `quote()`, at covenant derivation — before funding.
2335
- */
2336
- declare class OperatorUnreachable extends Error {
2337
- readonly name = "OperatorUnreachable";
2338
- constructor(detail: string, options?: ErrorOptions);
2339
- }
2340
- /**
2341
- * A corridor's dependency was explicitly overridden to nothing, or is required
2342
- * on this network and absent.
2343
- *
2344
- * Four overridable deps, not three: the arkade repository, the lightning
2345
- * decoder, the lightning covclaimd deployment key, and the onchain chain
2346
- * source. `undefined` takes the default; `null` is the refusal this names. The
2347
- * arkade module's co-signer key reaches it by the second door — it is not a
2348
- * `CorridorOverrides` key, but `EMULATOR_PUBKEYS` pins three of the five
2349
- * networks, so on `testnet` and `signet` the override is required and its
2350
- * absence is this rather than a bare `Error`.
2351
- *
2352
- * Boundary: dep resolution, when a route first touches that corridor. Never
2353
- * construction: a missing dep for a corridor nobody uses is not an error.
2354
- */
2355
- declare class MissingCorridorDep extends Error {
2356
- readonly corridor: CorridorId;
2357
- readonly dep: string;
2358
- readonly name = "MissingCorridorDep";
2359
- constructor(corridor: CorridorId, dep: string);
2360
- }
2361
- /** Every member of the taxonomy. */
2362
- type SwapError = AmbiguousDestination | UnsupportedRoute | DiscoverySnapshotUnavailable | AmountMismatch | AmountEncodingUnsupported | QuoteVerificationFailed | SwapRefusal | QuoteExpired | MaxFeeExceeded | InsufficientFunds | AcceptConflict | ClientDisposed | NotCancellable | InconsistentRoute | OperatorUnreachable | MissingCorridorDep;
2363
- /** The sixteen names. Derived, so there is no second list to drift. */
2364
- type SwapErrorName = SwapError["name"];
2365
- /** The sixteen, as values — what the coverage pass counts. */
2366
- declare const SWAP_ERROR_NAMES: readonly SwapErrorName[];
2367
- /**
2368
- * Whether `e` belongs to the taxonomy, optionally narrowed to one member.
2369
- *
2370
- * Catalog-driven rather than a chain of `instanceof`, so it stays total as
2371
- * members are added, and it rejects an impostor: a foreign error that happens to
2372
- * be named `QuoteExpired` fails the constructor check.
2373
- */
2374
- declare function isSwapError(e: unknown): e is SwapError;
2375
- declare function isSwapError<N extends SwapErrorName>(e: unknown, name: N): e is Extract<SwapError, {
2376
- name: N;
2377
- }>;
2378
-
2379
- /**
2380
- * Route resolution: the single place `to` is parsed, the corridor pair is
2381
- * decided, the amount is pinned and the market is chosen — everything that has
2382
- * to happen before a solver is told anything.
2383
- *
2384
- * The order is §3.1's and it is load-bearing. `to` is parsed first, because a
2385
- * destination fault is the caller's most likely mistake and the parse needs no
2386
- * market data. The corridor pair follows from the parse (or from `via` on a
2387
- * receive, the one flow where no instrument can exist yet), and it selects the
2388
- * `Route` variant — a pair outside the union is `UnsupportedRoute` here, before
2389
- * an RFQ round trip, an artifact or a record. Only then does the market index
2390
- * come in, and only then can a ticker be canonicalized, since the table a ticker
2391
- * resolves against is built out of the cards themselves.
2392
- *
2393
- * The amount is pinned last and before any network call: exactly one may be
2394
- * pinned, by the caller or by an invoice, and two is `AmountMismatch` — thrown
2395
- * with nothing disclosed, which is the whole reason it is thrown here.
2396
- */
2397
-
2398
- /** The four implemented corridor pairs, spelled as the route union spells them. */
2399
- declare const SUPPORTED_PAIRS: readonly ["arkade->arkade", "arkade->lightning", "lightning->arkade", "arkade->onchain"];
2400
- type SupportedPair = (typeof SUPPORTED_PAIRS)[number];
2401
- interface ResolveDeps {
2402
- readonly corridors: CorridorSet;
2403
- /** The network the wallet reported; every defaulted asset id is on it. */
2404
- readonly network: NetworkName;
2405
- readonly discovery: DiscoveryIndex;
2406
- readonly policy?: SwapPolicy;
2407
- /**
2408
- * `resolve()` reads what is in hand; `quote()` may fetch.
2409
- *
2410
- * The one difference between the two paths, and the reason it is a flag
2411
- * rather than two functions: everything else about resolution — the parse,
2412
- * the pair, the pin, the veto — has to be identical, or the resolution a
2413
- * caller vetoed would not be the one they quoted.
2414
- */
2415
- readonly mode: "resolve" | "quote";
2416
- }
2417
- /** What the quote path needs from a resolution, over what a caller sees. */
2418
- interface ResolvedRoute {
2419
- readonly resolution: RouteResolution;
2420
- /** Both legs in discovery's vocabulary — what the market lookup matched on. */
2421
- readonly legs: {
2422
- readonly give: DiscoveryLeg;
2423
- readonly take: DiscoveryLeg;
2424
- };
2425
- readonly give: ResolvedEndpoint;
2426
- readonly take: ResolvedEndpoint;
2427
- readonly pair: SupportedPair;
2428
- readonly candidates: readonly MarketCandidate[];
2429
- /** The chosen card, absent when nothing eligible survived. */
2430
- readonly market?: MarketCandidate;
2431
- readonly snapshot: DiscoverySnapshot;
2432
- readonly amount?: PinnedAmount;
2433
- /** The alias table the snapshot produced, so the quote path can reuse it. */
2434
- readonly aliases: AssetAliasTable;
2435
- }
2436
- /**
2437
- * Assemble the closed `Route` from two fully-instrumented legs.
2438
- *
2439
- * The one cast in the quote path, and it is confined to this function. The
2440
- * checker cannot correlate `corridor` and `asset` across two independently
2441
- * resolved values, but the pairing is a fact by the time we are here: every
2442
- * asset went through `toDiscoveryLeg`, which is what decided the corridor. The
2443
- * runtime re-check is cheap and turns a broken invariant into a throw at the
2444
- * boundary rather than a covenant built against the wrong rail.
2445
- */
2446
- declare const assembleRoute: (give: ResolvedEndpoint & {
2447
- instrument: Instrument;
2448
- }, take: ResolvedEndpoint & {
2449
- instrument: Instrument;
2450
- }) => Route;
2451
- declare const resolveRoute: (input: QuoteInput, deps: ResolveDeps) => Promise<ResolvedRoute>;
2452
-
2453
- /** A `number` of sats from atomic units, or {@link AmountEncodingUnsupported}. */
2454
- declare const satsOf: (value: bigint, field: string) => number;
2455
-
2456
- /**
2457
- * Verification, as one invariant instead of four scattered habits.
2458
- *
2459
- * v1 spreads these checks across four request entrypoints and reaches the offer
2460
- * path with none of them: `expectQuote` compares type, id and pair;
2461
- * `verifyLockupAddress` compares the derived address; `assertFundable`,
2462
- * `verifyReceiveInvoice` and `assertReceivable` gate expiry, headroom and the
2463
- * claim window on some legs and not others; and the docs push the rest — plan
2464
- * validation, the rendezvous choice, the invoice decode — onto the caller. This
2465
- * module runs the whole set, once, on both backends, before any quote is
2466
- * returned, and every failure is one error class with the check named on it.
2467
- *
2468
- * The gates themselves are still `rfq.ts`'s. They are audited, they carry the
2469
- * constants (`MIN_HEADROOM_SECONDS`, `MIN_CLAIM_WINDOW_SECONDS`) that mirror the
2470
- * covenant's own timing, and re-implementing them here would be a second
2471
- * opinion where the whole point is that there is one. What this adds is the
2472
- * mapping: a gate's stable `reason` becomes a {@link QuoteCheck}, so a caller
2473
- * switches on the check rather than on a string the wire's own vocabulary
2474
- * leaked.
2475
- *
2476
- * Two failures deliberately do NOT become verification failures. A solver
2477
- * declining is `SwapRefusal` — a decision, not a fault. And a quote that has
2478
- * expired, or is about to, is `QuoteExpired`: the terms were fine, the clock is
2479
- * the problem, and the remedy is a fresh quote rather than a different solver.
2480
- */
2481
-
2482
- /**
2483
- * The fifth check: who answered.
2484
- *
2485
- * §3.1 calls this a transport property rather than one of the four, and it is —
2486
- * but a property only the production transport happens to have is a check the
2487
- * caller can turn off by handing in a different transport, and verification that
2488
- * configuration can disable is not an invariant. So the transport delivers the
2489
- * attestation and this runs it, in addressed mode only: published RFQ has N
2490
- * unknown responders and attributes each bid by its own signature instead.
2491
- *
2492
- * `pinnable` is the trust boundary the cache leaves. The key this compares
2493
- * against is the card's `discovery_pubkey`, which a cached card carries
2494
- * unvalidated — so a snapshot read back out of local storage cannot supply it,
2495
- * and the check fails closed rather than pinning against content anyone with
2496
- * write access to the browser's storage could have chosen.
2497
- */
2498
- declare const verifyResponder: (input: {
2499
- /** The key this transport proves every reply came from, if it proves one. */
2500
- readonly attested?: Pubkey;
2501
- /** The card's `discovery_pubkey`. */
2502
- readonly expected?: Pubkey;
2503
- /** Whether `expected` came from a source that can be trusted to name it. */
2504
- readonly pinnable: boolean;
2505
- }) => void;
2506
- /**
2507
- * The pair check, run here as well as in the transport.
2508
- *
2509
- * `expectQuote` already compares it — this is not a gap being filled but the
2510
- * layer that OWNS the string doing its own comparison, so a transport that
2511
- * skips the check (or one a caller injected) cannot make the quote path skip it
2512
- * too. v1 documented this one as the caller's job, in bold.
2513
- */
2514
- declare const verifyPair: (quoted: unknown, requested: string) => void;
2515
- /**
2516
- * Derive the covenant, and fold every way that can fail into one check.
2517
- *
2518
- * `AddressMismatch` is the case §8 promised would fold in here: it is the
2519
- * `lockup_address` check under its v1 name, and keeping it as a seventeenth
2520
- * error would leave two classes for one condition across the v1/v2 seam. The
2521
- * other failures — a missing binding field, malformed hex from the solver — are
2522
- * the same check reached from further back: an address that cannot be derived
2523
- * cannot be compared, and both mean the same thing to a caller, which is do not
2524
- * fund this.
2525
- */
2526
- declare const verifyingDerivation: <T>(derive: () => T) => T;
2527
- /**
2528
- * The send legs' window gate: the quote's own expiry, the refund headroom, and
2529
- * — on `arkade -> onchain` — the L1 confirmation window and the timelock order
2530
- * between the two contracts.
2531
- */
2532
- declare const verifySendWindow: (input: {
2533
- readonly quote: RfqQuote;
2534
- readonly quoteId: QuoteId;
2535
- readonly now: number;
2536
- readonly invoiceExpiresAt?: number;
2537
- readonly onchain?: {
2538
- htlcLocktime: number;
2539
- minConfirmations: number;
2540
- direction: "send" | "receive";
2541
- };
2542
- }) => void;
2543
- /**
2544
- * The receive legs' window gate, measured from the pay deadline rather than
2545
- * from now.
2546
- *
2547
- * The semantics invert on these legs: `refund_locktime` is the SOLVER's, so
2548
- * BIP-113's lag extends the trader's claim window instead of shrinking it, and
2549
- * what can actually run out is the hold invoice. The window that matters is
2550
- * therefore the one left after a payer pays at the last possible moment.
2551
- */
2552
- declare const verifyReceiveWindow: (input: {
2553
- readonly quote: RfqQuote;
2554
- readonly quoteId: QuoteId;
2555
- readonly payDeadline: number;
2556
- readonly now: number;
2557
- }) => void;
2558
- /**
2559
- * The invoice check on a send: the solver quoted THIS invoice, and quoted it at
2560
- * a price that is a price.
2561
- *
2562
- * Both halves matter. A quote whose `to_amount` is not the invoice's amount is
2563
- * not a quote for this invoice — the BOLT11 profile is exact-out and the
2564
- * invoice is the amount pin. A `from_amount` below it is a negative spread,
2565
- * which is not a quote at all.
2566
- */
2567
- declare const verifySendInvoice: (input: {
2568
- /** The amount the trader's own decode read off the invoice. */
2569
- readonly invoiced: bigint;
2570
- readonly give: bigint;
2571
- readonly take: bigint;
2572
- }) => void;
2573
- /**
2574
- * The invoice check on a receive: bind the SOLVER's hold invoice to this swap's
2575
- * hash and to the quote.
2576
- *
2577
- * This is the only field the trader hands to a third party and the only attack
2578
- * on this corridor with no on-chain trace — an invoice on some other payment
2579
- * hash is paid to the solver in full and no lockup on `H` is ever funded. It is
2580
- * re-implemented here rather than delegated to `verifyReceiveInvoice` for one
2581
- * reason: that gate compares the decoded amount against `quote.from_amount` as a
2582
- * JS number, and under the amount migration that field arrives as either a
2583
- * number or a string. A `!==` between a string and a number is always true, and
2584
- * a check that always fails is not safer than one that compares the decoded
2585
- * bigint — it just refuses every quote from a solver that already migrated.
2586
- */
2587
- declare const verifyReceiveInvoiceFacts: (input: {
2588
- readonly invoice: string;
2589
- readonly decode: (bolt11: string) => InvoiceFacts;
2590
- /** `sha256(P)`, hex — the trader's OWN. */
2591
- readonly paymentHash: string;
2592
- /** The quote's `from_amount`: what the payer is asked for. */
2593
- readonly payAmount: bigint;
2594
- readonly validUntil: number;
2595
- }) => {
2596
- payDeadline: number;
2597
- };
2598
- /**
2599
- * The policy floor on a quote's remaining life.
2600
- *
2601
- * One layer above the wire's own refusal of a quote already past `valid_until`:
2602
- * that one says the terms are dead, this one says they will be before the caller
2603
- * can use them. Only the caller knows how long their flow takes between seeing
2604
- * terms and accepting them, so the floor is theirs to set — and with none set,
2605
- * only expiry itself refuses.
2606
- */
2607
- declare const verifyQuoteTtl: (input: {
2608
- readonly quoteId: QuoteId;
2609
- readonly expiresAt: number;
2610
- readonly now: number;
2611
- readonly floorSeconds?: number;
2612
- }) => void;
2613
- /**
2614
- * The quote answers the request that was made.
2615
- *
2616
- * `expectQuote` compares the pair, which says the quote is for this market;
2617
- * this says it is for this trade. The request names a side and an amount, and a
2618
- * quote that reprices the side the caller pinned is a quote for a different
2619
- * size — v1 checks it on two legs out of four and calls it `assertQuotedAmount`.
2620
- *
2621
- * It reports as the `pair` check rather than as a fifth-and-a-half one, because
2622
- * what it establishes is the same thing: the identity of the trade being
2623
- * quoted, which on the wire is the pair plus the pinned side. The closed
2624
- * {@link QuoteCheck} union gains no member for it, and the strings say exactly
2625
- * what disagreed.
2626
- */
2627
- declare const verifyQuotedAmount: (input: {
2628
- readonly pair: string;
2629
- readonly pinned: {
2630
- on: "give" | "take";
2631
- value: bigint;
2632
- };
2633
- readonly give: bigint;
2634
- readonly take: bigint;
2635
- }) => void;
1
+ export { e as AcceptConflict, g as AmbiguousDestination, h as AmountEncodingUnsupported, i as AmountMismatch, A as AssetAliasTable, n as CancelOutcome, p as ClientDisposed, z as CorridorOverrides, F as DiscoveryConfig, d as DiscoverySnapshot, H as DiscoverySnapshotUnavailable, I as DriveMode, K as ExchangeOptions, P as FeeCeiling, U as InconsistentRoute, V as InsufficientFunds, X as Market, Y as MaxFeeExceeded, Z as MissingCorridorDep, _ as NotCancellable, a3 as OperatorUnreachable, a5 as PayOptions, a6 as PayResult, a7 as QuoteCheck, a8 as QuoteExpired, aa as QuoteVerificationFailed, ab as REGISTRY_URL, ac as ReceiveArtifact, ad as ReceiveOptions, ae as ReceiveRequest, af as RecoveryResult, ag as RegisteredAsset, ah as RfqAuctionPolicy, al as RfqTransportFactory, an as SWAP_ERROR_NAMES, ao as SwapClient, ap as SwapClientConfig, as as SwapDriveRefusedError, at as SwapError, au as SwapErrorName, av as SwapFilter, S as SwapPolicy, aw as UnsupportedRoute, ax as VerbDeps, aB as canonicalAssetId, aG as createSwapClient, aL as exchange, aR as isSwapError, aZ as pay, b1 as receive } from './errors-hm7aqnRM.cjs';
2
+ import { d as AssetSwapRepository, h as AssetSwap, e as RfqSwapRecord, f as RfqSwapPageFilter, g as RfqSwapPageCursor, S as SwapRecord, b1 as MarketsCacheEntry, a4 as Outcome, ak as Swap, l as QuoteInput, i as RouteResolution, a6 as Quote, an as SwapUpdate, ao as Unsubscribe } from './repository-BuYWGAKz.cjs';
3
+ export { o as ARKADE_ASSET_NAMESPACE, p as Amount, q as AmountFormatError, s as AmountRefusal, t as Artifact, A as AssetId, u as AssetIdError, v as AssetIdRefusal, w as AssetNamespace, x as AssetOn, y as AssetPart, z as AssetRef, B as AssetScale, D as AssetSwapId, E as AtomicDecimal, F as AuctionMarketRef, G as AuctionProvenance, H as BITCOIN_RAILS, J as BTC_ASSET_PART, K as BitcoinRail, U as CardMarketRef, V as CorridorId, W as CorridorKind, b as CorridorSwapRecord, X as DepositArtifact, Y as DisplayDecimal, Z as Endpoint, _ as Ep, b2 as InMemoryAssetSwapRepository, I as Instrument, L as LockupSpendIndexer, a1 as MarketBackend, a2 as MarketRef, N as NetworkRef, O as OfferSwapRecord, a5 as ParsedAssetId, P as PinnedAmount, Q as QuoteId, a7 as QuoteLeg, a8 as RAILS, R as Rail, ab as RankedBid, ac as RawState, ad as RecordedArtifact, ae as RecordedEndpoint, af as RecordedInstrument, ag as RecordedLeg, j as ResolvedEndpoint, ah as RestoredMarketRef, b3 as RfqSwapState, k as Route, aj as SnapshotRef, b4 as SwapContractRegistry, al as SwapFamily, b5 as SwapOperator, am as SwapRecordCommon, ap as arkadeAsset, ar as assetPartOf, as as assetSwapIdOf, at as bitcoinNetworkOf, au as btcAssetPart, av as btcOn, aA as familyOfSwapId, aB as formatAssetId, aC as fromAtomicDecimal, aG as isAssetId, aH as isAtomicDecimal, aI as isBtcAsset, aJ as isBtcAssetLenient, aK as isNetworkRef, b6 as isRfqSwapTerminal, aL as issuanceOf, aO as parseAssetId, aP as quoteIdOfSwapId, aQ as railOf, aY as sameAsset, a_ as toAtomicDecimal } from './repository-BuYWGAKz.cjs';
4
+ export { C as ChainSource, I as InvoiceFacts, a as RFQ_REFUSAL_ERROR_CODES, b as RfqRefusalDetail, c as RfqRefusalErrorCode, d as RfqRefusalUnit, S as SwapRefusal, i as isRfqRefusalErrorCode } from './rfq-60PGpQ_x.cjs';
5
+ import { PageRequest, PageResult, PaymentHandle, PaymentRail, RouterPreferences, Wallet, PaymentRouter, PaymentStatus } from '@arkade-os/sdk';
6
+ export { C as CLAIM_PACKET_TYPE, a as ClaimPacketShape, L as LockupRegistrationFailed, S as SEALED_CIPHERTEXT_LENGTH, b as appendArkadeScript, c as claimPacketShape } from './lockupContract-5r5RlgOJ.cjs';
7
+ import '@arkade-os/solver-discovery';
8
+ import './offer-F88rtL_I.cjs';
2636
9
 
2637
10
  /** Browser backend over the SDK's shared IndexedDB manager. */
2638
11
  declare class IndexedDbAssetSwapRepository implements AssetSwapRepository {
@@ -2646,14 +19,16 @@ declare class IndexedDbAssetSwapRepository implements AssetSwapRepository {
2646
19
  * transaction, which `awaitTransaction` reports. */
2647
20
  private write;
2648
21
  saveSwap(swap: AssetSwap): Promise<void>;
2649
- getAllSwaps(): Promise<AssetSwap[]>;
22
+ getAssetSwapsPage(page: PageRequest): Promise<PageResult<AssetSwap>>;
2650
23
  saveRfqSwap(record: RfqSwapRecord): Promise<void>;
2651
24
  getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
2652
- getAllRfqSwaps(): Promise<RfqSwapRecord[]>;
25
+ getRfqSwapsPage(filter: RfqSwapPageFilter, page: PageRequest<RfqSwapPageCursor>): Promise<PageResult<RfqSwapRecord, RfqSwapPageCursor>>;
2653
26
  removeRfqSwap(rfqId: string): Promise<void>;
2654
27
  saveSwapRecord(record: SwapRecord): Promise<void>;
2655
28
  getSwapRecord(id: string): Promise<SwapRecord | undefined>;
2656
- getAllSwapRecords(): Promise<SwapRecord[]>;
29
+ getSwapRecordsPage(page: PageRequest): Promise<PageResult<SwapRecord>>;
30
+ private pageStore;
31
+ private resultOfPage;
2657
32
  removeSwapRecord(id: string): Promise<void>;
2658
33
  getScannedTxids(): Promise<Set<string>>;
2659
34
  markTxidsScanned(txids: Iterable<string>): Promise<void>;
@@ -2667,38 +42,18 @@ declare class IndexedDbAssetSwapRepository implements AssetSwapRepository {
2667
42
  }
2668
43
 
2669
44
  /**
2670
- * What the two v2 swap rails share: the client seam, the quote arithmetic, and
2671
- * the handle that observes a swap through core's four-state stream.
2672
- *
2673
- * A rail here is a thin adapter and deliberately nothing more. Persistence,
2674
- * refunds, recovery and the outcome vocabulary all live behind the v2 client;
2675
- * the rail's whole job is to turn a `PaymentRequest` into a `QuoteInput`, a
2676
- * `Quote` into a receiver-exact `RouteQuote`, and a swap's outcome stream into
2677
- * a `PaymentHandle`.
45
+ * What the two v2 swap rails share: the client seam, the quote arithmetic, and the handle that
46
+ * observes a swap through core's four-state stream. A rail is a thin adapter; persistence, refunds,
47
+ * recovery and outcomes live behind the v2 client.
2678
48
  *
2679
- * Two boundaries are crossed here and both are named. Amounts narrow from P3's
2680
- * `bigint` to core's `number` (see `client/sats.ts`). And a ranking estimate
2681
- * meets a binding quote: `RouteQuote.fee` is documented as "a display and
2682
- * ranking figure, not a guarantee" while a v2 `Quote` is verified before return
2683
- * and expires. `PaymentOption.quote()` is lazy and `options()` never calls it,
2684
- * so ranking is free — but a swap rail's `quote()` is an RFQ round trip that
2685
- * discloses an invoice and an amount, and an app that ranks then quotes several
2686
- * options would disclose to every solver. `available()` therefore **never
2687
- * quotes**: it resolves, which is network-free against the cached snapshot.
2688
- *
2689
- * A held `RouteQuote` can outlive its `Quote` — core's shape carries no
2690
- * `expiresAt` — and then `send()` throws `QuoteExpired` inside `makeHandle`'s
2691
- * run, which core turns into a terminal `failed`. That stays: re-quoting inside
2692
- * `send()` is the silent re-quote §3.2 forbids.
49
+ * Amounts narrow from `bigint` to core's `number` here (see `client/sats.ts`). `available()`
50
+ * **never quotes**: a swap rail's `quote()` is an RFQ round trip disclosing an invoice and amount, so
51
+ * ranking must not call it — it resolves, network-free against the cached snapshot. A held
52
+ * `RouteQuote` can outlive its `Quote` (core's shape has no `expiresAt`); `send()` then fails with
53
+ * `QuoteExpired` rather than silently re-quoting.
2693
54
  */
2694
55
 
2695
- /**
2696
- * The slice of `SwapClient` a rail uses.
2697
- *
2698
- * Structural and minimal, so what a rail can reach is visible in one place and
2699
- * a test can stand in for it without a wallet, a repository or a solver behind
2700
- * it. A full `SwapClient` satisfies it.
2701
- */
56
+ /** The minimal structural slice of `SwapClient` a rail uses, so a test can stand in for it. */
2702
57
  interface SwapRailClient {
2703
58
  resolve(input: QuoteInput): Promise<RouteResolution>;
2704
59
  quote(input: QuoteInput): Promise<Quote>;
@@ -2706,13 +61,9 @@ interface SwapRailClient {
2706
61
  onUpdate(fn: (update: SwapUpdate) => void): Unsubscribe;
2707
62
  }
2708
63
  /**
2709
- * A payment that ended in something other than success.
2710
- *
2711
- * Not a member of §7's taxonomy and suffixed to say so: that taxonomy is thrown
2712
- * *before* value moves, and this is an outcome reported after it did. It exists
2713
- * to carry the {@link Outcome} onto the handle's terminal `error`, which is
2714
- * where `refunded` and `lapsed` stay distinguishable after the four-state
2715
- * projection has mapped both to `failed`.
64
+ * A payment that ended in something other than success. Not part of the error taxonomy (thrown
65
+ * *before* value moves): this is an outcome reported after, carrying the {@link Outcome} so
66
+ * `refunded` and `lapsed` stay distinguishable once both project to `failed`.
2716
67
  */
2717
68
  declare class SwapPaymentFailedError extends Error {
2718
69
  readonly railId: string;
@@ -2724,15 +75,9 @@ declare class SwapPaymentFailedError extends Error {
2724
75
  /** `eligible > 0` for this input, or false for anything that will not route. */
2725
76
  declare const railAvailable: (client: SwapRailClient, input: QuoteInput) => Promise<boolean>;
2726
77
  /**
2727
- * The three receiver-exact numbers, checked against each other.
2728
- *
2729
- * `total === amount + fee` is core's contract and this is where a rail proves
2730
- * it rather than asserting it in a comment: `amount` is what the recipient
2731
- * gets, `fee` is what the rail and its counterparty charge on top, and `total`
2732
- * is what leaves the wallet. A `Quote` whose give leg does not equal the take
2733
- * leg plus the spread has broken an invariant M3 owns, and surfacing it here
2734
- * beats quoting a number that would rank this rail against the collaborative
2735
- * exit on a fee it does not charge.
78
+ * The three receiver-exact numbers, checked: `total === amount + fee` is core's contract (`amount`
79
+ * delivered, `fee` on top, `total` leaving the wallet). A violation is surfaced rather than ranked
80
+ * against the collaborative exit on a fee this rail does not charge.
2736
81
  */
2737
82
  declare const receiverExact: (railId: string, parts: {
2738
83
  amount: bigint;
@@ -2744,85 +89,43 @@ declare const receiverExact: (railId: string, parts: {
2744
89
  total: number;
2745
90
  };
2746
91
  /**
2747
- * Accept the quote, then observe it to its first terminal outcome.
2748
- *
2749
- * The handle's contract, stated once: it observes the payment up to and
2750
- * including the first terminal outcome, and every recovery past that point is
2751
- * observed on `client.onUpdate` — keyed by the tagged `RouteResult.swapId`, so
2752
- * the two views join. `client.onUpdate` replays synchronously on subscribe, so
2753
- * a swap that was already terminal by the time we subscribed still resolves.
92
+ * Accept the quote, then observe it up to its first terminal outcome; recovery past that is observed
93
+ * on `client.onUpdate`, keyed by the same `RouteResult.swapId`. `onUpdate` replays synchronously, so
94
+ * an already-terminal swap still resolves.
2754
95
  */
2755
96
  declare const swapHandle: (railId: string, client: SwapRailClient, quote: Quote) => Promise<PaymentHandle>;
2756
97
 
2757
98
  /**
2758
- * `lightning` — pay a BOLT11 invoice out of an Arkade balance, through the v2
2759
- * swap client.
2760
- *
2761
- * The rail id is a registry key with published history: the factory deleted
2762
- * with `packages/boltz-swap` registered `"lightning"`, and a key is what an
2763
- * app's `priority` array and `disabled` list name. It therefore stays
2764
- * `lightning` even though Q12 renamed the lightning *asset* namespace to
2765
- * `bolt11` — the divergence between a registry key and an asset vocabulary is
2766
- * recorded here, not resolved by a rename that would break every consumer's
2767
- * preferences.
99
+ * `lightning` — pay a BOLT11 invoice out of an Arkade balance, through the v2 swap client.
2768
100
  *
2769
- * The whole rail is an adapter. The invoice fixes the amount, the client
2770
- * verifies and prices the route, `accept()` persists before it funds, and the
2771
- * drive owns everything after — so there is no `persist`, no `awaitSettlement`
2772
- * and no solver selection to configure here.
101
+ * The rail id stays `lightning` although the asset namespace is `bolt11`: it is a published registry
102
+ * key that apps' `priority` and `disabled` lists name, so renaming would break their preferences.
103
+ * The rail is only an adapter; persistence, settlement and solver selection live in the client.
2773
104
  */
2774
105
 
2775
106
  declare const LIGHTNING_RAIL = "lightning";
2776
- /**
2777
- * Register alongside core's rails. The deleted factory's ranking was
2778
- * `["ark", "lightning", "onchain-swap", "onchain"]`; see
2779
- * {@link createSwapPaymentRouter}.
2780
- */
107
+ /** Register alongside core's rails; see {@link createSwapPaymentRouter} for the ranking. */
2781
108
  declare function lightningRail(client: SwapRailClient): PaymentRail;
2782
109
 
2783
110
  /**
2784
- * `onchain-swap` — pay an L1 address out of an Arkade balance through a solver,
2785
- * via the v2 swap client.
2786
- *
2787
- * Registered alongside core's `onchain` rail (the collaborative exit) and
2788
- * ranked ahead of it, with both left registered: the default is a *preference*,
2789
- * not a restriction. The preference self-heals by amount — an out-of-range
2790
- * request drops this rail at `available()` and `onchain` wins with no error.
2791
- *
2792
- * The id is the deleted factory's published registry key, `"onchain-swap"`,
2793
- * kept for the reason the `lightning` rail keeps its own: a rail id is what an
2794
- * app's `priority` array names.
2795
- *
2796
- * **The claim fee is this rail's whole subtlety.** On `arkade -> onchain` the
2797
- * trader claims the solver's L1 HTLC itself, and that claim's fee comes out of
2798
- * the HTLC output — `payout = utxo.amount - fee`. So the sats the recipient
2799
- * actually receives are less than the sats the solver locks, by an amount the
2800
- * swap quote knows nothing about. A rail that quoted the solver's spread alone
2801
- * would be reporting a fee it does not charge, and would win a ranking against
2802
- * the collaborative exit that it should lose.
111
+ * `onchain-swap` — pay an L1 address out of an Arkade balance through a solver, via the v2 swap
112
+ * client. Ranked ahead of core's `onchain` rail with both registered: an out-of-range request
113
+ * drops this rail at `available()` and `onchain` wins with no error. The id is what an app's
114
+ * `priority` array names, so it must stay `"onchain-swap"`.
2803
115
  *
2804
- * This rail therefore takes a claim fee-rate policy at construction and grosses
2805
- * the swap up by the estimate: it asks the solver for `amount + claimFee` on the
2806
- * take leg, so what lands after the claim is the `amount` the caller asked for,
2807
- * and it reports the estimate inside `fee` where a ranking can see it. A fee
2808
- * rate is environment-specific and is nobody's to default — the same reason
2809
- * `CorridorOverrides.onchain.claim` has no default.
2810
- *
2811
- * The same arithmetic gives the rail its floor: a payout under
2812
- * {@link ONCHAIN_DUST_SATS} is one `buildHtlcClaim` refuses to build, so an
2813
- * amount that small drops the rail at `available()` and is refused outright at
2814
- * `quote()` — before a lockup exists, rather than after one is funded.
116
+ * **The claim fee.** The trader claims the solver's L1 HTLC itself and the fee comes out of the
117
+ * output (`payout = utxo.amount - fee`), which the swap quote knows nothing about. So the rail
118
+ * grosses the take leg up by the estimated claim fee and reports it inside `fee`; quoting the
119
+ * spread alone would understate the cost and win rankings it should lose. A payout under
120
+ * {@link ONCHAIN_DUST_SATS} is refused before a lockup exists, not after one is funded.
2815
121
  */
2816
122
 
2817
123
  declare const ONCHAIN_SWAP_RAIL = "onchain-swap";
2818
124
  interface OnchainSwapRailDeps {
2819
125
  /**
2820
- * Sat/vB the trader's L1 claim will be built at — the rate the corridor's
2821
- * own `claim` dep will use.
2822
- *
2823
- * No default, and the rail refuses to exist without it: the fee comes out
2824
- * of the recipient's payout, so a rail with no rate either quotes a fee it
2825
- * does not charge or short-pays the recipient. Neither is a default.
126
+ * Sat/vB the trader's L1 claim will be built at — the rate the corridor's own `claim` dep
127
+ * uses. Required: without it the rail either quotes a fee it does not charge or short-pays
128
+ * the recipient.
2826
129
  */
2827
130
  readonly claimFeeRateSatVb: number;
2828
131
  /** vsize the claim is priced at. Defaults to {@link ONCHAIN_CLAIM_VSIZE}. */
@@ -2838,94 +141,48 @@ declare const claimFeeSats: (deps: OnchainSwapRailDeps) => bigint;
2838
141
  declare function onchainSwapRail(client: SwapRailClient, deps: OnchainSwapRailDeps): PaymentRail;
2839
142
 
2840
143
  /**
2841
- * The router that puts lightning and `arkade -> onchain` back into a payment
2842
- * app's reach.
2843
- *
2844
- * Core's `createDefaultPaymentRouter(wallet)` registers `ark` and `onchain` and
2845
- * nothing else. The two swap rails never lived there — they were in
2846
- * `packages/boltz-swap`, behind a second overload with the priority
2847
- * `["ark", "lightning", "onchain-swap", "onchain"]`, and ts-sdk #811 removed
2848
- * them along with the package. This is that overload's shape, rebuilt on the v2
2849
- * client.
144
+ * A payment router with the lightning and `arkade -> onchain` swap rails on top of core's
145
+ * `ark` and `onchain`. The rails close over their own deps rather than widening core's
146
+ * published `RouterContext` (whose legacy `swaps` slot is ignored).
2850
147
  *
2851
- * **The rails close over their own dependencies, and `RouterContext` is not
2852
- * re-opened.** Widening core's context was the alternative and it is the wrong
2853
- * half: it edits a published payment type, re-imports the `swaps?: unknown`
2854
- * smell that was deliberately deleted, and asks core to name things it cannot —
2855
- * a repository, a transport, a discovery index. A rail factory over an
2856
- * already-constructed `SwapClient` names none of that in core.
2857
- *
2858
- * This factory stays out of core's own, which is pinned at exactly
2859
- * `["ark", "onchain"]`. Registering the swap rails is the app's decision, and
2860
- * the ranking it gets is a *preference*: both `onchain-swap` and `onchain` stay
2861
- * registered, so an amount outside the solver's range drops the swap rail at
2862
- * `available()` and the collaborative exit wins with no error.
148
+ * Both `onchain-swap` and `onchain` stay registered, so an amount outside the solver's
149
+ * range drops the swap rail at `available()` and the collaborative exit wins, no error.
2863
150
  */
2864
151
 
2865
- /** The deleted factory's ranking, and the one this factory ships. */
152
+ /** The ranking this factory ships (the removed boltz-swap overload's). */
2866
153
  declare const SWAP_ROUTER_PRIORITY: readonly string[];
2867
154
  interface SwapPaymentRouterConfig extends OnchainSwapRailDeps {
2868
155
  /** Overrides the shipped ranking; `disabled`, `caps` and `tieBreak` pass through. */
2869
156
  readonly prefs?: RouterPreferences;
2870
157
  }
2871
158
  /**
2872
- * Core's four rails plus the two this package supplies, ranked as the deleted
2873
- * factory ranked them.
159
+ * Core's rails plus the two this package supplies, ranked by {@link SWAP_ROUTER_PRIORITY}.
2874
160
  *
2875
- * Takes the concrete `Wallet` because that is what `RouterContext` holds — core
2876
- * types it as the class, not `IWallet` — and the already-constructed client,
2877
- * because building one here would put storage, discovery and corridor policy
2878
- * behind a payment-router call that has no business deciding any of them.
161
+ * Takes the concrete `Wallet` because only it reaches `arkProvider`, which the `onchain`
162
+ * rail's fee source needs; and an already-constructed client so storage, discovery and
163
+ * corridor policy are not decided behind a router call.
2879
164
  */
2880
165
  declare function createSwapPaymentRouter(wallet: Wallet, client: SwapRailClient, config: SwapPaymentRouterConfig): PaymentRouter;
2881
166
 
2882
167
  /**
2883
- * Fourteen outcomes onto four payment statuses — the only artefact M7 mints.
2884
- *
2885
- * Declared **total** even though a send rail cannot reach every member, because
2886
- * a partial map is where the collapse hides: an outcome with no row does not
2887
- * fail loudly, it renders as whatever the lookup happens to return.
168
+ * Fourteen outcomes onto four payment statuses.
2888
169
  *
2889
- * The projection is lossy by construction and the loss is recoverable, which is
2890
- * the whole design. `refunded` and `lapsed` both land on `failed` — P6 exists so
2891
- * those two never become one word, and the difference survives on the update's
2892
- * `error`, which core's `PaymentHandle` docblock already reserves for it. No
2893
- * fifth `PaymentStatus` is proposed: a status is what a payment UI branches on,
2894
- * and "the trader's value came back" versus "the incoming payment never arrived"
2895
- * is a sentence, not a branch.
170
+ * Total even where a send rail cannot reach a member: a partial map fails silently, rendering a
171
+ * missing outcome as whatever the lookup returns. `refunded` and `lapsed` both become `failed`;
172
+ * the difference survives on the update's `error`, not a fifth status.
2896
173
  *
2897
- * **Where the rail goes terminal is a decision, not a rounding.** It goes
2898
- * terminal at `refunding`, not at `refunded`: `makeHandle` clears its subscriber
2899
- * set on a terminal update and replays-without-registering afterwards, so the
2900
- * `refunded` that follows could not reach that handle anyway — and holding
2901
- * terminality back until the refund resolves would hang every
2902
- * `settled({ timeoutMs })` caller for a whole refund window. The refund is
2903
- * observed through `client.onUpdate` and `swaps()`, keyed by the tagged
2904
- * `RouteResult.swapId`.
2905
- *
2906
- * The same rule answers the `unblock` backslide. `needs_recovery -> funded` is
2907
- * a legal re-entry that crosses the terminality boundary the rail just drew; it
2908
- * is emitted rather than swallowed, because the drive's idempotence key is the
2909
- * DERIVED outcome and the second `funded` is a new key — delivered on
2910
- * `client.onUpdate`, never through the handle, which stays terminal. A handle
2911
- * observes a payment up to and including its first terminal outcome; every
2912
- * recovery past that point is observed on the client's update stream.
174
+ * The rail goes terminal at `refunding`, not `refunded`: `makeHandle` drops subscribers on a
175
+ * terminal update, so `refunded` could not reach the handle anyway, and waiting would hang
176
+ * `settled({ timeoutMs })` for a whole refund window. Later updates (the refund, or an `unblock`
177
+ * `needs_recovery -> funded` re-entry) arrive on `client.onUpdate`, keyed by `RouteResult.swapId`.
2913
178
  */
2914
179
 
2915
- /**
2916
- * The projection, total over {@link Outcome}.
2917
- *
2918
- * The `on the rail` column of M7's table is not encoded here: a send rail
2919
- * cannot reach `open`, `filled`, `cancelling`, `cancelled` or `lapsed`, but a
2920
- * map that refused them would be a map with holes, and the point of totality is
2921
- * that there are none.
2922
- */
180
+ /** The projection, total over {@link Outcome}. */
2923
181
  declare const PAYMENT_STATUS: {
2924
182
  /** Persisted, funding not broadcast. */
2925
183
  readonly accepted: "pending";
2926
184
  readonly funding: "pending";
2927
- /** The lockup is funded. Nothing has emitted `"sent"` in core since the
2928
- * `onchain-swap` rail left with `packages/boltz-swap`. */
185
+ /** The lockup is funded. */
2929
186
  readonly funded: "sent";
2930
187
  /** Asset swaps only: an unfilled offer. */
2931
188
  readonly open: "pending";
@@ -2954,4 +211,4 @@ declare const paymentStatusOf: (outcome: Outcome) => PaymentStatus;
2954
211
  /** Whether this status ends the handle's observation. Core's own rule. */
2955
212
  declare const isTerminalStatus: (status: PaymentStatus) => boolean;
2956
213
 
2957
- export { AcceptConflict, type AcceptInput, type AddressParams, AmbiguousDestination, AmountEncodingUnsupported, AmountMismatch, AmountOn, type ArkadeCorridorDeps, Artifact, type AssetAliasTable, AssetId, AssetRef, AssetSwapId, AssetSwapRepository, type AttestingRfqTransport, CORRIDOR_FACTORIES, CardMarketRef, type ChainSourceBackend, type ClaimedDestination, ClientDisposed, Corridor, type CorridorBase, type CorridorClaim, type CorridorCovenant, type CorridorDeadline, type CorridorDeps, type CorridorDepsByCorridor, type CorridorDrive, type CorridorFactory, CorridorId, type CorridorLockup, type CorridorModule, type CorridorOverrides, type CorridorPass, type CorridorRecordStore, type CorridorSet, CorridorSwapRecord, DEFAULT_INVOICE_EXPIRY_SECONDS, type DiscoveryConfig, type DiscoveryIndex, type DiscoveryIndexInput, type DiscoveryLeg, type DiscoverySnapshot, DiscoverySnapshotUnavailable, type DriveMode, type DriveRefusal, type ExchangeOptions, FEED_TTL_MS, type FeeCeiling, type FeedFetch, type FeedQuoteInput, INDEXED_NETWORKS, INVOICE_HRPS, InconsistentRoute, IndexedDbAssetSwapRepository, Instrument, InsufficientFunds, type L1Tip, LIGHTNING_DRIVE, LIGHTNING_RAIL, type LightningCorridorDeps, type LockupOwner, type Market, MarketBackend, type MarketCandidate, MarketRef, MarketsCacheEntry, MaxFeeExceeded, MissingCorridorDep, NetworkRef, NotCancellable, ONCHAIN_DRIVE, ONCHAIN_SWAP_RAIL, type ObservationSeam, type OfferPreparation, OfferSwapRecord, type OnchainClaim, type OnchainCorridorDeps, type OnchainSwapRailDeps, OperatorUnreachable, Outcome, PAYMENT_STATUS, type ParsedRfqQuote, type PayOptions, type PayResult, PinnedAmount, Pubkey, Quote, type QuoteCheck, QuoteExpired, QuoteId, QuoteInput, type QuotePreparation, QuoteVerificationFailed, Rail, RankedBid, type ReceiveOptions, type ReceiveRequest, type RecordSink, type RecoveryResult, type RegisteredAsset, type ResolveDeps, ResolvedEndpoint, type ResolvedRoute, type RfqAuctionPolicy, type RfqPreparation, type RfqQuoteInput, type RfqRendezvous, type RfqTransportFactory, Route, RouteResolution, type RouteSide, SWAP_ERROR_NAMES, SWAP_ROUTER_PRIORITY, SnapshotRef, Swap, type SwapClient, type SwapClientConfig, type SwapDrive, type SwapDriveConfig, SwapDriveRefusedError, type SwapError, type SwapErrorName, SwapFamily, type SwapFilter, SwapOperator, SwapPaymentFailedError, type SwapPaymentRouterConfig, type SwapPolicy, type SwapRailClient, SwapRecord, SwapRefusal, SwapUpdate, Unsubscribe, UnsupportedRoute, type VerbDeps, acceptQuote, aliasTableFrom, applyOfferSpend, arkadeCorridor, assembleRoute, attesting, canonicalAssetId, cardMarketOf, chainSourceOver, chooseMarket, claimFeeSats, conflictingFields, corridorRecordStore, corridorSet, createSwapClient, createSwapDrive, createSwapPaymentRouter, decodeBolt11, discoveryIndex, eligibleMarkets, enforceFeeCeiling, esploraChainSource, esploraTip, exchange, feedFetch, isAddressable, isCardMarket, isIndexedNetwork, isSwapError, isTerminalStatus, isUsableCard, lightningCorridor, lightningRail, liveArkadeInfo, marketBackendOf, marketKeyOf, marketRefOf, networksOfInvoiceHrp, nostrTransportFactory, offerFactsOf, offerRecordSource, onchainCorridor, onchainSwapRail, parseRfqQuote, pay, paymentStatusOf, publicAssetId, quoteFromFeed, quoteViaRfq, railAvailable, readableRecord, receive, receiverExact, resolveCorridorBase, resolveCorridorDeps, resolveRoute, rfqLeg, rfqPairFor, rfqRecordOf, satsOf, scopedToRail, splitRecords, swapHandle, swapRecordOf, toDiscoveryLeg, usableMarkets, verifyPair, verifyQuoteTtl, verifyQuotedAmount, verifyReceiveInvoiceFacts, verifyReceiveWindow, verifyResponder, verifySendInvoice, verifySendWindow, verifyingDerivation, walletLockupIndexer, withCanonicalAmount, withOfferStatus, withRfqState };
214
+ export { AssetSwap, AssetSwapRepository, IndexedDbAssetSwapRepository, LIGHTNING_RAIL, MarketsCacheEntry, ONCHAIN_SWAP_RAIL, type OnchainSwapRailDeps, Outcome, PAYMENT_STATUS, Quote, QuoteInput, RfqSwapPageCursor, RfqSwapPageFilter, RouteResolution, SWAP_ROUTER_PRIORITY, Swap, SwapPaymentFailedError, type SwapPaymentRouterConfig, type SwapRailClient, SwapRecord, SwapUpdate, Unsubscribe, claimFeeSats, createSwapPaymentRouter, isTerminalStatus, lightningRail, onchainSwapRail, paymentStatusOf, railAvailable, receiverExact, swapHandle };