@satora/swap 1.12.0 → 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 (92) 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-YBQPH7NH.js → chunk-34OYIFOU.js} +506 -113
  8. package/dist/chunk-34OYIFOU.js.map +1 -0
  9. package/dist/{chunk-EL4FUZJO.cjs → chunk-3633KDTW.cjs} +879 -486
  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-KECPPSZL.js → chunk-KMBGRQS7.js} +5 -5
  24. package/dist/{chunk-KECPPSZL.js.map → chunk-KMBGRQS7.js.map} +1 -1
  25. package/dist/{chunk-QJ4EK6UG.cjs → chunk-LZQZYSOZ.cjs} +5 -5
  26. package/dist/{chunk-QJ4EK6UG.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-Y3ZVHXAJ.js → dist-3N76II5O.js} +14 -4
  30. package/dist/dist-KQINAMDC.cjs +406 -0
  31. package/dist/{dist-R6DUJG36.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 +30 -20
  36. package/dist/index.cjs.map +1 -1
  37. package/dist/index.js +18 -8
  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/client.d.cts +14 -9
  44. package/dist/types/cjs/pure/create/bitcoin-payout.d.cts +17 -0
  45. package/dist/types/cjs/pure/create/evm-to-arkade.d.cts +0 -5
  46. package/dist/types/cjs/pure/create/evm-to-lightning.d.cts +0 -8
  47. package/dist/types/cjs/pure/create/funding-terms.d.cts +2 -1
  48. package/dist/types/cjs/pure/create/payment-safety.d.cts +2 -0
  49. package/dist/types/cjs/pure/create/payout-slippage.d.cts +29 -0
  50. package/dist/types/cjs/pure/create/types.d.cts +9 -1
  51. package/dist/types/cjs/pure/esplora.d.cts +2 -0
  52. package/dist/types/cjs/pure/evm/funding-pins.d.cts +2 -0
  53. package/dist/types/cjs/pure/generated/api.d.cts +78 -0
  54. package/dist/types/cjs/pure/index.d.cts +3 -1
  55. package/dist/types/cjs/pure/refund/onchain.d.cts +4 -0
  56. package/dist/types/cjs/pure/storage/index.d.cts +1 -1
  57. package/dist/types/cjs/pure/storage/types.d.cts +22 -0
  58. package/dist/types/cjs/pure/version.d.cts +4 -4
  59. package/dist/types/cjs/swap/contracts/bitcoin-reader-esplora.d.cts +5 -0
  60. package/dist/types/esm/pure/client.d.ts +14 -9
  61. package/dist/types/esm/pure/create/bitcoin-payout.d.ts +17 -0
  62. package/dist/types/esm/pure/create/evm-to-arkade.d.ts +0 -5
  63. package/dist/types/esm/pure/create/evm-to-lightning.d.ts +0 -8
  64. package/dist/types/esm/pure/create/funding-terms.d.ts +2 -1
  65. package/dist/types/esm/pure/create/payment-safety.d.ts +2 -0
  66. package/dist/types/esm/pure/create/payout-slippage.d.ts +29 -0
  67. package/dist/types/esm/pure/create/types.d.ts +9 -1
  68. package/dist/types/esm/pure/esplora.d.ts +2 -0
  69. package/dist/types/esm/pure/evm/funding-pins.d.ts +2 -0
  70. package/dist/types/esm/pure/generated/api.d.ts +78 -0
  71. package/dist/types/esm/pure/index.d.ts +3 -1
  72. package/dist/types/esm/pure/refund/onchain.d.ts +4 -0
  73. package/dist/types/esm/pure/storage/index.d.ts +1 -1
  74. package/dist/types/esm/pure/storage/types.d.ts +22 -0
  75. package/dist/types/esm/pure/version.d.ts +4 -4
  76. package/dist/types/esm/swap/contracts/bitcoin-reader-esplora.d.ts +5 -0
  77. package/package.json +1 -1
  78. package/dist/bitcoin-reader-electrum-4PNSDHIA.js +0 -9
  79. package/dist/bitcoin-reader-electrum-VCQ5TQ44.cjs +0 -9
  80. package/dist/bitcoin-reader-esplora-6RH7S4BR.cjs +0 -14
  81. package/dist/bitcoin-reader-esplora-6RH7S4BR.cjs.map +0 -1
  82. package/dist/chunk-3ZMSZSAV.js.map +0 -1
  83. package/dist/chunk-5DQHR3RO.cjs.map +0 -1
  84. package/dist/chunk-EL4FUZJO.cjs.map +0 -1
  85. package/dist/chunk-INHFP222.cjs.map +0 -1
  86. package/dist/chunk-LSCRTQOS.js.map +0 -1
  87. package/dist/chunk-YBQPH7NH.js.map +0 -1
  88. package/dist/dist-R6DUJG36.cjs +0 -396
  89. /package/dist/{bitcoin-reader-electrum-4PNSDHIA.js.map → bitcoin-reader-electrum-VLYRII3T.js.map} +0 -0
  90. /package/dist/{bitcoin-reader-esplora-CGPF4H5Y.js.map → bitcoin-reader-esplora-LC673MQT.js.map} +0 -0
  91. /package/dist/{dist-Y3ZVHXAJ.js.map → dist-3N76II5O.js.map} +0 -0
  92. /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-KECPPSZL.js";
118
+ } from "./chunk-KMBGRQS7.js";
119
119
  import {
120
120
  ArkAddress,
121
121
  CSVMultisigTapscript,
@@ -11239,6 +11239,65 @@ init_secp256k12();
11239
11239
  init_legacy2();
11240
11240
  init_sha2();
11241
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
+ }
11242
11301
  var NUMS_POINT = hex.decode(
11243
11302
  "0250929b74c1a04954b78b4b6035e97a5e078a5a0f28ec96d547bfee9ace803ac0"
11244
11303
  );
