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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +52 -2
  2. package/dist/advanced.cjs +8376 -0
  3. package/dist/advanced.d.cts +550 -0
  4. package/dist/advanced.d.ts +550 -0
  5. package/dist/advanced.js +451 -0
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-HUQQVBC4.js +4262 -0
  8. package/dist/{chunk-EOYGUCDM.js → chunk-ITFCQWPG.js} +755 -1382
  9. package/dist/chunk-PVB7EBAM.js +2517 -0
  10. package/dist/errors-C3h8ANmE.d.ts +1560 -0
  11. package/dist/errors-hm7aqnRM.d.cts +1560 -0
  12. package/dist/index.cjs +4861 -3988
  13. package/dist/index.d.cts +69 -2812
  14. package/dist/index.d.ts +69 -2812
  15. package/dist/index.js +179 -3719
  16. package/dist/lockupContract-5r5RlgOJ.d.cts +137 -0
  17. package/dist/lockupContract-5r5RlgOJ.d.ts +137 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +249 -591
  20. package/dist/node/index.d.ts +249 -591
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +191 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer-Bd9Yvd8Z.d.ts +261 -0
  27. package/dist/offer-F88rtL_I.d.cts +261 -0
  28. package/dist/protocol.cjs +4086 -3706
  29. package/dist/protocol.d.cts +163 -768
  30. package/dist/protocol.d.ts +163 -768
  31. package/dist/protocol.js +190 -173
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BuYWGAKz.d.cts +2261 -0
  41. package/dist/repository-DYnRLPt-.d.ts +2261 -0
  42. package/dist/rfq-60PGpQ_x.d.cts +950 -0
  43. package/dist/rfq-60PGpQ_x.d.ts +950 -0
  44. package/dist/watch-BTyiBLSd.d.ts +74 -0
  45. package/dist/watch-M_KY-5ho.d.cts +74 -0
  46. package/package.json +20 -10
  47. package/dist/chunk-LYCMM3VB.js +0 -1357
  48. package/dist/chunk-U7VWWTL6.js +0 -66
  49. package/dist/repository-_zU9_pM3.d.cts +0 -3426
  50. package/dist/repository-kO95noyv.d.ts +0 -3426
  51. package/dist/rfq-DdBV4JO5.d.cts +0 -1097
  52. package/dist/rfq-DdBV4JO5.d.ts +0 -1097
  53. package/dist/watch-CQqvwgwY.d.cts +0 -96
  54. package/dist/watch-wMbmfN4p.d.ts +0 -96
@@ -1,67 +1,40 @@
1
1
  import { SQLExecutor } from '@arkade-os/sdk/repositories/sqlite';
2
- import { Corridor as Corridor$1, DiscoveredMarket } from '@arkade-os/solver-discovery';
3
- import { VHTLC, NetworkName } from '@arkade-os/sdk';
2
+ import { DiscoveredMarket } from '@arkade-os/solver-discovery';
3
+ import { VHTLC, NetworkName, PageRequest, PageResult } from '@arkade-os/sdk';
4
4
 
5
5
  /**
6
- * The platform's per-user configuration directory.
7
- *
8
- * The three conventions, in the order each platform expects:
9
- *
10
- * - Linux and the BSDs follow the XDG Base Directory spec — `$XDG_CONFIG_HOME`
11
- * when set to an absolute path, else `~/.config`. A relative value is
12
- * ignored, which the spec requires rather than suggests.
13
- * - macOS uses `~/Library/Application Support`.
14
- * - Windows uses `%APPDATA%`, falling back to the roaming path under the home
15
- * directory when the variable is missing — as it is in some service contexts.
6
+ * The platform's per-user configuration directory: `%APPDATA%` on Windows (falling back to the
7
+ * roaming path, as the variable is missing in some service contexts), `~/Library/Application
8
+ * Support` on macOS, else XDG (`$XDG_CONFIG_HOME` if absolute, else `~/.config`).
16
9
  */
17
10
  declare const configDir: (env?: NodeJS.ProcessEnv) => string;
18
11
  /**
19
- * The default database path for one network.
20
- *
21
- * Returned rather than created: opening it is what creates the directory, and a
22
- * caller that only wants to know where the file would be — to report it, to
23
- * back it up, to delete it — should not have to make one as a side effect.
12
+ * The default database path for one network. Returned, not created, so callers that only report,
13
+ * back up or delete it don't make a directory as a side effect.
24
14
  */
25
15
  declare const swapDatabasePath: (network: string, env?: NodeJS.ProcessEnv) => string;
26
16
 
27
17
  /** @deprecated Use `Outcome`. Moved off the package root to `@arkade-os/swap/protocol`. */
28
18
  type AssetSwapStatus = "pending" | "cancelling" | "fulfilled" | "cancelled" | "recoverable" | "awaiting_fill" | "claimable" | "claimed" | "refunded_l1";
29
19
  /**
30
- * The record fields a wallet-provisioned secret becomes — what
31
- * {@link swapSecretsToRecord} emits, and what every record type carrying swap
32
- * secrets embeds.
33
- *
34
- * A named type rather than four fields restated per record: the mapper and the
35
- * records it feeds must agree exactly, and a record that silently omits one of
36
- * these round-trips a swap whose preimage cannot be re-derived. Embedding makes
37
- * the omission a compile error instead.
38
- *
39
- * **Only `preimageHex` is secret.** `signingDescriptor` and `preimageSaltHex`
40
- * are public derivation inputs — they must survive a field-mapped backend, but
41
- * they leak nothing without the seed.
42
- *
43
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
20
+ * The record fields a wallet-provisioned secret becomes; every secret-carrying record embeds it, so
21
+ * omitting one (an unrecoverable preimage) is a compile error. **Only `preimageHex` is secret**; the
22
+ * descriptor and salt are public derivation inputs that leak nothing without the seed.
44
23
  */
45
24
  interface SwapSecretsProjection {
46
- /**
47
- * The wallet descriptor this swap's sender key comes from — a fresh HD
48
- * child, or a static wallet's `tr(pubkey)`. Public — the signer
49
- * re-derives from the wallet, so the record carries no key material.
50
- */
25
+ /** The wallet descriptor this swap's sender key comes from (a fresh HD child, or a static
26
+ * wallet's `tr(pubkey)`). Public; the record carries no key material. */
51
27
  signingDescriptor?: string;
52
28
  /** P, hex, when it cannot be re-derived from the seed at all: the user
53
29
  * supplied it, or the signer cannot sign deterministically. The swap's only
54
30
  * claim secret when present. */
55
31
  preimageHex?: string;
56
- /**
57
- * The salt P derives from, hex, on the salted arm — what a static wallet
58
- * gets instead of storing P. **Public**, and unlike every other field here
59
- * it is minted per swap: it is what stops one repeating key from handing
60
- * every swap the same preimage.
61
- */
32
+ /** The salt P derives from, hex — what a static wallet stores instead of P. **Public**, and minted
33
+ * per swap: it stops one repeating key from giving every swap the same preimage. */
62
34
  preimageSaltHex?: string;
63
35
  }
