@satora/swap 1.11.1 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/dist/bitcoin-reader-electrum-2N4LJCGD.cjs +9 -0
  2. package/dist/{bitcoin-reader-electrum-VCQ5TQ44.cjs.map → bitcoin-reader-electrum-2N4LJCGD.cjs.map} +1 -1
  3. package/dist/bitcoin-reader-electrum-VLYRII3T.js +9 -0
  4. package/dist/bitcoin-reader-esplora-CAR4P52J.cjs +16 -0
  5. package/dist/bitcoin-reader-esplora-CAR4P52J.cjs.map +1 -0
  6. package/dist/{bitcoin-reader-esplora-CGPF4H5Y.js → bitcoin-reader-esplora-LC673MQT.js} +4 -2
  7. package/dist/{chunk-WQMAL2VD.js → chunk-34OYIFOU.js} +764 -141
  8. package/dist/chunk-34OYIFOU.js.map +1 -0
  9. package/dist/{chunk-4NVWIR74.cjs → chunk-3633KDTW.cjs} +1128 -505
  10. package/dist/chunk-3633KDTW.cjs.map +1 -0
  11. package/dist/{chunk-LSCRTQOS.js → chunk-CUYLQTRF.js} +15 -20
  12. package/dist/chunk-CUYLQTRF.js.map +1 -0
  13. package/dist/{chunk-INHFP222.cjs → chunk-CY5M5X6S.cjs} +28 -30
  14. package/dist/chunk-CY5M5X6S.cjs.map +1 -0
  15. package/dist/{chunk-JZTF4JNH.cjs → chunk-EI5ILLQ3.cjs} +2 -2
  16. package/dist/{chunk-JZTF4JNH.cjs.map → chunk-EI5ILLQ3.cjs.map} +1 -1
  17. package/dist/{chunk-5DQHR3RO.cjs → chunk-FJS6RGUR.cjs} +16 -21
  18. package/dist/chunk-FJS6RGUR.cjs.map +1 -0
  19. package/dist/{chunk-3ZMSZSAV.js → chunk-I2NF63VZ.js} +27 -29
  20. package/dist/chunk-I2NF63VZ.js.map +1 -0
  21. package/dist/{chunk-JHZHRY7S.js → chunk-K2Q4JWB6.js} +2 -2
  22. package/dist/{chunk-JHZHRY7S.js.map → chunk-K2Q4JWB6.js.map} +1 -1
  23. package/dist/{chunk-TT3J2OOS.js → chunk-KMBGRQS7.js} +5 -5
  24. package/dist/{chunk-TT3J2OOS.js.map → chunk-KMBGRQS7.js.map} +1 -1
  25. package/dist/{chunk-Q4TOBBAN.cjs → chunk-LZQZYSOZ.cjs} +5 -5
  26. package/dist/{chunk-Q4TOBBAN.cjs.map → chunk-LZQZYSOZ.cjs.map} +1 -1
  27. package/dist/delegate.cjs +2 -2
  28. package/dist/delegate.js +1 -1
  29. package/dist/{dist-SHY7I6SH.js → dist-3N76II5O.js} +16 -4
  30. package/dist/dist-KQINAMDC.cjs +406 -0
  31. package/dist/{dist-MHRQ5FFV.cjs.map → dist-KQINAMDC.cjs.map} +1 -1
  32. package/dist/{fundSwap-UBCHMUP4-BEMQNSFQ.cjs → fundSwap-2D4IPYU4-4NELKB3Q.cjs} +7 -7
  33. package/dist/{fundSwap-UBCHMUP4-BEMQNSFQ.cjs.map → fundSwap-2D4IPYU4-4NELKB3Q.cjs.map} +1 -1
  34. package/dist/{fundSwap-UBCHMUP4-WBLYE6MC.js → fundSwap-2D4IPYU4-CDM3WRUF.js} +3 -3
  35. package/dist/index.cjs +41 -23
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.js +29 -11
  38. package/dist/index.js.map +1 -1
  39. package/dist/node.cjs +26 -5
  40. package/dist/node.cjs.map +1 -1
  41. package/dist/node.js +26 -5
  42. package/dist/node.js.map +1 -1
  43. package/dist/types/cjs/pure/api/client.d.cts +1 -0
  44. package/dist/types/cjs/pure/client.d.cts +44 -12
  45. package/dist/types/cjs/pure/compose-quote.d.cts +14 -1
  46. package/dist/types/cjs/pure/create/bitcoin-payout.d.cts +17 -0
  47. package/dist/types/cjs/pure/create/evm-to-arkade.d.cts +0 -5
  48. package/dist/types/cjs/pure/create/evm-to-lightning.d.cts +0 -8
  49. package/dist/types/cjs/pure/create/funding-terms.d.cts +2 -1
  50. package/dist/types/cjs/pure/create/index.d.cts +2 -1
  51. package/dist/types/cjs/pure/create/payment-safety.d.cts +2 -0
  52. package/dist/types/cjs/pure/create/payout-slippage.d.cts +29 -0
  53. package/dist/types/cjs/pure/create/spark-to-evm.d.cts +7 -0
  54. package/dist/types/cjs/pure/create/types.d.cts +102 -3
  55. package/dist/types/cjs/pure/esplora.d.cts +2 -0
  56. package/dist/types/cjs/pure/evm/funding-pins.d.cts +2 -0
  57. package/dist/types/cjs/pure/generated/api.d.cts +352 -2
  58. package/dist/types/cjs/pure/index.d.cts +6 -4
  59. package/dist/types/cjs/pure/refund/onchain.d.cts +4 -0
  60. package/dist/types/cjs/pure/storage/index.d.cts +1 -1
  61. package/dist/types/cjs/pure/storage/types.d.cts +22 -0
  62. package/dist/types/cjs/pure/swap-verification.d.cts +3 -1
  63. package/dist/types/cjs/pure/tokens.d.cts +5 -0
  64. package/dist/types/cjs/pure/types/chain.d.cts +2 -2
  65. package/dist/types/cjs/pure/types/index.d.cts +1 -0
  66. package/dist/types/cjs/pure/types/promo-code.d.cts +15 -0
  67. package/dist/types/cjs/pure/types/quote.d.cts +7 -0
  68. package/dist/types/cjs/pure/types/referral-fee.d.cts +8 -0
  69. package/dist/types/cjs/pure/version.d.cts +4 -4
  70. package/dist/types/cjs/swap/client.d.cts +2 -0
  71. package/dist/types/cjs/swap/contracts/bitcoin-reader-esplora.d.cts +5 -0
  72. package/dist/types/esm/pure/api/client.d.ts +1 -0
  73. package/dist/types/esm/pure/client.d.ts +44 -12
  74. package/dist/types/esm/pure/compose-quote.d.ts +14 -1
  75. package/dist/types/esm/pure/create/bitcoin-payout.d.ts +17 -0
  76. package/dist/types/esm/pure/create/evm-to-arkade.d.ts +0 -5
  77. package/dist/types/esm/pure/create/evm-to-lightning.d.ts +0 -8
  78. package/dist/types/esm/pure/create/funding-terms.d.ts +2 -1
  79. package/dist/types/esm/pure/create/index.d.ts +2 -1
  80. package/dist/types/esm/pure/create/payment-safety.d.ts +2 -0
  81. package/dist/types/esm/pure/create/payout-slippage.d.ts +29 -0
  82. package/dist/types/esm/pure/create/spark-to-evm.d.ts +7 -0
  83. package/dist/types/esm/pure/create/types.d.ts +102 -3
  84. package/dist/types/esm/pure/esplora.d.ts +2 -0
  85. package/dist/types/esm/pure/evm/funding-pins.d.ts +2 -0
  86. package/dist/types/esm/pure/generated/api.d.ts +352 -2
  87. package/dist/types/esm/pure/index.d.ts +6 -4
  88. package/dist/types/esm/pure/refund/onchain.d.ts +4 -0
  89. package/dist/types/esm/pure/storage/index.d.ts +1 -1
  90. package/dist/types/esm/pure/storage/types.d.ts +22 -0
  91. package/dist/types/esm/pure/swap-verification.d.ts +3 -1
  92. package/dist/types/esm/pure/tokens.d.ts +5 -0
  93. package/dist/types/esm/pure/types/chain.d.ts +2 -2
  94. package/dist/types/esm/pure/types/index.d.ts +1 -0
  95. package/dist/types/esm/pure/types/promo-code.d.ts +15 -0
  96. package/dist/types/esm/pure/types/quote.d.ts +7 -0
  97. package/dist/types/esm/pure/types/referral-fee.d.ts +8 -0
  98. package/dist/types/esm/pure/version.d.ts +4 -4
  99. package/dist/types/esm/swap/client.d.ts +2 -0
  100. package/dist/types/esm/swap/contracts/bitcoin-reader-esplora.d.ts +5 -0
  101. package/package.json +2 -2
  102. package/dist/bitcoin-reader-electrum-4PNSDHIA.js +0 -9
  103. package/dist/bitcoin-reader-electrum-VCQ5TQ44.cjs +0 -9
  104. package/dist/bitcoin-reader-esplora-6RH7S4BR.cjs +0 -14
  105. package/dist/bitcoin-reader-esplora-6RH7S4BR.cjs.map +0 -1
  106. package/dist/chunk-3ZMSZSAV.js.map +0 -1
  107. package/dist/chunk-4NVWIR74.cjs.map +0 -1
  108. package/dist/chunk-5DQHR3RO.cjs.map +0 -1
  109. package/dist/chunk-INHFP222.cjs.map +0 -1
  110. package/dist/chunk-LSCRTQOS.js.map +0 -1
  111. package/dist/chunk-WQMAL2VD.js.map +0 -1
  112. package/dist/dist-MHRQ5FFV.cjs +0 -394
  113. /package/dist/{bitcoin-reader-electrum-4PNSDHIA.js.map → bitcoin-reader-electrum-VLYRII3T.js.map} +0 -0
  114. /package/dist/{bitcoin-reader-esplora-CGPF4H5Y.js.map → bitcoin-reader-esplora-LC673MQT.js.map} +0 -0
  115. /package/dist/{dist-SHY7I6SH.js.map → dist-3N76II5O.js.map} +0 -0
  116. /package/dist/{fundSwap-UBCHMUP4-WBLYE6MC.js.map → fundSwap-2D4IPYU4-CDM3WRUF.js.map} +0 -0
