@arkade-os/swap 0.1.0-rc.9 → 0.1.0

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 (57) hide show
  1. package/README.md +261 -252
  2. package/dist/advanced.cjs +6376 -3097
  3. package/dist/advanced.d.cts +325 -282
  4. package/dist/advanced.d.ts +325 -282
  5. package/dist/advanced.js +343 -34
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-FMRAV77W.js +3065 -0
  8. package/dist/{chunk-NS3K6BZG.js → chunk-HRMWBULL.js} +1746 -628
  9. package/dist/chunk-WKJFXXSR.js +3382 -0
  10. package/dist/index.cjs +6809 -3915
  11. package/dist/index.d.cts +71 -243
  12. package/dist/index.d.ts +71 -243
  13. package/dist/index.js +131 -167
  14. package/dist/lockupContract-D7BNjksX.d.ts +148 -0
  15. package/dist/lockupContract-G-9CNRMq.d.cts +148 -0
  16. package/dist/node/index.cjs +61 -10
  17. package/dist/node/index.d.cts +307 -635
  18. package/dist/node/index.d.ts +307 -635
  19. package/dist/node/index.js +65 -10
  20. package/dist/nostr.cjs +427 -49
  21. package/dist/nostr.d.cts +59 -70
  22. package/dist/nostr.d.ts +59 -70
  23. package/dist/nostr.js +268 -36
  24. package/dist/offer-CcJfx5Fj.d.cts +269 -0
  25. package/dist/offer-DdB1M6FZ.d.ts +269 -0
  26. package/dist/offerFillPlan-BII0PW92.d.cts +1642 -0
  27. package/dist/offerFillPlan-CNTLVD7j.d.ts +1642 -0
  28. package/dist/protocol.cjs +5650 -4280
  29. package/dist/protocol.d.cts +258 -328
  30. package/dist/protocol.d.ts +258 -328
  31. package/dist/protocol.js +200 -224
  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-DmPzpbd7.d.ts +2342 -0
  41. package/dist/repository-DqdLVrVv.d.cts +2342 -0
  42. package/dist/{rfq-BO6o7NwS.d.ts → rfq-C0tHOvn6.d.cts} +323 -444
  43. package/dist/{rfq-BO6o7NwS.d.cts → rfq-C0tHOvn6.d.ts} +323 -444
  44. package/dist/watch-BonYT9af.d.cts +74 -0
  45. package/dist/watch-CmJQDtsy.d.ts +74 -0
  46. package/package.json +10 -10
  47. package/dist/chunk-JFKGMPMH.js +0 -3456
  48. package/dist/chunk-LLG7RD2T.js +0 -1499
  49. package/dist/chunk-U7VWWTL6.js +0 -66
  50. package/dist/errors-CNISbN0M.d.ts +0 -2218
  51. package/dist/errors-DwNhIP0N.d.cts +0 -2218
  52. package/dist/lockupContract-C8-Mcg69.d.ts +0 -664
  53. package/dist/lockupContract-mIt4syse.d.cts +0 -664
  54. package/dist/repository-CGPLbjBe.d.ts +0 -3489
  55. package/dist/repository-DSGGq0ct.d.cts +0 -3489
  56. package/dist/watch-DWyVqyEN.d.cts +0 -96
  57. package/dist/watch-DmvHNX6T.d.ts +0 -96