@@ -11368,7 +11427,14 @@ function buildOnchainClaimTransaction(params) {
11368
11427
  refundLocktime,
11369
11428
  params.btcHtlcScriptVersion
11370
11429
  );
11371
- 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
+ );
11372
11438
  if (fee >= htlcAmount) {
11373
11439
  throw new Error(
11374
11440
  `Fee (${fee} sats) exceeds HTLC amount (${htlcAmount} sats)`
@@ -11393,9 +11459,18 @@ function buildOnchainClaimTransaction(params) {
11393
11459
  amount: htlcAmount
11394
11460
  },
11395
11461
  tapLeafScript: [hashlockLeaf],
11396
- sequence: 4294967295
11462
+ sequence: validated ? 4294967293 : 4294967295
11397
11463
  });
11398
- 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
+ }
11399
11474
  const [controlBlockInfo, leafScriptWithVersion] = hashlockLeaf;
11400
11475
  const leafScript = leafScriptWithVersion.slice(0, -1);
11401
11476
  const leafVersion = leafScriptWithVersion[leafScriptWithVersion.length - 1];
@@ -11421,6 +11496,26 @@ function buildOnchainClaimTransaction(params) {
11421
11496
  tx.updateInput(0, {
11422
11497
  finalScriptWitness: [preimageBytes, sig, leafScript, encodedControlBlock]
11423
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
+ }
11424
11519
  const txHex = hex.encode(tx.extract());
11425
11520
  const txId = tx.id;
11426
11521
  const htlcAddress2 = Address(networkConfig).encode({
@@ -11428,6 +11523,7 @@ function buildOnchainClaimTransaction(params) {
11428
11523
  pubkey: p2tr2.tweakedPubkey
11429
11524
  });
11430
11525
  return {
11526
+ vsize: tx.vsize,
11431
11527
  txHex,
11432
11528
  txId,
11433
11529
  claimAmount,
@@ -12367,11 +12463,13 @@ async function createBitcoinToLightningSwap(options, ctx) {
12367
12463
  });
12368
12464
  return { response: data, swapParams };
12369
12465
  }
12370
- function fundingTermsOf(data) {
12466
+ function fundingTermsOf(data, depositor) {
12467
+ if (depositor) assertAddressEchoed(data, "client_evm_address", depositor);
12371
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) {
12372
12469
  return void 0;
12373
12470
  }
12374
12471
  return {
12472
+ depositor: depositor?.toLowerCase(),
12375
12473
  chainId: data.evm_chain_id,
12376
12474
  coordinator: data.evm_coordinator_address.toLowerCase(),
12377
12475
  htlcAddress: data.evm_htlc_address.toLowerCase(),
@@ -12391,7 +12489,7 @@ async function createEvmToArkadeSwapGeneric(options, ctx) {
12391
12489
  const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;
12392
12490
  const receiverPk = bytesToHex(swapParams.publicKey);
12393
12491
  const userId = bytesToHex(swapParams.userId);
12394
- const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;
12492
+ const userAddress = options.gasless ? deriveEvmAddress(swapParams.secretKey) : options.userAddress;
12395
12493
  const { data, error } = await ctx.apiClient.POST("/swap/evm/arkade", {
12396
12494
  body: {
12397
12495
  hash_lock: hashLock,
@@ -12428,18 +12526,84 @@ async function createEvmToArkadeSwapGeneric(options, ctx) {
12428
12526
  },
12429
12527
  options.targetAddress,
12430
12528
  void 0,
12431
- { evmFundingTerms: fundingTermsOf(data) }
12529
+ { evmFundingTerms: fundingTermsOf(data, userAddress) }
12432
12530
  );
12433
12531
  return { response: data, swapParams };
12434
12532
  });
12435
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
+ }
12436
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
+ }
12437
12601
  return retryOnHashCollision(ctx, async () => {
12438
12602
  const swapParams = await ctx.deriveSwapParams();
12439
12603
  const hashLock = `0x${bytesToHex(swapParams.preimageHash)}`;
12440
12604
  const claimPk = bytesToHex(swapParams.publicKey);
12441
12605
  const userId = bytesToHex(swapParams.userId);
12442
- const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;
12606
+ const userAddress = options.gasless ? deriveEvmAddress(swapParams.secretKey) : options.userAddress;
12443
12607
  const { data, error } = await ctx.apiClient.POST("/swap/evm/bitcoin", {
12444
12608
  body: {
12445
12609
  hash_lock: hashLock,
@@ -12451,6 +12615,7 @@ async function createEvmToBitcoinSwap(options, ctx) {
12451
12615
  user_address: userAddress,
12452
12616
  target_address: options.targetAddress,
12453
12617
  amount_in: options.sourceAmount ? options.sourceAmount.toString() : void 0,
12618
+ minimum_payout_sats: payment ? Number(payment.minimumPayoutSats) : void 0,
12454
12619
  amount_out: options.targetAmount ? Number(options.targetAmount) : void 0,
12455
12620
  referral_code: options.referralCode ?? ctx.referralCode,
12456
12621
  extra_fees: options.extraFees,
@@ -12476,7 +12641,10 @@ async function createEvmToBitcoinSwap(options, ctx) {
12476
12641
  },
12477
12642
  options.targetAddress,
12478
12643
  void 0,
12479
- { evmFundingTerms: fundingTermsOf(data) }
12644
+ {
12645
+ evmFundingTerms: fundingTermsOf(data, userAddress),
12646
+ bitcoinPayout: payment?.payout
12647
+ }
12480
12648
  );
12481
12649
  return { response: data, swapParams };
12482
12650
  });
@@ -12500,7 +12668,7 @@ async function createEvmToLightningSwap(options, ctx) {
12500
12668
  }
12501
12669
  const swapParams = await ctx.deriveSwapParams();
12502
12670
  const userId = bytesToHex(swapParams.userId);
12503
- const userAddress = options.gasless ? ctx.evmAddress : options.userAddress;
12671
+ const userAddress = options.gasless ? deriveEvmAddress(swapParams.secretKey) : options.userAddress;
12504
12672
  const { data, error } = await ctx.apiClient.POST("/swap/evm/lightning", {
12505
12673
  body: {
12506
12674
  lightning_invoice: options.lightningInvoice,
@@ -12536,7 +12704,10 @@ async function createEvmToLightningSwap(options, ctx) {
12536
12704
  },
12537
12705
  void 0,
12538
12706
  void 0,
12539
- { lightningPaymentHash, evmFundingTerms: fundingTermsOf(data) }
12707
+ {
12708
+ lightningPaymentHash,
12709
+ evmFundingTerms: fundingTermsOf(data, userAddress)
12710
+ }
12540
12711
  );
12541
12712
  return { response: data, swapParams };
12542
12713
  }
@@ -12746,6 +12917,14 @@ async function createSparkToEvmSwap(options, ctx, claimingAddressOverride) {
12746
12917
  return { response: data, swapParams };
12747
12918
  });
12748
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
+ }
12749
12928
  init_sha2();
12750
12929
  init_utils();
12751
12930
  var REQUEST_TIMEOUT_MS = 5e3;
@@ -13323,6 +13502,23 @@ async function broadcastTransactionWithRetry(esploraUrls, txHex, retries = 5) {
13323
13502
  }
13324
13503
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
13325
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
+ }
13326
13522
  init_utils();
13327
13523
  var KERNEL_DELEGATION_TARGET = "0xd6CEDDe84be40893d153Be9d467CD6aD37875b28";
13328
13524
  var KERNEL_VERSION = "0.3.3";
@@ -15937,6 +16133,7 @@ var Client = class _Client {
15937
16133
  #composeStaticCache = /* @__PURE__ */ new Map();
15938
16134
  #signerStorage;
15939
16135
  #swapStorage;
16136
+ #ephemeralKeyIndex = 0;
15940
16137
  #statusWatcher = null;
15941
16138
  #cctpInbound = null;
15942
16139
  #electrumWs = null;
@@ -16105,7 +16302,7 @@ var Client = class _Client {
16105
16302
  * @returns The derived swap parameters.
16106
16303
  */
16107
16304
  async deriveSwapParams() {
16108
- let index = 0;
16305
+ let index = this.#ephemeralKeyIndex++;
16109
16306
  if (this.#signerStorage) {
16110
16307
  index = await this.#signerStorage.incrementKeyIndex();
16111
16308
  }
@@ -16125,8 +16322,8 @@ var Client = class _Client {
16125
16322
  /**
16126
16323
  * Get the deterministic EVM address for this SDK key.
16127
16324
  *
16128
- * This address is reused across all gasless swaps, so a single
16129
- * 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).
16130
16327
  *
16131
16328
  * @returns Checksummed EVM address (0x-prefixed).
16132
16329
  */
@@ -16234,33 +16431,29 @@ var Client = class _Client {
16234
16431
  }
16235
16432
  return this.#getEvmSigningKey();
16236
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
+ }
16237
16445
  /**
16238
16446
  * Select the SDK-controlled EVM key that matches the swap's recorded depositor.
16239
16447
  *
16240
- * Current gasless EVM-sourced swaps use the deterministic wallet-level EVM key;
16241
- * 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
16242
16450
  * swaps still use the per-swap key even though client_evm_address may point at
16243
16451
  * the user's wallet rather than the later Permit2 depositor.
16244
16452
  */
16245
- #getCollabRefundEvmSigningKey(storedSwap, walletMethod = "collabRefundEvmWithSigner") {
16246
- const swapKey = storedSwap.secretKey;
16247
- const response = storedSwap.response;
16248
- if (!response.gasless) {
16249
- return swapKey;
16250
- }
16251
- const deterministicKey = this.#getEvmSigningKey();
16252
- const deterministicAddress = deriveEvmAddress(deterministicKey);
16253
- const swapAddress = deriveEvmAddress(swapKey);
16254
- const clientAddress = response.client_evm_address?.toLowerCase();
16255
- if (clientAddress === deterministicAddress.toLowerCase() || !clientAddress) {
16256
- return deterministicKey;
16257
- }
16258
- if (clientAddress === swapAddress.toLowerCase()) {
16259
- return swapKey;
16260
- }
16261
- throw new Error(
16262
- `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.`
16263
- );
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;
16264
16457
  }
16265
16458
  /**
16266
16459
  * Gets the current key index from storage.
@@ -17056,6 +17249,35 @@ var Client = class _Client {
17056
17249
  storedSwaps.push(stored);
17057
17250
  }
17058
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
+ }
17059
17281
  const currentKeyIndex = await this.getKeyIndex();
17060
17282
  const nextKeyIndex = Math.max(currentKeyIndex, data.next_index);
17061
17283
  if (nextKeyIndex !== currentKeyIndex) {
@@ -18190,16 +18412,51 @@ var Client = class _Client {
18190
18412
  message: `Could not find UTXO at HTLC address ${btcHtlcAddress} after waiting ${waitForFundingMs}ms. The server may not have funded the HTLC yet.`
18191
18413
  };
18192
18414
  }
18193
- const destinationAddress = options?.destinationAddress ?? storedPayoutTarget(storedSwap);
18194
- 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) {
18195
18424
  return {
18196
18425
  success: false,
18197
18426
  message: 'Destination address is required to claim BTC. Provide it via options: { destinationAddress: "bc1p..." }'
18198
18427
  };
18199
18428
  }
18200
- 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
+ }
18201
18457
  try {
18202
18458
  const result = buildOnchainClaimTransaction({
18459
+ bitcoinPayout,
18203
18460
  fundingTxId: htlcOutput.txid,
18204
18461
  fundingVout: htlcOutput.vout,
18205
18462
  htlcAmount: htlcOutput.amount,
@@ -18209,12 +18466,21 @@ var Client = class _Client {
18209
18466
  userSecretKey: storedSwap.secretKey,
18210
18467
  preimage: storedSwap.preimage,
18211
18468
  refundLocktime: btcRefundLocktime,
18212
- destinationAddress,
18469
+ // Unused when a payout is stored; checked above otherwise.
18470
+ destinationAddress: destinationAddress ?? "",
18213
18471
  feeRateSatPerVb,
18214
18472
  network,
18215
18473
  btcHtlcScriptVersion
18216
18474
  });
18217
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
+ }
18218
18484
  await this.#broadcastBtcTx(
18219
18485
  esploraUrls,
18220
18486
  network,
@@ -18928,16 +19194,29 @@ network='${network}'`
18928
19194
  * browser wallet usually cannot. Otherwise the wallet itself is the owner.
18929
19195
  * `hint` is appended to the error when neither is.
18930
19196
  */
18931
- #depositorOwnerSigner(swapResponse, walletSigner, hint) {
18932
- const depositor = swapResponse.client_evm_address?.toLowerCase();
18933
- if (depositor === this.getEvmAddress().toLowerCase()) {
18934
- return this.#keyOwnerSigner();
18935
- }
18936
- 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())
18937
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 {
18938
19217
  }
18939
19218
  throw new Error(
18940
- `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}` : ""}`
18941
19220
  );
18942
19221
  }
18943
19222
  /**
@@ -19442,7 +19721,7 @@ network='${network}'`
19442
19721
  "No secret key found for this swap. Cannot sign collab refund."
19443
19722
  );
19444
19723
  }
19445
- const evmKey = this.#getCollabRefundEvmSigningKey(storedSwap);
19724
+ const evmKey = await this.#getCollabRefundEvmSigningKey(storedSwap);
19446
19725
  const { digest, params } = await this.buildCollabRefundEvmTypedData(swapId);
19447
19726
  if (params.refundPath === "direct") {
19448
19727
  return this.#collabRefundEvmSponsored(swapId, params, evmKey);
@@ -20011,7 +20290,7 @@ network='${network}'`
20011
20290
  "No secret key found for this swap. Cannot authorize the rehash."
20012
20291
  );
20013
20292
  }
20014
- const evmKey = this.#getCollabRefundEvmSigningKey(
20293
+ const evmKey = await this.#getCollabRefundEvmSigningKey(
20015
20294
  storedSwap,
20016
20295
  "retrySwapWithInvoiceWithSigner"
20017
20296
  );
@@ -20159,6 +20438,13 @@ network='${network}'`
20159
20438
  // The payout this client asked for; claims pay here, never to a
20160
20439
  // server answer. Recovery rebuilding the swap keeps it.
20161
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,
20162
20448
  bridgeRecipient: bridge?.recipient,
20163
20449
  bridgeRecipientWallet: bridge?.recipientWallet,
20164
20450
  evmFundTxid: existing?.evmFundTxid,
@@ -20177,6 +20463,11 @@ network='${network}'`
20177
20463
  cctpBurnLastValidBlockHeight: existing?.cctpBurnLastValidBlockHeight
20178
20464
  };
20179
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
+ }
20180
20471
  }
20181
20472
  /**
20182
20473
  * Creates a swap by routing to the correct direction-specific method
@@ -20214,6 +20505,10 @@ network='${network}'`
20214
20505
  }
20215
20506
  const sourceAsset = "token_id" in src ? { chain: src.chain, token_id: src.token_id } : { chain: src.chain, token_id: src.tokenId };
20216
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
+ );
20217
20512
  if (isTronToken(sourceAsset.chain))
20218
20513
  throw new Error("Tron is a payout-only destination");
20219
20514
  const isTronTarget = isTronToken(targetAsset.chain) || options.bridgeParams?.targetChain === "Tron";
@@ -20309,6 +20604,11 @@ network='${network}'`
20309
20604
  sourceChain = "42161";
20310
20605
  sourceTokenId = USDC_ADDRESSES.Arbitrum;
20311
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
+ }
20312
20612
  if (isArkade(sourceAsset) && isEvmToken(targetChain)) {
20313
20613
  return this.createArkadeToEvmSwapGeneric({
20314
20614
  targetAddress: options.targetAddress,
@@ -20501,6 +20801,8 @@ network='${network}'`
20501
20801
  );
20502
20802
  }
