@buildonspark/spark-sdk 0.3.6 → 0.3.7

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 (70) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/dist/bare/index.cjs +9240 -9125
  3. package/dist/bare/index.d.cts +14 -11
  4. package/dist/bare/index.d.ts +14 -11
  5. package/dist/bare/index.js +3917 -3802
  6. package/dist/{chunk-XPHYQ2L6.js → chunk-KDEVNW7C.js} +4895 -4779
  7. package/dist/{chunk-LIZFXQWK.js → chunk-P4HYYSMU.js} +1 -1
  8. package/dist/{chunk-EHKP3Y65.js → chunk-SRPKOCG4.js} +1 -2
  9. package/dist/{chunk-FJ7LTA2O.js → chunk-UYTT3C6H.js} +1 -1
  10. package/dist/{client-AHn11NHe.d.cts → client-Bcb7TUIp.d.cts} +11 -9
  11. package/dist/{client-GOlkXliC.d.ts → client-D9T58OY8.d.ts} +11 -9
  12. package/dist/debug.cjs +1852 -1738
  13. package/dist/debug.d.cts +4 -4
  14. package/dist/debug.d.ts +4 -4
  15. package/dist/debug.js +2 -2
  16. package/dist/graphql/objects/index.d.cts +2 -2
  17. package/dist/graphql/objects/index.d.ts +2 -2
  18. package/dist/index.cjs +174 -58
  19. package/dist/index.d.cts +5 -5
  20. package/dist/index.d.ts +5 -5
  21. package/dist/index.js +3 -3
  22. package/dist/index.node.cjs +174 -57
  23. package/dist/index.node.d.cts +5 -5
  24. package/dist/index.node.d.ts +5 -5
  25. package/dist/index.node.js +2 -2
  26. package/dist/{logging-D7ukPwRA.d.ts → logging-JIaZZIbR.d.ts} +2 -2
  27. package/dist/{logging-CW3kwBaM.d.cts → logging-zkr4UlOi.d.cts} +2 -2
  28. package/dist/native/{index.cjs → index.react-native.cjs} +182 -62
  29. package/dist/native/{index.d.cts → index.react-native.d.cts} +19 -15
  30. package/dist/native/{index.d.ts → index.react-native.d.ts} +19 -15
  31. package/dist/native/{index.js → index.react-native.js} +179 -60
  32. package/dist/{spark-wallet-NxG55m7K.d.cts → spark-wallet-BuFrUWeE.d.cts} +4 -3
  33. package/dist/{spark-wallet-jwNvWvpK.d.ts → spark-wallet-CE5PYiIb.d.ts} +4 -3
  34. package/dist/{spark-wallet.browser-Cg4fB-Nm.d.ts → spark-wallet.browser-BwYkkOBU.d.ts} +1 -1
  35. package/dist/{spark-wallet.browser-Db7Y95Kt.d.cts → spark-wallet.browser-DC3jdQPW.d.cts} +1 -1
  36. package/dist/{spark-wallet.node-DB3ZqtJG.d.ts → spark-wallet.node-C9d2W-Nb.d.ts} +1 -1
  37. package/dist/{spark-wallet.node-HEG2ahNd.d.cts → spark-wallet.node-CR_zNxmy.d.cts} +1 -1
  38. package/dist/tests/test-utils.cjs +168 -51
  39. package/dist/tests/test-utils.d.cts +4 -4
  40. package/dist/tests/test-utils.d.ts +4 -4
  41. package/dist/tests/test-utils.js +4 -4
  42. package/dist/{token-transactions-B2-BO7Oz.d.ts → token-transactions-BZoJuvuE.d.ts} +1 -1
  43. package/dist/{token-transactions-BAN68xwg.d.cts → token-transactions-I_OFIoNH.d.cts} +1 -1
  44. package/dist/types/index.d.cts +1 -1
  45. package/dist/types/index.d.ts +1 -1
  46. package/package.json +14 -4
  47. package/src/graphql/client.ts +6 -9
  48. package/src/graphql/mutations/CompleteCoopExit.ts +1 -1
  49. package/src/graphql/mutations/RequestCoopExit.ts +3 -1
  50. package/src/graphql/mutations/RequestLightningSend.ts +3 -1
  51. package/src/graphql/objects/CompleteCoopExitInput.ts +22 -33
  52. package/src/graphql/objects/RequestCoopExitInput.ts +39 -45
  53. package/src/graphql/objects/RequestLightningSendInput.ts +31 -39
  54. package/src/index.react-native.ts +21 -0
  55. package/src/services/config.ts +2 -2
  56. package/src/services/connection/connection.ts +10 -0
  57. package/src/services/coop-exit.ts +5 -1
  58. package/src/services/token-transactions.ts +8 -8
  59. package/src/spark-wallet/spark-wallet.browser.ts +0 -1
  60. package/src/spark-wallet/spark-wallet.react-native.ts +5 -3
  61. package/src/spark-wallet/spark-wallet.ts +56 -9
  62. package/src/tests/integration/coop-exit.test.ts +2 -0
  63. package/src/tests/integration/lightning.test.ts +5 -1
  64. package/src/tests/integration/ssp/coop-exit-validation.test.ts +5 -6
  65. package/src/tests/integration/ssp/static_deposit.test.ts +45 -35
  66. package/src/tests/optimize.test.ts +45 -0
  67. package/src/tests/token-outputs.test.ts +60 -1
  68. package/src/tests/utils/test-faucet.ts +12 -8
  69. package/src/utils/optimize.ts +226 -0
  70. package/src/native/index.ts +0 -21
