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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +52 -2
  2. package/dist/advanced.cjs +8376 -0
  3. package/dist/advanced.d.cts +550 -0
  4. package/dist/advanced.d.ts +550 -0
  5. package/dist/advanced.js +451 -0
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-HUQQVBC4.js +4262 -0
  8. package/dist/{chunk-EOYGUCDM.js → chunk-ITFCQWPG.js} +755 -1382
  9. package/dist/chunk-PVB7EBAM.js +2517 -0
  10. package/dist/errors-C3h8ANmE.d.ts +1560 -0
  11. package/dist/errors-hm7aqnRM.d.cts +1560 -0
  12. package/dist/index.cjs +4861 -3988
  13. package/dist/index.d.cts +69 -2812
  14. package/dist/index.d.ts +69 -2812
  15. package/dist/index.js +179 -3719
  16. package/dist/lockupContract-5r5RlgOJ.d.cts +137 -0
  17. package/dist/lockupContract-5r5RlgOJ.d.ts +137 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +249 -591
  20. package/dist/node/index.d.ts +249 -591
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +191 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer-Bd9Yvd8Z.d.ts +261 -0
  27. package/dist/offer-F88rtL_I.d.cts +261 -0
  28. package/dist/protocol.cjs +4086 -3706
  29. package/dist/protocol.d.cts +163 -768
  30. package/dist/protocol.d.ts +163 -768
  31. package/dist/protocol.js +190 -173
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BuYWGAKz.d.cts +2261 -0
  41. package/dist/repository-DYnRLPt-.d.ts +2261 -0
  42. package/dist/rfq-60PGpQ_x.d.cts +950 -0
  43. package/dist/rfq-60PGpQ_x.d.ts +950 -0
  44. package/dist/watch-BTyiBLSd.d.ts +74 -0
  45. package/dist/watch-M_KY-5ho.d.cts +74 -0
  46. package/package.json +20 -10
  47. package/dist/chunk-LYCMM3VB.js +0 -1357
  48. package/dist/chunk-U7VWWTL6.js +0 -66
  49. package/dist/repository-_zU9_pM3.d.cts +0 -3426
  50. package/dist/repository-kO95noyv.d.ts +0 -3426
  51. package/dist/rfq-DdBV4JO5.d.cts +0 -1097
  52. package/dist/rfq-DdBV4JO5.d.ts +0 -1097
  53. package/dist/watch-CQqvwgwY.d.cts +0 -96
  54. package/dist/watch-wMbmfN4p.d.ts +0 -96