20503
20803
  return this.createEvmToBitcoinSwap({
20804
+ bitcoinPayout: options.bitcoinPayout,
20805
+ minimumRelayFeeRateSatPerVb: options.minimumRelayFeeRateSatPerVb,
20504
20806
  tokenAddress: sourceTokenId,
20505
20807
  evmChainId: Number(sourceChain),
20506
20808
  userAddress: options.userAddress ?? "",
@@ -20870,7 +21172,69 @@ network='${network}'`
20870
21172
  * ```
20871
21173
  */
20872
21174
  async createEvmToBitcoinSwap(options) {
20873
- 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;
20874
21238
  }
20875
21239
  // =========================================================================
20876
21240
  // Coordinator Funding (EVM-to-BTC via DEX + HTLC)
@@ -20938,7 +21302,10 @@ network='${network}'`
20938
21302
  );
20939
21303
  const deadline = BigInt(Math.floor(Date.now() / 1e3) + 30 * 60);
20940
21304
  const sourceAmount = checked.sourceAmount;
20941
- const evmKey = this.#getEvmSigningKey();
21305
+ const evmKey = await this.#getFundingEvmSigningKey(
21306
+ storedSwap,
21307
+ swap.gasless
21308
+ );
20942
21309
  const depositorAddress = deriveEvmAddress(evmKey);
20943
21310
  const digest = buildPermit2FundingDigest({
20944
21311
  chainId,
@@ -21235,7 +21602,7 @@ network='${network}'`
21235
21602
  swapId,
21236
21603
  expected,
21237
21604
  signer,
21238
- ownerSigner: this.#depositorOwnerSigner(
21605
+ ownerSigner: await this.#depositorOwnerSigner(
21239
21606
  swapResponse,
21240
21607
  signer,
21241
21608
  "Create the swap with `gasless: true` to settle through the SDK's key."
@@ -21435,7 +21802,7 @@ network='${network}'`
21435
21802
  }),
21436
21803
  amount
21437
21804
  );
21438
- const { cctpFundSwapFromSolana } = await import("./fundSwap-UBCHMUP4-WBLYE6MC.js");
21805
+ const { cctpFundSwapFromSolana } = await import("./fundSwap-2D4IPYU4-CDM3WRUF.js");
21439
21806
  const { aa } = this.cctpInbound;
21440
21807
  const cctp = await cctpFundSwapFromSolana(
21441
21808
  { apiClient: this.#apiClient, aa },
@@ -21443,7 +21810,7 @@ network='${network}'`
21443
21810
  swapId,
21444
21811
  expected,
21445
21812
  signer,
21446
- ownerSigner: this.#depositorOwnerSigner(
21813
+ ownerSigner: await this.#depositorOwnerSigner(
21447
21814
  swapResponse,
21448
21815
  void 0,
21449
21816
  "A swap funded from Solana must be created with `gasless: true`."
@@ -21889,7 +22256,7 @@ network='${network}'`
21889
22256
  oldSwap
21890
22257
  };
21891
22258
  }
21892
- const owner = signer ?? this.#keyOwnerSigner();
22259
+ const owner = await this.#depositorOwnerSigner(oldSwap, signer);
21893
22260
  const { accountAddress } = await this.cctpInbound.createSmartAccountClient({
21894
22261
  signer: owner
21895
22262
  });
@@ -21994,17 +22361,11 @@ network='${network}'`
21994
22361
  * address, an Arkade address, or for Lightning a BOLT11 invoice (its amount
21995
22362
  * must be covered by the refund), a Lightning address or an LNURL.
21996
22363
  * @param options.target - The payout type; defaults to the old swap's.
21997
- * @param options.signer - A signer for this client's key; defaults to one
21998
- * derived from it. Any other owner is rejected: the new swap is created
21999
- * gasless, which records this client's key as its depositor, and the
22000
- * 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.
22001
22367
  */
22002
22368
  async continueRefundedEvmSwap(oldSwapId, options) {
22003
- if (options.signer && options.signer.address.toLowerCase() !== this.getEvmAddress().toLowerCase()) {
22004
- throw new Error(
22005
- `Cannot continue refunded swap ${oldSwapId} with signer ${options.signer.address}: a continuation is funded from this client's key (${this.getEvmAddress()}).`
22006
- );
22007
- }
22008
22369
  const info = await this.getRefundedEvmSwapContinuation(
22009
22370
  oldSwapId,
22010
22371
  options.signer
@@ -22012,6 +22373,17 @@ network='${network}'`
22012
22373
  if (!info.eligible || !info.token || !info.amount || !info.oldSwap) {
22013
22374
  throw new Error(info.reason ?? "Refunded swap cannot be continued.");
22014
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
+ );
22015
22387
  const target = options.target ?? {
22016
22388
  evm_to_arkade: "arkade",
22017
22389
  evm_to_bitcoin: "bitcoin",
@@ -22022,7 +22394,7 @@ network='${network}'`
22022
22394
  tokenAddress: info.token.address,
22023
22395
  evmChainId: 42161,
22024
22396
  userAddress: info.smartAccountAddress ?? "",
22025
- gasless: true
22397
+ gasless: false
22026
22398
  };
22027
22399
  let created;
22028
22400
  if (target === "arkade") {
@@ -22048,6 +22420,18 @@ network='${network}'`
22048
22420
  );
22049
22421
  }
22050
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
+ }
22051
22435
  const submitted = await this.cctpInbound.submitBalanceUserOp({
22052
22436
  swapId: newSwapId,
22053
22437
  // The new swap's own hash and terms, recorded when it was just
@@ -22059,7 +22443,7 @@ network='${network}'`
22059
22443
  ),
22060
22444
  pins: options.funding
22061
22445
  },
22062
- signer: options.signer ?? this.#keyOwnerSigner(),
22446
+ signer: await this.#depositorOwnerSigner(info.oldSwap, options.signer),
22063
22447
  expectedMaxSourceAmount: sourceAmount
22064
22448
  });