@@ -39,7 +39,7 @@ import {
39
39
  refundForAsOwnRefund,
40
40
  submitCctpInboundBalanceUserOp,
41
41
  submitCctpInboundUserOp
42
- } from "./chunk-JHZHRY7S.js";
42
+ } from "./chunk-K2Q4JWB6.js";
43
43
  import {
44
44
  createPublicClient,
45
45
  http
@@ -115,7 +115,7 @@ import {
115
115
  sha2562,
116
116
  sha512,
117
117
  utils
118
- } from "./chunk-TT3J2OOS.js";
118
+ } from "./chunk-KMBGRQS7.js";
119
119
  import {
120
120
  ArkAddress,
121
121
  CSVMultisigTapscript,
@@ -156,6 +156,7 @@ import {
156
156
  base58check,
157
157
  base64,
158
158
  bech32,
159
+ bech32m,
159
160
  hex,
160
161
  init_base
161
162
  } from "./chunk-OBFZJKRF.js";
@@ -7949,6 +7950,7 @@ var TBTC_ETHEREUM = "0x18084fbA666a33d37592fA2633fD49a74DD93a88";
7949
7950
  var TBTC_ARBITRUM = "0x6c84a8f1c29108F47a79964b5Fe888D4f4D0dE40";
7950
7951
  var Asset = {
7951
7952
  // Bitcoin
7953
+ BTC_SPARK: { chain: "Spark", tokenId: "btc" },
7952
7954
  BTC_LIGHTNING: { chain: "Lightning", tokenId: "btc" },
7953
7955
  BTC_ARKADE: { chain: "Arkade", tokenId: "btc" },
7954
7956
  BTC_ONCHAIN: { chain: "Bitcoin", tokenId: "btc" },
@@ -8039,7 +8041,7 @@ function isBtcOnchain(token) {
8039
8041
  return token.chain.toLowerCase() === "bitcoin";
8040
8042
  }
8041
8043
  function isBtc(token) {
8042
- return isLightning(token) || isArkade(token) || isBtcOnchain(token);
8044
+ return isSpark(token) || isLightning(token) || isArkade(token) || isBtcOnchain(token);
8043
8045
  }
8044
8046
  function isBtcPegged(token) {
8045
8047
  const sym = token.symbol.toLowerCase();
@@ -8126,6 +8128,7 @@ function toChain(str) {
8126
8128
  if (c === "arbitrum" || c === "42161") return "42161";
8127
8129
  if (c === "rootstock" || c === "30") return "30";
8128
8130
  if (c === "31") return "31";
8131
+ if (c === "spark") return "Spark";
8129
8132
  if (c === "lightning") return "Lightning";
8130
8133
  if (c === "arkade") return "Arkade";
8131
8134
  if (c === "bitcoin") return "Bitcoin";
@@ -8183,6 +8186,9 @@ function getUsdt0BridgeTokens() {
8183
8186
  }
8184
8187
  return tokens;
8185
8188
  }
8189
+ function isSpark(token) {
8190
+ return token.chain.toLowerCase() === "spark";
8191
+ }
8186
8192
  function pivotForChain(chainConfig, chain) {
8187
8193
  const entry = chainConfig.chains.find((c) => c.chain === chain);
8188
8194
  if (!entry) return void 0;
@@ -8388,9 +8394,10 @@ async function composeBtcToEvm(params, deps) {
8388
8394
  );
8389
8395
  }
8390
8396
  const { btcSats, evmSmallest, evmDecimals } = pivot;
8397
+ ensureWithinPromoCap(deps, btcSats);
8391
8398
  let { bridgeFee } = pivot;
8392
8399
  const networkFeeSats = baseNetworkFeeSats + pivot.bridgeNativeFeeSats;
8393
- const effectiveFeePct = (deps.referralBaseFeeRate ?? pair.fee_percentage) + (deps.referralExtraFeeRate ?? 0);
8400
+ const effectiveFeePct = baseFeePct(deps, pair.fee_percentage) + (deps.referralExtraFeeRate ?? 0);
8394
8401
  const FEE_SCALE = 10n ** 18n;
8395
8402
  const feePctScaled = BigInt(Math.round(effectiveFeePct * Number(FEE_SCALE)));
8396
8403
  const protocolFee = Number(btcSats * feePctScaled / FEE_SCALE);
@@ -8430,7 +8437,7 @@ async function composeBtcToEvm(params, deps) {
8430
8437
  protocol_fee: protocolFee,
8431
8438
  protocol_fee_rate: effectiveFeePct,
8432
8439
  min_amount: pair.min_sats,
8433
- max_amount: pair.max_sats,
8440
+ max_amount: maxSats(deps, pair.max_sats),
8434
8441
  source_amount: btcSats.toString(),
8435
8442
  // Source-pinned: `evmSmallest` is the delivered (fee-netted) DEX output, so
8436
8443
  // gross it back up by the bridge fee — `target_amount` is the gross output
@@ -8442,7 +8449,8 @@ async function composeBtcToEvm(params, deps) {
8442
8449
  target_amount: (params.sourceAmount != null ? grossTarget : evmSmallest).toString(),
8443
8450
  net_source_amount: netSource.toString(),
8444
8451
  net_target_amount: netTarget.toString(),
8445
- bridge_fee: bridgeFee > 0n ? Number(bridgeFee) : void 0
8452
+ bridge_fee: bridgeFee > 0n ? Number(bridgeFee) : void 0,
8453
+ promo: deps.referralPromo
8446
8454
  };
8447
8455
  }
8448
8456
  async function dexSourcePinned(btcSats, params, deps, btcPegged, pivotChainId, toToken, pivotScale) {
@@ -8551,7 +8559,8 @@ async function composeEvmToBtc(params, deps) {
8551
8559
  );
8552
8560
  }
8553
8561
  const { btcSats, evmSmallest, evmDecimals, bridgeFee } = pivot;
8554
- const effectiveFeePct = (deps.referralBaseFeeRate ?? pair.fee_percentage) + (deps.referralExtraFeeRate ?? 0);
8562
+ ensureWithinPromoCap(deps, btcSats);
8563
+ const effectiveFeePct = baseFeePct(deps, pair.fee_percentage) + (deps.referralExtraFeeRate ?? 0);
8555
8564
  const FEE_SCALE = 10n ** 18n;
8556
8565
  const feePctScaled = BigInt(Math.round(effectiveFeePct * Number(FEE_SCALE)));
8557
8566
  const protocolFee = Number(btcSats * feePctScaled / FEE_SCALE);
@@ -8573,7 +8582,7 @@ async function composeEvmToBtc(params, deps) {
8573
8582
  protocol_fee: protocolFee,
8574
8583
  protocol_fee_rate: effectiveFeePct,
8575
8584
  min_amount: pair.min_sats,
8576
- max_amount: pair.max_sats,
8585
+ max_amount: maxSats(deps, pair.max_sats),
8577
8586
  // EVM→BTC: the EVM source is the bridged side. The dex-quote already
8578
8587
  // reports `evmSmallest` as the gross the user supplies (the inbound fee was
8579
8588
  // folded onto it), so `source_amount` needs no adjustment — just surface
@@ -8582,7 +8591,8 @@ async function composeEvmToBtc(params, deps) {
8582
8591
  target_amount: btcSats.toString(),
8583
8592
  net_source_amount: netSource.toString(),
8584
8593
  net_target_amount: netTarget.toString(),
8585
- bridge_fee: bridgeFee > 0n ? Number(bridgeFee) : void 0
8594
+ bridge_fee: bridgeFee > 0n ? Number(bridgeFee) : void 0,
8595
+ promo: deps.referralPromo
8586
8596
  };
8587
8597
  }
8588
8598
  async function dexEvmToBtcSourcePinned(evmSmallest, params, deps, btcPegged, pivotChainId, tokenChainId, pivotScale) {
@@ -8636,6 +8646,20 @@ function calculateExchangeRate(btcSats, evmSmallest, evmDecimals) {
8636
8646
  frac = frac.replace(/0+$/, "");
8637
8647
  return frac.length === 0 ? intPart.toString() : `${intPart}.${frac}`;
8638
8648
  }
8649
+ function baseFeePct(deps, pairFeePct) {
8650
+ return deps.referralPromo?.fee_rate ?? deps.referralBaseFeeRate ?? pairFeePct;
8651
+ }
8652
+ function ensureWithinPromoCap(deps, btcSats) {
8653
+ const promo = deps.referralPromo;
8654
+ if (promo && btcSats > BigInt(promo.max_amount_sats)) {
8655
+ throw new Error(
8656
+ `promo code only applies to swaps up to ${promo.max_amount_sats} sats`
8657
+ );
8658
+ }
8659
+ }
8660
+ function maxSats(deps, pairMaxSats) {
8661
+ return deps.referralPromo ? Math.max(pairMaxSats, deps.referralPromo.max_amount_sats) : pairMaxSats;
8662
+ }
8639
8663
  init_sha2();
8640
8664
  init_utils();
8641
8665
  init_bip32();
@@ -11215,6 +11239,65 @@ init_secp256k12();
11215
11239
  init_legacy2();
11216
11240
  init_sha2();
11217
11241
  init_base();
11242
+ var MAX_MONEY = 2100000000000000n;
11243
+ var MAX_PAYOUT_FEE_SATS = 100000n;
11244
+ function validateBitcoinPayout(payout, network) {
11245
+ if (typeof payout !== "object" || payout === null)
11246
+ throw new Error("A Bitcoin payout must be an object");
11247
+ if (!Array.isArray(payout.recipients) || payout.recipients.length < 1 || payout.recipients.length > 100)
11248
+ throw new Error("A Bitcoin payout needs 1\u2013100 recipients");
11249
+ const sats = (value) => {
11250
+ if (typeof value !== "string" || !/^[0-9]{1,16}$/.test(value))
11251
+ throw new Error("Payout amounts must be integer satoshi strings");
11252
+ const amount = BigInt(value);
11253
+ if (amount > MAX_MONEY) throw new Error("Payout exceeds Bitcoin supply");
11254
+ return amount;
11255
+ };
11256
+ const fee = sats(payout.feeSats);
11257
+ if (fee < 1n || fee > MAX_PAYOUT_FEE_SATS)
11258
+ throw new Error("Payout fee must be between 1 and 100,000 sats");
11259
+ let total = 0n;
11260
+ for (const recipient of payout.recipients) {
11261
+ let decoded;
11262
+ try {
11263
+ decoded = Address(network).decode(recipient.address);
11264
+ } catch {
11265
+ throw new Error(
11266
+ "Recipient address is not a valid address for this network"
11267
+ );
11268
+ }
11269
+ if (!decoded || !["pkh", "sh", "wpkh", "wsh", "tr"].includes(decoded.type))
11270
+ throw new Error("Unsupported Bitcoin recipient address");
11271
+ const amount = sats(recipient.amountSats);
11272
+ if (amount < 546n)
11273
+ throw new Error("Each recipient must receive at least 546 sats");
11274
+ total += amount;
11275
+ }
11276
+ if (total + fee > MAX_MONEY) throw new Error("Payout exceeds Bitcoin supply");
11277
+ return { total, fee };
11278
+ }
11279
+ function allocateBitcoinPayout(payout, funded, fee = BigInt(payout.feeSats)) {
11280
+ const amounts = payout.recipients.map((r) => BigInt(r.amountSats));
11281
+ const total = amounts.reduce((a, b) => a + b, 0n);
11282
+ const remainder = funded - total - fee;
11283
+ if (remainder < 0n)
11284
+ throw new Error(
11285
+ "Funded amount cannot cover the committed recipients and fee"
11286
+ );
11287
+ const shares = amounts.map((amount) => remainder * amount / total);
11288
+ let leftover = remainder - shares.reduce((a, b) => a + b, 0n);
11289
+ return {
11290
+ feeSats: fee.toString(),
11291
+ recipients: payout.recipients.map((recipient, index) => {
11292
+ const extra = leftover > 0n ? 1n : 0n;
11293
+ leftover -= extra;
11294
+ return {
11295
+ address: recipient.address,
11296
+ amountSats: (amounts[index] + shares[index] + extra).toString()
11297
+ };
11298
+ })
11299
+ };
11300
+ }
11218
11301
  var NUMS_POINT = hex.decode(
11219
11302
  "0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"
11220
11303
  );
@@ -11344,7 +11427,14 @@ function buildOnchainClaimTransaction(params) {
11344
11427
  refundLocktime,
11345
11428
  params.btcHtlcScriptVersion
11346
11429
  );
11347
- const fee = CLAIM_TX_VBYTES * BigInt(Math.ceil(feeRateSatPerVb));
11430
+ const payout = params.bitcoinPayout;
11431
+ const validated = payout !== void 0 ? validateBitcoinPayout(payout, getNetwork(network)) : void 0;
11432
+ const fee = validated?.fee ?? CLAIM_TX_VBYTES * BigInt(Math.ceil(feeRateSatPerVb));
11433
+ const remainder = validated ? htlcAmount - validated.total - fee : 0n;
11434
+ if (validated && remainder < 0n)
11435
+ throw new Error(
11436
+ "Funded amount cannot cover the committed recipients and fee"
11437
+ );
11348
11438
  if (fee >= htlcAmount) {
11349
11439
  throw new Error(
11350
11440
  `Fee (${fee} sats) exceeds HTLC amount (${htlcAmount} sats)`
@@ -11369,9 +11459,18 @@ function buildOnchainClaimTransaction(params) {
11369
11459
  amount: htlcAmount
11370
11460
  },
11371
11461
  tapLeafScript: [hashlockLeaf],
11372
- sequence: 4294967295
11462
+ sequence: validated ? 4294967293 : 4294967295
11373
11463
  });
11374
- tx.addOutputAddress(destinationAddress, claimAmount, networkConfig);
11464
+ if (validated && payout) {
11465
+ for (const recipient of allocateBitcoinPayout(payout, htlcAmount, fee).recipients)
11466
+ tx.addOutputAddress(
11467
+ recipient.address,
11468
+ BigInt(recipient.amountSats),
11469
+ networkConfig
11470
+ );
11471
+ } else {
11472
+ tx.addOutputAddress(destinationAddress, claimAmount, networkConfig);
11473
+ }
11375
11474
  const [controlBlockInfo, leafScriptWithVersion] = hashlockLeaf;
11376
11475
  const leafScript = leafScriptWithVersion.slice(0, -1);
11377
11476
  const leafVersion = leafScriptWithVersion[leafScriptWithVersion.length - 1];
@@ -11397,6 +11496,26 @@ function buildOnchainClaimTransaction(params) {
11397
11496
  tx.updateInput(0, {
11398
11497
  finalScriptWitness: [preimageBytes, sig, leafScript, encodedControlBlock]
11399
11498
  });
11499
+ if (validated && payout) {
11500
+ if (!Number.isFinite(feeRateSatPerVb) || feeRateSatPerVb <= 0)
11501
+ throw new Error("Fee rate must be a positive number of sat/vB");
11502
+ if (Number(fee) / tx.vsize < feeRateSatPerVb) {
11503
+ let required = BigInt(Math.ceil(tx.vsize * feeRateSatPerVb));
11504
+ if (Number(required - 1n) / tx.vsize >= feeRateSatPerVb) required -= 1n;
11505
+ if (required > MAX_PAYOUT_FEE_SATS)
11506
+ throw new Error(
11507
+ `A ${feeRateSatPerVb} sat/vB claim needs ${required} sats, above the ${MAX_PAYOUT_FEE_SATS}-sat payout fee cap`
11508
+ );
11509
+ if (htlcAmount - validated.total < required)
11510
+ throw new Error(
11511
+ `Surplus cannot cover the ${required}-sat fee for ${feeRateSatPerVb} sat/vB without reducing recipients`
11512
+ );
11513
+ return buildOnchainClaimTransaction({
11514
+ ...params,
11515
+ bitcoinPayout: { ...payout, feeSats: required.toString() }
11516
+ });
11517
+ }
11518
+ }
11400
11519
  const txHex = hex.encode(tx.extract());
11401
11520
  const txId = tx.id;
11402
11521
  const htlcAddress2 = Address(networkConfig).encode({
@@ -11404,6 +11523,7 @@ function buildOnchainClaimTransaction(params) {
11404
11523
  pubkey: p2tr2.tweakedPubkey
11405
11524
  });
11406
11525
  return {
11526
+ vsize: tx.vsize,
11407
11527
  txHex,
11408
11528
  txId,
11409
11529
  claimAmount,
@@ -11797,6 +11917,9 @@ function recoveredKeysChange(stored, index, derivedPreimageHash) {
11797
11917
  function unboundTerms(fresh, swapParams) {
11798
11918
  try {
11799
11919
  switch (fresh.direction) {
11920
+ case "spark_to_evm":
11921
+ assertSparkFunding(fresh, bytesToHex(swapParams.preimageHash));
11922
+ break;
11800
11923
  case "lightning_to_arkade":
11801
11924
  case "lightning_to_evm":
11802
11925
  case "lightning_to_bitcoin":
@@ -11878,6 +12001,7 @@ var PAYOUT_FIELD = {
11878
12001
  arkade_to_evm: "target_evm_address",
11879
12002
  bitcoin_to_evm: "target_evm_address",
11880
12003
  lightning_to_evm: "target_evm_address",
12004
+ spark_to_evm: "target_evm_address",
11881
12005
  evm_to_bitcoin: "target_btc_address",
11882
12006
  lightning_to_bitcoin: "target_btc_address",
11883
12007
  btc_to_arkade: "target_arkade_address",
@@ -11931,6 +12055,15 @@ function withStoredTerms(stored, fresh, refused) {
11931
12055
  if (field in before) kept[field] = before[field];
11932
12056
  else if (condemned.includes(field)) delete kept[field];
11933
12057
  }
12058
+ if (stored.response.direction === "spark_to_evm") {
12059
+ const original = stored.response;
12060
+ kept.funding = {
12061
+ ...original.funding,
12062
+ payment_id: fresh.direction === "spark_to_evm" ? fresh.funding?.payment_id ?? original.funding.payment_id : original.funding.payment_id
12063
+ };
12064
+ kept.source_amount = original.source_amount;
12065
+ kept.network = original.network;
12066
+ }
11934
12067
  return kept;
11935
12068
  }
11936
12069
  function swapTermsChange(stored, fresh) {
@@ -11954,6 +12087,30 @@ function swapTermsChange(stored, fresh) {
11954
12087
  };
11955
12088
  const payout = compare(["direction", "bridge_target_chain"], (value) => value) ?? compare(PAYOUT_FIELDS, addressKey);
11956
12089
  if (payout) return payout;
12090
+ if (stored.response.direction === "spark_to_evm" && fresh.direction === "spark_to_evm") {
12091
+ const old = stored.response;
12092
+ if (old.funding.address !== fresh.funding.address)
12093
+ return changed(
12094
+ "funding.address",
12095
+ old.funding.address,
12096
+ fresh.funding.address
12097
+ );
12098
+ if (old.funding.expiry_duration_secs !== fresh.funding.expiry_duration_secs)
12099
+ return changed(
12100
+ "funding.expiry_duration_secs",
12101
+ String(old.funding.expiry_duration_secs),
12102
+ String(fresh.funding.expiry_duration_secs)
12103
+ );
12104
+ if (old.source_amount !== fresh.source_amount)
12105
+ return changed("source_amount", old.source_amount, fresh.source_amount);
12106
+ if (old.network !== fresh.network)
12107
+ return changed("network", old.network, fresh.network);
12108
+ try {
12109
+ assertSparkFunding(fresh, stored.preimageHash);
12110
+ } catch (error) {
12111
+ return error instanceof SwapVerificationError ? error : changed("funding", "valid native Spark terms", String(error));
12112
+ }
12113
+ }
11957
12114
  if (EVM_SOURCED.has(stored.response.direction)) return void 0;
11958
12115
  const difference = compare(HASH_FIELDS, normalizeHash) ?? compare(ADDRESS_FIELDS, (address2) => address2.toLowerCase()) ?? compare(INVOICE_FIELDS, invoiceKey);
11959
12116
  if (difference) return difference;
@@ -11971,6 +12128,50 @@ function swapTermsChange(stored, fresh) {
11971
12128
  }
11972
12129
  return void 0;
11973
12130
  }
12131
+ function assertSparkFunding(data, ownHash) {
12132
+ const fail = (field, expected, received) => {
12133
+ throw new SwapVerificationError("Invalid native Spark funding terms", {
12134
+ field,
12135
+ expected,
12136
+ received,
12137
+ swapId: data.id
12138
+ });
12139
+ };
12140
+ if (normalizeHash(data.hash_lock) !== normalizeHash(ownHash)) {
12141
+ fail("hash_lock", ownHash, data.hash_lock);
12142
+ }
12143
+ let prefix;
12144
+ try {
12145
+ prefix = bech32m.decode(
12146
+ data.funding.address,
12147
+ 1023
12148
+ ).prefix;
12149
+ } catch {
12150
+ fail(
12151
+ "funding.address",
12152
+ "valid Spark bech32m address",
12153
+ data.funding.address
12154
+ );
12155
+ return;
12156
+ }
12157
+ const expectedPrefix = data.network === "bitcoin" ? "spark" : data.network === "regtest" ? "sparkrt" : void 0;
12158
+ if (!expectedPrefix || prefix !== expectedPrefix)
12159
+ fail(
12160
+ "funding.address",
12161
+ expectedPrefix ?? "supported Spark network",
12162
+ prefix
12163
+ );
12164
+ if (!Number.isSafeInteger(data.funding.expiry_duration_secs) || data.funding.expiry_duration_secs <= 0) {
12165
+ fail(
12166
+ "funding.expiry_duration_secs",
12167
+ "positive safe integer",
12168
+ String(data.funding.expiry_duration_secs)
12169
+ );
12170
+ }
12171
+ if (!/^[1-9][0-9]*$/.test(data.source_amount) || BigInt(data.source_amount) > 18446744073709551615n) {
12172
+ fail("source_amount", "positive u64 sats", data.source_amount);
12173
+ }
12174
+ }
11974
12175
  var MAX_RETRIES = 10;
11975
12176
  var SKIP_COUNT = 10;
11976
12177
  function isHashCollisionError(message) {
@@ -12024,6 +12225,7 @@ async function createArkadeToEvmSwapGeneric(options, ctx, claimingAddressOverrid
12024
12225
  amount_out: options.targetAmount?.toString(),
12025
12226
  referral_code: options.referralCode ?? ctx.referralCode,
12026
12227
  extra_fees: options.extraFees,
12228
+ promo_code: options.promoCode,
12027
12229
  gasless: options.gasless ?? true,
12028
12230
  bridge_target_chain: options.bridgeParams?.targetChain,
12029
12231
  bridge_target_token_address: options.bridgeParams?.targetTokenAddress,
@@ -12089,7 +12291,8 @@ async function createArkadeToLightningSwap(options, ctx) {
12089
12291
  user_id: userId,
12090
12292
  arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,
12091
12293
  referral_code: options.referralCode ?? ctx.referralCode,
12092
- extra_fees: options.extraFees
12294
+ extra_fees: options.extraFees,
12295
+ promo_code: options.promoCode
12093
12296
  };
12094
12297
  const { data, error } = await ctx.apiClient.POST("/swap/arkade/lightning", {
12095
12298
  body
@@ -12129,6 +12332,7 @@ async function createBitcoinToEvmSwap(options, ctx, claimingAddressOverride) {
12129
12332
  amount_out: options.targetAmount?.toString(),
12130
12333
  referral_code: options.referralCode ?? ctx.referralCode,
12131
12334
  extra_fees: options.extraFees,
12335
+ promo_code: options.promoCode,
12132
12336
  gasless: options.gasless ?? true,
12133
12337
  bridge_target_chain: options.bridgeParams?.targetChain,
12134
12338
  bridge_target_token_address: options.bridgeParams?.targetTokenAddress,
@@ -12180,6 +12384,7 @@ async function createBitcoinToArkadeSwap(options, ctx) {
12180
12384
  target_arkade_address: options.targetAddress,
12181
12385
  referral_code: options.referralCode ?? ctx.referralCode,
12182
12386
  extra_fees: options.extraFees,
12387
+ promo_code: options.promoCode,
12183
12388
  btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,
12184
12389
  arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT
12185
12390
  };
@@ -12237,7 +12442,8 @@ async function createBitcoinToLightningSwap(options, ctx) {
12237
12442
  user_id: userId,
12238
12443
  btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,
12239
12444
  referral_code: options.referralCode ?? ctx.referralCode,
12240
- extra_fees: options.extraFees
12445
+ extra_fees: options.extraFees,
12446
+ promo_code: options.promoCode
12241
12447
  };
12242
12448
  const { data, error } = await ctx.apiClient.POST("/swap/bitcoin/lightning", {
12243
12449
  body
@@ -12257,11 +12463,13 @@ async function createBitcoinToLightningSwap(options, ctx) {
12257
12463
  });
12258
12464
  return { response: data, swapParams };
12259
12465
  }
12260
- function fundingTermsOf(data) {
12466
+ function fundingTermsOf(data, depositor) {
12467
+ if (depositor) assertAddressEchoed(data, "client_evm_address", depositor);
12261
12468
  if (!data.evm_chain_id || !data.evm_coordinator_address || !data.evm_htlc_address || !data.server_evm_address || !data.evm_refund_locktime || data.source_amount === void 0 || data.source_amount === null || !data.source_token?.token_id) {
12262
12469
  return void 0;
12263
12470
  }
12264
12471
  return {
12472
+ depositor: depositor?.toLowerCase(),
12265
12473
  chainId: data.evm_chain_id,
12266
12474
  coordinator: data.evm_coordinator_address.toLowerCase(),
12267
12475
  htlcAddress: data.evm_htlc_address.toLowerCase(),
@@ -12281,7 +12489,7 @@ async function createEvmToArkadeSwapGeneric(options, ctx) {
12281
12489
  const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;
12282
12490
  const receiverPk = bytesToHex(swapParams.publicKey);
12283
12491
  const userId = bytesToHex(swapParams.userId);
12284
- const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;
12492
+ const userAddress = options.gasless ? deriveEvmAddress(swapParams.secretKey) : options.userAddress;
12285
12493
  const { data, error } = await ctx.apiClient.POST("/swap/evm/arkade", {
12286
12494
  body: {
12287
12495
  hash_lock: hashLock,
@@ -12295,6 +12503,7 @@ async function createEvmToArkadeSwapGeneric(options, ctx) {
12295
12503
  amount_out: options.targetAmount ? Number(options.targetAmount) : void 0,
12296
12504
  referral_code: options.referralCode ?? ctx.referralCode,
12297
12505
  extra_fees: options.extraFees,
12506
+ promo_code: options.promoCode,
12298
12507
  gasless: options.gasless ?? false,
12299
12508
  arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,
12300
12509
  bridge_source_chain: options.inboundBridgeParams?.sourceChain,
@@ -12317,18 +12526,84 @@ async function createEvmToArkadeSwapGeneric(options, ctx) {
12317
12526
  },
12318
12527
  options.targetAddress,
12319
12528
  void 0,
12320
- { evmFundingTerms: fundingTermsOf(data) }
12529
+ { evmFundingTerms: fundingTermsOf(data, userAddress) }
12321
12530
  );
12322
12531
  return { response: data, swapParams };
12323
12532
  });
12324
12533
  }
12534
+ var DUST = 546n;
12535
+ function tolerance(bps) {
12536
+ const value = bps ?? 0;
12537
+ if (!Number.isInteger(value) || value < 0 || value > 100)
12538
+ throw new Error("Payment slippage must be between 0 and 100 basis points");
12539
+ return BigInt(value);
12540
+ }
12541
+ function floorOf(amount, bps) {
12542
+ const loss = amount * bps / 10000n;
12543
+ return amount - (loss < amount - DUST ? loss : amount - DUST);
12544
+ }
12545
+ var NETWORKS = [
12546
+ NETWORK,
12547
+ TEST_NETWORK,
12548
+ { ...TEST_NETWORK, bech32: "bcrt" }
12549
+ ];
12550
+ function bitcoinNetworkOf(address2) {
12551
+ const network = NETWORKS.find((candidate) => {
12552
+ try {
12553
+ Address(candidate).decode(address2);
12554
+ return true;
12555
+ } catch {
12556
+ return false;
12557
+ }
12558
+ });
12559
+ if (!network) throw new Error("Invalid Bitcoin recovery address");
12560
+ return network;
12561
+ }
12562
+ function commitBitcoinPayment(request, network) {
12563
+ const bps = tolerance(request.maxSlippageBps);
12564
+ const nominal = {
12565
+ recipients: request.recipients.map((r) => ({ ...r })),
12566
+ feeSats: request.feeSats
12567
+ };
12568
+ const { total, fee } = validateBitcoinPayout(nominal, network);
12569
+ const payout = {
12570
+ recipients: nominal.recipients.map((r) => ({
12571
+ address: r.address,
12572
+ amountSats: floorOf(BigInt(r.amountSats), bps).toString()
12573
+ })),
12574
+ feeSats: nominal.feeSats
12575
+ };
12576
+ const floors = validateBitcoinPayout(payout, network);
12577
+ return {
12578
+ payout,
12579
+ minimumPayoutSats: floors.total + floors.fee,
12580
+ nominalSats: total + fee
12581
+ };
12582
+ }
12583
+ function minimumBitcoinPayout(request, network) {
12584
+ return commitBitcoinPayment(request, network).minimumPayoutSats;
12585
+ }
12325
12586
  async function createEvmToBitcoinSwap(options, ctx) {
12587
+ let payment;
12588
+ if (options.bitcoinPayout !== void 0) {
12589
+ if (options.sourceAmount !== void 0)
12590
+ throw new Error("Payments require an exact target amount");
12591
+ const committed = commitBitcoinPayment(
12592
+ options.bitcoinPayout,
12593
+ bitcoinNetworkOf(options.targetAddress)
12594
+ );
12595
+ if (!Number.isSafeInteger(options.targetAmount) || committed.nominalSats !== BigInt(options.targetAmount))
12596
+ throw new Error(
12597
+ "Payment total must equal recipients plus the Bitcoin fee"
12598
+ );
12599
+ payment = committed;
12600
+ }
12326
12601
  return retryOnHashCollision(ctx, async () => {
12327
12602
  const swapParams = await ctx.deriveSwapParams();
12328
12603
  const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;
12329
12604
  const claimPk = bytesToHex(swapParams.publicKey);
12330
12605
  const userId = bytesToHex(swapParams.userId);
12331
- const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;
12606
+ const userAddress = options.gasless ? deriveEvmAddress(swapParams.secretKey) : options.userAddress;
12332
12607
  const { data, error } = await ctx.apiClient.POST("/swap/evm/bitcoin", {
12333
12608
  body: {
12334
12609
  hash_lock: hashLock,
@@ -12340,9 +12615,11 @@ async function createEvmToBitcoinSwap(options, ctx) {
12340
12615
  user_address: userAddress,
12341
12616
  target_address: options.targetAddress,
12342
12617
  amount_in: options.sourceAmount ? options.sourceAmount.toString() : void 0,
12618
+ minimum_payout_sats: payment ? Number(payment.minimumPayoutSats) : void 0,
12343
12619
  amount_out: options.targetAmount ? Number(options.targetAmount) : void 0,
12344
12620
  referral_code: options.referralCode ?? ctx.referralCode,
12345
12621
  extra_fees: options.extraFees,
12622
+ promo_code: options.promoCode,
12346
12623
  gasless: options.gasless ?? false,
12347
12624
  bridge_source_chain: options.inboundBridgeParams?.sourceChain,
12348
12625
  bridge_source_token_address: options.inboundBridgeParams?.sourceTokenAddress
@@ -12364,7 +12641,10 @@ async function createEvmToBitcoinSwap(options, ctx) {
12364
12641
  },
12365
12642
  options.targetAddress,
12366
12643
  void 0,
12367
- { evmFundingTerms: fundingTermsOf(data) }
12644
+ {
12645
+ evmFundingTerms: fundingTermsOf(data, userAddress),
12646
+ bitcoinPayout: payment?.payout
12647
+ }
12368
12648
  );
12369
12649
  return { response: data, swapParams };
12370
12650
  });
@@ -12388,7 +12668,7 @@ async function createEvmToLightningSwap(options, ctx) {
12388
12668
  }
12389
12669
  const swapParams = await ctx.deriveSwapParams();
12390
12670
  const userId = bytesToHex(swapParams.userId);
12391
- const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;
12671
+ const userAddress = options.gasless ? deriveEvmAddress(swapParams.secretKey) : options.userAddress;
12392
12672
  const { data, error } = await ctx.apiClient.POST("/swap/evm/lightning", {
12393
12673
  body: {
12394
12674
  lightning_invoice: options.lightningInvoice,
@@ -12402,6 +12682,7 @@ async function createEvmToLightningSwap(options, ctx) {
12402
12682
  user_id: userId,
12403
12683
  referral_code: options.referralCode ?? ctx.referralCode,
12404
12684
  extra_fees: options.extraFees,
12685
+ promo_code: options.promoCode,
12405
12686
  gasless: options.gasless ?? false,
12406
12687
  bridge_source_chain: options.inboundBridgeParams?.sourceChain,
12407
12688
  bridge_source_token_address: options.inboundBridgeParams?.sourceTokenAddress
@@ -12423,7 +12704,10 @@ async function createEvmToLightningSwap(options, ctx) {
12423
12704
  },
12424
12705
  void 0,
12425
12706
  void 0,
12426
- { lightningPaymentHash, evmFundingTerms: fundingTermsOf(data) }
12707
+ {
12708
+ lightningPaymentHash,
12709
+ evmFundingTerms: fundingTermsOf(data, userAddress)
12710
+ }
12427
12711
  );
12428
12712
  return { response: data, swapParams };
12429
12713
  }
@@ -12449,6 +12733,7 @@ async function createLightningToArkadeSwap(options, ctx) {
12449
12733
  arkade_htlc_script_version: ARKADE_HTLC_SCRIPT_VERSION_STRICT,
12450
12734
  referral_code: options.referralCode ?? ctx.referralCode,
12451
12735
  extra_fees: options.extraFees,
12736
+ promo_code: options.promoCode,
12452
12737
  // `undefined` is omitted from the JSON body so the server applies its
12453
12738
  // default; an explicit "" is sent to blank the invoice description.
12454
12739
  invoice_description: options.invoiceDescription
@@ -12491,6 +12776,7 @@ async function createLightningToBitcoinSwap(options, ctx) {
12491
12776
  btc_htlc_script_version: BTC_HTLC_SCRIPT_VERSION_STRICT,
12492
12777
  referral_code: options.referralCode ?? ctx.referralCode,
12493
12778
  extra_fees: options.extraFees,
12779
+ promo_code: options.promoCode,
12494
12780
  invoice_description: options.invoiceDescription
12495
12781
  };
12496
12782
  const { data, error } = await ctx.apiClient.POST(
@@ -12535,6 +12821,7 @@ async function createLightningToEvmSwap(options, ctx, claimingAddressOverride) {
12535
12821
  invoice_description: options.invoiceDescription,
12536
12822
  referral_code: options.referralCode ?? ctx.referralCode,
12537
12823
  extra_fees: options.extraFees,
12824
+ promo_code: options.promoCode,
12538
12825
  gasless: options.gasless ?? true,
12539
12826
  bridge_target_chain: options.bridgeParams?.targetChain,
12540
12827
  bridge_target_token_address: options.bridgeParams?.targetTokenAddress,
@@ -12568,6 +12855,76 @@ async function createLightningToEvmSwap(options, ctx, claimingAddressOverride) {
12568
12855
  return { response: data, swapParams };
12569
12856
  });
12570
12857
  }
12858
+ async function createSparkToEvmSwap(options, ctx, claimingAddressOverride) {
12859
+ if (options.sourceAmount == null === (options.targetAmount == null)) {
12860
+ throw new Error("Provide exactly one of sourceAmount or targetAmount");
12861
+ }
12862
+ if (options.sourceAmount != null && (!Number.isSafeInteger(options.sourceAmount) || options.sourceAmount <= 0)) {
12863
+ throw new Error("sourceAmount must be a positive safe integer in sats");
12864
+ }
12865
+ return retryOnHashCollision(ctx, async () => {
12866
+ const swapParams = await ctx.deriveSwapParams();
12867
+ const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;
12868
+ const userId = bytesToHex(swapParams.userId);
12869
+ const claimingAddress = claimingAddressOverride ?? deriveEvmAddress(swapParams.secretKey);
12870
+ const body = {
12871
+ hash_lock: hashLock,
12872
+ user_id: userId,
12873
+ claiming_address: claimingAddress,
12874
+ target_address: options.targetAddress,
12875
+ token_address: options.tokenAddress,
12876
+ evm_chain_id: options.evmChainId,
12877
+ amount_in: options.sourceAmount,
12878
+ amount_out: options.targetAmount?.toString(),
12879
+ referral_code: options.referralCode ?? ctx.referralCode,
12880
+ extra_fees: options.extraFees,
12881
+ promo_code: options.promoCode,
12882
+ gasless: options.gasless ?? true,
12883
+ bridge_target_chain: options.bridgeParams?.targetChain,
12884
+ bridge_target_token_address: options.bridgeParams?.targetTokenAddress,
12885
+ bridge_recipient_setup: options.bridgeParams?.recipientSetup
12886
+ };
12887
+ const { data, error } = await ctx.apiClient.POST("/swap/spark/evm", {
12888
+ body
12889
+ });
12890
+ if (error) {
12891
+ throw new Error(`Failed to create swap: ${JSON.stringify(error)}`);
12892
+ }
12893
+ if (!data) {
12894
+ throw new Error("No swap data returned");
12895
+ }
12896
+ assertSparkFunding(data, hashLock);
12897
+ if (options.sourceAmount != null && BigInt(data.source_amount) !== BigInt(options.sourceAmount)) {
12898
+ throw new Error(
12899
+ "Native Spark source amount differs from the requested amount"
12900
+ );
12901
+ }
12902
+ assertAddressEchoed(data, "target_evm_address", options.targetAddress);
12903
+ assertAddressEchoed(data, "client_evm_address", claimingAddress);
12904
+ await ctx.storeSwap(
12905
+ data.id,
12906
+ swapParams,
12907
+ {
12908
+ ...data,
12909
+ direction: "spark_to_evm"
12910
+ },
12911
+ options.targetAddress,
12912
+ {
12913
+ recipient: options.bridgeParams?.recipient,
12914
+ recipientWallet: options.bridgeParams?.recipientWallet
12915
+ }
12916
+ );
12917
+ return { response: data, swapParams };
12918
+ });
12919
+ }
12920
+ function assertPaymentClaimWindow(network, refundLocktime, alreadySubmitted = false, now = Math.floor(Date.now() / 1e3)) {
12921
+ if (!Number.isFinite(refundLocktime))
12922
+ throw new Error("Invalid Bitcoin refund expiry");
12923
+ if (!alreadySubmitted && refundLocktime - now < (network === "mainnet" ? 600 : 30))
12924
+ throw new Error(
12925
+ "Too close to Bitcoin refund expiry to safely reveal the payment preimage"
12926
+ );
12927
+ }
12571
12928
  init_sha2();
12572
12929
  init_utils();
12573
12930
  var REQUEST_TIMEOUT_MS = 5e3;
@@ -13145,6 +13502,23 @@ async function broadcastTransactionWithRetry(esploraUrls, txHex, retries = 5) {
13145
13502
  }
13146
13503
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
13147
13504
  }
13505
+ async function fetchMinimumRelayFeeRate(esploraUrls) {
13506
+ try {
13507
+ return await withFallback(esploraUrls, async (url) => {
13508
+ const response = await fetchWithTimeout(
13509
+ `${url}/v1/fees/recommended`,
13510
+ LOOKUP_TIMEOUT_MS
13511
+ );
13512
+ if (!response.ok) throw new Error("Relay policy unavailable");
13513
+ const { minimumFee } = await response.json();
13514
+ if (typeof minimumFee !== "number" || !Number.isFinite(minimumFee) || minimumFee < 0)
13515
+ throw new Error("Invalid relay policy");
13516
+ return minimumFee;
13517
+ });
13518
+ } catch {
13519
+ return void 0;
13520
+ }
13521
+ }
13148
13522
  init_utils();
13149
13523
  var KERNEL_DELEGATION_TARGET = "0xd6CEDDe84be40893d153Be9d467CD6aD37875b28";
13150
13524
  var KERNEL_VERSION = "0.3.3";
@@ -14971,13 +15345,15 @@ function fromWireQuoteResponse(wire) {
14971
15345
  target_amount: wire.target_amount,
14972
15346
  net_source_amount: wire.net_source_amount,
14973
15347
  net_target_amount: wire.net_target_amount,
14974
- bridge_fee: wire.bridge_fee ?? void 0
15348
+ bridge_fee: wire.bridge_fee ?? void 0,
15349
+ promo: wire.promo ?? void 0
14975
15350
  };
14976
15351
  }
14977
15352
  function fromWireReferralFeeResponse(wire) {
14978
15353
  return {
14979
15354
  extra_fee_rate: wire.extra_fee_rate,
14980
15355
  base_fee_rate: wire.base_fee_rate ?? void 0,
15356
+ promo: wire.promo ?? void 0,
14981
15357
  referral_label: wire.referral_label ?? void 0
14982
15358
  };
14983
15359
  }
@@ -15425,7 +15801,8 @@ function satsToLightningOptions(options, sourceName) {
15425
15801
  const kind = classifyLightningDestination(destination);
15426
15802
  const common = {
15427
15803
  referralCode: options.referralCode,
15428
- extraFees: options.extraFees
15804
+ extraFees: options.extraFees,
15805
+ promoCode: options.promoCode
15429
15806
  };
15430
15807
  if (kind === "invoice") {
15431
15808
  if (options.sourceAmount != null && options.targetAmount != null) {
@@ -15756,6 +16133,7 @@ var Client = class _Client {
15756
16133
  #composeStaticCache = /* @__PURE__ */ new Map();
15757
16134
  #signerStorage;
15758
16135
  #swapStorage;
16136
+ #ephemeralKeyIndex = 0;
15759
16137
  #statusWatcher = null;
15760
16138
  #cctpInbound = null;
15761
16139
  #electrumWs = null;
@@ -15924,7 +16302,7 @@ var Client = class _Client {
15924
16302
  * @returns The derived swap parameters.
15925
16303
  */
15926
16304
  async deriveSwapParams() {
15927
- let index = 0;
16305
+ let index = this.#ephemeralKeyIndex++;
15928
16306
  if (this.#signerStorage) {
15929
16307
  index = await this.#signerStorage.incrementKeyIndex();
15930
16308
  }
@@ -15944,8 +16322,8 @@ var Client = class _Client {
15944
16322
  /**
15945
16323
  * Get the deterministic EVM address for this SDK key.
15946
16324
  *
15947
- * This address is reused across all gasless swaps, so a single
15948
- * Permit2 approval is sufficient for multiple swaps.
16325
+ * Legacy wallet-level address. New gasless swaps use their own deposit
16326
+ * address; read it from the swap response or getSwapDepositorKey(swapId).
15949
16327
  *
15950
16328
  * @returns Checksummed EVM address (0x-prefixed).
15951
16329
  */
@@ -16053,33 +16431,29 @@ var Client = class _Client {
16053
16431
  }
16054
16432
  return this.#getEvmSigningKey();
16055
16433
  }
16434
+ async #getFundingEvmSigningKey(storedSwap, gasless) {
16435
+ const depositor = storedSwap.evmFundingTerms?.depositor;
16436
+ if (depositor) {
16437
+ const { privateKey } = await this.getSwapDepositorKey(storedSwap.swapId);
16438
+ if (deriveEvmAddress(privateKey).toLowerCase() !== depositor.toLowerCase()) {
16439
+ throw new Error("Funding key does not match the pinned depositor.");
16440
+ }
16441
+ return privateKey;
16442
+ }
16443
+ return gasless ? this.#getCollabRefundEvmSigningKey(storedSwap) : this.#getEvmSigningKey();
16444
+ }
16056
16445
  /**
16057
16446
  * Select the SDK-controlled EVM key that matches the swap's recorded depositor.
16058
16447
  *
16059
- * Current gasless EVM-sourced swaps use the deterministic wallet-level EVM key;
16060
- * older gasless swaps may have used the per-swap key. Non-gasless SDK-funded
16448
+ * New gasless EVM-sourced swaps use their per-swap key; existing swaps
16449
+ * may still use the deterministic wallet-level EVM key. Non-gasless SDK-funded
16061
16450
  * swaps still use the per-swap key even though client_evm_address may point at
16062
16451
  * the user's wallet rather than the later Permit2 depositor.
16063
16452
  */
16064
- #getCollabRefundEvmSigningKey(storedSwap, walletMethod = "collabRefundEvmWithSigner") {
16065
- const swapKey = storedSwap.secretKey;
16066
- const response = storedSwap.response;
16067
- if (!response.gasless) {
16068
- return swapKey;
16069
- }
16070
- const deterministicKey = this.#getEvmSigningKey();
16071
- const deterministicAddress = deriveEvmAddress(deterministicKey);
16072
- const swapAddress = deriveEvmAddress(swapKey);
16073
- const clientAddress = response.client_evm_address?.toLowerCase();
16074
- if (clientAddress === deterministicAddress.toLowerCase() || !clientAddress) {
16075
- return deterministicKey;
16076
- }
16077
- if (clientAddress === swapAddress.toLowerCase()) {
16078
- return swapKey;
16079
- }
16080
- throw new Error(
16081
- `Cannot sign for this swap with an SDK-controlled key: swap depositor is ${response.client_evm_address ?? "unknown"}, but SDK-controlled addresses are ${deterministicAddress} (current gasless key) and ${swapAddress} (legacy per-swap key). Use ${walletMethod} with the depositor wallet instead.`
16082
- );
16453
+ async #getCollabRefundEvmSigningKey(storedSwap, _walletMethod = "collabRefundEvmWithSigner") {
16454
+ if (!storedSwap.evmFundingTerms?.depositor && !storedSwap.response.gasless && storedSwap.evmDepositorKeyIndex === void 0 && !storedSwap.evmDepositorSecretKey)
16455
+ return storedSwap.secretKey;
16456
+ return (await this.getSwapDepositorKey(storedSwap.swapId)).privateKey;
16083
16457
  }
16084
16458
  /**
16085
16459
  * Gets the current key index from storage.
@@ -16263,7 +16637,11 @@ var Client = class _Client {
16263
16637
  async getReferralFee(params) {
16264
16638
  const { data, error } = await this.#apiClient.GET("/referral-fee", {
16265
16639
  params: {
16266
- query: { ref: params.referralCode, extra_fees: params.extraFees }
16640
+ query: {
16641
+ ref: params.referralCode,
16642
+ extra_fees: params.extraFees,
16643
+ promo_code: params.promoCode
16644
+ }
16267
16645
  }
16268
16646
  });
16269
16647
  if (error || !data) {
@@ -16334,12 +16712,14 @@ var Client = class _Client {
16334
16712
  ...params,
16335
16713
  referralCode: params.referralCode ?? this.#config.referralCode
16336
16714
  };
16337
- const referralFee = params.referralCode != null || params.extraFees != null ? this.#composeStatic(
16715
+ const fetchReferralFee = () => this.getReferralFee({
16716
+ referralCode: params.referralCode,
16717
+ extraFees: params.extraFees,
16718
+ promoCode: params.promoCode
16719
+ });
16720
+ const referralFee = params.promoCode != null ? fetchReferralFee() : params.referralCode != null || params.extraFees != null ? this.#composeStatic(
16338
16721
  `referral-fee|${params.referralCode ?? ""}|${params.extraFees ?? ""}`,
16339
- () => this.getReferralFee({
16340
- referralCode: params.referralCode,
16341
- extraFees: params.extraFees
16342
- })
16722
+ fetchReferralFee
16343
16723
  ) : Promise.resolve(void 0);
16344
16724
  const [swapPairs, networkFees, chainConfig, referral] = await Promise.all([
16345
16725
  this.#composeStatic("swap-pairs", () => this.getSwapPairs()),
@@ -16353,6 +16733,7 @@ var Client = class _Client {
16353
16733
  chainConfig,
16354
16734
  referralExtraFeeRate: referral?.extra_fee_rate,
16355
16735
  referralBaseFeeRate: referral?.base_fee_rate,
16736
+ referralPromo: referral?.promo,
16356
16737
  getDexQuote: (p) => this.getDexQuote(p)
16357
16738
  });
16358
16739
  }
@@ -16426,6 +16807,7 @@ var Client = class _Client {
16426
16807
  // Per-call referral wins; fall back to the client default.
16427
16808
  referralCode: params.referralCode ?? this.#config.referralCode,
16428
16809
  extraFees: params.extraFees,
16810
+ promoCode: params.promoCode,
16429
16811
  bridgeRecipientSetup: params.bridgeRecipientSetup
16430
16812
  });
16431
16813
  } catch (err) {
@@ -16479,7 +16861,8 @@ var Client = class _Client {
16479
16861
  target_amount_sats: params.targetAmountSats,
16480
16862
  // Per-call referral wins; fall back to the client default.
16481
16863
  ref: params.referralCode ?? this.#config.referralCode,
16482
- extra_fees: params.extraFees
16864
+ extra_fees: params.extraFees,
16865
+ promo_code: params.promoCode
16483
16866
  }
16484
16867
  }
16485
16868
  });
@@ -16504,7 +16887,8 @@ var Client = class _Client {
16504
16887
  protocolFeeRate: data.protocol_fee_rate,
16505
16888
  minAmountSats: data.min_amount_sats,
16506
16889
  maxAmountSats: data.max_amount_sats,
16507
- exchangeRate: data.exchange_rate
16890
+ exchangeRate: data.exchange_rate,
16891
+ promo: data.promo ?? void 0
16508
16892
  };
16509
16893
  }
16510
16894
  /**
@@ -16532,7 +16916,8 @@ var Client = class _Client {
16532
16916
  lnurl: kind === "lnurl" ? destination : void 0,
16533
16917
  targetAmountSats,
16534
16918
  referralCode: params.referralCode,
16535
- extraFees: params.extraFees
16919
+ extraFees: params.extraFees,
16920
+ promoCode: params.promoCode
16536
16921
  });
16537
16922
  const sourceAmountOut = evmSource ? q.sourceAmount : sourcePinned ? q.sourceAmount : String(q.targetAmountSats);
16538
16923
  const targetAmountOut = !evmSource && sourcePinned ? q.sourceAmount : String(q.targetAmountSats);
@@ -16547,7 +16932,8 @@ var Client = class _Client {
16547
16932
  source_amount: sourceAmountOut,
16548
16933
  target_amount: targetAmountOut,
16549
16934
  net_source_amount: q.sourceAmount,
16550
- net_target_amount: String(q.targetAmountSats)
16935
+ net_target_amount: String(q.targetAmountSats),
16936
+ promo: q.promo
16551
16937
  };
16552
16938
  }
16553
16939
  /**
@@ -16640,7 +17026,8 @@ var Client = class _Client {
16640
17026
  // Per-call referralCode wins; fall back to the client config default
16641
17027
  // (set via withReferralCode / withOrgCode).
16642
17028
  ref: params.referralCode ?? this.#config.referralCode,
16643
- extra_fees: params.extraFees
17029
+ extra_fees: params.extraFees,
17030
+ promo_code: params.promoCode
16644
17031
  };
16645
17032
  const { data, error } = await this.#apiClient.GET("/quote", {
16646
17033
  params: {
@@ -16862,6 +17249,35 @@ var Client = class _Client {
16862
17249
  storedSwaps.push(stored);
16863
17250
  }
16864
17251
  }
17252
+ if (this.#swapStorage) {
17253
+ const recovered = await this.#swapStorage.getAll();
17254
+ for (const current of recovered) {
17255
+ if (current.evmFundingTerms?.depositor || current.evmDepositorSecretKey)
17256
+ continue;
17257
+ const response = current.response;
17258
+ if (response.gasless !== false || !response.client_evm_address)
17259
+ continue;
17260
+ const predecessor = recovered.find(
17261
+ (candidate) => candidate.swapId !== current.swapId && ["clientrefunded", "clientrefundedserverrefunded"].includes(
17262
+ candidate.response.status
17263
+ ) && candidate.keyIndex < current.keyIndex && deriveEvmAddress(
17264
+ this.deriveSwapParamsAtIndex(candidate.keyIndex).secretKey
17265
+ ).toLowerCase() === deriveEvmAddress(candidate.secretKey).toLowerCase() && deriveEvmAddress(candidate.secretKey).toLowerCase() === response.client_evm_address.toLowerCase()
17266
+ );
17267
+ if (predecessor) {
17268
+ const updated = {
17269
+ ...current,
17270
+ evmDepositorSecretKey: predecessor.secretKey,
17271
+ evmDepositorKeyIndex: predecessor.keyIndex
17272
+ };
17273
+ await this.#swapStorage.store(updated);
17274
+ const index = storedSwaps.findIndex(
17275
+ (swap) => swap.swapId === current.swapId
17276
+ );
17277
+ if (index >= 0) storedSwaps[index] = updated;
17278
+ }
17279
+ }
17280
+ }
16865
17281
  const currentKeyIndex = await this.getKeyIndex();
16866
17282
  const nextKeyIndex = Math.max(currentKeyIndex, data.next_index);
16867
17283
  if (nextKeyIndex !== currentKeyIndex) {
@@ -17015,7 +17431,7 @@ var Client = class _Client {
17015
17431
  }
17016
17432
  const swap = storedSwap.response;
17017
17433
  const secret = storedSwap.preimage;
17018
- if (swap.direction === "arkade_to_evm" || swap.direction === "bitcoin_to_evm" || swap.direction === "lightning_to_evm") {
17434
+ if (swap.direction === "arkade_to_evm" || swap.direction === "bitcoin_to_evm" || swap.direction === "lightning_to_evm" || swap.direction === "spark_to_evm") {
17019
17435
  const evmSwap = swap;
17020
17436
  const bridgeTargetChain = evmSwap.bridge_target_chain;
17021
17437
  const isSolanaBridge = bridgeTargetChain === "Solana";
@@ -17087,7 +17503,7 @@ var Client = class _Client {
17087
17503
  const swap = await this.getSwap(id, {
17088
17504
  updateStorage: true
17089
17505
  });
17090
- if (swap.direction !== "arkade_to_evm" && swap.direction !== "bitcoin_to_evm" && swap.direction !== "lightning_to_evm") {
17506
+ if (swap.direction !== "arkade_to_evm" && swap.direction !== "bitcoin_to_evm" && swap.direction !== "lightning_to_evm" && swap.direction !== "spark_to_evm") {
17091
17507
  throw new Error(
17092
17508
  `Expected an EVM-targeted swap (arkade_to_evm, bitcoin_to_evm or lightning_to_evm), got ${swap.direction}.`
17093
17509
  );
@@ -17275,7 +17691,7 @@ var Client = class _Client {
17275
17691
  }
17276
17692
  /** Whether an EVM claim can use the existing automatic sponsorship path. */
17277
17693
  canSponsorClaim(swap) {
17278
- return (swap.direction === "arkade_to_evm" || swap.direction === "bitcoin_to_evm" || swap.direction === "lightning_to_evm") && swap.evm_chain_id !== 30 && swap.evm_chain_id !== 31;
17694
+ return (swap.direction === "arkade_to_evm" || swap.direction === "bitcoin_to_evm" || swap.direction === "lightning_to_evm" || swap.direction === "spark_to_evm") && swap.evm_chain_id !== 30 && swap.evm_chain_id !== 31;
17279
17695
  }
17280
17696
  /**
17281
17697
  * Claims through the existing server relay or configured Arbitrum UserOp.
@@ -17996,16 +18412,51 @@ var Client = class _Client {
17996
18412
  message: `Could not find UTXO at HTLC address ${btcHtlcAddress} after waiting ${waitForFundingMs}ms. The server may not have funded the HTLC yet.`
17997
18413
  };
17998
18414
  }
17999
- const destinationAddress = options?.destinationAddress ?? storedPayoutTarget(storedSwap);
18000
- if (!destinationAddress) {
18415
+ const bitcoinPayout = storedSwap.bitcoinPayout;
18416
+ if (bitcoinPayout !== void 0 && options?.destinationAddress) {
18417
+ return {
18418
+ success: false,
18419
+ message: "This swap pays stored Bitcoin recipients; destinationAddress cannot override them."
18420
+ };
18421
+ }
18422
+ const destinationAddress = bitcoinPayout !== void 0 ? "" : options?.destinationAddress ?? storedPayoutTarget(storedSwap);
18423
+ if (bitcoinPayout === void 0 && !destinationAddress) {
18001
18424
  return {
18002
18425
  success: false,
18003
18426
  message: 'Destination address is required to claim BTC. Provide it via options: { destinationAddress: "bc1p..." }'
18004
18427
  };
18005
18428
  }
18006
- const feeRateSatPerVb = options?.feeRateSatPerVb ?? Math.max(2, await fetchFeeRateEstimate(esploraUrls, 2) ?? 0);
18429
+ let feeRateSatPerVb = options?.feeRateSatPerVb ?? Math.max(2, await fetchFeeRateEstimate(esploraUrls, 2) ?? 0);
18430
+ if (bitcoinPayout !== void 0) {
18431
+ const requested = options?.feeRateSatPerVb;
18432
+ if (requested !== void 0 && (!Number.isFinite(requested) || requested <= 0))
18433
+ return {
18434
+ success: false,
18435
+ message: "Failed to build claim transaction: Fee rate must be a positive number of sat/vB"
18436
+ };
18437
+ const relayFloor = options?.minimumRelayFeeRateSatPerVb ?? (network === "regtest" ? 0 : await fetchMinimumRelayFeeRate(esploraUrls));
18438
+ if (relayFloor === void 0 || !Number.isFinite(relayFloor) || relayFloor < 0)
18439
+ return {
18440
+ success: false,
18441
+ message: "Could not verify Bitcoin relay policy. Retry when the explorer is available or supply minimumRelayFeeRateSatPerVb."
18442
+ };
18443
+ feeRateSatPerVb = Math.max(feeRateSatPerVb, relayFloor);
18444
+ try {
18445
+ assertPaymentClaimWindow(
18446
+ network,
18447
+ btcRefundLocktime,
18448
+ !!storedSwap.bitcoinClaimBroadcast
18449
+ );
18450
+ } catch (error) {
18451
+ return {
18452
+ success: false,
18453
+ message: error instanceof Error ? error.message : String(error)
18454
+ };
18455
+ }
18456
+ }
18007
18457
  try {
18008
18458
  const result = buildOnchainClaimTransaction({
18459
+ bitcoinPayout,
18009
18460
  fundingTxId: htlcOutput.txid,
18010
18461
  fundingVout: htlcOutput.vout,
18011
18462
  htlcAmount: htlcOutput.amount,
@@ -18015,12 +18466,21 @@ var Client = class _Client {
18015
18466
  userSecretKey: storedSwap.secretKey,
18016
18467
  preimage: storedSwap.preimage,
18017
18468
  refundLocktime: btcRefundLocktime,
18018
- destinationAddress,
18469
+ // Unused when a payout is stored; checked above otherwise.
18470
+ destinationAddress: destinationAddress ?? "",
18019
18471
  feeRateSatPerVb,
18020
18472
  network,
18021
18473
  btcHtlcScriptVersion
18022
18474
  });
18023
18475
  try {
18476
+ if (bitcoinPayout !== void 0 && this.#swapStorage) {
18477
+ const latest = await this.#swapStorage.get(storedSwap.swapId);
18478
+ await this.#swapStorage.store({
18479
+ ...latest ?? storedSwap,
18480
+ // Once submitted, even a timeout can mean the preimage is public.
18481
+ bitcoinClaimBroadcast: result.txId
18482
+ });
18483
+ }
18024
18484
  await this.#broadcastBtcTx(
18025
18485
  esploraUrls,
18026
18486
  network,
@@ -18734,16 +19194,29 @@ network='${network}'`
18734
19194
  * browser wallet usually cannot. Otherwise the wallet itself is the owner.
18735
19195
  * `hint` is appended to the error when neither is.
18736
19196
  */
18737
- #depositorOwnerSigner(swapResponse, walletSigner, hint) {
18738
- const depositor = swapResponse.client_evm_address?.toLowerCase();
18739
- if (depositor === this.getEvmAddress().toLowerCase()) {
18740
- return this.#keyOwnerSigner();
18741
- }
18742
- if (walletSigner && depositor === walletSigner.address.toLowerCase()) {
19197
+ async #depositorOwnerSigner(swapResponse, walletSigner, hint) {
19198
+ const stored = await this.getStoredSwap(swapResponse.id);
19199
+ const depositor = (stored?.evmFundingTerms?.depositor ?? swapResponse.client_evm_address)?.toLowerCase();
19200
+ if (walletSigner && depositor === walletSigner.address.toLowerCase())
18743
19201
  return walletSigner;
19202
+ if (depositor === this.getEvmAddress().toLowerCase())
19203
+ return keyToKernelOwnerSigner(
19204
+ this.#signer.deriveEvmKey().secretKey,
19205
+ 42161
19206
+ );
19207
+ try {
19208
+ const { privateKey, address: address2 } = await this.getSwapDepositorKey(
19209
+ swapResponse.id
19210
+ );
19211
+ if (address2.toLowerCase() === depositor)
19212
+ return keyToKernelOwnerSigner(
19213
+ hexToBytes(privateKey.replace(/^0x/, "")),
19214
+ 42161
19215
+ );
19216
+ } catch {
18744
19217
  }
18745
19218
  throw new Error(
18746
- `Swap ${swapResponse.id} was created for depositor ${depositor}, which is neither this client's key nor the given wallet.${hint ? ` ${hint}` : ""}`
19219
+ `Swap ${swapResponse.id} was created for a depositor which is neither this client's key nor the given wallet; use refundEvmWithSigner.${hint ? ` ${hint}` : ""}`
18747
19220
  );
18748
19221
  }
18749
19222
  /**
@@ -19248,7 +19721,7 @@ network='${network}'`
19248
19721
  "No secret key found for this swap. Cannot sign collab refund."
19249
19722
  );
19250
19723
  }
19251
- const evmKey = this.#getCollabRefundEvmSigningKey(storedSwap);
19724
+ const evmKey = await this.#getCollabRefundEvmSigningKey(storedSwap);
19252
19725
  const { digest, params } = await this.buildCollabRefundEvmTypedData(swapId);
19253
19726
  if (params.refundPath === "direct") {
19254
19727
  return this.#collabRefundEvmSponsored(swapId, params, evmKey);
@@ -19817,7 +20290,7 @@ network='${network}'`
19817
20290
  "No secret key found for this swap. Cannot authorize the rehash."
19818
20291
  );
19819
20292
  }
19820
- const evmKey = this.#getCollabRefundEvmSigningKey(
20293
+ const evmKey = await this.#getCollabRefundEvmSigningKey(
19821
20294
  storedSwap,
19822
20295
  "retrySwapWithInvoiceWithSigner"
19823
20296
  );
@@ -19965,6 +20438,13 @@ network='${network}'`
19965
20438
  // The payout this client asked for; claims pay here, never to a
19966
20439
  // server answer. Recovery rebuilding the swap keeps it.
19967
20440
  targetAddress: targetAddress ?? existing?.targetAddress,
20441
+ bitcoinPayout: commitments?.bitcoinPayout ?? existing?.bitcoinPayout,
20442
+ payRecipientNames: existing?.payRecipientNames,
20443
+ payRequestedAmounts: existing?.payRequestedAmounts,
20444
+ payUsdRate: existing?.payUsdRate,
20445
+ bitcoinClaimBroadcast: existing?.bitcoinClaimBroadcast,
20446
+ evmDepositorKeyIndex: existing?.evmDepositorKeyIndex,
20447
+ evmDepositorSecretKey: existing?.evmDepositorSecretKey,
19968
20448
  bridgeRecipient: bridge?.recipient,
19969
20449
  bridgeRecipientWallet: bridge?.recipientWallet,
19970
20450
  evmFundTxid: existing?.evmFundTxid,
@@ -19983,6 +20463,11 @@ network='${network}'`
19983
20463
  cctpBurnLastValidBlockHeight: existing?.cctpBurnLastValidBlockHeight
19984
20464
  };
19985
20465
  await this.#swapStorage.store(storedSwap);
20466
+ if (storedSwap.bitcoinPayout) {
20467
+ const persisted = await this.#swapStorage.get(swapId);
20468
+ if (JSON.stringify(persisted?.bitcoinPayout) !== JSON.stringify(storedSwap.bitcoinPayout))
20469
+ throw new Error("Swap storage did not preserve the payment recipients");
20470
+ }
19986
20471
  }
19987
20472
  /**
19988
20473
  * Creates a swap by routing to the correct direction-specific method
@@ -20020,6 +20505,10 @@ network='${network}'`
20020
20505
  }
20021
20506
  const sourceAsset = "token_id" in src ? { chain: src.chain, token_id: src.token_id } : { chain: src.chain, token_id: src.tokenId };
20022
20507
  const targetAsset = "token_id" in tgt ? { chain: tgt.chain, token_id: tgt.token_id } : { chain: tgt.chain, token_id: tgt.tokenId };
20508
+ if (options.bitcoinPayout && (!this.#swapStorage || !isBtcOnchain(targetAsset)))
20509
+ throw new Error(
20510
+ "Bitcoin payments require persistent storage and a Bitcoin onchain target"
20511
+ );
20023
20512
  if (isTronToken(sourceAsset.chain))
20024
20513
  throw new Error("Tron is a payout-only destination");
20025
20514
  const isTronTarget = isTronToken(targetAsset.chain) || options.bridgeParams?.targetChain === "Tron";
@@ -20072,6 +20561,7 @@ network='${network}'`
20072
20561
  sourceAmount: options.sourceAmount,
20073
20562
  referralCode: options.referralCode,
20074
20563
  extraFees: options.extraFees,
20564
+ promoCode: options.promoCode,
20075
20565
  bridgeRecipientSetup: options.bridgeRecipientSetup
20076
20566
  });
20077
20567
  if (BigInt(quote.net_target_amount) <= 0n) {
@@ -20114,6 +20604,11 @@ network='${network}'`
20114
20604
  sourceChain = "42161";
20115
20605
  sourceTokenId = USDC_ADDRESSES.Arbitrum;
20116
20606
  }
20607
+ if (options.bitcoinPayout && !isEvmSwapSource(sourceChain, sourceTokenId)) {
20608
+ throw new Error(
20609
+ "Bitcoin payments require an EVM or bridged USDC funding source"
20610
+ );
20611
+ }
20117
20612
  if (isArkade(sourceAsset) && isEvmToken(targetChain)) {
20118
20613
  return this.createArkadeToEvmSwapGeneric({
20119
20614
  targetAddress: options.targetAddress,
@@ -20123,6 +20618,7 @@ network='${network}'`
20123
20618
  targetAmount: options.targetAmount ? BigInt(options.targetAmount) : void 0,
20124
20619
  referralCode: options.referralCode,
20125
20620
  extraFees: options.extraFees,
20621
+ promoCode: options.promoCode,
20126
20622
  bridgeParams
20127
20623
  });
20128
20624
  }
@@ -20148,7 +20644,8 @@ network='${network}'`
20148
20644
  ...options.sourceAmount != null ? { sourceAmountSats: Number(options.sourceAmount) } : { targetAmountSats: Number(options.targetAmount) },
20149
20645
  targetAddress: options.targetAddress,
20150
20646
  referralCode: options.referralCode,
20151
- extraFees: options.extraFees
20647
+ extraFees: options.extraFees,
20648
+ promoCode: options.promoCode
20152
20649
  });
20153
20650
  }
20154
20651
  if (isLightning(sourceAsset) && isBtcOnchain(targetAsset)) {
@@ -20161,7 +20658,8 @@ network='${network}'`
20161
20658
  ...options.sourceAmount != null ? { sourceAmountSats: Number(options.sourceAmount) } : { targetAmountSats: Number(options.targetAmount) },
20162
20659
  targetAddress: options.targetAddress,
20163
20660
  referralCode: options.referralCode,
20164
- extraFees: options.extraFees
20661
+ extraFees: options.extraFees,
20662
+ promoCode: options.promoCode
20165
20663
  });
20166
20664
  }
20167
20665
  if (isLightning(sourceAsset) && isEvmToken(targetChain)) {
@@ -20178,6 +20676,25 @@ network='${network}'`
20178
20676
  targetAmount: options.targetAmount == null ? void 0 : BigInt(options.targetAmount),
20179
20677
  referralCode: options.referralCode,
20180
20678
  extraFees: options.extraFees,
20679
+ promoCode: options.promoCode,
20680
+ bridgeParams
20681
+ });
20682
+ }
20683
+ if (sourceAsset.chain === "Spark" && isEvmToken(targetChain)) {
20684
+ if (options.sourceAmount == null === (options.targetAmount == null)) {
20685
+ throw new Error(
20686
+ "Provide exactly one of sourceAmount (sats on Spark) or targetAmount (token units to receive) for Spark \u2192 EVM swaps"
20687
+ );
20688
+ }
20689
+ return this.createSparkToEvmSwap({
20690
+ targetAddress: options.targetAddress,
20691
+ tokenAddress,
20692
+ evmChainId: Number(targetChain),
20693
+ sourceAmount: options.sourceAmount == null ? void 0 : Number(options.sourceAmount),
20694
+ targetAmount: options.targetAmount == null ? void 0 : BigInt(options.targetAmount),
20695
+ referralCode: options.referralCode,
20696
+ extraFees: options.extraFees,
20697
+ promoCode: options.promoCode,
20181
20698
  bridgeParams
20182
20699
  });
20183
20700
  }
@@ -20190,6 +20707,7 @@ network='${network}'`
20190
20707
  targetAmount: options.targetAmount == null ? void 0 : BigInt(options.targetAmount),
20191
20708
  referralCode: options.referralCode,
20192
20709
  extraFees: options.extraFees,
20710
+ promoCode: options.promoCode,
20193
20711
  bridgeParams
20194
20712
  });
20195
20713
  }
@@ -20203,7 +20721,8 @@ network='${network}'`
20203
20721
  satsReceive: Number(options.targetAmount),
20204
20722
  targetAddress: options.targetAddress,
20205
20723
  referralCode: options.referralCode,
20206
- extraFees: options.extraFees
20724
+ extraFees: options.extraFees,
20725
+ promoCode: options.promoCode
20207
20726
  });
20208
20727
  }
20209
20728
  if (isEvmSwapSource(sourceChain, sourceTokenId) && isLightning(targetAsset)) {
@@ -20220,6 +20739,7 @@ network='${network}'`
20220
20739
  userAddress: options.userAddress,
20221
20740
  referralCode: options.referralCode,
20222
20741
  extraFees: options.extraFees,
20742
+ promoCode: options.promoCode,
20223
20743
  gasless: options.gasless,
20224
20744
  inboundBridgeParams
20225
20745
  };
@@ -20269,6 +20789,7 @@ network='${network}'`
20269
20789
  targetAmount: options.targetAmount == null ? void 0 : Number(options.targetAmount),
20270
20790
  referralCode: options.referralCode,
20271
20791
  extraFees: options.extraFees,
20792
+ promoCode: options.promoCode,
20272
20793
  gasless: options.gasless,
20273
20794
  inboundBridgeParams
20274
20795
  });
@@ -20280,6 +20801,8 @@ network='${network}'`
20280
20801
  );
20281
20802
  }
20282
20803
  return this.createEvmToBitcoinSwap({
20804
+ bitcoinPayout: options.bitcoinPayout,
20805
+ minimumRelayFeeRateSatPerVb: options.minimumRelayFeeRateSatPerVb,
20283
20806
  tokenAddress: sourceTokenId,
20284
20807
  evmChainId: Number(sourceChain),
20285
20808
  userAddress: options.userAddress ?? "",
@@ -20288,6 +20811,7 @@ network='${network}'`
20288
20811
  targetAmount: options.targetAmount == null ? void 0 : Number(options.targetAmount),
20289
20812
  referralCode: options.referralCode,
20290
20813
  extraFees: options.extraFees,
20814
+ promoCode: options.promoCode,
20291
20815
  gasless: options.gasless,
20292
20816
  inboundBridgeParams
20293
20817
  });
@@ -20475,6 +20999,13 @@ network='${network}'`
20475
20999
  await this.#rifClaimAddress(options)
20476
21000
  );
20477
21001
  }
21002
+ async createSparkToEvmSwap(options) {
21003
+ return createSparkToEvmSwap(
21004
+ options,
21005
+ this.#getCreateContext(),
21006
+ await this.#rifClaimAddress(options)
21007
+ );
21008
+ }
20478
21009
  // =========================================================================
20479
21010
  // Swap Creation - Arkade to Lightning
20480
21011
  // =========================================================================
@@ -20641,7 +21172,69 @@ network='${network}'`
20641
21172
  * ```
20642
21173
  */
20643
21174
  async createEvmToBitcoinSwap(options) {
20644
- return createEvmToBitcoinSwap(options, this.#getCreateContext());
21175
+ if (options.bitcoinPayout && !this.#swapStorage)
21176
+ throw new Error("Bitcoin payments require persistent storage");
21177
+ const context = this.#getCreateContext();
21178
+ const created = await createEvmToBitcoinSwap(options, {
21179
+ ...context,
21180
+ storeSwap: async (id, swapParams, response, target, bridge, commitments) => {
21181
+ if (options.bitcoinPayout) {
21182
+ const r = response;
21183
+ const network = r.network === "bitcoin" ? "mainnet" : r.network;
21184
+ assertPaymentClaimWindow(network, r.btc_refund_locktime);
21185
+ const urls = this.#config.esploraUrl ?? DEFAULT_ESPLORA_URLS[network];
21186
+ const relayFloor = options.minimumRelayFeeRateSatPerVb ?? (network === "regtest" ? 0 : await fetchMinimumRelayFeeRate(urls));
21187
+ if (relayFloor === void 0 || !Number.isFinite(relayFloor) || relayFloor < 0)
21188
+ throw new Error(
21189
+ "Cannot verify Bitcoin relay policy before funding. Configure a relay-policy explorer or minimumRelayFeeRateSatPerVb."
21190
+ );
21191
+ const committed = commitments?.bitcoinPayout;
21192
+ if (!committed) throw new Error("Payment commitments are missing");
21193
+ const minimum = BigInt(committed.feeSats) + committed.recipients.reduce(
21194
+ (sum, recipient) => sum + BigInt(recipient.amountSats),
21195
+ 0n
21196
+ );
21197
+ try {
21198
+ buildOnchainClaimTransaction({
21199
+ fundingTxId: "00".repeat(32),
21200
+ fundingVout: 0,
21201
+ htlcAmount: minimum,
21202
+ hashLock: r.btc_hash_lock,
21203
+ userClaimPubKey: bytesToHex(swapParams.publicKey).slice(2),
21204
+ serverRefundPubKey: r.btc_server_refund_pk.replace(
21205
+ /^(02|03)(?=[0-9a-fA-F]{64}$)/,
21206
+ ""
21207
+ ),
21208
+ userSecretKey: bytesToHex(swapParams.secretKey),
21209
+ preimage: bytesToHex(swapParams.preimage),
21210
+ refundLocktime: r.btc_refund_locktime,
21211
+ destinationAddress: options.targetAddress,
21212
+ bitcoinPayout: committed,
21213
+ // The builder needs a positive rate; regtest has no relay floor.
21214
+ feeRateSatPerVb: Math.max(relayFloor, Number.MIN_VALUE),
21215
+ network,
21216
+ btcHtlcScriptVersion: r.btc_htlc_script_version
21217
+ });
21218
+ } catch (error) {
21219
+ const message = error instanceof Error ? error.message : String(error);
21220
+ if (message.startsWith("Surplus cannot cover"))
21221
+ throw new Error(
21222
+ `Bitcoin payment fee is below the relay minimum of ${relayFloor} sat/vB. Increase it before funding.`
21223
+ );
21224
+ throw error;
21225
+ }
21226
+ }
21227
+ await context.storeSwap(
21228
+ id,
21229
+ swapParams,
21230
+ response,
21231
+ target,
21232
+ bridge,
21233
+ commitments
21234
+ );
21235
+ }
21236
+ });
21237
+ return created;
20645
21238
  }
20646
21239
  // =========================================================================
20647
21240
  // Coordinator Funding (EVM-to-BTC via DEX + HTLC)
@@ -20709,7 +21302,10 @@ network='${network}'`
20709
21302
  );
20710
21303
  const deadline = BigInt(Math.floor(Date.now() / 1e3) + 30 * 60);
20711
21304
  const sourceAmount = checked.sourceAmount;
20712
- const evmKey = this.#getEvmSigningKey();
21305
+ const evmKey = await this.#getFundingEvmSigningKey(
21306
+ storedSwap,
21307
+ swap.gasless
21308
+ );
20713
21309
  const depositorAddress = deriveEvmAddress(evmKey);
20714
21310
  const digest = buildPermit2FundingDigest({
20715
21311
  chainId,
@@ -21006,7 +21602,7 @@ network='${network}'`
21006
21602
  swapId,
21007
21603
  expected,
21008
21604
  signer,
21009
- ownerSigner: this.#depositorOwnerSigner(
21605
+ ownerSigner: await this.#depositorOwnerSigner(
21010
21606
  swapResponse,
21011
21607
  signer,
21012
21608
  "Create the swap with `gasless: true` to settle through the SDK's key."
@@ -21206,7 +21802,7 @@ network='${network}'`
21206
21802
  }),
21207
21803
  amount
21208
21804
  );
21209
- const { cctpFundSwapFromSolana } = await import("./fundSwap-UBCHMUP4-WBLYE6MC.js");
21805
+ const { cctpFundSwapFromSolana } = await import("./fundSwap-2D4IPYU4-CDM3WRUF.js");
21210
21806
  const { aa } = this.cctpInbound;
21211
21807
  const cctp = await cctpFundSwapFromSolana(
21212
21808
  { apiClient: this.#apiClient, aa },
@@ -21214,7 +21810,7 @@ network='${network}'`
21214
21810
  swapId,
21215
21811
  expected,
21216
21812
  signer,
21217
- ownerSigner: this.#depositorOwnerSigner(
21813
+ ownerSigner: await this.#depositorOwnerSigner(
21218
21814
  swapResponse,
21219
21815
  void 0,
21220
21816
  "A swap funded from Solana must be created with `gasless: true`."
@@ -21660,7 +22256,7 @@ network='${network}'`
21660
22256
  oldSwap
21661
22257
  };
21662
22258
  }
21663
- const owner = signer ?? this.#keyOwnerSigner();
22259
+ const owner = await this.#depositorOwnerSigner(oldSwap, signer);
21664
22260
  const { accountAddress } = await this.cctpInbound.createSmartAccountClient({
21665
22261
  signer: owner
21666
22262
  });
@@ -21765,17 +22361,11 @@ network='${network}'`
21765
22361
  * address, an Arkade address, or for Lightning a BOLT11 invoice (its amount
21766
22362
  * must be covered by the refund), a Lightning address or an LNURL.
21767
22363
  * @param options.target - The payout type; defaults to the old swap's.
21768
- * @param options.signer - A signer for this client's key; defaults to one
21769
- * derived from it. Any other owner is rejected: the new swap is created
21770
- * gasless, which records this client's key as its depositor, and the
21771
- * paymaster only sponsors funding from the depositor's account.
22364
+ * @param options.signer - A signer for the refunded deposit account. Defaults
22365
+ * to its SDK key. The continuation explicitly reuses that funded account
22366
+ * instead of allocating a new deposit address.
21772
22367
  */
21773
22368
  async continueRefundedEvmSwap(oldSwapId, options) {
21774
- if (options.signer && options.signer.address.toLowerCase() !== this.getEvmAddress().toLowerCase()) {
21775
- throw new Error(
21776
- `Cannot continue refunded swap ${oldSwapId} with signer ${options.signer.address}: a continuation is funded from this client's key (${this.getEvmAddress()}).`
21777
- );
21778
- }
21779
22369
  const info = await this.getRefundedEvmSwapContinuation(
21780
22370
  oldSwapId,
21781
22371
  options.signer
@@ -21783,6 +22373,17 @@ network='${network}'`
21783
22373
  if (!info.eligible || !info.token || !info.amount || !info.oldSwap) {
21784
22374
  throw new Error(info.reason ?? "Refunded swap cannot be continued.");
21785
22375
  }
22376
+ if (options.signer && options.signer.address.toLowerCase() !== info.smartAccountAddress?.toLowerCase()) {
22377
+ throw new Error(
22378
+ "Continuation must be funded from this client's key or the recorded depositor"
22379
+ );
22380
+ }
22381
+ const original = await this.getSwapDepositorKey(oldSwapId).catch(
22382
+ (error) => {
22383
+ if (!options.signer) throw error;
22384
+ return void 0;
22385
+ }
22386
+ );
21786
22387
  const target = options.target ?? {
21787
22388
  evm_to_arkade: "arkade",
21788
22389
  evm_to_bitcoin: "bitcoin",
@@ -21793,7 +22394,7 @@ network='${network}'`
21793
22394
  tokenAddress: info.token.address,
21794
22395
  evmChainId: 42161,
21795
22396
  userAddress: info.smartAccountAddress ?? "",
21796
- gasless: true
22397
+ gasless: false
21797
22398
  };
21798
22399
  let created;
21799
22400
  if (target === "arkade") {
@@ -21819,6 +22420,18 @@ network='${network}'`
21819
22420
  );
21820
22421
  }
21821
22422
  const newSwapId = created.response.id;
22423
+ if (this.#swapStorage) {
22424
+ const next = await this.getStoredSwap(newSwapId);
22425
+ const sharedAddress = deriveEvmAddress(
22426
+ this.#getEvmSigningKey()
22427
+ ).toLowerCase();
22428
+ if (next && original && original.address.toLowerCase() !== sharedAddress)
22429
+ await this.#swapStorage.store({
22430
+ ...next,
22431
+ evmDepositorKeyIndex: original.keyIndex,
22432
+ evmDepositorSecretKey: original.privateKey
22433
+ });
22434
+ }
21822
22435
  const submitted = await this.cctpInbound.submitBalanceUserOp({
21823
22436
  swapId: newSwapId,
21824
22437
  // The new swap's own hash and terms, recorded when it was just
@@ -21830,7 +22443,7 @@ network='${network}'`
21830
22443
  ),
21831
22444
  pins: options.funding
21832
22445
  },
21833
- signer: options.signer ?? this.#keyOwnerSigner(),
22446
+ signer: await this.#depositorOwnerSigner(info.oldSwap, options.signer),
21834
22447
  expectedMaxSourceAmount: sourceAmount
21835
22448
  });
21836
22449
  if (submitted.transactionHash) {
@@ -21877,20 +22490,7 @@ network='${network}'`
21877
22490
  `Sponsored refunds run on Arbitrum only; swap ${swapId} is on chain ${chainId}. Use refundEvmWithSigner.`
21878
22491
  );
21879
22492
  }
21880
- const { client_evm_address: depositor, gasless } = stored.response;
21881
- let owner;
21882
- if (depositor?.toLowerCase() === this.getEvmAddress().toLowerCase()) {
21883
- owner = this.#keyOwnerSigner();
21884
- } else if (gasless && depositor?.toLowerCase() === deriveEvmAddress(stored.secretKey).toLowerCase()) {
21885
- owner = keyToKernelOwnerSigner(
21886
- hexToBytes(stored.secretKey.replace(/^0x/, "")),
21887
- 42161
21888
- );
21889
- } else {
21890
- throw new Error(
21891
- `Swap ${swapId} was funded by ${depositor}, not this client's key; only gasless swaps can be refunded sponsored. Refund it with \`refundEvmWithSigner\` from that wallet.`
21892
- );
21893
- }
22493
+ const owner = await this.#depositorOwnerSigner(stored.response);
21894
22494
  const result = await this.refundSwap(swapId);
21895
22495
  if (!result.evmRefundData) {
21896
22496
  throw new Error(
@@ -21911,10 +22511,6 @@ network='${network}'`
21911
22511
  (account) => refundForAsOwnRefund(refund, account)
21912
22512
  );
21913
22513
  }
21914
- /** This client's key as the Kernel owner on Arbitrum. */
21915
- #keyOwnerSigner() {
21916
- return keyToKernelOwnerSigner(this.#signer.deriveEvmKey().secretKey, 42161);
21917
- }
21918
22514
  /**
21919
22515
  * An `eth_call` over the AA RPC, for reads on an account this client owns
21920
22516
  * with its key (whose signer does not read the chain).
@@ -22050,7 +22646,10 @@ network='${network}'`
22050
22646
  );
22051
22647
  const deadline = BigInt(Math.floor(Date.now() / 1e3) + 30 * 60);
22052
22648
  const sourceAmount = checked.sourceAmount;
22053
- const evmKey = this.#getEvmSigningKey();
22649
+ const evmKey = await this.#getFundingEvmSigningKey(
22650
+ storedSwap,
22651
+ swap.gasless
22652
+ );
22054
22653
  const depositorAddress = deriveEvmAddress(evmKey);
22055
22654
  const digest = buildPermit2FundingDigest({
22056
22655
  chainId,
@@ -22166,7 +22765,7 @@ network='${network}'`
22166
22765
  if (!this.#swapStorage)
22167
22766
  throw new Error("Sponsored funding requires swap storage");
22168
22767
  if (stored.evmFundingUserOpHash) {
22169
- const key2 = this.#gaslessDepositorKey(swapId, stored, swap);
22768
+ const key2 = await this.#gaslessDepositorKey(swapId, stored, swap);
22170
22769
  const { client } = await this.cctpInbound.createSmartAccountClient({
22171
22770
  signer: keyToKernelOwnerSigner(
22172
22771
  hexToBytes(key2.replace(/^0x/, "")),
@@ -22219,7 +22818,9 @@ network='${network}'`
22219
22818
  if (receipt.status === "reverted") {
22220
22819
  await this.#forgetEvmFunding(swapId, stored.evmFundTxid);
22221
22820
  } else if (receipt.status === "success" && receipt.logs !== void 0) {
22222
- const sender = (expected.terms.htlcVersion ?? 0) >= 7 ? deriveEvmAddress(this.#gaslessDepositorKey(swapId, stored, swap)) : expected.terms.coordinator;
22821
+ const sender = (expected.terms.htlcVersion ?? 0) >= 7 ? deriveEvmAddress(
22822
+ await this.#gaslessDepositorKey(swapId, stored, swap)
22823
+ ) : expected.terms.coordinator;
22223
22824
  const locks = findSwapCreated(receipt.logs, {
22224
22825
  htlcAddress: expected.terms.htlcAddress,
22225
22826
  hashLock: expected.hashLock,
@@ -22244,7 +22845,7 @@ network='${network}'`
22244
22845
  );
22245
22846
  }
22246
22847
  }
22247
- const key = this.#gaslessDepositorKey(swapId, stored, swap);
22848
+ const key = await this.#gaslessDepositorKey(swapId, stored, swap);
22248
22849
  const owner = keyToKernelOwnerSigner(
22249
22850
  hexToBytes(key.replace(/^0x/, "")),
22250
22851
  AA_CHAIN_ID
@@ -22288,18 +22889,23 @@ network='${network}'`
22288
22889
  * account, so a depositor this SDK does not control cannot be funded
22289
22890
  * here.
22290
22891
  */
22291
- #gaslessDepositorKey(swapId, stored, swap) {
22292
- const depositor = swap.client_evm_address?.toLowerCase();
22293
- const sharedKey = this.#getEvmSigningKey();
22294
- if (!depositor || depositor === deriveEvmAddress(sharedKey).toLowerCase()) {
22295
- return sharedKey;
22296
- }
22297
- if (depositor === deriveEvmAddress(stored.secretKey).toLowerCase()) {
22298
- return stored.secretKey;
22892
+ async #gaslessDepositorKey(swapId, stored, swap) {
22893
+ const depositor = (stored.evmFundingTerms?.depositor ?? swap.client_evm_address)?.toLowerCase();
22894
+ if (!depositor) return this.#getEvmSigningKey();
22895
+ let key;
22896
+ try {
22897
+ key = (await this.getSwapDepositorKey(swapId)).privateKey.replace(
22898
+ /^0x/,
22899
+ ""
22900
+ );
22901
+ } catch {
22902
+ key = void 0;
22299
22903
  }
22300
- throw new Error(
22301
- `Cannot fund swap ${swapId} sponsored: its depositor ${depositor} is not an SDK-controlled account. Fund it from that wallet with fundSwap.`
22302
- );
22904
+ if (!key || deriveEvmAddress(key).toLowerCase() !== depositor)
22905
+ throw new Error(
22906
+ `Cannot fund swap ${swapId} sponsored: its depositor ${depositor} is not an SDK-controlled account. Fund it from that wallet with fundSwap.`
22907
+ );
22908
+ return key;
22303
22909
  }
22304
22910
  /**
22305
22911
  * Get the ephemeral depositor key for a gasless swap funded swap.
@@ -22330,29 +22936,40 @@ network='${network}'`
22330
22936
  );
22331
22937
  }
22332
22938
  const response = storedSwap.response;
22333
- const depositor = response.client_evm_address?.toLowerCase();
22939
+ const depositor = (storedSwap.evmFundingTerms?.depositor ?? response.client_evm_address)?.toLowerCase();
22334
22940
  const sharedKey = this.#getEvmSigningKey();
22335
- const sharedAddress = deriveEvmAddress(sharedKey).toLowerCase();
22336
- const swapAddress = deriveEvmAddress(storedSwap.secretKey).toLowerCase();
22337
- let evmKey = sharedKey;
22338
- if (depositor === swapAddress) {
22339
- evmKey = storedSwap.secretKey;
22340
- } else if (depositor && depositor !== sharedAddress && response.gasless) {
22941
+ const indexedKey = storedSwap.evmDepositorKeyIndex !== void 0 ? bytesToHex(
22942
+ this.deriveSwapParamsAtIndex(storedSwap.evmDepositorKeyIndex).secretKey
22943
+ ) : void 0;
22944
+ const candidates = [
22945
+ storedSwap.secretKey,
22946
+ ...storedSwap.evmDepositorSecretKey ? [storedSwap.evmDepositorSecretKey] : [],
22947
+ ...indexedKey ? [indexedKey] : [],
22948
+ sharedKey
22949
+ ];
22950
+ const matched = depositor ? candidates.find(
22951
+ (key) => deriveEvmAddress(key).toLowerCase() === depositor
22952
+ ) : void 0;
22953
+ if (depositor && !matched && (response.gasless || storedSwap.evmFundingTerms?.depositor))
22341
22954
  throw new Error(
22342
- `Cannot export a deposit key for swap ${swapId}: depositor ${response.client_evm_address} is not an SDK-controlled account. Use the depositor wallet.`
22955
+ `Cannot export a deposit key for swap ${swapId}: no SDK key for its recorded depositor ${depositor}, which is not an SDK-controlled account. Restore the original deposit account or use its wallet.`
22343
22956
  );
22344
- }
22957
+ const evmKey = matched ?? sharedKey;
22345
22958
  const privateKey = evmKey.startsWith("0x") ? evmKey : `0x${evmKey}`;
22346
22959
  const address2 = deriveEvmAddress(evmKey);
22347
- return { privateKey, address: address2 };
22960
+ return {
22961
+ privateKey,
22962
+ address: address2,
22963
+ keyIndex: deriveEvmAddress(storedSwap.secretKey).toLowerCase() === address2.toLowerCase() ? storedSwap.keyIndex : indexedKey && deriveEvmAddress(indexedKey).toLowerCase() === address2.toLowerCase() ? storedSwap.evmDepositorKeyIndex : void 0
22964
+ };
22348
22965
  }
22349
22966
  /**
22350
22967
  * Wallet-level variant of {@link getSwapDepositorKey} — returns the
22351
22968
  * deterministic EVM signing key for this wallet without requiring a
22352
22969
  * specific swap to be stored locally.
22353
22970
  *
22354
- * This returns only the shared `m/44'/60'/0'/0/0` account, not a
22355
- * per-swap deposit key. Intended for legacy standalone recovery tools
22971
+ * Only for legacy wallet-level deposits (`m/44'/60'/0'/0/0`).
22972
+ * Use getSwapDepositorKey for per-swap deposits. Intended for recovery tools
22356
22973
  * where the user supplies the burn details manually and a per-swap
22357
22974
  * record may no longer exist (e.g. fresh device, cleared site data).
22358
22975
  */
@@ -22400,7 +23017,7 @@ network='${network}'`
22400
23017
  return recoverCctpInbound(
22401
23018
  { aa: this.#config.aa },
22402
23019
  {
22403
- signer: this.#depositorOwnerSigner(
23020
+ signer: await this.#depositorOwnerSigner(
22404
23021
  stored.response,
22405
23022
  options?.ownerSigner
22406
23023
  ),
@@ -22955,12 +23572,18 @@ export {
22955
23572
  getBridgeTargetChain,
22956
23573
  getCctpBridgeTokens,
22957
23574
  getUsdt0BridgeTokens,
23575
+ isSpark,
22958
23576
  Signer,
23577
+ validateBitcoinPayout,
23578
+ allocateBitcoinPayout,
22959
23579
  computeHash160,
22960
23580
  buildOnchainClaimTransaction,
22961
23581
  buildOnchainRefundTransaction,
22962
23582
  verifyHtlcAddress,
22963
23583
  SwapVerificationError,
23584
+ bitcoinNetworkOf,
23585
+ commitBitcoinPayment,
23586
+ minimumBitcoinPayout,
22964
23587
  addressToScriptHash,
22965
23588
  ElectrumWsClient,
22966
23589
  electrumFindOutputByAddress,
@@ -23005,4 +23628,4 @@ export {
23005
23628
  @scure/bip39/index.js:
23006
23629
  (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
23007
23630
  */
23008
- //# sourceMappingURL=chunk-WQMAL2VD.js.map
23631
+ //# sourceMappingURL=chunk-34OYIFOU.js.map