package/dist/debug.d.cts CHANGED
@@ -1,7 +1,7 @@
1
- import { B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, D as DecodedSparkAddressData, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, c as SparkAddressData, S as SparkAddressFormat, l as assertBech32, m as bech32mDecode, y as decodeBech32mTokenIdentifier, f as decodeSparkAddress, x as encodeBech32mTokenIdentifier, e as encodeSparkAddress, d as encodeSparkAddressWithSignature, r as getNetwork, s as getNetworkFromAddress, z as getNetworkFromBech32mTokenIdentifier, g as getNetworkFromSparkAddress, u as getNetworkFromString, i as isLegacySparkAddress, n as isSafeForNumber, j as isValidPublicKey, h as isValidSparkAddress, q as protoToNetwork, t as toProtoTimestamp, v as validateSparkInvoiceFields, k as validateSparkInvoiceSignature, b as ConfigOptions } from './spark-wallet-NxG55m7K.cjs';
2
- import { S as SparkWalletBrowser } from './spark-wallet.browser-Db7Y95Kt.cjs';
3
- import { ab as BroadcastConfig, ac as BroadcastResult, Q as DEFAULT_FEE_SATS, M as DIRECT_TIMELOCK_OFFSET, a9 as FeeBumpTxChain, a8 as FeeBumpTxPackage, a7 as FeeRate, O as INITIAL_DIRECT_SEQUENCE, N as INITIAL_SEQUENCE, ai as LOGGER_NAMES, a5 as LeafInfo, aj as LoggerName, ak as SparkSdkLogger, P as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, aa as TxChain, a6 as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a1 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, ag as constructFeeBumpTx, af as constructUnilateralExitFeeBumpPackages, ae as constructUnilateralExitTxs, _ as createConnectorRefundTransactions, X as createLeafNodeTx, V as createNodeTx, W as createNodeTxs, Y as createRefundTx, Z as createRefundTxs, S as createRootTx, F as createSigningCommitment, B as createSigningNonce, U as createSplitTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a2 as doesLeafNeedRefresh, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, $ as getCurrentTimelock, a4 as getEphemeralAnchorOutput, w as getLatestDepositTxId, a3 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, ah as getSparkAddressFromTaproot, a0 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, ad as isEphemeralAnchorOutput, x as isTxBroadcast, u as lastKeyWithTarget, R as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-CW3kwBaM.cjs';
4
- import { V as VerifiableSecretShare, h as bigIntToPrivateKey, c as computerLagrangeCoefficients, e as evaluatePolynomial, f as fieldDiv, b as generatePolynomialForSecretSharing, g as getRandomBigInt, m as modInverse, r as recoverSecret, s as splitSecret, d as splitSecretWithProofs, v as validateShare } from './client-AHn11NHe.cjs';
1
+ import { B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, D as DecodedSparkAddressData, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, c as SparkAddressData, S as SparkAddressFormat, l as assertBech32, m as bech32mDecode, y as decodeBech32mTokenIdentifier, f as decodeSparkAddress, x as encodeBech32mTokenIdentifier, e as encodeSparkAddress, d as encodeSparkAddressWithSignature, r as getNetwork, s as getNetworkFromAddress, z as getNetworkFromBech32mTokenIdentifier, g as getNetworkFromSparkAddress, u as getNetworkFromString, i as isLegacySparkAddress, n as isSafeForNumber, j as isValidPublicKey, h as isValidSparkAddress, q as protoToNetwork, t as toProtoTimestamp, v as validateSparkInvoiceFields, k as validateSparkInvoiceSignature, b as ConfigOptions } from './spark-wallet-BuFrUWeE.cjs';
2
+ import { S as SparkWalletBrowser } from './spark-wallet.browser-DC3jdQPW.cjs';
3
+ import { ab as BroadcastConfig, ac as BroadcastResult, Q as DEFAULT_FEE_SATS, M as DIRECT_TIMELOCK_OFFSET, a9 as FeeBumpTxChain, a8 as FeeBumpTxPackage, a7 as FeeRate, O as INITIAL_DIRECT_SEQUENCE, N as INITIAL_SEQUENCE, ai as LOGGER_NAMES, a5 as LeafInfo, aj as LoggerName, ak as SparkSdkLogger, P as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, aa as TxChain, a6 as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a1 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, ag as constructFeeBumpTx, af as constructUnilateralExitFeeBumpPackages, ae as constructUnilateralExitTxs, _ as createConnectorRefundTransactions, X as createLeafNodeTx, V as createNodeTx, W as createNodeTxs, Y as createRefundTx, Z as createRefundTxs, S as createRootTx, F as createSigningCommitment, B as createSigningNonce, U as createSplitTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a2 as doesLeafNeedRefresh, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, $ as getCurrentTimelock, a4 as getEphemeralAnchorOutput, w as getLatestDepositTxId, a3 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, ah as getSparkAddressFromTaproot, a0 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, ad as isEphemeralAnchorOutput, x as isTxBroadcast, u as lastKeyWithTarget, R as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-zkr4UlOi.cjs';
4
+ import { V as VerifiableSecretShare, h as bigIntToPrivateKey, c as computerLagrangeCoefficients, e as evaluatePolynomial, f as fieldDiv, b as generatePolynomialForSecretSharing, g as getRandomBigInt, m as modInverse, r as recoverSecret, s as splitSecret, d as splitSecretWithProofs, v as validateShare } from './client-Bcb7TUIp.cjs';
5
5
  import './spark-WA_4wcBr.cjs';
6
6
  import '@bufbuild/protobuf/wire';
7
7
  import 'nice-grpc-common';
package/dist/debug.d.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, D as DecodedSparkAddressData, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, c as SparkAddressData, S as SparkAddressFormat, l as assertBech32, m as bech32mDecode, y as decodeBech32mTokenIdentifier, f as decodeSparkAddress, x as encodeBech32mTokenIdentifier, e as encodeSparkAddress, d as encodeSparkAddressWithSignature, r as getNetwork, s as getNetworkFromAddress, z as getNetworkFromBech32mTokenIdentifier, g as getNetworkFromSparkAddress, u as getNetworkFromString, i as isLegacySparkAddress, n as isSafeForNumber, j as isValidPublicKey, h as isValidSparkAddress, q as protoToNetwork, t as toProtoTimestamp, v as validateSparkInvoiceFields, k as validateSparkInvoiceSignature, b as ConfigOptions } from './spark-wallet-jwNvWvpK.js';
2
- import { S as SparkWalletBrowser } from './spark-wallet.browser-Cg4fB-Nm.js';
3
- import { ab as BroadcastConfig, ac as BroadcastResult, Q as DEFAULT_FEE_SATS, M as DIRECT_TIMELOCK_OFFSET, a9 as FeeBumpTxChain, a8 as FeeBumpTxPackage, a7 as FeeRate, O as INITIAL_DIRECT_SEQUENCE, N as INITIAL_SEQUENCE, ai as LOGGER_NAMES, a5 as LeafInfo, aj as LoggerName, ak as SparkSdkLogger, P as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, aa as TxChain, a6 as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a1 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, ag as constructFeeBumpTx, af as constructUnilateralExitFeeBumpPackages, ae as constructUnilateralExitTxs, _ as createConnectorRefundTransactions, X as createLeafNodeTx, V as createNodeTx, W as createNodeTxs, Y as createRefundTx, Z as createRefundTxs, S as createRootTx, F as createSigningCommitment, B as createSigningNonce, U as createSplitTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a2 as doesLeafNeedRefresh, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, $ as getCurrentTimelock, a4 as getEphemeralAnchorOutput, w as getLatestDepositTxId, a3 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, ah as getSparkAddressFromTaproot, a0 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, ad as isEphemeralAnchorOutput, x as isTxBroadcast, u as lastKeyWithTarget, R as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-D7ukPwRA.js';
4
- import { V as VerifiableSecretShare, h as bigIntToPrivateKey, c as computerLagrangeCoefficients, e as evaluatePolynomial, f as fieldDiv, b as generatePolynomialForSecretSharing, g as getRandomBigInt, m as modInverse, r as recoverSecret, s as splitSecret, d as splitSecretWithProofs, v as validateShare } from './client-GOlkXliC.js';
1
+ import { B as Bech32mTokenIdentifier, w as Bech32mTokenIdentifierData, D as DecodedSparkAddressData, L as LegacySparkAddressFormat, N as Network, p as NetworkToProto, o as NetworkType, c as SparkAddressData, S as SparkAddressFormat, l as assertBech32, m as bech32mDecode, y as decodeBech32mTokenIdentifier, f as decodeSparkAddress, x as encodeBech32mTokenIdentifier, e as encodeSparkAddress, d as encodeSparkAddressWithSignature, r as getNetwork, s as getNetworkFromAddress, z as getNetworkFromBech32mTokenIdentifier, g as getNetworkFromSparkAddress, u as getNetworkFromString, i as isLegacySparkAddress, n as isSafeForNumber, j as isValidPublicKey, h as isValidSparkAddress, q as protoToNetwork, t as toProtoTimestamp, v as validateSparkInvoiceFields, k as validateSparkInvoiceSignature, b as ConfigOptions } from './spark-wallet-CE5PYiIb.js';
2
+ import { S as SparkWalletBrowser } from './spark-wallet.browser-BwYkkOBU.js';
3
+ import { ab as BroadcastConfig, ac as BroadcastResult, Q as DEFAULT_FEE_SATS, M as DIRECT_TIMELOCK_OFFSET, a9 as FeeBumpTxChain, a8 as FeeBumpTxPackage, a7 as FeeRate, O as INITIAL_DIRECT_SEQUENCE, N as INITIAL_SEQUENCE, ai as LOGGER_NAMES, a5 as LeafInfo, aj as LoggerName, ak as SparkSdkLogger, P as TEST_UNILATERAL_DIRECT_SEQUENCE, T as TEST_UNILATERAL_SEQUENCE, aa as TxChain, a6 as Utxo, q as addPrivateKeys, o as addPublicKeys, b as applyAdaptorToSignature, p as applyAdditiveTweakToPublicKey, J as checkIfSelectedOutputsAreAvailable, a1 as checkIfValidSequence, z as collectResponses, c as computeTaprootKeyNoScript, ag as constructFeeBumpTx, af as constructUnilateralExitFeeBumpPackages, ae as constructUnilateralExitTxs, _ as createConnectorRefundTransactions, X as createLeafNodeTx, V as createNodeTx, W as createNodeTxs, Y as createRefundTx, Z as createRefundTxs, S as createRootTx, F as createSigningCommitment, B as createSigningNonce, U as createSplitTx, H as decodeBytesToSigningCommitment, E as decodeBytesToSigningNonce, a2 as doesLeafNeedRefresh, G as encodeSigningCommitmentToBytes, D as encodeSigningNonceToBytes, K as filterTokenBalanceForTokenIdentifier, a as generateAdaptorFromSignature, g as generateSignatureFromExistingAdaptor, $ as getCurrentTimelock, a4 as getEphemeralAnchorOutput, w as getLatestDepositTxId, a3 as getNextTransactionSequence, f as getP2TRAddressFromPkScript, e as getP2TRAddressFromPublicKey, d as getP2TRScriptFromPublicKey, h as getP2WPKHAddressFromPublicKey, A as getRandomSigningNonce, k as getSigHashFromTx, C as getSigningCommitmentFromNonce, ah as getSparkAddressFromTaproot, a0 as getTransactionSequence, L as getTransferPackageSigningPayload, n as getTxEstimatedVbytesSizeByNumberOfInputsOutputs, j as getTxFromRawTxBytes, i as getTxFromRawTxHex, l as getTxId, m as getTxIdNoReverse, ad as isEphemeralAnchorOutput, x as isTxBroadcast, u as lastKeyWithTarget, R as maybeApplyFee, y as proofOfPossessionMessageHashForDepositAddress, r as subtractPrivateKeys, s as subtractPublicKeys, I as sumAvailableTokens, t as sumOfPrivateKeys, v as validateOutboundAdaptorSignature } from './logging-JIaZZIbR.js';
4
+ import { V as VerifiableSecretShare, h as bigIntToPrivateKey, c as computerLagrangeCoefficients, e as evaluatePolynomial, f as fieldDiv, b as generatePolynomialForSecretSharing, g as getRandomBigInt, m as modInverse, r as recoverSecret, s as splitSecret, d as splitSecretWithProofs, v as validateShare } from './client-D9T58OY8.js';
5
5
  import './spark-WA_4wcBr.js';
6
6
  import '@bufbuild/protobuf/wire';
7
7
  import 'nice-grpc-common';
package/dist/debug.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  SparkWalletBrowser
3
- } from "./chunk-EHKP3Y65.js";
3
+ } from "./chunk-SRPKOCG4.js";
4
4
  import {
5
5
  WalletConfig,
6
6
  utils_exports
7
- } from "./chunk-XPHYQ2L6.js";
7
+ } from "./chunk-KDEVNW7C.js";
8
8
  import "./chunk-NX5KPN5F.js";
