@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
@@ -0,0 +1,2261 @@
1
+ import { DiscoveredMarket } from '@arkade-os/solver-discovery';
2
+ import { IWallet, ProvisionedKey, ProvisionedClaimSecret, ArkProvider, RestIndexerProvider, IContractManager, VHTLC, Identity, Network, NetworkName, asset, PageRequest, PageResult } 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-60PGpQ_x.cjs';
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
+ declare const BTC_ASSET_ID = "btc";
9
+ /**
10
+ * The record fields a wallet-provisioned secret becomes; every secret-carrying record embeds it, so
11
+ * omitting one (an unrecoverable preimage) is a compile error. **Only `preimageHex` is secret**; the
12
+ * descriptor and salt are public derivation inputs that leak nothing without the seed.
13
+ */
14
+ interface SwapSecretsProjection {
15
+ /** The wallet descriptor this swap's sender key comes from (a fresh HD child, or a static
16
+ * wallet's `tr(pubkey)`). Public; the record carries no key material. */
17
+ signingDescriptor?: string;
18
+ /** P, hex, when it cannot be re-derived from the seed at all: the user
19
+ * supplied it, or the signer cannot sign deterministically. The swap's only
20
+ * claim secret when present. */
21
+ preimageHex?: string;
22
+ /** The salt P derives from, hex — what a static wallet stores instead of P. **Public**, and minted
23
+ * per swap: it stops one repeating key from giving every swap the same preimage. */
24
+ preimageSaltHex?: string;
25
+ }
26
+ /** The row {@link AssetSwapRepository} stores. A root export because custom storage backends are
27
+ * written against it. Not the v2 client's record (that is `SwapRecord`, projected as `Swap`). */
28
+ interface AssetSwap extends SwapSecretsProjection {
29
+ /** Funding txid — the swap's identity. */
30
+ id: string;
31
+ /** 'btc' or a 68-hex asset id. */
32
+ fromAsset: string;
33
+ toAsset: string;
34
+ /** Atomic amounts as strings (bigint is not JSON-safe). */
35
+ fromAmount: string;
36
+ /** The covenant wantAmount — a floor, the fill pays >= this. */
37
+ toAmount: string;
38
+ swapAddress: string;
39
+ /** Hex pkScript of the swap contract — the indexer monitoring key. */
40
+ swapPkScript: string;
41
+ /** TLV offer — needed to rebuild the contract for cancel. */
42
+ offerHex: string;
43
+ fundingTxid: string;
44
+ spentTxid?: string;
45
+ status: AssetSwapStatus;
46
+ createdAt: number;
47
+ completedAt?: number;
48
+ /** RFQ pair string, e.g. `arkade:BTC->onchain:BTC`. */
49
+ pair?: string;
50
+ /** `sha256(P)`, hex. Public, and how a restore confirms a candidate
51
+ * derivation is the right one. */
52
+ paymentHash?: string;
53
+ /** The L1 HTLC's pkScript, hex — the chain-watch key. */
54
+ htlcPkScriptHex?: string;
55
+ htlcLocktime?: number;
56
+ /** The L1 funding txid, once observed. */
57
+ l1Txid?: string;
58
+ }
59
+ /** The consumer read: a broken backend reads as no swaps rather than crashing a history view.
60
+ * Mutations must use {@link getAssetSwapsOrThrow}, or "backend gone" would masquerade as "no such
61
+ * swap" and skip the write silently. */
62
+ declare const getAssetSwaps: (repository: AssetSwapRepository) => Promise<AssetSwap[]>;
63
+ /** Add a swap; no-op if the id is already stored. Returns the updated list.
64
+ * THROWS on a failed write — nothing irreversible may happen until this record
65
+ * is durable, so the caller must not fund on a failure.
66
+ *
67
+ * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
68
+ */
69
+ declare const addAssetSwap: (repository: AssetSwapRepository, swap: AssetSwap) => Promise<AssetSwap[]>;
70
+ /** Merge changes into a swap by id. Returns the updated list. THROWS on a failed read or write —
71
+ * use it for a write that gates something irreversible; writes *after* the irreversible act belong
72
+ * on {@link updateAssetSwapBestEffort}.
73
+ *
74
+ * @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`.
75
+ */
76
+ declare const updateAssetSwap: (repository: AssetSwapRepository, id: string, changes: Partial<Omit<AssetSwap, "id">>) => Promise<AssetSwap[]>;
77
+ /**
78
+ * The record fields a wallet-provisioned secret becomes: `signingDescriptor` always, then at most
79
+ * one of `preimageHex` (the wallet cannot re-derive P) or `preimageSaltHex` (derivable but
80
+ * repeating key).
81
+ */
82
+ declare const swapSecretsToRecord: (secrets: ProvisionedKey | ProvisionedClaimSecret) => SwapSecretsProjection & {
83
+ signingDescriptor: string;
84
+ };
85
+ /** Why a wallet cannot produce a swap's preimage. */
86
+ type PreimageBlockedReason =
87
+ /** The record carries no `signingDescriptor`. */
88
+ "no-secrets"
89
+ /** `preimageHex` or `preimageSaltHex` is present but not 32 bytes of hex. */
90
+ | "malformed-record"
91
+ /** Nothing to derive from, or a descriptor this wallet holds no key for — merged because
92
+ * `contractSigner` reports the latter inconsistently; `cause` carries which. */
93
+ | "not-derivable"
94
+ /** Derived, but it does not hash to the record's `paymentHash`. */
95
+ | "hash-mismatch";
96
+ /**
97
+ * The wallet cannot produce this swap's preimage; `reason` says which way.
98
+ *
99
+ * Deliberately **not** {@link RefundNotLocallyPossibleError}: `RfqSwapManager` reports that as
100
+ * `needs_counterparty`, and a claim-path read failure is a different verdict.
101
+ */
102
+ declare class PreimageNotRecoverableError extends Error {
103
+ readonly reason: PreimageBlockedReason;
104
+ readonly name = "PreimageNotRecoverableError";
105
+ constructor(reason: PreimageBlockedReason, message: string, options?: {
106
+ cause?: unknown;
107
+ });
108
+ }
109
+ /**
110
+ * The preimage a swap record claims with — stored, or re-derived. Use this rather than composing by
111
+ * hand: forgetting `preimageSaltHex` yields a *wrong* preimage, not an error. Verified against
112
+ * `paymentHash` when present, since a wrong P otherwise surfaces as an opaque script failure at
113
+ * claim time. Every refusal is a {@link PreimageNotRecoverableError} with a `reason`.
114
+ */
115
+ declare const preimageForSwapRecord: (wallet: IWallet, record: SwapSecretsProjection & {
116
+ paymentHash?: string;
117
+ }) => Promise<Uint8Array>;
118
+
119
+ /** True for the states after which the solver will report nothing further. */
120
+ declare const isRfqTerminal: (state: string) => boolean;
121
+ /**
122
+ * Poll a swap's status until it reaches a terminal state. Same conventions as
123
+ * {@link awaitOnchainFill}; throws with `reason: "status_timeout"` past `deadline`.
124
+ *
125
+ * A `null` status is "not yet" (a status route can 404 briefly after a quote). Transport errors
126
+ * reject; restarting after a blip loses nothing, since the refund is gated on an absolute
127
+ * timelock.
128
+ */
129
+ declare function awaitRfqResolution(transport: RfqTransport, rfqId: string, options?: {
130
+ pollMs?: number;
131
+ deadline?: number;
132
+ }): Promise<RfqStatus>;
133
+ /**
134
+ * What a push needs from the operator: the broadcast pair, plus the info read that supplies
135
+ * `checkpointTapscript`. Narrow so a wallet's own connection satisfies it (see
136
+ * {@link walletOperator}) and no second connection is opened; a full `ArkProvider` also fits.
137
+ */
138
+ type SwapOperator = Pick<ArkProvider, "getInfo" | "submitTx" | "finalizeTx">;
139
+ /**
140
+ * The contract-manager surface the lockup lookup needs: the registered contract and its VTXOs,
141
+ * in one read. A real `ContractManager` syncs on every read and reports degraded fallback via
142
+ * `getSyncState()`; {@link findLockupVtxos} trusts this read.
143
+ */
144
+ type LockupContractSource = Pick<IContractManager, "getContractsWithVtxos">;
145
+ /** A still-refundable virtual output sitting at the swap lockup. */
146
+ interface LockupVtxo {
147
+ txid: string;
148
+ vout: number;
149
+ value: number;
150
+ /**
151
+ * The batch expired and the operator swept it: still the trader's money, but no longer a
152
+ * live leaf, so it can be RECOVERED into a fresh batch but not spent offchain
153
+ * (`canSpendOffchain` is false whenever `canRecoverOnchain` is true), whatever key signs.
154
+ * After recovery the ordinary CLTV refund works again; {@link pushRefundWithoutReceiver}
155
+ * refuses these rather than submitting a doomed spend.
156
+ */
157
+ recoverable: boolean;
158
+ }
159
+ /**
160
+ * Thrown when a refund was asked for over outputs that have been swept. Carries the outpoints so
161
+ * a caller can recover exactly those, then retry.
162
+ *
163
+ * The remedy is the SDK's `IVtxoManager.recoverVtxos()`, which covers a lockup once it is
164
+ * registered as a contract — so registration is what makes a swept lockup recoverable at all.
165
+ * Caveats a caller must hold:
166
+ *
167
+ * - **The wallet must hold the lockup's `sender` key**: recovery settles through
168
+ * `refundWithoutReceiver`.
169
+ * - **`refundLocktime` must have matured.** `recoverVtxos` settles every recoverable output in ONE
170
+ * round with no CLTV awareness, so recovering early can fail the whole batch.
171
+ */
172
+ declare class LockupNeedsRecoveryError extends Error {
173
+ readonly name = "LockupNeedsRecoveryError";
174
+ readonly reason = "needs_recovery";
175
+ /** `txid:vout` for each output that must be recovered first. */
176
+ readonly outpoints: string[];
177
+ /**
178
+ * The contract's `refundLocktime`; do not recover before it (see above). Seconds-based
179
+ * locktimes mature against chain time, not wall clock, so treat this as a floor.
180
+ */
181
+ readonly recoverableAfter: bigint;
182
+ constructor(outpoints: string[], recoverableAfter: bigint);
183
+ }
184
+ /**
185
+ * Every output still at the lockup script — spendable AND swept-but-recoverable, each tagged.
186
+ * This read, not the RFQ's reported state, is the authority on what is left.
187
+ *
188
+ * All of them, not the first: a lockup funded in several sends would otherwise be partly
189
+ * stranded. Visible is not refundable: see {@link LockupVtxo.recoverable}.
190
+ *
191
+ * **Unrolled and terminally spent outputs are dropped** (`isVtxoSpent`, the wallet's own
192
+ * spend gate): nothing offchain can reach them and `LockupVtxo` could not say so.
193
+ * {@link readLockupFate} reports exits as `exited`; this drop is the second line of defence.
194
+ *
195
+ * **Reads the REGISTERED contract row and trusts it**, with no fallback to a script query:
196
+ * callers own registration (`request*Send`, `RfqSwapManager.ensureRegistered`), and an empty row
197
+ * is honored as-is. {@link readLockupFate} stays on the indexer because it needs the spending
198
+ * transactions' witnesses, which the manager does not expose.
199
+ */
200
+ declare function findLockupVtxos(contracts: LockupContractSource, swapPkScript: Uint8Array): Promise<LockupVtxo[]>;
201
+ /**
202
+ * The indexer surface the lockup-spend read needs: the vtxo lookup, plus the raw transactions
203
+ * those vtxos were spent by. Taken by `SwapDriveConfig.indexer`; returned by
204
+ * `walletLockupIndexer()`.
205
+ */
206
+ type LockupSpendIndexer = Pick<RestIndexerProvider, "getVtxos" | "getVirtualTxs">;
207
+ /**
208
+ * What chain data says became of a swap lockup — the whole answer, with no
209
+ * solver involvement and nothing taken on the solver's word.
210
+ */
211
+ interface LockupSpend {
212
+ /** What the vtxo's `spentBy` names — the checkpoint, never the ark
213
+ * transaction. */
214
+ checkpointTxid: string;
215
+ /** The ark transaction that spent the above checkpoint output. What
216
+ * history correlation matches on; absent when the indexer omitted it. */
217
+ txid?: string;
218
+ }
219
+ type LockupFate =
220
+ /** At least one output at the lockup is still unspent. Not over. */
221
+ {
222
+ fate: "open";
223
+ }
224
+ /** Spent by a witness carrying a preimage that HASHES to the quote's `payment_hash`. */
225
+ | {
226
+ fate: "claimed";
227
+ preimage: Uint8Array;
228
+ spends: readonly LockupSpend[];
229
+ }
230
+ /** Fully spent, and nothing that spent it revealed a matching preimage —
231
+ * so the money went back to the trader. See {@link readLockupFate}. */
232
+ | {
233
+ fate: "returned";
234
+ spends: readonly LockupSpend[];
235
+ }
236
+ /**
237
+ * At least one output was unilaterally exited: onchain under the VHTLC script, beyond any
238
+ * offchain claim or refund. Not terminal and not a loss (`completeUnroll` plus an onchain
239
+ * spend can still end it). Outranks `open` and any sibling's verdict: unspent-but-unreachable
240
+ * is not a merely running swap.
241
+ */
242
+ | {
243
+ fate: "exited";
244
+ outpoints: readonly {
245
+ txid: string;
246
+ vout: number;
247
+ }[];
248
+ }
249
+ /** Nothing was learned (see {@link readLockupFate}). Never an answer. */
250
+ | {
251
+ fate: "unknown";
252
+ };
253
+ /**
254
+ * Decide from chain data alone whether a swap lockup settled, came back, or is
255
+ * still live.
256
+ *
257
+ * **Decidable without asking anyone.** Only the claim leaf reveals `P`, and the counterparty only
258
+ * legitimately obtains `P` by completing its side. Every OTHER leaf is a refund:
259
+ * `nonInteractiveRefund` is covenant-pinned to the trader's address and the rest need the
260
+ * trader's signature. So "spent, but not by a hash-verified claim" means the money came back.
261
+ *
262
+ * **A matching witness SHAPE is not proof**: only a candidate hashing to `paymentHash` counts.
263
+ * Being permissive would report "settled" for a swap that refunded.
264
+ *
265
+ * **`unknown` is not `returned`**: an empty vtxo set, an unnamed or unfetchable spend, or an
266
+ * undecodable blob all give `unknown`, and `getVirtualTxs` may return fewer txs than asked, so the
267
+ * observed set is counted. Treat `unknown` like `open`; the refund timelock ends the wait.
268
+ *
269
+ * An exit is checked first, across the whole set, so output order cannot change the answer.
270
+ * Read fresh on every poll, never cached.
271
+ */
272
+ declare function readLockupFate(indexer: LockupSpendIndexer, input: {
273
+ swapPkScript: Uint8Array;
274
+ /** `sha256(P)`, hex — the quote's `payment_hash`. */
275
+ paymentHash: string;
276
+ }): Promise<LockupFate>;
277
+ /**
278
+ * Build, sign, and push the `refundWithoutReceiver` spend: return every funded
279
+ * output at the lockup to the trader's refund address.
280
+ *
281
+ * The leaf is `CLTV(refundLocktime) + <sender> + <server>`: no emulator (it co-signs only the
282
+ * covenant leaves), so the tx is submitted SIGNED. One aggregate output, since this leaf has no
283
+ * covenant requiring index-aligned outputs.
284
+ *
285
+ * `refundPkScript` defaults to the contract's committed `senderPkScript` (the trader's quote-time
286
+ * address); overridable because this leaf genuinely permits any destination.
287
+ *
288
+ * **Median-time-past (BIP-113), not wall clock, decides spendability**: it trails by about an
289
+ * hour, so an early rejection is expected; {@link refundIfUnresolved} retries.
290
+ *
291
+ * **Swept outputs refuse the whole push** with {@link LockupNeedsRecoveryError}: one swept input
292
+ * would sink the aggregate tx, and silently filtering it would report success over unmoved money.
293
+ */
294
+ declare function pushRefundWithoutReceiver(operator: SwapOperator, input: {
295
+ contract: InstanceType<typeof VHTLC.ScriptV2>;
296
+ /** The `sender` signer. Build it with {@link senderIdentityForSwapRecord}, so every
297
+ * inability to produce it is a typed, permanent {@link RefundNotLocallyPossibleError}. */
298
+ sender: Identity;
299
+ vtxos: readonly LockupVtxo[];
300
+ /** Defaults to the contract's own committed refund destination. */
301
+ refundPkScript?: Uint8Array;
302
+ /** @see operatorUnrollScript */
303
+ network?: Network;
304
+ }): Promise<{
305
+ txid: string;
306
+ amount: number;
307
+ }>;
308
+ type RefundOutcome =
309
+ /** The solver resolved it — claimed (`settled`) or returned it (`refunded`). */
310
+ {
311
+ outcome: "resolved";
312
+ status: RfqStatus;
313
+ }
314
+ /** The trader took it back via `refundWithoutReceiver`. */
315
+ | {
316
+ outcome: "refunded";
317
+ txid: string;
318
+ amount: number;
319
+ status: RfqStatus | null;
320
+ }
321
+ /** The refund window opened but the lockup holds nothing to return. */
322
+ | {
323
+ outcome: "nothing_to_refund";
324
+ status: RfqStatus | null;
325
+ }
326
+ /**
327
+ * The money is still at the lockup but its batch was swept; no waiting fixes that (see
328
+ * {@link LockupNeedsRecoveryError}). Recover the named outpoints, then call again.
329
+ */
330
+ | {
331
+ outcome: "needs_recovery";
332
+ outpoints: string[];
333
+ vtxos: LockupVtxo[];
334
+ status: RfqStatus | null;
335
+ }
336
+ /**
337
+ * The lockup was unilaterally exited: its outputs sit onchain, beyond any offchain refund.
338
+ * Complete the unroll and spend the named outputs onchain.
339
+ *
340
+ * **`outpoints` may not be the whole lockup.** `exited` fires as soon as ANY output exited
341
+ * (the same rule `RfqSwapManager` uses; the two must agree), and a still-live sibling is left
342
+ * for the caller to pursue separately. Distinct from `needs_recovery`, whose batch-recovery
343
+ * remedy cannot reach an onchain output.
344
+ */
345
+ | {
346
+ outcome: "exited";
347
+ outpoints: string[];
348
+ status: RfqStatus | null;
349
+ };
350
+ /**
351
+ * Ask first, then fall back: watch the swap for the solver to resolve it, and
352
+ * if `refundLocktime` matures without that happening, take the lockup back
353
+ * with `refundWithoutReceiver`.
354
+ *
355
+ * - **A dead negotiation does not stop the wait** (see {@link RFQ_RESOLVED_STATES}).
356
+ * - **Early pushes may fail** while MTP catches up; retried at the poll interval until
357
+ * `attemptDeadline`, then the last error is rethrown.
358
+ * - **A swept lockup returns `needs_recovery`** instead of burning the window.
359
+ * - **An exited lockup returns `exited`**, checked first via {@link readLockupFate} (an extra
360
+ * indexer read per pass). A failing fate read is swallowed: it is a shortcut only.
361
+ *
362
+ * Safe to call late and to call again: an empty lockup is `nothing_to_refund`, not an error.
363
+ *
364
+ * @deprecated Use `client.recover()`. Moved off the package root to `@arkade-os/swap/protocol`.
365
+ */
366
+ declare function refundIfUnresolved(transport: RfqTransport, operator: SwapOperator, contracts: LockupContractSource, indexer: LockupSpendIndexer, input: {
367
+ rfqId: string;
368
+ contract: InstanceType<typeof VHTLC.ScriptV2>;
369
+ /** @see pushRefundWithoutReceiver */
370
+ sender: Identity;
371
+ /**
372
+ * `sha256(P)`, hex — the quote's `payment_hash`. Not derivable from `script`, whose
373
+ * `preimageHash` is a `hash160`.
374
+ */
375
+ paymentHash: string;
376
+ /** `refund_locktime` from the quote, unix seconds. */
377
+ refundLocktime: number;
378
+ /** Defaults to the contract's own committed refund destination. */
379
+ refundPkScript?: Uint8Array;
380
+ pollMs?: number;
381
+ /** Stop retrying the push at this unix time, rethrowing the last
382
+ * error. Defaults to `refundLocktime + REFUND_MTP_LAG_SECONDS`. */
383
+ attemptDeadline?: number;
384
+ /** Injected for tests; defaults to wall clock, in unix seconds. */
385
+ now?: () => number;
386
+ }): Promise<RefundOutcome>;
387
+
388
+ /**
389
+ * Where a monitored RFQ swap stands, and which of those states end it. Its own module so the
390
+ * record layer (retention via {@link isRfqSwapTerminal}) and the manager need not import each
391
+ * other at runtime; `swapManager.ts` re-exports all three names.
392
+ */
393
+ /**
394
+ * Where a monitored swap stands; the vocabulary of `CorridorSwapRecord.state`. `Outcome`, from
395
+ * `client.onUpdate()`, is the client-level projection over it.
396
+ *
397
+ * `claimable`/`claimed` apply when the TRADER has something to claim: the L1 fill on an onchain
398
+ * send, the solver-funded lockup on a receive. `lightning_send` has neither; the trader's only
399
+ * move there is the refund.
400
+ */
401
+ type RfqSwapState =
402
+ /** Live; nothing actionable yet. On a receive leg this covers the whole
403
+ * stretch before the solver funds anything. */
404
+ "pending"
405
+ /** There is something for the trader to take, and the window to take it is
406
+ * open: the confirmed L1 fill on an onchain send, or a lockup funded for at
407
+ * least `expectedAmount` on a receive. */
408
+ | "claimable"
409
+ /**
410
+ * The trader's claim has been made (L1 broadcast on an onchain send, Arkade submission on a
411
+ * receive). **On a receive this is a local belief, not a chain fact**, hence not terminal:
412
+ * `refunded` is still reachable if the claim never lands.
413
+ */
414
+ | "claimed"
415
+ /**
416
+ * This wallet will not act, and only the counterparty can change that
417
+ * (`RfqSwapCommon.blockedReason` says why).
418
+ *
419
+ * Send leg: the Arkade refund cannot be pushed from here (no secrets, foreign descriptor, or
420
+ * nothing wired). Receive leg: the lockup cannot be claimed — underfunded (publishing `P`
421
+ * for it is the attack `LockupAmountMismatchError` refuses) or its claim window shut.
422
+ *
423
+ * **Not terminal.** The money is still at the lockup and the refusal is re-checked every
424
+ * pass, so fixing the cause returns the swap to `pending`. On an onchain send the L1 half
425
+ * keeps being driven regardless.
426
+ */
427
+ | "needs_counterparty"
428
+ /**
429
+ * Terminal: the lockup was spent by a hash-verified claim, read off chain, never reported.
430
+ * On a send leg it is the counterparty's claim; on a receive leg the TRADER's own, matched by
431
+ * hash rather than our txid so a claim that lands without us still counts.
432
+ */
433
+ | "settled"
434
+ /**
435
+ * Terminal: the lockup was spent by something other than a claim. On a send leg that is the
436
+ * money coming back. **On a receive leg it is a LOSS**: every non-claim leaf is the
437
+ * solver's. Also where a receive swap ends when its window closes with nothing to observe.
438
+ */
439
+ | "refunded"
440
+ /** Terminal: an action failed and its window closed. */
441
+ | "failed";
442
+ /** Whether `CorridorSwapRecord.state` ends the swap. */
443
+ declare const isRfqSwapTerminal: (state: RfqSwapState) => boolean;
444
+
445
+ /**
446
+ * What the manager needs to register a swap's lockup with the wallet, so the indexer
447
+ * pushes its funding and spend.
448
+ *
449
+ * `address` is taken, not re-derived: it must be the one actually funded, and a local
450
+ * re-derivation would silently use the SDK's default network.
451
+ *
452
+ * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
453
+ */
454
+ interface RfqSwapLockup {
455
+ /** The covenant. Its `pkScript` MUST equal the record's `lockupPkScript`. */
456
+ script: InstanceType<typeof VHTLC.ScriptV2>;
457
+ /** The Arkade address that was funded. */
458
+ address: string;
459
+ }
460
+ interface RfqSwapCommon {
461
+ /** The negotiation id — this record's identity. */
462
+ rfqId: string;
463
+ state: RfqSwapState;
464
+ /** The Arkade lockup's scriptPubKey (`swapPkScript` from the request entrypoint): the
465
+ * only handle on the covenant whose spend witness decides the swap. */
466
+ lockupPkScript: Uint8Array;
467
+ /** The covenant behind {@link lockupPkScript}. Without it the manager still polls the
468
+ * swap, it just cannot subscribe; see {@link RfqSwapManagerDeps.contracts}. */
469
+ lockup?: RfqSwapLockup;
470
+ /**
471
+ * `sha256(P)`, hex — the quote's `payment_hash`. The claim leaf is spendable only by
472
+ * revealing its preimage, which makes settlement provable. For an onchain send the L1
473
+ * `htlc` carries the SAME hash. Not final: a hashlock belongs to a corridor (the stored
474
+ * record keeps it in `profile.hashlock`), and hashlock-free corridors may follow.
475
+ */
476
+ paymentHash: string;
477
+ /**
478
+ * `refund_locktime` from the quote, unix seconds. On a send leg it is the TRADER's:
479
+ * refund AFTER it. On a receive leg it is the SOLVER's: the trader must have claimed
480
+ * BEFORE it.
481
+ */
482
+ refundLocktime: number;
483
+ createdAt: number;
484
+ updatedAt: number;
485
+ /** Set once the trader's own `refundWithoutReceiver` push landed. */
486
+ refundTxid?: string;
487
+ /**
488
+ * The ark transactions that SPENT the lockup, from the chain read that ended the swap
489
+ * (`LockupFate.spends`) — moves no local action produced, so a terminal record can
490
+ * name them without another network read. Absent without a chain verdict, or when the
491
+ * indexer named only the checkpoint.
492
+ */
493
+ lockupSpendTxids?: string[];
494
+ /**
495
+ * `P`, hex — the preimage the solver revealed to claim the lockup. Lightning sends
496
+ * only (the payee mints `P`). A public settlement receipt, not a claim secret;
497
+ * `readLockupFate` verifies it against {@link paymentHash} before it is stamped.
498
+ */
499
+ settlementPreimageHex?: string;
500
+ /** Why `state` is `failed`. */
501
+ failure?: string;
502
+ /**
503
+ * Last local claim error while the receive swap is still retryable. Becomes the
504
+ * terminal `failure` if the window closes without a submitted claim.
505
+ */
506
+ claimFailure?: string;
507
+ /** Why `state` is `needs_counterparty`. Distinct from {@link failure},
508
+ * which means an action was attempted and did not work. */
509
+ blockedReason?: string;
510
+ }
511
+ /** `arkade:BTC->lightning:BTC`. The solver claims the lockup with the preimage it learns
512
+ * by paying, so that spend's witness proves the payment landed. */
513
+ interface LightningSendSwap extends RfqSwapCommon {
514
+ kind: "lightning_send";
515
+ }
516
+ /** `arkade:BTC->onchain:BTC`. Carries the L1 half the trader must claim. */
517
+ interface OnchainSendSwap extends RfqSwapCommon {
518
+ kind: "onchain_send";
519
+ /** The locally derived HTLC from `requestOnchainSend` — the manager reads
520
+ * `pkScript`, `paymentHash` and `refundLocktime` off it to classify. */
521
+ htlc: OnchainHtlc;
522
+ /** `profile.min_confirmations` from the quote. */
523
+ minConfirmations: number;
524
+ /** The quote's `to_amount`, captured at REQUEST time: read at claim time it
525
+ * would be whatever the solver funded. */
526
+ expectedAmount: number;
527
+ /** Where {@link RfqSwapManagerCallbacks.claimOnchain} pays; optional only
528
+ * so records predating its profile slot still restore. */
529
+ payoutPkScript?: Uint8Array;
530
+ /** The fill's outpoint, learned on first sighting. Without it a SPENT
531
+ * HTLC reads as never funded — see {@link classifyOnchainHtlc}. */
532
+ funding?: {
533
+ txid: string;
534
+ vout: number;
535
+ };
536
+ /** Our L1 claim's txid. */
537
+ claimTxid?: string;
538
+ }
539
+ /**
540
+ * `lightning:BTC->arkade:BTC`. The SOLVER funds the lockup and the TRADER claims it,
541
+ * publishing `P` so the solver can settle the payer's held Lightning HTLC.
542
+ *
543
+ * - **No trader-side refund.** Every non-claim leaf is the solver's; an unclaimed swap is
544
+ * lost when the solver reclaims at {@link RfqSwapCommon.refundLocktime}.
545
+ * - **The claim is the whole swap, on a deadline**, and the trader must be online:
546
+ * covclaimd cannot claim this covenant today.
547
+ */
548
+ interface LightningReceiveSwap extends RfqSwapCommon {
549
+ kind: "lightning_receive";
550
+ /**
551
+ * What the lockup must carry — the quote's `to_amount`, captured at REQUEST time.
552
+ *
553
+ * **Not re-derivable, not optional.** Read at claim time it would be whatever the
554
+ * solver funded (the dust-funding attack). A non-finite value is reported
555
+ * `needs_counterparty` and never claimed: comparing against `undefined`/`NaN` is
556
+ * false, which would delete the value gate rather than fail it.
557
+ */
558
+ expectedAmount: number;
559
+ /** Our Arkade claim's txid, once submitted. Set from the callback's return
560
+ * and never from a chain read — the chain's answer is `settled`. */
561
+ claimTxid?: string;
562
+ }
563
+ /**
564
+ * A monitored swap: a live record holding derived `Uint8Array`s, whose storable
565
+ * projection is `RfqSwapRecord`. With {@link RfqSwapManagerDeps.repository} the manager
566
+ * writes and rebuilds these itself ({@link RfqSwapManager.restoreFromRepository});
567
+ * otherwise the caller persists via {@link RfqSwapManagerCallbacks.saveSwap} and hands
568
+ * rebuilt swaps to {@link RfqSwapManager.start}.
569
+ *
570
+ * **`onchain:BTC->arkade:BTC` is deliberately not a member**: monitoring only its lockup
571
+ * half would silently let the trader's own L1 refund window pass.
572
+ */
573
+ type RfqSwap = LightningSendSwap | OnchainSendSwap | LightningReceiveSwap;
574
+ /** What the manager should do next about an onchain-send swap's L1 half.
575
+ *
576
+ * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
577
+ */
578
+ type OnchainSendAction =
579
+ /** Not funded yet, or not confirmed deep enough. */
580
+ "wait"
581
+ /** Funded, confirmed, and far enough from the refund leaf to claim safely. */
582
+ | "claim"
583
+ /** The claim is off the table for good; the money comes back through the
584
+ * Arkade lockup instead. */
585
+ | "claim_window_closed"
586
+ /** Our claim already landed (only the trader holds P). */
587
+ | "claimed"
588
+ /** The solver took its L1 refund — the fill is gone. */
589
+ | "swept";
590
+ /**
591
+ * The decision a "poll status, refund on timeout" loop gets wrong.
592
+ *
593
+ * `refundable` does NOT mean "refund the L1 HTLC": that leaf is the SOLVER's, so reaching
594
+ * it means the trader's claim was missed and only the Arkade-side refund remains.
595
+ *
596
+ * And `classifyOnchainHtlc` reports `claimable` until MTP reaches `refundLocktime`, while
597
+ * `claimOnchainFill` refuses from {@link ONCHAIN_CLAIM_MARGIN_SECONDS} before it
598
+ * (publishing P into the solver's live refund window risks losing the race AND the
599
+ * preimage). This function applies that margin so the drive falls back instead of
600
+ * throwing every poll.
601
+ */
602
+ declare function nextOnchainAction(input: {
603
+ phase: OnchainHtlcPhase;
604
+ /** `htlc.refundLocktime` — when the solver's L1 refund leaf opens. */
605
+ htlcLocktime: number;
606
+ /** Unix seconds. */
607
+ now: number;
608
+ }): OnchainSendAction;
609
+ /** What the trader's own `refundWithoutReceiver` push returned, or `null` when
610
+ * the lockup held nothing to return.
611
+ */
612
+ type ArkadeRefundResult = {
613
+ txid: string;
614
+ amount: number;
615
+ } | null;
616
+ /**
617
+ * The money-moving half, injected. The manager decides when; these do it.
618
+ *
619
+ * Use `arkadeRefunder` for `refundArkade` rather than assembling it. Do NOT wire it to
620
+ * `refundIfUnresolved`, whose own polling and MTP retry loop would nest inside the
621
+ * manager's. Resolve the sender key via `senderIdentityForSwapRecord`, which turns "this
622
+ * wallet cannot sign" into {@link RefundNotLocallyPossibleError} (`needs_counterparty`)
623
+ * instead of retrying for the whole refund window.
624
+ */
625
+ interface RfqSwapManagerCallbacks {
626
+ /** Build and broadcast the L1 claim. See `claimOnchainFill`. */
627
+ claimOnchain: (swap: OnchainSendSwap, utxo: ChainUtxo) => Promise<{
628
+ txid: string;
629
+ }>;
630
+ /**
631
+ * Claim the solver-funded lockup on a receive leg, revealing `P`. Wire it to
632
+ * `pushClaim` (the outputs are supplied, so `claimReceiveLockup`'s wait is redundant).
633
+ *
634
+ * **Pass `expectedAmount` and `partiallyClaimed` straight through.** The manager's
635
+ * value check decides WHEN to act; `pushClaim`'s decides whether `P` is published and
636
+ * is the load-bearing one. Do not drop it because the outer one exists.
637
+ */
638
+ claimLockup: (swap: LightningReceiveSwap, vtxos: readonly LockupVtxo[], options: {
639
+ /** A claim of ours is already out, so `P` is public and the value gate has
640
+ * nothing left to protect; lets a piecemeal funding still be swept. */
641
+ partiallyClaimed: boolean;
642
+ }) => Promise<{
643
+ txid: string;
644
+ amount: number;
645
+ }>;
646
+ /**
647
+ * Push `refundWithoutReceiver` for every output at the lockup (see
648
+ * `pushRefundWithoutReceiver`); return `null` for an empty lockup. Never called for a
649
+ * {@link LightningReceiveSwap}.
650
+ *
651
+ * Only {@link RefundNotLocallyPossibleError} is permanent. Any other throw is RETRIED
652
+ * each poll (reported via `onSwapFailed`) until `refundLocktime +
653
+ * REFUND_MTP_LAG_SECONDS`, then `failed` — right for e.g. `LockupNeedsRecoveryError`,
654
+ * but a wiring bug that always throws also looks transient. Throw
655
+ * {@link RefundNotLocallyPossibleError} for anything this wallet can never do.
656
+ */
657
+ refundArkade: (swap: RfqSwap) => Promise<ArkadeRefundResult>;
658
+ /**
659
+ * Whether a local refund is possible at all. Called every pass, even *before* the
660
+ * window opens, so an unrefundable swap says so while the solver can still act, and
661
+ * restoring the right wallet lifts it. Never called for a receive swap.
662
+ *
663
+ * Optional: omit to learn at push time via {@link RefundNotLocallyPossibleError}.
664
+ * Local by contract — no network call belongs here.
665
+ */
666
+ canRefundArkade?: (swap: RfqSwap) => Promise<{
667
+ ok: true;
668
+ } | {
669
+ ok: false;
670
+ reason: string;
671
+ }>;
672
+ /**
673
+ * Persist the record. Called after any pass that changed it.
674
+ *
675
+ * With {@link RfqSwapManagerDeps.repository} wired this is the SECOND write (after the
676
+ * canonical record); both must succeed for the pass to count as persisted. Keep it for
677
+ * secondary sinks only (metrics, a cache), not a duplicate write of that repository.
678
+ */
679
+ saveSwap: (swap: RfqSwap) => Promise<void>;
680
+ }
681
+ /**
682
+ * What {@link RfqSwapManager.setCallbacks} accepts: the full contract with the two
683
+ * kind-gated claims and `saveSwap` optional, so a consumer driving only lightning sends
684
+ * need not stub them to throw. Omitting all persistence is process-local mode.
685
+ *
686
+ * A kind whose claim is missing blocks at runtime instead: non-terminal, re-evaluated
687
+ * every pass, lifted once `setCallbacks` supplies it.
688
+ */
689
+ type AvailableRfqSwapManagerCallbacks = Omit<RfqSwapManagerCallbacks, "claimOnchain" | "claimLockup" | "saveSwap"> & Partial<Pick<RfqSwapManagerCallbacks, "claimOnchain" | "claimLockup" | "saveSwap">>;
690
+ type RfqSwapActionName = "claimOnchain" | "claimLockup" | "refundArkade";
691
+ /** @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
692
+ interface RfqSwapManagerEvents {
693
+ /** Every state change, including backwards ones: `claimed -> claimable` is expected on
694
+ * a receive the solver tops up after a claim. States describe what to do next, not
695
+ * progress. */
696
+ onSwapUpdate?: (swap: RfqSwap, previous: RfqSwapState) => void;
697
+ /** Fired once, when a swap leaves monitoring `settled` or `refunded`. Mutually
698
+ * exclusive with the final `onSwapFailed`. */
699
+ onSwapCompleted?: (swap: RfqSwap) => void;
700
+ /** Fired for any action that threw — including ones the manager will retry
701
+ * on the next pass — and once more when the swap finally ends `failed`. */
702
+ onSwapFailed?: (swap: RfqSwap, error: Error) => void;
703
+ onActionExecuted?: (swap: RfqSwap, action: RfqSwapActionName) => void;
704
+ }
705
+ type SwapUpdateListener = NonNullable<RfqSwapManagerEvents["onSwapUpdate"]>;
706
+ type SwapCompletedListener = NonNullable<RfqSwapManagerEvents["onSwapCompleted"]>;
707
+ type SwapFailedListener = NonNullable<RfqSwapManagerEvents["onSwapFailed"]>;
708
+ type ActionExecutedListener = NonNullable<RfqSwapManagerEvents["onActionExecuted"]>;
709
+ /** @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
710
+ interface RfqSwapManagerConfig {
711
+ /** Drive claims and refunds automatically (default: true). With this off the manager
712
+ * still watches and reports. */
713
+ enableAutoActions?: boolean;
714
+ /** How often to run a pass, ms. Default 5000. */
715
+ pollIntervalMs?: number;
716
+ /** Injected for tests; defaults to wall clock, in unix seconds. */
717
+ now?: () => number;
718
+ events?: RfqSwapManagerEvents;
719
+ }
720
+ /** The contract-manager surface this needs, satisfied structurally by a real
721
+ * `ContractManager` (`await wallet.getContractManager()`). */
722
+ type SwapContractRegistry = Pick<IContractManager, "createContract" | "getContracts" | "getContractsWithVtxos" | "onContractEvent" | "setContractWatchState">;
723
+ /**
724
+ * The record store the manager writes to: the four RFQ methods of `AssetSwapRepository`,
725
+ * so other backing stores need not implement the rest.
726
+ *
727
+ * Expect TWO calls per dirty swap per poll, `getRfqSwap` then `saveRfqSwap`: the store is
728
+ * the system of record, so a consumer's edit to a record's origin half must not be
729
+ * overwritten by the manager's boot-time copy.
730
+ */
731
+ interface RfqSwapRecordStore {
732
+ saveRfqSwap(record: RfqSwapRecord): Promise<void>;
733
+ getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
734
+ getRfqSwapsPage: AssetSwapRepository["getRfqSwapsPage"];
735
+ removeRfqSwap(rfqId: string): Promise<void>;
736
+ }
737
+ /**
738
+ * A swap was handed to the manager with a repository wired, no origin, and no record
739
+ * already in the store. Thrown at the door, not at the first write a pass later: by then
740
+ * funding is broadcast and the record would exist only in memory. Pass the origin the
741
+ * request entrypoint returned.
742
+ *
743
+ * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
744
+ */
745
+ declare class RfqSwapOriginRequired extends Error {
746
+ /** The swap that could not be admitted. */
747
+ readonly rfqId: string;
748
+ constructor(rfqId: string);
749
+ }
750
+ /** One stored record that could not be turned back into a live swap.
751
+ *
752
+ * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
753
+ */
754
+ interface RfqRestoreFailure {
755
+ rfqId: string;
756
+ /** Why — a covenant that does not derive the funded address, a lockup with
757
+ * no contract row, a corridor with no handler registered. */
758
+ error: Error;
759
+ }
760
+ /** @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`. */
761
+ interface RfqRestoreOptions {
762
+ /**
763
+ * Where each record's covenant parameters come from. Defaults to the lockup's contract
764
+ * row via {@link RfqSwapManagerDeps.contracts}. Whatever it returns is checked against
765
+ * the funded address by `rebuildRfqSwap`, so an override cannot watch the wrong
766
+ * covenant.
767
+ */
768
+ params?: (record: RfqSwapRecord) => Promise<LockupParams>;
769
+ /** Include terminal history in the returned array. Expensive for large wallets. */
770
+ includeTerminal?: boolean;
771
+ }
772
+ /** What {@link RfqSwapManager.restoreFromRepository} did.
773
+ *
774
+ * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
775
+ */
776
+ interface RfqRestoreResult {
777
+ /** Rebuilt active swaps, plus terminal history when `includeTerminal` is set. */
778
+ restored: RfqSwap[];
779
+ /** Kept in the store, but not rebuildable right now. */
780
+ failed: RfqRestoreFailure[];
781
+ /** Compatibility field; normal restore leaves history stored. */
782
+ pruned: string[];
783
+ }
784
+ /** The observation seams. None is owned by the manager and none holds keys; there is no
785
+ * `RfqTransport` on purpose (see the module doc). */
786
+ interface RfqSwapManagerDeps {
787
+ /** Arkade access: how every swap's resolution is determined. */
788
+ indexer: LockupSpendIndexer;
789
+ /** L1 access. Required to monitor onchain-send swaps. */
790
+ chain?: ChainSource;
791
+ /**
792
+ * The CANONICAL sink for RFQ swap records, read back by
793
+ * {@link RfqSwapManager.restoreFromRepository}. A first write needs the request-time
794
+ * `origin` ({@link RfqSwapManager.addSwap}).
795
+ */
796
+ repository?: RfqSwapRecordStore;
797
+ /**
798
+ * The wallet's contract manager (prefer `await wallet.getContractManager()`). Required:
799
+ * the lockup's VTXO state is read through `getContractsWithVtxos`, so claim and refund
800
+ * cannot work without it.
801
+ */
802
+ contracts: SwapContractRegistry;
803
+ }
804
+ /**
805
+ * Watches a set of live RFQ swaps and drives each to its end.
806
+ *
807
+ * One pass per swap every {@link RfqSwapManagerConfig.pollIntervalMs}, and early when a
808
+ * contract event names its lockup (which changes only WHEN a pass runs; see
809
+ * {@link subscribe}):
810
+ *
811
+ * 0. **Register the lockup** if needed. Best-effort; never blocks the steps below.
812
+ * 1. **Ask the chain what became of the lockup** ({@link readLockupFate}). A spend whose
813
+ * witness HASHES to `payment_hash` ends the swap `settled`; fully spent otherwise ends
814
+ * it `refunded`. `unknown` is NOT an answer: the pass continues, since deadlines ignore
815
+ * indexer outages. `exited` blocks the Arkade half but leaves the L1 half running.
816
+ * 2. **Drive the trader's claim**: the L1 fill on an onchain send
817
+ * ({@link nextOnchainAction}); the lockup itself on a receive, which ends the pass.
818
+ * 3. **Take the lockup back** (send legs, after `refundLocktime`), even after a
819
+ * successful L1 claim: the lockup is still the trader's if the solver never takes it.
820
+ * If no local refund is possible, report `needs_counterparty` instead of retrying.
821
+ *
822
+ * On a receive leg step 1's readings invert: `settled` is the trader's own claim,
823
+ * `refunded` the solver reclaiming an unclaimed lockup. And on the receive arm:
824
+ *
825
+ * - **A claim is matched by its preimage, never by our txid**, so a claim that lands
826
+ * without us (e.g. covclaimd) is still `settled`.
827
+ * - **`LockupFate.fate === "claimed"` maps to state `settled`, never `claimed`**: the
828
+ * state `claimed` only means we submitted something.
829
+ *
830
+ * @deprecated Use `createSwapClient`. Moved off the package root to `@arkade-os/swap/protocol`.
831
+ */
832
+ declare class RfqSwapManager {
833
+ private static readonly POLL_CONCURRENCY;
834
+ private readonly deps;
835
+ private readonly config;
836
+ private callbacks;
837
+ private readonly swapUpdateListeners;
838
+ private readonly swapCompletedListeners;
839
+ private readonly swapFailedListeners;
840
+ private readonly actionExecutedListeners;
841
+ private readonly monitored;
842
+ /** Monitored swaps by lockup script hex: a contract event names only a script. */
843
+ private readonly byLockupScript;
844
+ /**
845
+ * Swaps whose lockup registration has SETTLED, mapped to whether a contract row
846
+ * resulted. Membership stops per-pass round trips; the value stops a never-registered
847
+ * swap from retiring a nonexistent row and reporting a spurious failure.
848
+ */
849
+ private readonly registered;
850
+ /**
851
+ * Swaps whose `refundArkade` threw {@link RefundNotLocallyPossibleError} in this
852
+ * process, so the push is not re-issued every pass. Only
853
+ * {@link RfqSwapManagerCallbacks.canRefundArkade} clears it.
854
+ */
855
+ private readonly refundRefused;
856
+ /**
857
+ * Lockup outpoints already handed to a receive swap's claim callback, by rfqId. After a
858
+ * claim SUCCEEDS the indexer may still list its outputs as unspent; without this each
859
+ * pass would re-submit and report a working swap as failing. Process-local: a restart
860
+ * costs at most one rejected re-claim.
861
+ */
862
+ private readonly claimedOutpoints;
863
+ /** Live `onContractEvent` subscription, held so `stop()` can drop it. */
864
+ private unsubscribeContracts;
865
+ /** Recent terminal swaps; older durable outcomes are read from the record store on demand. */
866
+ private readonly finished;
867
+ /** Explicit removals stay suppressed for this manager lifetime; normal completions never enter this set.
868
+ * Each maps to its removal sequence, so restore can tell a removal made during its rebuild. */
869
+ private readonly removed;
870
+ private removalSeq;
871
+ private readonly waiters;
872
+ /**
873
+ * The request-time origin of each swap, by rfqId, needed to CREATE a record. Kept for
874
+ * the swap's whole life so a record the store loses is rewritten; dropped by
875
+ * {@link removeSwap} and by retention.
876
+ */
877
+ private readonly origins;
878
+ /** Records changed during the current pass, flushed to the repository and
879
+ * through `saveSwap`. */
880
+ private readonly dirty;
881
+ /** Race guard: one action at a time per swap. */
882
+ private readonly inProgress;
883
+ private activePolls;
884
+ private readonly pollWaiters;
885
+ private timer;
886
+ private running;
887
+ constructor(deps: RfqSwapManagerDeps, config?: RfqSwapManagerConfig);
888
+ /** Wire the money-moving half. Without it the manager only watches. See
889
+ * {@link AvailableRfqSwapManagerCallbacks}. */
890
+ setCallbacks(callbacks: AvailableRfqSwapManagerCallbacks): void;
891
+ onSwapUpdate(listener: SwapUpdateListener): () => void;
892
+ onSwapCompleted(listener: SwapCompletedListener): () => void;
893
+ onSwapFailed(listener: SwapFailedListener): () => void;
894
+ onActionExecuted(listener: ActionExecutedListener): () => void;
895
+ /**
896
+ * Rebuild stored swaps and take over monitoring them. By default only active states
897
+ * are read; terminal history stays stored and a late completion lookup reads one record
898
+ * by key (`includeTerminal` loads everything). Deliberately not part of {@link start},
899
+ * so records can be inspected without driving money. An unrebuildable record lands in
900
+ * {@link RfqRestoreResult.failed}, never fatal to the others.
901
+ */
902
+ restoreFromRepository(options?: RfqRestoreOptions): Promise<RfqRestoreResult>;
903
+ /**
904
+ * Drop stored records that are terminal and past `RFQ_SWAP_RETENTION_SECONDS` (per
905
+ * `shouldRetainRfqSwap`), and return their ids. Explicit only: restore keeps history.
906
+ * Loads every stored record; no backend offers indexed deletion.
907
+ */
908
+ pruneRetiredSwaps(): Promise<string[]>;
909
+ private dropRetired;
910
+ private forgetRetired;
911
+ private requireRepository;
912
+ /** The default covenant source: the wallet's own contract row for each lockup. */
913
+ private paramsFromContracts;
914
+ /**
915
+ * Load records and begin monitoring: one pass immediately (a restart may already be
916
+ * past a deadline), then every `pollIntervalMs`. Terminal outcomes in a repository are
917
+ * read on demand. Calling it again while running loads the records without re-arming,
918
+ * so a double-start never strands a funded swap.
919
+ *
920
+ * With a repository wired, a swap the store has never seen throws
921
+ * {@link RfqSwapOriginRequired} (use {@link addSwap} with its origin, or
922
+ * {@link restoreFromRepository}). Every swap is checked before any is tracked.
923
+ */
924
+ start(swaps?: readonly RfqSwap[]): Promise<void>;
925
+ /**
926
+ * Stop monitoring: clear the timer and drop the contract subscription. In-flight
927
+ * actions run to completion and {@link waitForSwapCompletion} promises stay pending
928
+ * (stop/start is a pause). Contract registrations are NOT undone: they are the
929
+ * wallet's, and dropping them would unwatch a still-funded lockup.
930
+ */
931
+ stop(): Promise<void>;
932
+ /**
933
+ * Begin monitoring a swap; polled immediately when the manager is running.
934
+ *
935
+ * @param origin - The request-time half a live swap cannot carry, needed to write its
936
+ * FIRST record. Required with a repository wired unless the store already holds the
937
+ * record (else {@link RfqSwapOriginRequired}). Inert without a repository.
938
+ */
939
+ addSwap(swap: RfqSwap, origin?: RfqSwapOrigin): Promise<void>;
940
+ /**
941
+ * Settle where this swap's record will come from, before it is monitored: a passed
942
+ * origin, one remembered from an earlier `addSwap`, or the stored record (one read).
943
+ */
944
+ private admit;
945
+ /** Forget a swap entirely, monitored or finished. Its contract row is left alone: the
946
+ * script may still hold money, and only a terminal swap's row is retired. */
947
+ removeSwap(rfqId: string): Promise<void>;
948
+ /** Every swap still being monitored. */
949
+ getPendingSwaps(): Promise<RfqSwap[]>;
950
+ /**
951
+ * Every swap this manager holds: {@link getPendingSwaps} plus the finished ones this
952
+ * process has seen (after {@link restoreFromRepository}, the retained history).
953
+ */
954
+ getAllSwaps(): Promise<RfqSwap[]>;
955
+ hasSwap(rfqId: string): Promise<boolean>;
956
+ /** True while an action for this swap holds the per-swap lock. */
957
+ isProcessing(rfqId: string): Promise<boolean>;
958
+ /** `finishedSwaps` counts terminal swaps cached in memory, not those only in the repository. */
959
+ getStats(): Promise<{
960
+ isRunning: boolean;
961
+ monitoredSwaps: number;
962
+ finishedSwaps: number;
963
+ inProgress: number;
964
+ pollIntervalMs: number;
965
+ }>;
966
+ /**
967
+ * Run one monitoring pass over every swap now, e.g. when a mobile app resumes. Passes
968
+ * do not overlap per swap: a concurrent call is a no-op for a swap already in progress.
969
+ */
970
+ poll(): Promise<void>;
971
+ private pollMany;
972
+ private acquirePollSlot;
973
+ /**
974
+ * Resolve once this swap's PAYOUT is decided: for onchain-send that is the L1 claim
975
+ * (`claimTxid` set), whatever the record's later label; otherwise `settled`/`refunded`
976
+ * (see {@link isPayoutDecided}).
977
+ *
978
+ * Rejects only on `failed`. `refunded` resolves, and on a receive leg it means the swap
979
+ * was lost — read `state`, do not infer success from resolution.
980
+ */
981
+ waitForSwapCompletion(rfqId: string): Promise<RfqSwapOutcome>;
982
+ private track;
983
+ /** Drops the swap from BOTH indexes. `pollSwap`'s `monitored` check also stops a late
984
+ * event, deliberately redundant so neither change alone re-drives a removed swap. */
985
+ private untrack;
986
+ /**
987
+ * Turn the indexer's push into an extra reason to run a pass — and nothing more.
988
+ *
989
+ * **Deliberately not a source of truth.** The pass re-reads the lockup via
990
+ * {@link readLockupFate}, so a missed, duplicated, reordered or FORGED event only
991
+ * changes latency, never beliefs, and never causes a claim or refund on its own. This
992
+ * must survive future changes: a BELIEVED event turns a relay outage into a correctness
993
+ * bug. The timer stays armed as the failsafe; every money deadline is an absolute
994
+ * timelock.
995
+ */
996
+ private subscribe;
997
+ /**
998
+ * Register this swap's lockup with the wallet's contract manager, once. A backstop:
999
+ * the request entrypoints register before funding, and `createContract` is
1000
+ * first-writer-wins.
1001
+ *
1002
+ * Best-effort: a failure is reported and retried next pass, never aborting this one.
1003
+ * Failing the pass over bookkeeping would trade a real timelock deadline for it.
1004
+ */
1005
+ private ensureRegistered;
1006
+ /** Stop watching a finished swap's lockup. `retained`, not deleted: the row keeps the
1007
+ * lockup's history readable while leaving the subscription and poll. Best-effort. */
1008
+ private retireContract;
1009
+ private arm;
1010
+ private pollSwap;
1011
+ private runPass;
1012
+ /**
1013
+ * The lockup was unilaterally exited: its outputs sit onchain, beyond any offchain
1014
+ * spend. `needs_counterparty`, not terminal: it can still end either way onchain. Set
1015
+ * here, not in `driveArkadeRefund`, whose `unblock` calls would lift it next pass.
1016
+ */
1017
+ private blockExitedLockup;
1018
+ /**
1019
+ * The receive leg's whole state machine: claim the solver-funded lockup while the
1020
+ * window is open, and recognise the shapes in which it can be lost.
1021
+ *
1022
+ * **The window closes at `refundLocktime`, on wall clock, with no margin.** Publishing
1023
+ * `P` into the solver's live refund window risks losing the race. No margin (unlike
1024
+ * `ONCHAIN_CLAIM_MARGIN_SECONDS`, which budgets for confirmations): this offchain claim
1025
+ * lands in seconds, and the solver's CLTV matures on MTP, which trails wall clock.
1026
+ *
1027
+ * After the window the trader has no move; the manager only watches.
1028
+ */
1029
+ private driveReceiveClaim;
1030
+ /** Claim what the solver funded, once it is enough (the inner gate that matters is
1031
+ * `pushClaim`'s; see {@link RfqSwapManagerCallbacks.claimLockup}). */
1032
+ private claimIfFunded;
1033
+ /** `handled` ends the pass; `continue` falls through to the refund gate. */
1034
+ private driveOnchain;
1035
+ private driveArkadeRefund;
1036
+ /** Whether any output was never handed to the claim callback (the only reason to
1037
+ * claim twice). */
1038
+ private hasUnclaimedOutpoint;
1039
+ private rememberClaimed;
1040
+ /**
1041
+ * L1 progress, which past the refund window must not overwrite a refusal: `claimed` is
1042
+ * re-asserted from chain every pass, so a blocked swap would flip forever. Only the
1043
+ * label defers; the claim itself always runs.
1044
+ */
1045
+ private setOnchainState;
1046
+ /** The probe's refusal reason, or `undefined`. A throwing probe is a refusal. */
1047
+ private probeRefusal;
1048
+ /** Report that no local refund will happen, without ending the swap. */
1049
+ private block;
1050
+ /** The way back out once actionable: to `claimed` if a claim txid exists, else
1051
+ * `pending`. */
1052
+ private unblock;
1053
+ /**
1054
+ * Record which ark transactions ended the lockup. Only named ark txids: a checkpoint
1055
+ * txid would name a transaction the wallet's activity never shows. Assigned, not
1056
+ * merged: the fate is one complete read, reached once.
1057
+ */
1058
+ private stampLockupSpends;
1059
+ /**
1060
+ * Keep the preimage that settled a Lightning send. Only that leg: the others' preimages
1061
+ * are the wallet's own secrets, already recoverable from `profile`.
1062
+ */
1063
+ private stampSettlementPreimage;
1064
+ private touch;
1065
+ private setState;
1066
+ /** Terminal failure. The `onSwapFailed` emission is left to
1067
+ * {@link finalize}, so this does not double-report. */
1068
+ private fail;
1069
+ private emitFailed;
1070
+ private emitAction;
1071
+ /**
1072
+ * Flush a changed record to every wired sink; true only if all took it (else it stays
1073
+ * dirty and unfinalized). The canonical repository write goes FIRST and a failure skips
1074
+ * `saveSwap`, so the secondary sink never gets ahead of the primary.
1075
+ */
1076
+ private save;
1077
+ /** The canonical write. True when there is no repository to write to. */
1078
+ private saveRecord;
1079
+ private originOrThrow;
1080
+ /** Drop a terminal swap from monitoring and report it exactly once, through either
1081
+ * `onSwapCompleted` or `onSwapFailed`. */
1082
+ private finalize;
1083
+ private rememberFinished;
1084
+ private settleWaiters;
1085
+ }
1086
+ /** What {@link RfqSwapManager.waitForSwapCompletion} reports. `txid` is the trader's own
1087
+ * claim or pushed refund, and always names something that landed; solver-side outcomes
1088
+ * and a lost receive carry none. Read `state` for whether the swap paid out.
1089
+ *
1090
+ * @deprecated Use `createSwapClient` and `client.onUpdate()`. Moved off the package root to `@arkade-os/swap/protocol`.
1091
+ */
1092
+ interface RfqSwapOutcome {
1093
+ state: RfqSwapState;
1094
+ txid?: string;
1095
+ }
1096
+
1097
+ /**
1098
+ * The swap kinds this projection covers — all three the manager monitors. `onchain_send`'s L1 keys
1099
+ * ride in its profile, since no contract row or `OnchainHtlc` field can give them back.
1100
+ */
1101
+ type PersistableRfqSwap = LightningSendSwap | LightningReceiveSwap | OnchainSendSwap;
1102
+ /**
1103
+ * The serialized covenant parameters a rebuild is given: `VHTLCV2ContractHandler`'s own wire shape,
1104
+ * exactly what a lockup's contract row stores under `params`.
1105
+ */
1106
+ type LockupParams = Record<string, string>;
1107
+ /**
1108
+ * How long a retired swap's record is kept, in SECONDS (the unit of `RfqSwap.updatedAt`).
1109
+ * Terminal records are history the wallet's own tx history cannot reconstruct; only the
1110
+ * explicit prune API drops them, restore keeps them.
1111
+ */
1112
+ /** @deprecated `accept()` writes the record; read it with `client.swaps()`. Moved off the package root to `@arkade-os/swap/protocol`. */
1113
+ declare const RFQ_SWAP_RETENTION_SECONDS: number;
1114
+ /** The immutable request-time half, and only what EVERY corridor has. Hex for
1115
+ * everything binary, so the record is plain JSON and survives any
1116
+ * structured-clone backend unchanged. */
1117
+ interface RfqSwapOrigin {
1118
+ /**
1119
+ * Which corridor this is. Resolves the handler that owns {@link profile};
1120
+ * see `rfqCorridor.ts`.
1121
+ *
1122
+ * The manager's own union, not an open string: a kind it does not branch on would persist and
1123
+ * rebuild here and then never be driven.
1124
+ */
1125
+ kind: PersistableRfqSwap["kind"];
1126
+ /**
1127
+ * The Arkade address that was funded: the handle {@link lockupContractParams} looks the row up
1128
+ * by, and, being taken from the entry point, the check that supplied params are THIS swap's.
1129
+ */
1130
+ lockupAddress: string;
1131
+ /**
1132
+ * The corridor's own half, as plain JSON — written by the caller from the
1133
+ * request result, kept current by the handler's `project`.
1134
+ *
1135
+ * Opaque here, so a new corridor ships without touching this file or the stores. Carries the
1136
+ * corridor's keys (`signer`, and `hashlock` with the `sha256(P)` the covenant cannot give
1137
+ * back); write them with `rfqSecretsProfile`. Not a consumer scratchpad: every write merges
1138
+ * `handler.project(swap)` over it.
1139
+ */
1140
+ profile: Record<string, unknown>;
1141
+ /** Consumer display metadata. The rebuild ignores it — `RfqSwapCommon`
1142
+ * carries no amount of its own. */
1143
+ amount?: number;
1144
+ /**
1145
+ * The ark transaction that funded {@link lockupAddress}. Origin, not manager state: only the
1146
+ * caller that broadcast it knows it, so it is written once and no `project` emits it.
1147
+ */
1148
+ fundingTxid?: string;
1149
+ }
1150
+ /** The stored record: the origin plus the manager's mutable state. */
1151
+ interface RfqSwapRecord extends RfqSwapOrigin {
1152
+ rfqId: string;
1153
+ state: RfqSwapState;
1154
+ createdAt: number;
1155
+ updatedAt: number;
1156
+ refundTxid?: string;
1157
+ /** See `RfqSwapCommon.lockupSpendTxids`. */
1158
+ lockupSpendTxids?: string[];
1159
+ /** See `RfqSwapCommon.settlementPreimageHex`. */
1160
+ settlementPreimageHex?: string;
1161
+ failure?: string;
1162
+ /** Last local receive-claim error while the swap is still retryable. */
1163
+ claimFailure?: string;
1164
+ blockedReason?: string;
1165
+ }
1166
+ /**
1167
+ * A stored record read under the current field names.
1168
+ *
1169
+ * `0.0.8`/`0.0.9` wrote `fundingArkTxid`, `refundArkTxid`, `lockupSpendArkTxids` and
1170
+ * `profile.claimArkTxid`, which current code would read as `undefined`. Every function here that
1171
+ * takes a record calls this, so no boot-time migration is needed and the next write drops the old
1172
+ * keys. Sharpest effect: a partly claimed receive leg keeps its `claimTxid`, so the value gate
1173
+ * stays disarmed over a public preimage.
1174
+ */
1175
+ declare function normalizeRfqSwapRecord(record: RfqSwapRecord): RfqSwapRecord;
1176
+ /** First write, at the moment the caller hands the swap to the manager. */
1177
+ declare function createRfqSwapRecord(origin: RfqSwapOrigin, swap: PersistableRfqSwap): RfqSwapRecord;
1178
+ /**
1179
+ * Every later write. The origin half is carried through untouched.
1180
+ *
1181
+ * The mutable half is REPLACED, not merged: `managerState` omits keys the live swap no longer
1182
+ * carries, and the manager deliberately clears `blockedReason` and `claimFailure`, whose stale
1183
+ * values would read as live refusal or retry state.
1184
+ */
1185
+ declare function updateRfqSwapRecord(record: RfqSwapRecord, swap: PersistableRfqSwap): RfqSwapRecord;
1186
+ /**
1187
+ * The immutable half of a stored record, on its own.
1188
+ *
1189
+ * Passing a `record` where an {@link RfqSwapOrigin} is wanted type-checks but is a bug: spread into
1190
+ * {@link createRfqSwapRecord} it carries stale `failure`/`blockedReason`/`claimFailure`/
1191
+ * `refundTxid` that `managerState` cannot clear. `restoreFromRepository` keeps this per record so
1192
+ * a later write can recreate a record the store lost.
1193
+ */
1194
+ declare function rfqSwapOriginOf(record: RfqSwapRecord): RfqSwapOrigin;
1195
+ /**
1196
+ * Rebuild the live record, purely and synchronously, for {@link RfqSwapManager.start}. `params`
1197
+ * (from {@link lockupContractParams} or a consumer-kept copy) are checked against the funded
1198
+ * address.
1199
+ */
1200
+ declare function rebuildRfqSwap(record: RfqSwapRecord, params: LockupParams): PersistableRfqSwap;
1201
+ /**
1202
+ * Whether a retired swap's record should be kept.
1203
+ *
1204
+ * `needs_counterparty` is not terminal and is never dropped: the money is still at the lockup and
1205
+ * the refusal is re-checked every pass.
1206
+ *
1207
+ * @param now Current time in **unix seconds**, the unit of `RfqSwap.updatedAt`. Pass
1208
+ * `Math.floor(Date.now() / 1000)`, never `Date.now()`: milliseconds against a seconds window would
1209
+ * retire every terminal record after ~43 minutes.
1210
+ */
1211
+ declare function shouldRetainRfqSwap(record: RfqSwapRecord, now: number): boolean;
1212
+
1213
+ /** What the codec needs from an asset. Structural, so discovery's `AssetInfo` satisfies it. */
1214
+ interface AssetScale {
1215
+ decimals: number;
1216
+ }
1217
+ declare const ATOMIC_DECIMAL: unique symbol;
1218
+ /** Atomic units written out: the form records and the wire hold. */
1219
+ type AtomicDecimal = string & {
1220
+ readonly [ATOMIC_DECIMAL]: true;
1221
+ };
1222
+ /** A string that is provably not an {@link AtomicDecimal}; plain strings qualify. */
1223
+ type DisplayDecimal = string & {
1224
+ readonly [ATOMIC_DECIMAL]?: never;
1225
+ };
1226
+ /** Why an amount was refused. */
1227
+ type AmountRefusal = "not_decimal" | "negative" | "too_precise" | "too_large" | "invalid_decimals" | "not_canonical";
1228
+ /**
1229
+ * An amount that cannot be represented in the form asked for. Not a `SwapError` (that taxonomy is
1230
+ * the client's, thrown before value moves); the wire's compatibility failure is
1231
+ * `AmountEncodingUnsupported`, in `rfqAmount.ts`.
1232
+ */
1233
+ declare class AmountFormatError extends Error {
1234
+ readonly reason: AmountRefusal;
1235
+ readonly name = "AmountFormatError";
1236
+ constructor(reason: AmountRefusal, message: string);
1237
+ }
1238
+ declare const Amount: {
1239
+ /**
1240
+ * A human decimal into atomic units.
1241
+ *
1242
+ * `string` only, no exponent: a `number` makes `100000` ambiguous between sats and BTC, and the
1243
+ * ambiguity resolves only after funding. Refuses rather than rounds input finer than the asset
1244
+ * (a truncated amount is a swap for the wrong size), and refuses results that would not survive
1245
+ * the record boundary.
1246
+ */
1247
+ parse(display: DisplayDecimal, asset: AssetScale): bigint;
1248
+ /** Atomic units into a human decimal, trailing zeros trimmed. Refuses a negative: every amount
1249
+ * here is an obligation, so a negative one is an upstream defect. */
1250
+ format(value: bigint, asset: AssetScale): string;
1251
+ };
1252
+ /**
1253
+ * Atomic units into the canonical decimal string records and the wire hold:
1254
+ * discovery's `AMOUNT_PATTERN` — unsigned, no leading zeros, at most 30 digits.
1255
+ */
1256
+ declare const toAtomicDecimal: (value: bigint) => AtomicDecimal;
1257
+ /** The canonical decimal string back into atomic units. Takes a plain `string`, as record reads and
1258
+ * `JSON.parse` hand back, so the safe direction needs no cast. */
1259
+ declare const fromAtomicDecimal: (text: string) => bigint;
1260
+ /** Whether `value` is already in the canonical atomic form. */
1261
+ declare const isAtomicDecimal: (value: unknown) => value is AtomicDecimal;
1262
+
1263
+ /**
1264
+ * Asset identity for the v2 client: CAIP-19 with the rail as the CAIP-2
1265
+ * namespace — `<rail>:<network>/<asset-ns>:<reference>`.
1266
+ *
1267
+ * Rail, not settlement chain, as namespace: cross-rail sameness becomes a comparison on the asset
1268
+ * part (`arkade:bitcoin/slip44:0` vs `bitcoin:bitcoin/slip44:0`), and `bip122:…/arkade:…` would
1269
+ * assert a relationship Arkade does not have. These ids parse under CAIP-19 but `arkade`,
1270
+ * `bitcoin` and `bolt11` are in no CASA registry; meaning is the alias layer's job.
1271
+ */
1272
+
1273
+ /**
1274
+ * A CAIP-2 namespace this client can spell. Closed, so an unimplemented rail fails at parse.
1275
+ *
1276
+ * `bolt11` is lightning: CAIP-2 namespaces are 3-8 chars, which `lightning` and `ln` miss. BOLT12
1277
+ * will be a separate corridor. `eip155` is grammar only: the EVM corridor is deferred, and refusal
1278
+ * belongs where a route is chosen (the alias layer), not where a string is read.
1279
+ */
1280
+ declare const RAILS: readonly ["arkade", "bitcoin", "bolt11", "eip155"];
1281
+ type Rail = (typeof RAILS)[number];
1282
+ /** The rails whose CAIP-2 reference is a bitcoin network rather than a chain id. */
1283
+ declare const BITCOIN_RAILS: readonly ["arkade", "bitcoin", "bolt11"];
1284
+ type BitcoinRail = (typeof BITCOIN_RAILS)[number];
1285
+ /**
1286
+ * The network half of a bitcoin-family chain part: core's own {@link NetworkName}, since the
1287
+ * wallet is the only source of the network.
1288
+ *
1289
+ * Wider than discovery's `NETWORKS` (which omits `testnet`): an asset on testnet exists whether or
1290
+ * not a market index covers it.
1291
+ */
1292
+ type NetworkRef = NetworkName;
1293
+ type BitcoinAssetId<R extends BitcoinRail> = `${R}:${NetworkRef}/${string}:${string}`;
1294
+ /**
1295
+ * A public asset id.
1296
+ *
1297
+ * A template literal type, so the package's other asset spellings (core's 68-hex id, discovery's
1298
+ * `AssetInfo.id`, the RFQ leg's `arkade:BTC`) are compile errors here, and `AssetId<"arkade">`
1299
+ * accepts no `bitcoin:` string (see `route.ts`).
1300
+ *
1301
+ * Deliberately not branded, so `client.quote({ give: "arkade:bitcoin/slip44:0" })` stays writable.
1302
+ * A value from a record or the wire is a `string`: parse it with {@link parseAssetId}, never cast.
1303
+ */
1304
+ type AssetId<R extends Rail = Rail> = R extends BitcoinRail ? BitcoinAssetId<R> : `eip155:${number}/${string}:${string}`;
1305
+ /** The `<asset-ns>:<reference>` half of an id — what sameness compares. */
1306
+ type AssetPart = `${string}:${string}`;
1307
+ /**
1308
+ * BTC's asset part on mainnet.
1309
+ *
1310
+ * @deprecated BTC's asset part depends on the network; use {@link btcAssetPart}, or
1311
+ * {@link isBtcAsset} to recognize BTC. Kept with its mainnet meaning for one release.
1312
+ */
1313
+ declare const BTC_ASSET_PART = "slip44:0";
1314
+ /** The asset namespace an Arkade-issued asset takes. */
1315
+ declare const ARKADE_ASSET_NAMESPACE = "asset";
1316
+ interface ParsedAssetId {
1317
+ /** CAIP-2 namespace. */
1318
+ readonly rail: Rail;
1319
+ /**
1320
+ * CAIP-2 reference: the bitcoin network on a bitcoin-family rail, the
1321
+ * decimal chain id on `eip155`.
1322
+ */
1323
+ readonly reference: string;
1324
+ /** CAIP-19 asset namespace — `slip44`, `asset`, `erc20`. */
1325
+ readonly assetNamespace: AssetNamespace;
1326
+ /** CAIP-19 asset reference. */
1327
+ readonly assetReference: string;
1328
+ }
1329
+ /** Why an id was refused. Stable strings; callers switch on them. */
1330
+ type AssetIdRefusal = "malformed" | "uppercase" | "unknown_rail" | "unknown_network" | "invalid_chain_id" | "unknown_asset_namespace" | "invalid_asset_reference" | "token_id_unsupported" | "unknown_alias" | "ambiguous_alias";
1331
+ /**
1332
+ * A string that is not a public asset id.
1333
+ *
1334
+ * Not in the §7 `SwapError` taxonomy on purpose: that is thrown by verbs before value moves; this
1335
+ * is a codec refusing input before a swap exists (as core's `AssetId.fromBytes` does).
1336
+ */
1337
+ declare class AssetIdError extends Error {
1338
+ readonly reason: AssetIdRefusal;
1339
+ readonly value: string;
1340
+ constructor(reason: AssetIdRefusal, value: string, detail: string, options?: ErrorOptions);
1341
+ }
1342
+ /**
1343
+ * The asset namespaces this client spells, and the reference form each takes. Closed like the
1344
+ * rail set, so `arkade:bitcoin/asset:notahex` is a parse failure, not an unserved RFQ pair.
1345
+ */
1346
+ declare const REFERENCE_RULE: {
1347
+ readonly slip44: RegExp;
1348
+ /** The 68-lowercase-hex identity form; `asset.AssetId` then re-validates it. */
1349
+ readonly asset: RegExp;
1350
+ /**
1351
+ * Reserved for §9. Lowercase, never EIP-55: mixed case would be two spellings of one asset
1352
+ * comparing unequal in a pair string, a record and a cache key.
1353
+ */
1354
+ readonly erc20: RegExp;
1355
+ };
1356
+ type AssetNamespace = keyof typeof REFERENCE_RULE;
1357
+ /** Whether `value` is a network core can resolve. Read off core's own table, so
1358
+ * a network added there needs no edit here. */
1359
+ declare const isNetworkRef: (value: string) => value is NetworkRef;
1360
+ /**
1361
+ * Parse an id, or refuse it.
1362
+ *
1363
+ * @throws {AssetIdError} with a stable {@link AssetIdRefusal} `reason`.
1364
+ */
1365
+ declare const parseAssetId: (value: string) => ParsedAssetId;
1366
+ /** Whether `value` parses as a public asset id. */
1367
+ declare const isAssetId: (value: string) => value is AssetId;
1368
+ /** Build an id from its parts, validating the result. */
1369
+ declare const formatAssetId: <R extends Rail>(parts: ParsedAssetId & {
1370
+ rail: R;
1371
+ }) => AssetId<R>;
1372
+ /** The rail an id names. */
1373
+ declare const railOf: (id: AssetId) => Rail;
1374
+ /**
1375
+ * The bitcoin network an id settles on, or `undefined` on a rail whose CAIP-2
1376
+ * reference is a chain id rather than a network.
1377
+ */
1378
+ declare const bitcoinNetworkOf: (id: AssetId) => NetworkRef | undefined;
1379
+ /** The `<asset-ns>:<reference>` half. */
1380
+ declare const assetPartOf: (id: AssetId) => AssetPart;
1381
+ /**
1382
+ * Whether two ids name the same asset on (possibly) different rails.
1383
+ *
1384
+ * Only the rail is dropped; the CAIP-2 reference must still agree. Otherwise regtest BTC would
1385
+ * equal mainnet BTC, and an ERC-20 address copied across chains would equal its twin. Comparing
1386
+ * references across rail families is safe: a bitcoin network name is never a decimal chain id.
1387
+ */
1388
+ declare const sameAsset: (a: AssetId, b: AssetId) => boolean;
1389
+ /**
1390
+ * BTC's asset part on a bitcoin network: SLIP-44 coin type 0 ("Bitcoin") on mainnet, coin type 1
1391
+ * ("Testnet (all coins)") on every other network. Discovery's card validator enforces the same
1392
+ * split, so an id minted any other way never matches a card's `caip19_id`.
1393
+ */
1394
+ declare const btcAssetPart: (network: NetworkRef) => AssetPart;
1395
+ /** BTC on a bitcoin-family rail: the same coin, named once per rail. */
1396
+ declare const btcOn: <R extends BitcoinRail>(rail: R, network: NetworkRef) => AssetId<R>;
1397
+ /**
1398
+ * Whether `id` is BTC on its own network: `slip44:0` on mainnet, `slip44:1` elsewhere. Strict, so
1399
+ * new input with the wrong coin type for its network is not BTC.
1400
+ */
1401
+ declare const isBtcAsset: (id: AssetId) => boolean;
1402
+ /**
1403
+ * {@link isBtcAsset}, also accepting `slip44:0` on a test network: the id every network got
1404
+ * before BTC's asset part depended on the network. For ids read back from storage only, so a
1405
+ * record written then still reads as BTC; new input goes through {@link isBtcAsset}.
1406
+ */
1407
+ declare const isBtcAssetLenient: (id: AssetId) => boolean;
1408
+ /**
1409
+ * An Arkade-issued asset.
1410
+ *
1411
+ * Takes `asset.AssetId`, not hex: `hex.decode` accepts uppercase but `toString()` emits lowercase,
1412
+ * so the type enforces the case rule. The reference is that 68-hex identity verbatim, pinned by
1413
+ * `asset.ASSET_ID_VECTORS` across repos; adding a `<genesis_txid>.<idx>` spelling would be one
1414
+ * more silently-disagreeing site.
1415
+ */
1416
+ declare const arkadeAsset: (network: NetworkRef, id: asset.AssetId) => AssetId<"arkade">;
1417
+ /**
1418
+ * The issuance identity nested inside an arkade id; `undefined` for BTC.
1419
+ *
1420
+ * The inverse of {@link arkadeAsset}, and the round trip the shared vectors
1421
+ * pin: the 34 bytes in equal the 34 bytes out.
1422
+ */
1423
+ declare const issuanceOf: (id: AssetId<"arkade">) => asset.AssetId | undefined;
1424
+
1425
+ /**
1426
+ * The corridor axis, and its bijection with the rail namespaces.
1427
+ *
1428
+ * Routes speak `arkade | lightning | onchain`; CAIP-2 asset namespaces are `arkade | bolt11 |
1429
+ * bitcoin`. Both stay: rail names would make the public route vocabulary protocol-shaped, and
1430
+ * `lightning:` overruns CAIP-2's eight-character namespace cap. {@link railOfCorridor} is total, and
1431
+ * `route.ts` ties an endpoint's corridor to its asset's rail in the type system.
1432
+ */
1433
+
1434
+ /** The corridor a leg settles on — caller-facing route names, independent of discovery's CAIP rail
1435
+ * identifiers. */
1436
+ declare const CORRIDORS: readonly ["arkade", "lightning", "onchain"];
1437
+ type Corridor = (typeof CORRIDORS)[number];
1438
+ /** A corridor id: the three implemented corridors plus EVM chains. The template arm stays open on
1439
+ * purpose — which chains a registry lists is a listing decision, not an id-grammar one. */
1440
+ type CorridorId = Corridor | `eip155:${number}`;
1441
+ /** The rail namespace a corridor's assets are spelled on. */
1442
+ type RailOf<C extends CorridorId> = C extends "arkade" ? "arkade" : C extends "lightning" ? "bolt11" : C extends "onchain" ? "bitcoin" : "eip155";
1443
+ /** The rail a corridor's assets are spelled on. Total, and the type agrees. */
1444
+ declare const railOfCorridor: <C extends CorridorId>(corridor: C) => RailOf<C>;
1445
+ /** The corridor a rail belongs to, or `undefined` for `eip155`, whose corridor id needs a chain
1446
+ * reference this side cannot invent. */
1447
+ declare const corridorOfRail: (rail: Rail) => Corridor | undefined;
1448
+
1449
+ /**
1450
+ * The two string aliases the v2 surface is written in. Aliases rather than branded types, so
1451
+ * literals need no constructor.
1452
+ */
1453
+ /** Lowercase hex, no `0x` prefix — the encoding `@scure/base`'s `hex` emits. */
1454
+ type Hex = string;
1455
+ /** A secp256k1 public key as {@link Hex}: x-only (32 bytes) or compressed (33). */
1456
+ type Pubkey = Hex;
1457
+
1458
+ /**
1459
+ * One outcome vocabulary over the protocol's two state machines (`RfqSwapState` for
1460
+ * corridors, `AssetSwapStatus` for offers), and the translation that produces it.
1461
+ *
1462
+ * **The axis is whose lockup the pass reads, not send-versus-receive.** A non-claim spend
1463
+ * of the trader's lockup returns the trader's money (`refunded`); the identical spend of
1464
+ * the solver's lockup on `lightning -> arkade` means the incoming payment never arrived
1465
+ * (`lapsed`). So on the receive leg the wire's `refunded` is a LOSS.
1466
+ *
1467
+ * Ownership is read off {@link LIGHTNING_DRIVE} and {@link ONCHAIN_DRIVE}, not restated.
1468
+ */
1469
+
1470
+ /** What happened to a swap, trader-centric, in one vocabulary for both families (§3.5). */
1471
+ type Outcome =
1472
+ /** Persisted, and its funding has not been broadcast. */
1473
+ "accepted"
1474
+ /** The funding is broadcast and the drive has not adopted the swap yet. */
1475
+ | "funding"
1476
+ /** The trader's lockup is funded and the swap is live. */
1477
+ | "funded"
1478
+ /** Waiting on the counterparty: an unpaid invoice, an unfilled offer. */
1479
+ | "open"
1480
+ /** An offer covenant was filled. */
1481
+ | "filled"
1482
+ /** The trader's own claim is confirmed on chain. */
1483
+ | "claimed"
1484
+ /** A lightning send settled: the solver's hash-verified spend IS the
1485
+ * invoice being paid. */
1486
+ | "paid" | "cancelling" | "cancelled"
1487
+ /** A send leg past `refundLocktime` with a refund push in flight. */
1488
+ | "refunding"
1489
+ /** The trader's value came back. Send legs only, ever. */
1490
+ | "refunded"
1491
+ /** A receive leg the trader never claimed: the solver took the lockup back
1492
+ * and the incoming payment never arrived. */
1493
+ | "lapsed"
1494
+ /** Surfaced, never silently retried, and never terminal. */
1495
+ | "needs_recovery"
1496
+ /** An action failed and its window closed. */
1497
+ | "failed";
1498
+ /**
1499
+ * The untranslated protocol word, for support and audit. Failure reasons are on
1500
+ * {@link Swap}, not here.
1501
+ *
1502
+ * `wire`, `htlc` and `fate` are declared to fix the shape but populated by nothing yet.
1503
+ */
1504
+ type RawState = {
1505
+ readonly family: "rfq";
1506
+ readonly state: RfqSwapState;
1507
+ readonly wire?: RfqStatus["state"];
1508
+ readonly htlc?: OnchainHtlcPhase;
1509
+ readonly fate?: LockupFate;
1510
+ } | {
1511
+ readonly family: "offer";
1512
+ readonly status: AssetSwapStatus;
1513
+ };
1514
+ /** What `onUpdate` delivers. */
1515
+ interface SwapUpdate {
1516
+ readonly swap: Swap;
1517
+ readonly outcome: Outcome;
1518
+ readonly detail: RawState;
1519
+ }
1520
+ /** What every listener registration hands back. */
1521
+ type Unsubscribe = () => void;
1522
+ /** The manager's route-pair vocabulary — a route pair, not a corridor. */
1523
+ type CorridorKind = PersistableRfqSwap["kind"];
1524
+ /** Which route side (and so which {@link CorridorPass}) each corridor kind is: the trader
1525
+ * TAKES on lightning in `lightning_send` and GIVES on it in `lightning_receive`. */
1526
+ declare const CORRIDOR_PASS: {
1527
+ readonly lightning_send: {
1528
+ readonly lockups: readonly [{
1529
+ readonly covenant: "arkade_lockup";
1530
+ readonly owner: "trader";
1531
+ readonly deadline: "refund_locktime";
1532
+ }];
1533
+ readonly actions: readonly ["refundArkade"];
1534
+ readonly seams: readonly ["indexer"];
1535
+ };
1536
+ readonly lightning_receive: {
1537
+ readonly lockups: readonly [{
1538
+ readonly covenant: "arkade_lockup";
1539
+ readonly owner: "solver";
1540
+ readonly deadline: "refund_locktime";
1541
+ }];
1542
+ readonly actions: readonly ["claimLockup"];
1543
+ readonly seams: readonly ["indexer"];
1544
+ };
1545
+ readonly onchain_send: {
1546
+ readonly lockups: readonly [{
1547
+ readonly covenant: "arkade_lockup";
1548
+ readonly owner: "trader";
1549
+ readonly deadline: "refund_locktime";
1550
+ }, {
1551
+ readonly covenant: "onchain_htlc";
1552
+ readonly owner: "solver";
1553
+ readonly deadline: "htlc_refund_locktime";
1554
+ }];
1555
+ readonly actions: readonly ["claimOnchain", "refundArkade"];
1556
+ readonly seams: readonly ["indexer", "chain"];
1557
+ };
1558
+ };
1559
+ /** Whose the arkade lockup is, per corridor kind (`lockups[0]` on every pass). */
1560
+ declare const LOCKUP_OWNER: {
1561
+ readonly lightning_send: "trader";
1562
+ readonly lightning_receive: "solver";
1563
+ readonly onchain_send: "trader";
1564
+ };
1565
+ /** Whether this kind's drive pass reads L1, i.e. needs the onchain corridor's deps. */
1566
+ declare const readsChain: (kind: CorridorKind) => boolean;
1567
+ /** The corridor family's translation. */
1568
+ declare const corridorOutcome: (kind: CorridorKind, state: RfqSwapState) => Outcome;
1569
+ declare const offerOutcome: (status: AssetSwapStatus) => Outcome;
1570
+ /**
1571
+ * What a record reports when nothing live stands behind it: `accepted` until funding is
1572
+ * broadcast, then `funding` until the drive adopts it (the manager writes nothing until
1573
+ * its first pass). An offer has no live object, so past funding its record IS the state.
1574
+ */
1575
+ declare const recordOutcome: (record: {
1576
+ family: "offer" | "rfq";
1577
+ fundingTxid?: string;
1578
+ status?: AssetSwapStatus;
1579
+ }) => Outcome;
1580
+ /** `Outcome` projected onto `activity.ts`'s coarser, opaque history-row token. */
1581
+ declare const ACTIVITY_TOKEN: Record<Outcome, string>;
1582
+
1583
+ /**
1584
+ * A route is two endpoints, each an asset on a corridor, plus the instrument that settles it.
1585
+ *
1586
+ * Two invariants live in the types: an {@link Endpoint}'s corridor and asset cannot disagree, and
1587
+ * `onchain -> arkade` is not in {@link Route}, so a resolved misroute is a compile error (before
1588
+ * resolution it is `UnsupportedRoute`, thrown ahead of RFQ disclosure, persistence and funding).
1589
+ */
1590
+
1591
+ /**
1592
+ * A leg's concrete settlement locus. Direction comes from give versus take,
1593
+ * never from the instrument.
1594
+ *
1595
+ * `{ kind: "wallet" }` is the only instrument the SDK can sign for, so nobody passes it: the
1596
+ * caller provides non-wallet take instruments (`to`), the quote provides non-wallet give
1597
+ * instruments (the artifact), and every remaining slot resolves to `wallet`. It is an explicit
1598
+ * variant because an absent field would conflate wallet-by-default with not-yet-resolved.
1599
+ */
1600
+ type Instrument = {
1601
+ kind: "wallet";
1602
+ } | {
1603
+ kind: "address";
1604
+ address: string;
1605
+ /**
1606
+ * The amount a BIP21 URI pinned beside the address, when one did. Carried here so a
1607
+ * caller passing a different `amount` trips `AmountMismatch`, as with a bolt11 amount.
1608
+ */
1609
+ amount?: bigint;
1610
+ } | {
1611
+ kind: "invoice";
1612
+ bolt11: string;
1613
+ paymentHash: Hex;
1614
+ amount?: bigint;
1615
+ expiresAt: number;
1616
+ };
1617
+ /**
1618
+ * The asset ids corridor `C` can carry.
1619
+ *
1620
+ * On bitcoin-family corridors the tie is the rail alone. On EVM, `eip155:8453` is the CAIP-2 chain
1621
+ * part, so the asset id must start with the corridor id verbatim; a rail-only check would admit
1622
+ * `eip155:1/erc20:…` on a Base corridor.
1623
+ */
1624
+ type AssetOn<C extends CorridorId> = C extends Corridor ? AssetId<RailOf<C>> : `${C}/${AssetPart}`;
1625
+ /**
1626
+ * An asset on a corridor, with the instrument that settles it. `corridor` is a cross-check (the id
1627
+ * already carries its rail), typed so the two cannot disagree.
1628
+ *
1629
+ * Distributive over `C` on purpose: `{ corridor: C; asset: AssetOn<C> }` at `C = CorridorId`
1630
+ * widens each field independently and would admit `{ corridor: "arkade", asset: "bitcoin:…" }`.
1631
+ */
1632
+ type Endpoint<C extends CorridorId = CorridorId> = C extends CorridorId ? {
1633
+ corridor: C;
1634
+ asset: AssetOn<C>;
1635
+ /** Resolved by the client, never constructed by callers. */
1636
+ instrument: Instrument;
1637
+ } : never;
1638
+ /** Shorthand for one corridor's endpoint, as the route union spells it. */
1639
+ type Ep<C extends CorridorId> = Endpoint<C>;
1640
+ /**
1641
+ * The implemented routes, as a closed union.
1642
+ *
1643
+ * `onchain -> arkade` is deliberately absent until the manager owns the
1644
+ * trader's L1 refund path end to end.
1645
+ */
1646
+ type Route = {
1647
+ give: Ep<"arkade">;
1648
+ take: Ep<"arkade">;
1649
+ } | {
1650
+ give: Ep<"arkade">;
1651
+ take: Ep<"lightning">;
1652
+ } | {
1653
+ give: Ep<"lightning">;
1654
+ take: Ep<"arkade">;
1655
+ } | {
1656
+ give: Ep<"arkade">;
1657
+ take: Ep<"onchain">;
1658
+ };
1659
+ /**
1660
+ * The one thing a counterparty must see, when a route has one.
1661
+ *
1662
+ * No `chain` field on the deposit: the chain part lives inside `asset`, and a second spelling
1663
+ * would be a fact two fields can disagree about.
1664
+ */
1665
+ type Artifact = {
1666
+ kind: "invoice";
1667
+ bolt11: string;
1668
+ } | DepositArtifact;
1669
+ /**
1670
+ * The deposit half of {@link Artifact}, distributed over the corridor for the same reason as
1671
+ * {@link Endpoint}.
1672
+ */
1673
+ type DepositArtifact<C extends CorridorId = CorridorId> = C extends CorridorId ? {
1674
+ kind: "deposit";
1675
+ corridor: C;
1676
+ address: string;
1677
+ asset: AssetOn<C>;
1678
+ amount: bigint;
1679
+ expiresAt?: number;
1680
+ } : never;
1681
+
1682
+ /** Which side of the trade an amount pins, in v2's vocabulary. */
1683
+ type AmountOn = "give" | "take";
1684
+ /** The same axis on the wire, where the key is `amount_side`. */
1685
+ type RfqAmountSide = "from" | "to";
1686
+ /** v2 to the wire. One translation point, so the rename cannot spread. */
1687
+ declare const toRfqAmountSide: (on: AmountOn) => RfqAmountSide;
1688
+ /** The wire back to v2. */
1689
+ declare const fromRfqAmountSide: (side: RfqAmountSide) => AmountOn;
1690
+ /**
1691
+ * An amount out to the wire, as the canonical decimal string.
1692
+ *
1693
+ * @param field - Named in the error, to tell `from_amount` from `to_amount`.
1694
+ */
1695
+ declare const encodeRfqAmount: (value: bigint, field: string) => AtomicDecimal;
1696
+ /**
1697
+ * An amount in from the wire: the canonical string, or a JSON number inside the
1698
+ * safe-integer window (the only place v2 tolerates a number).
1699
+ *
1700
+ * @throws {@link AmountEncodingUnsupported} for a non-canonical string too; this fires
1701
+ * before verification's semantic checks, not as one of them.
1702
+ */
1703
+ declare const decodeRfqAmount: (raw: unknown, field: string) => bigint;
1704
+ /**
1705
+ * A `bigint` amount into a foreign `number` one, checked rather than a bare `Number()`
1706
+ * (a sat count past 2^53 is not a payment, so refusing it is sound).
1707
+ */
1708
+ declare const toSafeNumber: (value: bigint, field: string) => number;
1709
+
1710
+ /**
1711
+ * What a quote is: the order, fully resolved, plus the provenance that says who priced it and
1712
+ * where that card came from. Types only — the quote path assembles these, `accept()` consumes
1713
+ * them.
1714
+ *
1715
+ * A `Quote` is binding terms plus the evidence for them: every field is something the caller must
1716
+ * act on or be able to audit. Nothing internal rides along (no covenant, secret or transport).
1717
+ */
1718
+
1719
+ /**
1720
+ * A quote's identity, minted by the client at quote time on every backend: feed-priced quotes
1721
+ * have no solver id, and `accept()` is idempotent by quote id *only* (§3.2).
1722
+ */
1723
+ type QuoteId = string;
1724
+ /**
1725
+ * A caller's spelling of an asset: a public id, or a ticker the alias layer canonicalizes against
1726
+ * the registry. `(string & {})` rather than `string` keeps editor completion of the id form.
1727
+ */
1728
+ type AssetRef = AssetId | (string & {});
1729
+ /**
1730
+ * Everything a caller supplies: two asset ids or one destination string, one amount, which side
1731
+ * it pins, and — on receives, where no instrument exists yet — a corridor.
1732
+ */
1733
+ interface QuoteInput {
1734
+ /** Omitted when the route determines it: the give leg is the wallet's. */
1735
+ give?: AssetRef;
1736
+ /** Omitted when `to` determines it — a corridor that carries BTC only does. */
1737
+ take?: AssetRef;
1738
+ /** A self-describing instrument: bolt11, an Arkade address, or `bc1…`. */
1739
+ to?: string;
1740
+ /** Receive flows only: names the corridor when no instrument can exist yet. */
1741
+ via?: CorridorId;
1742
+ /** Atomic units. Exactly one amount may be pinned — see `amountOn`. */
1743
+ amount?: bigint;
1744
+ /** Which leg `amount` pins. Required with `amount`, and refused with an
1745
+ * invoice, which pins one already. */
1746
+ amountOn?: AmountOn;
1747
+ }
1748
+ /** Which backend priced a quote. The card decides it; no client switch does. */
1749
+ type MarketBackend = "rfq" | "feed";
1750
+ /** Where a snapshot came from, and how fresh it is. */
1751
+ interface SnapshotRef {
1752
+ /** Unix ms the markets were read from their sources. */
1753
+ readonly fetchedAt: number;
1754
+ /**
1755
+ * The registry answered in this read (cards are not replayed from local storage).
1756
+ *
1757
+ * `false` is marked, not refused: a stale snapshot still prices a feed-priced quote. It cannot
1758
+ * supply the key an addressed RFQ's responder is checked against, because cached cards are
1759
+ * only partly revalidated (`isMarketShaped`).
1760
+ */
1761
+ readonly live: boolean;
1762
+ /** How the markets were obtained. */
1763
+ readonly source: "live" | "cache" | "injected";
1764
+ /** The registry URL behind it, or `undefined` for an injected snapshot. */
1765
+ readonly registry?: string;
1766
+ }
1767
+ /**
1768
+ * Which card priced a quote, and from which registry. A union because an auction-closed quote
1769
+ * (§10) has a market key and no card, and a restored record has neither.
1770
+ */
1771
+ type MarketRef = CardMarketRef | AuctionMarketRef | RestoredMarketRef;
1772
+ interface CardMarketRef {
1773
+ readonly kind: "card";
1774
+ /**
1775
+ * The canonical market key, `<corridor>:<id>/<corridor>:<id>`, under rfq-protocol.md §2's leg
1776
+ * order — arkade first when exactly one leg is arkade, lexicographic otherwise — never the
1777
+ * card's own base/quote order (see `marketKeyOf`).
1778
+ */
1779
+ readonly key: string;
1780
+ readonly backend: MarketBackend;
1781
+ /** The registry URL, or the label a locally pinned card was loaded under. */
1782
+ readonly source: string;
1783
+ readonly sourceType: "registry" | "local";
1784
+ /** The solver's name, as the card publishes it. Display, never identity. */
1785
+ readonly solver: string;
1786
+ /** The card's signing key. Absent on spot cards, which need no rendezvous. */
1787
+ readonly discoveryPubkey?: Pubkey;
1788
+ /** The card's display label, e.g. `BTC/lightning:BTC`. Display only. */
1789
+ readonly pair: string;
1790
+ readonly snapshot: SnapshotRef;
1791
+ }
1792
+ /** §10, reserved: a quote closed out of a published auction has no card. */
1793
+ interface AuctionMarketRef {
1794
+ readonly kind: "auction";
1795
+ readonly key: string;
1796
+ readonly backend: "rfq";
1797
+ }
1798
+ /** A record rebuilt after a restore (from the funding tx, or a v1 corridor row): no card stands
1799
+ * behind it. */
1800
+ interface RestoredMarketRef {
1801
+ readonly kind: "restored";
1802
+ readonly backend: "feed" | "rfq";
1803
+ }
1804
+ /**
1805
+ * One bid seen in a published auction (§10, Q9): a counter-amount on the leg the client did not
1806
+ * fix, attributed to the event key that signed it — NOT the covenant's `solver_pubkey`.
1807
+ */
1808
+ interface RankedBid {
1809
+ /** The event key that signed the bid. Attribution, not a covenant role. */
1810
+ readonly bidder: Pubkey;
1811
+ /** The counter-amount, on the leg the client left free. */
1812
+ readonly amount: bigint;
1813
+ readonly amountOn: AmountOn;
1814
+ readonly expiresAt: number;
1815
+ }
1816
+ /**
1817
+ * The auction a published-RFQ quote was closed out of (§10, Q9). Reserved and inert: `quote()`
1818
+ * never populates it.
1819
+ */
1820
+ interface AuctionProvenance {
1821
+ /** The market key the open request was tagged with. */
1822
+ readonly marketKey: string;
1823
+ /** The bid that was closed with. */
1824
+ readonly winner: RankedBid;
1825
+ /** Every other bid seen before the window closed. */
1826
+ readonly losers: readonly RankedBid[];
1827
+ /** Unix seconds the bid window closed. */
1828
+ readonly closedAt: number;
1829
+ }
1830
+ /** One leg's obligation: an asset, and exactly how much of it. */
1831
+ interface QuoteLeg {
1832
+ readonly asset: AssetId;
1833
+ readonly amount: bigint;
1834
+ }
1835
+ /**
1836
+ * The order, fully resolved. Both amounts are exact obligations with the fee already inside;
1837
+ * `fee` restates the spread rather than adding to it.
1838
+ */
1839
+ interface Quote {
1840
+ readonly id: QuoteId;
1841
+ /** Both endpoints resolved, instruments included. */
1842
+ readonly route: Route;
1843
+ /** What the trader gives, fee included. */
1844
+ readonly give: QuoteLeg;
1845
+ /** What the trader takes. */
1846
+ readonly take: QuoteLeg;
1847
+ /** Corridor routes: the hash both covenants commit to. */
1848
+ readonly lock?: {
1849
+ readonly hash: Hex;
1850
+ };
1851
+ /** Which card priced this, from which registry, how fresh. */
1852
+ readonly market: MarketRef;
1853
+ /** RFQ routes: the committed counterparty, from the quote's covenant role. */
1854
+ readonly solver?: Pubkey;
1855
+ /** §10 only, and never populated today. */
1856
+ readonly auction?: AuctionProvenance;
1857
+ /** Unix seconds. Non-optional on both backends — a feed-priced quote has no
1858
+ * wire expiry to inherit, so the client mints one from the feed's freshness. */
1859
+ readonly expiresAt: number;
1860
+ /**
1861
+ * Corridor routes: when the trader's value comes back if the swap does not complete. Absent on
1862
+ * asset swaps (an offer covenant never expires); corridor quotes without it are refused.
1863
+ */
1864
+ readonly refundLocktime?: number;
1865
+ /**
1866
+ * The one thing a counterparty must see, when this route has one.
1867
+ *
1868
+ * Do not show it until `accept()` has resolved: a Lightning receive's invoice is minted here,
1869
+ * but its preimage secrets are persisted only by `accept()`. `receive()` does both.
1870
+ */
1871
+ readonly artifact?: Artifact;
1872
+ /** The spread, plus any deposit carrier the payout does not return, on the leg where it is exact. */
1873
+ readonly fee: {
1874
+ readonly amount: bigint;
1875
+ readonly asset: AssetId;
1876
+ };
1877
+ }
1878
+ /**
1879
+ * An endpoint as `resolve()` can answer for it, before any disclosure. Not an `Endpoint`, whose
1880
+ * instrument is required: a receive leg has none until the quote returns (the instrument IS the
1881
+ * artifact the solver mints).
1882
+ */
1883
+ interface ResolvedEndpoint {
1884
+ readonly corridor: Corridor;
1885
+ readonly asset: AssetId;
1886
+ /** Absent only while the leg's instrument does not exist yet. */
1887
+ readonly instrument?: Instrument;
1888
+ }
1889
+ /** The amount a caller or a destination pinned, and which leg it pins. */
1890
+ interface PinnedAmount {
1891
+ readonly value: bigint;
1892
+ readonly on: AmountOn;
1893
+ /**
1894
+ * What pinned it, for an `AmountMismatch` diagnostic. `"destination"` covers an
1895
+ * amount-bearing bolt11 and a BIP21 `amount=`.
1896
+ */
1897
+ readonly source: "caller" | "destination";
1898
+ }
1899
+ /**
1900
+ * What `resolve()` answers: the route's shape, the market that would price it, and what the
1901
+ * active snapshot serves. `eligible: 0` is not a resolution failure; `quote()` is where it becomes
1902
+ * `UnsupportedRoute`.
1903
+ */
1904
+ interface RouteResolution {
1905
+ readonly give: ResolvedEndpoint;
1906
+ readonly take: ResolvedEndpoint;
1907
+ /** The card that would price it: the first eligible one after policy. */
1908
+ readonly market?: MarketRef;
1909
+ /** How many markets serve this pair on the active snapshot, after policy. */
1910
+ readonly eligible: number;
1911
+ /** Where the market data came from, and how fresh it is. */
1912
+ readonly snapshot: SnapshotRef;
1913
+ /** The amount pinned so far, when the input pinned one. */
1914
+ readonly amount?: PinnedAmount;
1915
+ }
1916
+
1917
+ /**
1918
+ * What survives a crash, and the public shape `accept()` hands back.
1919
+ *
1920
+ * {@link SwapRecord} is the storage form (amounts as canonical atomic decimal strings); {@link Swap}
1921
+ * is the caller's answer with `bigint` amounts and the resolved `Route`.
1922
+ *
1923
+ * **The key is the quote id, on every route**, which is what makes persist-first possible (v1 keyed
1924
+ * on the funding txid, so no record could precede the money). `fundingTxid` is a later write.
1925
+ * **No `bigint` anywhere, at any depth**: SQLite and Realm `JSON.stringify` the record whole
1926
+ * (`test/client/record.types.ts` proves it structurally).
1927
+ */
1928
+
1929
+ /** Which family a record belongs to — what the drive's outcome table branches on without a read. */
1930
+ type SwapFamily = "offer" | "rfq";
1931
+ /**
1932
+ * The public swap id, `offer:<QuoteId>` / `rfq:<QuoteId>`. Presentation, not a second identity:
1933
+ * storage, the drive and `accept()`'s idempotency key on the bare quote id. The prefix makes
1934
+ * `NotCancellable` a parse, with no repository read for a corridor id.
1935
+ */
1936
+ type AssetSwapId = `${SwapFamily}:${QuoteId}`;
1937
+ /** The public id a record answers with — the tag, minted off its family. */
1938
+ declare const assetSwapIdOf: (family: SwapFamily, quoteId: QuoteId) => AssetSwapId;
1939
+ declare const OFFER_SWAP_ID_PREFIX: "offer:";
1940
+ declare const RFQ_SWAP_ID_PREFIX: "rfq:";
1941
+ /** The family an id names, or `undefined` for an untagged (`/protocol`-reader-era) id. */
1942
+ declare const familyOfSwapId: (swapId: string) => SwapFamily | undefined;
1943
+ /** The bare quote id under the tag; an untagged id passes through unchanged. */
1944
+ declare const quoteIdOfSwapId: (swapId: string) => QuoteId;
1945
+ /** One leg's obligation, in the form a record holds it. */
1946
+ interface RecordedLeg {
1947
+ readonly asset: AssetId;
1948
+ /** Atomic units as a canonical decimal string — never a `bigint`. */
1949
+ readonly amount: AtomicDecimal;
1950
+ }
1951
+ /** An endpoint as the record holds it; field for field `Instrument`'s shape, so `acceptConflict`
1952
+ * compares like with like. */
1953
+ interface RecordedEndpoint {
1954
+ readonly corridor: CorridorId;
1955
+ readonly asset: AssetId;
1956
+ readonly instrument: RecordedInstrument;
1957
+ }
1958
+ /** {@link Instrument}, with the invoice arm's amount in decimal form. */
1959
+ type RecordedInstrument = {
1960
+ readonly kind: "wallet";
1961
+ } | {
1962
+ readonly kind: "address";
1963
+ readonly address: string;
1964
+ } | {
1965
+ readonly kind: "invoice";
1966
+ readonly bolt11: string;
1967
+ readonly paymentHash: Hex;
1968
+ readonly amount?: AtomicDecimal;
1969
+ readonly expiresAt: number;
1970
+ };
1971
+ /** {@link Artifact}, with the deposit arm's amount in decimal form. */
1972
+ type RecordedArtifact = {
1973
+ readonly kind: "invoice";
1974
+ readonly bolt11: string;
1975
+ } | {
1976
+ readonly kind: "deposit";
1977
+ readonly corridor: CorridorId;
1978
+ readonly address: string;
1979
+ readonly asset: AssetId;
1980
+ readonly amount: AtomicDecimal;
1981
+ readonly expiresAt?: number;
1982
+ };
1983
+ /** The half both families carry: what `AcceptConflict` compares and no chain read can give back. */
1984
+ interface SwapRecordCommon {
1985
+ /** The client-minted quote id — the primary key. */
1986
+ readonly id: QuoteId;
1987
+ readonly family: SwapFamily;
1988
+ /** Both endpoints, instruments included. Nested under `route` so field names match `Quote`'s and
1989
+ * the conflict check walks both shapes without translation. */
1990
+ readonly route: {
1991
+ readonly give: RecordedEndpoint;
1992
+ readonly take: RecordedEndpoint;
1993
+ };
1994
+ /** The two obligations — `AcceptConflict` item 2. */
1995
+ readonly give: RecordedLeg;
1996
+ readonly take: RecordedLeg;
1997
+ /** The spread, as the quote precomputed it. */
1998
+ readonly fee: RecordedLeg;
1999
+ /** Which card priced this, from which registry, how fresh — stored WHOLE (a projection could not
2000
+ * rebuild `CardMarketRef`); `snapshot` is as read at accept, not restamped. */
2001
+ readonly market: MarketRef;
2002
+ /** The committed counterparty key from the quote's covenant role — NOT `CardMarketRef.solver`,
2003
+ * which is a display name. `AcceptConflict` compares this one. */
2004
+ readonly solver?: Pubkey;
2005
+ /** The quote's own deadline, unix seconds — what makes a stalled accept a
2006
+ * benign abandon rather than a live obligation. */
2007
+ readonly expiresAt: number;
2008
+ /** The one thing a counterparty must see, when the route has one. Durable because a duplicate
2009
+ * accept after a restart must return the SAME invoice, and the quote object is gone by then. */
2010
+ readonly artifact?: RecordedArtifact;
2011
+ /** The funding transaction, once known. A later best-effort write; set-where-absent is a benign
2012
+ * resume, never an `AcceptConflict`. */
2013
+ readonly fundingTxid?: string;
2014
+ /** Last retryable receive-claim error; becomes the terminal failure if the claim window closes. */
2015
+ readonly claimFailure?: string;
2016
+ /** Terminal failure reason. */
2017
+ readonly failure?: string;
2018
+ /** Refusal reason while `state` is `needs_counterparty`. */
2019
+ readonly blockedReason?: string;
2020
+ /** Unix **seconds**, both — the unit `RfqSwapRecord` carries and
2021
+ * `shouldRetainRfqSwap` compares against, not `AssetSwap`'s milliseconds. */
2022
+ readonly createdAt: number;
2023
+ readonly updatedAt: number;
2024
+ }
2025
+ /** `arkade <-> arkade`: the offer covenant. `offerHex` is the whole covenant, so no tree params. */
2026
+ interface OfferSwapRecord extends SwapRecordCommon {
2027
+ readonly family: "offer";
2028
+ /** v1's raw status vocabulary, read verbatim by the drive's `RawState`. */
2029
+ readonly status: AssetSwapStatus;
2030
+ /** The TLV offer, hex. The only input `cancelOffer` needs. */
2031
+ readonly offerHex: string;
2032
+ readonly swapAddress: string;
2033
+ /** The covenant's scriptPubKey, hex — the indexer's monitoring key and the reconcile's match key. */
2034
+ readonly swapPkScript: string;
2035
+ /** Sats riding an asset deposit, decimal: the solver's published carrier, which the fill is
2036
+ * priced against. Absent for a BTC deposit and for feed-priced swaps (the SDK default). */
2037
+ readonly carrierSats?: string;
2038
+ readonly spentTxid?: string;
2039
+ readonly completedAt?: number;
2040
+ }
2041
+ /**
2042
+ * The three corridor routes: a VHTLC lockup, its clocks and its secrets.
2043
+ *
2044
+ * **No covenant tree here.** `accept()` registers a contract row before the lockup can be funded,
2045
+ * keyed by the script its params derive (`createContract` refuses params that don't reproduce it);
2046
+ * storing the tree again would be two sources for one covenant.
2047
+ */
2048
+ interface CorridorSwapRecord extends SwapRecordCommon {
2049
+ readonly family: "rfq";
2050
+ /** v1's raw state vocabulary, read verbatim by the drive's `RawState`. */
2051
+ readonly state: RfqSwapState;
2052
+ /** The route pair in the manager's vocabulary (`lightning_send`/`lightning_receive` are one
2053
+ * corridor from opposite ends); resolves the handler that owns {@link profile}. */
2054
+ readonly kind: PersistableRfqSwap["kind"];
2055
+ /** The solver's own id for the negotiation, echoed back on the wire. */
2056
+ readonly rfqId: string;
2057
+ /** The Arkade address that was funded, and the swap's handle on its
2058
+ * covenant row. */
2059
+ readonly lockupAddress: string;
2060
+ /** Its pkScript, hex — the row's key and the reconcile's match key. */
2061
+ readonly lockupPkScript: string;
2062
+ /** The hash both covenants commit to. `sha256(P)`, hex. */
2063
+ readonly lock: {
2064
+ readonly hash: Hex;
2065
+ };
2066
+ /** When the trader's value comes back if the swap does not complete. */
2067
+ readonly refundLocktime: number;
2068
+ /**
2069
+ * The corridor's own half, as plain JSON (written by `rfqSecretsProfile`, read by
2070
+ * `rfqCorridorHandlers.hydrate`), so a new corridor ships without touching this file. Its
2071
+ * `expectedAmount` is a `number`; the decimal-string rule covers only this record's own fields.
2072
+ *
2073
+ * **The swap's secrets live here** (`profile.signer`, and `profile.hashlock` on a preimage-locked
2074
+ * leg), deliberately not duplicated at top level.
2075
+ */
2076
+ readonly profile: Record<string, unknown>;
2077
+ readonly refundTxid?: string;
2078
+ readonly lockupSpendTxids?: readonly string[];
2079
+ /**
2080
+ * `P`, hex — the preimage the solver revealed to settle a Lightning send. Not a copy of our claim
2081
+ * secret (the payee mints `P` on that leg), and already public: read from the spending witness.
2082
+ */
2083
+ readonly settlementPreimageHex?: string;
2084
+ }
2085
+ /** Everything `accept()` persists, both families in one key space. */
2086
+ type SwapRecord = OfferSwapRecord | CorridorSwapRecord;
2087
+ /**
2088
+ * A swap, as a caller reads it: the quote's terms plus what has happened to them. `artifact` stays
2089
+ * optional because `ReceiveRequest` is `Swap & { artifact: Artifact }`; the reason strings live here
2090
+ * because `SwapUpdate.detail` is only the `RawState` word.
2091
+ */
2092
+ interface Swap {
2093
+ readonly id: AssetSwapId;
2094
+ readonly family: SwapFamily;
2095
+ /** Where this swap stands, in the one vocabulary both families share. */
2096
+ readonly outcome: Outcome;
2097
+ /** Both endpoints resolved, instruments included. */
2098
+ readonly route: Route;
2099
+ /** What the trader gives, fee included. */
2100
+ readonly give: QuoteLeg;
2101
+ /** What the trader takes. */
2102
+ readonly take: QuoteLeg;
2103
+ /** The spread, denominated on the leg where it is exact. */
2104
+ readonly fee: QuoteLeg;
2105
+ readonly market: MarketRef;
2106
+ readonly solver?: Pubkey;
2107
+ /** Corridor routes: the hash both covenants commit to. */
2108
+ readonly lock?: {
2109
+ readonly hash: Hex;
2110
+ };
2111
+ /** Corridor routes: when the trader's value comes back. */
2112
+ readonly refundLocktime?: number;
2113
+ readonly artifact?: Artifact;
2114
+ readonly expiresAt: number;
2115
+ /** Absent until the funding is broadcast and its txid written. */
2116
+ readonly fundingTxid?: string;
2117
+ /** Why the swap `failed`, when it did — only the record knows why. */
2118
+ readonly failure?: string;
2119
+ /** Why this wallet will not act, while `needs_recovery`. Under `drive: "manual"`/`"readonly"` the
2120
+ * configuration refusals are not translated to `needs_recovery`, and this still carries them. */
2121
+ readonly blockedReason?: string;
2122
+ readonly createdAt: number;
2123
+ readonly updatedAt: number;
2124
+ }
2125
+ /** An endpoint into its stored form. */
2126
+ declare const recordEndpoint: (endpoint: {
2127
+ corridor: CorridorId;
2128
+ asset: string;
2129
+ instrument: Instrument;
2130
+ }) => RecordedEndpoint;
2131
+ /** An instrument into its stored form: only the invoice arm's amount moves. */
2132
+ declare const recordInstrument: (instrument: Instrument) => RecordedInstrument;
2133
+ /** A stored instrument back into the live union. */
2134
+ declare const instrumentOf: (instrument: RecordedInstrument) => Instrument;
2135
+ /** An artifact into its stored form. */
2136
+ declare const recordArtifact: (artifact: Artifact) => RecordedArtifact;
2137
+ /** A stored artifact back into the live union. */
2138
+ declare const artifactOf: (artifact: RecordedArtifact) => Artifact;
2139
+ /** A leg into its stored form. */
2140
+ declare const recordLeg: (leg: QuoteLeg) => RecordedLeg;
2141
+ /** A stored leg back into `bigint` units. */
2142
+ declare const legOf: (leg: RecordedLeg) => QuoteLeg;
2143
+ /**
2144
+ * The public {@link Swap} a stored record answers with — the one read path, so a duplicate
2145
+ * `accept()` answers from the record, not the evictable preparation cache. `outcome` is a parameter
2146
+ * because only the drive knows whether it holds live state. The `Route` cast is safe because
2147
+ * `accept()` only writes records from a `Quote` whose route was already resolved.
2148
+ */
2149
+ declare const swapOf: (record: SwapRecord, outcome: Outcome) => Swap;
2150
+ /**
2151
+ * Whether the give leg is funded from the wallet (gates `accept()`'s balance check and send). The
2152
+ * **instrument**, not the asset: a `lightning -> arkade` receive gives BTC via a hold invoice a third
2153
+ * party pays, and an asset test would refuse the canonical empty-wallet receive.
2154
+ */
2155
+ declare const fundsFromWallet: (route: {
2156
+ give: {
2157
+ instrument: Instrument | RecordedInstrument;
2158
+ };
2159
+ }) => boolean;
2160
+
2161
+ /** A cached registry discovery result. Refetchable, but must survive a cold boot:
2162
+ * serving it stale keeps quoting alive while a registry is down. */
2163
+ interface MarketsCacheEntry {
2164
+ markets: DiscoveredMarket[];
2165
+ fetchedAt: number;
2166
+ }
2167
+ interface RfqSwapPageFilter {
2168
+ state?: RfqSwapState;
2169
+ /** Inclusive Unix seconds. */
2170
+ since?: number;
2171
+ }
2172
+ interface RfqSwapPageCursor {
2173
+ updatedAt: number;
2174
+ rfqId: string;
2175
+ }
2176
+ /**
2177
+ * Everything the package persists: versioned interface, AsyncDisposable, one backend
2178
+ * per platform. Durable records and rebuildable state (scan cursor, markets cache) share
2179
+ * one store because they share a lifetime: one wallet on one device.
2180
+ *
2181
+ * Collection reads are paged. RFQ reads may filter by state and date.
2182
+ */
2183
+ interface AssetSwapRepository extends AsyncDisposable {
2184
+ /** Bumped on every shape change (5: v2 swap-record store) so an implementor built
2185
+ * against an older shape cannot satisfy this one silently. */
2186
+ readonly version: 5;
2187
+ /** Insert or replace a swap by id. Store the record whole: a field-mapped backend
2188
+ * dropping `preimageHex` or `preimageSaltHex` leaves the swap unclaimable.
2189
+ *
2190
+ * Records must be **JSON-safe**: SQLite and Realm serialize to JSON, so a `Date`
2191
+ * comes back a string, a `Set`/`Map` empty, and a `bigint` throws — unlike
2192
+ * IndexedDB's structured clone. Keep consumer-added fields JSON-safe. */
2193
+ saveSwap(swap: AssetSwap): Promise<void>;
2194
+ getAssetSwapsPage(page: PageRequest): Promise<PageResult<AssetSwap>>;
2195
+ /**
2196
+ * Insert or replace a monitored RFQ swap by `rfqId`.
2197
+ *
2198
+ * Store the record WHOLE: every field is a covenant parameter or manager state, and a
2199
+ * dropped one surfaces much later as a refund that cannot be signed.
2200
+ */
2201
+ saveRfqSwap(record: RfqSwapRecord): Promise<void>;
2202
+ /** One record by key. */
2203
+ getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
2204
+ getRfqSwapsPage(filter: RfqSwapPageFilter, page: PageRequest<RfqSwapPageCursor>): Promise<PageResult<RfqSwapRecord, RfqSwapPageCursor>>;
2205
+ /** Drop one record. Only explicit pruning calls this; restore keeps history. */
2206
+ removeRfqSwap(rfqId: string): Promise<void>;
2207
+ /**
2208
+ * Insert or replace a v2 swap record (what `accept()` writes) by its quote id.
2209
+ *
2210
+ * Separate from `swaps`: the v1 read path silently drops rows with neither `offerHex`
2211
+ * nor `paymentHash` as corrupt. v1 readers not seeing v2 rows is by design.
2212
+ *
2213
+ * Store the record WHOLE. Amounts are canonical decimal strings so every backend
2214
+ * agrees; a `bigint` would throw on SQLite/Realm and round-trip on IndexedDB.
2215
+ */
2216
+ saveSwapRecord(record: SwapRecord): Promise<void>;
2217
+ /** `undefined` on a miss — the ordinary answer for a first `accept()`, and what
2218
+ * makes it idempotent. */
2219
+ getSwapRecord(id: string): Promise<SwapRecord | undefined>;
2220
+ getSwapRecordsPage(page: PageRequest): Promise<PageResult<SwapRecord>>;
2221
+ /** Drop one, once it is past retention. */
2222
+ removeSwapRecord(id: string): Promise<void>;
2223
+ /**
2224
+ * Sent txids already checked for offer packets (see restore.ts). Deliberately shared
2225
+ * by both record families: they walk the same sent-txid set, and two cursors would
2226
+ * each re-walk what the other already answered.
2227
+ */
2228
+ getScannedTxids(): Promise<Set<string>>;
2229
+ markTxidsScanned(txids: Iterable<string>): Promise<void>;
2230
+ /** Cached registry markets, or undefined on a miss. Shared by both record families,
2231
+ * like the cursor, so one registry has one staleness clock. */
2232
+ getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
2233
+ saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
2234
+ clear(): Promise<void>;
2235
+ }
2236
+ declare class InMemoryAssetSwapRepository implements AssetSwapRepository {
2237
+ readonly version: 5;
2238
+ private readonly swaps;
2239
+ private readonly records;
2240
+ private readonly rfqSwaps;
2241
+ private readonly scanned;
2242
+ private readonly markets;
2243
+ saveSwap(swap: AssetSwap): Promise<void>;
2244
+ getAssetSwapsPage(page: PageRequest): Promise<PageResult<AssetSwap>>;
2245
+ saveRfqSwap(record: RfqSwapRecord): Promise<void>;
2246
+ getRfqSwap(rfqId: string): Promise<RfqSwapRecord | undefined>;
2247
+ getRfqSwapsPage(filter: RfqSwapPageFilter, page: PageRequest<RfqSwapPageCursor>): Promise<PageResult<RfqSwapRecord, RfqSwapPageCursor>>;
2248
+ removeRfqSwap(rfqId: string): Promise<void>;
2249
+ saveSwapRecord(record: SwapRecord): Promise<void>;
2250
+ getSwapRecord(id: string): Promise<SwapRecord | undefined>;
2251
+ getSwapRecordsPage(page: PageRequest): Promise<PageResult<SwapRecord>>;
2252
+ removeSwapRecord(id: string): Promise<void>;
2253
+ getScannedTxids(): Promise<Set<string>>;
2254
+ markTxidsScanned(txids: Iterable<string>): Promise<void>;
2255
+ getCachedMarkets(network: string, registry: string): Promise<MarketsCacheEntry | undefined>;
2256
+ saveCachedMarkets(network: string, registry: string, entry: MarketsCacheEntry): Promise<void>;
2257
+ clear(): Promise<void>;
2258
+ [Symbol.asyncDispose](): Promise<void>;
2259
+ }
2260
+
2261
+ export { type Hex as $, type AssetId as A, type AssetScale as B, type Corridor as C, type AssetSwapId as D, type AtomicDecimal as E, type AuctionMarketRef as F, type AuctionProvenance as G, BITCOIN_RAILS as H, type Instrument as I, BTC_ASSET_PART as J, type BitcoinRail as K, type LockupSpendIndexer as L, CORRIDORS 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, CORRIDOR_PASS as T, type CardMarketRef as U, type CorridorId as V, type CorridorKind as W, type DepositArtifact as X, type DisplayDecimal as Y, type Endpoint as Z, type Ep as _, type RfqSwapRecordStore as a, toRfqAmountSide as a$, LOCKUP_OWNER as a0, type MarketBackend as a1, type MarketRef as a2, OFFER_SWAP_ID_PREFIX as a3, type Outcome as a4, type ParsedAssetId as a5, type Quote as a6, type QuoteLeg as a7, RAILS as a8, RFQ_SWAP_ID_PREFIX as a9, familyOfSwapId as aA, formatAssetId as aB, fromAtomicDecimal as aC, fromRfqAmountSide as aD, fundsFromWallet as aE, instrumentOf as aF, isAssetId as aG, isAtomicDecimal as aH, isBtcAsset as aI, isBtcAssetLenient as aJ, isNetworkRef as aK, issuanceOf as aL, legOf as aM, offerOutcome as aN, parseAssetId as aO, quoteIdOfSwapId as aP, railOf as aQ, railOfCorridor as aR, readsChain as aS, recordArtifact as aT, recordEndpoint as aU, recordInstrument as aV, recordLeg as aW, recordOutcome as aX, sameAsset as aY, swapOf as aZ, toAtomicDecimal as a_, type RailOf as aa, type RankedBid as ab, type RawState as ac, type RecordedArtifact as ad, type RecordedEndpoint as ae, type RecordedInstrument as af, type RecordedLeg as ag, type RestoredMarketRef as ah, type RfqAmountSide as ai, type SnapshotRef as aj, type Swap as ak, type SwapFamily as al, type SwapRecordCommon as am, type SwapUpdate as an, type Unsubscribe as ao, arkadeAsset as ap, artifactOf as aq, assetPartOf as ar, assetSwapIdOf as as, bitcoinNetworkOf as at, btcAssetPart as au, btcOn as av, corridorOfRail as aw, corridorOutcome as ax, decodeRfqAmount as ay, encodeRfqAmount as az, type CorridorSwapRecord as b, toSafeNumber as b0, type MarketsCacheEntry as b1, InMemoryAssetSwapRepository as b2, type RfqSwapState as b3, type SwapContractRegistry as b4, type SwapOperator as b5, isRfqSwapTerminal as b6, type RfqSwapManagerCallbacks as b7, type RfqSwapActionName as b8, type SwapSecretsProjection as b9, type RfqSwapManagerEvents as bA, type RfqSwapOrigin as bB, RfqSwapOriginRequired as bC, type RfqSwapOutcome as bD, addAssetSwap as bE, awaitRfqResolution as bF, createRfqSwapRecord as bG, findLockupVtxos as bH, getAssetSwaps as bI, isRfqTerminal as bJ, nextOnchainAction as bK, normalizeRfqSwapRecord as bL, preimageForSwapRecord as bM, pushRefundWithoutReceiver as bN, readLockupFate as bO, rebuildRfqSwap as bP, refundIfUnresolved as bQ, rfqSwapOriginOf as bR, shouldRetainRfqSwap as bS, swapSecretsToRecord as bT, updateAssetSwap as bU, updateRfqSwapRecord as bV, type LockupContractSource as ba, type RfqSwap as bb, type ArkadeRefundResult as bc, type LockupVtxo as bd, type AvailableRfqSwapManagerCallbacks as be, BTC_ASSET_ID as bf, type LightningReceiveSwap as bg, type LightningSendSwap as bh, type LockupFate as bi, LockupNeedsRecoveryError as bj, type LockupParams as bk, type LockupSpend as bl, type OnchainSendAction as bm, type OnchainSendSwap as bn, type PersistableRfqSwap as bo, type PreimageBlockedReason as bp, PreimageNotRecoverableError as bq, RFQ_SWAP_RETENTION_SECONDS as br, type RefundOutcome as bs, type RfqRestoreFailure as bt, type RfqRestoreOptions as bu, type RfqRestoreResult as bv, type RfqSwapLockup as bw, RfqSwapManager as bx, type RfqSwapManagerConfig as by, type RfqSwapManagerDeps as bz, type AssetSwapStatus as c, type AssetSwapRepository as d, type RfqSwapRecord as e, type RfqSwapPageFilter as f, type RfqSwapPageCursor as g, type AssetSwap as h, type RouteResolution as i, type ResolvedEndpoint as j, type Route as k, type QuoteInput as l, type Pubkey as m, ACTIVITY_TOKEN as n, ARKADE_ASSET_NAMESPACE as o, Amount as p, AmountFormatError as q, type AmountOn as r, type AmountRefusal as s, type Artifact as t, AssetIdError as u, type AssetIdRefusal as v, type AssetNamespace as w, type AssetOn as x, type AssetPart as y, type AssetRef as z };