@arkade-os/boltz-swap 0.3.32 → 0.3.33
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 +22 -26
- package/dist/{arkade-swaps-CS8FZSVL.d.cts → arkade-swaps-9M7FRuq1.d.cts} +57 -5
- package/dist/{arkade-swaps-WiKCanCL.d.ts → arkade-swaps-DNsyWeFr.d.ts} +57 -5
- package/dist/{chunk-NHBWNN6H.js → chunk-HNQDJOLM.js} +8 -27
- package/dist/{chunk-B3Q4TFWT.js → chunk-SJ5SYSMK.js} +551 -779
- package/dist/chunk-SJQJQO7P.js +25 -0
- package/dist/expo/background.cjs +573 -805
- package/dist/expo/background.d.cts +3 -3
- package/dist/expo/background.d.ts +3 -3
- package/dist/expo/background.js +8 -20
- package/dist/expo/index.cjs +574 -783
- package/dist/expo/index.d.cts +7 -5
- package/dist/expo/index.d.ts +7 -5
- package/dist/expo/index.js +17 -20
- package/dist/index.cjs +732 -931
- package/dist/index.d.cts +80 -10
- package/dist/index.d.ts +80 -10
- package/dist/index.js +126 -115
- package/dist/repositories/realm/index.cjs +10 -22
- package/dist/repositories/realm/index.d.cts +7 -5
- package/dist/repositories/realm/index.d.ts +7 -5
- package/dist/repositories/realm/index.js +8 -22
- package/dist/repositories/sqlite/index.cjs +12 -23
- package/dist/repositories/sqlite/index.d.cts +1 -1
- package/dist/repositories/sqlite/index.d.ts +1 -1
- package/dist/repositories/sqlite/index.js +10 -23
- package/dist/{swapsPollProcessor-wYOMzldd.d.ts → swapsPollProcessor-CEgeGlbP.d.ts} +3 -3
- package/dist/{swapsPollProcessor-BF3uTFae.d.cts → swapsPollProcessor-CuITxZie.d.cts} +3 -3
- package/dist/{types-BBI7-KJ0.d.cts → types-CrKkVzBB.d.cts} +9 -3
- package/dist/{types-BBI7-KJ0.d.ts → types-CrKkVzBB.d.ts} +9 -3
- package/package.json +10 -25
package/dist/index.cjs
CHANGED
|
@@ -41,6 +41,7 @@ __export(index_exports, {
|
|
|
41
41
|
InvoiceFailedToPayError: () => InvoiceFailedToPayError,
|
|
42
42
|
NetworkError: () => NetworkError,
|
|
43
43
|
PreimageFetchError: () => PreimageFetchError,
|
|
44
|
+
QuoteRejectedError: () => QuoteRejectedError,
|
|
44
45
|
SchemaError: () => SchemaError,
|
|
45
46
|
ServiceWorkerArkadeLightning: () => ServiceWorkerArkadeSwaps,
|
|
46
47
|
ServiceWorkerArkadeSwaps: () => ServiceWorkerArkadeSwaps,
|
|
@@ -99,7 +100,10 @@ var SwapError = class extends Error {
|
|
|
99
100
|
/** The pending swap associated with this error, if available. */
|
|
100
101
|
pendingSwap;
|
|
101
102
|
constructor(options = {}) {
|
|
102
|
-
super(
|
|
103
|
+
super(
|
|
104
|
+
options.message ?? "Error during swap.",
|
|
105
|
+
options.cause !== void 0 ? { cause: options.cause } : void 0
|
|
106
|
+
);
|
|
103
107
|
this.name = "SwapError";
|
|
104
108
|
this.isClaimable = options.isClaimable ?? false;
|
|
105
109
|
this.isRefundable = options.isRefundable ?? false;
|
|
@@ -191,6 +195,96 @@ var TransactionRefundedError = class extends SwapError {
|
|
|
191
195
|
this.name = "TransactionRefundedError";
|
|
192
196
|
}
|
|
193
197
|
};
|
|
198
|
+
var QuoteRejectedError = class _QuoteRejectedError extends SwapError {
|
|
199
|
+
reason;
|
|
200
|
+
quotedAmount;
|
|
201
|
+
floor;
|
|
202
|
+
constructor(options) {
|
|
203
|
+
super({
|
|
204
|
+
message: options.message ?? _QuoteRejectedError.defaultMessage(options),
|
|
205
|
+
...options
|
|
206
|
+
});
|
|
207
|
+
this.name = "QuoteRejectedError";
|
|
208
|
+
this.reason = options.reason;
|
|
209
|
+
this.quotedAmount = "quotedAmount" in options ? options.quotedAmount : void 0;
|
|
210
|
+
this.floor = "floor" in options ? options.floor : void 0;
|
|
211
|
+
}
|
|
212
|
+
static defaultMessage(options) {
|
|
213
|
+
switch (options.reason) {
|
|
214
|
+
case "below_floor":
|
|
215
|
+
return `Boltz quote ${options.quotedAmount} is below acceptable floor ${options.floor}`;
|
|
216
|
+
case "non_positive":
|
|
217
|
+
return `Boltz quote ${options.quotedAmount} is not positive`;
|
|
218
|
+
case "no_baseline":
|
|
219
|
+
return "Cannot accept quote: no minAcceptableAmount and no stored pending swap";
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
/**
|
|
223
|
+
* Serialize into a plain `Error` whose `.message` carries the full
|
|
224
|
+
* rejection payload as JSON behind a marker prefix. Structured clone
|
|
225
|
+
* (used by `postMessage` between page and service worker) preserves
|
|
226
|
+
* `Error.message` reliably but strips custom `.name` and own properties,
|
|
227
|
+
* so we move the typed data into the message field for transport.
|
|
228
|
+
*/
|
|
229
|
+
toTransportError() {
|
|
230
|
+
return new Error(
|
|
231
|
+
QUOTE_REJECTION_TRANSPORT_PREFIX + JSON.stringify({
|
|
232
|
+
reason: this.reason,
|
|
233
|
+
message: this.message,
|
|
234
|
+
quotedAmount: this.quotedAmount,
|
|
235
|
+
floor: this.floor
|
|
236
|
+
})
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Inverse of `toTransportError`. Returns a real `QuoteRejectedError` if
|
|
241
|
+
* `error` carries the transport prefix, else `null`.
|
|
242
|
+
*/
|
|
243
|
+
static fromTransportError(error) {
|
|
244
|
+
if (!(error instanceof Error) || !error.message.startsWith(QUOTE_REJECTION_TRANSPORT_PREFIX)) {
|
|
245
|
+
return null;
|
|
246
|
+
}
|
|
247
|
+
const payload = error.message.slice(QUOTE_REJECTION_TRANSPORT_PREFIX.length);
|
|
248
|
+
let data;
|
|
249
|
+
try {
|
|
250
|
+
data = JSON.parse(payload);
|
|
251
|
+
} catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
if (typeof data.reason !== "string" || !QUOTE_REJECTION_REASONS.has(data.reason)) {
|
|
255
|
+
return null;
|
|
256
|
+
}
|
|
257
|
+
const message = typeof data.message === "string" ? data.message : void 0;
|
|
258
|
+
const reason = data.reason;
|
|
259
|
+
const quotedAmount = typeof data.quotedAmount === "number" ? data.quotedAmount : null;
|
|
260
|
+
const floor = typeof data.floor === "number" ? data.floor : null;
|
|
261
|
+
switch (reason) {
|
|
262
|
+
case "below_floor":
|
|
263
|
+
if (quotedAmount === null || floor === null) return null;
|
|
264
|
+
return new _QuoteRejectedError({
|
|
265
|
+
reason,
|
|
266
|
+
quotedAmount,
|
|
267
|
+
floor,
|
|
268
|
+
message
|
|
269
|
+
});
|
|
270
|
+
case "non_positive":
|
|
271
|
+
if (quotedAmount === null) return null;
|
|
272
|
+
return new _QuoteRejectedError({
|
|
273
|
+
reason,
|
|
274
|
+
quotedAmount,
|
|
275
|
+
message
|
|
276
|
+
});
|
|
277
|
+
case "no_baseline":
|
|
278
|
+
return new _QuoteRejectedError({ reason, message });
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
};
|
|
282
|
+
var QUOTE_REJECTION_TRANSPORT_PREFIX = "QUOTE_REJECTED::";
|
|
283
|
+
var QUOTE_REJECTION_REASONS = /* @__PURE__ */ new Set([
|
|
284
|
+
"below_floor",
|
|
285
|
+
"non_positive",
|
|
286
|
+
"no_baseline"
|
|
287
|
+
]);
|
|
194
288
|
var BoltzRefundError = class extends Error {
|
|
195
289
|
constructor(message, cause) {
|
|
196
290
|
super(message);
|
|
@@ -206,18 +300,10 @@ var import_sdk8 = require("@arkade-os/sdk");
|
|
|
206
300
|
var import_sdk = require("@arkade-os/sdk");
|
|
207
301
|
var import_base = require("@scure/base");
|
|
208
302
|
var isSubmarineFailedStatus = (status) => {
|
|
209
|
-
return [
|
|
210
|
-
"invoice.failedToPay",
|
|
211
|
-
"transaction.lockupFailed",
|
|
212
|
-
"swap.expired"
|
|
213
|
-
].includes(status);
|
|
303
|
+
return ["invoice.failedToPay", "transaction.lockupFailed", "swap.expired"].includes(status);
|
|
214
304
|
};
|
|
215
305
|
var isSubmarineFinalStatus = (status) => {
|
|
216
|
-
return [
|
|
217
|
-
"invoice.failedToPay",
|
|
218
|
-
"transaction.claimed",
|
|
219
|
-
"swap.expired"
|
|
220
|
-
].includes(status);
|
|
306
|
+
return ["invoice.failedToPay", "transaction.claimed", "swap.expired"].includes(status);
|
|
221
307
|
};
|
|
222
308
|
var isSubmarinePendingStatus = (status) => {
|
|
223
309
|
return [
|
|
@@ -231,11 +317,7 @@ var isSubmarinePendingStatus = (status) => {
|
|
|
231
317
|
].includes(status);
|
|
232
318
|
};
|
|
233
319
|
var isSubmarineRefundableStatus = (status) => {
|
|
234
|
-
return [
|
|
235
|
-
"invoice.failedToPay",
|
|
236
|
-
"transaction.lockupFailed",
|
|
237
|
-
"swap.expired"
|
|
238
|
-
].includes(status);
|
|
320
|
+
return ["invoice.failedToPay", "transaction.lockupFailed", "swap.expired"].includes(status);
|
|
239
321
|
};
|
|
240
322
|
var isSubmarineSuccessStatus = (status) => {
|
|
241
323
|
return status === "transaction.claimed";
|
|
@@ -259,11 +341,7 @@ var isReverseFinalStatus = (status) => {
|
|
|
259
341
|
].includes(status);
|
|
260
342
|
};
|
|
261
343
|
var isReversePendingStatus = (status) => {
|
|
262
|
-
return [
|
|
263
|
-
"swap.created",
|
|
264
|
-
"transaction.mempool",
|
|
265
|
-
"transaction.confirmed"
|
|
266
|
-
].includes(status);
|
|
344
|
+
return ["swap.created", "transaction.mempool", "transaction.confirmed"].includes(status);
|
|
267
345
|
};
|
|
268
346
|
var isReverseClaimableStatus = (status) => {
|
|
269
347
|
return ["transaction.mempool", "transaction.confirmed"].includes(status);
|
|
@@ -275,10 +353,7 @@ var isChainFailedStatus = (status) => {
|
|
|
275
353
|
return ["transaction.failed", "swap.expired"].includes(status);
|
|
276
354
|
};
|
|
277
355
|
var isChainClaimableStatus = (status) => {
|
|
278
|
-
return [
|
|
279
|
-
"transaction.server.mempool",
|
|
280
|
-
"transaction.server.confirmed"
|
|
281
|
-
].includes(status);
|
|
356
|
+
return ["transaction.server.mempool", "transaction.server.confirmed"].includes(status);
|
|
282
357
|
};
|
|
283
358
|
var isChainFinalStatus = (status) => {
|
|
284
359
|
return [
|
|
@@ -417,8 +492,7 @@ var BASE_URLS = {
|
|
|
417
492
|
var isSwapNotFoundBody = (error) => {
|
|
418
493
|
const needle = "could not find swap";
|
|
419
494
|
const fromJson = error.errorData?.error;
|
|
420
|
-
if (typeof fromJson === "string" && fromJson.toLowerCase().includes(needle))
|
|
421
|
-
return true;
|
|
495
|
+
if (typeof fromJson === "string" && fromJson.toLowerCase().includes(needle)) return true;
|
|
422
496
|
return error.message.toLowerCase().includes(needle);
|
|
423
497
|
};
|
|
424
498
|
var BoltzSwapProvider = class {
|
|
@@ -432,10 +506,7 @@ var BoltzSwapProvider = class {
|
|
|
432
506
|
this.network = config.network;
|
|
433
507
|
this.referralId = config.referralId ?? "arkade-ts-sdk";
|
|
434
508
|
const apiUrl = config.apiUrl || BASE_URLS[config.network];
|
|
435
|
-
if (!apiUrl)
|
|
436
|
-
throw new Error(
|
|
437
|
-
`API URL is required for network: ${config.network}`
|
|
438
|
-
);
|
|
509
|
+
if (!apiUrl) throw new Error(`API URL is required for network: ${config.network}`);
|
|
439
510
|
this.apiUrl = apiUrl;
|
|
440
511
|
this.wsUrl = this.apiUrl.replace(/^http(s)?:\/\//, "ws$1://").replace("9069", "9004") + "/v2/ws";
|
|
441
512
|
}
|
|
@@ -454,10 +525,7 @@ var BoltzSwapProvider = class {
|
|
|
454
525
|
/** Returns current Lightning swap fees (submarine + reverse) from Boltz. */
|
|
455
526
|
async getFees() {
|
|
456
527
|
const [submarine, reverse] = await Promise.all([
|
|
457
|
-
this.request(
|
|
458
|
-
"/v2/swap/submarine",
|
|
459
|
-
"GET"
|
|
460
|
-
),
|
|
528
|
+
this.request("/v2/swap/submarine", "GET"),
|
|
461
529
|
this.request("/v2/swap/reverse", "GET")
|
|
462
530
|
]);
|
|
463
531
|
if (!isGetSubmarinePairsResponse(submarine))
|
|
@@ -477,10 +545,7 @@ var BoltzSwapProvider = class {
|
|
|
477
545
|
}
|
|
478
546
|
/** Returns current Lightning swap min/max limits from Boltz. */
|
|
479
547
|
async getLimits() {
|
|
480
|
-
const response = await this.request(
|
|
481
|
-
"/v2/swap/submarine",
|
|
482
|
-
"GET"
|
|
483
|
-
);
|
|
548
|
+
const response = await this.request("/v2/swap/submarine", "GET");
|
|
484
549
|
if (!isGetSubmarinePairsResponse(response))
|
|
485
550
|
throw new SchemaError({ message: "error fetching limits" });
|
|
486
551
|
return {
|
|
@@ -490,10 +555,7 @@ var BoltzSwapProvider = class {
|
|
|
490
555
|
}
|
|
491
556
|
/** Returns the current BTC chain tip height from Boltz. */
|
|
492
557
|
async getChainHeight() {
|
|
493
|
-
const response = await this.request(
|
|
494
|
-
"/v2/chain/heights",
|
|
495
|
-
"GET"
|
|
496
|
-
);
|
|
558
|
+
const response = await this.request("/v2/chain/heights", "GET");
|
|
497
559
|
if (typeof response?.BTC !== "number")
|
|
498
560
|
throw new SchemaError({
|
|
499
561
|
message: "error fetching chain heights"
|
|
@@ -523,10 +585,7 @@ var BoltzSwapProvider = class {
|
|
|
523
585
|
async getSwapStatus(id) {
|
|
524
586
|
let response;
|
|
525
587
|
try {
|
|
526
|
-
response = await this.request(
|
|
527
|
-
`/v2/swap/${id}`,
|
|
528
|
-
"GET"
|
|
529
|
-
);
|
|
588
|
+
response = await this.request(`/v2/swap/${id}`, "GET");
|
|
530
589
|
} catch (error) {
|
|
531
590
|
if (error instanceof NetworkError && error.statusCode === 404 && isSwapNotFoundBody(error)) {
|
|
532
591
|
throw new SwapNotFoundError(id, error.errorData);
|
|
@@ -622,12 +681,10 @@ var BoltzSwapProvider = class {
|
|
|
622
681
|
throw new SwapError({ message: "Invalid 'to' chain" });
|
|
623
682
|
if (["BTC", "ARK"].indexOf(from) === -1)
|
|
624
683
|
throw new SwapError({ message: "Invalid 'from' chain" });
|
|
625
|
-
if (to === from)
|
|
626
|
-
throw new SwapError({ message: "Invalid swap direction" });
|
|
684
|
+
if (to === from) throw new SwapError({ message: "Invalid swap direction" });
|
|
627
685
|
if (!preimageHash || preimageHash.length != 64)
|
|
628
686
|
throw new SwapError({ message: "Invalid preimageHash" });
|
|
629
|
-
if (feeSatsPerByte <= 0)
|
|
630
|
-
throw new SwapError({ message: "Invalid feeSatsPerByte" });
|
|
687
|
+
if (feeSatsPerByte <= 0) throw new SwapError({ message: "Invalid feeSatsPerByte" });
|
|
631
688
|
if (serverLockAmount !== void 0 && userLockAmount !== void 0 || serverLockAmount === void 0 && userLockAmount === void 0)
|
|
632
689
|
throw new SwapError({
|
|
633
690
|
message: "Either serverLockAmount or userLockAmount must be provided"
|
|
@@ -682,12 +739,8 @@ var BoltzSwapProvider = class {
|
|
|
682
739
|
message: "Error refunding submarine swap"
|
|
683
740
|
});
|
|
684
741
|
return {
|
|
685
|
-
transaction: import_sdk.Transaction.fromPSBT(
|
|
686
|
-
|
|
687
|
-
),
|
|
688
|
-
checkpoint: import_sdk.Transaction.fromPSBT(
|
|
689
|
-
import_base.base64.decode(response.checkpoint)
|
|
690
|
-
)
|
|
742
|
+
transaction: import_sdk.Transaction.fromPSBT(import_base.base64.decode(response.transaction)),
|
|
743
|
+
checkpoint: import_sdk.Transaction.fromPSBT(import_base.base64.decode(response.checkpoint))
|
|
691
744
|
};
|
|
692
745
|
}
|
|
693
746
|
/** Requests Boltz co-signature for a chain swap refund. Returns signed transaction + checkpoint. */
|
|
@@ -706,53 +759,53 @@ var BoltzSwapProvider = class {
|
|
|
706
759
|
message: "Error refunding chain swap"
|
|
707
760
|
});
|
|
708
761
|
return {
|
|
709
|
-
transaction: import_sdk.Transaction.fromPSBT(
|
|
710
|
-
|
|
711
|
-
),
|
|
712
|
-
checkpoint: import_sdk.Transaction.fromPSBT(
|
|
713
|
-
import_base.base64.decode(response.checkpoint)
|
|
714
|
-
)
|
|
762
|
+
transaction: import_sdk.Transaction.fromPSBT(import_base.base64.decode(response.transaction)),
|
|
763
|
+
checkpoint: import_sdk.Transaction.fromPSBT(import_base.base64.decode(response.checkpoint))
|
|
715
764
|
};
|
|
716
765
|
}
|
|
717
|
-
/**
|
|
766
|
+
/**
|
|
767
|
+
* Monitors swap status updates and forwards them to the update callback.
|
|
768
|
+
* Prefers a WebSocket subscription; on connection error or premature close
|
|
769
|
+
* it falls back to REST polling so callers don't fail when the WS endpoint
|
|
770
|
+
* is flaky (observed in CI). Resolves when the swap reaches a terminal
|
|
771
|
+
* status.
|
|
772
|
+
*/
|
|
718
773
|
async monitorSwap(swapId, update) {
|
|
719
774
|
return new Promise((resolve, reject) => {
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
);
|
|
775
|
+
let settled = false;
|
|
776
|
+
let lastStatus = null;
|
|
777
|
+
let pollTimer = null;
|
|
778
|
+
let webSocket = null;
|
|
779
|
+
let connectionTimeout = null;
|
|
780
|
+
const cleanup = () => {
|
|
781
|
+
if (connectionTimeout) {
|
|
782
|
+
clearTimeout(connectionTimeout);
|
|
783
|
+
connectionTimeout = null;
|
|
784
|
+
}
|
|
785
|
+
if (pollTimer) {
|
|
786
|
+
clearInterval(pollTimer);
|
|
787
|
+
pollTimer = null;
|
|
788
|
+
}
|
|
789
|
+
if (webSocket) {
|
|
790
|
+
try {
|
|
791
|
+
webSocket.close();
|
|
792
|
+
} catch {
|
|
793
|
+
}
|
|
794
|
+
webSocket = null;
|
|
795
|
+
}
|
|
742
796
|
};
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
797
|
+
const finish = (err) => {
|
|
798
|
+
if (settled) return;
|
|
799
|
+
settled = true;
|
|
800
|
+
cleanup();
|
|
801
|
+
if (err) reject(err);
|
|
802
|
+
else resolve();
|
|
746
803
|
};
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
if (
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
reject(new SwapError({ message: msg.args[0].error }));
|
|
753
|
-
}
|
|
754
|
-
const status = msg.args[0].status;
|
|
755
|
-
const negotiable = status === "transaction.lockupFailed" && msg.args[0].failureDetails?.actual !== void 0 && msg.args[0].failureDetails?.expected !== void 0;
|
|
804
|
+
const handleStatus = (status, data) => {
|
|
805
|
+
if (settled) return;
|
|
806
|
+
if (status === lastStatus) return;
|
|
807
|
+
lastStatus = status;
|
|
808
|
+
const negotiable = status === "transaction.lockupFailed" && data?.failureDetails?.actual !== void 0 && data?.failureDetails?.expected !== void 0;
|
|
756
809
|
switch (status) {
|
|
757
810
|
case "invoice.settled":
|
|
758
811
|
case "transaction.claimed":
|
|
@@ -761,13 +814,13 @@ var BoltzSwapProvider = class {
|
|
|
761
814
|
case "invoice.failedToPay":
|
|
762
815
|
case "transaction.failed":
|
|
763
816
|
case "swap.expired":
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
817
|
+
update(status, data);
|
|
818
|
+
finish();
|
|
819
|
+
return;
|
|
767
820
|
case "transaction.lockupFailed":
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
821
|
+
update(status, data);
|
|
822
|
+
if (!negotiable) finish();
|
|
823
|
+
return;
|
|
771
824
|
case "invoice.paid":
|
|
772
825
|
case "invoice.pending":
|
|
773
826
|
case "invoice.set":
|
|
@@ -777,9 +830,77 @@ var BoltzSwapProvider = class {
|
|
|
777
830
|
case "transaction.claim.pending":
|
|
778
831
|
case "transaction.server.mempool":
|
|
779
832
|
case "transaction.server.confirmed":
|
|
780
|
-
update(status,
|
|
833
|
+
update(status, data);
|
|
834
|
+
return;
|
|
781
835
|
}
|
|
782
836
|
};
|
|
837
|
+
const startPolling = () => {
|
|
838
|
+
if (settled || pollTimer) return;
|
|
839
|
+
const poll = async () => {
|
|
840
|
+
if (settled) return;
|
|
841
|
+
try {
|
|
842
|
+
const result = await this.getSwapStatus(swapId);
|
|
843
|
+
handleStatus(result.status, { ...result, id: swapId });
|
|
844
|
+
} catch {
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
pollTimer = setInterval(poll, 1e3);
|
|
848
|
+
poll();
|
|
849
|
+
};
|
|
850
|
+
try {
|
|
851
|
+
webSocket = new globalThis.WebSocket(this.wsUrl);
|
|
852
|
+
connectionTimeout = setTimeout(() => {
|
|
853
|
+
try {
|
|
854
|
+
webSocket?.close();
|
|
855
|
+
} catch {
|
|
856
|
+
}
|
|
857
|
+
webSocket = null;
|
|
858
|
+
startPolling();
|
|
859
|
+
}, 5e3);
|
|
860
|
+
webSocket.onerror = () => {
|
|
861
|
+
if (connectionTimeout) {
|
|
862
|
+
clearTimeout(connectionTimeout);
|
|
863
|
+
connectionTimeout = null;
|
|
864
|
+
}
|
|
865
|
+
webSocket = null;
|
|
866
|
+
startPolling();
|
|
867
|
+
};
|
|
868
|
+
webSocket.onopen = () => {
|
|
869
|
+
if (connectionTimeout) {
|
|
870
|
+
clearTimeout(connectionTimeout);
|
|
871
|
+
connectionTimeout = null;
|
|
872
|
+
}
|
|
873
|
+
webSocket?.send(
|
|
874
|
+
JSON.stringify({
|
|
875
|
+
op: "subscribe",
|
|
876
|
+
channel: "swap.update",
|
|
877
|
+
args: [swapId]
|
|
878
|
+
})
|
|
879
|
+
);
|
|
880
|
+
};
|
|
881
|
+
webSocket.onclose = () => {
|
|
882
|
+
if (connectionTimeout) {
|
|
883
|
+
clearTimeout(connectionTimeout);
|
|
884
|
+
connectionTimeout = null;
|
|
885
|
+
}
|
|
886
|
+
if (!settled && !pollTimer) startPolling();
|
|
887
|
+
};
|
|
888
|
+
webSocket.onmessage = (rawMsg) => {
|
|
889
|
+
try {
|
|
890
|
+
const msg = JSON.parse(rawMsg.data);
|
|
891
|
+
if (msg.event !== "update" || msg.args?.[0]?.id !== swapId) return;
|
|
892
|
+
if (msg.args[0].error) {
|
|
893
|
+
finish(new SwapError({ message: msg.args[0].error }));
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
handleStatus(msg.args[0].status, msg.args[0]);
|
|
897
|
+
} catch {
|
|
898
|
+
}
|
|
899
|
+
};
|
|
900
|
+
} catch {
|
|
901
|
+
webSocket = null;
|
|
902
|
+
startPolling();
|
|
903
|
+
}
|
|
783
904
|
});
|
|
784
905
|
}
|
|
785
906
|
/** Returns current chain swap fees for a given pair (e.g. ARK→BTC). */
|
|
@@ -787,10 +908,7 @@ var BoltzSwapProvider = class {
|
|
|
787
908
|
if (from === to) {
|
|
788
909
|
throw new SwapError({ message: "Invalid chain pair" });
|
|
789
910
|
}
|
|
790
|
-
const response = await this.request(
|
|
791
|
-
"/v2/swap/chain",
|
|
792
|
-
"GET"
|
|
793
|
-
);
|
|
911
|
+
const response = await this.request("/v2/swap/chain", "GET");
|
|
794
912
|
if (!isGetChainPairsResponse(response))
|
|
795
913
|
throw new SchemaError({ message: "error fetching fees" });
|
|
796
914
|
if (!response[from]?.[to]) {
|
|
@@ -805,10 +923,7 @@ var BoltzSwapProvider = class {
|
|
|
805
923
|
if (from === to) {
|
|
806
924
|
throw new SwapError({ message: "Invalid chain pair" });
|
|
807
925
|
}
|
|
808
|
-
const response = await this.request(
|
|
809
|
-
"/v2/swap/chain",
|
|
810
|
-
"GET"
|
|
811
|
-
);
|
|
926
|
+
const response = await this.request("/v2/swap/chain", "GET");
|
|
812
927
|
if (!isGetChainPairsResponse(response))
|
|
813
928
|
throw new SchemaError({ message: "error fetching limits" });
|
|
814
929
|
if (!response[from]?.[to]) {
|
|
@@ -937,9 +1052,7 @@ var BoltzSwapProvider = class {
|
|
|
937
1052
|
return await response.json();
|
|
938
1053
|
} catch (error) {
|
|
939
1054
|
if (error instanceof NetworkError) throw error;
|
|
940
|
-
throw new NetworkError(
|
|
941
|
-
`Request to ${url} failed: ${error.message}`
|
|
942
|
-
);
|
|
1055
|
+
throw new NetworkError(`Request to ${url} failed: ${error.message}`);
|
|
943
1056
|
}
|
|
944
1057
|
}
|
|
945
1058
|
};
|
|
@@ -961,8 +1074,7 @@ var findKeyIndex = (keys, target) => keys.findIndex((k) => (0, import_utils.equa
|
|
|
961
1074
|
var assertPublicKeys = (keys) => {
|
|
962
1075
|
const seen = /* @__PURE__ */ new Set();
|
|
963
1076
|
for (const key of keys) {
|
|
964
|
-
if (key.length !== 33)
|
|
965
|
-
throw new Error(`public key must be 33 bytes, got ${key.length}`);
|
|
1077
|
+
if (key.length !== 33) throw new Error(`public key must be 33 bytes, got ${key.length}`);
|
|
966
1078
|
const enc = import_base2.hex.encode(key);
|
|
967
1079
|
if (seen.has(enc)) throw new Error(`duplicate public key ${enc}`);
|
|
968
1080
|
seen.add(enc);
|
|
@@ -970,9 +1082,7 @@ var assertPublicKeys = (keys) => {
|
|
|
970
1082
|
};
|
|
971
1083
|
var aggregateKeys = (publicKeys, tweak) => {
|
|
972
1084
|
assertPublicKeys([...publicKeys]);
|
|
973
|
-
return (0, import_musig2.keyAggExport)(
|
|
974
|
-
(0, import_musig2.keyAggregate)([...publicKeys], tweak ? [tweak] : [], tweak ? [true] : [])
|
|
975
|
-
);
|
|
1085
|
+
return (0, import_musig2.keyAggExport)((0, import_musig2.keyAggregate)([...publicKeys], tweak ? [tweak] : [], tweak ? [true] : []));
|
|
976
1086
|
};
|
|
977
1087
|
var MusigKeyAgg = class _MusigKeyAgg {
|
|
978
1088
|
constructor(privateKey, myPublicKey, publicKeys, myIndex, aggPubkey, internalKey, _tweak) {
|
|
@@ -1019,18 +1129,12 @@ var MusigWithMessage = class {
|
|
|
1019
1129
|
this.msg = msg;
|
|
1020
1130
|
}
|
|
1021
1131
|
generateNonce() {
|
|
1022
|
-
const nonce = (0, import_musig2.nonceGen)(
|
|
1023
|
-
this.myPublicKey,
|
|
1024
|
-
this.privateKey,
|
|
1025
|
-
this.aggPubkey,
|
|
1026
|
-
this.msg
|
|
1027
|
-
);
|
|
1132
|
+
const nonce = (0, import_musig2.nonceGen)(this.myPublicKey, this.privateKey, this.aggPubkey, this.msg);
|
|
1028
1133
|
return new MusigWithNonce(
|
|
1029
1134
|
this.privateKey,
|
|
1030
1135
|
this.myPublicKey,
|
|
1031
1136
|
this.publicKeys,
|
|
1032
1137
|
this.myIndex,
|
|
1033
|
-
this.aggPubkey,
|
|
1034
1138
|
this.tweak,
|
|
1035
1139
|
this.msg,
|
|
1036
1140
|
nonce
|
|
@@ -1038,12 +1142,11 @@ var MusigWithMessage = class {
|
|
|
1038
1142
|
}
|
|
1039
1143
|
};
|
|
1040
1144
|
var MusigWithNonce = class {
|
|
1041
|
-
constructor(privateKey, myPublicKey, publicKeys, myIndex,
|
|
1145
|
+
constructor(privateKey, myPublicKey, publicKeys, myIndex, tweak, msg, nonce) {
|
|
1042
1146
|
this.privateKey = privateKey;
|
|
1043
1147
|
this.myPublicKey = myPublicKey;
|
|
1044
1148
|
this.publicKeys = publicKeys;
|
|
1045
1149
|
this.myIndex = myIndex;
|
|
1046
|
-
this.aggPubkey = aggPubkey;
|
|
1047
1150
|
this.tweak = tweak;
|
|
1048
1151
|
this.msg = msg;
|
|
1049
1152
|
this.nonce = nonce;
|
|
@@ -1075,10 +1178,8 @@ var MusigWithNonce = class {
|
|
|
1075
1178
|
const aggregatedNonce = (0, import_musig2.nonceAggregate)([...ordered]);
|
|
1076
1179
|
return new MusigNoncesAggregated(
|
|
1077
1180
|
this.privateKey,
|
|
1078
|
-
this.myPublicKey,
|
|
1079
1181
|
this.publicKeys,
|
|
1080
1182
|
this.myIndex,
|
|
1081
|
-
this.aggPubkey,
|
|
1082
1183
|
this.tweak,
|
|
1083
1184
|
this.msg,
|
|
1084
1185
|
this.nonce,
|
|
@@ -1088,12 +1189,10 @@ var MusigWithNonce = class {
|
|
|
1088
1189
|
}
|
|
1089
1190
|
};
|
|
1090
1191
|
var MusigNoncesAggregated = class {
|
|
1091
|
-
constructor(privateKey,
|
|
1192
|
+
constructor(privateKey, publicKeys, myIndex, tweak, msg, nonce, pubNonces, aggregatedNonce) {
|
|
1092
1193
|
this.privateKey = privateKey;
|
|
1093
|
-
this.myPublicKey = myPublicKey;
|
|
1094
1194
|
this.publicKeys = publicKeys;
|
|
1095
1195
|
this.myIndex = myIndex;
|
|
1096
|
-
this.aggPubkey = aggPubkey;
|
|
1097
1196
|
this.tweak = tweak;
|
|
1098
1197
|
this.msg = msg;
|
|
1099
1198
|
this.nonce = nonce;
|
|
@@ -1139,11 +1238,7 @@ var MusigSession = class {
|
|
|
1139
1238
|
const index = typeof publicKeyOrIndex === "number" ? publicKeyOrIndex : findKeyIndex(this.publicKeys, publicKeyOrIndex);
|
|
1140
1239
|
if (index < 0 || index >= this.publicKeys.length)
|
|
1141
1240
|
throw new Error("public key not found or index out of range");
|
|
1142
|
-
if (!this.session.partialSigVerify(
|
|
1143
|
-
signature,
|
|
1144
|
-
[...this.pubNonces],
|
|
1145
|
-
index
|
|
1146
|
-
)) {
|
|
1241
|
+
if (!this.session.partialSigVerify(signature, [...this.pubNonces], index)) {
|
|
1147
1242
|
throw new Error("invalid partial signature");
|
|
1148
1243
|
}
|
|
1149
1244
|
this.partialSignatures[index] = signature;
|
|
@@ -1152,12 +1247,7 @@ var MusigSession = class {
|
|
|
1152
1247
|
signPartial() {
|
|
1153
1248
|
const sig = this.session.sign(this.nonce.secret, this.privateKey, true);
|
|
1154
1249
|
this.partialSignatures[this.myIndex] = sig;
|
|
1155
|
-
return new MusigSigned(
|
|
1156
|
-
this.session,
|
|
1157
|
-
[...this.partialSignatures],
|
|
1158
|
-
sig,
|
|
1159
|
-
this.nonce.public
|
|
1160
|
-
);
|
|
1250
|
+
return new MusigSigned(this.session, [...this.partialSignatures], sig, this.nonce.public);
|
|
1161
1251
|
}
|
|
1162
1252
|
};
|
|
1163
1253
|
var MusigSigned = class {
|
|
@@ -1171,14 +1261,11 @@ var MusigSigned = class {
|
|
|
1171
1261
|
if (this.partialSignatures.some((s) => s === null)) {
|
|
1172
1262
|
throw new Error("not all partial signatures are set");
|
|
1173
1263
|
}
|
|
1174
|
-
return this.session.partialSigAgg(
|
|
1175
|
-
this.partialSignatures
|
|
1176
|
-
);
|
|
1264
|
+
return this.session.partialSigAgg(this.partialSignatures);
|
|
1177
1265
|
}
|
|
1178
1266
|
};
|
|
1179
1267
|
var create = (privateKey, publicKeys) => {
|
|
1180
|
-
if (publicKeys.length < 2)
|
|
1181
|
-
throw new Error("need at least 2 keys to aggregate");
|
|
1268
|
+
if (publicKeys.length < 2) throw new Error("need at least 2 keys to aggregate");
|
|
1182
1269
|
const keys = [...publicKeys];
|
|
1183
1270
|
assertPublicKeys(keys);
|
|
1184
1271
|
Object.freeze(keys);
|
|
@@ -1186,14 +1273,7 @@ var create = (privateKey, publicKeys) => {
|
|
|
1186
1273
|
const myIndex = findKeyIndex(keys, myPublicKey);
|
|
1187
1274
|
if (myIndex === -1) throw new Error("our key is not in publicKeys");
|
|
1188
1275
|
const aggPubkey = aggregateKeys(keys);
|
|
1189
|
-
return new MusigKeyAgg(
|
|
1190
|
-
privateKey,
|
|
1191
|
-
myPublicKey,
|
|
1192
|
-
keys,
|
|
1193
|
-
myIndex,
|
|
1194
|
-
aggPubkey,
|
|
1195
|
-
aggPubkey
|
|
1196
|
-
);
|
|
1276
|
+
return new MusigKeyAgg(privateKey, myPublicKey, keys, myIndex, aggPubkey, aggPubkey);
|
|
1197
1277
|
};
|
|
1198
1278
|
|
|
1199
1279
|
// src/utils/boltz-swap-tx.ts
|
|
@@ -1269,9 +1349,7 @@ var taprootHashTree = (tree) => {
|
|
|
1269
1349
|
};
|
|
1270
1350
|
var tweakMusig = (musig, tree) => {
|
|
1271
1351
|
const tweak = taprootHashTree(tree).hash;
|
|
1272
|
-
return musig.xonlyTweakAdd(
|
|
1273
|
-
import_secp256k12.schnorr.utils.taggedHash("TapTweak", musig.aggPubkey, tweak)
|
|
1274
|
-
);
|
|
1352
|
+
return musig.xonlyTweakAdd(import_secp256k12.schnorr.utils.taggedHash("TapTweak", musig.aggPubkey, tweak));
|
|
1275
1353
|
};
|
|
1276
1354
|
var toXOnly = (pubKey) => {
|
|
1277
1355
|
if (pubKey.length === 32) return pubKey;
|
|
@@ -1283,9 +1361,7 @@ var toXOnly = (pubKey) => {
|
|
|
1283
1361
|
}
|
|
1284
1362
|
return pubKey.subarray(1, 33);
|
|
1285
1363
|
}
|
|
1286
|
-
throw new Error(
|
|
1287
|
-
`Invalid public key length: expected 32 or 33 bytes, got ${pubKey.length}`
|
|
1288
|
-
);
|
|
1364
|
+
throw new Error(`Invalid public key length: expected 32 or 33 bytes, got ${pubKey.length}`);
|
|
1289
1365
|
};
|
|
1290
1366
|
var p2trScript = (publicKey) => import_btc_signer.Script.encode(["OP_1", toXOnly(publicKey)]);
|
|
1291
1367
|
var detectSwapOutput = (tweakedKey, transaction) => {
|
|
@@ -1300,8 +1376,7 @@ var detectSwapOutput = (tweakedKey, transaction) => {
|
|
|
1300
1376
|
};
|
|
1301
1377
|
var DUMMY_TAPROOT_SIGNATURE = new Uint8Array(64);
|
|
1302
1378
|
var constructClaimTransaction = (utxo, destinationScript, fee) => {
|
|
1303
|
-
if (fee < BigInt(0) || fee >= utxo.amount)
|
|
1304
|
-
throw new Error("fee exceeds utxo amount");
|
|
1379
|
+
if (fee < BigInt(0) || fee >= utxo.amount) throw new Error("fee exceeds utxo amount");
|
|
1305
1380
|
const tx = new import_btc_signer.Transaction({ version: 2 });
|
|
1306
1381
|
tx.addOutput({
|
|
1307
1382
|
amount: utxo.amount - fee,
|
|
@@ -1320,9 +1395,7 @@ var constructClaimTransaction = (utxo, destinationScript, fee) => {
|
|
|
1320
1395
|
};
|
|
1321
1396
|
var targetFee = (satPerVbyte, constructTx) => {
|
|
1322
1397
|
const tx = constructTx(BigInt(1));
|
|
1323
|
-
return constructTx(
|
|
1324
|
-
BigInt(Math.ceil((tx.vsize + tx.inputsLength) * satPerVbyte))
|
|
1325
|
-
);
|
|
1398
|
+
return constructTx(BigInt(Math.ceil((tx.vsize + tx.inputsLength) * satPerVbyte)));
|
|
1326
1399
|
};
|
|
1327
1400
|
|
|
1328
1401
|
// src/utils/decoding.ts
|
|
@@ -1330,9 +1403,7 @@ var import_light_bolt11_decoder = __toESM(require("light-bolt11-decoder"), 1);
|
|
|
1330
1403
|
var import_sdk2 = require("@arkade-os/sdk");
|
|
1331
1404
|
var decodeInvoice = (invoice) => {
|
|
1332
1405
|
const decoded = import_light_bolt11_decoder.default.decode(invoice);
|
|
1333
|
-
const millisats = Number(
|
|
1334
|
-
decoded.sections.find((s) => s.name === "amount")?.value ?? "0"
|
|
1335
|
-
);
|
|
1406
|
+
const millisats = Number(decoded.sections.find((s) => s.name === "amount")?.value ?? "0");
|
|
1336
1407
|
return {
|
|
1337
1408
|
expiry: decoded.expiry ?? 3600,
|
|
1338
1409
|
amountSats: Math.floor(millisats / 1e3),
|
|
@@ -1406,10 +1477,7 @@ function extractTimeLockFromLeafOutput(scriptHex) {
|
|
|
1406
1477
|
const data = opcodes[hasCSV - 1];
|
|
1407
1478
|
if (data instanceof Uint8Array) {
|
|
1408
1479
|
const dataBytes = new Uint8Array(data).reverse();
|
|
1409
|
-
const {
|
|
1410
|
-
blocks,
|
|
1411
|
-
seconds
|
|
1412
|
-
} = import_bip68.default.decode(
|
|
1480
|
+
const { blocks, seconds } = import_bip68.default.decode(
|
|
1413
1481
|
parseInt(import_base5.hex.encode(dataBytes), 16)
|
|
1414
1482
|
);
|
|
1415
1483
|
return blocks ?? seconds ?? 0;
|
|
@@ -1516,9 +1584,7 @@ var SwapManager = class _SwapManager {
|
|
|
1516
1584
|
this.wsConnectedListeners.add(config.events.onWebSocketConnected);
|
|
1517
1585
|
}
|
|
1518
1586
|
if (config.events?.onWebSocketDisconnected) {
|
|
1519
|
-
this.wsDisconnectedListeners.add(
|
|
1520
|
-
config.events.onWebSocketDisconnected
|
|
1521
|
-
);
|
|
1587
|
+
this.wsDisconnectedListeners.add(config.events.onWebSocketDisconnected);
|
|
1522
1588
|
}
|
|
1523
1589
|
this.currentReconnectDelay = this.config.reconnectDelayMs;
|
|
1524
1590
|
this.currentPollRetryDelay = this.config.pollRetryDelayMs;
|
|
@@ -1669,9 +1735,7 @@ var SwapManager = class _SwapManager {
|
|
|
1669
1735
|
*/
|
|
1670
1736
|
setPollInterval(ms) {
|
|
1671
1737
|
if (ms <= 0) {
|
|
1672
|
-
throw new RangeError(
|
|
1673
|
-
`setPollInterval: ms must be a positive number, got ${ms}`
|
|
1674
|
-
);
|
|
1738
|
+
throw new RangeError(`setPollInterval: ms must be a positive number, got ${ms}`);
|
|
1675
1739
|
}
|
|
1676
1740
|
const cappedInterval = Math.min(ms, this.config.maxPollIntervalMs);
|
|
1677
1741
|
if (cappedInterval !== ms) {
|
|
@@ -1680,10 +1744,7 @@ var SwapManager = class _SwapManager {
|
|
|
1680
1744
|
);
|
|
1681
1745
|
}
|
|
1682
1746
|
this.config.pollInterval = cappedInterval;
|
|
1683
|
-
this.currentPollRetryDelay = Math.min(
|
|
1684
|
-
cappedInterval,
|
|
1685
|
-
this.config.pollRetryDelayMs
|
|
1686
|
-
);
|
|
1747
|
+
this.currentPollRetryDelay = Math.min(cappedInterval, this.config.pollRetryDelayMs);
|
|
1687
1748
|
if (this.isRunning) {
|
|
1688
1749
|
if (this.usePollingFallback) {
|
|
1689
1750
|
this.startPollingFallback();
|
|
@@ -1768,9 +1829,7 @@ var SwapManager = class _SwapManager {
|
|
|
1768
1829
|
}
|
|
1769
1830
|
if (this.isFinalStatus(swap)) {
|
|
1770
1831
|
if (isPendingReverseSwap(swap)) {
|
|
1771
|
-
const response = await this.swapProvider.getReverseSwapTxId(
|
|
1772
|
-
swap.id
|
|
1773
|
-
);
|
|
1832
|
+
const response = await this.swapProvider.getReverseSwapTxId(swap.id);
|
|
1774
1833
|
return { txid: response.id };
|
|
1775
1834
|
}
|
|
1776
1835
|
if (isPendingSubmarineSwap(swap)) {
|
|
@@ -1787,31 +1846,19 @@ var SwapManager = class _SwapManager {
|
|
|
1787
1846
|
if (updatedSwap.status === "invoice.settled") {
|
|
1788
1847
|
this.swapProvider.getReverseSwapTxId(updatedSwap.id).then((response) => resolve({ txid: response.id })).catch((error) => reject(error));
|
|
1789
1848
|
} else {
|
|
1790
|
-
reject(
|
|
1791
|
-
new Error(
|
|
1792
|
-
`Swap failed with status: ${updatedSwap.status}`
|
|
1793
|
-
)
|
|
1794
|
-
);
|
|
1849
|
+
reject(new Error(`Swap failed with status: ${updatedSwap.status}`));
|
|
1795
1850
|
}
|
|
1796
1851
|
} else if (isPendingSubmarineSwap(updatedSwap)) {
|
|
1797
1852
|
if (updatedSwap.status === "transaction.claimed") {
|
|
1798
1853
|
resolve({ txid: updatedSwap.id });
|
|
1799
1854
|
} else {
|
|
1800
|
-
reject(
|
|
1801
|
-
new Error(
|
|
1802
|
-
`Swap failed with status: ${updatedSwap.status}`
|
|
1803
|
-
)
|
|
1804
|
-
);
|
|
1855
|
+
reject(new Error(`Swap failed with status: ${updatedSwap.status}`));
|
|
1805
1856
|
}
|
|
1806
1857
|
} else if (isPendingChainSwap(updatedSwap)) {
|
|
1807
1858
|
if (updatedSwap.status === "transaction.claimed") {
|
|
1808
1859
|
resolve({ txid: updatedSwap.id });
|
|
1809
1860
|
} else {
|
|
1810
|
-
reject(
|
|
1811
|
-
new Error(
|
|
1812
|
-
`Swap failed with status: ${updatedSwap.status}`
|
|
1813
|
-
)
|
|
1814
|
-
);
|
|
1861
|
+
reject(new Error(`Swap failed with status: ${updatedSwap.status}`));
|
|
1815
1862
|
}
|
|
1816
1863
|
}
|
|
1817
1864
|
};
|
|
@@ -1854,16 +1901,12 @@ var SwapManager = class _SwapManager {
|
|
|
1854
1901
|
const connectionTimeout = setTimeout(() => {
|
|
1855
1902
|
logger.error("WebSocket connection timeout");
|
|
1856
1903
|
this.websocket?.close();
|
|
1857
|
-
this.enterPollingFallback(
|
|
1858
|
-
new NetworkError("WebSocket connection failed")
|
|
1859
|
-
);
|
|
1904
|
+
this.enterPollingFallback(new NetworkError("WebSocket connection failed"));
|
|
1860
1905
|
}, 1e4);
|
|
1861
1906
|
this.websocket.onerror = (error) => {
|
|
1862
1907
|
clearTimeout(connectionTimeout);
|
|
1863
1908
|
logger.error("WebSocket error:", error);
|
|
1864
|
-
this.enterPollingFallback(
|
|
1865
|
-
new NetworkError("WebSocket connection failed")
|
|
1866
|
-
);
|
|
1909
|
+
this.enterPollingFallback(new NetworkError("WebSocket connection failed"));
|
|
1867
1910
|
};
|
|
1868
1911
|
this.websocket.onopen = () => {
|
|
1869
1912
|
clearTimeout(connectionTimeout);
|
|
@@ -1903,9 +1946,7 @@ var SwapManager = class _SwapManager {
|
|
|
1903
1946
|
};
|
|
1904
1947
|
} catch (error) {
|
|
1905
1948
|
logger.error("Failed to create WebSocket:", error);
|
|
1906
|
-
this.enterPollingFallback(
|
|
1907
|
-
new NetworkError("WebSocket connection failed")
|
|
1908
|
-
);
|
|
1949
|
+
this.enterPollingFallback(new NetworkError("WebSocket connection failed"));
|
|
1909
1950
|
}
|
|
1910
1951
|
}
|
|
1911
1952
|
/**
|
|
@@ -1940,11 +1981,8 @@ var SwapManager = class _SwapManager {
|
|
|
1940
1981
|
* Schedule WebSocket reconnection with exponential backoff
|
|
1941
1982
|
*/
|
|
1942
1983
|
scheduleReconnect() {
|
|
1943
|
-
if (this.reconnectTimer || this.webSocketUnavailable || !this.hasWebSocketSupport())
|
|
1944
|
-
|
|
1945
|
-
logger.log(
|
|
1946
|
-
`Scheduling WebSocket reconnect in ${this.currentReconnectDelay}ms`
|
|
1947
|
-
);
|
|
1984
|
+
if (this.reconnectTimer || this.webSocketUnavailable || !this.hasWebSocketSupport()) return;
|
|
1985
|
+
logger.log(`Scheduling WebSocket reconnect in ${this.currentReconnectDelay}ms`);
|
|
1948
1986
|
this.reconnectTimer = setTimeout(() => {
|
|
1949
1987
|
this.reconnectTimer = null;
|
|
1950
1988
|
this.isReconnecting = false;
|
|
@@ -1959,8 +1997,7 @@ var SwapManager = class _SwapManager {
|
|
|
1959
1997
|
* Subscribe to a specific swap ID on the WebSocket
|
|
1960
1998
|
*/
|
|
1961
1999
|
subscribeToSwap(swapId) {
|
|
1962
|
-
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN)
|
|
1963
|
-
return;
|
|
2000
|
+
if (!this.websocket || this.websocket.readyState !== WebSocket.OPEN) return;
|
|
1964
2001
|
this.websocket.send(
|
|
1965
2002
|
JSON.stringify({
|
|
1966
2003
|
op: "subscribe",
|
|
@@ -1983,9 +2020,7 @@ var SwapManager = class _SwapManager {
|
|
|
1983
2020
|
if (msg.args[0].error) {
|
|
1984
2021
|
logger.error(`Swap ${swapId} error:`, msg.args[0].error);
|
|
1985
2022
|
const error = new Error(msg.args[0].error);
|
|
1986
|
-
this.swapFailedListeners.forEach(
|
|
1987
|
-
(listener) => listener(swap, error)
|
|
1988
|
-
);
|
|
2023
|
+
this.swapFailedListeners.forEach((listener) => listener(swap, error));
|
|
1989
2024
|
return;
|
|
1990
2025
|
}
|
|
1991
2026
|
const newStatus = msg.args[0].status;
|
|
@@ -2003,19 +2038,14 @@ var SwapManager = class _SwapManager {
|
|
|
2003
2038
|
const oldStatus = swap.status;
|
|
2004
2039
|
if (oldStatus === newStatus) return;
|
|
2005
2040
|
swap.status = newStatus;
|
|
2006
|
-
this.swapUpdateListeners.forEach(
|
|
2007
|
-
(listener) => listener(swap, oldStatus)
|
|
2008
|
-
);
|
|
2041
|
+
this.swapUpdateListeners.forEach((listener) => listener(swap, oldStatus));
|
|
2009
2042
|
const subscribers = this.swapSubscriptions.get(swap.id);
|
|
2010
2043
|
if (subscribers) {
|
|
2011
2044
|
subscribers.forEach((callback) => {
|
|
2012
2045
|
try {
|
|
2013
2046
|
callback(swap, oldStatus);
|
|
2014
2047
|
} catch (error) {
|
|
2015
|
-
logger.error(
|
|
2016
|
-
`Error in swap subscription callback for ${swap.id}:`,
|
|
2017
|
-
error
|
|
2018
|
-
);
|
|
2048
|
+
logger.error(`Error in swap subscription callback for ${swap.id}:`, error);
|
|
2019
2049
|
}
|
|
2020
2050
|
});
|
|
2021
2051
|
}
|
|
@@ -2040,9 +2070,7 @@ var SwapManager = class _SwapManager {
|
|
|
2040
2070
|
*/
|
|
2041
2071
|
async executeAutonomousAction(swap) {
|
|
2042
2072
|
if (this.swapsInProgress.has(swap.id)) {
|
|
2043
|
-
logger.log(
|
|
2044
|
-
`Swap ${swap.id} is already being processed, skipping autonomous action`
|
|
2045
|
-
);
|
|
2073
|
+
logger.log(`Swap ${swap.id} is already being processed, skipping autonomous action`);
|
|
2046
2074
|
return;
|
|
2047
2075
|
}
|
|
2048
2076
|
try {
|
|
@@ -2057,9 +2085,7 @@ var SwapManager = class _SwapManager {
|
|
|
2057
2085
|
if (isReverseClaimableStatus(swap.status)) {
|
|
2058
2086
|
logger.log(`Auto-claiming reverse swap ${swap.id}`);
|
|
2059
2087
|
await this.executeClaimAction(swap);
|
|
2060
|
-
this.actionExecutedListeners.forEach(
|
|
2061
|
-
(listener) => listener(swap, "claim")
|
|
2062
|
-
);
|
|
2088
|
+
this.actionExecutedListeners.forEach((listener) => listener(swap, "claim"));
|
|
2063
2089
|
}
|
|
2064
2090
|
} else if (isPendingSubmarineSwap(swap)) {
|
|
2065
2091
|
if (!swap.request?.invoice || swap.request.invoice.length === 0) {
|
|
@@ -2071,9 +2097,7 @@ var SwapManager = class _SwapManager {
|
|
|
2071
2097
|
if (isSubmarineRefundableStatus(swap.status)) {
|
|
2072
2098
|
logger.log(`Auto-refunding submarine swap ${swap.id}`);
|
|
2073
2099
|
await this.executeRefundAction(swap);
|
|
2074
|
-
this.actionExecutedListeners.forEach(
|
|
2075
|
-
(listener) => listener(swap, "refund")
|
|
2076
|
-
);
|
|
2100
|
+
this.actionExecutedListeners.forEach((listener) => listener(swap, "refund"));
|
|
2077
2101
|
}
|
|
2078
2102
|
} else if (isPendingChainSwap(swap)) {
|
|
2079
2103
|
if (isChainClaimableStatus(swap.status)) {
|
|
@@ -2123,13 +2147,8 @@ var SwapManager = class _SwapManager {
|
|
|
2123
2147
|
}
|
|
2124
2148
|
}
|
|
2125
2149
|
} catch (error) {
|
|
2126
|
-
logger.error(
|
|
2127
|
-
|
|
2128
|
-
error
|
|
2129
|
-
);
|
|
2130
|
-
this.swapFailedListeners.forEach(
|
|
2131
|
-
(listener) => listener(swap, error)
|
|
2132
|
-
);
|
|
2150
|
+
logger.error(`Failed to execute autonomous action for swap ${swap.id}:`, error);
|
|
2151
|
+
this.swapFailedListeners.forEach((listener) => listener(swap, error));
|
|
2133
2152
|
} finally {
|
|
2134
2153
|
this.swapsInProgress.delete(swap.id);
|
|
2135
2154
|
}
|
|
@@ -2230,9 +2249,7 @@ var SwapManager = class _SwapManager {
|
|
|
2230
2249
|
logger.log(`Resuming chain refund for swap ${swap.id}`);
|
|
2231
2250
|
await this.executeAutonomousAction(swap);
|
|
2232
2251
|
} else if (isPendingChainSwap(swap) && swap.request.to === "ARK" && isChainSignableStatus(swap.status)) {
|
|
2233
|
-
logger.log(
|
|
2234
|
-
`Resuming server claim signing for swap ${swap.id}`
|
|
2235
|
-
);
|
|
2252
|
+
logger.log(`Resuming server claim signing for swap ${swap.id}`);
|
|
2236
2253
|
await this.executeAutonomousAction(swap);
|
|
2237
2254
|
}
|
|
2238
2255
|
} catch (error) {
|
|
@@ -2291,9 +2308,7 @@ var SwapManager = class _SwapManager {
|
|
|
2291
2308
|
}
|
|
2292
2309
|
async pollSingleSwap(swap) {
|
|
2293
2310
|
try {
|
|
2294
|
-
const statusResponse = await this.swapProvider.getSwapStatus(
|
|
2295
|
-
swap.id
|
|
2296
|
-
);
|
|
2311
|
+
const statusResponse = await this.swapProvider.getSwapStatus(swap.id);
|
|
2297
2312
|
this.notFoundCounts.delete(swap.id);
|
|
2298
2313
|
if (statusResponse.status !== swap.status) {
|
|
2299
2314
|
await this.handleSwapStatusUpdate(swap, statusResponse.status);
|
|
@@ -2304,9 +2319,7 @@ var SwapManager = class _SwapManager {
|
|
|
2304
2319
|
return;
|
|
2305
2320
|
}
|
|
2306
2321
|
if (error instanceof NetworkError && error.statusCode === 429) {
|
|
2307
|
-
logger.warn(
|
|
2308
|
-
`Rate-limited polling swap ${swap.id}, retrying in 2s`
|
|
2309
|
-
);
|
|
2322
|
+
logger.warn(`Rate-limited polling swap ${swap.id}, retrying in 2s`);
|
|
2310
2323
|
const existing = this.pollRetryTimers.get(swap.id);
|
|
2311
2324
|
if (existing) clearTimeout(existing);
|
|
2312
2325
|
this.pollRetryTimers.set(
|
|
@@ -2314,25 +2327,17 @@ var SwapManager = class _SwapManager {
|
|
|
2314
2327
|
setTimeout(async () => {
|
|
2315
2328
|
this.pollRetryTimers.delete(swap.id);
|
|
2316
2329
|
try {
|
|
2317
|
-
const retry = await this.swapProvider.getSwapStatus(
|
|
2318
|
-
swap.id
|
|
2319
|
-
);
|
|
2330
|
+
const retry = await this.swapProvider.getSwapStatus(swap.id);
|
|
2320
2331
|
this.notFoundCounts.delete(swap.id);
|
|
2321
2332
|
if (retry.status !== swap.status) {
|
|
2322
|
-
await this.handleSwapStatusUpdate(
|
|
2323
|
-
swap,
|
|
2324
|
-
retry.status
|
|
2325
|
-
);
|
|
2333
|
+
await this.handleSwapStatusUpdate(swap, retry.status);
|
|
2326
2334
|
}
|
|
2327
2335
|
} catch (retryError) {
|
|
2328
2336
|
if (retryError instanceof SwapNotFoundError) {
|
|
2329
2337
|
await this.handleSwapNotFound(swap);
|
|
2330
2338
|
return;
|
|
2331
2339
|
}
|
|
2332
|
-
logger.error(
|
|
2333
|
-
`Retry poll for swap ${swap.id} also failed:`,
|
|
2334
|
-
retryError
|
|
2335
|
-
);
|
|
2340
|
+
logger.error(`Retry poll for swap ${swap.id} also failed:`, retryError);
|
|
2336
2341
|
}
|
|
2337
2342
|
}, 2e3)
|
|
2338
2343
|
);
|
|
@@ -2384,9 +2389,7 @@ var SwapManager = class _SwapManager {
|
|
|
2384
2389
|
this.pollRetryTimers.delete(swap.id);
|
|
2385
2390
|
}
|
|
2386
2391
|
this.notFoundCounts.delete(swap.id);
|
|
2387
|
-
this.swapUpdateListeners.forEach(
|
|
2388
|
-
(listener) => listener(swap, oldStatus)
|
|
2389
|
-
);
|
|
2392
|
+
this.swapUpdateListeners.forEach((listener) => listener(swap, oldStatus));
|
|
2390
2393
|
const subscribers = this.swapSubscriptions.get(swap.id);
|
|
2391
2394
|
if (subscribers) {
|
|
2392
2395
|
subscribers.forEach((callback) => {
|
|
@@ -2451,9 +2454,7 @@ async function saveSwap(swap, saver) {
|
|
|
2451
2454
|
if (saver.saveSubmarineSwap) {
|
|
2452
2455
|
await saver.saveSubmarineSwap(swap);
|
|
2453
2456
|
} else {
|
|
2454
|
-
console.warn(
|
|
2455
|
-
"No saveSubmarineSwap handler provided, swap not saved"
|
|
2456
|
-
);
|
|
2457
|
+
console.warn("No saveSubmarineSwap handler provided, swap not saved");
|
|
2457
2458
|
}
|
|
2458
2459
|
} else if (isPendingChainSwap(swap)) {
|
|
2459
2460
|
if (saver.saveChainSwap) {
|
|
@@ -2517,6 +2518,26 @@ function enrichSubmarineSwapInvoice(swap, invoice) {
|
|
|
2517
2518
|
return swap;
|
|
2518
2519
|
}
|
|
2519
2520
|
|
|
2521
|
+
// src/repositories/swap-repository.ts
|
|
2522
|
+
function hasImpossibleSwapsFilter(filter) {
|
|
2523
|
+
if (!filter) return false;
|
|
2524
|
+
return Array.isArray(filter.id) && filter.id.length === 0 || Array.isArray(filter.status) && filter.status.length === 0 || Array.isArray(filter.type) && filter.type.length === 0;
|
|
2525
|
+
}
|
|
2526
|
+
function matchesCriterion(value, criterion) {
|
|
2527
|
+
if (criterion === void 0) return true;
|
|
2528
|
+
return Array.isArray(criterion) ? criterion.includes(value) : value === criterion;
|
|
2529
|
+
}
|
|
2530
|
+
function applySwapsFilter(swaps, filter) {
|
|
2531
|
+
return swaps.filter(
|
|
2532
|
+
(swap) => !!swap && matchesCriterion(swap.id, filter.id) && matchesCriterion(swap.status, filter.status) && matchesCriterion(swap.type, filter.type)
|
|
2533
|
+
);
|
|
2534
|
+
}
|
|
2535
|
+
function applyCreatedAtOrder(swaps, filter) {
|
|
2536
|
+
if (filter?.orderBy !== "createdAt") return swaps;
|
|
2537
|
+
const direction = filter.orderDirection === "asc" ? 1 : -1;
|
|
2538
|
+
return swaps.slice().sort((a, b) => (a.createdAt - b.createdAt) * direction);
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2520
2541
|
// src/repositories/IndexedDb/swap-repository.ts
|
|
2521
2542
|
var import_sdk4 = require("@arkade-os/sdk");
|
|
2522
2543
|
var DEFAULT_DB_NAME = "arkade-boltz-swap";
|
|
@@ -2532,6 +2553,10 @@ function initDatabase(db) {
|
|
|
2532
2553
|
swapStore.createIndex("createdAt", "createdAt", { unique: false });
|
|
2533
2554
|
}
|
|
2534
2555
|
}
|
|
2556
|
+
function asArray(v) {
|
|
2557
|
+
if (v === void 0) return void 0;
|
|
2558
|
+
return Array.isArray(v) ? v : [v];
|
|
2559
|
+
}
|
|
2535
2560
|
var IndexedDbSwapRepository = class {
|
|
2536
2561
|
constructor(dbName = DEFAULT_DB_NAME) {
|
|
2537
2562
|
this.dbName = dbName;
|
|
@@ -2546,10 +2571,7 @@ var IndexedDbSwapRepository = class {
|
|
|
2546
2571
|
async saveSwap(swap) {
|
|
2547
2572
|
const db = await this.getDB();
|
|
2548
2573
|
return new Promise((resolve, reject) => {
|
|
2549
|
-
const transaction = db.transaction(
|
|
2550
|
-
[STORE_SWAPS_STATE],
|
|
2551
|
-
"readwrite"
|
|
2552
|
-
);
|
|
2574
|
+
const transaction = db.transaction([STORE_SWAPS_STATE], "readwrite");
|
|
2553
2575
|
const store = transaction.objectStore(STORE_SWAPS_STATE);
|
|
2554
2576
|
const request = store.put(swap);
|
|
2555
2577
|
request.onsuccess = () => resolve();
|
|
@@ -2559,10 +2581,7 @@ var IndexedDbSwapRepository = class {
|
|
|
2559
2581
|
async deleteSwap(id) {
|
|
2560
2582
|
const db = await this.getDB();
|
|
2561
2583
|
return new Promise((resolve, reject) => {
|
|
2562
|
-
const transaction = db.transaction(
|
|
2563
|
-
[STORE_SWAPS_STATE],
|
|
2564
|
-
"readwrite"
|
|
2565
|
-
);
|
|
2584
|
+
const transaction = db.transaction([STORE_SWAPS_STATE], "readwrite");
|
|
2566
2585
|
const store = transaction.objectStore(STORE_SWAPS_STATE);
|
|
2567
2586
|
const request = store.delete(id);
|
|
2568
2587
|
request.onsuccess = () => resolve();
|
|
@@ -2575,10 +2594,7 @@ var IndexedDbSwapRepository = class {
|
|
|
2575
2594
|
async clear() {
|
|
2576
2595
|
const db = await this.getDB();
|
|
2577
2596
|
return new Promise((resolve, reject) => {
|
|
2578
|
-
const transaction = db.transaction(
|
|
2579
|
-
[STORE_SWAPS_STATE],
|
|
2580
|
-
"readwrite"
|
|
2581
|
-
);
|
|
2597
|
+
const transaction = db.transaction([STORE_SWAPS_STATE], "readwrite");
|
|
2582
2598
|
const store = transaction.objectStore(STORE_SWAPS_STATE);
|
|
2583
2599
|
const request = store.clear();
|
|
2584
2600
|
request.onsuccess = () => resolve();
|
|
@@ -2595,11 +2611,10 @@ var IndexedDbSwapRepository = class {
|
|
|
2595
2611
|
request.onsuccess = () => resolve(request.result ?? []);
|
|
2596
2612
|
})
|
|
2597
2613
|
);
|
|
2598
|
-
return Promise.all(requests).then(
|
|
2599
|
-
(results) => results.flatMap((result) => result)
|
|
2600
|
-
);
|
|
2614
|
+
return Promise.all(requests).then((results) => results.flatMap((result) => result));
|
|
2601
2615
|
}
|
|
2602
2616
|
async getAllSwapsFromStore(filter) {
|
|
2617
|
+
if (hasImpossibleSwapsFilter(filter)) return [];
|
|
2603
2618
|
const db = await this.getDB();
|
|
2604
2619
|
const store = db.transaction([STORE_SWAPS_STATE], "readonly").objectStore(STORE_SWAPS_STATE);
|
|
2605
2620
|
if (!filter || Object.keys(filter).length === 0) {
|
|
@@ -2609,9 +2624,8 @@ var IndexedDbSwapRepository = class {
|
|
|
2609
2624
|
request.onerror = () => reject(request.error);
|
|
2610
2625
|
});
|
|
2611
2626
|
}
|
|
2612
|
-
const
|
|
2613
|
-
if (
|
|
2614
|
-
const ids = normalizedFilter.get("id");
|
|
2627
|
+
const ids = asArray(filter.id);
|
|
2628
|
+
if (ids) {
|
|
2615
2629
|
const swaps = await Promise.all(
|
|
2616
2630
|
ids.map(
|
|
2617
2631
|
(id) => new Promise((resolve, reject) => {
|
|
@@ -2621,34 +2635,17 @@ var IndexedDbSwapRepository = class {
|
|
|
2621
2635
|
})
|
|
2622
2636
|
)
|
|
2623
2637
|
);
|
|
2624
|
-
return
|
|
2625
|
-
this.applySwapsFilter(swaps, normalizedFilter),
|
|
2626
|
-
filter
|
|
2627
|
-
);
|
|
2638
|
+
return applyCreatedAtOrder(applySwapsFilter(swaps, filter), filter);
|
|
2628
2639
|
}
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
const swaps = await this.getSwapsByIndexValues(
|
|
2632
|
-
|
|
2633
|
-
"type",
|
|
2634
|
-
types
|
|
2635
|
-
);
|
|
2636
|
-
return this.sortIfNeeded(
|
|
2637
|
-
this.applySwapsFilter(swaps, normalizedFilter),
|
|
2638
|
-
filter
|
|
2639
|
-
);
|
|
2640
|
+
const types = asArray(filter.type);
|
|
2641
|
+
if (types) {
|
|
2642
|
+
const swaps = await this.getSwapsByIndexValues(store, "type", types);
|
|
2643
|
+
return applyCreatedAtOrder(applySwapsFilter(swaps, filter), filter);
|
|
2640
2644
|
}
|
|
2641
|
-
|
|
2642
|
-
|
|
2643
|
-
const swaps = await this.getSwapsByIndexValues(
|
|
2644
|
-
|
|
2645
|
-
"status",
|
|
2646
|
-
ids
|
|
2647
|
-
);
|
|
2648
|
-
return this.sortIfNeeded(
|
|
2649
|
-
this.applySwapsFilter(swaps, normalizedFilter),
|
|
2650
|
-
filter
|
|
2651
|
-
);
|
|
2645
|
+
const statuses = asArray(filter.status);
|
|
2646
|
+
if (statuses) {
|
|
2647
|
+
const swaps = await this.getSwapsByIndexValues(store, "status", statuses);
|
|
2648
|
+
return applyCreatedAtOrder(applySwapsFilter(swaps, filter), filter);
|
|
2652
2649
|
}
|
|
2653
2650
|
if (filter.orderBy === "createdAt") {
|
|
2654
2651
|
return this.getAllSwapsByCreatedAt(store, filter.orderDirection);
|
|
@@ -2658,22 +2655,7 @@ var IndexedDbSwapRepository = class {
|
|
|
2658
2655
|
request.onsuccess = () => resolve(request.result ?? []);
|
|
2659
2656
|
request.onerror = () => reject(request.error);
|
|
2660
2657
|
});
|
|
2661
|
-
return
|
|
2662
|
-
this.applySwapsFilter(allSwaps, normalizedFilter),
|
|
2663
|
-
filter
|
|
2664
|
-
);
|
|
2665
|
-
}
|
|
2666
|
-
applySwapsFilter(swaps, filter) {
|
|
2667
|
-
return swaps.filter((swap) => {
|
|
2668
|
-
if (swap === void 0) return false;
|
|
2669
|
-
if (filter.has("id") && !filter.get("id")?.includes(swap.id))
|
|
2670
|
-
return false;
|
|
2671
|
-
if (filter.has("status") && !filter.get("status")?.includes(swap.status))
|
|
2672
|
-
return false;
|
|
2673
|
-
if (filter.has("type") && !filter.get("type")?.includes(swap.type))
|
|
2674
|
-
return false;
|
|
2675
|
-
return true;
|
|
2676
|
-
});
|
|
2658
|
+
return applyCreatedAtOrder(applySwapsFilter(allSwaps, filter), filter);
|
|
2677
2659
|
}
|
|
2678
2660
|
async getAllSwapsByCreatedAt(store, orderDirection) {
|
|
2679
2661
|
const index = store.index("createdAt");
|
|
@@ -2693,30 +2675,12 @@ var IndexedDbSwapRepository = class {
|
|
|
2693
2675
|
};
|
|
2694
2676
|
});
|
|
2695
2677
|
}
|
|
2696
|
-
sortIfNeeded(swaps, filter) {
|
|
2697
|
-
if (filter?.orderBy !== "createdAt") return swaps;
|
|
2698
|
-
const direction = filter.orderDirection === "asc" ? 1 : -1;
|
|
2699
|
-
return swaps.slice().sort((a, b) => (a.createdAt - b.createdAt) * direction);
|
|
2700
|
-
}
|
|
2701
2678
|
async [Symbol.asyncDispose]() {
|
|
2702
2679
|
if (!this.db) return;
|
|
2703
2680
|
await (0, import_sdk4.closeDatabase)(this.dbName);
|
|
2704
2681
|
this.db = null;
|
|
2705
2682
|
}
|
|
2706
2683
|
};
|
|
2707
|
-
var FILTER_FIELDS = ["id", "status", "type"];
|
|
2708
|
-
function normalizeFilter(filter) {
|
|
2709
|
-
const res = /* @__PURE__ */ new Map();
|
|
2710
|
-
FILTER_FIELDS.forEach((current) => {
|
|
2711
|
-
if (!filter?.[current]) return;
|
|
2712
|
-
if (Array.isArray(filter[current])) {
|
|
2713
|
-
res.set(current, filter[current]);
|
|
2714
|
-
} else {
|
|
2715
|
-
res.set(current, [filter[current]]);
|
|
2716
|
-
}
|
|
2717
|
-
});
|
|
2718
|
-
return res;
|
|
2719
|
-
}
|
|
2720
2684
|
|
|
2721
2685
|
// src/utils/identity.ts
|
|
2722
2686
|
var import_sdk5 = require("@arkade-os/sdk");
|
|
@@ -2728,13 +2692,8 @@ function claimVHTLCIdentity(identity, preimage) {
|
|
|
2728
2692
|
let signedTx = await identity.sign(cpy, inputIndexes);
|
|
2729
2693
|
signedTx = import_sdk5.Transaction.fromPSBT(signedTx.toPSBT());
|
|
2730
2694
|
if (preimage) {
|
|
2731
|
-
for (const inputIndex of inputIndexes || Array.from(
|
|
2732
|
-
|
|
2733
|
-
(_, i) => i
|
|
2734
|
-
)) {
|
|
2735
|
-
(0, import_sdk5.setArkPsbtField)(signedTx, inputIndex, import_sdk5.ConditionWitness, [
|
|
2736
|
-
preimage
|
|
2737
|
-
]);
|
|
2695
|
+
for (const inputIndex of inputIndexes || Array.from({ length: signedTx.inputsLength }, (_, i) => i)) {
|
|
2696
|
+
(0, import_sdk5.setArkPsbtField)(signedTx, inputIndex, import_sdk5.ConditionWitness, [preimage]);
|
|
2738
2697
|
}
|
|
2739
2698
|
}
|
|
2740
2699
|
return signedTx;
|
|
@@ -2789,17 +2748,13 @@ function createVHTLCBatchHandler(intentId, vhtlc, arkProvider, identity, session
|
|
|
2789
2748
|
if (!sweepTapTreeRoot) {
|
|
2790
2749
|
throw new Error("Sweep tap tree root not set");
|
|
2791
2750
|
}
|
|
2792
|
-
const xOnlyPublicKeys = event.cosignersPublicKeys.map(
|
|
2793
|
-
(k) => k.slice(2)
|
|
2794
|
-
);
|
|
2751
|
+
const xOnlyPublicKeys = event.cosignersPublicKeys.map((k) => k.slice(2));
|
|
2795
2752
|
const signerPublicKey = await session.getPublicKey();
|
|
2796
2753
|
const xonlySignerPublicKey = signerPublicKey.subarray(1);
|
|
2797
2754
|
if (!xOnlyPublicKeys.includes(import_base7.hex.encode(xonlySignerPublicKey))) {
|
|
2798
2755
|
return { skip: true };
|
|
2799
2756
|
}
|
|
2800
|
-
const commitmentTx = import_sdk6.Transaction.fromPSBT(
|
|
2801
|
-
import_base7.base64.decode(event.unsignedCommitmentTx)
|
|
2802
|
-
);
|
|
2757
|
+
const commitmentTx = import_sdk6.Transaction.fromPSBT(import_base7.base64.decode(event.unsignedCommitmentTx));
|
|
2803
2758
|
(0, import_sdk6.validateVtxoTxGraph)(vtxoTree, commitmentTx, sweepTapTreeRoot);
|
|
2804
2759
|
const sharedOutput = commitmentTx.getOutput(0);
|
|
2805
2760
|
if (!sharedOutput?.amount) {
|
|
@@ -2815,18 +2770,11 @@ function createVHTLCBatchHandler(intentId, vhtlc, arkProvider, identity, session
|
|
|
2815
2770
|
if (!session) {
|
|
2816
2771
|
return { fullySigned: true };
|
|
2817
2772
|
}
|
|
2818
|
-
const { hasAllNonces } = await session.aggregatedNonces(
|
|
2819
|
-
event.txid,
|
|
2820
|
-
event.nonces
|
|
2821
|
-
);
|
|
2773
|
+
const { hasAllNonces } = await session.aggregatedNonces(event.txid, event.nonces);
|
|
2822
2774
|
if (!hasAllNonces) return { fullySigned: false };
|
|
2823
2775
|
const signatures = await session.sign();
|
|
2824
2776
|
const pubkey = import_base7.hex.encode(await session.getPublicKey());
|
|
2825
|
-
await arkProvider.submitTreeSignatures(
|
|
2826
|
-
event.id,
|
|
2827
|
-
pubkey,
|
|
2828
|
-
signatures
|
|
2829
|
-
);
|
|
2777
|
+
await arkProvider.submitTreeSignatures(event.id, pubkey, signatures);
|
|
2830
2778
|
return { fullySigned: true };
|
|
2831
2779
|
},
|
|
2832
2780
|
onBatchFinalization: async (event, _, connectorTree) => {
|
|
@@ -2834,9 +2782,7 @@ function createVHTLCBatchHandler(intentId, vhtlc, arkProvider, identity, session
|
|
|
2834
2782
|
return;
|
|
2835
2783
|
}
|
|
2836
2784
|
if (!connectorTree) {
|
|
2837
|
-
throw new Error(
|
|
2838
|
-
"BatchFinalizationEvent: expected connector tree to be defined"
|
|
2839
|
-
);
|
|
2785
|
+
throw new Error("BatchFinalizationEvent: expected connector tree to be defined");
|
|
2840
2786
|
}
|
|
2841
2787
|
(0, import_sdk6.validateConnectorsTxGraph)(event.commitmentTx, connectorTree);
|
|
2842
2788
|
const connectors = connectorTree.leaves();
|
|
@@ -2851,9 +2797,7 @@ function createVHTLCBatchHandler(intentId, vhtlc, arkProvider, identity, session
|
|
|
2851
2797
|
connectors[connectorIndex]
|
|
2852
2798
|
);
|
|
2853
2799
|
const signedForfeitTx = await identity.sign(forfeitTx);
|
|
2854
|
-
await arkProvider.submitSignedForfeitTxs([
|
|
2855
|
-
import_base7.base64.encode(signedForfeitTx.toPSBT())
|
|
2856
|
-
]);
|
|
2800
|
+
await arkProvider.submitSignedForfeitTxs([import_base7.base64.encode(signedForfeitTx.toPSBT())]);
|
|
2857
2801
|
}
|
|
2858
2802
|
};
|
|
2859
2803
|
}
|
|
@@ -2913,36 +2857,22 @@ var createVHTLCScript = (args) => {
|
|
|
2913
2857
|
serverPubkey,
|
|
2914
2858
|
timeoutBlockHeights: vhtlcTimeouts
|
|
2915
2859
|
} = args;
|
|
2916
|
-
const receiverXOnlyPublicKey = normalizeToXOnlyKey(
|
|
2917
|
-
|
|
2918
|
-
|
|
2919
|
-
);
|
|
2920
|
-
const senderXOnlyPublicKey = normalizeToXOnlyKey(
|
|
2921
|
-
import_base8.hex.decode(senderPubkey),
|
|
2922
|
-
"sender"
|
|
2923
|
-
);
|
|
2924
|
-
const serverXOnlyPublicKey = normalizeToXOnlyKey(
|
|
2925
|
-
import_base8.hex.decode(serverPubkey),
|
|
2926
|
-
"server"
|
|
2927
|
-
);
|
|
2860
|
+
const receiverXOnlyPublicKey = normalizeToXOnlyKey(import_base8.hex.decode(receiverPubkey), "receiver");
|
|
2861
|
+
const senderXOnlyPublicKey = normalizeToXOnlyKey(import_base8.hex.decode(senderPubkey), "sender");
|
|
2862
|
+
const serverXOnlyPublicKey = normalizeToXOnlyKey(import_base8.hex.decode(serverPubkey), "server");
|
|
2928
2863
|
const vhtlcScript = new import_sdk7.VHTLC.Script({
|
|
2929
2864
|
preimageHash: (0, import_legacy.ripemd160)(preimageHash),
|
|
2930
2865
|
sender: senderXOnlyPublicKey,
|
|
2931
2866
|
receiver: receiverXOnlyPublicKey,
|
|
2932
2867
|
server: serverXOnlyPublicKey,
|
|
2933
2868
|
refundLocktime: BigInt(vhtlcTimeouts.refund),
|
|
2934
|
-
unilateralClaimDelay: toBip68RelativeTimelock(
|
|
2935
|
-
|
|
2936
|
-
),
|
|
2937
|
-
unilateralRefundDelay: toBip68RelativeTimelock(
|
|
2938
|
-
vhtlcTimeouts.unilateralRefund
|
|
2939
|
-
),
|
|
2869
|
+
unilateralClaimDelay: toBip68RelativeTimelock(vhtlcTimeouts.unilateralClaim),
|
|
2870
|
+
unilateralRefundDelay: toBip68RelativeTimelock(vhtlcTimeouts.unilateralRefund),
|
|
2940
2871
|
unilateralRefundWithoutReceiverDelay: toBip68RelativeTimelock(
|
|
2941
2872
|
vhtlcTimeouts.unilateralRefundWithoutReceiver
|
|
2942
2873
|
)
|
|
2943
2874
|
});
|
|
2944
|
-
if (!vhtlcScript.claimScript)
|
|
2945
|
-
throw new Error("Failed to create VHTLC script");
|
|
2875
|
+
if (!vhtlcScript.claimScript) throw new Error("Failed to create VHTLC script");
|
|
2946
2876
|
const hrp = network === "bitcoin" ? "ark" : "tark";
|
|
2947
2877
|
const vhtlcAddress = vhtlcScript.address(hrp, serverXOnlyPublicKey).encode();
|
|
2948
2878
|
return { vhtlcScript, vhtlcAddress };
|
|
@@ -2976,11 +2906,7 @@ var joinBatch = async (arkProvider, identity, input, output, {
|
|
|
2976
2906
|
unknown: [import_sdk7.VtxoTaprootTree.encode(input.tapTree)],
|
|
2977
2907
|
sequence: (0, import_sdk7.getSequence)(input.tapLeafScript)
|
|
2978
2908
|
};
|
|
2979
|
-
const registerIntent = import_sdk7.Intent.create(
|
|
2980
|
-
intentMessage,
|
|
2981
|
-
[intentInput],
|
|
2982
|
-
[output]
|
|
2983
|
-
);
|
|
2909
|
+
const registerIntent = import_sdk7.Intent.create(intentMessage, [intentInput], [output]);
|
|
2984
2910
|
const deleteIntent = import_sdk7.Intent.create(deleteMessage, [intentInput]);
|
|
2985
2911
|
const [signedRegisterIntent, signedDeleteIntent] = await Promise.all([
|
|
2986
2912
|
identity.sign(registerIntent),
|
|
@@ -3004,14 +2930,8 @@ var joinBatch = async (arkProvider, identity, input, output, {
|
|
|
3004
2930
|
normalizeToXOnlyKey(forfeitPubkey, "forfeit"),
|
|
3005
2931
|
isRecoverable2 ? void 0 : import_btc_signer4.OutScript.encode(decodedAddress)
|
|
3006
2932
|
);
|
|
3007
|
-
const topics = [
|
|
3008
|
-
|
|
3009
|
-
`${input.txid}:${input.vout}`
|
|
3010
|
-
];
|
|
3011
|
-
const eventStream = arkProvider.getEventStream(
|
|
3012
|
-
abortController.signal,
|
|
3013
|
-
topics
|
|
3014
|
-
);
|
|
2933
|
+
const topics = [import_base8.hex.encode(signerPublicKey), `${input.txid}:${input.vout}`];
|
|
2934
|
+
const eventStream = arkProvider.getEventStream(abortController.signal, topics);
|
|
3015
2935
|
const commitmentTxid = await import_sdk7.Batch.join(eventStream, handler, {
|
|
3016
2936
|
abortController
|
|
3017
2937
|
});
|
|
@@ -3032,14 +2952,8 @@ var joinBatch = async (arkProvider, identity, input, output, {
|
|
|
3032
2952
|
};
|
|
3033
2953
|
var claimVHTLCwithOffchainTx = async (identity, vhtlcScript, serverXOnlyPublicKey, input, output, arkInfo, arkProvider) => {
|
|
3034
2954
|
const rawCheckpointTapscript = import_base8.hex.decode(arkInfo.checkpointTapscript);
|
|
3035
|
-
const serverUnrollScript = import_sdk7.CSVMultisigTapscript.decode(
|
|
3036
|
-
|
|
3037
|
-
);
|
|
3038
|
-
const { arkTx, checkpoints } = (0, import_sdk7.buildOffchainTx)(
|
|
3039
|
-
[input],
|
|
3040
|
-
[output],
|
|
3041
|
-
serverUnrollScript
|
|
3042
|
-
);
|
|
2955
|
+
const serverUnrollScript = import_sdk7.CSVMultisigTapscript.decode(rawCheckpointTapscript);
|
|
2956
|
+
const { arkTx, checkpoints } = (0, import_sdk7.buildOffchainTx)([input], [output], serverUnrollScript);
|
|
3043
2957
|
const signedArkTx = await identity.sign(arkTx);
|
|
3044
2958
|
const { arkTxid, finalArkTx, signedCheckpointTxs } = await arkProvider.submitTx(
|
|
3045
2959
|
import_base8.base64.encode(signedArkTx.toPSBT()),
|
|
@@ -3047,9 +2961,7 @@ var claimVHTLCwithOffchainTx = async (identity, vhtlcScript, serverXOnlyPublicKe
|
|
|
3047
2961
|
);
|
|
3048
2962
|
const finalTx = import_sdk7.Transaction.fromPSBT(import_base8.base64.decode(finalArkTx));
|
|
3049
2963
|
const serverPubkeyHex = import_base8.hex.encode(serverXOnlyPublicKey);
|
|
3050
|
-
const claimLeafHash = (0, import_payment3.tapLeafHash)(
|
|
3051
|
-
scriptFromTapLeafScript(vhtlcScript.claim())
|
|
3052
|
-
);
|
|
2964
|
+
const claimLeafHash = (0, import_payment3.tapLeafHash)(scriptFromTapLeafScript(vhtlcScript.claim()));
|
|
3053
2965
|
for (let i = 0; i < finalTx.inputsLength; i++) {
|
|
3054
2966
|
if (!verifySignatures(finalTx, i, [serverPubkeyHex], claimLeafHash)) {
|
|
3055
2967
|
throw new Error("Invalid final Ark transaction");
|
|
@@ -3059,13 +2971,9 @@ var claimVHTLCwithOffchainTx = async (identity, vhtlcScript, serverXOnlyPublicKe
|
|
|
3059
2971
|
signedCheckpointTxs.map(async (c, idx) => {
|
|
3060
2972
|
const tx = import_sdk7.Transaction.fromPSBT(import_base8.base64.decode(c));
|
|
3061
2973
|
const checkpointLeaf = checkpoints[idx].getInput(0).tapLeafScript[0];
|
|
3062
|
-
const cpLeafHash = (0, import_payment3.tapLeafHash)(
|
|
3063
|
-
scriptFromTapLeafScript(checkpointLeaf)
|
|
3064
|
-
);
|
|
2974
|
+
const cpLeafHash = (0, import_payment3.tapLeafHash)(scriptFromTapLeafScript(checkpointLeaf));
|
|
3065
2975
|
if (!verifySignatures(tx, 0, [serverPubkeyHex], cpLeafHash)) {
|
|
3066
|
-
throw new Error(
|
|
3067
|
-
"Invalid server signature in checkpoint transaction"
|
|
3068
|
-
);
|
|
2976
|
+
throw new Error("Invalid server signature in checkpoint transaction");
|
|
3069
2977
|
}
|
|
3070
2978
|
const signedCheckpoint = await identity.sign(tx, [0]);
|
|
3071
2979
|
return import_base8.base64.encode(signedCheckpoint.toPSBT());
|
|
@@ -3075,61 +2983,37 @@ var claimVHTLCwithOffchainTx = async (identity, vhtlcScript, serverXOnlyPublicKe
|
|
|
3075
2983
|
};
|
|
3076
2984
|
var refundVHTLCwithOffchainTx = async (swapId, identity, arkProvider, boltzXOnlyPublicKey, ourXOnlyPublicKey, serverXOnlyPublicKey, input, output, arkInfo, refundFunc) => {
|
|
3077
2985
|
const rawCheckpointTapscript = import_base8.hex.decode(arkInfo.checkpointTapscript);
|
|
3078
|
-
const serverUnrollScript = import_sdk7.CSVMultisigTapscript.decode(
|
|
3079
|
-
|
|
2986
|
+
const serverUnrollScript = import_sdk7.CSVMultisigTapscript.decode(rawCheckpointTapscript);
|
|
2987
|
+
const { arkTx: unsignedRefundTx, checkpoints: checkpointPtxs } = (0, import_sdk7.buildOffchainTx)(
|
|
2988
|
+
[input],
|
|
2989
|
+
[output],
|
|
2990
|
+
serverUnrollScript
|
|
3080
2991
|
);
|
|
3081
|
-
const { arkTx: unsignedRefundTx, checkpoints: checkpointPtxs } = (0, import_sdk7.buildOffchainTx)([input], [output], serverUnrollScript);
|
|
3082
2992
|
if (checkpointPtxs.length !== 1)
|
|
3083
|
-
throw new Error(
|
|
3084
|
-
`Expected one checkpoint transaction, got ${checkpointPtxs.length}`
|
|
3085
|
-
);
|
|
2993
|
+
throw new Error(`Expected one checkpoint transaction, got ${checkpointPtxs.length}`);
|
|
3086
2994
|
const unsignedCheckpointTx = checkpointPtxs[0];
|
|
3087
2995
|
let boltzSignedRefundTx;
|
|
3088
2996
|
let boltzSignedCheckpointTx;
|
|
3089
2997
|
try {
|
|
3090
|
-
const result = await refundFunc(
|
|
3091
|
-
swapId,
|
|
3092
|
-
unsignedRefundTx,
|
|
3093
|
-
unsignedCheckpointTx
|
|
3094
|
-
);
|
|
2998
|
+
const result = await refundFunc(swapId, unsignedRefundTx, unsignedCheckpointTx);
|
|
3095
2999
|
boltzSignedRefundTx = result.transaction;
|
|
3096
3000
|
boltzSignedCheckpointTx = result.checkpoint;
|
|
3097
3001
|
} catch (error) {
|
|
3098
|
-
throw new BoltzRefundError(
|
|
3099
|
-
`Boltz rejected refund for swap ${swapId}`,
|
|
3100
|
-
error
|
|
3101
|
-
);
|
|
3002
|
+
throw new BoltzRefundError(`Boltz rejected refund for swap ${swapId}`, error);
|
|
3102
3003
|
}
|
|
3103
3004
|
const boltzXOnlyPublicKeyHex = import_base8.hex.encode(boltzXOnlyPublicKey);
|
|
3104
|
-
const refundLeafHash = (0, import_payment3.tapLeafHash)(
|
|
3105
|
-
|
|
3106
|
-
);
|
|
3107
|
-
if (!verifySignatures(
|
|
3108
|
-
boltzSignedRefundTx,
|
|
3109
|
-
0,
|
|
3110
|
-
[boltzXOnlyPublicKeyHex],
|
|
3111
|
-
refundLeafHash
|
|
3112
|
-
)) {
|
|
3005
|
+
const refundLeafHash = (0, import_payment3.tapLeafHash)(scriptFromTapLeafScript(input.tapLeafScript));
|
|
3006
|
+
if (!verifySignatures(boltzSignedRefundTx, 0, [boltzXOnlyPublicKeyHex], refundLeafHash)) {
|
|
3113
3007
|
throw new Error("Invalid Boltz signature in refund transaction");
|
|
3114
3008
|
}
|
|
3115
3009
|
const checkpointLeaf = unsignedCheckpointTx.getInput(0).tapLeafScript[0];
|
|
3116
|
-
const checkpointLeafHash = (0, import_payment3.tapLeafHash)(
|
|
3117
|
-
|
|
3118
|
-
);
|
|
3119
|
-
if (!verifySignatures(
|
|
3120
|
-
boltzSignedCheckpointTx,
|
|
3121
|
-
0,
|
|
3122
|
-
[boltzXOnlyPublicKeyHex],
|
|
3123
|
-
checkpointLeafHash
|
|
3124
|
-
)) {
|
|
3010
|
+
const checkpointLeafHash = (0, import_payment3.tapLeafHash)(scriptFromTapLeafScript(checkpointLeaf));
|
|
3011
|
+
if (!verifySignatures(boltzSignedCheckpointTx, 0, [boltzXOnlyPublicKeyHex], checkpointLeafHash)) {
|
|
3125
3012
|
throw new Error("Invalid Boltz signature in checkpoint transaction");
|
|
3126
3013
|
}
|
|
3127
3014
|
const signedRefundTx = await identity.sign(unsignedRefundTx);
|
|
3128
3015
|
const signedCheckpointTx = await identity.sign(unsignedCheckpointTx);
|
|
3129
|
-
const combinedSignedRefundTx = (0, import_sdk7.combineTapscriptSigs)(
|
|
3130
|
-
boltzSignedRefundTx,
|
|
3131
|
-
signedRefundTx
|
|
3132
|
-
);
|
|
3016
|
+
const combinedSignedRefundTx = (0, import_sdk7.combineTapscriptSigs)(boltzSignedRefundTx, signedRefundTx);
|
|
3133
3017
|
const combinedSignedCheckpointTx = (0, import_sdk7.combineTapscriptSigs)(
|
|
3134
3018
|
boltzSignedCheckpointTx,
|
|
3135
3019
|
signedCheckpointTx
|
|
@@ -3153,25 +3037,16 @@ var refundVHTLCwithOffchainTx = async (swapId, identity, arkProvider, boltzXOnly
|
|
|
3153
3037
|
`Expected one signed checkpoint transaction, got ${signedCheckpointTxs.length}`
|
|
3154
3038
|
);
|
|
3155
3039
|
}
|
|
3156
|
-
const serverSignedCheckpointTx = import_sdk7.Transaction.fromPSBT(
|
|
3157
|
-
import_base8.base64.decode(signedCheckpointTxs[0])
|
|
3158
|
-
);
|
|
3040
|
+
const serverSignedCheckpointTx = import_sdk7.Transaction.fromPSBT(import_base8.base64.decode(signedCheckpointTxs[0]));
|
|
3159
3041
|
const serverPubkeyHex = import_base8.hex.encode(serverXOnlyPublicKey);
|
|
3160
|
-
if (!verifySignatures(
|
|
3161
|
-
serverSignedCheckpointTx,
|
|
3162
|
-
0,
|
|
3163
|
-
[serverPubkeyHex],
|
|
3164
|
-
checkpointLeafHash
|
|
3165
|
-
)) {
|
|
3042
|
+
if (!verifySignatures(serverSignedCheckpointTx, 0, [serverPubkeyHex], checkpointLeafHash)) {
|
|
3166
3043
|
throw new Error("Invalid server signature in checkpoint transaction");
|
|
3167
3044
|
}
|
|
3168
3045
|
const finalCheckpointTx = (0, import_sdk7.combineTapscriptSigs)(
|
|
3169
3046
|
combinedSignedCheckpointTx,
|
|
3170
3047
|
serverSignedCheckpointTx
|
|
3171
3048
|
);
|
|
3172
|
-
await arkProvider.finalizeTx(arkTxid, [
|
|
3173
|
-
import_base8.base64.encode(finalCheckpointTx.toPSBT())
|
|
3174
|
-
]);
|
|
3049
|
+
await arkProvider.finalizeTx(arkTxid, [import_base8.base64.encode(finalCheckpointTx.toPSBT())]);
|
|
3175
3050
|
};
|
|
3176
3051
|
function scriptFromTapLeafScript(leaf) {
|
|
3177
3052
|
return leaf[1].subarray(0, leaf[1].length - 1);
|
|
@@ -3179,21 +3054,21 @@ function scriptFromTapLeafScript(leaf) {
|
|
|
3179
3054
|
|
|
3180
3055
|
// src/arkade-swaps.ts
|
|
3181
3056
|
var dedupeVtxos = (vtxos) => [
|
|
3182
|
-
...new Map(
|
|
3183
|
-
vtxos.map((vtxo) => [`${vtxo.txid}:${vtxo.vout}`, vtxo])
|
|
3184
|
-
).values()
|
|
3057
|
+
...new Map(vtxos.map((vtxo) => [`${vtxo.txid}:${vtxo.vout}`, vtxo])).values()
|
|
3185
3058
|
];
|
|
3186
3059
|
var hasNonEmptyString = (value) => typeof value === "string" && value.length > 0;
|
|
3187
3060
|
var canRecoverViaBoltz3of3 = (refundableVtxos, swap) => {
|
|
3188
3061
|
const hasRequiredSwapMetadata = hasNonEmptyString(swap.id) && hasNonEmptyString(swap.request.refundPublicKey) && hasNonEmptyString(swap.response.address) && hasNonEmptyString(swap.response.claimPublicKey) && !!swap.response.timeoutBlockHeights;
|
|
3189
3062
|
if (!hasRequiredSwapMetadata) return false;
|
|
3190
|
-
return refundableVtxos.some(
|
|
3191
|
-
(vtxo) => !vtxo.isSpent && !(0, import_sdk8.isRecoverable)(vtxo)
|
|
3192
|
-
);
|
|
3063
|
+
return refundableVtxos.some((vtxo) => !vtxo.isSpent && !(0, import_sdk8.isRecoverable)(vtxo));
|
|
3193
3064
|
};
|
|
3194
3065
|
var isSubmarineRefundLocktimeReached = (refundTimestamp) => Math.floor(Date.now() / 1e3) >= refundTimestamp;
|
|
3195
3066
|
var CLAIM_VTXO_RETRY_ATTEMPTS = 3;
|
|
3196
3067
|
var CLAIM_VTXO_RETRY_DELAY_MS = 500;
|
|
3068
|
+
var quoteOptionsForSwap = (swap) => {
|
|
3069
|
+
const amount = swap.response?.claimDetails?.amount;
|
|
3070
|
+
return typeof amount === "number" ? { minAcceptableAmount: amount } : void 0;
|
|
3071
|
+
};
|
|
3197
3072
|
var ArkadeSwaps = class _ArkadeSwaps {
|
|
3198
3073
|
/** The Arkade wallet instance used for signing and address generation. */
|
|
3199
3074
|
wallet;
|
|
@@ -3229,10 +3104,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3229
3104
|
return new _ArkadeSwaps(config);
|
|
3230
3105
|
}
|
|
3231
3106
|
const arkProvider = config.arkProvider ?? config.wallet.arkProvider;
|
|
3232
|
-
if (!arkProvider)
|
|
3233
|
-
throw new Error(
|
|
3234
|
-
"Ark provider is required either in wallet or config."
|
|
3235
|
-
);
|
|
3107
|
+
if (!arkProvider) throw new Error("Ark provider is required either in wallet or config.");
|
|
3236
3108
|
const arkInfo = await arkProvider.getInfo();
|
|
3237
3109
|
const network = arkInfo.network;
|
|
3238
3110
|
const swapProvider = new BoltzSwapProvider({ network });
|
|
@@ -3243,16 +3115,11 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3243
3115
|
if (!config.swapProvider) throw new Error("Swap provider is required.");
|
|
3244
3116
|
this.wallet = config.wallet;
|
|
3245
3117
|
const arkProvider = config.arkProvider ?? config.wallet.arkProvider;
|
|
3246
|
-
if (!arkProvider)
|
|
3247
|
-
throw new Error(
|
|
3248
|
-
"Ark provider is required either in wallet or config."
|
|
3249
|
-
);
|
|
3118
|
+
if (!arkProvider) throw new Error("Ark provider is required either in wallet or config.");
|
|
3250
3119
|
this.arkProvider = arkProvider;
|
|
3251
3120
|
const indexerProvider = config.indexerProvider ?? config.wallet.indexerProvider;
|
|
3252
3121
|
if (!indexerProvider)
|
|
3253
|
-
throw new Error(
|
|
3254
|
-
"Indexer provider is required either in wallet or config."
|
|
3255
|
-
);
|
|
3122
|
+
throw new Error("Indexer provider is required either in wallet or config.");
|
|
3256
3123
|
this.indexerProvider = indexerProvider;
|
|
3257
3124
|
this.swapProvider = config.swapProvider;
|
|
3258
3125
|
if (config.swapRepository) {
|
|
@@ -3263,10 +3130,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3263
3130
|
if (config.swapManager !== false) {
|
|
3264
3131
|
const swapManagerConfig = !config.swapManager || config.swapManager === true ? {} : config.swapManager;
|
|
3265
3132
|
const shouldAutostart = swapManagerConfig.autoStart ?? true;
|
|
3266
|
-
this.swapManager = new SwapManager(
|
|
3267
|
-
this.swapProvider,
|
|
3268
|
-
swapManagerConfig
|
|
3269
|
-
);
|
|
3133
|
+
this.swapManager = new SwapManager(this.swapProvider, swapManagerConfig);
|
|
3270
3134
|
this.swapManager.setCallbacks({
|
|
3271
3135
|
claim: async (swap) => {
|
|
3272
3136
|
await this.claimVHTLC(swap);
|
|
@@ -3414,19 +3278,15 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3414
3278
|
* @throws {SwapError} If amount is <= 0 or key retrieval fails.
|
|
3415
3279
|
*/
|
|
3416
3280
|
async createReverseSwap(args) {
|
|
3417
|
-
if (args.amount <= 0)
|
|
3418
|
-
|
|
3419
|
-
const claimPublicKey = import_base9.hex.encode(
|
|
3420
|
-
await this.wallet.identity.compressedPublicKey()
|
|
3421
|
-
);
|
|
3281
|
+
if (args.amount <= 0) throw new SwapError({ message: "Amount must be greater than 0" });
|
|
3282
|
+
const claimPublicKey = import_base9.hex.encode(await this.wallet.identity.compressedPublicKey());
|
|
3422
3283
|
if (!claimPublicKey)
|
|
3423
3284
|
throw new SwapError({
|
|
3424
3285
|
message: "Failed to get claim public key from wallet"
|
|
3425
3286
|
});
|
|
3426
3287
|
const preimage = (0, import_utils3.randomBytes)(32);
|
|
3427
3288
|
const preimageHash = import_base9.hex.encode((0, import_sha23.sha256)(preimage));
|
|
3428
|
-
if (!preimageHash)
|
|
3429
|
-
throw new SwapError({ message: "Failed to get preimage hash" });
|
|
3289
|
+
if (!preimageHash) throw new SwapError({ message: "Failed to get preimage hash" });
|
|
3430
3290
|
const swapRequest = {
|
|
3431
3291
|
invoiceAmount: args.amount,
|
|
3432
3292
|
claimPublicKey,
|
|
@@ -3456,18 +3316,14 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3456
3316
|
*/
|
|
3457
3317
|
async claimVHTLC(pendingSwap) {
|
|
3458
3318
|
if (!pendingSwap.preimage)
|
|
3459
|
-
throw new Error(
|
|
3460
|
-
`Swap ${pendingSwap.id}: preimage is required to claim VHTLC`
|
|
3461
|
-
);
|
|
3319
|
+
throw new Error(`Swap ${pendingSwap.id}: preimage is required to claim VHTLC`);
|
|
3462
3320
|
const {
|
|
3463
3321
|
refundPublicKey,
|
|
3464
3322
|
lockupAddress,
|
|
3465
3323
|
timeoutBlockHeights: vhtlcTimeouts
|
|
3466
3324
|
} = pendingSwap.response;
|
|
3467
3325
|
if (!refundPublicKey || !lockupAddress || !vhtlcTimeouts)
|
|
3468
|
-
throw new Error(
|
|
3469
|
-
`Swap ${pendingSwap.id}: incomplete reverse swap response`
|
|
3470
|
-
);
|
|
3326
|
+
throw new Error(`Swap ${pendingSwap.id}: incomplete reverse swap response`);
|
|
3471
3327
|
const preimage = import_base9.hex.decode(pendingSwap.preimage);
|
|
3472
3328
|
const arkInfo = await this.arkProvider.getInfo();
|
|
3473
3329
|
const address = await this.wallet.getAddress();
|
|
@@ -3512,15 +3368,11 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3512
3368
|
break;
|
|
3513
3369
|
}
|
|
3514
3370
|
if (attempt < CLAIM_VTXO_RETRY_ATTEMPTS) {
|
|
3515
|
-
await new Promise(
|
|
3516
|
-
(resolve) => setTimeout(resolve, CLAIM_VTXO_RETRY_DELAY_MS)
|
|
3517
|
-
);
|
|
3371
|
+
await new Promise((resolve) => setTimeout(resolve, CLAIM_VTXO_RETRY_DELAY_MS));
|
|
3518
3372
|
}
|
|
3519
3373
|
}
|
|
3520
3374
|
if (!vtxo) {
|
|
3521
|
-
throw new Error(
|
|
3522
|
-
`Swap ${pendingSwap.id}: no spendable virtual coins found`
|
|
3523
|
-
);
|
|
3375
|
+
throw new Error(`Swap ${pendingSwap.id}: no spendable virtual coins found`);
|
|
3524
3376
|
}
|
|
3525
3377
|
if (vtxo.isSpent) {
|
|
3526
3378
|
throw new Error(`Swap ${pendingSwap.id}: VHTLC is already spent`);
|
|
@@ -3534,10 +3386,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3534
3386
|
amount: BigInt(vtxo.value),
|
|
3535
3387
|
script: import_sdk8.ArkAddress.decode(address).pkScript
|
|
3536
3388
|
};
|
|
3537
|
-
const vhtlcIdentity = claimVHTLCIdentity(
|
|
3538
|
-
this.wallet.identity,
|
|
3539
|
-
preimage
|
|
3540
|
-
);
|
|
3389
|
+
const vhtlcIdentity = claimVHTLCIdentity(this.wallet.identity, preimage);
|
|
3541
3390
|
let finalStatus;
|
|
3542
3391
|
if ((0, import_sdk8.isRecoverable)(vtxo)) {
|
|
3543
3392
|
await this.joinBatch(vhtlcIdentity, input, output, arkInfo);
|
|
@@ -3656,9 +3505,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3656
3505
|
async sendLightningPayment(args) {
|
|
3657
3506
|
const pendingSwap = await this.createSubmarineSwap(args);
|
|
3658
3507
|
if (!pendingSwap.response.address)
|
|
3659
|
-
throw new Error(
|
|
3660
|
-
`Swap ${pendingSwap.id}: missing address in submarine swap response`
|
|
3661
|
-
);
|
|
3508
|
+
throw new Error(`Swap ${pendingSwap.id}: missing address in submarine swap response`);
|
|
3662
3509
|
await this.savePendingSubmarineSwap(pendingSwap);
|
|
3663
3510
|
const txid = await this.wallet.send({
|
|
3664
3511
|
address: pendingSwap.response.address,
|
|
@@ -3691,9 +3538,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3691
3538
|
* @throws {SwapError} If invoice is missing or key retrieval fails.
|
|
3692
3539
|
*/
|
|
3693
3540
|
async createSubmarineSwap(args) {
|
|
3694
|
-
const refundPublicKey = import_base9.hex.encode(
|
|
3695
|
-
await this.wallet.identity.compressedPublicKey()
|
|
3696
|
-
);
|
|
3541
|
+
const refundPublicKey = import_base9.hex.encode(await this.wallet.identity.compressedPublicKey());
|
|
3697
3542
|
if (!refundPublicKey)
|
|
3698
3543
|
throw new SwapError({
|
|
3699
3544
|
message: "Failed to get refund public key from wallet"
|
|
@@ -3731,9 +3576,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3731
3576
|
async buildSubmarineVHTLCContext(swap, arkInfo) {
|
|
3732
3577
|
const preimageHash = swap.request.invoice ? getInvoicePaymentHash(swap.request.invoice) : swap.preimageHash;
|
|
3733
3578
|
if (!preimageHash)
|
|
3734
|
-
throw new Error(
|
|
3735
|
-
`Swap ${swap.id}: preimage hash is required to refund VHTLC`
|
|
3736
|
-
);
|
|
3579
|
+
throw new Error(`Swap ${swap.id}: preimage hash is required to refund VHTLC`);
|
|
3737
3580
|
const resolvedArkInfo = arkInfo ?? await this.arkProvider.getInfo();
|
|
3738
3581
|
const ourXOnlyPublicKey = normalizeToXOnlyKey(
|
|
3739
3582
|
await this.wallet.identity.xOnlyPublicKey(),
|
|
@@ -3747,9 +3590,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3747
3590
|
);
|
|
3748
3591
|
const { claimPublicKey, timeoutBlockHeights: vhtlcTimeouts } = swap.response;
|
|
3749
3592
|
if (!claimPublicKey || !vhtlcTimeouts)
|
|
3750
|
-
throw new Error(
|
|
3751
|
-
`Swap ${swap.id}: incomplete submarine swap response`
|
|
3752
|
-
);
|
|
3593
|
+
throw new Error(`Swap ${swap.id}: incomplete submarine swap response`);
|
|
3753
3594
|
const boltzXOnlyPublicKey = normalizeToXOnlyKey(
|
|
3754
3595
|
import_base9.hex.decode(claimPublicKey),
|
|
3755
3596
|
"boltz",
|
|
@@ -3764,9 +3605,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3764
3605
|
timeoutBlockHeights: vhtlcTimeouts
|
|
3765
3606
|
});
|
|
3766
3607
|
if (!vhtlcScript.claimScript)
|
|
3767
|
-
throw new Error(
|
|
3768
|
-
`Swap ${swap.id}: failed to create VHTLC script for submarine swap`
|
|
3769
|
-
);
|
|
3608
|
+
throw new Error(`Swap ${swap.id}: failed to create VHTLC script for submarine swap`);
|
|
3770
3609
|
if (vhtlcAddress !== swap.response.address)
|
|
3771
3610
|
throw new Error(
|
|
3772
3611
|
`VHTLC address mismatch for swap ${swap.id}: expected ${swap.response.address}, got ${vhtlcAddress}`
|
|
@@ -3805,10 +3644,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3805
3644
|
recoverableOnly: true
|
|
3806
3645
|
})
|
|
3807
3646
|
]);
|
|
3808
|
-
const refundableVtxos = dedupeVtxos([
|
|
3809
|
-
...spendableResult.vtxos,
|
|
3810
|
-
...recoverableResult.vtxos
|
|
3811
|
-
]);
|
|
3647
|
+
const refundableVtxos = dedupeVtxos([...spendableResult.vtxos, ...recoverableResult.vtxos]);
|
|
3812
3648
|
let diagnostic;
|
|
3813
3649
|
if (refundableVtxos.length === 0) {
|
|
3814
3650
|
const { vtxos: allVtxos } = await this.indexerProvider.getVtxos({
|
|
@@ -3828,13 +3664,8 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3828
3664
|
submarineRecoveryInfoFromLookup(swap, lookup) {
|
|
3829
3665
|
const { refundableVtxos, diagnostic, vhtlcTimeouts } = lookup;
|
|
3830
3666
|
if (refundableVtxos.length > 0) {
|
|
3831
|
-
const cltvSatisfied = isSubmarineRefundLocktimeReached(
|
|
3832
|
-
|
|
3833
|
-
);
|
|
3834
|
-
const amountSats = refundableVtxos.reduce(
|
|
3835
|
-
(sum, vtxo) => sum + Number(vtxo.value),
|
|
3836
|
-
0
|
|
3837
|
-
);
|
|
3667
|
+
const cltvSatisfied = isSubmarineRefundLocktimeReached(vhtlcTimeouts.refund);
|
|
3668
|
+
const amountSats = refundableVtxos.reduce((sum, vtxo) => sum + Number(vtxo.value), 0);
|
|
3838
3669
|
const isRecoverable2 = cltvSatisfied || canRecoverViaBoltz3of3(refundableVtxos, swap);
|
|
3839
3670
|
return {
|
|
3840
3671
|
swap,
|
|
@@ -3898,19 +3729,13 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3898
3729
|
);
|
|
3899
3730
|
}
|
|
3900
3731
|
if (diagnostic.allSpent) {
|
|
3901
|
-
throw new Error(
|
|
3902
|
-
`Swap ${pendingSwap.id}: VHTLC is already spent`
|
|
3903
|
-
);
|
|
3732
|
+
throw new Error(`Swap ${pendingSwap.id}: VHTLC is already spent`);
|
|
3904
3733
|
}
|
|
3905
|
-
throw new Error(
|
|
3906
|
-
`Swap ${pendingSwap.id}: VHTLC has no refundable VTXOs yet`
|
|
3907
|
-
);
|
|
3734
|
+
throw new Error(`Swap ${pendingSwap.id}: VHTLC has no refundable VTXOs yet`);
|
|
3908
3735
|
}
|
|
3909
3736
|
const outputScript = import_sdk8.ArkAddress.decode(address).pkScript;
|
|
3910
3737
|
const refundWithoutReceiverLeaf = vhtlcScript.refundWithoutReceiver();
|
|
3911
|
-
const cltvSatisfied = isSubmarineRefundLocktimeReached(
|
|
3912
|
-
vhtlcTimeouts.refund
|
|
3913
|
-
);
|
|
3738
|
+
const cltvSatisfied = isSubmarineRefundLocktimeReached(vhtlcTimeouts.refund);
|
|
3914
3739
|
let boltzCallCount = 0;
|
|
3915
3740
|
let sweptCount = 0;
|
|
3916
3741
|
let skippedCount = 0;
|
|
@@ -3962,9 +3787,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3962
3787
|
input,
|
|
3963
3788
|
output,
|
|
3964
3789
|
arkInfo,
|
|
3965
|
-
this.swapProvider.refundSubmarineSwap.bind(
|
|
3966
|
-
this.swapProvider
|
|
3967
|
-
)
|
|
3790
|
+
this.swapProvider.refundSubmarineSwap.bind(this.swapProvider)
|
|
3968
3791
|
);
|
|
3969
3792
|
boltzCallCount++;
|
|
3970
3793
|
sweptCount++;
|
|
@@ -3987,13 +3810,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
3987
3810
|
tapLeafScript: refundWithoutReceiverLeaf,
|
|
3988
3811
|
tapTree: vhtlcScript.encode()
|
|
3989
3812
|
};
|
|
3990
|
-
await this.joinBatch(
|
|
3991
|
-
this.wallet.identity,
|
|
3992
|
-
fallbackInput,
|
|
3993
|
-
output,
|
|
3994
|
-
arkInfo,
|
|
3995
|
-
false
|
|
3996
|
-
);
|
|
3813
|
+
await this.joinBatch(this.wallet.identity, fallbackInput, output, arkInfo, false);
|
|
3997
3814
|
sweptCount++;
|
|
3998
3815
|
}
|
|
3999
3816
|
}
|
|
@@ -4089,10 +3906,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4089
3906
|
try {
|
|
4090
3907
|
return {
|
|
4091
3908
|
swap,
|
|
4092
|
-
context: await this.buildSubmarineVHTLCContext(
|
|
4093
|
-
swap,
|
|
4094
|
-
arkInfo
|
|
4095
|
-
)
|
|
3909
|
+
context: await this.buildSubmarineVHTLCContext(swap, arkInfo)
|
|
4096
3910
|
};
|
|
4097
3911
|
} catch (err) {
|
|
4098
3912
|
return {
|
|
@@ -4105,9 +3919,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4105
3919
|
const valid = prepared.filter(
|
|
4106
3920
|
(item) => "context" in item
|
|
4107
3921
|
);
|
|
4108
|
-
const scripts = [
|
|
4109
|
-
...new Set(valid.map(({ context }) => context.vhtlcPkScriptHex))
|
|
4110
|
-
];
|
|
3922
|
+
const scripts = [...new Set(valid.map(({ context }) => context.vhtlcPkScriptHex))];
|
|
4111
3923
|
const refundableByScript = /* @__PURE__ */ new Map();
|
|
4112
3924
|
if (scripts.length > 0) {
|
|
4113
3925
|
const [spendableResult, recoverableResult] = await Promise.all([
|
|
@@ -4142,9 +3954,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4142
3954
|
error: item.error
|
|
4143
3955
|
};
|
|
4144
3956
|
}
|
|
4145
|
-
const refundableVtxos = refundableByScript.get(
|
|
4146
|
-
item.context.vhtlcPkScriptHex.toLowerCase()
|
|
4147
|
-
) ?? [];
|
|
3957
|
+
const refundableVtxos = refundableByScript.get(item.context.vhtlcPkScriptHex.toLowerCase()) ?? [];
|
|
4148
3958
|
return this.submarineRecoveryInfoFromLookup(item.swap, {
|
|
4149
3959
|
...item.context,
|
|
4150
3960
|
refundableVtxos
|
|
@@ -4323,9 +4133,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4323
4133
|
*/
|
|
4324
4134
|
async waitAndClaimBtc(pendingSwap) {
|
|
4325
4135
|
if (this.swapManager && await this.swapManager.hasSwap(pendingSwap.id)) {
|
|
4326
|
-
const { txid } = await this.swapManager.waitForSwapCompletion(
|
|
4327
|
-
pendingSwap.id
|
|
4328
|
-
);
|
|
4136
|
+
const { txid } = await this.swapManager.waitForSwapCompletion(pendingSwap.id);
|
|
4329
4137
|
return { txid };
|
|
4330
4138
|
}
|
|
4331
4139
|
return new Promise((resolve, reject) => {
|
|
@@ -4352,24 +4160,25 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4352
4160
|
}
|
|
4353
4161
|
case "transaction.claimed":
|
|
4354
4162
|
await updateSwapStatus();
|
|
4355
|
-
const claimedStatus = await this.getSwapStatus(
|
|
4356
|
-
pendingSwap.id
|
|
4357
|
-
);
|
|
4163
|
+
const claimedStatus = await this.getSwapStatus(pendingSwap.id);
|
|
4358
4164
|
resolve({
|
|
4359
4165
|
txid: claimedStatus.transaction?.id ?? ""
|
|
4360
4166
|
});
|
|
4361
4167
|
break;
|
|
4362
4168
|
case "transaction.lockupFailed":
|
|
4363
4169
|
await updateSwapStatus();
|
|
4364
|
-
await this.quoteSwap(swap.response.id).catch(
|
|
4365
|
-
|
|
4366
|
-
|
|
4367
|
-
|
|
4368
|
-
|
|
4369
|
-
|
|
4370
|
-
|
|
4371
|
-
|
|
4372
|
-
|
|
4170
|
+
await this.quoteSwap(swap.response.id, quoteOptionsForSwap(swap)).catch(
|
|
4171
|
+
(err) => {
|
|
4172
|
+
reject(
|
|
4173
|
+
new SwapError({
|
|
4174
|
+
message: `Failed to renegotiate quote: ${err.message}`,
|
|
4175
|
+
isRefundable: true,
|
|
4176
|
+
pendingSwap: swap,
|
|
4177
|
+
cause: err
|
|
4178
|
+
})
|
|
4179
|
+
);
|
|
4180
|
+
}
|
|
4181
|
+
);
|
|
4373
4182
|
break;
|
|
4374
4183
|
case "swap.expired":
|
|
4375
4184
|
await updateSwapStatus();
|
|
@@ -4407,30 +4216,18 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4407
4216
|
*/
|
|
4408
4217
|
async claimBtc(pendingSwap) {
|
|
4409
4218
|
if (!pendingSwap.toAddress)
|
|
4410
|
-
throw new Error(
|
|
4411
|
-
`Swap ${pendingSwap.id}: destination address is required`
|
|
4412
|
-
);
|
|
4219
|
+
throw new Error(`Swap ${pendingSwap.id}: destination address is required`);
|
|
4413
4220
|
if (!pendingSwap.response.claimDetails.swapTree)
|
|
4414
|
-
throw new Error(
|
|
4415
|
-
`Swap ${pendingSwap.id}: missing swap tree in claim details`
|
|
4416
|
-
);
|
|
4221
|
+
throw new Error(`Swap ${pendingSwap.id}: missing swap tree in claim details`);
|
|
4417
4222
|
if (!pendingSwap.response.claimDetails.serverPublicKey)
|
|
4418
|
-
throw new Error(
|
|
4419
|
-
`Swap ${pendingSwap.id}: missing server public key in claim details`
|
|
4420
|
-
);
|
|
4223
|
+
throw new Error(`Swap ${pendingSwap.id}: missing server public key in claim details`);
|
|
4421
4224
|
const swapStatus = await this.getSwapStatus(pendingSwap.id);
|
|
4422
4225
|
if (!swapStatus.transaction?.hex)
|
|
4423
|
-
throw new Error(
|
|
4424
|
-
|
|
4425
|
-
);
|
|
4426
|
-
const lockupTx = import_btc_signer5.Transaction.fromRaw(
|
|
4427
|
-
import_base9.hex.decode(swapStatus.transaction.hex)
|
|
4428
|
-
);
|
|
4226
|
+
throw new Error(`Swap ${pendingSwap.id}: BTC transaction hex is required`);
|
|
4227
|
+
const lockupTx = import_btc_signer5.Transaction.fromRaw(import_base9.hex.decode(swapStatus.transaction.hex));
|
|
4429
4228
|
const arkInfo = await this.arkProvider.getInfo();
|
|
4430
4229
|
const network = arkInfo.network === "bitcoin" ? import_utils4.NETWORK : arkInfo.network === "mutinynet" ? MUTINYNET_NETWORK : REGTEST_NETWORK;
|
|
4431
|
-
const swapTree = deserializeSwapTree(
|
|
4432
|
-
pendingSwap.response.claimDetails.swapTree
|
|
4433
|
-
);
|
|
4230
|
+
const swapTree = deserializeSwapTree(pendingSwap.response.claimDetails.swapTree);
|
|
4434
4231
|
const musig = tweakMusig(
|
|
4435
4232
|
create(import_base9.hex.decode(pendingSwap.ephemeralKey), [
|
|
4436
4233
|
import_base9.hex.decode(pendingSwap.response.claimDetails.serverPublicKey),
|
|
@@ -4451,19 +4248,14 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4451
4248
|
vout: swapOutput.vout,
|
|
4452
4249
|
transactionId: lockupTx.id
|
|
4453
4250
|
},
|
|
4454
|
-
import_btc_signer5.OutScript.encode(
|
|
4455
|
-
(0, import_btc_signer5.Address)(network).decode(pendingSwap.toAddress)
|
|
4456
|
-
),
|
|
4251
|
+
import_btc_signer5.OutScript.encode((0, import_btc_signer5.Address)(network).decode(pendingSwap.toAddress)),
|
|
4457
4252
|
feeToDeliverExactAmount > fee ? feeToDeliverExactAmount : fee
|
|
4458
4253
|
)
|
|
4459
4254
|
);
|
|
4460
4255
|
const musigMessage = musig.message(
|
|
4461
|
-
claimTx.preimageWitnessV1(
|
|
4462
|
-
|
|
4463
|
-
|
|
4464
|
-
import_btc_signer5.SigHash.DEFAULT,
|
|
4465
|
-
[swapOutput.amount]
|
|
4466
|
-
)
|
|
4256
|
+
claimTx.preimageWitnessV1(0, [swapOutput.script], import_btc_signer5.SigHash.DEFAULT, [
|
|
4257
|
+
swapOutput.amount
|
|
4258
|
+
])
|
|
4467
4259
|
).generateNonce();
|
|
4468
4260
|
const signedTxData = await this.swapProvider.postChainClaimDetails(
|
|
4469
4261
|
pendingSwap.response.id,
|
|
@@ -4477,14 +4269,10 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4477
4269
|
}
|
|
4478
4270
|
);
|
|
4479
4271
|
if (!signedTxData.pubNonce || !signedTxData.partialSignature)
|
|
4480
|
-
throw new Error(
|
|
4481
|
-
`Swap ${pendingSwap.id}: invalid signature data from server`
|
|
4482
|
-
);
|
|
4272
|
+
throw new Error(`Swap ${pendingSwap.id}: invalid signature data from server`);
|
|
4483
4273
|
const musigSession = musigMessage.aggregateNonces([
|
|
4484
4274
|
[
|
|
4485
|
-
import_base9.hex.decode(
|
|
4486
|
-
pendingSwap.response.claimDetails.serverPublicKey
|
|
4487
|
-
),
|
|
4275
|
+
import_base9.hex.decode(pendingSwap.response.claimDetails.serverPublicKey),
|
|
4488
4276
|
import_base9.hex.decode(signedTxData.pubNonce)
|
|
4489
4277
|
]
|
|
4490
4278
|
]).initializeSession();
|
|
@@ -4504,13 +4292,9 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4504
4292
|
*/
|
|
4505
4293
|
async refundArk(pendingSwap) {
|
|
4506
4294
|
if (!pendingSwap.response.lockupDetails.serverPublicKey)
|
|
4507
|
-
throw new Error(
|
|
4508
|
-
`Swap ${pendingSwap.id}: missing server public key in lockup details`
|
|
4509
|
-
);
|
|
4295
|
+
throw new Error(`Swap ${pendingSwap.id}: missing server public key in lockup details`);
|
|
4510
4296
|
if (!pendingSwap.response.lockupDetails.timeouts)
|
|
4511
|
-
throw new Error(
|
|
4512
|
-
`Swap ${pendingSwap.id}: missing timeouts in lockup details`
|
|
4513
|
-
);
|
|
4297
|
+
throw new Error(`Swap ${pendingSwap.id}: missing timeouts in lockup details`);
|
|
4514
4298
|
const arkInfo = await this.arkProvider.getInfo();
|
|
4515
4299
|
const address = await this.wallet.getAddress();
|
|
4516
4300
|
const ourXOnlyPublicKey = normalizeToXOnlyKey(
|
|
@@ -4552,9 +4336,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4552
4336
|
timeoutBlockHeights: pendingSwap.response.lockupDetails.timeouts
|
|
4553
4337
|
});
|
|
4554
4338
|
if (!vhtlcScript.refundScript)
|
|
4555
|
-
throw new Error(
|
|
4556
|
-
`Swap ${pendingSwap.id}: failed to create VHTLC script for chain swap`
|
|
4557
|
-
);
|
|
4339
|
+
throw new Error(`Swap ${pendingSwap.id}: failed to create VHTLC script for chain swap`);
|
|
4558
4340
|
if (pendingSwap.response.lockupDetails.lockupAddress !== vhtlcAddress) {
|
|
4559
4341
|
throw new SwapError({
|
|
4560
4342
|
message: "Unable to claim: invalid VHTLC address"
|
|
@@ -4635,9 +4417,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4635
4417
|
*/
|
|
4636
4418
|
async waitAndClaimArk(pendingSwap) {
|
|
4637
4419
|
if (this.swapManager && await this.swapManager.hasSwap(pendingSwap.id)) {
|
|
4638
|
-
const { txid } = await this.swapManager.waitForSwapCompletion(
|
|
4639
|
-
pendingSwap.id
|
|
4640
|
-
);
|
|
4420
|
+
const { txid } = await this.swapManager.waitForSwapCompletion(pendingSwap.id);
|
|
4641
4421
|
return { txid };
|
|
4642
4422
|
}
|
|
4643
4423
|
return new Promise((resolve, reject) => {
|
|
@@ -4658,37 +4438,33 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4658
4438
|
break;
|
|
4659
4439
|
case "transaction.claimed":
|
|
4660
4440
|
await updateSwapStatus();
|
|
4661
|
-
const claimedStatus = await this.getSwapStatus(
|
|
4662
|
-
pendingSwap.id
|
|
4663
|
-
);
|
|
4441
|
+
const claimedStatus = await this.getSwapStatus(pendingSwap.id);
|
|
4664
4442
|
resolve({
|
|
4665
4443
|
txid: claimedStatus.transaction?.id ?? ""
|
|
4666
4444
|
});
|
|
4667
4445
|
break;
|
|
4668
4446
|
case "transaction.claim.pending":
|
|
4669
4447
|
await updateSwapStatus();
|
|
4670
|
-
await this.signCooperativeClaimForServer(swap).catch(
|
|
4448
|
+
await this.signCooperativeClaimForServer(swap).catch((err) => {
|
|
4449
|
+
logger.error(`Failed to sign cooperative claim for ${swap.id}:`, err);
|
|
4450
|
+
});
|
|
4451
|
+
break;
|
|
4452
|
+
case "transaction.lockupFailed":
|
|
4453
|
+
await updateSwapStatus();
|
|
4454
|
+
await this.quoteSwap(swap.response.id, quoteOptionsForSwap(swap)).catch(
|
|
4671
4455
|
(err) => {
|
|
4672
|
-
|
|
4673
|
-
|
|
4674
|
-
|
|
4456
|
+
reject(
|
|
4457
|
+
new SwapError({
|
|
4458
|
+
message: `Failed to renegotiate quote: ${err.message}`,
|
|
4459
|
+
isRefundable: false,
|
|
4460
|
+
// TODO btc refund not implemented yet
|
|
4461
|
+
pendingSwap: swap,
|
|
4462
|
+
cause: err
|
|
4463
|
+
})
|
|
4675
4464
|
);
|
|
4676
4465
|
}
|
|
4677
4466
|
);
|
|
4678
4467
|
break;
|
|
4679
|
-
case "transaction.lockupFailed":
|
|
4680
|
-
await updateSwapStatus();
|
|
4681
|
-
await this.quoteSwap(swap.response.id).catch((err) => {
|
|
4682
|
-
reject(
|
|
4683
|
-
new SwapError({
|
|
4684
|
-
message: `Failed to renegotiate quote: ${err.message}`,
|
|
4685
|
-
isRefundable: false,
|
|
4686
|
-
// TODO btc refund not implemented yet
|
|
4687
|
-
pendingSwap: swap
|
|
4688
|
-
})
|
|
4689
|
-
);
|
|
4690
|
-
});
|
|
4691
|
-
break;
|
|
4692
4468
|
case "swap.expired":
|
|
4693
4469
|
await updateSwapStatus();
|
|
4694
4470
|
reject(
|
|
@@ -4728,17 +4504,11 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4728
4504
|
*/
|
|
4729
4505
|
async claimArk(pendingSwap) {
|
|
4730
4506
|
if (!pendingSwap.toAddress)
|
|
4731
|
-
throw new Error(
|
|
4732
|
-
`Swap ${pendingSwap.id}: destination address is required`
|
|
4733
|
-
);
|
|
4507
|
+
throw new Error(`Swap ${pendingSwap.id}: destination address is required`);
|
|
4734
4508
|
if (!pendingSwap.response.claimDetails.serverPublicKey)
|
|
4735
|
-
throw new Error(
|
|
4736
|
-
`Swap ${pendingSwap.id}: missing server public key in claim details`
|
|
4737
|
-
);
|
|
4509
|
+
throw new Error(`Swap ${pendingSwap.id}: missing server public key in claim details`);
|
|
4738
4510
|
if (!pendingSwap.response.claimDetails.timeouts)
|
|
4739
|
-
throw new Error(
|
|
4740
|
-
`Swap ${pendingSwap.id}: missing timeouts in claim details`
|
|
4741
|
-
);
|
|
4511
|
+
throw new Error(`Swap ${pendingSwap.id}: missing timeouts in claim details`);
|
|
4742
4512
|
const arkInfo = await this.arkProvider.getInfo();
|
|
4743
4513
|
const preimage = import_base9.hex.decode(pendingSwap.preimage);
|
|
4744
4514
|
const address = await this.wallet.getAddress();
|
|
@@ -4750,10 +4520,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4750
4520
|
pendingSwap.response.claimDetails.serverPublicKey,
|
|
4751
4521
|
"sender"
|
|
4752
4522
|
);
|
|
4753
|
-
const serverXOnlyPublicKey = normalizeToXOnlyKey(
|
|
4754
|
-
arkInfo.signerPubkey,
|
|
4755
|
-
"server"
|
|
4756
|
-
);
|
|
4523
|
+
const serverXOnlyPublicKey = normalizeToXOnlyKey(arkInfo.signerPubkey, "server");
|
|
4757
4524
|
const { vhtlcAddress, vhtlcScript } = this.createVHTLCScript({
|
|
4758
4525
|
network: arkInfo.network,
|
|
4759
4526
|
preimageHash: import_base9.hex.decode(pendingSwap.request.preimageHash),
|
|
@@ -4763,9 +4530,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4763
4530
|
timeoutBlockHeights: pendingSwap.response.claimDetails.timeouts
|
|
4764
4531
|
});
|
|
4765
4532
|
if (!vhtlcScript.claimScript)
|
|
4766
|
-
throw new Error(
|
|
4767
|
-
`Swap ${pendingSwap.id}: failed to create VHTLC script for chain swap`
|
|
4768
|
-
);
|
|
4533
|
+
throw new Error(`Swap ${pendingSwap.id}: failed to create VHTLC script for chain swap`);
|
|
4769
4534
|
if (pendingSwap.response.claimDetails.lockupAddress !== vhtlcAddress) {
|
|
4770
4535
|
throw new SwapError({
|
|
4771
4536
|
message: "Unable to claim: invalid VHTLC address"
|
|
@@ -4782,15 +4547,11 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4782
4547
|
break;
|
|
4783
4548
|
}
|
|
4784
4549
|
if (attempt < CLAIM_VTXO_RETRY_ATTEMPTS) {
|
|
4785
|
-
await new Promise(
|
|
4786
|
-
(resolve) => setTimeout(resolve, CLAIM_VTXO_RETRY_DELAY_MS)
|
|
4787
|
-
);
|
|
4550
|
+
await new Promise((resolve) => setTimeout(resolve, CLAIM_VTXO_RETRY_DELAY_MS));
|
|
4788
4551
|
}
|
|
4789
4552
|
}
|
|
4790
4553
|
if (!vtxo) {
|
|
4791
|
-
throw new Error(
|
|
4792
|
-
`Swap ${pendingSwap.id}: no spendable virtual coins found`
|
|
4793
|
-
);
|
|
4554
|
+
throw new Error(`Swap ${pendingSwap.id}: no spendable virtual coins found`);
|
|
4794
4555
|
}
|
|
4795
4556
|
const input = {
|
|
4796
4557
|
...vtxo,
|
|
@@ -4801,10 +4562,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4801
4562
|
amount: BigInt(vtxo.value),
|
|
4802
4563
|
script: import_sdk8.ArkAddress.decode(address).pkScript
|
|
4803
4564
|
};
|
|
4804
|
-
const vhtlcIdentity = claimVHTLCIdentity(
|
|
4805
|
-
this.wallet.identity,
|
|
4806
|
-
preimage
|
|
4807
|
-
);
|
|
4565
|
+
const vhtlcIdentity = claimVHTLCIdentity(this.wallet.identity, preimage);
|
|
4808
4566
|
if ((0, import_sdk8.isRecoverable)(vtxo)) {
|
|
4809
4567
|
await this.joinBatch(vhtlcIdentity, input, output, arkInfo);
|
|
4810
4568
|
} else {
|
|
@@ -4830,16 +4588,10 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4830
4588
|
*/
|
|
4831
4589
|
async signCooperativeClaimForServer(pendingSwap) {
|
|
4832
4590
|
if (!pendingSwap.response.lockupDetails.swapTree)
|
|
4833
|
-
throw new Error(
|
|
4834
|
-
`Swap ${pendingSwap.id}: missing swap tree in lockup details`
|
|
4835
|
-
);
|
|
4591
|
+
throw new Error(`Swap ${pendingSwap.id}: missing swap tree in lockup details`);
|
|
4836
4592
|
if (!pendingSwap.response.lockupDetails.serverPublicKey)
|
|
4837
|
-
throw new Error(
|
|
4838
|
-
|
|
4839
|
-
);
|
|
4840
|
-
const claimDetails = await this.swapProvider.getChainClaimDetails(
|
|
4841
|
-
pendingSwap.id
|
|
4842
|
-
);
|
|
4593
|
+
throw new Error(`Swap ${pendingSwap.id}: missing server public key in lockup details`);
|
|
4594
|
+
const claimDetails = await this.swapProvider.getChainClaimDetails(pendingSwap.id);
|
|
4843
4595
|
const serverPubKey = pendingSwap.response.lockupDetails.serverPublicKey;
|
|
4844
4596
|
if (claimDetails.publicKey !== serverPubKey) {
|
|
4845
4597
|
throw new Error(
|
|
@@ -4855,9 +4607,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4855
4607
|
);
|
|
4856
4608
|
const musigNonces = musig.message(import_base9.hex.decode(claimDetails.transactionHash)).generateNonce().aggregateNonces([
|
|
4857
4609
|
[
|
|
4858
|
-
import_base9.hex.decode(
|
|
4859
|
-
pendingSwap.response.lockupDetails.serverPublicKey
|
|
4860
|
-
),
|
|
4610
|
+
import_base9.hex.decode(pendingSwap.response.lockupDetails.serverPublicKey),
|
|
4861
4611
|
import_base9.hex.decode(claimDetails.pubNonce)
|
|
4862
4612
|
]
|
|
4863
4613
|
]).initializeSession();
|
|
@@ -4876,10 +4626,8 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4876
4626
|
* @returns The transaction ID of the claim.
|
|
4877
4627
|
*/
|
|
4878
4628
|
async waitAndClaimChain(pendingSwap) {
|
|
4879
|
-
if (pendingSwap.request.to === "ARK")
|
|
4880
|
-
|
|
4881
|
-
if (pendingSwap.request.to === "BTC")
|
|
4882
|
-
return this.waitAndClaimBtc(pendingSwap);
|
|
4629
|
+
if (pendingSwap.request.to === "ARK") return this.waitAndClaimArk(pendingSwap);
|
|
4630
|
+
if (pendingSwap.request.to === "BTC") return this.waitAndClaimBtc(pendingSwap);
|
|
4883
4631
|
throw new SwapError({
|
|
4884
4632
|
message: `Unsupported swap destination: ${pendingSwap.request.to}`
|
|
4885
4633
|
});
|
|
@@ -4894,11 +4642,9 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4894
4642
|
*/
|
|
4895
4643
|
async createChainSwap(args) {
|
|
4896
4644
|
const { to, from, receiverLockAmount, senderLockAmount, toAddress } = args;
|
|
4897
|
-
if (!toAddress)
|
|
4898
|
-
throw new SwapError({ message: "Destination address is required" });
|
|
4645
|
+
if (!toAddress) throw new SwapError({ message: "Destination address is required" });
|
|
4899
4646
|
const feeSatsPerByte = args.feeSatsPerByte ?? 1;
|
|
4900
|
-
if (feeSatsPerByte <= 0)
|
|
4901
|
-
throw new SwapError({ message: "Invalid feeSatsPerByte" });
|
|
4647
|
+
if (feeSatsPerByte <= 0) throw new SwapError({ message: "Invalid feeSatsPerByte" });
|
|
4902
4648
|
let amount, serverLockAmount, userLockAmount;
|
|
4903
4649
|
if (receiverLockAmount) {
|
|
4904
4650
|
amount = receiverLockAmount;
|
|
@@ -4913,8 +4659,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4913
4659
|
}
|
|
4914
4660
|
const preimage = (0, import_utils3.randomBytes)(32);
|
|
4915
4661
|
const preimageHash = import_base9.hex.encode((0, import_sha23.sha256)(preimage));
|
|
4916
|
-
if (!preimageHash)
|
|
4917
|
-
throw new SwapError({ message: "Failed to get preimage hash" });
|
|
4662
|
+
if (!preimageHash) throw new SwapError({ message: "Failed to get preimage hash" });
|
|
4918
4663
|
const ephemeralKey = import_secp256k13.secp256k1.utils.randomSecretKey();
|
|
4919
4664
|
const refundPublicKey = to === "ARK" ? import_base9.hex.encode(import_secp256k13.secp256k1.getPublicKey(ephemeralKey)) : import_base9.hex.encode(await this.wallet.identity.compressedPublicKey());
|
|
4920
4665
|
if (!refundPublicKey)
|
|
@@ -4963,30 +4708,20 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
4963
4708
|
const { to, from, swap, arkInfo } = args;
|
|
4964
4709
|
if (from === "ARK") {
|
|
4965
4710
|
if (!swap.response.lockupDetails.serverPublicKey)
|
|
4966
|
-
throw new Error(
|
|
4967
|
-
`Swap ${swap.id}: missing serverPublicKey in lockup details`
|
|
4968
|
-
);
|
|
4711
|
+
throw new Error(`Swap ${swap.id}: missing serverPublicKey in lockup details`);
|
|
4969
4712
|
if (!swap.response.lockupDetails.timeouts)
|
|
4970
|
-
throw new Error(
|
|
4971
|
-
`Swap ${swap.id}: missing timeouts in lockup details`
|
|
4972
|
-
);
|
|
4713
|
+
throw new Error(`Swap ${swap.id}: missing timeouts in lockup details`);
|
|
4973
4714
|
}
|
|
4974
4715
|
if (to === "ARK") {
|
|
4975
4716
|
if (!swap.response.claimDetails.serverPublicKey)
|
|
4976
|
-
throw new Error(
|
|
4977
|
-
`Swap ${swap.id}: missing serverPublicKey in claim details`
|
|
4978
|
-
);
|
|
4717
|
+
throw new Error(`Swap ${swap.id}: missing serverPublicKey in claim details`);
|
|
4979
4718
|
if (!swap.response.claimDetails.timeouts)
|
|
4980
|
-
throw new Error(
|
|
4981
|
-
`Swap ${swap.id}: missing timeouts in claim details`
|
|
4982
|
-
);
|
|
4719
|
+
throw new Error(`Swap ${swap.id}: missing timeouts in claim details`);
|
|
4983
4720
|
}
|
|
4984
4721
|
const lockupAddress = to === "ARK" ? swap.response.claimDetails.lockupAddress : swap.response.lockupDetails.lockupAddress;
|
|
4985
4722
|
const receiverPubkey = to === "ARK" ? swap.request.claimPublicKey : swap.response.lockupDetails.serverPublicKey;
|
|
4986
4723
|
const senderPubkey = to === "ARK" ? swap.response.claimDetails.serverPublicKey : swap.request.refundPublicKey;
|
|
4987
|
-
const serverPubkey = import_base9.hex.encode(
|
|
4988
|
-
normalizeToXOnlyKey(arkInfo.signerPubkey, "server")
|
|
4989
|
-
);
|
|
4724
|
+
const serverPubkey = import_base9.hex.encode(normalizeToXOnlyKey(arkInfo.signerPubkey, "server"));
|
|
4990
4725
|
const vhtlcTimeouts = to === "ARK" ? swap.response.claimDetails.timeouts : swap.response.lockupDetails.timeouts;
|
|
4991
4726
|
const { vhtlcAddress } = this.createVHTLCScript({
|
|
4992
4727
|
network: arkInfo.network,
|
|
@@ -5004,15 +4739,110 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5004
4739
|
return true;
|
|
5005
4740
|
}
|
|
5006
4741
|
/**
|
|
5007
|
-
* Renegotiates the quote for an existing swap.
|
|
4742
|
+
* Renegotiates the quote for an existing chain swap. Convenience wrapper
|
|
4743
|
+
* over `getSwapQuote` + `acceptSwapQuote` with a safety floor.
|
|
4744
|
+
*
|
|
4745
|
+
* The floor is resolved in order:
|
|
4746
|
+
* 1. `options.minAcceptableAmount` if provided.
|
|
4747
|
+
* 2. The original `response.claimDetails.amount` of the stored
|
|
4748
|
+
* pending swap (Boltz-confirmed server-lock amount at creation).
|
|
4749
|
+
* 3. Otherwise throws `QuoteRejectedError({ reason: "no_baseline" })`.
|
|
4750
|
+
*
|
|
4751
|
+
* `options.maxSlippageBps` (default 0) relaxes the floor by basis points.
|
|
4752
|
+
* Quotes ≤ 0 are always rejected. On rejection the acceptance is NOT
|
|
4753
|
+
* posted to Boltz.
|
|
4754
|
+
*
|
|
4755
|
+
* Prefer `getSwapQuote` / `acceptSwapQuote` for callers that want to
|
|
4756
|
+
* inspect the quote before committing.
|
|
4757
|
+
*
|
|
5008
4758
|
* @param swapId - The ID of the swap.
|
|
4759
|
+
* @param options - Optional floor and slippage configuration.
|
|
5009
4760
|
* @returns The accepted quote amount.
|
|
4761
|
+
* @throws QuoteRejectedError if the quote is non-positive, below the
|
|
4762
|
+
* effective floor, or no baseline is available.
|
|
5010
4763
|
*/
|
|
5011
|
-
async quoteSwap(swapId) {
|
|
4764
|
+
async quoteSwap(swapId, options) {
|
|
4765
|
+
const effectiveFloor = await this.resolveEffectiveFloor(swapId, options);
|
|
4766
|
+
const amount = await this.getSwapQuote(swapId);
|
|
4767
|
+
this.validateQuote(amount, effectiveFloor);
|
|
4768
|
+
await this.swapProvider.postChainQuote(swapId, { amount });
|
|
4769
|
+
return amount;
|
|
4770
|
+
}
|
|
4771
|
+
/**
|
|
4772
|
+
* Fetches a renegotiated quote from Boltz without accepting it.
|
|
4773
|
+
* Pair with `acceptSwapQuote` to commit a specific value.
|
|
4774
|
+
*/
|
|
4775
|
+
async getSwapQuote(swapId) {
|
|
5012
4776
|
const { amount } = await this.swapProvider.getChainQuote(swapId);
|
|
4777
|
+
return amount;
|
|
4778
|
+
}
|
|
4779
|
+
/**
|
|
4780
|
+
* Accepts a quote amount for an existing chain swap, after validating it
|
|
4781
|
+
* against the configured floor. See `quoteSwap` for floor-resolution rules.
|
|
4782
|
+
*
|
|
4783
|
+
* @throws QuoteRejectedError if `amount` ≤ 0, below the effective floor,
|
|
4784
|
+
* or no baseline is available.
|
|
4785
|
+
*/
|
|
4786
|
+
async acceptSwapQuote(swapId, amount, options) {
|
|
4787
|
+
const effectiveFloor = await this.resolveEffectiveFloor(swapId, options);
|
|
4788
|
+
this.validateQuote(amount, effectiveFloor);
|
|
5013
4789
|
await this.swapProvider.postChainQuote(swapId, { amount });
|
|
5014
4790
|
return amount;
|
|
5015
4791
|
}
|
|
4792
|
+
async resolveEffectiveFloor(swapId, options) {
|
|
4793
|
+
this.validateQuoteOptions(options);
|
|
4794
|
+
const floor = await this.resolveQuoteFloor(swapId, options);
|
|
4795
|
+
const slippageBps = options?.maxSlippageBps ?? 0;
|
|
4796
|
+
return Math.floor(floor - floor * slippageBps / 1e4);
|
|
4797
|
+
}
|
|
4798
|
+
async resolveQuoteFloor(swapId, options) {
|
|
4799
|
+
if (options?.minAcceptableAmount !== void 0) {
|
|
4800
|
+
return options.minAcceptableAmount;
|
|
4801
|
+
}
|
|
4802
|
+
const swaps = await this.swapRepository.getAllSwaps({
|
|
4803
|
+
id: swapId,
|
|
4804
|
+
type: "chain"
|
|
4805
|
+
});
|
|
4806
|
+
const stored = swaps[0];
|
|
4807
|
+
const amount = stored?.response?.claimDetails?.amount;
|
|
4808
|
+
if (typeof amount !== "number") {
|
|
4809
|
+
throw new QuoteRejectedError({ reason: "no_baseline" });
|
|
4810
|
+
}
|
|
4811
|
+
return amount;
|
|
4812
|
+
}
|
|
4813
|
+
validateQuoteOptions(options) {
|
|
4814
|
+
if (options?.minAcceptableAmount !== void 0) {
|
|
4815
|
+
const v = options.minAcceptableAmount;
|
|
4816
|
+
if (!Number.isInteger(v) || v <= 0) {
|
|
4817
|
+
throw new TypeError(
|
|
4818
|
+
`Invalid minAcceptableAmount: ${v} \u2014 must be a positive integer`
|
|
4819
|
+
);
|
|
4820
|
+
}
|
|
4821
|
+
}
|
|
4822
|
+
if (options?.maxSlippageBps !== void 0) {
|
|
4823
|
+
const v = options.maxSlippageBps;
|
|
4824
|
+
if (!Number.isInteger(v) || v < 0 || v > 1e4) {
|
|
4825
|
+
throw new TypeError(
|
|
4826
|
+
`Invalid maxSlippageBps: ${v} \u2014 must be an integer in [0, 10000]`
|
|
4827
|
+
);
|
|
4828
|
+
}
|
|
4829
|
+
}
|
|
4830
|
+
}
|
|
4831
|
+
validateQuote(amount, effectiveFloor) {
|
|
4832
|
+
if (!(amount > 0)) {
|
|
4833
|
+
throw new QuoteRejectedError({
|
|
4834
|
+
reason: "non_positive",
|
|
4835
|
+
quotedAmount: amount
|
|
4836
|
+
});
|
|
4837
|
+
}
|
|
4838
|
+
if (amount < effectiveFloor) {
|
|
4839
|
+
throw new QuoteRejectedError({
|
|
4840
|
+
reason: "below_floor",
|
|
4841
|
+
quotedAmount: amount,
|
|
4842
|
+
floor: effectiveFloor
|
|
4843
|
+
});
|
|
4844
|
+
}
|
|
4845
|
+
}
|
|
5016
4846
|
// =========================================================================
|
|
5017
4847
|
// Shared utilities
|
|
5018
4848
|
// =========================================================================
|
|
@@ -5026,14 +4856,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5026
4856
|
* @returns The commitment transaction ID.
|
|
5027
4857
|
*/
|
|
5028
4858
|
async joinBatch(identity, input, output, arkInfo, isRecoverable2 = true) {
|
|
5029
|
-
return joinBatch(
|
|
5030
|
-
this.arkProvider,
|
|
5031
|
-
identity,
|
|
5032
|
-
input,
|
|
5033
|
-
output,
|
|
5034
|
-
arkInfo,
|
|
5035
|
-
isRecoverable2
|
|
5036
|
-
);
|
|
4859
|
+
return joinBatch(this.arkProvider, identity, input, output, arkInfo, isRecoverable2);
|
|
5037
4860
|
}
|
|
5038
4861
|
/**
|
|
5039
4862
|
* Creates a VHTLC script for the swap.
|
|
@@ -5071,9 +4894,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5071
4894
|
async getPendingSubmarineSwaps() {
|
|
5072
4895
|
const swaps = await this.getPendingSubmarineSwapsFromStorage();
|
|
5073
4896
|
if (!swaps) return [];
|
|
5074
|
-
return swaps.filter(
|
|
5075
|
-
(swap) => swap.status === "invoice.set"
|
|
5076
|
-
);
|
|
4897
|
+
return swaps.filter((swap) => swap.status === "invoice.set");
|
|
5077
4898
|
}
|
|
5078
4899
|
/**
|
|
5079
4900
|
* Returns pending reverse swaps (those with status `swap.created`).
|
|
@@ -5081,9 +4902,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5081
4902
|
async getPendingReverseSwaps() {
|
|
5082
4903
|
const swaps = await this.getPendingReverseSwapsFromStorage();
|
|
5083
4904
|
if (!swaps) return [];
|
|
5084
|
-
return swaps.filter(
|
|
5085
|
-
(swap) => swap.status === "swap.created"
|
|
5086
|
-
);
|
|
4905
|
+
return swaps.filter((swap) => swap.status === "swap.created");
|
|
5087
4906
|
}
|
|
5088
4907
|
/**
|
|
5089
4908
|
* Returns pending chain swaps (those with status `swap.created`).
|
|
@@ -5122,10 +4941,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5122
4941
|
this.savePendingReverseSwap.bind(this)
|
|
5123
4942
|
)
|
|
5124
4943
|
).catch((error) => {
|
|
5125
|
-
logger.error(
|
|
5126
|
-
`Failed to refresh swap status for ${swap.id}:`,
|
|
5127
|
-
error
|
|
5128
|
-
);
|
|
4944
|
+
logger.error(`Failed to refresh swap status for ${swap.id}:`, error);
|
|
5129
4945
|
})
|
|
5130
4946
|
);
|
|
5131
4947
|
}
|
|
@@ -5139,23 +4955,15 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5139
4955
|
this.savePendingSubmarineSwap.bind(this)
|
|
5140
4956
|
)
|
|
5141
4957
|
).catch((error) => {
|
|
5142
|
-
logger.error(
|
|
5143
|
-
`Failed to refresh swap status for ${swap.id}:`,
|
|
5144
|
-
error
|
|
5145
|
-
);
|
|
4958
|
+
logger.error(`Failed to refresh swap status for ${swap.id}:`, error);
|
|
5146
4959
|
})
|
|
5147
4960
|
);
|
|
5148
4961
|
}
|
|
5149
4962
|
for (const swap of await this.getPendingChainSwapsFromStorage()) {
|
|
5150
4963
|
if (isChainFinalStatus(swap.status)) continue;
|
|
5151
4964
|
promises.push(
|
|
5152
|
-
this.getSwapStatus(swap.id).then(
|
|
5153
|
-
(
|
|
5154
|
-
).catch((error) => {
|
|
5155
|
-
logger.error(
|
|
5156
|
-
`Failed to refresh swap status for ${swap.id}:`,
|
|
5157
|
-
error
|
|
5158
|
-
);
|
|
4965
|
+
this.getSwapStatus(swap.id).then(({ status }) => this.savePendingChainSwap({ ...swap, status })).catch((error) => {
|
|
4966
|
+
logger.error(`Failed to refresh swap status for ${swap.id}:`, error);
|
|
5159
4967
|
})
|
|
5160
4968
|
);
|
|
5161
4969
|
}
|
|
@@ -5172,9 +4980,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5172
4980
|
* display/monitoring and are not automatically wired into the SwapManager.
|
|
5173
4981
|
*/
|
|
5174
4982
|
async restoreSwaps(boltzFees) {
|
|
5175
|
-
const publicKey = import_base9.hex.encode(
|
|
5176
|
-
await this.wallet.identity.compressedPublicKey()
|
|
5177
|
-
);
|
|
4983
|
+
const publicKey = import_base9.hex.encode(await this.wallet.identity.compressedPublicKey());
|
|
5178
4984
|
if (!publicKey) throw new Error("Failed to get public key from wallet");
|
|
5179
4985
|
const fees = boltzFees ?? await this.swapProvider.getFees();
|
|
5180
4986
|
const chainSwaps = [];
|
|
@@ -5226,25 +5032,14 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5226
5032
|
preimage: ""
|
|
5227
5033
|
});
|
|
5228
5034
|
} else if (isRestoredSubmarineSwap(swap)) {
|
|
5229
|
-
const {
|
|
5230
|
-
amount,
|
|
5231
|
-
lockupAddress,
|
|
5232
|
-
serverPublicKey,
|
|
5233
|
-
tree,
|
|
5234
|
-
timeoutBlockHeights
|
|
5235
|
-
} = swap.refundDetails;
|
|
5035
|
+
const { amount, lockupAddress, serverPublicKey, tree, timeoutBlockHeights } = swap.refundDetails;
|
|
5236
5036
|
let preimage = "";
|
|
5237
5037
|
if (!isSubmarineFinalStatus(status)) {
|
|
5238
5038
|
try {
|
|
5239
|
-
const data = await this.swapProvider.getSwapPreimage(
|
|
5240
|
-
swap.id
|
|
5241
|
-
);
|
|
5039
|
+
const data = await this.swapProvider.getSwapPreimage(swap.id);
|
|
5242
5040
|
preimage = data.preimage;
|
|
5243
5041
|
} catch (error) {
|
|
5244
|
-
logger.warn(
|
|
5245
|
-
`Failed to restore preimage for submarine swap ${id}`,
|
|
5246
|
-
error
|
|
5247
|
-
);
|
|
5042
|
+
logger.warn(`Failed to restore preimage for submarine swap ${id}`, error);
|
|
5248
5043
|
}
|
|
5249
5044
|
}
|
|
5250
5045
|
submarineSwaps.push({
|
|
@@ -5282,12 +5077,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5282
5077
|
} else if (isRestoredChainSwap(swap)) {
|
|
5283
5078
|
const refundDetails = swap.refundDetails;
|
|
5284
5079
|
if (!refundDetails) continue;
|
|
5285
|
-
const {
|
|
5286
|
-
amount,
|
|
5287
|
-
lockupAddress,
|
|
5288
|
-
serverPublicKey,
|
|
5289
|
-
timeoutBlockHeight
|
|
5290
|
-
} = refundDetails;
|
|
5080
|
+
const { amount, lockupAddress, serverPublicKey, timeoutBlockHeight } = refundDetails;
|
|
5291
5081
|
chainSwaps.push({
|
|
5292
5082
|
id,
|
|
5293
5083
|
type: "chain",
|
|
@@ -5337,6 +5127,12 @@ var ArkadeSwaps = class _ArkadeSwaps {
|
|
|
5337
5127
|
|
|
5338
5128
|
// src/serviceWorker/arkade-swaps-message-handler.ts
|
|
5339
5129
|
var import_sdk9 = require("@arkade-os/sdk");
|
|
5130
|
+
function toQuoteTransportError(error) {
|
|
5131
|
+
if (error instanceof QuoteRejectedError) {
|
|
5132
|
+
return error.toTransportError();
|
|
5133
|
+
}
|
|
5134
|
+
return error;
|
|
5135
|
+
}
|
|
5340
5136
|
var DEFAULT_MESSAGE_TAG = "ARKADE_SWAPS_UPDATER";
|
|
5341
5137
|
var HANDLER_NOT_INITIALIZED = "ArkadeSwaps handler not initialized";
|
|
5342
5138
|
var HandlerNotInitializedError = class extends Error {
|
|
@@ -5452,9 +5248,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5452
5248
|
try {
|
|
5453
5249
|
switch (message.type) {
|
|
5454
5250
|
case "CREATE_LIGHTNING_INVOICE": {
|
|
5455
|
-
const res = await this.handler.createLightningInvoice(
|
|
5456
|
-
message.payload
|
|
5457
|
-
);
|
|
5251
|
+
const res = await this.handler.createLightningInvoice(message.payload);
|
|
5458
5252
|
return this.tagged({
|
|
5459
5253
|
id,
|
|
5460
5254
|
type: "LIGHTNING_INVOICE_CREATED",
|
|
@@ -5462,9 +5256,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5462
5256
|
});
|
|
5463
5257
|
}
|
|
5464
5258
|
case "SEND_LIGHTNING_PAYMENT": {
|
|
5465
|
-
const res = await this.handler.sendLightningPayment(
|
|
5466
|
-
message.payload
|
|
5467
|
-
);
|
|
5259
|
+
const res = await this.handler.sendLightningPayment(message.payload);
|
|
5468
5260
|
return this.tagged({
|
|
5469
5261
|
id,
|
|
5470
5262
|
type: "LIGHTNING_PAYMENT_SENT",
|
|
@@ -5472,9 +5264,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5472
5264
|
});
|
|
5473
5265
|
}
|
|
5474
5266
|
case "CREATE_SUBMARINE_SWAP": {
|
|
5475
|
-
const res = await this.handler.createSubmarineSwap(
|
|
5476
|
-
message.payload
|
|
5477
|
-
);
|
|
5267
|
+
const res = await this.handler.createSubmarineSwap(message.payload);
|
|
5478
5268
|
return this.tagged({
|
|
5479
5269
|
id,
|
|
5480
5270
|
type: "SUBMARINE_SWAP_CREATED",
|
|
@@ -5482,9 +5272,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5482
5272
|
});
|
|
5483
5273
|
}
|
|
5484
5274
|
case "CREATE_REVERSE_SWAP": {
|
|
5485
|
-
const res = await this.handler.createReverseSwap(
|
|
5486
|
-
message.payload
|
|
5487
|
-
);
|
|
5275
|
+
const res = await this.handler.createReverseSwap(message.payload);
|
|
5488
5276
|
return this.tagged({
|
|
5489
5277
|
id,
|
|
5490
5278
|
type: "REVERSE_SWAP_CREATED",
|
|
@@ -5495,9 +5283,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5495
5283
|
await this.handler.claimVHTLC(message.payload);
|
|
5496
5284
|
return this.tagged({ id, type: "VHTLC_CLAIMED" });
|
|
5497
5285
|
case "REFUND_VHTLC": {
|
|
5498
|
-
const outcome = await this.handler.refundVHTLC(
|
|
5499
|
-
message.payload
|
|
5500
|
-
);
|
|
5286
|
+
const outcome = await this.handler.refundVHTLC(message.payload);
|
|
5501
5287
|
return this.tagged({
|
|
5502
5288
|
id,
|
|
5503
5289
|
type: "VHTLC_REFUNDED",
|
|
@@ -5505,9 +5291,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5505
5291
|
});
|
|
5506
5292
|
}
|
|
5507
5293
|
case "INSPECT_SUBMARINE_RECOVERY": {
|
|
5508
|
-
const info = await this.handler.inspectSubmarineRecovery(
|
|
5509
|
-
message.payload
|
|
5510
|
-
);
|
|
5294
|
+
const info = await this.handler.inspectSubmarineRecovery(message.payload);
|
|
5511
5295
|
return this.tagged({
|
|
5512
5296
|
id,
|
|
5513
5297
|
type: "SUBMARINE_RECOVERY_INSPECTED",
|
|
@@ -5523,9 +5307,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5523
5307
|
});
|
|
5524
5308
|
}
|
|
5525
5309
|
case "RECOVER_SUBMARINE_FUNDS": {
|
|
5526
|
-
const outcome = await this.handler.recoverSubmarineFunds(
|
|
5527
|
-
message.payload
|
|
5528
|
-
);
|
|
5310
|
+
const outcome = await this.handler.recoverSubmarineFunds(message.payload);
|
|
5529
5311
|
return this.tagged({
|
|
5530
5312
|
id,
|
|
5531
5313
|
type: "SUBMARINE_FUNDS_RECOVERED",
|
|
@@ -5533,9 +5315,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5533
5315
|
});
|
|
5534
5316
|
}
|
|
5535
5317
|
case "RECOVER_ALL_SUBMARINE_FUNDS": {
|
|
5536
|
-
const results = await this.handler.recoverAllSubmarineFunds(
|
|
5537
|
-
message.payload
|
|
5538
|
-
);
|
|
5318
|
+
const results = await this.handler.recoverAllSubmarineFunds(message.payload);
|
|
5539
5319
|
return this.tagged({
|
|
5540
5320
|
id,
|
|
5541
5321
|
type: "ALL_SUBMARINE_FUNDS_RECOVERED",
|
|
@@ -5543,9 +5323,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5543
5323
|
});
|
|
5544
5324
|
}
|
|
5545
5325
|
case "WAIT_AND_CLAIM": {
|
|
5546
|
-
const res = await this.handler.waitAndClaim(
|
|
5547
|
-
message.payload
|
|
5548
|
-
);
|
|
5326
|
+
const res = await this.handler.waitAndClaim(message.payload);
|
|
5549
5327
|
return this.tagged({
|
|
5550
5328
|
id,
|
|
5551
5329
|
type: "WAIT_AND_CLAIMED",
|
|
@@ -5553,9 +5331,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5553
5331
|
});
|
|
5554
5332
|
}
|
|
5555
5333
|
case "WAIT_FOR_SWAP_SETTLEMENT": {
|
|
5556
|
-
const res = await this.handler.waitForSwapSettlement(
|
|
5557
|
-
message.payload
|
|
5558
|
-
);
|
|
5334
|
+
const res = await this.handler.waitForSwapSettlement(message.payload);
|
|
5559
5335
|
return this.tagged({
|
|
5560
5336
|
id,
|
|
5561
5337
|
type: "SWAP_SETTLED",
|
|
@@ -5563,9 +5339,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5563
5339
|
});
|
|
5564
5340
|
}
|
|
5565
5341
|
case "RESTORE_SWAPS": {
|
|
5566
|
-
const res = await this.handler.restoreSwaps(
|
|
5567
|
-
message.payload
|
|
5568
|
-
);
|
|
5342
|
+
const res = await this.handler.restoreSwaps(message.payload);
|
|
5569
5343
|
return this.tagged({
|
|
5570
5344
|
id,
|
|
5571
5345
|
type: "SWAPS_RESTORED",
|
|
@@ -5595,23 +5369,15 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5595
5369
|
});
|
|
5596
5370
|
}
|
|
5597
5371
|
case "GET_FEES": {
|
|
5598
|
-
const res = message.payload ? await this.handler.getFees(
|
|
5599
|
-
message.payload.from,
|
|
5600
|
-
message.payload.to
|
|
5601
|
-
) : await this.handler.getFees();
|
|
5372
|
+
const res = message.payload ? await this.handler.getFees(message.payload.from, message.payload.to) : await this.handler.getFees();
|
|
5602
5373
|
return this.tagged({ id, type: "FEES", payload: res });
|
|
5603
5374
|
}
|
|
5604
5375
|
case "GET_LIMITS": {
|
|
5605
|
-
const res = message.payload ? await this.handler.getLimits(
|
|
5606
|
-
message.payload.from,
|
|
5607
|
-
message.payload.to
|
|
5608
|
-
) : await this.handler.getLimits();
|
|
5376
|
+
const res = message.payload ? await this.handler.getLimits(message.payload.from, message.payload.to) : await this.handler.getLimits();
|
|
5609
5377
|
return this.tagged({ id, type: "LIMITS", payload: res });
|
|
5610
5378
|
}
|
|
5611
5379
|
case "GET_SWAP_STATUS": {
|
|
5612
|
-
const res = await this.handler.getSwapStatus(
|
|
5613
|
-
message.payload.swapId
|
|
5614
|
-
);
|
|
5380
|
+
const res = await this.handler.getSwapStatus(message.payload.swapId);
|
|
5615
5381
|
return this.tagged({
|
|
5616
5382
|
id,
|
|
5617
5383
|
type: "SWAP_STATUS",
|
|
@@ -5670,9 +5436,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5670
5436
|
});
|
|
5671
5437
|
}
|
|
5672
5438
|
case "CREATE_CHAIN_SWAP": {
|
|
5673
|
-
const res = await this.handler.createChainSwap(
|
|
5674
|
-
message.payload
|
|
5675
|
-
);
|
|
5439
|
+
const res = await this.handler.createChainSwap(message.payload);
|
|
5676
5440
|
return this.tagged({
|
|
5677
5441
|
id,
|
|
5678
5442
|
type: "CHAIN_SWAP_CREATED",
|
|
@@ -5680,9 +5444,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5680
5444
|
});
|
|
5681
5445
|
}
|
|
5682
5446
|
case "WAIT_AND_CLAIM_CHAIN": {
|
|
5683
|
-
const res = await this.handler.waitAndClaimChain(
|
|
5684
|
-
message.payload
|
|
5685
|
-
);
|
|
5447
|
+
const res = await this.handler.waitAndClaimChain(message.payload);
|
|
5686
5448
|
return this.tagged({
|
|
5687
5449
|
id,
|
|
5688
5450
|
type: "CHAIN_CLAIMED",
|
|
@@ -5690,9 +5452,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5690
5452
|
});
|
|
5691
5453
|
}
|
|
5692
5454
|
case "WAIT_AND_CLAIM_ARK": {
|
|
5693
|
-
const res = await this.handler.waitAndClaimArk(
|
|
5694
|
-
message.payload
|
|
5695
|
-
);
|
|
5455
|
+
const res = await this.handler.waitAndClaimArk(message.payload);
|
|
5696
5456
|
return this.tagged({
|
|
5697
5457
|
id,
|
|
5698
5458
|
type: "ARK_CLAIMED",
|
|
@@ -5700,9 +5460,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5700
5460
|
});
|
|
5701
5461
|
}
|
|
5702
5462
|
case "WAIT_AND_CLAIM_BTC": {
|
|
5703
|
-
const res = await this.handler.waitAndClaimBtc(
|
|
5704
|
-
message.payload
|
|
5705
|
-
);
|
|
5463
|
+
const res = await this.handler.waitAndClaimBtc(message.payload);
|
|
5706
5464
|
return this.tagged({
|
|
5707
5465
|
id,
|
|
5708
5466
|
type: "BTC_CLAIMED",
|
|
@@ -5719,9 +5477,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5719
5477
|
await this.handler.refundArk(message.payload);
|
|
5720
5478
|
return this.tagged({ id, type: "ARK_REFUND_EXECUTED" });
|
|
5721
5479
|
case "SIGN_SERVER_CLAIM":
|
|
5722
|
-
await this.handler.signCooperativeClaimForServer(
|
|
5723
|
-
message.payload
|
|
5724
|
-
);
|
|
5480
|
+
await this.handler.signCooperativeClaimForServer(message.payload);
|
|
5725
5481
|
return this.tagged({ id, type: "SERVER_CLAIM_SIGNED" });
|
|
5726
5482
|
case "VERIFY_CHAIN_SWAP": {
|
|
5727
5483
|
const verified = await this.handler.verifyChainSwap({
|
|
@@ -5734,14 +5490,47 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5734
5490
|
});
|
|
5735
5491
|
}
|
|
5736
5492
|
case "QUOTE_SWAP": {
|
|
5737
|
-
|
|
5738
|
-
|
|
5739
|
-
|
|
5740
|
-
|
|
5741
|
-
|
|
5742
|
-
|
|
5743
|
-
|
|
5744
|
-
|
|
5493
|
+
try {
|
|
5494
|
+
const amount = await this.handler.quoteSwap(
|
|
5495
|
+
message.payload.swapId,
|
|
5496
|
+
message.payload.options
|
|
5497
|
+
);
|
|
5498
|
+
return this.tagged({
|
|
5499
|
+
id,
|
|
5500
|
+
type: "SWAP_QUOTED",
|
|
5501
|
+
payload: { amount }
|
|
5502
|
+
});
|
|
5503
|
+
} catch (e) {
|
|
5504
|
+
throw toQuoteTransportError(e);
|
|
5505
|
+
}
|
|
5506
|
+
}
|
|
5507
|
+
case "GET_SWAP_QUOTE": {
|
|
5508
|
+
try {
|
|
5509
|
+
const amount = await this.handler.getSwapQuote(message.payload.swapId);
|
|
5510
|
+
return this.tagged({
|
|
5511
|
+
id,
|
|
5512
|
+
type: "SWAP_QUOTE_RETRIEVED",
|
|
5513
|
+
payload: { amount }
|
|
5514
|
+
});
|
|
5515
|
+
} catch (e) {
|
|
5516
|
+
throw toQuoteTransportError(e);
|
|
5517
|
+
}
|
|
5518
|
+
}
|
|
5519
|
+
case "ACCEPT_SWAP_QUOTE": {
|
|
5520
|
+
try {
|
|
5521
|
+
const amount = await this.handler.acceptSwapQuote(
|
|
5522
|
+
message.payload.swapId,
|
|
5523
|
+
message.payload.amount,
|
|
5524
|
+
message.payload.options
|
|
5525
|
+
);
|
|
5526
|
+
return this.tagged({
|
|
5527
|
+
id,
|
|
5528
|
+
type: "SWAP_QUOTE_ACCEPTED",
|
|
5529
|
+
payload: { amount }
|
|
5530
|
+
});
|
|
5531
|
+
} catch (e) {
|
|
5532
|
+
throw toQuoteTransportError(e);
|
|
5533
|
+
}
|
|
5745
5534
|
}
|
|
5746
5535
|
/* --- SwapManager methods --- */
|
|
5747
5536
|
case "SM-START": {
|
|
@@ -5757,9 +5546,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5757
5546
|
return this.tagged({ id, type: "SM-SWAP_ADDED" });
|
|
5758
5547
|
}
|
|
5759
5548
|
case "SM-REMOVE_SWAP": {
|
|
5760
|
-
await this.getSwapManagerOrThrow().removeSwap(
|
|
5761
|
-
message.payload.swapId
|
|
5762
|
-
);
|
|
5549
|
+
await this.getSwapManagerOrThrow().removeSwap(message.payload.swapId);
|
|
5763
5550
|
return this.tagged({ id, type: "SM-SWAP_REMOVED" });
|
|
5764
5551
|
}
|
|
5765
5552
|
case "SM-GET_PENDING_SWAPS": {
|
|
@@ -5771,9 +5558,7 @@ var ArkadeSwapsMessageHandler = class _ArkadeSwapsMessageHandler {
|
|
|
5771
5558
|
});
|
|
5772
5559
|
}
|
|
5773
5560
|
case "SM-HAS_SWAP": {
|
|
5774
|
-
const has = await this.getSwapManagerOrThrow().hasSwap(
|
|
5775
|
-
message.payload.swapId
|
|
5776
|
-
);
|
|
5561
|
+
const has = await this.getSwapManagerOrThrow().hasSwap(message.payload.swapId);
|
|
5777
5562
|
return this.tagged({
|
|
5778
5563
|
id,
|
|
5779
5564
|
type: "SM-HAS_SWAP_RESULT",
|
|
@@ -5893,6 +5678,11 @@ function isMessageBusNotInitializedError(error) {
|
|
|
5893
5678
|
function isHandlerNotInitializedError(error) {
|
|
5894
5679
|
return error instanceof Error && error.message.includes(HANDLER_NOT_INITIALIZED);
|
|
5895
5680
|
}
|
|
5681
|
+
function rethrowIfQuoteRejected(error) {
|
|
5682
|
+
if (error instanceof QuoteRejectedError) throw error;
|
|
5683
|
+
const rebuilt = QuoteRejectedError.fromTransportError(error);
|
|
5684
|
+
if (rebuilt) throw rebuilt;
|
|
5685
|
+
}
|
|
5896
5686
|
var DEFAULT_MESSAGE_TIMEOUT_MS = 3e4;
|
|
5897
5687
|
var NO_MESSAGE_TIMEOUT_MS = 0;
|
|
5898
5688
|
var DEDUPABLE_REQUEST_TYPES = /* @__PURE__ */ new Set([
|
|
@@ -5949,7 +5739,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
5949
5739
|
};
|
|
5950
5740
|
const initMessage = {
|
|
5951
5741
|
tag: messageTag,
|
|
5952
|
-
id: getRandomId(),
|
|
5742
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
5953
5743
|
type: "INIT_ARKADE_SWAPS",
|
|
5954
5744
|
payload: initPayload
|
|
5955
5745
|
};
|
|
@@ -5962,7 +5752,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
5962
5752
|
throw new Error("SwapManager is not enabled.");
|
|
5963
5753
|
}
|
|
5964
5754
|
await this.sendMessage({
|
|
5965
|
-
id: getRandomId(),
|
|
5755
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
5966
5756
|
tag: this.messageTag,
|
|
5967
5757
|
type: "SM-START"
|
|
5968
5758
|
});
|
|
@@ -5970,7 +5760,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
5970
5760
|
async stopSwapManager() {
|
|
5971
5761
|
if (!this.withSwapManager) return;
|
|
5972
5762
|
await this.sendMessage({
|
|
5973
|
-
id: getRandomId(),
|
|
5763
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
5974
5764
|
tag: this.messageTag,
|
|
5975
5765
|
type: "SM-STOP"
|
|
5976
5766
|
});
|
|
@@ -5985,21 +5775,21 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
5985
5775
|
const proxy = {
|
|
5986
5776
|
start: async () => {
|
|
5987
5777
|
await send({
|
|
5988
|
-
id: getRandomId(),
|
|
5778
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
5989
5779
|
tag,
|
|
5990
5780
|
type: "SM-START"
|
|
5991
5781
|
});
|
|
5992
5782
|
},
|
|
5993
5783
|
stop: async () => {
|
|
5994
5784
|
await send({
|
|
5995
|
-
id: getRandomId(),
|
|
5785
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
5996
5786
|
tag,
|
|
5997
5787
|
type: "SM-STOP"
|
|
5998
5788
|
});
|
|
5999
5789
|
},
|
|
6000
5790
|
addSwap: async (swap) => {
|
|
6001
5791
|
await send({
|
|
6002
|
-
id: getRandomId(),
|
|
5792
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6003
5793
|
tag,
|
|
6004
5794
|
type: "SM-ADD_SWAP",
|
|
6005
5795
|
payload: swap
|
|
@@ -6007,7 +5797,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6007
5797
|
},
|
|
6008
5798
|
removeSwap: async (swapId) => {
|
|
6009
5799
|
await send({
|
|
6010
|
-
id: getRandomId(),
|
|
5800
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6011
5801
|
tag,
|
|
6012
5802
|
type: "SM-REMOVE_SWAP",
|
|
6013
5803
|
payload: { swapId }
|
|
@@ -6015,7 +5805,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6015
5805
|
},
|
|
6016
5806
|
getPendingSwaps: async () => {
|
|
6017
5807
|
const res = await send({
|
|
6018
|
-
id: getRandomId(),
|
|
5808
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6019
5809
|
tag,
|
|
6020
5810
|
type: "SM-GET_PENDING_SWAPS"
|
|
6021
5811
|
});
|
|
@@ -6023,7 +5813,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6023
5813
|
},
|
|
6024
5814
|
hasSwap: async (swapId) => {
|
|
6025
5815
|
const res = await send({
|
|
6026
|
-
id: getRandomId(),
|
|
5816
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6027
5817
|
tag,
|
|
6028
5818
|
type: "SM-HAS_SWAP",
|
|
6029
5819
|
payload: { swapId }
|
|
@@ -6032,7 +5822,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6032
5822
|
},
|
|
6033
5823
|
isProcessing: async (swapId) => {
|
|
6034
5824
|
const res = await send({
|
|
6035
|
-
id: getRandomId(),
|
|
5825
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6036
5826
|
tag,
|
|
6037
5827
|
type: "SM-IS_PROCESSING",
|
|
6038
5828
|
payload: { swapId }
|
|
@@ -6041,7 +5831,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6041
5831
|
},
|
|
6042
5832
|
getStats: async () => {
|
|
6043
5833
|
const res = await send({
|
|
6044
|
-
id: getRandomId(),
|
|
5834
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6045
5835
|
tag,
|
|
6046
5836
|
type: "SM-GET_STATS"
|
|
6047
5837
|
});
|
|
@@ -6049,7 +5839,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6049
5839
|
},
|
|
6050
5840
|
waitForSwapCompletion: async (swapId) => {
|
|
6051
5841
|
const res = await send({
|
|
6052
|
-
id: getRandomId(),
|
|
5842
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6053
5843
|
tag,
|
|
6054
5844
|
type: "SM-WAIT_FOR_COMPLETION",
|
|
6055
5845
|
payload: { swapId }
|
|
@@ -6113,7 +5903,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6113
5903
|
async createLightningInvoice(args) {
|
|
6114
5904
|
try {
|
|
6115
5905
|
const res = await this.sendMessage({
|
|
6116
|
-
id: getRandomId(),
|
|
5906
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6117
5907
|
tag: this.messageTag,
|
|
6118
5908
|
type: "CREATE_LIGHTNING_INVOICE",
|
|
6119
5909
|
payload: args
|
|
@@ -6126,7 +5916,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6126
5916
|
async sendLightningPayment(args) {
|
|
6127
5917
|
try {
|
|
6128
5918
|
const res = await this.sendMessage({
|
|
6129
|
-
id: getRandomId(),
|
|
5919
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6130
5920
|
tag: this.messageTag,
|
|
6131
5921
|
type: "SEND_LIGHTNING_PAYMENT",
|
|
6132
5922
|
payload: args
|
|
@@ -6139,7 +5929,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6139
5929
|
async createSubmarineSwap(args) {
|
|
6140
5930
|
try {
|
|
6141
5931
|
const res = await this.sendMessage({
|
|
6142
|
-
id: getRandomId(),
|
|
5932
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6143
5933
|
tag: this.messageTag,
|
|
6144
5934
|
type: "CREATE_SUBMARINE_SWAP",
|
|
6145
5935
|
payload: args
|
|
@@ -6152,7 +5942,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6152
5942
|
async createReverseSwap(args) {
|
|
6153
5943
|
try {
|
|
6154
5944
|
const res = await this.sendMessage({
|
|
6155
|
-
id: getRandomId(),
|
|
5945
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6156
5946
|
tag: this.messageTag,
|
|
6157
5947
|
type: "CREATE_REVERSE_SWAP",
|
|
6158
5948
|
payload: args
|
|
@@ -6164,7 +5954,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6164
5954
|
}
|
|
6165
5955
|
async claimVHTLC(pendingSwap) {
|
|
6166
5956
|
await this.sendMessage({
|
|
6167
|
-
id: getRandomId(),
|
|
5957
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6168
5958
|
tag: this.messageTag,
|
|
6169
5959
|
type: "CLAIM_VHTLC",
|
|
6170
5960
|
payload: pendingSwap
|
|
@@ -6172,7 +5962,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6172
5962
|
}
|
|
6173
5963
|
async refundVHTLC(pendingSwap) {
|
|
6174
5964
|
const res = await this.sendMessage({
|
|
6175
|
-
id: getRandomId(),
|
|
5965
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6176
5966
|
tag: this.messageTag,
|
|
6177
5967
|
type: "REFUND_VHTLC",
|
|
6178
5968
|
payload: pendingSwap
|
|
@@ -6181,7 +5971,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6181
5971
|
}
|
|
6182
5972
|
async inspectSubmarineRecovery(swap) {
|
|
6183
5973
|
const res = await this.sendMessage({
|
|
6184
|
-
id: getRandomId(),
|
|
5974
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6185
5975
|
tag: this.messageTag,
|
|
6186
5976
|
type: "INSPECT_SUBMARINE_RECOVERY",
|
|
6187
5977
|
payload: swap
|
|
@@ -6190,7 +5980,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6190
5980
|
}
|
|
6191
5981
|
async scanRecoverableSubmarineSwaps() {
|
|
6192
5982
|
const res = await this.sendMessage({
|
|
6193
|
-
id: getRandomId(),
|
|
5983
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6194
5984
|
tag: this.messageTag,
|
|
6195
5985
|
type: "SCAN_RECOVERABLE_SUBMARINE_SWAPS"
|
|
6196
5986
|
});
|
|
@@ -6198,7 +5988,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6198
5988
|
}
|
|
6199
5989
|
async recoverSubmarineFunds(swap) {
|
|
6200
5990
|
const res = await this.sendMessage({
|
|
6201
|
-
id: getRandomId(),
|
|
5991
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6202
5992
|
tag: this.messageTag,
|
|
6203
5993
|
type: "RECOVER_SUBMARINE_FUNDS",
|
|
6204
5994
|
payload: swap
|
|
@@ -6207,7 +5997,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6207
5997
|
}
|
|
6208
5998
|
async recoverAllSubmarineFunds(swaps) {
|
|
6209
5999
|
const res = await this.sendMessage({
|
|
6210
|
-
id: getRandomId(),
|
|
6000
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6211
6001
|
tag: this.messageTag,
|
|
6212
6002
|
type: "RECOVER_ALL_SUBMARINE_FUNDS",
|
|
6213
6003
|
payload: swaps
|
|
@@ -6217,7 +6007,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6217
6007
|
async waitAndClaim(pendingSwap) {
|
|
6218
6008
|
try {
|
|
6219
6009
|
const res = await this.sendMessage({
|
|
6220
|
-
id: getRandomId(),
|
|
6010
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6221
6011
|
tag: this.messageTag,
|
|
6222
6012
|
type: "WAIT_AND_CLAIM",
|
|
6223
6013
|
payload: pendingSwap
|
|
@@ -6232,7 +6022,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6232
6022
|
async waitForSwapSettlement(pendingSwap) {
|
|
6233
6023
|
try {
|
|
6234
6024
|
const res = await this.sendMessage({
|
|
6235
|
-
id: getRandomId(),
|
|
6025
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6236
6026
|
tag: this.messageTag,
|
|
6237
6027
|
type: "WAIT_FOR_SWAP_SETTLEMENT",
|
|
6238
6028
|
payload: pendingSwap
|
|
@@ -6245,7 +6035,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6245
6035
|
async restoreSwaps(boltzFees) {
|
|
6246
6036
|
try {
|
|
6247
6037
|
const res = await this.sendMessage({
|
|
6248
|
-
id: getRandomId(),
|
|
6038
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6249
6039
|
tag: this.messageTag,
|
|
6250
6040
|
type: "RESTORE_SWAPS",
|
|
6251
6041
|
payload: boltzFees
|
|
@@ -6258,7 +6048,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6258
6048
|
async arkToBtc(args) {
|
|
6259
6049
|
try {
|
|
6260
6050
|
const res = await this.sendMessage({
|
|
6261
|
-
id: getRandomId(),
|
|
6051
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6262
6052
|
tag: this.messageTag,
|
|
6263
6053
|
type: "ARK_TO_BTC",
|
|
6264
6054
|
payload: args
|
|
@@ -6273,7 +6063,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6273
6063
|
async btcToArk(args) {
|
|
6274
6064
|
try {
|
|
6275
6065
|
const res = await this.sendMessage({
|
|
6276
|
-
id: getRandomId(),
|
|
6066
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6277
6067
|
tag: this.messageTag,
|
|
6278
6068
|
type: "BTC_TO_ARK",
|
|
6279
6069
|
payload: args
|
|
@@ -6288,7 +6078,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6288
6078
|
async createChainSwap(args) {
|
|
6289
6079
|
try {
|
|
6290
6080
|
const res = await this.sendMessage({
|
|
6291
|
-
id: getRandomId(),
|
|
6081
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6292
6082
|
tag: this.messageTag,
|
|
6293
6083
|
type: "CREATE_CHAIN_SWAP",
|
|
6294
6084
|
payload: args
|
|
@@ -6301,7 +6091,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6301
6091
|
async waitAndClaimChain(pendingSwap) {
|
|
6302
6092
|
try {
|
|
6303
6093
|
const res = await this.sendMessage({
|
|
6304
|
-
id: getRandomId(),
|
|
6094
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6305
6095
|
tag: this.messageTag,
|
|
6306
6096
|
type: "WAIT_AND_CLAIM_CHAIN",
|
|
6307
6097
|
payload: pendingSwap
|
|
@@ -6316,7 +6106,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6316
6106
|
async waitAndClaimArk(pendingSwap) {
|
|
6317
6107
|
try {
|
|
6318
6108
|
const res = await this.sendMessage({
|
|
6319
|
-
id: getRandomId(),
|
|
6109
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6320
6110
|
tag: this.messageTag,
|
|
6321
6111
|
type: "WAIT_AND_CLAIM_ARK",
|
|
6322
6112
|
payload: pendingSwap
|
|
@@ -6331,7 +6121,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6331
6121
|
async waitAndClaimBtc(pendingSwap) {
|
|
6332
6122
|
try {
|
|
6333
6123
|
const res = await this.sendMessage({
|
|
6334
|
-
id: getRandomId(),
|
|
6124
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6335
6125
|
tag: this.messageTag,
|
|
6336
6126
|
type: "WAIT_AND_CLAIM_BTC",
|
|
6337
6127
|
payload: pendingSwap
|
|
@@ -6345,7 +6135,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6345
6135
|
}
|
|
6346
6136
|
async claimArk(pendingSwap) {
|
|
6347
6137
|
await this.sendMessage({
|
|
6348
|
-
id: getRandomId(),
|
|
6138
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6349
6139
|
tag: this.messageTag,
|
|
6350
6140
|
type: "CLAIM_ARK",
|
|
6351
6141
|
payload: pendingSwap
|
|
@@ -6353,7 +6143,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6353
6143
|
}
|
|
6354
6144
|
async claimBtc(pendingSwap) {
|
|
6355
6145
|
await this.sendMessage({
|
|
6356
|
-
id: getRandomId(),
|
|
6146
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6357
6147
|
tag: this.messageTag,
|
|
6358
6148
|
type: "CLAIM_BTC",
|
|
6359
6149
|
payload: pendingSwap
|
|
@@ -6361,7 +6151,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6361
6151
|
}
|
|
6362
6152
|
async refundArk(pendingSwap) {
|
|
6363
6153
|
await this.sendMessage({
|
|
6364
|
-
id: getRandomId(),
|
|
6154
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6365
6155
|
tag: this.messageTag,
|
|
6366
6156
|
type: "REFUND_ARK",
|
|
6367
6157
|
payload: pendingSwap
|
|
@@ -6369,7 +6159,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6369
6159
|
}
|
|
6370
6160
|
async signCooperativeClaimForServer(pendingSwap) {
|
|
6371
6161
|
await this.sendMessage({
|
|
6372
|
-
id: getRandomId(),
|
|
6162
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6373
6163
|
tag: this.messageTag,
|
|
6374
6164
|
type: "SIGN_SERVER_CLAIM",
|
|
6375
6165
|
payload: pendingSwap
|
|
@@ -6378,7 +6168,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6378
6168
|
async verifyChainSwap(args) {
|
|
6379
6169
|
try {
|
|
6380
6170
|
const res = await this.sendMessage({
|
|
6381
|
-
id: getRandomId(),
|
|
6171
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6382
6172
|
tag: this.messageTag,
|
|
6383
6173
|
type: "VERIFY_CHAIN_SWAP",
|
|
6384
6174
|
payload: {
|
|
@@ -6393,19 +6183,48 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6393
6183
|
throw new Error("Cannot verify chain swap", { cause: e });
|
|
6394
6184
|
}
|
|
6395
6185
|
}
|
|
6396
|
-
async quoteSwap(swapId) {
|
|
6186
|
+
async quoteSwap(swapId, options) {
|
|
6397
6187
|
try {
|
|
6398
6188
|
const res = await this.sendMessage({
|
|
6399
|
-
id: getRandomId(),
|
|
6189
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6400
6190
|
tag: this.messageTag,
|
|
6401
6191
|
type: "QUOTE_SWAP",
|
|
6402
|
-
payload: { swapId }
|
|
6192
|
+
payload: { swapId, options }
|
|
6403
6193
|
});
|
|
6404
6194
|
return res.payload.amount;
|
|
6405
6195
|
} catch (e) {
|
|
6196
|
+
rethrowIfQuoteRejected(e);
|
|
6406
6197
|
throw new Error("Cannot quote swap", { cause: e });
|
|
6407
6198
|
}
|
|
6408
6199
|
}
|
|
6200
|
+
async getSwapQuote(swapId) {
|
|
6201
|
+
try {
|
|
6202
|
+
const res = await this.sendMessage({
|
|
6203
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6204
|
+
tag: this.messageTag,
|
|
6205
|
+
type: "GET_SWAP_QUOTE",
|
|
6206
|
+
payload: { swapId }
|
|
6207
|
+
});
|
|
6208
|
+
return res.payload.amount;
|
|
6209
|
+
} catch (e) {
|
|
6210
|
+
rethrowIfQuoteRejected(e);
|
|
6211
|
+
throw new Error("Cannot get swap quote", { cause: e });
|
|
6212
|
+
}
|
|
6213
|
+
}
|
|
6214
|
+
async acceptSwapQuote(swapId, amount, options) {
|
|
6215
|
+
try {
|
|
6216
|
+
const res = await this.sendMessage({
|
|
6217
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6218
|
+
tag: this.messageTag,
|
|
6219
|
+
type: "ACCEPT_SWAP_QUOTE",
|
|
6220
|
+
payload: { swapId, amount, options }
|
|
6221
|
+
});
|
|
6222
|
+
return res.payload.amount;
|
|
6223
|
+
} catch (e) {
|
|
6224
|
+
rethrowIfQuoteRejected(e);
|
|
6225
|
+
throw new Error("Cannot accept swap quote", { cause: e });
|
|
6226
|
+
}
|
|
6227
|
+
}
|
|
6409
6228
|
enrichReverseSwapPreimage(swap, preimage) {
|
|
6410
6229
|
return enrichReverseSwapPreimage(swap, preimage);
|
|
6411
6230
|
}
|
|
@@ -6413,9 +6232,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6413
6232
|
return enrichSubmarineSwapInvoice(swap, invoice);
|
|
6414
6233
|
}
|
|
6415
6234
|
createVHTLCScript(_args) {
|
|
6416
|
-
throw new Error(
|
|
6417
|
-
"createVHTLCScript is not supported via service worker"
|
|
6418
|
-
);
|
|
6235
|
+
throw new Error("createVHTLCScript is not supported via service worker");
|
|
6419
6236
|
}
|
|
6420
6237
|
async joinBatch(_identity, _input, _output, _arkInfo, _isRecoverable = true) {
|
|
6421
6238
|
throw new Error("joinBatch is not supported via service worker");
|
|
@@ -6426,7 +6243,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6426
6243
|
}
|
|
6427
6244
|
try {
|
|
6428
6245
|
const res = await this.sendMessage({
|
|
6429
|
-
id: getRandomId(),
|
|
6246
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6430
6247
|
tag: this.messageTag,
|
|
6431
6248
|
type: "GET_FEES",
|
|
6432
6249
|
...from !== void 0 && to !== void 0 ? { payload: { from, to } } : {}
|
|
@@ -6442,7 +6259,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6442
6259
|
}
|
|
6443
6260
|
try {
|
|
6444
6261
|
const res = await this.sendMessage({
|
|
6445
|
-
id: getRandomId(),
|
|
6262
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6446
6263
|
tag: this.messageTag,
|
|
6447
6264
|
type: "GET_LIMITS",
|
|
6448
6265
|
...from !== void 0 && to !== void 0 ? { payload: { from, to } } : {}
|
|
@@ -6455,7 +6272,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6455
6272
|
async getSwapStatus(swapId) {
|
|
6456
6273
|
try {
|
|
6457
6274
|
const res = await this.sendMessage({
|
|
6458
|
-
id: getRandomId(),
|
|
6275
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6459
6276
|
tag: this.messageTag,
|
|
6460
6277
|
type: "GET_SWAP_STATUS",
|
|
6461
6278
|
payload: { swapId }
|
|
@@ -6468,7 +6285,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6468
6285
|
async getPendingSubmarineSwaps() {
|
|
6469
6286
|
try {
|
|
6470
6287
|
const res = await this.sendMessage({
|
|
6471
|
-
id: getRandomId(),
|
|
6288
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6472
6289
|
tag: this.messageTag,
|
|
6473
6290
|
type: "GET_PENDING_SUBMARINE_SWAPS"
|
|
6474
6291
|
});
|
|
@@ -6482,7 +6299,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6482
6299
|
async getPendingReverseSwaps() {
|
|
6483
6300
|
try {
|
|
6484
6301
|
const res = await this.sendMessage({
|
|
6485
|
-
id: getRandomId(),
|
|
6302
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6486
6303
|
tag: this.messageTag,
|
|
6487
6304
|
type: "GET_PENDING_REVERSE_SWAPS"
|
|
6488
6305
|
});
|
|
@@ -6494,7 +6311,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6494
6311
|
async getPendingChainSwaps() {
|
|
6495
6312
|
try {
|
|
6496
6313
|
const res = await this.sendMessage({
|
|
6497
|
-
id: getRandomId(),
|
|
6314
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6498
6315
|
tag: this.messageTag,
|
|
6499
6316
|
type: "GET_PENDING_CHAIN_SWAPS"
|
|
6500
6317
|
});
|
|
@@ -6506,7 +6323,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6506
6323
|
async getSwapHistory() {
|
|
6507
6324
|
try {
|
|
6508
6325
|
const res = await this.sendMessage({
|
|
6509
|
-
id: getRandomId(),
|
|
6326
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6510
6327
|
tag: this.messageTag,
|
|
6511
6328
|
type: "GET_SWAP_HISTORY"
|
|
6512
6329
|
});
|
|
@@ -6517,7 +6334,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6517
6334
|
}
|
|
6518
6335
|
async refreshSwapsStatus() {
|
|
6519
6336
|
await this.sendMessage({
|
|
6520
|
-
id: getRandomId(),
|
|
6337
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6521
6338
|
tag: this.messageTag,
|
|
6522
6339
|
type: "REFRESH_SWAPS_STATUS"
|
|
6523
6340
|
});
|
|
@@ -6545,10 +6362,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6545
6362
|
return new Promise((resolve, reject) => {
|
|
6546
6363
|
const cleanup = () => {
|
|
6547
6364
|
clearTimeout(timeoutId);
|
|
6548
|
-
navigator.serviceWorker.removeEventListener(
|
|
6549
|
-
"message",
|
|
6550
|
-
messageHandler
|
|
6551
|
-
);
|
|
6365
|
+
navigator.serviceWorker.removeEventListener("message", messageHandler);
|
|
6552
6366
|
};
|
|
6553
6367
|
const timeoutId = timeoutMs > 0 ? setTimeout(() => {
|
|
6554
6368
|
cleanup();
|
|
@@ -6590,21 +6404,14 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6590
6404
|
pingServiceWorker() {
|
|
6591
6405
|
if (this.pingPromise) return this.pingPromise;
|
|
6592
6406
|
this.pingPromise = new Promise((resolve, reject) => {
|
|
6593
|
-
const pingId = getRandomId();
|
|
6407
|
+
const pingId = (0, import_sdk10.getRandomId)();
|
|
6594
6408
|
const cleanup = () => {
|
|
6595
6409
|
clearTimeout(timeoutId);
|
|
6596
|
-
navigator.serviceWorker.removeEventListener(
|
|
6597
|
-
"message",
|
|
6598
|
-
onMessage
|
|
6599
|
-
);
|
|
6410
|
+
navigator.serviceWorker.removeEventListener("message", onMessage);
|
|
6600
6411
|
};
|
|
6601
6412
|
const timeoutId = setTimeout(() => {
|
|
6602
6413
|
cleanup();
|
|
6603
|
-
reject(
|
|
6604
|
-
new import_sdk10.ServiceWorkerTimeoutError(
|
|
6605
|
-
"Service worker ping timed out"
|
|
6606
|
-
)
|
|
6607
|
-
);
|
|
6414
|
+
reject(new import_sdk10.ServiceWorkerTimeoutError("Service worker ping timed out"));
|
|
6608
6415
|
}, 2e3);
|
|
6609
6416
|
const onMessage = (event) => {
|
|
6610
6417
|
if (event.data?.id === pingId && event.data?.tag === "PONG") {
|
|
@@ -6632,9 +6439,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6632
6439
|
await this.reinitialize();
|
|
6633
6440
|
}
|
|
6634
6441
|
}
|
|
6635
|
-
const timeoutMs = LONG_RUNNING_ARKADE_SWAPS_REQUEST_TYPES.has(
|
|
6636
|
-
request.type
|
|
6637
|
-
) ? NO_MESSAGE_TIMEOUT_MS : DEFAULT_MESSAGE_TIMEOUT_MS;
|
|
6442
|
+
const timeoutMs = LONG_RUNNING_ARKADE_SWAPS_REQUEST_TYPES.has(request.type) ? NO_MESSAGE_TIMEOUT_MS : DEFAULT_MESSAGE_TIMEOUT_MS;
|
|
6638
6443
|
const maxRetries = 2;
|
|
6639
6444
|
for (let attempt = 0; ; attempt++) {
|
|
6640
6445
|
try {
|
|
@@ -6657,13 +6462,10 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6657
6462
|
const initMessage = {
|
|
6658
6463
|
tag: this.messageTag,
|
|
6659
6464
|
type: "INIT_ARKADE_SWAPS",
|
|
6660
|
-
id: getRandomId(),
|
|
6465
|
+
id: (0, import_sdk10.getRandomId)(),
|
|
6661
6466
|
payload: this.initPayload
|
|
6662
6467
|
};
|
|
6663
|
-
await this.sendMessageDirect(
|
|
6664
|
-
initMessage,
|
|
6665
|
-
DEFAULT_MESSAGE_TIMEOUT_MS
|
|
6666
|
-
);
|
|
6468
|
+
await this.sendMessageDirect(initMessage, DEFAULT_MESSAGE_TIMEOUT_MS);
|
|
6667
6469
|
})().finally(() => {
|
|
6668
6470
|
this.reinitPromise = null;
|
|
6669
6471
|
});
|
|
@@ -6672,10 +6474,7 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6672
6474
|
initEventStream() {
|
|
6673
6475
|
if (this.eventListenerInitialized) return;
|
|
6674
6476
|
this.eventListenerInitialized = true;
|
|
6675
|
-
navigator.serviceWorker.addEventListener(
|
|
6676
|
-
"message",
|
|
6677
|
-
this.handleEventMessage
|
|
6678
|
-
);
|
|
6477
|
+
navigator.serviceWorker.addEventListener("message", this.handleEventMessage);
|
|
6679
6478
|
}
|
|
6680
6479
|
handleEventMessage = (event) => {
|
|
6681
6480
|
const data = event.data;
|
|
@@ -6722,9 +6521,6 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
|
|
|
6722
6521
|
}
|
|
6723
6522
|
};
|
|
6724
6523
|
};
|
|
6725
|
-
function getRandomId() {
|
|
6726
|
-
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
6727
|
-
}
|
|
6728
6524
|
|
|
6729
6525
|
// src/repositories/migrationFromContracts.ts
|
|
6730
6526
|
var MIGRATION_KEY = "migration-from-storage-adapter-swaps";
|
|
@@ -6734,8 +6530,14 @@ async function migrateToSwapRepository(storageAdapter, fresh) {
|
|
|
6734
6530
|
if (migration === "done") {
|
|
6735
6531
|
return false;
|
|
6736
6532
|
}
|
|
6737
|
-
const reverseSwaps = await getContractCollection(
|
|
6738
|
-
|
|
6533
|
+
const reverseSwaps = await getContractCollection(
|
|
6534
|
+
storageAdapter,
|
|
6535
|
+
"reverseSwaps"
|
|
6536
|
+
);
|
|
6537
|
+
const submarineSwaps = await getContractCollection(
|
|
6538
|
+
storageAdapter,
|
|
6539
|
+
"submarineSwaps"
|
|
6540
|
+
);
|
|
6739
6541
|
for (const swap of reverseSwaps) {
|
|
6740
6542
|
await fresh.saveSwap(swap);
|
|
6741
6543
|
}
|
|
@@ -6745,9 +6547,7 @@ async function migrateToSwapRepository(storageAdapter, fresh) {
|
|
|
6745
6547
|
await storageAdapter.setItem(MIGRATION_KEY, "done");
|
|
6746
6548
|
return true;
|
|
6747
6549
|
} catch (error) {
|
|
6748
|
-
if (error instanceof Error && error.message.includes(
|
|
6749
|
-
"One of the specified object stores was not found."
|
|
6750
|
-
)) {
|
|
6550
|
+
if (error instanceof Error && error.message.includes("One of the specified object stores was not found.")) {
|
|
6751
6551
|
return false;
|
|
6752
6552
|
}
|
|
6753
6553
|
throw error;
|
|
@@ -6778,6 +6578,7 @@ async function getContractCollection(storage, contractType) {
|
|
|
6778
6578
|
InvoiceFailedToPayError,
|
|
6779
6579
|
NetworkError,
|
|
6780
6580
|
PreimageFetchError,
|
|
6581
|
+
QuoteRejectedError,
|
|
6781
6582
|
SchemaError,
|
|
6782
6583
|
ServiceWorkerArkadeLightning,
|
|
6783
6584
|
ServiceWorkerArkadeSwaps,
|