@arkade-os/boltz-swap 0.3.8 → 0.3.10

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.
@@ -1,5 +1,5 @@
1
1
  import { IWallet, ArkProvider, IndexerProvider, ArkInfo, Identity, ArkTxInput, VHTLC } from '@arkade-os/sdk';
2
- import { l as BoltzSwapProvider, V as SwapManager, i as SwapRepository, X as ArkadeSwapsCreateConfig, A as ArkadeSwapsConfig, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, b as PendingReverseSwap, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, h as ArkToBtcResponse, a as PendingChainSwap, B as BtcToArkResponse, d as Chain, F as FeesResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from './types-DCCYGYCD.js';
2
+ import { l as BoltzSwapProvider, V as SwapManager, i as SwapRepository, X as ArkadeSwapsCreateConfig, A as ArkadeSwapsConfig, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, b as PendingReverseSwap, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, h as ArkToBtcResponse, a as PendingChainSwap, B as BtcToArkResponse, d as Chain, F as FeesResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from './types-CEmBBA71.cjs';
3
3
  import { TransactionOutput } from '@scure/btc-signer/psbt.js';
4
4
 
5
5
  /**
@@ -68,6 +68,13 @@ declare class ArkadeSwaps {
68
68
  * Dispose of resources (stops SwapManager and cleans up).
69
69
  * Can be called manually or automatically with `await using` syntax (TypeScript 5.2+).
70
70
  */
71
+ /**
72
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
73
+ *
74
+ * **Destructive** — any swap in a non-terminal state will lose its
75
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
76
+ */
77
+ reset(): Promise<void>;
71
78
  dispose(): Promise<void>;
72
79
  /**
73
80
  * Symbol.asyncDispose for automatic cleanup with `await using` syntax.
@@ -426,6 +433,13 @@ interface IArkadeSwaps extends AsyncDisposable {
426
433
  getSwapStatus(swapId: string): Promise<GetSwapStatusResponse>;
427
434
  enrichReverseSwapPreimage(swap: PendingReverseSwap, preimage: string): PendingReverseSwap;
428
435
  enrichSubmarineSwapInvoice(swap: PendingSubmarineSwap, invoice: string): PendingSubmarineSwap;
436
+ /**
437
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
438
+ *
439
+ * **Destructive** — any swap in a non-terminal state will lose its
440
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
441
+ */
442
+ reset(): Promise<void>;
429
443
  dispose(): Promise<void>;
430
444
  }
431
445
 
@@ -1,5 +1,5 @@
1
1
  import { IWallet, ArkProvider, IndexerProvider, ArkInfo, Identity, ArkTxInput, VHTLC } from '@arkade-os/sdk';
2
- import { l as BoltzSwapProvider, V as SwapManager, i as SwapRepository, X as ArkadeSwapsCreateConfig, A as ArkadeSwapsConfig, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, b as PendingReverseSwap, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, h as ArkToBtcResponse, a as PendingChainSwap, B as BtcToArkResponse, d as Chain, F as FeesResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from './types-DCCYGYCD.cjs';
2
+ import { l as BoltzSwapProvider, V as SwapManager, i as SwapRepository, X as ArkadeSwapsCreateConfig, A as ArkadeSwapsConfig, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, b as PendingReverseSwap, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, h as ArkToBtcResponse, a as PendingChainSwap, B as BtcToArkResponse, d as Chain, F as FeesResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from './types-CEmBBA71.js';
3
3
  import { TransactionOutput } from '@scure/btc-signer/psbt.js';
4
4
 
5
5
  /**
@@ -68,6 +68,13 @@ declare class ArkadeSwaps {
68
68
  * Dispose of resources (stops SwapManager and cleans up).
69
69
  * Can be called manually or automatically with `await using` syntax (TypeScript 5.2+).
70
70
  */
71
+ /**
72
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
73
+ *
74
+ * **Destructive** — any swap in a non-terminal state will lose its
75
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
76
+ */
77
+ reset(): Promise<void>;
71
78
  dispose(): Promise<void>;
72
79
  /**
73
80
  * Symbol.asyncDispose for automatic cleanup with `await using` syntax.
@@ -426,6 +433,13 @@ interface IArkadeSwaps extends AsyncDisposable {
426
433
  getSwapStatus(swapId: string): Promise<GetSwapStatusResponse>;
427
434
  enrichReverseSwapPreimage(swap: PendingReverseSwap, preimage: string): PendingReverseSwap;
428
435
  enrichSubmarineSwapInvoice(swap: PendingSubmarineSwap, invoice: string): PendingSubmarineSwap;
436
+ /**
437
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
438
+ *
439
+ * **Destructive** — any swap in a non-terminal state will lose its
440
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
441
+ */
442
+ reset(): Promise<void>;
429
443
  dispose(): Promise<void>;
430
444
  }
431
445
 
@@ -2,8 +2,8 @@ import {
2
2
  defineExpoSwapBackgroundTask,
3
3
  registerExpoSwapBackgroundTask,
4
4
  unregisterExpoSwapBackgroundTask
5
- } from "./chunk-XUBVFCQZ.js";
6
- import "./chunk-ZJ2Q5QSA.js";
5
+ } from "./chunk-QGPE6POI.js";
6
+ import "./chunk-NTTONVRX.js";
7
7
  import "./chunk-3RG5ZIWI.js";
8
8
  export {
9
9
  defineExpoSwapBackgroundTask,
@@ -865,6 +865,8 @@ var SwapManager = class {
865
865
  // All swaps passed to start(), including completed ones
866
866
  pollTimer = null;
867
867
  reconnectTimer = null;
868
+ initialPollTimer = null;
869
+ pollRetryTimers = /* @__PURE__ */ new Map();
868
870
  isRunning = false;
869
871
  currentReconnectDelay;
870
872
  currentPollRetryDelay;
@@ -1048,6 +1050,14 @@ var SwapManager = class {
1048
1050
  clearTimeout(this.reconnectTimer);
1049
1051
  this.reconnectTimer = null;
1050
1052
  }
1053
+ if (this.initialPollTimer) {
1054
+ clearTimeout(this.initialPollTimer);
1055
+ this.initialPollTimer = null;
1056
+ }
1057
+ for (const timer of this.pollRetryTimers.values()) {
1058
+ clearTimeout(timer);
1059
+ }
1060
+ this.pollRetryTimers.clear();
1051
1061
  }
1052
1062
  /**
1053
1063
  * Set the polling interval (ms).
@@ -1103,6 +1113,11 @@ var SwapManager = class {
1103
1113
  async removeSwap(swapId) {
1104
1114
  this.monitoredSwaps.delete(swapId);
1105
1115
  this.swapSubscriptions.delete(swapId);
1116
+ const retryTimer = this.pollRetryTimers.get(swapId);
1117
+ if (retryTimer) {
1118
+ clearTimeout(retryTimer);
1119
+ this.pollRetryTimers.delete(swapId);
1120
+ }
1106
1121
  logger.log(`Removed swap ${swapId} from monitoring`);
1107
1122
  }
1108
1123
  /**
@@ -1253,12 +1268,25 @@ var SwapManager = class {
1253
1268
  for (const swapId of this.monitoredSwaps.keys()) {
1254
1269
  this.subscribeToSwap(swapId);
1255
1270
  }
1256
- this.pollAllSwaps();
1271
+ if (this.initialPollTimer) {
1272
+ clearTimeout(this.initialPollTimer);
1273
+ this.initialPollTimer = null;
1274
+ }
1275
+ this.initialPollTimer = setTimeout(() => {
1276
+ this.initialPollTimer = null;
1277
+ if (this.isRunning) {
1278
+ this.pollAllSwaps();
1279
+ }
1280
+ }, 2e3);
1257
1281
  this.startPolling();
1258
1282
  this.wsConnectedListeners.forEach((listener) => listener());
1259
1283
  };
1260
1284
  this.websocket.onclose = () => {
1261
1285
  clearTimeout(connectionTimeout);
1286
+ if (this.initialPollTimer) {
1287
+ clearTimeout(this.initialPollTimer);
1288
+ this.initialPollTimer = null;
1289
+ }
1262
1290
  this.websocket = null;
1263
1291
  if (this.isRunning) {
1264
1292
  this.scheduleReconnect();
@@ -1287,6 +1315,10 @@ var SwapManager = class {
1287
1315
  */
1288
1316
  enterPollingFallback(error) {
1289
1317
  if (!this.isRunning) return;
1318
+ if (this.initialPollTimer) {
1319
+ clearTimeout(this.initialPollTimer);
1320
+ this.initialPollTimer = null;
1321
+ }
1290
1322
  this.isReconnecting = false;
1291
1323
  this.websocket = null;
1292
1324
  this.usePollingFallback = true;
@@ -1388,6 +1420,11 @@ var SwapManager = class {
1388
1420
  if (this.isFinalStatus(swap)) {
1389
1421
  this.monitoredSwaps.delete(swap.id);
1390
1422
  this.swapSubscriptions.delete(swap.id);
1423
+ const retryTimer = this.pollRetryTimers.get(swap.id);
1424
+ if (retryTimer) {
1425
+ clearTimeout(retryTimer);
1426
+ this.pollRetryTimers.delete(swap.id);
1427
+ }
1391
1428
  this.swapCompletedListeners.forEach((listener) => listener(swap));
1392
1429
  }
1393
1430
  }
@@ -1652,7 +1689,37 @@ var SwapManager = class {
1652
1689
  );
1653
1690
  }
1654
1691
  } catch (error) {
1655
- logger.error(`Failed to poll swap ${swap.id}:`, error);
1692
+ if (error instanceof NetworkError && error.statusCode === 429) {
1693
+ logger.warn(
1694
+ `Rate-limited polling swap ${swap.id}, retrying in 2s`
1695
+ );
1696
+ const existing = this.pollRetryTimers.get(swap.id);
1697
+ if (existing) clearTimeout(existing);
1698
+ this.pollRetryTimers.set(
1699
+ swap.id,
1700
+ setTimeout(async () => {
1701
+ this.pollRetryTimers.delete(swap.id);
1702
+ try {
1703
+ const retry = await this.swapProvider.getSwapStatus(
1704
+ swap.id
1705
+ );
1706
+ if (retry.status !== swap.status) {
1707
+ await this.handleSwapStatusUpdate(
1708
+ swap,
1709
+ retry.status
1710
+ );
1711
+ }
1712
+ } catch (retryError) {
1713
+ logger.error(
1714
+ `Retry poll for swap ${swap.id} also failed:`,
1715
+ retryError
1716
+ );
1717
+ }
1718
+ }, 2e3)
1719
+ );
1720
+ } else {
1721
+ logger.error(`Failed to poll swap ${swap.id}:`, error);
1722
+ }
1656
1723
  }
1657
1724
  }