9
9
  import "./chunk-XWLR6G5C.js";
10
10
  import "./chunk-J2P3KTQP.js";
@@ -1,5 +1,5 @@
1
- import { B as BitcoinNetwork, P as PageInfo, J as SspClient } from '../../client-AHn11NHe.cjs';
2
- export { O as ClaimStaticDeposit, C as ClaimStaticDepositOutput, Q as ClaimStaticDepositStatus, R as CompleteCoopExitInput, X as CompleteLeavesSwapInput, Y as CoopExitFeeEstimate, Z as CoopExitFeeEstimatesInput, _ as CoopExitFeeEstimatesOutput, F as CoopExitFeeQuote, a0 as CoopExitFeeQuoteInput, G as CoopExitRequest, a2 as CurrencyAmount, a3 as CurrencyUnit, E as ExitSpeed, a4 as GetChallengeOutput, a5 as Invoice, a6 as Leaf, L as LeavesSwapFeeEstimateOutput, a8 as LeavesSwapRequest, x as LightningReceiveRequest, aa as LightningReceiveRequestStatus, z as LightningSendFeeEstimateInput, ab as LightningSendFeeEstimateOutput, y as LightningSendRequest, ad as LightningSendRequestStatus, ae as RequestCoopExitInput, af as RequestLeavesSwapInput, ag as RequestLightningReceiveInput, ah as RequestLightningSendInput, ai as SparkCoopExitRequestStatus, aj as SparkLeavesSwapRequestStatus, ak as SparkTransferToLeavesConnection, al as StaticDepositQuoteInput, u as StaticDepositQuoteOutput, am as SwapLeaf, an as Transfer, ao as UserLeafInput, ap as VerifyChallengeOutput, N as getClaimStaticDepositQuery, $ as getCoopExitFeeQuoteQuery, a1 as getCoopExitRequestQuery, a7 as getLeavesSwapRequestQuery, a9 as getLightningReceiveRequestQuery, ac as getLightningSendRequestQuery } from '../../client-AHn11NHe.cjs';
1
+ import { B as BitcoinNetwork, P as PageInfo, J as SspClient } from '../../client-Bcb7TUIp.cjs';
2
+ export { O as ClaimStaticDeposit, C as ClaimStaticDepositOutput, Q as ClaimStaticDepositStatus, R as CompleteCoopExitInput, X as CompleteLeavesSwapInput, Y as CoopExitFeeEstimate, Z as CoopExitFeeEstimatesInput, _ as CoopExitFeeEstimatesOutput, F as CoopExitFeeQuote, a0 as CoopExitFeeQuoteInput, G as CoopExitRequest, a2 as CurrencyAmount, a3 as CurrencyUnit, E as ExitSpeed, a4 as GetChallengeOutput, a5 as Invoice, a6 as Leaf, L as LeavesSwapFeeEstimateOutput, a8 as LeavesSwapRequest, x as LightningReceiveRequest, aa as LightningReceiveRequestStatus, z as LightningSendFeeEstimateInput, ab as LightningSendFeeEstimateOutput, y as LightningSendRequest, ad as LightningSendRequestStatus, ae as RequestCoopExitInput, af as RequestLeavesSwapInput, ag as RequestLightningReceiveInput, ah as RequestLightningSendInput, ai as SparkCoopExitRequestStatus, aj as SparkLeavesSwapRequestStatus, ak as SparkTransferToLeavesConnection, al as StaticDepositQuoteInput, u as StaticDepositQuoteOutput, am as SwapLeaf, an as Transfer, ao as UserLeafInput, ap as VerifyChallengeOutput, N as getClaimStaticDepositQuery, $ as getCoopExitFeeQuoteQuery, a1 as getCoopExitRequestQuery, a7 as getLeavesSwapRequestQuery, a9 as getLightningReceiveRequestQuery, ac as getLightningSendRequestQuery } from '../../client-Bcb7TUIp.cjs';
3
3
  import { Query } from '@lightsparkdev/core';