22065
22449
  if (submitted.transactionHash) {
@@ -22106,20 +22490,7 @@ network='${network}'`
22106
22490
  `Sponsored refunds run on Arbitrum only; swap ${swapId} is on chain ${chainId}. Use refundEvmWithSigner.`
22107
22491
  );
22108
22492
  }
22109
- const { client_evm_address: depositor, gasless } = stored.response;
22110
- let owner;
22111
- if (depositor?.toLowerCase() === this.getEvmAddress().toLowerCase()) {
22112
- owner = this.#keyOwnerSigner();
22113
- } else if (gasless && depositor?.toLowerCase() === deriveEvmAddress(stored.secretKey).toLowerCase()) {
22114
- owner = keyToKernelOwnerSigner(
22115
- hexToBytes(stored.secretKey.replace(/^0x/, "")),
22116
- 42161
22117
- );
22118
- } else {
22119
- throw new Error(
22120
- `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.`
22121
- );
22122
- }
22493
+ const owner = await this.#depositorOwnerSigner(stored.response);
22123
22494
  const result = await this.refundSwap(swapId);
22124
22495
  if (!result.evmRefundData) {
22125
22496
  throw new Error(
@@ -22140,10 +22511,6 @@ network='${network}'`
22140
22511
  (account) => refundForAsOwnRefund(refund, account)
22141
22512
  );