@@ -1,3426 +0,0 @@
1
- import { Corridor as Corridor$1, DiscoveredMarket } from '@arkade-os/solver-discovery';
2
- import { IWallet, ProvisionedKey, ProvisionedClaimSecret, ArkProvider, RestIndexerProvider, VHTLC, Identity, IContractManager, NetworkName, asset } from '@arkade-os/sdk';
3
- import { w as RfqStatus, a as RfqTransport, O as OnchainHtlc, g as ChainUtxo, C as ChainSource, t as OnchainHtlcPhase } from './rfq-DdBV4JO5.js';
4
-
5
- /** @deprecated Use `Outcome`. Moved off the package root to `@arkade-os/swap/protocol`. */
6
- type AssetSwapStatus = "pending" | "cancelling" | "fulfilled" | "cancelled" | "recoverable" | "awaiting_fill" | "claimable" | "claimed" | "refunded_l1";
7
- /** The sentinel asset id for BTC itself, as opposed to a 68-hex asset id.
8
- * Lives here with the {@link AssetSwap} fields it describes so the market and
9
- * restore layers share one spelling instead of re-typing the literal.
10
- *
11
- * @deprecated A record-local sentinel, not a public id. The v2 asset id is `btcOn(rail, network)`, and `client.swaps()` projects records that carry it. Moved off the package root to `@arkade-os/swap/protocol`.
12
- */
13
- declare const BTC_ASSET_ID = "btc";
14
- /**
15
- * The record fields a wallet-provisioned secret becomes — what
16
- * {@link swapSecretsToRecord} emits, and what every record type carrying swap
17
- * secrets embeds.
18
- *
19
- * A named type rather than four fields restated per record: the mapper and the
20
- * records it feeds must agree exactly, and a record that silently omits one of
21
- * these round-trips a swap whose preimage cannot be re-derived. Embedding makes
22
- * the omission a compile error instead.
23
- *
24
- * **Only `preimageHex` is secret.** `signingDescriptor` and `preimageSaltHex`
25
- * are public derivation inputs — they must survive a field-mapped backend, but
26
- * they leak nothing without the seed.
27
- *
28
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
29
- */
30
- interface SwapSecretsProjection {
31
- /**
32
- * The wallet descriptor this swap's sender key comes from — a fresh HD
33
- * child, or a static wallet's `tr(pubkey)`. Public — the signer
34
- * re-derives from the wallet, so the record carries no key material.
35
- */
36
- signingDescriptor?: string;
37
- /** P, hex, when it cannot be re-derived from the seed at all: the user
38
- * supplied it, or the signer cannot sign deterministically. The swap's only
39
- * claim secret when present. */
40
- preimageHex?: string;
41
- /**
42
- * The salt P derives from, hex, on the salted arm — what a static wallet
43
- * gets instead of storing P. **Public**, and unlike every other field here
44
- * it is minted per swap: it is what stops one repeating key from handing
45
- * every swap the same preimage.
46
- */
47
- preimageSaltHex?: string;
48
- }
49
- /** @deprecated Use `Swap`, projected by `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`. */
50
- interface AssetSwap extends SwapSecretsProjection {
51
- /** Funding txid — the swap's identity. */
52
- id: string;
53
- /** 'btc' or a 68-hex asset id. */
54
- fromAsset: string;
55
- toAsset: string;
56
- /** Atomic amounts as strings (bigint is not JSON-safe). */
57
- fromAmount: string;
58
- /** The covenant wantAmount — a floor, the fill pays >= this. */
59
- toAmount: string;
60
- swapAddress: string;
61
- /** Hex pkScript of the swap contract — the indexer monitoring key. */
62
- swapPkScript: string;
63
- /** TLV offer — needed to rebuild the contract for cancel. */
64
- offerHex: string;
65
- fundingTxid: string;
66
- spentTxid?: string;
67
- status: AssetSwapStatus;
68
- createdAt: number;
69
- completedAt?: number;
70
- /** RFQ pair string, e.g. `arkade:BTC->onchain:BTC`. */
71
- pair?: string;
72
- /** `sha256(P)`, hex. Public, and how a restore confirms a candidate
73
- * derivation is the right one. */
74
- paymentHash?: string;
75
- /** The L1 HTLC's pkScript, hex — the chain-watch key. */
76
- htlcPkScriptHex?: string;
77
- htlcLocktime?: number;
78
- /** The L1 funding txid, once observed. */
79
- l1Txid?: string;
80
- }
81
- /** The consumer read: a broken backend reads as no swaps rather than crashing
82
- * a history view. Mutations must use {@link getAssetSwapsOrThrow} instead —
83
- * swallowing the read there would let "the backend is gone" masquerade as "no
84
- * such swap" and skip the write silently.
85
- *
86
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
87
- */
88
- declare const getAssetSwaps: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
89
- /** Add a swap; no-op if the id is already stored. Returns the updated list.
90
- * THROWS on a failed write — nothing irreversible may happen until this record
91
- * is durable, so the caller must not fund on a failure.
92
- *
93
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
94
- */
95
- declare const addAssetSwap: (repository: AssetSwapRepository, swap: AssetSwap) => Promise<AssetSwap[]>;
96
- /** Merge changes into a swap by id. Returns the updated list.
97
- * THROWS on a failed read or write, like {@link addAssetSwap} — use this for a
98
- * write that gates something irreversible. Transitions written *after* the
99
- * irreversible act belong on {@link updateAssetSwapBestEffort}.
100
- *
101
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
102
- */
103
- declare const updateAssetSwap: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<AssetSwap[]>;
104
- /**
105
- * The record fields a wallet-provisioned secret becomes.
106
- *
107
- * `signingDescriptor` is public and always stored — it is what recovers the
108
- * signer. Then at most one of: `preimageHex`, when the wallet says it cannot
109
- * re-derive P and it becomes the swap's only claim secret; or
110
- * `preimageSaltHex`, the public input a derivable-but-repeating key needs.
111
- *
112
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
113
- */
114
- declare const swapSecretsToRecord: (secrets: ProvisionedKey | ProvisionedClaimSecret) => SwapSecretsProjection & {
115
- signingDescriptor: string;
116
- };
117
- /** Why a wallet cannot produce a swap's preimage.
118
- *
119
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
120
- */
121
- type PreimageBlockedReason =
122
- /** The record carries no `signingDescriptor`. */
123
- "no-secrets"
124
- /** `preimageHex` or `preimageSaltHex` is present but not 32 bytes of hex. */
125
- | "malformed-record"
126
- /**
127
- * Nothing to derive from: a descriptor that repeats across swaps, with
128
- * neither a stored preimage nor a salt — or one this wallet holds no key
129
- * for. Merged deliberately: `contractSigner` reports a key it does not
130
- * hold as a plain `Error` for static wallets and a `ForeignDescriptorError`
131
- * for HD ones, so splitting the two here would mean matching on message
132
- * text, which is the thing this type exists to avoid. The `cause` carries
133
- * whichever it was.
134
- */
135
- | "not-derivable"
136
- /** Derived, but it does not hash to the record's `paymentHash`. */
137
- | "hash-mismatch";
138
- /**
139
- * The wallet cannot produce this swap's preimage, and which of the four ways
140
- * is `reason`.
141
- *
142
- * Deliberately **not** {@link RefundNotLocallyPossibleError}: that one means
143
- * "no local refund is possible", and `RfqSwapManager` acts on it by reporting
144
- * `needs_counterparty`. A claim-path read failure is a different verdict, and
145
- * borrowing the refund error would have the manager announce one for the
146
- * other.
147
- *
148
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
149
- */
150
- declare class PreimageNotRecoverableError extends Error {
151
- readonly reason: PreimageBlockedReason;
152
- readonly name = "PreimageNotRecoverableError";
153
- constructor(reason: PreimageBlockedReason, message: string, options?: {
154
- cause?: unknown;
155
- });
156
- }
157
- /**
158
- * The preimage a swap record claims with — stored, or re-derived from the
159
- * wallet.
160
- *
161
- * The record-shaped inverse of {@link swapSecretsToRecord}, and the one place
162
- * that knows which of a record's fields `contractPreimage` needs. Wire claim
163
- * paths here rather than composing it by hand: a caller that forgets to pass
164
- * `preimageSaltHex` gets a *wrong* preimage from a wallet that can derive,
165
- * not an error.
166
- *
167
- * Verifies the result against `paymentHash` when the record carries one. The
168
- * salted arm has two inputs that can be wrong — the key and the salt — where
169
- * the HD arm had one, and a wrong P otherwise surfaces as an opaque script
170
- * failure at claim time, long after the mistake.
171
- *
172
- * Every refusal is a {@link PreimageNotRecoverableError} carrying a `reason`,
173
- * so a caller can tell "this record predates the descriptor" from "the salt is
174
- * corrupt" without reading message text.
175
- *
176
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
177
- */
178
- declare const preimageForSwapRecord: (wallet: IWallet, record: SwapSecretsProjection & {
179
- paymentHash?: string;
180
- }) => Promise<Uint8Array>;
181
-
182
- /** True for the states after which the solver will report nothing further.
183
- *
184
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
185
- */
186
- declare const isRfqTerminal: (state: string) => boolean;
187
- /**
188
- * Poll a swap's status until it reaches a terminal state.
189
- *
190
- * Same shape and conventions as {@link awaitOnchainFill}: a `pollMs` interval,
191
- * an optional unix-seconds `deadline`, and a thrown error carrying a stable
192
- * `reason` when that deadline passes.
193
- *
194
- * A `null` status (the solver has no record of this `rfq_id`) is treated as
195
- * "not yet", not as an answer — a status route can legitimately 404 for a
196
- * moment after a quote is issued. The deadline is what bounds that wait.
197
- *
198
- * Transport errors are NOT swallowed; a failing `status()` call rejects this
199
- * function. Callers polling across a long refund window should expect to
200
- * restart it after a network blip — nothing is lost by doing so, since the
201
- * refund path this feeds is gated on an absolute timelock that does not
202
- * expire.
203
- *
204
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
205
- */
206
- declare function awaitRfqResolution(transport: RfqTransport, rfqId: string, options?: {
207
- pollMs?: number;
208
- deadline?: number;
209
- }): Promise<RfqStatus>;
210
- /** The indexer surface the lockup lookup needs. */
211
- /**
212
- * What a push needs from the operator: the broadcast pair, plus the info read
213
- * that supplies `checkpointTapscript`.
214
- *
215
- * Narrow on purpose. A wallet's own connection satisfies it —
216
- * `getArkadeBroadcaster()` for the pair and `getArkadeInfo()` for the read — so
217
- * a plugin composes one from the wallet it already has and never opens a second
218
- * connection of its own (#734). A full `ArkProvider` still fits, structurally.
219
- */
220
- type SwapOperator = Pick<ArkProvider, "getInfo" | "submitTx" | "finalizeTx">;
221
- /** @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`. */
222
- type RefundIndexer = Pick<RestIndexerProvider, "getVtxos">;
223
- /** A still-refundable virtual output sitting at the swap lockup.
224
- *
225
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
226
- */
227
- interface LockupVtxo {
228
- txid: string;
229
- vout: number;
230
- value: number;
231
- /**
232
- * The batch this output lived in expired and the operator swept it, so it
233
- * is no longer a live leaf — it can be RECOVERED, but not spent offchain.
234
- *
235
- * It is still the trader's money and it is still visible, which is why
236
- * {@link findLockupVtxos} returns it. What it is not is refundable by
237
- * {@link pushRefundWithoutReceiver}: that builds an offchain Ark
238
- * transaction, and the SDK's own predicates put the two states on opposite
239
- * sides — `canSpendOffchain` is false whenever `canRecoverOnchain` is true
240
- * (`wallet/vtxo.ts`), and the latter is documented as "must be recovered
241
- * into a fresh batch rather than spent offchain". Holding the trader's
242
- * `sender` key does not change that; a sweep removes the leaf from the live
243
- * tree, not the signature from the trader.
244
- *
245
- * Opposite, but not exhaustive: an unrolled output satisfies neither, and
246
- * {@link findLockupVtxos} drops those before they reach this type at all.
247
- *
248
- * So the remedy is recovery (renewing the output into a fresh batch),
249
- * after which the ordinary CLTV refund works again. This package does not
250
- * build that round — see {@link pushRefundWithoutReceiver}, which refuses
251
- * rather than submitting a spend that cannot succeed.
252
- */
253
- recoverable: boolean;
254
- }
255
- /**
256
- * Thrown when a refund was asked for over outputs that have been swept.
257
- *
258
- * Carries the outpoints so a caller can act — recover exactly those, then
259
- * retry — instead of reading a server rejection and guessing. `reason` follows
260
- * the same convention as `awaitOnchainFill`'s `fill_timeout` and
261
- * `claimOnchainFill`'s `claim_window_closed`.
262
- *
263
- * **The remedy already exists; this package does not reimplement it.** The SDK
264
- * recovers swept outputs by re-registering them into a fresh batch, through
265
- * `IVtxoManager.recoverVtxos()`. It reads the wallet's registered-contract
266
- * snapshot (`recoverVtxos` → `wallet.getVtxos({ withRecoverable: true })` →
267
- * `contractSnapshot()` → `contractManager.getContractsWithVtxos()`), so it
268
- * covers a swap lockup as soon as that lockup is registered as a contract —
269
- * which is what {@link RfqSwapManagerDeps.contracts} does. Registration is
270
- * therefore not only a latency optimization; it is what turns a swept lockup
271
- * from a dead end into something the ordinary wallet path can recover.
272
- *
273
- * Two caveats a caller must hold, neither enforceable from here:
274
- *
275
- * - **The wallet must hold the lockup's `sender` key**, because recovery
276
- * settles through `refundWithoutReceiver` — the leaf `vhtlc-v2` annotates
277
- * these VTXOs with.
278
- * - **`refundLocktime` must have matured.** That leaf carries a CLTV, so a
279
- * recovery round including this VTXO earlier is rejected. `recoverVtxos`
280
- * sweeps every recoverable output in ONE settlement and has no CLTV
281
- * awareness, so recovering early can fail the whole batch rather than just
282
- * this output.
283
- *
284
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
285
- */
286
- declare class LockupNeedsRecoveryError extends Error {
287
- readonly name = "LockupNeedsRecoveryError";
288
- readonly reason = "needs_recovery";
289
- /** `txid:vout` for each output that must be recovered first. */
290
- readonly outpoints: string[];
291
- /**
292
- * The contract's `refundLocktime`. Recovering before this matures is the
293
- * hazard described above: `recoverVtxos()` sweeps EVERY recoverable output
294
- * into one settlement with no CLTV awareness, so an early attempt can fail
295
- * the whole batch — including unrelated outputs that were otherwise fine.
296
- *
297
- * Exposed as a value, not only inside the message, so a caller can skip
298
- * pre-CLTV recoverable outputs without parsing prose. Seconds-based
299
- * locktimes mature against the chain tip's timestamp rather than wall
300
- * clock, so treat this as a floor to wait past, not an exact alarm.
301
- */
302
- readonly recoverableAfter: bigint;
303
- constructor(outpoints: string[], recoverableAfter: bigint);
304
- }
305
- /**
306
- * Every output still sitting at the lockup script — spendable AND
307
- * swept-but-recoverable, each tagged with which it is.
308
- *
309
- * All of them, not the first: a trader may fund a lockup in more than one
310
- * send, and refunding only `vtxos[0]` returns part of the money and strands
311
- * the rest at a script whose other refund paths are all longer.
312
- *
313
- * BOTH queries, because they are disjoint sets and `spendableOnly` alone goes
314
- * blind at exactly the wrong moment. A lockup whose batch expiry passed is
315
- * swept into the recoverable set, and this function exists to serve swaps that
316
- * sat unresolved — which are precisely the ones most likely to have got there.
317
- * Reading only the spendable set would report `nothing_to_refund` over money
318
- * that is still sitting at the script, which is worse than an error: it looks
319
- * like a resolved swap.
320
- *
321
- * **Visible is not the same as refundable.** A `recoverable` output cannot be
322
- * spent offchain at all — see {@link LockupVtxo.recoverable} — so this set is
323
- * "what is there", not "what {@link pushRefundWithoutReceiver} can take back".
324
- * That function refuses the recoverable ones by name rather than submitting a
325
- * spend the server must reject.
326
- *
327
- * **Unrolled outputs are the one exception, and are dropped.** A unilaterally
328
- * exited output lives onchain behind its CSV; no offchain spend of any leaf can
329
- * reach it, and `LockupVtxo` carries no field to say so, so a caller could not
330
- * tell it apart from a live one. Whether arkd returns such an output under
331
- * `spendableOnly` is not determinable from here, so the exclusion is made
332
- * defensively rather than assumed. It costs the two waiting callers nothing
333
- * they wanted: `awaitLockupFunding` keeps waiting for a claimable lockup
334
- * instead of publishing `P` into a spend that cannot land, and
335
- * `refundIfUnresolved` reports rather than grinding a doomed push to its
336
- * deadline. Both that function and `RfqSwapManager` name the exit through
337
- * {@link readLockupFate}, which queries unfiltered and reports it as `exited`;
338
- * this drop is the second line, and what still refuses the push on a pass where
339
- * the fate read learned nothing.
340
- *
341
- * This read — not the RFQ's reported state — is the authority on whether
342
- * there is anything left at the lockup.
343
- *
344
- * **Not replaced by the contract manager's VTXO state, deliberately.** Once a
345
- * lockup is registered (see `RfqSwapManagerDeps.contracts`) the wallet tracks
346
- * these same outputs, and `getContractsWithVtxos` plus `canSpendOffchain` /
347
- * `canRecoverOnchain` would classify them. That is a WEAKER answer here on two
348
- * counts: it serves the wallet REPOSITORY, which a degraded sync will happily
349
- * hand back stale (`getSyncState()` reports `degraded` and returns cached rows
350
- * rather than failing), and its height-based expiry test needs a chain tip this
351
- * module does not have. The two queries below ask the indexer itself and need
352
- * neither. Ask-the-indexer, don't-trust-local-state — the same posture
353
- * {@link readLockupFate} takes, and for the same reason: this decides money.
354
- *
355
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
356
- */
357
- declare function findLockupVtxos(indexer: RefundIndexer, swapPkScript: Uint8Array): Promise<LockupVtxo[]>;
358
- /**
359
- * The indexer surface the lockup-spend read needs: the vtxo lookup, plus the
360
- * raw transactions those vtxos were spent by. Same narrow-seam style as
361
- * {@link RefundIndexer} and `restore.ts`'s `RestoreIndexer`, and satisfied by
362
- * {@link RestIndexerProvider}.
363
- *
364
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
365
- */
366
- type LockupSpendIndexer = Pick<RestIndexerProvider, "getVtxos" | "getVirtualTxs">;
367
- /**
368
- * What chain data says became of a swap lockup — the whole answer, with no
369
- * solver involvement and nothing taken on the solver's word.
370
- *
371
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
372
- */
373
- interface LockupSpend {
374
- /** What the vtxo's `spentBy` names — the checkpoint, never the ark
375
- * transaction. */
376
- checkpointTxid: string;
377
- /** The ark transaction that spent the above checkpoint output. What
378
- * history correlation matches on; absent when the indexer omitted it. */
379
- txid?: string;
380
- }
381
- /** @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`. */
382
- type LockupFate =
383
- /** At least one output at the lockup is still unspent. Not over. */
384
- {
385
- fate: "open";
386
- }
387
- /** Spent by a witness carrying a preimage that HASHES to the quote's
388
- * `payment_hash`. Only the claim leaf can reveal one, and the only
389
- * legitimate way the solver obtains it is by completing its side. */
390
- | {
391
- fate: "claimed";
392
- preimage: Uint8Array;
393
- spends: readonly LockupSpend[];
394
- }
395
- /** Fully spent, and nothing that spent it revealed a matching preimage —
396
- * so the money went back to the trader. See {@link readLockupFate}. */
397
- | {
398
- fate: "returned";
399
- spends: readonly LockupSpend[];
400
- }
401
- /**
402
- * At least one output was unilaterally exited: it sits onchain under the
403
- * VHTLC script, where no offchain claim or refund can reach it.
404
- *
405
- * Not terminal, and not a loss. The money is still under the same script
406
- * with the same leaves, so `completeUnroll` plus an onchain spend can still
407
- * end the swap either way — which is why this outranks `open`: an output
408
- * that is "still unspent" but unreachable is not a swap that is merely
409
- * running.
410
- *
411
- * It outranks a verdict too, on a lockup where a sibling output was claimed
412
- * or returned. That is the rule `open` already sets, not a new one: the
413
- * unspent test short-circuits before any witness is read, so a partially
414
- * resolved lockup has never reported `claimed`/`returned`. What changes is
415
- * only that such a lockup now says why it is unresolved.
416
- */
417
- | {
418
- fate: "exited";
419
- outpoints: readonly {
420
- txid: string;
421
- vout: number;
422
- }[];
423
- }
424
- /** Nothing was learned: no outputs visible, an output spent by nothing the
425
- * indexer names, a spend it could not produce, or a blob that would not
426
- * decode. Never an answer. */
427
- | {
428
- fate: "unknown";
429
- };
430
- /**
431
- * Decide from chain data alone whether a swap lockup settled, came back, or is
432
- * still live.
433
- *
434
- * **Why this is decidable without asking anyone.** The lockup's claim leaf can
435
- * only be spent by revealing `P`, so a spend witness carrying a value that
436
- * hashes to the quote's `payment_hash` is proof the claim leaf was used — and
437
- * the only legitimate way the counterparty obtains `P` is by completing its
438
- * side of the swap. Every OTHER leaf is a refund: `nonInteractiveRefund` is
439
- * covenant-pinned to the trader's own address (`enforcePayTo(senderPkScript)`),
440
- * and `refund`, `refundWithoutReceiver`, `unilateralRefund` and
441
- * `unilateralRefundWithoutReceiver` all require the trader's own signature. So
442
- * "spent, but not by a hash-verified claim" means the money went back to the
443
- * trader, and nothing here has to trust a counterparty to say so.
444
- *
445
- * **A matching witness SHAPE is not proof.** Only a candidate that hashes to
446
- * `paymentHash` may be read as a claim; a 32-byte item that hashes to anything
447
- * else is just bytes, and is treated as a refund. Getting this wrong in the
448
- * permissive direction would report "settled" for a swap that actually
449
- * refunded, which is precisely the fact a trader is relying on.
450
- *
451
- * **`unknown` is not `returned`.** An empty vtxo set (indexer lag, or a lockup
452
- * not visible yet), a `spentBy` the indexer cannot produce a transaction for,
453
- * or a blob that will not decode all come back as `unknown`. `getVirtualTxs`
454
- * may legitimately return fewer transactions than were asked for, so the
455
- * observed set is counted rather than assumed complete. The caller's correct
456
- * response to `unknown` is the same as to `open`: keep watching, and let the
457
- * refund timelock — which no outage can move — be what ends the wait.
458
- *
459
- * **An exit is read before anything else, and over the whole set.** It is the
460
- * one fact that makes an unspent output unreachable, so it outranks `open`; and
461
- * it is scanned across every output rather than in outpoint order, so which
462
- * output happens to come first cannot change the answer.
463
- *
464
- * Ask-the-indexer, don't-trust-local-state: read fresh on every poll, never
465
- * cached, the same posture {@link findLockupVtxos} already establishes.
466
- *
467
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
468
- */
469
- declare function readLockupFate(indexer: LockupSpendIndexer, input: {
470
- swapPkScript: Uint8Array;
471
- /** `sha256(P)`, hex — the quote's `payment_hash`. */
472
- paymentHash: string;
473
- }): Promise<LockupFate>;
474
- /**
475
- * Build, sign, and push the `refundWithoutReceiver` spend: return every funded
476
- * output at the lockup to the trader's refund address.
477
- *
478
- * The leaf is `CLTV(refundLocktime) + <sender> + <server>` — the trader's own
479
- * VHTLC `sender` key and the Arkade server, and NOBODY else. In particular the
480
- * emulator is not involved: it co-signs only the two covenant leaves
481
- * (`nonInteractiveClaim` / `nonInteractiveRefund`), which is why the solver's
482
- * own escape hatch has to go through it and this one does not. So unlike that
483
- * push, this transaction is submitted SIGNED, and the only counterparty is the
484
- * Arkade server doing what it does for any collaborative spend.
485
- *
486
- * One aggregate output, not one per input — again unlike the solver's covenant
487
- * refund, which needs index-aligned outputs because its ArkadeScript inspects
488
- * the output at the current input's index. This leaf carries no covenant, so a
489
- * single output paying the whole balance is both valid and cheaper.
490
- *
491
- * `refundPkScript` defaults to the destination the contract itself commits to
492
- * (`nonInteractiveRefund`'s `senderPkScript`, i.e. the address the trader gave
493
- * at quote time), so the ordinary call cannot send the refund somewhere the
494
- * trader did not intend. It is overridable because this leaf, having no
495
- * covenant, genuinely does permit any destination.
496
- *
497
- * **Consensus, not wall clock, decides when this is spendable.** A seconds
498
- * locktime matures against median-time-past, which trails real time by roughly
499
- * an hour, so a push issued the moment `refundLocktime` passes can be rejected
500
- * until enough blocks land. That is expected, not a failure — see
501
- * {@link refundIfUnresolved}, which retries.
502
- *
503
- * **Swept outputs are refused, not attempted.** This is an OFFCHAIN spend, and
504
- * a swept output is no longer a live leaf: `canSpendOffchain` is false wherever
505
- * `canRecoverOnchain` is true, so a recoverable input cannot be spent this way
506
- * whatever key signs it (see
507
- * {@link LockupVtxo.recoverable}). Because every input lands in ONE aggregate
508
- * transaction, a single swept output would take the live ones down with it —
509
- * so the whole push is refused with {@link LockupNeedsRecoveryError} naming the
510
- * outpoints, rather than submitted and rejected. Filtering them out silently
511
- * would be worse still: it would report success over money that never moved.
512
- *
513
- * @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
514
- */
515
- declare function pushRefundWithoutReceiver(operator: SwapOperator, input: {
516
- contract: InstanceType<typeof VHTLC.ScriptV2>;
517
- /** The `sender` signer. Build it from the swap record with
518
- * {@link senderIdentityForSwapRecord} — on an HD wallet that resolves
519
- * from the seed, with no stored key bytes anywhere, and every way the
520
- * wallet can fail to produce it arrives as one typed
521
- * {@link RefundNotLocallyPossibleError} the manager reads as permanent
522
- * rather than retrying for the rest of the refund window. */
523
- sender: Identity;
524
- vtxos: readonly LockupVtxo[];
525
- /** Defaults to the contract's own committed refund destination. */
526
- refundPkScript?: Uint8Array;
527
- }): Promise<{
528
- txid: string;
529
- amount: number;
530
- }>;
531
- /** @deprecated Recovery is internal to the drive; use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`. */
532
- type RefundOutcome =
533
- /** The solver resolved it — claimed (`settled`) or returned it (`refunded`). */
534
- {
535
- outcome: "resolved";
536
- status: RfqStatus;
537
- }
538
- /** The trader took it back via `refundWithoutReceiver`. */
539
- | {
540
- outcome: "refunded";
541
- txid: string;
542
- amount: number;
543
- status: RfqStatus | null;
544
- }
545
- /** The refund window opened but the lockup holds nothing to return. */
546
- | {
547
- outcome: "nothing_to_refund";
548
- status: RfqStatus | null;
549
- }
550
- /**
551
- * The money is still at the lockup, but its batch was swept, so no offchain
552
- * spend can take it back until it is recovered into a fresh batch. Returned
553
- * rather than retried: unlike a median-time-past refusal, no amount of
554
- * waiting fixes this — see {@link LockupNeedsRecoveryError}. Recover the
555
- * named outpoints, then call this again.
556
- */
557
- | {
558
- outcome: "needs_recovery";
559
- outpoints: string[];
560
- vtxos: LockupVtxo[];
561
- status: RfqStatus | null;
562
- }
563
- /**
564
- * The lockup was unilaterally exited: its outputs sit onchain under the VHTLC
565
- * script, where no offchain refund can reach them. Returned rather than
566
- * retried: no amount of waiting changes where the money lives. Complete the
567
- * unroll and spend the named outputs onchain.
568
- *
569
- * **`outpoints` is not necessarily the whole lockup, and `exited` does not
570
- * mean "nothing left to refund".** A lockup funded by more than one UTXO
571
- * reports `exited` as soon as ANY of them has been exited, and `outpoints`
572
- * names only those; a still-live sibling is left unrefunded, and this call
573
- * will not come back for it — the outcome is terminal, so the caller's retry
574
- * loop ends here. That is deliberate rather than an oversight: `RfqSwapManager`
575
- * reports the same lockup `exited` on the same any-output rule, and the two
576
- * must not disagree. It does make the surviving outputs the caller's to
577
- * pursue, through an independent onchain or offchain recovery path that this
578
- * function will not reach.
579
- *
580
- * Distinct from {@link RefundOutcome} `needs_recovery` on purpose: that
581
- * variant's remedy is recovery into a fresh batch, which is a spend no batch
582
- * can make for an output that is already onchain.
583
- */
584
- | {
585
- outcome: "exited";
586
- outpoints: string[];
587
- status: RfqStatus | null;
588
- };
589
- /**
590
- * Ask first, then fall back: watch the swap for the solver to resolve it, and
591
- * if `refundLocktime` matures without that happening, take the lockup back
592
- * with `refundWithoutReceiver`.
593
- *
594
- * This is the whole trader-side failure story in one call. It polls `status()`
595
- * — the only "asking" this protocol has (see the module doc) — and returns as
596
- * soon as the solver reports `settled` or `refunded`. Otherwise, once the
597
- * quote's `refund_locktime` passes, it looks up what is actually at the lockup
598
- * and pushes the refund.
599
- *
600
- * Two behaviours worth knowing:
601
- *
602
- * - **A dead negotiation is not a reason to stop.** `refused`, `expired` and
603
- * `stuck` are terminal states, but a trader can be holding a funded lockup in
604
- * every one of them, so they do not end the wait — only `settled`/`refunded`
605
- * do (see {@link RFQ_RESOLVED_STATES}). What ends it otherwise is the
606
- * timelock.
607
- * - **The first push after the deadline may legitimately fail.** Median-time-
608
- * past trails wall clock, so the server can still consider the leaf locked
609
- * for a while after `refundLocktime` passes in real time. Failures are
610
- * retried at the poll interval until `attemptDeadline`, after which the last
611
- * error is rethrown rather than swallowed.
612
- * - **A swept lockup ends the wait instead of consuming it.** Once the batch
613
- * is gone the CLTV refund is not "not yet" but "not this way", so it returns
614
- * `needs_recovery` naming the outpoints rather than retrying until the
615
- * deadline. Recover them and call again.
616
- * - **An exited lockup ends it the same way, and is checked first.** Each pass
617
- * past the deadline asks {@link readLockupFate} before reading what is
618
- * refundable, so an output that has been unilaterally exited returns `exited`
619
- * instead of feeding a push that cannot land. It costs one extra `getVtxos`
620
- * per such pass (three where there were two), plus a `getVirtualTxs` on a
621
- * fully-spent lockup; only the pass that returns `exited` saves the other two.
622
- * Paid to prevent a push that would otherwise be retried to the deadline and
623
- * then rethrown. A failing fate read is swallowed, not raised: it is a
624
- * shortcut, and losing it must not end a wait the ordinary path could answer.
625
- *
626
- * A lockup funded in two sends of which only one exited reports `exited` for
627
- * the whole thing and leaves the live half unrefunded. That is deliberate:
628
- * `RfqSwapManager` reports the same lockup `exited` on the same any-output
629
- * rule, and the two must not disagree.
630
- *
631
- * Safe to call late, and safe to call again: a caller recovering from a crash
632
- * well past the deadline skips straight to the push, and a lockup that is
633
- * already empty comes back as `nothing_to_refund` instead of an error.
634
- *
635
- * @deprecated Use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
636
- */
637
- declare function refundIfUnresolved(transport: RfqTransport, operator: SwapOperator, indexer: LockupSpendIndexer, input: {
638
- rfqId: string;
639
- contract: InstanceType<typeof VHTLC.ScriptV2>;
640
- /** @see pushRefundWithoutReceiver */
641
- sender: Identity;
642
- /**
643
- * `sha256(P)`, hex — the quote's `payment_hash`, as {@link readLockupFate}
644
- * takes it. Not derivable from `script`, whose `preimageHash` is a
645
- * `hash160` of the same secret.
646
- */
647
- paymentHash: string;
648
- /** `refund_locktime` from the quote, unix seconds. */
649
- refundLocktime: number;
650
- /** Defaults to the contract's own committed refund destination. */
651
- refundPkScript?: Uint8Array;
652
- pollMs?: number;
653
- /** Stop retrying the push at this unix time, rethrowing the last
654
- * error. Defaults to `refundLocktime + REFUND_MTP_LAG_SECONDS`. */
655
- attemptDeadline?: number;
656
- /** Injected for tests; defaults to wall clock, in unix seconds. */
657
- now?: () => number;
658
- }): Promise<RefundOutcome>;
659
-
660
- /**
661
- * Where a monitored RFQ swap stands, and which of those states end it.
662
- *
663
- * Its own module rather than a corner of `swapManager.ts` because the
664
- * dependency runs the other way: the record layer decides retention from
665
- * {@link isRfqSwapTerminal}, and the manager persists through the record
666
- * layer. With the vocabulary here, neither has to import the other at runtime.
667
- * `swapManager.ts` re-exports all three names, so nothing about the public
668
- * surface moved.
669
- */
670
- /**
671
- * Where a monitored swap stands.
672
- *
673
- * `claimable` and `claimed` are the states of a swap the TRADER has something
674
- * to claim on: the L1 fill on an onchain send, and the solver-funded lockup on
675
- * a receive. Only `lightning_send` has neither — there the solver claims the
676
- * lockup, and the trader's only move is the refund.
677
- *
678
- * @deprecated Use `Outcome`, delivered by `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
679
- */
680
- type RfqSwapState =
681
- /** Live; nothing actionable yet. On a receive leg this covers the whole
682
- * stretch before the solver funds anything. */
683
- "pending"
684
- /** There is something for the trader to take, and the window to take it is
685
- * open: the confirmed L1 fill on an onchain send, or a lockup funded for at
686
- * least `expectedAmount` on a receive. */
687
- | "claimable"
688
- /**
689
- * The trader's claim has been made — its L1 broadcast on an onchain send,
690
- * its Arkade submission on a receive.
691
- *
692
- * **On a receive this is a local belief and not a chain fact**, which is
693
- * why it is not terminal: `settled` is the chain's answer, and `refunded`
694
- * is still reachable from here if the claim never lands and the solver
695
- * takes the lockup back.
696
- */
697
- | "claimed"
698
- /**
699
- * This wallet will not act, and only the counterparty can change that.
700
- *
701
- * On a send leg: the Arkade refund cannot be pushed from here — no secrets
702
- * on the record, a descriptor from another seed, or nothing wired to act —
703
- * so the lockup comes back only if the counterparty claims it or the wallet
704
- * that can sign it is restored. On a receive leg: the trader holds no
705
- * refund at all, so this is a lockup that cannot be claimed — funded for
706
- * less than the swap agreed (publishing `P` for it is the whole attack
707
- * `LockupAmountMismatchError` exists to refuse), or one whose claim window
708
- * shut unclaimed. `RfqSwapCommon.blockedReason` says which.
709
- *
710
- * **Not terminal, and not a dead end.** The money is still at the lockup,
711
- * so the counterparty's move is still observable and still ends the swap;
712
- * and the refusal is re-checked every pass, so restoring the right wallet,
713
- * wiring the callbacks, or the solver topping the lockup up returns the
714
- * swap to `pending` and resumes the normal drive. For an onchain-send swap
715
- * it says nothing about the L1 half, which keeps being driven and claimed.
716
- */
717
- | "needs_counterparty"
718
- /**
719
- * Terminal: the lockup was spent by a hash-verified claim. Read off chain,
720
- * never reported.
721
- *
722
- * On a send leg that claim is the counterparty's, and it is proof the
723
- * counterparty completed its side. On a receive leg it is the TRADER's own
724
- * — matched by the hash and not by our txid, so a claim that lands without
725
- * us still counts (see `RfqSwapManager`).
726
- */
727
- | "settled"
728
- /**
729
- * Terminal: the lockup was spent by something other than a claim.
730
- *
731
- * On a send leg that is the money coming back, by the solver's hand or the
732
- * trader's. **On a receive leg it is a LOSS**: the lockup was the solver's
733
- * money, every non-claim leaf is the solver's, and a swap that ends here
734
- * ended with the trader's incoming payment never arriving. It is also where
735
- * a receive swap ends when its window closes with nothing left to observe —
736
- * see `RfqSwapManager`.
737
- */
738
- | "refunded"
739
- /** Terminal: an action failed and its window closed. */
740
- | "failed";
741
- /** @deprecated Use `Outcome`, delivered by `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
742
- declare const isRfqSwapTerminal: (state: RfqSwapState) => boolean;
743
-
744
- /**
745
- * What the manager needs to register a swap's lockup with the wallet, so the
746
- * indexer pushes its funding and its spend instead of being asked every few
747
- * seconds.
748
- *
749
- * Both fields are things the caller already holds. `script` is the very object
750
- * `pushRefundWithoutReceiver` and `pushClaim` take, so a caller wired to act has
751
- * it in hand; `address` is the request entrypoint's own return value. The
752
- * address is taken rather than re-derived on purpose — the row's address must be
753
- * the one that was actually funded, and a local re-derivation would silently use
754
- * the SDK's default network, which is the exact bug `registerOfferContract`
755
- * guards against.
756
- *
757
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
758
- */
759
- interface RfqSwapLockup {
760
- /** The covenant. Its `pkScript` MUST equal the record's `lockupPkScript`. */
761
- script: InstanceType<typeof VHTLC.ScriptV2>;
762
- /** The Arkade address that was funded. */
763
- address: string;
764
- }
765
- interface RfqSwapCommon {
766
- /** The negotiation id — this record's identity. */
767
- rfqId: string;
768
- state: RfqSwapState;
769
- /** The Arkade lockup's scriptPubKey — `swapPkScript` from any of the four
770
- * request entrypoints. This is what the manager watches to decide the swap:
771
- * it is the only handle on the covenant whose spend witness says whether
772
- * the swap settled or came back. */
773
- lockupPkScript: Uint8Array;
774
- /** The covenant behind {@link lockupPkScript}, when the caller wants the
775
- * lockup registered with a contract manager. Optional: without it the
776
- * manager still watches the swap on its timer, it just cannot subscribe.
777
- * See {@link RfqSwapManagerDeps.contracts}. */
778
- lockup?: RfqSwapLockup;
779
- /**
780
- * `sha256(P)`, hex — the quote's `payment_hash`. The claim leaf can only
781
- * be spent by revealing a value that hashes to this, which is what makes a
782
- * settlement provable rather than reported. For an onchain send this is
783
- * the SAME hash the L1 `htlc` carries: one `P` unlocks both legs.
784
- *
785
- * True of the three corridors that exist today and only of them: a hashlock
786
- * belongs to a CORRIDOR, and a banco-style one settles without any. The
787
- * stored record already says so — the hash lives in `profile.hashlock`, not
788
- * on `RfqSwapRecord` — and this field follows onto the per-corridor swap
789
- * types when the first such corridor lands. Do not read the current shape as
790
- * settled.
791
- */
792
- paymentHash: string;
793
- /**
794
- * `refund_locktime` from the quote, unix seconds.
795
- *
796
- * Whose deadline it is inverts with the direction, and so does what to do
797
- * about it. On a send leg it is the TRADER's: the lockup is the trader's
798
- * money and this gates the refund that takes it back, so it is a moment to
799
- * act AFTER. On a receive leg it is the SOLVER's: the trader has no refund
800
- * leaf at all, and this is the moment to have claimed BEFORE.
801
- */
802
- refundLocktime: number;
803
- createdAt: number;
804
- updatedAt: number;
805
- /** Set once the trader's own `refundWithoutReceiver` push landed. */
806
- refundTxid?: string;
807
- /**
808
- * The ark transactions that SPENT the lockup, stamped from the chain read
809
- * that ended the swap — `LockupFate.spends`, whichever verdict it reached.
810
- *
811
- * The counterparty's move, on every leg but one: a solver claim on a send,
812
- * a solver reclaim on a receive, and — the exception — the trader's own
813
- * claim when a receive settles. What they have in common is that no local
814
- * action produced them, so nothing else on this record can name them:
815
- * {@link refundTxid} names only a push this wallet made, and
816
- * `claimTxid` only a submission it made.
817
- *
818
- * Stamped so a terminal record answers "which transaction ended this" from
819
- * storage. Without it the only source is another read of the lockup — a
820
- * network round trip per terminal swap, which is what activity correlation
821
- * has to pay on the offline-first path where it is least affordable.
822
- *
823
- * Absent when the swap ended without a chain verdict, or when the indexer
824
- * named the checkpoint but not the ark transaction — the same `txid`
825
- * `LockupSpend` declares optional, for the same reason.
826
- */
827
- lockupSpendTxids?: string[];
828
- /** Why `state` is `failed`. */
829
- failure?: string;
830
- /**
831
- * Last local claim error while the receive swap is still retryable.
832
- *
833
- * Distinct from terminal `failure`: this records a claim attempt that failed
834
- * before the window closed. If the window later closes without a submitted
835
- * claim, it becomes the terminal failure reason.
836
- */
837
- claimFailure?: string;
838
- /** Why `state` is `needs_counterparty`. Distinct from {@link failure},
839
- * which means an action was attempted and did not work. */
840
- blockedReason?: string;
841
- }
842
- /** `arkade:BTC->lightning:BTC`. Nothing for the trader to claim: the solver
843
- * claims the lockup with the preimage it learns by paying the invoice — which
844
- * is exactly why that spend's witness is proof the payment landed.
845
- *
846
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
847
- */
848
- interface LightningSendSwap extends RfqSwapCommon {
849
- kind: "lightning_send";
850
- }
851
- /** `arkade:BTC->onchain:BTC`. Carries the L1 half the trader must claim.
852
- *
853
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
854
- */
855
- interface OnchainSendSwap extends RfqSwapCommon {
856
- kind: "onchain_send";
857
- /** The locally derived HTLC from `requestOnchainSend` — the manager reads
858
- * `pkScript`, `paymentHash` and `refundLocktime` off it to classify. */
859
- htlc: OnchainHtlc;
860
- /** `profile.min_confirmations` from the quote. */
861
- minConfirmations: number;
862
- /** Where {@link RfqSwapManagerCallbacks.claimOnchain} pays; optional only
863
- * so records predating its profile slot still restore. */
864
- payoutPkScript?: Uint8Array;
865
- /** The fill's outpoint, learned on first sighting. Without it a SPENT
866
- * HTLC reads as never funded — see {@link classifyOnchainHtlc}. */
867
- funding?: {
868
- txid: string;
869
- vout: number;
870
- };
871
- /** Our L1 claim's txid. */
872
- claimTxid?: string;
873
- }
874
- /**
875
- * `lightning:BTC->arkade:BTC`. The inverted leg: the SOLVER funds the lockup
876
- * and the TRADER claims it, and that claim is what publishes `P` and lets the
877
- * solver settle the payer's held Lightning HTLC.
878
- *
879
- * Two consequences shape how this record is driven, both of them absent from
880
- * the send legs:
881
- *
882
- * - **There is no trader-side refund.** Every non-claim leaf of this covenant
883
- * is the solver's, so the manager never calls
884
- * {@link RfqSwapManagerCallbacks.refundArkade} for one of these. A swap that
885
- * is not claimed is simply lost — the solver reclaims at
886
- * {@link RfqSwapCommon.refundLocktime} and the payer is refunded when the
887
- * held HTLC lapses.
888
- * - **The claim is the whole swap, and it is on a deadline.** The trader must
889
- * be online for it: covclaimd cannot claim this covenant today, so the claim
890
- * packet's offline path does not run.
891
- *
892
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
893
- */
894
- interface LightningReceiveSwap extends RfqSwapCommon {
895
- kind: "lightning_receive";
896
- /**
897
- * What the lockup must carry — the quote's `to_amount`, captured at REQUEST
898
- * time and persisted with the record.
899
- *
900
- * **Not re-derivable, and not optional.** Captured at claim time it would
901
- * be whatever the solver funded, which is the dust-funding attack rather
902
- * than a check on it. A record that reaches the manager without a finite
903
- * value here is reported `needs_counterparty` and never claimed: a
904
- * comparison against `undefined` or `NaN` is false, so an unusable
905
- * comparand does not fail the value gate, it deletes it.
906
- */
907
- expectedAmount: number;
908
- /** Our Arkade claim's txid, once submitted. Set from the callback's return
909
- * and never from a chain read — the chain's answer is `settled`. */
910
- claimTxid?: string;
911
- }
912
- /**
913
- * A monitored swap.
914
- *
915
- * This is a live record, not a serialization format: `lockupPkScript` and
916
- * `htlc` hold derived `Uint8Array`s, and `RfqSwapRecord` is its storable
917
- * projection. Give the manager a {@link RfqSwapManagerDeps.repository} and it
918
- * writes and rebuilds these itself, through
919
- * {@link RfqSwapManager.restoreFromRepository}. A caller keeping its own store
920
- * projects it in {@link RfqSwapManagerCallbacks.saveSwap} instead, rebuilds it
921
- * on restart the way it was made — `lightningSendContract` /
922
- * `lightningReceiveContract` / `onchainHtlcScript` over the quote's binding fields —
923
- * and hands the result to {@link RfqSwapManager.start}.
924
- *
925
- * **`onchain:BTC->arkade:BTC` is deliberately not a member yet.** Its Arkade
926
- * half is the same solver-funded lockup as {@link LightningReceiveSwap}'s, but
927
- * it also has an L1 half the trader funds and must take back itself
928
- * (`buildHtlcRefund` at the HTLC's own `htlc_locktime`), which is a second
929
- * deadline, a second observation seam and a second action callback. Adding the
930
- * lockup half alone would produce a manager that silently lets that L1 refund
931
- * window pass — the one failure mode {@link RfqSwapManager} refuses elsewhere
932
- * by name (see `driveOnchain`'s missing-`ChainSource` check). Until the L1
933
- * refund is driven too, that corridor is better served by the request and claim
934
- * functions directly than by a monitor that covers half of it.
935
- *
936
- * @deprecated Use `Swap`, projected by `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
937
- */
938
- type RfqSwap = LightningSendSwap | OnchainSendSwap | LightningReceiveSwap;
939
- /** What the manager should do next about an onchain-send swap's L1 half.
940
- *
941
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
942
- */
943
- type OnchainSendAction =
944
- /** Not funded yet, or not confirmed deep enough. */
945
- "wait"
946
- /** Funded, confirmed, and far enough from the refund leaf to claim safely. */
947
- | "claim"
948
- /** The claim is off the table for good; the money comes back through the
949
- * Arkade lockup instead. */
950
- | "claim_window_closed"
951
- /** Our claim already landed (only the trader holds P). */
952
- | "claimed"
953
- /** The solver took its L1 refund — the fill is gone. */
954
- | "swept";
955
- /**
956
- * The decision a "poll status, refund on timeout" loop gets wrong.
957
- *
958
- * {@link OnchainHtlcPhase} runs `unfunded -> awaiting_confirmations ->
959
- * claimable -> (refundable | claimed | swept)`, and `refundable` does NOT mean
960
- * "time to refund the L1 HTLC" — the trader has no key on that leaf; it is the
961
- * SOLVER's refund, and reaching it means the trader's claim was missed. So the
962
- * L1 claim has to be driven before it, and from it the only remaining move is
963
- * the Arkade-side refund.
964
- *
965
- * There is a second, quieter trap between those two functions:
966
- * `classifyOnchainHtlc` reports `claimable` right up until median-time-past
967
- * reaches `refundLocktime`, while `claimOnchainFill` refuses from
968
- * {@link ONCHAIN_CLAIM_MARGIN_SECONDS} before it — because broadcasting
969
- * publishes P, and doing that into the counterparty's live refund window risks
970
- * losing the race AND giving away the preimage. Driving straight off the phase
971
- * would therefore spend that whole margin throwing `claim_window_closed` at
972
- * every poll and never fall back. This function applies the margin, so
973
- * "claimable" here means claimable by `claimOnchainFill` too.
974
- *
975
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
976
- */
977
- declare function nextOnchainAction(input: {
978
- phase: OnchainHtlcPhase;
979
- /** `htlc.refundLocktime` — when the solver's L1 refund leaf opens. */
980
- htlcLocktime: number;
981
- /** Unix seconds. */
982
- now: number;
983
- }): OnchainSendAction;
984
- /** What the trader's own `refundWithoutReceiver` push returned, or `null` when
985
- * the lockup held nothing to return.
986
- *
987
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
988
- */
989
- type ArkadeRefundResult = {
990
- txid: string;
991
- amount: number;
992
- } | null;
993
- /**
994
- * The money-moving half, injected. The manager decides when; these do it.
995
- *
996
- * Neither action gets a retry loop of its own here — see the module doc. Take
997
- * `arkadeRefunder` for `refundArkade` rather than assembling it: it composes
998
- * the atomic push (`findLockupVtxos` + `senderIdentityForSwapRecord` +
999
- * `pushRefundWithoutReceiver`) and keeps the three rules below structural.
1000
- *
1001
- * Do NOT wire `refundArkade` to `refundIfUnresolved`: that function is the
1002
- * single-swap version of this whole class and brings its own status polling
1003
- * and its own MTP retry loop, which would nest inside the manager's.
1004
- *
1005
- * Resolve the sender key through `senderIdentityForSwapRecord`: it is
1006
- * what turns "this wallet cannot sign this swap" into
1007
- * {@link RefundNotLocallyPossibleError}, which the manager reports as
1008
- * `needs_counterparty` instead of retrying for the whole refund window.
1009
- *
1010
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1011
- */
1012
- interface RfqSwapManagerCallbacks {
1013
- /** Build and broadcast the L1 claim. See `claimOnchainFill`. */
1014
- claimOnchain: (swap: OnchainSendSwap, utxo: ChainUtxo) => Promise<{
1015
- txid: string;
1016
- }>;
1017
- /**
1018
- * Claim the solver-funded lockup on a receive leg, revealing `P`. Wire it
1019
- * to `pushClaim` — the outputs are supplied, so `findLockupVtxos` has
1020
- * already been called and `claimReceiveLockup`'s wait would only sit on a
1021
- * lockup the manager has just seen.
1022
- *
1023
- * **Pass `expectedAmount` and `partiallyClaimed` straight through.** The
1024
- * manager checks the funded value before calling this, but that check
1025
- * decides WHEN to act; `pushClaim`'s decides whether `P` is published, and
1026
- * it is the one that runs with nothing between it and the signature. Two
1027
- * checks, one of which is load-bearing — do not drop the inner one because
1028
- * the outer one exists.
1029
- *
1030
- * Required here, like {@link claimOnchain}: a receive swap monitored with
1031
- * nothing wired to claim it is a swap that quietly expires, and a compile
1032
- * error is the right way to learn that. A consumer that drives only the
1033
- * kinds needing neither installs
1034
- * {@link AvailableRfqSwapManagerCallbacks} instead and takes the runtime
1035
- * refusal in its place.
1036
- */
1037
- claimLockup: (swap: LightningReceiveSwap, vtxos: readonly LockupVtxo[], options: {
1038
- /** A claim of ours is already out, so `P` is public and the value
1039
- * gate has nothing left to protect — pass this to `pushClaim` so a
1040
- * funding that arrived piecemeal can still be swept. */
1041
- partiallyClaimed: boolean;
1042
- }) => Promise<{
1043
- txid: string;
1044
- amount: number;
1045
- }>;
1046
- /**
1047
- * Push `refundWithoutReceiver` for every output at the lockup. See
1048
- * `pushRefundWithoutReceiver`; return `null` for an empty lockup. Never
1049
- * called for a {@link LightningReceiveSwap} — that leg's refund leaf is the
1050
- * solver's.
1051
- *
1052
- * Only {@link RefundNotLocallyPossibleError} is read as permanent. Every
1053
- * other throw is treated as transient and RETRIED once a poll: each attempt
1054
- * reports through `onSwapFailed` unwrapped, and the swap ends `failed` only
1055
- * past `refundLocktime + REFUND_MTP_LAG_SECONDS`. That is deliberate for a
1056
- * genuinely transient failure — `LockupNeedsRecoveryError` is the
1057
- * case it is built for, since recovery is something the caller can perform
1058
- * while the window is still open — but it means a wiring mistake that
1059
- * throws unconditionally does not read as `needs_counterparty`. It reports
1060
- * once a poll for the rest of the refund window and then ends `failed`.
1061
- * Throw {@link RefundNotLocallyPossibleError} for anything this wallet will
1062
- * never be able to do.
1063
- */
1064
- refundArkade: (swap: RfqSwap) => Promise<ArkadeRefundResult>;
1065
- /**
1066
- * Whether a local refund is possible at all — the record's secrets, against
1067
- * this wallet. Called every pass, including *before* the refund window
1068
- * opens, so a swap nobody can refund says so while the solver can still
1069
- * act, instead of at the deadline; and so restoring the right wallet lifts
1070
- * the state again. Never called for a receive swap: there is no local
1071
- * refund there to probe for.
1072
- *
1073
- * Optional: omit to answer "yes" and learn at push time, from
1074
- * {@link RefundNotLocallyPossibleError}. Local by contract — no network
1075
- * call belongs here.
1076
- */
1077
- canRefundArkade?: (swap: RfqSwap) => Promise<{
1078
- ok: true;
1079
- } | {
1080
- ok: false;
1081
- reason: string;
1082
- }>;
1083
- /**
1084
- * Persist the record. Called after any pass that changed it.
1085
- *
1086
- * With {@link RfqSwapManagerDeps.repository} wired this is the SECOND
1087
- * write of the pass, not the only one: the manager writes the canonical
1088
- * `RfqSwapRecord` itself and then calls this. Both must succeed for the
1089
- * pass to count as persisted, so a rejection here still holds waiters and
1090
- * finalization back exactly as it does without a repository. A consumer
1091
- * whose `saveSwap` writes that same repository by hand should
1092
- * drop the duplicate when it wires the dep, and keep this for genuinely
1093
- * secondary sinks: metrics, a cache, a second store.
1094
- */
1095
- saveSwap: (swap: RfqSwap) => Promise<void>;
1096
- }
1097
- /**
1098
- * What {@link RfqSwapManager.setCallbacks} accepts: the full contract, minus
1099
- * the two claims that are already kind-gated at dispatch, and minus
1100
- * `saveSwap`. A consumer driving only lightning sends reaches neither claim,
1101
- * and stubbing them to throw is not a contract — it is a lie the compiler
1102
- * waves through.
1103
- *
1104
- * `saveSwap` is optional for the same reason one step removed: with
1105
- * {@link RfqSwapManagerDeps.repository} wired the manager writes the record
1106
- * itself, so a consumer with no second sink has nothing to put here, and a
1107
- * no-op stub would be that same lie. Omitting BOTH is the documented
1108
- * process-local mode: state is kept in memory and dies with the process,
1109
- * which is what a manager with no callbacks at all already does today.
1110
- *
1111
- * The strict {@link RfqSwapManagerCallbacks} is untouched and still means
1112
- * "fully wired", so a helper that takes one and calls `claimOnchain` keeps its
1113
- * guarantee. Only the parameter widens, which every existing caller satisfies.
1114
- *
1115
- * The compile-time guarantee this trades away is bought back at runtime: a
1116
- * kind whose claim is missing blocks — non-terminal, re-evaluated every pass,
1117
- * and lifted the moment `setCallbacks` supplies it.
1118
- *
1119
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1120
- */
1121
- type AvailableRfqSwapManagerCallbacks = Omit<RfqSwapManagerCallbacks, "claimOnchain" | "claimLockup" | "saveSwap"> & Partial<Pick<RfqSwapManagerCallbacks, "claimOnchain" | "claimLockup" | "saveSwap">>;
1122
- /** The actions the manager executes on a caller's behalf.
1123
- *
1124
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1125
- */
1126
- type RfqSwapActionName = "claimOnchain" | "claimLockup" | "refundArkade";
1127
- /** @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
1128
- interface RfqSwapManagerEvents {
1129
- /** Every state change, including ones that read as going backwards.
1130
- * `claimed -> claimable` is legal and expected on a receive swap the solver
1131
- * funds piecemeal: a lockup topped up after a claim is a new claimable
1132
- * event, and the label says so before the sweep goes out. Treat these
1133
- * states as a description of what to do next, not as a progress bar. */
1134
- onSwapUpdate?: (swap: RfqSwap, previous: RfqSwapState) => void;
1135
- /** Fired once, when a swap leaves monitoring `settled` or `refunded`.
1136
- * A swap that ends `failed` reports through `onSwapFailed` instead — the
1137
- * two are mutually exclusive. */
1138
- onSwapCompleted?: (swap: RfqSwap) => void;
1139
- /** Fired for any action that threw — including ones the manager will retry
1140
- * on the next pass — and once more when the swap finally ends `failed`. */
1141
- onSwapFailed?: (swap: RfqSwap, error: Error) => void;
1142
- onActionExecuted?: (swap: RfqSwap, action: RfqSwapActionName) => void;
1143
- }
1144
- type SwapUpdateListener = NonNullable<RfqSwapManagerEvents["onSwapUpdate"]>;
1145
- type SwapCompletedListener = NonNullable<RfqSwapManagerEvents["onSwapCompleted"]>;
1146
- type SwapFailedListener = NonNullable<RfqSwapManagerEvents["onSwapFailed"]>;
1147
- type ActionExecutedListener = NonNullable<RfqSwapManagerEvents["onActionExecuted"]>;
1148
- /** @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
1149
- interface RfqSwapManagerConfig {
1150
- /** Drive claims and refunds automatically (default: true). With this off
1151
- * the manager still watches and reports, so a caller can act by hand off
1152
- * `claimable`. */
1153
- enableAutoActions?: boolean;
1154
- /** How often to run a pass, ms. Default 5000 — the same interval
1155
- * `awaitOnchainFill` and `refundIfUnresolved` poll at. */
1156
- pollIntervalMs?: number;
1157
- /** Injected for tests; defaults to wall clock, in unix seconds — the same
1158
- * convention `refundIfUnresolved` uses. */
1159
- now?: () => number;
1160
- events?: RfqSwapManagerEvents;
1161
- }
1162
- /** The contract-manager surface this needs, narrowed for injection — the same
1163
- * seam style as {@link LockupSpendIndexer} and `refund.ts`'s
1164
- * `RefundIndexer`, and satisfied structurally by a real
1165
- * `ContractManager` (`await wallet.getContractManager()`).
1166
- *
1167
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1168
- */
1169
- type SwapContractRegistry = Pick<IContractManager, "createContract" | "getContracts" | "onContractEvent" | "setContractWatchState">;
1170
- /**
1171
- * The record store the manager writes to, narrowed to the four RFQ methods —
1172
- * the same seam style as {@link LockupSpendIndexer} and
1173
- * {@link SwapContractRegistry}, and satisfied structurally by a real
1174
- * `AssetSwapRepository`.
1175
- *
1176
- * Narrowed rather than imported whole so this module keeps no runtime edge to
1177
- * `repository.ts`, and so a caller with a different backing store — a server
1178
- * process holding many wallets' records in one table — can satisfy it without
1179
- * implementing the offer-swap and markets halves it has no use for.
1180
- *
1181
- * Expect TWO calls per dirty swap per poll: `getRfqSwap` then `saveRfqSwap`.
1182
- * The read is deliberate — the store is the system of record, so a consumer's
1183
- * own edit to a record's origin half must not be overwritten by a copy the
1184
- * manager took at boot — but a backend where a keyed read is expensive should
1185
- * know it is on the write path, not just the restore path.
1186
- *
1187
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1188
- */
1189
- interface RfqSwapRecordStore {
1190
- saveRfqSwap(record: RfqSwapRecord): Promise<void>;
1191
- getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
1192
- getAllRfqSwaps(): Promise<RfqSwapRecord[]>;
1193
- removeRfqSwap(rfqId: string): Promise<void>;
1194
- }
1195
- /**
1196
- * A swap was handed to the manager with a repository wired, no origin, and no
1197
- * record already in the store.
1198
- *
1199
- * Thrown at the door rather than at the first write, because the write happens
1200
- * a pass later and by then the funding is broadcast: a swap admitted here and
1201
- * refused at `save` would be monitored, acted on, and unwritable — the record
1202
- * would exist only in memory while its lockup held money, and a restart would
1203
- * lose it. The remedy is to pass the origin, which the caller has: it is what
1204
- * the request entrypoint returned.
1205
- *
1206
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1207
- */
1208
- declare class RfqSwapOriginRequired extends Error {
1209
- /** The swap that could not be admitted. */
1210
- readonly rfqId: string;
1211
- constructor(rfqId: string);
1212
- }
1213
- /** One stored record that could not be turned back into a live swap.
1214
- *
1215
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1216
- */
1217
- interface RfqRestoreFailure {
1218
- rfqId: string;
1219
- /** Why — a covenant that does not derive the funded address, a lockup with
1220
- * no contract row, a corridor with no handler registered. */
1221
- error: Error;
1222
- }
1223
- /** @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
1224
- interface RfqRestoreOptions {
1225
- /**
1226
- * Where each record's covenant parameters come from. Defaults to the
1227
- * lockup's own contract row, read through
1228
- * {@link RfqSwapManagerDeps.contracts}.
1229
- *
1230
- * Override it when the covenant lives somewhere else — a consumer keeping
1231
- * its own copy of `VHTLCV2ContractHandler.serializeParams(...)`, or a
1232
- * process with no contract manager at all. Whatever it returns is still
1233
- * checked against the record's funded address by `rebuildRfqSwap`, so an
1234
- * override cannot produce a swap watching the wrong covenant.
1235
- */
1236
- params?: (record: RfqSwapRecord) => Promise<LockupParams>;
1237
- }
1238
- /** What {@link RfqSwapManager.restoreFromRepository} did. Every stored record
1239
- * is in exactly one of the three lists.
1240
- *
1241
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1242
- */
1243
- interface RfqRestoreResult {
1244
- /** Rebuilt: monitored, or kept as finished when already terminal. */
1245
- restored: RfqSwap[];
1246
- /** Kept in the store, but not rebuildable right now. */
1247
- failed: RfqRestoreFailure[];
1248
- /** Removed: terminal and past `RFQ_SWAP_RETENTION_SECONDS`. */
1249
- pruned: string[];
1250
- }
1251
- /** The observation seams. None is owned by the manager, and none holds keys —
1252
- * same philosophy as `onchainHtlc.ts`'s `ChainSource`. There is no
1253
- * `RfqTransport` here on purpose: nothing this manager decides depends on the
1254
- * solver answering (see the module doc).
1255
- *
1256
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1257
- */
1258
- interface RfqSwapManagerDeps {
1259
- /** Arkade access. Required: this is how a swap's resolution is determined,
1260
- * for both legs. */
1261
- indexer: LockupSpendIndexer;
1262
- /** L1 access. Required to monitor onchain-send swaps; a lightning-only
1263
- * caller can leave it out. */
1264
- chain?: ChainSource;
1265
- /**
1266
- * Where the manager persists RFQ swap records, when a caller wants it to.
1267
- *
1268
- * Wiring it makes the repository the CANONICAL sink: every pass that
1269
- * changed a swap is written here as an {@link RfqSwapRecord}, and
1270
- * {@link RfqSwapManager.restoreFromRepository} reads it back. That removes
1271
- * the origin trap a caller otherwise hits assembling the write by hand —
1272
- * `updateRfqSwapRecord` needs the existing record and
1273
- * `createRfqSwapRecord` needs request-time facts the live swap does not
1274
- * carry, so the first write of a swap cannot be composed from the swap
1275
- * alone. The manager resolves that itself, which is what
1276
- * {@link RfqSwapManager.addSwap}'s `origin` parameter is for.
1277
- *
1278
- * Optional, like every other dep here: without it the manager persists
1279
- * through {@link RfqSwapManagerCallbacks.saveSwap} exactly as before, and
1280
- * without either it keeps its state in memory.
1281
- */
1282
- repository?: RfqSwapRecordStore;
1283
- /**
1284
- * The wallet's contract manager, when there is one. Optional in the same
1285
- * way {@link chain} is: a caller with no wallet, or one that only wants the
1286
- * timer, still gets a fully working manager — the subscription is a
1287
- * LATENCY optimization and nothing depends on it.
1288
- *
1289
- * Supplying it buys two things. The lockup gets REGISTERED, which is what
1290
- * puts it in the wallet's own contract set at all — a prerequisite for
1291
- * anything that has to act on the lockup before its batch expires, since an
1292
- * expired lockup is swept and loses every cooperative path. And the indexer
1293
- * PUSHES its funding and its spend, so a settlement is noticed when it
1294
- * happens rather than up to `pollIntervalMs` later.
1295
- *
1296
- * Prefer `await wallet.getContractManager()` over constructing one, the way
1297
- * `createOffer` does.
1298
- */
1299
- contracts?: SwapContractRegistry;
1300
- }
1301
- /**
1302
- * Watches a set of live RFQ swaps and drives each to its end.
1303
- *
1304
- * One pass per swap, in this order, every
1305
- * {@link RfqSwapManagerConfig.pollIntervalMs} — and additionally the moment a
1306
- * contract event names that swap's lockup, which changes only WHEN a pass runs,
1307
- * never what it concludes (see {@link subscribe}):
1308
- *
1309
- * 0. **Register the lockup**, if a contract manager was supplied and it is not
1310
- * registered yet. Best-effort; never blocks the steps below.
1311
- * 1. **Ask the chain what became of the lockup** — {@link readLockupFate}. A
1312
- * spend whose witness HASHES to the quote's `payment_hash` ends the swap
1313
- * `settled`; a lockup fully spent by anything else ends it `refunded`.
1314
- * Anything the indexer could not answer is `unknown`, which is NOT an
1315
- * answer: the pass carries on to the steps below, whose deadlines an indexer
1316
- * outage has no bearing on. `exited` — an output unilaterally taken onchain
1317
- * — ends neither the swap nor the pass: it blocks the Arkade half below,
1318
- * with the L1 half left running.
1319
- * 2. **Drive the trader's claim.** On an onchain send that is the L1 fill — see
1320
- * {@link nextOnchainAction}. On a receive it is the lockup itself, and it
1321
- * ends the pass: that leg has no step 3.
1322
- * 3. **Take the lockup back**, send legs only, once `refundLocktime` has passed
1323
- * and step 1 has not ended the swap. This runs for onchain-send too,
1324
- * including after a successful claim: the trader's lockup is still funded and
1325
- * still theirs to recover if the solver never comes for it. When no local
1326
- * refund is possible at all — no secrets, another wallet's descriptor,
1327
- * nothing wired — the swap reports `needs_counterparty` instead of retrying
1328
- * a push that cannot work.
1329
- *
1330
- * **What step 1 proves depends on the direction.** On a send leg every non-claim
1331
- * leaf pays the trader's own committed address or needs the trader's own
1332
- * signature, so "spent, but not by a hash-verified claim" means the money came
1333
- * back. On a receive leg those leaves are the SOLVER's and the claim leaf is the
1334
- * trader's, so the same two readings mean the opposite things — `settled` is the
1335
- * trader's own claim landing, `refunded` is the solver taking back a lockup the
1336
- * trader failed to claim. The read is identical; only the state docs differ.
1337
- *
1338
- * Two things about the receive arm that are easy to get wrong, and are asserted
1339
- * in the tests rather than left to be inferred:
1340
- *
1341
- * - **A claim is matched by its preimage, never by our txid.** The covenant's
1342
- * `nonInteractiveClaim` leaf is pinned to the trader's own payout script, so a
1343
- * claim that lands without us — covclaimd, the day it works — still pays the
1344
- * trader and is still `settled`. Matching on the txid we submitted would turn
1345
- * that success into an anomaly.
1346
- * - **`LockupFate.fate === "claimed"` maps to the state `settled`, never to the
1347
- * state `claimed`.** The two words live one layer apart: the fate is the
1348
- * chain's, the state is ours, and the state `claimed` means only that we
1349
- * submitted something.
1350
- *
1351
- * @deprecated Use `createSwapClient`. Moved off the package root to `@arkade-os/swap/protocol`.
1352
- */
1353
- declare class RfqSwapManager {
1354
- private readonly deps;
1355
- private readonly config;
1356
- private callbacks;
1357
- private readonly swapUpdateListeners;
1358
- private readonly swapCompletedListeners;
1359
- private readonly swapFailedListeners;
1360
- private readonly actionExecutedListeners;
1361
- private readonly monitored;
1362
- /** Monitored swaps by lockup script hex, so a contract event — which names
1363
- * a script and nothing else — can find the swap it belongs to. */
1364
- private readonly byLockupScript;
1365
- /**
1366
- * Swaps whose lockup registration has been SETTLED one way or another,
1367
- * mapped to whether a contract row actually resulted. Membership is what
1368
- * stops a per-pass retry from becoming a per-pass round trip; the value is
1369
- * what keeps a swap that could never be registered from later trying to
1370
- * retire a row that does not exist, which would report a spurious failure
1371
- * on a swap that in fact succeeded.
1372
- */
1373
- private readonly registered;
1374
- /**
1375
- * Swaps whose `refundArkade` answered {@link RefundNotLocallyPossibleError}
1376
- * in this process. Membership stops the push from being re-issued every
1377
- * pass — it cannot start working on its own, and re-issuing it is the
1378
- * grind `needs_counterparty` exists to remove. Only
1379
- * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it, so a caller
1380
- * with no probe learns again on the next start, when the wallet that can
1381
- * sign may well have been restored.
1382
- */
1383
- private readonly refundRefused;
1384
- /**
1385
- * The lockup outpoints a receive swap's claim callback has already been
1386
- * handed, by rfqId.
1387
- *
1388
- * What this exists to prevent: a claim SUCCEEDS, and for the next few
1389
- * passes the indexer still lists those outputs as unspent. Without a
1390
- * record of what was already claimed, every one of those passes would
1391
- * re-submit the same spend, fail against the server, and report a swap
1392
- * that in fact worked as failing. With one, a re-claim happens only when
1393
- * an outpoint appears that was never claimed — a lockup funded piecemeal,
1394
- * which is legitimate and which `partiallyClaimed` exists for.
1395
- *
1396
- * Process-local: after a restart a swap with a live claim tries once more.
1397
- * That is the recovery case rather than the spam one — a claim that never
1398
- * landed leaves its outputs unspent, and one that did leaves a single
1399
- * rejection.
1400
- */
1401
- private readonly claimedOutpoints;
1402
- /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
1403
- private unsubscribeContracts;
1404
- /** Terminal records, kept so a late {@link waitForSwapCompletion} still
1405
- * answers instead of throwing "not found". Cleared by {@link removeSwap}. */
1406
- private readonly finished;
1407
- private readonly waiters;
1408
- /**
1409
- * The request-time origin of each swap the manager may have to CREATE a
1410
- * record for, by rfqId.
1411
- *
1412
- * Needed only for a swap the store has never seen: once a record exists,
1413
- * `updateRfqSwapRecord` carries the origin half through and the map is
1414
- * redundant. It is kept anyway for the swap's whole life, so a record the
1415
- * store loses between passes is rewritten rather than lost — and dropped
1416
- * by {@link removeSwap} and by retention, which are the two places a swap
1417
- * stops being this manager's business.
1418
- */
1419
- private readonly origins;
1420
- /** Records changed during the current pass, flushed to the repository and
1421
- * through `saveSwap`. */
1422
- private readonly dirty;
1423
- /** Race guard: one action at a time per swap. */
1424
- private readonly inProgress;
1425
- private timer;
1426
- private running;
1427
- constructor(deps: RfqSwapManagerDeps, config?: RfqSwapManagerConfig);
1428
- /** Wire the money-moving half. Without it the manager only watches. The
1429
- * two claims may be omitted for a consumer that drives no kind reaching
1430
- * them — see {@link AvailableRfqSwapManagerCallbacks}. */
1431
- setCallbacks(callbacks: AvailableRfqSwapManagerCallbacks): void;
1432
- onSwapUpdate(listener: SwapUpdateListener): () => void;
1433
- onSwapCompleted(listener: SwapCompletedListener): () => void;
1434
- onSwapFailed(listener: SwapFailedListener): () => void;
1435
- onActionExecuted(listener: ActionExecutedListener): () => void;
1436
- /**
1437
- * Rebuild every stored swap and take over monitoring them.
1438
- *
1439
- * The composition a consumer otherwise writes by hand, and the one place
1440
- * all four pieces meet: retention decides what to keep
1441
- * (`shouldRetainRfqSwap`), the lockup's contract row supplies the covenant
1442
- * (`lockupContractParams`), `rebuildRfqSwap` turns a record back into a
1443
- * live swap, and each rebuilt swap arrives with its own origin, so nothing
1444
- * is asked of the caller.
1445
- *
1446
- * **Deliberately not part of {@link start}.** A consumer that wants to
1447
- * look at its records — count them, show them, prune and stop — is not
1448
- * forced to start driving money to do it. Call this first and `start()`
1449
- * after; a manager already running polls the restored swaps at once.
1450
- *
1451
- * Retention runs BEFORE the rebuild, so a record past
1452
- * `RFQ_SWAP_RETENTION_SECONDS` costs no contract lookup on its way to being
1453
- * dropped.
1454
- *
1455
- * **A record that cannot be rebuilt is reported, never swallowed and never
1456
- * fatal.** `rebuildRfqSwap` throws by design when the covenant params do
1457
- * not derive the funded address, and `lockupContractParams` throws
1458
- * `LockupContractMissing` when the wallet has no row for the lockup — both
1459
- * say something true about that one record, and neither is a reason to
1460
- * strand the others. They come back in {@link RfqRestoreResult.failed}.
1461
- */
1462
- restoreFromRepository(options?: RfqRestoreOptions): Promise<RfqRestoreResult>;
1463
- /**
1464
- * Drop stored records that are terminal and past
1465
- * `RFQ_SWAP_RETENTION_SECONDS`, and return their ids.
1466
- *
1467
- * `needs_counterparty` is never dropped, however old: the money is still at
1468
- * the lockup and the counterparty's move still ends the swap. That rule
1469
- * lives in `shouldRetainRfqSwap`, which this defers to rather than
1470
- * restating.
1471
- *
1472
- * Public because retention is a caller's cadence, not the manager's: a
1473
- * long-lived process wants it on a timer of its own, a mobile app wants it
1474
- * at boot. {@link restoreFromRepository} runs it first, so the boot path
1475
- * needs no separate call.
1476
- */
1477
- pruneRetiredSwaps(): Promise<string[]>;
1478
- private dropRetired;
1479
- private requireRepository;
1480
- /** The default covenant source: the wallet's own contract row for each
1481
- * lockup, which is where registration put it before the address could be
1482
- * funded. */
1483
- private paramsFromContracts;
1484
- /**
1485
- * Load records and begin monitoring. Runs one pass immediately — a caller
1486
- * resuming after a restart may be well past a deadline already — then
1487
- * every `pollIntervalMs`. Records that are already terminal are kept only
1488
- * so {@link waitForSwapCompletion} can answer for them.
1489
- *
1490
- * Calling it again while running loads the records and returns rather than
1491
- * re-arming — dropping them silently would strand a funded swap on a
1492
- * caller's harmless double-start.
1493
- *
1494
- * The signature is unchanged with a {@link RfqSwapManagerDeps.repository}
1495
- * wired; the origins are resolved from the store instead, by the same rule
1496
- * {@link addSwap} applies. A swap the store has never seen throws
1497
- * {@link RfqSwapOriginRequired} — hand that one to `addSwap` with its
1498
- * origin, or restore the whole set with {@link restoreFromRepository},
1499
- * which needs no caller input at all. Every swap is checked before any is
1500
- * tracked, so a bad one in the list does not leave a half-loaded manager.
1501
- */
1502
- start(swaps?: readonly RfqSwap[]): Promise<void>;
1503
- /**
1504
- * Stop monitoring and clear the timer. In-flight actions are not
1505
- * cancellable and run to completion; outstanding
1506
- * {@link waitForSwapCompletion} promises are left pending, since
1507
- * stop/start is a pause rather than a cancellation.
1508
- *
1509
- * The contract subscription is dropped too — an open stream with nothing
1510
- * reacting to it is a leak, and {@link start} puts it back. What is NOT
1511
- * undone is the contract registration: those rows are the wallet's, they
1512
- * outlive this manager's lifecycle, and dropping them would unwatch a
1513
- * lockup that is still funded.
1514
- */
1515
- stop(): Promise<void>;
1516
- /**
1517
- * Begin monitoring a swap. Polled immediately when the manager is running,
1518
- * so a just-funded swap does not wait out a whole interval.
1519
- *
1520
- * `origin` is the request-time half a live swap cannot carry — the corridor,
1521
- * the funded address, the corridor's profile, the funding txid — and it is
1522
- * what lets the manager write this swap's FIRST record. Supply it whenever
1523
- * a {@link RfqSwapManagerDeps.repository} is wired and the swap is new. It
1524
- * may be omitted for a swap the store already holds a record for, which is
1525
- * then read to confirm it; omitting it for one the store has never seen
1526
- * throws {@link RfqSwapOriginRequired} rather than admitting a swap whose
1527
- * record could never be written. With no repository wired the parameter is
1528
- * inert.
1529
- */
1530
- addSwap(swap: RfqSwap, origin?: RfqSwapOrigin): Promise<void>;
1531
- /**
1532
- * Settle where this swap's record will come from, before it is monitored.
1533
- *
1534
- * Three ways it can be answered, in order: the caller passed an origin, one
1535
- * is already remembered from an earlier `addSwap`, or the store holds a
1536
- * record — which is the origin, already written. Only the last costs a read,
1537
- * and only when the first two are absent.
1538
- */
1539
- private admit;
1540
- /** Forget a swap entirely, monitored or finished.
1541
- *
1542
- * Its contract row is left alone: registration is a wallet-level fact about
1543
- * a script that may still hold money, and this call says only that THIS
1544
- * manager stops driving the swap. Retiring the row is reserved for a swap
1545
- * that reached a terminal state, where the lockup is provably done. */
1546
- removeSwap(rfqId: string): Promise<void>;
1547
- /** Every swap still being monitored. */
1548
- getPendingSwaps(): Promise<RfqSwap[]>;
1549
- /**
1550
- * Every swap this manager holds — {@link getPendingSwaps} plus the ones
1551
- * that already ended. The two sets are disjoint: a swap leaves `monitored`
1552
- * as it enters `finished`.
1553
- *
1554
- * The finished half is what this process has seen, which after
1555
- * {@link restoreFromRepository} is the stored history minus what retention
1556
- * pruned. A manager that has restored nothing answers with the live swaps
1557
- * alone.
1558
- */
1559
- getAllSwaps(): Promise<RfqSwap[]>;
1560
- hasSwap(rfqId: string): Promise<boolean>;
1561
- /** True while an action for this swap holds the per-swap lock. */
1562
- isProcessing(rfqId: string): Promise<boolean>;
1563
- getStats(): Promise<{
1564
- isRunning: boolean;
1565
- monitoredSwaps: number;
1566
- finishedSwaps: number;
1567
- inProgress: number;
1568
- pollIntervalMs: number;
1569
- }>;
1570
- /**
1571
- * Run one monitoring pass over every swap now.
1572
- *
1573
- * {@link start} calls this on an interval, but it is public on purpose: a
1574
- * caller that sleeps its process (a mobile app resuming, a service worker
1575
- * waking) wants a pass on that event rather than at the next tick. Passes
1576
- * do not overlap per swap — the in-progress lock makes a concurrent call a
1577
- * no-op for any swap already being worked on.
1578
- */
1579
- poll(): Promise<void>;
1580
- /**
1581
- * Resolve once this swap's PAYOUT is decided — which for onchain-send is
1582
- * the L1 claim, not the end of the record's life: once `claimTxid` is set
1583
- * the trader has the coins it swapped for, and what remains is the manager
1584
- * watching the Arkade lockup close. That holds however the record is
1585
- * labelled afterwards, `needs_counterparty` included. Lightning-send has no
1586
- * such split and resolves at `settled`/`refunded`, and so does lightning
1587
- * receive — see {@link isPayoutDecided} for why its own claim txid does not
1588
- * decide it.
1589
- *
1590
- * Rejects only on `failed`. `refunded` resolves: on a send leg a refund is
1591
- * an outcome the caller asked this manager to drive, not an exception. On a
1592
- * receive leg it is the swap being lost, which is still an answer and not
1593
- * an error — read `state`, do not infer success from resolution.
1594
- */
1595
- waitForSwapCompletion(rfqId: string): Promise<RfqSwapOutcome>;
1596
- private track;
1597
- /** Drops the swap from BOTH indexes. The event index is the one that stops
1598
- * a late event finding a swap that is gone; `pollSwap`'s own
1599
- * `monitored` check would also catch it, and deliberately still does —
1600
- * either alone is sufficient, which is what keeps a future change to one of
1601
- * them from silently re-driving a cancelled swap. */
1602
- private untrack;
1603
- /**
1604
- * Turn the indexer's push into an extra reason to run a pass — and nothing
1605
- * more.
1606
- *
1607
- * **This is deliberately not a source of truth.** An event names a script;
1608
- * the reaction is to run the ordinary pass for the swap at that script, and
1609
- * that pass re-reads the lockup through {@link readLockupFate} exactly as
1610
- * the timer's pass does. So an event that is missed, duplicated, reordered
1611
- * or outright FORGED can only cost or save latency — it can never change
1612
- * what this manager believes about a swap, and it can never on its own
1613
- * cause a claim or a refund. That property is what makes it safe to bolt a
1614
- * best-effort stream onto a money path, and it must survive any future
1615
- * change here: the moment an event is BELIEVED rather than merely acted on,
1616
- * a relay outage becomes a correctness problem instead of a latency one.
1617
- *
1618
- * The timer stays armed regardless, and is the failsafe. Every deadline
1619
- * that moves money — `refundLocktime`, the L1 claim window — is an absolute
1620
- * timelock that passes whether or not a single event ever arrives.
1621
- */
1622
- private subscribe;
1623
- /**
1624
- * Register this swap's lockup with the wallet's contract manager, once.
1625
- *
1626
- * The backstop, not the primary site: `requestLightningSend` /
1627
- * `requestOnchainSend` register before the caller can fund, so this covers
1628
- * swaps whose records predate that — and costs nothing when it does not,
1629
- * since `createContract` is first-writer-wins.
1630
- *
1631
- * Best-effort by design: a failure here is reported and retried on the next
1632
- * pass, and never aborts the pass it is part of. Registration buys latency
1633
- * and puts the lockup in the wallet's contract set; it decides nothing. The
1634
- * money path below it reads the indexer directly and is gated on timelocks
1635
- * that a missing contract row has no bearing on, so failing the pass over
1636
- * this would trade a real deadline for a bookkeeping one.
1637
- */
1638
- private ensureRegistered;
1639
- /** Stop watching a finished swap's lockup. Retained, not deleted: the row
1640
- * is what keeps the lockup's own VTXOs annotatable and its history
1641
- * readable, while `retained` is what drops it from the subscription and
1642
- * the poll — a settled swap that stayed watched would cost the wallet a
1643
- * script for its whole life. Best-effort — the swap is over either way. */
1644
- private retireContract;
1645
- private arm;
1646
- private pollSwap;
1647
- private runPass;
1648
- /**
1649
- * The lockup was unilaterally exited: its outputs sit onchain under the
1650
- * VHTLC script, where no offchain claim or refund can reach them.
1651
- *
1652
- * `needs_counterparty` rather than a terminal state, because the money still
1653
- * needs action and the swap can still end either way — an onchain claim can
1654
- * reveal the preimage, an onchain refund can return it — and that state is
1655
- * documented as re-checked every pass. It must be set from HERE and not from
1656
- * inside `driveArkadeRefund`, whose two `unblock` calls would lift it again
1657
- * on the very next pass.
1658
- */
1659
- private blockExitedLockup;
1660
- /**
1661
- * The receive leg's whole state machine: claim the solver-funded lockup
1662
- * while the window is open, and recognise the shapes in which it can be
1663
- * lost.
1664
- *
1665
- * **The window closes at `refundLocktime`, on wall clock, with no margin.**
1666
- * Both halves of that are deliberate. It closes there because publishing
1667
- * `P` into the solver's live refund window risks losing the race and
1668
- * handing over the preimage anyway — the hazard `ONCHAIN_CLAIM_MARGIN_SECONDS`
1669
- * guards on the L1 side. It takes no margin because the two situations are
1670
- * not alike: that one budgets for confirmation depth, while this claim is an
1671
- * offchain spend that lands in seconds. Wall clock is already the
1672
- * conservative reading — the solver's leaf is a CLTV, which matures against
1673
- * median-time-past, and MTP trails wall clock — so the real window extends
1674
- * PAST this deadline rather than ending before it. Every second of margin
1675
- * subtracted here is a second of live claim window given away for nothing.
1676
- *
1677
- * **The trader has no move after it.** Nothing here can take the lockup
1678
- * back, so once the window shuts the swap is the solver's to resolve and
1679
- * this manager's job is to watch it happen and then stop.
1680
- */
1681
- private driveReceiveClaim;
1682
- /**
1683
- * Claim what the solver funded, once it is enough.
1684
- *
1685
- * The value gate here decides WHEN to act. `pushClaim`'s decides whether
1686
- * `P` is published, and runs with nothing between it and the signature —
1687
- * the check that matters is the inner one, and this is not a reason to
1688
- * relax it.
1689
- */
1690
- private claimIfFunded;
1691
- /** `handled` ends the pass; `continue` falls through to the refund gate. */
1692
- private driveOnchain;
1693
- private driveArkadeRefund;
1694
- /** Whether any of these outputs has never been handed to the claim
1695
- * callback — the only reason to claim a lockup a second time. */
1696
- private hasUnclaimedOutpoint;
1697
- private rememberClaimed;
1698
- /**
1699
- * L1 progress, which past the refund window must not overwrite a refusal.
1700
- * The two halves are independent — a claimed fill says nothing about
1701
- * whether this wallet can take the Arkade lockup back — and `claimed` is
1702
- * re-asserted from chain on every pass, so without this a blocked swap
1703
- * would flip between the two states forever. The claim itself always runs;
1704
- * only the label defers, and only once the refund is the live half.
1705
- */
1706
- private setOnchainState;
1707
- /** The probe's refusal reason, or `undefined` when a local refund is
1708
- * possible as far as anyone here can tell. A probe that throws is treated
1709
- * as a refusal: a capability check that cannot answer is not a yes. */
1710
- private probeRefusal;
1711
- /** Report that no local refund will happen, without ending the swap. */
1712
- private block;
1713
- /** The way back out, taken as soon as the swap becomes actionable again.
1714
- * Back to what the record can prove, not to `pending` unconditionally: a
1715
- * swap that already made its claim has a txid for it, and reporting that
1716
- * swap as `pending` would un-say something true. */
1717
- private unblock;
1718
- /**
1719
- * Record which ark transactions ended the lockup.
1720
- *
1721
- * Only the ones the indexer actually named: `LockupSpend.txid` is
1722
- * optional, and a checkpoint txid is not what history correlates on — a
1723
- * record carrying one would name a transaction the wallet's own activity
1724
- * never shows. Fewer txids is the right failure here.
1725
- *
1726
- * Assigned rather than merged: the fate is one read of the whole lockup,
1727
- * so it is the complete answer for this swap, and a swap only reaches a
1728
- * verdict once.
1729
- */
1730
- private stampLockupSpends;
1731
- private touch;
1732
- private setState;
1733
- /** Terminal failure. The `onSwapFailed` emission is left to
1734
- * {@link finalize}, so this does not double-report. */
1735
- private fail;
1736
- private emitFailed;
1737
- private emitAction;
1738
- /**
1739
- * Flush a changed record to every sink that is wired, and say whether all
1740
- * of them took it.
1741
- *
1742
- * Up to two writes, in this order: the canonical `RfqSwapRecord` to
1743
- * {@link RfqSwapManagerDeps.repository}, then
1744
- * {@link RfqSwapManagerCallbacks.saveSwap}. Both gate — a rejection from
1745
- * either leaves the record dirty and monitored, so waiters stay unsettled
1746
- * and a terminal swap is not finalized until the write it claims lands.
1747
- * That is exactly today's rule for `saveSwap`, applied to whichever sinks
1748
- * exist; wiring the repository does not weaken it.
1749
- *
1750
- * The canonical write goes FIRST and a failure there skips the second.
1751
- * `saveSwap` is a projection of the record, and projecting a state the
1752
- * record of record has just refused would leave the secondary sink ahead
1753
- * of the primary — the one ordering that survives no restart.
1754
- *
1755
- * With neither wired the state is process-local, which is what a manager
1756
- * with no callbacks has always done.
1757
- */
1758
- private save;
1759
- /** The canonical write. True when there is no repository to write to. */
1760
- private saveRecord;
1761
- private originOrThrow;
1762
- /**
1763
- * Drop a terminal swap from monitoring and report it exactly once.
1764
- *
1765
- * `onSwapCompleted` and `onSwapFailed` are mutually exclusive here: a
1766
- * listener named "completed" that also fires on failure is a trap, so a
1767
- * swap that leaves monitoring reports through exactly one of them.
1768
- */
1769
- private finalize;
1770
- private settleWaiters;
1771
- }
1772
- /** What {@link RfqSwapManager.waitForSwapCompletion} reports. `txid` is the
1773
- * trader's own claim — L1 for a claimed onchain send, Arkade for a claimed
1774
- * receive — or the ark txid for a refund the trader pushed; a solver-side
1775
- * settlement or refund carries none, and a receive swap that ended `refunded`
1776
- * carries none either, however far its claim got (see {@link outcomeOf}). So
1777
- * a `txid` here always names something that happened, and `state` remains the
1778
- * only thing to read for whether the swap paid out.
1779
- *
1780
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1781
- */
1782
- interface RfqSwapOutcome {
1783
- state: RfqSwapState;
1784
- txid?: string;
1785
- }
1786
-
1787
- /**
1788
- * The swap kinds this projection covers — all three the manager monitors.
1789
- *
1790
- * `onchain_send` carries an L1 half nothing else can rebuild. Its Arkade lockup
1791
- * has a contract row like the others, but the HTLC is Bitcoin L1, not an Arkade
1792
- * contract, so no row exists for it; and `OnchainHtlc` exposes only derived
1793
- * values — `address`, `pkScript`, `leaves`, `controlBlocks` — never the
1794
- * `claimKey`/`refundKey` `onchainHtlcScript` takes as inputs. So they ride in
1795
- * that corridor's {@link RfqSwapOrigin.profile}, and without them a restored
1796
- * swap would let its L1 refund window pass unwatched.
1797
- *
1798
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1799
- */
1800
- type PersistableRfqSwap = LightningSendSwap | LightningReceiveSwap | OnchainSendSwap;
1801
- /**
1802
- * The serialized covenant parameters a rebuild is given.
1803
- *
1804
- * `VHTLCV2ContractHandler`'s own wire shape — what `serializeParams` writes and
1805
- * `createScript` reads — which is exactly what a lockup's contract row stores
1806
- * under `params`.
1807
- *
1808
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1809
- */
1810
- type LockupParams = Record<string, string>;
1811
- /**
1812
- * How long a retired swap's record is kept, in SECONDS.
1813
- *
1814
- * Terminal records are history, not garbage: the covenant's spender is a
1815
- * transaction the wallet never signed, so its own history cannot reconstruct
1816
- * them. Kept for a month, then dropped so a hot wallet's store stays bounded.
1817
- *
1818
- * Seconds, not milliseconds, because that is the unit `RfqSwap.updatedAt`
1819
- * carries; the manager stamps it from `RfqSwapManagerConfig.now`, which is
1820
- * "wall clock, in unix seconds". Comparing it against `Date.now()` would drop
1821
- * every terminal record after ~43 minutes.
1822
- *
1823
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1824
- */
1825
- declare const RFQ_SWAP_RETENTION_SECONDS: number;
1826
- /** The immutable request-time half, and only what EVERY corridor has. Hex for
1827
- * everything binary, so the record is plain JSON and survives any
1828
- * structured-clone backend unchanged.
1829
- *
1830
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1831
- */
1832
- interface RfqSwapOrigin {
1833
- /**
1834
- * Which corridor this is. Resolves the handler that owns {@link profile};
1835
- * see `rfqCorridor.ts`.
1836
- *
1837
- * The manager's own union, not an open string: `RfqSwapManager` branches on
1838
- * `kind` to decide what to drive, so a corridor it does not know could be
1839
- * persisted and rebuilt here and then never driven — which is the failure
1840
- * this whole file is arranged to make impossible.
1841
- */
1842
- kind: PersistableRfqSwap["kind"];
1843
- /**
1844
- * The Arkade address that was funded.
1845
- *
1846
- * Both the swap's handle on its covenant — {@link lockupContractParams}
1847
- * looks the contract row up by the script it decodes to — and, being taken
1848
- * from the entry point rather than re-derived, the check that the
1849
- * parameters a caller supplies belong to THIS swap.
1850
- */
1851
- lockupAddress: string;
1852
- /**
1853
- * The corridor's own half, as plain JSON — written by the caller from the
1854
- * request result, kept current by the handler's `project`.
1855
- *
1856
- * Opaque here on purpose. Nothing in this file, the repository or the
1857
- * IndexedDB store interprets it, which is what lets a new corridor ship
1858
- * without touching any of them. It carries the corridor's keys as well as
1859
- * its state: `signer` (which wallet key signs this leg) and, on a corridor
1860
- * locked to a preimage, `hashlock` — see `rfqProfileParts.ts`, and write
1861
- * both with `rfqSecretsProfile` rather than by hand.
1862
- *
1863
- * Not a consumer scratchpad: every write merges it as `{ ...profile,
1864
- * ...handler.project(swap) }`, so a consumer key colliding with one the
1865
- * handler projects is silently overwritten on every pass.
1866
- */
1867
- profile: Record<string, unknown>;
1868
- /** Consumer display metadata. The rebuild ignores it — `RfqSwapCommon`
1869
- * carries no amount of its own. */
1870
- amount?: number;
1871
- /**
1872
- * The ark transaction that funded {@link lockupAddress}.
1873
- *
1874
- * Origin, not manager state: the caller broadcasts the funding and knows
1875
- * its txid, while the manager watches the lockup by script and never
1876
- * learns it. So it is written once at record creation, like {@link amount},
1877
- * and no corridor `project` emits it.
1878
- */
1879
- fundingTxid?: string;
1880
- }
1881
- /** The stored record: the origin plus the manager's mutable state.
1882
- *
1883
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1884
- */
1885
- interface RfqSwapRecord extends RfqSwapOrigin {
1886
- rfqId: string;
1887
- state: RfqSwapState;
1888
- createdAt: number;
1889
- updatedAt: number;
1890
- refundTxid?: string;
1891
- /** The ark transactions that spent the lockup, stamped by the manager from
1892
- * the chain read that ended the swap. See
1893
- * `RfqSwapCommon.lockupSpendTxids`. */
1894
- lockupSpendTxids?: string[];
1895
- failure?: string;
1896
- /** Last local receive-claim error while the swap is still retryable. */
1897
- claimFailure?: string;
1898
- blockedReason?: string;
1899
- }
1900
- /**
1901
- * A stored record read under the current field names.
1902
- *
1903
- * Four fields were renamed after `0.0.9`: `fundingArkTxid`, `refundArkTxid`,
1904
- * `lockupSpendArkTxids`, and the receive corridor's `profile.claimArkTxid`. All
1905
- * four arrived together with record persistence itself in `0.0.8`, so `0.0.8`
1906
- * and `0.0.9` are the only versions that ever wrote them. Backends store the
1907
- * record WHOLE, so such a store still holds the old names on disk and the
1908
- * current code reads every one of them as `undefined`.
1909
- *
1910
- * Called by every function here that takes a record, so a consumer needs no
1911
- * boot-time migration of its own; and because the old keys never reach the
1912
- * object handed back, the next write persists the record without them.
1913
- *
1914
- * What it buys, in descending order of sharpness: a receive leg with a partial
1915
- * claim already out keeps its `claimTxid`, so the value gate stays disarmed
1916
- * rather than re-blocking the rest of a lockup whose preimage is public;
1917
- * `refunded` swaps report an outcome txid again; and activity answers from the
1918
- * record instead of falling back to a lockup read per query. It is NOT a
1919
- * re-refund fix — `refunded` is terminal, and `restoreFromRepository` puts a
1920
- * terminal record straight into `finished` without ever driving it.
1921
- *
1922
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1923
- */
1924
- declare function normalizeRfqSwapRecord(record: RfqSwapRecord): RfqSwapRecord;
1925
- /** First write, at the moment the caller hands the swap to the manager.
1926
- *
1927
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1928
- */
1929
- declare function createRfqSwapRecord(origin: RfqSwapOrigin, swap: PersistableRfqSwap): RfqSwapRecord;
1930
- /**
1931
- * Every later write. The origin half is carried through untouched.
1932
- *
1933
- * The mutable half is REPLACED, not merged. `managerState` omits a key the live
1934
- * swap no longer carries, so spreading it over the old record could only ever
1935
- * set these fields, never clear them. The manager clears them on purpose: it
1936
- * deletes `blockedReason` when a swap leaves `needs_counterparty` and
1937
- * `claimFailure` when a swap becomes terminal, precisely because stale mutable
1938
- * reasons read as live refusal or retry state.
1939
- *
1940
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1941
- */
1942
- declare function updateRfqSwapRecord(record: RfqSwapRecord, swap: PersistableRfqSwap): RfqSwapRecord;
1943
- /**
1944
- * The immutable half of a stored record, on its own.
1945
- *
1946
- * A record IS an origin plus manager state, so `record` where an
1947
- * {@link RfqSwapOrigin} is wanted type-checks — and is a bug. Spread into
1948
- * {@link createRfqSwapRecord} it carries the OLD state's `failure`,
1949
- * `blockedReason`, `claimFailure` and `refundTxid` past `managerState`, which omits
1950
- * fields the live swap no longer has and therefore cannot clear them. That is the same
1951
- * trap {@link updateRfqSwapRecord} strips those mutable fields to avoid; this is
1952
- * how a caller holding only a record gets an origin that is safe to keep.
1953
- *
1954
- * What `RfqSwapManager.restoreFromRepository` remembers for each record it
1955
- * rebuilds, so a later write can create the record again if the store lost it.
1956
- *
1957
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1958
- */
1959
- declare function rfqSwapOriginOf(record: RfqSwapRecord): RfqSwapOrigin;
1960
- /**
1961
- * Rebuild the live record. Pure, and synchronous, given the covenant's
1962
- * parameters.
1963
- *
1964
- * Hand the result to {@link RfqSwapManager.start}. Take `params` from the
1965
- * lockup's contract row — {@link lockupContractParams} is the one-liner — or
1966
- * from a copy of `VHTLCV2ContractHandler.serializeParams(script.options)` a
1967
- * consumer keeps itself; either way they are checked against the address that
1968
- * was actually funded, so the `lockupPkScript` this produces is the one the
1969
- * funded lockup is keyed by.
1970
- *
1971
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1972
- */
1973
- declare function rebuildRfqSwap(record: RfqSwapRecord, params: LockupParams): PersistableRfqSwap;
1974
- /**
1975
- * Whether a retired swap's record should be kept.
1976
- *
1977
- * `needs_counterparty` is deliberately not terminal and is never dropped: the
1978
- * money is still at the lockup, the counterparty's move is still what ends the
1979
- * swap, and the refusal is re-checked every pass; restoring the right wallet
1980
- * returns it to `pending`.
1981
- *
1982
- * @param now Current time in **unix seconds**; the same unit as
1983
- * `RfqSwap.updatedAt`, which the manager stamps from
1984
- * `RfqSwapManagerConfig.now`. Pass `Math.floor(Date.now() / 1000)`, never
1985
- * `Date.now()`: milliseconds against a seconds window would retire every
1986
- * terminal record after ~43 minutes.
1987
- *
1988
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
1989
- */
1990
- declare function shouldRetainRfqSwap(record: RfqSwapRecord, now: number): boolean;
1991
-
1992
- /**
1993
- * What the codec needs from an asset, and nothing else. Structural, so
1994
- * discovery's `AssetInfo` satisfies it directly and this module reaches for no
1995
- * network layer. There is no id-to-decimals lookup at M1: that needs the
1996
- * registry M3 builds, and M3 adds an id-taking convenience on top of this rather
1997
- * than replacing it.
1998
- */
1999
- interface AssetScale {
2000
- decimals: number;
2001
- }
2002
- declare const ATOMIC_DECIMAL: unique symbol;
2003
- /** Atomic units written out: the form records and the wire hold. */
2004
- type AtomicDecimal = string & {
2005
- readonly [ATOMIC_DECIMAL]: true;
2006
- };
2007
- /** A string that is provably not an {@link AtomicDecimal}; plain strings qualify. */
2008
- type DisplayDecimal = string & {
2009
- readonly [ATOMIC_DECIMAL]?: never;
2010
- };
2011
- /** Why an amount was refused. */
2012
- type AmountRefusal = "not_decimal" | "negative" | "too_precise" | "too_large" | "invalid_decimals" | "not_canonical";
2013
- /**
2014
- * An amount that cannot be represented in the form asked for.
2015
- *
2016
- * Not a member of the §7 `SwapError` taxonomy: that taxonomy is the client
2017
- * surface's, thrown by a verb before value moves, and this is a codec refusing
2018
- * its input before a swap exists. The wire's compatibility failure is different
2019
- * and does have a member — `AmountEncodingUnsupported`, in `rfqAmount.ts`.
2020
- */
2021
- declare class AmountFormatError extends Error {
2022
- readonly reason: AmountRefusal;
2023
- readonly name = "AmountFormatError";
2024
- constructor(reason: AmountRefusal, message: string);
2025
- }
2026
- declare const Amount: {
2027
- /**
2028
- * A human decimal into atomic units.
2029
- *
2030
- * `string` only, and no exponent. Accepting a `number` is the whole v1
2031
- * footgun: it makes `100000` ambiguous between sats and whole BTC, and by
2032
- * the time the ambiguity resolves the offer is funded. Exponent form goes
2033
- * for the same reason — a UI never produces `1e-4`, so accepting it only
2034
- * widens what a mistake can look like.
2035
- *
2036
- * Refuses rather than rounds when the input is finer than the asset: a
2037
- * silently truncated amount is a swap for the wrong size, and nothing
2038
- * downstream can tell it was ever a different number. Refuses too when the
2039
- * result would not survive the record boundary, so one law holds in both
2040
- * directions.
2041
- */
2042
- parse(display: DisplayDecimal, asset: AssetScale): bigint;
2043
- /**
2044
- * Atomic units into a human decimal, trailing zeros trimmed.
2045
- *
2046
- * Refuses a negative: every amount on this surface is an obligation, and a
2047
- * negative one is a defect upstream rather than a number to render.
2048
- */
2049
- format(value: bigint, asset: AssetScale): string;
2050
- };
2051
- /**
2052
- * Atomic units into the canonical decimal string records and the wire hold:
2053
- * discovery's `AMOUNT_PATTERN` — unsigned, no leading zeros, at most 30 digits.
2054
- */
2055
- declare const toAtomicDecimal: (value: bigint) => AtomicDecimal;
2056
- /**
2057
- * The canonical decimal string back into atomic units.
2058
- *
2059
- * Takes a plain `string` on purpose: it is what a record read and a `JSON.parse`
2060
- * hand back, and demanding a cast would put one on the safe direction.
2061
- */
2062
- declare const fromAtomicDecimal: (text: string) => bigint;
2063
- /** Whether `value` is already in the canonical atomic form. */
2064
- declare const isAtomicDecimal: (value: unknown) => value is AtomicDecimal;
2065
-
2066
- /**
2067
- * Asset identity for the v2 client: CAIP-19 with the rail as the CAIP-2
2068
- * namespace — `<rail>:<network>/<asset-ns>:<reference>`.
2069
- *
2070
- * The rail is the namespace rather than the settlement chain because sameness
2071
- * across rails is then a comparison on the asset part instead of a shared
2072
- * string: `arkade:bitcoin/slip44:0` and `bitcoin:bitcoin/slip44:0` are one BTC
2073
- * on two rails, and nothing has to agree on a single id for them. Arkade has no
2074
- * CAIP-2 namespace and no bitcoin-chain identity to nest under, so
2075
- * `bip122:…/arkade:…` would assert a relationship it does not have.
2076
- *
2077
- * These ids parse under CAIP-19 and resolve under no published namespace spec:
2078
- * `arkade`, `bitcoin` and `bolt11` are registered in no CASA registry. That is
2079
- * the price of naming rails instead of chains, and it costs nothing here — this
2080
- * module is the grammar, and what an id *means* is the alias layer's job.
2081
- */
2082
-
2083
- /**
2084
- * A CAIP-2 namespace this client can spell. Closed rather than open to the
2085
- * CAIP-2 character class, so a rail nobody implements is a parse failure here
2086
- * rather than a lookup miss three layers down.
2087
- *
2088
- * `bolt11` is lightning: CAIP-2 caps a namespace at eight characters, which
2089
- * `lightning` overruns, and floors it at three, which `ln` misses. It names the
2090
- * instrument the rail carries today; BOLT12 is a separate corridor when it
2091
- * ships.
2092
- *
2093
- * `eip155` is grammar and nothing else. §9's EVM corridor is deferred, and §9
2094
- * exists to prove the seams hold, so its own examples have to parse; the
2095
- * refusal belongs where a route is chosen, not where a string is read, and the
2096
- * alias layer is where it happens.
2097
- */
2098
- declare const RAILS: readonly ["arkade", "bitcoin", "bolt11", "eip155"];
2099
- type Rail = (typeof RAILS)[number];
2100
- /** The rails whose CAIP-2 reference is a bitcoin network rather than a chain id. */
2101
- declare const BITCOIN_RAILS: readonly ["arkade", "bitcoin", "bolt11"];
2102
- type BitcoinRail = (typeof BITCOIN_RAILS)[number];
2103
- /**
2104
- * The network half of a bitcoin-family chain part: core's own
2105
- * {@link NetworkName}, because the wallet is the only source of the network —
2106
- * v2 accepts no server URL anywhere — and this is the vocabulary a wallet
2107
- * resolves to.
2108
- *
2109
- * It is one wider than discovery's `NETWORKS`, which omits `testnet`. That
2110
- * difference belongs to the alias layer and not to the grammar: an asset on
2111
- * testnet exists whether or not anyone publishes a market index for it, so
2112
- * amputating the identity to match the index would make a network the SDK fully
2113
- * supports unnameable.
2114
- */
2115
- type NetworkRef = NetworkName;
2116
- type BitcoinAssetId<R extends BitcoinRail> = `${R}:${NetworkRef}/${string}:${string}`;
2117
- /**
2118
- * A public asset id.
2119
- *
2120
- * A template literal type and not `string`, which is what makes the other three
2121
- * asset spellings in this package — core's 68-hex `asset.AssetId#toString()`,
2122
- * discovery's `AssetInfo.id`, the RFQ leg's `arkade:BTC` — a compile error in a
2123
- * slot that wants a public id, rather than a wrong pair string three layers
2124
- * down. The rail parameter carries that further: `AssetId<"arkade">` accepts no
2125
- * `bitcoin:` string, which is what makes an endpoint whose corridor and asset
2126
- * disagree a compile error (see `route.ts`).
2127
- *
2128
- * Deliberately not branded — `client.quote({ give: "arkade:bitcoin/slip44:0" })`
2129
- * must stay writable, and the spec's own examples are written that way — so the
2130
- * shape is what the type checks and {@link parseAssetId} is the gate for
2131
- * everything else. A value out of a record or off the wire is a `string`: parse
2132
- * it, never cast it.
2133
- */
2134
- type AssetId<R extends Rail = Rail> = R extends BitcoinRail ? BitcoinAssetId<R> : `eip155:${number}/${string}:${string}`;
2135
- /** The `<asset-ns>:<reference>` half of an id — what sameness compares. */
2136
- type AssetPart = `${string}:${string}`;
2137
- /** BTC's asset part on every rail that carries it (SLIP-44 coin type 0). */
2138
- declare const BTC_ASSET_PART = "slip44:0";
2139
- /** The asset namespace an Arkade-issued asset takes. */
2140
- declare const ARKADE_ASSET_NAMESPACE = "asset";
2141
- interface ParsedAssetId {
2142
- /** CAIP-2 namespace. */
2143
- readonly rail: Rail;
2144
- /**
2145
- * CAIP-2 reference: the bitcoin network on a bitcoin-family rail, the
2146
- * decimal chain id on `eip155`.
2147
- */
2148
- readonly reference: string;
2149
- /** CAIP-19 asset namespace — `slip44`, `asset`, `erc20`. */
2150
- readonly assetNamespace: AssetNamespace;
2151
- /** CAIP-19 asset reference. */
2152
- readonly assetReference: string;
2153
- }
2154
- /** Why an id was refused. Stable strings; callers switch on them. */
2155
- type AssetIdRefusal = "malformed" | "uppercase" | "unknown_rail" | "unknown_network" | "invalid_chain_id" | "unknown_asset_namespace" | "invalid_asset_reference" | "token_id_unsupported" | "unknown_alias" | "ambiguous_alias";
2156
- /**
2157
- * A string that is not a public asset id.
2158
- *
2159
- * Not a member of the §7 `SwapError` taxonomy, and deliberately so: that
2160
- * taxonomy is the client surface's, thrown by a verb before value moves, and
2161
- * this is a codec refusing its input before a swap exists at all. Core's own
2162
- * `AssetId.fromBytes` sets the same precedent.
2163
- */
2164
- declare class AssetIdError extends Error {
2165
- readonly reason: AssetIdRefusal;
2166
- readonly value: string;
2167
- constructor(reason: AssetIdRefusal, value: string, detail: string, options?: ErrorOptions);
2168
- }
2169
- /**
2170
- * The asset namespaces this client spells, and the reference form each takes.
2171
- *
2172
- * Closed for the same reason the rail set is: the parser *is* the vocabulary,
2173
- * and an id nothing downstream can map is a lookup miss dressed as an id. The
2174
- * per-namespace form is what makes `arkade:bitcoin/asset:notahex` a parse
2175
- * failure rather than an unserved RFQ pair.
2176
- */
2177
- declare const REFERENCE_RULE: {
2178
- readonly slip44: RegExp;
2179
- /** The 68-lowercase-hex identity form; `asset.AssetId` then re-validates it. */
2180
- readonly asset: RegExp;
2181
- /**
2182
- * Reserved for §9. Lowercase, never EIP-55: a checksum belongs on an
2183
- * address a human types, and an id here comes out of the alias table or a
2184
- * market card. Mixed case would be two spellings of one asset comparing
2185
- * unequal in a pair string, a record and a cache key.
2186
- */
2187
- readonly erc20: RegExp;
2188
- };
2189
- type AssetNamespace = keyof typeof REFERENCE_RULE;
2190
- /** Whether `value` is a network core can resolve. Read off core's own table, so
2191
- * a network added there needs no edit here. */
2192
- declare const isNetworkRef: (value: string) => value is NetworkRef;
2193
- /**
2194
- * Parse an id, or refuse it.
2195
- *
2196
- * Total over strings and throwing rather than returning a result, because every
2197
- * caller in the client either has an id or has nothing to do: an unparsed id
2198
- * has no route, no market and no leg.
2199
- */
2200
- declare const parseAssetId: (value: string) => ParsedAssetId;
2201
- /** Whether `value` parses as a public asset id. */
2202
- declare const isAssetId: (value: string) => value is AssetId;
2203
- /** Build an id from its parts, validating the result. */
2204
- declare const formatAssetId: <R extends Rail>(parts: ParsedAssetId & {
2205
- rail: R;
2206
- }) => AssetId<R>;
2207
- /** The rail an id names. */
2208
- declare const railOf: (id: AssetId) => Rail;
2209
- /**
2210
- * The bitcoin network an id settles on, or `undefined` on a rail whose CAIP-2
2211
- * reference is a chain id rather than a network.
2212
- */
2213
- declare const bitcoinNetworkOf: (id: AssetId) => NetworkRef | undefined;
2214
- /** The `<asset-ns>:<reference>` half. */
2215
- declare const assetPartOf: (id: AssetId) => AssetPart;
2216
- /**
2217
- * Whether two ids name the same asset on (possibly) different rails.
2218
- *
2219
- * This is the whole reason the rail is the namespace: BTC's sameness is the
2220
- * shared `slip44:0`, a comparison, where a single cross-rail id would have made
2221
- * it a string both sides had to already agree on.
2222
- *
2223
- * The rail is the *only* half sameness drops. The CAIP-2 reference still has to
2224
- * agree: `arkade:regtest/slip44:0` and `bitcoin:bitcoin/slip44:0` share a coin
2225
- * type and nothing else — regtest BTC settles nothing on mainnet — and an ERC-20
2226
- * contract address repeats verbatim across every chain that copied the token, so
2227
- * the asset part alone would make USDT-on-mainnet the same asset as its address
2228
- * twin on another chain. Comparing references across rail families is safe on a
2229
- * plain string: a bitcoin network name is never a decimal chain id.
2230
- */
2231
- declare const sameAsset: (a: AssetId, b: AssetId) => boolean;
2232
- /** BTC on a bitcoin-family rail: the same coin, named once per rail. */
2233
- declare const btcOn: <R extends BitcoinRail>(rail: R, network: NetworkRef) => AssetId<R>;
2234
- /**
2235
- * An Arkade-issued asset.
2236
- *
2237
- * Takes `asset.AssetId` rather than a hex string for the reason `arkadeAssetLeg`
2238
- * does (`rfq.ts:111`): `hex.decode` accepts uppercase where `hex.encode` emits
2239
- * only lowercase, so the parameter type is what enforces the case rule, and a
2240
- * value that reached us as `A1B2…` leaves here as `a1b2…`.
2241
- *
2242
- * The reference is that identity verbatim — 68 lowercase hex, `toString()`'s
2243
- * own output. The spec's prose spells it `<genesis_txid>.<idx>`, which is what
2244
- * those bytes mean, not a second encoding: the identity is implemented in seven
2245
- * places across three repos and pinned by `asset.ASSET_ID_VECTORS` precisely
2246
- * because every disagreement between sites fails silently, so this layer adds
2247
- * no eighth spelling.
2248
- */
2249
- declare const arkadeAsset: (network: NetworkRef, id: asset.AssetId) => AssetId<"arkade">;
2250
- /**
2251
- * The issuance identity nested inside an arkade id; `undefined` for BTC.
2252
- *
2253
- * The inverse of {@link arkadeAsset}, and the round trip the shared vectors
2254
- * pin: the 34 bytes in equal the 34 bytes out.
2255
- */
2256
- declare const issuanceOf: (id: AssetId<"arkade">) => asset.AssetId | undefined;
2257
-
2258
- /**
2259
- * The corridor axis, and its bijection with the rail namespaces.
2260
- *
2261
- * One axis, two vocabularies: discovery speaks `arkade | lightning | onchain`
2262
- * and an asset id's CAIP-2 namespace is `arkade | bolt11 | bitcoin`. They agree
2263
- * on one member of three. Collapsing them was the alternative and it loses
2264
- * either way — take the rail names and every market lookup translates on the
2265
- * way out to discovery; take the corridor names and `lightning:` overruns
2266
- * CAIP-2's eight-character namespace cap.
2267
- *
2268
- * So both stay, and the disagreement is spent once, here: `Corridor` is
2269
- * discovery's type verbatim, {@link railOfCorridor} is total, and `route.ts`
2270
- * ties an endpoint's corridor to its asset's rail in the type system so the two
2271
- * cannot disagree in a value.
2272
- */
2273
-
2274
- /**
2275
- * The corridor a leg settles on.
2276
- *
2277
- * Aliased from discovery rather than re-declared: it is discovery's vocabulary,
2278
- * the alias layer has to speak it, and a re-declaration would drift silently
2279
- * the day discovery adds a corridor.
2280
- */
2281
- type Corridor = Corridor$1;
2282
- /** Discovery's corridor list, re-exported so this package does not redeclare it. */
2283
- declare const CORRIDORS: readonly ["arkade", "lightning", "onchain"];
2284
- /**
2285
- * A corridor id: the three implemented corridors plus §9's EVM chains.
2286
- *
2287
- * The template arm stays open against the registry's closed enum on purpose —
2288
- * which chains a registry lists is a listing decision, not an id-grammar one.
2289
- */
2290
- type CorridorId = Corridor | `eip155:${number}`;
2291
- /** The rail namespace a corridor's assets are spelled on. */
2292
- type RailOf<C extends CorridorId> = C extends "arkade" ? "arkade" : C extends "lightning" ? "bolt11" : C extends "onchain" ? "bitcoin" : "eip155";
2293
- /** The rail a corridor's assets are spelled on. Total, and the type agrees. */
2294
- declare const railOfCorridor: <C extends CorridorId>(corridor: C) => RailOf<C>;
2295
- /**
2296
- * The corridor a rail belongs to, or `undefined` for `eip155` — whose corridor
2297
- * id carries a chain reference this side has no way to invent.
2298
- */
2299
- declare const corridorOfRail: (rail: Rail) => Corridor | undefined;
2300
-
2301
- /**
2302
- * The two string aliases the v2 surface is written in.
2303
- *
2304
- * Aliases rather than branded types: they document what a field carries at the
2305
- * places §3.1's `Quote` reads (`lock.hash`, `solver`) without making every
2306
- * literal go through a constructor. Core exports neither, so nothing here is a
2307
- * duplicate.
2308
- */
2309
- /** Lowercase hex, no `0x` prefix — the encoding `@scure/base`'s `hex` emits. */
2310
- type Hex = string;
2311
- /** A secp256k1 public key as {@link Hex}: x-only (32 bytes) or compressed (33). */
2312
- type Pubkey = Hex;
2313
-
2314
- /**
2315
- * One outcome vocabulary, and the translation that produces it.
2316
- *
2317
- * The protocol keeps two state machines — `RfqSwapState` for the corridors and
2318
- * `AssetSwapStatus` for offers — and v1 handed both to every consumer, who then
2319
- * wrote `family === "offer" ? swap.status : swap.state` and decided what each
2320
- * word meant. {@link Outcome} is that decision, made once.
2321
- *
2322
- * **The axis is not send-versus-receive: it is whose lockup the pass reads.**
2323
- * On `arkade -> lightning` and `arkade -> onchain` the arkade lockup is the
2324
- * trader's, so a non-claim spend of it returns the trader's money. On
2325
- * `lightning -> arkade` it is the solver's, so the identical chain read means
2326
- * the trader's incoming payment never arrived. `refunded` and `lapsed` are that
2327
- * one difference, and the reason this enum refuses to inherit the protocol's
2328
- * word: on the receive leg the state the wire calls `refunded` is a LOSS.
2329
- *
2330
- * The ownership is not restated here. {@link LIGHTNING_DRIVE} and
2331
- * {@link ONCHAIN_DRIVE} already declare it per route side — that is what M2
2332
- * minted `CorridorPass` for — so this module reads it off them and a corridor
2333
- * that changes its mind is a compile error rather than a second table to keep
2334
- * in step.
2335
- *
2336
- * Three outcomes come from neither machine, and they are the record's and the
2337
- * clock's: `accepted` and `funding` describe a record the drive holds no live
2338
- * state for, and `refunding` a send leg past its deadline with a push in
2339
- * flight. All three still carry the raw word their machine holds, because
2340
- * {@link SwapUpdate.detail} is `RawState` and `RawState` is the raw word.
2341
- */
2342
-
2343
- /**
2344
- * What happened to a swap, in one vocabulary for both families.
2345
- *
2346
- * Trader-centric by definition. Fourteen members, §3.5's, and the two that
2347
- * carry the whole point are `refunded` — the trader's value came back — and
2348
- * `lapsed`, the solver reclaiming a lockup the trader failed to claim.
2349
- */
2350
- type Outcome =
2351
- /** Persisted, and its funding has not been broadcast. */
2352
- "accepted"
2353
- /** The funding is broadcast and the drive has not adopted the swap yet. */
2354
- | "funding"
2355
- /** The trader's lockup is funded and the swap is live. */
2356
- | "funded"
2357
- /** Waiting on the counterparty: an unpaid invoice, an unfilled offer. */
2358
- | "open"
2359
- /** An offer covenant was filled. */
2360
- | "filled"
2361
- /** The trader's own claim is confirmed on chain. */
2362
- | "claimed"
2363
- /** A lightning send settled: the solver's hash-verified spend IS the
2364
- * invoice being paid. */
2365
- | "paid" | "cancelling" | "cancelled"
2366
- /** A send leg past `refundLocktime` with a refund push in flight. */
2367
- | "refunding"
2368
- /** The trader's value came back. Send legs only, ever. */
2369
- | "refunded"
2370
- /** A receive leg the trader never claimed: the solver took the lockup back
2371
- * and the incoming payment never arrived. */
2372
- | "lapsed"
2373
- /** Surfaced, never silently retried, and never terminal. */
2374
- | "needs_recovery"
2375
- /** An action failed and its window closed. */
2376
- | "failed";
2377
- /**
2378
- * The untranslated protocol word, for support and audit.
2379
- *
2380
- * A tagged union over the two families rather than a bare string, so M6's
2381
- * cancel path reads the family split off the update one lookup earlier than a
2382
- * repository read. The reason strings are deliberately NOT here: `failure` and
2383
- * `blockedReason` arrive on the record as fields, not as vocabulary, and
2384
- * {@link Swap} is where a consumer reads them.
2385
- *
2386
- * `wire`, `htlc` and `fate` are the supporting vocabularies a pass consults.
2387
- * They are declared because the shape is fixed here rather than left to the
2388
- * first consumer that wants one, and populated by nothing today: the manager
2389
- * surfaces neither the L1 phase nor the lockup fate on its update callback, and
2390
- * the solver's own `RfqStatus` is a self-report no drive pass reads at all.
2391
- */
2392
- type RawState = {
2393
- readonly family: "rfq";
2394
- readonly state: RfqSwapState;
2395
- readonly wire?: RfqStatus["state"];
2396
- readonly htlc?: OnchainHtlcPhase;
2397
- readonly fate?: LockupFate;
2398
- } | {
2399
- readonly family: "offer";
2400
- readonly status: AssetSwapStatus;
2401
- };
2402
- /** What `onUpdate` delivers. */
2403
- interface SwapUpdate {
2404
- readonly swap: Swap;
2405
- readonly outcome: Outcome;
2406
- readonly detail: RawState;
2407
- }
2408
- /** What every listener registration hands back. */
2409
- type Unsubscribe = () => void;
2410
- /** The manager's route-pair vocabulary — a route pair, not a corridor. */
2411
- type CorridorKind = PersistableRfqSwap["kind"];
2412
- /**
2413
- * Which route side each corridor kind is, and so which {@link CorridorPass}
2414
- * describes its drive.
2415
- *
2416
- * `lightning_send` is `arkade -> lightning`: the trader TAKES on lightning.
2417
- * `lightning_receive` is `lightning -> arkade`: the trader GIVES on it.
2418
- */
2419
- declare const CORRIDOR_PASS: {
2420
- readonly lightning_send: {
2421
- readonly lockups: readonly [{
2422
- readonly covenant: "arkade_lockup";
2423
- readonly owner: "trader";
2424
- readonly deadline: "refund_locktime";
2425
- }];
2426
- readonly actions: readonly ["refundArkade"];
2427
- readonly seams: readonly ["indexer"];
2428
- };
2429
- readonly lightning_receive: {
2430
- readonly lockups: readonly [{
2431
- readonly covenant: "arkade_lockup";
2432
- readonly owner: "solver";
2433
- readonly deadline: "refund_locktime";
2434
- }];
2435
- readonly actions: readonly ["claimLockup"];
2436
- readonly seams: readonly ["indexer"];
2437
- };
2438
- readonly onchain_send: {
2439
- readonly lockups: readonly [{
2440
- readonly covenant: "arkade_lockup";
2441
- readonly owner: "trader";
2442
- readonly deadline: "refund_locktime";
2443
- }, {
2444
- readonly covenant: "onchain_htlc";
2445
- readonly owner: "solver";
2446
- readonly deadline: "htlc_refund_locktime";
2447
- }];
2448
- readonly actions: readonly ["claimOnchain", "refundArkade"];
2449
- readonly seams: readonly ["indexer", "chain"];
2450
- };
2451
- };
2452
- /**
2453
- * Whose the arkade lockup is, per corridor kind — read off the corridor
2454
- * modules' own declarations rather than restated.
2455
- *
2456
- * The arkade lockup is `lockups[0]` on all three, which is the order
2457
- * `CorridorPass.lockups` documents: "every covenant the pass reads, in the
2458
- * order it reads them", and step 1 of every pass is the arkade lockup.
2459
- */
2460
- declare const LOCKUP_OWNER: {
2461
- readonly lightning_send: "trader";
2462
- readonly lightning_receive: "solver";
2463
- readonly onchain_send: "trader";
2464
- };
2465
- /** Whether this kind's drive pass reads L1 — the seam that decides whether the
2466
- * onchain corridor's deps have to be resolved at all. */
2467
- declare const readsChain: (kind: CorridorKind) => boolean;
2468
- /** The corridor family's translation. */
2469
- declare const corridorOutcome: (kind: CorridorKind, state: RfqSwapState) => Outcome;
2470
- declare const offerOutcome: (status: AssetSwapStatus) => Outcome;
2471
- /**
2472
- * What a record reports when nothing live stands behind it.
2473
- *
2474
- * Two of the three record-and-clock projections, and the reason they are a
2475
- * projection at all: nothing is written when a swap is handed to the manager,
2476
- * so the first write is the first pass, and until then the record and the
2477
- * funding txid are the whole answer. A corridor record therefore reads
2478
- * `accepted` until its funding is broadcast and `funding` until the drive
2479
- * adopts it — including the receive leg, whose `accepted -> open` arrow is
2480
- * exactly the durable invoice becoming a watched one.
2481
- *
2482
- * The offer family has no live object of its own — its watcher is event-driven
2483
- * over the store — so past the funding the record IS the state.
2484
- */
2485
- declare const recordOutcome: (record: {
2486
- family: "offer" | "rfq";
2487
- fundingTxid?: string;
2488
- status?: AssetSwapStatus;
2489
- }) => Outcome;
2490
- /**
2491
- * `Outcome`, as `activity.ts`'s opaque grouping token.
2492
- *
2493
- * The resolver's vocabulary is deliberately coarser than this one — it labels a
2494
- * history row, not a swap's state — so this is a projection and not a rename.
2495
- * `lost` is what `lapsed` projects to, which is the token that file already
2496
- * emitted by hand for a receive leg's `refunded`.
2497
- */
2498
- declare const ACTIVITY_TOKEN: Record<Outcome, string>;
2499
-
2500
- /**
2501
- * A route is two endpoints, each an asset on a corridor, plus the instrument
2502
- * that settles it.
2503
- *
2504
- * Two invariants live in the types rather than in a check. An endpoint's
2505
- * corridor and its asset cannot disagree, because {@link Endpoint} is a union
2506
- * with one member per corridor and each member types its asset as
2507
- * {@link AssetOn} of that one corridor. And `onchain -> arkade` is not in
2508
- * {@link Route} at all, so once a route has been resolved the misroute is a
2509
- * compile error; before resolution it is `UnsupportedRoute`, thrown ahead of
2510
- * RFQ disclosure, artifact creation, persistence and funding.
2511
- */
2512
-
2513
- /**
2514
- * A leg's concrete settlement locus. Direction comes from give versus take,
2515
- * never from the instrument.
2516
- *
2517
- * `{ kind: "wallet" }` is the only instrument the SDK holds signing authority
2518
- * over, which is why it is the only one nobody passes: `accept()` spends the
2519
- * balance and lands the claim on wallet legs and merely watches the others. The
2520
- * supply law is that the caller provides non-wallet take instruments (that is
2521
- * what `to` is), the quote provides non-wallet give instruments (that is
2522
- * exactly what the artifact is), and every remaining slot resolves to `wallet`.
2523
- *
2524
- * `wallet` is an explicit variant rather than an absent field because absence
2525
- * would mean two unrelated things — wallet-by-default and not-yet-resolved —
2526
- * and a receive leg lives in the second state until the quote returns.
2527
- */
2528
- type Instrument = {
2529
- kind: "wallet";
2530
- } | {
2531
- kind: "address";
2532
- address: string;
2533
- } | {
2534
- kind: "invoice";
2535
- bolt11: string;
2536
- paymentHash: Hex;
2537
- amount?: bigint;
2538
- expiresAt: number;
2539
- };
2540
- /**
2541
- * The asset ids corridor `C` can carry.
2542
- *
2543
- * On the three bitcoin-family corridors the corridor names no network, so the
2544
- * tie is the rail alone. On an EVM corridor it is more than that: `eip155:8453`
2545
- * *is* the CAIP-2 chain part its assets are spelled with, so the asset id has to
2546
- * start with the corridor id verbatim. Enforcing only the rail there would admit
2547
- * `eip155:1/erc20:…` on a Base corridor — the same near-miss `sameAsset` refuses
2548
- * one layer up, an address being a chain's fact and not a token's.
2549
- */
2550
- type AssetOn<C extends CorridorId> = C extends Corridor ? AssetId<RailOf<C>> : `${C}/${AssetPart}`;
2551
- /**
2552
- * An asset on a corridor, with the instrument that settles it.
2553
- *
2554
- * `corridor` is a cross-check rather than an input: every id already carries
2555
- * its rail. Typing `asset` against that rail is what makes the cross-check free
2556
- * — there is no value in which the two disagree.
2557
- *
2558
- * Distributed over `C` rather than written as one object whose two fields both
2559
- * mention it: `{ corridor: C; asset: AssetOn<C> }` at `C = CorridorId` widens
2560
- * *each field independently* to its own union, and correlates nothing —
2561
- * `{ corridor: "arkade", asset: "bitcoin:…" }` satisfies it. The conditional
2562
- * makes `Endpoint` the union of the four single-corridor shapes instead, so the
2563
- * pairing survives the default type argument, which is the case every unwitnessed
2564
- * `Endpoint` in a signature lands on.
2565
- */
2566
- type Endpoint<C extends CorridorId = CorridorId> = C extends CorridorId ? {
2567
- corridor: C;
2568
- asset: AssetOn<C>;
2569
- /** Resolved by the client, never constructed by callers. */
2570
- instrument: Instrument;
2571
- } : never;
2572
- /** Shorthand for one corridor's endpoint, as the route union spells it. */
2573
- type Ep<C extends CorridorId> = Endpoint<C>;
2574
- /**
2575
- * The implemented routes, as a closed union.
2576
- *
2577
- * `onchain -> arkade` is deliberately absent until the manager owns the
2578
- * trader's L1 refund path end to end.
2579
- */
2580
- type Route = {
2581
- give: Ep<"arkade">;
2582
- take: Ep<"arkade">;
2583
- } | {
2584
- give: Ep<"arkade">;
2585
- take: Ep<"lightning">;
2586
- } | {
2587
- give: Ep<"lightning">;
2588
- take: Ep<"arkade">;
2589
- } | {
2590
- give: Ep<"arkade">;
2591
- take: Ep<"onchain">;
2592
- };
2593
- /**
2594
- * The one thing a counterparty must see, when a route has one.
2595
- *
2596
- * The deposit variant carries no `chain` field. §3.4 reserved one and Q12 made
2597
- * it redundant: the chain part lives inside `asset`, and a second, untyped
2598
- * spelling of it is a fact two fields can disagree about with nothing checking.
2599
- * `corridor` stays because it is the typed axis `route.ts` already ties to the
2600
- * asset's rail — a cross-check, where `chain?: string | number` was a copy.
2601
- */
2602
- type Artifact = {
2603
- kind: "invoice";
2604
- bolt11: string;
2605
- } | DepositArtifact;
2606
- /**
2607
- * The deposit half of {@link Artifact}, distributed over the corridor for the
2608
- * reason {@link Endpoint} is: `corridor` is only a cross-check if a value cannot
2609
- * spell it against an asset from another corridor.
2610
- */
2611
- type DepositArtifact<C extends CorridorId = CorridorId> = C extends CorridorId ? {
2612
- kind: "deposit";
2613
- corridor: C;
2614
- address: string;
2615
- asset: AssetOn<C>;
2616
- amount: bigint;
2617
- expiresAt?: number;
2618
- } : never;
2619
-
2620
- /** Which side of the trade an amount pins, in v2's vocabulary. */
2621
- type AmountOn = "give" | "take";
2622
- /** The same axis on the wire, where the key is `amount_side`. */
2623
- type RfqAmountSide = "from" | "to";
2624
- /** v2 to the wire. One translation point, so the rename cannot spread. */
2625
- declare const toRfqAmountSide: (on: AmountOn) => RfqAmountSide;
2626
- /** The wire back to v2. */
2627
- declare const fromRfqAmountSide: (side: RfqAmountSide) => AmountOn;
2628
- /**
2629
- * An amount out to the wire, as the canonical decimal string.
2630
- *
2631
- * `field` has no default: every throw on a quote would otherwise say `"amount"`,
2632
- * and telling `from_amount` from `to_amount` is the only thing it is for.
2633
- */
2634
- declare const encodeRfqAmount: (value: bigint, field: string) => AtomicDecimal;
2635
- /**
2636
- * An amount in from the wire.
2637
- *
2638
- * Accepts the canonical string, or a JSON number inside the safe-integer window
2639
- * — the migration's compatibility arm, and the only place a number is tolerated
2640
- * anywhere in v2. A non-canonical string is this error too, not a verification
2641
- * failure: verification is the four semantic checks over a well-formed quote,
2642
- * and this fires before them.
2643
- */
2644
- declare const decodeRfqAmount: (raw: unknown, field: string) => bigint;
2645
- /**
2646
- * A `bigint` amount into a foreign `number` one, checked.
2647
- *
2648
- * Core's payment router types its amounts as `number` sats and M7's swap-backed
2649
- * rail narrows at that boundary rather than changing a published core type. The
2650
- * narrowing is sound because both sides are sats and a sat count past 2^53 is
2651
- * not a payment — but it has to be checked, which is why it lives here beside
2652
- * the error rather than as a bare `Number()` at the call site.
2653
- */
2654
- declare const toSafeNumber: (value: bigint, field: string) => number;
2655
-
2656
- /**
2657
- * What a quote is: the order, fully resolved, plus the provenance that says who
2658
- * priced it and where that card came from.
2659
- *
2660
- * M1 named these shapes and left them to whichever milestone decided their
2661
- * semantics; this is that milestone, so `QuoteId`, `QuoteInput`, `Quote`,
2662
- * `MarketRef` and `AuctionProvenance` are declared here rather than beside the
2663
- * types they are built out of. Nothing in this module has behaviour — the quote
2664
- * path assembles these, `accept()` (M4) consumes them.
2665
- *
2666
- * The one rule worth restating at the top: a `Quote` is binding terms plus the
2667
- * evidence for them. Every field is either something the caller must act on
2668
- * (the two obligations, the artifact, the deadline) or something they must be
2669
- * able to audit afterwards (the market, the solver, the checks that passed).
2670
- * Nothing internal rides along — no covenant, no secret, no transport.
2671
- */
2672
-
2673
- /**
2674
- * A quote's identity, minted by the client at quote time.
2675
- *
2676
- * Client-minted everywhere, not just where the wire offers no id: a feed-priced
2677
- * offer quote has no solver-minted id at all, and `accept()` is idempotent by
2678
- * quote id *and only* by quote id (§3.2), so an identity that exists on one
2679
- * backend and not the other could not carry that rule. An alias rather than a
2680
- * brand, matching `Hex` and `Pubkey` beside it.
2681
- */
2682
- type QuoteId = string;
2683
- /**
2684
- * A caller's spelling of an asset: a public id, or a ticker the alias layer
2685
- * canonicalizes against the registry.
2686
- *
2687
- * `AssetId | (string & {})` rather than `string`, so an editor still completes
2688
- * the id form and a mistyped id still shows up as one — `AssetId | string`
2689
- * collapses to `string` and takes both with it.
2690
- */
2691
- type AssetRef = AssetId | (string & {});
2692
- /**
2693
- * Everything a caller supplies. §4's bottom line: two asset ids or one
2694
- * destination string, one amount, which side it pins, and — on receives, where
2695
- * no instrument exists yet — a corridor.
2696
- */
2697
- interface QuoteInput {
2698
- /** Omitted when the route determines it: the give leg is the wallet's. */
2699
- give?: AssetRef;
2700
- /** Omitted when `to` determines it — a corridor that carries BTC only does. */
2701
- take?: AssetRef;
2702
- /** A self-describing instrument: bolt11, an Arkade address, or `bc1…`. */
2703
- to?: string;
2704
- /** Receive flows only: names the corridor when no instrument can exist yet. */
2705
- via?: CorridorId;
2706
- /** Atomic units. Exactly one amount may be pinned — see `amountOn`. */
2707
- amount?: bigint;
2708
- /** Which leg `amount` pins. Required with `amount`, and refused with an
2709
- * invoice, which pins one already. */
2710
- amountOn?: AmountOn;
2711
- }
2712
- /** Which backend priced a quote. The card decides it; no client switch does. */
2713
- type MarketBackend = "rfq" | "feed";
2714
- /** Where a snapshot came from, and how fresh it is. */
2715
- interface SnapshotRef {
2716
- /** Unix ms the markets were read from their sources. */
2717
- readonly fetchedAt: number;
2718
- /**
2719
- * The registry answered in this read, so the cards are registry-served
2720
- * rather than replayed out of local storage.
2721
- *
2722
- * `false` is not an error: a stale snapshot still resolves and still prices
2723
- * a feed-priced quote — it is marked, not refused. What it cannot do is
2724
- * supply the key an addressed RFQ's responder is checked against, because
2725
- * that field is unvalidated cache content (`isMarketShaped` revalidates
2726
- * four fields and trusts the rest).
2727
- */
2728
- readonly live: boolean;
2729
- /** How the markets were obtained. */
2730
- readonly source: "live" | "cache" | "injected";
2731
- /** The registry URL behind it, or `undefined` for an injected snapshot. */
2732
- readonly registry?: string;
2733
- }
2734
- /**
2735
- * Which card priced a quote, and from which registry.
2736
- *
2737
- * A union rather than a bag of optionals, because §10's published RFQ is the
2738
- * one place the sentence "the market picks the backend" stops: a quote closed
2739
- * out of an open auction has a market *key* and no card behind it, so every
2740
- * card-derived field is absent at once rather than one at a time. Sizing that
2741
- * arm now costs a discriminant and keeps the addressed arm total.
2742
- */
2743
- type MarketRef = CardMarketRef | AuctionMarketRef;
2744
- interface CardMarketRef {
2745
- readonly kind: "card";
2746
- /**
2747
- * The canonical market key, `<corridor>:<id>/<corridor>:<id>`, derived under
2748
- * rfq-protocol.md §2's leg order — arkade first when exactly one leg is
2749
- * arkade, lexicographic otherwise — and never read off the card's own
2750
- * base/quote order. The two agree for every card the registry's reducer
2751
- * validated, and a card published outside it is exactly where the silent
2752
- * miss lives.
2753
- */
2754
- readonly key: string;
2755
- readonly backend: MarketBackend;
2756
- /** The registry URL, or the label a locally pinned card was loaded under. */
2757
- readonly source: string;
2758
- readonly sourceType: "registry" | "local";
2759
- /** The solver's name, as the card publishes it. Display, never identity. */
2760
- readonly solver: string;
2761
- /** The card's signing key. Absent on spot cards, which need no rendezvous. */
2762
- readonly discoveryPubkey?: Pubkey;
2763
- /** The card's display label, e.g. `BTC/lightning:BTC`. Display only. */
2764
- readonly pair: string;
2765
- readonly snapshot: SnapshotRef;
2766
- }
2767
- /** §10, reserved: a quote closed out of a published auction has no card. */
2768
- interface AuctionMarketRef {
2769
- readonly kind: "auction";
2770
- readonly key: string;
2771
- readonly backend: "rfq";
2772
- }
2773
- /**
2774
- * One bid seen in a published auction (§10, Q9).
2775
- *
2776
- * Typed against ts-sdk #777's shipped draft rather than invented: a bid is a
2777
- * counter-amount on the leg the client did not fix, attributed to the event key
2778
- * that signed it — which is NOT the covenant's `solver_pubkey`, a role key the
2779
- * quote fills from a different field.
2780
- */
2781
- interface RankedBid {
2782
- /** The event key that signed the bid. Attribution, not a covenant role. */
2783
- readonly bidder: Pubkey;
2784
- /** The counter-amount, on the leg the client left free. */
2785
- readonly amount: bigint;
2786
- readonly amountOn: AmountOn;
2787
- readonly expiresAt: number;
2788
- }
2789
- /**
2790
- * The auction a published-RFQ quote was closed out of (§10, Q9).
2791
- *
2792
- * Reserved and inert: `quote()` never populates it, and Q9 froze the name so
2793
- * the shape it will take cannot be occupied by something else in the meantime.
2794
- */
2795
- interface AuctionProvenance {
2796
- /** The market key the open request was tagged with. */
2797
- readonly marketKey: string;
2798
- /** The bid that was closed with. */
2799
- readonly winner: RankedBid;
2800
- /** Every other bid seen before the window closed. */
2801
- readonly losers: readonly RankedBid[];
2802
- /** Unix seconds the bid window closed. */
2803
- readonly closedAt: number;
2804
- }
2805
- /** One leg's obligation: an asset, and exactly how much of it. */
2806
- interface QuoteLeg {
2807
- readonly asset: AssetId;
2808
- readonly amount: bigint;
2809
- }
2810
- /**
2811
- * The order, fully resolved.
2812
- *
2813
- * Both amounts are exact obligations with the fee already inside them, which is
2814
- * what `fee` restates rather than adds: it is the spread, precomputed, so a
2815
- * verb (M7) can compare it to a ceiling without re-deriving it from a price.
2816
- */
2817
- interface Quote {
2818
- readonly id: QuoteId;
2819
- /** Both endpoints resolved, instruments included. */
2820
- readonly route: Route;
2821
- /** What the trader gives, fee included. */
2822
- readonly give: QuoteLeg;
2823
- /** What the trader takes. */
2824
- readonly take: QuoteLeg;
2825
- /** Corridor routes: the hash both covenants commit to. */
2826
- readonly lock?: {
2827
- readonly hash: Hex;
2828
- };
2829
- /** Which card priced this, from which registry, how fresh. */
2830
- readonly market: MarketRef;
2831
- /** RFQ routes: the committed counterparty, from the quote's covenant role. */
2832
- readonly solver?: Pubkey;
2833
- /** §10 only, and never populated today. */
2834
- readonly auction?: AuctionProvenance;
2835
- /** Unix seconds. Non-optional on both backends — a feed-priced quote has no
2836
- * wire expiry to inherit, so the client mints one from the feed's freshness. */
2837
- readonly expiresAt: number;
2838
- /**
2839
- * Corridor routes: when the trader's value comes back if the swap does not
2840
- * complete.
2841
- *
2842
- * Optional on the type because an asset swap has no refund clock at all —
2843
- * an offer covenant never expires — and non-optional in practice on every
2844
- * corridor route, where the wire's own field is optional and the client
2845
- * refuses a quote without it.
2846
- */
2847
- readonly refundLocktime?: number;
2848
- /** The one thing a counterparty must see, when this route has one. */
2849
- readonly artifact?: Artifact;
2850
- /** The spread, denominated on the leg where it is exact. */
2851
- readonly fee: {
2852
- readonly amount: bigint;
2853
- readonly asset: AssetId;
2854
- };
2855
- }
2856
- /**
2857
- * An endpoint as `resolve()` can answer for it, before any disclosure.
2858
- *
2859
- * Not an `Endpoint`: that type's instrument is non-optional, deliberately, and a
2860
- * receive leg has none until the quote returns — the instrument IS the artifact
2861
- * the solver mints. Absence here means exactly that one thing, because the
2862
- * wallet case is spelled `{ kind: "wallet" }` rather than left out.
2863
- */
2864
- interface ResolvedEndpoint {
2865
- readonly corridor: Corridor;
2866
- readonly asset: AssetId;
2867
- /** Absent only while the leg's instrument does not exist yet. */
2868
- readonly instrument?: Instrument;
2869
- }
2870
- /** The amount a caller (or an invoice) pinned, and which leg it pins. */
2871
- interface PinnedAmount {
2872
- readonly value: bigint;
2873
- readonly on: AmountOn;
2874
- /** What pinned it, for the diagnostic an `AmountMismatch` carries. */
2875
- readonly source: "caller" | "invoice";
2876
- }
2877
- /**
2878
- * What `resolve()` answers: the route's shape, the market that would price it,
2879
- * and what the active snapshot actually serves.
2880
- *
2881
- * `eligible` is reported alongside rather than folded into an error because
2882
- * zero is not a failure of resolution: the destination parsed, the corridor pair
2883
- * is implemented, and nothing about the route is wrong — there is simply no
2884
- * market for it on this snapshot. `quote()` is where that becomes
2885
- * `UnsupportedRoute`, since a quote cannot proceed past market selection.
2886
- */
2887
- interface RouteResolution {
2888
- readonly give: ResolvedEndpoint;
2889
- readonly take: ResolvedEndpoint;
2890
- /** The card that would price it: the first eligible one after policy. */
2891
- readonly market?: MarketRef;
2892
- /** How many markets serve this pair on the active snapshot, after policy. */
2893
- readonly eligible: number;
2894
- /** Where the market data came from, and how fresh it is. */
2895
- readonly snapshot: SnapshotRef;
2896
- /** The amount pinned so far, when the input pinned one. */
2897
- readonly amount?: PinnedAmount;
2898
- }
2899
-
2900
- /**
2901
- * What survives a crash, and the public shape `accept()` hands back.
2902
- *
2903
- * Two types, one key. {@link SwapRecord} is the storage form — JSON-safe by
2904
- * declaration, every amount a canonical decimal string — and {@link Swap} is the
2905
- * answer a caller reads, with `bigint` amounts and the resolved `Route`. The
2906
- * conversion between them is §D's record-boundary codec, and it is not a third
2907
- * law: `toAtomicDecimal`/`fromAtomicDecimal` already ship in `./amount`, minted
2908
- * by M1 and used by M3's wire adapter, so both sites emit the same canonical
2909
- * form — atomic units, unsigned, no leading zeros, never a scaled display
2910
- * decimal.
2911
- *
2912
- * **The key is the quote id, on every route.** That is what makes persist-first
2913
- * representable at all: v1's `AssetSwap.id` *is* the funding txid
2914
- * (`store.ts:70-71`), so a record could not exist before the money did, and
2915
- * `coverage.ts` carries a process-local issuance mark precisely to paper over
2916
- * the gap. Here the record precedes the funding and `fundingTxid` is a later,
2917
- * best-effort write.
2918
- *
2919
- * **JSON-safe means no `bigint` anywhere, at any depth.** The SQLite and Realm
2920
- * backends `JSON.stringify` the record whole, so a `bigint` throws on two
2921
- * backends and round-trips on the third — the asymmetry
2922
- * `test/repository.test.ts` refuses to paper over. Every amount here is an
2923
- * {@link AtomicDecimal}; `test/client/record.types.ts` proves the absence
2924
- * structurally rather than by review.
2925
- */
2926
-
2927
- /**
2928
- * Which family a record belongs to, and the discriminant M5's `RawState` keys
2929
- * on.
2930
- *
2931
- * Not a cosmetic tag. v1's two families occupied one `string` id space by
2932
- * accident — an offer record's id a funding txid, a corridor record's an
2933
- * `rfqId` — and keying both on `QuoteId` closes that collision (§B). The tag is
2934
- * what M6's public id carries, and what lets M5 branch its outcome table
2935
- * without a repository read.
2936
- */
2937
- type SwapFamily = "offer" | "rfq";
2938
- /**
2939
- * The public swap id: the family tag over the client-minted quote id,
2940
- * `offer:<QuoteId>` / `rfq:<QuoteId>`, as {@link Swap.id} carries it.
2941
- *
2942
- * The tag is presentation, not a second identity — storage, the drive and
2943
- * `accept()`'s idempotency stay keyed on the bare quote id. But a branded
2944
- * string erases at runtime, so the tag is not cosmetic either: it makes
2945
- * `NotCancellable` a parse of the prefix — a corridor id refused with no
2946
- * repository read, an offer id distinguished from a corridor id the way the v1
2947
- * read could not be — and it retypes the id a caller hands around, so
2948
- * `cancel(swap.id)` and `recover(swap.id)` stop being two spellings of one
2949
- * thing. An id arriving untagged from `/protocol`'s re-exported readers takes
2950
- * the same one read the tagged form takes.
2951
- */
2952
- type AssetSwapId = `${SwapFamily}:${QuoteId}`;
2953
- /** The public id a record answers with — the tag, minted off its family. */
2954
- declare const assetSwapIdOf: (family: SwapFamily, quoteId: QuoteId) => AssetSwapId;
2955
- declare const OFFER_SWAP_ID_PREFIX: "offer:";
2956
- declare const RFQ_SWAP_ID_PREFIX: "rfq:";
2957
- /**
2958
- * The family an id names, or `undefined` for an id no prefix tags — the form
2959
- * `/protocol`'s re-exported readers still hand back, which takes the
2960
- * repository read rather than the parse.
2961
- */
2962
- declare const familyOfSwapId: (swapId: string) => SwapFamily | undefined;
2963
- /**
2964
- * The bare quote id under the tag — what storage, the drive and `accept()`'s
2965
- * idempotency key on. Strips a family prefix when one is present and passes an
2966
- * untagged id through unchanged, so a reader-era id still reaches its record.
2967
- */
2968
- declare const quoteIdOfSwapId: (swapId: string) => QuoteId;
2969
- /** One leg's obligation, in the form a record holds it. */
2970
- interface RecordedLeg {
2971
- readonly asset: AssetId;
2972
- /** Atomic units as a canonical decimal string — never a `bigint`. */
2973
- readonly amount: AtomicDecimal;
2974
- }
2975
- /**
2976
- * An endpoint as the record holds it: the corridor, the asset, the instrument.
2977
- *
2978
- * `Instrument`'s invoice arm carries a `bigint` amount, so it cannot be stored
2979
- * as declared — {@link RecordedInstrument} is the same union with that one field
2980
- * in decimal form. The rest is field for field identical, which is what keeps the
2981
- * comparison in `acceptConflict` honest.
2982
- */
2983
- interface RecordedEndpoint {
2984
- readonly corridor: CorridorId;
2985
- readonly asset: AssetId;
2986
- readonly instrument: RecordedInstrument;
2987
- }
2988
- /** {@link Instrument}, with the invoice arm's amount in decimal form. */
2989
- type RecordedInstrument = {
2990
- readonly kind: "wallet";
2991
- } | {
2992
- readonly kind: "address";
2993
- readonly address: string;
2994
- } | {
2995
- readonly kind: "invoice";
2996
- readonly bolt11: string;
2997
- readonly paymentHash: Hex;
2998
- readonly amount?: AtomicDecimal;
2999
- readonly expiresAt: number;
3000
- };
3001
- /** {@link Artifact}, with the deposit arm's amount in decimal form. */
3002
- type RecordedArtifact = {
3003
- readonly kind: "invoice";
3004
- readonly bolt11: string;
3005
- } | {
3006
- readonly kind: "deposit";
3007
- readonly corridor: CorridorId;
3008
- readonly address: string;
3009
- readonly asset: AssetId;
3010
- readonly amount: AtomicDecimal;
3011
- readonly expiresAt?: number;
3012
- };
3013
- /**
3014
- * The half both families carry.
3015
- *
3016
- * Every field is either something `AcceptConflict` compares (§3.2's list), or
3017
- * something M5 named as a cross-milestone ask, or the two timestamps. Nothing
3018
- * is here for display: a record carries what no covenant and no chain read can
3019
- * give back, which is the same rule `RfqSwapRecord` is arranged by.
3020
- */
3021
- interface SwapRecordCommon {
3022
- /** The client-minted quote id — the primary key, per C1 and §B. */
3023
- readonly id: QuoteId;
3024
- readonly family: SwapFamily;
3025
- /**
3026
- * Both endpoints, instruments included — `AcceptConflict` items 1 and 3.
3027
- *
3028
- * Nested under `route` so the record's field names are `Quote`'s field
3029
- * names: the conflict check walks the two shapes together, and a record
3030
- * that spelled the same fact differently would make every comparison a
3031
- * translation.
3032
- */
3033
- readonly route: {
3034
- readonly give: RecordedEndpoint;
3035
- readonly take: RecordedEndpoint;
3036
- };
3037
- /** The two obligations — `AcceptConflict` item 2. */
3038
- readonly give: RecordedLeg;
3039
- readonly take: RecordedLeg;
3040
- /** The spread, as the quote precomputed it. */
3041
- readonly fee: RecordedLeg;
3042
- /**
3043
- * Which card priced this, from which registry, how fresh — stored WHOLE.
3044
- *
3045
- * A trimmed projection could not rebuild the type {@link Swap.market}
3046
- * promises: `CardMarketRef` requires `kind`, `pair` and `snapshot` beside
3047
- * the fields a summary would keep. Every member is a string, number or
3048
- * boolean, so the union round-trips through JSON untouched, and `snapshot`
3049
- * is restated as read at accept rather than restamped — a past `fetchedAt`
3050
- * beside the recorded `live` is the honest answer about how fresh the card
3051
- * was when this swap was accepted.
3052
- */
3053
- readonly market: MarketRef;
3054
- /**
3055
- * The committed counterparty, from the quote's covenant role.
3056
- *
3057
- * NOT `CardMarketRef.solver`, which is the card's display name. Two
3058
- * different facts that v1 spelled with one word: this one is a key that
3059
- * ends up in a covenant leaf, the other is a label. `AcceptConflict`
3060
- * compares this one.
3061
- */
3062
- readonly solver?: Pubkey;
3063
- /** The quote's own deadline, unix seconds — what makes a stalled accept a
3064
- * benign abandon rather than a live obligation. */
3065
- readonly expiresAt: number;
3066
- /**
3067
- * The one thing a counterparty must see, when this route has one.
3068
- *
3069
- * Durable because a duplicate accept must return the SAME invoice, and the
3070
- * invoice lives on the quote object — nowhere in the corridor profile. A
3071
- * caller that re-accepts after a restart has no quote object left, so
3072
- * without this field the only honest answer would be a second invoice,
3073
- * which §3.2 forbids by name.
3074
- */
3075
- readonly artifact?: RecordedArtifact;
3076
- /**
3077
- * The transaction that funded this swap, once known.
3078
- *
3079
- * A later, best-effort write, and the field that separates M5's `accepted`
3080
- * from `funding`. Set-where-absent is a benign resume and never an
3081
- * `AcceptConflict` — §3.2 says so by name.
3082
- */
3083
- readonly fundingTxid?: string;
3084
- /**
3085
- * Last local receive-claim error while the swap is still retryable. If the
3086
- * claim window later closes without a submitted claim, this becomes the
3087
- * terminal failure reason after restore.
3088
- */
3089
- readonly claimFailure?: string;
3090
- /** Terminal failure reason. */
3091
- readonly failure?: string;
3092
- /** Refusal reason while `state` is `needs_counterparty`. */
3093
- readonly blockedReason?: string;
3094
- /** Unix **seconds**, both — the unit `RfqSwapRecord` carries and
3095
- * `shouldRetainRfqSwap` compares against, not `AssetSwap`'s milliseconds. */
3096
- readonly createdAt: number;
3097
- readonly updatedAt: number;
3098
- }
3099
- /**
3100
- * `arkade <-> arkade`: the offer covenant, and what cancels it.
3101
- *
3102
- * `offerHex` is the whole covenant — `cancelOffer` needs nothing else to
3103
- * rebuild it — so this arm stores no tree parameters of its own.
3104
- */
3105
- interface OfferSwapRecord extends SwapRecordCommon {
3106
- readonly family: "offer";
3107
- /** v1's raw status vocabulary, which M5's `RawState` reads verbatim. */
3108
- readonly status: AssetSwapStatus;
3109
- /** The TLV offer, hex. The only input `cancelOffer` needs. */
3110
- readonly offerHex: string;
3111
- readonly swapAddress: string;
3112
- /** The covenant's scriptPubKey, hex — the indexer's monitoring key, and
3113
- * what §F's reconcile matches a discovered deposit against. */
3114
- readonly swapPkScript: string;
3115
- readonly spentTxid?: string;
3116
- readonly completedAt?: number;
3117
- }
3118
- /**
3119
- * The three corridor routes: a VHTLC lockup, its clocks and its secrets.
3120
- *
3121
- * **No covenant tree here.** Every lockup registers a contract row before its
3122
- * address can be funded, and that row already holds the parameters, keyed by
3123
- * the script they derive — a key `createContract` refuses to write unless the
3124
- * params reproduce it. Storing the tree a second time would be two sources for
3125
- * one covenant. `accept()` is what writes that row (see `./accept.ts`), which
3126
- * is why a persisted record always has one.
3127
- */
3128
- interface CorridorSwapRecord extends SwapRecordCommon {
3129
- readonly family: "rfq";
3130
- /** v1's raw state vocabulary, read verbatim by M5's `RawState`. */
3131
- readonly state: RfqSwapState;
3132
- /**
3133
- * Which corridor, in the manager's own vocabulary.
3134
- *
3135
- * `PersistableRfqSwap["kind"]` rather than a `Corridor`: it is a route pair
3136
- * — `lightning_send` and `lightning_receive` are one corridor from opposite
3137
- * ends — and it is what resolves the handler that owns {@link profile}.
3138
- */
3139
- readonly kind: PersistableRfqSwap["kind"];
3140
- /** The solver's own id for the negotiation, echoed back on the wire. */
3141
- readonly rfqId: string;
3142
- /** The Arkade address that was funded, and the swap's handle on its
3143
- * covenant row. */
3144
- readonly lockupAddress: string;
3145
- /** Its pkScript, hex — the row's key, and §F's matching key. */
3146
- readonly lockupPkScript: string;
3147
- /** The hash both covenants commit to. `sha256(P)`, hex. */
3148
- readonly lock: {
3149
- readonly hash: Hex;
3150
- };
3151
- /** When the trader's value comes back if the swap does not complete. */
3152
- readonly refundLocktime: number;
3153
- /**
3154
- * The corridor's own half, as plain JSON.
3155
- *
3156
- * v1's opaque bag (`rfqRecord.ts:108-123`), written with `rfqSecretsProfile`
3157
- * and read by `rfqCorridorHandlers.hydrate` — reused rather than
3158
- * reinvented, so M5 rebuilds through machinery that already exists and a new
3159
- * corridor still ships without touching this file. It is also what carries
3160
- * `expectedAmount`, the claim value gate's request-time input.
3161
- *
3162
- * Amounts inside it follow v1's shapes (`expectedAmount` is a `number`),
3163
- * which is JSON-safe and therefore fine: the decimal-string law governs
3164
- * this record's OWN amount fields, not the bag it carries forward.
3165
- *
3166
- * **This is also where the swap's secrets live** — `profile.signer` and,
3167
- * on a leg locked to a preimage, `profile.hashlock`. Deliberately not a
3168
- * second copy at the record's top level: `rfqClaimSecretOf` and
3169
- * `preimageForSwapRecord` already read them from here, and two homes for
3170
- * one claim secret is two things to keep in step with one of them always
3171
- * empty. At most one of `preimageHex`/`preimageSaltHex` is ever written,
3172
- * and which arm exists is decided by the wallet's provisioning result, not
3173
- * here.
3174
- */
3175
- readonly profile: Record<string, unknown>;
3176
- readonly refundTxid?: string;
3177
- readonly lockupSpendTxids?: readonly string[];
3178
- }
3179
- /** Everything `accept()` persists, both families in one key space. */
3180
- type SwapRecord = OfferSwapRecord | CorridorSwapRecord;
3181
- /**
3182
- * A swap, as a caller reads it.
3183
- *
3184
- * The quote's terms plus what has happened to them. `bigint` amounts and the
3185
- * resolved `Route`, because this is the public answer and the record is the
3186
- * storage form — §D's codec is the boundary between the two.
3187
- *
3188
- * `artifact` stays optional: M7's `ReceiveRequest` is `Swap & { artifact:
3189
- * Artifact }`, and an intersection cannot narrow a field that is already
3190
- * required. `id` is the tagged public form {@link AssetSwapId} — minted from
3191
- * `record.family` by {@link swapOf} — while storage, the drive and `accept()`'s
3192
- * idempotency stay keyed on the bare quote id.
3193
- *
3194
- * {@link outcome} and the two reason strings are M5's, and they are here rather
3195
- * than on `SwapUpdate.detail` because `detail` is typed `RawState` — the raw
3196
- * machine word and nothing else. The reasons live on `SwapRecordCommon`, the
3197
- * internal record, so without this a consumer told a swap `needs_recovery` had
3198
- * nowhere to read WHY.
3199
- */
3200
- interface Swap {
3201
- readonly id: AssetSwapId;
3202
- readonly family: SwapFamily;
3203
- /** Where this swap stands, in the one vocabulary both families share. */
3204
- readonly outcome: Outcome;
3205
- /** Both endpoints resolved, instruments included. */
3206
- readonly route: Route;
3207
- /** What the trader gives, fee included. */
3208
- readonly give: QuoteLeg;
3209
- /** What the trader takes. */
3210
- readonly take: QuoteLeg;
3211
- /** The spread, denominated on the leg where it is exact. */
3212
- readonly fee: QuoteLeg;
3213
- readonly market: MarketRef;
3214
- readonly solver?: Pubkey;
3215
- /** Corridor routes: the hash both covenants commit to. */
3216
- readonly lock?: {
3217
- readonly hash: Hex;
3218
- };
3219
- /** Corridor routes: when the trader's value comes back. */
3220
- readonly refundLocktime?: number;
3221
- readonly artifact?: Artifact;
3222
- readonly expiresAt: number;
3223
- /** Absent until the funding is broadcast and its txid written. */
3224
- readonly fundingTxid?: string;
3225
- /**
3226
- * Why the swap `failed`, when it did.
3227
- *
3228
- * Carried across from the record rather than derived: the outcome says
3229
- * WHICH terminal state, and only the record says why.
3230
- */
3231
- readonly failure?: string;
3232
- /**
3233
- * Why this wallet will not act, while the outcome is `needs_recovery`.
3234
- *
3235
- * Also what makes a suppressed configuration block legible: under
3236
- * `drive: "manual"` or `"readonly"` the three configuration refusals are
3237
- * not translated to `needs_recovery`, and this is where the reason is
3238
- * still read.
3239
- */
3240
- readonly blockedReason?: string;
3241
- readonly createdAt: number;
3242
- readonly updatedAt: number;
3243
- }
3244
- /** An endpoint into its stored form. */
3245
- declare const recordEndpoint: (endpoint: {
3246
- corridor: CorridorId;
3247
- asset: string;
3248
- instrument: Instrument;
3249
- }) => RecordedEndpoint;
3250
- /** An instrument into its stored form: only the invoice arm's amount moves. */
3251
- declare const recordInstrument: (instrument: Instrument) => RecordedInstrument;
3252
- /** A stored instrument back into the live union. */
3253
- declare const instrumentOf: (instrument: RecordedInstrument) => Instrument;
3254
- /** An artifact into its stored form. */
3255
- declare const recordArtifact: (artifact: Artifact) => RecordedArtifact;
3256
- /** A stored artifact back into the live union. */
3257
- declare const artifactOf: (artifact: RecordedArtifact) => Artifact;
3258
- /** A leg into its stored form. */
3259
- declare const recordLeg: (leg: QuoteLeg) => RecordedLeg;
3260
- /** A stored leg back into `bigint` units. */
3261
- declare const legOf: (leg: RecordedLeg) => QuoteLeg;
3262
- /**
3263
- * The public {@link Swap} a stored record answers with.
3264
- *
3265
- * The one read path, so a duplicate `accept()` answers from the record rather
3266
- * than from the in-memory preparation cache — which is bounded, evicted in
3267
- * insertion order, and therefore not a durable answer to anything.
3268
- *
3269
- * The outcome is a parameter rather than a field read off the record: it is
3270
- * derived from the record, the clock AND whether the drive holds live state for
3271
- * this swap, and only the drive knows the third. Passing it keeps `Swap.outcome`
3272
- * non-optional, which is what stops a caller from having to test for it.
3273
- *
3274
- * The `Route` is reassembled from the two stored endpoints. The cast is the
3275
- * seam: `Route` is a closed union of four corridor pairs and a record read off
3276
- * disk carries two independently-typed endpoints, so nothing in the type system
3277
- * can re-correlate them. What guarantees the pairing is that `accept()` only
3278
- * ever writes a record from a `Quote` whose route was already resolved through
3279
- * that union.
3280
- */
3281
- declare const swapOf: (record: SwapRecord, outcome: Outcome) => Swap;
3282
- /**
3283
- * Whether this swap's give leg is funded from the wallet.
3284
- *
3285
- * The discriminant for every funding-route decision in `accept()` — the balance
3286
- * pre-flight, the `wallet.send`, the funding-txid write. It is the
3287
- * **instrument** and not the asset: a `lightning -> arkade` receive gives BTC
3288
- * too, but the give instrument is the hold invoice a third party pays, so an
3289
- * asset-branched test would send every receive down the wallet-balance path and
3290
- * refuse the canonical empty-wallet receive.
3291
- */
3292
- declare const fundsFromWallet: (route: {
3293
- give: {
3294
- instrument: Instrument | RecordedInstrument;
3295
- };
3296
- }) => boolean;
3297
-
3298
- /** A registry discovery result held for reuse. Refetchable — unlike a swap
3299
- * record, losing it costs one network round trip — but it must survive a cold
3300
- * boot: serving it stale is what keeps quoting alive while a registry is down. */
3301
- interface MarketsCacheEntry {
3302
- markets: DiscoveredMarket[];
3303
- fetchedAt: number;
3304
- }
3305
- /**
3306
- * Everything the package persists, following the monorepo repository
3307
- * convention: versioned interface, AsyncDisposable, one backend per platform.
3308
- * Consumers construct exactly one of these; there is no second storage seam.
3309
- *
3310
- * Durable records (swaps) and rebuildable state (the restore scan's txid
3311
- * cursor, the markets cache) live side by side because they share a
3312
- * lifetime: all three belong to one wallet on one device, and a consumer
3313
- * that wipes one wants all three gone.
3314
- *
3315
- * ponytail: no query filters — every consumer reads all swaps and filters
3316
- * in memory; add a filter type when a consumer needs subset queries.
3317
- */
3318
- interface AssetSwapRepository extends AsyncDisposable {
3319
- /** 5 adds the v2 swap-record store — one row per accepted swap, keyed by
3320
- * the client-minted quote id. 4 added `getRfqSwap`; 3 added the other RFQ
3321
- * methods below; 2 was the released shape — swaps, scan cursor, markets,
3322
- * with `preimageSaltHex` on the swap record — so an implementor built
3323
- * against any of them cannot satisfy this one silently. */
3324
- readonly version: 5;
3325
- /** Insert or replace a swap by id. Store the record whole: `preimageHex`
3326
- * and `preimageSaltHex` both leave the swap unclaimable if a field-mapped
3327
- * backend drops them — the first is the only claim secret of a swap whose
3328
- * signer cannot derive, the second the public input every other static
3329
- * wallet's preimage derives from.
3330
- *
3331
- * Records must be **JSON-safe**: the SQLite and Realm backends serialize
3332
- * the record to JSON, so a `Date` in a consumer-added field comes back a
3333
- * string, a `Set`/`Map` comes back empty, and a `bigint` throws here —
3334
- * none of which happens on IndexedDB's structured clone. `AssetSwap` as
3335
- * declared is JSON-safe; keep added fields that way. */
3336
- saveSwap(swap: AssetSwap): Promise<void>;
3337
- /** All stored swaps, in no particular order — `getAssetSwaps` is the
3338
- * canonical newest-first read. */
3339
- getAllSwaps(): Promise<AssetSwap[]>;
3340
- /**
3341
- * Insert or replace a monitored RFQ swap by `rfqId`.
3342
- *
3343
- * Store the record WHOLE. Every field is a covenant tree parameter or the
3344
- * manager's own state, and a field-mapped backend that drops one round-trips
3345
- * a record whose covenant `rebuildRfqSwap` cannot reproduce — which surfaces
3346
- * as a refund that cannot be signed, long after the write.
3347
- */
3348
- saveRfqSwap(record: RfqSwapRecord): Promise<void>;
3349
- /** One record by key. `undefined` on a miss — retention prunes terminal
3350
- * records, so absence is ordinary and not an error. */
3351
- getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
3352
- /** Every stored RFQ swap record, in no particular order. */
3353
- getAllRfqSwaps(): Promise<RfqSwapRecord[]>;
3354
- /** Drop one, once it is past retention — see `shouldRetainRfqSwap`. */
3355
- removeRfqSwap(rfqId: string): Promise<void>;
3356
- /**
3357
- * Insert or replace a v2 swap record by its quote id.
3358
- *
3359
- * The store the v2 client's `accept()` writes, and the reason this
3360
- * interface is at 5. Separate from `swaps` rather than sharing it: the v1
3361
- * read path drops any row carrying neither `offerHex` nor `paymentHash`
3362
- * (`getAssetSwapsOrThrow`), silently and as corrupt, so a v2 record in that
3363
- * store would be pinned by a v1 predicate — and the two histories are meant
3364
- * to be disjoint for the deprecation window anyway. A v1 reader not seeing
3365
- * v2 rows is the design, asserted in the conformance suite rather than
3366
- * tolerated.
3367
- *
3368
- * Store the record WHOLE, and note that it is **JSON-safe by declaration**:
3369
- * every amount on it is a canonical decimal string, precisely so the SQLite
3370
- * and Realm backends' `JSON.stringify` and IndexedDB's structured clone
3371
- * agree. A `bigint` reaching here would throw on two backends and
3372
- * round-trip on the third.
3373
- */
3374
- saveSwapRecord(record: SwapRecord): Promise<void>;
3375
- /** One record by quote id. `undefined` on a miss — which is the ordinary
3376
- * answer for a first `accept()`, and what makes it idempotent. */
3377
- getSwapRecord(id: string): Promise<SwapRecord | undefined>;
3378
- /** Every stored v2 record, in no particular order. */
3379
- getAllSwapRecords(): Promise<SwapRecord[]>;
3380
- /** Drop one, once it is past retention. */
3381
- removeSwapRecord(id: string): Promise<void>;
3382
- /**
3383
- * Sent txids already checked for offer packets (see restore.ts).
3384
- *
3385
- * **Shared across both record families, deliberately.** This is not
3386
- * record-family data — it marks txids of transactions a scan has answered,
3387
- * whatever family a later record belongs to — and both families walk the
3388
- * same sent-txid set during the deprecation window. Two cursors would have
3389
- * each side re-walking deposits the other already answered.
3390
- */
3391
- getScannedTxids(): Promise<Set<string>>;
3392
- markTxidsScanned(txids: Iterable<string>): Promise<void>;
3393
- /** Cached registry markets, or undefined on a miss. Shared across both
3394
- * record families for the reason the cursor is: the key is network-and-
3395
- * registry, not a store, and two caches would serve two staleness clocks
3396
- * for one registry. */
3397
- getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
3398
- saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
3399
- clear(): Promise<void>;
3400
- }
3401
- declare class InMemoryAssetSwapRepository implements AssetSwapRepository {
3402
- readonly version: 5;
3403
- private readonly swaps;
3404
- private readonly records;
3405
- private readonly rfqSwaps;
3406
- private readonly scanned;
3407
- private readonly markets;
3408
- saveSwap(swap: AssetSwap): Promise<void>;
3409
- getAllSwaps(): Promise<AssetSwap[]>;
3410
- saveRfqSwap(record: RfqSwapRecord): Promise<void>;
3411
- getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
3412
- getAllRfqSwaps(): Promise<RfqSwapRecord[]>;
3413
- removeRfqSwap(rfqId: string): Promise<void>;
3414
- saveSwapRecord(record: SwapRecord): Promise<void>;
3415
- getSwapRecord(id: string): Promise<SwapRecord | undefined>;
3416
- getAllSwapRecords(): Promise<SwapRecord[]>;
3417
- removeSwapRecord(id: string): Promise<void>;
3418
- getScannedTxids(): Promise<Set<string>>;
3419
- markTxidsScanned(txids: Iterable<string>): Promise<void>;
3420
- getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
3421
- saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
3422
- clear(): Promise<void>;
3423
- [Symbol.asyncDispose](): Promise<void>;
3424
- }
3425
-
3426
- export { type AtomicDecimal as $, type AssetSwapRepository as A, type AssetSwapStatus as B, type Corridor as C, type Route as D, type AssetSwap as E, type MarketsCacheEntry as F, ACTIVITY_TOKEN as G, ARKADE_ASSET_NAMESPACE as H, type Instrument as I, Amount as J, AmountFormatError as K, type LockupSpendIndexer as L, type MarketBackend as M, type NetworkRef as N, type Outcome as O, type Pubkey as P, type QuoteInput as Q, type RfqSwapManagerCallbacks as R, type SwapOperator as S, type AmountRefusal as T, type Unsubscribe as U, AssetIdError as V, type AssetIdRefusal as W, type AssetNamespace as X, type AssetOn as Y, type AssetPart as Z, type AssetScale as _, type RfqSwapActionName as a, toRfqAmountSide as a$, type AuctionMarketRef as a0, type AuctionProvenance as a1, BITCOIN_RAILS as a2, BTC_ASSET_PART as a3, type BitcoinRail as a4, CORRIDORS as a5, CORRIDOR_PASS as a6, type CorridorKind as a7, type DepositArtifact as a8, type DisplayDecimal as a9, decodeRfqAmount as aA, encodeRfqAmount as aB, familyOfSwapId as aC, formatAssetId as aD, fromAtomicDecimal as aE, fromRfqAmountSide as aF, fundsFromWallet as aG, instrumentOf as aH, isAssetId as aI, isAtomicDecimal as aJ, isNetworkRef as aK, issuanceOf as aL, legOf as aM, offerOutcome as aN, parseAssetId as aO, quoteIdOfSwapId as aP, railOf as aQ, railOfCorridor as aR, readsChain as aS, recordArtifact as aT, recordEndpoint as aU, recordInstrument as aV, recordLeg as aW, recordOutcome as aX, sameAsset as aY, swapOf as aZ, toAtomicDecimal as a_, type Endpoint as aa, type Ep as ab, type Hex as ac, InMemoryAssetSwapRepository as ad, LOCKUP_OWNER as ae, OFFER_SWAP_ID_PREFIX as af, type ParsedAssetId as ag, type QuoteLeg as ah, RAILS as ai, RFQ_SWAP_ID_PREFIX as aj, type RailOf as ak, type RawState as al, type RecordedArtifact as am, type RecordedEndpoint as an, type RecordedInstrument as ao, type RecordedLeg as ap, type RfqAmountSide as aq, type SwapRecordCommon as ar, arkadeAsset as as, artifactOf as at, assetPartOf as au, assetSwapIdOf as av, bitcoinNetworkOf as aw, btcOn as ax, corridorOfRail as ay, corridorOutcome as az, type AssetId as b, toSafeNumber as b0, type SwapSecretsProjection as b1, type RfqSwapState as b2, type RefundIndexer as b3, type RfqSwap as b4, type ArkadeRefundResult as b5, type LockupVtxo as b6, type AvailableRfqSwapManagerCallbacks as b7, BTC_ASSET_ID as b8, type LightningReceiveSwap as b9, findLockupVtxos as bA, getAssetSwaps as bB, isRfqSwapTerminal as bC, isRfqTerminal as bD, nextOnchainAction as bE, normalizeRfqSwapRecord as bF, preimageForSwapRecord as bG, pushRefundWithoutReceiver as bH, readLockupFate as bI, rebuildRfqSwap as bJ, refundIfUnresolved as bK, rfqSwapOriginOf as bL, shouldRetainRfqSwap as bM, swapSecretsToRecord as bN, updateAssetSwap as bO, updateRfqSwapRecord as bP, type LightningSendSwap as ba, type LockupFate as bb, LockupNeedsRecoveryError as bc, type LockupParams as bd, type LockupSpend as be, type OnchainSendAction as bf, type OnchainSendSwap as bg, type PersistableRfqSwap as bh, type PreimageBlockedReason as bi, PreimageNotRecoverableError as bj, RFQ_SWAP_RETENTION_SECONDS as bk, type RefundOutcome as bl, type RfqRestoreFailure as bm, type RfqRestoreOptions as bn, type RfqRestoreResult as bo, type RfqSwapLockup as bp, RfqSwapManager as bq, type RfqSwapManagerConfig as br, type RfqSwapManagerDeps as bs, type RfqSwapManagerEvents as bt, type RfqSwapOrigin as bu, RfqSwapOriginRequired as bv, type RfqSwapOutcome as bw, addAssetSwap as bx, awaitRfqResolution as by, createRfqSwapRecord as bz, type SnapshotRef as c, type CardMarketRef as d, type MarketRef as e, type AssetRef as f, type AmountOn as g, type Swap as h, type CorridorId as i, type Artifact as j, type Quote as k, type RankedBid as l, type SwapUpdate as m, type SwapRecord as n, type QuoteId as o, type SwapContractRegistry as p, type ResolvedEndpoint as q, type PinnedAmount as r, type Rail as s, type AssetSwapId as t, type SwapFamily as u, type RouteResolution as v, type RfqSwapRecordStore as w, type CorridorSwapRecord as x, type OfferSwapRecord as y, type RfqSwapRecord as z };