4
4
  import '../../spark-WA_4wcBr.cjs';
5
5
  import '@scure/btc-signer';
@@ -1,5 +1,5 @@
1
- import { B as BitcoinNetwork, P as PageInfo, J as SspClient } from '../../client-GOlkXliC.js';
2
- export { O as ClaimStaticDeposit, C as ClaimStaticDepositOutput, Q as ClaimStaticDepositStatus, R as CompleteCoopExitInput, X as CompleteLeavesSwapInput, Y as CoopExitFeeEstimate, Z as CoopExitFeeEstimatesInput, _ as CoopExitFeeEstimatesOutput, F as CoopExitFeeQuote, a0 as CoopExitFeeQuoteInput, G as CoopExitRequest, a2 as CurrencyAmount, a3 as CurrencyUnit, E as ExitSpeed, a4 as GetChallengeOutput, a5 as Invoice, a6 as Leaf, L as LeavesSwapFeeEstimateOutput, a8 as LeavesSwapRequest, x as LightningReceiveRequest, aa as LightningReceiveRequestStatus, z as LightningSendFeeEstimateInput, ab as LightningSendFeeEstimateOutput, y as LightningSendRequest, ad as LightningSendRequestStatus, ae as RequestCoopExitInput, af as RequestLeavesSwapInput, ag as RequestLightningReceiveInput, ah as RequestLightningSendInput, ai as SparkCoopExitRequestStatus, aj as SparkLeavesSwapRequestStatus, ak as SparkTransferToLeavesConnection, al as StaticDepositQuoteInput, u as StaticDepositQuoteOutput, am as SwapLeaf, an as Transfer, ao as UserLeafInput, ap as VerifyChallengeOutput, N as getClaimStaticDepositQuery, $ as getCoopExitFeeQuoteQuery, a1 as getCoopExitRequestQuery, a7 as getLeavesSwapRequestQuery, a9 as getLightningReceiveRequestQuery, ac as getLightningSendRequestQuery } from '../../client-GOlkXliC.js';
1
+ import { B as BitcoinNetwork, P as PageInfo, J as SspClient } from '../../client-D9T58OY8.js';
2
+ export { O as ClaimStaticDeposit, C as ClaimStaticDepositOutput, Q as ClaimStaticDepositStatus, R as CompleteCoopExitInput, X as CompleteLeavesSwapInput, Y as CoopExitFeeEstimate, Z as CoopExitFeeEstimatesInput, _ as CoopExitFeeEstimatesOutput, F as CoopExitFeeQuote, a0 as CoopExitFeeQuoteInput, G as CoopExitRequest, a2 as CurrencyAmount, a3 as CurrencyUnit, E as ExitSpeed, a4 as GetChallengeOutput, a5 as Invoice, a6 as Leaf, L as LeavesSwapFeeEstimateOutput, a8 as LeavesSwapRequest, x as LightningReceiveRequest, aa as LightningReceiveRequestStatus, z as LightningSendFeeEstimateInput, ab as LightningSendFeeEstimateOutput, y as LightningSendRequest, ad as LightningSendRequestStatus, ae as RequestCoopExitInput, af as RequestLeavesSwapInput, ag as RequestLightningReceiveInput, ah as RequestLightningSendInput, ai as SparkCoopExitRequestStatus, aj as SparkLeavesSwapRequestStatus, ak as SparkTransferToLeavesConnection, al as StaticDepositQuoteInput, u as StaticDepositQuoteOutput, am as SwapLeaf, an as Transfer, ao as UserLeafInput, ap as VerifyChallengeOutput, N as getClaimStaticDepositQuery, $ as getCoopExitFeeQuoteQuery, a1 as getCoopExitRequestQuery, a7 as getLeavesSwapRequestQuery, a9 as getLightningReceiveRequestQuery, ac as getLightningSendRequestQuery } from '../../client-D9T58OY8.js';
3
3
  import { Query } from '@lightsparkdev/core';
4
4
  import '../../spark-WA_4wcBr.js';
5
5
  import '@scure/btc-signer';
package/dist/index.cjs CHANGED
@@ -18073,8 +18073,8 @@ function addPrivateKeys(a, b) {
18073
18073
  }
18074
18074
  const privA = import_secp256k14.secp256k1.utils.normPrivateKeyToScalar(a);
18075
18075
  const privB = import_secp256k14.secp256k1.utils.normPrivateKeyToScalar(b);
18076
- const sum = (privA + privB) % import_secp256k14.secp256k1.CURVE.n;
18077
- return (0, import_utils6.numberToBytesBE)(sum, 32);
18076
+ const sum2 = (privA + privB) % import_secp256k14.secp256k1.CURVE.n;
18077
+ return (0, import_utils6.numberToBytesBE)(sum2, 32);
18078
18078
  }