22142
22513
  }
22143
- /** This client's key as the Kernel owner on Arbitrum. */
22144
- #keyOwnerSigner() {
22145
- return keyToKernelOwnerSigner(this.#signer.deriveEvmKey().secretKey, 42161);
22146
- }
22147
22514
  /**
22148
22515
  * An `eth_call` over the AA RPC, for reads on an account this client owns
22149
22516
  * with its key (whose signer does not read the chain).
@@ -22279,7 +22646,10 @@ network='${network}'`
22279
22646
  );
22280
22647
  const deadline = BigInt(Math.floor(Date.now() / 1e3) + 30 * 60);
22281
22648
  const sourceAmount = checked.sourceAmount;
22282
- const evmKey = this.#getEvmSigningKey();
22649
+ const evmKey = await this.#getFundingEvmSigningKey(
22650
+ storedSwap,
22651
+ swap.gasless
22652
+ );
22283
22653
  const depositorAddress = deriveEvmAddress(evmKey);
22284
22654
  const digest = buildPermit2FundingDigest({
22285
22655
  chainId,
@@ -22395,7 +22765,7 @@ network='${network}'`
22395
22765
  if (!this.#swapStorage)
22396
22766
  throw new Error("Sponsored funding requires swap storage");
22397
22767
  if (stored.evmFundingUserOpHash) {
22398
- const key2 = this.#gaslessDepositorKey(swapId, stored, swap);
22768
+ const key2 = await this.#gaslessDepositorKey(swapId, stored, swap);
22399
22769
  const { client } = await this.cctpInbound.createSmartAccountClient({
22400
22770
  signer: keyToKernelOwnerSigner(
22401
22771
  hexToBytes(key2.replace(/^0x/, "")),
@@ -22448,7 +22818,9 @@ network='${network}'`
22448
22818
  if (receipt.status === "reverted") {
22449
22819
  await this.#forgetEvmFunding(swapId, stored.evmFundTxid);
22450
22820
  } else if (receipt.status === "success" && receipt.logs !== void 0) {
22451
- 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;
22452
22824
  const locks = findSwapCreated(receipt.logs, {
22453
22825
  htlcAddress: expected.terms.htlcAddress,
22454
22826
  hashLock: expected.hashLock,
@@ -22473,7 +22845,7 @@ network='${network}'`
22473
22845
  );
22474
22846
  }
22475
22847
  }
22476
- const key = this.#gaslessDepositorKey(swapId, stored, swap);
22848
+ const key = await this.#gaslessDepositorKey(swapId, stored, swap);
22477
22849
  const owner = keyToKernelOwnerSigner(
22478
22850
  hexToBytes(key.replace(/^0x/, "")),
22479
22851
  AA_CHAIN_ID
@@ -22517,18 +22889,23 @@ network='${network}'`
22517
22889
  * account, so a depositor this SDK does not control cannot be funded
22518
22890
  * here.
22519
22891
  */
