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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +52 -2
  2. package/dist/advanced.cjs +8376 -0
  3. package/dist/advanced.d.cts +550 -0
  4. package/dist/advanced.d.ts +550 -0
  5. package/dist/advanced.js +451 -0
  6. package/dist/chunk-A3SHHRX4.js +104 -0
  7. package/dist/chunk-HUQQVBC4.js +4262 -0
  8. package/dist/{chunk-EOYGUCDM.js → chunk-ITFCQWPG.js} +755 -1382
  9. package/dist/chunk-PVB7EBAM.js +2517 -0
  10. package/dist/errors-C3h8ANmE.d.ts +1560 -0
  11. package/dist/errors-hm7aqnRM.d.cts +1560 -0
  12. package/dist/index.cjs +4861 -3988
  13. package/dist/index.d.cts +69 -2812
  14. package/dist/index.d.ts +69 -2812
  15. package/dist/index.js +179 -3719
  16. package/dist/lockupContract-5r5RlgOJ.d.cts +137 -0
  17. package/dist/lockupContract-5r5RlgOJ.d.ts +137 -0
  18. package/dist/node/index.cjs +61 -10
  19. package/dist/node/index.d.cts +249 -591
  20. package/dist/node/index.d.ts +249 -591
  21. package/dist/node/index.js +65 -10
  22. package/dist/nostr.cjs +191 -11
  23. package/dist/nostr.d.cts +23 -68
  24. package/dist/nostr.d.ts +23 -68
  25. package/dist/nostr.js +3 -4
  26. package/dist/offer-Bd9Yvd8Z.d.ts +261 -0
  27. package/dist/offer-F88rtL_I.d.cts +261 -0
  28. package/dist/protocol.cjs +4086 -3706
  29. package/dist/protocol.d.cts +163 -768
  30. package/dist/protocol.d.ts +163 -768
  31. package/dist/protocol.js +190 -173
  32. package/dist/repositories/realm/index.cjs +55 -11
  33. package/dist/repositories/realm/index.d.cts +18 -30
  34. package/dist/repositories/realm/index.d.ts +18 -30
  35. package/dist/repositories/realm/index.js +49 -12
  36. package/dist/repositories/sqlite/index.cjs +61 -10
  37. package/dist/repositories/sqlite/index.d.cts +7 -6
  38. package/dist/repositories/sqlite/index.d.ts +7 -6
  39. package/dist/repositories/sqlite/index.js +57 -11
  40. package/dist/repository-BuYWGAKz.d.cts +2261 -0
  41. package/dist/repository-DYnRLPt-.d.ts +2261 -0
  42. package/dist/rfq-60PGpQ_x.d.cts +950 -0
  43. package/dist/rfq-60PGpQ_x.d.ts +950 -0
  44. package/dist/watch-BTyiBLSd.d.ts +74 -0
  45. package/dist/watch-M_KY-5ho.d.cts +74 -0
  46. package/package.json +20 -10
  47. package/dist/chunk-LYCMM3VB.js +0 -1357
  48. package/dist/chunk-U7VWWTL6.js +0 -66
  49. package/dist/repository-_zU9_pM3.d.cts +0 -3426
  50. package/dist/repository-kO95noyv.d.ts +0 -3426
  51. package/dist/rfq-DdBV4JO5.d.cts +0 -1097
  52. package/dist/rfq-DdBV4JO5.d.ts +0 -1097
  53. package/dist/watch-CQqvwgwY.d.cts +0 -96
  54. package/dist/watch-wMbmfN4p.d.ts +0 -96