64
- /** @deprecated Use `Swap`, projected by `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`. */
36
+ /** The row {@link AssetSwapRepository} stores. A root export because custom storage backends are
37
+ * written against it. Not the v2 client's record (that is `SwapRecord`, projected as `Swap`). */
65
38
  interface AssetSwap extends SwapSecretsProjection {
66
39
  /** Funding txid — the swap's identity. */
67
40
  id: string;
@@ -94,7 +67,6 @@ interface AssetSwap extends SwapSecretsProjection {
94
67
  l1Txid?: string;
95
68
  }
96
69
 
97
- /** @deprecated Internal to the onchain corridor; no replacement. Moved off the package root to `@arkade-os/swap/protocol`. */
98
70
  interface OnchainHtlc {
99
71
  address: string;
100
72
  /** `0x5120…` — the P2TR output script. */
@@ -113,24 +85,17 @@ interface OnchainHtlc {
113
85
  }
114
86
 
115
87
  /**
116
- * Where a monitored RFQ swap stands, and which of those states end it.
117
- *
118
- * Its own module rather than a corner of `swapManager.ts` because the
119
- * dependency runs the other way: the record layer decides retention from
120
- * {@link isRfqSwapTerminal}, and the manager persists through the record
121
- * layer. With the vocabulary here, neither has to import the other at runtime.
122
- * `swapManager.ts` re-exports all three names, so nothing about the public
123
- * surface moved.
88
+ * Where a monitored RFQ swap stands, and which of those states end it. Its own module so the
89
+ * record layer (retention via {@link isRfqSwapTerminal}) and the manager need not import each
90
+ * other at runtime; `swapManager.ts` re-exports all three names.
124
91
  */
125
92
  /**
126
- * Where a monitored swap stands.
127
- *
128
- * `claimable` and `claimed` are the states of a swap the TRADER has something
129
- * to claim on: the L1 fill on an onchain send, and the solver-funded lockup on
130
- * a receive. Only `lightning_send` has neither — there the solver claims the
131
- * lockup, and the trader's only move is the refund.
93
+ * Where a monitored swap stands; the vocabulary of `CorridorSwapRecord.state`. `Outcome`, from
94
+ * `client.onUpdate()`, is the client-level projection over it.
132
95
  *
133
- * @deprecated Use `Outcome`, delivered by `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
96
+ * `claimable`/`claimed` apply when the TRADER has something to claim: the L1 fill on an onchain
97
+ * send, the solver-funded lockup on a receive. `lightning_send` has neither; the trader's only
98
+ * move there is the refund.
134
99
  */
135
100
  type RfqSwapState =
136
101
  /** Live; nothing actionable yet. On a receive leg this covers the whole
@@ -141,71 +106,45 @@ type RfqSwapState =
141
106
  * least `expectedAmount` on a receive. */
142
107
  | "claimable"
143
108
  /**
144
- * The trader's claim has been made — its L1 broadcast on an onchain send,
145
- * its Arkade submission on a receive.
146
- *
147
- * **On a receive this is a local belief and not a chain fact**, which is
148
- * why it is not terminal: `settled` is the chain's answer, and `refunded`
149
- * is still reachable from here if the claim never lands and the solver
150
- * takes the lockup back.
109
+ * The trader's claim has been made (L1 broadcast on an onchain send, Arkade submission on a
110
+ * receive). **On a receive this is a local belief, not a chain fact**, hence not terminal:
111
+ * `refunded` is still reachable if the claim never lands.
151
112
  */
152
113
  | "claimed"
153
114
  /**
154
- * This wallet will not act, and only the counterparty can change that.
115
+ * This wallet will not act, and only the counterparty can change that
116
+ * (`RfqSwapCommon.blockedReason` says why).
155
117
  *
156
- * On a send leg: the Arkade refund cannot be pushed from here — no secrets
157
- * on the record, a descriptor from another seed, or nothing wired to act —
158
- * so the lockup comes back only if the counterparty claims it or the wallet
159
- * that can sign it is restored. On a receive leg: the trader holds no
160
- * refund at all, so this is a lockup that cannot be claimed — funded for
161
- * less than the swap agreed (publishing `P` for it is the whole attack
162
- * `LockupAmountMismatchError` exists to refuse), or one whose claim window
163
- * shut unclaimed. `RfqSwapCommon.blockedReason` says which.
118
+ * Send leg: the Arkade refund cannot be pushed from here (no secrets, foreign descriptor, or
119
+ * nothing wired). Receive leg: the lockup cannot be claimed — underfunded (publishing `P`
120
+ * for it is the attack `LockupAmountMismatchError` refuses) or its claim window shut.
164
121
  *
165
- * **Not terminal, and not a dead end.** The money is still at the lockup,
166
- * so the counterparty's move is still observable and still ends the swap;
167
- * and the refusal is re-checked every pass, so restoring the right wallet,
168
- * wiring the callbacks, or the solver topping the lockup up returns the
169
- * swap to `pending` and resumes the normal drive. For an onchain-send swap
170
- * it says nothing about the L1 half, which keeps being driven and claimed.
122
+ * **Not terminal.** The money is still at the lockup and the refusal is re-checked every
123
+ * pass, so fixing the cause returns the swap to `pending`. On an onchain send the L1 half
124
+ * keeps being driven regardless.
171
125
  */
172
126
  | "needs_counterparty"
173
127
  /**
174
- * Terminal: the lockup was spent by a hash-verified claim. Read off chain,
175
- * never reported.
176
- *
177
- * On a send leg that claim is the counterparty's, and it is proof the
178
- * counterparty completed its side. On a receive leg it is the TRADER's own
179
- * — matched by the hash and not by our txid, so a claim that lands without
180
- * us still counts (see `RfqSwapManager`).
128
+ * Terminal: the lockup was spent by a hash-verified claim, read off chain, never reported.
129
+ * On a send leg it is the counterparty's claim; on a receive leg the TRADER's own, matched by
130
+ * hash rather than our txid so a claim that lands without us still counts.
181
131
  */
182
132
  | "settled"
183
133
  /**
184
- * Terminal: the lockup was spent by something other than a claim.
185
- *
186
- * On a send leg that is the money coming back, by the solver's hand or the
187
- * trader's. **On a receive leg it is a LOSS**: the lockup was the solver's
188
- * money, every non-claim leaf is the solver's, and a swap that ends here
189
- * ended with the trader's incoming payment never arriving. It is also where
190
- * a receive swap ends when its window closes with nothing left to observe —
191
- * see `RfqSwapManager`.
134
+ * Terminal: the lockup was spent by something other than a claim. On a send leg that is the
135
+ * money coming back. **On a receive leg it is a LOSS**: every non-claim leaf is the
136
+ * solver's. Also where a receive swap ends when its window closes with nothing to observe.
192
137
  */
193
138
  | "refunded"
194
139
  /** Terminal: an action failed and its window closed. */
195
140
  | "failed";
196
141
 
197
142
  /**
198
- * What the manager needs to register a swap's lockup with the wallet, so the
199
- * indexer pushes its funding and its spend instead of being asked every few
200
- * seconds.
143
+ * What the manager needs to register a swap's lockup with the wallet, so the indexer
144
+ * pushes its funding and spend.
201
145
  *
202
- * Both fields are things the caller already holds. `script` is the very object
203
- * `pushRefundWithoutReceiver` and `pushClaim` take, so a caller wired to act has
204
- * it in hand; `address` is the request entrypoint's own return value. The
205
- * address is taken rather than re-derived on purpose — the row's address must be
206
- * the one that was actually funded, and a local re-derivation would silently use
207
- * the SDK's default network, which is the exact bug `registerOfferContract`
208
- * guards against.
146
+ * `address` is taken, not re-derived: it must be the one actually funded, and a local
147
+ * re-derivation would silently use the SDK's default network.
209
148
  *
210
149
  * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
211
150
  */
@@ -219,38 +158,23 @@ interface RfqSwapCommon {
219
158
  /** The negotiation id — this record's identity. */
220
159
  rfqId: string;
221
160
  state: RfqSwapState;
222
- /** The Arkade lockup's scriptPubKey — `swapPkScript` from any of the four
223
- * request entrypoints. This is what the manager watches to decide the swap:
224
- * it is the only handle on the covenant whose spend witness says whether
225
- * the swap settled or came back. */
161
+ /** The Arkade lockup's scriptPubKey (`swapPkScript` from the request entrypoint): the
162
+ * only handle on the covenant whose spend witness decides the swap. */
226
163
  lockupPkScript: Uint8Array;
227
- /** The covenant behind {@link lockupPkScript}, when the caller wants the
228
- * lockup registered with a contract manager. Optional: without it the
229
- * manager still watches the swap on its timer, it just cannot subscribe.
230
- * See {@link RfqSwapManagerDeps.contracts}. */
164
+ /** The covenant behind {@link lockupPkScript}. Without it the manager still polls the
165
+ * swap, it just cannot subscribe; see {@link RfqSwapManagerDeps.contracts}. */
231
166
  lockup?: RfqSwapLockup;
232
167
  /**
233
- * `sha256(P)`, hex — the quote's `payment_hash`. The claim leaf can only
234
- * be spent by revealing a value that hashes to this, which is what makes a
235
- * settlement provable rather than reported. For an onchain send this is
236
- * the SAME hash the L1 `htlc` carries: one `P` unlocks both legs.
237
- *
238
- * True of the three corridors that exist today and only of them: a hashlock
239
- * belongs to a CORRIDOR, and a banco-style one settles without any. The
240
- * stored record already says so — the hash lives in `profile.hashlock`, not
241
- * on `RfqSwapRecord` — and this field follows onto the per-corridor swap
242
- * types when the first such corridor lands. Do not read the current shape as
243
- * settled.
168
+ * `sha256(P)`, hex — the quote's `payment_hash`. The claim leaf is spendable only by
169
+ * revealing its preimage, which makes settlement provable. For an onchain send the L1
170
+ * `htlc` carries the SAME hash. Not final: a hashlock belongs to a corridor (the stored
171
+ * record keeps it in `profile.hashlock`), and hashlock-free corridors may follow.
244
172
  */
245
173
  paymentHash: string;
246
174
  /**
247
- * `refund_locktime` from the quote, unix seconds.
248
- *
249
- * Whose deadline it is inverts with the direction, and so does what to do
250
- * about it. On a send leg it is the TRADER's: the lockup is the trader's
251
- * money and this gates the refund that takes it back, so it is a moment to
252
- * act AFTER. On a receive leg it is the SOLVER's: the trader has no refund
253
- * leaf at all, and this is the moment to have claimed BEFORE.
175
+ * `refund_locktime` from the quote, unix seconds. On a send leg it is the TRADER's:
176
+ * refund AFTER it. On a receive leg it is the SOLVER's: the trader must have claimed
177
+ * BEFORE it.
254
178
  */
255
179
  refundLocktime: number;
256
180
  createdAt: number;
@@ -258,53 +182,35 @@ interface RfqSwapCommon {
258
182
  /** Set once the trader's own `refundWithoutReceiver` push landed. */
259
183
  refundTxid?: string;
260
184
  /**
261
- * The ark transactions that SPENT the lockup, stamped from the chain read
262
- * that ended the swap — `LockupFate.spends`, whichever verdict it reached.
263
- *
264
- * The counterparty's move, on every leg but one: a solver claim on a send,
265
- * a solver reclaim on a receive, and — the exception — the trader's own
266
- * claim when a receive settles. What they have in common is that no local
267
- * action produced them, so nothing else on this record can name them:
268
- * {@link refundTxid} names only a push this wallet made, and
269
- * `claimTxid` only a submission it made.
270
- *
271
- * Stamped so a terminal record answers "which transaction ended this" from
272
- * storage. Without it the only source is another read of the lockup — a
273
- * network round trip per terminal swap, which is what activity correlation
274
- * has to pay on the offline-first path where it is least affordable.
275
- *
276
- * Absent when the swap ended without a chain verdict, or when the indexer
277
- * named the checkpoint but not the ark transaction — the same `txid`
278
- * `LockupSpend` declares optional, for the same reason.
185
+ * The ark transactions that SPENT the lockup, from the chain read that ended the swap
186
+ * (`LockupFate.spends`) — moves no local action produced, so a terminal record can
187
+ * name them without another network read. Absent without a chain verdict, or when the
188
+ * indexer named only the checkpoint.
279
189
  */
280
190
  lockupSpendTxids?: string[];
191
+ /**
192
+ * `P`, hex — the preimage the solver revealed to claim the lockup. Lightning sends
193
+ * only (the payee mints `P`). A public settlement receipt, not a claim secret;
194
+ * `readLockupFate` verifies it against {@link paymentHash} before it is stamped.
195
+ */
196
+ settlementPreimageHex?: string;
281
197
  /** Why `state` is `failed`. */
282
198
  failure?: string;
283
199
  /**
284
- * Last local claim error while the receive swap is still retryable.
285
- *
286
- * Distinct from terminal `failure`: this records a claim attempt that failed
287
- * before the window closed. If the window later closes without a submitted
288
- * claim, it becomes the terminal failure reason.
200
+ * Last local claim error while the receive swap is still retryable. Becomes the
201
+ * terminal `failure` if the window closes without a submitted claim.
289
202
  */
290
203
  claimFailure?: string;
291
204
  /** Why `state` is `needs_counterparty`. Distinct from {@link failure},
292
205
  * which means an action was attempted and did not work. */
293
206
  blockedReason?: string;
294
207
  }
295
- /** `arkade:BTC->lightning:BTC`. Nothing for the trader to claim: the solver
296
- * claims the lockup with the preimage it learns by paying the invoice — which
297
- * is exactly why that spend's witness is proof the payment landed.
298
- *
299
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
300
- */
208
+ /** `arkade:BTC->lightning:BTC`. The solver claims the lockup with the preimage it learns
209
+ * by paying, so that spend's witness proves the payment landed. */
301
210
  interface LightningSendSwap extends RfqSwapCommon {
302
211
  kind: "lightning_send";
303
212
  }
304
- /** `arkade:BTC->onchain:BTC`. Carries the L1 half the trader must claim.
305
- *
306
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
307
- */
213
+ /** `arkade:BTC->onchain:BTC`. Carries the L1 half the trader must claim. */
308
214
  interface OnchainSendSwap extends RfqSwapCommon {
309
215
  kind: "onchain_send";
310
216
  /** The locally derived HTLC from `requestOnchainSend` — the manager reads
@@ -312,6 +218,9 @@ interface OnchainSendSwap extends RfqSwapCommon {
312
218
  htlc: OnchainHtlc;
313
219
  /** `profile.min_confirmations` from the quote. */
314
220
  minConfirmations: number;
221
+ /** The quote's `to_amount`, captured at REQUEST time: read at claim time it
222
+ * would be whatever the solver funded. */
223
+ expectedAmount: number;
315
224
  /** Where {@link RfqSwapManagerCallbacks.claimOnchain} pays; optional only
316
225
  * so records predating its profile slot still restore. */
317
226
  payoutPkScript?: Uint8Array;
@@ -325,37 +234,23 @@ interface OnchainSendSwap extends RfqSwapCommon {
325
234
  claimTxid?: string;
326
235
  }
327
236
  /**
328
- * `lightning:BTC->arkade:BTC`. The inverted leg: the SOLVER funds the lockup
329
- * and the TRADER claims it, and that claim is what publishes `P` and lets the
330
- * solver settle the payer's held Lightning HTLC.
237
+ * `lightning:BTC->arkade:BTC`. The SOLVER funds the lockup and the TRADER claims it,
238
+ * publishing `P` so the solver can settle the payer's held Lightning HTLC.
331
239
  *
332
- * Two consequences shape how this record is driven, both of them absent from
333
- * the send legs:
334
- *
335
- * - **There is no trader-side refund.** Every non-claim leaf of this covenant
336
- * is the solver's, so the manager never calls
337
- * {@link RfqSwapManagerCallbacks.refundArkade} for one of these. A swap that
338
- * is not claimed is simply lost — the solver reclaims at
339
- * {@link RfqSwapCommon.refundLocktime} and the payer is refunded when the
340
- * held HTLC lapses.
341
- * - **The claim is the whole swap, and it is on a deadline.** The trader must
342
- * be online for it: covclaimd cannot claim this covenant today, so the claim
343
- * packet's offline path does not run.
344
- *
345
- * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
240
+ * - **No trader-side refund.** Every non-claim leaf is the solver's; an unclaimed swap is
241
+ * lost when the solver reclaims at {@link RfqSwapCommon.refundLocktime}.
242
+ * - **The claim is the whole swap, on a deadline**, and the trader must be online:
243
+ * covclaimd cannot claim this covenant today.
346
244
  */
347
245
  interface LightningReceiveSwap extends RfqSwapCommon {
348
246
  kind: "lightning_receive";
349
247
  /**
350
- * What the lockup must carry — the quote's `to_amount`, captured at REQUEST
351
- * time and persisted with the record.
248
+ * What the lockup must carry — the quote's `to_amount`, captured at REQUEST time.
352
249
  *
353
- * **Not re-derivable, and not optional.** Captured at claim time it would
354
- * be whatever the solver funded, which is the dust-funding attack rather
355
- * than a check on it. A record that reaches the manager without a finite
356
- * value here is reported `needs_counterparty` and never claimed: a
357
- * comparison against `undefined` or `NaN` is false, so an unusable
358
- * comparand does not fail the value gate, it deletes it.
250
+ * **Not re-derivable, not optional.** Read at claim time it would be whatever the
251
+ * solver funded (the dust-funding attack). A non-finite value is reported
252
+ * `needs_counterparty` and never claimed: comparing against `undefined`/`NaN` is
253
+ * false, which would delete the value gate rather than fail it.
359
254
  */
360
255
  expectedAmount: number;
361
256
  /** Our Arkade claim's txid, once submitted. Set from the callback's return
@@ -364,88 +259,57 @@ interface LightningReceiveSwap extends RfqSwapCommon {
364
259
  }
365
260
 
366
261
  /**
367
- * The swap kinds this projection covers — all three the manager monitors.
368
- *
369
- * `onchain_send` carries an L1 half nothing else can rebuild. Its Arkade lockup
370
- * has a contract row like the others, but the HTLC is Bitcoin L1, not an Arkade
371
- * contract, so no row exists for it; and `OnchainHtlc` exposes only derived
372
- * values — `address`, `pkScript`, `leaves`, `controlBlocks` — never the
373
- * `claimKey`/`refundKey` `onchainHtlcScript` takes as inputs. So they ride in
374
- * that corridor's {@link RfqSwapOrigin.profile}, and without them a restored
375
- * swap would let its L1 refund window pass unwatched.
376
- *
377
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
262
+ * The swap kinds this projection covers — all three the manager monitors. `onchain_send`'s L1 keys
263
+ * ride in its profile, since no contract row or `OnchainHtlc` field can give them back.
378
264
  */
379
265
  type PersistableRfqSwap = LightningSendSwap | LightningReceiveSwap | OnchainSendSwap;
380
266
  /** The immutable request-time half, and only what EVERY corridor has. Hex for
381
267
  * everything binary, so the record is plain JSON and survives any
382
- * structured-clone backend unchanged.
383
- *
384
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
385
- */
268
+ * structured-clone backend unchanged. */
386
269
  interface RfqSwapOrigin {
387
270
  /**
388
271
  * Which corridor this is. Resolves the handler that owns {@link profile};
389
272
  * see `rfqCorridor.ts`.
390
273
  *
391
- * The manager's own union, not an open string: `RfqSwapManager` branches on
392
- * `kind` to decide what to drive, so a corridor it does not know could be
393
- * persisted and rebuilt here and then never driven — which is the failure
394
- * this whole file is arranged to make impossible.
274
+ * The manager's own union, not an open string: a kind it does not branch on would persist and
275
+ * rebuild here and then never be driven.
395
276
  */
396
277
  kind: PersistableRfqSwap["kind"];
397
278
  /**
398
- * The Arkade address that was funded.
399
- *
400
- * Both the swap's handle on its covenant — {@link lockupContractParams}
401
- * looks the contract row up by the script it decodes to — and, being taken
402
- * from the entry point rather than re-derived, the check that the
403
- * parameters a caller supplies belong to THIS swap.
279
+ * The Arkade address that was funded: the handle {@link lockupContractParams} looks the row up
280
+ * by, and, being taken from the entry point, the check that supplied params are THIS swap's.
404
281
  */
405
282
  lockupAddress: string;
406
283
  /**
407
284
  * The corridor's own half, as plain JSON — written by the caller from the
408
285
  * request result, kept current by the handler's `project`.
409
286
  *
410
- * Opaque here on purpose. Nothing in this file, the repository or the
411
- * IndexedDB store interprets it, which is what lets a new corridor ship
412
- * without touching any of them. It carries the corridor's keys as well as
413
- * its state: `signer` (which wallet key signs this leg) and, on a corridor
414
- * locked to a preimage, `hashlock` — see `rfqProfileParts.ts`, and write
415
- * both with `rfqSecretsProfile` rather than by hand.
416
- *
417
- * Not a consumer scratchpad: every write merges it as `{ ...profile,
418
- * ...handler.project(swap) }`, so a consumer key colliding with one the
419
- * handler projects is silently overwritten on every pass.
287
+ * Opaque here, so a new corridor ships without touching this file or the stores. Carries the
288
+ * corridor's keys (`signer`, and `hashlock` with the `sha256(P)` the covenant cannot give
289
+ * back); write them with `rfqSecretsProfile`. Not a consumer scratchpad: every write merges
290
+ * `handler.project(swap)` over it.
420
291
  */
421
292
  profile: Record<string, unknown>;
422
293
  /** Consumer display metadata. The rebuild ignores it — `RfqSwapCommon`
423
294
  * carries no amount of its own. */
424
295
  amount?: number;
425
296
  /**
426
- * The ark transaction that funded {@link lockupAddress}.
427
- *
428
- * Origin, not manager state: the caller broadcasts the funding and knows
429
- * its txid, while the manager watches the lockup by script and never
430
- * learns it. So it is written once at record creation, like {@link amount},
431
- * and no corridor `project` emits it.
297
+ * The ark transaction that funded {@link lockupAddress}. Origin, not manager state: only the
298
+ * caller that broadcast it knows it, so it is written once and no `project` emits it.
432
299
  */
433
300
  fundingTxid?: string;
434
301
  }
435
- /** The stored record: the origin plus the manager's mutable state.
436
- *
437
- * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
438
- */
302
+ /** The stored record: the origin plus the manager's mutable state. */
439
303
  interface RfqSwapRecord extends RfqSwapOrigin {
440
304
  rfqId: string;
441
305
  state: RfqSwapState;
442
306
  createdAt: number;
443
307
  updatedAt: number;
444
308
  refundTxid?: string;
445
- /** The ark transactions that spent the lockup, stamped by the manager from
446
- * the chain read that ended the swap. See
447
- * `RfqSwapCommon.lockupSpendTxids`. */
309
+ /** See `RfqSwapCommon.lockupSpendTxids`. */
448
310
  lockupSpendTxids?: string[];
311
+ /** See `RfqSwapCommon.settlementPreimageHex`. */
312
+ settlementPreimageHex?: string;
449
313
  failure?: string;
450
314
  /** Last local receive-claim error while the swap is still retryable. */
451
315
  claimFailure?: string;
@@ -462,33 +326,18 @@ type AtomicDecimal = string & {
462
326
  * Asset identity for the v2 client: CAIP-19 with the rail as the CAIP-2
463
327
  * namespace — `<rail>:<network>/<asset-ns>:<reference>`.
464
328
  *
465
- * The rail is the namespace rather than the settlement chain because sameness
466
- * across rails is then a comparison on the asset part instead of a shared
467
- * string: `arkade:bitcoin/slip44:0` and `bitcoin:bitcoin/slip44:0` are one BTC
468
- * on two rails, and nothing has to agree on a single id for them. Arkade has no
469
- * CAIP-2 namespace and no bitcoin-chain identity to nest under, so
470
- * `bip122:…/arkade:…` would assert a relationship it does not have.
471
- *
472
- * These ids parse under CAIP-19 and resolve under no published namespace spec:
473
- * `arkade`, `bitcoin` and `bolt11` are registered in no CASA registry. That is
474
- * the price of naming rails instead of chains, and it costs nothing here — this
475
- * module is the grammar, and what an id *means* is the alias layer's job.
329
+ * Rail, not settlement chain, as namespace: cross-rail sameness becomes a comparison on the asset
330
+ * part (`arkade:bitcoin/slip44:0` vs `bitcoin:bitcoin/slip44:0`), and `bip122:…/arkade:…` would
331
+ * assert a relationship Arkade does not have. These ids parse under CAIP-19 but `arkade`,
332
+ * `bitcoin` and `bolt11` are in no CASA registry; meaning is the alias layer's job.
476
333
  */
477
334
 
478
335
  /**
479
- * A CAIP-2 namespace this client can spell. Closed rather than open to the
480
- * CAIP-2 character class, so a rail nobody implements is a parse failure here
481
- * rather than a lookup miss three layers down.
336
+ * A CAIP-2 namespace this client can spell. Closed, so an unimplemented rail fails at parse.
482
337
  *
483
- * `bolt11` is lightning: CAIP-2 caps a namespace at eight characters, which
484
- * `lightning` overruns, and floors it at three, which `ln` misses. It names the
485
- * instrument the rail carries today; BOLT12 is a separate corridor when it
486
- * ships.
487
- *
488
- * `eip155` is grammar and nothing else. §9's EVM corridor is deferred, and §9
489
- * exists to prove the seams hold, so its own examples have to parse; the
490
- * refusal belongs where a route is chosen, not where a string is read, and the
491
- * alias layer is where it happens.
338
+ * `bolt11` is lightning: CAIP-2 namespaces are 3-8 chars, which `lightning` and `ln` miss. BOLT12
339
+ * will be a separate corridor. `eip155` is grammar only: the EVM corridor is deferred, and refusal
340
+ * belongs where a route is chosen (the alias layer), not where a string is read.
492
341
  */
493
342
  declare const RAILS: readonly ["arkade", "bitcoin", "bolt11", "eip155"];
494
343
  type Rail = (typeof RAILS)[number];
@@ -496,77 +345,46 @@ type Rail = (typeof RAILS)[number];
496
345
  declare const BITCOIN_RAILS: readonly ["arkade", "bitcoin", "bolt11"];
497
346
  type BitcoinRail = (typeof BITCOIN_RAILS)[number];
498
347
  /**
499
- * The network half of a bitcoin-family chain part: core's own
500
- * {@link NetworkName}, because the wallet is the only source of the network —
501
- * v2 accepts no server URL anywhere — and this is the vocabulary a wallet
502
- * resolves to.
348
+ * The network half of a bitcoin-family chain part: core's own {@link NetworkName}, since the
349
+ * wallet is the only source of the network.
503
350
  *
504
- * It is one wider than discovery's `NETWORKS`, which omits `testnet`. That
505
- * difference belongs to the alias layer and not to the grammar: an asset on
506
- * testnet exists whether or not anyone publishes a market index for it, so
507
- * amputating the identity to match the index would make a network the SDK fully
508
- * supports unnameable.
351
+ * Wider than discovery's `NETWORKS` (which omits `testnet`): an asset on testnet exists whether or
352
+ * not a market index covers it.
509
353
  */
510
354
  type NetworkRef = NetworkName;
511
355
  type BitcoinAssetId<R extends BitcoinRail> = `${R}:${NetworkRef}/${string}:${string}`;
512
356
  /**
513
357
  * A public asset id.
514
358
  *
515
- * A template literal type and not `string`, which is what makes the other three
516
- * asset spellings in this package — core's 68-hex `asset.AssetId#toString()`,
517
- * discovery's `AssetInfo.id`, the RFQ leg's `arkade:BTC` — a compile error in a
518
- * slot that wants a public id, rather than a wrong pair string three layers
519
- * down. The rail parameter carries that further: `AssetId<"arkade">` accepts no
520
- * `bitcoin:` string, which is what makes an endpoint whose corridor and asset
521
- * disagree a compile error (see `route.ts`).
359
+ * A template literal type, so the package's other asset spellings (core's 68-hex id, discovery's
360
+ * `AssetInfo.id`, the RFQ leg's `arkade:BTC`) are compile errors here, and `AssetId<"arkade">`
361
+ * accepts no `bitcoin:` string (see `route.ts`).
522
362
  *
523
- * Deliberately not branded — `client.quote({ give: "arkade:bitcoin/slip44:0" })`
524
- * must stay writable, and the spec's own examples are written that way — so the
525
- * shape is what the type checks and {@link parseAssetId} is the gate for
526
- * everything else. A value out of a record or off the wire is a `string`: parse
527
- * it, never cast it.
363
+ * Deliberately not branded, so `client.quote({ give: "arkade:bitcoin/slip44:0" })` stays writable.
364
+ * A value from a record or the wire is a `string`: parse it with {@link parseAssetId}, never cast.
528
365
  */
529
366
  type AssetId<R extends Rail = Rail> = R extends BitcoinRail ? BitcoinAssetId<R> : `eip155:${number}/${string}:${string}`;
530
367
 
531
368
  /**
532
369
  * The corridor axis, and its bijection with the rail namespaces.
533
370
  *
534
- * One axis, two vocabularies: discovery speaks `arkade | lightning | onchain`
535
- * and an asset id's CAIP-2 namespace is `arkade | bolt11 | bitcoin`. They agree
536
- * on one member of three. Collapsing them was the alternative and it loses
537
- * either way — take the rail names and every market lookup translates on the
538
- * way out to discovery; take the corridor names and `lightning:` overruns
539
- * CAIP-2's eight-character namespace cap.
540
- *
541
- * So both stay, and the disagreement is spent once, here: `Corridor` is
542
- * discovery's type verbatim, {@link railOfCorridor} is total, and `route.ts`
543
- * ties an endpoint's corridor to its asset's rail in the type system so the two
544
- * cannot disagree in a value.
371
+ * Routes speak `arkade | lightning | onchain`; CAIP-2 asset namespaces are `arkade | bolt11 |
372
+ * bitcoin`. Both stay: rail names would make the public route vocabulary protocol-shaped, and
373
+ * `lightning:` overruns CAIP-2's eight-character namespace cap. {@link railOfCorridor} is total, and
374
+ * `route.ts` ties an endpoint's corridor to its asset's rail in the type system.
545
375
  */
546
376
 
547
- /**
548
- * The corridor a leg settles on.
549
- *
550
- * Aliased from discovery rather than re-declared: it is discovery's vocabulary,
551
- * the alias layer has to speak it, and a re-declaration would drift silently
552
- * the day discovery adds a corridor.
553
- */
554
- type Corridor = Corridor$1;
555
- /**
556
- * A corridor id: the three implemented corridors plus §9's EVM chains.
557
- *
558
- * The template arm stays open against the registry's closed enum on purpose —
559
- * which chains a registry lists is a listing decision, not an id-grammar one.
560
- */
377
+ /** The corridor a leg settles on — caller-facing route names, independent of discovery's CAIP rail
378
+ * identifiers. */
379
+ declare const CORRIDORS: readonly ["arkade", "lightning", "onchain"];
380
+ type Corridor = (typeof CORRIDORS)[number];
381
+ /** A corridor id: the three implemented corridors plus EVM chains. The template arm stays open on
382
+ * purpose — which chains a registry lists is a listing decision, not an id-grammar one. */
561
383
  type CorridorId = Corridor | `eip155:${number}`;
562
384
 
563
385
  /**
564
- * The two string aliases the v2 surface is written in.
565
- *
566
- * Aliases rather than branded types: they document what a field carries at the
567
- * places §3.1's `Quote` reads (`lock.hash`, `solver`) without making every
568
- * literal go through a constructor. Core exports neither, so nothing here is a
569
- * duplicate.
386
+ * The two string aliases the v2 surface is written in. Aliases rather than branded types, so
387
+ * literals need no constructor.
570
388
  */
571
389
  /** Lowercase hex, no `0x` prefix — the encoding `@scure/base`'s `hex` emits. */
572
390
  type Hex = string;
@@ -574,30 +392,17 @@ type Hex = string;
574
392
  type Pubkey = Hex;
575
393
 
576
394
  /**
577
- * What a quote is: the order, fully resolved, plus the provenance that says who
578
- * priced it and where that card came from.
395
+ * What a quote is: the order, fully resolved, plus the provenance that says who priced it and
396
+ * where that card came from. Types only — the quote path assembles these, `accept()` consumes
397
+ * them.
579
398
  *
580
- * M1 named these shapes and left them to whichever milestone decided their
581
- * semantics; this is that milestone, so `QuoteId`, `QuoteInput`, `Quote`,
582
- * `MarketRef` and `AuctionProvenance` are declared here rather than beside the
583
- * types they are built out of. Nothing in this module has behaviour — the quote
584
- * path assembles these, `accept()` (M4) consumes them.
585
- *
586
- * The one rule worth restating at the top: a `Quote` is binding terms plus the
587
- * evidence for them. Every field is either something the caller must act on
588
- * (the two obligations, the artifact, the deadline) or something they must be
589
- * able to audit afterwards (the market, the solver, the checks that passed).
590
- * Nothing internal rides along — no covenant, no secret, no transport.
399
+ * A `Quote` is binding terms plus the evidence for them: every field is something the caller must
400
+ * act on or be able to audit. Nothing internal rides along (no covenant, secret or transport).
591
401
  */
592
402
 
593
403
  /**
594
- * A quote's identity, minted by the client at quote time.
595
- *
596
- * Client-minted everywhere, not just where the wire offers no id: a feed-priced
597
- * offer quote has no solver-minted id at all, and `accept()` is idempotent by
598
- * quote id *and only* by quote id (§3.2), so an identity that exists on one
599
- * backend and not the other could not carry that rule. An alias rather than a
600
- * brand, matching `Hex` and `Pubkey` beside it.
404
+ * A quote's identity, minted by the client at quote time on every backend: feed-priced quotes
405
+ * have no solver id, and `accept()` is idempotent by quote id *only* (§3.2).
601
406
  */
602
407
  type QuoteId = string;
603
408
  /** Which backend priced a quote. The card decides it; no client switch does. */
@@ -607,14 +412,11 @@ interface SnapshotRef {
607
412
  /** Unix ms the markets were read from their sources. */
608
413
  readonly fetchedAt: number;
609
414
  /**
610
- * The registry answered in this read, so the cards are registry-served
611
- * rather than replayed out of local storage.
415
+ * The registry answered in this read (cards are not replayed from local storage).
612
416
  *
613
- * `false` is not an error: a stale snapshot still resolves and still prices
614
- * a feed-priced quote — it is marked, not refused. What it cannot do is
615
- * supply the key an addressed RFQ's responder is checked against, because
616
- * that field is unvalidated cache content (`isMarketShaped` revalidates
617
- * four fields and trusts the rest).
417
+ * `false` is marked, not refused: a stale snapshot still prices a feed-priced quote. It cannot
418
+ * supply the key an addressed RFQ's responder is checked against, because cached cards are
419
+ * only partly revalidated (`isMarketShaped`).
618
420
  */
619
421
  readonly live: boolean;
620
422
  /** How the markets were obtained. */
@@ -623,24 +425,16 @@ interface SnapshotRef {
623
425
  readonly registry?: string;
624
426
  }
625
427
  /**
626
- * Which card priced a quote, and from which registry.
627
- *
628
- * A union rather than a bag of optionals, because §10's published RFQ is the
629
- * one place the sentence "the market picks the backend" stops: a quote closed
630
- * out of an open auction has a market *key* and no card behind it, so every
631
- * card-derived field is absent at once rather than one at a time. Sizing that
632
- * arm now costs a discriminant and keeps the addressed arm total.
428
+ * Which card priced a quote, and from which registry. A union because an auction-closed quote
429
+ * (§10) has a market key and no card, and a restored record has neither.
633
430
  */
634
- type MarketRef = CardMarketRef | AuctionMarketRef;
431
+ type MarketRef = CardMarketRef | AuctionMarketRef | RestoredMarketRef;
635
432
  interface CardMarketRef {
636
433
  readonly kind: "card";
637
434
  /**
638
- * The canonical market key, `<corridor>:<id>/<corridor>:<id>`, derived under
639
- * rfq-protocol.md §2's leg order — arkade first when exactly one leg is
640
- * arkade, lexicographic otherwise — and never read off the card's own
641
- * base/quote order. The two agree for every card the registry's reducer
642
- * validated, and a card published outside it is exactly where the silent
643
- * miss lives.
435
+ * The canonical market key, `<corridor>:<id>/<corridor>:<id>`, under rfq-protocol.md §2's leg
436
+ * order — arkade first when exactly one leg is arkade, lexicographic otherwise — never the
437
+ * card's own base/quote order (see `marketKeyOf`).
644
438
  */
645
439
  readonly key: string;
646
440
  readonly backend: MarketBackend;
@@ -661,44 +455,26 @@ interface AuctionMarketRef {
661
455
  readonly key: string;
662
456
  readonly backend: "rfq";
663
457
  }
458
+ /** A record rebuilt after a restore (from the funding tx, or a v1 corridor row): no card stands
459
+ * behind it. */
460
+ interface RestoredMarketRef {
461
+ readonly kind: "restored";
462
+ readonly backend: "feed" | "rfq";
463
+ }
664
464
 
665
465
  /**
666
466
  * What survives a crash, and the public shape `accept()` hands back.
667
467
  *
668
- * Two types, one key. {@link SwapRecord} is the storage form — JSON-safe by
669
- * declaration, every amount a canonical decimal string — and {@link Swap} is the
670
- * answer a caller reads, with `bigint` amounts and the resolved `Route`. The
671
- * conversion between them is §D's record-boundary codec, and it is not a third
672
- * law: `toAtomicDecimal`/`fromAtomicDecimal` already ship in `./amount`, minted
673
- * by M1 and used by M3's wire adapter, so both sites emit the same canonical
674
- * form — atomic units, unsigned, no leading zeros, never a scaled display
675
- * decimal.
468
+ * {@link SwapRecord} is the storage form (amounts as canonical atomic decimal strings); {@link Swap}
469
+ * is the caller's answer with `bigint` amounts and the resolved `Route`.
676
470
  *
677
- * **The key is the quote id, on every route.** That is what makes persist-first
678
- * representable at all: v1's `AssetSwap.id` *is* the funding txid
679
- * (`store.ts:70-71`), so a record could not exist before the money did, and
680
- * `coverage.ts` carries a process-local issuance mark precisely to paper over
681
- * the gap. Here the record precedes the funding and `fundingTxid` is a later,
682
- * best-effort write.
683
- *
684
- * **JSON-safe means no `bigint` anywhere, at any depth.** The SQLite and Realm
685
- * backends `JSON.stringify` the record whole, so a `bigint` throws on two
686
- * backends and round-trips on the third — the asymmetry
687
- * `test/repository.test.ts` refuses to paper over. Every amount here is an
688
- * {@link AtomicDecimal}; `test/client/record.types.ts` proves the absence
689
- * structurally rather than by review.
471
+ * **The key is the quote id, on every route**, which is what makes persist-first possible (v1 keyed
472
+ * on the funding txid, so no record could precede the money). `fundingTxid` is a later write.
473
+ * **No `bigint` anywhere, at any depth**: SQLite and Realm `JSON.stringify` the record whole
474
+ * (`test/client/record.types.ts` proves it structurally).
690
475
  */
691
476
 
692
- /**
693
- * Which family a record belongs to, and the discriminant M5's `RawState` keys
694
- * on.
695
- *
696
- * Not a cosmetic tag. v1's two families occupied one `string` id space by
697
- * accident — an offer record's id a funding txid, a corridor record's an
698
- * `rfqId` — and keying both on `QuoteId` closes that collision (§B). The tag is
699
- * what M6's public id carries, and what lets M5 branch its outcome table
700
- * without a repository read.
701
- */
477
+ /** Which family a record belongs to — what the drive's outcome table branches on without a read. */
702
478
  type SwapFamily = "offer" | "rfq";
703
479
  /** One leg's obligation, in the form a record holds it. */
704
480
  interface RecordedLeg {
@@ -706,14 +482,8 @@ interface RecordedLeg {
706
482
  /** Atomic units as a canonical decimal string — never a `bigint`. */
707
483
  readonly amount: AtomicDecimal;
708
484
  }
709
- /**
710
- * An endpoint as the record holds it: the corridor, the asset, the instrument.
711
- *
712
- * `Instrument`'s invoice arm carries a `bigint` amount, so it cannot be stored
713
- * as declared — {@link RecordedInstrument} is the same union with that one field
714
- * in decimal form. The rest is field for field identical, which is what keeps the
715
- * comparison in `acceptConflict` honest.
716
- */
485
+ /** An endpoint as the record holds it; field for field `Instrument`'s shape, so `acceptConflict`
486
+ * compares like with like. */
717
487
  interface RecordedEndpoint {
718
488
  readonly corridor: CorridorId;
719
489
  readonly asset: AssetId;
@@ -744,26 +514,13 @@ type RecordedArtifact = {
744
514
  readonly amount: AtomicDecimal;
745
515
  readonly expiresAt?: number;
746
516
  };
747
- /**
748
- * The half both families carry.
749
- *
750
- * Every field is either something `AcceptConflict` compares (§3.2's list), or
751
- * something M5 named as a cross-milestone ask, or the two timestamps. Nothing
752
- * is here for display: a record carries what no covenant and no chain read can
753
- * give back, which is the same rule `RfqSwapRecord` is arranged by.
754
- */
517
+ /** The half both families carry: what `AcceptConflict` compares and no chain read can give back. */
755
518
  interface SwapRecordCommon {
756
- /** The client-minted quote id — the primary key, per C1 and §B. */
519
+ /** The client-minted quote id — the primary key. */
757
520
  readonly id: QuoteId;
758
521
  readonly family: SwapFamily;
759
- /**
760
- * Both endpoints, instruments included — `AcceptConflict` items 1 and 3.
761
- *
762
- * Nested under `route` so the record's field names are `Quote`'s field
763
- * names: the conflict check walks the two shapes together, and a record
764
- * that spelled the same fact differently would make every comparison a
765
- * translation.
766
- */
522
+ /** Both endpoints, instruments included. Nested under `route` so field names match `Quote`'s and
523
+ * the conflict check walks both shapes without translation. */
767
524
  readonly route: {
768
525
  readonly give: RecordedEndpoint;
769
526
  readonly take: RecordedEndpoint;
@@ -773,53 +530,22 @@ interface SwapRecordCommon {
773
530
  readonly take: RecordedLeg;
774
531
  /** The spread, as the quote precomputed it. */
775
532
  readonly fee: RecordedLeg;
776
- /**
777
- * Which card priced this, from which registry, how fresh — stored WHOLE.
778
- *
779
- * A trimmed projection could not rebuild the type {@link Swap.market}
780
- * promises: `CardMarketRef` requires `kind`, `pair` and `snapshot` beside
781
- * the fields a summary would keep. Every member is a string, number or
782
- * boolean, so the union round-trips through JSON untouched, and `snapshot`
783
- * is restated as read at accept rather than restamped — a past `fetchedAt`
784
- * beside the recorded `live` is the honest answer about how fresh the card
785
- * was when this swap was accepted.
786
- */
533
+ /** Which card priced this, from which registry, how fresh — stored WHOLE (a projection could not
534
+ * rebuild `CardMarketRef`); `snapshot` is as read at accept, not restamped. */
787
535
  readonly market: MarketRef;
788
- /**
789
- * The committed counterparty, from the quote's covenant role.
790
- *
791
- * NOT `CardMarketRef.solver`, which is the card's display name. Two
792
- * different facts that v1 spelled with one word: this one is a key that
793
- * ends up in a covenant leaf, the other is a label. `AcceptConflict`
794
- * compares this one.
795
- */
536
+ /** The committed counterparty key from the quote's covenant role — NOT `CardMarketRef.solver`,
537
+ * which is a display name. `AcceptConflict` compares this one. */
796
538
  readonly solver?: Pubkey;
797
539
  /** The quote's own deadline, unix seconds — what makes a stalled accept a
798
540
  * benign abandon rather than a live obligation. */
799
541
  readonly expiresAt: number;
800
- /**
801
- * The one thing a counterparty must see, when this route has one.
802
- *
803
- * Durable because a duplicate accept must return the SAME invoice, and the
804
- * invoice lives on the quote object — nowhere in the corridor profile. A
805
- * caller that re-accepts after a restart has no quote object left, so
806
- * without this field the only honest answer would be a second invoice,
807
- * which §3.2 forbids by name.
808
- */
542
+ /** The one thing a counterparty must see, when the route has one. Durable because a duplicate
543
+ * accept after a restart must return the SAME invoice, and the quote object is gone by then. */
809
544
  readonly artifact?: RecordedArtifact;
810
- /**
811
- * The transaction that funded this swap, once known.
812
- *
813
- * A later, best-effort write, and the field that separates M5's `accepted`
814
- * from `funding`. Set-where-absent is a benign resume and never an
815
- * `AcceptConflict` — §3.2 says so by name.
816
- */
545
+ /** The funding transaction, once known. A later best-effort write; set-where-absent is a benign
546
+ * resume, never an `AcceptConflict`. */
817
547
  readonly fundingTxid?: string;
818
- /**
819
- * Last local receive-claim error while the swap is still retryable. If the
820
- * claim window later closes without a submitted claim, this becomes the
821
- * terminal failure reason after restore.
822
- */
548
+ /** Last retryable receive-claim error; becomes the terminal failure if the claim window closes. */
823
549
  readonly claimFailure?: string;
824
550
  /** Terminal failure reason. */
825
551
  readonly failure?: string;
@@ -830,53 +556,42 @@ interface SwapRecordCommon {
830
556
  readonly createdAt: number;
831
557
  readonly updatedAt: number;
832
558
  }
833
- /**
834
- * `arkade <-> arkade`: the offer covenant, and what cancels it.
835
- *
836
- * `offerHex` is the whole covenant — `cancelOffer` needs nothing else to
837
- * rebuild it — so this arm stores no tree parameters of its own.
838
- */
559
+ /** `arkade <-> arkade`: the offer covenant. `offerHex` is the whole covenant, so no tree params. */
839
560
  interface OfferSwapRecord extends SwapRecordCommon {
840
561
  readonly family: "offer";
841
- /** v1's raw status vocabulary, which M5's `RawState` reads verbatim. */
562
+ /** v1's raw status vocabulary, read verbatim by the drive's `RawState`. */
842
563
  readonly status: AssetSwapStatus;
843
564
  /** The TLV offer, hex. The only input `cancelOffer` needs. */
844
565
  readonly offerHex: string;
845
566
  readonly swapAddress: string;
846
- /** The covenant's scriptPubKey, hex — the indexer's monitoring key, and
847
- * what §F's reconcile matches a discovered deposit against. */
567
+ /** The covenant's scriptPubKey, hex — the indexer's monitoring key and the reconcile's match key. */
848
568
  readonly swapPkScript: string;
569
+ /** Sats riding an asset deposit, decimal: the solver's published carrier, which the fill is
570
+ * priced against. Absent for a BTC deposit and for feed-priced swaps (the SDK default). */
571
+ readonly carrierSats?: string;
849
572
  readonly spentTxid?: string;
850
573
  readonly completedAt?: number;
851
574
  }
852
575
  /**
853
576
  * The three corridor routes: a VHTLC lockup, its clocks and its secrets.
854
577
  *
855
- * **No covenant tree here.** Every lockup registers a contract row before its
856
- * address can be funded, and that row already holds the parameters, keyed by
857
- * the script they derive — a key `createContract` refuses to write unless the
858
- * params reproduce it. Storing the tree a second time would be two sources for
859
- * one covenant. `accept()` is what writes that row (see `./accept.ts`), which
860
- * is why a persisted record always has one.
578
+ * **No covenant tree here.** `accept()` registers a contract row before the lockup can be funded,
579
+ * keyed by the script its params derive (`createContract` refuses params that don't reproduce it);
580
+ * storing the tree again would be two sources for one covenant.
861
581
  */
862
582
  interface CorridorSwapRecord extends SwapRecordCommon {
863
583
  readonly family: "rfq";
864
- /** v1's raw state vocabulary, read verbatim by M5's `RawState`. */
584
+ /** v1's raw state vocabulary, read verbatim by the drive's `RawState`. */
865
585
  readonly state: RfqSwapState;
866
- /**
867
- * Which corridor, in the manager's own vocabulary.
868
- *
869
- * `PersistableRfqSwap["kind"]` rather than a `Corridor`: it is a route pair
870
- * — `lightning_send` and `lightning_receive` are one corridor from opposite
871
- * ends — and it is what resolves the handler that owns {@link profile}.
872
- */
586
+ /** The route pair in the manager's vocabulary (`lightning_send`/`lightning_receive` are one
587
+ * corridor from opposite ends); resolves the handler that owns {@link profile}. */
873
588
  readonly kind: PersistableRfqSwap["kind"];
874
589
  /** The solver's own id for the negotiation, echoed back on the wire. */
875
590
  readonly rfqId: string;
876
591
  /** The Arkade address that was funded, and the swap's handle on its
877
592
  * covenant row. */
878
593
  readonly lockupAddress: string;
879
- /** Its pkScript, hex — the row's key, and §F's matching key. */
594
+ /** Its pkScript, hex — the row's key and the reconcile's match key. */
880
595
  readonly lockupPkScript: string;
881
596
  /** The hash both covenants commit to. `sha256(P)`, hex. */
882
597
  readonly lock: {
@@ -885,163 +600,116 @@ interface CorridorSwapRecord extends SwapRecordCommon {
885
600
  /** When the trader's value comes back if the swap does not complete. */
886
601
  readonly refundLocktime: number;
887
602
  /**
888
- * The corridor's own half, as plain JSON.
889
- *
890
- * v1's opaque bag (`rfqRecord.ts:108-123`), written with `rfqSecretsProfile`
891
- * and read by `rfqCorridorHandlers.hydrate` — reused rather than
892
- * reinvented, so M5 rebuilds through machinery that already exists and a new
893
- * corridor still ships without touching this file. It is also what carries
894
- * `expectedAmount`, the claim value gate's request-time input.
895
- *
896
- * Amounts inside it follow v1's shapes (`expectedAmount` is a `number`),
897
- * which is JSON-safe and therefore fine: the decimal-string law governs
898
- * this record's OWN amount fields, not the bag it carries forward.
603
+ * The corridor's own half, as plain JSON (written by `rfqSecretsProfile`, read by
604
+ * `rfqCorridorHandlers.hydrate`), so a new corridor ships without touching this file. Its
605
+ * `expectedAmount` is a `number`; the decimal-string rule covers only this record's own fields.
899
606
  *
900
- * **This is also where the swap's secrets live** — `profile.signer` and,
901
- * on a leg locked to a preimage, `profile.hashlock`. Deliberately not a
902
- * second copy at the record's top level: `rfqClaimSecretOf` and
903
- * `preimageForSwapRecord` already read them from here, and two homes for
904
- * one claim secret is two things to keep in step with one of them always
905
- * empty. At most one of `preimageHex`/`preimageSaltHex` is ever written,
906
- * and which arm exists is decided by the wallet's provisioning result, not
907
- * here.
607
+ * **The swap's secrets live here** (`profile.signer`, and `profile.hashlock` on a preimage-locked
608
+ * leg), deliberately not duplicated at top level.
908
609
  */
909
610
  readonly profile: Record<string, unknown>;
910
611
  readonly refundTxid?: string;
911
612
  readonly lockupSpendTxids?: readonly string[];
613
+ /**
614
+ * `P`, hex — the preimage the solver revealed to settle a Lightning send. Not a copy of our claim
615
+ * secret (the payee mints `P` on that leg), and already public: read from the spending witness.
616
+ */
617
+ readonly settlementPreimageHex?: string;
912
618
  }
913
619
  /** Everything `accept()` persists, both families in one key space. */
914
620
  type SwapRecord = OfferSwapRecord | CorridorSwapRecord;
915
621
 
916
- /** A registry discovery result held for reuse. Refetchable — unlike a swap
917
- * record, losing it costs one network round trip — but it must survive a cold
918
- * boot: serving it stale is what keeps quoting alive while a registry is down. */
622
+ /** A cached registry discovery result. Refetchable, but must survive a cold boot:
623
+ * serving it stale keeps quoting alive while a registry is down. */
919
624
  interface MarketsCacheEntry {
920
625
  markets: DiscoveredMarket[];
921
626
  fetchedAt: number;
922
627
  }
628
+ interface RfqSwapPageFilter {
629
+ state?: RfqSwapState;
630
+ /** Inclusive Unix seconds. */
631
+ since?: number;
632
+ }
633
+ interface RfqSwapPageCursor {
634
+ updatedAt: number;
635
+ rfqId: string;
636
+ }
923
637
  /**
924
- * Everything the package persists, following the monorepo repository
925
- * convention: versioned interface, AsyncDisposable, one backend per platform.
926
- * Consumers construct exactly one of these; there is no second storage seam.
638
+ * Everything the package persists: versioned interface, AsyncDisposable, one backend
639
+ * per platform. Durable records and rebuildable state (scan cursor, markets cache) share
640
+ * one store because they share a lifetime: one wallet on one device.
927
641
  *
928
- * Durable records (swaps) and rebuildable state (the restore scan's txid
929
- * cursor, the markets cache) live side by side because they share a
930
- * lifetime: all three belong to one wallet on one device, and a consumer
931
- * that wipes one wants all three gone.
932
- *
933
- * ponytail: no query filters — every consumer reads all swaps and filters
934
- * in memory; add a filter type when a consumer needs subset queries.
642
+ * Collection reads are paged. RFQ reads may filter by state and date.
935
643
  */
936
644
  interface AssetSwapRepository extends AsyncDisposable {
937
- /** 5 adds the v2 swap-record store — one row per accepted swap, keyed by
938
- * the client-minted quote id. 4 added `getRfqSwap`; 3 added the other RFQ
939
- * methods below; 2 was the released shape — swaps, scan cursor, markets,
940
- * with `preimageSaltHex` on the swap record — so an implementor built
941
- * against any of them cannot satisfy this one silently. */
645
+ /** Bumped on every shape change (5: v2 swap-record store) so an implementor built
646
+ * against an older shape cannot satisfy this one silently. */
942
647
  readonly version: 5;
943
- /** Insert or replace a swap by id. Store the record whole: `preimageHex`
944
- * and `preimageSaltHex` both leave the swap unclaimable if a field-mapped
945
- * backend drops them — the first is the only claim secret of a swap whose
946
- * signer cannot derive, the second the public input every other static
947
- * wallet's preimage derives from.
648
+ /** Insert or replace a swap by id. Store the record whole: a field-mapped backend
649
+ * dropping `preimageHex` or `preimageSaltHex` leaves the swap unclaimable.
948
650
  *
949
- * Records must be **JSON-safe**: the SQLite and Realm backends serialize
950
- * the record to JSON, so a `Date` in a consumer-added field comes back a
951
- * string, a `Set`/`Map` comes back empty, and a `bigint` throws here —
952
- * none of which happens on IndexedDB's structured clone. `AssetSwap` as
953
- * declared is JSON-safe; keep added fields that way. */
651
+ * Records must be **JSON-safe**: SQLite and Realm serialize to JSON, so a `Date`
652
+ * comes back a string, a `Set`/`Map` empty, and a `bigint` throws — unlike
653
+ * IndexedDB's structured clone. Keep consumer-added fields JSON-safe. */
954
654
  saveSwap(swap: AssetSwap): Promise<void>;
955
- /** All stored swaps, in no particular order — `getAssetSwaps` is the
956
- * canonical newest-first read. */
957
- getAllSwaps(): Promise<AssetSwap[]>;
655
+ getAssetSwapsPage(page: PageRequest): Promise<PageResult<AssetSwap>>;
958
656
  /**
959
657
  * Insert or replace a monitored RFQ swap by `rfqId`.
960
658
  *
961
- * Store the record WHOLE. Every field is a covenant tree parameter or the
962
- * manager's own state, and a field-mapped backend that drops one round-trips
963
- * a record whose covenant `rebuildRfqSwap` cannot reproduce — which surfaces
964
- * as a refund that cannot be signed, long after the write.
659
+ * Store the record WHOLE: every field is a covenant parameter or manager state, and a
660
+ * dropped one surfaces much later as a refund that cannot be signed.
965
661
  */
966
662
  saveRfqSwap(record: RfqSwapRecord): Promise<void>;
967
- /** One record by key. `undefined` on a miss — retention prunes terminal
968
- * records, so absence is ordinary and not an error. */
663
+ /** One record by key. */
969
664
  getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
970
- /** Every stored RFQ swap record, in no particular order. */
971
- getAllRfqSwaps(): Promise<RfqSwapRecord[]>;
972
- /** Drop one, once it is past retention — see `shouldRetainRfqSwap`. */
665
+ getRfqSwapsPage(filter: RfqSwapPageFilter, page: PageRequest<RfqSwapPageCursor>): Promise<PageResult<RfqSwapRecord, RfqSwapPageCursor>>;
666
+ /** Drop one record. Only explicit pruning calls this; restore keeps history. */
973
667
  removeRfqSwap(rfqId: string): Promise<void>;
974
668
  /**
975
- * Insert or replace a v2 swap record by its quote id.
669
+ * Insert or replace a v2 swap record (what `accept()` writes) by its quote id.
976
670
  *
977
- * The store the v2 client's `accept()` writes, and the reason this
978
- * interface is at 5. Separate from `swaps` rather than sharing it: the v1
979
- * read path drops any row carrying neither `offerHex` nor `paymentHash`
980
- * (`getAssetSwapsOrThrow`), silently and as corrupt, so a v2 record in that
981
- * store would be pinned by a v1 predicate — and the two histories are meant
982
- * to be disjoint for the deprecation window anyway. A v1 reader not seeing
983
- * v2 rows is the design, asserted in the conformance suite rather than
984
- * tolerated.
671
+ * Separate from `swaps`: the v1 read path silently drops rows with neither `offerHex`
672
+ * nor `paymentHash` as corrupt. v1 readers not seeing v2 rows is by design.
985
673
  *
986
- * Store the record WHOLE, and note that it is **JSON-safe by declaration**:
987
- * every amount on it is a canonical decimal string, precisely so the SQLite
988
- * and Realm backends' `JSON.stringify` and IndexedDB's structured clone
989
- * agree. A `bigint` reaching here would throw on two backends and
990
- * round-trip on the third.
674
+ * Store the record WHOLE. Amounts are canonical decimal strings so every backend
675
+ * agrees; a `bigint` would throw on SQLite/Realm and round-trip on IndexedDB.
991
676
  */
992
677
  saveSwapRecord(record: SwapRecord): Promise<void>;
993
- /** One record by quote id. `undefined` on a miss — which is the ordinary
994
- * answer for a first `accept()`, and what makes it idempotent. */
678
+ /** `undefined` on a miss — the ordinary answer for a first `accept()`, and what
679
+ * makes it idempotent. */
995
680
  getSwapRecord(id: string): Promise<SwapRecord | undefined>;
996
- /** Every stored v2 record, in no particular order. */
997
- getAllSwapRecords(): Promise<SwapRecord[]>;
681
+ getSwapRecordsPage(page: PageRequest): Promise<PageResult<SwapRecord>>;
998
682
  /** Drop one, once it is past retention. */
999
683
  removeSwapRecord(id: string): Promise<void>;
1000
684
  /**
1001
- * Sent txids already checked for offer packets (see restore.ts).
1002
- *
1003
- * **Shared across both record families, deliberately.** This is not
1004
- * record-family data — it marks txids of transactions a scan has answered,
1005
- * whatever family a later record belongs to — and both families walk the
1006
- * same sent-txid set during the deprecation window. Two cursors would have
1007
- * each side re-walking deposits the other already answered.
685
+ * Sent txids already checked for offer packets (see restore.ts). Deliberately shared
686
+ * by both record families: they walk the same sent-txid set, and two cursors would
687
+ * each re-walk what the other already answered.
1008
688
  */
1009
689
  getScannedTxids(): Promise<Set<string>>;
1010
690
  markTxidsScanned(txids: Iterable<string>): Promise<void>;
1011
- /** Cached registry markets, or undefined on a miss. Shared across both
1012
- * record families for the reason the cursor is: the key is network-and-
1013
- * registry, not a store, and two caches would serve two staleness clocks
1014
- * for one registry. */
691
+ /** Cached registry markets, or undefined on a miss. Shared by both record families,
692
+ * like the cursor, so one registry has one staleness clock. */
1015
693
  getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
1016
694
  saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
1017
695
  clear(): Promise<void>;
1018
696
  }
1019
697
 
1020
698
  /**
1021
- * An executor that owns its connection.
1022
- *
1023
- * `SQLExecutor` declares no lifecycle — the interface is three query methods,
1024
- * because every other implementation wraps a connection the consumer already
1025
- * opened. This one opens the file itself, so it is the one that has something
1026
- * to close.
699
+ * An executor that owns its connection. `SQLExecutor` declares no lifecycle because other
700
+ * implementations wrap a consumer-opened connection; this one opens the file itself.
1027
701
  */
1028
702
  interface NodeSqlExecutor extends SQLExecutor {
1029
703
  /** Close the underlying database handle. Idempotent. */
1030
704
  close(): Promise<void>;
1031
705
  }
1032
706
  /**
1033
- * Open (creating if absent) a SQLite database at `path`.
707
+ * Open (creating the file and its parent directory if absent) a SQLite database at `path`.
1034
708
  *
1035
- * **One instance per file, held for the process's life.** `runInTransaction`
1036
- * keys its write chain on the executor *object* through a `WeakMap`, so a
1037
- * second executor over the same file forks the chain and two "transactions" can
1038
- * interleave on one connection. Every repository on a database must be handed
1039
- * the same instance — which is what {@link nodeSwapRepository} does for the
709
+ * **One instance per file, held for the process's life.** `runInTransaction` keys its write chain
710
+ * on the executor *object* via a `WeakMap`, so a second executor over the same file forks the
711
+ * chain and two "transactions" can interleave. {@link nodeSwapRepository} handles this for the
1040
712
  * common case.
1041
- *
1042
- * The parent directory is created on open: the config dir exists on any real
1043
- * machine but `arkade/swaps` under it does not, and failing on a first run for
1044
- * a directory the caller never chose would be a poor default.
1045
713
  */
1046
714
  declare const createNodeSqlExecutor: (path: string) => NodeSqlExecutor;
1047
715
  interface NodeSwapRepositoryOptions {
@@ -1056,19 +724,9 @@ interface NodeSwapRepositoryOptions {
1056
724
  readonly prefix?: string;
1057
725
  }
1058
726
  /**
1059
- * The Node storage default, connection included.
1060
- *
1061
- * This is where D1/D2's ownership rule lands: the returned repository's
1062
- * `[Symbol.asyncDispose]` closes the connection **it** opened, and an injected
1063
- * repository is disposed by whoever built it — which is already true of every
1064
- * other backend, whose disposal is a no-op precisely because the consumer owns
1065
- * the handle.
1066
- *
1067
- * Hanging ownership on the repository rather than on a client lifecycle method
1068
- * is deliberate: the v2 client has no `stop()` or `dispose()` yet — the
1069
- * lifecycle is the next milestone's — and a connection that could only be
1070
- * closed through a method that does not exist would leak until the process
1071
- * ended.
727
+ * The Node storage default, connection included. Its `[Symbol.asyncDispose]` closes the
728
+ * connection **it** opened; an injected repository is disposed by whoever built it. Ownership
729
+ * sits on the repository because the v2 client has no `dispose()` yet.
1072
730
  *
1073
731
  * ```ts
1074
732
  * await using repository = nodeSwapRepository({ network: "mainnet" });