22520
- #gaslessDepositorKey(swapId, stored, swap) {
22521
- const depositor = swap.client_evm_address?.toLowerCase();
22522
- const sharedKey = this.#getEvmSigningKey();
22523
- if (!depositor || depositor === deriveEvmAddress(sharedKey).toLowerCase()) {
22524
- return sharedKey;
22525
- }
22526
- if (depositor === deriveEvmAddress(stored.secretKey).toLowerCase()) {
22527
- 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;
22528
22903
  }
22529
- throw new Error(
22530
- `Cannot fund swap ${swapId} sponsored: its depositor ${depositor} is not an SDK-controlled account. Fund it from that wallet with fundSwap.`
22531
- );
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;
22532
22909
  }
22533
22910
  /**
22534
22911
  * Get the ephemeral depositor key for a gasless swap funded swap.
@@ -22559,29 +22936,40 @@ network='${network}'`
22559
22936
  );
22560
22937
  }
22561
22938
  const response = storedSwap.response;
22562
- const depositor = response.client_evm_address?.toLowerCase();
22939
+ const depositor = (storedSwap.evmFundingTerms?.depositor ?? response.client_evm_address)?.toLowerCase();
22563
22940
  const sharedKey = this.#getEvmSigningKey();
22564
- const sharedAddress = deriveEvmAddress(sharedKey).toLowerCase();
22565
- const swapAddress = deriveEvmAddress(storedSwap.secretKey).toLowerCase();
22566
- let evmKey = sharedKey;
22567
- if (depositor === swapAddress) {
22568
- evmKey = storedSwap.secretKey;
22569
- } 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))
22570
22954
  throw new Error(
22571
- `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.`
22572
22956
  );
22573
- }
22957
+ const evmKey = matched ?? sharedKey;
22574
22958
  const privateKey = evmKey.startsWith("0x") ? evmKey : `0x${evmKey}`;
22575
22959
  const address2 = deriveEvmAddress(evmKey);
22576
- 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
+ };
22577
22965
  }
22578
22966
  /**
22579
22967
  * Wallet-level variant of {@link getSwapDepositorKey} — returns the
22580
22968
  * deterministic EVM signing key for this wallet without requiring a
22581
22969
  * specific swap to be stored locally.
22582
22970
  *
22583
- * This returns only the shared `m/44'/60'/0'/0/0` account, not a
22584
- * 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
22585
22973
  * where the user supplies the burn details manually and a per-swap
22586
22974
  * record may no longer exist (e.g. fresh device, cleared site data).
22587
22975
  */