package/dist/index.js CHANGED
@@ -1,3428 +1,104 @@
1
1
  import {
2
- ACTIVITY_TOKEN,
3
- BTC_ASSET_ID,
4
- CORRIDOR_PASS,
5
- INVOICE_HRPS,
6
- LIGHTNING_DRIVE,
7
- LOCKUP_OWNER,
8
- LockupNeedsRecoveryError,
9
- MARKETS_CACHE_TTL_MS,
10
- NoSpendableDepositError,
11
- OFFER_PACKET_TYPE,
12
- ONCHAIN_DRIVE,
13
- OfferCovenantMismatchError,
14
- QUOTE_OPTIONS,
15
- RETIRABLE,
16
- RefundNotLocallyPossibleError,
17
- RfqSwapManager,
18
- arkadeRefunder,
19
- classifyDepositSpend,
20
- corridorOutcome,
21
- createOffer,
22
- decodeOffer,
23
- findLockupVtxos,
24
- isRfqConfigurationRefusal,
25
- isRfqSwapTerminal,
26
- lightningCorridor,
27
- makeCachedFeedFetch,
28
- networksOfInvoiceHrp,
29
- offerOutcome,
30
- onchainCorridor,
31
- onchainSendProfile,
32
- preimageForSwapRecord,
33
- prepareOfferCancel,
34
- pushClaim,
35
- readsChain,
36
- rebuildRfqSwap,
37
- recordOutcome,
38
- restoreAssetSwaps,
39
- retireOfferContract,
40
- retireSettledOfferContracts,
41
- rfqClaimDestinationOf,
42
- rfqClaimSecretOf,
43
- rfqSecretsProfile,
44
- rfqSignerOf,
45
- rfqSwapOriginOf,
46
- senderIdentityForSwapRecord,
47
- spendTxidsOf,
48
- walletOperator,
49
- watchOfferSwaps
50
- } from "./chunk-EOYGUCDM.js";
51
- import {
52
- ARKADE_BTC,
53
- AddressMismatch,
54
- L1_NETWORKS,
55
- LIGHTNING_BTC,
56
- ONCHAIN_BTC,
57
- ONCHAIN_CLAIM_VSIZE,
58
- ONCHAIN_DUST_SATS,
59
- SwapRefusal,
60
- assertFundable,
61
- assertPairLength,
62
- assertReceivable,
63
- deriveLightningReceive,
64
- deriveLightningSend,
65
- deriveOnchainSend,
66
- l1NetworkFromArk,
67
- l1ScriptForAddress,
68
- lightningReceiveRequest,
69
- lightningSendRequest,
70
- lockupContractParams,
71
- newRfqId,
72
- onchainSendRequest,
73
- registerLockupContract,
74
- rfqPair,
75
- sealClaimPacket,
76
- unilateralClaimDelay
77
- } from "./chunk-LYCMM3VB.js";
78
- import {
79
- InMemoryAssetSwapRepository,
80
- marketsCacheKey
81
- } from "./chunk-U7VWWTL6.js";
82
-
83
- // src/client/accept.ts
84
- import { hex } from "@scure/base";
85
- import { asset as asset2, getAllNormalizedVtxos } from "@arkade-os/sdk";
86
-
87
- // src/client/assetId.ts
88
- import { asset, networks } from "@arkade-os/sdk";
89
- var RAILS = ["arkade", "bitcoin", "bolt11", "eip155"];
90
- var BITCOIN_RAILS = ["arkade", "bitcoin", "bolt11"];
91
- var BTC_ASSET_PART = "slip44:0";
92
- var ARKADE_ASSET_NAMESPACE = "asset";
93
- var AssetIdError = class extends Error {
94
- reason;
95
- value;
96
- constructor(reason, value, detail, options) {
97
- super(`invalid asset id ${JSON.stringify(value)}: ${detail}`, options);
98
- this.name = "AssetIdError";
99
- this.reason = reason;
100
- this.value = value;
101
- }
102
- };
103
- var REFERENCE_RULE = {
104
- slip44: /^(0|[1-9][0-9]{0,9})$/,
105
- /** The 68-lowercase-hex identity form; `asset.AssetId` then re-validates it. */
106
- asset: /^[0-9a-f]{68}$/,
107
- /**
108
- * Reserved for §9. Lowercase, never EIP-55: a checksum belongs on an
109
- * address a human types, and an id here comes out of the alias table or a
110
- * market card. Mixed case would be two spellings of one asset comparing
111
- * unequal in a pair string, a record and a cache key.
112
- */
113
- erc20: /^0x[0-9a-f]{40}$/
114
- };
115
- var CHAIN_REFERENCE = /^[-_a-z0-9]{1,32}$/;
116
- var CHAIN_ID = /^(0|[1-9][0-9]*)$/;
117
- var ASSET_REFERENCE = /^[-.%a-z0-9]{1,128}$/;
118
- var isRail = (value) => RAILS.includes(value);
119
- var isNetworkRef = (value) => Object.hasOwn(networks, value);
120
- var parseAssetId = (value) => {
121
- if (/[A-Z]/.test(value)) {
122
- throw new AssetIdError(
123
- "uppercase",
124
- value,
125
- "ids are lowercase throughout \u2014 lowercase an EIP-55 reference before it becomes one"
126
- );
127
- }
128
- const slash = value.indexOf("/");
129
- if (slash < 0) {
130
- throw new AssetIdError("malformed", value, "expected <rail>:<network>/<asset-ns>:<ref>");
131
- }
132
- if (value.indexOf("/", slash + 1) >= 0) {
133
- throw new AssetIdError(
134
- "token_id_unsupported",
135
- value,
136
- "a CAIP-19 token id has no meaning here"
137
- );
138
- }
139
- const chain = value.slice(0, slash);
140
- const assetPart = value.slice(slash + 1);
141
- const chainColon = chain.indexOf(":");
142
- const assetColon = assetPart.indexOf(":");
143
- if (chainColon < 0 || assetColon < 0) {
144
- throw new AssetIdError("malformed", value, "expected <rail>:<network>/<asset-ns>:<ref>");
145
- }
146
- const rail = chain.slice(0, chainColon);
147
- const reference = chain.slice(chainColon + 1);
148
- const assetNamespace = assetPart.slice(0, assetColon);
149
- const assetReference = assetPart.slice(assetColon + 1);
150
- if (!isRail(rail)) {
151
- throw new AssetIdError("unknown_rail", value, `no rail named ${JSON.stringify(rail)}`);
152
- }
153
- if (!CHAIN_REFERENCE.test(reference)) {
154
- throw new AssetIdError("malformed", value, "the chain reference is not CAIP-2 shaped");
155
- }
156
- if (rail === "eip155") {
157
- if (!CHAIN_ID.test(reference)) {
158
- throw new AssetIdError("invalid_chain_id", value, "eip155 takes a decimal chain id");
159
- }
160
- } else if (!isNetworkRef(reference)) {
161
- throw new AssetIdError(
162
- "unknown_network",
163
- value,
164
- `no bitcoin network named ${JSON.stringify(reference)}`
165
- );
166
- }
167
- if (!Object.hasOwn(REFERENCE_RULE, assetNamespace)) {
168
- throw new AssetIdError(
169
- "unknown_asset_namespace",
170
- value,
171
- `no asset namespace named ${JSON.stringify(assetNamespace)}`
172
- );
173
- }
174
- const namespace = assetNamespace;
175
- if (!ASSET_REFERENCE.test(assetReference) || !REFERENCE_RULE[namespace].test(assetReference)) {
176
- throw new AssetIdError(
177
- "invalid_asset_reference",
178
- value,
179
- `${namespace} takes no reference ${JSON.stringify(assetReference)}`
180
- );
181
- }
182
- if (namespace === ARKADE_ASSET_NAMESPACE) {
183
- try {
184
- asset.AssetId.fromString(assetReference);
185
- } catch (cause) {
186
- throw new AssetIdError(
187
- "invalid_asset_reference",
188
- value,
189
- "core refuses that issuance identity",
190
- { cause }
191
- );
192
- }
193
- }
194
- return { rail, reference, assetNamespace: namespace, assetReference };
195
- };
196
- var isAssetId = (value) => {
197
- try {
198
- parseAssetId(value);
199
- return true;
200
- } catch {
201
- return false;
202
- }
203
- };
204
- var formatAssetId = (parts) => {
205
- const id = `${parts.rail}:${parts.reference}/${parts.assetNamespace}:${parts.assetReference}`;
206
- parseAssetId(id);
207
- return id;
208
- };
209
- var railOf = (id) => parseAssetId(id).rail;
210
- var bitcoinNetworkOf = (id) => {
211
- const { rail, reference } = parseAssetId(id);
212
- return rail === "eip155" ? void 0 : reference;
213
- };
214
- var assetPartOf = (id) => {
215
- const { assetNamespace, assetReference } = parseAssetId(id);
216
- return `${assetNamespace}:${assetReference}`;
217
- };
218
- var sameAsset = (a, b) => {
219
- const left = parseAssetId(a);
220
- const right = parseAssetId(b);
221
- return left.reference === right.reference && left.assetNamespace === right.assetNamespace && left.assetReference === right.assetReference;
222
- };
223
- var btcOn = (rail, network) => (
224
- // The checker will not resolve the conditional against an unbound `R`; the
225
- // assertion is confined to this expression and never reaches a call site.
226
- `${rail}:${network}/${BTC_ASSET_PART}`
227
- );
228
- var arkadeAsset = (network, id) => `arkade:${network}/${ARKADE_ASSET_NAMESPACE}:${id.toString()}`;
229
- var issuanceOf = (id) => {
230
- const { assetNamespace, assetReference } = parseAssetId(id);
231
- return assetNamespace === ARKADE_ASSET_NAMESPACE ? asset.AssetId.fromString(assetReference) : void 0;
232
- };
233
-
234
- // src/client/aliases.ts
235
- import { NETWORKS, isNetwork } from "@arkade-os/solver-discovery";
236
-
237
- // src/client/errors.ts
238
- var AmbiguousDestination = class extends Error {
239
- constructor(destination, detail) {
240
- super(`cannot route ${JSON.stringify(destination)}: ${detail}`);
241
- this.destination = destination;
242
- }
243
- destination;
244
- name = "AmbiguousDestination";
245
- };
246
- var UnsupportedRoute = class extends Error {
247
- name = "UnsupportedRoute";
248
- give;
249
- take;
250
- constructor(detail, corridors = {}) {
251
- super(`unsupported route: ${detail}`);
252
- this.give = corridors.give;
253
- this.take = corridors.take;
254
- }
255
- };
256
- var DiscoverySnapshotUnavailable = class extends Error {
257
- constructor(network, detail) {
258
- super(`cannot resolve on ${network} offline: ${detail}`);
259
- this.network = network;
260
- }
261
- network;
262
- name = "DiscoverySnapshotUnavailable";
263
- };
264
- var AmountMismatch = class extends Error {
265
- constructor(sources) {
266
- super(`exactly one amount may be pinned; got ${sources[0]} and ${sources[1]}`);
267
- this.sources = sources;
268
- }
269
- sources;
270
- name = "AmountMismatch";
271
- };
272
- var AmountEncodingUnsupported = class extends Error {
273
- constructor(field, value, detail, options) {
274
- super(`${field}: ${detail}`, options);
275
- this.field = field;
276
- this.value = value;
277
- }
278
- field;
279
- value;
280
- name = "AmountEncodingUnsupported";
281
- };
282
- var QuoteVerificationFailed = class extends Error {
283
- constructor(check, expected, actual, options) {
284
- super(`quote failed the ${check} check \u2014 refusing to fund`, options);
285
- this.check = check;
286
- this.expected = expected;
287
- this.actual = actual;
288
- }
289
- check;
290
- name = "QuoteVerificationFailed";
291
- expected;
292
- actual;
293
- };
294
- var QuoteExpired = class extends Error {
295
- constructor(quoteId, expiresAt, now) {
296
- super(`quote ${quoteId} expired at ${expiresAt}, ${now - expiresAt} ago`);
297
- this.quoteId = quoteId;
298
- this.expiresAt = expiresAt;
299
- this.now = now;
300
- }
301
- quoteId;
302
- expiresAt;
303
- now;
304
- name = "QuoteExpired";
305
- };
306
- var MaxFeeExceeded = class extends Error {
307
- constructor(quoteId, asset3, fee, maxFee) {
308
- super(`fee ${fee} of ${asset3} exceeds the ${maxFee} ceiling`);
309
- this.quoteId = quoteId;
310
- this.asset = asset3;
311
- this.fee = fee;
312
- this.maxFee = maxFee;
313
- }
314
- quoteId;
315
- asset;
316
- fee;
317
- maxFee;
318
- name = "MaxFeeExceeded";
319
- };
320
- var InsufficientFunds = class extends Error {
321
- constructor(asset3, required, available) {
322
- super(
323
- `funding needs ${required} of ${asset3}` + (available === void 0 ? "" : `, wallet holds ${available}`)
324
- );
325
- this.asset = asset3;
326
- this.required = required;
327
- this.available = available;
328
- }
329
- asset;
330
- required;
331
- name = "InsufficientFunds";
332
- available;
333
- };
334
- var AcceptConflict = class extends Error {
335
- constructor(quoteId, swapId, fields) {
336
- super(`accept ${quoteId} conflicts with swap ${swapId} on ${fields.join(", ")}`);
337
- this.quoteId = quoteId;
338
- this.swapId = swapId;
339
- this.fields = fields;
340
- }
341
- quoteId;
342
- swapId;
343
- fields;
344
- name = "AcceptConflict";
345
- };
346
- var ClientDisposed = class extends Error {
347
- constructor(method) {
348
- super(`${method}() called after the client was disposed`);
349
- this.method = method;
350
- }
351
- method;
352
- name = "ClientDisposed";
353
- };
354
- var NotCancellable = class extends Error {
355
- constructor(swapId) {
356
- super(`swap ${swapId} is not a cancellable asset swap`);
357
- this.swapId = swapId;
358
- }
359
- swapId;
360
- name = "NotCancellable";
361
- };
362
- var InconsistentRoute = class extends Error {
363
- constructor(asset3, destination) {
364
- super(`destination ${JSON.stringify(destination)} is not on ${asset3}'s chain`);
365
- this.asset = asset3;
366
- this.destination = destination;
367
- }
368
- asset;
369
- destination;
370
- name = "InconsistentRoute";
371
- };
372
- var OperatorUnreachable = class extends Error {
373
- name = "OperatorUnreachable";
374
- constructor(detail, options) {
375
- super(`cannot derive a covenant: ${detail}`, options);
376
- }
377
- };
378
- var MissingCorridorDep = class extends Error {
379
- constructor(corridor, dep) {
380
- super(`the ${corridor} corridor has no ${dep}`);
381
- this.corridor = corridor;
382
- this.dep = dep;
383
- }
384
- corridor;
385
- dep;
386
- name = "MissingCorridorDep";
387
- };
388
- var SWAP_ERRORS = {
2
+ ARKADE_ASSET_NAMESPACE,
3
+ AcceptConflict,
389
4
  AmbiguousDestination,
390
- UnsupportedRoute,
391
- DiscoverySnapshotUnavailable,
392
- AmountMismatch,
5
+ Amount,
393
6
  AmountEncodingUnsupported,
394
- QuoteVerificationFailed,
395
- SwapRefusal,
396
- QuoteExpired,
397
- MaxFeeExceeded,
398
- InsufficientFunds,
399
- AcceptConflict,
7
+ AmountFormatError,
8
+ AmountMismatch,
9
+ AssetIdError,
10
+ BITCOIN_RAILS,
11
+ BTC_ASSET_PART,
400
12
  ClientDisposed,
401
- NotCancellable,
13
+ DiscoverySnapshotUnavailable,
402
14
  InconsistentRoute,
15
+ InsufficientFunds,
16
+ MaxFeeExceeded,
17
+ MissingCorridorDep,
18
+ NotCancellable,
19
+ ONCHAIN_SWAP_RAIL,
403
20
  OperatorUnreachable,
404
- MissingCorridorDep
405
- };
406
- var SWAP_ERROR_NAMES = Object.keys(SWAP_ERRORS);
407
- function isSwapError(e, name) {
408
- if (!(e instanceof Error)) return false;
409
- const table = SWAP_ERRORS;
410
- const ctor = table[e.name];
411
- if (ctor === void 0 || !(e instanceof ctor)) return false;
412
- return name === void 0 || e.name === name;
413
- }
414
-
415
- // src/client/aliases.ts
416
- var toDiscoveryLeg = (id) => {
417
- const { rail, assetNamespace, assetReference } = parseAssetId(id);
418
- const asset3 = `${assetNamespace}:${assetReference}`;
419
- if (rail === "arkade") {
420
- if (asset3 === BTC_ASSET_PART) return { corridor: "arkade", assetId: BTC_ASSET_ID };
421
- if (assetNamespace === ARKADE_ASSET_NAMESPACE) {
422
- return { corridor: "arkade", assetId: assetReference };
423
- }
424
- throw new UnsupportedRoute(`the arkade corridor has no ${asset3}`);
425
- }
426
- if (rail === "bolt11") {
427
- if (asset3 === BTC_ASSET_PART) return { corridor: "lightning", assetId: BTC_ASSET_ID };
428
- throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset3}`);
429
- }
430
- if (rail === "bitcoin") {
431
- if (asset3 === BTC_ASSET_PART) return { corridor: "onchain", assetId: BTC_ASSET_ID };
432
- throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset3}`);
433
- }
434
- throw new UnsupportedRoute(`no corridor serves ${id}`);
435
- };
436
- var INDEXED_NETWORKS = NETWORKS;
437
- var isIndexedNetwork = (network) => isNetwork(network);
438
- var networkOfRow = (row) => parseAssetId(row.id).reference;
439
- var canonicalAssetId = (input, table) => {
440
- if (isAssetId(input)) return input;
441
- const wanted = input.trim().toLowerCase();
442
- const matches = table.assets.filter(
443
- (row) => row.ticker.toLowerCase() === wanted && networkOfRow(row) === table.network
444
- );
445
- if (matches.length === 0) {
446
- throw new AssetIdError(
447
- "unknown_alias",
448
- input,
449
- `no asset with that ticker on ${table.network}`
450
- );
451
- }
452
- const distinct = new Set(matches.map((row) => row.id));
453
- if (distinct.size > 1) {
454
- throw new AssetIdError(
455
- "ambiguous_alias",
456
- input,
457
- `${distinct.size} assets on ${table.network} answer to that ticker: ${[...distinct].join(", ")}`
458
- );
459
- }
460
- return matches[0].id;
461
- };
462
-
463
- // src/client/amount.ts
464
- import {
465
- AMOUNT_PATTERN,
466
- MAX_ASSET_DECIMALS,
467
- fromAtomic,
468
- isAmount,
469
- toAtomic
470
- } from "@arkade-os/solver-discovery";
471
- var AmountFormatError = class extends Error {
472
- constructor(reason, message) {
473
- super(message);
474
- this.reason = reason;
475
- }
476
- reason;
477
- name = "AmountFormatError";
478
- };
479
- var SCALED_DECIMAL = /^([0-9]+)(?:\.([0-9]+))?$/;
480
- var ATOMIC_CEILING = 10n ** 30n;
481
- var MAX_SIGNIFICANT_DIGITS = 64;
482
- var assertDecimals = (decimals) => {
483
- if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_ASSET_DECIMALS) {
484
- throw new AmountFormatError(
485
- "invalid_decimals",
486
- `decimals must be an integer in [0, ${MAX_ASSET_DECIMALS}], got ${decimals}`
487
- );
488
- }
489
- };
490
- var assertRepresentable = (value, what) => {
491
- if (value >= ATOMIC_CEILING) {
492
- throw new AmountFormatError(
493
- "too_large",
494
- `${what} does not fit the canonical 30-digit encoding`
495
- );
496
- }
497
- };
498
- var Amount = {
499
- /**
500
- * A human decimal into atomic units.
501
- *
502
- * `string` only, and no exponent. Accepting a `number` is the whole v1
503
- * footgun: it makes `100000` ambiguous between sats and whole BTC, and by
504
- * the time the ambiguity resolves the offer is funded. Exponent form goes
505
- * for the same reason — a UI never produces `1e-4`, so accepting it only
506
- * widens what a mistake can look like.
507
- *
508
- * Refuses rather than rounds when the input is finer than the asset: a
509
- * silently truncated amount is a swap for the wrong size, and nothing
510
- * downstream can tell it was ever a different number. Refuses too when the
511
- * result would not survive the record boundary, so one law holds in both
512
- * directions.
513
- */
514
- parse(display, asset3) {
515
- assertDecimals(asset3.decimals);
516
- const parts = SCALED_DECIMAL.exec(display);
517
- if (!parts) {
518
- throw new AmountFormatError(
519
- "not_decimal",
520
- `not an unsigned decimal amount: ${JSON.stringify(display)} (write 0.5, not .5; no sign, exponent, separator or space)`
521
- );
522
- }
523
- const [, whole, fraction = ""] = parts;
524
- if (fraction.length > asset3.decimals) {
525
- throw new AmountFormatError(
526
- "too_precise",
527
- `${display} has more precision than ${asset3.decimals} decimals allow`
528
- );
529
- }
530
- if (whole.length + fraction.length > MAX_SIGNIFICANT_DIGITS) {
531
- throw new AmountFormatError("too_large", `${display} has too many digits`);
532
- }
533
- const value = toAtomic(display, asset3.decimals);
534
- assertRepresentable(value, `${display} at ${asset3.decimals} decimals`);
535
- return value;
536
- },
537
- /**
538
- * Atomic units into a human decimal, trailing zeros trimmed.
539
- *
540
- * Refuses a negative: every amount on this surface is an obligation, and a
541
- * negative one is a defect upstream rather than a number to render.
542
- */
543
- format(value, asset3) {
544
- assertDecimals(asset3.decimals);
545
- if (value < 0n) {
546
- throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
547
- }
548
- assertRepresentable(value, `${value}`);
549
- return fromAtomic(value, asset3.decimals);
550
- }
551
- };
552
- var toAtomicDecimal = (value) => {
553
- if (value < 0n) {
554
- throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
555
- }
556
- assertRepresentable(value, `${value}`);
557
- return value.toString();
558
- };
559
- var fromAtomicDecimal = (text) => {
560
- if (!isAmount(text)) {
561
- throw new AmountFormatError(
562
- "not_canonical",
563
- `not a canonical atomic amount: ${JSON.stringify(text)}`
564
- );
565
- }
566
- return BigInt(text);
567
- };
568
- var isAtomicDecimal = (value) => typeof value === "string" && AMOUNT_PATTERN.test(value);
569
-
570
- // src/client/rfqAmount.ts
571
- import { isAmount as isAmount2 } from "@arkade-os/solver-discovery";
572
- var toRfqAmountSide = (on) => on === "give" ? "from" : "to";
573
- var fromRfqAmountSide = (side) => side === "from" ? "give" : "take";
574
- var encodeRfqAmount = (value, field) => {
575
- try {
576
- return toAtomicDecimal(value);
577
- } catch (cause) {
578
- throw new AmountEncodingUnsupported(
579
- field,
580
- `${value}`,
581
- "the wire's canonical encoding cannot carry it",
582
- { cause }
583
- );
584
- }
585
- };
586
- var decodeRfqAmount = (raw, field) => {
587
- if (typeof raw === "string") {
588
- if (!isAmount2(raw)) {
589
- throw new AmountEncodingUnsupported(
590
- field,
591
- raw,
592
- "not a canonical decimal amount (unsigned, no leading zeros, 30 digits)"
593
- );
594
- }
595
- return BigInt(raw);
596
- }
597
- if (typeof raw === "number") {
598
- if (!Number.isSafeInteger(raw) || raw < 0) {
599
- throw new AmountEncodingUnsupported(
600
- field,
601
- `${raw}`,
602
- // Past 2^53 the number arrived already rounded — there is no
603
- // "narrow carefully" branch, only a wrong amount.
604
- "a JSON number amount is only readable as a non-negative safe integer"
605
- );
606
- }
607
- return BigInt(raw);
608
- }
609
- throw new AmountEncodingUnsupported(
610
- field,
611
- typeof raw === "bigint" || typeof raw === "boolean" ? `${raw}` : String(raw),
612
- `expected a decimal string, got ${typeof raw}`
613
- );
614
- };
615
- var toSafeNumber = (value, field) => {
616
- if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
617
- throw new AmountEncodingUnsupported(
618
- field,
619
- `${value}`,
620
- "does not fit a non-negative safe integer"
621
- );
622
- }
623
- return Number(value);
624
- };
625
-
626
- // src/client/record.ts
627
- var assetSwapIdOf = (family, quoteId) => `${family}:${quoteId}`;
628
- var OFFER_SWAP_ID_PREFIX = "offer:";
629
- var RFQ_SWAP_ID_PREFIX = "rfq:";
630
- var familyOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? "offer" : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? "rfq" : void 0;
631
- var quoteIdOfSwapId = (swapId) => swapId.startsWith(OFFER_SWAP_ID_PREFIX) ? swapId.slice(OFFER_SWAP_ID_PREFIX.length) : swapId.startsWith(RFQ_SWAP_ID_PREFIX) ? swapId.slice(RFQ_SWAP_ID_PREFIX.length) : swapId;
632
- var recordEndpoint = (endpoint2) => ({
633
- corridor: endpoint2.corridor,
634
- asset: endpoint2.asset,
635
- instrument: recordInstrument(endpoint2.instrument)
636
- });
637
- var recordInstrument = (instrument) => {
638
- switch (instrument.kind) {
639
- case "wallet":
640
- return { kind: "wallet" };
641
- case "address":
642
- return { kind: "address", address: instrument.address };
643
- case "invoice":
644
- return {
645
- kind: "invoice",
646
- bolt11: instrument.bolt11,
647
- paymentHash: instrument.paymentHash,
648
- ...instrument.amount === void 0 ? {} : { amount: toAtomicDecimal(instrument.amount) },
649
- expiresAt: instrument.expiresAt
650
- };
651
- }
652
- };
653
- var instrumentOf = (instrument) => {
654
- switch (instrument.kind) {
655
- case "wallet":
656
- return { kind: "wallet" };
657
- case "address":
658
- return { kind: "address", address: instrument.address };
659
- case "invoice":
660
- return {
661
- kind: "invoice",
662
- bolt11: instrument.bolt11,
663
- paymentHash: instrument.paymentHash,
664
- ...instrument.amount === void 0 ? {} : { amount: fromAtomicDecimal(instrument.amount) },
665
- expiresAt: instrument.expiresAt
666
- };
667
- }
668
- };
669
- var recordArtifact = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
670
- kind: "deposit",
671
- corridor: artifact.corridor,
672
- address: artifact.address,
673
- asset: artifact.asset,
674
- amount: toAtomicDecimal(artifact.amount),
675
- ...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
676
- };
677
- var artifactOf = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
678
- kind: "deposit",
679
- corridor: artifact.corridor,
680
- address: artifact.address,
681
- asset: artifact.asset,
682
- amount: fromAtomicDecimal(artifact.amount),
683
- ...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
684
- };
685
- var recordLeg = (leg) => ({
686
- asset: leg.asset,
687
- amount: toAtomicDecimal(leg.amount)
688
- });
689
- var legOf = (leg) => ({
690
- asset: leg.asset,
691
- amount: fromAtomicDecimal(leg.amount)
692
- });
693
- var swapOf = (record, outcome) => ({
694
- id: assetSwapIdOf(record.family, record.id),
695
- family: record.family,
696
- outcome,
697
- route: {
698
- give: {
699
- corridor: record.route.give.corridor,
700
- asset: record.route.give.asset,
701
- instrument: instrumentOf(record.route.give.instrument)
702
- },
703
- take: {
704
- corridor: record.route.take.corridor,
705
- asset: record.route.take.asset,
706
- instrument: instrumentOf(record.route.take.instrument)
707
- }
708
- },
709
- give: legOf(record.give),
710
- take: legOf(record.take),
711
- fee: legOf(record.fee),
712
- market: record.market,
713
- ...record.solver === void 0 ? {} : { solver: record.solver },
714
- ...record.family === "rfq" ? { lock: record.lock } : {},
715
- ...record.family === "rfq" ? { refundLocktime: record.refundLocktime } : {},
716
- ...record.artifact === void 0 ? {} : { artifact: artifactOf(record.artifact) },
717
- expiresAt: record.expiresAt,
718
- ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
719
- ...record.failure === void 0 ? {} : { failure: record.failure },
720
- ...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason },
721
- createdAt: record.createdAt,
722
- updatedAt: record.updatedAt
723
- });
724
- var fundsFromWallet = (route) => route.give.instrument.kind === "wallet";
725
-
726
- // src/client/accept.ts
727
- var storageOf = (repository) => {
728
- if (repository === void 0) {
729
- throw new MissingCorridorDep("arkade", "repository");
730
- }
731
- return repository;
732
- };
733
- var sameRecordedInstrument = (a, b) => {
734
- switch (a.kind) {
735
- case "wallet":
736
- return b.kind === "wallet";
737
- case "address":
738
- return b.kind === "address" && a.address === b.address;
739
- case "invoice":
740
- return b.kind === "invoice" && a.bolt11 === b.bolt11 && a.paymentHash === b.paymentHash && a.amount === b.amount && a.expiresAt === b.expiresAt;
741
- }
742
- };
743
- var conflictingFields = (record, quote) => {
744
- const incoming = recordedFacts(quote);
745
- const stored = {
746
- "route.pair": `${record.route.give.corridor}->${record.route.take.corridor}`,
747
- "give.asset": record.route.give.asset,
748
- "take.asset": record.route.take.asset,
749
- "give.amount": record.give.amount,
750
- "take.amount": record.take.amount,
751
- "give.instrument": record.route.give.instrument,
752
- "take.instrument": record.route.take.instrument,
753
- "lock.hash": record.family === "rfq" ? record.lock.hash : void 0,
754
- refundLocktime: record.family === "rfq" ? String(record.refundLocktime) : void 0,
755
- solver: record.solver,
756
- "market.source": marketSourceOf(record.market)
757
- };
758
- return Object.keys(incoming).filter((field) => {
759
- if (field === "give.instrument" || field === "take.instrument") {
760
- return !sameRecordedInstrument(stored[field], incoming[field]);
761
- }
762
- const a = stored[field];
763
- const b = incoming[field];
764
- if (a === void 0 && b === void 0) return false;
765
- return a !== b;
766
- });
767
- };
768
- var recordedFacts = (quote) => ({
769
- "route.pair": `${quote.route.give.corridor}->${quote.route.take.corridor}`,
770
- "give.asset": quote.route.give.asset,
771
- "take.asset": quote.route.take.asset,
772
- "give.amount": recordLeg(quote.give).amount,
773
- "take.amount": recordLeg(quote.take).amount,
774
- "give.instrument": recordEndpoint(quote.route.give).instrument,
775
- "take.instrument": recordEndpoint(quote.route.take).instrument,
776
- "lock.hash": quote.lock?.hash,
777
- refundLocktime: quote.refundLocktime === void 0 ? void 0 : String(quote.refundLocktime),
778
- solver: quote.solver,
779
- "market.source": marketSourceOf(quote.market)
780
- });
781
- var marketSourceOf = (market) => market.kind === "card" ? market.source : void 0;
782
- var assertFundable2 = async (wallet, quote) => {
783
- const give = quote.give;
784
- const balance = await wallet.getBalance();
785
- if (assetPartOf(give.asset) === BTC_ASSET_PART) {
786
- const available2 = BigInt(balance.available);
787
- if (available2 < give.amount) {
788
- throw new InsufficientFunds(give.asset, give.amount, available2);
789
- }
790
- return;
791
- }
792
- const held = balance.availableAssets.find((a) => give.asset.endsWith(a.assetId));
793
- const available = held?.amount ?? 0n;
794
- if (available < give.amount) {
795
- throw new InsufficientFunds(give.asset, give.amount, available);
796
- }
797
- };
798
- var commonOf = (quote, now) => ({
799
- id: quote.id,
800
- route: {
801
- give: recordEndpoint(quote.route.give),
802
- take: recordEndpoint(quote.route.take)
803
- },
804
- give: recordLeg(quote.give),
805
- take: recordLeg(quote.take),
806
- fee: recordLeg(quote.fee),
807
- market: quote.market,
808
- ...quote.solver === void 0 ? {} : { solver: quote.solver },
809
- expiresAt: quote.expiresAt,
810
- ...quote.artifact === void 0 ? {} : { artifact: recordArtifact(quote.artifact) },
811
- createdAt: now,
812
- updatedAt: now
813
- });
814
- var corridorRecord = (quote, preparation, now) => {
815
- if (quote.lock === void 0 || quote.refundLocktime === void 0) {
816
- throw new Error(`corridor quote ${quote.id} carries no lock hash or refund locktime`);
817
- }
818
- return {
819
- ...commonOf(quote, now),
820
- family: "rfq",
821
- state: "pending",
822
- kind: kindOf(preparation),
823
- rfqId: preparation.rfqId,
824
- lockupAddress: preparation.lockup.address,
825
- lockupPkScript: hex.encode(preparation.lockup.pkScript),
826
- lock: { hash: quote.lock.hash },
827
- refundLocktime: quote.refundLocktime,
828
- profile: profileOf(preparation, quote.lock.hash)
829
- };
830
- };
831
- var kindOf = (preparation) => {
832
- switch (preparation.route) {
833
- case "arkade->lightning":
834
- return "lightning_send";
835
- case "lightning->arkade":
836
- return "lightning_receive";
837
- case "arkade->onchain":
838
- return "onchain_send";
839
- }
840
- };
841
- var profileOf = (preparation, paymentHash) => {
842
- const secrets = rfqSecretsProfile(preparation.secrets, paymentHash);
843
- switch (preparation.route) {
844
- case "arkade->lightning":
845
- return { ...secrets };
846
- case "lightning->arkade":
847
- return {
848
- ...secrets,
849
- expectedAmount: toSafeNumber(preparation.expectedAmount, "expectedAmount"),
850
- payoutAddress: preparation.payoutAddress
851
- };
852
- case "arkade->onchain":
853
- return {
854
- ...secrets,
855
- ...onchainSendProfile({
856
- htlc: preparation.htlc,
857
- htlcParams: preparation.htlcParams,
858
- l1Network: preparation.l1Network,
859
- minConfirmations: preparation.minConfirmations,
860
- payoutPkScript: preparation.payoutPkScript
861
- })
862
- };
863
- }
864
- };
865
- var acceptQuote = async (input) => {
866
- const { quote, wallet, now } = input;
867
- const repository = storageOf(input.repository);
868
- const answer = (record2) => input.drive ? input.drive.adopt(record2) : swapOf(record2, recordOutcome(record2));
869
- const expired = now > quote.expiresAt;
870
- const stored = await repository.getSwapRecord(quote.id);
871
- if (stored !== void 0) {
872
- const fields = conflictingFields(stored, quote);
873
- if (fields.length > 0) {
874
- throw new AcceptConflict(quote.id, stored.id, fields);
875
- }
876
- if (stored.fundingTxid !== void 0) return answer(stored);
877
- if (!fundsFromWallet(stored.route)) return answer(stored);
878
- const found = await reconcileFunding({ wallet }, stored);
879
- if (found !== void 0) {
880
- return answer(await stampFunding(repository, stored, found, now));
881
- }
882
- if (expired) throw new QuoteExpired(quote.id, quote.expiresAt, now);
883
- return answer(await fundAndStamp({ wallet, now }, stored, repository));
884
- }
885
- if (expired) throw new QuoteExpired(quote.id, quote.expiresAt, now);
886
- const preparation = input.preparation;
887
- if (preparation === void 0) {
888
- throw new Error(
889
- `quote ${quote.id} was not derived by this client instance; re-quote before accepting`
890
- );
891
- }
892
- const funds = fundsFromWallet(quote.route);
893
- if (funds) await assertFundable2(wallet, quote);
894
- const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
895
- await repository.saveSwapRecord(record);
896
- if (!funds) return answer(record);
897
- return answer(await fundAndStamp({ wallet, now }, record, repository));
898
- };
899
- var registeredOfferRecord = async (input, preparation) => {
900
- const { quote, wallet, corridors, now } = input;
901
- const { plan } = preparation;
902
- const arkade = corridors.get("arkade").deps;
903
- const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
904
- const offer = await createOffer(wallet, {
905
- // Keyed on the receive side: the covenant binds what the fill delivers.
906
- wantAmount: plan.receive.atomic,
907
- ...receiveIsBtc ? { offerAsset: asset2.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: asset2.AssetId.fromString(plan.receive.asset.id) },
908
- emulatorPubkey: arkade.emulatorPubkey
909
- });
910
- return {
911
- ...commonOf(quote, now),
912
- family: "offer",
913
- status: "pending",
914
- offerHex: offer.offerHex,
915
- swapAddress: offer.address,
916
- swapPkScript: hex.encode(offer.swapPkScript)
917
- };
918
- };
919
- var registeredCorridorRecord = async (input, preparation) => {
920
- const contracts = await input.wallet.getContractManager();
921
- await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address);
922
- return corridorRecord(input.quote, preparation, input.now);
923
- };
924
- var fundAndStamp = async (input, record, repository) => {
925
- const txid = await fund(input, record);
926
- return stampFunding(repository, record, txid, input.now);
927
- };
928
- var stampFunding = async (repository, record, fundingTxid, now) => {
929
- const stamped = { ...record, fundingTxid, updatedAt: now };
930
- try {
931
- await repository.saveSwapRecord(stamped);
932
- } catch (error) {
933
- console.warn(`[swap] funded ${record.id} but could not store its txid`, error);
934
- }
935
- return stamped;
936
- };
937
- var fund = async (input, record) => {
938
- const { wallet } = input;
939
- if (record.family === "offer") {
940
- const amount = fromAtomicDecimal(record.give.amount);
941
- const depositIsBtc = assetPartOf(record.route.give.asset) === BTC_ASSET_PART;
942
- return wallet.send({
943
- address: record.swapAddress,
944
- // An asset deposit rides the SDK's dust-sat carrier, so the sats
945
- // amount is left to the default rather than set here.
946
- ...depositIsBtc ? { amount: toSafeNumber(amount, "give.amount") } : {
947
- assets: [
948
- { assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
949
- ]
950
- },
951
- extensions: [offerExtensionOf(record)]
952
- });
953
- }
954
- if (record.kind === "lightning_receive") {
955
- throw new Error(`receive swap ${record.id} funds nothing from this wallet`);
956
- }
957
- return wallet.send({
958
- address: record.lockupAddress,
959
- amount: toSafeNumber(fromAtomicDecimal(record.give.amount), "give.amount")
960
- });
961
- };
962
- var offerExtensionOf = (record) => ({
963
- type: OFFER_PACKET_TYPE,
964
- payload: hex.decode(record.offerHex)
965
- });
966
- var reconcileFunding = async (input, record) => {
967
- const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
968
- const expected = BigInt(record.give.amount);
969
- const reader = await input.wallet.getArkadeReader();
970
- const vtxos = await getAllNormalizedVtxos(reader, [script]);
971
- const deposit = vtxos.find((vtxo) => depositMatches(vtxo, record, expected));
972
- return deposit?.txid;
973
- };
974
- var depositMatches = (vtxo, record, expected) => {
975
- const giveAsset = record.route.give.asset;
976
- if (assetPartOf(giveAsset) === BTC_ASSET_PART) {
977
- return BigInt(vtxo.value) === expected;
978
- }
979
- return (vtxo.assets ?? []).some(
980
- (entry) => giveAsset.endsWith(entry.assetId) && entry.amount === expected
981
- );
982
- };
983
- var swapRecordOf = async (repository, id) => storageOf(repository).getSwapRecord(id);
984
-
985
- // src/client/aliasTable.ts
986
- import { marketCorridor } from "@arkade-os/solver-discovery";
987
-
988
- // src/client/corridor.ts
989
- import {
990
- CORRIDORS as DISCOVERY_CORRIDORS
991
- } from "@arkade-os/solver-discovery";
992
- var CORRIDORS = DISCOVERY_CORRIDORS;
993
- var RAIL_BY_CORRIDOR = {
994
- arkade: "arkade",
995
- lightning: "bolt11",
996
- onchain: "bitcoin"
997
- };
998
- var CORRIDOR_BY_RAIL = {
999
- arkade: "arkade",
1000
- bolt11: "lightning",
1001
- bitcoin: "onchain"
1002
- };
1003
- var railOfCorridor = (corridor) => corridor in RAIL_BY_CORRIDOR ? RAIL_BY_CORRIDOR[corridor] : "eip155";
1004
- var corridorOfRail = (rail) => rail === "eip155" ? void 0 : CORRIDOR_BY_RAIL[rail];
1005
-
1006
- // src/client/aliasTable.ts
1007
- var ARKADE_ASSET_IDENTITY = /^[0-9a-f]{68}$/;
1008
- var publicAssetId = (corridor, assetId, network) => {
1009
- const rail = railOfCorridor(corridor);
1010
- if (assetId === BTC_ASSET_ID) return btcOn(rail, network);
1011
- if (rail !== "arkade") return void 0;
1012
- if (!ARKADE_ASSET_IDENTITY.test(assetId)) return void 0;
1013
- return `arkade:${network}/${ARKADE_ASSET_NAMESPACE}:${assetId}`;
1014
- };
1015
- var aliasTableFrom = (markets, network) => {
1016
- const rows = /* @__PURE__ */ new Map();
1017
- const add = (card, side) => {
1018
- const info = side === "base" ? card.base_asset : card.quote_asset;
1019
- const id = publicAssetId(marketCorridor(card, side), info.id, network);
1020
- if (id === void 0 || typeof info.ticker !== "string" || info.ticker === "") return;
1021
- rows.set(`${id} ${info.ticker.toLowerCase()}`, { id, ticker: info.ticker });
1022
- };
1023
- for (const card of markets) {
1024
- add(card, "base");
1025
- add(card, "quote");
1026
- }
1027
- return { network, assets: [...rows.values()] };
1028
- };
1029
- var scopedToRail = (table, rail) => ({
1030
- network: table.network,
1031
- assets: table.assets.filter((row) => row.id.startsWith(`${rail}:`))
1032
- });
1033
-
1034
- // src/client/client.ts
1035
- import { hex as hex6 } from "@scure/base";
1036
-
1037
- // src/client/corridors/registry.ts
1038
- import { isLnurl } from "@arkade-os/sdk";
1039
-
1040
- // src/client/corridors/arkade.ts
1041
- import { ArkAddress, arkTarget, assertRecipientArkadeAddress } from "@arkade-os/sdk";
1042
- var ARKADE_DRIVE = {};
1043
- var messageOf = (error) => error instanceof Error ? error.message : String(error);
1044
- var arkadeCorridor = Object.assign(
1045
- (deps) => ({
1046
- corridor: "arkade",
1047
- deps,
1048
- drive: ARKADE_DRIVE,
1049
- matches(raw) {
1050
- const target = arkTarget(raw);
1051
- if (target === void 0) return void 0;
1052
- try {
1053
- const address = ArkAddress.decode(target);
1054
- assertRecipientArkadeAddress(target, address, {
1055
- hrp: deps.network.hrp,
1056
- signerSet: deps.signerSet
1057
- });
1058
- } catch (error) {
1059
- return { refused: messageOf(error) };
1060
- }
1061
- return { claimed: { kind: "address", address: target } };
1062
- }
1063
- }),
1064
- { target: arkTarget }
1065
- );
1066
-
1067
- // src/client/corridors/deps.ts
1068
- import {
1069
- ESPLORA_URL,
1070
- defaultEmulatorPubkey,
1071
- getNetwork,
1072
- resolveEmulatorPubkey,
1073
- signerSetFromInfo
1074
- } from "@arkade-os/sdk";
1075
-
1076
- // src/client/corridors/bolt11.ts
1077
- import bolt11 from "light-bolt11-decoder";
1078
- var DEFAULT_INVOICE_EXPIRY_SECONDS = 3600;
1079
- var valueOf = (decoded, name) => decoded.sections.find(
1080
- (section) => section.name === name
1081
- )?.value;
1082
- var PAYMENT_HASH = /^[0-9a-f]{64}$/;
1083
- var decodeBolt11 = (invoice) => {
1084
- const decoded = bolt11.decode(invoice);
1085
- const timestamp = valueOf(decoded, "timestamp");
1086
- if (typeof timestamp !== "number" || !Number.isFinite(timestamp)) {
1087
- throw new Error("bolt11 invoice carries no timestamp");
1088
- }
1089
- const expiry = valueOf(decoded, "expiry");
1090
- const expiresAt = timestamp + (typeof expiry === "number" ? expiry : DEFAULT_INVOICE_EXPIRY_SECONDS);
1091
- const paymentHash = valueOf(decoded, "payment_hash");
1092
- if (typeof paymentHash !== "string" || !PAYMENT_HASH.test(paymentHash)) {
1093
- throw new Error("bolt11 invoice carries no payment hash");
1094
- }
1095
- const millisats = valueOf(decoded, "amount");
1096
- const amountSats = typeof millisats === "string" ? Number(BigInt(millisats) / 1000n) : (
1097
- /* amountless */
1098
- 0
1099
- );
1100
- return { raw: invoice, paymentHash, amountSats, expiresAt };
1101
- };
1102
-
1103
- // src/client/corridors/chainSource.ts
1104
- import { hex as hex2 } from "@scure/base";
1105
- import * as btc from "@scure/btc-signer";
1106
- import { EsploraProvider } from "@arkade-os/sdk";
1107
- var addressOfScript = (script, network) => btc.Address(network).encode(btc.OutScript.decode(script));
1108
- var chainSourceOver = (backend, network) => {
1109
- const spenderFromVins = async (txid, vout, pkScript) => {
1110
- let address;
1111
- try {
1112
- address = addressOfScript(pkScript, network);
1113
- } catch {
1114
- return void 0;
1115
- }
1116
- for (const tx of await backend.provider.getTransactions(address)) {
1117
- if ((tx.vin ?? []).some((input) => input.txid === txid && input.vout === vout)) {
1118
- return tx.txid;
1119
- }
1120
- }
1121
- return void 0;
1122
- };
1123
- return {
1124
- async getScriptUtxos(pkScript) {
1125
- const address = addressOfScript(pkScript, network);
1126
- const [coins, tip] = await Promise.all([
1127
- backend.provider.getCoins(address),
1128
- backend.tip()
1129
- ]);
1130
- return coins.map((coin) => ({
1131
- txid: coin.txid,
1132
- vout: coin.vout,
1133
- // `Coin.value` is `number` sats; the HTLC's is `bigint`.
1134
- amount: BigInt(coin.value),
1135
- // `Coin` carries a height, never a depth, so the tip is the
1136
- // second half of the answer. A confirmed coin is one deep, not
1137
- // zero — the block it landed in counts.
1138
- confirmations: coin.status.confirmed && coin.status.block_height !== void 0 ? Math.max(0, tip.height - coin.status.block_height + 1) : 0
1139
- }));
1140
- },
1141
- async getSpendingTx(txid, vout, pkScript) {
1142
- const outspends = await backend.provider.getTxOutspends(txid);
1143
- const outspend = outspends[vout];
1144
- if (!outspend?.spent) return null;
1145
- const spender = outspend.txid || await spenderFromVins(txid, vout, pkScript);
1146
- if (!spender) return null;
1147
- return { txHex: hex2.encode(await backend.provider.getRawTransaction(spender)) };
1148
- },
1149
- broadcast(txHex) {
1150
- return backend.provider.broadcastTransaction(txHex);
1151
- },
1152
- async getMtp() {
1153
- return (await backend.tip()).mtp;
1154
- }
1155
- };
1156
- };
1157
- var esploraTip = async (esploraUrl, fetchImpl) => {
1158
- const response = await (fetchImpl ?? fetch)(`${esploraUrl}/blocks`);
1159
- if (!response.ok) {
1160
- throw new Error(`failed to read the chain tip: ${response.status} ${response.statusText}`);
1161
- }
1162
- const blocks = await response.json();
1163
- const tip = Array.isArray(blocks) ? blocks[0] : void 0;
1164
- if (!tip || typeof tip.height !== "number" || typeof tip.mediantime !== "number" || !(tip.mediantime > 0)) {
1165
- throw new Error(`esplora returned no usable chain tip for ${esploraUrl}`);
1166
- }
1167
- return { height: tip.height, mtp: tip.mediantime };
1168
- };
1169
- var esploraChainSource = (input) => chainSourceOver(
1170
- {
1171
- provider: new EsploraProvider(input.esploraUrl),
1172
- tip: () => esploraTip(input.esploraUrl, input.fetchImpl)
1173
- },
1174
- input.network
1175
- );
1176
-
1177
- // src/client/corridors/deps.ts
1178
- var refusedIfNull = (value, corridor, dep) => {
1179
- if (value === null) throw new MissingCorridorDep(corridor, dep);
1180
- return value;
1181
- };
1182
- var emulatorPubkeyFor = (base) => {
1183
- if (base.emulatorPubkey !== void 0) {
1184
- return resolveEmulatorPubkey(base.network, base.emulatorPubkey);
1185
- }
1186
- try {
1187
- return defaultEmulatorPubkey(base.network);
1188
- } catch {
1189
- throw new MissingCorridorDep(
1190
- "arkade",
1191
- `covenant co-signer key (none is pinned for ${base.networkName}; pass emulatorPubkey)`
1192
- );
1193
- }
1194
- };
1195
- function resolveCorridorDeps(corridor, overrides, base) {
1196
- switch (corridor) {
1197
- case "arkade": {
1198
- const repository = refusedIfNull(overrides?.arkade?.repository, "arkade", "repository") ?? base.repository;
1199
- return {
1200
- wallet: base.wallet,
1201
- operator: base.operator,
1202
- networkName: base.networkName,
1203
- network: base.network,
1204
- signerSet: base.signerSet,
1205
- emulatorPubkey: emulatorPubkeyFor(base),
1206
- repository
1207
- };
1208
- }
1209
- case "lightning": {
1210
- return {
1211
- networkName: base.networkName,
1212
- decode: refusedIfNull(overrides?.lightning?.decode, "lightning", "bolt11 decoder") ?? decodeBolt11,
1213
- covclaimd: refusedIfNull(
1214
- overrides?.lightning?.covclaimd,
1215
- "lightning",
1216
- "covclaimd deployment key"
1217
- )
1218
- };
1219
- }
1220
- case "onchain": {
1221
- const chain = refusedIfNull(overrides?.onchain?.chain, "onchain", "chain source");
1222
- const claim = refusedIfNull(overrides?.onchain?.claim, "onchain", "L1 claim callback");
1223
- return {
1224
- networkName: base.networkName,
1225
- chain: esploraChainSource({
1226
- esploraUrl: chain?.esploraUrl ?? ESPLORA_URL[base.networkName],
1227
- network: L1_NETWORKS[l1NetworkFromArk(base.networkName)],
1228
- fetchImpl: base.fetchImpl
1229
- }),
1230
- ...claim === void 0 ? {} : { claim }
1231
- };
1232
- }
1233
- }
1234
- }
1235
- var liveArkadeInfo = async (wallet, opts = {}) => {
1236
- const requireLive = opts.requireLive ?? true;
1237
- try {
1238
- return await wallet.getArkadeInfo({ requireLive });
1239
- } catch (cause) {
1240
- throw new OperatorUnreachable(
1241
- `the Arkade server info could not be read${requireLive ? " live" : ""}: ${cause instanceof Error ? cause.message : String(cause)}`,
1242
- { cause }
1243
- );
1244
- }
1245
- };
1246
- var resolveCorridorBase = async (input) => {
1247
- const info = await liveArkadeInfo(input.wallet, { requireLive: input.requireLive });
1248
- const networkName = info.network;
1249
- return {
1250
- wallet: input.wallet,
1251
- operator: input.operator,
1252
- networkName,
1253
- network: getNetwork(networkName),
1254
- signerSet: signerSetFromInfo(info),
1255
- emulatorPubkey: input.emulatorPubkey,
1256
- fetchImpl: input.fetchImpl,
1257
- repository: input.repository
1258
- };
1259
- };
1260
-
1261
- // src/client/corridors/registry.ts
1262
- var CORRIDOR_FACTORIES = {
1263
- arkade: arkadeCorridor,
1264
- lightning: lightningCorridor,
1265
- onchain: onchainCorridor
1266
- };
1267
- var corridorSet = (base, overrides) => {
1268
- const built = /* @__PURE__ */ new Map();
1269
- const get = (corridor) => {
1270
- const memoized = built.get(corridor);
1271
- if (memoized) return memoized;
1272
- const factory = CORRIDOR_FACTORIES[corridor];
1273
- const module = factory(resolveCorridorDeps(corridor, overrides, base));
1274
- built.set(corridor, module);
1275
- return module;
1276
- };
1277
- return {
1278
- get,
1279
- claim(raw) {
1280
- const owners = CORRIDORS.filter(
1281
- (corridor) => CORRIDOR_FACTORIES[corridor].target(raw) !== void 0
1282
- );
1283
- if (owners.length === 0) {
1284
- if (isLnurl(raw)) return void 0;
1285
- throw new AmbiguousDestination(raw, "no corridor recognises this destination");
1286
- }
1287
- const claims = [];
1288
- const refusals = [];
1289
- for (const corridor of owners) {
1290
- const answer = get(corridor).matches(raw);
1291
- if (answer?.claimed) claims.push({ corridor, instrument: answer.claimed });
1292
- else if (answer?.refused) refusals.push(`${corridor}: ${answer.refused}`);
1293
- }
1294
- if (claims.length > 1) {
1295
- throw new AmbiguousDestination(
1296
- raw,
1297
- `it names ${claims.map((claim) => claim.corridor).join(" and ")}, with nothing to choose between them`
1298
- );
1299
- }
1300
- if (claims.length === 1) return claims[0];
1301
- if (refusals.length > 0) throw new AmbiguousDestination(raw, refusals.join("; "));
1302
- return void 0;
1303
- }
1304
- };
1305
- };
1306
-
1307
- // src/client/discovery.ts
1308
- import {
1309
- MAX_RELAYS,
1310
- discover,
1311
- isRfqMarket
1312
- } from "@arkade-os/solver-discovery";
1313
- var HEX_64 = /^[0-9a-f]{64}$/;
1314
- var isRelayList = (value) => Array.isArray(value) && value.length > 0 && value.length <= MAX_RELAYS && value.every((relay) => typeof relay === "string" && relay.startsWith("wss://"));
1315
- var isCorridorField = (value) => value === void 0 || CORRIDORS.includes(value);
1316
- var isUsableCard = (value) => {
1317
- const card = value;
1318
- if (typeof card?.pair !== "string" || typeof card.solver !== "string" || typeof card.source !== "string" || card.sourceType !== "registry" && card.sourceType !== "local" || typeof card.base_asset?.id !== "string" || typeof card.quote_asset?.id !== "string" || typeof card.base_asset.decimals !== "number" || typeof card.quote_asset.decimals !== "number" || !isCorridorField(card.base_corridor) || !isCorridorField(card.quote_corridor)) {
1319
- return false;
1320
- }
1321
- if (isRfqMarket(card)) {
1322
- if (typeof card.discovery_pubkey !== "string" || !HEX_64.test(card.discovery_pubkey)) {
1323
- return false;
1324
- }
1325
- if (!isRelayList(card.transports?.nostr?.relays)) return false;
1326
- }
1327
- return true;
1328
- };
1329
- var readCache = async (repository, network, registry) => {
1330
- try {
1331
- const entry = await repository.getCachedMarkets(network, registry);
1332
- if (!Array.isArray(entry?.markets) || typeof entry?.fetchedAt !== "number") return;
1333
- const markets = entry.markets.filter(isUsableCard);
1334
- return { markets, fetchedAt: entry.fetchedAt };
1335
- } catch {
1336
- return void 0;
1337
- }
1338
- };
1339
- var discoveryIndex = (input) => {
1340
- const config = input.config ?? {};
1341
- const network = config.network ?? input.network;
1342
- const registry = config.registryUrl;
1343
- const injected = config.snapshot && {
1344
- markets: config.snapshot,
1345
- ref: { fetchedAt: Date.now(), live: true, source: "injected" }
1346
- };
1347
- let held;
1348
- const unavailable = (detail) => {
1349
- throw new DiscoverySnapshotUnavailable(input.network, detail);
1350
- };
1351
- const sources = () => {
1352
- if (!isIndexedNetwork(network)) return {};
1353
- if (!registry) return {};
1354
- return { network, registry };
1355
- };
1356
- const whyUnavailable = () => {
1357
- if (!isIndexedNetwork(network)) return `no market index is published for ${network}`;
1358
- if (!registry) return "no registry URL is configured, and no snapshot was injected";
1359
- return `the registry ${registry} could not be reached and nothing is cached`;
1360
- };
1361
- const fromCache = async () => {
1362
- const { network: indexed, registry: url } = sources();
1363
- if (!indexed || !url || !input.repository) return void 0;
1364
- const cached = await readCache(input.repository, indexed, url);
1365
- if (!cached) return void 0;
1366
- return {
1367
- markets: cached.markets,
1368
- ref: {
1369
- fetchedAt: cached.fetchedAt,
1370
- // The cards were read back out of local storage, whatever their
1371
- // age: nothing here can attest that a registry ever served them.
1372
- live: false,
1373
- source: "cache",
1374
- registry: url
1375
- }
1376
- };
1377
- };
1378
- const peek = async () => {
1379
- if (injected) return injected;
1380
- if (held) return held;
1381
- const cached = await fromCache();
1382
- if (cached) {
1383
- held = cached;
1384
- return cached;
1385
- }
1386
- return unavailable(whyUnavailable());
1387
- };
1388
- const load = async (opts = {}) => {
1389
- if (injected) return injected;
1390
- const fresh = held?.ref.live === true && Date.now() - held.ref.fetchedAt < MARKETS_CACHE_TTL_MS;
1391
- if (fresh && !opts.refresh) return held;
1392
- const { network: indexed, registry: url } = sources();
1393
- if (!indexed || !url) {
1394
- return unavailable(whyUnavailable());
1395
- }
1396
- const result = await discover({
1397
- registries: [url],
1398
- localCards: [...config.localCards ?? []],
1399
- network: indexed,
1400
- fetchImpl: config.fetchImpl
1401
- });
1402
- if (result.warnings.length) config.logger?.("solver discovery:", ...result.warnings);
1403
- if (result.sources.some((source) => source.ok)) {
1404
- const fetchedAt = Date.now();
1405
- held = {
1406
- markets: result.markets,
1407
- ref: { fetchedAt, live: true, source: "live", registry: url }
1408
- };
1409
- if (input.repository) {
1410
- try {
1411
- await input.repository.saveCachedMarkets(indexed, url, {
1412
- markets: result.markets,
1413
- fetchedAt
1414
- });
1415
- } catch {
1416
- }
1417
- }
1418
- return held;
1419
- }
1420
- const cached = await fromCache();
1421
- if (cached) {
1422
- held = cached;
1423
- return cached;
1424
- }
1425
- return unavailable(whyUnavailable());
1426
- };
1427
- return { peek, load };
1428
- };
1429
-
1430
- // src/client/cancel.ts
1431
- import { base64, hex as hex3 } from "@scure/base";
1432
- import { ArkAddress as ArkAddress2, Transaction } from "@arkade-os/sdk";
1433
-
1434
- // src/client/driveRecords.ts
1435
- var splitRecords = (records) => {
1436
- const corridor = [];
1437
- const offer = [];
1438
- for (const record of records) {
1439
- if (record.family === "rfq") corridor.push(record);
1440
- else offer.push(record);
1441
- }
1442
- return { corridor, offer };
1443
- };
1444
- var rfqRecordOf = (record) => ({
1445
- kind: record.kind,
1446
- lockupAddress: record.lockupAddress,
1447
- profile: record.profile,
1448
- ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
1449
- rfqId: record.rfqId,
1450
- state: record.state,
1451
- createdAt: record.createdAt,
1452
- updatedAt: record.updatedAt,
1453
- ...record.refundTxid === void 0 ? {} : { refundTxid: record.refundTxid },
1454
- ...record.lockupSpendTxids?.length ? { lockupSpendTxids: [...record.lockupSpendTxids] } : {},
1455
- ...record.failure === void 0 ? {} : { failure: record.failure },
1456
- ...record.claimFailure === void 0 ? {} : { claimFailure: record.claimFailure },
1457
- ...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason }
1458
- });
1459
- var withRfqState = (record, state) => {
1460
- const {
1461
- refundTxid: _refundTxid,
1462
- lockupSpendTxids: _lockupSpendTxids,
1463
- failure: _failure,
1464
- claimFailure: _claimFailure,
1465
- blockedReason: _blockedReason,
1466
- ...origin
1467
- } = record;
1468
- return {
1469
- ...origin,
1470
- state: state.state,
1471
- profile: state.profile,
1472
- updatedAt: state.updatedAt,
1473
- ...state.refundTxid === void 0 ? {} : { refundTxid: state.refundTxid },
1474
- ...state.lockupSpendTxids?.length ? { lockupSpendTxids: [...state.lockupSpendTxids] } : {},
1475
- ...state.failure === void 0 ? {} : { failure: state.failure },
1476
- ...state.claimFailure === void 0 ? {} : { claimFailure: state.claimFailure },
1477
- ...state.blockedReason === void 0 ? {} : { blockedReason: state.blockedReason }
1478
- };
1479
- };
1480
- var corridorRecordStore = (repository, onRecord = () => {
1481
- }, admits = () => true) => {
1482
- const byRfqId = /* @__PURE__ */ new Map();
1483
- const index = (record) => {
1484
- byRfqId.set(record.rfqId, record.id);
1485
- };
1486
- const recordFor = async (rfqId) => {
1487
- const known = byRfqId.get(rfqId);
1488
- if (known !== void 0) {
1489
- const record = await repository.getSwapRecord(known);
1490
- if (record?.family === "rfq") return record;
1491
- }
1492
- const { corridor } = splitRecords(await repository.getAllSwapRecords());
1493
- for (const record of corridor) index(record);
1494
- const found = byRfqId.get(rfqId);
1495
- return found === void 0 ? void 0 : corridor.find((r) => r.id === found);
1496
- };
1497
- return {
1498
- index,
1499
- quoteIdOf: (rfqId) => byRfqId.get(rfqId),
1500
- async getAllRfqSwaps() {
1501
- const { corridor } = splitRecords(await repository.getAllSwapRecords());
1502
- for (const record of corridor) index(record);
1503
- return corridor.filter(admits).map(rfqRecordOf);
1504
- },
1505
- async getRfqSwap(rfqId) {
1506
- const record = await recordFor(rfqId);
1507
- return record === void 0 ? void 0 : rfqRecordOf(record);
1508
- },
1509
- async saveRfqSwap(state) {
1510
- const record = await recordFor(state.rfqId);
1511
- if (record === void 0) {
1512
- throw new Error(
1513
- `no v2 swap record for rfq ${state.rfqId}; the drive cannot write its state`
1514
- );
1515
- }
1516
- const updated = withRfqState(record, state);
1517
- await repository.saveSwapRecord(updated);
1518
- onRecord(updated);
1519
- },
1520
- async removeRfqSwap() {
1521
- }
1522
- };
1523
- };
1524
- var offerFactsOf = (record) => ({
1525
- id: record.id,
1526
- status: record.status,
1527
- offerHex: record.offerHex,
1528
- swapPkScript: record.swapPkScript,
1529
- ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
1530
- ...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
1531
- // Milliseconds: `coverage.ts` marks issuance with `Date.now()`, and a
1532
- // seconds value compared against it leaves every issued script outstanding
1533
- // for the life of the process.
1534
- createdAt: record.createdAt * 1e3
1535
- });
1536
- var offerRecordSource = (repository, onRecord = () => {
1537
- }, now = () => Math.floor(Date.now() / 1e3)) => {
1538
- const list = async () => {
1539
- const { offer } = splitRecords(await repository.getAllSwapRecords());
1540
- return offer.map(offerFactsOf);
1541
- };
1542
- return {
1543
- list,
1544
- async apply(swap, changes) {
1545
- const stored = await repository.getSwapRecord(swap.id);
1546
- if (stored === void 0 || stored.family !== "offer") {
1547
- return { persisted: false, swaps: await list() };
1548
- }
1549
- const updated = applyOfferSpend(stored, changes, now());
1550
- try {
1551
- await repository.saveSwapRecord(updated);
1552
- onRecord(updated);
1553
- const swaps = (await list()).map(
1554
- (s) => s.id === updated.id ? offerFactsOf(updated) : s
1555
- );
1556
- return { persisted: true, swaps };
1557
- } catch (error) {
1558
- console.warn(`[swap] failed to persist offer spend for ${swap.id}`, error);
1559
- return { persisted: false, swaps: await list() };
1560
- }
1561
- }
1562
- };
1563
- };
1564
- var applyOfferSpend = (record, changes, now) => ({
1565
- ...record,
1566
- status: changes.status,
1567
- spentTxid: changes.spentTxid,
1568
- // The watcher's `completedAt` comes off a contract event's timestamp, in
1569
- // milliseconds; this record's timestamps are unix seconds.
1570
- ...changes.completedAt === void 0 ? {} : { completedAt: Math.floor(changes.completedAt / 1e3) },
1571
- updatedAt: now
1572
- });
1573
- var withOfferStatus = (record, status, now) => ({ ...record, status, updatedAt: now });
1574
- var walletLockupIndexer = (wallet) => {
1575
- let reader;
1576
- const reading = () => reader ??= wallet.getArkadeReader();
1577
- return {
1578
- getVtxos: async (opts) => {
1579
- if (!opts) {
1580
- throw new Error("getVtxos on the swap indexer requires scripts or outpoints");
1581
- }
1582
- return (await reading()).getVtxos(opts);
1583
- },
1584
- getVirtualTxs: async (...args) => (await reading()).getVirtualTxs(...args)
1585
- };
1586
- };
1587
-
1588
- // src/client/cancel.ts
1589
- var OFFER_TERMINAL = (record) => record.status === "cancelled" || record.status === "fulfilled";
1590
- var cancelSwap = async (input) => {
1591
- const { wallet, repository, record, drive, indexer } = input;
1592
- const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
1593
- if (OFFER_TERMINAL(record)) {
1594
- return { outcome: record.status === "cancelled" ? "cancelled" : "filled" };
1595
- }
1596
- if (offerOutcome(record.status) === "needs_recovery") {
1597
- return { outcome: "needs_recovery" };
1598
- }
1599
- const gated2 = withStatus(record, "cancelling", now());
1600
- await repository.saveSwapRecord(gated2);
1601
- drive.ingest(gated2);
1602
- let prepared;
1603
- try {
1604
- prepared = await prepareOfferCancel(wallet, record.offerHex, {
1605
- swapAddress: record.swapAddress,
1606
- ...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid }
1607
- });
1608
- } catch (error) {
1609
- if (error instanceof OfferCovenantMismatchError) {
1610
- const rolledBack = withStatus(record, record.status, now());
1611
- try {
1612
- await repository.saveSwapRecord(rolledBack);
1613
- } catch (rollbackError) {
1614
- console.warn(
1615
- `[swap] could not roll back cancel gate for ${record.id}`,
1616
- rollbackError
1617
- );
1618
- }
1619
- drive.ingest(rolledBack);
1620
- throw error;
1621
- }
1622
- if (isMissingVtxo(error)) {
1623
- const reconciled = await reconcileDepositSpend(record, indexer);
1624
- if (reconciled === void 0) {
1625
- return { outcome: "needs_recovery" };
1626
- }
1627
- const { kind, spentTxid } = reconciled;
1628
- const settled2 = withStatus(gated2, kind, now(), {
1629
- spentTxid,
1630
- // Mirrors the watcher: a completion time is a fill's, not a
1631
- // cancel's.
1632
- ...kind === "fulfilled" ? { completedAt: now() } : {}
1633
- });
1634
- const { persisted: persisted2 } = await persistBestEffort(repository, settled2);
1635
- drive.ingest(settled2);
1636
- if (persisted2) await retireOfferScripts(wallet, repository, settled2);
1637
- return { outcome: kind === "cancelled" ? "cancelled" : "filled" };
1638
- }
1639
- throw error;
1640
- }
1641
- const txid = await prepared.send();
1642
- const settled = withStatus(gated2, "cancelled", now(), { spentTxid: txid });
1643
- const { persisted } = await persistBestEffort(repository, settled);
1644
- drive.ingest(settled);
1645
- if (persisted) {
1646
- await retireOfferScripts(wallet, repository, settled);
1647
- }
1648
- return { outcome: "cancelled" };
1649
- };
1650
- var reconcileDepositSpend = async (record, indexer) => {
1651
- const offer = decodeOffer(hex3.decode(record.offerHex));
1652
- const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
1653
- const all = vtxos ?? [];
1654
- const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
1655
- if (deposit === void 0) return void 0;
1656
- const candidates = spendTxidsOf(deposit);
1657
- if (candidates.length === 0) return void 0;
1658
- const spentTxid = deposit.arkTxId || deposit.spentBy;
1659
- if (!spentTxid) return void 0;
1660
- const { txs } = await indexer.getVirtualTxs(candidates);
1661
- const parsed = txs.map((psbt) => {
1662
- try {
1663
- return Transaction.fromPSBT(base64.decode(psbt));
1664
- } catch {
1665
- return void 0;
1666
- }
1667
- }).filter((tx) => tx !== void 0);
1668
- const operatorPubkey = ArkAddress2.decode(record.swapAddress).serverPubKey;
1669
- const kind = classifyDepositSpend(offer, operatorPubkey, parsed, {
1670
- txid: deposit.txid,
1671
- vout: deposit.vout
1672
- });
1673
- if (kind === "indeterminate") return void 0;
1674
- return { kind, spentTxid };
1675
- };
1676
- var withStatus = (record, status, now, extra = {}) => ({
1677
- ...record,
1678
- status,
1679
- ...extra.spentTxid === void 0 ? {} : { spentTxid: extra.spentTxid },
1680
- ...extra.completedAt === void 0 ? {} : { completedAt: extra.completedAt },
1681
- updatedAt: now
1682
- });
1683
- var persistBestEffort = async (repository, record) => {
1684
- try {
1685
- await repository.saveSwapRecord(record);
1686
- return { persisted: true };
1687
- } catch (error) {
1688
- console.warn(`[swap] could not persist cancel for ${record.id}`, error);
1689
- return { persisted: false };
1690
- }
1691
- };
1692
- var retireOfferScripts = async (wallet, repository, record) => {
1693
- try {
1694
- const { offer } = splitRecords(await repository.getAllSwapRecords());
1695
- await retireOfferContract(
1696
- await wallet.getContractManager(),
1697
- offer.map(offerFactsOf),
1698
- record.swapPkScript
1699
- );
1700
- } catch (error) {
1701
- console.warn(`[swap] could not retire offer script for ${record.id}`, error);
1702
- }
1703
- };
1704
- var isMissingVtxo = (error) => error instanceof NoSpendableDepositError;
1705
-
1706
- // src/client/drive.ts
1707
- import { ArkAddress as ArkAddress3, contractSigner } from "@arkade-os/sdk";
1708
- import { hex as hex4 } from "@scure/base";
1709
- var SwapDriveRefusedError = class extends Error {
1710
- constructor(reason, detail, swapId) {
1711
- super(detail);
1712
- this.reason = reason;
1713
- this.swapId = swapId;
1714
- }
1715
- reason;
1716
- swapId;
1717
- name = "SwapDriveRefusedError";
1718
- };
1719
- var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
1720
- var traderClaimTxid = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
1721
- var readableRecord = (record) => {
1722
- if (typeof record?.id !== "string" || record.route?.give === void 0) return false;
1723
- if (record.family === "rfq") {
1724
- return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
1725
- }
1726
- return record.family === "offer" && typeof record.offerHex === "string";
1727
- };
1728
- var createSwapDrive = (config) => {
1729
- const { wallet, operator, repository, corridors, indexer } = config;
1730
- const mode = config.mode ?? "auto";
1731
- const now = config.now ?? (() => Math.floor(Date.now() / 1e3));
1732
- const records = /* @__PURE__ */ new Map();
1733
- const live = /* @__PURE__ */ new Map();
1734
- const refunding = /* @__PURE__ */ new Set();
1735
- const swept = /* @__PURE__ */ new Map();
1736
- const passed = /* @__PURE__ */ new Set();
1737
- const delivered = /* @__PURE__ */ new Map();
1738
- const listeners = /* @__PURE__ */ new Set();
1739
- let disposed = false;
1740
- let startRequested = mode === "auto";
1741
- let watcher;
1742
- let readyPromise;
1743
- const inFlight = /* @__PURE__ */ new Set();
1744
- let queue = Promise.resolve();
1745
- const track = (work) => {
1746
- inFlight.add(work);
1747
- void work.then(
1748
- () => inFlight.delete(work),
1749
- () => inFlight.delete(work)
1750
- );
1751
- return work;
1752
- };
1753
- const enqueue = (task) => {
1754
- queue = queue.then(task).catch((error) => {
1755
- console.warn("[swap] the drive could not register a swap", error);
1756
- });
1757
- };
1758
- const idle = async () => {
1759
- do {
1760
- await queue;
1761
- await Promise.allSettled([...inFlight]);
1762
- await watcher?.idle();
1763
- } while (inFlight.size > 0);
1764
- };
1765
- const remember = (record) => {
1766
- records.set(record.id, record);
1767
- emit(record.id);
1768
- };
1769
- const storage = () => {
1770
- if (!repository) throw new Error("the drive has no repository");
1771
- return repository;
1772
- };
1773
- const undrivable = /* @__PURE__ */ new Set();
1774
- let bridge;
1775
- const corridorStore = () => bridge ??= corridorRecordStore(
1776
- storage(),
1777
- remember,
1778
- // Terminal records are readable but never driven: excluding them
1779
- // here is what keeps `restoreFromRepository` from rebuilding each
1780
- // one — a covenant derivation and a contract row lookup per
1781
- // record — only to file it in the manager's `finished` set. The
1782
- // exclusion is on the manager's read, not the record: the drive's
1783
- // own `records` registry keeps every readable record, and the
1784
- // index still learns an excluded record's `rfqId` (see
1785
- // `getAllRfqSwaps`), so a consumer handing its swap to the manager
1786
- // directly keeps resolving.
1787
- (r) => !undrivable.has(r.id) && !isRfqSwapTerminal(r.state)
1788
- );
1789
- const effectiveState = (swap) => {
1790
- if (mode === "auto") return swap.state;
1791
- if (swap.state !== "needs_counterparty") return swap.state;
1792
- if (!isRfqConfigurationRefusal(swap.blockedReason)) return swap.state;
1793
- return traderClaimTxid(swap) ? "claimed" : "pending";
1794
- };
1795
- const outcomeOfEntry = (record, current) => {
1796
- if (record.family === "offer") return recordOutcome(record);
1797
- if (current === void 0) {
1798
- if (isRfqSwapTerminal(record.state)) return corridorOutcome(record.kind, record.state);
1799
- return recordOutcome(record);
1800
- }
1801
- const state = effectiveState(current);
1802
- if (state === "pending" && !passed.has(record.id)) return recordOutcome(record);
1803
- if (isRfqSwapTerminal(state)) return corridorOutcome(current.kind, state);
1804
- if (LOCKUP_OWNER[current.kind] === "trader" && refunding.has(record.id) && now() >= current.refundLocktime) {
1805
- return "refunding";
1806
- }
1807
- if (swept.has(record.id)) return "needs_recovery";
1808
- return corridorOutcome(current.kind, state);
1809
- };
1810
- const detailOf = (record, current) => record.family === "offer" ? { family: "offer", status: record.status } : { family: "rfq", state: current?.state ?? record.state };
1811
- const publicSwap = (record, outcome, current) => {
1812
- const base = swapOf(record, outcome);
1813
- if (current === void 0) return base;
1814
- const { failure: _failure, blockedReason: _blockedReason, ...rest } = base;
1815
- return {
1816
- ...rest,
1817
- ...current.failure === void 0 ? {} : { failure: current.failure },
1818
- ...current.blockedReason === void 0 ? {} : { blockedReason: current.blockedReason }
1819
- };
1820
- };
1821
- const updateFor = (id) => {
1822
- const record = records.get(id);
1823
- if (record === void 0) return void 0;
1824
- const current = live.get(id);
1825
- const outcome = outcomeOfEntry(record, current);
1826
- return {
1827
- swap: publicSwap(record, outcome, current),
1828
- outcome,
1829
- detail: detailOf(record, current)
1830
- };
1831
- };
1832
- const deliver = (update, to) => {
1833
- for (const listener of to) {
1834
- try {
1835
- listener(update);
1836
- } catch {
1837
- }
1838
- }
1839
- };
1840
- function emit(id) {
1841
- const update = updateFor(id);
1842
- if (update === void 0) return;
1843
- if (delivered.get(id) === update.outcome) return;
1844
- delivered.set(id, update.outcome);
1845
- deliver(update, listeners);
1846
- }
1847
- const emitAll = () => {
1848
- for (const id of records.keys()) emit(id);
1849
- };
1850
- const touch = (rfqId, swap) => {
1851
- const id = bridge?.quoteIdOf(rfqId);
1852
- if (id === void 0) return;
1853
- live.set(id, swap);
1854
- passed.add(id);
1855
- emit(id);
1856
- };
1857
- const managerDeps = { indexer };
1858
- if (config.contracts) managerDeps.contracts = config.contracts;
1859
- const manager = new RfqSwapManager(managerDeps, {
1860
- ...config.pollIntervalMs === void 0 ? {} : { pollIntervalMs: config.pollIntervalMs },
1861
- now
1862
- });
1863
- manager.onSwapUpdate((swap) => touch(swap.rfqId, swap));
1864
- manager.onSwapCompleted((swap) => touch(swap.rfqId, swap));
1865
- manager.onSwapFailed((swap, error) => {
1866
- const id = bridge?.quoteIdOf(swap.rfqId);
1867
- if (id !== void 0 && error instanceof LockupNeedsRecoveryError) {
1868
- swept.set(id, error.outpoints);
1869
- }
1870
- touch(swap.rfqId, swap);
1871
- });
1872
- let onchainSeams;
1873
- const resolveOnchain = async () => {
1874
- if (onchainSeams !== void 0) return onchainSeams !== null;
1875
- try {
1876
- const deps = (await corridors()).get("onchain").deps;
1877
- onchainSeams = { chain: deps.chain, ...deps.claim ? { claim: deps.claim } : {} };
1878
- managerDeps.chain = deps.chain;
1879
- return true;
1880
- } catch (error) {
1881
- console.warn(
1882
- "[swap] the onchain corridor has no chain source, so its swaps cannot be driven",
1883
- error
1884
- );
1885
- onchainSeams = null;
1886
- return false;
1887
- }
1888
- };
1889
- const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
1890
- const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
1891
- const record = await corridorStore().getRfqSwap(swap.rfqId);
1892
- if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
1893
- const secret = rfqClaimSecretOf(record);
1894
- if (!secret) throw new Error(`rfq swap ${swap.rfqId} carries no claim secret`);
1895
- const script = swap.lockup?.script;
1896
- if (!script) throw new Error(`rfq swap ${swap.rfqId} carries no lockup covenant`);
1897
- const payoutAddress = rfqClaimDestinationOf(record);
1898
- if (!payoutAddress) {
1899
- throw new Error(`rfq swap ${swap.rfqId} carries no claim destination`);
1900
- }
1901
- return track(
1902
- pushClaim(operator, {
1903
- contract: script,
1904
- receiver: await contractSigner(wallet, secret.signingDescriptor),
1905
- preimage: await preimageForSwapRecord(wallet, secret),
1906
- vtxos,
1907
- destinationPkScript: ArkAddress3.decode(payoutAddress).pkScript,
1908
- // Passed straight through, both of them: the manager's own value
1909
- // check decides WHEN to act, `pushClaim`'s decides whether `P` is
1910
- // published, and it is the one with nothing between it and the
1911
- // signature.
1912
- expectedAmount: swap.expectedAmount,
1913
- partiallyClaimed
1914
- })
1915
- );
1916
- };
1917
- const canRefundArkade = async (swap) => {
1918
- const record = await corridorStore().getRfqSwap(swap.rfqId);
1919
- if (!record) {
1920
- return {
1921
- ok: false,
1922
- reason: `no stored record for ${swap.rfqId}; the descriptor that signs its refund lives there`
1923
- };
1924
- }
1925
- const signer = rfqSignerOf(record);
1926
- try {
1927
- await senderIdentityForSwapRecord(wallet, signer ?? {});
1928
- return { ok: true };
1929
- } catch (error) {
1930
- if (error instanceof RefundNotLocallyPossibleError) {
1931
- return { ok: false, reason: error.message };
1932
- }
1933
- throw error;
1934
- }
1935
- };
1936
- const wireCallbacks = () => {
1937
- if (mode === "readonly") return;
1938
- const push = arkadeRefunder({
1939
- operator,
1940
- indexer,
1941
- wallet,
1942
- repository: corridorStore()
1943
- });
1944
- manager.setCallbacks({
1945
- refundArkade: async (swap) => {
1946
- const id = bridge?.quoteIdOf(swap.rfqId);
1947
- if (id !== void 0) {
1948
- swept.delete(id);
1949
- refunding.add(id);
1950
- passed.add(id);
1951
- emit(id);
1952
- }
1953
- try {
1954
- return await track(push(swap));
1955
- } finally {
1956
- if (id !== void 0) refunding.delete(id);
1957
- }
1958
- },
1959
- canRefundArkade,
1960
- claimLockup,
1961
- ...onchainSeams?.claim ? { claimOnchain: onchainSeams.claim } : {}
1962
- });
1963
- };
1964
- let offerSource;
1965
- const offers = () => offerSource ??= offerRecordSource(storage(), remember, now);
1966
- const sweepOfferDeposits = async (offer) => {
1967
- const funded = offer.filter(
1968
- (record) => record.fundingTxid !== void 0 && !RETIRABLE.includes(record.status)
1969
- );
1970
- if (funded.length === 0) return;
1971
- const store = storage();
1972
- const [history, scanned, address] = await Promise.all([
1973
- wallet.getTransactionHistory(),
1974
- store.getScannedTxids(),
1975
- wallet.getAddress()
1976
- ]);
1977
- const txs = history.map((tx) => ({
1978
- // `TxType` is `"SENT"`/`"RECEIVED"`; the scan filters on `"sent"`.
1979
- type: String(tx.type).toLowerCase(),
1980
- redeemTxid: tx.key.arkTxid,
1981
- ...tx.key.boardingTxid ? { boardingTxid: tx.key.boardingTxid } : {},
1982
- ...tx.key.commitmentTxid ? { roundTxid: tx.key.commitmentTxid } : {},
1983
- // The scan reads unix SECONDS; a wallet transaction carries ms.
1984
- ...tx.createdAt ? { createdAt: Math.floor(tx.createdAt / 1e3) } : {}
1985
- }));
1986
- const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
1987
- operatorPubkey: ArkAddress3.decode(address).serverPubKey,
1988
- scanned
1989
- });
1990
- const byDeposit = new Map(restored.map((s) => [`${s.swapPkScript}:${s.fundingTxid}`, s]));
1991
- const stillLive = /* @__PURE__ */ new Set();
1992
- for (const record of funded) {
1993
- const found = byDeposit.get(`${record.swapPkScript}:${record.fundingTxid}`);
1994
- const status = found?.status ?? record.status;
1995
- if (status !== record.status) {
1996
- const updated = withOfferStatus(record, status, now());
1997
- await store.saveSwapRecord(updated);
1998
- remember(updated);
1999
- }
2000
- if (OFFER_LIVE(status) && record.fundingTxid) stillLive.add(record.fundingTxid);
2001
- }
2002
- await store.markTxidsScanned(scannedTxids.filter((txid) => !stillLive.has(txid)));
2003
- const registry = managerDeps.contracts;
2004
- if (registry) {
2005
- const { offer: current } = splitRecords(await store.getAllSwapRecords());
2006
- await retireSettledOfferContracts(registry, current.map(offerFactsOf));
2007
- }
2008
- };
2009
- const contractsOf = async () => managerDeps.contracts ??= await wallet.getContractManager();
2010
- const registerCorridorSwap = async (record) => {
2011
- if (mode === "readonly") return;
2012
- if (!await drivable(record)) {
2013
- undrivable.add(record.id);
2014
- return;
2015
- }
2016
- const contracts = await contractsOf();
2017
- const stored = rfqRecordOf(record);
2018
- const params = await lockupContractParams(contracts, record.lockupAddress);
2019
- const swap = rebuildRfqSwap(stored, params);
2020
- live.set(record.id, swap);
2021
- await manager.addSwap(swap, rfqSwapOriginOf(stored));
2022
- await markPassed();
2023
- emit(record.id);
2024
- await arm();
2025
- emit(record.id);
2026
- };
2027
- const hasLiveWork = async (offer) => (await manager.getPendingSwaps()).length > 0 || offer.some((r) => OFFER_LIVE(r.status));
2028
- const markPassed = async () => {
2029
- if (!(await manager.getStats()).isRunning) return;
2030
- for (const swap of await manager.getAllSwaps()) {
2031
- const id = bridge?.quoteIdOf(swap.rfqId);
2032
- if (id !== void 0) passed.add(id);
2033
- }
2034
- };
2035
- const arm = async () => {
2036
- if (mode === "readonly" || !startRequested) return;
2037
- if (!repository) return;
2038
- await contractsOf();
2039
- wireCallbacks();
2040
- await manager.start();
2041
- await markPassed();
2042
- if (!watcher && repository) {
2043
- watcher = await watchOfferSwaps({
2044
- wallet,
2045
- source: offers(),
2046
- onUpdate: (swap) => emit(swap.id)
2047
- });
2048
- }
2049
- };
2050
- const restore = async () => {
2051
- if (!repository) return;
2052
- const all = await repository.getAllSwapRecords();
2053
- const { corridor, offer } = splitRecords(all.filter(readableRecord));
2054
- for (const record of [...corridor, ...offer]) records.set(record.id, record);
2055
- const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
2056
- const store = corridorStore();
2057
- for (const record of liveCorridor) store.index(record);
2058
- if (liveCorridor.length > 0) {
2059
- await contractsOf();
2060
- for (const record of liveCorridor) {
2061
- if (!await drivable(record)) undrivable.add(record.id);
2062
- }
2063
- managerDeps.repository = store;
2064
- const result = await manager.restoreFromRepository();
2065
- for (const swap of result.restored) {
2066
- const id = store.quoteIdOf(swap.rfqId);
2067
- if (id !== void 0) live.set(id, swap);
2068
- }
2069
- for (const failure of result.failed) {
2070
- console.warn(`[swap] could not restore rfq swap ${failure.rfqId}`, failure.error);
2071
- }
2072
- }
2073
- try {
2074
- await sweepOfferDeposits(offer);
2075
- } catch (error) {
2076
- console.warn("[swap] the offer deposit sweep did not complete", error);
2077
- }
2078
- emitAll();
2079
- if (mode === "auto" && await hasLiveWork(offer)) {
2080
- try {
2081
- await arm();
2082
- } catch (error) {
2083
- console.warn("[swap] the drive could not arm after its restore", error);
2084
- }
2085
- }
2086
- emitAll();
2087
- };
2088
- const ready = () => readyPromise ??= restore();
2089
- const stop = async () => {
2090
- await queue;
2091
- await manager.stop();
2092
- watcher?.stop();
2093
- await watcher?.idle();
2094
- watcher = void 0;
2095
- if (mode === "manual") startRequested = false;
2096
- };
2097
- const recoverer = async () => {
2098
- const probe = wallet.getVtxoManager;
2099
- if (typeof probe !== "function") {
2100
- throw new SwapDriveRefusedError(
2101
- "no-recovery-support",
2102
- "this wallet exposes no VTXO manager, so no recovery round can be run"
2103
- );
2104
- }
2105
- return probe.call(wallet);
2106
- };
2107
- const recoverableAt = async (script) => (await findLockupVtxos(indexer, script)).filter((vtxo) => vtxo.recoverable);
2108
- const recover = async (id) => {
2109
- if (disposed) throw new ClientDisposed("recover");
2110
- if (mode === "readonly") {
2111
- throw new SwapDriveRefusedError(
2112
- "readonly",
2113
- 'this client is configured drive: "readonly" and actuates nothing',
2114
- id
2115
- );
2116
- }
2117
- await ready();
2118
- const record = records.get(id) ?? await repository?.getSwapRecord(id);
2119
- if (record === void 0) {
2120
- throw new SwapDriveRefusedError("unknown-swap", `no swap record for ${id}`, id);
2121
- }
2122
- records.set(record.id, record);
2123
- if (record.family === "rfq") {
2124
- if (now() < record.refundLocktime) {
2125
- throw new SwapDriveRefusedError(
2126
- "refund-window-open",
2127
- `swap ${id}'s lockup cannot be recovered before its refund locktime ${record.refundLocktime}`,
2128
- id
2129
- );
2130
- }
2131
- const script = hex4.decode(record.lockupPkScript);
2132
- const before = await recoverableAt(script);
2133
- if (before.length === 0) {
2134
- throw new SwapDriveRefusedError(
2135
- "nothing-swept",
2136
- `swap ${id} has no swept outputs to recover`,
2137
- id
2138
- );
2139
- }
2140
- const txid2 = await track((await recoverer()).recoverVtxos());
2141
- const after2 = await recoverableAt(script);
2142
- const still = new Set(after2.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`));
2143
- const recovered2 = before.every((vtxo) => !still.has(`${vtxo.txid}:${vtxo.vout}`));
2144
- if (recovered2) swept.delete(id);
2145
- await manager.poll();
2146
- await markPassed();
2147
- return { recovered: recovered2, txid: txid2, swap: swapView(id) };
2148
- }
2149
- if (record.status !== "recoverable") {
2150
- throw new SwapDriveRefusedError(
2151
- "nothing-swept",
2152
- `offer swap ${id} is ${record.status}, so it has nothing swept to recover`,
2153
- id
2154
- );
2155
- }
2156
- const txid = await track((await recoverer()).recoverVtxos());
2157
- await sweepOfferDeposits([records.get(id)]);
2158
- const after = records.get(id);
2159
- const recovered = after?.family === "offer" && after.status !== "recoverable";
2160
- return { recovered, txid, swap: swapView(id) };
2161
- };
2162
- const swapView = (id) => {
2163
- const update = updateFor(id);
2164
- if (update === void 0) throw new Error(`the drive holds no swap ${id}`);
2165
- return update.swap;
2166
- };
2167
- return {
2168
- get ready() {
2169
- return ready();
2170
- },
2171
- start: async () => {
2172
- if (disposed) throw new ClientDisposed("start");
2173
- if (mode === "readonly") {
2174
- throw new SwapDriveRefusedError(
2175
- "readonly",
2176
- 'this client is configured drive: "readonly" and will not start a drive loop'
2177
- );
2178
- }
2179
- startRequested = true;
2180
- await ready();
2181
- await arm();
2182
- },
2183
- stop: async () => {
2184
- await readyPromise?.catch(() => {
2185
- });
2186
- await stop();
2187
- },
2188
- dispose: async () => {
2189
- if (disposed) return;
2190
- disposed = true;
2191
- await stop();
2192
- await idle();
2193
- listeners.clear();
2194
- },
2195
- onUpdate: (fn) => {
2196
- if (disposed) throw new ClientDisposed("onUpdate");
2197
- listeners.add(fn);
2198
- for (const id of records.keys()) {
2199
- const update = updateFor(id);
2200
- if (update === void 0) continue;
2201
- delivered.set(id, update.outcome);
2202
- deliver(update, [fn]);
2203
- }
2204
- void ready().catch(() => {
2205
- });
2206
- return () => {
2207
- listeners.delete(fn);
2208
- };
2209
- },
2210
- adopt: (record) => {
2211
- if (disposed) throw new ClientDisposed("accept");
2212
- records.set(record.id, record);
2213
- if (record.family === "rfq") {
2214
- corridorStore().index(record);
2215
- managerDeps.repository = corridorStore();
2216
- enqueue(() => registerCorridorSwap(record));
2217
- } else {
2218
- enqueue(() => arm());
2219
- }
2220
- emit(record.id);
2221
- return swapView(record.id);
2222
- },
2223
- swap: (id) => updateFor(id)?.swap,
2224
- outcomeOf: (record) => outcomeOfEntry(record, live.get(record.id)),
2225
- ingest: (record) => remember(record),
2226
- recover,
2227
- idle
2228
- };
2229
- };
2230
-
2231
- // src/client/quoteOffer.ts
21
+ PAYMENT_STATUS,
22
+ QuoteExpired,
23
+ QuoteVerificationFailed,
24
+ RAILS,
25
+ REGISTRY_URL,
26
+ SWAP_ERROR_NAMES,
27
+ SwapDriveRefusedError,
28
+ SwapPaymentFailedError,
29
+ UnsupportedRoute,
30
+ arkadeAsset,
31
+ assetPartOf,
32
+ assetSwapIdOf,
33
+ bitcoinNetworkOf,
34
+ btcAssetPart,
35
+ btcOn,
36
+ canonicalAssetId,
37
+ claimFeeSats,
38
+ createSwapClient,
39
+ exchange,
40
+ familyOfSwapId,
41
+ formatAssetId,
42
+ fromAtomicDecimal,
43
+ isAssetId,
44
+ isAtomicDecimal,
45
+ isBtcAsset,
46
+ isBtcAssetLenient,
47
+ isNetworkRef,
48
+ isSwapError,
49
+ isTerminalStatus,
50
+ issuanceOf,
51
+ onchainSwapRail,
52
+ parseAssetId,
53
+ pay,
54
+ paymentStatusOf,
55
+ quoteIdOfSwapId,
56
+ quoteMeta,
57
+ railAvailable,
58
+ railOf,
59
+ receive,
60
+ receiverExact,
61
+ sameAsset,
62
+ swapHandle,
63
+ toAtomicDecimal
64
+ } from "./chunk-HUQQVBC4.js";
2232
65
  import {
2233
- computeWantAmount,
2234
- quoteOffer
2235
- } from "@arkade-os/solver-discovery";
2236
-
2237
- // src/client/market.ts
66
+ isRfqSwapTerminal
67
+ } from "./chunk-ITFCQWPG.js";
2238
68
  import {
2239
- isRfqMarket as isRfqMarket2,
2240
- marketCorridor as marketCorridor2,
2241
- marketLegKey,
2242
- selectMarkets
2243
- } from "@arkade-os/solver-discovery";
2244
- var marketKeyOf = (card) => {
2245
- const base = marketLegKey(card, "base");
2246
- const quote = marketLegKey(card, "quote");
2247
- const baseIsArkade = marketCorridor2(card, "base") === "arkade";
2248
- const quoteIsArkade = marketCorridor2(card, "quote") === "arkade";
2249
- if (baseIsArkade !== quoteIsArkade) {
2250
- return baseIsArkade ? `${base}/${quote}` : `${quote}/${base}`;
2251
- }
2252
- return base <= quote ? `${base}/${quote}` : `${quote}/${base}`;
2253
- };
2254
- var isAddressable = (card) => !isRfqMarket2(card) || typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
2255
- var marketBackendOf = (card) => isRfqMarket2(card) ? "rfq" : "feed";
2256
- var usableMarkets = (snapshot, policy) => {
2257
- const allowed = policy?.allowedRegistries;
2258
- return (allowed ? snapshot.markets.filter((card) => allowed.includes(card.source)) : snapshot.markets).filter(isAddressable);
2259
- };
2260
- var eligibleMarkets = (snapshot, legs, policy) => {
2261
- const markets = usableMarkets(snapshot, policy);
2262
- const { give, take } = legs;
2263
- if (give.corridor === take.corridor && give.assetId === take.assetId) return [];
2264
- const oriented = (side) => {
2265
- const base = side === "base" ? give : take;
2266
- const quote = side === "base" ? take : give;
2267
- return selectMarkets([...markets], {
2268
- baseId: base.assetId,
2269
- quoteId: quote.assetId,
2270
- baseCorridor: base.corridor,
2271
- quoteCorridor: quote.corridor,
2272
- // The trader receives the take leg, so that side must be one the
2273
- // solver can pay out; a direction nobody solves yields no market.
2274
- wantSide: side === "base" ? "quote" : "base"
2275
- }).map((card) => ({
2276
- card,
2277
- give: side,
2278
- backend: marketBackendOf(card),
2279
- key: marketKeyOf(card)
2280
- }));
2281
- };
2282
- return [...oriented("base"), ...oriented("quote")];
2283
- };
2284
- var chooseMarket = (candidates, policy) => {
2285
- if (candidates.length === 0) return void 0;
2286
- if (!policy?.selectMarket) return candidates[0];
2287
- const chosen = policy.selectMarket(candidates);
2288
- if (chosen === void 0) return void 0;
2289
- if (!candidates.includes(chosen)) {
2290
- throw new Error("policy.selectMarket returned a market that was not among the candidates");
2291
- }
2292
- return chosen;
2293
- };
2294
- var marketRefOf = (candidate, snapshot) => cardMarketOf(candidate.card, snapshot, candidate.key, candidate.backend);
2295
- var cardMarketOf = (card, snapshot, key, backend) => ({
2296
- kind: "card",
2297
- key,
2298
- backend,
2299
- source: card.source,
2300
- sourceType: card.sourceType,
2301
- solver: card.solver,
2302
- ...card.discovery_pubkey === void 0 ? {} : { discoveryPubkey: card.discovery_pubkey },
2303
- pair: card.pair,
2304
- snapshot
2305
- });
2306
- var isCardMarket = (market) => market.kind === "card";
2307
-
2308
- // src/client/resolve.ts
2309
- var SUPPORTED_PAIRS = [
2310
- "arkade->arkade",
2311
- "arkade->lightning",
2312
- "lightning->arkade",
2313
- "arkade->onchain"
2314
- ];
2315
- var isSupportedPair = (pair) => SUPPORTED_PAIRS.includes(pair);
2316
- var assembleRoute = (give, take) => {
2317
- for (const leg of [give, take]) {
2318
- const rail = railOfCorridor(leg.corridor);
2319
- if (!leg.asset.startsWith(`${rail}:`)) {
2320
- throw new Error(
2321
- `route leg ${leg.corridor} carries ${leg.asset}, which is not on the ${rail} rail`
2322
- );
2323
- }
2324
- }
2325
- return { give, take };
2326
- };
2327
- var endpoint = (corridor, asset3, instrument) => ({
2328
- corridor,
2329
- asset: asset3,
2330
- ...instrument === void 0 ? {} : { instrument }
2331
- });
2332
- var legFor = (asset3, expected) => {
2333
- const leg = toDiscoveryLeg(asset3);
2334
- if (expected !== void 0 && leg.corridor !== expected) {
2335
- throw new UnsupportedRoute(
2336
- `${asset3} settles on ${leg.corridor}, and this leg is ${expected}`,
2337
- { give: leg.corridor, take: expected }
2338
- );
2339
- }
2340
- return leg;
2341
- };
2342
- var resolveRoute = async (input, deps) => {
2343
- const claimed = input.to === void 0 ? void 0 : deps.corridors.claim(input.to);
2344
- if (input.to !== void 0 && claimed === void 0) {
2345
- throw new UnsupportedRoute(`no corridor serves ${JSON.stringify(input.to)}`);
2346
- }
2347
- if (claimed?.corridor === "arkade") {
2348
- throw new UnsupportedRoute(
2349
- "an Arkade address is a plain Arkade payment, not a swap \u2014 send it with the wallet",
2350
- { take: "arkade" }
2351
- );
2352
- }
2353
- const snapshot = deps.mode === "quote" ? await deps.discovery.load() : await deps.discovery.peek();
2354
- const aliases = aliasTableFrom(snapshot.markets, deps.network);
2355
- if (input.via !== void 0 && (input.via === "arkade" || !isCorridor(input.via))) {
2356
- throw new UnsupportedRoute(
2357
- `via names ${input.via}, which is not a corridor a receive can arrive over`
2358
- );
2359
- }
2360
- const giveCorridor = input.via;
2361
- const takeCorridor = claimed?.corridor ?? (giveCorridor === void 0 ? void 0 : "arkade");
2362
- const takeAsset = assetFor(input.take, takeCorridor ?? "arkade", deps.network, aliases);
2363
- const giveAsset = assetFor(input.give, giveCorridor ?? "arkade", deps.network, aliases);
2364
- const takeLeg = legFor(takeAsset, takeCorridor);
2365
- const giveLeg = legFor(giveAsset, giveCorridor);
2366
- if (giveLeg.corridor === takeLeg.corridor && giveLeg.assetId === takeLeg.assetId) {
2367
- throw new UnsupportedRoute(
2368
- `both legs are ${giveAsset} on ${giveLeg.corridor} \u2014 name the other side with take, a destination, or via`,
2369
- { give: giveLeg.corridor, take: takeLeg.corridor }
2370
- );
2371
- }
2372
- const pair = `${giveLeg.corridor}->${takeLeg.corridor}`;
2373
- if (!isSupportedPair(pair)) {
2374
- throw new UnsupportedRoute(
2375
- pair === "onchain->arkade" ? "onchain -> arkade is not served until the client owns the trader's L1 refund path end to end" : `${pair} is not an implemented route`,
2376
- { give: giveLeg.corridor, take: takeLeg.corridor }
2377
- );
2378
- }
2379
- const give = endpoint(
2380
- giveLeg.corridor,
2381
- giveAsset,
2382
- giveLeg.corridor === "arkade" ? { kind: "wallet" } : void 0
2383
- );
2384
- const take = endpoint(
2385
- takeLeg.corridor,
2386
- takeAsset,
2387
- claimed?.instrument ?? (takeLeg.corridor === "arkade" ? { kind: "wallet" } : void 0)
2388
- );
2389
- const amount = pinAmount(input, take.instrument);
2390
- const candidates = eligibleMarkets(snapshot, { give: giveLeg, take: takeLeg }, deps.policy);
2391
- const market = chooseMarket(candidates, deps.policy);
2392
- const resolution = {
2393
- give,
2394
- take,
2395
- ...market === void 0 ? {} : { market: marketRefOf(market, snapshot.ref) },
2396
- eligible: market === void 0 ? 0 : candidates.length,
2397
- snapshot: snapshot.ref,
2398
- ...amount === void 0 ? {} : { amount }
2399
- };
2400
- return {
2401
- resolution,
2402
- legs: { give: giveLeg, take: takeLeg },
2403
- give,
2404
- take,
2405
- pair,
2406
- candidates,
2407
- ...market === void 0 ? {} : { market },
2408
- snapshot,
2409
- ...amount === void 0 ? {} : { amount },
2410
- aliases
2411
- };
2412
- };
2413
- var isCorridor = (value) => value === "arkade" || value === "lightning" || value === "onchain";
2414
- var assetFor = (ref, corridor, network, aliases) => ref === void 0 ? btcOn(railOfCorridor(corridor), network) : (
2415
- // Scoped to the leg's rail, because BTC has one id per rail and a
2416
- // whole-table lookup would refuse `"BTC"` as ambiguous on any snapshot
2417
- // carrying a corridor market — see `scopedToRail`.
2418
- canonicalAssetId(ref, scopedToRail(aliases, railOfCorridor(corridor)))
2419
- );
2420
- var pinAmount = (input, takeInstrument) => {
2421
- const invoiced = takeInstrument?.kind === "invoice" && takeInstrument.amount !== void 0 ? takeInstrument.amount : void 0;
2422
- if (input.amount !== void 0 && invoiced !== void 0) {
2423
- throw new AmountMismatch([`the invoice's ${invoiced}`, `amount ${input.amount}`]);
2424
- }
2425
- if (input.amount !== void 0) {
2426
- if (input.amountOn === void 0) {
2427
- throw new Error("amount needs amountOn ('give' or 'take') to say which leg it pins");
2428
- }
2429
- if (input.amount <= 0n) {
2430
- throw new Error(`amount must be positive, got ${input.amount}`);
2431
- }
2432
- return { value: input.amount, on: input.amountOn, source: "caller" };
2433
- }
2434
- if (invoiced !== void 0) return { value: invoiced, on: "take", source: "invoice" };
2435
- return void 0;
2436
- };
2437
-
2438
- // src/client/verify.ts
2439
- var reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
2440
- var CHECK_BY_REASON = {
2441
- invoice_expired: "invoice",
2442
- invoice_undecodable: "invoice",
2443
- invoice_hash_mismatch: "invoice",
2444
- invoice_amount_mismatch: "invoice",
2445
- insufficient_headroom: "refund_window",
2446
- missing_refund_locktime: "refund_window",
2447
- claim_window_too_short: "refund_window",
2448
- confirmations_out_of_range: "refund_window",
2449
- timelock_order: "refund_window",
2450
- quote_malformed: "refund_window"
2451
- };
2452
- var gated = (run, quote) => {
2453
- try {
2454
- run();
2455
- } catch (error) {
2456
- const reason = reasonOf(error);
2457
- if (reason === "quote_expired") {
2458
- throw new QuoteExpired(quote.id, quote.expiresAt, quote.now);
2459
- }
2460
- const check = reason === void 0 ? void 0 : CHECK_BY_REASON[reason];
2461
- if (check === void 0) throw error;
2462
- throw new QuoteVerificationFailed(
2463
- check,
2464
- void 0,
2465
- error instanceof Error ? error.message : String(error),
2466
- { cause: error }
2467
- );
2468
- }
2469
- };
2470
- var verifyResponder = (input) => {
2471
- if (!input.pinnable || input.expected === void 0) {
2472
- throw new QuoteVerificationFailed(
2473
- "responder",
2474
- "a registry-served card naming the solver's discovery key",
2475
- input.expected === void 0 ? "the card names no discovery key" : "the card came out of the local cache, which does not authenticate it"
2476
- );
2477
- }
2478
- if (input.attested === void 0) {
2479
- throw new QuoteVerificationFailed(
2480
- "responder",
2481
- input.expected,
2482
- "the transport attests nobody"
2483
- );
2484
- }
2485
- if (input.attested !== input.expected) {
2486
- throw new QuoteVerificationFailed("responder", input.expected, input.attested);
2487
- }
2488
- };
2489
- var verifyPair = (quoted, requested) => {
2490
- if (quoted !== requested) {
2491
- throw new QuoteVerificationFailed("pair", requested, String(quoted));
2492
- }
2493
- };
2494
- var verifyingDerivation = (derive) => {
2495
- try {
2496
- return derive();
2497
- } catch (error) {
2498
- if (error instanceof AddressMismatch) {
2499
- const derived = Array.isArray(error.derived) ? error.derived.join(", ") : error.derived;
2500
- throw new QuoteVerificationFailed("lockup_address", derived, error.quoted, {
2501
- cause: error
2502
- });
2503
- }
2504
- if (error instanceof Error) {
2505
- throw new QuoteVerificationFailed("lockup_address", void 0, error.message, {
2506
- cause: error
2507
- });
2508
- }
2509
- throw error;
2510
- }
2511
- };
2512
- var verifySendWindow = (input) => {
2513
- gated(
2514
- () => assertFundable({
2515
- quote: input.quote,
2516
- now: input.now,
2517
- ...input.invoiceExpiresAt === void 0 ? {} : { invoiceExpiresAt: input.invoiceExpiresAt },
2518
- ...input.onchain === void 0 ? {} : { onchain: input.onchain }
2519
- }),
2520
- { id: input.quoteId, expiresAt: input.quote.valid_until, now: input.now }
2521
- );
2522
- };
2523
- var verifyReceiveWindow = (input) => {
2524
- gated(
2525
- () => assertReceivable({
2526
- quote: input.quote,
2527
- payDeadline: input.payDeadline,
2528
- now: input.now
2529
- }),
2530
- { id: input.quoteId, expiresAt: input.payDeadline, now: input.now }
2531
- );
2532
- };
2533
- var verifySendInvoice = (input) => {
2534
- const invoiced = input.invoiced;
2535
- if (input.take !== invoiced) {
2536
- throw new QuoteVerificationFailed("invoice", `${invoiced}`, `${input.take}`);
2537
- }
2538
- if (input.give < input.take) {
2539
- throw new QuoteVerificationFailed(
2540
- "invoice",
2541
- `at least the invoice's ${invoiced}`,
2542
- `${input.give}, a negative spread`
2543
- );
2544
- }
2545
- };
2546
- var verifyReceiveInvoiceFacts = (input) => {
2547
- let decoded;
2548
- try {
2549
- decoded = input.decode(input.invoice);
2550
- } catch (cause) {
2551
- throw new QuoteVerificationFailed(
2552
- "invoice",
2553
- "a decodable BOLT11",
2554
- cause instanceof Error ? cause.message : String(cause),
2555
- { cause }
2556
- );
2557
- }
2558
- if (!Number.isFinite(decoded.expiresAt)) {
2559
- throw new QuoteVerificationFailed("invoice", "a finite expiry", `${decoded.expiresAt}`);
2560
- }
2561
- if (!Number.isFinite(input.validUntil)) {
2562
- throw new QuoteVerificationFailed(
2563
- "refund_window",
2564
- "a finite valid_until",
2565
- `${input.validUntil}`
2566
- );
2567
- }
2568
- if (decoded.paymentHash !== input.paymentHash) {
2569
- throw new QuoteVerificationFailed("invoice", input.paymentHash, decoded.paymentHash);
2570
- }
2571
- if (!Number.isSafeInteger(decoded.amountSats) || decoded.amountSats <= 0) {
2572
- throw new QuoteVerificationFailed(
2573
- "invoice",
2574
- `${input.payAmount}`,
2575
- "the invoice names no amount"
2576
- );
2577
- }
2578
- if (BigInt(decoded.amountSats) !== input.payAmount) {
2579
- throw new QuoteVerificationFailed("invoice", `${input.payAmount}`, `${decoded.amountSats}`);
2580
- }
2581
- return { payDeadline: Math.min(decoded.expiresAt, input.validUntil) };
2582
- };
2583
- var verifyQuoteTtl = (input) => {
2584
- const floor = input.floorSeconds ?? 0;
2585
- if (input.expiresAt - input.now <= floor) {
2586
- throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
2587
- }
2588
- };
2589
- var verifyQuotedAmount = (input) => {
2590
- const quoted = input.pinned.on === "give" ? input.give : input.take;
2591
- if (quoted !== input.pinned.value) {
2592
- throw new QuoteVerificationFailed(
2593
- "pair",
2594
- `${input.pair} ${input.pinned.on}=${input.pinned.value}`,
2595
- `${input.pair} ${input.pinned.on}=${quoted}`
2596
- );
2597
- }
2598
- if (input.take > input.give) {
2599
- throw new QuoteVerificationFailed(
2600
- "pair",
2601
- `${input.pair} give >= take`,
2602
- `give=${input.give} take=${input.take}`
2603
- );
2604
- }
2605
- };
2606
-
2607
- // src/client/quoteOffer.ts
2608
- var FEED_TTL_MS = 3e4;
2609
- var feedFetch = (base = fetch) => {
2610
- const at = /* @__PURE__ */ new Map();
2611
- const probe = async (input, init) => {
2612
- at.set(input instanceof Request ? input.url : String(input), Date.now());
2613
- return base(input, init);
2614
- };
2615
- return { fetch: makeCachedFeedFetch(FEED_TTL_MS, probe), fetchedAt: (url) => at.get(url) };
2616
- };
2617
- var quoteFromFeed = async (input) => {
2618
- const { candidate, amount } = input;
2619
- if (amount === void 0) {
2620
- throw new Error("an asset swap needs an amount and the side it pins");
2621
- }
2622
- const plan = await quoteOffer(candidate.card, {
2623
- give: candidate.give,
2624
- ...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
2625
- ...QUOTE_OPTIONS,
2626
- fetchImpl: input.feed.fetch
2627
- });
2628
- verifyPlanLegs(plan, input.legs, candidate.give);
2629
- const expiresAt = feedExpiry(candidate.card, input.feed, input.now);
2630
- verifyQuoteTtl({
2631
- quoteId: input.quoteId,
2632
- expiresAt,
2633
- now: input.now,
2634
- floorSeconds: input.policy?.quoteTtlFloorSeconds
2635
- });
2636
- const route = assembleRoute(
2637
- { ...input.endpoints.give, instrument: { kind: "wallet" } },
2638
- { ...input.endpoints.take, instrument: { kind: "wallet" } }
2639
- );
2640
- return {
2641
- quote: {
2642
- id: input.quoteId,
2643
- route,
2644
- give: { asset: input.endpoints.give.asset, amount: plan.deposit.atomic },
2645
- take: { asset: input.endpoints.take.asset, amount: plan.receive.atomic },
2646
- market: input.market,
2647
- expiresAt,
2648
- fee: { amount: spreadOf(plan), asset: input.endpoints.take.asset }
2649
- },
2650
- preparation: { backend: "feed", card: candidate.card, plan, give: candidate.give }
2651
- };
2652
- };
2653
- var spreadOf = (plan) => {
2654
- const fair = computeWantAmount({
2655
- deposit: plan.deposit.atomic,
2656
- give: plan.give,
2657
- price: plan.price,
2658
- feeBps: 0,
2659
- safetyBps: 0
2660
- });
2661
- const spread = fair - plan.receive.atomic;
2662
- return spread > 0n ? spread : 0n;
2663
- };
2664
- var feedExpiry = (card, feed, now) => {
2665
- const readAt = card.price_feed === void 0 ? void 0 : feed.fetchedAt(card.price_feed);
2666
- const from = readAt === void 0 ? now : Math.floor(readAt / 1e3);
2667
- return from + FEED_TTL_MS / 1e3;
2668
- };
2669
- var verifyPlanLegs = (plan, legs, give) => {
2670
- const expected = `${legs.give.assetId}->${legs.take.assetId}`;
2671
- const priced = `${plan.deposit.asset.id}->${plan.receive.asset.id}`;
2672
- if (expected !== priced || plan.give !== give) {
2673
- throw new QuoteVerificationFailed("pair", expected, priced);
2674
- }
2675
- };
2676
-
2677
- // src/client/quoteRfq.ts
2678
- import { hex as hex5 } from "@scure/base";
2679
- import { secp256k1 } from "@noble/curves/secp256k1.js";
69
+ CLAIM_PACKET_TYPE,
70
+ LockupRegistrationFailed,
71
+ RFQ_REFUSAL_ERROR_CODES,
72
+ SEALED_CIPHERTEXT_LENGTH,
73
+ SwapRefusal,
74
+ appendArkadeScript,
75
+ claimPacketShape,
76
+ isRfqRefusalErrorCode
77
+ } from "./chunk-PVB7EBAM.js";
2680
78
  import {
2681
- networkFromArkadeInfo,
2682
- provisionClaimSecret,
2683
- provisionRefundKey,
2684
- toXOnly
2685
- } from "@arkade-os/sdk";
2686
-
2687
- // src/client/rfqWire.ts
2688
- var BTC_LEG = {
2689
- arkade: ARKADE_BTC,
2690
- lightning: LIGHTNING_BTC,
2691
- onchain: ONCHAIN_BTC
2692
- };
2693
- var rfqLeg = (leg) => leg.assetId === BTC_ASSET_ID ? BTC_LEG[leg.corridor] : `${leg.corridor}:${leg.assetId}`;
2694
- var rfqPairFor = (give, take) => {
2695
- const pair = rfqPair(rfqLeg(give), rfqLeg(take));
2696
- assertPairLength(pair);
2697
- return pair;
2698
- };
2699
- var withCanonicalAmount = (payload, amount) => ({
2700
- ...payload,
2701
- amount: encodeRfqAmount(amount, "amount")
2702
- });
2703
- var parseRfqQuote = (quote) => ({
2704
- raw: quote,
2705
- rfqId: quote.rfq_id,
2706
- pair: quote.pair,
2707
- give: decodeRfqAmount(quote.from_amount, "from_amount"),
2708
- take: decodeRfqAmount(quote.to_amount, "to_amount"),
2709
- solver: quote.solver_pubkey,
2710
- validUntil: quote.valid_until,
2711
- ...quote.refund_locktime === void 0 ? {} : { refundLocktime: quote.refund_locktime },
2712
- profile: quote.profile ?? {}
2713
- });
2714
-
2715
- // src/client/quoteRfq.ts
2716
- var covenantInputs = (input) => {
2717
- const network = networkFromArkadeInfo(input.info);
2718
- const arkade = input.corridors.get("arkade").deps;
2719
- return {
2720
- operatorPubkey: toXOnly(hex5.decode(input.info.signerPubkey), "ark signer key"),
2721
- // The per-network pin the arkade module already resolved, never a key
2722
- // the operator reports about itself: this one ends up in a covenant leaf
2723
- // that decides who can move the funds.
2724
- emulatorPubkey: toXOnly(hex5.decode(arkade.emulatorPubkey), "emulator signer key"),
2725
- claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
2726
- hrp: network.hrp
2727
- };
2728
- };
2729
- var sealingKey = (deps) => {
2730
- const configured = deps.covclaimd?.pubkey;
2731
- if (configured === void 0) {
2732
- return secp256k1.getPublicKey(secp256k1.utils.randomSecretKey(), true);
2733
- }
2734
- const key = hex5.decode(configured);
2735
- if (key.length !== 33) {
2736
- throw new Error(
2737
- `the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
2738
- );
2739
- }
2740
- return key;
2741
- };
2742
- var pinnedFor = (input) => {
2743
- if (input.amount === void 0) {
2744
- throw new Error(`a ${input.route} quote needs an amount and the side it pins`);
2745
- }
2746
- return input.amount;
2747
- };
2748
- var quoteViaRfq = async (input) => {
2749
- verifyResponder({
2750
- attested: input.transport.attestedResponder,
2751
- expected: input.market.discoveryPubkey,
2752
- pinnable: input.market.snapshot.live
2753
- });
2754
- switch (input.route) {
2755
- case "arkade->lightning":
2756
- return quoteLightningSend(input);
2757
- case "lightning->arkade":
2758
- return quoteLightningReceive(input);
2759
- case "arkade->onchain":
2760
- return quoteOnchainSend(input);
2761
- }
2762
- };
2763
- var quoteLightningSend = async (input) => {
2764
- const invoice = input.endpoints.take.instrument;
2765
- if (invoice?.kind !== "invoice" || invoice.amount === void 0) {
2766
- throw new Error("a lightning send is quoted against the amountful invoice it pays");
2767
- }
2768
- const pair = rfqPairFor(input.legs.give, input.legs.take);
2769
- const rfqId = newRfqId();
2770
- const secrets = await provisionRefundKey(input.wallet);
2771
- const wire = await input.transport.requestQuote(
2772
- lightningSendRequest({
2773
- rfqId,
2774
- invoice: invoice.bolt11,
2775
- refundAddress: secrets.address,
2776
- senderPubkey: secrets.pubkey
2777
- })
2778
- );
2779
- verifyPair(wire.pair, pair);
2780
- const parsed = parseRfqQuote(wire);
2781
- verifySendInvoice({ invoiced: invoice.amount, give: parsed.give, take: parsed.take });
2782
- const covenant = covenantInputs(input);
2783
- const derived = verifyingDerivation(
2784
- () => deriveLightningSend({
2785
- quote: wire,
2786
- paymentHash: invoice.paymentHash,
2787
- senderPubkey: secrets.pubkey,
2788
- refundPkScript: secrets.pkScript,
2789
- ...covenant
2790
- })
2791
- );
2792
- verifySendWindow({
2793
- quote: wire,
2794
- quoteId: input.quoteId,
2795
- now: input.now,
2796
- invoiceExpiresAt: invoice.expiresAt
2797
- });
2798
- verifyQuoteTtl({
2799
- quoteId: input.quoteId,
2800
- expiresAt: parsed.validUntil,
2801
- now: input.now,
2802
- floorSeconds: input.policy?.quoteTtlFloorSeconds
2803
- });
2804
- return {
2805
- quote: {
2806
- id: input.quoteId,
2807
- route: assembleRoute(
2808
- { ...input.endpoints.give, instrument: { kind: "wallet" } },
2809
- { ...input.endpoints.take, instrument: invoice }
2810
- ),
2811
- give: { asset: input.endpoints.give.asset, amount: parsed.give },
2812
- take: { asset: input.endpoints.take.asset, amount: parsed.take },
2813
- lock: { hash: invoice.paymentHash },
2814
- market: input.market,
2815
- solver: parsed.solver,
2816
- expiresAt: parsed.validUntil,
2817
- refundLocktime: derived.refundLocktime,
2818
- fee: { amount: parsed.give - parsed.take, asset: input.endpoints.give.asset }
2819
- },
2820
- preparation: {
2821
- backend: "rfq",
2822
- route: "arkade->lightning",
2823
- card: input.candidate.card,
2824
- rfqId,
2825
- wire: parsed,
2826
- lockup: {
2827
- address: derived.address,
2828
- script: derived.script,
2829
- pkScript: derived.swapPkScript
2830
- },
2831
- contractParams: derived.contractParams,
2832
- secrets,
2833
- refundAddress: secrets.address,
2834
- fundAmount: parsed.give
2835
- }
2836
- };
2837
- };
2838
- var quoteLightningReceive = async (input) => {
2839
- const pinned = pinnedFor(input);
2840
- const pair = rfqPairFor(input.legs.give, input.legs.take);
2841
- const rfqId = newRfqId();
2842
- const secrets = await provisionClaimSecret(input.wallet);
2843
- const paymentHash = hex5.encode(secrets.paymentHash);
2844
- const payoutAddress = await input.wallet.getAddress();
2845
- const lightning = input.corridors.get("lightning").deps;
2846
- const claimPacket = await sealClaimPacket({
2847
- preimage: secrets.preimage,
2848
- covclaimdPubkey: sealingKey(lightning)
2849
- });
2850
- const wire = await input.transport.requestQuote(
2851
- withCanonicalAmount(
2852
- lightningReceiveRequest({
2853
- rfqId,
2854
- paymentHash,
2855
- payoutAddress,
2856
- payoutPubkey: secrets.pubkey,
2857
- claimPacket: claimPacket.ciphertext,
2858
- // Placeholder: the v1 builders type this field `number`, and the
2859
- // wire adapter re-encodes it as the canonical decimal string.
2860
- // Encoding it here as well would put the decision in two places.
2861
- amount: 0,
2862
- amountSide: toRfqAmountSide(pinned.on)
2863
- }),
2864
- pinned.value
2865
- )
2866
- );
2867
- verifyPair(wire.pair, pair);
2868
- const parsed = parseRfqQuote(wire);
2869
- verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
2870
- const covenant = covenantInputs(input);
2871
- const derived = verifyingDerivation(
2872
- () => deriveLightningReceive({
2873
- quote: wire,
2874
- paymentHash,
2875
- payoutPubkey: secrets.pubkey,
2876
- payoutAddress,
2877
- operatorPubkey: covenant.operatorPubkey,
2878
- emulatorPubkey: covenant.emulatorPubkey,
2879
- claimDelay: covenant.claimDelay,
2880
- hrp: covenant.hrp
2881
- })
2882
- );
2883
- const { payDeadline } = verifyReceiveInvoiceFacts({
2884
- invoice: derived.invoice,
2885
- decode: lightning.decode,
2886
- paymentHash,
2887
- payAmount: parsed.give,
2888
- validUntil: parsed.validUntil
2889
- });
2890
- verifyReceiveWindow({
2891
- quote: wire,
2892
- quoteId: input.quoteId,
2893
- payDeadline,
2894
- now: input.now
2895
- });
2896
- verifyQuoteTtl({
2897
- quoteId: input.quoteId,
2898
- // The hold invoice's window is minutes where the quote's is an hour, so
2899
- // the deadline that binds this leg is the earlier of the two — which is
2900
- // what `payDeadline` already is.
2901
- expiresAt: payDeadline,
2902
- now: input.now,
2903
- floorSeconds: input.policy?.quoteTtlFloorSeconds
2904
- });
2905
- const artifact = { kind: "invoice", bolt11: derived.invoice };
2906
- return {
2907
- quote: {
2908
- id: input.quoteId,
2909
- route: assembleRoute(
2910
- {
2911
- ...input.endpoints.give,
2912
- instrument: {
2913
- kind: "invoice",
2914
- bolt11: derived.invoice,
2915
- paymentHash,
2916
- amount: parsed.give,
2917
- expiresAt: payDeadline
2918
- }
2919
- },
2920
- { ...input.endpoints.take, instrument: { kind: "wallet" } }
2921
- ),
2922
- give: { asset: input.endpoints.give.asset, amount: parsed.give },
2923
- take: { asset: input.endpoints.take.asset, amount: parsed.take },
2924
- lock: { hash: paymentHash },
2925
- market: input.market,
2926
- solver: parsed.solver,
2927
- expiresAt: payDeadline,
2928
- refundLocktime: derived.refundLocktime,
2929
- artifact,
2930
- fee: { amount: parsed.give - parsed.take, asset: input.endpoints.give.asset }
2931
- },
2932
- preparation: {
2933
- backend: "rfq",
2934
- route: "lightning->arkade",
2935
- card: input.candidate.card,
2936
- rfqId,
2937
- wire: parsed,
2938
- lockup: {
2939
- address: derived.address,
2940
- script: derived.script,
2941
- pkScript: derived.swapPkScript
2942
- },
2943
- contractParams: derived.contractParams,
2944
- secrets,
2945
- payoutAddress,
2946
- expectedAmount: parsed.take,
2947
- payDeadline
2948
- }
2949
- };
2950
- };
2951
- var quoteOnchainSend = async (input) => {
2952
- const pinned = pinnedFor(input);
2953
- const destination = input.endpoints.take.instrument;
2954
- if (destination?.kind !== "address") {
2955
- throw new Error("an onchain send is quoted against the L1 address it pays");
2956
- }
2957
- const l1Network = l1NetworkFromArk(input.info.network);
2958
- const payoutPkScript = l1ScriptForAddress(destination.address, l1Network);
2959
- const pair = rfqPairFor(input.legs.give, input.legs.take);
2960
- const rfqId = newRfqId();
2961
- const secrets = await provisionClaimSecret(input.wallet);
2962
- const payoutKey = await provisionRefundKey(input.wallet);
2963
- const paymentHash = hex5.encode(secrets.paymentHash);
2964
- const wire = await input.transport.requestQuote(
2965
- withCanonicalAmount(
2966
- onchainSendRequest({
2967
- rfqId,
2968
- paymentHash,
2969
- payoutPubkey: payoutKey.pubkey,
2970
- refundAddress: payoutKey.address,
2971
- senderPubkey: secrets.pubkey,
2972
- amount: 0,
2973
- amountSide: toRfqAmountSide(pinned.on)
2974
- }),
2975
- pinned.value
2976
- )
2977
- );
2978
- verifyPair(wire.pair, pair);
2979
- const parsed = parseRfqQuote(wire);
2980
- verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
2981
- const covenant = covenantInputs(input);
2982
- const derived = verifyingDerivation(
2983
- () => deriveOnchainSend({
2984
- quote: wire,
2985
- paymentHash,
2986
- payoutPubkey: payoutKey.pubkey,
2987
- operatorPubkey: covenant.operatorPubkey,
2988
- emulatorPubkey: covenant.emulatorPubkey,
2989
- claimDelay: covenant.claimDelay,
2990
- hrp: covenant.hrp,
2991
- l1Network,
2992
- refundAddress: payoutKey.address,
2993
- senderPubkey: secrets.pubkey
2994
- })
2995
- );
2996
- verifySendWindow({
2997
- quote: wire,
2998
- quoteId: input.quoteId,
2999
- now: input.now,
3000
- onchain: {
3001
- htlcLocktime: derived.htlcLocktime,
3002
- minConfirmations: derived.minConfirmations,
3003
- direction: "send"
3004
- }
3005
- });
3006
- verifyQuoteTtl({
3007
- quoteId: input.quoteId,
3008
- expiresAt: parsed.validUntil,
3009
- now: input.now,
3010
- floorSeconds: input.policy?.quoteTtlFloorSeconds
3011
- });
3012
- return {
3013
- quote: {
3014
- id: input.quoteId,
3015
- route: assembleRoute(
3016
- { ...input.endpoints.give, instrument: { kind: "wallet" } },
3017
- { ...input.endpoints.take, instrument: destination }
3018
- ),
3019
- give: { asset: input.endpoints.give.asset, amount: parsed.give },
3020
- take: { asset: input.endpoints.take.asset, amount: parsed.take },
3021
- lock: { hash: paymentHash },
3022
- market: input.market,
3023
- solver: parsed.solver,
3024
- expiresAt: parsed.validUntil,
3025
- // Read off the derivation and not off the wire: the field is
3026
- // optional there, a solver may carry it in the profile instead, and
3027
- // the derivation is what settles which one this covenant used.
3028
- refundLocktime: derived.refundLocktime,
3029
- fee: { amount: parsed.give - parsed.take, asset: input.endpoints.give.asset }
3030
- },
3031
- preparation: {
3032
- backend: "rfq",
3033
- route: "arkade->onchain",
3034
- card: input.candidate.card,
3035
- rfqId,
3036
- wire: parsed,
3037
- lockup: {
3038
- address: derived.address,
3039
- script: derived.script,
3040
- pkScript: derived.swapPkScript
3041
- },
3042
- secrets,
3043
- refundAddress: payoutKey.address,
3044
- fundAmount: parsed.give,
3045
- payoutKey,
3046
- payoutPkScript,
3047
- htlc: derived.htlc,
3048
- htlcParams: derived.htlcParams,
3049
- l1Network: derived.l1Network,
3050
- minConfirmations: derived.minConfirmations
3051
- }
3052
- };
3053
- };
3054
-
3055
- // src/client/verbs.ts
3056
- import { arkTarget as arkTarget2, resolveSendAmount } from "@arkade-os/sdk";
3057
-
3058
- // src/client/sats.ts
3059
- var satsOf = (value, field) => {
3060
- if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
3061
- throw new AmountEncodingUnsupported(
3062
- field,
3063
- `${value}`,
3064
- "outside the non-negative safe-integer window core's payment amounts are numbers in"
3065
- );
3066
- }
3067
- return Number(value);
3068
- };
3069
-
3070
- // src/client/verbs.ts
3071
- var enforceFeeCeiling = (quote, call, policy) => {
3072
- let ceiling;
3073
- for (const [source, limit] of [
3074
- ["maxFee", call],
3075
- ["policy.maxFee", policy]
3076
- ]) {
3077
- if (limit === void 0) continue;
3078
- if (!sameAsset(limit.asset, quote.fee.asset)) {
3079
- throw new Error(
3080
- `${source} is denominated in ${limit.asset} and the quote's fee in ${quote.fee.asset} \u2014 no rate converts one ceiling into the other`
3081
- );
3082
- }
3083
- ceiling = ceiling === void 0 || limit.amount < ceiling ? limit.amount : ceiling;
3084
- }
3085
- if (ceiling !== void 0 && quote.fee.amount > ceiling) {
3086
- throw new MaxFeeExceeded(quote.id, quote.fee.asset, quote.fee.amount, ceiling);
3087
- }
3088
- };
3089
- var settle = async (deps, input, maxFee) => {
3090
- const quote = await deps.quote(input);
3091
- enforceFeeCeiling(quote, maxFee, deps.policyMaxFee);
3092
- return deps.accept(quote);
3093
- };
3094
- var pay = async (deps, destination, options = {}) => {
3095
- const arkade = arkTarget2(destination);
3096
- if (arkade !== void 0) {
3097
- const amount = resolveSendAmount(
3098
- "ark",
3099
- destination,
3100
- options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
3101
- );
3102
- return { kind: "payment", txid: await deps.wallet.send({ address: arkade, amount }) };
3103
- }
3104
- const swap = await settle(
3105
- deps,
3106
- {
3107
- to: destination,
3108
- // `amountOn: "take"` because the number a caller writes beside a
3109
- // destination is what the recipient gets. An invoice pins the same
3110
- // leg by existing, which is why passing both is `AmountMismatch`.
3111
- ...options.amount === void 0 ? {} : { amount: options.amount, amountOn: "take" }
3112
- },
3113
- options.maxFee
3114
- );
3115
- return { kind: "swap", swap };
3116
- };
3117
- var receive = async (deps, options) => {
3118
- const swap = await settle(
3119
- deps,
3120
- {
3121
- via: options.via,
3122
- ...options.asset === void 0 ? {} : { take: options.asset },
3123
- amount: options.amount,
3124
- // The trader's side is the take leg: `receive({ amount })` is
3125
- // "credit me this much", not "let the payer send this much".
3126
- amountOn: "take"
3127
- },
3128
- options.maxFee
3129
- );
3130
- if (swap.artifact === void 0) {
3131
- throw new Error(
3132
- `receive over ${options.via} returned no artifact \u2014 there is nothing to show a payer`
3133
- );
3134
- }
3135
- return swap;
3136
- };
3137
- var exchange = async (deps, options) => settle(
3138
- deps,
3139
- {
3140
- ...options.give === void 0 ? {} : { give: options.give },
3141
- ...options.take === void 0 ? {} : { take: options.take },
3142
- ...options.amount === void 0 ? {} : { amount: options.amount },
3143
- ...options.amountOn === void 0 ? {} : { amountOn: options.amountOn }
3144
- },
3145
- options.maxFee
3146
- );
3147
-
3148
- // src/client/transport.ts
3149
- var attesting = (transport, responder) => Object.assign(transport, { attestedResponder: responder });
3150
- var nostrTransportFactory = async (rendezvous) => {
3151
- const { nostrRfqTransport } = await import("./nostr.js");
3152
- return attesting(
3153
- nostrRfqTransport({
3154
- relays: [...rendezvous.relays],
3155
- solverPubkey: rendezvous.solverPubkey
3156
- }),
3157
- rendezvous.solverPubkey
3158
- );
3159
- };
3160
-
3161
- // src/client/client.ts
3162
- var PREPARATIONS_HELD = 64;
3163
- var mintQuoteId = () => hex6.encode(crypto.getRandomValues(new Uint8Array(16)));
3164
- var createSwapClient = (config) => {
3165
- const { wallet } = config;
3166
- const operator = config.operator ?? walletOperator(wallet);
3167
- const feed = feedFetch(config.fetchImpl ?? fetch);
3168
- const preparations = /* @__PURE__ */ new Map();
3169
- const indexer = walletLockupIndexer(wallet);
3170
- let disposed = false;
3171
- const ensureLive = (method) => {
3172
- if (disposed) throw new ClientDisposed(method);
3173
- };
3174
- let drive;
3175
- const driving = () => drive ??= createSwapDrive({
3176
- wallet,
3177
- operator,
3178
- ...config.repository === void 0 ? {} : { repository: config.repository },
3179
- corridors: async () => (await resolved()).corridors,
3180
- ...config.policy?.drive === void 0 ? {} : { mode: config.policy.drive },
3181
- indexer
3182
- });
3183
- let context;
3184
- const resolved = () => context ??= (async () => {
3185
- const base = await resolveCorridorBase({
3186
- wallet,
3187
- operator,
3188
- ...config.emulatorPubkey === void 0 ? {} : { emulatorPubkey: config.emulatorPubkey },
3189
- ...config.fetchImpl === void 0 ? {} : { fetchImpl: config.fetchImpl },
3190
- requireLive: false
3191
- });
3192
- return {
3193
- base,
3194
- corridors: corridorSet(base, config.corridors),
3195
- discovery: discoveryIndex({
3196
- network: base.networkName,
3197
- ...config.discovery === void 0 ? {} : { config: config.discovery },
3198
- ...config.repository === void 0 ? {} : { repository: config.repository }
3199
- })
3200
- };
3201
- })().catch((error) => {
3202
- context = void 0;
3203
- throw error;
3204
- });
3205
- const route = async (input, mode) => {
3206
- const { base, corridors, discovery } = await resolved();
3207
- return resolveRoute(input, {
3208
- corridors,
3209
- network: base.networkName,
3210
- discovery,
3211
- ...config.policy === void 0 ? {} : { policy: config.policy },
3212
- mode
3213
- });
3214
- };
3215
- const remember = (id, preparation) => {
3216
- preparations.set(id, preparation);
3217
- while (preparations.size > PREPARATIONS_HELD) {
3218
- const oldest = preparations.keys().next();
3219
- if (oldest.done) break;
3220
- preparations.delete(oldest.value);
3221
- }
3222
- };
3223
- const client = {
3224
- resolve: async (input) => {
3225
- ensureLive("resolve");
3226
- return (await route(input, "resolve")).resolution;
3227
- },
3228
- quote: async (input) => {
3229
- ensureLive("quote");
3230
- const { corridors, discovery } = await resolved();
3231
- let resolvedRoute = await route(input, "quote");
3232
- if (resolvedRoute.market?.backend === "rfq" && !resolvedRoute.snapshot.ref.live) {
3233
- await discovery.load({ refresh: true });
3234
- resolvedRoute = await route(input, "quote");
3235
- }
3236
- const { market } = resolvedRoute;
3237
- if (market === void 0) {
3238
- throw new UnsupportedRoute(
3239
- `no market serves ${resolvedRoute.legs.give.corridor}:${resolvedRoute.legs.give.assetId} -> ${resolvedRoute.legs.take.corridor}:${resolvedRoute.legs.take.assetId} on the active discovery snapshot`,
3240
- {
3241
- give: resolvedRoute.legs.give.corridor,
3242
- take: resolvedRoute.legs.take.corridor
3243
- }
3244
- );
3245
- }
3246
- const marketRef = resolvedRoute.resolution.market;
3247
- if (marketRef === void 0 || marketRef.kind !== "card") {
3248
- throw new Error("a resolved market must carry its card's provenance");
3249
- }
3250
- corridors.get(resolvedRoute.legs.give.corridor);
3251
- corridors.get(resolvedRoute.legs.take.corridor);
3252
- const quoteId = mintQuoteId();
3253
- const now = Math.floor(Date.now() / 1e3);
3254
- if (resolvedRoute.pair === "arkade->arkade") {
3255
- const { quote, preparation } = await quoteFromFeed({
3256
- quoteId,
3257
- candidate: market,
3258
- market: marketRef,
3259
- legs: resolvedRoute.legs,
3260
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
3261
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
3262
- feed,
3263
- ...config.policy === void 0 ? {} : { policy: config.policy },
3264
- now
3265
- });
3266
- remember(quoteId, preparation);
3267
- return quote;
3268
- }
3269
- const info = await liveArkadeInfo(wallet, { requireLive: true });
3270
- const rendezvous = market.card.discovery_pubkey;
3271
- if (rendezvous === void 0) {
3272
- throw new Error(`card ${market.card.solver} names no discovery key to address`);
3273
- }
3274
- const transport = await (config.transportFor ?? nostrTransportFactory)({
3275
- card: market.card,
3276
- solverPubkey: rendezvous,
3277
- relays: market.card.transports?.nostr?.relays ?? []
3278
- });
3279
- try {
3280
- const { quote, preparation } = await quoteViaRfq({
3281
- quoteId,
3282
- route: resolvedRoute.pair,
3283
- candidate: market,
3284
- market: marketRef,
3285
- legs: resolvedRoute.legs,
3286
- endpoints: { give: resolvedRoute.give, take: resolvedRoute.take },
3287
- ...resolvedRoute.amount === void 0 ? {} : { amount: resolvedRoute.amount },
3288
- wallet,
3289
- info,
3290
- corridors,
3291
- transport,
3292
- ...config.policy === void 0 ? {} : { policy: config.policy },
3293
- now
3294
- });
3295
- remember(quoteId, preparation);
3296
- return quote;
3297
- } finally {
3298
- await transport.close().catch(() => {
3299
- });
3300
- }
3301
- },
3302
- accept: async (quote) => {
3303
- ensureLive("accept");
3304
- const { corridors } = await resolved();
3305
- const drive2 = driving();
3306
- await drive2.ready;
3307
- const preparation = preparations.get(quote.id);
3308
- return acceptQuote({
3309
- quote,
3310
- ...preparation === void 0 ? {} : { preparation },
3311
- wallet,
3312
- repository: config.repository,
3313
- corridors,
3314
- drive: drive2,
3315
- now: Math.floor(Date.now() / 1e3)
3316
- });
3317
- },
3318
- cancel: async (swapId) => {
3319
- ensureLive("cancel");
3320
- if (familyOfSwapId(swapId) === "rfq") throw new NotCancellable(swapId);
3321
- const repository = config.repository;
3322
- if (repository === void 0) {
3323
- throw new MissingCorridorDep("arkade", "repository");
3324
- }
3325
- const drive2 = driving();
3326
- await drive2.ready;
3327
- const record = await repository.getSwapRecord(quoteIdOfSwapId(swapId));
3328
- if (record === void 0 || record.family !== "offer") {
3329
- throw new NotCancellable(swapId);
3330
- }
3331
- return cancelSwap({ wallet, repository, record, drive: drive2, indexer });
3332
- },
3333
- swaps: async (filter) => {
3334
- ensureLive("swaps");
3335
- const repository = config.repository;
3336
- if (repository === void 0) return [];
3337
- const drive2 = driving();
3338
- await drive2.ready;
3339
- const records = await repository.getAllSwapRecords();
3340
- const swaps = [];
3341
- for (const record of records) {
3342
- if (!readableRecord(record)) continue;
3343
- const live = drive2.swap(record.id);
3344
- swaps.push(live ?? swapOf(record, drive2.outcomeOf(record)));
3345
- }
3346
- if (filter === void 0) return swaps;
3347
- return swaps.filter(
3348
- (swap) => (filter.family === void 0 || swap.family === filter.family) && (filter.outcome === void 0 || swap.outcome === filter.outcome)
3349
- );
3350
- },
3351
- markets: async () => {
3352
- ensureLive("markets");
3353
- const { discovery } = await resolved();
3354
- const snapshot = await discovery.load();
3355
- return usableMarkets(snapshot, config.policy).map(
3356
- (card) => cardMarketOf(card, snapshot.ref, marketKeyOf(card), marketBackendOf(card))
3357
- );
3358
- },
3359
- pay: async (destination, options) => {
3360
- ensureLive("pay");
3361
- return pay(verbs, destination, options);
3362
- },
3363
- receive: async (options) => {
3364
- ensureLive("receive");
3365
- return receive(verbs, options);
3366
- },
3367
- exchange: async (options) => {
3368
- ensureLive("exchange");
3369
- return exchange(verbs, options);
3370
- },
3371
- preparationOf: (id) => {
3372
- ensureLive("preparationOf");
3373
- return preparations.get(id);
3374
- },
3375
- get ready() {
3376
- ensureLive("ready");
3377
- return driving().ready;
3378
- },
3379
- // `async`, so the refusal is a rejection rather than a synchronous
3380
- // throw: these are declared `Promise<void>` and a caller is entitled to
3381
- // `.catch()` them.
3382
- start: async () => {
3383
- ensureLive("start");
3384
- return driving().start();
3385
- },
3386
- stop: async () => {
3387
- ensureLive("stop");
3388
- return driving().stop();
3389
- },
3390
- [Symbol.asyncDispose]: async () => {
3391
- if (disposed) return;
3392
- disposed = true;
3393
- await drive?.dispose();
3394
- },
3395
- onUpdate: (fn) => {
3396
- ensureLive("onUpdate");
3397
- return driving().onUpdate(fn);
3398
- },
3399
- recover: async (id) => {
3400
- ensureLive("recover");
3401
- return driving().recover(quoteIdOfSwapId(id));
3402
- }
3403
- };
3404
- const verbs = {
3405
- wallet,
3406
- quote: (input) => client.quote(input),
3407
- accept: (quote) => client.accept(quote),
3408
- ...config.policy?.maxFee === void 0 ? {} : { policyMaxFee: config.policy.maxFee }
3409
- };
3410
- return client;
3411
- };
79
+ InMemoryAssetSwapRepository,
80
+ assertRfqSwapPageFilter,
81
+ marketsCacheKey
82
+ } from "./chunk-A3SHHRX4.js";
3412
83
 
