@arkade-os/swap 0.1.0-rc.13 → 0.1.0-rc.15

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