@@ -1,2218 +0,0 @@
1
- import { IWallet, NetworkName, Network, SignerSet, ArkadeInfo, VHTLC, ProvisionedKey, ProvisionedClaimSecret } from '@arkade-os/sdk';
2
- import { a$ as SwapOperator, c as AssetSwapRepository, j as Pubkey, b1 as RfqSwapManagerCallbacks, C as Corridor, I as Instrument, b2 as RfqSwapActionName, N as NetworkRef, A as AssetId, af as SnapshotRef, _ as MarketBackend, K as CardMarketRef, $ as MarketRef, w as AssetRef, o as AmountOn, ag as Swap, M as CorridorId, U as DepositArtifact, i as QuoteInput, a3 as Quote, a8 as RankedBid, aj as SwapUpdate, ak as Unsubscribe, S as SwapRecord, Q as QuoteId, a1 as Outcome, L as LockupSpendIndexer, a_ as SwapContractRegistry, g as ResolvedEndpoint, P as PinnedAmount, O as OfferSwapRecord, y as AssetSwapId, ah as SwapFamily, f as RouteResolution } from './repository-CGPLbjBe.js';
3
- import { I as InvoiceFacts, C as ChainSource, R as RfqQuote, e as RfqTransport, L as LightningSendContractParams, f as LightningReceiveContractParams, O as OnchainHtlc, g as OnchainHtlcParams, h as OnchainNetwork, S as SwapRefusal } from './rfq-BO6o7NwS.js';
4
- import { Network as Network$1, LocalCardInput, DiscoveredMarket, Side, OfferPlan } from '@arkade-os/solver-discovery';
5
-
6
- /**
7
- * What a corridor is given, what a caller may replace, and where "overridden to
8
- * nothing" is refused.
9
- *
10
- * §6's rules stand as written; what is added here is a shape, because
11
- * `chain?: ChainSource` cannot tell "absent, use the default" from "disabled,
12
- * deliberately". Almost every override field is `T | null`: `undefined` takes
13
- * the default, `null` is the refusal, and {@link resolveCorridorDeps} throws
14
- * {@link MissingCorridorDep} naming the dep. It cannot reuse the facade's
15
- * `need()` guard, which tests `value === undefined` and passes a deliberate
16
- * `null` straight through. The one exception is documented where it lives:
17
- * the onchain claim fee-rate, whose "disabled" is a working manual mode
18
- * rather than a missing dep.
19
- *
20
- * Resolution runs when a route first touches a corridor and never at
21
- * construction — a missing dep for a corridor nobody uses is not an error, which
22
- * is `MissingCorridorDep`'s own boundary note and what §6 means by "at quote
23
- * time". The registry beside this file is what memoizes that.
24
- *
25
- * Four keys, not three: §6 gives lightning two overridable deps and the
26
- * covclaimd deployment key is the second. The operator seam and the co-signer
27
- * key are deliberately NOT among them — an override there is a trust anchor §6
28
- * never granted — so the co-signer arrives on {@link CorridorBase} instead, the
29
- * way the facade already threads it.
30
- */
31
-
32
- /**
33
- * The facts every module reads and no caller replaces.
34
- *
35
- * Both wallet and operator seam, and the split is what each is for: the wallet
36
- * answers *who and where* — it is the only thing that can make the live,
37
- * fail-closed info read, since `SwapOperator.getInfo()` takes no options — and
38
- * the operator seam answers *submit and finalize*. Collapsing either into the
39
- * other would delete a seam the unit tests already double.
40
- */
41
- interface CorridorBase {
42
- readonly wallet: IWallet;
43
- readonly operator: SwapOperator;
44
- /** The network the live operator info named. */
45
- readonly networkName: NetworkName;
46
- /** Address parameters for {@link networkName}. */
47
- readonly network: Network;
48
- /** The operator's signer set, for the rotation-aware recipient check. */
49
- readonly signerSet: SignerSet;
50
- /**
51
- * Covenant co-signer override, 33-byte compressed hex.
52
- *
53
- * A dep of the arkade module and not a `CorridorOverrides` key, by the same
54
- * rule that keeps the operator seam out of them. Required on `testnet` and
55
- * `signet`, which `EMULATOR_PUBKEYS` does not pin.
56
- */
57
- readonly emulatorPubkey?: string;
58
- /** For hosts without a global `fetch`, and for tests. */
59
- readonly fetchImpl?: typeof fetch;
60
- /**
61
- * The client's storage, if it was given one.
62
- *
63
- * Here rather than only in the override matrix so the two seams cannot be
64
- * two different objects: a client that takes a repository and an arkade
65
- * override that names one would otherwise write records to one and read the
66
- * markets cache from the other. The override still wins where it is set,
67
- * and a deliberate `null` there still refuses.
68
- */
69
- readonly repository?: AssetSwapRepository;
70
- }
71
- /**
72
- * §6's override matrix, with each field widened to admit the refusal.
73
- *
74
- * An override replaces a dependency inside an implemented corridor. It never
75
- * enables a route, never selects a solver or transport, and never alters
76
- * settlement behaviour — and each one is a named trust anchor: the chain source
77
- * is whose L1 view evidence is reconciled against, the decoder is who validates
78
- * an invoice before display, the covclaimd key is who may open the sealed claim
79
- * packet, the repository is where persist-first lands.
80
- */
81
- interface CorridorOverrides {
82
- arkade?: {
83
- /** Where persist-first lands. Defaults to the client's own
84
- * `repository`, so the two seams are one object; `null` refuses. */
85
- repository?: AssetSwapRepository | null;
86
- };
87
- lightning?: {
88
- /** Default: the package's own {@link decodeBolt11}. */
89
- decode?: ((bolt11: string) => InvoiceFacts) | null;
90
- /** Default: none — nothing is sealed and no packet is sent, so the
91
- * trader must claim its own lockup before `refund_locktime`. */
92
- covclaimd?: {
93
- pubkey: Pubkey;
94
- } | null;
95
- };
96
- onchain?: {
97
- /** Default: `ESPLORA_URL[network]`. The override is the URL, not a
98
- * `ChainSource`: there is no wallet-held provider to substitute. */
99
- chain?: {
100
- esploraUrl: string;
101
- } | null;
102
- /**
103
- * How the trader's L1 claim is built and broadcast. Default: see
104
- * {@link OnchainCorridorDeps.claim} — synthesized from
105
- * {@link claimFeeRateSatVb} when one is resolvable, so an explicit
106
- * `null` here preserves manual mode.
107
- */
108
- claim?: OnchainClaim | null;
109
- /**
110
- * Sat/vB the trader's L1 claim will be built at — and, on the quote
111
- * path, the rate the take leg is grossed up by so the recipient nets
112
- * the requested amount after the claim's fee. Default:
113
- * {@link ONCHAIN_CLAIM_FEE_RATE_SATVB}, per network. Environment-
114
- * sensitive (mempool congestion moves it) and so overridable.
115
- *
116
- * `null` here is NOT the refusal the other override fields carry: it
117
- * is "no default claim", and manual mode is a meaningful state for
118
- * this dep rather than a broken one — the corridor still quotes
119
- * (forwarding the take leg verbatim) and still drives the lockup,
120
- * and the L1 claim is the caller's to make by hand.
121
- */
122
- claimFeeRateSatVb?: number | null;
123
- /**
124
- * The vsize the claim is priced at for the recipient-exact gross-up,
125
- * when a caller knows better than the constant. Default:
126
- * {@link ONCHAIN_CLAIM_VSIZE}; `null` is "no override given", like
127
- * `undefined` — the estimate is the constant either way. The claim
128
- * build itself measures its own transaction and never reads this.
129
- */
130
- claimVsize?: number | null;
131
- };
132
- }
133
- /**
134
- * Build and broadcast the L1 claim of an `arkade -> onchain` fill.
135
- *
136
- * The manager's own callback type, so a caller wires `claimOnchainFill` to it
137
- * without a second shape to translate through.
138
- */
139
- type OnchainClaim = RfqSwapManagerCallbacks["claimOnchain"];
140
- /**
141
- * The per-network default for the trader's L1 claim fee rate, sat/vB.
142
- *
143
- * One number for every network, and deliberately the RELAY FLOOR rather than a
144
- * market estimate: the rate both builds the claim and prices the
145
- * recipient-exact gross-up, so a value invented to look precise would be a lie
146
- * in two places at once — and an over-quoted test-network rate would short the
147
- * recipient. 1 sat/vB is what every esplora deployment here will relay and,
148
- * in practice on the test networks, what confirms in the next block. On
149
- * mainnet it is a floor a routing UI should override UPWARD in congestion —
150
- * the claim has a consensus deadline (`htlc.refundLocktime`), and a claim that
151
- * confirms slowly is a claim that can miss it, so a caller with fee-rate
152
- * information should spend it here.
153
- *
154
- * `Partial` on purpose: a network absent from this table means "no default",
155
- * and the corridor resolves to manual mode there rather than to a number
156
- * nobody justified. Every network the vocabulary knows is named; the Partial
157
- * is for the ones it learns later.
158
- */
159
- declare const ONCHAIN_CLAIM_FEE_RATE_SATVB: Partial<Record<NetworkName, number>>;
160
- /** The arkade corridor's deps. Only the repository is overridable. */
161
- interface ArkadeCorridorDeps {
162
- readonly wallet: IWallet;
163
- readonly operator: SwapOperator;
164
- readonly networkName: NetworkName;
165
- readonly network: Network;
166
- readonly signerSet: SignerSet;
167
- /**
168
- * The pinned per-network co-signer, or the caller's override.
169
- *
170
- * Resolved from the network NAME the wallet reports, never from a key the
171
- * operator reports about itself — `defaultEmulatorPubkey` refuses that
172
- * self-report by name, because the value ends up in a covenant leaf that
173
- * decides who can move the funds.
174
- */
175
- readonly emulatorPubkey: string;
176
- readonly repository: AssetSwapRepository | undefined;
177
- }
178
- /** The lightning corridor's deps. */
179
- interface LightningCorridorDeps {
180
- readonly networkName: NetworkName;
181
- readonly decode: (bolt11: string) => InvoiceFacts;
182
- /** `undefined` means no covclaimd is deployed — nothing is sealed and no
183
- * packet is sent. Not a missing dep. */
184
- readonly covclaimd: {
185
- pubkey: Pubkey;
186
- } | undefined;
187
- }
188
- /** The onchain corridor's deps. */
189
- interface OnchainCorridorDeps {
190
- readonly networkName: NetworkName;
191
- readonly chain: ChainSource;
192
- /**
193
- * How the trader's L1 claim is built and broadcast, when a caller supplies
194
- * one.
195
- *
196
- * The caller's callback, verbatim — never a synthesized one. The wallet-
197
- * backed DEFAULT claim is built one layer out, in the drive, which is the
198
- * seam that has the record store and the wallet in hand; what it needs
199
- * from here is {@link claimFeeRateSatVb}, and its absence — an override
200
- * `null` on it, or a network with no entry in
201
- * {@link ONCHAIN_CLAIM_FEE_RATE_SATVB} — is exactly what keeps manual
202
- * mode on. Without any claim the drive reports an `arkade -> onchain`
203
- * swap's L1 half blocked, with the reason naming the missing callback
204
- * rather than a counterparty who has done nothing wrong; the Arkade
205
- * lockup keeps being driven and refunded either way.
206
- *
207
- * A dep of the onchain corridor rather than a `SwapClientConfig` field,
208
- * because that is what it is: a route that never touches this corridor
209
- * never resolves it, and a deliberate `null` refuses at the same boundary
210
- * as the chain source.
211
- */
212
- readonly claim?: OnchainClaim;
213
- /**
214
- * The fee rate the onchain arm's two fee-paid places share, sat/vB.
215
- *
216
- * Feeds BOTH halves of the recipient-exact deal, and they must stay on one
217
- * number: the quote path grosses the take leg UP by the claim this rate
218
- * prices (`claimFeeSats`), and the default claim build prices the actual
219
- * claim with it. Quoting against one number and building against another
220
- * is how the recipient ends up short anyway.
221
- *
222
- * Resolved from the network's floor in {@link ONCHAIN_CLAIM_FEE_RATE_SATVB}
223
- * with the override winning; `undefined` when the network has no entry —
224
- * which is what keeps a deliberate "no default claim" (the override
225
- * `null`) and an unknown network on the same honest answer, rather than on
226
- * an invented rate.
227
- */
228
- readonly claimFeeRateSatVb?: number;
229
- /**
230
- * The vsize the gross-up prices the claim at; the claim build measures its
231
- * own transaction and never reads this. Default {@link ONCHAIN_CLAIM_VSIZE}.
232
- */
233
- readonly claimVsize?: number;
234
- }
235
- /** Which corridor gets which dep record. */
236
- interface CorridorDepsByCorridor {
237
- arkade: ArkadeCorridorDeps;
238
- lightning: LightningCorridorDeps;
239
- onchain: OnchainCorridorDeps;
240
- }
241
- /** Any corridor's deps. */
242
- type CorridorDeps = CorridorDepsByCorridor[Corridor];
243
- /**
244
- * A corridor's deps, with `undefined` taking the default and `null` refused.
245
- *
246
- * Per corridor, and never for all three at once: resolving a corridor a route
247
- * does not touch is what would turn a deliberate `null` on an unused corridor
248
- * into an error.
249
- */
250
- declare function resolveCorridorDeps<C extends Corridor>(corridor: C, overrides: CorridorOverrides | undefined, base: CorridorBase): CorridorDepsByCorridor[C];
251
- /**
252
- * The operator info read, wrapped so every way it can fail arrives as one
253
- * typed error.
254
- *
255
- * The whole read is wrapped rather than a matched subset of its failures:
256
- * `requireLive` re-throws the provider's raw error unwrapped, which is a
257
- * `FetchError`, a `ProviderUnavailableError`, an `ArkError`, a bare `Error` or a
258
- * `TimeoutError` depending on how the read failed — and across a service-worker
259
- * boundary it is a fresh `Error` whose only branchable identity is `cause.name`.
260
- * A `catch` on a matched set would let exactly those through untyped.
261
- *
262
- * `requireLive` is the caller's, and the two callers want opposite things.
263
- * Every covenant derivation reads live (§6), because a snapshot binds a covenant
264
- * to a signer key the operator may no longer co-sign for. A destination *parse*
265
- * does not derive anything, and the client's `resolve()` promises to answer
266
- * without new disclosure and offline — so it takes the wallet's own fallback
267
- * read, which is live when the operator is reachable and the persisted snapshot
268
- * when it is not.
269
- */
270
- declare const liveArkadeInfo: (wallet: IWallet, opts?: {
271
- requireLive?: boolean;
272
- }) => Promise<ArkadeInfo>;
273
- /**
274
- * The one operator read, made once for all three corridors.
275
- *
276
- * The network narrowing after it is core's own fail-closed one and stays that
277
- * way: an operator that answers with a network name this SDK does not know is
278
- * not unreachable, and resolving it to mainnet parameters is the failure mode
279
- * `getNetwork` exists to prevent.
280
- */
281
- declare const resolveCorridorBase: (input: {
282
- wallet: IWallet;
283
- operator: SwapOperator;
284
- emulatorPubkey?: string;
285
- fetchImpl?: typeof fetch;
286
- /** The client's storage, threaded so the arkade dep can default to it. */
287
- repository?: AssetSwapRepository;
288
- /** Defaults to `true` — see {@link liveArkadeInfo}. */
289
- requireLive?: boolean;
290
- }) => Promise<CorridorBase>;
291
-
292
- /**
293
- * One contract, three implementations.
294
- *
295
- * A corridor module owns four things: its parse claim over destination strings
296
- * and the {@link Instrument} that claim produces, the deps it closes over, the
297
- * observation seams a drive pass reads, and the lockup-owner axis the outcome
298
- * table keys on. Not the table itself — the module declares the axis, and the
299
- * drive layer writes the table against it.
300
- *
301
- * The key is the **corridor**, not v1's `RfqSwap["kind"]`. That union —
302
- * `lightning_send | onchain_send | lightning_receive` — is a route pair, and two
303
- * of its three members are the lightning corridor seen from opposite ends. The
304
- * kind-keyed `RfqCorridorHandler` in `../../rfqCorridor.ts` is untouched and
305
- * stays: `project`/`hydrate` are per-route facts about a *stored record*, and
306
- * folding them in here would make this module own a persistence schema it does
307
- * not decide.
308
- *
309
- * Registration is internal, exactly as `rfqCorridor.ts` argues for its own
310
- * registry: a corridor registered from outside would parse and quote and then
311
- * sit undriven, which is worse than not being registrable at all.
312
- */
313
-
314
- /**
315
- * A module's answer about one destination string. Three outcomes, not two.
316
- *
317
- * "An {@link Instrument} or nothing" cannot say *mine, and wrong* — a `tb1…` on
318
- * a mainnet wallet, another operator's Arkade address, a bolt11 the shape-only
319
- * classifier admits and the decoder then refuses. Collapsing those into *not
320
- * mine* hands a well-formed destination to `UnsupportedRoute`, which names the
321
- * wrong fault, so the refusal is its own arm and the registry turns it into
322
- * `AmbiguousDestination` with the reason attached.
323
- *
324
- * The two object arms are mutually exclusive by construction (`refused?: never`
325
- * / `claimed?: never`), so the registry's count over them is total.
326
- */
327
- type CorridorClaim = {
328
- claimed: Instrument;
329
- refused?: never;
330
- } | {
331
- refused: string;
332
- claimed?: never;
333
- } | undefined;
334
- /** What a drive pass reads. Two, and a solver status read is not one of them. */
335
- type ObservationSeam =
336
- /** Arkade access — `RfqSwapManagerDeps.indexer`. */
337
- "indexer"
338
- /** L1 access — `RfqSwapManagerDeps.chain`. */
339
- | "chain";
340
- /** A covenant a pass reads. */
341
- type CorridorCovenant =
342
- /** The Arkade-side VHTLC every corridor route has exactly one of. */
343
- "arkade_lockup"
344
- /** The L1 HTLC, which only `arkade -> onchain` adds. */
345
- | "onchain_htlc";
346
- /**
347
- * Whose covenant it is — the axis the outcome table keys on.
348
- *
349
- * *Which* lockup a pass reads does not discriminate: every route reads the same
350
- * Arkade lockup and only `arkade -> onchain` reads a second. What inverts is
351
- * ownership, and with it what to do about the deadline: on a give-side leg the
352
- * lockup is the TRADER's and the deadline is a moment to act after, on a
353
- * take-side leg it is the SOLVER's and the deadline is a moment to have acted
354
- * before.
355
- */
356
- type LockupOwner = "trader" | "solver";
357
- /** The deadlines the code already fixes. Margins belong to the drive layer. */
358
- type CorridorDeadline =
359
- /** `RfqSwapCommon.refundLocktime`, on every kind. */
360
- "refund_locktime"
361
- /** `OnchainSendSwap.htlc.refundLocktime`, on `arkade -> onchain` alone. */
362
- | "htlc_refund_locktime";
363
- /** One covenant a pass reads, with its owner and the deadline it runs against. */
364
- interface CorridorLockup {
365
- readonly covenant: CorridorCovenant;
366
- readonly owner: LockupOwner;
367
- readonly deadline: CorridorDeadline;
368
- }
369
- /**
370
- * Which side of a route this corridor is on: the trader gives on it, or takes
371
- * on it. The direction is what inverts every ownership answer below.
372
- */
373
- type RouteSide = "give" | "take";
374
- /** What a drive pass does about a route whose non-arkade leg is this corridor. */
375
- interface CorridorPass {
376
- /** Every covenant the pass reads, in the order it reads them. */
377
- readonly lockups: readonly CorridorLockup[];
378
- /** The actions the manager may execute; a subset of v1's own union. */
379
- readonly actions: readonly RfqSwapActionName[];
380
- /** The seams the pass reads. */
381
- readonly seams: readonly ObservationSeam[];
382
- }
383
- /**
384
- * A corridor's drive facts, per side of the route it serves.
385
- *
386
- * Partial on purpose, and each absence is a decision: `onchain` has no `give`
387
- * entry because `onchain -> arkade` is outside the `Route` union — covering its
388
- * Arkade half alone would produce a manager that silently lets the trader's L1
389
- * refund window pass — and `arkade` has neither, because `arkade -> arkade` is
390
- * an offer covenant with no lockup, no RFQ deadline and no manager action. On
391
- * every corridor route the arkade leg's lockup IS the route's lockup, and it is
392
- * declared once, by the counter-corridor's entry.
393
- */
394
- type CorridorDrive = Partial<Record<RouteSide, CorridorPass>>;
395
- /**
396
- * One corridor.
397
- *
398
- * `deps` are closed over at construction rather than passed per call: the
399
- * network, the operator's signer set and the decoder are all needed at the
400
- * parse, and none of them is in the destination string.
401
- */
402
- interface CorridorModule<D = unknown> {
403
- readonly corridor: Corridor;
404
- /**
405
- * This corridor's claim over `raw` — a bare destination or a BIP21 URI.
406
- *
407
- * **Sync, non-throwing and amount-blind**, and none of the three is this
408
- * module's to reopen: core's rail contract is `match(req, ctx): boolean`,
409
- * "classification only — amount-blind", and core's router calls it bare
410
- * inside `options()`. A plain Arkade destination stays core's own `ark` rail
411
- * and is wrapped by nothing, but one shape across all three beats a second
412
- * one for the corridor that happens not to be wrapped.
413
- */
414
- matches(raw: string): CorridorClaim;
415
- readonly deps: D;
416
- readonly drive: CorridorDrive;
417
- }
418
- /**
419
- * A module's factory, plus the one question that can be asked without deps.
420
- *
421
- * `target` is core's classifier for this corridor's destination class — the
422
- * same one `matches` extracts with, named once so there is no second spelling
423
- * to drift. The registry asks it FIRST, and that is what keeps
424
- * `MissingCorridorDep`'s contract: a bolt11 arriving while the onchain chain
425
- * source is overridden to `null` must not resolve the onchain corridor's deps,
426
- * because a missing dep for a corridor nobody uses is not an error.
427
- */
428
- interface CorridorFactory<D> {
429
- (deps: D): CorridorModule<D>;
430
- /** The destination class this corridor speaks for. Dep-free by
431
- * construction: core's classifiers read the string and nothing else. */
432
- readonly target: (raw: string) => string | undefined;
433
- }
434
-
435
- /** The shipped corridors. Total over `Corridor`, checked at compile time. */
436
- declare const CORRIDOR_FACTORIES: {
437
- readonly arkade: CorridorFactory<ArkadeCorridorDeps>;
438
- readonly lightning: CorridorFactory<LightningCorridorDeps>;
439
- readonly onchain: CorridorFactory<OnchainCorridorDeps>;
440
- };
441
- /** What a destination resolves to: the corridor that claimed it, and how it
442
- * settles. No asset — no destination class carries one, since every Arkade
443
- * asset shares a single address form. */
444
- interface ClaimedDestination {
445
- corridor: Corridor;
446
- instrument: Instrument;
447
- }
448
- /**
449
- * The corridors of one client, with deps resolved on first use.
450
- *
451
- * The laziness is the contract: `resolveCorridorDeps` throws
452
- * `MissingCorridorDep` for a dep overridden to `null`, and a missing dep for a
453
- * corridor nobody uses is not an error.
454
- */
455
- interface CorridorSet {
456
- /** The module for `corridor`, resolving and memoizing its deps on the first
457
- * call. Throws `MissingCorridorDep` when a dep of THIS corridor was
458
- * overridden to nothing. */
459
- get<C extends Corridor>(corridor: C): CorridorModule<CorridorDepsByCorridor[C]>;
460
- /**
461
- * Which corridor claims `raw`, if any.
462
- *
463
- * @throws {AmbiguousDestination} when more than one corridor claims it,
464
- * when the corridor that owns its class refuses it, or when nothing
465
- * classifies it at all.
466
- * @throws {MissingCorridorDep} when the corridor that owns this destination
467
- * has a dep disabled via overrides.
468
- * @returns `undefined` when core classifies the string but no corridor
469
- * serves it — an LNURL today — which becomes `UnsupportedRoute` at route
470
- * resolution rather than a parse failure here.
471
- */
472
- claim(raw: string): ClaimedDestination | undefined;
473
- }
474
- declare const corridorSet: (base: CorridorBase, overrides?: CorridorOverrides) => CorridorSet;
475
-
476
- /**
477
- * The alias layer: public ids down to the vocabulary discovery and RFQ speak.
478
- *
479
- * One way only. A public id is CAIP-19 and carries its rail; discovery keeps
480
- * chain-relative leg keys (a `Corridor` plus an `AssetInfo.id` of `"btc"` or
481
- * the 68-hex identity), and the two are not in bijection — several public ids
482
- * can share one discovery asset. Promising a round trip through it was the
483
- * mistake the earlier Q5 shape made; what does round-trip byte-for-byte is the
484
- * covenant identity itself, which this layer carries verbatim.
485
- *
486
- * Registry ratification of the CAIP form (Q11) does not block any of this: if
487
- * solver-registry adopts it, the table below shortens.
488
- *
489
- * The RFQ wire's `pair` string is not built here. It is `<from-leg>-><to-leg>`,
490
- * byte-compared by the solver and length-capped, and the quote path's request
491
- * builder owns it — a CAIP-19 id would both break the comparison and overrun
492
- * the cap.
493
- */
494
-
495
- /** What discovery names a leg by: its corridor, and the asset id on it. */
496
- interface DiscoveryLeg {
497
- corridor: Corridor;
498
- /** `"btc"`, or the 68-hex Arkade asset identity. */
499
- assetId: string;
500
- /** Full CAIP-19 id used by solver-discovery's canonical market selector. */
501
- marketId: AssetId;
502
- }
503
- /**
504
- * A public id down to its discovery leg.
505
- *
506
- * Total over the ids v2 can route and refusing everything else: an `eip155:` id
507
- * is grammar-valid and unserved (§9 is deferred), and a non-BTC asset on
508
- * lightning or L1 names a corridor that carries only BTC.
509
- */
510
- declare const toDiscoveryLeg: (id: AssetId) => DiscoveryLeg;
511
- /** One registry row: what a ticker canonicalizes to. */
512
- interface RegisteredAsset {
513
- id: AssetId;
514
- /** The display ticker. Matched case-insensitively; never an identity. */
515
- ticker: string;
516
- }
517
- /**
518
- * The table caller input is canonicalized against.
519
- *
520
- * Injected rather than fetched: M1 owns no network layer, and the quote path
521
- * fills this from discovery when it has one.
522
- */
523
- interface AssetAliasTable {
524
- /** The wallet's network. An id on any other network is not a candidate. */
525
- network: NetworkRef;
526
- assets: readonly RegisteredAsset[];
527
- }
528
- /**
529
- * The networks discovery publishes a market index for, restated as network
530
- * references.
531
- *
532
- * The two vocabularies are spelled identically and differ only in that core
533
- * carries `testnet` and discovery does not, so the narrowing is set membership
534
- * and nothing more. The `satisfies` is the pin: a rename on either side fails
535
- * to compile here instead of degrading into a silent "no index for this
536
- * network".
537
- */
538
- declare const INDEXED_NETWORKS: readonly ["bitcoin", "signet", "mutinynet", "regtest"];
539
- /**
540
- * Whether a market index can be fetched for `network`.
541
- *
542
- * Partial by construction, and `testnet` is the member outside it: an asset on
543
- * testnet is nameable — `arkade:testnet/slip44:0` is a valid id — there is
544
- * simply no published index to price it against. Which error that becomes is
545
- * the quote path's call, not this layer's.
546
- */
547
- declare const isIndexedNetwork: (network: NetworkRef) => network is Network$1;
548
- /**
549
- * Caller input to a public id: an id passes through validated, a ticker is
550
- * resolved against the table.
551
- *
552
- * Ticker matching is case-insensitive and scoped to the wallet's network, and a
553
- * ticker that matches more than one asset on that network is refused rather
554
- * than guessed — two assets called `USDT` are exactly the case where guessing
555
- * sends the money to the wrong one.
556
- */
557
- declare const canonicalAssetId: (input: string, table: AssetAliasTable) => AssetId;
558
-
559
- /**
560
- * Discovery, and the three states one `DiscoveredMarket[]` used to collapse.
561
- *
562
- * `discoverMarkets` answers one array for three different situations: no
563
- * registry configured (or a network with no published index), a stale cache
564
- * served because every source failed, and a reachable registry that lists
565
- * nothing. They are not the same answer and they do not deserve the same
566
- * behaviour, so this module separates them and carries the difference on the
567
- * snapshot rather than in a comment:
568
- *
569
- * - **No data at all** — no registry, an unindexed network, or an unreachable
570
- * one with nothing cached — is {@link DiscoverySnapshotUnavailable}. There is
571
- * no route state for "resolved against nothing".
572
- * - **A stale cache** resolves and prices, and is marked stale. It is still a
573
- * snapshot; what it cannot do is supply the key an addressed RFQ's responder
574
- * is checked against (see `live` below).
575
- * - **Reachable and empty** is a snapshot like any other, with no markets in it.
576
- * The route resolves; `quote()` is where an empty eligible set becomes
577
- * `UnsupportedRoute`.
578
- *
579
- * It wraps discovery rather than `discoverMarkets`, and the reason is the same
580
- * separation: `discover()` reports per-source outcomes and `discoverMarkets`
581
- * spends them on the way out. `discoverMarkets` itself is untouched — the
582
- * wallet's own wrapper around it keeps working — and the cache is the same
583
- * entry under the same key, so a v1 read warms a v2 quote and back.
584
- *
585
- * The cache is also a trust boundary. `isMarketShaped` revalidates four fields
586
- * on read and trusts the rest, `discovery_pubkey` and `transports` included, and
587
- * those two are precisely what an addressed RFQ addresses itself to. So a cached
588
- * card is revalidated here against every field this client depends on, and a
589
- * snapshot that came out of the cache is marked `live: false` — the responder
590
- * check refuses to pin against cache content whatever its shape.
591
- */
592
-
593
- /**
594
- * The default solver registry index per network, derived the way
595
- * `ESPLORA_URL[network]` is for the onchain chain source: the wallet reports a
596
- * network, and the client asks the reference registry's index for it.
597
- *
598
- * Every indexed network has an entry — the registry's CI publishes a per-network
599
- * index (possibly an empty one) for each, so a caller with nothing but `wallet`
600
- * and `repository` discovers against the same curation the ecosystem reads. An
601
- * explicit `registryUrl` overrides the default; `null` opts out of a registry
602
- * entirely.
603
- */
604
- declare const REGISTRY_URL: Record<Network$1, string>;
605
- /** Where the client's market data comes from. Every field is optional: absent
606
- * registry config falls back to {@link REGISTRY_URL} for the wallet's network,
607
- * and an injected snapshot needs no registry at all. */
608
- interface DiscoveryConfig {
609
- /**
610
- * The network's solver registry index URL.
611
- *
612
- * Absent means the network default ({@link REGISTRY_URL}), which an explicit
613
- * URL overrides — a self-hosted registry, a fixture, or a pinned fork.
614
- * `null` is the deliberate opt-out: no registry is asked for anything,
615
- * which — without an injected snapshot — is the unavailable case and not an
616
- * empty market set.
617
- */
618
- readonly registryUrl?: string | null;
619
- /** Locally pinned solver cards, merged with the registry's. */
620
- readonly localCards?: readonly LocalCardInput[];
621
- /**
622
- * Markets to resolve against without touching the network.
623
- *
624
- * Caller-supplied and therefore trusted the way config is: an injected
625
- * snapshot can pin an RFQ responder, where a cached one cannot.
626
- */
627
- readonly snapshot?: readonly DiscoveredMarket[];
628
- /** Overrides the network the wallet reports. For tests and multi-network hosts. */
629
- readonly network?: Network$1;
630
- readonly fetchImpl?: typeof fetch;
631
- /** Receives discovery warnings (stale index, skipped cards, …). */
632
- readonly logger?: (...args: unknown[]) => void;
633
- }
634
- /** A market set, and where it came from. */
635
- interface DiscoverySnapshot {
636
- readonly markets: readonly DiscoveredMarket[];
637
- readonly ref: SnapshotRef;
638
- }
639
- interface DiscoveryIndex {
640
- /**
641
- * The snapshot in hand, without touching the network — an injected one, one
642
- * this client already loaded, or the repository's cache.
643
- *
644
- * @throws {DiscoverySnapshotUnavailable} when there is none.
645
- */
646
- peek(): Promise<DiscoverySnapshot>;
647
- /**
648
- * A snapshot, fetching when there is none in hand or when asked to refresh.
649
- *
650
- * @throws {DiscoverySnapshotUnavailable} when the fetch leaves it with
651
- * nothing either.
652
- */
653
- load(opts?: {
654
- refresh?: boolean;
655
- }): Promise<DiscoverySnapshot>;
656
- }
657
- /**
658
- * Whether a card read back out of the cache is one this client may act on.
659
- *
660
- * Wider than `isMarketShaped`, and deliberately so: that predicate guards the
661
- * v1 pricing path, which reads asset ids and decimals, where this one guards a
662
- * path that also addresses a solver over a rendezvous the card names. A stored
663
- * entry outlives the schema that wrote it AND the storage it sits in, so every
664
- * field the client depends on is re-checked rather than four of them.
665
- */
666
- declare const isUsableCard: (value: unknown) => value is DiscoveredMarket;
667
- interface DiscoveryIndexInput {
668
- /** The network the wallet reported. */
669
- readonly network: NetworkName;
670
- readonly config?: DiscoveryConfig;
671
- /** Backs the shared markets cache. Without one, every load hits the registry. */
672
- readonly repository?: AssetSwapRepository;
673
- }
674
- /**
675
- * One client's view of the market index.
676
- *
677
- * Holds at most one snapshot and hands the same one back until it ages out or a
678
- * caller asks for a refresh, so a `resolve()` and the `quote()` after it agree
679
- * on what the market was — two loads a second apart returning different cards
680
- * would make the resolution the caller vetoed a different one from the quote
681
- * they got.
682
- */
683
- declare const discoveryIndex: (input: DiscoveryIndexInput) => DiscoveryIndex;
684
-
685
- /**
686
- * Market resolution: `(give.asset, take.asset, corridors)` to the card that
687
- * prices the swap, and the provenance that card leaves on the quote.
688
- *
689
- * The lookup itself is discovery's — `selectMarkets` matches a leg pair — and
690
- * this module supplies
691
- * the three things around it that the client cannot borrow: the policy filters
692
- * that run before disclosure, the canonical market key derived under the
693
- * protocol's own leg order rather than the card's, and the addressability check
694
- * that keeps an unreachable corridor card out of the candidate set instead of
695
- * failing at the transport.
696
- *
697
- * `findMarket` is not what this calls, and the reason is the candidate set:
698
- * that helper answers with the single best market of one orientation, and
699
- * `policy.selectMarket` is defined over every eligible card. Both orientations
700
- * are tried here for the same reason it tries them — a registry may publish
701
- * either leg as base.
702
- */
703
-
704
- /** One card that can price this route, with what the route needs read off it. */
705
- interface MarketCandidate {
706
- readonly card: DiscoveredMarket;
707
- /** Which side of the card the trader gives; the other side is received. */
708
- readonly give: Side;
709
- /** Which backend the card selects. The card decides, never the client. */
710
- readonly backend: MarketBackend;
711
- /** The canonical market key — see {@link marketKeyOf}. */
712
- readonly key: string;
713
- }
714
- /**
715
- * The market's canonical key, `<corridor>:<id>/<corridor>:<id>`, under
716
- * rfq-protocol.md §2's leg order: when exactly one leg is arkade it comes
717
- * first; when both or neither are, the legs sort lexicographically.
718
- *
719
- * Derived here, from the card in hand, rather than taken from `marketPairKey`,
720
- * which emits the card's own base/quote order. The two agree for every card the
721
- * registry's reducer validated — it enforces the arkade-as-base half — and
722
- * disagree for a card published outside it, which is where the miss would be
723
- * silent: both sides of a published negotiation derive this key independently
724
- * and subscribe by it, so a key one character apart is not an error either side
725
- * can report, it is a request nobody answers.
726
- */
727
- declare const marketKeyOf: (card: DiscoveredMarket) => string;
728
- /**
729
- * Whether a corridor card can actually be addressed.
730
- *
731
- * A corridor market is negotiated per trade over the rendezvous the card names,
732
- * so a card missing its key or its relays prices nothing, whatever its feed
733
- * says. Dropping it here rather than at the transport is what keeps "no market
734
- * serves this pair" one answer instead of two: an unaddressable card in the
735
- * candidate set would be selected, disclose nothing, and fail as a transport
736
- * error that reads like an outage.
737
- */
738
- declare const isAddressable: (card: DiscoveredMarket) => boolean;
739
- /** Which backend a card selects — the card decides it, never the client. */
740
- declare const marketBackendOf: (card: DiscoveredMarket) => MarketBackend;
741
- /**
742
- * The cards on a snapshot this client may act on at all, before any pair is
743
- * named: the policy's registry allowlist, then addressability.
744
- *
745
- * Shared by the routing read and `markets()`, so the escape hatch cannot offer
746
- * a card the quote path would then refuse.
747
- */
748
- declare const usableMarkets: (snapshot: DiscoverySnapshot, policy?: SwapPolicy) => DiscoveredMarket[];
749
- /**
750
- * Every card on the snapshot that serves this leg pair, best-ranked first,
751
- * after policy.
752
- *
753
- * The allowed-registry filter runs first and matches `source` exactly. It is
754
- * `source` and not `discovery_pubkey` because the latter is the field a cached
755
- * card carries unvalidated: filtering trust on untrusted content would give the
756
- * allowlist the shape of a check and none of the effect.
757
- *
758
- * `takeAmount` is the pinned trade size on the leg the trader receives, and it
759
- * is what makes a card's own `min/max` bounds mean something: without it a
760
- * snapshot serving the pair answers "eligible" for any size, and the swap rails'
761
- * documented self-healing — an out-of-range amount drops the rail at
762
- * `available()` and the collaborative exit wins — never fires.
763
- *
764
- * @param takeAmount The pin on the TAKE leg only, which is the side `wantSide`
765
- * names. Omitting it skips the bounds entirely — an unpinned read is not a
766
- * zero-sized trade. A GIVE-side pin is deliberately not converted and passed:
767
- * that would need a price this read does not have, so a give-side amount past
768
- * a card's ceiling still answers `eligible: 1` here and is refused by the
769
- * solver instead. That asymmetry is the known sharp edge of this parameter.
770
- */
771
- declare const eligibleMarkets: (snapshot: DiscoverySnapshot, legs: {
772
- give: DiscoveryLeg;
773
- take: DiscoveryLeg;
774
- }, policy?: SwapPolicy, takeAmount?: bigint) => MarketCandidate[];
775
- /**
776
- * The card that prices this swap: the best-ranked candidate, or the one the
777
- * application's policy chose instead.
778
- *
779
- * A veto — `undefined` from `selectMarket` — is not an error here. It empties
780
- * the eligible set, and an empty set is a route no market serves on this
781
- * snapshot, which is one condition with one answer whether it was emptied by
782
- * the registry, by the allowlist or by the application.
783
- */
784
- declare const chooseMarket: (candidates: readonly MarketCandidate[], policy?: SwapPolicy) => MarketCandidate | undefined;
785
- /** The provenance a candidate leaves on every quote it prices. */
786
- declare const marketRefOf: (candidate: MarketCandidate, snapshot: SnapshotRef) => CardMarketRef;
787
- /** A card's own provenance — the same fields {@link marketRefOf} writes, read
788
- * off the card rather than off a routed candidate. */
789
- declare const cardMarketOf: (card: DiscoveredMarket, snapshot: SnapshotRef, key: string, backend: MarketBackend) => CardMarketRef;
790
- /** Narrow a `MarketRef` to the card arm — the only one minted today. */
791
- declare const isCardMarket: (market: MarketRef) => market is CardMarketRef;
792
- /**
793
- * A market as the v2 client publishes it — one shape with {@link CardMarketRef},
794
- * the type `Quote.market` already points at.
795
- *
796
- * `markets()` is the escape hatch, and its return is deliberately the same card
797
- * a quote cites: a caller picking a market for a custom `quote()` reads the same
798
- * provenance the quote will carry, key for key and snapshot for snapshot.
799
- * Discovery's own `DiscoveredMarket` never crosses the v2 root — its asset ids
800
- * (`"btc"` or a 68-hex string) and its display `pair` are exactly the vocabulary
801
- * the alias layer exists to keep off it. The honest limit of the escape hatch
802
- * is that it carries no discovery asset id; an integrator needing the native
803
- * cards keeps the package's own discovery reader below the public surface.
804
- */
805
- type Market = CardMarketRef;
806
-
807
- /**
808
- * The three product-facing verbs, and the one thing they add.
809
- *
810
- * `pay`, `receive` and `exchange` compile a {@link QuoteInput}, call `quote`,
811
- * check `quote.fee` against a ceiling and call `accept`. Everything they call
812
- * was built in M3–M6; what they add is the ceiling — and what they subtract is
813
- * vocabulary. A product integrating payments never sees the words route,
814
- * corridor, market or quote.
815
- *
816
- * The verbs are deliberately thin, and one asymmetry is the reason they exist
817
- * at all: `receive` is what makes the artifact's exposure order unlosable. It
818
- * returns only after `accept()` has persisted, so a caller cannot show a payer
819
- * an invoice whose claim secret is still in memory — the ordering M4 bought,
820
- * stated in a signature.
821
- *
822
- * §5's fourth row — `pay` to a plain Arkade address — is not a swap and must
823
- * not become one. It delegates: same asset, same rail, rate 1, nothing swapped.
824
- * See {@link PayResult}.
825
- */
826
-
827
- /**
828
- * A fee ceiling: an amount, and the asset it is denominated in.
829
- *
830
- * The asset is not ceremony. M3/D denominates the fee on the give leg on
831
- * corridor routes and on the take leg on asset swaps, so a bare `bigint` names
832
- * no asset — and on `exchange` the caller cannot know which leg carries it
833
- * before quoting. A ceiling whose asset is not the fee's is a refusal rather
834
- * than a conversion: the SDK holds no rate, and inventing one to compare two
835
- * numbers is how a ceiling silently stops being one.
836
- *
837
- * The same shape on every verb and on {@link SwapPolicy.maxFee}, so the call
838
- * ceiling and the policy ceiling it is taken against are comparable without a
839
- * translation.
840
- */
841
- interface FeeCeiling {
842
- readonly amount: bigint;
843
- readonly asset: AssetId;
844
- }
845
- /**
846
- * What `pay` takes beside the destination.
847
- *
848
- * `amount` is what the *recipient* gets, and it is omitted exactly when the
849
- * destination pins it — an amount-bearing bolt11 does, and passing one beside
850
- * it is `AmountMismatch`. §9.5's EVM destinations grow a required `take` here;
851
- * they are deferred, so it is not declared yet.
852
- */
853
- interface PayOptions {
854
- /** Atomic units delivered to the recipient. Omitted when an invoice pins it. */
855
- readonly amount?: bigint;
856
- readonly maxFee?: FeeCeiling;
857
- }
858
- /**
859
- * What `receive` takes.
860
- *
861
- * `via` names the corridor because a receive has no instrument to parse — the
862
- * instrument *is* the artifact the solver mints, and it does not exist until
863
- * the quote comes back. `asset` is reserved for §9.5's EVM form: on the
864
- * implemented corridors the corridor carries BTC and nothing else, so naming
865
- * one would be a fact with nothing to disagree with.
866
- */
867
- interface ReceiveOptions {
868
- /** Atomic units the trader receives. */
869
- readonly amount: bigint;
870
- readonly via: CorridorId;
871
- /** §9.5, reserved: the asset arriving, where a corridor carries more than one. */
872
- readonly asset?: AssetRef;
873
- readonly maxFee?: FeeCeiling;
874
- }
875
- /**
876
- * What `exchange` takes: {@link QuoteInput} minus `to` and `via`, plus the
877
- * ceiling.
878
- *
879
- * Thin because `exchange` hides the two-step, not the vocabulary — an asset
880
- * swap names both assets by construction, and there is nothing left to infer.
881
- */
882
- interface ExchangeOptions {
883
- readonly give?: AssetRef;
884
- readonly take?: AssetRef;
885
- readonly amount?: bigint;
886
- readonly amountOn?: AmountOn;
887
- readonly maxFee?: FeeCeiling;
888
- }
889
- /**
890
- * The artifact a receive over corridor `C` comes back with.
891
- *
892
- * Corridor determines kind, not just shape: only `lightning` mints an invoice —
893
- * that corridor is the hand-off of a bolt11 the solver created, so the artifact
894
- * *is* the request's payload — and every other implemented receive is a deposit
895
- * the payer sends to. Without the conditional the return is the full
896
- * `Artifact` union, and `receive({ via: "lightning" }).artifact.bolt11` — the
897
- * exact thing the quickstart does — does not compile without a manual `kind`
898
- * check. Typed here, beside the verb, because the invoice choice is `receive`'s
899
- * promise rather than a fact about `Artifact` itself.
900
- *
901
- * Distributed over `C` for the reason {@link DepositArtifact} is: the default
902
- * `CorridorId` lands on the full union rather than on one member's fields
903
- * widened over every corridor's.
904
- */
905
- type ReceiveArtifact<C extends CorridorId = CorridorId> = C extends CorridorId ? C extends "lightning" ? {
906
- kind: "invoice";
907
- bolt11: string;
908
- } : DepositArtifact<C> : never;
909
- /**
910
- * What `receive` answers with: a {@link Swap} whose artifact is a guarantee
911
- * rather than a maybe.
912
- *
913
- * An intersection rather than a parallel record, because that is where the
914
- * guarantee gets *stated*: `Quote.artifact` and `Swap.artifact` are optional —
915
- * three of the four routes have nothing a counterparty must see — and a receive
916
- * always has one. Narrowing the field on the base type is not open to an
917
- * intersection, so this is the shape that says it.
918
- */
919
- type ReceiveRequest<C extends CorridorId = CorridorId> = Swap & {
920
- readonly artifact: ReceiveArtifact<C>;
921
- };
922
- /**
923
- * What `pay` answers with.
924
- *
925
- * Two arms, because §5's four destination rows are not four swaps. A bolt11 and
926
- * a `bc1…` cross a corridor and produce a {@link Swap}; a plain Arkade address
927
- * is a plain Arkade payment and produces a txid and no swap id. Manufacturing a
928
- * `Swap` for the second would be a swap record for something nothing swapped —
929
- * same asset, same rail, rate 1 — and rejecting it instead would put a branch in
930
- * every product's one pay box rather than once here.
931
- */
932
- type PayResult = {
933
- readonly kind: "swap";
934
- readonly swap: Swap;
935
- } | {
936
- readonly kind: "payment";
937
- readonly txid: string;
938
- };
939
- /** What a verb needs from the client it hangs off. */
940
- interface VerbDeps {
941
- readonly wallet: IWallet;
942
- quote(input: QuoteInput): Promise<Quote>;
943
- accept(quote: Quote): Promise<Swap>;
944
- /** {@link SwapPolicy.maxFee}, when the client was configured with one. */
945
- readonly policyMaxFee?: FeeCeiling;
946
- }
947
- /**
948
- * The effective ceiling, and the refusal when the quote is over it.
949
- *
950
- * The effective ceiling is the **minimum** of the call's and the policy's: a
951
- * policy ceiling a call could raise would be decorative, and a call ceiling a
952
- * policy could raise would make the tighter of two explicit instructions lose.
953
- * Either may be absent; both absent means no ceiling, which is the documented
954
- * default and not a zero.
955
- *
956
- * A ceiling denominated in another asset is refused as caller input rather than
957
- * as a member of §7's taxonomy: the taxonomy's members are conditions of the
958
- * swap, and this is a field naming the wrong unit — the same rule that keeps
959
- * "amount needs amountOn" a plain `Error`.
960
- *
961
- * @throws {MaxFeeExceeded} when `quote.fee` is over the effective ceiling —
962
- * between `quote` and `accept`, so nothing was funded.
963
- */
964
- declare const enforceFeeCeiling: (quote: Quote, call: FeeCeiling | undefined, policy: FeeCeiling | undefined) => void;
965
- /**
966
- * Pay a destination: a bolt11, a `bc1…`, or a plain Arkade address.
967
- *
968
- * The Arkade arm is checked first and against core's own parse, so a bare
969
- * address and a BIP21 `ark=` param behave identically here and in the `ark`
970
- * rail — one classification, not two that can drift. It settles through
971
- * `wallet.send`, which is what the `ark` rail settles through: fee 0 and
972
- * receiver-exact for free, with nothing to quote and nothing to persist.
973
- */
974
- declare const pay: (deps: VerbDeps, destination: string, options?: PayOptions) => Promise<PayResult>;
975
- /**
976
- * Ask for an incoming payment over `via`, and get back the artifact to show.
977
- *
978
- * The artifact is non-optional on the return type and the assertion behind it
979
- * is real: a receive route has one by construction, and a client that answered
980
- * without one has failed rather than answered.
981
- */
982
- declare const receive: <C extends CorridorId = CorridorId>(deps: VerbDeps, options: ReceiveOptions & {
983
- readonly via: C;
984
- }) => Promise<ReceiveRequest<C>>;
985
- /** Swap one Arkade asset for another. */
986
- declare const exchange: (deps: VerbDeps, options: ExchangeOptions) => Promise<Swap>;
987
-
988
- /**
989
- * Application policy: the vetoes and floors a client applies before it
990
- * discloses anything, plus the two names §10 reserved.
991
- *
992
- * Six members touch the quote path — four active here, two inert — and
993
- * {@link SwapPolicy.drive} is the lifecycle's. `maxFee` landed with M7, the
994
- * milestone that can enforce it: a ceiling declared before a layer applies it
995
- * is a field, not a policy.
996
- *
997
- * Every active member has the same shape of purpose: it runs BEFORE the RFQ
998
- * round trip that discloses an invoice or an amount. A policy that could only
999
- * reject a quote after it arrived would be a preference, not a policy.
1000
- */
1001
-
1002
- /**
1003
- * A published-RFQ auction's parameters (§10, Q9).
1004
- *
1005
- * Reserved and inert: nothing reads it, and its shape is sized against ts-sdk
1006
- * #777's draft so the name cannot be occupied by something narrower in the
1007
- * meantime — a bid window, the relay set unioned across the pair's cards, and
1008
- * the fresh per-open transport key rfq-protocol.md §4.6 recommends for
1009
- * unlinkability.
1010
- */
1011
- interface RfqAuctionPolicy {
1012
- /** How long to hold the bid window open, in ms. */
1013
- readonly windowMs: number;
1014
- /** Relays to publish the open request on. Unioned across the pair's cards. */
1015
- readonly relays?: readonly string[];
1016
- /** §4.6's SHOULD: a fresh transport key per open, so bids are unlinkable. */
1017
- readonly freshTransportKey?: boolean;
1018
- }
1019
- /**
1020
- * How much the client drives on its own.
1021
- *
1022
- * The split is the one `RfqSwapManager` already draws between reading its
1023
- * records and driving them: `restoreFromRepository` is documented as NOT part
1024
- * of `start()`, precisely so a consumer can look at its swaps without being
1025
- * made to move money to do it. This promotes that to configuration.
1026
- */
1027
- type DriveMode =
1028
- /**
1029
- * Default. Construction's restore-read arms the drive when it finds live
1030
- * work, and the first `accept()` arms it when it does not.
1031
- */
1032
- "auto"
1033
- /** Restores, then waits: no timer and no stream until `start()`. */
1034
- | "manual"
1035
- /**
1036
- * Restores and reports, and never actuates. It discovers nothing new — no
1037
- * pass runs, so no claim, no refund and no recovery round — which is what
1038
- * keeps `swaps()` and `onUpdate` honest for an inspection-only consumer.
1039
- */
1040
- | "readonly";
1041
- interface SwapPolicy {
1042
- /**
1043
- * How much the client drives on its own. Default `"auto"`.
1044
- *
1045
- * Policy rather than a `SwapClientConfig` field for the same reason the
1046
- * other five members are: it is a caller's decision about behaviour, not a
1047
- * dependency the client needs to work.
1048
- */
1049
- readonly drive?: DriveMode;
1050
- /**
1051
- * The most a swap may cost, as a standing instruction.
1052
- *
1053
- * The verbs take the **minimum** of this and their own `maxFee`, so a call
1054
- * can only tighten it: a policy ceiling a call could raise would be
1055
- * decorative. Enforced between `quote` and `accept` and nowhere else —
1056
- * before funding, which is the only place a ceiling is worth anything.
1057
- *
1058
- * Denominated, like every ceiling on this surface: the fee sits on the give
1059
- * leg on corridor routes and the take leg on asset swaps, so a bare number
1060
- * would name no asset. A ceiling whose asset is not the quoted fee's is
1061
- * refused rather than converted.
1062
- */
1063
- readonly maxFee?: FeeCeiling;
1064
- /**
1065
- * The last word on which market prices a swap.
1066
- *
1067
- * Called with every eligible candidate, best-ranked first, and answering
1068
- * `undefined` vetoes them all — which lands where an empty candidate set
1069
- * lands, as `UnsupportedRoute`, and not as a seventeenth error member. The
1070
- * answer must be one of the candidates: a card from somewhere else has not
1071
- * been through the pair, corridor and addressability checks that produced
1072
- * this list.
1073
- */
1074
- readonly selectMarket?: (candidates: readonly MarketCandidate[]) => MarketCandidate | undefined;
1075
- /**
1076
- * The registries whose cards may price a swap, matched exactly against
1077
- * `DiscoveredMarket.source`.
1078
- *
1079
- * On `source` and never on `discovery_pubkey`, which is the field the cache
1080
- * does not revalidate on read: filtering an allowlist on unvalidated cache
1081
- * content would reintroduce the hole the allowlist exists to close. Exact
1082
- * URLs, not hostnames or origins — and a locally pinned card follows
1083
- * whatever label discovery recorded for it, which is a path, not a URL.
1084
- *
1085
- * Absent means every source. An allowlist that empties the candidate set is
1086
- * the empty-eligible-set case, not a refusal of its own.
1087
- */
1088
- readonly allowedRegistries?: readonly string[];
1089
- /**
1090
- * The least validity a quote may arrive with, in seconds.
1091
- *
1092
- * One layer above the wire's own refusal of a quote already past
1093
- * `valid_until`: a quote with four seconds left is not expired and is not
1094
- * usable either, and the caller is the only one who knows how long their
1095
- * flow takes between seeing terms and accepting them. Under the floor is
1096
- * `QuoteExpired`, thrown from `quote()` rather than handed back to fail at
1097
- * `accept()`.
1098
- */
1099
- readonly quoteTtlFloorSeconds?: number;
1100
- /**
1101
- * §10, reserved and inert: the published-RFQ auction's parameters.
1102
- */
1103
- readonly rfq?: RfqAuctionPolicy;
1104
- /**
1105
- * §10, reserved and inert: which bid to close a published auction with.
1106
- */
1107
- readonly selectBid?: (bids: readonly RankedBid[]) => RankedBid | undefined;
1108
- }
1109
-
1110
- /**
1111
- * The drive: what makes the v2 client self-driving, and the one place the two
1112
- * families' state becomes one {@link Outcome}.
1113
- *
1114
- * Two drivers sit behind one lifecycle — `RfqSwapManager` for the corridor
1115
- * swaps and `watchOfferSwaps` for the offers — and they stay separate here, as
1116
- * they are in v1: liveness is their union, arming is one idempotent call over
1117
- * both, and `stop()` pays the asymmetry the facade already pays (the manager
1118
- * stays reusable, the watcher is a one-shot unsubscribe rebuilt on the next
1119
- * start).
1120
- *
1121
- * **The poll loop is the correctness mechanism.** The contract-event
1122
- * subscription only makes a pass run early, and that pass re-reads the lockup
1123
- * exactly as the timer's does, so a missed, duplicated, reordered or forged
1124
- * event costs or saves latency and nothing else. Stated as an invariant here
1125
- * because it is what makes dropping the stream on `stop()` safe: NO OUTCOME IS
1126
- * EVER WRITTEN FROM AN EVENT PAYLOAD.
1127
- *
1128
- * **No backoff, deliberately.** The poll interval is already the retry cadence
1129
- * and `REFUND_MTP_LAG_SECONDS` already the deadline, so a backoff on a money
1130
- * push could only push a retry past the deadline it exists to beat.
1131
- *
1132
- * What this module does NOT do is decide anything about a swap from the
1133
- * solver's word: there is no `RfqTransport` here, exactly as there is none in
1134
- * the manager.
1135
- */
1136
-
1137
- /** Why the drive refused. */
1138
- type DriveRefusal =
1139
- /** `drive: "readonly"` actuates nothing, and this asked it to. */
1140
- "readonly"
1141
- /** No record with this id, here or in the repository. */
1142
- | "unknown-swap"
1143
- /** The lockup's `refundLocktime` has not matured, so a recovery round
1144
- * including it would be rejected — and `recoverVtxos` settles EVERY
1145
- * recoverable output in one batch, so an early attempt can fail unrelated
1146
- * outputs with it. */
1147
- | "refund-window-open"
1148
- /** Nothing at this swap has been swept, so there is nothing to recover.
1149
- * The two `needs_counterparty` sources of `needs_recovery` land here. */
1150
- | "nothing-swept"
1151
- /** This wallet exposes no VTXO manager, so no recovery round can be run. */
1152
- | "no-recovery-support";
1153
- /**
1154
- * The drive declined, with the reason as a value.
1155
- *
1156
- * Not a member of §7's sixteen, and it keeps the `Error` suffix to say so —
1157
- * `errors.ts`'s own naming rule. What it replaces is `recoverVtxos`'s bare
1158
- * `Error("No recoverable VTXOs found")`, which is outside the taxonomy and
1159
- * carries nothing a caller can branch on.
1160
- *
1161
- * M6's error-coverage pass ruled it a documented NON-member: no §7 member names
1162
- * a drive-refusal condition, so none absorbs these four, and the suffix rule is
1163
- * working as intended rather than marking a loose end.
1164
- */
1165
- declare class SwapDriveRefusedError extends Error {
1166
- readonly reason: DriveRefusal;
1167
- readonly swapId?: QuoteId | undefined;
1168
- readonly name = "SwapDriveRefusedError";
1169
- constructor(reason: DriveRefusal, detail: string, swapId?: QuoteId | undefined);
1170
- }
1171
- /** What {@link SwapDrive.recover} did. */
1172
- interface RecoveryResult {
1173
- /**
1174
- * Whether THIS swap's outpoints were included in the round.
1175
- *
1176
- * A settlement txid is not success: `recoverVtxos` takes no outpoints — it
1177
- * reads the whole wallet, drops what `unspendableNow` refuses, then prices
1178
- * and caps the rest highest-value-first with the overflow deferred to the
1179
- * next cycle. So the named lockup is re-read afterwards and this is that
1180
- * read's answer.
1181
- */
1182
- readonly recovered: boolean;
1183
- /** The settlement the round produced, when one ran. */
1184
- readonly txid?: string;
1185
- /** The swap, after the immediate pass that followed. */
1186
- readonly swap: Swap;
1187
- }
1188
- interface SwapDriveConfig {
1189
- readonly wallet: IWallet;
1190
- readonly operator: SwapOperator;
1191
- /** No repository is legal and shipped: `ready` resolves, nothing arms, and
1192
- * `accept()` keeps its own refusal. */
1193
- readonly repository?: AssetSwapRepository;
1194
- /**
1195
- * The client's corridors, for the two deps a drive pass needs and the quote
1196
- * path does not: the L1 chain source and the L1 claim callback. Read
1197
- * through the set so resolution stays lazy — a client whose `onchain` deps
1198
- * are deliberately `null` and which never drives an `arkade -> onchain`
1199
- * swap never resolves them, which is what `MissingCorridorDep`'s boundary
1200
- * note requires.
1201
- */
1202
- readonly corridors: () => Promise<CorridorSet>;
1203
- readonly mode?: DriveMode;
1204
- /**
1205
- * How often the fallback poll pass runs. Default 5000 ms — the same
1206
- * interval `RfqSwapManagerConfig.pollIntervalMs` documents one layer
1207
- * down, and the retry cadence for the refund push after
1208
- * `refundLocktime`. Tune only relative to that default.
1209
- */
1210
- readonly pollIntervalMs?: number;
1211
- /** Unix seconds. Injected for tests. */
1212
- readonly now?: () => number;
1213
- /** The Arkade observation seam. Defaults to the wallet's own reader; taken
1214
- * as an input so a drive test can double one without a wallet behind it. */
1215
- readonly indexer: LockupSpendIndexer;
1216
- /** Defaults to `wallet.getContractManager()`, resolved on first arm. */
1217
- readonly contracts?: SwapContractRegistry;
1218
- }
1219
- interface SwapDrive {
1220
- /**
1221
- * The restore-read, and — when it armed — the first pass after it.
1222
- *
1223
- * Lazy: construction stays inert and the first await is what drives it.
1224
- * Rejects only when the repository itself is unreadable, per Q3; a corrupt
1225
- * record is filtered and every per-swap problem is an outcome.
1226
- */
1227
- readonly ready: Promise<void>;
1228
- start(): Promise<void>;
1229
- stop(): Promise<void>;
1230
- dispose(): Promise<void>;
1231
- onUpdate(fn: (update: SwapUpdate) => void): Unsubscribe;
1232
- /**
1233
- * Take a freshly persisted record into the drive and answer with its public
1234
- * form.
1235
- *
1236
- * Synchronous by design: `accept()` returns once the record is durable and
1237
- * does NOT await the first pass, so the registration this schedules runs
1238
- * behind the return.
1239
- */
1240
- adopt(record: SwapRecord): Swap;
1241
- /** The public form of a record this drive holds. */
1242
- swap(id: QuoteId): Swap | undefined;
1243
- /** The outcome a record would report with no live state behind it. */
1244
- outcomeOf(record: SwapRecord): Outcome;
1245
- /**
1246
- * Take a record written OUTSIDE the drive's own loops — today, the
1247
- * awaited cancel call — into the registry, and emit through `onUpdate`.
1248
- *
1249
- * Cancel writes at two edges, the gate and the settlement, and the
1250
- * delivery channel for both is this registry: replay plus the
1251
- * `(swapId, outcome)` key absorb a later pass over the same record, whether
1252
- * or not the drive armed.
1253
- */
1254
- ingest(record: SwapRecord): void;
1255
- recover(id: QuoteId): Promise<RecoveryResult>;
1256
- /** Everything this drive has in flight — registrations and money pushes.
1257
- * Exposed so a test can be deterministic and so dispose can drain. */
1258
- idle(): Promise<void>;
1259
- }
1260
- /**
1261
- * Whether a stored blob is a record this drive can read at all.
1262
- *
1263
- * The v1 store's rule, applied to the v2 keyspace: a corrupt row is filtered
1264
- * rather than fatal, because one unreadable record must not stop a client from
1265
- * driving every other swap it holds. Everything checked here is something the
1266
- * drive dereferences unconditionally.
1267
- */
1268
- declare const readableRecord: (record: SwapRecord) => boolean;
1269
- declare const createSwapDrive: (config: SwapDriveConfig) => SwapDrive;
1270
-
1271
- /**
1272
- * The feed-priced backend: an arkade-to-arkade asset swap, priced from the
1273
- * card's own feed with no round trip to anybody.
1274
- *
1275
- * The market picks the backend — a card with both legs on arkade prices from
1276
- * its feed, and one with a leg off it is negotiated over RFQ — so nothing here
1277
- * is a client switch. What this module owns are the two things the offer path
1278
- * has never had an answer for.
1279
- *
1280
- * **The margin.** `quoteOffer` defaults `safetyBps` to 50, the package exports
1281
- * `QUOTE_OPTIONS = { safetyBps: 0 }` and the wallet passes it, and the v1 facade
1282
- * passes neither — so one card priced two different offers depending on which
1283
- * path built it. `Quote.fee` is one number with one definition, so this picks:
1284
- * the package constant, no cushion. A safety margin is a pre-payment against
1285
- * price drift between quote and fill, and that drift is the solver's risk to
1286
- * manage rather than the trader's to prepay; charging it would also inflate the
1287
- * fee a verb's `maxFee` ceiling is compared against, which is a ceiling on what
1288
- * the trader pays, not on what the client padded.
1289
- *
1290
- * **The expiry.** §3.1 makes `expiresAt` non-optional and a feed-priced quote
1291
- * has no `valid_until` to inherit — `OfferPlan` carries no expiry at all. The
1292
- * only staleness bound in the whole path is the feed cache's TTL, so that is
1293
- * what the quote's life is minted from: the moment the feed value was actually
1294
- * read from upstream, plus the TTL. A quote whose price is thirty seconds old
1295
- * expires when the price does, which is the honest bound; the policy floor then
1296
- * applies to a number the client chose rather than one a solver asserted.
1297
- */
1298
-
1299
- /**
1300
- * How long a feed value is reused, and therefore how long a quote priced from
1301
- * one lives.
1302
- *
1303
- * The same number in both roles on purpose: a quote is only as fresh as the
1304
- * price behind it, and two TTLs would let a quote outlive the value it quoted.
1305
- */
1306
- declare const FEED_TTL_MS = 30000;
1307
- /** A fetch that caches feed values, and remembers when each was really read. */
1308
- interface FeedFetch {
1309
- readonly fetch: typeof fetch;
1310
- /** Unix ms the value behind `url` was last read from upstream. */
1311
- fetchedAt(url: string): number | undefined;
1312
- }
1313
- /**
1314
- * The client's feed fetcher.
1315
- *
1316
- * The upstream probe sits INSIDE the cache rather than around it, which is what
1317
- * makes `fetchedAt` mean what it says: the cache calls through only on a miss,
1318
- * so the recorded time is the age of the value that was served, not the time it
1319
- * was served. Wrapping the other way would restamp every cache hit as fresh and
1320
- * hand back a quote whose expiry outlived its price.
1321
- */
1322
- declare const feedFetch: (base?: typeof fetch) => FeedFetch;
1323
- /** What `accept()` (M4) needs back from a feed-priced quote. */
1324
- interface OfferPreparation {
1325
- readonly backend: "feed";
1326
- readonly card: DiscoveredMarket;
1327
- /** The plan the offer covenant is built from: both amounts and both assets. */
1328
- readonly plan: OfferPlan;
1329
- readonly give: Side;
1330
- }
1331
- interface FeedQuoteInput {
1332
- readonly quoteId: QuoteId;
1333
- readonly candidate: MarketCandidate;
1334
- readonly market: CardMarketRef;
1335
- readonly legs: {
1336
- readonly give: DiscoveryLeg;
1337
- readonly take: DiscoveryLeg;
1338
- };
1339
- readonly endpoints: {
1340
- readonly give: ResolvedEndpoint;
1341
- readonly take: ResolvedEndpoint;
1342
- };
1343
- readonly amount?: PinnedAmount;
1344
- readonly feed: FeedFetch;
1345
- readonly policy?: SwapPolicy;
1346
- /** Unix seconds. */
1347
- readonly now: number;
1348
- }
1349
- declare const quoteFromFeed: (input: FeedQuoteInput) => Promise<{
1350
- quote: Quote;
1351
- preparation: OfferPreparation;
1352
- }>;
1353
-
1354
- /**
1355
- * The RFQ wire adapter: the pair string, the amount encoding, and the parse
1356
- * that turns a solver's reply into values the rest of the client can compare.
1357
- *
1358
- * **The pair string is wire, and it is owned here.** Two different fields are
1359
- * called `pair`. The registry's is a display label (`BTC/lightning:BTC`); the
1360
- * wire's is `<from-leg>-><to-leg>` over legs of `<corridor>:<asset>`, where the
1361
- * asset is a registered ticker or, on arkade only, the 68-hex asset id. Solvers
1362
- * compare it byte for byte and cap it at 158 characters, so a CAIP-19 id cannot
1363
- * go on it — it would fail the comparison and overrun the cap. The public alias
1364
- * layer therefore stops one level above this, at a corridor and a discovery
1365
- * asset id, and the string is built here, one layer below anything public.
1366
- *
1367
- * **Amounts go out as canonical decimal strings, unconditionally.** The solver
1368
- * accepts them on all four corridor request schemas today, and emitting a string
1369
- * is never a narrowing — where a JSON number past 2^53 has already lost the
1370
- * amount before anyone can check it. The receipt side takes either form through
1371
- * M1's adapter, a number only while it is a non-negative safe integer, which is
1372
- * why `AmountEncodingUnsupported` is a receipt-side error here: it fires on the
1373
- * way in, before verification, never on the way out.
1374
- */
1375
-
1376
- /**
1377
- * One leg, as the wire spells it.
1378
- *
1379
- * The BTC legs come from `rfq.ts`'s own constants rather than being rebuilt out
1380
- * of the corridor name and a ticker: the solver compares these byte for byte,
1381
- * and a second construction of `arkade:BTC` is a second thing that can drift.
1382
- * An arkade-issued asset is the id verbatim, lowercase — which is what makes the
1383
- * discovery leg the right input, since the alias layer already lowercased it.
1384
- */
1385
- declare const rfqLeg: (leg: DiscoveryLeg) => string;
1386
- /**
1387
- * The directional pair for a route, checked against the wire's length cap.
1388
- *
1389
- * Direction is give-to-take and never the card's base/quote order: the card
1390
- * describes a market, the pair describes this trade.
1391
- */
1392
- declare const rfqPairFor: (give: DiscoveryLeg, take: DiscoveryLeg) => string;
1393
- /**
1394
- * A request payload with its amount in the wire's canonical string encoding.
1395
- *
1396
- * The payload itself is built by `rfq.ts`'s own request builders — they are the
1397
- * schema, and a second copy of the profile field names is a second thing to keep
1398
- * in step with a `.strict()` remote schema. What this adds is the one field
1399
- * whose encoding M3 decided: `amount`, out as a decimal string on every corridor
1400
- * that carries one.
1401
- */
1402
- declare const withCanonicalAmount: (payload: Record<string, unknown>, amount: bigint) => Record<string, unknown>;
1403
- /**
1404
- * A solver's quote, with the fields the client compares against pulled out and
1405
- * decoded once.
1406
- *
1407
- * The amounts are the point: `RfqQuote` declares them `number`, the migration
1408
- * has them arriving as either, and every check downstream is a comparison. One
1409
- * decode at the boundary is what keeps a string amount from failing a `!==`
1410
- * against a bigint three layers down and reading as a solver mismatch.
1411
- */
1412
- interface ParsedRfqQuote {
1413
- /** The reply verbatim, for the record and for anything not decoded here. */
1414
- readonly raw: RfqQuote;
1415
- readonly rfqId: string;
1416
- readonly pair: string;
1417
- /** `from_amount`: what the trader gives, atomic units of the give leg. */
1418
- readonly give: bigint;
1419
- /** `to_amount`: what the trader takes. */
1420
- readonly take: bigint;
1421
- /** The covenant role key the quote commits to. */
1422
- readonly solver: Pubkey;
1423
- readonly validUntil: number;
1424
- /** Optional on the wire; every corridor route refuses a quote without it. */
1425
- readonly refundLocktime?: number;
1426
- readonly profile: Record<string, unknown>;
1427
- }
1428
- /** Read a solver's quote, decoding both amounts. */
1429
- declare const parseRfqQuote: (quote: RfqQuote) => ParsedRfqQuote;
1430
-
1431
- /**
1432
- * The transport seam, and the attestation the responder check runs on.
1433
- *
1434
- * §4 makes the transport an inference: the card names the rendezvous — its
1435
- * relays and its discovery key — and the client opens it, where v1 had the
1436
- * caller hand-build `nostrRfqTransport({relays, solverPubkey})`. What the card
1437
- * cannot say is whether the transport that gets built authenticates anybody, and
1438
- * that is the whole of G2: the production Nostr transport does, through its
1439
- * `authors` filter and the per-solver conversation key, while `httpTransport`
1440
- * and `relayTransport` attest nobody and route on `rfq_id` alone.
1441
- *
1442
- * So the attestation is a property of the transport and is declared by whoever
1443
- * built it. A transport that filters replies to one author sets
1444
- * {@link AttestingRfqTransport.attestedResponder} to that author; anything else
1445
- * leaves it absent and fails the `responder` check. That is deliberately the
1446
- * fail-closed default: the two dev transports do not authenticate, and a client
1447
- * that quoted over them as though they did would be verifying nothing while
1448
- * reporting that it verified four things.
1449
- *
1450
- * The default factory reaches `./nostr` through a dynamic import, which is what
1451
- * keeps `nostr-tools` an optional peer dependency: a consumer doing HTTP-only
1452
- * swaps against its own transport never loads the subpath, exactly as importing
1453
- * it directly never loaded it for them.
1454
- */
1455
-
1456
- /**
1457
- * An {@link RfqTransport} that can prove who answered.
1458
- *
1459
- * Optional rather than required, because the interface has three
1460
- * implementations today and only one of them can fill it. Absent means "attests
1461
- * nobody", which the responder check refuses — a transport is never trusted for
1462
- * a claim it did not make.
1463
- */
1464
- interface AttestingRfqTransport extends RfqTransport {
1465
- /**
1466
- * The key every reply on this transport is proven to come from.
1467
- *
1468
- * x-only hex, and it must be a claim the transport ENFORCES — a filter that
1469
- * only this author's events satisfy, plus a conversation key only this
1470
- * author can decrypt to. Setting it without that is worse than leaving it
1471
- * absent: it turns a check into a decoration.
1472
- */
1473
- readonly attestedResponder?: Pubkey;
1474
- }
1475
- /** What a factory is told about the card it is opening a rendezvous to. */
1476
- interface RfqRendezvous {
1477
- readonly card: DiscoveredMarket;
1478
- /** The card's `discovery_pubkey` — who the request is addressed to. */
1479
- readonly solverPubkey: Pubkey;
1480
- /** The card's relays. */
1481
- readonly relays: readonly string[];
1482
- }
1483
- type RfqTransportFactory = (rendezvous: RfqRendezvous) => AttestingRfqTransport | Promise<AttestingRfqTransport>;
1484
- /** Declare that `transport` proves every reply came from `responder`. */
1485
- declare const attesting: <T extends RfqTransport>(transport: T, responder: Pubkey) => AttestingRfqTransport;
1486
- /**
1487
- * The default: the card's own Nostr rendezvous.
1488
- *
1489
- * It attests the card's discovery key because `nostrRfqTransport` subscribes
1490
- * with `authors: [solverPubkey]` and decrypts with the conversation key derived
1491
- * against that same key — a reply from anyone else is either filtered out by the
1492
- * relay or fails to decrypt into anything with an `rfq_id`.
1493
- */
1494
- declare const nostrTransportFactory: RfqTransportFactory;
1495
-
1496
- /** The covenant and the keys behind one quoted corridor swap. */
1497
- interface CommonPreparation {
1498
- readonly backend: "rfq";
1499
- readonly card: DiscoveredMarket;
1500
- readonly rfqId: string;
1501
- /** The solver's reply, decoded once. */
1502
- readonly wire: ParsedRfqQuote;
1503
- /** The trader's OWN derivation of the Arkade lockup. */
1504
- readonly lockup: {
1505
- readonly address: string;
1506
- readonly script: InstanceType<typeof VHTLC.ScriptV2>;
1507
- readonly pkScript: Uint8Array;
1508
- };
1509
- }
1510
- /**
1511
- * What `accept()` inherits from a quote.
1512
- *
1513
- * Held in memory by the client, keyed by quote id, and written nowhere: M3's
1514
- * boundary is that `quote()` persists nothing. It exists so the covenant a
1515
- * quote was verified against is the covenant that gets funded — re-deriving it
1516
- * at accept from the stored quote would be a second derivation of the same tree,
1517
- * and two derivations that can disagree is the failure this package guards
1518
- * against everywhere else.
1519
- */
1520
- type RfqPreparation = (CommonPreparation & {
1521
- readonly route: "arkade->lightning";
1522
- readonly contractParams: LightningSendContractParams;
1523
- /** The refund key, and the address the quote named. */
1524
- readonly secrets: ProvisionedKey;
1525
- readonly refundAddress: string;
1526
- /** What the lockup must carry: the quote's give amount. */
1527
- readonly fundAmount: bigint;
1528
- }) | (CommonPreparation & {
1529
- readonly route: "lightning->arkade";
1530
- readonly contractParams: LightningReceiveContractParams;
1531
- readonly secrets: ProvisionedClaimSecret;
1532
- readonly payoutAddress: string;
1533
- /** What the solver's lockup must carry — the claim refuses less. */
1534
- readonly expectedAmount: bigint;
1535
- /** Last moment the hold invoice can be paid, unix seconds. */
1536
- readonly payDeadline: number;
1537
- }) | (CommonPreparation & {
1538
- readonly route: "arkade->onchain";
1539
- readonly secrets: ProvisionedClaimSecret;
1540
- readonly refundAddress: string;
1541
- readonly fundAmount: bigint;
1542
- /** The L1 claim key, provisioned by the wallet like every other key. */
1543
- readonly payoutKey: ProvisionedKey;
1544
- /** Where the claim PAYS — the take endpoint's own address, encoded.
1545
- * Distinct from {@link payoutKey}, which only AUTHORISES the claim:
1546
- * the claim's output is the spender's choice and the resolved
1547
- * destination is the only thing that names it. */
1548
- readonly payoutPkScript: Uint8Array;
1549
- readonly htlc: OnchainHtlc;
1550
- readonly htlcParams: OnchainHtlcParams;
1551
- readonly l1Network: OnchainNetwork;
1552
- readonly minConfirmations: number;
1553
- });
1554
- interface RfqQuoteInput {
1555
- readonly quoteId: QuoteId;
1556
- readonly route: "arkade->lightning" | "lightning->arkade" | "arkade->onchain";
1557
- readonly candidate: MarketCandidate;
1558
- readonly market: CardMarketRef;
1559
- readonly legs: {
1560
- readonly give: DiscoveryLeg;
1561
- readonly take: DiscoveryLeg;
1562
- };
1563
- readonly endpoints: {
1564
- readonly give: ResolvedEndpoint;
1565
- readonly take: ResolvedEndpoint;
1566
- };
1567
- readonly amount?: PinnedAmount;
1568
- readonly wallet: IWallet;
1569
- /** Live, per section 6: a snapshot binds a covenant to a key that may have rotated. */
1570
- readonly info: ArkadeInfo;
1571
- /**
1572
- * The corridor modules, unresolved.
1573
- *
1574
- * The set rather than two dep records, because resolution is what refuses a
1575
- * dep overridden to nothing — and a route that never touches lightning must
1576
- * not resolve its decoder to find that out. Each arm below asks for exactly
1577
- * the corridors it uses.
1578
- */
1579
- readonly corridors: CorridorSet;
1580
- readonly transport: AttestingRfqTransport;
1581
- readonly policy?: SwapPolicy;
1582
- /** Unix seconds. */
1583
- readonly now: number;
1584
- }
1585
- declare const quoteViaRfq: (input: RfqQuoteInput) => Promise<{
1586
- quote: Quote;
1587
- preparation: RfqPreparation;
1588
- }>;
1589
-
1590
- /** What a quote derived, kept in memory for the accept that may follow. */
1591
- type QuotePreparation = RfqPreparation | OfferPreparation;
1592
- interface AcceptInput {
1593
- readonly quote: Quote;
1594
- readonly preparation?: QuotePreparation;
1595
- readonly wallet: IWallet;
1596
- readonly repository: AssetSwapRepository | undefined;
1597
- readonly corridors: CorridorSet;
1598
- /**
1599
- * The drive, when the caller has one.
1600
- *
1601
- * Two jobs, and the second is M5's edit to this file's shipped behaviour.
1602
- * It turns a record into the public {@link Swap} — which now carries an
1603
- * `outcome`, and only the drive knows whether it holds live state for this
1604
- * swap — and it ARMS: the accepted swap is registered with the manager
1605
- * rather than persisted and left, which is what M4 deliberately did not do.
1606
- * The registration runs behind the return, so this call still does not wait
1607
- * on a first pass.
1608
- *
1609
- * Optional so the accept pipeline stays testable on its own; without one
1610
- * the answer is the record's projection and nothing is driven.
1611
- */
1612
- readonly drive?: SwapDrive;
1613
- /** Unix seconds. */
1614
- readonly now: number;
1615
- }
1616
- declare const conflictingFields: (record: SwapRecord, quote: Quote) => string[];
1617
- /**
1618
- * Accept a quote: make it durable, then move the value.
1619
- *
1620
- * Idempotent by quote id and only by quote id. A second call with the same
1621
- * quote returns the stored swap when the funding txid is already known, resumes
1622
- * the record when it is not, and refuses as `AcceptConflict` only when the
1623
- * durable evidence contradicts the quote on a material field.
1624
- */
1625
- declare const acceptQuote: (input: AcceptInput) => Promise<Swap>;
1626
- /** The stored record for a quote id, for a caller that holds only the id. */
1627
- declare const swapRecordOf: (repository: AssetSwapRepository | undefined, id: QuoteId) => Promise<SwapRecord | undefined>;
1628
-
1629
- /** What `cancel()` did to the deposit. §3.3's widened return: the
1630
- * `indeterminate` spend is `needs_recovery`, because value moved and the local
1631
- * rebuild cannot name how. */
1632
- type CancelOutcome = "cancelled" | "filled" | "needs_recovery";
1633
- interface CancelInput {
1634
- readonly wallet: IWallet;
1635
- readonly repository: AssetSwapRepository;
1636
- /** The record to cancel, read by the caller after `drive.ready` — the one
1637
- * read the call makes, and what the gate is written from. */
1638
- readonly record: OfferSwapRecord;
1639
- /** The delivery channel both edges emit through, armed or not. */
1640
- readonly drive: SwapDrive;
1641
- /** The Arkade observation seam — the wallet's own reader, as everywhere. */
1642
- readonly indexer: LockupSpendIndexer;
1643
- /** Unix seconds. Injected for tests. */
1644
- readonly now?: () => number;
1645
- }
1646
- /**
1647
- * Cancel one offer swap, reconciling the fill race and writing the v2 record.
1648
- *
1649
- * The caller has already made the strict read — a repository this call cannot
1650
- * read must not read as "no record here" and send a cancel past its gate — and
1651
- * refused the corridor tag and the missing record as `NotCancellable`.
1652
- */
1653
- declare const cancelSwap: (input: CancelInput) => Promise<{
1654
- outcome: CancelOutcome;
1655
- }>;
1656
-
1657
- interface SwapClientConfig {
1658
- /**
1659
- * The wallet, and through it the operator: server info, chain reads and
1660
- * broadcast all come from it, and no server URL is accepted anywhere.
1661
- */
1662
- readonly wallet: IWallet;
1663
- /**
1664
- * Storage: the accept records, the markets cache, the restore-scan cursor.
1665
- *
1666
- * One seam for all three — the arkade corridor's `repository` override
1667
- * defaults to this object, so a client cannot write records to one store
1668
- * and read its cache from another.
1669
- *
1670
- * No implicit default, and never an in-memory fallback: silently losing
1671
- * active swaps is the thing a storage default exists to prevent. A browser
1672
- * consumer passes `IndexedDbAssetSwapRepository`, a Node consumer imports
1673
- * `@arkade-os/swap/node` for the file-backed SQLite default, and a test
1674
- * passes `InMemoryAssetSwapRepository` — explicitly, which is the only way
1675
- * ephemeral storage is available. `accept()` without one is
1676
- * `MissingCorridorDep("arkade", "repository")`; `quote()` and `resolve()`
1677
- * work without one, since neither persists anything.
1678
- */
1679
- readonly repository?: AssetSwapRepository;
1680
- readonly discovery?: DiscoveryConfig;
1681
- /** Dependency overrides only: they never enable a route or pick a solver. */
1682
- readonly corridors?: CorridorOverrides;
1683
- readonly policy?: SwapPolicy;
1684
- /** Covenant co-signer override, 33-byte compressed hex. */
1685
- readonly emulatorPubkey?: string;
1686
- /** Overrides the wallet's own connection; for tests and a second operator. */
1687
- readonly operator?: SwapOperator;
1688
- readonly fetchImpl?: typeof fetch;
1689
- /**
1690
- * How a card's rendezvous is opened. Defaults to the card's Nostr transport,
1691
- * which is the only shipped one that can attest who answered — an injected
1692
- * transport that attests nobody fails the responder check rather than
1693
- * quietly quoting against an unauthenticated wire.
1694
- */
1695
- readonly transportFor?: RfqTransportFactory;
1696
- }
1697
- interface SwapClient {
1698
- /**
1699
- * The restore-read, and — when it armed — the first pass after it.
1700
- *
1701
- * There is no required `start()`. Construction stays inert and this is what
1702
- * drives the one read of the repository; under `drive: "auto"` the read arms
1703
- * the loop when it finds live work, and the first `accept()` arms it when it
1704
- * does not. A resumed swap may already be past a deadline, which is why
1705
- * arming runs one pass immediately rather than waiting out an interval.
1706
- *
1707
- * **Rejects only when the repository itself is unreadable.** A client that
1708
- * cannot read its own records cannot drive them safely. Everything
1709
- * per-record resolves this and surfaces through the normal channels instead:
1710
- * a corrupt record is filtered, a swap that will not rebuild reports off its
1711
- * record, and a first pass that finds a swept lockup reports
1712
- * `needs_recovery` through {@link onUpdate}.
1713
- */
1714
- readonly ready: Promise<void>;
1715
- /**
1716
- * Arm the drive. Idempotent, and required only by `drive: "manual"`.
1717
- *
1718
- * Double arming is a no-op, so a React double-mount and two concurrent
1719
- * callers are both safe.
1720
- *
1721
- * @throws {SwapDriveRefusedError} under `drive: "readonly"`, which actuates
1722
- * nothing — silence would leave two contradictory instructions standing.
1723
- */
1724
- start(): Promise<void>;
1725
- /**
1726
- * Release the live resources this instance owns, and stay reusable.
1727
- *
1728
- * Timers cleared, the contract subscription dropped, in-flight actions left
1729
- * to run to completion, and outstanding work left where it is: stop/start is
1730
- * a pause, not a cancellation. What is NOT undone is durable — the records
1731
- * stay, and so do the wallet's contract registrations, because dropping one
1732
- * unwatches a funded lockup.
1733
- */
1734
- stop(): Promise<void>;
1735
- /**
1736
- * Terminal cleanup: {@link stop} plus draining what is in flight, dropping
1737
- * every listener, and making the instance terminal.
1738
- *
1739
- * It drains rather than returning while a refund push is mid-flight —
1740
- * nothing in this package takes an `AbortSignal`, so the alternative is
1741
- * calling an instance terminal while it is still moving money. Durable swap
1742
- * records, contract registrations and recovery metadata all survive it: a
1743
- * new client restores and resumes from them, and an injected repository is
1744
- * never closed — the client closes only a connection it opened itself.
1745
- *
1746
- * From M6 every other member refuses with {@link ClientDisposed} afterwards.
1747
- * The two exceptions are teardown, and for one reason: refusing a cleanup
1748
- * call turns correct teardown into a throw. A second dispose is a no-op, and
1749
- * so is an {@link Unsubscribe} this client already handed out.
1750
- */
1751
- [Symbol.asyncDispose](): Promise<void>;
1752
- /**
1753
- * Every outcome transition, in one vocabulary for both families.
1754
- *
1755
- * Subscribing replays the current outcome of every swap this client knows,
1756
- * then streams transitions. Delivery is idempotent per `(swapId, outcome)`,
1757
- * and because the outcome is DERIVED rather than stored the key is the
1758
- * derived one — so the legal `claimed -> claimable` backslide, which
1759
- * produces `funded` twice, is delivered once.
1760
- */
1761
- onUpdate(fn: (update: SwapUpdate) => void): Unsubscribe;
1762
- /**
1763
- * Recover a swap whose value was swept, then run one immediate pass.
1764
- *
1765
- * The recovery round itself is the wallet's — this package deliberately
1766
- * builds none — and it takes no outpoints: it reads the whole wallet, drops
1767
- * what it cannot settle, and caps the batch, deferring the overflow. So a
1768
- * settlement txid is not success, and this re-reads the named lockup to
1769
- * answer whether THIS swap's outputs were included.
1770
- *
1771
- * @throws {SwapDriveRefusedError} under `drive: "readonly"`; for a lockup
1772
- * still inside its refund window, where a round including it can fail the
1773
- * whole batch; and for a swap with nothing swept — which is what a
1774
- * `needs_recovery` that came from `needs_counterparty` is.
1775
- */
1776
- recover(swapId: AssetSwapId): Promise<RecoveryResult>;
1777
- /**
1778
- * Cancel an asset swap: take back an unfilled offer's deposit.
1779
- *
1780
- * Defined only for asset swaps and typed that way — an HTLC corridor swap
1781
- * has phases instead, and its exits are a claim or a refund. The id arrives
1782
- * tagged (`offer:<quoteId>` / `rfq:<quoteId>`), so a corridor id refuses on
1783
- * the parse with no repository read, and an offer id no record backs refuses
1784
- * after the one read this call needed anyway.
1785
- *
1786
- * Cancel races a fill. When the deposit is already spent, the spending
1787
- * transaction is reconciled against the covenant's leaves and the outcome
1788
- * is `filled` rather than a throw — v1's documented throw-means-completed
1789
- * behaviour was a trap. A spend the local rebuild cannot classify is
1790
- * `needs_recovery`: value moved and the client cannot name how, which is
1791
- * what {@link recover} drives.
1792
- *
1793
- * @throws {NotCancellable} for a corridor-tagged id, or an id no record backs.
1794
- * @throws {MissingCorridorDep} when the client was given no repository.
1795
- * @throws {ClientDisposed} after disposal.
1796
- */
1797
- cancel(swapId: AssetSwapId): Promise<{
1798
- outcome: CancelOutcome;
1799
- }>;
1800
- /**
1801
- * Every swap this client wrote — both families, live and ended.
1802
- *
1803
- * One read over the uniform v2 keyspace, projected through the same
1804
- * derivation the drive publishes: the drive's live answer where it holds the
1805
- * record, the no-live-state projection otherwise. Membership is therefore
1806
- * independent of `start()` and of drive mode. A record that will not decode
1807
- * is skipped rather than fatal. **The v2 keyspace is never pruned** — the
1808
- * store grows for the life of the wallet, which this method documents
1809
- * rather than hides.
1810
- *
1811
- * The filter is in-memory; the scope is the v2 client's own history. v1-era
1812
- * rows in the `swaps` and `rfqSwaps` keyspaces are not part of the answer —
1813
- * they belong to `/protocol`'s re-exported readers.
1814
- */
1815
- swaps(filter?: SwapFilter): Promise<Swap[]>;
1816
- /**
1817
- * The markets a `quote()` could be priced against, as {@link Market} — one
1818
- * shape with what `Quote.market` references. The escape hatch for a caller
1819
- * picking a market for a custom `quote()`: it reads the same card the quote
1820
- * will cite, and the same filters the routing read applies, so it cannot
1821
- * offer one `quote()` would then refuse. Never required.
1822
- *
1823
- * Reads the snapshot the way `quote()` does and not the way `resolve()`
1824
- * does — fetching when there is none in hand — because this is what a
1825
- * caller reaches for BEFORE quoting.
1826
- *
1827
- * @throws {DiscoverySnapshotUnavailable} when the fetch leaves it with
1828
- * nothing either.
1829
- */
1830
- markets(): Promise<Market[]>;
1831
- /**
1832
- * The route, the market that would price it, and what the active snapshot
1833
- * serves — without disclosing anything to anybody.
1834
- *
1835
- * Network-free against injected or cached discovery data, which is the point
1836
- * of having it: application policy gets to veto before an RFQ round trip
1837
- * discloses an invoice or an amount.
1838
- */
1839
- resolve(input: QuoteInput): Promise<RouteResolution>;
1840
- /** Verified, binding terms. Nothing is persisted, funded or watched. */
1841
- quote(input: QuoteInput): Promise<Quote>;
1842
- /**
1843
- * Make the quote durable, then move the value.
1844
- *
1845
- * One ordering, on every route: the record and its secrets are at rest
1846
- * before anything irreversible, and the funding txid is a later best-effort
1847
- * write. Idempotent by quote id and only by quote id — a second call with
1848
- * the same quote returns or resumes the stored swap and never mints a
1849
- * second invoice or funds a second time.
1850
- *
1851
- * Does not arm a drive loop or a watcher: this returns once the record is
1852
- * durable. On `lightning -> arkade` that means a durable invoice the payer
1853
- * can be shown — which is the point of the ordering, since showing one
1854
- * whose claim secret is still in memory is what buys a lockup nobody can
1855
- * claim.
1856
- *
1857
- * @throws {QuoteExpired} past `quote.expiresAt`; the client never re-quotes.
1858
- * @throws {InsufficientFunds} before the persist, on funding routes only.
1859
- * @throws {AcceptConflict} when a record for this quote id contradicts it.
1860
- * @throws {MissingCorridorDep} when the client was given no repository.
1861
- */
1862
- accept(quote: Quote): Promise<Swap>;
1863
- /**
1864
- * Pay a destination: a bolt11, a `bc1…`, or a plain Arkade address.
1865
- *
1866
- * One call for §5's whole pay box. `quote` → fee ceiling → `accept`, with
1867
- * the amount taken as what the recipient gets; an amount-bearing invoice
1868
- * pins it already, so passing one beside it is `AmountMismatch`.
1869
- *
1870
- * A plain Arkade address is **not** a swap and does not become one: it
1871
- * settles through `wallet.send` and answers `{ kind: "payment", txid }`,
1872
- * which is why the return is a union. Rejecting it would put the same
1873
- * branch in every product that has one pay box.
1874
- *
1875
- * @throws {MaxFeeExceeded} when the quoted fee is over `maxFee` or
1876
- * `policy.maxFee`, whichever is tighter — before anything is funded.
1877
- */
1878
- pay(destination: string, options?: PayOptions): Promise<PayResult>;
1879
- /**
1880
- * Ask for an incoming payment, and get back the artifact to show its payer.
1881
- *
1882
- * Returns only after `accept()` has persisted, which is the point: an
1883
- * invoice shown to a payer while its claim secret is still in memory buys a
1884
- * lockup nobody can claim. The artifact is non-optional on the return type
1885
- * for the same reason — a receive has one by construction.
1886
- *
1887
- * Generic over `via` so the artifact's shape follows the corridor the
1888
- * caller named — `receive({ via: "lightning" })` answers the invoice arm
1889
- * and `.artifact.bolt11` needs no `kind` check. See
1890
- * {@link ReceiveArtifact} for why the tie lives here and not on
1891
- * `Artifact`.
1892
- *
1893
- * @throws {MaxFeeExceeded} as {@link pay} does.
1894
- */
1895
- receive<C extends CorridorId = CorridorId>(options: ReceiveOptions & {
1896
- readonly via: C;
1897
- }): Promise<ReceiveRequest<C>>;
1898
- /**
1899
- * Swap one Arkade asset for another.
1900
- *
1901
- * @throws {MaxFeeExceeded} as {@link pay} does.
1902
- */
1903
- exchange(options: ExchangeOptions): Promise<Swap>;
1904
- /**
1905
- * What the quote with this id derived — the covenant, the keys, the wire
1906
- * reply.
1907
- *
1908
- * Process-local and deliberately not durable: M3 persists nothing, and M4's
1909
- * `accept()` is what turns this into a record. It exists so the covenant a
1910
- * quote was verified against is the one that gets funded, rather than a
1911
- * second derivation of the same tree.
1912
- */
1913
- preparationOf(id: QuoteId): QuotePreparation | undefined;
1914
- }
1915
- /** The in-memory filter {@link SwapClient.swaps} applies. */
1916
- interface SwapFilter {
1917
- readonly family?: SwapFamily;
1918
- readonly outcome?: Outcome;
1919
- }
1920
- declare const createSwapClient: (config: SwapClientConfig) => SwapClient;
1921
-
1922
- /**
1923
- * The §7 taxonomy, as typed errors.
1924
- *
1925
- * The contract every member shares: it is thrown before value moves, or not at
1926
- * all. Anything that can go wrong after funding is an outcome, not an exception,
1927
- * and belongs to the drive loop instead. Each class names the boundary it fires
1928
- * at, because that is the part a caller cannot infer from the name.
1929
- *
1930
- * Naming rule, and it cuts both ways. A member of this taxonomy is a bare
1931
- * condition noun — `QuoteExpired`, `NotCancellable` — because `SwapRefusal` is
1932
- * one and §8 keeps it unchanged, so a module holding all sixteen is bare or it
1933
- * is the first mixed-convention module in the package. An error class that is
1934
- * *not* a member keeps the `Error` suffix: `AssetIdError` and
1935
- * `AmountFormatError` are codec faults on caller input, and the suffix is what
1936
- * says so at the catch site.
1937
- *
1938
- * v1's `AddressMismatch` (`rfq.ts:163`) is deliberately not a seventeenth
1939
- * member: M3 folds it into {@link QuoteVerificationFailed}'s `lockup_address`
1940
- * check, and M8 gives it the `/protocol` re-export and the `@deprecated`
1941
- * pointer. Tagging it here would deprecate a live behaviour against a
1942
- * replacement that does not exist yet.
1943
- */
1944
-
1945
- /**
1946
- * The checks §3.1 runs on every quote, before it is returned.
1947
- *
1948
- * Four of them are the spec's, and the fifth is M3's answer to G2. §3.1 states
1949
- * that "who answered is a transport property, not one of those four checks",
1950
- * and the two dev transports authenticate nobody — so leaving attestation at
1951
- * the transport makes verification skippable by configuration, which is the one
1952
- * thing verification may not be. `responder` is therefore *delivered* as a
1953
- * transport property and *run* as a check, and §3.1's sentence narrows to
1954
- * addressed mode with it: published RFQ (§10) attributes each bid by its own
1955
- * signature and inherits no transport attestation at all.
1956
- */
1957
- type QuoteCheck = "pair" | "lockup_address" | "invoice" | "refund_window" | "responder";
1958
- /**
1959
- * `to` is underdetermined — it parses as nothing, as more than one thing, or as
1960
- * one thing the corridor that owns it refuses.
1961
- *
1962
- * The third arm is the one a name reading only "ambiguous" would hide. A
1963
- * corridor module answers *mine, and wrong* for a `tb1…` on a mainnet wallet,
1964
- * another operator's Arkade address, or a bolt11 the shape-only classifier
1965
- * admits and the decoder then rejects; collapsing that into *not mine* would
1966
- * hand a well-formed destination to {@link UnsupportedRoute}, which names the
1967
- * wrong fault. The refusal rides on `detail`, so the taxonomy stays at sixteen.
1968
- *
1969
- * A destination core classifies but no module claims — an LNURL today — is NOT
1970
- * this: it is left unclaimed at the parse and becomes {@link UnsupportedRoute}
1971
- * at route resolution.
1972
- *
1973
- * Boundary: `resolve()`/`quote()`, the single place `to` is parsed.
1974
- */
1975
- declare class AmbiguousDestination extends Error {
1976
- readonly destination: string;
1977
- readonly name = "AmbiguousDestination";
1978
- constructor(destination: string, detail: string);
1979
- }
1980
- /**
1981
- * The corridor pair is not in the implemented route union — `onchain -> arkade`
1982
- * included, until the manager owns the trader's L1 refund path end to end.
1983
- *
1984
- * Boundary: route resolution, before RFQ disclosure, artifact creation,
1985
- * persistence or funding. Also the alias layer, for a rail no corridor serves,
1986
- * and `quote()` for a pair no discovered market serves on the active snapshot —
1987
- * a resolved route with an empty eligible set, which is an absence of a
1988
- * market-shaped thing rather than a wrong pairing, and so this member rather
1989
- * than a seventeenth.
1990
- */
1991
- declare class UnsupportedRoute extends Error {
1992
- readonly name = "UnsupportedRoute";
1993
- readonly give: CorridorId | undefined;
1994
- readonly take: CorridorId | undefined;
1995
- constructor(detail: string, corridors?: {
1996
- give?: CorridorId;
1997
- take?: CorridorId;
1998
- });
1999
- }
2000
- /**
2001
- * `resolve()` needs market data and has neither an injected nor a cached
2002
- * snapshot. Deliberately not a third, half-resolved route state: the type system
2003
- * excludes one, and a caller that needs offline resolution warms or injects a
2004
- * snapshot.
2005
- *
2006
- * Boundary: `resolve()`, and `quote()` when the fetch it is allowed to make
2007
- * leaves it with nothing either — no registry configured, an unindexed network,
2008
- * or an unreachable registry with no cache behind it. Fetching is what `quote()`
2009
- * may do that `resolve()` may not; having no market data at all is the same
2010
- * condition on both.
2011
- */
2012
- declare class DiscoverySnapshotUnavailable extends Error {
2013
- readonly network: NetworkName;
2014
- readonly name = "DiscoverySnapshotUnavailable";
2015
- constructor(network: NetworkName, detail: string);
2016
- }
2017
- /**
2018
- * Two amounts are pinned. Exactly one may be: the caller's `amount` +
2019
- * `amountOn`, or the invoice's.
2020
- *
2021
- * Boundary: `quote()`, before any network round trip.
2022
- */
2023
- declare class AmountMismatch extends Error {
2024
- readonly sources: readonly [string, string];
2025
- readonly name = "AmountMismatch";
2026
- constructor(sources: readonly [string, string]);
2027
- }
2028
- /**
2029
- * The amount cannot cross this encoding without an unsafe narrowing — a quote
2030
- * field arriving as a JSON number past 2^53, a non-canonical decimal string, or
2031
- * a `bigint` too large for a foreign `number` amount.
2032
- *
2033
- * Boundary: the RFQ adapter, both directions; from M7, core's payment rails.
2034
- */
2035
- declare class AmountEncodingUnsupported extends Error {
2036
- readonly field: string;
2037
- readonly value: string;
2038
- readonly name = "AmountEncodingUnsupported";
2039
- constructor(field: string, value: string, detail: string, options?: ErrorOptions);
2040
- }
2041
- /**
2042
- * A solver response failed a local check. v1 documented the pair check as the
2043
- * caller's job, in bold; here it is an invariant. v1's `AddressMismatch` is the
2044
- * `lockup_address` case of this and folds into it at M3.
2045
- *
2046
- * Boundary: `quote()`, before the quote is returned and so before funding.
2047
- */
2048
- declare class QuoteVerificationFailed extends Error {
2049
- readonly check: QuoteCheck;
2050
- readonly name = "QuoteVerificationFailed";
2051
- readonly expected: string | undefined;
2052
- readonly actual: string | undefined;
2053
- constructor(check: QuoteCheck, expected?: string, actual?: string,
2054
- /** The gate or derivation this folds in, kept as the `cause` chain:
2055
- * `expected`/`actual` say what disagreed, and the cause says which
2056
- * check said so. */
2057
- options?: ErrorOptions);
2058
- }
2059
- /**
2060
- * A quote past its TTL, or so close to it that acting on it is the same thing.
2061
- *
2062
- * Two boundaries, one condition. At `accept()` it is the spec's: the client
2063
- * never silently re-quotes, because the price the caller saw is not the price
2064
- * they would get. At `quote()` it is `policy.quoteTtlFloorSeconds` — a quote arriving
2065
- * with less validity left than the caller can use is expired on arrival, and
2066
- * saying so beats handing back terms that die between the return and the accept.
2067
- *
2068
- * Boundary: `quote()`, against the policy floor; `accept()`, before persistence.
2069
- */
2070
- declare class QuoteExpired extends Error {
2071
- readonly quoteId: string;
2072
- readonly expiresAt: number;
2073
- readonly now: number;
2074
- readonly name = "QuoteExpired";
2075
- constructor(quoteId: string, expiresAt: number, now: number);
2076
- }
2077
- /**
2078
- * The quote's fee is over the verb's ceiling.
2079
- *
2080
- * Carries the terms rather than the quote: a `Quote` field would make this
2081
- * module depend on M3, and an app re-presenting the terms calls `quote()` again
2082
- * anyway.
2083
- *
2084
- * Boundary: the verbs layer, between `quote` and `accept` — before funding.
2085
- */
2086
- declare class MaxFeeExceeded extends Error {
2087
- readonly quoteId: string;
2088
- readonly asset: AssetId;
2089
- readonly fee: bigint;
2090
- readonly maxFee: bigint;
2091
- readonly name = "MaxFeeExceeded";
2092
- constructor(quoteId: string, asset: AssetId, fee: bigint, maxFee: bigint);
2093
- }
2094
- /**
2095
- * The wallet cannot fund the give leg. v1 left this to `validatePlan` and the
2096
- * caller, and `validatePlan` returned rather than threw.
2097
- *
2098
- * Boundary: `accept()`, before persistence and funding.
2099
- */
2100
- declare class InsufficientFunds extends Error {
2101
- readonly asset: AssetId;
2102
- readonly required: bigint;
2103
- readonly name = "InsufficientFunds";
2104
- readonly available: bigint | undefined;
2105
- constructor(asset: AssetId, required: bigint, available?: bigint);
2106
- }
2107
- /**
2108
- * A quote id maps to a persisted accept record that contradicts it. Only
2109
- * incompatible *durable evidence* qualifies — an ordinary duplicate `accept()`
2110
- * returns or resumes the original swap, and a funding txid appearing where there
2111
- * was none is a benign resume.
2112
- *
2113
- * Boundary: `accept()`, on the persisted record, before any second funding.
2114
- */
2115
- declare class AcceptConflict extends Error {
2116
- readonly quoteId: string;
2117
- readonly swapId: string;
2118
- readonly fields: readonly string[];
2119
- readonly name = "AcceptConflict";
2120
- constructor(quoteId: string, swapId: string, fields: readonly string[]);
2121
- }
2122
- /**
2123
- * A method called after async disposal. Disposal is terminal for the instance;
2124
- * the durable records survive it and a new client resumes them.
2125
- *
2126
- * Boundary: every client method, before it does anything.
2127
- */
2128
- declare class ClientDisposed extends Error {
2129
- readonly method: string;
2130
- readonly name = "ClientDisposed";
2131
- constructor(method: string);
2132
- }
2133
- /**
2134
- * `cancel()` on a swap this client cannot cancel. The asymmetry is structural:
2135
- * an offer covenant has no expiry, so cancellation is an unfilled offer's only
2136
- * exit, where an HTLC has phases and its exits are a claim or a refund.
2137
- *
2138
- * Three ways of refusing, one condition. A corridor-tagged id is refused on the
2139
- * parse of its prefix, with no repository read; an `offer:` id no record backs
2140
- * is refused after the one read cancel needed anyway; and an untagged id from
2141
- * `/protocol`'s readers takes that same read. The taxonomy stays at sixteen —
2142
- * a "no such swap" member would split one condition across two classes by
2143
- * which call noticed it.
2144
- *
2145
- * Boundary: `cancel()`.
2146
- */
2147
- declare class NotCancellable extends Error {
2148
- readonly swapId: string;
2149
- readonly name = "NotCancellable";
2150
- constructor(swapId: string);
2151
- }
2152
- /**
2153
- * A destination disagrees with its asset's chain.
2154
- *
2155
- * Inert by ruling. §9's EVM corridor is the only place two chain identities can
2156
- * disagree, and it is deferred, so nothing throws this yet. Declared anyway so
2157
- * the taxonomy has no unowned member, and so M6's coverage pass can assert that
2158
- * exactly one declared error has no throwing site — this one. Its fields are
2159
- * pinned now for the same reason: nothing throws it, so this is the moment to
2160
- * say what the evidence is.
2161
- */
2162
- declare class InconsistentRoute extends Error {
2163
- readonly asset: AssetId;
2164
- readonly destination: string;
2165
- readonly name = "InconsistentRoute";
2166
- constructor(asset: AssetId, destination: string);
2167
- }
2168
- /**
2169
- * `getArkadeInfo({ requireLive: true })` failed while deriving a covenant. A
2170
- * snapshot would bind the covenant to a signer key the operator may no longer
2171
- * co-sign for, so this fails closed rather than falling back.
2172
- *
2173
- * Boundary: `quote()`, at covenant derivation — before funding.
2174
- */
2175
- declare class OperatorUnreachable extends Error {
2176
- readonly name = "OperatorUnreachable";
2177
- constructor(detail: string, options?: ErrorOptions);
2178
- }
2179
- /**
2180
- * A corridor's dependency was explicitly overridden to nothing, or is required
2181
- * on this network and absent.
2182
- *
2183
- * Four overridable deps, not three: the arkade repository, the lightning
2184
- * decoder, the lightning covclaimd deployment key, and the onchain chain
2185
- * source. `undefined` takes the default; `null` is the refusal this names. The
2186
- * arkade module's co-signer key reaches it by the second door — it is not a
2187
- * `CorridorOverrides` key, but `EMULATOR_PUBKEYS` pins three of the five
2188
- * networks, so on `testnet` and `signet` the override is required and its
2189
- * absence is this rather than a bare `Error`.
2190
- *
2191
- * Boundary: dep resolution, when a route first touches that corridor. Never
2192
- * construction: a missing dep for a corridor nobody uses is not an error.
2193
- */
2194
- declare class MissingCorridorDep extends Error {
2195
- readonly corridor: CorridorId;
2196
- readonly dep: string;
2197
- readonly name = "MissingCorridorDep";
2198
- constructor(corridor: CorridorId, dep: string);
2199
- }
2200
- /** Every member of the taxonomy. */
2201
- type SwapError = AmbiguousDestination | UnsupportedRoute | DiscoverySnapshotUnavailable | AmountMismatch | AmountEncodingUnsupported | QuoteVerificationFailed | SwapRefusal | QuoteExpired | MaxFeeExceeded | InsufficientFunds | AcceptConflict | ClientDisposed | NotCancellable | InconsistentRoute | OperatorUnreachable | MissingCorridorDep;
2202
- /** The sixteen names. Derived, so there is no second list to drift. */
2203
- type SwapErrorName = SwapError["name"];
2204
- /** The sixteen, as values — what the coverage pass counts. */
2205
- declare const SWAP_ERROR_NAMES: readonly SwapErrorName[];
2206
- /**
2207
- * Whether `e` belongs to the taxonomy, optionally narrowed to one member.
2208
- *
2209
- * Catalog-driven rather than a chain of `instanceof`, so it stays total as
2210
- * members are added, and it rejects an impostor: a foreign error that happens to
2211
- * be named `QuoteExpired` fails the constructor check.
2212
- */
2213
- declare function isSwapError(e: unknown): e is SwapError;
2214
- declare function isSwapError<N extends SwapErrorName>(e: unknown, name: N): e is Extract<SwapError, {
2215
- name: N;
2216
- }>;
2217
-
2218
- export { type OfferPreparation as $, type AssetAliasTable as A, type DiscoveryConfig as B, type CorridorFactory as C, type DiscoveryIndex as D, type DiscoveryIndexInput as E, DiscoverySnapshotUnavailable as F, type DriveMode as G, type DriveRefusal as H, type ExchangeOptions as I, FEED_TTL_MS as J, type FeeCeiling as K, type LightningCorridorDeps as L, type MarketCandidate as M, type FeedFetch as N, type OnchainCorridorDeps as O, type FeedQuoteInput as P, INDEXED_NETWORKS as Q, InconsistentRoute as R, type SwapPolicy as S, InsufficientFunds as T, type LockupOwner as U, type Market as V, MaxFeeExceeded as W, MissingCorridorDep as X, NotCancellable as Y, ONCHAIN_CLAIM_FEE_RATE_SATVB as Z, type ObservationSeam as _, type ArkadeCorridorDeps as a, resolveCorridorBase as a$, type OnchainClaim as a0, OperatorUnreachable as a1, type ParsedRfqQuote as a2, type PayOptions as a3, type PayResult as a4, type QuoteCheck as a5, QuoteExpired as a6, type QuotePreparation as a7, QuoteVerificationFailed as a8, REGISTRY_URL as a9, cardMarketOf as aA, chooseMarket as aB, conflictingFields as aC, corridorSet as aD, createSwapClient as aE, createSwapDrive as aF, discoveryIndex as aG, eligibleMarkets as aH, enforceFeeCeiling as aI, exchange as aJ, feedFetch as aK, isAddressable as aL, isCardMarket as aM, isIndexedNetwork as aN, isSwapError as aO, isUsableCard as aP, liveArkadeInfo as aQ, marketBackendOf as aR, marketKeyOf as aS, marketRefOf as aT, nostrTransportFactory as aU, parseRfqQuote as aV, pay as aW, quoteFromFeed as aX, quoteViaRfq as aY, readableRecord as aZ, receive as a_, type ReceiveArtifact as aa, type ReceiveOptions as ab, type ReceiveRequest as ac, type RecoveryResult as ad, type RegisteredAsset as ae, type RfqAuctionPolicy as af, type RfqPreparation as ag, type RfqQuoteInput as ah, type RfqRendezvous as ai, type RfqTransportFactory as aj, type RouteSide as ak, SWAP_ERROR_NAMES as al, type SwapClient as am, type SwapClientConfig as an, type SwapDrive as ao, type SwapDriveConfig as ap, SwapDriveRefusedError as aq, type SwapError as ar, type SwapErrorName as as, type SwapFilter as at, UnsupportedRoute as au, type VerbDeps as av, acceptQuote as aw, attesting as ax, cancelSwap as ay, canonicalAssetId as az, type CorridorSet as b, resolveCorridorDeps as b0, rfqLeg as b1, rfqPairFor as b2, swapRecordOf as b3, toDiscoveryLeg as b4, usableMarkets as b5, withCanonicalAmount as b6, type DiscoveryLeg as c, type DiscoverySnapshot as d, AcceptConflict as e, type AcceptInput as f, AmbiguousDestination as g, AmountEncodingUnsupported as h, AmountMismatch as i, type AttestingRfqTransport as j, CORRIDOR_FACTORIES as k, type CancelInput as l, type CancelOutcome as m, type ClaimedDestination as n, ClientDisposed as o, type CorridorBase as p, type CorridorClaim as q, type CorridorCovenant as r, type CorridorDeadline as s, type CorridorDeps as t, type CorridorDepsByCorridor as u, type CorridorDrive as v, type CorridorLockup as w, type CorridorModule as x, type CorridorOverrides as y, type CorridorPass as z };