1658
1725
  );
@@ -3039,6 +3106,16 @@ var ArkadeSwaps = class _ArkadeSwaps {
3039
3106
  * Dispose of resources (stops SwapManager and cleans up).
3040
3107
  * Can be called manually or automatically with `await using` syntax (TypeScript 5.2+).
3041
3108
  */
3109
+ /**
3110
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
3111
+ *
3112
+ * **Destructive** — any swap in a non-terminal state will lose its
3113
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
3114
+ */
3115
+ async reset() {
3116
+ await this.dispose();
3117
+ await this.swapRepository.clear();
3118
+ }
3042
3119
  async dispose() {
3043
3120
  if (this.swapManager) {
3044
3121
  await this.stopSwapManager();
@@ -3362,21 +3439,6 @@ var ArkadeSwaps = class _ArkadeSwaps {
3362
3439
  const preimageHash = pendingSwap.request.invoice ? getInvoicePaymentHash(pendingSwap.request.invoice) : pendingSwap.preimageHash;
3363
3440
  if (!preimageHash)
3364
3441
  throw new Error("Preimage hash is required to refund VHTLC");
3365
- const vhtlcPkScript = ArkAddress2.decode(
3366
- pendingSwap.response.address
3367
- ).pkScript;
3368
- const { vtxos } = await this.indexerProvider.getVtxos({
3369
- scripts: [hex8.encode(vhtlcPkScript)]
3370
- });
3371
- if (vtxos.length === 0) {
3372
- throw new Error(
3373
- `VHTLC not found for address ${pendingSwap.response.address}`
3374
- );
3375
- }
3376
- const vtxo = vtxos[0];
3377
- if (vtxo.isSpent) {
3378
- throw new Error("VHTLC is already spent");
3379
- }
3380
3442
  const arkInfo = await this.arkProvider.getInfo();
3381
3443
  const address = await this.wallet.getAddress();
3382
3444
  if (!address) throw new Error("Failed to get ark address from wallet");
@@ -3395,7 +3457,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
3395
3457
  "boltz",
3396
3458
  pendingSwap.id
3397
3459
  );
3398
- const { vhtlcScript } = this.createVHTLCScript({
3460
+ const { vhtlcScript, vhtlcAddress } = this.createVHTLCScript({
3399
3461
  network: arkInfo.network,
3400
3462
  preimageHash: hex8.decode(preimageHash),
3401
3463
  receiverPubkey: hex8.encode(boltzXOnlyPublicKey),
@@ -3405,32 +3467,64 @@ var ArkadeSwaps = class _ArkadeSwaps {
3405
3467
  });
3406
3468
  if (!vhtlcScript.claimScript)
3407
3469
  throw new Error("Failed to create VHTLC script for submarine swap");
3408
- const isRecoverableVtxo = isRecoverable(vtxo);
3409
- const input = {
3410
- ...vtxo,
3411
- tapLeafScript: isRecoverableVtxo ? vhtlcScript.refundWithoutReceiver() : vhtlcScript.refund(),
3412
- tapTree: vhtlcScript.encode()
3413
- };
3414
- const output = {
3415
- amount: BigInt(vtxo.value),
3416
- script: ArkAddress2.decode(address).pkScript
3417
- };
3418
- if (isRecoverableVtxo) {
3419
- await this.joinBatch(this.wallet.identity, input, output, arkInfo);
3420
- } else {
3421
- await refundVHTLCwithOffchainTx(
3422
- pendingSwap.id,
3423
- this.wallet.identity,
3424
- this.arkProvider,
3425
- boltzXOnlyPublicKey,
3426
- ourXOnlyPublicKey,
3427
- serverXOnlyPublicKey,
3428
- input,
3429
- output,
3430
- arkInfo,
3431
- this.swapProvider.refundSubmarineSwap.bind(this.swapProvider)
3470
+ if (vhtlcAddress !== pendingSwap.response.address)
3471
+ throw new Error(
3472
+ `VHTLC address mismatch for swap ${pendingSwap.id}: expected ${pendingSwap.response.address}, got ${vhtlcAddress}`
3473
+ );
3474
+ const vhtlcPkScriptHex = hex8.encode(vhtlcScript.pkScript);
3475
+ const { vtxos: spendableVtxos } = await this.indexerProvider.getVtxos({
3476
+ scripts: [vhtlcPkScriptHex],
3477
+ spendableOnly: true
3478
+ });
3479
+ if (spendableVtxos.length === 0) {
3480
+ const { vtxos: allVtxos } = await this.indexerProvider.getVtxos({
3481
+ scripts: [vhtlcPkScriptHex]
3482
+ });
3483
+ throw new Error(
3484
+ allVtxos.length > 0 ? "VHTLC is already spent" : `VHTLC not found for address ${pendingSwap.response.address}`
3432
3485
  );
3433
3486
  }
3487
+ const outputScript = ArkAddress2.decode(address).pkScript;
3488
+ let boltzCallCount = 0;
3489
+ for (const vtxo of spendableVtxos) {
3490
+ const isRecoverableVtxo = isRecoverable(vtxo);
3491
+ const input = {
3492
+ ...vtxo,
3493
+ tapLeafScript: isRecoverableVtxo ? vhtlcScript.refundWithoutReceiver() : vhtlcScript.refund(),
3494
+ tapTree: vhtlcScript.encode()
3495
+ };
3496
+ const output = {
3497
+ amount: BigInt(vtxo.value),
3498
+ script: outputScript
3499
+ };
3500
+ if (isRecoverableVtxo) {
3501
+ await this.joinBatch(
3502
+ this.wallet.identity,
3503
+ input,
3504
+ output,
3505
+ arkInfo
3506
+ );
3507
+ } else {
3508
+ if (boltzCallCount > 0) {
3509
+ await new Promise((r) => setTimeout(r, 2e3));
3510
+ }
3511
+ await refundVHTLCwithOffchainTx(
3512
+ pendingSwap.id,
3513
+ this.wallet.identity,
3514
+ this.arkProvider,
3515
+ boltzXOnlyPublicKey,
3516
+ ourXOnlyPublicKey,
3517
+ serverXOnlyPublicKey,
3518
+ input,
3519
+ output,
3520
+ arkInfo,
3521
+ this.swapProvider.refundSubmarineSwap.bind(
3522
+ this.swapProvider
3523
+ )
3524
+ );
3525
+ boltzCallCount++;
3526
+ }
3527
+ }
3434
3528
  await updateSubmarineSwapStatus(
3435
3529
  pendingSwap,
3436
3530
  pendingSwap.status,
@@ -4409,16 +4503,18 @@ var ArkadeSwaps = class _ArkadeSwaps {
4409
4503
  } else if (isRestoredSubmarineSwap(swap)) {
4410
4504
  const { amount, lockupAddress, serverPublicKey, tree } = swap.refundDetails;
4411
4505
  let preimage = "";
4412
- try {
4413
- const data = await this.swapProvider.getSwapPreimage(
4414
- swap.id
4415
- );
4416
- preimage = data.preimage;
4417
- } catch (error) {
4418
- logger.warn(
4419
- `Failed to restore preimage for submarine swap ${id}`,
4420
- error
4421
- );
4506
+ if (!isSubmarineFinalStatus(status)) {
4507
+ try {
4508
+ const data = await this.swapProvider.getSwapPreimage(
4509
+ swap.id
4510
+ );
4511
+ preimage = data.preimage;
4512
+ } catch (error) {
4513
+ logger.warn(
4514
+ `Failed to restore preimage for submarine swap ${id}`,
4515
+ error
4516
+ );
4517
+ }
4422
4518
  }
4423
4519
  submarineSwaps.push({
4424
4520
  id,
@@ -8,7 +8,7 @@ import {
8
8
  isSubmarineFinalStatus,
9
9
  isSubmarineSwapRefundable,
10
10
  logger
11
- } from "./chunk-ZJ2Q5QSA.js";
11
+ } from "./chunk-NTTONVRX.js";
12
12
  import {
13
13
  __require
14
14
  } from "./chunk-3RG5ZIWI.js";
@@ -1277,6 +1277,8 @@ var init_swap_manager = __esm({
1277
1277
  // All swaps passed to start(), including completed ones
1278
1278
  pollTimer = null;
1279
1279
  reconnectTimer = null;
1280
+ initialPollTimer = null;
1281
+ pollRetryTimers = /* @__PURE__ */ new Map();
1280
1282
  isRunning = false;
1281
1283
  currentReconnectDelay;
1282
1284
  currentPollRetryDelay;
@@ -1460,6 +1462,14 @@ var init_swap_manager = __esm({
1460
1462
  clearTimeout(this.reconnectTimer);
1461
1463
  this.reconnectTimer = null;
1462
1464
  }
1465
+ if (this.initialPollTimer) {
1466
+ clearTimeout(this.initialPollTimer);
1467
+ this.initialPollTimer = null;
1468
+ }
1469
+ for (const timer of this.pollRetryTimers.values()) {
1470
+ clearTimeout(timer);
1471
+ }
1472
+ this.pollRetryTimers.clear();
1463
1473
  }
1464
1474
  /**
1465
1475
  * Set the polling interval (ms).
@@ -1515,6 +1525,11 @@ var init_swap_manager = __esm({
1515
1525
  async removeSwap(swapId) {
1516
1526
  this.monitoredSwaps.delete(swapId);
1517
1527
  this.swapSubscriptions.delete(swapId);
1528
+ const retryTimer = this.pollRetryTimers.get(swapId);
1529
+ if (retryTimer) {
1530
+ clearTimeout(retryTimer);
1531
+ this.pollRetryTimers.delete(swapId);
1532
+ }
1518
1533
  logger.log(`Removed swap ${swapId} from monitoring`);
1519
1534
  }
1520
1535
  /**
@@ -1665,12 +1680,25 @@ var init_swap_manager = __esm({
1665
1680
  for (const swapId of this.monitoredSwaps.keys()) {
1666
1681
  this.subscribeToSwap(swapId);
1667
1682
  }
1668
- this.pollAllSwaps();
1683
+ if (this.initialPollTimer) {
1684
+ clearTimeout(this.initialPollTimer);
1685
+ this.initialPollTimer = null;
1686
+ }
1687
+ this.initialPollTimer = setTimeout(() => {
1688
+ this.initialPollTimer = null;
1689
+ if (this.isRunning) {
1690
+ this.pollAllSwaps();
1691
+ }
1692
+ }, 2e3);
1669
1693
  this.startPolling();
1670
1694
  this.wsConnectedListeners.forEach((listener) => listener());
1671
1695
  };
1672
1696
  this.websocket.onclose = () => {
1673
1697
  clearTimeout(connectionTimeout);
1698
+ if (this.initialPollTimer) {
1699
+ clearTimeout(this.initialPollTimer);
1700
+ this.initialPollTimer = null;
1701
+ }
1674
1702
  this.websocket = null;
1675
1703
  if (this.isRunning) {
1676
1704
  this.scheduleReconnect();
@@ -1699,6 +1727,10 @@ var init_swap_manager = __esm({
1699
1727
  */
1700
1728
  enterPollingFallback(error) {
1701
1729
  if (!this.isRunning) return;
1730
+ if (this.initialPollTimer) {
1731
+ clearTimeout(this.initialPollTimer);
1732
+ this.initialPollTimer = null;
1733
+ }
1702
1734
  this.isReconnecting = false;
1703
1735
  this.websocket = null;
1704
1736
  this.usePollingFallback = true;
@@ -1800,6 +1832,11 @@ var init_swap_manager = __esm({
1800
1832
  if (this.isFinalStatus(swap)) {
1801
1833
  this.monitoredSwaps.delete(swap.id);
1802
1834
  this.swapSubscriptions.delete(swap.id);
1835
+ const retryTimer = this.pollRetryTimers.get(swap.id);
1836
+ if (retryTimer) {
1837
+ clearTimeout(retryTimer);
1838
+ this.pollRetryTimers.delete(swap.id);
1839
+ }
1803
1840
  this.swapCompletedListeners.forEach((listener) => listener(swap));
1804
1841
  }
1805
1842
  }
@@ -2064,7 +2101,37 @@ var init_swap_manager = __esm({
2064
2101
  );
2065
2102
  }
2066
2103
  } catch (error) {
2067
- logger.error(`Failed to poll swap ${swap.id}:`, error);
2104
+ if (error instanceof NetworkError && error.statusCode === 429) {
2105
+ logger.warn(
2106
+ `Rate-limited polling swap ${swap.id}, retrying in 2s`
2107
+ );
2108
+ const existing = this.pollRetryTimers.get(swap.id);
2109
+ if (existing) clearTimeout(existing);
2110
+ this.pollRetryTimers.set(
2111
+ swap.id,
2112
+ setTimeout(async () => {
2113
+ this.pollRetryTimers.delete(swap.id);
2114
+ try {
2115
+ const retry = await this.swapProvider.getSwapStatus(
2116
+ swap.id
2117
+ );
2118
+ if (retry.status !== swap.status) {
2119
+ await this.handleSwapStatusUpdate(
2120
+ swap,
2121
+ retry.status
2122
+ );
2123
+ }
2124
+ } catch (retryError) {
2125
+ logger.error(
2126
+ `Retry poll for swap ${swap.id} also failed:`,
2127
+ retryError
2128
+ );
2129
+ }
2130
+ }, 2e3)
2131
+ );
2132
+ } else {
2133
+ logger.error(`Failed to poll swap ${swap.id}:`, error);
2134
+ }
2068
2135
  }
2069
2136
  }
2070
2137
  );
@@ -3044,6 +3111,16 @@ var init_arkade_swaps = __esm({
3044
3111
  * Dispose of resources (stops SwapManager and cleans up).
3045
3112
  * Can be called manually or automatically with `await using` syntax (TypeScript 5.2+).
3046
3113
  */
3114
+ /**
3115
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
3116
+ *
3117
+ * **Destructive** — any swap in a non-terminal state will lose its
3118
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
3119
+ */
3120
+ async reset() {
3121
+ await this.dispose();
3122
+ await this.swapRepository.clear();
3123
+ }
3047
3124
  async dispose() {
3048
3125
  if (this.swapManager) {
3049
3126
  await this.stopSwapManager();
@@ -3367,21 +3444,6 @@ var init_arkade_swaps = __esm({
3367
3444
  const preimageHash = pendingSwap.request.invoice ? getInvoicePaymentHash(pendingSwap.request.invoice) : pendingSwap.preimageHash;
3368
3445
  if (!preimageHash)
3369
3446
  throw new Error("Preimage hash is required to refund VHTLC");
3370
- const vhtlcPkScript = import_sdk8.ArkAddress.decode(
3371
- pendingSwap.response.address
3372
- ).pkScript;
3373
- const { vtxos } = await this.indexerProvider.getVtxos({
3374
- scripts: [import_base9.hex.encode(vhtlcPkScript)]
3375
- });
3376
- if (vtxos.length === 0) {
3377
- throw new Error(
3378
- `VHTLC not found for address ${pendingSwap.response.address}`
3379
- );
3380
- }
3381
- const vtxo = vtxos[0];
3382
- if (vtxo.isSpent) {
3383
- throw new Error("VHTLC is already spent");
3384
- }
3385
3447
  const arkInfo = await this.arkProvider.getInfo();
3386
3448
  const address = await this.wallet.getAddress();
3387
3449
  if (!address) throw new Error("Failed to get ark address from wallet");
@@ -3400,7 +3462,7 @@ var init_arkade_swaps = __esm({
3400
3462
  "boltz",
3401
3463
  pendingSwap.id
3402
3464
  );
3403
- const { vhtlcScript } = this.createVHTLCScript({
3465
+ const { vhtlcScript, vhtlcAddress } = this.createVHTLCScript({
3404
3466
  network: arkInfo.network,
3405
3467
  preimageHash: import_base9.hex.decode(preimageHash),
3406
3468
  receiverPubkey: import_base9.hex.encode(boltzXOnlyPublicKey),
@@ -3410,32 +3472,64 @@ var init_arkade_swaps = __esm({
3410
3472
  });
3411
3473
  if (!vhtlcScript.claimScript)
3412
3474
  throw new Error("Failed to create VHTLC script for submarine swap");
3413
- const isRecoverableVtxo = (0, import_sdk8.isRecoverable)(vtxo);
3414
- const input = {
3415
- ...vtxo,
3416
- tapLeafScript: isRecoverableVtxo ? vhtlcScript.refundWithoutReceiver() : vhtlcScript.refund(),
3417
- tapTree: vhtlcScript.encode()
3418
- };
3419
- const output = {
3420
- amount: BigInt(vtxo.value),
3421
- script: import_sdk8.ArkAddress.decode(address).pkScript
3422
- };
3423
- if (isRecoverableVtxo) {
3424
- await this.joinBatch(this.wallet.identity, input, output, arkInfo);
3425
- } else {
3426
- await refundVHTLCwithOffchainTx(
3427
- pendingSwap.id,
3428
- this.wallet.identity,
3429
- this.arkProvider,
3430
- boltzXOnlyPublicKey,
3431
- ourXOnlyPublicKey,
3432
- serverXOnlyPublicKey,
3433
- input,
3434
- output,
3435
- arkInfo,
3436
- this.swapProvider.refundSubmarineSwap.bind(this.swapProvider)
3475
+ if (vhtlcAddress !== pendingSwap.response.address)
3476
+ throw new Error(
3477
+ `VHTLC address mismatch for swap ${pendingSwap.id}: expected ${pendingSwap.response.address}, got ${vhtlcAddress}`
3478
+ );
3479
+ const vhtlcPkScriptHex = import_base9.hex.encode(vhtlcScript.pkScript);
3480
+ const { vtxos: spendableVtxos } = await this.indexerProvider.getVtxos({
3481
+ scripts: [vhtlcPkScriptHex],
3482
+ spendableOnly: true
3483
+ });
3484
+ if (spendableVtxos.length === 0) {
3485
+ const { vtxos: allVtxos } = await this.indexerProvider.getVtxos({
3486
+ scripts: [vhtlcPkScriptHex]
3487
+ });
3488
+ throw new Error(
3489
+ allVtxos.length > 0 ? "VHTLC is already spent" : `VHTLC not found for address ${pendingSwap.response.address}`
3437
3490
  );
3438
3491
  }
3492
+ const outputScript = import_sdk8.ArkAddress.decode(address).pkScript;
3493
+ let boltzCallCount = 0;
3494
+ for (const vtxo of spendableVtxos) {
3495
+ const isRecoverableVtxo = (0, import_sdk8.isRecoverable)(vtxo);
3496
+ const input = {
3497
+ ...vtxo,
3498
+ tapLeafScript: isRecoverableVtxo ? vhtlcScript.refundWithoutReceiver() : vhtlcScript.refund(),
3499
+ tapTree: vhtlcScript.encode()
3500
+ };
3501
+ const output = {
3502
+ amount: BigInt(vtxo.value),
3503
+ script: outputScript
3504
+ };
3505
+ if (isRecoverableVtxo) {
3506
+ await this.joinBatch(
3507
+ this.wallet.identity,
3508
+ input,
3509
+ output,
3510
+ arkInfo
3511
+ );
3512
+ } else {
3513
+ if (boltzCallCount > 0) {
3514
+ await new Promise((r) => setTimeout(r, 2e3));
3515
+ }
3516
+ await refundVHTLCwithOffchainTx(
3517
+ pendingSwap.id,
3518
+ this.wallet.identity,
3519
+ this.arkProvider,
3520
+ boltzXOnlyPublicKey,
3521
+ ourXOnlyPublicKey,
3522
+ serverXOnlyPublicKey,
3523
+ input,
3524
+ output,
3525
+ arkInfo,
3526
+ this.swapProvider.refundSubmarineSwap.bind(
3527
+ this.swapProvider
3528
+ )
3529
+ );
3530
+ boltzCallCount++;
3531
+ }
3532
+ }
3439
3533
  await updateSubmarineSwapStatus(
3440
3534
  pendingSwap,
3441
3535
  pendingSwap.status,
@@ -4414,16 +4508,18 @@ var init_arkade_swaps = __esm({
4414
4508
  } else if (isRestoredSubmarineSwap(swap)) {
4415
4509
  const { amount, lockupAddress, serverPublicKey, tree } = swap.refundDetails;
4416
4510
  let preimage = "";
4417
- try {
4418
- const data = await this.swapProvider.getSwapPreimage(
4419
- swap.id
4420
- );
4421
- preimage = data.preimage;
4422
- } catch (error) {
4423
- logger.warn(
4424
- `Failed to restore preimage for submarine swap ${id}`,
4425
- error
4426
- );
4511
+ if (!isSubmarineFinalStatus(status)) {
4512
+ try {
4513
+ const data = await this.swapProvider.getSwapPreimage(
4514
+ swap.id
4515
+ );
4516
+ preimage = data.preimage;
4517
+ } catch (error) {
4518
+ logger.warn(
4519
+ `Failed to restore preimage for submarine swap ${id}`,
4520
+ error
4521
+ );
4522
+ }
4427
4523
  }
4428
4524
  submarineSwaps.push({
4429
4525
  id,
@@ -4887,6 +4983,16 @@ var ExpoArkadeSwaps = class _ExpoArkadeSwaps {
4887
4983
  await taskQueue.addTask(task);
4888
4984
  }
4889
4985
  // ── Lifecycle ────────────────────────────────────────────────────
4986
+ /**
4987
+ * Reset all swap state: stops polling and clears the swap repository.
4988
+ *
4989
+ * **Destructive** — any swap in a non-terminal state will lose its
4990
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
4991
+ */
4992
+ async reset() {
4993
+ await this.dispose();
4994
+ await this.inner.swapRepository.clear();
4995
+ }
4890
4996
  async dispose() {
4891
4997
  if (this.foregroundIntervalId) {
4892
4998
  clearInterval(this.foregroundIntervalId);
@@ -1,5 +1,5 @@
1
- import { I as IArkadeSwaps, A as ArkadeSwaps } from '../arkade-swaps-DnhnGtTb.cjs';
2
- import { A as ArkadeSwapsConfig, i as SwapRepository, l as BoltzSwapProvider, N as Network, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, b as PendingReverseSwap, F as FeesResponse, a as PendingChainSwap, h as ArkToBtcResponse, B as BtcToArkResponse, d as Chain, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from '../types-DCCYGYCD.cjs';
1
+ import { I as IArkadeSwaps, A as ArkadeSwaps } from '../arkade-swaps--vc0H2oD.cjs';
2
+ import { A as ArkadeSwapsConfig, i as SwapRepository, l as BoltzSwapProvider, N as Network, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, b as PendingReverseSwap, F as FeesResponse, a as PendingChainSwap, h as ArkToBtcResponse, B as BtcToArkResponse, d as Chain, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from '../types-CEmBBA71.cjs';
3
3
  import { Identity, ArkProvider, IndexerProvider, IWallet, ArkInfo, ArkTxInput, VHTLC } from '@arkade-os/sdk';
4
4
  import { AsyncStorageTaskQueue, TaskProcessor } from '@arkade-os/sdk/worker/expo';
5
5
  import { TransactionOutput } from '@scure/btc-signer/psbt.js';
@@ -124,6 +124,13 @@ declare class ExpoArkadeSwaps implements IArkadeSwaps {
124
124
  private startForegroundPolling;
125
125
  private runForegroundPoll;
126
126
  private seedSwapPollTask;
127
+ /**
128
+ * Reset all swap state: stops polling and clears the swap repository.
129
+ *
130
+ * **Destructive** — any swap in a non-terminal state will lose its
131
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
132
+ */
133
+ reset(): Promise<void>;
127
134
  dispose(): Promise<void>;
128
135
  [Symbol.asyncDispose](): Promise<void>;
129
136
  startSwapManager(): Promise<void>;
@@ -1,5 +1,5 @@
1
- import { I as IArkadeSwaps, A as ArkadeSwaps } from '../arkade-swaps-MmMjdK2G.js';
2
- import { A as ArkadeSwapsConfig, i as SwapRepository, l as BoltzSwapProvider, N as Network, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, b as PendingReverseSwap, F as FeesResponse, a as PendingChainSwap, h as ArkToBtcResponse, B as BtcToArkResponse, d as Chain, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from '../types-DCCYGYCD.js';
1
+ import { I as IArkadeSwaps, A as ArkadeSwaps } from '../arkade-swaps-qQuX73sR.js';
2
+ import { A as ArkadeSwapsConfig, i as SwapRepository, l as BoltzSwapProvider, N as Network, j as SwapManagerClient, C as CreateLightningInvoiceRequest, e as CreateLightningInvoiceResponse, S as SendLightningPaymentRequest, f as SendLightningPaymentResponse, c as PendingSubmarineSwap, b as PendingReverseSwap, F as FeesResponse, a as PendingChainSwap, h as ArkToBtcResponse, B as BtcToArkResponse, d as Chain, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, P as PendingSwap } from '../types-CEmBBA71.js';
3
3
  import { Identity, ArkProvider, IndexerProvider, IWallet, ArkInfo, ArkTxInput, VHTLC } from '@arkade-os/sdk';
4
4
  import { AsyncStorageTaskQueue, TaskProcessor } from '@arkade-os/sdk/worker/expo';
5
5
  import { TransactionOutput } from '@scure/btc-signer/psbt.js';
@@ -124,6 +124,13 @@ declare class ExpoArkadeSwaps implements IArkadeSwaps {
124
124
  private startForegroundPolling;
125
125
  private runForegroundPoll;
126
126
  private seedSwapPollTask;
127
+ /**
128
+ * Reset all swap state: stops polling and clears the swap repository.
129
+ *
130
+ * **Destructive** — any swap in a non-terminal state will lose its
131
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
132
+ */
133
+ reset(): Promise<void>;
127
134
  dispose(): Promise<void>;
128
135
  [Symbol.asyncDispose](): Promise<void>;
129
136
  startSwapManager(): Promise<void>;
@@ -4,10 +4,10 @@ import {
4
4
  registerExpoSwapBackgroundTask,
5
5
  swapsPollProcessor,
6
6
  unregisterExpoSwapBackgroundTask
7
- } from "../chunk-XUBVFCQZ.js";
7
+ } from "../chunk-QGPE6POI.js";
8
8
  import {
9
9
  ArkadeSwaps
10
- } from "../chunk-ZJ2Q5QSA.js";
10
+ } from "../chunk-NTTONVRX.js";
11
11
  import "../chunk-3RG5ZIWI.js";
12
12
 
13
13
  // src/expo/arkade-lightning.ts
@@ -56,7 +56,7 @@ var ExpoArkadeSwaps = class _ExpoArkadeSwaps {
56
56
  await instance.seedSwapPollTask();
57
57
  if (config.background.minimumBackgroundInterval) {
58
58
  try {
59
- const { registerExpoSwapBackgroundTask: registerExpoSwapBackgroundTask2 } = await import("../background-RLZLTWCI.js");
59
+ const { registerExpoSwapBackgroundTask: registerExpoSwapBackgroundTask2 } = await import("../background-SASNQHX4.js");
60
60
  await registerExpoSwapBackgroundTask2(
61
61
  config.background.taskName,
62
62
  {
@@ -112,6 +112,16 @@ var ExpoArkadeSwaps = class _ExpoArkadeSwaps {
112
112
  await taskQueue.addTask(task);
113
113
  }
114
114
  // ── Lifecycle ────────────────────────────────────────────────────
115
+ /**
116
+ * Reset all swap state: stops polling and clears the swap repository.
117
+ *
118
+ * **Destructive** — any swap in a non-terminal state will lose its
119
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
120
+ */
121
+ async reset() {
122
+ await this.dispose();
123
+ await this.inner.swapRepository.clear();
124
+ }
115
125
  async dispose() {
116
126
  if (this.foregroundIntervalId) {
117
127
  clearInterval(this.foregroundIntervalId);
@@ -119,7 +129,7 @@ var ExpoArkadeSwaps = class _ExpoArkadeSwaps {
119
129
  }
120
130
  await this.inner.dispose();
121
131
  try {
122
- const { unregisterExpoSwapBackgroundTask: unregisterExpoSwapBackgroundTask2 } = await import("../background-RLZLTWCI.js");
132
+ const { unregisterExpoSwapBackgroundTask: unregisterExpoSwapBackgroundTask2 } = await import("../background-SASNQHX4.js");
123
133
  await unregisterExpoSwapBackgroundTask2(this.taskName);
124
134
  } catch (err) {
125
135
  const message = err instanceof Error ? err.message : String(err);
package/dist/index.cjs CHANGED
@@ -1383,6 +1383,8 @@ var SwapManager = class {
1383
1383
  // All swaps passed to start(), including completed ones
1384
1384
  pollTimer = null;
1385
1385
  reconnectTimer = null;
1386
+ initialPollTimer = null;
1387
+ pollRetryTimers = /* @__PURE__ */ new Map();
1386
1388
  isRunning = false;
1387
1389
  currentReconnectDelay;
1388
1390
  currentPollRetryDelay;
@@ -1566,6 +1568,14 @@ var SwapManager = class {
1566
1568
  clearTimeout(this.reconnectTimer);
1567
1569
  this.reconnectTimer = null;
1568
1570
  }
1571
+ if (this.initialPollTimer) {
1572
+ clearTimeout(this.initialPollTimer);
1573
+ this.initialPollTimer = null;
1574
+ }
1575
+ for (const timer of this.pollRetryTimers.values()) {
1576
+ clearTimeout(timer);
1577
+ }
1578
+ this.pollRetryTimers.clear();
1569
1579
  }
1570
1580
  /**
1571
1581
  * Set the polling interval (ms).
@@ -1621,6 +1631,11 @@ var SwapManager = class {
1621
1631
  async removeSwap(swapId) {
1622
1632
  this.monitoredSwaps.delete(swapId);
1623
1633
  this.swapSubscriptions.delete(swapId);
1634
+ const retryTimer = this.pollRetryTimers.get(swapId);
1635
+ if (retryTimer) {
1636
+ clearTimeout(retryTimer);
1637
+ this.pollRetryTimers.delete(swapId);
1638
+ }
1624
1639
  logger.log(`Removed swap ${swapId} from monitoring`);
1625
1640
  }
1626
1641
  /**
@@ -1771,12 +1786,25 @@ var SwapManager = class {
1771
1786
  for (const swapId of this.monitoredSwaps.keys()) {
1772
1787
  this.subscribeToSwap(swapId);
1773
1788
  }
1774
- this.pollAllSwaps();
1789
+ if (this.initialPollTimer) {
1790
+ clearTimeout(this.initialPollTimer);
1791
+ this.initialPollTimer = null;
1792
+ }
1793
+ this.initialPollTimer = setTimeout(() => {
1794
+ this.initialPollTimer = null;
1795
+ if (this.isRunning) {
1796
+ this.pollAllSwaps();
1797
+ }
1798
+ }, 2e3);
1775
1799
  this.startPolling();
1776
1800
  this.wsConnectedListeners.forEach((listener) => listener());
1777
1801
  };
1778
1802
  this.websocket.onclose = () => {
1779
1803
  clearTimeout(connectionTimeout);
1804
+ if (this.initialPollTimer) {
1805
+ clearTimeout(this.initialPollTimer);
1806
+ this.initialPollTimer = null;
1807
+ }
1780
1808
  this.websocket = null;
1781
1809
  if (this.isRunning) {
1782
1810
  this.scheduleReconnect();
@@ -1805,6 +1833,10 @@ var SwapManager = class {
1805
1833
  */
1806
1834
  enterPollingFallback(error) {
1807
1835
  if (!this.isRunning) return;
1836
+ if (this.initialPollTimer) {
1837
+ clearTimeout(this.initialPollTimer);
1838
+ this.initialPollTimer = null;
1839
+ }
1808
1840
  this.isReconnecting = false;
1809
1841
  this.websocket = null;
1810
1842
  this.usePollingFallback = true;
@@ -1906,6 +1938,11 @@ var SwapManager = class {
1906
1938
  if (this.isFinalStatus(swap)) {
1907
1939
  this.monitoredSwaps.delete(swap.id);
1908
1940
  this.swapSubscriptions.delete(swap.id);
1941
+ const retryTimer = this.pollRetryTimers.get(swap.id);
1942
+ if (retryTimer) {
1943
+ clearTimeout(retryTimer);
1944
+ this.pollRetryTimers.delete(swap.id);
1945
+ }
1909
1946
  this.swapCompletedListeners.forEach((listener) => listener(swap));
1910
1947
  }
1911
1948
  }
@@ -2170,7 +2207,37 @@ var SwapManager = class {
2170
2207
  );
2171
2208
  }
2172
2209
  } catch (error) {
2173
- logger.error(`Failed to poll swap ${swap.id}:`, error);
2210
+ if (error instanceof NetworkError && error.statusCode === 429) {
2211
+ logger.warn(
2212
+ `Rate-limited polling swap ${swap.id}, retrying in 2s`
2213
+ );
2214
+ const existing = this.pollRetryTimers.get(swap.id);
2215
+ if (existing) clearTimeout(existing);
2216
+ this.pollRetryTimers.set(
2217
+ swap.id,
2218
+ setTimeout(async () => {
2219
+ this.pollRetryTimers.delete(swap.id);
2220
+ try {
2221
+ const retry = await this.swapProvider.getSwapStatus(
2222
+ swap.id
2223
+ );
2224
+ if (retry.status !== swap.status) {
2225
+ await this.handleSwapStatusUpdate(
2226
+ swap,
2227
+ retry.status
2228
+ );
2229
+ }
2230
+ } catch (retryError) {
2231
+ logger.error(
2232
+ `Retry poll for swap ${swap.id} also failed:`,
2233
+ retryError
2234
+ );
2235
+ }
2236
+ }, 2e3)
2237
+ );
2238
+ } else {
2239
+ logger.error(`Failed to poll swap ${swap.id}:`, error);
2240
+ }
2174
2241
  }
2175
2242
  }
2176
2243
  );
@@ -3098,6 +3165,16 @@ var ArkadeSwaps = class _ArkadeSwaps {
3098
3165
  * Dispose of resources (stops SwapManager and cleans up).
3099
3166
  * Can be called manually or automatically with `await using` syntax (TypeScript 5.2+).
3100
3167
  */
3168
+ /**
3169
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
3170
+ *
3171
+ * **Destructive** — any swap in a non-terminal state will lose its
3172
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
3173
+ */
3174
+ async reset() {
3175
+ await this.dispose();
3176
+ await this.swapRepository.clear();
3177
+ }
3101
3178
  async dispose() {
3102
3179
  if (this.swapManager) {
3103
3180
  await this.stopSwapManager();
@@ -3421,21 +3498,6 @@ var ArkadeSwaps = class _ArkadeSwaps {
3421
3498
  const preimageHash = pendingSwap.request.invoice ? getInvoicePaymentHash(pendingSwap.request.invoice) : pendingSwap.preimageHash;
3422
3499
  if (!preimageHash)
3423
3500
  throw new Error("Preimage hash is required to refund VHTLC");
3424
- const vhtlcPkScript = import_sdk8.ArkAddress.decode(
3425
- pendingSwap.response.address
3426
- ).pkScript;
3427
- const { vtxos } = await this.indexerProvider.getVtxos({
3428
- scripts: [import_base9.hex.encode(vhtlcPkScript)]
3429
- });
3430
- if (vtxos.length === 0) {
3431
- throw new Error(
3432
- `VHTLC not found for address ${pendingSwap.response.address}`
3433
- );
3434
- }
3435
- const vtxo = vtxos[0];
3436
- if (vtxo.isSpent) {
3437
- throw new Error("VHTLC is already spent");
3438
- }
3439
3501
  const arkInfo = await this.arkProvider.getInfo();
3440
3502
  const address = await this.wallet.getAddress();
3441
3503
  if (!address) throw new Error("Failed to get ark address from wallet");
@@ -3454,7 +3516,7 @@ var ArkadeSwaps = class _ArkadeSwaps {
3454
3516
  "boltz",
3455
3517
  pendingSwap.id
3456
3518
  );
3457
- const { vhtlcScript } = this.createVHTLCScript({
3519
+ const { vhtlcScript, vhtlcAddress } = this.createVHTLCScript({
3458
3520
  network: arkInfo.network,
3459
3521
  preimageHash: import_base9.hex.decode(preimageHash),
3460
3522
  receiverPubkey: import_base9.hex.encode(boltzXOnlyPublicKey),
@@ -3464,32 +3526,64 @@ var ArkadeSwaps = class _ArkadeSwaps {
3464
3526
  });
3465
3527
  if (!vhtlcScript.claimScript)
3466
3528
  throw new Error("Failed to create VHTLC script for submarine swap");
3467
- const isRecoverableVtxo = (0, import_sdk8.isRecoverable)(vtxo);
3468
- const input = {
3469
- ...vtxo,
3470
- tapLeafScript: isRecoverableVtxo ? vhtlcScript.refundWithoutReceiver() : vhtlcScript.refund(),
3471
- tapTree: vhtlcScript.encode()
3472
- };
3473
- const output = {
3474
- amount: BigInt(vtxo.value),
3475
- script: import_sdk8.ArkAddress.decode(address).pkScript
3476
- };
3477
- if (isRecoverableVtxo) {
3478
- await this.joinBatch(this.wallet.identity, input, output, arkInfo);
3479
- } else {
3480
- await refundVHTLCwithOffchainTx(
3481
- pendingSwap.id,
3482
- this.wallet.identity,
3483
- this.arkProvider,
3484
- boltzXOnlyPublicKey,
3485
- ourXOnlyPublicKey,
3486
- serverXOnlyPublicKey,
3487
- input,
3488
- output,
3489
- arkInfo,
3490
- this.swapProvider.refundSubmarineSwap.bind(this.swapProvider)
3529
+ if (vhtlcAddress !== pendingSwap.response.address)
3530
+ throw new Error(
3531
+ `VHTLC address mismatch for swap ${pendingSwap.id}: expected ${pendingSwap.response.address}, got ${vhtlcAddress}`
3532
+ );
3533
+ const vhtlcPkScriptHex = import_base9.hex.encode(vhtlcScript.pkScript);
3534
+ const { vtxos: spendableVtxos } = await this.indexerProvider.getVtxos({
3535
+ scripts: [vhtlcPkScriptHex],
3536
+ spendableOnly: true
3537
+ });
3538
+ if (spendableVtxos.length === 0) {
3539
+ const { vtxos: allVtxos } = await this.indexerProvider.getVtxos({
3540
+ scripts: [vhtlcPkScriptHex]
3541
+ });
3542
+ throw new Error(
3543
+ allVtxos.length > 0 ? "VHTLC is already spent" : `VHTLC not found for address ${pendingSwap.response.address}`
3491
3544
  );
3492
3545
  }
3546
+ const outputScript = import_sdk8.ArkAddress.decode(address).pkScript;
3547
+ let boltzCallCount = 0;
3548
+ for (const vtxo of spendableVtxos) {
3549
+ const isRecoverableVtxo = (0, import_sdk8.isRecoverable)(vtxo);
3550
+ const input = {
3551
+ ...vtxo,
3552
+ tapLeafScript: isRecoverableVtxo ? vhtlcScript.refundWithoutReceiver() : vhtlcScript.refund(),
3553
+ tapTree: vhtlcScript.encode()
3554
+ };
3555
+ const output = {
3556
+ amount: BigInt(vtxo.value),
3557
+ script: outputScript
3558
+ };
3559
+ if (isRecoverableVtxo) {
3560
+ await this.joinBatch(
3561
+ this.wallet.identity,
3562
+ input,
3563
+ output,
3564
+ arkInfo
3565
+ );
3566
+ } else {
3567
+ if (boltzCallCount > 0) {
3568
+ await new Promise((r) => setTimeout(r, 2e3));
3569
+ }
3570
+ await refundVHTLCwithOffchainTx(
3571
+ pendingSwap.id,
3572
+ this.wallet.identity,
3573
+ this.arkProvider,
3574
+ boltzXOnlyPublicKey,
3575
+ ourXOnlyPublicKey,
3576
+ serverXOnlyPublicKey,
3577
+ input,
3578
+ output,
3579
+ arkInfo,
3580
+ this.swapProvider.refundSubmarineSwap.bind(
3581
+ this.swapProvider
3582
+ )
3583
+ );
3584
+ boltzCallCount++;
3585
+ }
3586
+ }
3493
3587
  await updateSubmarineSwapStatus(
3494
3588
  pendingSwap,
3495
3589
  pendingSwap.status,
@@ -4468,16 +4562,18 @@ var ArkadeSwaps = class _ArkadeSwaps {
4468
4562
  } else if (isRestoredSubmarineSwap(swap)) {
4469
4563
  const { amount, lockupAddress, serverPublicKey, tree } = swap.refundDetails;
4470
4564
  let preimage = "";
4471
- try {
4472
- const data = await this.swapProvider.getSwapPreimage(
4473
- swap.id
4474
- );
4475
- preimage = data.preimage;
4476
- } catch (error) {
4477
- logger.warn(
4478
- `Failed to restore preimage for submarine swap ${id}`,
4479
- error
4480
- );
4565
+ if (!isSubmarineFinalStatus(status)) {
4566
+ try {
4567
+ const data = await this.swapProvider.getSwapPreimage(
4568
+ swap.id
4569
+ );
4570
+ preimage = data.preimage;
4571
+ } catch (error) {
4572
+ logger.warn(
4573
+ `Failed to restore preimage for submarine swap ${id}`,
4574
+ error
4575
+ );
4576
+ }
4481
4577
  }
4482
4578
  submarineSwaps.push({
4483
4579
  id,
@@ -5630,6 +5726,16 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
5630
5726
  type: "REFRESH_SWAPS_STATUS"
5631
5727
  });
5632
5728
  }
5729
+ /**
5730
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
5731
+ *
5732
+ * **Destructive** — any swap in a non-terminal state will lose its
5733
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
5734
+ */
5735
+ async reset() {
5736
+ await this.dispose();
5737
+ await this.swapRepository.clear();
5738
+ }
5633
5739
  async dispose() {
5634
5740
  if (this.withSwapManager) {
5635
5741
  await this.stopSwapManager().catch(() => {
package/dist/index.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { I as IArkadeSwaps } from './arkade-swaps-DnhnGtTb.cjs';
2
- export { A as ArkadeSwaps } from './arkade-swaps-DnhnGtTb.cjs';
3
- import { P as PendingSwap, D as DecodedInvoice, a as PendingChainSwap, b as PendingReverseSwap, c as PendingSubmarineSwap, A as ArkadeSwapsConfig, N as Network, C as CreateLightningInvoiceRequest, S as SendLightningPaymentRequest, F as FeesResponse, d as Chain, e as CreateLightningInvoiceResponse, f as SendLightningPaymentResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, h as ArkToBtcResponse, B as BtcToArkResponse, i as SwapRepository, j as SwapManagerClient, k as GetSwapsFilter } from './types-DCCYGYCD.cjs';
4
- export { X as ArkadeSwapsCreateConfig, l as BoltzSwapProvider, m as BoltzSwapStatus, W as IncomingPaymentSubscription, V as SwapManager, $ as SwapManagerCallbacks, Z as SwapManagerConfig, _ as SwapManagerEvents, Y as Vtxo, n as isChainClaimableStatus, o as isChainFailedStatus, p as isChainFinalStatus, q as isChainPendingStatus, r as isChainRefundableStatus, s as isChainSignableStatus, t as isChainSuccessStatus, u as isChainSwapClaimable, v as isChainSwapRefundable, w as isPendingChainSwap, x as isPendingReverseSwap, y as isPendingSubmarineSwap, z as isReverseClaimableStatus, E as isReverseFailedStatus, H as isReverseFinalStatus, I as isReversePendingStatus, J as isReverseSuccessStatus, K as isReverseSwapClaimable, M as isSubmarineFailedStatus, O as isSubmarineFinalStatus, Q as isSubmarinePendingStatus, T as isSubmarineRefundableStatus, R as isSubmarineSuccessStatus, U as isSubmarineSwapRefundable } from './types-DCCYGYCD.cjs';
1
+ import { I as IArkadeSwaps } from './arkade-swaps--vc0H2oD.cjs';
2
+ export { A as ArkadeSwaps } from './arkade-swaps--vc0H2oD.cjs';
3
+ import { P as PendingSwap, D as DecodedInvoice, a as PendingChainSwap, b as PendingReverseSwap, c as PendingSubmarineSwap, A as ArkadeSwapsConfig, N as Network, C as CreateLightningInvoiceRequest, S as SendLightningPaymentRequest, F as FeesResponse, d as Chain, e as CreateLightningInvoiceResponse, f as SendLightningPaymentResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, h as ArkToBtcResponse, B as BtcToArkResponse, i as SwapRepository, j as SwapManagerClient, k as GetSwapsFilter } from './types-CEmBBA71.cjs';
4
+ export { X as ArkadeSwapsCreateConfig, l as BoltzSwapProvider, m as BoltzSwapStatus, W as IncomingPaymentSubscription, V as SwapManager, $ as SwapManagerCallbacks, Z as SwapManagerConfig, _ as SwapManagerEvents, Y as Vtxo, n as isChainClaimableStatus, o as isChainFailedStatus, p as isChainFinalStatus, q as isChainPendingStatus, r as isChainRefundableStatus, s as isChainSignableStatus, t as isChainSuccessStatus, u as isChainSwapClaimable, v as isChainSwapRefundable, w as isPendingChainSwap, x as isPendingReverseSwap, y as isPendingSubmarineSwap, z as isReverseClaimableStatus, E as isReverseFailedStatus, H as isReverseFinalStatus, I as isReversePendingStatus, J as isReverseSuccessStatus, K as isReverseSwapClaimable, M as isSubmarineFailedStatus, O as isSubmarineFinalStatus, Q as isSubmarinePendingStatus, T as isSubmarineRefundableStatus, R as isSubmarineSuccessStatus, U as isSubmarineSwapRefundable } from './types-CEmBBA71.cjs';
5
5
  import { Transaction } from '@scure/btc-signer';
6
6
  import { MessageHandler, RequestEnvelope, ArkInfo, ResponseEnvelope, IWallet, IReadonlyWallet, VHTLC, Identity, ArkTxInput } from '@arkade-os/sdk';
7
7
  import { TransactionOutput } from '@scure/btc-signer/psbt.js';
@@ -656,6 +656,13 @@ declare class ServiceWorkerArkadeSwaps implements IArkadeSwaps {
656
656
  getPendingChainSwaps(): Promise<PendingChainSwap[]>;
657
657
  getSwapHistory(): Promise<(PendingReverseSwap | PendingSubmarineSwap | PendingChainSwap)[]>;
658
658
  refreshSwapsStatus(): Promise<void>;
659
+ /**
660
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
661
+ *
662
+ * **Destructive** — any swap in a non-terminal state will lose its
663
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
664
+ */
665
+ reset(): Promise<void>;
659
666
  dispose(): Promise<void>;
660
667
  [Symbol.asyncDispose](): Promise<void>;
661
668
  private sendMessageDirect;
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { I as IArkadeSwaps } from './arkade-swaps-MmMjdK2G.js';
2
- export { A as ArkadeSwaps } from './arkade-swaps-MmMjdK2G.js';
3
- import { P as PendingSwap, D as DecodedInvoice, a as PendingChainSwap, b as PendingReverseSwap, c as PendingSubmarineSwap, A as ArkadeSwapsConfig, N as Network, C as CreateLightningInvoiceRequest, S as SendLightningPaymentRequest, F as FeesResponse, d as Chain, e as CreateLightningInvoiceResponse, f as SendLightningPaymentResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, h as ArkToBtcResponse, B as BtcToArkResponse, i as SwapRepository, j as SwapManagerClient, k as GetSwapsFilter } from './types-DCCYGYCD.js';
4
- export { X as ArkadeSwapsCreateConfig, l as BoltzSwapProvider, m as BoltzSwapStatus, W as IncomingPaymentSubscription, V as SwapManager, $ as SwapManagerCallbacks, Z as SwapManagerConfig, _ as SwapManagerEvents, Y as Vtxo, n as isChainClaimableStatus, o as isChainFailedStatus, p as isChainFinalStatus, q as isChainPendingStatus, r as isChainRefundableStatus, s as isChainSignableStatus, t as isChainSuccessStatus, u as isChainSwapClaimable, v as isChainSwapRefundable, w as isPendingChainSwap, x as isPendingReverseSwap, y as isPendingSubmarineSwap, z as isReverseClaimableStatus, E as isReverseFailedStatus, H as isReverseFinalStatus, I as isReversePendingStatus, J as isReverseSuccessStatus, K as isReverseSwapClaimable, M as isSubmarineFailedStatus, O as isSubmarineFinalStatus, Q as isSubmarinePendingStatus, T as isSubmarineRefundableStatus, R as isSubmarineSuccessStatus, U as isSubmarineSwapRefundable } from './types-DCCYGYCD.js';
1
+ import { I as IArkadeSwaps } from './arkade-swaps-qQuX73sR.js';
2
+ export { A as ArkadeSwaps } from './arkade-swaps-qQuX73sR.js';
3
+ import { P as PendingSwap, D as DecodedInvoice, a as PendingChainSwap, b as PendingReverseSwap, c as PendingSubmarineSwap, A as ArkadeSwapsConfig, N as Network, C as CreateLightningInvoiceRequest, S as SendLightningPaymentRequest, F as FeesResponse, d as Chain, e as CreateLightningInvoiceResponse, f as SendLightningPaymentResponse, g as ChainFeesResponse, L as LimitsResponse, G as GetSwapStatusResponse, h as ArkToBtcResponse, B as BtcToArkResponse, i as SwapRepository, j as SwapManagerClient, k as GetSwapsFilter } from './types-CEmBBA71.js';
4
+ export { X as ArkadeSwapsCreateConfig, l as BoltzSwapProvider, m as BoltzSwapStatus, W as IncomingPaymentSubscription, V as SwapManager, $ as SwapManagerCallbacks, Z as SwapManagerConfig, _ as SwapManagerEvents, Y as Vtxo, n as isChainClaimableStatus, o as isChainFailedStatus, p as isChainFinalStatus, q as isChainPendingStatus, r as isChainRefundableStatus, s as isChainSignableStatus, t as isChainSuccessStatus, u as isChainSwapClaimable, v as isChainSwapRefundable, w as isPendingChainSwap, x as isPendingReverseSwap, y as isPendingSubmarineSwap, z as isReverseClaimableStatus, E as isReverseFailedStatus, H as isReverseFinalStatus, I as isReversePendingStatus, J as isReverseSuccessStatus, K as isReverseSwapClaimable, M as isSubmarineFailedStatus, O as isSubmarineFinalStatus, Q as isSubmarinePendingStatus, T as isSubmarineRefundableStatus, R as isSubmarineSuccessStatus, U as isSubmarineSwapRefundable } from './types-CEmBBA71.js';
5
5
  import { Transaction } from '@scure/btc-signer';
6
6
  import { MessageHandler, RequestEnvelope, ArkInfo, ResponseEnvelope, IWallet, IReadonlyWallet, VHTLC, Identity, ArkTxInput } from '@arkade-os/sdk';
7
7
  import { TransactionOutput } from '@scure/btc-signer/psbt.js';
@@ -656,6 +656,13 @@ declare class ServiceWorkerArkadeSwaps implements IArkadeSwaps {
656
656
  getPendingChainSwaps(): Promise<PendingChainSwap[]>;
657
657
  getSwapHistory(): Promise<(PendingReverseSwap | PendingSubmarineSwap | PendingChainSwap)[]>;
658
658
  refreshSwapsStatus(): Promise<void>;
659
+ /**
660
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
661
+ *
662
+ * **Destructive** — any swap in a non-terminal state will lose its
663
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
664
+ */
665
+ reset(): Promise<void>;
659
666
  dispose(): Promise<void>;
660
667
  [Symbol.asyncDispose](): Promise<void>;
661
668
  private sendMessageDirect;
package/dist/index.js CHANGED
@@ -49,7 +49,7 @@ import {
49
49
  updateReverseSwapStatus,
50
50
  updateSubmarineSwapStatus,
51
51
  verifySignatures
52
- } from "./chunk-ZJ2Q5QSA.js";
52
+ } from "./chunk-NTTONVRX.js";
53
53
  import "./chunk-3RG5ZIWI.js";
54
54
 
55
55
  // src/serviceWorker/arkade-swaps-message-handler.ts
@@ -1123,6 +1123,16 @@ var ServiceWorkerArkadeSwaps = class _ServiceWorkerArkadeSwaps {
1123
1123
  type: "REFRESH_SWAPS_STATUS"
1124
1124
  });
1125
1125
  }
1126
+ /**
1127
+ * Reset all swap state: stops the SwapManager and clears the swap repository.
1128
+ *
1129
+ * **Destructive** — any swap in a non-terminal state will lose its
1130
+ * refund/claim path. Intended for wallet-reset / dev / test scenarios only.
1131
+ */
1132
+ async reset() {
1133
+ await this.dispose();
1134
+ await this.swapRepository.clear();
1135
+ }
1126
1136
  async dispose() {
1127
1137
  if (this.withSwapManager) {
1128
1138
  await this.stopSwapManager().catch(() => {
@@ -1,4 +1,4 @@
1
- import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-DCCYGYCD.cjs';
1
+ import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-CEmBBA71.cjs';
2
2
  import '@arkade-os/sdk';
3
3
 
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-DCCYGYCD.js';
1
+ import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-CEmBBA71.js';
2
2
  import '@arkade-os/sdk';
3
3
 
4
4
  /**
@@ -1,5 +1,5 @@
1
1
  import { SQLExecutor } from '@arkade-os/sdk/repositories/sqlite';
2
- import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-DCCYGYCD.cjs';
2
+ import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-CEmBBA71.cjs';
3
3
  import '@arkade-os/sdk';
4
4
 
5
5
  /**
@@ -1,5 +1,5 @@
1
1
  import { SQLExecutor } from '@arkade-os/sdk/repositories/sqlite';
2
- import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-DCCYGYCD.js';
2
+ import { i as SwapRepository, P as PendingSwap, k as GetSwapsFilter } from '../../types-CEmBBA71.js';
3
3
  import '@arkade-os/sdk';
4
4
 
5
5
  /**
@@ -489,6 +489,8 @@ declare class SwapManager implements SwapManagerClient {
489
489
  private initialSwaps;
490
490
  private pollTimer;
491
491
  private reconnectTimer;
492
+ private initialPollTimer;
493
+ private pollRetryTimers;
492
494
  private isRunning;
493
495
  private currentReconnectDelay;
494
496
  private currentPollRetryDelay;
@@ -489,6 +489,8 @@ declare class SwapManager implements SwapManagerClient {
489
489
  private initialSwaps;
490
490
  private pollTimer;
491
491
  private reconnectTimer;
492
+ private initialPollTimer;
493
+ private pollRetryTimers;
492
494
  private isRunning;
493
495
  private currentReconnectDelay;
494
496
  private currentPollRetryDelay;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arkade-os/boltz-swap",
3
- "version": "0.3.8",
3
+ "version": "0.3.10",
4
4
  "type": "module",
5
5
  "description": "A production-ready TypeScript package that brings Boltz submarine-swaps to Arkade.",
6
6
  "main": "./dist/index.js",