@@ -22629,7 +23017,7 @@ network='${network}'`
22629
23017
  return recoverCctpInbound(
22630
23018
  { aa: this.#config.aa },
22631
23019
  {
22632
- signer: this.#depositorOwnerSigner(
23020
+ signer: await this.#depositorOwnerSigner(
22633
23021
  stored.response,
22634
23022
  options?.ownerSigner
22635
23023
  ),
@@ -23186,11 +23574,16 @@ export {
23186
23574
  getUsdt0BridgeTokens,
23187
23575
  isSpark,
23188
23576
  Signer,
23577
+ validateBitcoinPayout,
23578
+ allocateBitcoinPayout,
23189
23579
  computeHash160,
23190
23580
  buildOnchainClaimTransaction,
23191
23581
  buildOnchainRefundTransaction,
23192
23582
  verifyHtlcAddress,
23193
23583
  SwapVerificationError,
23584
+ bitcoinNetworkOf,
23585
+ commitBitcoinPayment,
23586
+ minimumBitcoinPayout,
23194
23587
  addressToScriptHash,
23195
23588
  ElectrumWsClient,
23196
23589
  electrumFindOutputByAddress,
@@ -23235,4 +23628,4 @@ export {
23235
23628
  @scure/bip39/index.js:
23236
23629
  (*! scure-bip39 - MIT License (c) 2022 Patricio Palladino, Paul Miller (paulmillr.com) *)
23237
23630
  */
23238
- //# sourceMappingURL=chunk-YBQPH7NH.js.map
23631
+ //# sourceMappingURL=chunk-34OYIFOU.js.map