18079
18079
  function subtractPrivateKeys(a, b) {
18080
18080
  if (a.length !== 32 || b.length !== 32) {
@@ -18086,11 +18086,11 @@ function subtractPrivateKeys(a, b) {
18086
18086
  }
18087
18087
  const privA = import_secp256k14.secp256k1.utils.normPrivateKeyToScalar(a);
18088
18088
  const privB = import_secp256k14.secp256k1.utils.normPrivateKeyToScalar(b);
18089
- const sum = (import_secp256k14.secp256k1.CURVE.n - privB + privA) % import_secp256k14.secp256k1.CURVE.n;
18090
- return (0, import_utils6.numberToBytesBE)(sum, 32);
18089
+ const sum2 = (import_secp256k14.secp256k1.CURVE.n - privB + privA) % import_secp256k14.secp256k1.CURVE.n;
18090
+ return (0, import_utils6.numberToBytesBE)(sum2, 32);
18091
18091
  }
18092
18092
  function sumOfPrivateKeys(keys) {
18093
- return keys.reduce((sum, key) => {
18093
+ return keys.reduce((sum2, key) => {
18094
18094
  if (key.length !== 32) {
18095
18095
  throw new ValidationError("Private keys must be 32 bytes", {
18096
18096
  field: "privateKey",
@@ -18098,7 +18098,7 @@ function sumOfPrivateKeys(keys) {
18098
18098
  expected: 32
18099
18099
  });
18100
18100
  }
18101
- return addPrivateKeys(sum, key);
18101
+ return addPrivateKeys(sum2, key);
18102
18102
  });
18103
18103
  }
18104
18104
  function lastKeyWithTarget(target, keys) {
@@ -18109,8 +18109,8 @@ function lastKeyWithTarget(target, keys) {
18109
18109
  expected: 32
18110
18110
  });
18111
18111
  }
18112
- const sum = sumOfPrivateKeys(keys);
18113
- return subtractPrivateKeys(target, sum);
18112
+ const sum2 = sumOfPrivateKeys(keys);
18113
+ return subtractPrivateKeys(target, sum2);
18114
18114
  }
18115
18115
 
18116
18116
  // src/utils/mempool.ts
@@ -19814,7 +19814,7 @@ var import_utils9 = require("@noble/curves/utils");
19814
19814
  function sumAvailableTokens(outputs) {
19815
19815
  try {
19816
19816
  return outputs.reduce(
19817
- (sum, output) => sum + BigInt((0, import_utils9.bytesToNumberBE)(output.output.tokenAmount)),
19817
+ (sum2, output) => sum2 + BigInt((0, import_utils9.bytesToNumberBE)(output.output.tokenAmount)),
19818
19818
  BigInt(0)
19819
19819
  );
19820
19820
  } catch (error) {
@@ -20744,7 +20744,7 @@ var isWebExtension = (
20744
20744
  "chrome" in globalThis && globalThis.chrome.runtime?.id
20745
20745
  );
20746
20746
  var userAgent = "navigator" in globalThis ? globalThis.navigator.userAgent || "unknown-user-agent" : void 0;
20747
- var packageVersion = true ? "0.3.6" : "unknown";
20747
+ var packageVersion = true ? "0.3.7" : "unknown";
20748
20748
  var baseEnvStr = "unknown";
20749
20749
  if (isBun) {
20750
20750
  const bunVersion = "version" in globalThis.Bun ? globalThis.Bun.version : "unknown-version";
@@ -21417,7 +21417,7 @@ fragment CoopExitRequestFragment on CoopExitRequest {
21417
21417
  var CompleteCoopExit = `
21418
21418
  mutation CompleteCoopExit(
21419
21419
  $user_outbound_transfer_external_id: UUID!
21420
- $coop_exit_request_id: ID!
21420
+ $coop_exit_request_id: ID
21421
21421
  ) {
21422
21422
  complete_coop_exit(input: {
21423
21423
  user_outbound_transfer_external_id: $user_outbound_transfer_external_id
@@ -21495,11 +21495,12 @@ var RequestCoopExit = `
21495
21495
  mutation RequestCoopExit(
21496
21496
  $leaf_external_ids: [UUID!]!
21497
21497
  $withdrawal_address: String!
21498
- $idempotency_key: String!
21498
+ $idempotency_key: String
21499
21499
  $exit_speed: ExitSpeed!
21500
21500
  $withdraw_all: Boolean
21501
21501
  $fee_leaf_external_ids: [UUID!]
21502
21502
  $fee_quote_id: ID
21503
+ $user_outbound_transfer_external_id: UUID
21503
21504
  ) {
21504
21505
  request_coop_exit(
21505
21506
  input: {
@@ -21510,6 +21511,7 @@ var RequestCoopExit = `
21510
21511
  withdraw_all: $withdraw_all
21511
21512
  fee_leaf_external_ids: $fee_leaf_external_ids
21512
21513
  fee_quote_id: $fee_quote_id
21514
+ user_outbound_transfer_external_id: $user_outbound_transfer_external_id
21513
21515
  }
21514
21516
  ) {
21515
21517
  request {
@@ -21558,13 +21560,15 @@ init_buffer();
21558
21560
  var RequestLightningSend = `
21559
21561
  mutation RequestLightningSend(
21560
21562
  $encoded_invoice: String!
21561
- $idempotency_key: String!
21563
+ $idempotency_key: String
21562
21564
  $amount_sats: Long
21565
+ $user_outbound_transfer_external_id: UUID
21563
21566
  ) {
21564
21567
  request_lightning_send(input: {
21565
21568
  encoded_invoice: $encoded_invoice
21566
21569
  idempotency_key: $idempotency_key
21567
21570
  amount_sats: $amount_sats
21571
+ user_outbound_transfer_external_id: $user_outbound_transfer_external_id
21568
21572
  }) {
21569
21573
  request {
21570
21574
  ...LightningSendRequestFragment
@@ -22014,14 +22018,12 @@ var SspClient = class {
22014
22018
  throw new Error("Not implemented");
22015
22019
  }
22016
22020
  async completeCoopExit({
22017
- userOutboundTransferExternalId,
22018
- coopExitRequestId
22021
+ userOutboundTransferExternalId
22019
22022
  }) {
22020
22023
  return await this.executeRawQuery({
22021
22024
  queryPayload: CompleteCoopExit,
22022
22025
  variables: {
22023
- user_outbound_transfer_external_id: userOutboundTransferExternalId,
22024
- coop_exit_request_id: coopExitRequestId
22026
+ user_outbound_transfer_external_id: userOutboundTransferExternalId
22025
22027
  },
22026
22028
  constructObject: (response) => {
22027
22029
  return CoopExitRequestFromJson(response.complete_coop_exit.request);
@@ -22031,29 +22033,28 @@ var SspClient = class {
22031
22033
  async requestCoopExit({
22032
22034
  leafExternalIds,
22033
22035
  withdrawalAddress,
22034
- idempotencyKey,
22035
22036
  exitSpeed,
22036
22037
  feeLeafExternalIds,
22037
22038
  feeQuoteId,
22038
- withdrawAll
22039
+ withdrawAll,
22040
+ userOutboundTransferExternalId
22039
22041
  }) {
22040
22042
  return await this.executeRawQuery({
22041
22043
  queryPayload: RequestCoopExit,
22042
22044
  variables: {
22043
22045
  leaf_external_ids: leafExternalIds,
22044
22046
  withdrawal_address: withdrawalAddress,
22045
- idempotency_key: idempotencyKey,
22046
22047
  exit_speed: exitSpeed,
22047
22048
  fee_leaf_external_ids: feeLeafExternalIds,
22048
22049
  fee_quote_id: feeQuoteId,
22049
- withdraw_all: withdrawAll
22050
+ withdraw_all: withdrawAll,
22051
+ user_outbound_transfer_external_id: userOutboundTransferExternalId
22050
22052
  },
22051
22053
  constructObject: (response) => {
22052
22054
  return CoopExitRequestFromJson(response.request_coop_exit.request);
22053
22055
  }
22054
22056
  });
22055
22057
  }
22056
- // TODO: Lets name this better
22057
22058
  async requestLightningReceive({
22058
22059
  amountSats,
22059
22060
  network,
@@ -22085,15 +22086,15 @@ var SspClient = class {
22085
22086
  }
22086
22087
  async requestLightningSend({
22087
22088
  encodedInvoice,
22088
- idempotencyKey,
22089
- amountSats
22089
+ amountSats,
22090
+ userOutboundTransferExternalId
22090
22091
  }) {
22091
22092
  return await this.executeRawQuery({
22092
22093
  queryPayload: RequestLightningSend,
22093
22094
  variables: {
22094
22095
  encoded_invoice: encodedInvoice,
22095
- idempotency_key: idempotencyKey,
22096
- amount_sats: amountSats
22096
+ amount_sats: amountSats,
22097
+ user_outbound_transfer_external_id: userOutboundTransferExternalId
22097
22098
  },
22098
22099
  constructObject: (response) => {
22099
22100
  return LightningSendRequestFromJson(
@@ -22438,13 +22439,13 @@ var WalletConfigService = class {
22438
22439
  config;
22439
22440
  signer;
22440
22441
  sspClientOptions;
22441
- constructor(options, signer) {
22442
+ constructor(options = {}, signer) {
22442
22443
  const network = options?.network ?? "REGTEST";
22443
22444
  this.config = {
22444
22445
  ...this.getDefaultConfig(Network2[network]),
22445
22446
  ...options
22446
22447
  };
22447
- this.signer = signer ?? new DefaultSparkSigner();
22448
+ this.signer = signer;
22448
22449
  this.sspClientOptions = this.config.sspClientOptions;
22449
22450
  }
22450
22451
  getDefaultConfig(network) {
@@ -25992,6 +25993,13 @@ var ConnectionManager = class {
25992
25993
  lastError = error;
25993
25994
  continue;
25994
25995
  }
25996
+ if (error.message.includes("UNAVAILABLE: No connection established.")) {
25997
+ console.warn(
25998
+ `Authentication attempt ${attempt + 1} failed due to unavailable status, retrying...`
25999
+ );
26000
+ lastError = error;
26001
+ continue;
26002
+ }
25995
26003
  throw new AuthenticationError(
25996
26004
  "Authentication failed",
25997
26005
  {
@@ -27541,7 +27549,8 @@ var CoopExitService = class extends BaseTransferService {
27541
27549
  leaves,
27542
27550
  exitTxId,
27543
27551
  connectorOutputs,
27544
- receiverPubKey
27552
+ receiverPubKey,
27553
+ transferId
27545
27554
  }) {
27546
27555
  const {
27547
27556
  transfer,
@@ -27552,7 +27561,8 @@ var CoopExitService = class extends BaseTransferService {
27552
27561
  leaves,
27553
27562
  exitTxId,
27554
27563
  connectorOutputs,
27555
- receiverPubKey
27564
+ receiverPubKey,
27565
+ transferId
27556
27566
  );
27557
27567
  const transferTweak = await this.deliverTransferPackage(
27558
27568
  transfer,
@@ -27633,7 +27643,7 @@ var CoopExitService = class extends BaseTransferService {
27633
27643
  directFromCpfpRefundTx
27634
27644
  };
27635
27645
  }
27636
- async signCoopExitRefunds(leaves, exitTxId, connectorOutputs, receiverPubKey) {
27646
+ async signCoopExitRefunds(leaves, exitTxId, connectorOutputs, receiverPubKey, transferId) {
27637
27647
  if (leaves.length !== connectorOutputs.length) {
27638
27648
  throw new ValidationError(
27639
27649
  "Mismatch between leaves and connector outputs",
@@ -27737,7 +27747,7 @@ var CoopExitService = class extends BaseTransferService {
27737
27747
  try {
27738
27748
  response = await sparkClient.cooperative_exit_v2({
27739
27749
  transfer: {
27740
- transferId: (0, import_uuidv73.uuidv7)(),
27750
+ transferId,
27741
27751
  leavesToSend: signingJobs,
27742
27752
  ownerIdentityPublicKey: await this.config.signer.getIdentityPublicKey(),
27743
27753
  receiverIdentityPublicKey: receiverPubKey,
@@ -29217,7 +29227,7 @@ function hashTokenTransactionV1(tokenTransaction, partialHash = false) {
29217
29227
  }
29218
29228
  const finalHashObj = import_sha212.sha256.create();
29219
29229
  const concatenatedHashes = new Uint8Array(
29220
- allHashes.reduce((sum, hash) => sum + hash.length, 0)
29230
+ allHashes.reduce((sum2, hash) => sum2 + hash.length, 0)
29221
29231
  );
29222
29232
  let offset = 0;
29223
29233
  for (const hash of allHashes) {
@@ -29690,7 +29700,7 @@ function hashTokenTransactionV2(tokenTransaction, partialHash = false) {
29690
29700
  }
29691
29701
  const finalHashObj = import_sha212.sha256.create();
29692
29702
  const concatenatedHashes = new Uint8Array(
29693
- allHashes.reduce((sum, hash) => sum + hash.length, 0)
29703
+ allHashes.reduce((sum2, hash) => sum2 + hash.length, 0)
29694
29704
  );
29695
29705
  let offset = 0;
29696
29706
  for (const hash of allHashes) {
@@ -29738,7 +29748,7 @@ function hashOperatorSpecificTokenTransactionSignablePayload(payload) {
29738
29748
  allHashes.push(hashObj.digest());
29739
29749
  const finalHashObj = import_sha212.sha256.create();
29740
29750
  const concatenatedHashes = new Uint8Array(
29741
- allHashes.reduce((sum, hash) => sum + hash.length, 0)
29751
+ allHashes.reduce((sum2, hash) => sum2 + hash.length, 0)
29742
29752
  );
29743
29753
  let offset = 0;
29744
29754
  for (const hash of allHashes) {
@@ -30065,7 +30075,7 @@ var TokenTransactionService = class {
30065
30075
  });
30066
30076
  }
30067
30077
  const totalTokenAmount = receiverOutputs.reduce(
30068
- (sum, transfer) => sum + transfer.tokenAmount,
30078
+ (sum2, transfer) => sum2 + transfer.tokenAmount,
30069
30079
  0n
30070
30080
  );
30071
30081
  let outputsToUse;
@@ -30153,7 +30163,7 @@ var TokenTransactionService = class {
30153
30163
  );
30154
30164
  const availableTokenAmount = sumAvailableTokens(selectedOutputs);
30155
30165
  const totalRequestedAmount = tokenOutputData.reduce(
30156
- (sum, output) => sum + output.tokenAmount,
30166
+ (sum2, output) => sum2 + output.tokenAmount,
30157
30167
  0n
30158
30168
  );
30159
30169
  const tokenOutputs = tokenOutputData.map(
@@ -30529,15 +30539,15 @@ var TokenTransactionService = class {
30529
30539
  sortTokenOutputsByStrategy(tokenOutputs, strategy) {
30530
30540
  if (strategy === "SMALL_FIRST") {
30531
30541
  tokenOutputs.sort((a, b) => {
30532
- return Number(
30533
- (0, import_utils19.bytesToNumberBE)(a.output.tokenAmount) - (0, import_utils19.bytesToNumberBE)(b.output.tokenAmount)
30534
- );
30542
+ const amountA = (0, import_utils19.bytesToNumberBE)(a.output.tokenAmount);
30543
+ const amountB = (0, import_utils19.bytesToNumberBE)(b.output.tokenAmount);
30544
+ return amountA < amountB ? -1 : amountA > amountB ? 1 : 0;
30535
30545
  });
30536
30546
  } else {
30537
30547
  tokenOutputs.sort((a, b) => {
30538
- return Number(
30539
- (0, import_utils19.bytesToNumberBE)(b.output.tokenAmount) - (0, import_utils19.bytesToNumberBE)(a.output.tokenAmount)
30540
- );
30548
+ const amountA = (0, import_utils19.bytesToNumberBE)(a.output.tokenAmount);
30549
+ const amountB = (0, import_utils19.bytesToNumberBE)(b.output.tokenAmount);
30550
+ return amountB < amountA ? -1 : amountB > amountA ? 1 : 0;
30541
30551
  });
30542
30552
  }
30543
30553
  }
@@ -30826,7 +30836,7 @@ var COIN_AMOUNT = 10000000n;
30826
30836
  var FEE_AMOUNT = 1000n;
30827
30837
  var TARGET_NUM_COINS = 20;
30828
30838
  var BitcoinFaucet = class _BitcoinFaucet {
30829
- constructor(url = "http://127.0.0.1:8332", username = "testutil", password = "testutilpassword") {
30839
+ constructor(url, username, password) {
30830
30840
  this.url = url;
30831
30841
  this.username = username;
30832
30842
  this.password = password;
@@ -30839,8 +30849,11 @@ var BitcoinFaucet = class _BitcoinFaucet {
30839
30849
  static instance = null;
30840
30850
  miningAddress;
30841
30851
  lock = Promise.resolve();
30842
- static getInstance(url = "http://127.0.0.1:8332", username = "testutil", password = "testutilpassword") {
30852
+ static getInstance() {
30843
30853
  if (!_BitcoinFaucet.instance) {
30854
+ const url = process.env.BITCOIN_RPC_URL || (process.env.MINIKUBE_IP ? `http://${process.env.MINIKUBE_IP}:8332` : "http://127.0.0.1:8332");
30855
+ const username = process.env.BITCOIN_RPC_USER || "testutil";
30856
+ const password = process.env.BITCOIN_RPC_PASSWORD || "testutilpassword";
30844
30857
  _BitcoinFaucet.instance = new _BitcoinFaucet(url, username, password);
30845
30858
  }
30846
30859
  return _BitcoinFaucet.instance;
@@ -31123,6 +31136,76 @@ function chunkArray(arr, size) {
31123
31136
  return chunks;
31124
31137
  }
31125
31138
 
31139
+ // src/utils/optimize.ts
31140
+ init_buffer();
31141
+ var DENOMINATIONS = Array.from({ length: 28 }, (_, i) => 2 ** i);
31142
+ function assert(condition, message) {
31143
+ if (!condition) {
31144
+ throw new InternalValidationError(message || "Assertion failed");
31145
+ }
31146
+ }
31147
+ function sum(arr) {
31148
+ return arr.reduce((a, b) => a + b, 0);
31149
+ }
31150
+ function sorted(arr) {
31151
+ return [...arr].sort((a, b) => a - b);
31152
+ }
31153
+ function equals(a, b) {
31154
+ return a.length === b.length && a.every((val, index) => val === b[index]);
31155
+ }
31156
+ function greedyLeaves(amount) {
31157
+ const leaves = [];
31158
+ let remaining = amount;
31159
+ for (let i = DENOMINATIONS.length - 1; i >= 0; i--) {
31160
+ const leaf = DENOMINATIONS[i];
31161
+ if (typeof leaf === "number" && leaf > 0) {
31162
+ while (remaining >= leaf) {
31163
+ remaining -= leaf;
31164
+ leaves.push(leaf);
31165
+ }
31166
+ }
31167
+ }
31168
+ assert(sum(leaves) === amount, "greedy_leaves: sum mismatch");
31169
+ return sorted(leaves);
31170
+ }
31171
+ var Swap = class {
31172
+ inLeaves;
31173
+ outLeaves;
31174
+ constructor(inLeaves, outLeaves) {
31175
+ this.inLeaves = [...inLeaves];
31176
+ this.outLeaves = [...outLeaves];
31177
+ assert(
31178
+ sum(this.inLeaves) === sum(this.outLeaves),
31179
+ "Swap in/out leaves must sum to same value for swap: " + this.toString()
31180
+ );
31181
+ }
31182
+ toString() {
31183
+ return `Swap(in=${JSON.stringify(this.inLeaves)}, out=${JSON.stringify(this.outLeaves)})`;
31184
+ }
31185
+ };
31186
+ function maximizeUnilateralExit(inputLeaves, maxLeavesPerSwap = 64) {
31187
+ const swaps = [];
31188
+ let batch = [];
31189
+ let leaves = sorted(inputLeaves);
31190
+ while (leaves.length > 0) {
31191
+ batch.push(leaves.shift());
31192
+ const target = greedyLeaves(sum(batch));
31193
+ if (batch.length >= maxLeavesPerSwap || target.length >= maxLeavesPerSwap) {
31194
+ if (!equals(target, batch)) {
31195
+ swaps.push(new Swap([...batch], target));
31196
+ }
31197
+ batch = [];
31198
+ }
31199
+ }
31200
+ if (batch.length > 0) {
31201
+ const target = greedyLeaves(sum(batch));
31202
+ if (!equals(target, batch)) {
31203
+ swaps.push(new Swap([...batch], target));
31204
+ }
31205
+ }
31206
+ return swaps;
31207
+ }
31208
+
31126
31209
  // src/utils/retry.ts
31127
31210
  init_buffer();
31128
31211
  var DEFAULT_RETRY_CONFIG = {
@@ -31226,8 +31309,9 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
31226
31309
  // Add this property near the top of the class with other private properties
31227
31310
  claimTransfersInterval = null;
31228
31311
  tracer = null;
31229
- constructor(options, signer) {
31312
+ constructor(options, signerArg) {
31230
31313
  super();
31314
+ const signer = signerArg || this.buildSigner();
31231
31315
  this.config = new WalletConfigService(options, signer);
31232
31316
  this.connectionManager = this.buildConnectionManager(this.config);
31233
31317
  this.signingService = new SigningService(this.config);
@@ -31285,6 +31369,9 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
31285
31369
  }
31286
31370
  return this.sspClient;
31287
31371
  }
31372
+ buildSigner() {
31373
+ return new DefaultSparkSigner();
31374
+ }
31288
31375
  buildConnectionManager(config) {
31289
31376
  return new ConnectionManager(config);
31290
31377
  }
@@ -31646,8 +31733,34 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
31646
31733
  await this.withLeaves(async () => {
31647
31734
  this.optimizationInProgress = true;
31648
31735
  try {
31649
- if (this.leaves.length > 0) {
31650
- await this.requestLeavesSwap({ leaves: this.leaves });
31736
+ this.leaves = await this.getLeaves();
31737
+ const swaps = maximizeUnilateralExit(
31738
+ this.leaves.map((leaf) => leaf.value)
31739
+ );
31740
+ const valueToNodes = /* @__PURE__ */ new Map();
31741
+ this.leaves.forEach((leaf) => {
31742
+ if (!valueToNodes.has(leaf.value)) {
31743
+ valueToNodes.set(leaf.value, []);
31744
+ }
31745
+ valueToNodes.get(leaf.value).push(leaf);
31746
+ });
31747
+ for (const swap of swaps) {
31748
+ const leavesToSend = [];
31749
+ for (const leafValue of swap.inLeaves) {
31750
+ const nodes = valueToNodes.get(leafValue);
31751
+ if (nodes && nodes.length > 0) {
31752
+ const node = nodes.shift();
31753
+ leavesToSend.push(node);
31754
+ } else {
31755
+ throw new InternalValidationError(
31756
+ `No unused leaf with value ${leafValue} found in leaves`
31757
+ );
31758
+ }
31759
+ }
31760
+ await this.requestLeavesSwap({
31761
+ leaves: leavesToSend,
31762
+ targetAmounts: swap.outLeaves
31763
+ });
31651
31764
  }
31652
31765
  this.leaves = await this.getLeaves();
31653
31766
  } finally {
@@ -32218,6 +32331,10 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
32218
32331
  directSignatureMap,
32219
32332
  directFromCpfpSignatureMap
32220
32333
  );
32334
+ const leavesToRemove = new Set(leavesBatch.map((leaf) => leaf.id));
32335
+ this.leaves = [
32336
+ ...this.leaves.filter((leaf) => !leavesToRemove.has(leaf.id))
32337
+ ];
32221
32338
  const completeResponse = await sspClient.completeLeaveSwap({
32222
32339
  adaptorSecretKey: (0, import_utils24.bytesToHex)(cpfpAdaptorPrivateKey),
32223
32340
  directAdaptorSecretKey: (0, import_utils24.bytesToHex)(directAdaptorPrivateKey),
@@ -32806,7 +32923,7 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
32806
32923
  creditAmountView.setUint32(4, upperHalf, true);
32807
32924
  parts.push(new Uint8Array(creditAmountBuffer));
32808
32925
  parts.push((0, import_utils24.hexToBytes)(sspSignature));
32809
- const totalLength = parts.reduce((sum, part) => sum + part.length, 0);
32926
+ const totalLength = parts.reduce((sum2, part) => sum2 + part.length, 0);
32810
32927
  const payload = new Uint8Array(totalLength);
32811
32928
  let offset = 0;
32812
32929
  for (const part of parts) {
@@ -33902,8 +34019,8 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
33902
34019
  );
33903
34020
  const sspResponse = await sspClient.requestLightningSend({
33904
34021
  encodedInvoice: invoice,
33905
- idempotencyKey: (0, import_uuidv75.uuidv7)(),
33906
- amountSats: isZeroAmountInvoice ? amountSatsToSend : void 0
34022
+ amountSats: isZeroAmountInvoice ? amountSatsToSend : void 0,
34023
+ userOutboundTransferExternalId: swapResponse.transfer.id
33907
34024
  });
33908
34025
  if (!sspResponse) {
33909
34026
  throw new Error("Failed to contact SSP");
@@ -34209,12 +34326,13 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
34209
34326
  }
34210
34327
  }))
34211
34328
  );
34329
+ const transferId = (0, import_uuidv75.uuidv7)();
34212
34330
  const requestCoopExitParams = {
34213
34331
  leafExternalIds: leavesToSendToSsp.map((leaf) => leaf.id),
34214
34332
  withdrawalAddress: onchainAddress,
34215
- idempotencyKey: (0, import_uuidv75.uuidv7)(),
34216
34333
  exitSpeed,
34217
- withdrawAll: deductFeeFromWithdrawalAmount
34334
+ withdrawAll: deductFeeFromWithdrawalAmount,
34335
+ userOutboundTransferExternalId: transferId
34218
34336
  };
34219
34337
  if (!deductFeeFromWithdrawalAmount) {
34220
34338
  requestCoopExitParams.feeQuoteId = feeEstimate.id;
@@ -34249,11 +34367,11 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
34249
34367
  leaves: leafKeyTweaks,
34250
34368
  exitTxId: coopExitTxId,
34251
34369
  connectorOutputs,
34252
- receiverPubKey: sspPubIdentityKey
34370
+ receiverPubKey: sspPubIdentityKey,
34371
+ transferId
34253
34372
  });
34254
34373
  const completeResponse = await sspClient.completeCoopExit({
34255
- userOutboundTransferExternalId: transfer.transfer.id,
34256
- coopExitRequestId: coopExitRequest.id
34374
+ userOutboundTransferExternalId: transfer.transfer.id
34257
34375
  });
34258
34376
  return completeResponse;
34259
34377
  }
@@ -34975,7 +35093,6 @@ var SparkWallet = class extends import_eventemitter3.EventEmitter {
34975
35093
  const consoleOptions = wallet.config.getConsoleOptions();
34976
35094
  const spanProcessors = [];
34977
35095
  if (consoleOptions.otel) {
34978
- console.log("OpenTelemetry client logging enabled.");
34979
35096
  spanProcessors.push(new import_sdk_trace_base.SimpleSpanProcessor(new import_sdk_trace_base.ConsoleSpanExporter()));
34980
35097
  }
34981
35098
  const traceUrls = this.getOtelTraceUrls();
@@ -35168,7 +35285,6 @@ var SparkWalletBrowser = class extends SparkWallet {
35168
35285
  spanProcessors,
35169
35286
  traceUrls
35170
35287
  }) {
35171
- console.log("initializeTracerEnvBrowser");
35172
35288
  initializeTracerEnvBrowser({ spanProcessors, traceUrls });
35173
35289
  }
35174
35290
  };