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