@arkade-os/swap 0.1.0-rc.9 → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +261 -252
- package/dist/advanced.cjs +6376 -3097
- package/dist/advanced.d.cts +325 -282
- package/dist/advanced.d.ts +325 -282
- package/dist/advanced.js +343 -34
- package/dist/chunk-A3SHHRX4.js +104 -0
- package/dist/chunk-FMRAV77W.js +3065 -0
- package/dist/{chunk-NS3K6BZG.js → chunk-HRMWBULL.js} +1746 -628
- package/dist/chunk-WKJFXXSR.js +3382 -0
- package/dist/index.cjs +6809 -3915
- package/dist/index.d.cts +71 -243
- package/dist/index.d.ts +71 -243
- package/dist/index.js +131 -167
- package/dist/lockupContract-D7BNjksX.d.ts +148 -0
- package/dist/lockupContract-G-9CNRMq.d.cts +148 -0
- package/dist/node/index.cjs +61 -10
- package/dist/node/index.d.cts +307 -635
- package/dist/node/index.d.ts +307 -635
- package/dist/node/index.js +65 -10
- package/dist/nostr.cjs +427 -49
- package/dist/nostr.d.cts +59 -70
- package/dist/nostr.d.ts +59 -70
- package/dist/nostr.js +268 -36
- package/dist/offer-CcJfx5Fj.d.cts +269 -0
- package/dist/offer-DdB1M6FZ.d.ts +269 -0
- package/dist/offerFillPlan-BII0PW92.d.cts +1642 -0
- package/dist/offerFillPlan-CNTLVD7j.d.ts +1642 -0
- package/dist/protocol.cjs +5650 -4280
- package/dist/protocol.d.cts +258 -328
- package/dist/protocol.d.ts +258 -328
- package/dist/protocol.js +200 -224
- package/dist/repositories/realm/index.cjs +55 -11
- package/dist/repositories/realm/index.d.cts +18 -30
- package/dist/repositories/realm/index.d.ts +18 -30
- package/dist/repositories/realm/index.js +49 -12
- package/dist/repositories/sqlite/index.cjs +61 -10
- package/dist/repositories/sqlite/index.d.cts +7 -6
- package/dist/repositories/sqlite/index.d.ts +7 -6
- package/dist/repositories/sqlite/index.js +57 -11
- package/dist/repository-DmPzpbd7.d.ts +2342 -0
- package/dist/repository-DqdLVrVv.d.cts +2342 -0
- package/dist/{rfq-BO6o7NwS.d.ts → rfq-C0tHOvn6.d.cts} +323 -444
- package/dist/{rfq-BO6o7NwS.d.cts → rfq-C0tHOvn6.d.ts} +323 -444
- package/dist/watch-BonYT9af.d.cts +74 -0
- package/dist/watch-CmJQDtsy.d.ts +74 -0
- package/package.json +10 -10
- package/dist/chunk-JFKGMPMH.js +0 -3456
- package/dist/chunk-LLG7RD2T.js +0 -1499
- package/dist/chunk-U7VWWTL6.js +0 -66
- package/dist/errors-CNISbN0M.d.ts +0 -2218
- package/dist/errors-DwNhIP0N.d.cts +0 -2218
- package/dist/lockupContract-C8-Mcg69.d.ts +0 -664
- package/dist/lockupContract-mIt4syse.d.cts +0 -664
- package/dist/repository-CGPLbjBe.d.ts +0 -3489
- package/dist/repository-DSGGq0ct.d.cts +0 -3489
- package/dist/watch-DWyVqyEN.d.cts +0 -96
- package/dist/watch-DmvHNX6T.d.ts +0 -96
|
@@ -1,21 +1,26 @@
|
|
|
1
1
|
import {
|
|
2
|
-
|
|
2
|
+
DEGRADED_RETRY_MS,
|
|
3
3
|
LOCKUP_OWNER,
|
|
4
4
|
LockupNeedsRecoveryError,
|
|
5
5
|
MARKETS_CACHE_TTL_MS,
|
|
6
|
-
|
|
7
|
-
OFFER_PACKET_TYPE,
|
|
8
|
-
OfferCovenantMismatchError,
|
|
6
|
+
PAYMENT_HASH,
|
|
9
7
|
QUOTE_OPTIONS,
|
|
10
|
-
RETIRABLE,
|
|
11
8
|
RefundNotLocallyPossibleError,
|
|
12
9
|
RfqSwapManager,
|
|
13
10
|
arkadeRefunder,
|
|
11
|
+
assertReceiverPaidEchoMatchesExpected,
|
|
12
|
+
assetPaymentFacts,
|
|
13
|
+
assetPaymentOf,
|
|
14
|
+
captureAssetPayment,
|
|
15
|
+
chainSourceFrom,
|
|
14
16
|
classifyDepositSpend,
|
|
15
17
|
corridorOutcome,
|
|
16
|
-
|
|
17
|
-
|
|
18
|
+
encodeCarrierRequest,
|
|
19
|
+
familyOfSwapId,
|
|
18
20
|
findLockupVtxos,
|
|
21
|
+
fromAtomicDecimal,
|
|
22
|
+
fundingWasNotSubmitted,
|
|
23
|
+
fundsFromWallet,
|
|
19
24
|
isRfqConfigurationRefusal,
|
|
20
25
|
isRfqSwapTerminal,
|
|
21
26
|
lightningCorridor,
|
|
@@ -23,43 +28,69 @@ import {
|
|
|
23
28
|
marketAssetId,
|
|
24
29
|
marketCorridor,
|
|
25
30
|
marketPairLabel,
|
|
31
|
+
normalizeRfqSwapRecord,
|
|
26
32
|
offerOutcome,
|
|
27
33
|
onchainCorridor,
|
|
34
|
+
onchainReceiveProfile,
|
|
28
35
|
onchainSendProfile,
|
|
29
|
-
|
|
30
|
-
|
|
36
|
+
parseCarrierEcho,
|
|
37
|
+
parseTopLevelCarrierSats,
|
|
31
38
|
pushClaim,
|
|
39
|
+
quoteIdOfSwapId,
|
|
32
40
|
readsChain,
|
|
33
41
|
rebuildRfqSwap,
|
|
42
|
+
recordArtifact,
|
|
43
|
+
recordAssetPayment,
|
|
44
|
+
recordEndpoint,
|
|
45
|
+
recordLeg,
|
|
34
46
|
recordOutcome,
|
|
47
|
+
registryAnswered,
|
|
35
48
|
restoreAssetSwaps,
|
|
36
|
-
retireOfferContract,
|
|
37
|
-
retireSettledOfferContracts,
|
|
38
|
-
rfqClaimDestinationOf,
|
|
39
|
-
rfqClaimSecretOf,
|
|
40
|
-
rfqSecretsProfile,
|
|
41
|
-
rfqSignerOf,
|
|
42
49
|
rfqSwapOriginOf,
|
|
43
50
|
senderIdentityForSwapRecord,
|
|
44
51
|
spendTxidsOf,
|
|
52
|
+
storedFundingBounds,
|
|
53
|
+
swapOf,
|
|
54
|
+
toAtomicDecimal,
|
|
55
|
+
toRestoreTx,
|
|
56
|
+
trackDelivery,
|
|
57
|
+
transportCardsOf,
|
|
58
|
+
undeliveredCarry,
|
|
45
59
|
walletOperator,
|
|
46
60
|
watchOfferSwaps
|
|
47
|
-
} from "./chunk-
|
|
61
|
+
} from "./chunk-WKJFXXSR.js";
|
|
48
62
|
import {
|
|
49
63
|
ARKADE_BTC,
|
|
64
|
+
ASSET_CARRIER_SATS,
|
|
50
65
|
AddressMismatch,
|
|
66
|
+
BTC_ASSET_ID,
|
|
51
67
|
L1_NETWORKS,
|
|
52
68
|
LIGHTNING_BTC,
|
|
69
|
+
LockupContractMissing,
|
|
70
|
+
NoSpendableDepositError,
|
|
71
|
+
OFFER_CONTRACT_KIND,
|
|
72
|
+
OFFER_PACKET_TYPE,
|
|
53
73
|
ONCHAIN_BTC,
|
|
54
74
|
ONCHAIN_CLAIM_VSIZE,
|
|
55
75
|
ONCHAIN_DUST_SATS,
|
|
76
|
+
OfferCovenantMismatchError,
|
|
77
|
+
RETIRABLE,
|
|
56
78
|
SwapRefusal,
|
|
79
|
+
arkadeSwapRequest,
|
|
80
|
+
assembleOfferFill,
|
|
57
81
|
assertFundable,
|
|
58
82
|
assertPairLength,
|
|
59
83
|
assertReceivable,
|
|
84
|
+
bindsClaimAmount,
|
|
85
|
+
buildHtlcRefund,
|
|
60
86
|
claimOnchainFill,
|
|
87
|
+
connectFillContract,
|
|
88
|
+
createOffer,
|
|
89
|
+
decodeOffer,
|
|
61
90
|
deriveLightningReceive,
|
|
62
91
|
deriveLightningSend,
|
|
92
|
+
deriveOffer,
|
|
93
|
+
deriveOnchainReceive,
|
|
63
94
|
deriveOnchainSend,
|
|
64
95
|
l1NetworkFromArk,
|
|
65
96
|
l1ScriptForAddress,
|
|
@@ -67,12 +98,38 @@ import {
|
|
|
67
98
|
lightningSendRequest,
|
|
68
99
|
lockupContractParams,
|
|
69
100
|
newRfqId,
|
|
101
|
+
nextClaimFeeRate,
|
|
102
|
+
offerTermsFromQuote,
|
|
103
|
+
onchainReceiveRequest,
|
|
70
104
|
onchainSendRequest,
|
|
105
|
+
preimageForSwapRecord,
|
|
106
|
+
prepareOfferCancel,
|
|
107
|
+
promoteOfferContract,
|
|
108
|
+
quoteCarrierSats,
|
|
109
|
+
registerDerivedOffer,
|
|
71
110
|
registerLockupContract,
|
|
111
|
+
resolveDeposit,
|
|
112
|
+
resolveReceivePkScript,
|
|
113
|
+
restoreOfferCoverage,
|
|
114
|
+
retireOfferContract,
|
|
115
|
+
retireSettledOfferContracts,
|
|
116
|
+
rfqClaimDestinationOf,
|
|
117
|
+
rfqClaimSecretOf,
|
|
72
118
|
rfqPair,
|
|
119
|
+
rfqSecretsProfile,
|
|
120
|
+
rfqSignerOf,
|
|
73
121
|
sealClaimPacket,
|
|
74
|
-
|
|
75
|
-
|
|
122
|
+
swapPrograms,
|
|
123
|
+
unilateralClaimDelay,
|
|
124
|
+
verifyOfferAddress,
|
|
125
|
+
withExitClosure
|
|
126
|
+
} from "./chunk-FMRAV77W.js";
|
|
127
|
+
import {
|
|
128
|
+
assertRfqSwapPageFilter,
|
|
129
|
+
collectAssetSwaps,
|
|
130
|
+
collectRfqSwaps,
|
|
131
|
+
collectSwapRecords
|
|
132
|
+
} from "./chunk-A3SHHRX4.js";
|
|
76
133
|
|
|
77
134
|
// src/client/assetId.ts
|
|
78
135
|
import { asset, networks } from "@arkade-os/sdk";
|
|
@@ -95,10 +152,8 @@ var REFERENCE_RULE = {
|
|
|
95
152
|
/** The 68-lowercase-hex identity form; `asset.AssetId` then re-validates it. */
|
|
96
153
|
asset: /^[0-9a-f]{68}$/,
|
|
97
154
|
/**
|
|
98
|
-
* Reserved for §9. Lowercase, never EIP-55:
|
|
99
|
-
*
|
|
100
|
-
* market card. Mixed case would be two spellings of one asset comparing
|
|
101
|
-
* unequal in a pair string, a record and a cache key.
|
|
155
|
+
* Reserved for §9. Lowercase, never EIP-55: mixed case would be two spellings of one asset
|
|
156
|
+
* comparing unequal in a pair string, a record and a cache key.
|
|
102
157
|
*/
|
|
103
158
|
erc20: /^0x[0-9a-f]{40}$/
|
|
104
159
|
};
|
|
@@ -210,11 +265,20 @@ var sameAsset = (a, b) => {
|
|
|
210
265
|
const right = parseAssetId(b);
|
|
211
266
|
return left.reference === right.reference && left.assetNamespace === right.assetNamespace && left.assetReference === right.assetReference;
|
|
212
267
|
};
|
|
268
|
+
var btcAssetPart = (network) => network === "bitcoin" ? "slip44:0" : "slip44:1";
|
|
213
269
|
var btcOn = (rail, network) => (
|
|
214
|
-
//
|
|
215
|
-
|
|
216
|
-
`${rail}:${network}/${BTC_ASSET_PART}`
|
|
270
|
+
// TS won't resolve the conditional against an unbound `R`; the cast stays in this expression.
|
|
271
|
+
`${rail}:${network}/${btcAssetPart(network)}`
|
|
217
272
|
);
|
|
273
|
+
var isBtcAsset = (id) => {
|
|
274
|
+
const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
|
|
275
|
+
return rail !== "eip155" && `${assetNamespace}:${assetReference}` === btcAssetPart(reference);
|
|
276
|
+
};
|
|
277
|
+
var isBtcAssetLenient = (id) => {
|
|
278
|
+
if (isBtcAsset(id)) return true;
|
|
279
|
+
const { rail, assetNamespace, assetReference } = parseAssetId(id);
|
|
280
|
+
return rail !== "eip155" && assetNamespace === "slip44" && assetReference === "0";
|
|
281
|
+
};
|
|
218
282
|
var arkadeAsset = (network, id) => `arkade:${network}/${ARKADE_ASSET_NAMESPACE}:${id.toString()}`;
|
|
219
283
|
var issuanceOf = (id) => {
|
|
220
284
|
const { assetNamespace, assetReference } = parseAssetId(id);
|
|
@@ -291,10 +355,10 @@ var QuoteExpired = class extends Error {
|
|
|
291
355
|
name = "QuoteExpired";
|
|
292
356
|
};
|
|
293
357
|
var MaxFeeExceeded = class extends Error {
|
|
294
|
-
constructor(quoteId,
|
|
295
|
-
super(`fee ${fee} of ${
|
|
358
|
+
constructor(quoteId, asset5, fee, maxFee) {
|
|
359
|
+
super(`fee ${fee} of ${asset5} exceeds the ${maxFee} ceiling`);
|
|
296
360
|
this.quoteId = quoteId;
|
|
297
|
-
this.asset =
|
|
361
|
+
this.asset = asset5;
|
|
298
362
|
this.fee = fee;
|
|
299
363
|
this.maxFee = maxFee;
|
|
300
364
|
}
|
|
@@ -305,11 +369,11 @@ var MaxFeeExceeded = class extends Error {
|
|
|
305
369
|
name = "MaxFeeExceeded";
|
|
306
370
|
};
|
|
307
371
|
var InsufficientFunds = class extends Error {
|
|
308
|
-
constructor(
|
|
372
|
+
constructor(asset5, required, available) {
|
|
309
373
|
super(
|
|
310
|
-
`funding needs ${required} of ${
|
|
374
|
+
`funding needs ${required} of ${asset5}` + (available === void 0 ? "" : `, wallet holds ${available}`)
|
|
311
375
|
);
|
|
312
|
-
this.asset =
|
|
376
|
+
this.asset = asset5;
|
|
313
377
|
this.required = required;
|
|
314
378
|
this.available = available;
|
|
315
379
|
}
|
|
@@ -347,9 +411,9 @@ var NotCancellable = class extends Error {
|
|
|
347
411
|
name = "NotCancellable";
|
|
348
412
|
};
|
|
349
413
|
var InconsistentRoute = class extends Error {
|
|
350
|
-
constructor(
|
|
351
|
-
super(`destination ${JSON.stringify(destination)} is not on ${
|
|
352
|
-
this.asset =
|
|
414
|
+
constructor(asset5, destination) {
|
|
415
|
+
super(`destination ${JSON.stringify(destination)} is not on ${asset5}'s chain`);
|
|
416
|
+
this.asset = asset5;
|
|
353
417
|
this.destination = destination;
|
|
354
418
|
}
|
|
355
419
|
asset;
|
|
@@ -402,25 +466,27 @@ function isSwapError(e, name) {
|
|
|
402
466
|
// src/client/aliases.ts
|
|
403
467
|
import { NETWORKS, isNetwork } from "@arkade-os/solver-discovery";
|
|
404
468
|
var toDiscoveryLeg = (id) => {
|
|
405
|
-
const { rail, assetNamespace, assetReference } = parseAssetId(id);
|
|
406
|
-
const
|
|
469
|
+
const { rail, reference, assetNamespace, assetReference } = parseAssetId(id);
|
|
470
|
+
const asset5 = `${assetNamespace}:${assetReference}`;
|
|
471
|
+
const isBtc = isBtcAsset(id);
|
|
472
|
+
if (!isBtc && rail !== "eip155" && (asset5 === "slip44:0" || asset5 === "slip44:1")) {
|
|
473
|
+
const expected = btcOn(rail, reference);
|
|
474
|
+
throw new UnsupportedRoute(`${id} is not BTC on ${reference}: BTC there is ${expected}`);
|
|
475
|
+
}
|
|
407
476
|
if (rail === "arkade") {
|
|
408
|
-
if (
|
|
409
|
-
return { corridor: "arkade", assetId: BTC_ASSET_ID, marketId: id };
|
|
477
|
+
if (isBtc) return { corridor: "arkade", assetId: BTC_ASSET_ID, marketId: id };
|
|
410
478
|
if (assetNamespace === ARKADE_ASSET_NAMESPACE) {
|
|
411
479
|
return { corridor: "arkade", assetId: assetReference, marketId: id };
|
|
412
480
|
}
|
|
413
|
-
throw new UnsupportedRoute(`the arkade corridor has no ${
|
|
481
|
+
throw new UnsupportedRoute(`the arkade corridor has no ${asset5}`);
|
|
414
482
|
}
|
|
415
483
|
if (rail === "bolt11") {
|
|
416
|
-
if (
|
|
417
|
-
|
|
418
|
-
throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset3}`);
|
|
484
|
+
if (isBtc) return { corridor: "lightning", assetId: BTC_ASSET_ID, marketId: id };
|
|
485
|
+
throw new UnsupportedRoute(`the lightning corridor carries BTC only, not ${asset5}`);
|
|
419
486
|
}
|
|
420
487
|
if (rail === "bitcoin") {
|
|
421
|
-
if (
|
|
422
|
-
|
|
423
|
-
throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset3}`);
|
|
488
|
+
if (isBtc) return { corridor: "onchain", assetId: BTC_ASSET_ID, marketId: id };
|
|
489
|
+
throw new UnsupportedRoute(`the onchain corridor carries BTC only, not ${asset5}`);
|
|
424
490
|
}
|
|
425
491
|
throw new UnsupportedRoute(`no corridor serves ${id}`);
|
|
426
492
|
};
|
|
@@ -451,115 +517,8 @@ var canonicalAssetId = (input, table) => {
|
|
|
451
517
|
return matches[0].id;
|
|
452
518
|
};
|
|
453
519
|
|
|
454
|
-
// src/client/amount.ts
|
|
455
|
-
import {
|
|
456
|
-
AMOUNT_PATTERN,
|
|
457
|
-
MAX_ASSET_DECIMALS,
|
|
458
|
-
fromAtomic,
|
|
459
|
-
isAmount,
|
|
460
|
-
toAtomic
|
|
461
|
-
} from "@arkade-os/solver-discovery";
|
|
462
|
-
var AmountFormatError = class extends Error {
|
|
463
|
-
constructor(reason, message) {
|
|
464
|
-
super(message);
|
|
465
|
-
this.reason = reason;
|
|
466
|
-
}
|
|
467
|
-
reason;
|
|
468
|
-
name = "AmountFormatError";
|
|
469
|
-
};
|
|
470
|
-
var SCALED_DECIMAL = /^([0-9]+)(?:\.([0-9]+))?$/;
|
|
471
|
-
var ATOMIC_CEILING = 10n ** 30n;
|
|
472
|
-
var MAX_SIGNIFICANT_DIGITS = 64;
|
|
473
|
-
var assertDecimals = (decimals) => {
|
|
474
|
-
if (!Number.isInteger(decimals) || decimals < 0 || decimals > MAX_ASSET_DECIMALS) {
|
|
475
|
-
throw new AmountFormatError(
|
|
476
|
-
"invalid_decimals",
|
|
477
|
-
`decimals must be an integer in [0, ${MAX_ASSET_DECIMALS}], got ${decimals}`
|
|
478
|
-
);
|
|
479
|
-
}
|
|
480
|
-
};
|
|
481
|
-
var assertRepresentable = (value, what) => {
|
|
482
|
-
if (value >= ATOMIC_CEILING) {
|
|
483
|
-
throw new AmountFormatError(
|
|
484
|
-
"too_large",
|
|
485
|
-
`${what} does not fit the canonical 30-digit encoding`
|
|
486
|
-
);
|
|
487
|
-
}
|
|
488
|
-
};
|
|
489
|
-
var Amount = {
|
|
490
|
-
/**
|
|
491
|
-
* A human decimal into atomic units.
|
|
492
|
-
*
|
|
493
|
-
* `string` only, and no exponent. Accepting a `number` is the whole v1
|
|
494
|
-
* footgun: it makes `100000` ambiguous between sats and whole BTC, and by
|
|
495
|
-
* the time the ambiguity resolves the offer is funded. Exponent form goes
|
|
496
|
-
* for the same reason — a UI never produces `1e-4`, so accepting it only
|
|
497
|
-
* widens what a mistake can look like.
|
|
498
|
-
*
|
|
499
|
-
* Refuses rather than rounds when the input is finer than the asset: a
|
|
500
|
-
* silently truncated amount is a swap for the wrong size, and nothing
|
|
501
|
-
* downstream can tell it was ever a different number. Refuses too when the
|
|
502
|
-
* result would not survive the record boundary, so one law holds in both
|
|
503
|
-
* directions.
|
|
504
|
-
*/
|
|
505
|
-
parse(display, asset3) {
|
|
506
|
-
assertDecimals(asset3.decimals);
|
|
507
|
-
const parts = SCALED_DECIMAL.exec(display);
|
|
508
|
-
if (!parts) {
|
|
509
|
-
throw new AmountFormatError(
|
|
510
|
-
"not_decimal",
|
|
511
|
-
`not an unsigned decimal amount: ${JSON.stringify(display)} (write 0.5, not .5; no sign, exponent, separator or space)`
|
|
512
|
-
);
|
|
513
|
-
}
|
|
514
|
-
const [, whole, fraction = ""] = parts;
|
|
515
|
-
if (fraction.length > asset3.decimals) {
|
|
516
|
-
throw new AmountFormatError(
|
|
517
|
-
"too_precise",
|
|
518
|
-
`${display} has more precision than ${asset3.decimals} decimals allow`
|
|
519
|
-
);
|
|
520
|
-
}
|
|
521
|
-
if (whole.length + fraction.length > MAX_SIGNIFICANT_DIGITS) {
|
|
522
|
-
throw new AmountFormatError("too_large", `${display} has too many digits`);
|
|
523
|
-
}
|
|
524
|
-
const value = toAtomic(display, asset3.decimals);
|
|
525
|
-
assertRepresentable(value, `${display} at ${asset3.decimals} decimals`);
|
|
526
|
-
return value;
|
|
527
|
-
},
|
|
528
|
-
/**
|
|
529
|
-
* Atomic units into a human decimal, trailing zeros trimmed.
|
|
530
|
-
*
|
|
531
|
-
* Refuses a negative: every amount on this surface is an obligation, and a
|
|
532
|
-
* negative one is a defect upstream rather than a number to render.
|
|
533
|
-
*/
|
|
534
|
-
format(value, asset3) {
|
|
535
|
-
assertDecimals(asset3.decimals);
|
|
536
|
-
if (value < 0n) {
|
|
537
|
-
throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
|
|
538
|
-
}
|
|
539
|
-
assertRepresentable(value, `${value}`);
|
|
540
|
-
return fromAtomic(value, asset3.decimals);
|
|
541
|
-
}
|
|
542
|
-
};
|
|
543
|
-
var toAtomicDecimal = (value) => {
|
|
544
|
-
if (value < 0n) {
|
|
545
|
-
throw new AmountFormatError("negative", `amount must be non-negative, got ${value}`);
|
|
546
|
-
}
|
|
547
|
-
assertRepresentable(value, `${value}`);
|
|
548
|
-
return value.toString();
|
|
549
|
-
};
|
|
550
|
-
var fromAtomicDecimal = (text) => {
|
|
551
|
-
if (!isAmount(text)) {
|
|
552
|
-
throw new AmountFormatError(
|
|
553
|
-
"not_canonical",
|
|
554
|
-
`not a canonical atomic amount: ${JSON.stringify(text)}`
|
|
555
|
-
);
|
|
556
|
-
}
|
|
557
|
-
return BigInt(text);
|
|
558
|
-
};
|
|
559
|
-
var isAtomicDecimal = (value) => typeof value === "string" && AMOUNT_PATTERN.test(value);
|
|
560
|
-
|
|
561
520
|
// src/client/rfqAmount.ts
|
|
562
|
-
import { isAmount
|
|
521
|
+
import { isAmount } from "@arkade-os/solver-discovery";
|
|
563
522
|
var toRfqAmountSide = (on) => on === "give" ? "from" : "to";
|
|
564
523
|
var fromRfqAmountSide = (side) => side === "from" ? "give" : "take";
|
|
565
524
|
var encodeRfqAmount = (value, field) => {
|
|
@@ -576,7 +535,7 @@ var encodeRfqAmount = (value, field) => {
|
|
|
576
535
|
};
|
|
577
536
|
var decodeRfqAmount = (raw, field) => {
|
|
578
537
|
if (typeof raw === "string") {
|
|
579
|
-
if (!
|
|
538
|
+
if (!isAmount(raw)) {
|
|
580
539
|
throw new AmountEncodingUnsupported(
|
|
581
540
|
field,
|
|
582
541
|
raw,
|
|
@@ -590,8 +549,6 @@ var decodeRfqAmount = (raw, field) => {
|
|
|
590
549
|
throw new AmountEncodingUnsupported(
|
|
591
550
|
field,
|
|
592
551
|
`${raw}`,
|
|
593
|
-
// Past 2^53 the number arrived already rounded — there is no
|
|
594
|
-
// "narrow carefully" branch, only a wrong amount.
|
|
595
552
|
"a JSON number amount is only readable as a non-negative safe integer"
|
|
596
553
|
);
|
|
597
554
|
}
|
|
@@ -614,109 +571,48 @@ var toSafeNumber = (value, field) => {
|
|
|
614
571
|
return Number(value);
|
|
615
572
|
};
|
|
616
573
|
|
|
617
|
-
// src/client/
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
}
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
...instrument.amount === void 0 ? {} : { amount: fromAtomicDecimal(instrument.amount) },
|
|
656
|
-
expiresAt: instrument.expiresAt
|
|
657
|
-
};
|
|
574
|
+
// src/client/accept.ts
|
|
575
|
+
import { hex as hex2 } from "@scure/base";
|
|
576
|
+
import { stableStringify } from "@arkade-os/solver-discovery";
|
|
577
|
+
import {
|
|
578
|
+
asset as asset2,
|
|
579
|
+
getAllNormalizedVtxos,
|
|
580
|
+
SendDeadlineExceededError
|
|
581
|
+
} from "@arkade-os/sdk";
|
|
582
|
+
|
|
583
|
+
// src/client/fundingNotSubmitted.ts
|
|
584
|
+
import { ArkAddress } from "@arkade-os/sdk";
|
|
585
|
+
import { hex } from "@scure/base";
|
|
586
|
+
var retireUnsubmittedFunding = async (wallet, repository, record, contracts) => {
|
|
587
|
+
if (!fundingWasNotSubmitted(record)) return;
|
|
588
|
+
const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
|
|
589
|
+
try {
|
|
590
|
+
await retireOfferContract(
|
|
591
|
+
contracts ?? await wallet.getContractManager(),
|
|
592
|
+
async () => {
|
|
593
|
+
const records = await collectSwapRecords(repository);
|
|
594
|
+
const native = records.map((row) => ({
|
|
595
|
+
id: row.id,
|
|
596
|
+
swapPkScript: row.family === "offer" ? row.swapPkScript : row.lockupPkScript,
|
|
597
|
+
createdAt: row.createdAt * 1e3,
|
|
598
|
+
status: row.family === "offer" ? row.status : fundingWasNotSubmitted(row) ? "cancelled" : row.state === "settled" || row.state === "refunded" ? "fulfilled" : "pending"
|
|
599
|
+
}));
|
|
600
|
+
const legacy = (await collectRfqSwaps(repository)).map((row) => ({
|
|
601
|
+
swapPkScript: hex.encode(ArkAddress.decode(row.lockupAddress).pkScript),
|
|
602
|
+
createdAt: row.createdAt * 1e3,
|
|
603
|
+
status: row.state === "settled" || row.state === "refunded" ? "fulfilled" : "pending"
|
|
604
|
+
}));
|
|
605
|
+
return [...native, ...legacy];
|
|
606
|
+
},
|
|
607
|
+
script,
|
|
608
|
+
{ scope: wallet }
|
|
609
|
+
);
|
|
610
|
+
} catch (error) {
|
|
611
|
+
console.warn(`[swap] could not retire unsent funding for ${record.id}`, error);
|
|
658
612
|
}
|
|
659
613
|
};
|
|
660
|
-
var recordArtifact = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
|
|
661
|
-
kind: "deposit",
|
|
662
|
-
corridor: artifact.corridor,
|
|
663
|
-
address: artifact.address,
|
|
664
|
-
asset: artifact.asset,
|
|
665
|
-
amount: toAtomicDecimal(artifact.amount),
|
|
666
|
-
...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
|
|
667
|
-
};
|
|
668
|
-
var artifactOf = (artifact) => artifact.kind === "invoice" ? { kind: "invoice", bolt11: artifact.bolt11 } : {
|
|
669
|
-
kind: "deposit",
|
|
670
|
-
corridor: artifact.corridor,
|
|
671
|
-
address: artifact.address,
|
|
672
|
-
asset: artifact.asset,
|
|
673
|
-
amount: fromAtomicDecimal(artifact.amount),
|
|
674
|
-
...artifact.expiresAt === void 0 ? {} : { expiresAt: artifact.expiresAt }
|
|
675
|
-
};
|
|
676
|
-
var recordLeg = (leg) => ({
|
|
677
|
-
asset: leg.asset,
|
|
678
|
-
amount: toAtomicDecimal(leg.amount)
|
|
679
|
-
});
|
|
680
|
-
var legOf = (leg) => ({
|
|
681
|
-
asset: leg.asset,
|
|
682
|
-
amount: fromAtomicDecimal(leg.amount)
|
|
683
|
-
});
|
|
684
|
-
var swapOf = (record, outcome) => ({
|
|
685
|
-
id: assetSwapIdOf(record.family, record.id),
|
|
686
|
-
family: record.family,
|
|
687
|
-
outcome,
|
|
688
|
-
route: {
|
|
689
|
-
give: {
|
|
690
|
-
corridor: record.route.give.corridor,
|
|
691
|
-
asset: record.route.give.asset,
|
|
692
|
-
instrument: instrumentOf(record.route.give.instrument)
|
|
693
|
-
},
|
|
694
|
-
take: {
|
|
695
|
-
corridor: record.route.take.corridor,
|
|
696
|
-
asset: record.route.take.asset,
|
|
697
|
-
instrument: instrumentOf(record.route.take.instrument)
|
|
698
|
-
}
|
|
699
|
-
},
|
|
700
|
-
give: legOf(record.give),
|
|
701
|
-
take: legOf(record.take),
|
|
702
|
-
fee: legOf(record.fee),
|
|
703
|
-
market: record.market,
|
|
704
|
-
...record.solver === void 0 ? {} : { solver: record.solver },
|
|
705
|
-
...record.family === "rfq" ? { lock: record.lock } : {},
|
|
706
|
-
...record.family === "rfq" ? { refundLocktime: record.refundLocktime } : {},
|
|
707
|
-
...record.artifact === void 0 ? {} : { artifact: artifactOf(record.artifact) },
|
|
708
|
-
expiresAt: record.expiresAt,
|
|
709
|
-
...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
|
|
710
|
-
...record.failure === void 0 ? {} : { failure: record.failure },
|
|
711
|
-
...record.blockedReason === void 0 ? {} : { blockedReason: record.blockedReason },
|
|
712
|
-
createdAt: record.createdAt,
|
|
713
|
-
updatedAt: record.updatedAt
|
|
714
|
-
});
|
|
715
|
-
var fundsFromWallet = (route) => route.give.instrument.kind === "wallet";
|
|
716
614
|
|
|
717
615
|
// src/client/accept.ts
|
|
718
|
-
import { hex } from "@scure/base";
|
|
719
|
-
import { asset as asset2, getAllNormalizedVtxos } from "@arkade-os/sdk";
|
|
720
616
|
var acceptLocks = /* @__PURE__ */ new Map();
|
|
721
617
|
var runSerialized = (id, body) => {
|
|
722
618
|
const tail = acceptLocks.get(id) ?? Promise.resolve();
|
|
@@ -751,6 +647,7 @@ var conflictingFields = (record, quote) => {
|
|
|
751
647
|
const incoming = recordedFacts(quote);
|
|
752
648
|
const stored = {
|
|
753
649
|
"route.pair": `${record.route.give.corridor}->${record.route.take.corridor}`,
|
|
650
|
+
assetPayment: assetPaymentFacts(record.assetPayment),
|
|
754
651
|
"give.asset": record.route.give.asset,
|
|
755
652
|
"take.asset": record.route.take.asset,
|
|
756
653
|
"give.amount": record.give.amount,
|
|
@@ -774,6 +671,9 @@ var conflictingFields = (record, quote) => {
|
|
|
774
671
|
};
|
|
775
672
|
var recordedFacts = (quote) => ({
|
|
776
673
|
"route.pair": `${quote.route.give.corridor}->${quote.route.take.corridor}`,
|
|
674
|
+
assetPayment: assetPaymentFacts(
|
|
675
|
+
quote.assetPayment === void 0 ? void 0 : recordAssetPayment(quote.assetPayment)
|
|
676
|
+
),
|
|
777
677
|
"give.asset": quote.route.give.asset,
|
|
778
678
|
"take.asset": quote.route.take.asset,
|
|
779
679
|
"give.amount": recordLeg(quote.give).amount,
|
|
@@ -789,21 +689,14 @@ var marketSourceOf = (market) => market.kind === "card" ? market.source : void 0
|
|
|
789
689
|
var assertFundable2 = async (wallet, quote) => {
|
|
790
690
|
const give = quote.give;
|
|
791
691
|
const balance = await wallet.getBalance();
|
|
792
|
-
|
|
793
|
-
const available2 = BigInt(balance.available);
|
|
794
|
-
if (available2 < give.amount) {
|
|
795
|
-
throw new InsufficientFunds(give.asset, give.amount, available2);
|
|
796
|
-
}
|
|
797
|
-
return;
|
|
798
|
-
}
|
|
799
|
-
const held = balance.availableAssets.find((a) => give.asset.endsWith(a.assetId));
|
|
800
|
-
const available = held?.amount ?? 0n;
|
|
692
|
+
const available = isBtcAsset(give.asset) ? BigInt(balance.available) : balance.availableAssets.find((a) => give.asset.endsWith(a.assetId))?.amount ?? 0n;
|
|
801
693
|
if (available < give.amount) {
|
|
802
694
|
throw new InsufficientFunds(give.asset, give.amount, available);
|
|
803
695
|
}
|
|
804
696
|
};
|
|
805
697
|
var commonOf = (quote, now) => ({
|
|
806
698
|
id: quote.id,
|
|
699
|
+
...quote.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(quote.assetPayment) },
|
|
807
700
|
route: {
|
|
808
701
|
give: recordEndpoint(quote.route.give),
|
|
809
702
|
take: recordEndpoint(quote.route.take)
|
|
@@ -826,24 +719,20 @@ var corridorRecord = (quote, preparation, now) => {
|
|
|
826
719
|
...commonOf(quote, now),
|
|
827
720
|
family: "rfq",
|
|
828
721
|
state: "pending",
|
|
829
|
-
kind:
|
|
722
|
+
kind: KIND_OF[preparation.route],
|
|
830
723
|
rfqId: preparation.rfqId,
|
|
831
724
|
lockupAddress: preparation.lockup.address,
|
|
832
|
-
lockupPkScript:
|
|
725
|
+
lockupPkScript: hex2.encode(preparation.lockup.pkScript),
|
|
833
726
|
lock: { hash: quote.lock.hash },
|
|
834
727
|
refundLocktime: quote.refundLocktime,
|
|
835
728
|
profile: profileOf(preparation, quote.lock.hash)
|
|
836
729
|
};
|
|
837
730
|
};
|
|
838
|
-
var
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
return "lightning_receive";
|
|
844
|
-
case "arkade->onchain":
|
|
845
|
-
return "onchain_send";
|
|
846
|
-
}
|
|
731
|
+
var KIND_OF = {
|
|
732
|
+
"arkade->lightning": "lightning_send",
|
|
733
|
+
"lightning->arkade": "lightning_receive",
|
|
734
|
+
"arkade->onchain": "onchain_send",
|
|
735
|
+
"onchain->arkade": "onchain_receive"
|
|
847
736
|
};
|
|
848
737
|
var profileOf = (preparation, paymentHash) => {
|
|
849
738
|
const secrets = rfqSecretsProfile(preparation.secrets, paymentHash);
|
|
@@ -864,9 +753,24 @@ var profileOf = (preparation, paymentHash) => {
|
|
|
864
753
|
htlcParams: preparation.htlcParams,
|
|
865
754
|
l1Network: preparation.l1Network,
|
|
866
755
|
minConfirmations: preparation.minConfirmations,
|
|
756
|
+
expectedAmount: toSafeNumber(preparation.expectedAmount, "expectedAmount"),
|
|
867
757
|
payoutPkScript: preparation.payoutPkScript
|
|
868
758
|
})
|
|
869
759
|
};
|
|
760
|
+
case "onchain->arkade":
|
|
761
|
+
return {
|
|
762
|
+
...secrets,
|
|
763
|
+
expectedAmount: toSafeNumber(preparation.expectedAmount, "expectedAmount"),
|
|
764
|
+
payoutAddress: preparation.payoutAddress,
|
|
765
|
+
...onchainReceiveProfile({
|
|
766
|
+
htlc: preparation.htlc,
|
|
767
|
+
htlcParams: preparation.htlcParams,
|
|
768
|
+
l1Network: preparation.l1Network,
|
|
769
|
+
minConfirmations: preparation.minConfirmations,
|
|
770
|
+
refundPkScript: preparation.refundPkScript,
|
|
771
|
+
refundDescriptor: preparation.refundKey.descriptor
|
|
772
|
+
})
|
|
773
|
+
};
|
|
870
774
|
}
|
|
871
775
|
};
|
|
872
776
|
var acceptQuote = async (input) => runSerialized(input.quote.id, () => acceptQuoteBody(input));
|
|
@@ -881,6 +785,7 @@ var acceptQuoteBody = async (input) => {
|
|
|
881
785
|
if (fields.length > 0) {
|
|
882
786
|
throw new AcceptConflict(quote.id, stored.id, fields);
|
|
883
787
|
}
|
|
788
|
+
if (fundingWasNotSubmitted(stored)) return answer(stored);
|
|
884
789
|
if (stored.fundingTxid !== void 0) return answer(stored);
|
|
885
790
|
if (!fundsFromWallet(stored.route)) return answer(stored);
|
|
886
791
|
const found = await reconcileFunding({ wallet }, stored);
|
|
@@ -888,7 +793,13 @@ var acceptQuoteBody = async (input) => {
|
|
|
888
793
|
return answer(await stampFunding(repository, stored, found, now));
|
|
889
794
|
}
|
|
890
795
|
if (expired) throw new QuoteExpired(quote.id, quote.expiresAt, now);
|
|
891
|
-
return answer(
|
|
796
|
+
return answer(
|
|
797
|
+
await fundAndStamp(
|
|
798
|
+
{ wallet, now, validUntil: input.validUntil, drive: input.drive },
|
|
799
|
+
stored,
|
|
800
|
+
repository
|
|
801
|
+
)
|
|
802
|
+
);
|
|
892
803
|
}
|
|
893
804
|
if (expired) throw new QuoteExpired(quote.id, quote.expiresAt, now);
|
|
894
805
|
const preparation = input.preparation;
|
|
@@ -899,39 +810,117 @@ var acceptQuoteBody = async (input) => {
|
|
|
899
810
|
}
|
|
900
811
|
const funds = fundsFromWallet(quote.route);
|
|
901
812
|
if (funds) await assertFundable2(wallet, quote);
|
|
902
|
-
const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
|
|
813
|
+
const record = preparation.backend === "feed" ? await registeredOfferRecord(input, preparation) : preparation.route === "arkade->arkade" ? await registeredAssetRecord(input, preparation) : await registeredCorridorRecord(input, preparation);
|
|
903
814
|
await repository.saveSwapRecord(record);
|
|
904
815
|
if (!funds) return answer(record);
|
|
905
|
-
return answer(
|
|
816
|
+
return answer(
|
|
817
|
+
await fundAndStamp(
|
|
818
|
+
{
|
|
819
|
+
wallet,
|
|
820
|
+
now,
|
|
821
|
+
validUntil: input.validUntil,
|
|
822
|
+
drive: input.drive,
|
|
823
|
+
firstFundingAttempt: true
|
|
824
|
+
},
|
|
825
|
+
record,
|
|
826
|
+
repository
|
|
827
|
+
)
|
|
828
|
+
);
|
|
906
829
|
};
|
|
907
830
|
var registeredOfferRecord = async (input, preparation) => {
|
|
908
831
|
const { quote, wallet, corridors, now } = input;
|
|
909
832
|
const { plan } = preparation;
|
|
910
|
-
const
|
|
833
|
+
const arkade2 = corridors.get("arkade").deps;
|
|
911
834
|
const receiveIsBtc = plan.receive.asset.id === BTC_ASSET_ID;
|
|
912
|
-
const offer = await createOffer(
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
835
|
+
const offer = await createOffer(
|
|
836
|
+
wallet,
|
|
837
|
+
{
|
|
838
|
+
// Keyed on the receive side: the covenant binds what the fill delivers.
|
|
839
|
+
wantAmount: plan.receive.atomic,
|
|
840
|
+
...receiveIsBtc ? { offerAsset: asset2.AssetId.fromString(plan.deposit.asset.id) } : { wantAsset: asset2.AssetId.fromString(plan.receive.asset.id) },
|
|
841
|
+
emulatorPubkey: arkade2.emulatorPubkey
|
|
842
|
+
},
|
|
843
|
+
{ coverageId: quote.id }
|
|
844
|
+
);
|
|
918
845
|
return {
|
|
919
846
|
...commonOf(quote, now),
|
|
920
847
|
family: "offer",
|
|
921
848
|
status: "pending",
|
|
922
849
|
offerHex: offer.offerHex,
|
|
923
850
|
swapAddress: offer.address,
|
|
924
|
-
swapPkScript:
|
|
851
|
+
swapPkScript: hex2.encode(offer.swapPkScript)
|
|
852
|
+
};
|
|
853
|
+
};
|
|
854
|
+
var registeredAssetRecord = async (input, preparation) => {
|
|
855
|
+
if (stableStringify(
|
|
856
|
+
input.quote.assetPayment === void 0 ? void 0 : recordAssetPayment(input.quote.assetPayment)
|
|
857
|
+
) !== stableStringify(
|
|
858
|
+
preparation.assetPayment === void 0 ? void 0 : recordAssetPayment(preparation.assetPayment)
|
|
859
|
+
))
|
|
860
|
+
throw new Error("asset payment differs from verified quote preparation");
|
|
861
|
+
if (preparation.assetPaymentRecipient !== void 0 && stableStringify(input.quote.route.take.instrument) !== stableStringify(preparation.assetPaymentRecipient))
|
|
862
|
+
throw new Error("asset payment recipient differs from verified quote preparation");
|
|
863
|
+
await registerDerivedOffer(input.wallet, preparation.offer, { coverageId: input.quote.id });
|
|
864
|
+
return {
|
|
865
|
+
...commonOf(input.quote, input.now),
|
|
866
|
+
...preparation.assetPayment === void 0 ? {} : { assetPayment: recordAssetPayment(preparation.assetPayment) },
|
|
867
|
+
family: "offer",
|
|
868
|
+
status: "pending",
|
|
869
|
+
offerHex: preparation.offer.offerHex,
|
|
870
|
+
swapAddress: preparation.offer.address,
|
|
871
|
+
swapPkScript: hex2.encode(preparation.offer.swapPkScript),
|
|
872
|
+
...preparation.carrierSats === void 0 ? {} : { carrierSats: preparation.carrierSats.toString() }
|
|
925
873
|
};
|
|
926
874
|
};
|
|
927
875
|
var registeredCorridorRecord = async (input, preparation) => {
|
|
928
876
|
const contracts = await input.wallet.getContractManager();
|
|
929
|
-
await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address
|
|
877
|
+
await registerLockupContract(contracts, preparation.lockup.script, preparation.lockup.address, {
|
|
878
|
+
coverageId: input.quote.id,
|
|
879
|
+
scope: input.wallet
|
|
880
|
+
});
|
|
881
|
+
await promoteOfferContract(
|
|
882
|
+
contracts,
|
|
883
|
+
hex2.encode(preparation.lockup.script.pkScript),
|
|
884
|
+
void 0,
|
|
885
|
+
{
|
|
886
|
+
coverageId: input.quote.id,
|
|
887
|
+
scope: input.wallet
|
|
888
|
+
}
|
|
889
|
+
);
|
|
930
890
|
return corridorRecord(input.quote, preparation, input.now);
|
|
931
891
|
};
|
|
932
892
|
var fundAndStamp = async (input, record, repository) => {
|
|
933
|
-
const
|
|
934
|
-
|
|
893
|
+
const bounds = storedFundingBounds(record.assetPayment, record.expiresAt);
|
|
894
|
+
const cap = input.validUntil === void 0 ? bounds.validUntil : Math.min(input.validUntil, bounds.validUntil ?? record.expiresAt);
|
|
895
|
+
const validUntil = cap === void 0 ? void 0 : Math.min(cap, record.expiresAt);
|
|
896
|
+
if (input.firstFundingAttempt && record.assetPayment !== void 0 && validUntil !== void 0 && validUntil < record.assetPayment.validUntil) {
|
|
897
|
+
record = { ...record, assetPayment: { ...record.assetPayment, validUntil } };
|
|
898
|
+
await repository.saveSwapRecord(record);
|
|
899
|
+
}
|
|
900
|
+
try {
|
|
901
|
+
const txid = await fund({ ...input, ...bounds, validUntil }, record);
|
|
902
|
+
return stampFunding(repository, record, txid, input.now);
|
|
903
|
+
} catch (error) {
|
|
904
|
+
if (input.firstFundingAttempt && validUntil !== void 0 && error instanceof SendDeadlineExceededError) {
|
|
905
|
+
const stopped = {
|
|
906
|
+
...record,
|
|
907
|
+
...record.family === "offer" ? { status: "cancelled" } : { state: "failed" },
|
|
908
|
+
fundingNotSubmitted: { reason: "send_deadline", validUntil },
|
|
909
|
+
updatedAt: Math.floor(Date.now() / 1e3)
|
|
910
|
+
};
|
|
911
|
+
try {
|
|
912
|
+
await repository.saveSwapRecord(stopped);
|
|
913
|
+
input.drive?.ingest(stopped);
|
|
914
|
+
await retireUnsubmittedFunding(input.wallet, repository, stopped);
|
|
915
|
+
} catch (cause) {
|
|
916
|
+
console.warn(
|
|
917
|
+
`[swap] could not finish unsent funding cleanup for ${record.id}`,
|
|
918
|
+
cause
|
|
919
|
+
);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
throw error;
|
|
923
|
+
}
|
|
935
924
|
};
|
|
936
925
|
var stampFunding = async (repository, record, fundingTxid, now) => {
|
|
937
926
|
const stamped = { ...record, fundingTxid, updatedAt: now };
|
|
@@ -944,14 +933,20 @@ var stampFunding = async (repository, record, fundingTxid, now) => {
|
|
|
944
933
|
};
|
|
945
934
|
var fund = async (input, record) => {
|
|
946
935
|
const { wallet } = input;
|
|
936
|
+
const send = (recipient) => input.validUntil === void 0 && input.inputExpiryFloor === void 0 ? wallet.send(recipient) : wallet.send({
|
|
937
|
+
recipients: [recipient],
|
|
938
|
+
...input.validUntil === void 0 ? {} : { validUntil: input.validUntil },
|
|
939
|
+
...input.inputExpiryFloor === void 0 ? {} : { inputExpiryFloor: input.inputExpiryFloor }
|
|
940
|
+
});
|
|
947
941
|
if (record.family === "offer") {
|
|
948
942
|
const amount = fromAtomicDecimal(record.give.amount);
|
|
949
|
-
const depositIsBtc =
|
|
950
|
-
return
|
|
943
|
+
const depositIsBtc = isBtcAssetLenient(record.route.give.asset);
|
|
944
|
+
return send({
|
|
951
945
|
address: record.swapAddress,
|
|
952
|
-
// An asset deposit rides
|
|
953
|
-
//
|
|
946
|
+
// An asset deposit rides a dust-sat carrier: the solver's published one when the record
|
|
947
|
+
// names it (the fill is priced against it), else the SDK default.
|
|
954
948
|
...depositIsBtc ? { amount: toSafeNumber(amount, "give.amount") } : {
|
|
949
|
+
...record.carrierSats === void 0 ? {} : { amount: toSafeNumber(BigInt(record.carrierSats), "carrierSats") },
|
|
955
950
|
assets: [
|
|
956
951
|
{ assetId: toDiscoveryLeg(record.route.give.asset).assetId, amount }
|
|
957
952
|
]
|
|
@@ -959,17 +954,17 @@ var fund = async (input, record) => {
|
|
|
959
954
|
extensions: [offerExtensionOf(record)]
|
|
960
955
|
});
|
|
961
956
|
}
|
|
962
|
-
if (record.kind === "lightning_receive") {
|
|
957
|
+
if (record.kind === "lightning_receive" || record.kind === "onchain_receive") {
|
|
963
958
|
throw new Error(`receive swap ${record.id} funds nothing from this wallet`);
|
|
964
959
|
}
|
|
965
|
-
return
|
|
960
|
+
return send({
|
|
966
961
|
address: record.lockupAddress,
|
|
967
962
|
amount: toSafeNumber(fromAtomicDecimal(record.give.amount), "give.amount")
|
|
968
963
|
});
|
|
969
964
|
};
|
|
970
965
|
var offerExtensionOf = (record) => ({
|
|
971
966
|
type: OFFER_PACKET_TYPE,
|
|
972
|
-
payload:
|
|
967
|
+
payload: hex2.decode(record.offerHex)
|
|
973
968
|
});
|
|
974
969
|
var reconcileFunding = async (input, record) => {
|
|
975
970
|
const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
|
|
@@ -981,7 +976,7 @@ var reconcileFunding = async (input, record) => {
|
|
|
981
976
|
};
|
|
982
977
|
var depositMatches = (vtxo, record, expected) => {
|
|
983
978
|
const giveAsset = record.route.give.asset;
|
|
984
|
-
if (
|
|
979
|
+
if (isBtcAssetLenient(giveAsset)) {
|
|
985
980
|
return BigInt(vtxo.value) === expected;
|
|
986
981
|
}
|
|
987
982
|
return (vtxo.assets ?? []).some(
|
|
@@ -1037,7 +1032,7 @@ var scopedToRail = (table, rail) => ({
|
|
|
1037
1032
|
});
|
|
1038
1033
|
|
|
1039
1034
|
// src/client/corridors/arkade.ts
|
|
1040
|
-
import { ArkAddress, arkTarget, assertRecipientArkadeAddress } from "@arkade-os/sdk";
|
|
1035
|
+
import { ArkAddress as ArkAddress2, arkTarget, assertRecipientArkadeAddress } from "@arkade-os/sdk";
|
|
1041
1036
|
var ARKADE_DRIVE = {};
|
|
1042
1037
|
var messageOf = (error) => error instanceof Error ? error.message : String(error);
|
|
1043
1038
|
var arkadeCorridor = Object.assign(
|
|
@@ -1049,7 +1044,7 @@ var arkadeCorridor = Object.assign(
|
|
|
1049
1044
|
const target = arkTarget(raw);
|
|
1050
1045
|
if (target === void 0) return void 0;
|
|
1051
1046
|
try {
|
|
1052
|
-
const address =
|
|
1047
|
+
const address = ArkAddress2.decode(target);
|
|
1053
1048
|
assertRecipientArkadeAddress(target, address, {
|
|
1054
1049
|
hrp: deps.network.hrp,
|
|
1055
1050
|
signerSet: deps.signerSet
|
|
@@ -1069,7 +1064,6 @@ var DEFAULT_INVOICE_EXPIRY_SECONDS = 3600;
|
|
|
1069
1064
|
var valueOf = (decoded, name) => decoded.sections.find(
|
|
1070
1065
|
(section) => section.name === name
|
|
1071
1066
|
)?.value;
|
|
1072
|
-
var PAYMENT_HASH = /^[0-9a-f]{64}$/;
|
|
1073
1067
|
var decodeBolt11 = (invoice) => {
|
|
1074
1068
|
const decoded = bolt11.decode(invoice);
|
|
1075
1069
|
const timestamp = valueOf(decoded, "timestamp");
|
|
@@ -1091,7 +1085,7 @@ var decodeBolt11 = (invoice) => {
|
|
|
1091
1085
|
};
|
|
1092
1086
|
|
|
1093
1087
|
// src/client/corridors/chainSource.ts
|
|
1094
|
-
import { hex as
|
|
1088
|
+
import { hex as hex3 } from "@scure/base";
|
|
1095
1089
|
import * as btc from "@scure/btc-signer";
|
|
1096
1090
|
import { EsploraProvider } from "@arkade-os/sdk";
|
|
1097
1091
|
var addressOfScript = (script, network) => btc.Address(network).encode(btc.OutScript.decode(script));
|
|
@@ -1120,11 +1114,8 @@ var chainSourceOver = (backend, network) => {
|
|
|
1120
1114
|
return coins.map((coin) => ({
|
|
1121
1115
|
txid: coin.txid,
|
|
1122
1116
|
vout: coin.vout,
|
|
1123
|
-
// `Coin.value` is `number` sats; the HTLC's is `bigint`.
|
|
1124
1117
|
amount: BigInt(coin.value),
|
|
1125
|
-
//
|
|
1126
|
-
// second half of the answer. A confirmed coin is one deep, not
|
|
1127
|
-
// zero — the block it landed in counts.
|
|
1118
|
+
// A confirmed coin is one deep, not zero: its own block counts.
|
|
1128
1119
|
confirmations: coin.status.confirmed && coin.status.block_height !== void 0 ? Math.max(0, tip.height - coin.status.block_height + 1) : 0
|
|
1129
1120
|
}));
|
|
1130
1121
|
},
|
|
@@ -1134,13 +1125,19 @@ var chainSourceOver = (backend, network) => {
|
|
|
1134
1125
|
if (!outspend?.spent) return null;
|
|
1135
1126
|
const spender = outspend.txid || await spenderFromVins(txid, vout, pkScript);
|
|
1136
1127
|
if (!spender) return null;
|
|
1137
|
-
return { txHex:
|
|
1128
|
+
return { txHex: hex3.encode(await backend.provider.getRawTransaction(spender)) };
|
|
1138
1129
|
},
|
|
1139
1130
|
broadcast(txHex) {
|
|
1140
1131
|
return backend.provider.broadcastTransaction(txHex);
|
|
1141
1132
|
},
|
|
1142
1133
|
async getMtp() {
|
|
1143
1134
|
return (await backend.tip()).mtp;
|
|
1135
|
+
},
|
|
1136
|
+
async getTxStatus(txid) {
|
|
1137
|
+
return (await backend.provider.getTxStatus(txid)).confirmed ? "confirmed" : "unconfirmed";
|
|
1138
|
+
},
|
|
1139
|
+
getFeeRate() {
|
|
1140
|
+
return backend.provider.getFeeRate();
|
|
1144
1141
|
}
|
|
1145
1142
|
};
|
|
1146
1143
|
};
|
|
@@ -1183,6 +1180,12 @@ var refusedIfNull = (value, corridor, dep) => {
|
|
|
1183
1180
|
if (value === null) throw new MissingCorridorDep(corridor, dep);
|
|
1184
1181
|
return value;
|
|
1185
1182
|
};
|
|
1183
|
+
var refusedIfMalformed = (value, dep) => {
|
|
1184
|
+
if (value !== void 0 && value !== null && !(Number.isFinite(value) && value > 0)) {
|
|
1185
|
+
throw new MissingCorridorDep("onchain", dep);
|
|
1186
|
+
}
|
|
1187
|
+
return value;
|
|
1188
|
+
};
|
|
1186
1189
|
var emulatorPubkeyFor = (base) => {
|
|
1187
1190
|
if (base.emulatorPubkey !== void 0) {
|
|
1188
1191
|
return resolveEmulatorPubkey(base.network, base.emulatorPubkey);
|
|
@@ -1224,26 +1227,27 @@ function resolveCorridorDeps(corridor, overrides, base) {
|
|
|
1224
1227
|
case "onchain": {
|
|
1225
1228
|
const chain = refusedIfNull(overrides?.onchain?.chain, "onchain", "chain source");
|
|
1226
1229
|
const claim = refusedIfNull(overrides?.onchain?.claim, "onchain", "L1 claim callback");
|
|
1227
|
-
const
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1230
|
+
const refund = refusedIfNull(
|
|
1231
|
+
overrides?.onchain?.refund,
|
|
1232
|
+
"onchain",
|
|
1233
|
+
"L1 refund callback"
|
|
1234
|
+
);
|
|
1235
|
+
const feeRateOverride = refusedIfMalformed(
|
|
1236
|
+
overrides?.onchain?.claimFeeRateSatVb,
|
|
1237
|
+
"L1 claim fee rate"
|
|
1238
|
+
);
|
|
1231
1239
|
const claimFeeRateSatVb = feeRateOverride === null ? void 0 : feeRateOverride ?? ONCHAIN_CLAIM_FEE_RATE_SATVB[base.networkName];
|
|
1232
|
-
const
|
|
1233
|
-
|
|
1234
|
-
throw new MissingCorridorDep("onchain", "L1 claim vsize");
|
|
1235
|
-
}
|
|
1236
|
-
const claimVsize = vsizeOverride === null ? ONCHAIN_CLAIM_VSIZE : vsizeOverride ?? ONCHAIN_CLAIM_VSIZE;
|
|
1240
|
+
const claimVsize = refusedIfMalformed(overrides?.onchain?.claimVsize, "L1 claim vsize") ?? ONCHAIN_CLAIM_VSIZE;
|
|
1241
|
+
const l1Network = l1NetworkFromArk(base.networkName);
|
|
1237
1242
|
return {
|
|
1238
1243
|
networkName: base.networkName,
|
|
1239
|
-
chain: esploraChainSource({
|
|
1244
|
+
chain: chain && "provider" in chain ? chainSourceFrom(chain.provider, l1Network) : esploraChainSource({
|
|
1240
1245
|
esploraUrl: chain?.esploraUrl ?? ESPLORA_URL[base.networkName],
|
|
1241
|
-
network: L1_NETWORKS[
|
|
1246
|
+
network: L1_NETWORKS[l1Network],
|
|
1242
1247
|
fetchImpl: base.fetchImpl
|
|
1243
1248
|
}),
|
|
1244
1249
|
...claim === void 0 ? {} : { claim },
|
|
1245
|
-
|
|
1246
|
-
// same: no default claim path, manual mode.
|
|
1250
|
+
...refund === void 0 ? {} : { refund },
|
|
1247
1251
|
...claimFeeRateSatVb === void 0 ? {} : { claimFeeRateSatVb },
|
|
1248
1252
|
claimVsize
|
|
1249
1253
|
};
|
|
@@ -1376,6 +1380,7 @@ var discoveryIndex = (input) => {
|
|
|
1376
1380
|
ref: { fetchedAt: Date.now(), live: true, source: "injected" }
|
|
1377
1381
|
};
|
|
1378
1382
|
let held;
|
|
1383
|
+
let revalidateAt = 0;
|
|
1379
1384
|
const unavailable = (detail) => {
|
|
1380
1385
|
throw new DiscoverySnapshotUnavailable(input.network, detail);
|
|
1381
1386
|
};
|
|
@@ -1399,8 +1404,7 @@ var discoveryIndex = (input) => {
|
|
|
1399
1404
|
markets: cached.markets,
|
|
1400
1405
|
ref: {
|
|
1401
1406
|
fetchedAt: cached.fetchedAt,
|
|
1402
|
-
//
|
|
1403
|
-
// age: nothing here can attest that a registry ever served them.
|
|
1407
|
+
// Whatever its age: nothing attests a registry ever served these cards.
|
|
1404
1408
|
live: false,
|
|
1405
1409
|
source: "cache",
|
|
1406
1410
|
registry: url
|
|
@@ -1415,30 +1419,50 @@ var discoveryIndex = (input) => {
|
|
|
1415
1419
|
held = cached;
|
|
1416
1420
|
return cached;
|
|
1417
1421
|
}
|
|
1422
|
+
const { network: indexed, registry: url } = sources();
|
|
1423
|
+
if (indexed && url && config.localCards?.length) {
|
|
1424
|
+
const { markets } = await discover({
|
|
1425
|
+
registries: [],
|
|
1426
|
+
localCards: [...config.localCards],
|
|
1427
|
+
network: indexed
|
|
1428
|
+
});
|
|
1429
|
+
if (markets.length > 0) {
|
|
1430
|
+
return { markets, ref: { fetchedAt: Date.now(), live: true, source: "local" } };
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1418
1433
|
return unavailable(whyUnavailable());
|
|
1419
1434
|
};
|
|
1420
1435
|
const load = async (opts = {}) => {
|
|
1421
1436
|
if (injected) return injected;
|
|
1422
|
-
const fresh = held?.ref.live === true && Date.now()
|
|
1437
|
+
const fresh = held?.ref.live === true && Date.now() < revalidateAt;
|
|
1423
1438
|
if (fresh && !opts.refresh) return held;
|
|
1424
1439
|
const { network: indexed, registry: url } = sources();
|
|
1425
1440
|
if (!indexed || !url) {
|
|
1426
1441
|
return unavailable(whyUnavailable());
|
|
1427
1442
|
}
|
|
1443
|
+
const delivery = trackDelivery(transportCardsOf(config.transportCards));
|
|
1428
1444
|
const result = await discover({
|
|
1429
1445
|
registries: [url],
|
|
1430
1446
|
localCards: [...config.localCards ?? []],
|
|
1431
1447
|
network: indexed,
|
|
1432
|
-
fetchImpl: config.fetchImpl
|
|
1448
|
+
fetchImpl: config.fetchImpl,
|
|
1449
|
+
transportCards: delivery.fetcher
|
|
1433
1450
|
});
|
|
1434
1451
|
if (result.warnings.length) config.logger?.("solver discovery:", ...result.warnings);
|
|
1435
|
-
if (result.sources
|
|
1452
|
+
if (registryAnswered(result.sources)) {
|
|
1436
1453
|
const fetchedAt = Date.now();
|
|
1437
1454
|
held = {
|
|
1438
1455
|
markets: result.markets,
|
|
1439
1456
|
ref: { fetchedAt, live: true, source: "live", registry: url }
|
|
1440
1457
|
};
|
|
1441
|
-
|
|
1458
|
+
const undelivered = delivery.undelivered();
|
|
1459
|
+
const keepsCache = undelivered.size > 0 && input.repository !== void 0 && undeliveredCarry(
|
|
1460
|
+
result.markets,
|
|
1461
|
+
undelivered,
|
|
1462
|
+
await readCache(input.repository, indexed, url)
|
|
1463
|
+
).length > 0;
|
|
1464
|
+
revalidateAt = fetchedAt + (keepsCache ? DEGRADED_RETRY_MS : MARKETS_CACHE_TTL_MS);
|
|
1465
|
+
if (input.repository && !keepsCache) {
|
|
1442
1466
|
try {
|
|
1443
1467
|
await input.repository.saveCachedMarkets(indexed, url, {
|
|
1444
1468
|
markets: result.markets,
|
|
@@ -1454,12 +1478,26 @@ var discoveryIndex = (input) => {
|
|
|
1454
1478
|
held = cached;
|
|
1455
1479
|
return cached;
|
|
1456
1480
|
}
|
|
1481
|
+
if (result.markets.length > 0) {
|
|
1482
|
+
const fetchedAt = Date.now();
|
|
1483
|
+
held = { markets: result.markets, ref: { fetchedAt, live: true, source: "local" } };
|
|
1484
|
+
revalidateAt = fetchedAt + DEGRADED_RETRY_MS;
|
|
1485
|
+
return held;
|
|
1486
|
+
}
|
|
1457
1487
|
return unavailable(whyUnavailable());
|
|
1458
1488
|
};
|
|
1459
1489
|
return { peek, load };
|
|
1460
1490
|
};
|
|
1461
1491
|
|
|
1462
1492
|
// src/client/driveRecords.ts
|
|
1493
|
+
import {
|
|
1494
|
+
ArkAddress as ArkAddress3,
|
|
1495
|
+
asset as asset3,
|
|
1496
|
+
assertPageRequest,
|
|
1497
|
+
pageResult
|
|
1498
|
+
} from "@arkade-os/sdk";
|
|
1499
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
1500
|
+
import { hex as hex4 } from "@scure/base";
|
|
1463
1501
|
var splitRecords = (records) => {
|
|
1464
1502
|
const corridor = [];
|
|
1465
1503
|
const offer = [];
|
|
@@ -1478,12 +1516,15 @@ var rfqRecordOf = (record) => ({
|
|
|
1478
1516
|
state: record.state,
|
|
1479
1517
|
createdAt: record.createdAt,
|
|
1480
1518
|
updatedAt: record.updatedAt,
|
|
1481
|
-
...record
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
...
|
|
1485
|
-
...
|
|
1486
|
-
...
|
|
1519
|
+
...mutableHalfOf(record)
|
|
1520
|
+
});
|
|
1521
|
+
var mutableHalfOf = (from) => ({
|
|
1522
|
+
...from.refundTxid === void 0 ? {} : { refundTxid: from.refundTxid },
|
|
1523
|
+
...from.lockupSpendTxids?.length ? { lockupSpendTxids: [...from.lockupSpendTxids] } : {},
|
|
1524
|
+
...from.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: from.settlementPreimageHex },
|
|
1525
|
+
...from.failure === void 0 ? {} : { failure: from.failure },
|
|
1526
|
+
...from.claimFailure === void 0 ? {} : { claimFailure: from.claimFailure },
|
|
1527
|
+
...from.blockedReason === void 0 ? {} : { blockedReason: from.blockedReason }
|
|
1487
1528
|
});
|
|
1488
1529
|
var withRfqState = (record, state) => {
|
|
1489
1530
|
const {
|
|
@@ -1500,14 +1541,20 @@ var withRfqState = (record, state) => {
|
|
|
1500
1541
|
state: state.state,
|
|
1501
1542
|
profile: state.profile,
|
|
1502
1543
|
updatedAt: state.updatedAt,
|
|
1503
|
-
...state
|
|
1504
|
-
...state.lockupSpendTxids?.length ? { lockupSpendTxids: [...state.lockupSpendTxids] } : {},
|
|
1505
|
-
...state.settlementPreimageHex === void 0 ? {} : { settlementPreimageHex: state.settlementPreimageHex },
|
|
1506
|
-
...state.failure === void 0 ? {} : { failure: state.failure },
|
|
1507
|
-
...state.claimFailure === void 0 ? {} : { claimFailure: state.claimFailure },
|
|
1508
|
-
...state.blockedReason === void 0 ? {} : { blockedReason: state.blockedReason }
|
|
1544
|
+
...mutableHalfOf(state)
|
|
1509
1545
|
};
|
|
1510
1546
|
};
|
|
1547
|
+
var pageRfqRecords = (records, filter, page) => {
|
|
1548
|
+
const rows = records.filter(
|
|
1549
|
+
(record) => (filter.state === void 0 || record.state === filter.state) && (filter.since === void 0 || record.updatedAt >= filter.since) && (!page.after || record.updatedAt > page.after.updatedAt || record.updatedAt === page.after.updatedAt && record.rfqId > page.after.rfqId)
|
|
1550
|
+
).sort(
|
|
1551
|
+
(a, b) => a.updatedAt - b.updatedAt || (a.rfqId < b.rfqId ? -1 : a.rfqId > b.rfqId ? 1 : 0)
|
|
1552
|
+
).slice(0, page.limit + 1);
|
|
1553
|
+
return pageResult(rows, page.limit, (record) => ({
|
|
1554
|
+
updatedAt: record.updatedAt,
|
|
1555
|
+
rfqId: record.rfqId
|
|
1556
|
+
}));
|
|
1557
|
+
};
|
|
1511
1558
|
var corridorRecordStore = (repository, onRecord = () => {
|
|
1512
1559
|
}, admits = () => true) => {
|
|
1513
1560
|
const byRfqId = /* @__PURE__ */ new Map();
|
|
@@ -1520,7 +1567,7 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
1520
1567
|
const record = await repository.getSwapRecord(known);
|
|
1521
1568
|
if (record?.family === "rfq") return record;
|
|
1522
1569
|
}
|
|
1523
|
-
const { corridor } = splitRecords(await repository
|
|
1570
|
+
const { corridor } = splitRecords(await collectSwapRecords(repository));
|
|
1524
1571
|
for (const record of corridor) index(record);
|
|
1525
1572
|
const found = byRfqId.get(rfqId);
|
|
1526
1573
|
return found === void 0 ? void 0 : corridor.find((r) => r.id === found);
|
|
@@ -1528,10 +1575,12 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
1528
1575
|
return {
|
|
1529
1576
|
index,
|
|
1530
1577
|
quoteIdOf: (rfqId) => byRfqId.get(rfqId),
|
|
1531
|
-
async
|
|
1532
|
-
|
|
1578
|
+
async getRfqSwapsPage(filter, page) {
|
|
1579
|
+
assertPageRequest(page);
|
|
1580
|
+
assertRfqSwapPageFilter(filter);
|
|
1581
|
+
const { corridor } = splitRecords(await collectSwapRecords(repository));
|
|
1533
1582
|
for (const record of corridor) index(record);
|
|
1534
|
-
return corridor.filter(admits).map(rfqRecordOf);
|
|
1583
|
+
return pageRfqRecords(corridor.filter(admits).map(rfqRecordOf), filter, page);
|
|
1535
1584
|
},
|
|
1536
1585
|
async getRfqSwap(rfqId) {
|
|
1537
1586
|
const record = await recordFor(rfqId);
|
|
@@ -1554,20 +1603,18 @@ var corridorRecordStore = (repository, onRecord = () => {
|
|
|
1554
1603
|
};
|
|
1555
1604
|
var offerFactsOf = (record) => ({
|
|
1556
1605
|
id: record.id,
|
|
1606
|
+
coverageId: record.id,
|
|
1557
1607
|
status: record.status,
|
|
1558
1608
|
offerHex: record.offerHex,
|
|
1559
1609
|
swapPkScript: record.swapPkScript,
|
|
1560
1610
|
...record.fundingTxid === void 0 ? {} : { fundingTxid: record.fundingTxid },
|
|
1561
1611
|
...record.spentTxid === void 0 ? {} : { spentTxid: record.spentTxid },
|
|
1562
|
-
// Milliseconds: `coverage.ts` marks issuance with `Date.now()`, and a
|
|
1563
|
-
// seconds value compared against it leaves every issued script outstanding
|
|
1564
|
-
// for the life of the process.
|
|
1565
1612
|
createdAt: record.createdAt * 1e3
|
|
1566
1613
|
});
|
|
1567
1614
|
var offerRecordSource = (repository, onRecord = () => {
|
|
1568
1615
|
}, now = () => Math.floor(Date.now() / 1e3)) => {
|
|
1569
1616
|
const list = async () => {
|
|
1570
|
-
const { offer } = splitRecords(await repository
|
|
1617
|
+
const { offer } = splitRecords(await collectSwapRecords(repository));
|
|
1571
1618
|
return offer.map(offerFactsOf);
|
|
1572
1619
|
};
|
|
1573
1620
|
return {
|
|
@@ -1596,12 +1643,93 @@ var applyOfferSpend = (record, changes, now) => ({
|
|
|
1596
1643
|
...record,
|
|
1597
1644
|
status: changes.status,
|
|
1598
1645
|
spentTxid: changes.spentTxid,
|
|
1599
|
-
//
|
|
1600
|
-
// milliseconds; this record's timestamps are unix seconds.
|
|
1646
|
+
// event timestamps are milliseconds; this record's are unix seconds
|
|
1601
1647
|
...changes.completedAt === void 0 ? {} : { completedAt: Math.floor(changes.completedAt / 1e3) },
|
|
1602
1648
|
updatedAt: now
|
|
1603
1649
|
});
|
|
1604
|
-
var
|
|
1650
|
+
var withDepositFate = (record, fate, now) => ({
|
|
1651
|
+
...record,
|
|
1652
|
+
status: fate.status,
|
|
1653
|
+
...fate.spentTxid === void 0 ? {} : { spentTxid: fate.spentTxid },
|
|
1654
|
+
...fate.completedAt === void 0 ? {} : { completedAt: Math.floor(fate.completedAt / 1e3) },
|
|
1655
|
+
updatedAt: now
|
|
1656
|
+
});
|
|
1657
|
+
var DEPOSIT_SPENT = (status) => status === "cancelled" || status === "fulfilled";
|
|
1658
|
+
var fateMoved = (record, fate) => {
|
|
1659
|
+
if (DEPOSIT_SPENT(record.status) && !DEPOSIT_SPENT(fate.status)) return false;
|
|
1660
|
+
return record.status !== fate.status || fate.spentTxid !== void 0 && record.spentTxid !== fate.spentTxid || fate.completedAt !== void 0 && record.completedAt !== Math.floor(fate.completedAt / 1e3);
|
|
1661
|
+
};
|
|
1662
|
+
var restoredOfferRecord = (swap, network, now) => {
|
|
1663
|
+
const give = restoredAssetId(network, swap.fromAsset);
|
|
1664
|
+
const take = restoredAssetId(network, swap.toAsset);
|
|
1665
|
+
const createdAt = Math.floor(swap.createdAt / 1e3);
|
|
1666
|
+
return withDepositFate(
|
|
1667
|
+
{
|
|
1668
|
+
id: swap.fundingTxid,
|
|
1669
|
+
family: "offer",
|
|
1670
|
+
route: {
|
|
1671
|
+
give: { corridor: "arkade", asset: give, instrument: { kind: "wallet" } },
|
|
1672
|
+
take: { corridor: "arkade", asset: take, instrument: { kind: "wallet" } }
|
|
1673
|
+
},
|
|
1674
|
+
give: { asset: give, amount: toAtomicDecimal(BigInt(swap.fromAmount)) },
|
|
1675
|
+
take: { asset: take, amount: toAtomicDecimal(BigInt(swap.toAmount)) },
|
|
1676
|
+
fee: { asset: take, amount: toAtomicDecimal(0n) },
|
|
1677
|
+
market: { kind: "restored", backend: "feed" },
|
|
1678
|
+
expiresAt: createdAt,
|
|
1679
|
+
status: swap.status,
|
|
1680
|
+
offerHex: swap.offerHex,
|
|
1681
|
+
swapAddress: swap.swapAddress,
|
|
1682
|
+
swapPkScript: swap.swapPkScript,
|
|
1683
|
+
fundingTxid: swap.fundingTxid,
|
|
1684
|
+
createdAt,
|
|
1685
|
+
updatedAt: now
|
|
1686
|
+
},
|
|
1687
|
+
swap,
|
|
1688
|
+
now
|
|
1689
|
+
);
|
|
1690
|
+
};
|
|
1691
|
+
var restoredAssetId = (network, id) => id === BTC_ASSET_ID ? btcOn("arkade", network) : arkadeAsset(network, asset3.AssetId.fromString(id));
|
|
1692
|
+
var RESTORED_CORRIDORS = {
|
|
1693
|
+
lightning_send: ["arkade", "lightning"],
|
|
1694
|
+
lightning_receive: ["lightning", "arkade"],
|
|
1695
|
+
onchain_send: ["arkade", "onchain"],
|
|
1696
|
+
onchain_receive: ["onchain", "arkade"]
|
|
1697
|
+
};
|
|
1698
|
+
var restoredCorridorRecord = (stored, network, refundLocktime) => {
|
|
1699
|
+
const v1 = normalizeRfqSwapRecord(stored);
|
|
1700
|
+
const hashlock = v1.profile.hashlock;
|
|
1701
|
+
const hash = typeof hashlock?.paymentHash === "string" ? hashlock.paymentHash : v1.settlementPreimageHex === void 0 ? void 0 : hex4.encode(sha256(hex4.decode(v1.settlementPreimageHex)));
|
|
1702
|
+
if (hash === void 0) throw new Error(`v1 rfq swap ${v1.rfqId} has no payment hash`);
|
|
1703
|
+
const [giveCorridor, takeCorridor] = RESTORED_CORRIDORS[v1.kind];
|
|
1704
|
+
const give = btcOn(railOfCorridor(giveCorridor), network);
|
|
1705
|
+
const take = btcOn(railOfCorridor(takeCorridor), network);
|
|
1706
|
+
const amount = toAtomicDecimal(BigInt(v1.amount ?? 0));
|
|
1707
|
+
return {
|
|
1708
|
+
id: v1.rfqId,
|
|
1709
|
+
family: "rfq",
|
|
1710
|
+
route: {
|
|
1711
|
+
give: { corridor: giveCorridor, asset: give, instrument: { kind: "wallet" } },
|
|
1712
|
+
take: { corridor: takeCorridor, asset: take, instrument: { kind: "wallet" } }
|
|
1713
|
+
},
|
|
1714
|
+
give: { asset: give, amount },
|
|
1715
|
+
take: { asset: take, amount },
|
|
1716
|
+
fee: { asset: give, amount: toAtomicDecimal(0n) },
|
|
1717
|
+
market: { kind: "restored", backend: "rfq" },
|
|
1718
|
+
expiresAt: v1.createdAt,
|
|
1719
|
+
state: v1.state,
|
|
1720
|
+
kind: v1.kind,
|
|
1721
|
+
rfqId: v1.rfqId,
|
|
1722
|
+
lockupAddress: v1.lockupAddress,
|
|
1723
|
+
lockupPkScript: hex4.encode(ArkAddress3.decode(v1.lockupAddress).pkScript),
|
|
1724
|
+
lock: { hash },
|
|
1725
|
+
refundLocktime,
|
|
1726
|
+
profile: v1.profile,
|
|
1727
|
+
...v1.fundingTxid === void 0 ? {} : { fundingTxid: v1.fundingTxid },
|
|
1728
|
+
...mutableHalfOf(v1),
|
|
1729
|
+
createdAt: v1.createdAt,
|
|
1730
|
+
updatedAt: v1.updatedAt
|
|
1731
|
+
};
|
|
1732
|
+
};
|
|
1605
1733
|
var walletLockupIndexer = (wallet) => {
|
|
1606
1734
|
let reader;
|
|
1607
1735
|
const reading = () => reader ??= wallet.getArkadeReader();
|
|
@@ -1617,17 +1745,14 @@ var walletLockupIndexer = (wallet) => {
|
|
|
1617
1745
|
};
|
|
1618
1746
|
|
|
1619
1747
|
// src/client/cancel.ts
|
|
1620
|
-
import { base64, hex as
|
|
1621
|
-
import { ArkAddress as
|
|
1622
|
-
var OFFER_TERMINAL = (record) => record.status === "cancelled" || record.status === "fulfilled";
|
|
1748
|
+
import { base64, hex as hex5 } from "@scure/base";
|
|
1749
|
+
import { ArkAddress as ArkAddress4, Transaction } from "@arkade-os/sdk";
|
|
1623
1750
|
var cancelSwap = async (input) => {
|
|
1624
1751
|
const { wallet, repository, record, drive, indexer } = input;
|
|
1625
1752
|
const now = input.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
if (offerOutcome(record.status) === "needs_recovery") {
|
|
1630
|
-
return { outcome: "needs_recovery" };
|
|
1753
|
+
const outcome = offerOutcome(record.status);
|
|
1754
|
+
if (outcome === "cancelled" || outcome === "filled" || outcome === "needs_recovery") {
|
|
1755
|
+
return { outcome };
|
|
1631
1756
|
}
|
|
1632
1757
|
const gated2 = withStatus(record, "cancelling", now());
|
|
1633
1758
|
await repository.saveSwapRecord(gated2);
|
|
@@ -1652,7 +1777,7 @@ var cancelSwap = async (input) => {
|
|
|
1652
1777
|
drive.ingest(rolledBack);
|
|
1653
1778
|
throw error;
|
|
1654
1779
|
}
|
|
1655
|
-
if (
|
|
1780
|
+
if (error instanceof NoSpendableDepositError) {
|
|
1656
1781
|
const reconciled = await reconcileDepositSpend(record, indexer);
|
|
1657
1782
|
if (reconciled === void 0) {
|
|
1658
1783
|
return { outcome: "needs_recovery" };
|
|
@@ -1681,7 +1806,7 @@ var cancelSwap = async (input) => {
|
|
|
1681
1806
|
return { outcome: "cancelled" };
|
|
1682
1807
|
};
|
|
1683
1808
|
var reconcileDepositSpend = async (record, indexer) => {
|
|
1684
|
-
const offer = decodeOffer(
|
|
1809
|
+
const offer = decodeOffer(hex5.decode(record.offerHex));
|
|
1685
1810
|
const { vtxos } = await indexer.getVtxos({ scripts: [record.swapPkScript] });
|
|
1686
1811
|
const all = vtxos ?? [];
|
|
1687
1812
|
const deposit = record.fundingTxid === void 0 ? all.length === 1 ? all[0] : void 0 : all.find((vtxo) => vtxo.txid === record.fundingTxid);
|
|
@@ -1698,7 +1823,7 @@ var reconcileDepositSpend = async (record, indexer) => {
|
|
|
1698
1823
|
return void 0;
|
|
1699
1824
|
}
|
|
1700
1825
|
}).filter((tx) => tx !== void 0);
|
|
1701
|
-
const operatorPubkey =
|
|
1826
|
+
const operatorPubkey = ArkAddress4.decode(record.swapAddress).serverPubKey;
|
|
1702
1827
|
const kind = classifyDepositSpend(offer, operatorPubkey, parsed, {
|
|
1703
1828
|
txid: deposit.txid,
|
|
1704
1829
|
vout: deposit.vout
|
|
@@ -1724,72 +1849,294 @@ var persistBestEffort = async (repository, record) => {
|
|
|
1724
1849
|
};
|
|
1725
1850
|
var retireOfferScripts = async (wallet, repository, record) => {
|
|
1726
1851
|
try {
|
|
1727
|
-
const { offer } = splitRecords(await repository
|
|
1852
|
+
const { offer } = splitRecords(await collectSwapRecords(repository));
|
|
1728
1853
|
await retireOfferContract(
|
|
1729
1854
|
await wallet.getContractManager(),
|
|
1730
1855
|
offer.map(offerFactsOf),
|
|
1731
|
-
record.swapPkScript
|
|
1856
|
+
record.swapPkScript,
|
|
1857
|
+
{ scope: wallet }
|
|
1732
1858
|
);
|
|
1733
1859
|
} catch (error) {
|
|
1734
1860
|
console.warn(`[swap] could not retire offer script for ${record.id}`, error);
|
|
1735
1861
|
}
|
|
1736
1862
|
};
|
|
1737
|
-
var isMissingVtxo = (error) => error instanceof NoSpendableDepositError;
|
|
1738
1863
|
|
|
1739
1864
|
// src/client/drive.ts
|
|
1740
1865
|
import {
|
|
1741
|
-
ArkAddress as
|
|
1866
|
+
ArkAddress as ArkAddress5,
|
|
1742
1867
|
contractSigner,
|
|
1868
|
+
getNetwork as getNetwork2,
|
|
1743
1869
|
identityDescriptor
|
|
1744
1870
|
} from "@arkade-os/sdk";
|
|
1745
|
-
import { hex as
|
|
1746
|
-
|
|
1747
|
-
|
|
1748
|
-
|
|
1749
|
-
|
|
1750
|
-
|
|
1871
|
+
import { hex as hex6 } from "@scure/base";
|
|
1872
|
+
|
|
1873
|
+
// src/migrateOfferRows.ts
|
|
1874
|
+
import { arkade } from "@arkade-os/sdk";
|
|
1875
|
+
|
|
1876
|
+
// src/legacy/swap-want-asset.program.v0.json
|
|
1877
|
+
var swap_want_asset_program_v0_default = {
|
|
1878
|
+
version: 0,
|
|
1879
|
+
name: "banco-btc-to-asset",
|
|
1880
|
+
params: [
|
|
1881
|
+
{ name: "makerWP", type: "pubkey" },
|
|
1882
|
+
{ name: "wantAmount", type: "int" },
|
|
1883
|
+
{ name: "wantAssetTxid", type: "hash" },
|
|
1884
|
+
{ name: "wantAssetGroupIndex", type: "int" },
|
|
1885
|
+
{ name: "server", type: "pubkey" },
|
|
1886
|
+
{ name: "user", type: "pubkey" }
|
|
1887
|
+
],
|
|
1888
|
+
functions: {
|
|
1889
|
+
fulfill: {
|
|
1890
|
+
tapscript: { signers: ["$server"] },
|
|
1891
|
+
arkadeScript: {
|
|
1892
|
+
asm: [
|
|
1893
|
+
0,
|
|
1894
|
+
"$wantAssetTxid",
|
|
1895
|
+
"$wantAssetGroupIndex",
|
|
1896
|
+
"INSPECTOUTASSETLOOKUP",
|
|
1897
|
+
"VERIFY",
|
|
1898
|
+
"$wantAmount",
|
|
1899
|
+
"GREATERTHANOREQUAL",
|
|
1900
|
+
"VERIFY",
|
|
1901
|
+
0,
|
|
1902
|
+
"INSPECTOUTPUTSCRIPTPUBKEY",
|
|
1903
|
+
1,
|
|
1904
|
+
"EQUALVERIFY",
|
|
1905
|
+
"$makerWP",
|
|
1906
|
+
"EQUAL"
|
|
1907
|
+
]
|
|
1908
|
+
}
|
|
1909
|
+
},
|
|
1910
|
+
cancel: {
|
|
1911
|
+
tapscript: { signers: ["$user", "$server"] }
|
|
1912
|
+
}
|
|
1751
1913
|
}
|
|
1752
|
-
reason;
|
|
1753
|
-
swapId;
|
|
1754
|
-
name = "SwapDriveRefusedError";
|
|
1755
1914
|
};
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
var
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
1915
|
+
|
|
1916
|
+
// src/legacy/swap-want-btc.program.v0.json
|
|
1917
|
+
var swap_want_btc_program_v0_default = {
|
|
1918
|
+
version: 0,
|
|
1919
|
+
name: "banco-asset-to-btc",
|
|
1920
|
+
params: [
|
|
1921
|
+
{ name: "makerWP", type: "pubkey" },
|
|
1922
|
+
{ name: "wantAmount", type: "int" },
|
|
1923
|
+
{ name: "server", type: "pubkey" },
|
|
1924
|
+
{ name: "user", type: "pubkey" }
|
|
1925
|
+
],
|
|
1926
|
+
functions: {
|
|
1927
|
+
fulfill: {
|
|
1928
|
+
tapscript: { signers: ["$server"] },
|
|
1929
|
+
arkadeScript: {
|
|
1930
|
+
asm: [
|
|
1931
|
+
0,
|
|
1932
|
+
"INSPECTOUTPUTVALUE",
|
|
1933
|
+
"$wantAmount",
|
|
1934
|
+
"GREATERTHANOREQUAL",
|
|
1935
|
+
"VERIFY",
|
|
1936
|
+
0,
|
|
1937
|
+
"INSPECTOUTPUTSCRIPTPUBKEY",
|
|
1938
|
+
1,
|
|
1939
|
+
"EQUALVERIFY",
|
|
1940
|
+
"$makerWP",
|
|
1941
|
+
"EQUAL"
|
|
1942
|
+
]
|
|
1943
|
+
}
|
|
1944
|
+
},
|
|
1945
|
+
cancel: {
|
|
1946
|
+
tapscript: { signers: ["$user", "$server"] }
|
|
1947
|
+
}
|
|
1762
1948
|
}
|
|
1763
|
-
return record.family === "offer" && typeof record.offerHex === "string";
|
|
1764
1949
|
};
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
|
|
1772
|
-
|
|
1773
|
-
|
|
1774
|
-
|
|
1775
|
-
|
|
1776
|
-
let disposed = false;
|
|
1777
|
-
let startRequested = mode === "auto";
|
|
1778
|
-
let watcher;
|
|
1779
|
-
let readyPromise;
|
|
1780
|
-
const inFlight = /* @__PURE__ */ new Set();
|
|
1781
|
-
let queue = Promise.resolve();
|
|
1782
|
-
const track = (work) => {
|
|
1783
|
-
inFlight.add(work);
|
|
1784
|
-
void work.then(
|
|
1785
|
-
() => inFlight.delete(work),
|
|
1786
|
-
() => inFlight.delete(work)
|
|
1787
|
-
);
|
|
1788
|
-
return work;
|
|
1950
|
+
|
|
1951
|
+
// src/migrateOfferRows.ts
|
|
1952
|
+
function withExitV0(program, exit) {
|
|
1953
|
+
if (!exit) return program;
|
|
1954
|
+
return {
|
|
1955
|
+
...program,
|
|
1956
|
+
params: [...program.params, { name: "exitDelay", type: "int" }],
|
|
1957
|
+
functions: {
|
|
1958
|
+
...program.functions,
|
|
1959
|
+
exit: { tapscript: { signers: ["$user"], csv: { type: exit, value: "$exitDelay" } } }
|
|
1960
|
+
}
|
|
1789
1961
|
};
|
|
1790
|
-
|
|
1791
|
-
|
|
1792
|
-
|
|
1962
|
+
}
|
|
1963
|
+
var V0_TO_V1 = /* @__PURE__ */ new Map();
|
|
1964
|
+
for (const [v0, v1] of [
|
|
1965
|
+
[swap_want_btc_program_v0_default, swapPrograms.wantBtc],
|
|
1966
|
+
[swap_want_asset_program_v0_default, swapPrograms.wantAsset]
|
|
1967
|
+
]) {
|
|
1968
|
+
for (const exit of [void 0, "blocks", "seconds"]) {
|
|
1969
|
+
const timelock = exit && { type: exit, value: BigInt(0) };
|
|
1970
|
+
V0_TO_V1.set(
|
|
1971
|
+
JSON.stringify(withExitV0(v0, exit)),
|
|
1972
|
+
arkade.stringifyArtifact(withExitClosure(v1, timelock))
|
|
1973
|
+
);
|
|
1974
|
+
}
|
|
1975
|
+
}
|
|
1976
|
+
async function migrateV0OfferRows(contractManager) {
|
|
1977
|
+
const migrated = [];
|
|
1978
|
+
const skipped = [];
|
|
1979
|
+
for (const row of await contractManager.getUnsupportedContracts()) {
|
|
1980
|
+
if (row.type !== "arkade" || row.metadata?.kind !== OFFER_CONTRACT_KIND) continue;
|
|
1981
|
+
const program = V0_TO_V1.get(row.params.program);
|
|
1982
|
+
if (!program) {
|
|
1983
|
+
skipped.push({ script: row.script, reason: "not a bundled Program v0 offer" });
|
|
1984
|
+
continue;
|
|
1985
|
+
}
|
|
1986
|
+
try {
|
|
1987
|
+
await contractManager.createContract({
|
|
1988
|
+
type: row.type,
|
|
1989
|
+
script: row.script,
|
|
1990
|
+
address: row.address,
|
|
1991
|
+
params: { ...row.params, program },
|
|
1992
|
+
label: row.label,
|
|
1993
|
+
metadata: row.metadata
|
|
1994
|
+
});
|
|
1995
|
+
migrated.push(row.script);
|
|
1996
|
+
} catch (error) {
|
|
1997
|
+
skipped.push({
|
|
1998
|
+
script: row.script,
|
|
1999
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
2000
|
+
});
|
|
2001
|
+
}
|
|
2002
|
+
}
|
|
2003
|
+
return { migrated, skipped };
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
// src/client/legacyRecords.ts
|
|
2007
|
+
import { assertPageRequest as assertPageRequest2 } from "@arkade-os/sdk";
|
|
2008
|
+
var readLegacyRfqSwaps = async (repository, filter = {}) => {
|
|
2009
|
+
try {
|
|
2010
|
+
return await collectRfqSwaps(repository, filter);
|
|
2011
|
+
} catch (error) {
|
|
2012
|
+
console.warn("[swap] the v1 rfq swaps could not be read", error);
|
|
2013
|
+
return [];
|
|
2014
|
+
}
|
|
2015
|
+
};
|
|
2016
|
+
var legacyLiveRfqSwaps = async (repository) => (await readLegacyRfqSwaps(repository)).filter((record) => !isRfqSwapTerminal(record.state));
|
|
2017
|
+
var withLegacyRfqSwaps = (bridge, repository, admits) => {
|
|
2018
|
+
const legacy = /* @__PURE__ */ new Set();
|
|
2019
|
+
return {
|
|
2020
|
+
index: bridge.index,
|
|
2021
|
+
quoteIdOf: bridge.quoteIdOf,
|
|
2022
|
+
async getRfqSwapsPage(filter, page) {
|
|
2023
|
+
assertPageRequest2(page);
|
|
2024
|
+
assertRfqSwapPageFilter(filter);
|
|
2025
|
+
const v2 = await collectRfqSwaps(bridge, filter);
|
|
2026
|
+
const held = new Set(
|
|
2027
|
+
splitRecords(await collectSwapRecords(repository)).corridor.map((r) => r.rfqId)
|
|
2028
|
+
);
|
|
2029
|
+
const v1 = (await readLegacyRfqSwaps(repository, filter)).filter(
|
|
2030
|
+
(record) => !held.has(record.rfqId) && admits(record)
|
|
2031
|
+
);
|
|
2032
|
+
for (const record of v1) legacy.add(record.rfqId);
|
|
2033
|
+
return pageRfqRecords([...v2, ...v1], filter, page);
|
|
2034
|
+
},
|
|
2035
|
+
async getRfqSwap(rfqId) {
|
|
2036
|
+
if (!legacy.has(rfqId)) {
|
|
2037
|
+
const record2 = await bridge.getRfqSwap(rfqId);
|
|
2038
|
+
if (record2 !== void 0) return record2;
|
|
2039
|
+
}
|
|
2040
|
+
const record = await repository.getRfqSwap(rfqId);
|
|
2041
|
+
if (record !== void 0) legacy.add(rfqId);
|
|
2042
|
+
return record;
|
|
2043
|
+
},
|
|
2044
|
+
async saveRfqSwap(record) {
|
|
2045
|
+
if (legacy.has(record.rfqId)) await repository.saveRfqSwap(record);
|
|
2046
|
+
else await bridge.saveRfqSwap(record);
|
|
2047
|
+
},
|
|
2048
|
+
removeRfqSwap: (rfqId) => bridge.removeRfqSwap(rfqId)
|
|
2049
|
+
};
|
|
2050
|
+
};
|
|
2051
|
+
var legacyRfqSwapsToAdopt = async (repository) => {
|
|
2052
|
+
const v1 = await readLegacyRfqSwaps(repository);
|
|
2053
|
+
if (v1.length === 0) return [];
|
|
2054
|
+
const records = await collectSwapRecords(repository);
|
|
2055
|
+
const held = new Set(splitRecords(records).corridor.map((record) => record.rfqId));
|
|
2056
|
+
const ids = new Set(records.map((record) => record.id));
|
|
2057
|
+
return v1.filter((record) => {
|
|
2058
|
+
if (held.has(record.rfqId)) return false;
|
|
2059
|
+
if (ids.has(record.rfqId)) {
|
|
2060
|
+
console.warn(`[swap] v1 rfq swap ${record.rfqId} collides with a v2 record id`);
|
|
2061
|
+
return false;
|
|
2062
|
+
}
|
|
2063
|
+
return true;
|
|
2064
|
+
});
|
|
2065
|
+
};
|
|
2066
|
+
var readLegacyAssetSwaps = async (repository) => {
|
|
2067
|
+
try {
|
|
2068
|
+
return await collectAssetSwaps(repository);
|
|
2069
|
+
} catch (error) {
|
|
2070
|
+
console.warn("[swap] the v1 swaps could not be read", error);
|
|
2071
|
+
return [];
|
|
2072
|
+
}
|
|
2073
|
+
};
|
|
2074
|
+
var legacyOfferDepositsToAdopt = async (repository) => {
|
|
2075
|
+
const unadopted = (await readLegacyAssetSwaps(repository)).filter(
|
|
2076
|
+
(swap) => !!swap.offerHex && !!swap.fundingTxid
|
|
2077
|
+
);
|
|
2078
|
+
if (unadopted.length === 0) return /* @__PURE__ */ new Set();
|
|
2079
|
+
const { offer } = splitRecords(await collectSwapRecords(repository));
|
|
2080
|
+
const adopted = new Set(offer.map((record) => record.fundingTxid));
|
|
2081
|
+
return new Set(unadopted.map((swap) => swap.fundingTxid).filter((txid) => !adopted.has(txid)));
|
|
2082
|
+
};
|
|
2083
|
+
|
|
2084
|
+
// src/client/drive.ts
|
|
2085
|
+
var SwapDriveRefusedError = class extends Error {
|
|
2086
|
+
constructor(reason, detail, swapId) {
|
|
2087
|
+
super(detail);
|
|
2088
|
+
this.reason = reason;
|
|
2089
|
+
this.swapId = swapId;
|
|
2090
|
+
}
|
|
2091
|
+
reason;
|
|
2092
|
+
swapId;
|
|
2093
|
+
name = "SwapDriveRefusedError";
|
|
2094
|
+
};
|
|
2095
|
+
var OFFER_LIVE = (status) => status === "pending" || status === "cancelling";
|
|
2096
|
+
var traderClaimTxid = (swap) => swap.kind === "lightning_send" ? void 0 : swap.claimTxid;
|
|
2097
|
+
var readableRecord = (record) => {
|
|
2098
|
+
if (typeof record?.id !== "string" || record.route?.give === void 0) return false;
|
|
2099
|
+
if (record.assetPayment !== void 0) {
|
|
2100
|
+
try {
|
|
2101
|
+
assetPaymentOf(record.assetPayment, record.expiresAt);
|
|
2102
|
+
} catch {
|
|
2103
|
+
return false;
|
|
2104
|
+
}
|
|
2105
|
+
}
|
|
2106
|
+
if (record.family === "rfq") {
|
|
2107
|
+
return typeof record.rfqId === "string" && typeof record.lockupAddress === "string";
|
|
2108
|
+
}
|
|
2109
|
+
return record.family === "offer" && typeof record.offerHex === "string";
|
|
2110
|
+
};
|
|
2111
|
+
var createSwapDrive = (config) => {
|
|
2112
|
+
const { wallet, operator, repository, corridors, indexer } = config;
|
|
2113
|
+
const mode = config.mode ?? "auto";
|
|
2114
|
+
const now = config.now ?? (() => Math.floor(Date.now() / 1e3));
|
|
2115
|
+
const records = /* @__PURE__ */ new Map();
|
|
2116
|
+
const live = /* @__PURE__ */ new Map();
|
|
2117
|
+
const refunding = /* @__PURE__ */ new Set();
|
|
2118
|
+
const swept = /* @__PURE__ */ new Map();
|
|
2119
|
+
const recoveredIn = /* @__PURE__ */ new Set();
|
|
2120
|
+
const passed = /* @__PURE__ */ new Set();
|
|
2121
|
+
const delivered = /* @__PURE__ */ new Map();
|
|
2122
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
2123
|
+
let disposed = false;
|
|
2124
|
+
let startRequested = mode === "auto";
|
|
2125
|
+
let watcher;
|
|
2126
|
+
let readyPromise;
|
|
2127
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
2128
|
+
let queue = Promise.resolve();
|
|
2129
|
+
const track = (work) => {
|
|
2130
|
+
inFlight.add(work);
|
|
2131
|
+
void work.then(
|
|
2132
|
+
() => inFlight.delete(work),
|
|
2133
|
+
() => inFlight.delete(work)
|
|
2134
|
+
);
|
|
2135
|
+
return work;
|
|
2136
|
+
};
|
|
2137
|
+
const enqueue = (task) => {
|
|
2138
|
+
queue = queue.then(task).catch((error) => {
|
|
2139
|
+
console.warn("[swap] the drive could not register a swap", error);
|
|
1793
2140
|
});
|
|
1794
2141
|
};
|
|
1795
2142
|
const idle = async () => {
|
|
@@ -1808,20 +2155,23 @@ var createSwapDrive = (config) => {
|
|
|
1808
2155
|
return repository;
|
|
1809
2156
|
};
|
|
1810
2157
|
const undrivable = /* @__PURE__ */ new Set();
|
|
2158
|
+
const undrivableLegacy = /* @__PURE__ */ new Set();
|
|
1811
2159
|
let bridge;
|
|
1812
|
-
|
|
1813
|
-
|
|
1814
|
-
|
|
1815
|
-
|
|
1816
|
-
|
|
1817
|
-
|
|
1818
|
-
|
|
1819
|
-
|
|
1820
|
-
|
|
1821
|
-
|
|
1822
|
-
|
|
1823
|
-
|
|
1824
|
-
|
|
2160
|
+
let readThrough;
|
|
2161
|
+
const corridorStore = () => (
|
|
2162
|
+
// LEGACY(v1): unwrap to `bridge` alone once the read-through goes.
|
|
2163
|
+
readThrough ??= withLegacyRfqSwaps(
|
|
2164
|
+
bridge ??= corridorRecordStore(
|
|
2165
|
+
storage(),
|
|
2166
|
+
remember,
|
|
2167
|
+
// Terminal records stay readable but are excluded from the manager's read, sparing
|
|
2168
|
+
// a rebuild per record just to file it `finished`. The index still learns their
|
|
2169
|
+
// `rfqId` (see `getRfqSwapsPage`).
|
|
2170
|
+
(r) => !undrivable.has(r.id) && !isRfqSwapTerminal(r.state)
|
|
2171
|
+
),
|
|
2172
|
+
storage(),
|
|
2173
|
+
(r) => !undrivableLegacy.has(r.rfqId) && !isRfqSwapTerminal(r.state)
|
|
2174
|
+
)
|
|
1825
2175
|
);
|
|
1826
2176
|
const effectiveState = (swap) => {
|
|
1827
2177
|
if (mode === "auto") return swap.state;
|
|
@@ -1830,6 +2180,7 @@ var createSwapDrive = (config) => {
|
|
|
1830
2180
|
return traderClaimTxid(swap) ? "claimed" : "pending";
|
|
1831
2181
|
};
|
|
1832
2182
|
const outcomeOfEntry = (record, current) => {
|
|
2183
|
+
if (fundingWasNotSubmitted(record)) return "cancelled";
|
|
1833
2184
|
if (record.family === "offer") return recordOutcome(record);
|
|
1834
2185
|
if (current === void 0) {
|
|
1835
2186
|
if (isRfqSwapTerminal(record.state)) return corridorOutcome(record.kind, record.state);
|
|
@@ -1857,7 +2208,7 @@ var createSwapDrive = (config) => {
|
|
|
1857
2208
|
};
|
|
1858
2209
|
const updateFor = (id) => {
|
|
1859
2210
|
const record = records.get(id);
|
|
1860
|
-
if (record === void 0) return void 0;
|
|
2211
|
+
if (record === void 0 || !readableRecord(record)) return void 0;
|
|
1861
2212
|
const current = live.get(id);
|
|
1862
2213
|
const outcome = outcomeOfEntry(record, current);
|
|
1863
2214
|
return {
|
|
@@ -1907,8 +2258,15 @@ var createSwapDrive = (config) => {
|
|
|
1907
2258
|
touch(swap.rfqId, swap);
|
|
1908
2259
|
});
|
|
1909
2260
|
let onchainSeams;
|
|
2261
|
+
const liveFeeRate = async (chain) => {
|
|
2262
|
+
try {
|
|
2263
|
+
return await chain.getFeeRate?.();
|
|
2264
|
+
} catch {
|
|
2265
|
+
return void 0;
|
|
2266
|
+
}
|
|
2267
|
+
};
|
|
1910
2268
|
const defaultOnchainClaim = (chain, feeRateSatVb) => {
|
|
1911
|
-
return async (swap, utxo) => {
|
|
2269
|
+
return async (swap, utxo, options) => {
|
|
1912
2270
|
const record = await corridorStore().getRfqSwap(swap.rfqId);
|
|
1913
2271
|
if (!record) {
|
|
1914
2272
|
throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
|
|
@@ -1919,7 +2277,7 @@ var createSwapDrive = (config) => {
|
|
|
1919
2277
|
const signer = await contractSigner(wallet, await identityDescriptor(wallet.identity));
|
|
1920
2278
|
const claimKey = record.profile.claimKey;
|
|
1921
2279
|
if (typeof claimKey === "string") {
|
|
1922
|
-
const held =
|
|
2280
|
+
const held = hex6.encode(await signer.xOnlyPublicKey());
|
|
1923
2281
|
if (held !== claimKey) {
|
|
1924
2282
|
throw new Error(
|
|
1925
2283
|
`this wallet's identity key ${held} is not the payout key ${claimKey} rfq swap ${swap.rfqId} was quoted against \u2014 a wrong seed, or key provisioning has drifted from the identity key`
|
|
@@ -1929,17 +2287,54 @@ var createSwapDrive = (config) => {
|
|
|
1929
2287
|
if (!swap.payoutPkScript) {
|
|
1930
2288
|
throw new Error(`rfq swap ${swap.rfqId} carries no claim payout script`);
|
|
1931
2289
|
}
|
|
2290
|
+
const rate = nextClaimFeeRate({
|
|
2291
|
+
configuredSatVb: feeRateSatVb,
|
|
2292
|
+
utxoAmount: utxo.amount,
|
|
2293
|
+
estimateSatVb: await liveFeeRate(chain),
|
|
2294
|
+
...swap.claimFeeRateSatVb === void 0 ? {} : { lastSatVb: swap.claimFeeRateSatVb },
|
|
2295
|
+
...options?.bump ? { bump: true } : {}
|
|
2296
|
+
});
|
|
1932
2297
|
const { txid } = await track(
|
|
1933
2298
|
claimOnchainFill(chain, {
|
|
1934
2299
|
htlc: swap.htlc,
|
|
1935
2300
|
utxo,
|
|
1936
2301
|
preimage,
|
|
1937
2302
|
payoutPkScript: swap.payoutPkScript,
|
|
1938
|
-
feeRateSatVb,
|
|
1939
|
-
sign: (sighash) => signer.signMessage(sighash, "schnorr")
|
|
2303
|
+
feeRateSatVb: rate,
|
|
2304
|
+
sign: (sighash) => signer.signMessage(sighash, "schnorr"),
|
|
2305
|
+
...swap.claimTxid ? { republish: true } : {}
|
|
1940
2306
|
})
|
|
1941
2307
|
);
|
|
1942
|
-
return { txid };
|
|
2308
|
+
return { txid, feeRateSatVb: rate };
|
|
2309
|
+
};
|
|
2310
|
+
};
|
|
2311
|
+
const defaultOnchainRefund = (chain, feeRateSatVb) => {
|
|
2312
|
+
return async (swap, utxo) => {
|
|
2313
|
+
const record = await corridorStore().getRfqSwap(swap.rfqId);
|
|
2314
|
+
if (!record) {
|
|
2315
|
+
throw new Error(`rfq swap ${swap.rfqId} has no stored record to refund from`);
|
|
2316
|
+
}
|
|
2317
|
+
const descriptor = record.profile.refundDescriptor;
|
|
2318
|
+
if (typeof descriptor !== "string") {
|
|
2319
|
+
throw new Error(
|
|
2320
|
+
`rfq swap ${swap.rfqId} carries no refund descriptor; wire the onchain corridor's refund callback to take its L1 funding back`
|
|
2321
|
+
);
|
|
2322
|
+
}
|
|
2323
|
+
const signer = await contractSigner(wallet, descriptor);
|
|
2324
|
+
const held = hex6.encode(await signer.xOnlyPublicKey());
|
|
2325
|
+
if (held !== record.profile.refundKey) {
|
|
2326
|
+
throw new Error(
|
|
2327
|
+
`the key behind ${descriptor} is ${held}, not the refund key ${String(record.profile.refundKey)} rfq swap ${swap.rfqId}'s HTLC was derived with`
|
|
2328
|
+
);
|
|
2329
|
+
}
|
|
2330
|
+
const { txHex } = await buildHtlcRefund({
|
|
2331
|
+
htlc: swap.htlc,
|
|
2332
|
+
utxo,
|
|
2333
|
+
payoutPkScript: swap.refundPkScript,
|
|
2334
|
+
feeRateSatVb,
|
|
2335
|
+
sign: (sighash) => signer.signMessage(sighash, "schnorr")
|
|
2336
|
+
});
|
|
2337
|
+
return { txid: await track(chain.broadcast(txHex)) };
|
|
1943
2338
|
};
|
|
1944
2339
|
};
|
|
1945
2340
|
const resolveOnchain = async () => {
|
|
@@ -1947,7 +2342,12 @@ var createSwapDrive = (config) => {
|
|
|
1947
2342
|
try {
|
|
1948
2343
|
const deps = (await corridors()).get("onchain").deps;
|
|
1949
2344
|
const claim = deps.claim ?? (deps.claimFeeRateSatVb === void 0 ? void 0 : defaultOnchainClaim(deps.chain, deps.claimFeeRateSatVb));
|
|
1950
|
-
|
|
2345
|
+
const refund = deps.refund ?? (deps.claimFeeRateSatVb === void 0 ? void 0 : defaultOnchainRefund(deps.chain, deps.claimFeeRateSatVb));
|
|
2346
|
+
onchainSeams = {
|
|
2347
|
+
chain: deps.chain,
|
|
2348
|
+
...claim ? { claim } : {},
|
|
2349
|
+
...refund ? { refund } : {}
|
|
2350
|
+
};
|
|
1951
2351
|
managerDeps.chain = deps.chain;
|
|
1952
2352
|
return true;
|
|
1953
2353
|
} catch (error) {
|
|
@@ -1960,6 +2360,7 @@ var createSwapDrive = (config) => {
|
|
|
1960
2360
|
}
|
|
1961
2361
|
};
|
|
1962
2362
|
const drivable = async (record) => !readsChain(record.kind) || await resolveOnchain();
|
|
2363
|
+
const pinnedNetwork = async () => getNetwork2(await config.network());
|
|
1963
2364
|
const claimLockup = async (swap, vtxos, { partiallyClaimed }) => {
|
|
1964
2365
|
const record = await corridorStore().getRfqSwap(swap.rfqId);
|
|
1965
2366
|
if (!record) throw new Error(`rfq swap ${swap.rfqId} has no stored record to claim from`);
|
|
@@ -1977,13 +2378,11 @@ var createSwapDrive = (config) => {
|
|
|
1977
2378
|
receiver: await contractSigner(wallet, secret.signingDescriptor),
|
|
1978
2379
|
preimage: await preimageForSwapRecord(wallet, secret),
|
|
1979
2380
|
vtxos,
|
|
1980
|
-
destinationPkScript:
|
|
1981
|
-
// Passed
|
|
1982
|
-
// check decides WHEN to act, `pushClaim`'s decides whether `P` is
|
|
1983
|
-
// published, and it is the one with nothing between it and the
|
|
1984
|
-
// signature.
|
|
2381
|
+
destinationPkScript: ArkAddress5.decode(payoutAddress).pkScript,
|
|
2382
|
+
// Passed through: `pushClaim`'s own value check decides whether `P` is published.
|
|
1985
2383
|
expectedAmount: swap.expectedAmount,
|
|
1986
|
-
partiallyClaimed
|
|
2384
|
+
partiallyClaimed,
|
|
2385
|
+
network: await pinnedNetwork()
|
|
1987
2386
|
})
|
|
1988
2387
|
);
|
|
1989
2388
|
};
|
|
@@ -2010,9 +2409,10 @@ var createSwapDrive = (config) => {
|
|
|
2010
2409
|
if (mode === "readonly") return;
|
|
2011
2410
|
const push = arkadeRefunder({
|
|
2012
2411
|
operator,
|
|
2013
|
-
|
|
2412
|
+
contracts: lockupSource,
|
|
2014
2413
|
wallet,
|
|
2015
|
-
repository: corridorStore()
|
|
2414
|
+
repository: corridorStore(),
|
|
2415
|
+
network: pinnedNetwork
|
|
2016
2416
|
});
|
|
2017
2417
|
manager.setCallbacks({
|
|
2018
2418
|
refundArkade: async (swap) => {
|
|
@@ -2031,56 +2431,83 @@ var createSwapDrive = (config) => {
|
|
|
2031
2431
|
},
|
|
2032
2432
|
canRefundArkade,
|
|
2033
2433
|
claimLockup,
|
|
2034
|
-
...onchainSeams?.claim ? { claimOnchain: onchainSeams.claim } : {}
|
|
2434
|
+
...onchainSeams?.claim ? { claimOnchain: onchainSeams.claim } : {},
|
|
2435
|
+
...onchainSeams?.refund ? { refundOnchain: onchainSeams.refund } : {}
|
|
2035
2436
|
});
|
|
2036
2437
|
};
|
|
2037
2438
|
let offerSource;
|
|
2038
2439
|
const offers = () => offerSource ??= offerRecordSource(storage(), remember, now);
|
|
2039
|
-
const
|
|
2040
|
-
const funded = offer.filter(
|
|
2041
|
-
(record) => record.fundingTxid !== void 0 && !RETIRABLE.includes(record.status)
|
|
2042
|
-
);
|
|
2043
|
-
if (funded.length === 0) return;
|
|
2440
|
+
const restoreOfferDeposits = async (reopen = []) => {
|
|
2044
2441
|
const store = storage();
|
|
2045
|
-
const [history, scanned, address] = await Promise.all([
|
|
2442
|
+
const [history, scanned, address, network] = await Promise.all([
|
|
2046
2443
|
wallet.getTransactionHistory(),
|
|
2047
2444
|
store.getScannedTxids(),
|
|
2048
|
-
wallet.getAddress()
|
|
2445
|
+
wallet.getAddress(),
|
|
2446
|
+
config.network()
|
|
2049
2447
|
]);
|
|
2050
|
-
const txs = history.map(
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
...tx.key.commitmentTxid ? { roundTxid: tx.key.commitmentTxid } : {},
|
|
2056
|
-
// The scan reads unix SECONDS; a wallet transaction carries ms.
|
|
2057
|
-
...tx.createdAt ? { createdAt: Math.floor(tx.createdAt / 1e3) } : {}
|
|
2058
|
-
}));
|
|
2448
|
+
const txs = history.map(toRestoreTx);
|
|
2449
|
+
const { hrp, serverPubKey: operatorPubkey } = ArkAddress5.decode(address);
|
|
2450
|
+
const reopened = await legacyOfferDepositsToAdopt(store);
|
|
2451
|
+
for (const txid of reopen) reopened.add(txid);
|
|
2452
|
+
const cursor = reopened.size === 0 ? scanned : new Set([...scanned].filter((txid) => !reopened.has(txid)));
|
|
2059
2453
|
const { restored, scannedTxids } = await restoreAssetSwaps(indexer, txs, /* @__PURE__ */ new Set(), {
|
|
2060
|
-
operatorPubkey
|
|
2061
|
-
scanned
|
|
2454
|
+
operatorPubkey,
|
|
2455
|
+
scanned: cursor,
|
|
2456
|
+
hrp,
|
|
2457
|
+
recoveredIn
|
|
2062
2458
|
});
|
|
2063
|
-
const
|
|
2064
|
-
const
|
|
2065
|
-
|
|
2066
|
-
|
|
2067
|
-
|
|
2068
|
-
|
|
2069
|
-
|
|
2070
|
-
|
|
2071
|
-
|
|
2459
|
+
const { offer } = splitRecords(await collectSwapRecords(store));
|
|
2460
|
+
const current = new Map(offer.map((record) => [record.id, record]));
|
|
2461
|
+
const byDeposit = new Map(
|
|
2462
|
+
offer.filter((record) => record.fundingTxid !== void 0).map((record) => [`${record.swapPkScript}:${record.fundingTxid}`, record])
|
|
2463
|
+
);
|
|
2464
|
+
const unstamped = /* @__PURE__ */ new Map();
|
|
2465
|
+
for (const record of offer) {
|
|
2466
|
+
if (record.fundingTxid !== void 0 || !OFFER_LIVE(record.status)) continue;
|
|
2467
|
+
unstamped.set(record.swapPkScript, [
|
|
2468
|
+
...unstamped.get(record.swapPkScript) ?? [],
|
|
2469
|
+
record
|
|
2470
|
+
]);
|
|
2471
|
+
}
|
|
2472
|
+
const write = async (record) => {
|
|
2473
|
+
await store.saveSwapRecord(record);
|
|
2474
|
+
current.set(record.id, record);
|
|
2475
|
+
remember(record);
|
|
2476
|
+
};
|
|
2477
|
+
for (const found of restored) {
|
|
2478
|
+
const known = byDeposit.get(`${found.swapPkScript}:${found.fundingTxid}`);
|
|
2479
|
+
if (known !== void 0) {
|
|
2480
|
+
if (fateMoved(known, found)) await write(withDepositFate(known, found, now()));
|
|
2481
|
+
continue;
|
|
2072
2482
|
}
|
|
2073
|
-
|
|
2483
|
+
const orphan = unstamped.get(found.swapPkScript)?.shift();
|
|
2484
|
+
if (orphan !== void 0) {
|
|
2485
|
+
await write(
|
|
2486
|
+
withDepositFate({ ...orphan, fundingTxid: found.fundingTxid }, found, now())
|
|
2487
|
+
);
|
|
2488
|
+
continue;
|
|
2489
|
+
}
|
|
2490
|
+
await write(restoredOfferRecord(found, network, now()));
|
|
2491
|
+
}
|
|
2492
|
+
const stillLive = /* @__PURE__ */ new Set();
|
|
2493
|
+
for (const record of current.values()) {
|
|
2494
|
+
if (OFFER_LIVE(record.status) && record.fundingTxid) stillLive.add(record.fundingTxid);
|
|
2074
2495
|
}
|
|
2075
2496
|
await store.markTxidsScanned(scannedTxids.filter((txid) => !stillLive.has(txid)));
|
|
2076
2497
|
const registry = managerDeps.contracts;
|
|
2077
2498
|
if (registry) {
|
|
2078
|
-
|
|
2079
|
-
|
|
2499
|
+
await retireSettledOfferContracts(registry, [...current.values()].map(offerFactsOf), {
|
|
2500
|
+
scope: wallet
|
|
2501
|
+
});
|
|
2080
2502
|
}
|
|
2503
|
+
return [...current.values()];
|
|
2081
2504
|
};
|
|
2082
2505
|
const contractsOf = async () => managerDeps.contracts ??= await wallet.getContractManager();
|
|
2506
|
+
const lockupSource = {
|
|
2507
|
+
getContractsWithVtxos: async (filter) => (await contractsOf()).getContractsWithVtxos(filter)
|
|
2508
|
+
};
|
|
2083
2509
|
const registerCorridorSwap = async (record) => {
|
|
2510
|
+
if (fundingWasNotSubmitted(record)) return;
|
|
2084
2511
|
if (mode === "readonly") return;
|
|
2085
2512
|
if (!await drivable(record)) {
|
|
2086
2513
|
undrivable.add(record.id);
|
|
@@ -2112,7 +2539,7 @@ var createSwapDrive = (config) => {
|
|
|
2112
2539
|
wireCallbacks();
|
|
2113
2540
|
await manager.start();
|
|
2114
2541
|
await markPassed();
|
|
2115
|
-
if (!watcher
|
|
2542
|
+
if (!watcher) {
|
|
2116
2543
|
watcher = await watchOfferSwaps({
|
|
2117
2544
|
wallet,
|
|
2118
2545
|
source: offers(),
|
|
@@ -2120,20 +2547,90 @@ var createSwapDrive = (config) => {
|
|
|
2120
2547
|
});
|
|
2121
2548
|
}
|
|
2122
2549
|
};
|
|
2550
|
+
const registerRestoredOffers = async (offers2) => {
|
|
2551
|
+
if (mode === "readonly") return;
|
|
2552
|
+
const live2 = offers2.filter(
|
|
2553
|
+
(record) => record.fundingTxid !== void 0 && !RETIRABLE.includes(record.status)
|
|
2554
|
+
);
|
|
2555
|
+
if (live2.length === 0) return;
|
|
2556
|
+
try {
|
|
2557
|
+
await restoreOfferCoverage(wallet, live2.map(offerFactsOf));
|
|
2558
|
+
} catch (error) {
|
|
2559
|
+
console.warn("[swap] could not register restored offer covenants", error);
|
|
2560
|
+
}
|
|
2561
|
+
};
|
|
2562
|
+
const adoptLegacyRfqSwaps = async (store) => {
|
|
2563
|
+
try {
|
|
2564
|
+
const toAdopt = await legacyRfqSwapsToAdopt(store);
|
|
2565
|
+
if (toAdopt.length === 0) return;
|
|
2566
|
+
const network = await config.network();
|
|
2567
|
+
const contracts = await contractsOf();
|
|
2568
|
+
for (const v1 of toAdopt) {
|
|
2569
|
+
try {
|
|
2570
|
+
const params = await lockupContractParams(contracts, v1.lockupAddress).catch(
|
|
2571
|
+
(error) => {
|
|
2572
|
+
if (error instanceof LockupContractMissing) return void 0;
|
|
2573
|
+
throw error;
|
|
2574
|
+
}
|
|
2575
|
+
);
|
|
2576
|
+
if (params === void 0 && !isRfqSwapTerminal(v1.state)) continue;
|
|
2577
|
+
const refundLocktime = params ? Number(params.refundLocktime) : 0;
|
|
2578
|
+
await store.saveSwapRecord(restoredCorridorRecord(v1, network, refundLocktime));
|
|
2579
|
+
} catch (error) {
|
|
2580
|
+
console.warn(`[swap] could not adopt v1 rfq swap ${v1.rfqId}`, error);
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
} catch (error) {
|
|
2584
|
+
console.warn("[swap] v1 rfq swap adoption did not complete", error);
|
|
2585
|
+
}
|
|
2586
|
+
};
|
|
2587
|
+
const migrateOfferRows = async () => {
|
|
2588
|
+
if (mode === "readonly") return;
|
|
2589
|
+
try {
|
|
2590
|
+
const { skipped } = await migrateV0OfferRows(await wallet.getContractManager());
|
|
2591
|
+
for (const { script, reason } of skipped) {
|
|
2592
|
+
console.warn(`[swap] could not migrate Program v0 offer row ${script}: ${reason}`);
|
|
2593
|
+
}
|
|
2594
|
+
} catch (error) {
|
|
2595
|
+
console.warn("[swap] Program v0 offer row migration did not complete", error);
|
|
2596
|
+
}
|
|
2597
|
+
};
|
|
2123
2598
|
const restore = async () => {
|
|
2599
|
+
void track(migrateOfferRows());
|
|
2124
2600
|
if (!repository) return;
|
|
2125
|
-
|
|
2601
|
+
await adoptLegacyRfqSwaps(repository);
|
|
2602
|
+
const all = await collectSwapRecords(repository);
|
|
2126
2603
|
const { corridor, offer } = splitRecords(all.filter(readableRecord));
|
|
2127
|
-
|
|
2604
|
+
const retiredScripts = /* @__PURE__ */ new Set();
|
|
2605
|
+
for (const record of [...corridor, ...offer]) {
|
|
2606
|
+
records.set(record.id, record);
|
|
2607
|
+
if (mode !== "readonly" && fundingWasNotSubmitted(record)) {
|
|
2608
|
+
const script = record.family === "offer" ? record.swapPkScript : record.lockupPkScript;
|
|
2609
|
+
if (retiredScripts.has(script)) continue;
|
|
2610
|
+
retiredScripts.add(script);
|
|
2611
|
+
try {
|
|
2612
|
+
await retireUnsubmittedFunding(wallet, repository, record, await contractsOf());
|
|
2613
|
+
} catch (error) {
|
|
2614
|
+
console.warn(
|
|
2615
|
+
`[swap] could not restore unsent coverage for ${record.id}`,
|
|
2616
|
+
error
|
|
2617
|
+
);
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
}
|
|
2128
2621
|
const liveCorridor = corridor.filter((record) => !isRfqSwapTerminal(record.state));
|
|
2129
2622
|
const store = corridorStore();
|
|
2130
2623
|
for (const record of liveCorridor) store.index(record);
|
|
2131
|
-
|
|
2624
|
+
const liveLegacy = await legacyLiveRfqSwaps(repository);
|
|
2625
|
+
if (liveCorridor.length > 0 || liveLegacy.length > 0) {
|
|
2132
2626
|
try {
|
|
2133
2627
|
await contractsOf();
|
|
2134
2628
|
for (const record of liveCorridor) {
|
|
2135
2629
|
if (!await drivable(record)) undrivable.add(record.id);
|
|
2136
2630
|
}
|
|
2631
|
+
for (const record of liveLegacy) {
|
|
2632
|
+
if (!await drivable(record)) undrivableLegacy.add(record.rfqId);
|
|
2633
|
+
}
|
|
2137
2634
|
managerDeps.repository = store;
|
|
2138
2635
|
const result = await manager.restoreFromRepository();
|
|
2139
2636
|
for (const swap of result.restored) {
|
|
@@ -2150,13 +2647,19 @@ var createSwapDrive = (config) => {
|
|
|
2150
2647
|
console.warn("[swap] the corridor restore could not drive", error);
|
|
2151
2648
|
}
|
|
2152
2649
|
}
|
|
2650
|
+
let offers2 = offer;
|
|
2153
2651
|
try {
|
|
2154
|
-
await
|
|
2652
|
+
offers2 = await restoreOfferDeposits(
|
|
2653
|
+
offer.flatMap(
|
|
2654
|
+
(record) => record.status === "recoverable" && record.fundingTxid !== void 0 ? [record.fundingTxid] : []
|
|
2655
|
+
)
|
|
2656
|
+
);
|
|
2155
2657
|
} catch (error) {
|
|
2156
|
-
console.warn("[swap] the offer deposit
|
|
2658
|
+
console.warn("[swap] the offer deposit restore did not complete", error);
|
|
2157
2659
|
}
|
|
2660
|
+
await registerRestoredOffers(offers2);
|
|
2158
2661
|
emitAll();
|
|
2159
|
-
if (mode === "auto" && await hasLiveWork(
|
|
2662
|
+
if (mode === "auto" && await hasLiveWork(offers2)) {
|
|
2160
2663
|
try {
|
|
2161
2664
|
await arm();
|
|
2162
2665
|
} catch (error) {
|
|
@@ -2184,7 +2687,7 @@ var createSwapDrive = (config) => {
|
|
|
2184
2687
|
}
|
|
2185
2688
|
return probe.call(wallet);
|
|
2186
2689
|
};
|
|
2187
|
-
const recoverableAt = async (script) => (await findLockupVtxos(
|
|
2690
|
+
const recoverableAt = async (script) => (await findLockupVtxos(lockupSource, script)).filter((vtxo) => vtxo.recoverable);
|
|
2188
2691
|
const recover = async (id) => {
|
|
2189
2692
|
if (disposed) throw new ClientDisposed("recover");
|
|
2190
2693
|
if (mode === "readonly") {
|
|
@@ -2208,7 +2711,7 @@ var createSwapDrive = (config) => {
|
|
|
2208
2711
|
id
|
|
2209
2712
|
);
|
|
2210
2713
|
}
|
|
2211
|
-
const script =
|
|
2714
|
+
const script = hex6.decode(record.lockupPkScript);
|
|
2212
2715
|
const before = await recoverableAt(script);
|
|
2213
2716
|
if (before.length === 0) {
|
|
2214
2717
|
throw new SwapDriveRefusedError(
|
|
@@ -2218,8 +2721,8 @@ var createSwapDrive = (config) => {
|
|
|
2218
2721
|
);
|
|
2219
2722
|
}
|
|
2220
2723
|
const txid2 = await track((await recoverer()).recoverVtxos());
|
|
2221
|
-
const
|
|
2222
|
-
const still = new Set(
|
|
2724
|
+
const after = await recoverableAt(script);
|
|
2725
|
+
const still = new Set(after.map((vtxo) => `${vtxo.txid}:${vtxo.vout}`));
|
|
2223
2726
|
const recovered2 = before.every((vtxo) => !still.has(`${vtxo.txid}:${vtxo.vout}`));
|
|
2224
2727
|
if (recovered2) swept.delete(id);
|
|
2225
2728
|
await manager.poll();
|
|
@@ -2233,10 +2736,31 @@ var createSwapDrive = (config) => {
|
|
|
2233
2736
|
id
|
|
2234
2737
|
);
|
|
2235
2738
|
}
|
|
2236
|
-
const
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2739
|
+
const wentHome = async () => {
|
|
2740
|
+
await restoreOfferDeposits(
|
|
2741
|
+
record.fundingTxid === void 0 ? [] : [record.fundingTxid]
|
|
2742
|
+
);
|
|
2743
|
+
const after = records.get(id);
|
|
2744
|
+
return after?.family === "offer" && after.status !== "recoverable";
|
|
2745
|
+
};
|
|
2746
|
+
try {
|
|
2747
|
+
if (await wentHome()) return { recovered: true, swap: swapView(id) };
|
|
2748
|
+
} catch (error) {
|
|
2749
|
+
console.warn(`[swap] could not re-read offer ${id} before recovering it`, error);
|
|
2750
|
+
}
|
|
2751
|
+
const vtxoManager = await recoverer();
|
|
2752
|
+
await restoreOfferCoverage(wallet, [offerFactsOf(record)]);
|
|
2753
|
+
const txid = await track(vtxoManager.recoverVtxos());
|
|
2754
|
+
recoveredIn.add(txid);
|
|
2755
|
+
let recovered = false;
|
|
2756
|
+
try {
|
|
2757
|
+
recovered = await wentHome();
|
|
2758
|
+
} catch (error) {
|
|
2759
|
+
console.warn(
|
|
2760
|
+
`[swap] recovered offer ${id} in ${txid}, but could not re-read it`,
|
|
2761
|
+
error
|
|
2762
|
+
);
|
|
2763
|
+
}
|
|
2240
2764
|
return { recovered, txid, swap: swapView(id) };
|
|
2241
2765
|
};
|
|
2242
2766
|
const swapView = (id) => {
|
|
@@ -2290,6 +2814,10 @@ var createSwapDrive = (config) => {
|
|
|
2290
2814
|
adopt: (record) => {
|
|
2291
2815
|
if (disposed) throw new ClientDisposed("accept");
|
|
2292
2816
|
records.set(record.id, record);
|
|
2817
|
+
if (fundingWasNotSubmitted(record)) {
|
|
2818
|
+
emit(record.id);
|
|
2819
|
+
return swapView(record.id);
|
|
2820
|
+
}
|
|
2293
2821
|
if (record.family === "rfq") {
|
|
2294
2822
|
corridorStore().index(record);
|
|
2295
2823
|
managerDeps.repository = corridorStore();
|
|
@@ -2325,8 +2853,9 @@ var marketKeyOf = (card) => {
|
|
|
2325
2853
|
}
|
|
2326
2854
|
return base <= quote ? `${base}/${quote}` : `${quote}/${base}`;
|
|
2327
2855
|
};
|
|
2328
|
-
var
|
|
2329
|
-
var
|
|
2856
|
+
var hasRendezvous = (card) => typeof card.discovery_pubkey === "string" && (card.transports?.nostr?.relays?.length ?? 0) > 0;
|
|
2857
|
+
var isAddressable = (card) => !isRfqMarket2(card) || hasRendezvous(card);
|
|
2858
|
+
var marketBackendOf = (card) => isRfqMarket2(card) || hasRendezvous(card) ? "rfq" : "feed";
|
|
2330
2859
|
var usableMarkets = (snapshot, policy) => {
|
|
2331
2860
|
const allowed = policy?.allowedRegistries;
|
|
2332
2861
|
return (allowed ? snapshot.markets.filter((card) => allowed.includes(card.source)) : snapshot.markets).filter(isAddressable);
|
|
@@ -2339,8 +2868,7 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
|
|
|
2339
2868
|
const base = side === "base" ? give : take;
|
|
2340
2869
|
const quote = side === "base" ? take : give;
|
|
2341
2870
|
const selection = {
|
|
2342
|
-
// The trader receives the take leg, so
|
|
2343
|
-
// solver can pay out; a direction nobody solves yields no market.
|
|
2871
|
+
// The trader receives the take leg, so the solver must be able to pay that side out.
|
|
2344
2872
|
wantSide: side === "base" ? "quote" : "base",
|
|
2345
2873
|
...takeAmount === void 0 ? {} : { wantAmount: takeAmount }
|
|
2346
2874
|
};
|
|
@@ -2354,9 +2882,7 @@ var eligibleMarkets = (snapshot, legs, policy, takeAmount) => {
|
|
|
2354
2882
|
quoteId: `${quote.corridor}:${quote.assetId}`,
|
|
2355
2883
|
...selection
|
|
2356
2884
|
});
|
|
2357
|
-
const selected = [...canonical, ...legacy]
|
|
2358
|
-
(card, index, all) => all.indexOf(card) === index
|
|
2359
|
-
);
|
|
2885
|
+
const selected = [.../* @__PURE__ */ new Set([...canonical, ...legacy])];
|
|
2360
2886
|
return selected.map((card) => ({
|
|
2361
2887
|
card,
|
|
2362
2888
|
give: side,
|
|
@@ -2395,7 +2921,8 @@ var SUPPORTED_PAIRS = [
|
|
|
2395
2921
|
"arkade->arkade",
|
|
2396
2922
|
"arkade->lightning",
|
|
2397
2923
|
"lightning->arkade",
|
|
2398
|
-
"arkade->onchain"
|
|
2924
|
+
"arkade->onchain",
|
|
2925
|
+
"onchain->arkade"
|
|
2399
2926
|
];
|
|
2400
2927
|
var isSupportedPair = (pair) => SUPPORTED_PAIRS.includes(pair);
|
|
2401
2928
|
var assembleRoute = (give, take) => {
|
|
@@ -2409,16 +2936,16 @@ var assembleRoute = (give, take) => {
|
|
|
2409
2936
|
}
|
|
2410
2937
|
return { give, take };
|
|
2411
2938
|
};
|
|
2412
|
-
var endpoint = (corridor,
|
|
2939
|
+
var endpoint = (corridor, asset5, instrument) => ({
|
|
2413
2940
|
corridor,
|
|
2414
|
-
asset:
|
|
2941
|
+
asset: asset5,
|
|
2415
2942
|
...instrument === void 0 ? {} : { instrument }
|
|
2416
2943
|
});
|
|
2417
|
-
var legFor = (
|
|
2418
|
-
const leg = toDiscoveryLeg(
|
|
2944
|
+
var legFor = (asset5, expected) => {
|
|
2945
|
+
const leg = toDiscoveryLeg(asset5);
|
|
2419
2946
|
if (expected !== void 0 && leg.corridor !== expected) {
|
|
2420
2947
|
throw new UnsupportedRoute(
|
|
2421
|
-
`${
|
|
2948
|
+
`${asset5} settles on ${leg.corridor}, and this leg is ${expected}`,
|
|
2422
2949
|
{ give: leg.corridor, take: expected }
|
|
2423
2950
|
);
|
|
2424
2951
|
}
|
|
@@ -2456,10 +2983,10 @@ var resolveRoute = async (input, deps) => {
|
|
|
2456
2983
|
}
|
|
2457
2984
|
const pair = `${giveLeg.corridor}->${takeLeg.corridor}`;
|
|
2458
2985
|
if (!isSupportedPair(pair)) {
|
|
2459
|
-
throw new UnsupportedRoute(
|
|
2460
|
-
|
|
2461
|
-
|
|
2462
|
-
);
|
|
2986
|
+
throw new UnsupportedRoute(`${pair} is not an implemented route`, {
|
|
2987
|
+
give: giveLeg.corridor,
|
|
2988
|
+
take: takeLeg.corridor
|
|
2989
|
+
});
|
|
2463
2990
|
}
|
|
2464
2991
|
const give = endpoint(
|
|
2465
2992
|
giveLeg.corridor,
|
|
@@ -2500,11 +3027,9 @@ var resolveRoute = async (input, deps) => {
|
|
|
2500
3027
|
aliases
|
|
2501
3028
|
};
|
|
2502
3029
|
};
|
|
2503
|
-
var isCorridor = (value) => value
|
|
3030
|
+
var isCorridor = (value) => CORRIDORS.includes(value);
|
|
2504
3031
|
var assetFor = (ref, corridor, network, aliases) => ref === void 0 ? btcOn(railOfCorridor(corridor), network) : (
|
|
2505
|
-
//
|
|
2506
|
-
// whole-table lookup would refuse `"BTC"` as ambiguous on any snapshot
|
|
2507
|
-
// carrying a corridor market — see `scopedToRail`.
|
|
3032
|
+
// Rail-scoped: BTC has one id per rail, so a whole-table `"BTC"` is ambiguous.
|
|
2508
3033
|
canonicalAssetId(ref, scopedToRail(aliases, railOfCorridor(corridor)))
|
|
2509
3034
|
);
|
|
2510
3035
|
var pinAmount = (input, takeInstrument) => {
|
|
@@ -2525,6 +3050,9 @@ var pinAmount = (input, takeInstrument) => {
|
|
|
2525
3050
|
return void 0;
|
|
2526
3051
|
};
|
|
2527
3052
|
|
|
3053
|
+
// src/client/policy.ts
|
|
3054
|
+
var DEFAULT_MAX_REFUND_WINDOW_SECONDS = 30 * 24 * 3600;
|
|
3055
|
+
|
|
2528
3056
|
// src/client/verify.ts
|
|
2529
3057
|
var reasonOf = (error) => error instanceof Error && typeof error.reason === "string" ? error.reason : void 0;
|
|
2530
3058
|
var CHECK_BY_REASON = {
|
|
@@ -2676,15 +3204,24 @@ var verifyQuoteTtl = (input) => {
|
|
|
2676
3204
|
throw new QuoteExpired(input.quoteId, input.expiresAt, input.now);
|
|
2677
3205
|
}
|
|
2678
3206
|
};
|
|
2679
|
-
var
|
|
2680
|
-
|
|
2681
|
-
|
|
3207
|
+
var CSV_GRANULARITY_SECONDS = 512;
|
|
3208
|
+
var verifyRefundWindow = (input) => {
|
|
3209
|
+
const max = input.maxSeconds ?? DEFAULT_MAX_REFUND_WINDOW_SECONDS;
|
|
3210
|
+
const window = input.refundLocktime - input.now;
|
|
3211
|
+
if (!(window <= max)) {
|
|
3212
|
+
throw new QuoteVerificationFailed("refund_window", `at most ${max}s`, `${window}s`);
|
|
3213
|
+
}
|
|
3214
|
+
const delay = input.refundWithoutReceiverDelay;
|
|
3215
|
+
if (delay !== void 0 && !(delay < max + CSV_GRANULARITY_SECONDS)) {
|
|
2682
3216
|
throw new QuoteVerificationFailed(
|
|
2683
|
-
"
|
|
2684
|
-
|
|
2685
|
-
`${
|
|
3217
|
+
"refund_window",
|
|
3218
|
+
`a solo-refund delay of at most ${max}s`,
|
|
3219
|
+
`${delay}s`
|
|
2686
3220
|
);
|
|
2687
3221
|
}
|
|
3222
|
+
};
|
|
3223
|
+
var verifyQuotedAmount = (input) => {
|
|
3224
|
+
verifyPinnedAmount(input);
|
|
2688
3225
|
if (input.take > input.give) {
|
|
2689
3226
|
throw new QuoteVerificationFailed(
|
|
2690
3227
|
"pair",
|
|
@@ -2693,10 +3230,44 @@ var verifyQuotedAmount = (input) => {
|
|
|
2693
3230
|
);
|
|
2694
3231
|
}
|
|
2695
3232
|
};
|
|
3233
|
+
var verifyCrossAssetAmount = (input) => {
|
|
3234
|
+
verifyPinnedAmount(input);
|
|
3235
|
+
if (input.give <= 0n || input.take <= 0n) {
|
|
3236
|
+
throw new QuoteVerificationFailed(
|
|
3237
|
+
"pair",
|
|
3238
|
+
`${input.pair} give > 0 take > 0`,
|
|
3239
|
+
`give=${input.give} take=${input.take}`
|
|
3240
|
+
);
|
|
3241
|
+
}
|
|
3242
|
+
};
|
|
3243
|
+
var verifiedCarrierSats = (quote) => {
|
|
3244
|
+
try {
|
|
3245
|
+
return quoteCarrierSats(quote);
|
|
3246
|
+
} catch (error) {
|
|
3247
|
+
if (reasonOf(error) !== "carrier_malformed") throw error;
|
|
3248
|
+
throw new QuoteVerificationFailed(
|
|
3249
|
+
"pair",
|
|
3250
|
+
"carrier_sats a non-negative integer",
|
|
3251
|
+
String(quote.carrier_sats),
|
|
3252
|
+
{ cause: error }
|
|
3253
|
+
);
|
|
3254
|
+
}
|
|
3255
|
+
};
|
|
3256
|
+
var verifyPinnedAmount = (input) => {
|
|
3257
|
+
const quoted = input.pinned.on === "give" ? input.give : input.take;
|
|
3258
|
+
if (quoted !== input.pinned.value) {
|
|
3259
|
+
throw new QuoteVerificationFailed(
|
|
3260
|
+
"pair",
|
|
3261
|
+
`${input.pair} ${input.pinned.on}=${input.pinned.value}`,
|
|
3262
|
+
`${input.pair} ${input.pinned.on}=${quoted}`
|
|
3263
|
+
);
|
|
3264
|
+
}
|
|
3265
|
+
};
|
|
2696
3266
|
|
|
2697
3267
|
// src/client/quoteOffer.ts
|
|
2698
3268
|
import {
|
|
2699
3269
|
computeWantAmount,
|
|
3270
|
+
marketLegKey as marketLegKey2,
|
|
2700
3271
|
quoteOffer
|
|
2701
3272
|
} from "@arkade-os/solver-discovery";
|
|
2702
3273
|
var FEED_TTL_MS = 3e4;
|
|
@@ -2716,6 +3287,9 @@ var quoteFromFeed = async (input) => {
|
|
|
2716
3287
|
const plan = await quoteOffer(candidate.card, {
|
|
2717
3288
|
give: candidate.give,
|
|
2718
3289
|
...amount.on === "give" ? { giveAmount: amount.value } : { wantAmount: amount.value },
|
|
3290
|
+
// What `fund` attaches to an asset deposit and the fill pays an asset want: the plan asks
|
|
3291
|
+
// for it back in a BTC payout, and charges it where the card declares a delivered carrier.
|
|
3292
|
+
carrierSats: ASSET_CARRIER_SATS,
|
|
2719
3293
|
...QUOTE_OPTIONS,
|
|
2720
3294
|
fetchImpl: input.feed.fetch
|
|
2721
3295
|
});
|
|
@@ -2739,12 +3313,21 @@ var quoteFromFeed = async (input) => {
|
|
|
2739
3313
|
take: { asset: input.endpoints.take.asset, amount: plan.receive.atomic },
|
|
2740
3314
|
market: input.market,
|
|
2741
3315
|
expiresAt,
|
|
2742
|
-
fee: {
|
|
3316
|
+
fee: {
|
|
3317
|
+
// The plan's payout returns the deposit's carrier; that part is not proceeds.
|
|
3318
|
+
amount: feedSpread(
|
|
3319
|
+
plan,
|
|
3320
|
+
plan.receive.atomic,
|
|
3321
|
+
sellsAssetForBtc(input.endpoints) ? ASSET_CARRIER_SATS : 0n
|
|
3322
|
+
),
|
|
3323
|
+
asset: input.endpoints.take.asset
|
|
3324
|
+
}
|
|
2743
3325
|
},
|
|
2744
3326
|
preparation: { backend: "feed", card: candidate.card, plan, give: candidate.give }
|
|
2745
3327
|
};
|
|
2746
3328
|
};
|
|
2747
|
-
var
|
|
3329
|
+
var feedSpread = (plan, take, carrierSats = 0n) => {
|
|
3330
|
+
const payout = take > carrierSats ? take - carrierSats : 0n;
|
|
2748
3331
|
const fair = computeWantAmount({
|
|
2749
3332
|
deposit: plan.deposit.atomic,
|
|
2750
3333
|
give: plan.give,
|
|
@@ -2752,22 +3335,110 @@ var spreadOf = (plan) => {
|
|
|
2752
3335
|
feeBps: 0,
|
|
2753
3336
|
safetyBps: 0
|
|
2754
3337
|
});
|
|
2755
|
-
const spread = fair -
|
|
3338
|
+
const spread = fair - payout;
|
|
2756
3339
|
return spread > 0n ? spread : 0n;
|
|
2757
3340
|
};
|
|
3341
|
+
var sellsAssetForBtc = (endpoints) => !isBtcAsset(endpoints.give.asset) && isBtcAsset(endpoints.take.asset);
|
|
2758
3342
|
var feedExpiry = (card, feed, now) => {
|
|
2759
3343
|
const readAt = card.price_feed === void 0 ? void 0 : feed.fetchedAt(card.price_feed);
|
|
2760
3344
|
const from = readAt === void 0 ? now : Math.floor(readAt / 1e3);
|
|
2761
3345
|
return from + FEED_TTL_MS / 1e3;
|
|
2762
3346
|
};
|
|
2763
3347
|
var verifyPlanLegs = (plan, legs, give) => {
|
|
2764
|
-
const
|
|
2765
|
-
const
|
|
2766
|
-
|
|
2767
|
-
|
|
3348
|
+
const take = give === "base" ? "quote" : "base";
|
|
3349
|
+
const spelled = (side) => marketLegKey2(plan.market, side);
|
|
3350
|
+
const names = (side, leg) => spelled(side) === leg.marketId || spelled(side) === `${leg.corridor}:${leg.assetId}`;
|
|
3351
|
+
if (plan.give !== give || !names(give, legs.give) || !names(take, legs.take)) {
|
|
3352
|
+
throw new QuoteVerificationFailed(
|
|
3353
|
+
"pair",
|
|
3354
|
+
`${legs.give.marketId}->${legs.take.marketId}`,
|
|
3355
|
+
`${spelled(give)}->${spelled(take)}`
|
|
3356
|
+
);
|
|
2768
3357
|
}
|
|
2769
3358
|
};
|
|
2770
3359
|
|
|
3360
|
+
// src/jointGraph.ts
|
|
3361
|
+
import { base64 as base642, hex as hex7 } from "@scure/base";
|
|
3362
|
+
import { sha256 as sha2562 } from "@noble/hashes/sha2.js";
|
|
3363
|
+
import { Transaction as Transaction2 } from "@arkade-os/sdk";
|
|
3364
|
+
function digestJointGraph(plan, template) {
|
|
3365
|
+
const parts = [];
|
|
3366
|
+
const pushU32 = (value) => {
|
|
3367
|
+
const len = new Uint8Array(4);
|
|
3368
|
+
new DataView(len.buffer).setUint32(0, value, false);
|
|
3369
|
+
parts.push(len);
|
|
3370
|
+
};
|
|
3371
|
+
const pushField = (bytes) => {
|
|
3372
|
+
pushU32(bytes.length);
|
|
3373
|
+
parts.push(bytes);
|
|
3374
|
+
};
|
|
3375
|
+
pushField(new TextEncoder().encode(template));
|
|
3376
|
+
pushField(unsignedPsbtBytes(parseGraphTx(plan.arkTx)));
|
|
3377
|
+
pushU32(plan.checkpoints.length);
|
|
3378
|
+
for (const checkpoint of plan.checkpoints) {
|
|
3379
|
+
pushField(unsignedPsbtBytes(parseGraphTx(checkpoint)));
|
|
3380
|
+
}
|
|
3381
|
+
pushU32(plan.inputOwners.length);
|
|
3382
|
+
for (const owner of plan.inputOwners) {
|
|
3383
|
+
if (owner === null) {
|
|
3384
|
+
parts.push(new Uint8Array([0]));
|
|
3385
|
+
} else {
|
|
3386
|
+
const bytes = new TextEncoder().encode(owner);
|
|
3387
|
+
parts.push(new Uint8Array([1]));
|
|
3388
|
+
pushField(bytes);
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
const preimage = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
3392
|
+
let at = 0;
|
|
3393
|
+
for (const part of parts) {
|
|
3394
|
+
preimage.set(part, at);
|
|
3395
|
+
at += part.length;
|
|
3396
|
+
}
|
|
3397
|
+
return hex7.encode(sha2562(preimage));
|
|
3398
|
+
}
|
|
3399
|
+
function verifyJointGraph(plan, template) {
|
|
3400
|
+
try {
|
|
3401
|
+
if (!plan || typeof plan !== "object") return false;
|
|
3402
|
+
if (typeof plan.arkTx !== "string" || plan.arkTx.length === 0) return false;
|
|
3403
|
+
if (!Array.isArray(plan.checkpoints) || plan.checkpoints.length < 1 || plan.checkpoints.some((c) => typeof c !== "string" || c.length === 0))
|
|
3404
|
+
return false;
|
|
3405
|
+
if (!/^[0-9a-f]{64}$/.test(plan.graphId)) return false;
|
|
3406
|
+
if (!Array.isArray(plan.inputOwners) || plan.inputOwners.some((o) => o !== null && (typeof o !== "string" || o.length === 0)))
|
|
3407
|
+
return false;
|
|
3408
|
+
if (plan.inputOwners.length !== plan.checkpoints.length) return false;
|
|
3409
|
+
const arkInputs = parseGraphTx(plan.arkTx).inputsLength;
|
|
3410
|
+
if (plan.checkpoints.length !== arkInputs) return false;
|
|
3411
|
+
if (plan.inputOwners.length !== arkInputs) return false;
|
|
3412
|
+
return digestJointGraph(
|
|
3413
|
+
{
|
|
3414
|
+
arkTx: plan.arkTx,
|
|
3415
|
+
checkpoints: [...plan.checkpoints],
|
|
3416
|
+
inputOwners: [...plan.inputOwners]
|
|
3417
|
+
},
|
|
3418
|
+
template
|
|
3419
|
+
) === plan.graphId;
|
|
3420
|
+
} catch {
|
|
3421
|
+
return false;
|
|
3422
|
+
}
|
|
3423
|
+
}
|
|
3424
|
+
function parseGraphTx(psbt) {
|
|
3425
|
+
return Transaction2.fromPSBT(base642.decode(psbt));
|
|
3426
|
+
}
|
|
3427
|
+
function deepFreeze(value) {
|
|
3428
|
+
if (value !== null && typeof value === "object") {
|
|
3429
|
+
for (const child of Object.values(value)) deepFreeze(child);
|
|
3430
|
+
Object.freeze(value);
|
|
3431
|
+
}
|
|
3432
|
+
return value;
|
|
3433
|
+
}
|
|
3434
|
+
function unsignedPsbtBytes(tx) {
|
|
3435
|
+
const stripped = tx.clone();
|
|
3436
|
+
for (let i = 0; i < stripped.inputsLength; i++) {
|
|
3437
|
+
stripped.updateInput(i, { tapScriptSig: void 0 });
|
|
3438
|
+
}
|
|
3439
|
+
return stripped.toPSBT();
|
|
3440
|
+
}
|
|
3441
|
+
|
|
2771
3442
|
// src/client/sats.ts
|
|
2772
3443
|
var satsOf = (value, field) => {
|
|
2773
3444
|
if (value < 0n || value > BigInt(Number.MAX_SAFE_INTEGER)) {
|
|
@@ -2785,8 +3456,7 @@ var PAYMENT_STATUS = {
|
|
|
2785
3456
|
/** Persisted, funding not broadcast. */
|
|
2786
3457
|
accepted: "pending",
|
|
2787
3458
|
funding: "pending",
|
|
2788
|
-
/** The lockup is funded.
|
|
2789
|
-
* `onchain-swap` rail left with `packages/boltz-swap`. */
|
|
3459
|
+
/** The lockup is funded. */
|
|
2790
3460
|
funded: "sent",
|
|
2791
3461
|
/** Asset swaps only: an unfilled offer. */
|
|
2792
3462
|
open: "pending",
|
|
@@ -2850,14 +3520,19 @@ var receiverExact = (railId, parts) => {
|
|
|
2850
3520
|
total: satsOf(parts.total, `${railId}.total`)
|
|
2851
3521
|
};
|
|
2852
3522
|
};
|
|
3523
|
+
var quoteMeta = (quote) => ({
|
|
3524
|
+
quoteId: quote.id,
|
|
3525
|
+
expiresAt: quote.expiresAt,
|
|
3526
|
+
...quote.refundLocktime === void 0 ? {} : { refundLocktime: quote.refundLocktime },
|
|
3527
|
+
...quote.solver === void 0 ? {} : { solver: quote.solver },
|
|
3528
|
+
...quote.lock === void 0 ? {} : { paymentHash: quote.lock.hash },
|
|
3529
|
+
...quote.market.kind === "restored" ? {} : { market: quote.market.key }
|
|
3530
|
+
});
|
|
2853
3531
|
var resultOf = (railId, swap) => ({
|
|
2854
3532
|
railId,
|
|
2855
|
-
//
|
|
2856
|
-
// which is where the outcomes past this handle's terminal one are read.
|
|
3533
|
+
// tagged, so it joins `client.swaps()`/`onUpdate` for outcomes past this handle's terminal one
|
|
2857
3534
|
swapId: swap.id,
|
|
2858
|
-
//
|
|
2859
|
-
// every other rail. A swap's later legs — the solver's fill, the trader's
|
|
2860
|
-
// L1 claim — are the client's to report, not the handle's.
|
|
3535
|
+
// the tx that left THIS wallet, as on every other rail; later legs are the client's to report
|
|
2861
3536
|
...swap.fundingTxid === void 0 ? {} : { txid: swap.fundingTxid }
|
|
2862
3537
|
});
|
|
2863
3538
|
var swapHandle = async (railId, client, quote) => makeHandle(railId, async (emit) => {
|
|
@@ -2937,8 +3612,7 @@ function onchainSwapRail(client, deps) {
|
|
|
2937
3612
|
}
|
|
2938
3613
|
const amounts = receiverExact(ONCHAIN_SWAP_RAIL, {
|
|
2939
3614
|
amount: payout,
|
|
2940
|
-
//
|
|
2941
|
-
// spread, and the claim the trader pays for out of the payout.
|
|
3615
|
+
// The solver's spread plus the claim the trader pays out of the payout.
|
|
2942
3616
|
fee: quote.fee.amount + claimFee,
|
|
2943
3617
|
total: quote.give.amount
|
|
2944
3618
|
});
|
|
@@ -2946,13 +3620,7 @@ function onchainSwapRail(client, deps) {
|
|
|
2946
3620
|
railId: ONCHAIN_SWAP_RAIL,
|
|
2947
3621
|
...amounts,
|
|
2948
3622
|
meta: {
|
|
2949
|
-
|
|
2950
|
-
expiresAt: quote.expiresAt,
|
|
2951
|
-
...quote.refundLocktime === void 0 ? {} : { refundLocktime: quote.refundLocktime },
|
|
2952
|
-
...quote.solver === void 0 ? {} : { solver: quote.solver },
|
|
2953
|
-
...quote.lock === void 0 ? {} : { paymentHash: quote.lock.hash },
|
|
2954
|
-
market: quote.market.key,
|
|
2955
|
-
// The estimate folded into `fee`, so a caller can see it.
|
|
3623
|
+
...quoteMeta(quote),
|
|
2956
3624
|
claimFeeSats: Number(claimFee),
|
|
2957
3625
|
// What the solver locks on L1, before the claim's fee.
|
|
2958
3626
|
htlcAmountSats: Number(quote.take.amount)
|
|
@@ -2992,22 +3660,29 @@ var parseRfqQuote = (quote) => ({
|
|
|
2992
3660
|
});
|
|
2993
3661
|
|
|
2994
3662
|
// src/client/quoteRfq.ts
|
|
2995
|
-
import { hex as
|
|
3663
|
+
import { hex as hex8 } from "@scure/base";
|
|
2996
3664
|
import {
|
|
3665
|
+
ArkAddress as ArkAddress6,
|
|
3666
|
+
asset as asset4,
|
|
2997
3667
|
networkFromArkadeInfo,
|
|
2998
3668
|
provisionClaimSecret,
|
|
2999
3669
|
provisionRefundKey,
|
|
3000
3670
|
toXOnly
|
|
3001
3671
|
} from "@arkade-os/sdk";
|
|
3672
|
+
import { quoteOffer as quoteOffer2 } from "@arkade-os/solver-discovery";
|
|
3673
|
+
var lockupOf = (derived) => ({
|
|
3674
|
+
address: derived.address,
|
|
3675
|
+
script: derived.script,
|
|
3676
|
+
pkScript: derived.swapPkScript
|
|
3677
|
+
});
|
|
3002
3678
|
var covenantInputs = (input) => {
|
|
3003
3679
|
const network = networkFromArkadeInfo(input.info);
|
|
3004
|
-
const
|
|
3680
|
+
const arkade2 = input.corridors.get("arkade").deps;
|
|
3005
3681
|
return {
|
|
3006
|
-
operatorPubkey: toXOnly(
|
|
3007
|
-
// The per-network pin
|
|
3008
|
-
// the operator reports about itself: this one ends up in a covenant leaf
|
|
3682
|
+
operatorPubkey: toXOnly(hex8.decode(input.info.signerPubkey), "ark signer key"),
|
|
3683
|
+
// The resolved per-network pin, never operator-reported: it lands in a covenant leaf
|
|
3009
3684
|
// that decides who can move the funds.
|
|
3010
|
-
emulatorPubkey: toXOnly(
|
|
3685
|
+
emulatorPubkey: toXOnly(hex8.decode(arkade2.emulatorPubkey), "emulator signer key"),
|
|
3011
3686
|
claimDelay: unilateralClaimDelay(Number(input.info.unilateralExitDelay)),
|
|
3012
3687
|
hrp: network.hrp
|
|
3013
3688
|
};
|
|
@@ -3015,7 +3690,7 @@ var covenantInputs = (input) => {
|
|
|
3015
3690
|
var sealingKey = (deps) => {
|
|
3016
3691
|
const configured = deps.covclaimd?.pubkey;
|
|
3017
3692
|
if (configured === void 0) return void 0;
|
|
3018
|
-
const key =
|
|
3693
|
+
const key = hex8.decode(configured);
|
|
3019
3694
|
if (key.length !== 33) {
|
|
3020
3695
|
throw new Error(
|
|
3021
3696
|
`the covclaimd deployment key must be 33-byte compressed hex, got ${key.length} bytes`
|
|
@@ -3035,15 +3710,199 @@ var quoteViaRfq = async (input) => {
|
|
|
3035
3710
|
expected: input.market.discoveryPubkey,
|
|
3036
3711
|
pinnable: input.market.snapshot.live
|
|
3037
3712
|
});
|
|
3713
|
+
if (input.assetPayment !== void 0 && input.route !== "arkade->arkade")
|
|
3714
|
+
throw new Error("assetPayment supports BTC-to-asset only");
|
|
3038
3715
|
switch (input.route) {
|
|
3716
|
+
case "arkade->arkade":
|
|
3717
|
+
return quoteArkadeAsset(input);
|
|
3039
3718
|
case "arkade->lightning":
|
|
3040
3719
|
return quoteLightningSend(input);
|
|
3041
3720
|
case "lightning->arkade":
|
|
3042
3721
|
return quoteLightningReceive(input);
|
|
3043
3722
|
case "arkade->onchain":
|
|
3044
3723
|
return quoteOnchainSend(input);
|
|
3724
|
+
case "onchain->arkade":
|
|
3725
|
+
return quoteOnchainReceive(input);
|
|
3045
3726
|
}
|
|
3046
3727
|
};
|
|
3728
|
+
var quoteArkadeAsset = async (input) => {
|
|
3729
|
+
const pinned = pinnedFor(input);
|
|
3730
|
+
const sides = assetSidesOf(input.legs);
|
|
3731
|
+
if (pinned.on !== "give" && sides.wantAsset === void 0)
|
|
3732
|
+
throw new Error("asset-to-BTC is exact-in only");
|
|
3733
|
+
const payment = input.assetPayment;
|
|
3734
|
+
if (payment !== void 0 && sides.wantAsset === void 0)
|
|
3735
|
+
throw new Error("assetPayment supports BTC-to-asset only");
|
|
3736
|
+
if (input.candidate.card.price_feed === void 0) {
|
|
3737
|
+
throw new UnsupportedRoute(
|
|
3738
|
+
`card ${input.candidate.card.solver} advertises no price feed to measure an asset swap's fee against`,
|
|
3739
|
+
{ give: "arkade", take: "arkade" }
|
|
3740
|
+
);
|
|
3741
|
+
}
|
|
3742
|
+
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
3743
|
+
const rfqId = newRfqId();
|
|
3744
|
+
const maker = await makerPosition(input.wallet);
|
|
3745
|
+
const receiveAddress = payment?.receiveAddress;
|
|
3746
|
+
const receivePkScript = resolveReceivePkScript(
|
|
3747
|
+
receiveAddress,
|
|
3748
|
+
maker.pkScript,
|
|
3749
|
+
networkFromArkadeInfo(input.info).hrp,
|
|
3750
|
+
toXOnly(hex8.decode(input.info.signerPubkey), "ark signer key")
|
|
3751
|
+
);
|
|
3752
|
+
const choice = payment?.carrier;
|
|
3753
|
+
const carrierRequest = choice === void 0 ? void 0 : choice.mode === "purchase" ? { mode: "purchase" } : {
|
|
3754
|
+
mode: "recycle_receiver",
|
|
3755
|
+
quoteId: choice.quote.quoteId,
|
|
3756
|
+
taxiUrl: choice.taxi.url,
|
|
3757
|
+
taxiKey: choice.taxi.operatorKey
|
|
3758
|
+
};
|
|
3759
|
+
if (choice?.mode === "recycleReceiver") {
|
|
3760
|
+
if (choice.quote.assetId !== sides.wantAsset?.toString())
|
|
3761
|
+
throw new Error("carrier quote assetId differs from requested asset");
|
|
3762
|
+
if (choice.quote.senderKey !== hex8.encode(maker.publicKey))
|
|
3763
|
+
throw new Error("carrier quote senderKey differs from wallet identity");
|
|
3764
|
+
if (input.now >= choice.quote.expiresAt - 30)
|
|
3765
|
+
throw new Error("carrier quote expired before RFQ");
|
|
3766
|
+
}
|
|
3767
|
+
const request = arkadeSwapRequest({
|
|
3768
|
+
rfqId,
|
|
3769
|
+
...sides,
|
|
3770
|
+
amount: pinned.value,
|
|
3771
|
+
amountSide: toRfqAmountSide(pinned.on),
|
|
3772
|
+
makerPkScript: receivePkScript,
|
|
3773
|
+
makerPublicKey: maker.publicKey
|
|
3774
|
+
});
|
|
3775
|
+
const wire = await input.transport.requestQuote({
|
|
3776
|
+
...request,
|
|
3777
|
+
profile: {
|
|
3778
|
+
...request.profile,
|
|
3779
|
+
...carrierRequest === void 0 ? {} : { carrier: encodeCarrierRequest(carrierRequest) }
|
|
3780
|
+
}
|
|
3781
|
+
});
|
|
3782
|
+
verifyPair(wire.pair, pair);
|
|
3783
|
+
const parsed = parseRfqQuote(wire);
|
|
3784
|
+
verifyCrossAssetAmount({ pair, pinned, give: parsed.give, take: parsed.take });
|
|
3785
|
+
verifyQuoteTtl({
|
|
3786
|
+
quoteId: input.quoteId,
|
|
3787
|
+
expiresAt: parsed.validUntil,
|
|
3788
|
+
now: input.now,
|
|
3789
|
+
floorSeconds: input.policy?.quoteTtlFloorSeconds
|
|
3790
|
+
});
|
|
3791
|
+
let assetPayment;
|
|
3792
|
+
if (payment !== void 0) {
|
|
3793
|
+
let carrier;
|
|
3794
|
+
if (carrierRequest !== void 0) {
|
|
3795
|
+
carrier = parseCarrierEcho(wire.profile?.carrier, carrierRequest);
|
|
3796
|
+
if (carrier.physicalSats !== input.info.dust)
|
|
3797
|
+
throw new Error("carrier physical differs from server dust");
|
|
3798
|
+
if (carrier.expiresAt > parsed.validUntil)
|
|
3799
|
+
throw new Error("carrier echo extends solver expiry");
|
|
3800
|
+
if (choice?.mode === "recycleReceiver") {
|
|
3801
|
+
if (wire.carrier_sats !== void 0)
|
|
3802
|
+
throw new Error("receiver-paid quote must publish no carrier_sats");
|
|
3803
|
+
assertReceiverPaidEchoMatchesExpected(carrier, choice.quote);
|
|
3804
|
+
} else if (parseTopLevelCarrierSats(wire.carrier_sats) !== carrier.physicalSats)
|
|
3805
|
+
throw new Error("carrier echo differs from carrier_sats");
|
|
3806
|
+
}
|
|
3807
|
+
const validUntil = Math.min(
|
|
3808
|
+
parsed.validUntil,
|
|
3809
|
+
carrier?.expiresAt ?? parsed.validUntil,
|
|
3810
|
+
choice?.mode === "recycleReceiver" ? choice.quote.expiresAt : parsed.validUntil
|
|
3811
|
+
) - 30;
|
|
3812
|
+
if (input.now >= validUntil) throw new Error("asset payment terms lapsed before funding");
|
|
3813
|
+
assetPayment = {
|
|
3814
|
+
receiveAddress: receiveAddress ?? new ArkAddress6(
|
|
3815
|
+
toXOnly(hex8.decode(input.info.signerPubkey), "ark signer key"),
|
|
3816
|
+
maker.pkScript.slice(2),
|
|
3817
|
+
networkFromArkadeInfo(input.info).hrp
|
|
3818
|
+
).encode(),
|
|
3819
|
+
validUntil,
|
|
3820
|
+
...carrier === void 0 ? {} : { carrier },
|
|
3821
|
+
...choice?.mode !== "recycleReceiver" || choice.inputExpiryFloor === void 0 ? {} : { inputExpiryFloor: choice.inputExpiryFloor }
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
if (assetPayment !== void 0) deepFreeze(assetPayment);
|
|
3825
|
+
const carrierSats = sides.offerAsset === void 0 ? void 0 : verifiedCarrierSats(wire);
|
|
3826
|
+
const reference = await quoteOffer2(input.candidate.card, {
|
|
3827
|
+
give: input.candidate.give,
|
|
3828
|
+
giveAmount: parsed.give,
|
|
3829
|
+
...carrierSats === void 0 ? {} : { carrierSats },
|
|
3830
|
+
...QUOTE_OPTIONS,
|
|
3831
|
+
fetchImpl: input.feed.fetch
|
|
3832
|
+
});
|
|
3833
|
+
verifyPlanLegs(reference, input.legs, input.candidate.give);
|
|
3834
|
+
const terms = offerTermsFromQuote(wire, sides);
|
|
3835
|
+
const offer = await deriveOffer(input.wallet, {
|
|
3836
|
+
wantAmount: terms.wantAmount,
|
|
3837
|
+
...terms.wantAsset === void 0 ? {} : { wantAsset: terms.wantAsset },
|
|
3838
|
+
...terms.offerAsset === void 0 ? {} : { offerAsset: terms.offerAsset },
|
|
3839
|
+
emulatorPubkey: input.corridors.get("arkade").deps.emulatorPubkey,
|
|
3840
|
+
maker,
|
|
3841
|
+
...receiveAddress === void 0 ? {} : { receiveAddress },
|
|
3842
|
+
info: input.info
|
|
3843
|
+
});
|
|
3844
|
+
verifyingDerivation(() => verifyOfferAddress(wire, offer));
|
|
3845
|
+
return {
|
|
3846
|
+
quote: {
|
|
3847
|
+
id: input.quoteId,
|
|
3848
|
+
...assetPayment === void 0 ? {} : { assetPayment },
|
|
3849
|
+
route: assembleRoute(
|
|
3850
|
+
{ ...input.endpoints.give, instrument: { kind: "wallet" } },
|
|
3851
|
+
{
|
|
3852
|
+
...input.endpoints.take,
|
|
3853
|
+
instrument: receiveAddress === void 0 ? { kind: "wallet" } : { kind: "address", address: receiveAddress }
|
|
3854
|
+
}
|
|
3855
|
+
),
|
|
3856
|
+
give: { asset: input.endpoints.give.asset, amount: parsed.give },
|
|
3857
|
+
take: { asset: input.endpoints.take.asset, amount: parsed.take },
|
|
3858
|
+
market: input.market,
|
|
3859
|
+
solver: parsed.solver,
|
|
3860
|
+
expiresAt: parsed.validUntil,
|
|
3861
|
+
// Exactly one leg is BTC, so an asset deposit's carrier is on the payout's unit.
|
|
3862
|
+
fee: {
|
|
3863
|
+
amount: feedSpread(reference, parsed.take, carrierSats),
|
|
3864
|
+
asset: input.endpoints.take.asset
|
|
3865
|
+
}
|
|
3866
|
+
},
|
|
3867
|
+
preparation: {
|
|
3868
|
+
backend: "rfq",
|
|
3869
|
+
route: "arkade->arkade",
|
|
3870
|
+
card: input.candidate.card,
|
|
3871
|
+
rfqId,
|
|
3872
|
+
wire: parsed,
|
|
3873
|
+
offer,
|
|
3874
|
+
...assetPayment === void 0 ? {} : {
|
|
3875
|
+
assetPayment,
|
|
3876
|
+
assetPaymentRecipient: receiveAddress === void 0 ? { kind: "wallet" } : { kind: "address", address: receiveAddress }
|
|
3877
|
+
},
|
|
3878
|
+
...carrierSats === void 0 ? {} : { carrierSats }
|
|
3879
|
+
}
|
|
3880
|
+
};
|
|
3881
|
+
};
|
|
3882
|
+
var assetSidesOf = (legs) => {
|
|
3883
|
+
const giveIsBtc = legs.give.assetId === BTC_ASSET_ID;
|
|
3884
|
+
const takeIsBtc = legs.take.assetId === BTC_ASSET_ID;
|
|
3885
|
+
if (giveIsBtc && takeIsBtc) {
|
|
3886
|
+
throw new UnsupportedRoute("arkade:BTC -> arkade:BTC moves one asset, it swaps nothing", {
|
|
3887
|
+
give: "arkade",
|
|
3888
|
+
take: "arkade"
|
|
3889
|
+
});
|
|
3890
|
+
}
|
|
3891
|
+
if (!giveIsBtc && !takeIsBtc) {
|
|
3892
|
+
throw new UnsupportedRoute(
|
|
3893
|
+
`arkade:${legs.give.assetId} -> arkade:${legs.take.assetId}: an asset swap prices one asset against BTC, so exactly one leg must be BTC`,
|
|
3894
|
+
{ give: "arkade", take: "arkade" }
|
|
3895
|
+
);
|
|
3896
|
+
}
|
|
3897
|
+
return giveIsBtc ? { wantAsset: asset4.AssetId.fromString(legs.take.assetId) } : { offerAsset: asset4.AssetId.fromString(legs.give.assetId) };
|
|
3898
|
+
};
|
|
3899
|
+
var makerPosition = async (wallet) => {
|
|
3900
|
+
const [address, publicKey] = await Promise.all([
|
|
3901
|
+
wallet.getAddress(),
|
|
3902
|
+
wallet.identity.xOnlyPublicKey()
|
|
3903
|
+
]);
|
|
3904
|
+
return { pkScript: ArkAddress6.decode(address).pkScript, publicKey };
|
|
3905
|
+
};
|
|
3047
3906
|
var quoteLightningSend = async (input) => {
|
|
3048
3907
|
const invoice = input.endpoints.take.instrument;
|
|
3049
3908
|
if (invoice?.kind !== "invoice" || invoice.amount === void 0) {
|
|
@@ -3070,6 +3929,7 @@ var quoteLightningSend = async (input) => {
|
|
|
3070
3929
|
paymentHash: invoice.paymentHash,
|
|
3071
3930
|
senderPubkey: secrets.pubkey,
|
|
3072
3931
|
refundPkScript: secrets.pkScript,
|
|
3932
|
+
now: input.now,
|
|
3073
3933
|
...covenant
|
|
3074
3934
|
})
|
|
3075
3935
|
);
|
|
@@ -3079,6 +3939,12 @@ var quoteLightningSend = async (input) => {
|
|
|
3079
3939
|
now: input.now,
|
|
3080
3940
|
invoiceExpiresAt: invoice.expiresAt
|
|
3081
3941
|
});
|
|
3942
|
+
verifyRefundWindow({
|
|
3943
|
+
refundLocktime: derived.refundLocktime,
|
|
3944
|
+
refundWithoutReceiverDelay: derived.contractParams.refundWithoutReceiverDelay,
|
|
3945
|
+
now: input.now,
|
|
3946
|
+
maxSeconds: input.policy?.maxRefundWindowSeconds
|
|
3947
|
+
});
|
|
3082
3948
|
verifyQuoteTtl({
|
|
3083
3949
|
quoteId: input.quoteId,
|
|
3084
3950
|
expiresAt: parsed.validUntil,
|
|
@@ -3107,11 +3973,7 @@ var quoteLightningSend = async (input) => {
|
|
|
3107
3973
|
card: input.candidate.card,
|
|
3108
3974
|
rfqId,
|
|
3109
3975
|
wire: parsed,
|
|
3110
|
-
lockup:
|
|
3111
|
-
address: derived.address,
|
|
3112
|
-
script: derived.script,
|
|
3113
|
-
pkScript: derived.swapPkScript
|
|
3114
|
-
},
|
|
3976
|
+
lockup: lockupOf(derived),
|
|
3115
3977
|
contractParams: derived.contractParams,
|
|
3116
3978
|
secrets,
|
|
3117
3979
|
refundAddress: secrets.address,
|
|
@@ -3124,11 +3986,17 @@ var quoteLightningReceive = async (input) => {
|
|
|
3124
3986
|
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
3125
3987
|
const rfqId = newRfqId();
|
|
3126
3988
|
const secrets = await provisionClaimSecret(input.wallet);
|
|
3127
|
-
const paymentHash =
|
|
3989
|
+
const paymentHash = hex8.encode(secrets.paymentHash);
|
|
3128
3990
|
const payoutAddress = await input.wallet.getAddress();
|
|
3129
3991
|
const lightning = input.corridors.get("lightning").deps;
|
|
3130
3992
|
const sealTo = sealingKey(lightning);
|
|
3131
|
-
const
|
|
3993
|
+
const sealsAmount = pinned.on === "take" && input.legs.take.assetId === BTC_ASSET_ID;
|
|
3994
|
+
const binds = bindsClaimAmount();
|
|
3995
|
+
const claimPacket = sealTo !== void 0 && (!binds || sealsAmount) ? await sealClaimPacket({
|
|
3996
|
+
preimage: secrets.preimage,
|
|
3997
|
+
covclaimdPubkey: sealTo,
|
|
3998
|
+
minAmount: binds ? pinned.value : void 0
|
|
3999
|
+
}) : void 0;
|
|
3132
4000
|
const wire = await input.transport.requestQuote(
|
|
3133
4001
|
withCanonicalAmount(
|
|
3134
4002
|
lightningReceiveRequest({
|
|
@@ -3136,10 +4004,8 @@ var quoteLightningReceive = async (input) => {
|
|
|
3136
4004
|
paymentHash,
|
|
3137
4005
|
payoutAddress,
|
|
3138
4006
|
payoutPubkey: secrets.pubkey,
|
|
3139
|
-
claimPacket: claimPacket?.
|
|
3140
|
-
// Placeholder:
|
|
3141
|
-
// wire adapter re-encodes it as the canonical decimal string.
|
|
3142
|
-
// Encoding it here as well would put the decision in two places.
|
|
4007
|
+
claimPacket: claimPacket?.packet,
|
|
4008
|
+
// Placeholder: `withCanonicalAmount` writes the canonical decimal string.
|
|
3143
4009
|
amount: 0,
|
|
3144
4010
|
amountSide: toRfqAmountSide(pinned.on)
|
|
3145
4011
|
}),
|
|
@@ -3156,10 +4022,7 @@ var quoteLightningReceive = async (input) => {
|
|
|
3156
4022
|
paymentHash,
|
|
3157
4023
|
payoutPubkey: secrets.pubkey,
|
|
3158
4024
|
payoutAddress,
|
|
3159
|
-
|
|
3160
|
-
emulatorPubkey: covenant.emulatorPubkey,
|
|
3161
|
-
claimDelay: covenant.claimDelay,
|
|
3162
|
-
hrp: covenant.hrp
|
|
4025
|
+
...covenant
|
|
3163
4026
|
})
|
|
3164
4027
|
);
|
|
3165
4028
|
const { payDeadline } = verifyReceiveInvoiceFacts({
|
|
@@ -3177,9 +4040,7 @@ var quoteLightningReceive = async (input) => {
|
|
|
3177
4040
|
});
|
|
3178
4041
|
verifyQuoteTtl({
|
|
3179
4042
|
quoteId: input.quoteId,
|
|
3180
|
-
// The hold invoice's window
|
|
3181
|
-
// the deadline that binds this leg is the earlier of the two — which is
|
|
3182
|
-
// what `payDeadline` already is.
|
|
4043
|
+
// The hold invoice's window (minutes) binds, not the quote's (an hour).
|
|
3183
4044
|
expiresAt: payDeadline,
|
|
3184
4045
|
now: input.now,
|
|
3185
4046
|
floorSeconds: input.policy?.quoteTtlFloorSeconds
|
|
@@ -3217,11 +4078,7 @@ var quoteLightningReceive = async (input) => {
|
|
|
3217
4078
|
card: input.candidate.card,
|
|
3218
4079
|
rfqId,
|
|
3219
4080
|
wire: parsed,
|
|
3220
|
-
lockup:
|
|
3221
|
-
address: derived.address,
|
|
3222
|
-
script: derived.script,
|
|
3223
|
-
pkScript: derived.swapPkScript
|
|
3224
|
-
},
|
|
4081
|
+
lockup: lockupOf(derived),
|
|
3225
4082
|
contractParams: derived.contractParams,
|
|
3226
4083
|
secrets,
|
|
3227
4084
|
payoutAddress,
|
|
@@ -3248,7 +4105,7 @@ var quoteOnchainSend = async (input) => {
|
|
|
3248
4105
|
const quoted = claimFee === void 0 ? pinned : { on: pinned.on, value: pinned.value + claimFee, source: pinned.source };
|
|
3249
4106
|
const secrets = await provisionClaimSecret(input.wallet);
|
|
3250
4107
|
const payoutKey = await provisionRefundKey(input.wallet);
|
|
3251
|
-
const paymentHash =
|
|
4108
|
+
const paymentHash = hex8.encode(secrets.paymentHash);
|
|
3252
4109
|
const wire = await input.transport.requestQuote(
|
|
3253
4110
|
withCanonicalAmount(
|
|
3254
4111
|
onchainSendRequest({
|
|
@@ -3260,9 +4117,6 @@ var quoteOnchainSend = async (input) => {
|
|
|
3260
4117
|
amount: 0,
|
|
3261
4118
|
amountSide: toRfqAmountSide(pinned.on)
|
|
3262
4119
|
}),
|
|
3263
|
-
// The grossed pin, when one is active — see above. The solver's
|
|
3264
|
-
// obligation is the HTLC amount; the recipient's own amount is
|
|
3265
|
-
// that minus the claim's fee.
|
|
3266
4120
|
quoted.value
|
|
3267
4121
|
)
|
|
3268
4122
|
);
|
|
@@ -3283,10 +4137,7 @@ var quoteOnchainSend = async (input) => {
|
|
|
3283
4137
|
quote: wire,
|
|
3284
4138
|
paymentHash,
|
|
3285
4139
|
payoutPubkey: payoutKey.pubkey,
|
|
3286
|
-
|
|
3287
|
-
emulatorPubkey: covenant.emulatorPubkey,
|
|
3288
|
-
claimDelay: covenant.claimDelay,
|
|
3289
|
-
hrp: covenant.hrp,
|
|
4140
|
+
...covenant,
|
|
3290
4141
|
l1Network,
|
|
3291
4142
|
refundAddress: payoutKey.address,
|
|
3292
4143
|
senderPubkey: secrets.pubkey
|
|
@@ -3302,14 +4153,20 @@ var quoteOnchainSend = async (input) => {
|
|
|
3302
4153
|
direction: "send"
|
|
3303
4154
|
}
|
|
3304
4155
|
});
|
|
4156
|
+
verifyRefundWindow({
|
|
4157
|
+
refundLocktime: derived.refundLocktime,
|
|
4158
|
+
refundWithoutReceiverDelay: derived.refundWithoutReceiverDelay,
|
|
4159
|
+
now: input.now,
|
|
4160
|
+
maxSeconds: input.policy?.maxRefundWindowSeconds
|
|
4161
|
+
});
|
|
3305
4162
|
verifyQuoteTtl({
|
|
3306
4163
|
quoteId: input.quoteId,
|
|
3307
4164
|
expiresAt: parsed.validUntil,
|
|
3308
4165
|
now: input.now,
|
|
3309
4166
|
floorSeconds: input.policy?.quoteTtlFloorSeconds
|
|
3310
4167
|
});
|
|
3311
|
-
const reportedTake =
|
|
3312
|
-
const reportedFee =
|
|
4168
|
+
const reportedTake = parsed.take - (claimFee ?? 0n);
|
|
4169
|
+
const reportedFee = parsed.give - parsed.take + (claimFee ?? 0n);
|
|
3313
4170
|
return {
|
|
3314
4171
|
quote: {
|
|
3315
4172
|
id: input.quoteId,
|
|
@@ -3323,9 +4180,7 @@ var quoteOnchainSend = async (input) => {
|
|
|
3323
4180
|
market: input.market,
|
|
3324
4181
|
solver: parsed.solver,
|
|
3325
4182
|
expiresAt: parsed.validUntil,
|
|
3326
|
-
//
|
|
3327
|
-
// optional there, a solver may carry it in the profile instead, and
|
|
3328
|
-
// the derivation is what settles which one this covenant used.
|
|
4183
|
+
// Off the derivation, not the wire: it settles which locktime this covenant used.
|
|
3329
4184
|
refundLocktime: derived.refundLocktime,
|
|
3330
4185
|
fee: { amount: reportedFee, asset: input.endpoints.give.asset }
|
|
3331
4186
|
},
|
|
@@ -3335,14 +4190,12 @@ var quoteOnchainSend = async (input) => {
|
|
|
3335
4190
|
card: input.candidate.card,
|
|
3336
4191
|
rfqId,
|
|
3337
4192
|
wire: parsed,
|
|
3338
|
-
lockup:
|
|
3339
|
-
address: derived.address,
|
|
3340
|
-
script: derived.script,
|
|
3341
|
-
pkScript: derived.swapPkScript
|
|
3342
|
-
},
|
|
4193
|
+
lockup: lockupOf(derived),
|
|
3343
4194
|
secrets,
|
|
3344
4195
|
refundAddress: payoutKey.address,
|
|
3345
4196
|
fundAmount: parsed.give,
|
|
4197
|
+
// Gross, not `reportedTake`: netting would accept an HTLC short by the fee.
|
|
4198
|
+
expectedAmount: parsed.take,
|
|
3346
4199
|
payoutKey,
|
|
3347
4200
|
payoutPkScript,
|
|
3348
4201
|
htlc: derived.htlc,
|
|
@@ -3352,6 +4205,118 @@ var quoteOnchainSend = async (input) => {
|
|
|
3352
4205
|
}
|
|
3353
4206
|
};
|
|
3354
4207
|
};
|
|
4208
|
+
var quoteOnchainReceive = async (input) => {
|
|
4209
|
+
const pinned = pinnedFor(input);
|
|
4210
|
+
const pair = rfqPairFor(input.legs.give, input.legs.take);
|
|
4211
|
+
const rfqId = newRfqId();
|
|
4212
|
+
const l1Network = l1NetworkFromArk(input.info.network);
|
|
4213
|
+
const secrets = await provisionClaimSecret(input.wallet);
|
|
4214
|
+
const refundKey = await provisionRefundKey(input.wallet);
|
|
4215
|
+
const paymentHash = hex8.encode(secrets.paymentHash);
|
|
4216
|
+
const payoutAddress = await input.wallet.getAddress();
|
|
4217
|
+
const refundPkScript = l1ScriptForAddress(await input.wallet.getBoardingAddress(), l1Network);
|
|
4218
|
+
const wire = await input.transport.requestQuote(
|
|
4219
|
+
withCanonicalAmount(
|
|
4220
|
+
onchainReceiveRequest({
|
|
4221
|
+
rfqId,
|
|
4222
|
+
paymentHash,
|
|
4223
|
+
payoutAddress,
|
|
4224
|
+
payoutPubkey: secrets.pubkey,
|
|
4225
|
+
refundPubkey: refundKey.pubkey,
|
|
4226
|
+
// Placeholder: `withCanonicalAmount` writes the canonical decimal string.
|
|
4227
|
+
amount: 0,
|
|
4228
|
+
amountSide: toRfqAmountSide(pinned.on)
|
|
4229
|
+
}),
|
|
4230
|
+
pinned.value
|
|
4231
|
+
)
|
|
4232
|
+
);
|
|
4233
|
+
verifyPair(wire.pair, pair);
|
|
4234
|
+
const parsed = parseRfqQuote(wire);
|
|
4235
|
+
verifyQuotedAmount({ pair, pinned, give: parsed.give, take: parsed.take });
|
|
4236
|
+
const covenant = covenantInputs(input);
|
|
4237
|
+
const derived = verifyingDerivation(
|
|
4238
|
+
() => deriveOnchainReceive({
|
|
4239
|
+
quote: wire,
|
|
4240
|
+
paymentHash,
|
|
4241
|
+
payoutPubkey: secrets.pubkey,
|
|
4242
|
+
payoutAddress,
|
|
4243
|
+
refundPubkey: refundKey.pubkey,
|
|
4244
|
+
...covenant,
|
|
4245
|
+
l1Network
|
|
4246
|
+
})
|
|
4247
|
+
);
|
|
4248
|
+
verifySendWindow({
|
|
4249
|
+
quote: wire,
|
|
4250
|
+
quoteId: input.quoteId,
|
|
4251
|
+
now: input.now,
|
|
4252
|
+
onchain: {
|
|
4253
|
+
htlcLocktime: derived.htlcLocktime,
|
|
4254
|
+
minConfirmations: derived.minConfirmations,
|
|
4255
|
+
direction: "receive"
|
|
4256
|
+
}
|
|
4257
|
+
});
|
|
4258
|
+
verifyRefundWindow({
|
|
4259
|
+
refundLocktime: derived.htlcLocktime,
|
|
4260
|
+
now: input.now,
|
|
4261
|
+
maxSeconds: input.policy?.maxRefundWindowSeconds
|
|
4262
|
+
});
|
|
4263
|
+
verifyQuoteTtl({
|
|
4264
|
+
quoteId: input.quoteId,
|
|
4265
|
+
expiresAt: parsed.validUntil,
|
|
4266
|
+
now: input.now,
|
|
4267
|
+
floorSeconds: input.policy?.quoteTtlFloorSeconds
|
|
4268
|
+
});
|
|
4269
|
+
const artifact = {
|
|
4270
|
+
kind: "deposit",
|
|
4271
|
+
corridor: "onchain",
|
|
4272
|
+
address: derived.htlc.address,
|
|
4273
|
+
asset: input.endpoints.give.asset,
|
|
4274
|
+
amount: parsed.give,
|
|
4275
|
+
expiresAt: parsed.validUntil
|
|
4276
|
+
};
|
|
4277
|
+
return {
|
|
4278
|
+
quote: {
|
|
4279
|
+
id: input.quoteId,
|
|
4280
|
+
route: assembleRoute(
|
|
4281
|
+
{
|
|
4282
|
+
...input.endpoints.give,
|
|
4283
|
+
instrument: {
|
|
4284
|
+
kind: "address",
|
|
4285
|
+
address: derived.htlc.address,
|
|
4286
|
+
amount: parsed.give
|
|
4287
|
+
}
|
|
4288
|
+
},
|
|
4289
|
+
{ ...input.endpoints.take, instrument: { kind: "wallet" } }
|
|
4290
|
+
),
|
|
4291
|
+
give: { asset: input.endpoints.give.asset, amount: parsed.give },
|
|
4292
|
+
take: { asset: input.endpoints.take.asset, amount: parsed.take },
|
|
4293
|
+
lock: { hash: paymentHash },
|
|
4294
|
+
market: input.market,
|
|
4295
|
+
solver: parsed.solver,
|
|
4296
|
+
expiresAt: parsed.validUntil,
|
|
4297
|
+
refundLocktime: derived.refundLocktime,
|
|
4298
|
+
artifact,
|
|
4299
|
+
fee: { amount: parsed.give - parsed.take, asset: input.endpoints.give.asset }
|
|
4300
|
+
},
|
|
4301
|
+
preparation: {
|
|
4302
|
+
backend: "rfq",
|
|
4303
|
+
route: "onchain->arkade",
|
|
4304
|
+
card: input.candidate.card,
|
|
4305
|
+
rfqId,
|
|
4306
|
+
wire: parsed,
|
|
4307
|
+
lockup: lockupOf(derived),
|
|
4308
|
+
secrets,
|
|
4309
|
+
payoutAddress,
|
|
4310
|
+
expectedAmount: parsed.take,
|
|
4311
|
+
refundKey,
|
|
4312
|
+
refundPkScript,
|
|
4313
|
+
htlc: derived.htlc,
|
|
4314
|
+
htlcParams: derived.htlcParams,
|
|
4315
|
+
l1Network,
|
|
4316
|
+
minConfirmations: derived.minConfirmations
|
|
4317
|
+
}
|
|
4318
|
+
};
|
|
4319
|
+
};
|
|
3355
4320
|
|
|
3356
4321
|
// src/client/verbs.ts
|
|
3357
4322
|
import { arkTarget as arkTarget2, resolveSendAmount as resolveSendAmount2 } from "@arkade-os/sdk";
|
|
@@ -3379,22 +4344,20 @@ var settle = async (deps, input, maxFee) => {
|
|
|
3379
4344
|
return deps.accept(quote);
|
|
3380
4345
|
};
|
|
3381
4346
|
var pay = async (deps, destination, options = {}) => {
|
|
3382
|
-
const
|
|
3383
|
-
if (
|
|
4347
|
+
const arkade2 = arkTarget2(destination);
|
|
4348
|
+
if (arkade2 !== void 0) {
|
|
3384
4349
|
const amount = resolveSendAmount2(
|
|
3385
4350
|
"ark",
|
|
3386
4351
|
destination,
|
|
3387
4352
|
options.amount === void 0 ? void 0 : satsOf(options.amount, "amount")
|
|
3388
4353
|
);
|
|
3389
|
-
return { kind: "payment", txid: await deps.wallet.send({ address:
|
|
4354
|
+
return { kind: "payment", txid: await deps.wallet.send({ address: arkade2, amount }) };
|
|
3390
4355
|
}
|
|
3391
4356
|
const swap = await settle(
|
|
3392
4357
|
deps,
|
|
3393
4358
|
{
|
|
3394
4359
|
to: destination,
|
|
3395
|
-
//
|
|
3396
|
-
// destination is what the recipient gets. An invoice pins the same
|
|
3397
|
-
// leg by existing, which is why passing both is `AmountMismatch`.
|
|
4360
|
+
// The amount beside a destination is what the recipient gets.
|
|
3398
4361
|
...options.amount === void 0 ? {} : { amount: options.amount, amountOn: "take" }
|
|
3399
4362
|
},
|
|
3400
4363
|
options.maxFee
|
|
@@ -3408,8 +4371,7 @@ var receive = async (deps, options) => {
|
|
|
3408
4371
|
via: options.via,
|
|
3409
4372
|
...options.asset === void 0 ? {} : { take: options.asset },
|
|
3410
4373
|
amount: options.amount,
|
|
3411
|
-
//
|
|
3412
|
-
// "credit me this much", not "let the payer send this much".
|
|
4374
|
+
// "Credit me this much", not "let the payer send this much".
|
|
3413
4375
|
amountOn: "take"
|
|
3414
4376
|
},
|
|
3415
4377
|
options.maxFee
|
|
@@ -3434,21 +4396,26 @@ var exchange = async (deps, options) => settle(
|
|
|
3434
4396
|
|
|
3435
4397
|
// src/client/transport.ts
|
|
3436
4398
|
var attesting = (transport, responder) => Object.assign(transport, { attestedResponder: responder });
|
|
3437
|
-
var
|
|
3438
|
-
|
|
3439
|
-
|
|
3440
|
-
|
|
3441
|
-
|
|
3442
|
-
|
|
3443
|
-
|
|
3444
|
-
|
|
3445
|
-
|
|
4399
|
+
var createNostrTransportFactory = (pool) => {
|
|
4400
|
+
return async (rendezvous) => {
|
|
4401
|
+
const { nostrRfqTransport } = await import("./nostr.js");
|
|
4402
|
+
return attesting(
|
|
4403
|
+
nostrRfqTransport({
|
|
4404
|
+
relays: [...rendezvous.relays],
|
|
4405
|
+
solverPubkey: rendezvous.solverPubkey,
|
|
4406
|
+
...pool === void 0 ? {} : { pool }
|
|
4407
|
+
}),
|
|
4408
|
+
rendezvous.solverPubkey
|
|
4409
|
+
);
|
|
4410
|
+
};
|
|
3446
4411
|
};
|
|
4412
|
+
var nostrTransportFactory = createNostrTransportFactory();
|
|
3447
4413
|
|
|
3448
4414
|
// src/client/client.ts
|
|
3449
|
-
import { hex as
|
|
4415
|
+
import { hex as hex9 } from "@scure/base";
|
|
4416
|
+
import { captureSendDeadline } from "@arkade-os/sdk";
|
|
3450
4417
|
var PREPARATIONS_HELD = 64;
|
|
3451
|
-
var mintQuoteId = () =>
|
|
4418
|
+
var mintQuoteId = () => hex9.encode(crypto.getRandomValues(new Uint8Array(16)));
|
|
3452
4419
|
var createSwapClient = (config) => {
|
|
3453
4420
|
const { wallet } = config;
|
|
3454
4421
|
const operator = config.operator ?? walletOperator(wallet);
|
|
@@ -3465,6 +4432,7 @@ var createSwapClient = (config) => {
|
|
|
3465
4432
|
operator,
|
|
3466
4433
|
...config.repository === void 0 ? {} : { repository: config.repository },
|
|
3467
4434
|
corridors: async () => (await resolved()).corridors,
|
|
4435
|
+
network: async () => (await resolved()).base.networkName,
|
|
3468
4436
|
...config.policy?.drive === void 0 ? {} : { mode: config.policy.drive },
|
|
3469
4437
|
indexer
|
|
3470
4438
|
});
|
|
@@ -3502,10 +4470,8 @@ var createSwapClient = (config) => {
|
|
|
3502
4470
|
};
|
|
3503
4471
|
const remember = (id, preparation) => {
|
|
3504
4472
|
preparations.set(id, preparation);
|
|
3505
|
-
|
|
3506
|
-
|
|
3507
|
-
if (oldest.done) break;
|
|
3508
|
-
preparations.delete(oldest.value);
|
|
4473
|
+
if (preparations.size > PREPARATIONS_HELD) {
|
|
4474
|
+
preparations.delete(preparations.keys().next().value);
|
|
3509
4475
|
}
|
|
3510
4476
|
};
|
|
3511
4477
|
const client = {
|
|
@@ -3514,6 +4480,7 @@ var createSwapClient = (config) => {
|
|
|
3514
4480
|
return (await route(input, "resolve")).resolution;
|
|
3515
4481
|
},
|
|
3516
4482
|
quote: async (input) => {
|
|
4483
|
+
const assetPayment = captureAssetPayment(input.assetPayment);
|
|
3517
4484
|
ensureLive("quote");
|
|
3518
4485
|
const { corridors, discovery } = await resolved();
|
|
3519
4486
|
let resolvedRoute = await route(input, "quote");
|
|
@@ -3539,7 +4506,9 @@ var createSwapClient = (config) => {
|
|
|
3539
4506
|
corridors.get(resolvedRoute.legs.take.corridor);
|
|
3540
4507
|
const quoteId = mintQuoteId();
|
|
3541
4508
|
const now = Math.floor(Date.now() / 1e3);
|
|
3542
|
-
if (
|
|
4509
|
+
if (market.backend === "feed") {
|
|
4510
|
+
if (assetPayment !== void 0)
|
|
4511
|
+
throw new Error("assetPayment needs a negotiated BTC-to-asset market");
|
|
3543
4512
|
const { quote, preparation } = await quoteFromFeed({
|
|
3544
4513
|
quoteId,
|
|
3545
4514
|
candidate: market,
|
|
@@ -3568,6 +4537,7 @@ var createSwapClient = (config) => {
|
|
|
3568
4537
|
const { quote, preparation } = await quoteViaRfq({
|
|
3569
4538
|
quoteId,
|
|
3570
4539
|
route: resolvedRoute.pair,
|
|
4540
|
+
...assetPayment === void 0 ? {} : { assetPayment },
|
|
3571
4541
|
candidate: market,
|
|
3572
4542
|
market: marketRef,
|
|
3573
4543
|
legs: resolvedRoute.legs,
|
|
@@ -3577,6 +4547,7 @@ var createSwapClient = (config) => {
|
|
|
3577
4547
|
info,
|
|
3578
4548
|
corridors,
|
|
3579
4549
|
transport,
|
|
4550
|
+
feed,
|
|
3580
4551
|
...config.policy === void 0 ? {} : { policy: config.policy },
|
|
3581
4552
|
now
|
|
3582
4553
|
});
|
|
@@ -3587,7 +4558,8 @@ var createSwapClient = (config) => {
|
|
|
3587
4558
|
});
|
|
3588
4559
|
}
|
|
3589
4560
|
},
|
|
3590
|
-
accept: async (quote) => {
|
|
4561
|
+
accept: async (quote, options) => {
|
|
4562
|
+
const validUntil = captureSendDeadline(options?.validUntil);
|
|
3591
4563
|
ensureLive("accept");
|
|
3592
4564
|
const { corridors } = await resolved();
|
|
3593
4565
|
const drive2 = driving();
|
|
@@ -3595,6 +4567,7 @@ var createSwapClient = (config) => {
|
|
|
3595
4567
|
const preparation = preparations.get(quote.id);
|
|
3596
4568
|
return acceptQuote({
|
|
3597
4569
|
quote,
|
|
4570
|
+
...validUntil === void 0 ? {} : { validUntil },
|
|
3598
4571
|
...preparation === void 0 ? {} : { preparation },
|
|
3599
4572
|
wallet,
|
|
3600
4573
|
repository: config.repository,
|
|
@@ -3624,7 +4597,7 @@ var createSwapClient = (config) => {
|
|
|
3624
4597
|
if (repository === void 0) return [];
|
|
3625
4598
|
const drive2 = driving();
|
|
3626
4599
|
await drive2.ready;
|
|
3627
|
-
const records = await repository
|
|
4600
|
+
const records = await collectSwapRecords(repository);
|
|
3628
4601
|
const swaps = [];
|
|
3629
4602
|
for (const record of records) {
|
|
3630
4603
|
if (!readableRecord(record)) continue;
|
|
@@ -3664,9 +4637,7 @@ var createSwapClient = (config) => {
|
|
|
3664
4637
|
ensureLive("ready");
|
|
3665
4638
|
return driving().ready;
|
|
3666
4639
|
},
|
|
3667
|
-
// `async
|
|
3668
|
-
// throw: these are declared `Promise<void>` and a caller is entitled to
|
|
3669
|
-
// `.catch()` them.
|
|
4640
|
+
// `async` so the refusal is a rejection, as the `Promise<void>` signature promises
|
|
3670
4641
|
start: async () => {
|
|
3671
4642
|
ensureLive("start");
|
|
3672
4643
|
return driving().start();
|
|
@@ -3698,6 +4669,149 @@ var createSwapClient = (config) => {
|
|
|
3698
4669
|
return client;
|
|
3699
4670
|
};
|
|
3700
4671
|
|
|
4672
|
+
// src/offerFillPlan.ts
|
|
4673
|
+
import { base64 as base643, hex as hex10 } from "@scure/base";
|
|
4674
|
+
import { ArkAddress as ArkAddress7, Extension, P2A } from "@arkade-os/sdk";
|
|
4675
|
+
var OFFER_FILL_TEMPLATE = "offer-fill/1";
|
|
4676
|
+
var OFFER_FILL_OWNERS = [null, "solver", "sponsor"];
|
|
4677
|
+
async function buildOfferFillPlan(wallet, arkServerUrl, offerHex, opts) {
|
|
4678
|
+
const {
|
|
4679
|
+
fund: fund2,
|
|
4680
|
+
payoutScript,
|
|
4681
|
+
fundingTxid,
|
|
4682
|
+
fundingOutpoint,
|
|
4683
|
+
swapAddress,
|
|
4684
|
+
assetCarrierSats = ASSET_CARRIER_SATS,
|
|
4685
|
+
sponsor
|
|
4686
|
+
} = opts;
|
|
4687
|
+
const offer = decodeOffer(hex10.decode(offerHex));
|
|
4688
|
+
const contract = await connectFillContract(wallet, arkServerUrl, offer, { swapAddress });
|
|
4689
|
+
const vtxos = await contract.getUtxos();
|
|
4690
|
+
const vtxo = resolveDeposit(vtxos, { fundingTxid, fundingOutpoint });
|
|
4691
|
+
const solverPayout = payoutScript ?? ArkAddress7.decode(await wallet.getAddress()).pkScript;
|
|
4692
|
+
const sponsorLeg = sponsor !== void 0 ? normalizeSponsor(sponsor, assetCarrierSats) : void 0;
|
|
4693
|
+
const fill = contract.functions.fulfill();
|
|
4694
|
+
const layout = assembleOfferFill(fill, {
|
|
4695
|
+
offer,
|
|
4696
|
+
vtxo,
|
|
4697
|
+
solverFund: fund2,
|
|
4698
|
+
solverPayout,
|
|
4699
|
+
assetCarrierSats,
|
|
4700
|
+
sponsor: sponsorLeg
|
|
4701
|
+
});
|
|
4702
|
+
const { arkTx, checkpoints } = await fill.build();
|
|
4703
|
+
for (const [i, input] of layout.inputs.entries()) {
|
|
4704
|
+
if (!OFFER_FILL_OWNERS.includes(input.owner)) {
|
|
4705
|
+
throw new Error(`fill plan input ${i} names unknown owner ${input.owner}`);
|
|
4706
|
+
}
|
|
4707
|
+
}
|
|
4708
|
+
return toJointGraph(arkTx, checkpoints, layout, offer.wantAsset?.toString());
|
|
4709
|
+
}
|
|
4710
|
+
function normalizeSponsor(sponsor, assetCarrierSats) {
|
|
4711
|
+
return {
|
|
4712
|
+
fund: sponsor.fund,
|
|
4713
|
+
netContributionSats: sponsor.netContributionSats,
|
|
4714
|
+
fare: sponsor.fare !== void 0 ? {
|
|
4715
|
+
...sponsor.fare.assetId !== void 0 ? { assetId: sponsor.fare.assetId, amount: sponsor.fare.amount } : {},
|
|
4716
|
+
script: sponsor.fare.script,
|
|
4717
|
+
sats: sponsor.fare.sats ?? assetCarrierSats
|
|
4718
|
+
} : void 0,
|
|
4719
|
+
changeScript: sponsor.changeScript,
|
|
4720
|
+
combineSatsFareWithChange: sponsor.combineSatsFareWithChange
|
|
4721
|
+
};
|
|
4722
|
+
}
|
|
4723
|
+
function toJointGraph(arkTx, checkpoints, layout, wantedAssetId) {
|
|
4724
|
+
if (arkTx.inputsLength !== layout.inputs.length) {
|
|
4725
|
+
throw new Error(
|
|
4726
|
+
`fill plan built ${arkTx.inputsLength} inputs, expected ${layout.inputs.length}`
|
|
4727
|
+
);
|
|
4728
|
+
}
|
|
4729
|
+
if (checkpoints.length !== layout.inputs.length) {
|
|
4730
|
+
throw new Error(
|
|
4731
|
+
`fill plan built ${checkpoints.length} checkpoints, expected ${layout.inputs.length}`
|
|
4732
|
+
);
|
|
4733
|
+
}
|
|
4734
|
+
layout.inputs.forEach((input, i) => {
|
|
4735
|
+
const spent = checkpoints[i].getInput(0);
|
|
4736
|
+
if (!(spent.txid instanceof Uint8Array) || hex10.encode(spent.txid) !== input.txid || spent.index !== input.vout) {
|
|
4737
|
+
throw new Error(`fill plan checkpoint ${i} does not spend ${input.txid}:${input.vout}`);
|
|
4738
|
+
}
|
|
4739
|
+
});
|
|
4740
|
+
const payments = layout.outputs.length;
|
|
4741
|
+
if (arkTx.outputsLength !== payments + 2) {
|
|
4742
|
+
throw new Error(
|
|
4743
|
+
`fill plan built ${arkTx.outputsLength} outputs, expected ${payments} payments plus extension and anchor`
|
|
4744
|
+
);
|
|
4745
|
+
}
|
|
4746
|
+
layout.outputs.forEach((expected, i) => {
|
|
4747
|
+
const out = arkTx.getOutput(i);
|
|
4748
|
+
if (!out?.script || hex10.encode(out.script) !== hex10.encode(expected.script)) {
|
|
4749
|
+
throw new Error(`fill plan output ${i} is not the ${expected.role} script`);
|
|
4750
|
+
}
|
|
4751
|
+
if (out.amount !== expected.sats) {
|
|
4752
|
+
throw new Error(
|
|
4753
|
+
`fill plan output ${i} carries ${out.amount}, expected ${expected.sats}`
|
|
4754
|
+
);
|
|
4755
|
+
}
|
|
4756
|
+
});
|
|
4757
|
+
const ext = arkTx.getOutput(payments);
|
|
4758
|
+
if (!ext?.script || !Extension.isExtension(ext.script)) {
|
|
4759
|
+
throw new Error(`fill plan output ${payments} is not the extension packet`);
|
|
4760
|
+
}
|
|
4761
|
+
const anchor = arkTx.getOutput(payments + 1);
|
|
4762
|
+
if (!anchor?.script || hex10.encode(anchor.script) !== hex10.encode(P2A.script) || anchor.amount !== P2A.amount) {
|
|
4763
|
+
throw new Error(`fill plan output ${payments + 1} is not the anchor`);
|
|
4764
|
+
}
|
|
4765
|
+
const packet = Extension.fromTx(arkTx).getAssetPacket();
|
|
4766
|
+
for (const group of packet?.groups ?? []) {
|
|
4767
|
+
if (group.assetId === null) throw new Error("fill plan carries an issuance group");
|
|
4768
|
+
const assetId = group.assetId.toString();
|
|
4769
|
+
const unitsIn = group.inputs.reduce((s, input) => s + input.amount, BigInt(0));
|
|
4770
|
+
const unitsOut = group.outputs.reduce((s, output) => s + output.amount, BigInt(0));
|
|
4771
|
+
if (unitsIn !== unitsOut) {
|
|
4772
|
+
throw new Error(`fill plan asset ${assetId} mints ${unitsOut - unitsIn} units`);
|
|
4773
|
+
}
|
|
4774
|
+
for (const output of group.outputs) {
|
|
4775
|
+
const hosted = arkTx.getOutput(output.vout);
|
|
4776
|
+
if (output.vout >= payments || !hosted?.script || Extension.isExtension(hosted.script)) {
|
|
4777
|
+
throw new Error(
|
|
4778
|
+
`fill plan asset ${assetId} pays nonexistent output ${output.vout}`
|
|
4779
|
+
);
|
|
4780
|
+
}
|
|
4781
|
+
}
|
|
4782
|
+
}
|
|
4783
|
+
if (wantedAssetId !== void 0) {
|
|
4784
|
+
if ((packet?.groups.length ?? 0) === 0) {
|
|
4785
|
+
throw new Error(`fill plan carries no asset group, expected ${wantedAssetId}`);
|
|
4786
|
+
}
|
|
4787
|
+
const first = packet?.groups[0].assetId?.toString();
|
|
4788
|
+
if (first !== wantedAssetId) {
|
|
4789
|
+
throw new Error(
|
|
4790
|
+
`fill plan asset group 0 is ${first}, expected the wanted ${wantedAssetId}`
|
|
4791
|
+
);
|
|
4792
|
+
}
|
|
4793
|
+
}
|
|
4794
|
+
const arkTxPsbt = base643.encode(arkTx.toPSBT());
|
|
4795
|
+
const checkpointPsbts = checkpoints.map((c) => base643.encode(c.toPSBT()));
|
|
4796
|
+
const inputOwners = layout.inputs.map((input) => input.owner);
|
|
4797
|
+
const graph = {
|
|
4798
|
+
arkTx: arkTxPsbt,
|
|
4799
|
+
checkpoints: checkpointPsbts,
|
|
4800
|
+
graphId: digestJointGraph(
|
|
4801
|
+
{ arkTx: arkTxPsbt, checkpoints: checkpointPsbts, inputOwners },
|
|
4802
|
+
OFFER_FILL_TEMPLATE
|
|
4803
|
+
),
|
|
4804
|
+
inputOwners
|
|
4805
|
+
};
|
|
4806
|
+
return deepFreeze(graph);
|
|
4807
|
+
}
|
|
4808
|
+
function verifyOfferFillPlan(plan) {
|
|
4809
|
+
if (!plan || typeof plan !== "object" || !Array.isArray(plan.inputOwners)) return false;
|
|
4810
|
+
const allowed = OFFER_FILL_OWNERS;
|
|
4811
|
+
if (!plan.inputOwners.every((owner) => allowed.includes(owner))) return false;
|
|
4812
|
+
return verifyJointGraph(plan, OFFER_FILL_TEMPLATE);
|
|
4813
|
+
}
|
|
4814
|
+
|
|
3701
4815
|
export {
|
|
3702
4816
|
RAILS,
|
|
3703
4817
|
BITCOIN_RAILS,
|
|
@@ -3712,7 +4826,10 @@ export {
|
|
|
3712
4826
|
bitcoinNetworkOf,
|
|
3713
4827
|
assetPartOf,
|
|
3714
4828
|
sameAsset,
|
|
4829
|
+
btcAssetPart,
|
|
3715
4830
|
btcOn,
|
|
4831
|
+
isBtcAsset,
|
|
4832
|
+
isBtcAssetLenient,
|
|
3716
4833
|
arkadeAsset,
|
|
3717
4834
|
issuanceOf,
|
|
3718
4835
|
AmbiguousDestination,
|
|
@@ -3736,30 +4853,11 @@ export {
|
|
|
3736
4853
|
INDEXED_NETWORKS,
|
|
3737
4854
|
isIndexedNetwork,
|
|
3738
4855
|
canonicalAssetId,
|
|
3739
|
-
AmountFormatError,
|
|
3740
|
-
Amount,
|
|
3741
|
-
toAtomicDecimal,
|
|
3742
|
-
fromAtomicDecimal,
|
|
3743
|
-
isAtomicDecimal,
|
|
3744
4856
|
toRfqAmountSide,
|
|
3745
4857
|
fromRfqAmountSide,
|
|
3746
4858
|
encodeRfqAmount,
|
|
3747
4859
|
decodeRfqAmount,
|
|
3748
4860
|
toSafeNumber,
|
|
3749
|
-
assetSwapIdOf,
|
|
3750
|
-
OFFER_SWAP_ID_PREFIX,
|
|
3751
|
-
RFQ_SWAP_ID_PREFIX,
|
|
3752
|
-
familyOfSwapId,
|
|
3753
|
-
quoteIdOfSwapId,
|
|
3754
|
-
recordEndpoint,
|
|
3755
|
-
recordInstrument,
|
|
3756
|
-
instrumentOf,
|
|
3757
|
-
recordArtifact,
|
|
3758
|
-
artifactOf,
|
|
3759
|
-
recordLeg,
|
|
3760
|
-
legOf,
|
|
3761
|
-
swapOf,
|
|
3762
|
-
fundsFromWallet,
|
|
3763
4861
|
conflictingFields,
|
|
3764
4862
|
acceptQuote,
|
|
3765
4863
|
swapRecordOf,
|
|
@@ -3787,11 +4885,15 @@ export {
|
|
|
3787
4885
|
splitRecords,
|
|
3788
4886
|
rfqRecordOf,
|
|
3789
4887
|
withRfqState,
|
|
4888
|
+
pageRfqRecords,
|
|
3790
4889
|
corridorRecordStore,
|
|
3791
4890
|
offerFactsOf,
|
|
3792
4891
|
offerRecordSource,
|
|
3793
4892
|
applyOfferSpend,
|
|
3794
|
-
|
|
4893
|
+
withDepositFate,
|
|
4894
|
+
fateMoved,
|
|
4895
|
+
restoredOfferRecord,
|
|
4896
|
+
restoredCorridorRecord,
|
|
3795
4897
|
walletLockupIndexer,
|
|
3796
4898
|
cancelSwap,
|
|
3797
4899
|
SwapDriveRefusedError,
|
|
@@ -3808,6 +4910,7 @@ export {
|
|
|
3808
4910
|
isCardMarket,
|
|
3809
4911
|
assembleRoute,
|
|
3810
4912
|
resolveRoute,
|
|
4913
|
+
DEFAULT_MAX_REFUND_WINDOW_SECONDS,
|
|
3811
4914
|
verifyResponder,
|
|
3812
4915
|
verifyPair,
|
|
3813
4916
|
verifyingDerivation,
|
|
@@ -3816,10 +4919,19 @@ export {
|
|
|
3816
4919
|
verifySendInvoice,
|
|
3817
4920
|
verifyReceiveInvoiceFacts,
|
|
3818
4921
|
verifyQuoteTtl,
|
|
4922
|
+
verifyRefundWindow,
|
|
3819
4923
|
verifyQuotedAmount,
|
|
4924
|
+
verifyCrossAssetAmount,
|
|
4925
|
+
verifiedCarrierSats,
|
|
3820
4926
|
FEED_TTL_MS,
|
|
3821
4927
|
feedFetch,
|
|
3822
4928
|
quoteFromFeed,
|
|
4929
|
+
feedSpread,
|
|
4930
|
+
verifyPlanLegs,
|
|
4931
|
+
digestJointGraph,
|
|
4932
|
+
verifyJointGraph,
|
|
4933
|
+
deepFreeze,
|
|
4934
|
+
unsignedPsbtBytes,
|
|
3823
4935
|
satsOf,
|
|
3824
4936
|
PAYMENT_STATUS,
|
|
3825
4937
|
paymentStatusOf,
|
|
@@ -3827,6 +4939,7 @@ export {
|
|
|
3827
4939
|
SwapPaymentFailedError,
|
|
3828
4940
|
railAvailable,
|
|
3829
4941
|
receiverExact,
|
|
4942
|
+
quoteMeta,
|
|
3830
4943
|
swapHandle,
|
|
3831
4944
|
ONCHAIN_SWAP_RAIL,
|
|
3832
4945
|
claimFeeSats,
|
|
@@ -3841,6 +4954,11 @@ export {
|
|
|
3841
4954
|
receive,
|
|
3842
4955
|
exchange,
|
|
3843
4956
|
attesting,
|
|
4957
|
+
createNostrTransportFactory,
|
|
3844
4958
|
nostrTransportFactory,
|
|
3845
|
-
createSwapClient
|
|
4959
|
+
createSwapClient,
|
|
4960
|
+
OFFER_FILL_TEMPLATE,
|
|
4961
|
+
OFFER_FILL_OWNERS,
|
|
4962
|
+
buildOfferFillPlan,
|
|
4963
|
+
verifyOfferFillPlan
|
|
3846
4964
|
};
|