3413
84
  // src/indexedDbRepository.ts
3414
85
  import {
3415
86
  awaitTransaction,
3416
87
  createManagedConnection,
3417
- promisifyRequest
88
+ promisifyRequest,
89
+ assertPageRequest,
90
+ pageResult
3418
91
  } from "@arkade-os/sdk";
3419
92
  var DEFAULT_DB_NAME = "arkade-intents";
3420
- var DB_VERSION = 3;
93
+ var DB_VERSION = 5;
3421
94
  var STORE_SWAPS = "swaps";
3422
95
  var STORE_RFQ_SWAPS = "rfqSwaps";
3423
96
  var STORE_SWAP_RECORDS = "swapRecords";
3424
97
  var STORE_SCANNED = "scannedTxids";
3425
98
  var STORE_MARKETS = "markets";
99
+ var STATE_HISTORY_INDEX = "byStateUpdatedAtAndRfqId";
100
+ var HISTORY_INDEX = "byUpdatedAtAndRfqId";
101
+ var LEGACY_STATE_ID_INDEX = "byStateAndRfqId";
3426
102
  var STORES = [
3427
103
  [STORE_SWAPS, { keyPath: "id" }],
3428
104
  // v2. Separate from `swaps` rather than sharing it: the two record types
@@ -3436,12 +112,19 @@ var STORES = [
3436
112
  [STORE_SCANNED],
3437
113
  [STORE_MARKETS]
3438
114
  ];
3439
- function initDatabase(db, oldVersion, transaction) {
3440
- void oldVersion;
3441
- void transaction;
115
+ function initDatabase(db, _oldVersion, transaction) {
3442
116
  for (const [name, options] of STORES) {
3443
117
  if (!db.objectStoreNames.contains(name)) db.createObjectStore(name, options);
3444
118
  }
119
+ if (!transaction) throw new Error("IndexedDB upgrade transaction is missing");
120
+ const rfq = transaction.objectStore(STORE_RFQ_SWAPS);
121
+ if (!rfq.indexNames.contains(STATE_HISTORY_INDEX)) {
122
+ rfq.createIndex(STATE_HISTORY_INDEX, ["state", "updatedAt", "rfqId"]);
123
+ }
124
+ if (!rfq.indexNames.contains(HISTORY_INDEX)) {
125
+ rfq.createIndex(HISTORY_INDEX, ["updatedAt", "rfqId"]);
126
+ }
127
+ if (rfq.indexNames.contains(LEGACY_STATE_ID_INDEX)) rfq.deleteIndex(LEGACY_STATE_ID_INDEX);
3445
128
  }
3446
129
  var IndexedDbAssetSwapRepository = class {
3447
130
  version = 5;
@@ -3469,8 +152,8 @@ var IndexedDbAssetSwapRepository = class {
3469
152
  store.put(swap);
3470
153
  });
3471
154
  }
3472
- async getAllSwaps() {
3473
- return promisifyRequest((await this.readStore(STORE_SWAPS)).getAll());
155
+ async getAssetSwapsPage(page) {
156
+ return this.pageStore(STORE_SWAPS, page);
3474
157
  }
3475
158
  async saveRfqSwap(record) {
3476
159
  await this.write(STORE_RFQ_SWAPS, (store) => {
@@ -3480,8 +163,44 @@ var IndexedDbAssetSwapRepository = class {
3480
163
  async getRfqSwap(rfqId) {
3481
164
  return promisifyRequest((await this.readStore(STORE_RFQ_SWAPS)).get(rfqId));
3482
165
  }
3483
- async getAllRfqSwaps() {
3484
- return promisifyRequest((await this.readStore(STORE_RFQ_SWAPS)).getAll());
166
+ async getRfqSwapsPage(filter, page) {
167
+ assertPageRequest(page);
168
+ assertRfqSwapPageFilter(filter);
169
+ const store = await this.readStore(STORE_RFQ_SWAPS);
170
+ const state = filter.state;
171
+ const index = store.index(state === void 0 ? HISTORY_INDEX : STATE_HISTORY_INDEX);
172
+ const after = page.after;
173
+ const useAfter = after !== void 0 && after.updatedAt >= (filter.since ?? 0);
174
+ const start = state === void 0 ? [] : [state];
175
+ const range = useAfter ? IDBKeyRange.lowerBound([...start, after.updatedAt, after.rfqId], true) : IDBKeyRange.lowerBound([...start, filter.since ?? 0]);
176
+ const request = index.openCursor(range);
177
+ return new Promise((resolve, reject) => {
178
+ const rows = [];
179
+ request.onerror = () => reject(request.error);
180
+ request.onsuccess = () => {
181
+ const cursor = request.result;
182
+ if (!cursor || state !== void 0 && cursor.key[0] !== state) {
183
+ resolve(
184
+ pageResult(rows, page.limit, (row) => ({
185
+ updatedAt: row.updatedAt,
186
+ rfqId: row.rfqId
187
+ }))
188
+ );
189
+ return;
190
+ }
191
+ rows.push(cursor.value);
192
+ if (rows.length > page.limit) {
193
+ resolve(
194
+ pageResult(rows, page.limit, (row) => ({
195
+ updatedAt: row.updatedAt,
196
+ rfqId: row.rfqId
197
+ }))
198
+ );
199
+ return;
200
+ }
201
+ cursor.continue();
202
+ };
203
+ });
3485
204
  }
3486
205
  async removeRfqSwap(rfqId) {
3487
206
  await this.write(STORE_RFQ_SWAPS, (store) => {
@@ -3496,8 +215,38 @@ var IndexedDbAssetSwapRepository = class {
3496
215
  async getSwapRecord(id) {
3497
216
  return promisifyRequest((await this.readStore(STORE_SWAP_RECORDS)).get(id));
3498
217
  }
3499
- async getAllSwapRecords() {
3500
- return promisifyRequest((await this.readStore(STORE_SWAP_RECORDS)).getAll());
218
+ async getSwapRecordsPage(page) {
219
+ return this.pageStore(STORE_SWAP_RECORDS, page);
220
+ }
221
+ async pageStore(name, page) {
222
+ assertPageRequest(page);
223
+ const store = await this.readStore(name);
224
+ const range = page.after === void 0 ? void 0 : IDBKeyRange.lowerBound(page.after, true);
225
+ const request = store.openCursor(range);
226
+ return new Promise((resolve, reject) => {
227
+ const rows = [];
228
+ request.onerror = () => reject(request.error);
229
+ request.onsuccess = () => {
230
+ const cursor = request.result;
231
+ if (!cursor) {
232
+ resolve(this.resultOfPage(rows, page.limit));
233
+ return;
234
+ }
235
+ rows.push({ key: cursor.key, value: cursor.value });
236
+ if (rows.length > page.limit) {
237
+ resolve(this.resultOfPage(rows, page.limit));
238
+ return;
239
+ }
240
+ cursor.continue();
241
+ };
242
+ });
243
+ }
244
+ resultOfPage(rows, limit) {
245
+ const result = pageResult(rows, limit, (row) => row.key);
246
+ return {
247
+ items: result.items.map((row) => row.value),
248
+ ...result.nextCursor === void 0 ? {} : { nextCursor: result.nextCursor }
249
+ };
3501
250
  }
3502
251
  async removeSwapRecord(id) {
3503
252
  await this.write(STORE_SWAP_RECORDS, (store) => {
@@ -3539,117 +288,6 @@ var IndexedDbAssetSwapRepository = class {
3539
288
 
3540
289
  // src/payment/lightning.ts
3541
290
  import { assertNoAssets, assetsOf, invoiceTarget } from "@arkade-os/sdk";
3542
-
3543
- // src/payment/swapRail.ts
3544
- import { makeHandle } from "@arkade-os/sdk";
3545
-
3546
- // src/payment/status.ts
3547
- var PAYMENT_STATUS = {
3548
- /** Persisted, funding not broadcast. */
3549
- accepted: "pending",
3550
- funding: "pending",
3551
- /** The lockup is funded. Nothing has emitted `"sent"` in core since the
3552
- * `onchain-swap` rail left with `packages/boltz-swap`. */
3553
- funded: "sent",
3554
- /** Asset swaps only: an unfilled offer. */
3555
- open: "pending",
3556
- /** Asset swaps only. */
3557
- filled: "settled",
3558
- /** The trader's L1 claim on `arkade -> onchain`. */
3559
- claimed: "settled",
3560
- /** Terminal success on `arkade -> lightning`: the solver's hash-verified
3561
- * spend IS the invoice being paid. */
3562
- paid: "settled",
3563
- cancelling: "pending",
3564
- /** Value returned, and the router has no non-loss terminal to say so with. */
3565
- cancelled: "failed",
3566
- /** Terminal HERE, not at `refunded` — see the module docblock. */
3567
- refunding: "failed",
3568
- /** The trader's value came back. Reaches `onUpdate`, not the handle. */
3569
- refunded: "failed",
3570
- /** The solver reclaimed a receive-leg lockup: a loss, and not `refunded`. */
3571
- lapsed: "failed",
3572
- /** Never retried silently; `client.recover` drives it. */
3573
- needs_recovery: "failed",
3574
- failed: "failed"
3575
- };
3576
- var paymentStatusOf = (outcome) => PAYMENT_STATUS[outcome];
3577
- var isTerminalStatus = (status) => status === "settled" || status === "failed";
3578
-
3579
- // src/payment/swapRail.ts
3580
- var SwapPaymentFailedError = class extends Error {
3581
- constructor(railId, outcome, swap) {
3582
- super(
3583
- `${railId}: swap ${swap.id} ended ${outcome}` + (swap.failure === void 0 ? "" : `: ${swap.failure}`) + (swap.blockedReason === void 0 ? "" : ` (${swap.blockedReason})`)
3584
- );
3585
- this.railId = railId;
3586
- this.outcome = outcome;
3587
- this.swap = swap;
3588
- }
3589
- railId;
3590
- outcome;
3591
- swap;
3592
- name = "SwapPaymentFailedError";
3593
- };
3594
- var unroutable = (error) => isSwapError(error, "UnsupportedRoute") || isSwapError(error, "AmbiguousDestination");
3595
- var railAvailable = async (client, input) => {
3596
- try {
3597
- return (await client.resolve(input)).eligible > 0;
3598
- } catch (error) {
3599
- if (unroutable(error)) return false;
3600
- throw error;
3601
- }
3602
- };
3603
- var receiverExact = (railId, parts) => {
3604
- if (parts.total !== parts.amount + parts.fee) {
3605
- throw new Error(
3606
- `${railId}: ${parts.total} leaving the wallet is not ${parts.amount} delivered plus ${parts.fee} in fees \u2014 the quote is not receiver-exact`
3607
- );
3608
- }
3609
- return {
3610
- amount: satsOf(parts.amount, `${railId}.amount`),
3611
- fee: satsOf(parts.fee, `${railId}.fee`),
3612
- total: satsOf(parts.total, `${railId}.total`)
3613
- };
3614
- };
3615
- var resultOf = (railId, swap) => ({
3616
- railId,
3617
- // The tagged public form M6 minted — round-trippable to `client.swaps()`,
3618
- // which is where the outcomes past this handle's terminal one are read.
3619
- swapId: swap.id,
3620
- // The transaction that left THIS wallet, which is what `txid` means on
3621
- // every other rail. A swap's later legs — the solver's fill, the trader's
3622
- // L1 claim — are the client's to report, not the handle's.
3623
- ...swap.fundingTxid === void 0 ? {} : { txid: swap.fundingTxid }
3624
- });
3625
- var swapHandle = async (railId, client, quote) => makeHandle(railId, async (emit) => {
3626
- const accepted = await client.accept(quote);
3627
- return await new Promise((resolve, reject) => {
3628
- let finished = false;
3629
- let unsubscribe;
3630
- const listener = (update) => {
3631
- if (finished || update.swap.id !== accepted.id) return;
3632
- const status = paymentStatusOf(update.outcome);
3633
- const result = resultOf(railId, update.swap);
3634
- if (!isTerminalStatus(status)) {
3635
- emit({ status, result });
3636
- return;
3637
- }
3638
- finished = true;
3639
- unsubscribe?.();
3640
- if (status === "settled") {
3641
- emit({ status, result });
3642
- resolve(result);
3643
- return;
3644
- }
3645
- reject(new SwapPaymentFailedError(railId, update.outcome, update.swap));
3646
- };
3647
- unsubscribe = client.onUpdate(listener);
3648
- if (finished) unsubscribe();
3649
- });
3650
- });
3651
-
3652
- // src/payment/lightning.ts
3653
291
  var LIGHTNING_RAIL = "lightning";
3654
292
  var inputFor = (invoice, amount) => ({
3655
293
  to: invoice,
@@ -3658,8 +296,7 @@ var inputFor = (invoice, amount) => ({
3658
296
  function lightningRail(client) {
3659
297
  return {
3660
298
  id: LIGHTNING_RAIL,
3661
- // Amount-blind and non-throwing: classification only, which is what
3662
- // keeps `match` from being a second gate on top of `available`.
299
+ // classification only, so `match` is not a second gate on top of `available`
3663
300
  match: (req) => invoiceTarget(req.raw) !== void 0,
3664
301
  available: async (req) => {
3665
302
  if (assetsOf(req).length > 0) return false;
@@ -3682,102 +319,15 @@ function lightningRail(client) {
3682
319
  return {
3683
320
  railId: LIGHTNING_RAIL,
3684
321
  ...amounts,
3685
- meta: {
3686
- quoteId: quote.id,
3687
- // A `RouteQuote` carries no expiry of its own, so a held one
3688
- // can outlive the terms behind it. This is where a caller
3689
- // can see that; `send()` refuses with `QuoteExpired` rather
3690
- // than silently re-quoting.
3691
- expiresAt: quote.expiresAt,
3692
- ...quote.refundLocktime === void 0 ? {} : { refundLocktime: quote.refundLocktime },
3693
- ...quote.solver === void 0 ? {} : { solver: quote.solver },
3694
- ...quote.lock === void 0 ? {} : { paymentHash: quote.lock.hash },
3695
- market: quote.market.key
3696
- },
322
+ meta: quoteMeta(quote),
3697
323
  send: () => swapHandle(LIGHTNING_RAIL, client, quote)
3698
324
  };
3699
325
  }
3700
326
  };
3701
327
  }
3702
328
 
3703
- // src/payment/onchainSwap.ts
3704
- import {
3705
- assertNoAssets as assertNoAssets2,
3706
- assetsOf as assetsOf2,
3707
- btcTarget,
3708
- resolveSendAmount as resolveSendAmount2,
3709
- tryResolveSendAmount
3710
- } from "@arkade-os/sdk";
3711
- var ONCHAIN_SWAP_RAIL = "onchain-swap";
3712
- var claimFeeSats = (deps) => BigInt(Math.ceil((deps.claimVsize ?? ONCHAIN_CLAIM_VSIZE) * deps.claimFeeRateSatVb));
3713
- function onchainSwapRail(client, deps) {
3714
- if (!Number.isFinite(deps.claimFeeRateSatVb) || deps.claimFeeRateSatVb <= 0) {
3715
- throw new Error(
3716
- `${ONCHAIN_SWAP_RAIL}: claimFeeRateSatVb must be positive, got ${deps.claimFeeRateSatVb}`
3717
- );
3718
- }
3719
- const claimFee = claimFeeSats(deps);
3720
- const inputFor2 = (address, amount) => ({
3721
- to: address,
3722
- amount: BigInt(amount) + claimFee,
3723
- amountOn: "take"
3724
- });
3725
- return {
3726
- id: ONCHAIN_SWAP_RAIL,
3727
- match: (req) => btcTarget(req.raw) !== void 0,
3728
- available: async (req) => {
3729
- if (assetsOf2(req).length > 0) return false;
3730
- const address = btcTarget(req.raw);
3731
- if (address === void 0) return false;
3732
- const amount = tryResolveSendAmount(req.raw, req.amount);
3733
- if (amount === void 0) return false;
3734
- if (BigInt(amount) < ONCHAIN_DUST_SATS) return false;
3735
- return railAvailable(client, inputFor2(address, amount));
3736
- },
3737
- quote: async (req) => {
3738
- const address = btcTarget(req.raw);
3739
- if (address === void 0) {
3740
- throw new Error(`${ONCHAIN_SWAP_RAIL}: the request carries no bitcoin address`);
3741
- }
3742
- assertNoAssets2(ONCHAIN_SWAP_RAIL, req);
3743
- const amount = resolveSendAmount2(ONCHAIN_SWAP_RAIL, req.raw, req.amount);
3744
- const quote = await client.quote(inputFor2(address, amount));
3745
- const payout = quote.take.amount - claimFee;
3746
- if (payout < ONCHAIN_DUST_SATS) {
3747
- throw new Error(
3748
- `${ONCHAIN_SWAP_RAIL}: the solver's take leg of ${quote.take.amount} sat leaves ${payout} sat after the ${claimFee} sat claim fee, under the ${ONCHAIN_DUST_SATS} sat dust limit the claim is built against`
3749
- );
3750
- }
3751
- const amounts = receiverExact(ONCHAIN_SWAP_RAIL, {
3752
- amount: payout,
3753
- // Both halves of the cost, inside one number: the solver's
3754
- // spread, and the claim the trader pays for out of the payout.
3755
- fee: quote.fee.amount + claimFee,
3756
- total: quote.give.amount
3757
- });
3758
- return {
3759
- railId: ONCHAIN_SWAP_RAIL,
3760
- ...amounts,
3761
- meta: {
3762
- quoteId: quote.id,
3763
- expiresAt: quote.expiresAt,
3764
- ...quote.refundLocktime === void 0 ? {} : { refundLocktime: quote.refundLocktime },
3765
- ...quote.solver === void 0 ? {} : { solver: quote.solver },
3766
- ...quote.lock === void 0 ? {} : { paymentHash: quote.lock.hash },
3767
- market: quote.market.key,
3768
- // The estimate folded into `fee`, so a caller can see it.
3769
- claimFeeSats: Number(claimFee),
3770
- // What the solver locks on L1, before the claim's fee.
3771
- htlcAmountSats: Number(quote.take.amount)
3772
- },
3773
- send: () => swapHandle(ONCHAIN_SWAP_RAIL, client, quote)
3774
- };
3775
- }
3776
- };
3777
- }
3778
-
3779
329
  // src/payment/router.ts
3780
- import { PaymentRouter as Router, arkRail, onchainRail } from "@arkade-os/sdk";
330
+ import { PaymentRouter as Router, arkRail, onchainRail, walletFeeSource } from "@arkade-os/sdk";
3781
331
  var SWAP_ROUTER_PRIORITY = [
3782
332
  "ark",
3783
333
  LIGHTNING_RAIL,
@@ -3788,15 +338,9 @@ function createSwapPaymentRouter(wallet, client, config) {
3788
338
  return new Router({
3789
339
  wallet,
3790
340
  prefs: { priority: [...SWAP_ROUTER_PRIORITY], ...config.prefs }
3791
- }).use(arkRail()).use(onchainRail()).use(lightningRail(client)).use(
3792
- onchainSwapRail(client, {
3793
- claimFeeRateSatVb: config.claimFeeRateSatVb,
3794
- ...config.claimVsize === void 0 ? {} : { claimVsize: config.claimVsize }
3795
- })
3796
- );
341
+ }).use(arkRail()).use(onchainRail({ feeInfo: walletFeeSource(wallet) })).use(lightningRail(client)).use(onchainSwapRail(client, config));
3797
342
  }
3798
343
  export {
3799
- ACTIVITY_TOKEN,
3800
344
  ARKADE_ASSET_NAMESPACE,
3801
345
  AcceptConflict,
3802
346
  AmbiguousDestination,
@@ -3807,154 +351,70 @@ export {
3807
351
  AssetIdError,
3808
352
  BITCOIN_RAILS,
3809
353
  BTC_ASSET_PART,
3810
- CORRIDORS,
3811
- CORRIDOR_FACTORIES,
3812
- CORRIDOR_PASS,
354
+ CLAIM_PACKET_TYPE,
3813
355
  ClientDisposed,
3814
- DEFAULT_INVOICE_EXPIRY_SECONDS,
3815
356
  DiscoverySnapshotUnavailable,
3816
- FEED_TTL_MS,
3817
- INDEXED_NETWORKS,
3818
- INVOICE_HRPS,
3819
357
  InMemoryAssetSwapRepository,
3820
358
  InconsistentRoute,
3821
359
  IndexedDbAssetSwapRepository,
3822
360
  InsufficientFunds,
3823
- LIGHTNING_DRIVE,
3824
361
  LIGHTNING_RAIL,
3825
- LOCKUP_OWNER,
362
+ LockupRegistrationFailed,
3826
363
  MaxFeeExceeded,
3827
364
  MissingCorridorDep,
3828
365
  NotCancellable,
3829
- OFFER_SWAP_ID_PREFIX,
3830
- ONCHAIN_DRIVE,
3831
366
  ONCHAIN_SWAP_RAIL,
3832
367
  OperatorUnreachable,
3833
368
  PAYMENT_STATUS,
3834
369
  QuoteExpired,
3835
370
  QuoteVerificationFailed,
3836
371
  RAILS,
3837
- RFQ_SWAP_ID_PREFIX,
372
+ REGISTRY_URL,
373
+ RFQ_REFUSAL_ERROR_CODES,
374
+ SEALED_CIPHERTEXT_LENGTH,
3838
375
  SWAP_ERROR_NAMES,
3839
376
  SWAP_ROUTER_PRIORITY,
3840
377
  SwapDriveRefusedError,
3841
378
  SwapPaymentFailedError,
3842
379
  SwapRefusal,
3843
380
  UnsupportedRoute,
3844
- acceptQuote,
3845
- aliasTableFrom,
3846
- applyOfferSpend,
381
+ appendArkadeScript,
3847
382
  arkadeAsset,
3848
- arkadeCorridor,
3849
- artifactOf,
3850
- assembleRoute,
3851
383
  assetPartOf,
3852
384
  assetSwapIdOf,
3853
- attesting,
3854
385
  bitcoinNetworkOf,
386
+ btcAssetPart,
3855
387
  btcOn,
3856
388
  canonicalAssetId,
3857
- cardMarketOf,
3858
- chainSourceOver,
3859
- chooseMarket,
3860
389
  claimFeeSats,
3861
- conflictingFields,
3862
- corridorOfRail,
3863
- corridorOutcome,
3864
- corridorRecordStore,
3865
- corridorSet,
390
+ claimPacketShape,
3866
391
  createSwapClient,
3867
- createSwapDrive,
3868
392
  createSwapPaymentRouter,
3869
- decodeBolt11,
3870
- decodeRfqAmount,
3871
- discoveryIndex,
3872
- eligibleMarkets,
3873
- encodeRfqAmount,
3874
- enforceFeeCeiling,
3875
- esploraChainSource,
3876
- esploraTip,
3877
393
  exchange,
3878
394
  familyOfSwapId,
3879
- feedFetch,
3880
395
  formatAssetId,
3881
396
  fromAtomicDecimal,
3882
- fromRfqAmountSide,
3883
- fundsFromWallet,
3884
- instrumentOf,
3885
- isAddressable,
3886
397
  isAssetId,
3887
398
  isAtomicDecimal,
3888
- isCardMarket,
3889
- isIndexedNetwork,
399
+ isBtcAsset,
400
+ isBtcAssetLenient,
3890
401
  isNetworkRef,
402
+ isRfqRefusalErrorCode,
403
+ isRfqSwapTerminal,
3891
404
  isSwapError,
3892
405
  isTerminalStatus,
3893
- isUsableCard,
3894
406
  issuanceOf,
3895
- legOf,
3896
- lightningCorridor,
3897
407
  lightningRail,
3898
- liveArkadeInfo,
3899
- marketBackendOf,
3900
- marketKeyOf,
3901
- marketRefOf,
3902
- networksOfInvoiceHrp,
3903
- nostrTransportFactory,
3904
- offerFactsOf,
3905
- offerOutcome,
3906
- offerRecordSource,
3907
- onchainCorridor,
3908
408
  onchainSwapRail,
3909
409
  parseAssetId,
3910
- parseRfqQuote,
3911
410
  pay,
3912
411
  paymentStatusOf,
3913
- publicAssetId,
3914
- quoteFromFeed,
3915
412
  quoteIdOfSwapId,
3916
- quoteViaRfq,
3917
413
  railAvailable,
3918
414
  railOf,
3919
- railOfCorridor,
3920
- readableRecord,
3921
- readsChain,
3922
415
  receive,
3923
416
  receiverExact,
3924
- recordArtifact,
3925
- recordEndpoint,
3926
- recordInstrument,
3927
- recordLeg,
3928
- recordOutcome,
3929
- resolveCorridorBase,
3930
- resolveCorridorDeps,
3931
- resolveRoute,
3932
- rfqLeg,
3933
- rfqPairFor,
3934
- rfqRecordOf,
3935
417
  sameAsset,
3936
- satsOf,
3937
- scopedToRail,
3938
- splitRecords,
3939
418
  swapHandle,
3940
- swapOf,
3941
- swapRecordOf,
3942
- toAtomicDecimal,
3943
- toDiscoveryLeg,
3944
- toRfqAmountSide,
3945
- toSafeNumber,
3946
- usableMarkets,
3947
- verifyPair,
3948
- verifyQuoteTtl,
3949
- verifyQuotedAmount,
3950
- verifyReceiveInvoiceFacts,
3951
- verifyReceiveWindow,
3952
- verifyResponder,
3953
- verifySendInvoice,
3954
- verifySendWindow,
3955
- verifyingDerivation,
3956
- walletLockupIndexer,
3957
- withCanonicalAmount,
3958
- withOfferStatus,
3959
- withRfqState
419
+ toAtomicDecimal
3960
420
  };